diff --git a/.github/workflows/fdroid.yaml b/.github/workflows/fdroid.yaml index f986508fb..3829a32b6 100644 --- a/.github/workflows/fdroid.yaml +++ b/.github/workflows/fdroid.yaml @@ -22,6 +22,13 @@ on: - src-tauri/gen/android/** - .github/workflows/fdroid.yaml - .github/workflows/fdroid-build.yaml + - crates/vector-gpui/scripts/fdroid-build.sh + - crates/vector-gpui/android/** + - crates/vector-gpui/Cargo.toml + - crates/vector-gpui/Cargo.lock + +permissions: + contents: read concurrency: group: fdroid-${{ github.ref }} @@ -81,3 +88,47 @@ jobs: path: src-tauri/gen/android/app/build/outputs/apk/universal/release/app-universal-universal-release-unsigned.apk if-no-files-found: error + # The GPUI client's flavour, from its own recipe: the app v0.6 ships on F-Droid. + gpui: + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@v5 + + - uses: dtolnay/rust-toolchain@stable + + - uses: actions/setup-java@v5 + with: + distribution: temurin + java-version: '17' + + - uses: android-actions/setup-android@v4 + + - name: Android NDK + run: | + sdkmanager --install "ndk;29.0.14206865" + echo "NDK_HOME=$ANDROID_HOME/ndk/29.0.14206865" >> "$GITHUB_ENV" + + # Google's copy of Maven Central ahead of every repository: Central's CDN answers some + # runners 404. An init script, since F-Droid's scanner refuses unknown repositories. + - name: Maven mirror + run: | + mkdir -p ~/.gradle/init.d + cat > ~/.gradle/init.d/mirror.gradle <<'EOF' + beforeSettings { settings -> + def mirror = 'https://maven-central.storage-download.googleapis.com/maven2/' + settings.pluginManagement.repositories.maven { url = mirror } + settings.dependencyResolutionManagement.repositories.maven { url = mirror } + } + EOF + + - name: Prepare (network stage) + run: crates/vector-gpui/scripts/fdroid-build.sh prepare + + - name: Build + run: crates/vector-gpui/scripts/fdroid-build.sh build + + - uses: actions/upload-artifact@v6 + with: + name: Vector-GPUI-fdroid-unsigned + path: crates/vector-gpui/android/app/build/outputs/apk/release/*.apk + if-no-files-found: error diff --git a/.github/workflows/gpui-android.yaml b/.github/workflows/gpui-android.yaml new file mode 100644 index 000000000..18aeebe53 --- /dev/null +++ b/.github/workflows/gpui-android.yaml @@ -0,0 +1,258 @@ +name: GPUI Android + +# The GPUI client for Android phones, compiled with the runner's NDK: its platform +# (crates/vector-gpui/vendor/gpui_android) and the client itself. Its own concurrency group, so +# it never waits behind or replaces a desktop build. +on: + push: + branches: [gpui] + paths: + - 'crates/vector-gpui/**' + - 'crates/vector-i18n/**' + - 'crates/vector-core/**' + - 'crates/vector-calls/**' + - 'src-tauri/src/**' + - '.github/workflows/gpui-android.yaml' + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: gpui-android-${{ github.ref }} + cancel-in-progress: true + +env: + RUST_TOOLCHAIN: 1.98.0 + CARGO_TERM_COLOR: always + +jobs: + check: + strategy: + fail-fast: false + matrix: + include: + - name: platform + # Expected to fail until the client's desktop-only dependencies are ported. + - name: client + experimental: true + name: check (${{ matrix.name }}) + continue-on-error: ${{ matrix.experimental || false }} + runs-on: ubuntu-24.04 + defaults: + run: + working-directory: crates/vector-gpui + steps: + - uses: actions/checkout@v5 + + - uses: dtolnay/rust-toolchain@master + with: + toolchain: ${{ env.RUST_TOOLCHAIN }} + targets: aarch64-linux-android + components: clippy + + - name: NDK toolchain + run: | + ndk="$ANDROID_NDK_LATEST_HOME" + bin="$ndk/toolchains/llvm/prebuilt/linux-x86_64/bin" + { + echo "ANDROID_NDK_HOME=$ndk" + echo "ANDROID_NDK_ROOT=$ndk" + echo "ANDROID_NDK=$ndk" + echo "CC_aarch64_linux_android=$bin/aarch64-linux-android26-clang" + echo "CXX_aarch64_linux_android=$bin/aarch64-linux-android26-clang++" + echo "AR_aarch64_linux_android=$bin/llvm-ar" + echo "CARGO_TARGET_AARCH64_LINUX_ANDROID_LINKER=$bin/aarch64-linux-android26-clang" + } >> "$GITHUB_ENV" + + - uses: Swatinem/rust-cache@v2 + with: + workspaces: crates/vector-gpui -> target + key: android-aarch64-${{ matrix.name }} + + # Warnings fail only in our own platform crates: -D warnings would reach the vendored ones too. + - name: Clippy + if: matrix.name == 'platform' + shell: bash + run: | + cargo clippy --locked -p gpui_platform -p gpui_android --target aarch64-linux-android \ + --message-format short 2>&1 | tee clippy.log + ! grep -E '^vendor/gpui_(android|platform)/.*: (warning|error)' clippy.log + + - name: Check + if: matrix.name == 'client' + run: cargo check --locked --keep-going --lib --target aarch64-linux-android --no-default-features --features tor,i2p --message-format short + + # The app around the client: Kotlin, manifest and resources, which need no Rust to compile. + shell: + runs-on: ubuntu-24.04 + defaults: + run: + working-directory: crates/vector-gpui/android + steps: + - uses: actions/checkout@v5 + + - uses: actions/setup-java@v5 + with: + distribution: temurin + java-version: '17' + cache: gradle + + # Google's copy of Maven Central ahead of every repository: Central's CDN answers some + # runners 404. An init script, since F-Droid's scanner refuses unknown repositories. + - name: Maven mirror + run: | + mkdir -p ~/.gradle/init.d + cat > ~/.gradle/init.d/mirror.gradle <<'EOF' + beforeSettings { settings -> + def mirror = 'https://maven-central.storage-download.googleapis.com/maven2/' + settings.pluginManagement.repositories.maven { url = mirror } + settings.dependencyResolutionManagement.repositories.maven { url = mirror } + } + EOF + + - name: Compile + run: ./gradlew --no-daemon :app:compileDebugKotlin :app:compileReleaseKotlin + + # The phone app: a debug APK for arm64 phones, which installs beside an installed Vector. + apk: + needs: shell + # Expected to fail until the client links for Android. + continue-on-error: true + runs-on: ubuntu-24.04 + defaults: + run: + working-directory: crates/vector-gpui/android + steps: + - uses: actions/checkout@v5 + + - uses: dtolnay/rust-toolchain@master + with: + toolchain: ${{ env.RUST_TOOLCHAIN }} + targets: aarch64-linux-android + + - uses: actions/setup-java@v5 + with: + distribution: temurin + java-version: '17' + cache: gradle + + # Google's copy of Maven Central ahead of every repository: Central's CDN answers some + # runners 404. An init script, since F-Droid's scanner refuses unknown repositories. + - name: Maven mirror + run: | + mkdir -p ~/.gradle/init.d + cat > ~/.gradle/init.d/mirror.gradle <<'EOF' + beforeSettings { settings -> + def mirror = 'https://maven-central.storage-download.googleapis.com/maven2/' + settings.pluginManagement.repositories.maven { url = mirror } + settings.dependencyResolutionManagement.repositories.maven { url = mirror } + } + EOF + + - uses: Swatinem/rust-cache@v2 + with: + workspaces: crates/vector-gpui -> target + key: android-apk + + # One debug key across runs, so a test APK installs over the last one without an + # uninstall (which wipes the app's data). The secret holds it for good; the cache is + # evicted once the repo's caches pass 10 GB, and Gradle then makes a new key. + - name: Debug key + id: debug-key + env: + KEYSTORE: ${{ secrets.GPUI_ANDROID_DEBUG_KEYSTORE }} + run: | + if [ -n "$KEYSTORE" ]; then + mkdir -p ~/.android + printf '%s' "$KEYSTORE" | base64 -d > ~/.android/debug.keystore + echo "secret=1" >> "$GITHUB_OUTPUT" + else + echo "::warning::GPUI_ANDROID_DEBUG_KEYSTORE is not set: this APK's key lasts only as long as the Actions cache" + fi + + - if: steps.debug-key.outputs.secret != '1' + uses: actions/cache@v4 + with: + path: ~/.android/debug.keystore + key: gpui-android-debug-keystore-v1 + + - name: Build + run: ./gradlew --no-daemon :app:assembleDebug -PvectorNdk="$(basename "$ANDROID_NDK_LATEST_HOME")" + + - uses: actions/upload-artifact@v4 + with: + name: vector-gpui-android-arm64-debug + path: crates/vector-gpui/android/app/build/outputs/apk/debug/*.apk + retention-days: 14 + + # The app on emulated phones (x86_64, software GPU): what it shows after launch, and its log. + # Android 11 without Vulkan is the GLES path phones with PowerVR GPUs draw with. + emulator: + needs: shell + continue-on-error: true + runs-on: ubuntu-24.04 + strategy: + fail-fast: false + matrix: + include: + - { api: 34, gpu: vulkan, features: '' } + - { api: 30, gpu: gles, features: '-feature -Vulkan' } + name: emulator (API ${{ matrix.api }}, ${{ matrix.gpu }}) + steps: + - uses: actions/checkout@v5 + + - uses: dtolnay/rust-toolchain@master + with: + toolchain: ${{ env.RUST_TOOLCHAIN }} + targets: x86_64-linux-android + + - uses: actions/setup-java@v5 + with: + distribution: temurin + java-version: '17' + cache: gradle + + # Google's copy of Maven Central ahead of every repository: Central's CDN answers some + # runners 404. An init script, since F-Droid's scanner refuses unknown repositories. + - name: Maven mirror + run: | + mkdir -p ~/.gradle/init.d + cat > ~/.gradle/init.d/mirror.gradle <<'EOF' + beforeSettings { settings -> + def mirror = 'https://maven-central.storage-download.googleapis.com/maven2/' + settings.pluginManagement.repositories.maven { url = mirror } + settings.dependencyResolutionManagement.repositories.maven { url = mirror } + } + EOF + + - uses: Swatinem/rust-cache@v2 + with: + workspaces: crates/vector-gpui -> target + key: android-emulator + + - name: Build + working-directory: crates/vector-gpui/android + run: ./gradlew --no-daemon :app:assembleDebug -PvectorAbis=x86_64 -PvectorNdk="$(basename "$ANDROID_NDK_LATEST_HOME")" + + - name: KVM + run: | + echo 'KERNEL=="kvm", GROUP="kvm", MODE="0666", OPTIONS+="static_node=kvm"' | sudo tee /etc/udev/rules.d/99-kvm4all.rules + sudo udevadm control --reload-rules + sudo udevadm trigger --name-match=kvm + + - uses: reactivecircus/android-emulator-runner@v2 + with: + api-level: ${{ matrix.api }} + arch: x86_64 + target: google_apis + emulator-options: -no-window -gpu swiftshader_indirect -no-snapshot -noaudio -no-boot-anim ${{ matrix.features }} + disable-animations: true + script: crates/vector-gpui/android/scripts/emulator-smoke.sh crates/vector-gpui/android/app/build/outputs/apk/debug/app-debug.apk smoke + + - uses: actions/upload-artifact@v4 + if: always() + with: + name: vector-gpui-android-emulator-${{ matrix.api }} + path: smoke/ + retention-days: 14 diff --git a/.github/workflows/gpui.yaml b/.github/workflows/gpui.yaml new file mode 100644 index 000000000..cf08c1baa --- /dev/null +++ b/.github/workflows/gpui.yaml @@ -0,0 +1,358 @@ +name: GPUI build + +# The GPUI client on the platforms the cloud box can't build for. Its own workspace and lockfile, +# so nothing here touches the Tauri client's build. +on: + push: + branches: [gpui] + paths: + - 'crates/vector-gpui/**' + - 'crates/vector-i18n/**' + - 'crates/vector-core/**' + - 'crates/vector-calls/**' + - 'src-tauri/src/**' + - '.github/workflows/gpui.yaml' + pull_request: + paths: + - 'crates/vector-gpui/**' + - 'crates/vector-i18n/**' + - '.github/workflows/gpui.yaml' + workflow_dispatch: + # A release (publish.yaml) builds the updater bundles here, then signs and uploads them itself. + workflow_call: + inputs: + release_tag: + type: string + required: true + +permissions: + contents: read + +# A build takes most of an hour; a newer push waits for it rather than cancelling it. +concurrency: + group: gpui-${{ github.ref }} + cancel-in-progress: false + +env: + RUST_TOOLCHAIN: 1.98.0 + CARGO_TERM_COLOR: always + +jobs: + build: + # The port's own pull request builds on its pushes already. + if: ${{ !inputs.release_tag && (github.event_name != 'pull_request' || github.head_ref != 'gpui') }} + strategy: + fail-fast: false + matrix: + include: + # The arm64 pool rarely takes a job; the release builds use this one too. + - platform: macos-26-intel + features: '' + # No system FFmpeg on the runner: video attachments draw as files here for now. + - platform: windows-2022 + features: '--no-default-features --features tor,i2p' + runs-on: ${{ matrix.platform }} + defaults: + run: + working-directory: crates/vector-gpui + steps: + - uses: actions/checkout@v5 + + - uses: dtolnay/rust-toolchain@master + with: + toolchain: ${{ env.RUST_TOOLCHAIN }} + + - name: Prepare the runner (Windows) + if: startsWith(matrix.platform, 'windows') + shell: pwsh + run: | + Set-MpPreference -DisableRealtimeMonitoring $true + $drive = Split-Path -Qualifier $env:GITHUB_WORKSPACE + echo "CARGO_TARGET_DIR=$drive\t" >> $env:GITHUB_ENV + + - name: FFmpeg (macOS) + if: startsWith(matrix.platform, 'macos') + run: | + brew install ffmpeg@7 pkg-config + echo "PKG_CONFIG_PATH=$(brew --prefix ffmpeg@7)/lib/pkgconfig" >> "$GITHUB_ENV" + + # Whisper transcribes on Vulkan on x64 Windows, as the desktop client does. + - name: Cache Vulkan (Windows) + if: startsWith(matrix.platform, 'windows') + id: vulkan-cache + uses: actions/cache@v5 + with: + path: C:\vcpkg\installed + key: vulkan-x64-windows-headers-loader-spirv-tools-glslc + + - name: Install Vulkan SDK (Windows) + if: startsWith(matrix.platform, 'windows') && steps.vulkan-cache.outputs.cache-hit != 'true' + shell: pwsh + working-directory: . + run: | + vcpkg install vulkan:x64-windows vulkan-headers:x64-windows vulkan-loader:x64-windows spirv-tools:x64-windows + Invoke-WebRequest -Uri "https://jskitty.com/glslc.exe" -OutFile "glslc.exe" + $vcpkgBin = "C:\vcpkg\installed\x64-windows\bin" + New-Item -ItemType Directory -Force -Path $vcpkgBin + Move-Item "glslc.exe" "$vcpkgBin\glslc.exe" -Force + + - name: Vulkan environment (Windows) + if: startsWith(matrix.platform, 'windows') + shell: pwsh + run: | + $vcpkgBin = "C:\vcpkg\installed\x64-windows\bin" + echo "VULKAN_SDK=C:\vcpkg\installed\x64-windows" >> $env:GITHUB_ENV + echo "CMAKE_PREFIX_PATH=C:\vcpkg\installed\x64-windows" >> $env:GITHUB_ENV + echo "$vcpkgBin" >> $env:GITHUB_PATH + + - uses: Swatinem/rust-cache@v2 + with: + workspaces: crates/vector-gpui -> ${{ startsWith(matrix.platform, 'windows') && '../../../../t' || 'target' }} + key: ${{ matrix.platform }} + + - name: Build + shell: bash + run: cargo build --locked ${{ matrix.features }} + + - name: Tests + shell: bash + run: | + cargo test --locked ${{ matrix.features }} --lib + cargo test --locked --manifest-path ../vector-i18n/Cargo.toml + + # Release builds to try the port on a Mac or a PC: a push whose message carries [package]. + # Thin LTO keeps a cold build near an hour; unsigned, so first launch needs the OS's override. + package: + if: inputs.release_tag || github.event_name == 'workflow_dispatch' || (github.event_name == 'push' && contains(github.event.head_commit.message, '[package]')) + strategy: + fail-fast: false + matrix: + # The Tauri client's release targets, on the same runners: each of its installs has a + # bundle of its own kind to update to. macOS: both on the Intel image, Arm cross-compiled. + include: + - platform: macos-26-intel + target: aarch64-apple-darwin + out: aarch64-apple-darwin/release + features: '--target aarch64-apple-darwin --no-default-features --features video-static,tor,i2p' + ffmpeg: true + # ggml's native CPU probe would read the Intel host. + ggml_native: 'OFF' + - platform: macos-26-intel + target: x86_64-apple-darwin + out: x86_64-apple-darwin/release + features: '--target x86_64-apple-darwin --no-default-features --features video-static,tor,i2p' + ffmpeg: true + - platform: windows-2022 + target: x86_64-pc-windows-msvc + # The host's own target: a target directory level pushes whisper's Vulkan shader build past MAX_PATH. + out: release + features: '--no-default-features --features video-static,tor,i2p' + ffmpeg: true + # scripts/build-ffmpeg.sh has no Windows on Arm target yet: video attachments draw as files. + - platform: windows-11-arm + target: aarch64-pc-windows-msvc + out: release + features: '--no-default-features --features tor,i2p' + # The Tauri client's Linux release hosts: their glibc is the floor the packages run on. + - platform: ubuntu-22.04 + target: x86_64-unknown-linux-gnu + out: release + features: '--no-default-features --features video-static,tor,i2p' + ffmpeg: true + - platform: ubuntu-22.04-arm + target: aarch64-unknown-linux-gnu + out: release + features: '--no-default-features --features video-static,tor,i2p' + ffmpeg: true + runs-on: ${{ matrix.platform }} + env: + CARGO_PROFILE_RELEASE_LTO: thin + CARGO_PROFILE_RELEASE_CODEGEN_UNITS: '16' + # A release's bundles take the Tauri client's names; a test package keeps its own. + VECTOR_RELEASE: ${{ inputs.release_tag && '1' || '' }} + defaults: + run: + working-directory: crates/vector-gpui + steps: + - uses: actions/checkout@v5 + + - uses: dtolnay/rust-toolchain@master + with: + toolchain: ${{ env.RUST_TOOLCHAIN }} + targets: ${{ matrix.target }} + + - name: Prepare the runner (Windows) + if: startsWith(matrix.platform, 'windows') + shell: pwsh + run: | + Set-MpPreference -DisableRealtimeMonitoring $true + $drive = Split-Path -Qualifier $env:GITHUB_WORKSPACE + echo "CARGO_TARGET_DIR=$drive\t" >> $env:GITHUB_ENV + + # ring assembles its ARM64 Windows code with clang; MSVC's assembler can't. + - name: LLVM (Windows ARM) + if: matrix.platform == 'windows-11-arm' + shell: pwsh + run: | + if (-not (Test-Path "C:\Program Files\LLVM\bin\clang.exe")) { + if (Get-Command choco -ErrorAction SilentlyContinue) { choco install llvm -y --no-progress } + else { winget install --id LLVM.LLVM -e --silent --accept-package-agreements --accept-source-agreements } + } + echo "C:\Program Files\LLVM\bin" >> $env:GITHUB_PATH + + - name: Install dependencies (Linux) + if: startsWith(matrix.platform, 'ubuntu') + run: | + sudo apt-get update + sudo apt-get install -y libwebkit2gtk-4.1-dev libgtk-3-dev librsvg2-dev patchelf libasound2-dev \ + libxkbcommon-x11-dev libwayland-dev libx11-xcb-dev libxcb1-dev libfontconfig-dev libfreetype-dev \ + libvulkan-dev libssl-dev libzstd-dev clang cmake xdg-utils rpm + + # whisper builds its Vulkan backend on x64 Linux, which needs glslc, as in the Tauri release. + - name: Vulkan SDK (Linux x64) + if: matrix.platform == 'ubuntu-22.04' + run: | + wget -qO - https://packages.lunarg.com/lunarg-signing-key-pub.asc | sudo tee /etc/apt/trusted.gpg.d/lunarg.asc > /dev/null + sudo wget -qO /etc/apt/sources.list.d/lunarg-vulkan-jammy.list https://packages.lunarg.com/vulkan/lunarg-vulkan-jammy.list + sudo apt-get update + sudo apt-get install -y vulkan-sdk + + - name: Cache FFmpeg + if: matrix.ffmpeg + id: ffmpeg-cache + uses: actions/cache@v5 + with: + path: src-tauri/native-deps/ffmpeg/${{ matrix.target }} + key: ffmpeg-${{ matrix.target }}-${{ hashFiles('scripts/build-ffmpeg.sh') }} + + - name: Build FFmpeg (macOS, Linux) + if: matrix.ffmpeg && !startsWith(matrix.platform, 'windows') && steps.ffmpeg-cache.outputs.cache-hit != 'true' + working-directory: . + run: | + if [ "$RUNNER_OS" = macOS ]; then brew install nasm; else sudo apt-get install -y nasm; fi + scripts/build-ffmpeg.sh ${{ matrix.target }} + + - uses: ilammy/msvc-dev-cmd@v1 + if: matrix.ffmpeg && startsWith(matrix.platform, 'windows') && steps.ffmpeg-cache.outputs.cache-hit != 'true' + + - uses: msys2/setup-msys2@v2 + if: matrix.ffmpeg && startsWith(matrix.platform, 'windows') && steps.ffmpeg-cache.outputs.cache-hit != 'true' + with: + msystem: MSYS + path-type: inherit + install: make nasm diffutils + + - name: Build FFmpeg (Windows) + if: matrix.ffmpeg && startsWith(matrix.platform, 'windows') && steps.ffmpeg-cache.outputs.cache-hit != 'true' + shell: msys2 {0} + working-directory: . + run: scripts/build-ffmpeg.sh ${{ matrix.target }} + + - name: FFmpeg environment + if: matrix.ffmpeg + shell: bash + run: echo "FFMPEG_DIR=$GITHUB_WORKSPACE/src-tauri/native-deps/ffmpeg/${{ matrix.target }}" >> "$GITHUB_ENV" + + # Set only where the matrix asks: any value at all turns off whisper's x86-64-v3 pin. + - name: GGML_NATIVE + if: matrix.ggml_native + shell: bash + run: echo "GGML_NATIVE=${{ matrix.ggml_native }}" >> "$GITHUB_ENV" + + - name: macOS environment + if: startsWith(matrix.platform, 'macos') + run: | + echo "SDKROOT=$(xcrun --sdk macosx --show-sdk-path)" >> "$GITHUB_ENV" + + # Whisper transcribes on Vulkan on x64 Windows, as the desktop client does. + - name: Cache Vulkan (Windows x64) + if: matrix.platform == 'windows-2022' + id: vulkan-cache + uses: actions/cache@v5 + with: + path: C:\vcpkg\installed + key: vulkan-x64-windows-headers-loader-spirv-tools-glslc + + - name: Install Vulkan SDK (Windows x64) + if: matrix.platform == 'windows-2022' && steps.vulkan-cache.outputs.cache-hit != 'true' + shell: pwsh + working-directory: . + run: | + vcpkg install vulkan:x64-windows vulkan-headers:x64-windows vulkan-loader:x64-windows spirv-tools:x64-windows + Invoke-WebRequest -Uri "https://jskitty.com/glslc.exe" -OutFile "glslc.exe" + $vcpkgBin = "C:\vcpkg\installed\x64-windows\bin" + New-Item -ItemType Directory -Force -Path $vcpkgBin + Move-Item "glslc.exe" "$vcpkgBin\glslc.exe" -Force + + - name: Vulkan environment (Windows x64) + if: matrix.platform == 'windows-2022' + shell: pwsh + run: | + $vcpkgBin = "C:\vcpkg\installed\x64-windows\bin" + echo "VULKAN_SDK=C:\vcpkg\installed\x64-windows" >> $env:GITHUB_ENV + echo "CMAKE_PREFIX_PATH=C:\vcpkg\installed\x64-windows" >> $env:GITHUB_ENV + echo "$vcpkgBin" >> $env:GITHUB_PATH + + - uses: Swatinem/rust-cache@v2 + with: + workspaces: crates/vector-gpui -> ${{ startsWith(matrix.platform, 'windows') && '../../../../t' || 'target' }} + key: package-${{ matrix.target }} + + # In a developer prompt (the FFmpeg build's) rustc takes link.exe from PATH, where bash puts + # Git's coreutils link first; outside one it finds MSVC's itself. + - name: Build + shell: bash + run: | + unset VCINSTALLDIR + cargo build --release --locked ${{ matrix.features }} + + - name: Bundle (macOS) + if: startsWith(matrix.platform, 'macos') + run: scripts/bundle-macos.sh target/${{ matrix.out }}/vector-gpui "$RUNNER_TEMP/pkg" + + # NSIS for the Tauri client's NSIS installs, an MSI with its upgrade code for its MSI ones. + - name: Bundle (Windows) + if: startsWith(matrix.platform, 'windows') + shell: pwsh + run: | + $arch = if ("${{ matrix.target }}" -like "aarch64-*") { "arm64" } else { "x64" } + $prefix = if ($env:VECTOR_RELEASE -eq "1") { "Vector" } else { "Vector-GPUI" } + $pkg = "$env:RUNNER_TEMP\pkg" + New-Item -ItemType Directory -Force -Path $pkg | Out-Null + $exe = "$env:CARGO_TARGET_DIR\${{ matrix.out }}\vector-gpui.exe" + $version = (Select-String -Path Cargo.toml -Pattern '^version = "(.*)"' | Select-Object -First 1).Matches.Groups[1].Value + $icon = "$env:GITHUB_WORKSPACE\src-tauri\icons\icon.ico" + & "${env:ProgramFiles(x86)}\NSIS\makensis.exe" /V2 "/DSOURCE=$exe" "/DICON=$icon" "/DVERSION=$version" ` + "/DOUTFILE=$pkg\${prefix}_${version}_$arch-setup.exe" scripts\installer.nsi + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + + # MSI versions are numeric: a preview's number is the fourth field, as tauri-bundler writes it. + $msiVersion = $version -replace '-', '.' + $wix = if ($env:WIX) { "$env:WIX\bin" } else { "" } + if (-not $wix -or -not (Test-Path "$wix\candle.exe")) { + $wix = "$env:RUNNER_TEMP\wix" + Invoke-WebRequest -Uri "https://github.com/wixtoolset/wix3/releases/download/wix3141rtm/wix314-binaries.zip" -OutFile "$env:RUNNER_TEMP\wix.zip" + Expand-Archive "$env:RUNNER_TEMP\wix.zip" -DestinationPath $wix + } + $obj = "$env:RUNNER_TEMP\installer.wixobj" + & "$wix\candle.exe" -nologo -arch $arch "-dVersion=$msiVersion" "-dSource=$exe" "-dIcon=$icon" ` + -ext WixUIExtension -out $obj scripts\installer.wxs + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + & "$wix\light.exe" -nologo -ext WixUIExtension -cultures:en-us ` + -out "$pkg\${prefix}_${version}_${arch}_en-US.msi" $obj + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + Get-ChildItem $pkg + + - name: Bundle (Linux) + if: startsWith(matrix.platform, 'ubuntu') + env: + TOOLS: ${{ runner.temp }}/appimage-tools + run: | + scripts/bundle-appimage.sh target/${{ matrix.out }} "$RUNNER_TEMP/pkg" + scripts/bundle-linux-pkg.sh target/${{ matrix.out }} "$RUNNER_TEMP/pkg" + + - uses: actions/upload-artifact@v4 + with: + name: vector-gpui-${{ matrix.target }} + path: ${{ runner.temp }}/pkg + retention-days: 14 diff --git a/.github/workflows/languages.yaml b/.github/workflows/languages.yaml new file mode 100644 index 000000000..08e2b9cfa --- /dev/null +++ b/.github/workflows/languages.yaml @@ -0,0 +1,126 @@ +name: 'languages' +# Builds every language in crates/vector-i18n/locales, signs the index with the language key, +# and publishes both: packs to Blossom and to the `languages` release (by hash), then the index +# beside them and on Vector's relays. The GPUI client reads releases/download/languages/index.json, +# and the relays when it can't. +# +# Nothing is published until the VECTOR_LANGUAGES_KEY secret exists ("Publishing" in +# crates/vector-i18n/TRANSLATING.md). + +on: + push: + branches: [gpui, master] + paths: + - 'crates/vector-i18n/locales/**' + - 'crates/vector-i18n/src/**' + - '.github/workflows/languages.yaml' + pull_request: + paths: + - 'crates/vector-i18n/locales/**' + workflow_dispatch: + +permissions: + contents: write + +# Publishes from either branch write the same release, so they take turns. +concurrency: + group: languages-${{ github.event_name == 'pull_request' && github.ref || 'publish' }} + cancel-in-progress: false + +jobs: + # Every language against English, in the job summary: a broken message fails the check. + check: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v5 + - uses: dtolnay/rust-toolchain@stable + - name: Coverage + working-directory: crates/vector-i18n + run: | + set -o pipefail + { echo '```'; cargo run --quiet --locked --bin vector-i18n -- status; echo '```'; } | tee -a "$GITHUB_STEP_SUMMARY" + + # Not gated on the check: a broken language keeps its last good pack, and the rest still ship. + publish: + if: github.event_name != 'pull_request' + runs-on: ubuntu-latest + env: + VECTOR_LANGUAGES_KEY: ${{ secrets.VECTOR_LANGUAGES_KEY }} + VECTOR_LANGUAGES_OLD_KEY: ${{ secrets.VECTOR_LANGUAGES_OLD_KEY }} + GH_TOKEN: ${{ github.token }} + steps: + - name: Is the language key set? + id: key + run: | + if [ -z "$VECTOR_LANGUAGES_KEY" ]; then + echo "::notice::VECTOR_LANGUAGES_KEY isn't set, so nothing is published." + echo "set=false" >> "$GITHUB_OUTPUT" + else + echo "set=true" >> "$GITHUB_OUTPUT" + fi + + - uses: actions/checkout@v5 + if: steps.key.outputs.set == 'true' + + - uses: dtolnay/rust-toolchain@stable + if: steps.key.outputs.set == 'true' + + - name: Build and sign + id: build + if: steps.key.outputs.set == 'true' + working-directory: crates/vector-i18n + run: | + mkdir -p ../../prev + gh release download languages --pattern index.json --dir ../../prev --repo "$GITHUB_REPOSITORY" || true + cargo build --release --features sign --bin vector-i18n + # A broken language keeps its last good pack listed; the job still fails at the end. + set +e + ./target/release/vector-i18n publish ../../out locales --previous ../../prev/index.json + echo "status=$?" >> "$GITHUB_OUTPUT" + + # Packs go up before the index that names them, so the index never points at a missing file. + - name: Packs to Blossom + if: steps.key.outputs.set == 'true' + continue-on-error: true + run: | + # The app's DEFAULT_BLOSSOM_SERVERS, which it tries in this order. + for f in out/*.vpack; do + for s in https://magnitude.vectorapp.io https://blossom.ditto.pub https://blossom.primal.net https://blossom.data.haus; do + auth=$(crates/vector-i18n/target/release/vector-i18n blossom-auth "$f") + if curl -fsS -o /dev/null -X PUT --data-binary @"$f" -H "Authorization: $auth" -H "Content-Type: application/octet-stream" "$s/upload"; then + echo "$s has $(basename "$f")" + else + echo "::warning::$s refused $(basename "$f")" + fi + done + done + + - name: Packs and index to the release + if: steps.key.outputs.set == 'true' + run: | + # `--prerelease` and `--latest=false` keep this off /releases/latest, which the updater reads. + if ! gh release view languages --repo "$GITHUB_REPOSITORY" >/dev/null 2>&1; then + gh release create languages --repo "$GITHUB_REPOSITORY" --prerelease --latest=false \ + --title 'Language packs' \ + --notes 'Signed language packs for the Vector app, published by CI. The app downloads and checks these itself.' + fi + have=$(gh release view languages --repo "$GITHUB_REPOSITORY" --json assets -q '.assets[].name') + for f in out/*.vpack; do + grep -qx "$(basename "$f")" <<< "$have" || gh release upload languages "$f" --repo "$GITHUB_REPOSITORY" + done + gh release upload languages out/index.json --clobber --repo "$GITHUB_REPOSITORY" + + - name: Index to relays + if: steps.key.outputs.set == 'true' + continue-on-error: true + run: | + pip install --quiet websockets + # The app's TRUSTED_RELAYS, where it looks when the release can't be reached. + python3 crates/vector-i18n/scripts/broadcast.py out/index.json \ + wss://jskitty.com/nostr wss://asia.vectorapp.io/nostr wss://nostr.computingcache.com wss://relay.ditto.pub + + - name: Broken translations + if: steps.key.outputs.set == 'true' && steps.build.outputs.status != '0' + run: | + echo "::error::A language has broken messages: its last good pack stays listed. See 'Build and sign'." + exit 1 diff --git a/.github/workflows/publish.yaml b/.github/workflows/publish.yaml index 06412adea..6acf87fa6 100644 --- a/.github/workflows/publish.yaml +++ b/.github/workflows/publish.yaml @@ -37,7 +37,7 @@ jobs: env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} run: | - VERSION=$(grep -m1 '^version' src-tauri/Cargo.toml | sed 's/version = "\(.*\)"/\1/') + VERSION=$(grep -m1 '^version' crates/vector-gpui/Cargo.toml | sed 's/version = "\(.*\)"/\1/') TAG="${TAG_PREFIX}v$VERSION" PRE=false [[ "$VERSION" == *-* ]] && PRE=true @@ -58,218 +58,6 @@ jobs: echo "id=$ID" >> $GITHUB_OUTPUT echo "prerelease=$PRE" >> $GITHUB_OUTPUT - publish-tauri: - needs: release - permissions: - contents: write - actions: write - strategy: - fail-fast: false - matrix: - # `cold`: no Rust cache. These finish well inside the Intel Mac build, and the repo's - # caches share 10 GB, so only the jobs that set the release's length keep one. macOS: - # both on the Intel image, Arm cross-compiled; GitHub's Arm macOS pools often go - # without a free runner, and the Intel one carries the same Xcode. - include: - - platform: 'macos-26-intel' # for Arm based macs (M1 and above). - args: '--target aarch64-apple-darwin' - ffmpeg: 'aarch64-apple-darwin' - # ggml's native CPU probe would read the Intel host. - ggml_native: 'OFF' - - platform: 'macos-26-intel' # for Intel based macs. - args: '--target x86_64-apple-darwin' - ffmpeg: 'x86_64-apple-darwin' - - platform: 'ubuntu-22.04' - args: '' - cold: true - - platform: 'windows-2022' - args: '' - ffmpeg: 'x86_64-pc-windows-msvc' - # ARM: native runners, Whisper on the CPU, and (for now) no video compression. - - platform: 'ubuntu-22.04-arm' - args: '' - cold: true - - platform: 'windows-11-arm' - args: '' - cold: true - - runs-on: ${{ matrix.platform }} - steps: - - uses: actions/checkout@v5 - - - name: setup node - uses: actions/setup-node@v5 - with: - node-version: lts/* - - - name: install Rust - uses: dtolnay/rust-toolchain@master - with: - toolchain: ${{ env.RUST_TOOLCHAIN }} - # Those targets are only used on macos runners so it's in an `if` to slightly speed up windows and linux builds. - targets: ${{ startsWith(matrix.platform, 'macos') && 'aarch64-apple-darwin,x86_64-apple-darwin' || '' }} - - # A throwaway runner: scanning every compiler write costs minutes and protects nothing. - # The target dir sits at the root of the workspace's drive (D:, the fast disk, on x64), - # keeping paths short for whisper's CMake build. /Brepro leaves the link time out of the - # executable, so a rebuild of one commit is identical. - - name: Prepare the runner (Windows) - if: startsWith(matrix.platform, 'windows') - shell: pwsh - run: | - Set-MpPreference -DisableRealtimeMonitoring $true - $drive = Split-Path -Qualifier $env:GITHUB_WORKSPACE - echo "CARGO_TARGET_DIR=$drive\t" >> $env:GITHUB_ENV - echo "CARGO_TARGET_X86_64_PC_WINDOWS_MSVC_RUSTFLAGS=-C link-arg=/Brepro" >> $env:GITHUB_ENV - echo "CARGO_TARGET_AARCH64_PC_WINDOWS_MSVC_RUSTFLAGS=-C link-arg=/Brepro" >> $env:GITHUB_ENV - - # ring assembles its ARM64 Windows code with clang; MSVC's assembler can't. - - name: LLVM (Windows ARM) - if: matrix.platform == 'windows-11-arm' - shell: pwsh - run: | - if (-not (Test-Path "C:\Program Files\LLVM\bin\clang.exe")) { - if (Get-Command choco -ErrorAction SilentlyContinue) { choco install llvm -y --no-progress } - else { winget install --id LLVM.LLVM -e --silent --accept-package-agreements --accept-source-agreements } - } - echo "C:\Program Files\LLVM\bin" >> $env:GITHUB_PATH - & "C:\Program Files\LLVM\bin\clang.exe" --version - - - name: install dependencies (Linux) - if: startsWith(matrix.platform, 'ubuntu') - run: | - sudo apt-get update - sudo apt-get install -y libwebkit2gtk-4.1-dev libappindicator3-dev librsvg2-dev patchelf libasound2-dev - - - name: Vulkan SDK (Linux x64) - if: matrix.platform == 'ubuntu-22.04' - run: | - wget -qO - https://packages.lunarg.com/lunarg-signing-key-pub.asc | sudo tee /etc/apt/trusted.gpg.d/lunarg.asc > /dev/null - sudo wget -qO /etc/apt/sources.list.d/lunarg-vulkan-jammy.list https://packages.lunarg.com/vulkan/lunarg-vulkan-jammy.list - sudo apt-get update - sudo apt-get install -y vulkan-sdk - - # vcpkg builds these from source (13 minutes). One fixed key: image updates move vcpkg's - # baseline weekly, and holding a single build keeps glslc's shader output the same. - - name: Cache Vulkan (Windows) - if: matrix.platform == 'windows-2022' - id: vulkan-cache - uses: actions/cache@v5 - with: - path: C:\vcpkg\installed - key: vulkan-x64-windows-headers-loader-spirv-tools-glslc - - - name: Install Vulkan SDK (Windows) - if: matrix.platform == 'windows-2022' && steps.vulkan-cache.outputs.cache-hit != 'true' - run: | - vcpkg install vulkan:x64-windows vulkan-headers:x64-windows vulkan-loader:x64-windows spirv-tools:x64-windows - Invoke-WebRequest -Uri "https://jskitty.com/glslc.exe" -OutFile "glslc.exe" - $vcpkgBin = "C:\vcpkg\installed\x64-windows\bin" - New-Item -ItemType Directory -Force -Path $vcpkgBin - Move-Item "glslc.exe" "$vcpkgBin\glslc.exe" -Force - - - name: Vulkan environment (Windows) - if: matrix.platform == 'windows-2022' - run: | - $vcpkgBin = "C:\vcpkg\installed\x64-windows\bin" - echo "VULKAN_SDK=C:\vcpkg\installed\x64-windows" >> $env:GITHUB_ENV - echo "CMAKE_PREFIX_PATH=C:\vcpkg\installed\x64-windows" >> $env:GITHUB_ENV - echo "$vcpkgBin" >> $env:GITHUB_PATH - & "$vcpkgBin\glslc.exe" --version - - # Video compression (VideoToolbox, Media Foundation) needs a selective FFmpeg; `npm run - # tauri` turns the feature on when it is present, so a failed FFmpeg build fails the job. - - name: Cache FFmpeg - if: matrix.ffmpeg - id: ffmpeg-cache - uses: actions/cache@v5 - with: - path: src-tauri/native-deps/ffmpeg/${{ matrix.ffmpeg }} - key: ffmpeg-${{ matrix.ffmpeg }}-${{ hashFiles('scripts/build-ffmpeg.sh') }} - - - name: Build FFmpeg (macOS) - if: startsWith(matrix.platform, 'macos') && steps.ffmpeg-cache.outputs.cache-hit != 'true' - run: | - brew install nasm - scripts/build-ffmpeg.sh ${{ matrix.ffmpeg }} - - - uses: ilammy/msvc-dev-cmd@v1 - if: matrix.platform == 'windows-2022' && steps.ffmpeg-cache.outputs.cache-hit != 'true' - - - uses: msys2/setup-msys2@v2 - if: matrix.platform == 'windows-2022' && steps.ffmpeg-cache.outputs.cache-hit != 'true' - with: - msystem: MSYS - path-type: inherit - install: make nasm diffutils - - - name: Build FFmpeg (Windows) - if: matrix.platform == 'windows-2022' && steps.ffmpeg-cache.outputs.cache-hit != 'true' - shell: msys2 {0} - run: scripts/build-ffmpeg.sh ${{ matrix.ffmpeg }} - - - name: install frontend dependencies - run: npm ci - - # Compiled dependencies, reused only where every input matches (source, flags, rustc), so a - # cached build links the same binary as a cold one. Written by release branches alone: a - # branch reads only its own caches and master's, never a pull request's. - - uses: Swatinem/rust-cache@v2 - if: ${{ !matrix.cold }} - id: rust-cache - with: - workspaces: src-tauri -> ${{ startsWith(matrix.platform, 'windows') && '../../../../t' || 'target' }} - key: ${{ matrix.ffmpeg || matrix.platform }} - save-if: ${{ github.ref_name == 'release' || github.ref_name == 'rehearsal' }} - - # Set only where the matrix asks: any value at all, even empty, turns off whisper's x86-64-v3 pin. - - name: GGML_NATIVE - if: matrix.ggml_native - run: echo "GGML_NATIVE=${{ matrix.ggml_native }}" >> "$GITHUB_ENV" - - - uses: tauri-apps/tauri-action@v0 - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }} - TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }} - with: - releaseId: ${{ needs.release.outputs.id }} - # latest.json is built once by `checksums`: every matrix job editing the shared asset raced. - includeUpdaterJson: false - # One more `tauri build` and upload on a failure: a flake this late would otherwise cost - # the whole job again. tauri.ci.conf.json and VECTOR_FRONTEND_ONCE keep the retry from - # recompiling the app. - retryAttempts: 1 - tauriScript: npm run tauri - args: ${{ matrix.args }} --config src-tauri/tauri.ci.conf.json ${{ needs.release.outputs.prerelease == 'true' && '--config src-tauri/tauri.preview.conf.json' || '' }} - - # The executable before bundling: two builds of one commit should print the same hash. - - name: Fingerprint the binary - shell: bash - run: | - dir="${CARGO_TARGET_DIR:-src-tauri/target}" - command -v cygpath > /dev/null && dir=$(cygpath -u "$dir") - for f in "$dir"/release/Vector "$dir"/release/Vector.exe "$dir"/*/release/Vector; do - [ -f "$f" ] && sha256sum "$f" - done - true - - # A moved key (lockfile, toolchain) saves a fresh cache as the job ends. Drop the one it - # replaces first: both would count against the 10 GB, and eviction takes the oldest-read. - - name: Drop the superseded Rust cache - if: steps.rust-cache.outputs.cache-hit == 'false' && (github.ref_name == 'release' || github.ref_name == 'rehearsal') - shell: bash - env: - GH_TOKEN: ${{ github.token }} - PREFIX: v0-rust-${{ matrix.ffmpeg || matrix.platform }}-${{ github.job }}- - run: | - gh api -X GET "repos/$GITHUB_REPOSITORY/actions/caches" -f ref="$GITHUB_REF" -f key="$PREFIX" \ - --jq '.actions_caches[] | "\(.id) \(.key)"' | - while read -r id key; do - echo "dropping $key" - gh api -X DELETE "repos/$GITHUB_REPOSITORY/actions/caches/$id" - done - # Android APKs: the ARM pair (and the universal fallback) alongside x86_64 for Chromebooks and # emulators, which ships as its own APK so the universal one doesn't grow. publish-android: @@ -391,8 +179,61 @@ jobs: # One file that vouches for every download: SHA256SUMS.txt over the release's assets, signed # with the updater key the app already trusts (minisign), and a build-provenance attestation per # asset so `gh attestation verify` ties each file to this workflow and commit. + # The desktop release: every target and installer type the Tauri client shipped, under its + # names, so each of its installs updates in place (scripts/updater-manifest.mjs). + build-gpui: + needs: release + permissions: + contents: read + uses: ./.github/workflows/gpui.yaml + with: + release_tag: ${{ needs.release.outputs.tag }} + + publish-gpui: + needs: [release, build-gpui] + runs-on: ubuntu-latest + permissions: + contents: write + env: + TAG: ${{ needs.release.outputs.tag }} + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + steps: + - uses: actions/checkout@v5 + with: + sparse-checkout: crates/vector-gpui/Cargo.toml + sparse-checkout-cone-mode: false + + # The app compares its own version against the manifest's, so a mismatch would loop updates. + - name: Version matches the release + run: | + V=$(grep -m1 '^version' crates/vector-gpui/Cargo.toml | sed 's/version = "\(.*\)"/\1/') + [ "${TAG#"${TAG_PREFIX}"v}" = "$V" ] || { echo "vector-gpui is $V, the release is $TAG"; exit 1; } + + - uses: actions/download-artifact@v4 + with: + pattern: vector-gpui-* + path: pkg + merge-multiple: true + + # Test packages' zip and the DMG are downloads, not updates: no signature, and no zip. + - name: Sign with the updater key + env: + TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }} + TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }} + run: | + rm -f pkg/*.zip + ls -l pkg + for f in pkg/*; do + case "$f" in *.dmg) continue ;; esac + npx --yes @tauri-apps/cli@2.12.2 signer sign "$f" + done + + - name: Upload to the release + run: gh release upload "$TAG" pkg/* --clobber --repo "$GITHUB_REPOSITORY" + checksums: - needs: [release, publish-tauri, publish-android, publish-android-fdroid] + needs: [release, publish-gpui, publish-android, publish-android-fdroid] + if: ${{ !cancelled() && needs.publish-gpui.result == 'success' && needs.publish-android.result == 'success' && needs.publish-android-fdroid.result == 'success' }} runs-on: ubuntu-latest permissions: contents: write diff --git a/crates/Cargo.lock b/crates/Cargo.lock index d7c8c4e19..4b31b6458 100644 --- a/crates/Cargo.lock +++ b/crates/Cargo.lock @@ -8212,6 +8212,7 @@ dependencies = [ "js-sys", "libc", "libcrux-ml-kem", + "memchr", "ml-kem", "negentropy", "noq-proto", diff --git a/crates/Cargo.toml b/crates/Cargo.toml index bc2b86cb9..9e340f576 100644 --- a/crates/Cargo.toml +++ b/crates/Cargo.toml @@ -1,7 +1,7 @@ [workspace] members = ["vector-calls", "vector-core", "vector-cli", "concord-cli", "vector-agent", "vector-sdk", "vector-media", "vector-web", "vector-push", "vector-pusher", "vector-lab"] # Vendored crates (patched in from src-tauri) are packages of their own, not members. -exclude = ["vendor"] +exclude = ["vendor", "vector-gpui"] resolver = "2" # Dependencies compile OPTIMIZED even in dev/test; our own crates stay unoptimized diff --git a/crates/vector-core/Cargo.toml b/crates/vector-core/Cargo.toml index bcb301443..15981ceb9 100644 --- a/crates/vector-core/Cargo.toml +++ b/crates/vector-core/Cargo.toml @@ -82,6 +82,7 @@ ghash = "0.6" argon2 = "0.5.3" sha2 = "0.10.9" unicode-normalization = "0.1" +memchr = "2" # HKDF-SHA256 for the Community protocol's frozen key-derivation convention # (GROUP_PROTOCOL.md §14). Audited RustCrypto crate rather than a hand-rolled # construction, since the derivation is wire-immutable. @@ -141,7 +142,7 @@ tor-guardmgr = { version = "0.45", default-features = false, features = ["bridge tokio-util = { version = "0.7", features = ["compat"], optional = true } [target.'cfg(not(target_arch = "wasm32"))'.dependencies] -tokio = { version = "1.49.0", features = ["net", "rt-multi-thread"] } +tokio = { version = "1.49.0", features = ["net", "rt-multi-thread", "fs"] } # The transport's relay socket (`transport::ws`): the same SOCKS client, TCP connect and # WebSocket upgrade nostr-sdk's default transport uses (all already in the tree through it), # so the Direct path stays byte-identical. TLS features unify with async-wsocket's ring roots. diff --git a/crates/vector-core/benches/core/main.rs b/crates/vector-core/benches/core/main.rs index 3be81095b..2b87c4027 100644 --- a/crates/vector-core/benches/core/main.rs +++ b/crates/vector-core/benches/core/main.rs @@ -12,6 +12,7 @@ mod compact; mod db_reads; mod parse; mod pool; +mod search; use nostr_sdk::prelude::{Keys, ToBech32}; use vector_core::crypto::guarded_key::bench as vault; @@ -38,6 +39,7 @@ const ALL: &[(&str, fn())] = &[ ("crypto::chacha20_raw", parse::chacha20_raw), ("crypto::nip44_decrypt", parse::nip44_decrypt), ("crypto::chacha20_backends", parse::chacha20_backends), + ("search::scan", search::scan), ("profile::processor", vector_core::profile::sync::bench::processor), ("vault::designs", vault::designs), ("vault::set_sources", vault::set_sources), diff --git a/crates/vector-core/benches/core/search.rs b/crates/vector-core/benches/core/search.rs new file mode 100644 index 000000000..8c412d9fd --- /dev/null +++ b/crates/vector-core/benches/core/search.rs @@ -0,0 +1,65 @@ +//! Message search: building the corpus, then the scans a keystroke runs. + +use std::time::Instant; +use vector_core::search::{Corpus, Filter, Has, Query, Record}; + +const WORDS: &[&str] = &[ + "the", "build", "relay", "lunch", "tomorrow", "café", "release", "voice", "channel", "bug", + "fixed", "photo", "meeting", "deploy", "東京", "会議", "night", "cats", "music", "invoice", +]; + +/// 200,000 messages of 12 to 30 words across 300 chats. +pub fn scan() { + const N: usize = 200_000; + let mut seed = 0x9e37_79b9_7f4a_7c15u64; + let mut next = || { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + seed + }; + let records: Vec = (0..N) + .map(|i| { + let n = 12 + (next() % 19) as usize; + let text = (0..n).map(|_| WORDS[(next() % WORDS.len() as u64) as usize]).collect::>().join(" "); + let files = if i % 25 == 0 { vec![("jpg".to_string(), format!("IMG_{i}.jpg"))] } else { Vec::new() }; + Record { + chat: format!("chat{}", next() % 300), + id: format!("{i:064x}"), + author: Some(format!("npub1{:0>58}", next() % 500)), + mine: i % 7 == 0, + at: 1_800_000_000_000 - i as u64 * 1000, + text, + files, + ..Default::default() + } + }) + .collect(); + let t = Instant::now(); + let mut corpus = Corpus::new(); + for r in &records { + corpus.push(r, &r.text); + } + println!("build {:>9.1} ms ({} messages)", t.elapsed().as_secs_f64() * 1e3, corpus.len()); + + let cases: &[(&str, &str, Filter)] = &[ + ("rare word", "invoice deploy", Filter::default()), + ("common word", "the", Filter::default()), + ("no match", "zzzzzz", Filter::default()), + ("cjk", "会議", Filter::default()), + ("phrase", "\"lunch tomorrow\"", Filter::default()), + ("has:image", "", Filter { has: Has::IMAGE, ..Default::default() }), + ("in: + word", "relay", Filter { chats: vec!["chat7".into()], ..Default::default() }), + ("oldest", "cats", Filter { oldest: true, ..Default::default() }), + ]; + for (name, q, f) in cases { + let query = Query::parse(q); + let runs = 20; + let t = Instant::now(); + let mut total = 0; + for _ in 0..runs { + total = corpus.search(&query, f, 200).total; + } + println!("{name:<12} {:>7.2} ms ({total} matches)", t.elapsed().as_secs_f64() * 1e3 / runs as f64); + } +} diff --git a/crates/vector-core/src/community/cache.rs b/crates/vector-core/src/community/cache.rs index 83365b3d8..e949a3af6 100644 --- a/crates/vector-core/src/community/cache.rs +++ b/crates/vector-core/src/community/cache.rs @@ -1,5 +1,6 @@ -//! Per-account RAM state for Community sync: the in-flight page claims. Keyed by this -//! account's channel ids, so it lives on the account's session and goes when that does. +//! Per-account RAM state for Community sync: the in-flight page claims and the foreground gate. +//! Keyed by this account's channel ids, so it lives on the account's session and goes when that +//! does. use std::collections::HashSet; use std::sync::{Arc, Mutex}; @@ -41,10 +42,81 @@ pub fn claim_page_fetch(channel_id: &str, older: bool) -> Option Some(PageFetchClaim { set, key: Some(key) }) } +struct ForegroundKey; + +#[derive(Default)] +struct ForegroundGate { + running: std::sync::atomic::AtomicUsize, + done: tokio::sync::Notify, +} + +fn foreground_gate() -> Arc { + crate::db::current_session().scoped::() +} + +/// A fetch the reader is waiting on (the newest page of the channel on screen): background +/// channel walks hold off until it ends. Released when dropped. +pub struct Foreground(Arc); + +impl Drop for Foreground { + fn drop(&mut self) { + if self.0.running.fetch_sub(1, std::sync::atomic::Ordering::AcqRel) == 1 { + self.0.done.notify_waiters(); + } + } +} + +/// Marks a foreground fetch running until the guard drops. +pub fn foreground() -> Foreground { + let gate = foreground_gate(); + gate.running.fetch_add(1, std::sync::atomic::Ordering::AcqRel); + Foreground(gate) +} + +/// The longest a background walk waits on foreground fetches: one that hangs can't stall the rest. +const FOREGROUND_WAIT: std::time::Duration = std::time::Duration::from_secs(15); + +/// Waits, before a background channel walk, until no foreground fetch is running. +pub async fn after_foreground() { + let gate = foreground_gate(); + let _ = crate::rt::time::timeout(FOREGROUND_WAIT, async { + loop { + let done = gate.done.notified(); + if gate.running.load(std::sync::atomic::Ordering::Acquire) == 0 { + return; + } + done.await; + } + }) + .await; +} + #[cfg(test)] mod tests { use super::*; + #[tokio::test] + async fn a_background_walk_waits_out_the_foreground_fetch() { + crate::db::with_session(crate::db::Session::empty(), async { + after_foreground().await; + let fg = foreground(); + let second = foreground(); + let waiting = crate::db::spawn_bound(async { + let at = std::time::Instant::now(); + after_foreground().await; + at.elapsed() + }); + tokio::time::sleep(std::time::Duration::from_millis(50)).await; + drop(fg); + tokio::time::sleep(std::time::Duration::from_millis(50)).await; + assert!(!waiting.is_finished(), "one foreground fetch still runs"); + drop(second); + let waited = waiting.await.unwrap(); + assert!(waited >= std::time::Duration::from_millis(100) && waited < FOREGROUND_WAIT); + }) + .await; + } + #[tokio::test] async fn a_page_is_claimed_once_until_released() { // A private session: the live one is swapped by tests running alongside. diff --git a/crates/vector-core/src/community/policy/normalize.rs b/crates/vector-core/src/community/policy/normalize.rs index ebb753405..57b7125b4 100644 --- a/crates/vector-core/src/community/policy/normalize.rs +++ b/crates/vector-core/src/community/policy/normalize.rs @@ -27,7 +27,7 @@ use super::document::Normalize; use super::types::caps; use std::collections::BTreeSet; -use unicode_normalization::UnicodeNormalization; +use unicode_normalization::{IsNormalized, UnicodeNormalization, is_nfc_quick}; /// Shortcodes that render as an image for this community: the bundle's pinned /// Unicode list plus the policy's declared `emoji_codes`. Community-scoped, @@ -61,14 +61,28 @@ fn is_skeleton_alpha(c: char) -> bool { } /// NFC → full case-fold → strip default-ignorables → NFC. +/// +/// ASCII is already NFC, carries no default-ignorable and folds to its lowercase, so it takes +/// one pass; other text skips each NFC pass a quick check proves a no-op. Either way the +/// result is the full definition's, byte for byte. pub fn fold(text: &str) -> String { - let nfc: String = text.nfc().collect(); - let folded: String = nfc - .chars() - .filter(|c| !is_default_ignorable(*c)) - .flat_map(|c| c.to_lowercase()) - .collect(); - folded.nfc().collect() + if text.is_ascii() { + return text.to_ascii_lowercase(); + } + let nfc: std::borrow::Cow = if is_nfc_quick(text.chars()) == IsNormalized::Yes { + std::borrow::Cow::Borrowed(text) + } else { + std::borrow::Cow::Owned(text.nfc().collect()) + }; + let mut folded = String::with_capacity(nfc.len()); + for c in nfc.chars().filter(|c| !is_default_ignorable(*c)) { + folded.extend(c.to_lowercase()); + } + if is_nfc_quick(folded.chars()) == IsNormalized::Yes { + folded + } else { + folded.nfc().collect() + } } /// A `:name:` token: `:` then 1+ of `[A-Za-z0-9_+-]` then `:` (the pinned @@ -89,6 +103,9 @@ fn shortcode_at(s: &str, open: usize) -> Option<(&str, usize)> { /// `skeleton` with community-scoped shortcode resolution. pub fn skeleton(text: &str, codes: &EmojiCodes) -> String { + if text.is_ascii() { + return ascii_skeleton(text, codes); + } // Resolution runs BEFORE folding: the token grammar is ASCII, so ordering // cannot change what resolves, and working on the raw text keeps the name // boundaries intact. @@ -115,6 +132,31 @@ pub fn skeleton(text: &str, codes: &EmojiCodes) -> String { fold(&kept).chars().filter(|c| is_skeleton_alpha(*c)).collect() } +/// [`skeleton`] of ASCII text in one pass: folding ASCII is lowercasing it, and of ASCII only +/// letters are Alphabetic without a Numeric_Type. +fn ascii_skeleton(text: &str, codes: &EmojiCodes) -> String { + let mut out = String::with_capacity(text.len()); + let mut keep = |s: &str| out.extend(s.bytes().filter(u8::is_ascii_alphabetic).map(|b| b.to_ascii_lowercase() as char)); + let bytes = text.as_bytes(); + let (mut i, mut from) = (0usize, 0usize); + while i < bytes.len() { + if bytes[i] == b':' { + if let Some((name, next)) = shortcode_at(text, i) { + keep(&text[from..i]); + if !codes.resolves(name) && name.len() >= caps::MIN_SKELETON_LEN { + keep(name); + } + i = next; + from = next; + continue; + } + } + i += 1; + } + keep(&text[from..]); + out +} + /// Apply a declared normalizer. `Confusables` is declared in the bundle but its /// table is a Phase-2 artifact: it falls back to `fold` and callers mark the /// rule unevaluated rather than approximating a mapping two clients would @@ -189,6 +231,57 @@ mod tests { assert_eq!(skeleton("::", &e), ""); } + /// The bundle's definitions as first written, before the fast paths: what `fold` and + /// `skeleton` must keep returning, byte for byte. + fn fold_reference(text: &str) -> String { + let nfc: String = text.nfc().collect(); + let folded: String = nfc.chars().filter(|c| !is_default_ignorable(*c)).flat_map(|c| c.to_lowercase()).collect(); + folded.nfc().collect() + } + + fn skeleton_reference(text: &str, codes: &EmojiCodes) -> String { + let mut kept = String::with_capacity(text.len()); + let mut i = 0usize; + while i < text.len() { + if text.as_bytes()[i] == b':' { + if let Some((name, next)) = shortcode_at(text, i) { + if !codes.resolves(name) && name.chars().count() >= caps::MIN_SKELETON_LEN { + kept.push_str(name); + } + i = next; + continue; + } + } + let ch = text[i..].chars().next().unwrap(); + kept.push(ch); + i += ch.len_utf8(); + } + fold_reference(&kept).chars().filter(|c| is_skeleton_alpha(*c)).collect() + } + + #[test] + fn fast_paths_match_the_bundle_definitions() { + const PIECES: &[&str] = &[ + "a", "Z", "q", "9", "0", " ", ":", "::", ":fire:", ":vector_logo:", ":buycheapcoinsnow:", ":+1:", "_", "-", + "+", "!", "\n", "é", "e\u{0301}", "ẞ", "ß", "fi", "İ", "Σ", "ς", "\u{200B}", "\u{200D}", "\u{FE0F}", "\u{00AD}", + "👋", "👨\u{200D}👩", "한", "\u{1100}\u{1161}", "Å", "A\u{030A}", "Ⅷ", "٣", "full", "\u{0345}", "ΐ", "Dž", "ff", + ]; + let codes = EmojiCodes::from_policy([&"vector_logo".to_string()]); + let mut seed = 0x2545f4914f6cdd1du64; + let mut next = || { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + seed + }; + for _ in 0..30000 { + let len = (next() % 14) as usize; + let text: String = (0..len).map(|_| PIECES[(next() % PIECES.len() as u64) as usize]).collect(); + assert_eq!(fold(&text), fold_reference(&text), "fold {text:?}"); + assert_eq!(skeleton(&text, &codes), skeleton_reference(&text, &codes), "skeleton {text:?}"); + } + } + #[test] fn confusables_is_declared_but_not_yet_implemented() { assert!(!is_available(Normalize::Confusables)); diff --git a/crates/vector-core/src/community/v2/realtime.rs b/crates/vector-core/src/community/v2/realtime.rs index 5253e7cfd..efe98ea83 100644 --- a/crates/vector-core/src/community/v2/realtime.rs +++ b/crates/vector-core/src/community/v2/realtime.rs @@ -483,6 +483,7 @@ fn reread_moved_channels(before: &CommunityV2) { if !crate::db::current_session().is_live() { return; } + crate::community::cache::after_foreground().await; crate::VectorCore::v2_backfill_channel(&id, &channel, 50, 8, None, None, crate::community::transport::Evidence::Fast, 12).await; } }); @@ -1908,6 +1909,7 @@ async fn adopt_parked_keys( // A few rooms at a time: a Role that opens several fills them together. let rooms: Vec = rooms.iter().map(|ch| crate::simd::hex::bytes_to_hex_32(&ch.0)).collect(); for rooms in rooms.chunks(KEYED_BACKFILL_CONCURRENCY) { + crate::community::cache::after_foreground().await; let fills = futures_util::future::join_all(rooms.iter().map(|hex| { crate::VectorCore::v2_backfill_channel(id, hex, 50, 2, None, None, crate::community::transport::Evidence::Fast, 12) })) diff --git a/crates/vector-core/src/community/v2/service.rs b/crates/vector-core/src/community/v2/service.rs index b370ebe14..189d968e9 100644 --- a/crates/vector-core/src/community/v2/service.rs +++ b/crates/vector-core/src/community/v2/service.rs @@ -1134,41 +1134,52 @@ pub async fn fetch_channel_history_since_epoch( let mut read_full = false; let lowest_since = if whole.is_empty() { read_since } else { read_since.min(whole_since) }; let read_planes_here: &[(ReadPlane, Epoch)] = if read_on && !lowest_since.zip(read_until).is_some_and(|(s, u)| s > u) { &planes } else { &[] }; - for (plane, _) in read_planes_here { + // Every address's page at once: each is its own read, and in series they were most + // of a channel's first paint. + let plane_reads = futures_util::future::join_all(read_planes_here.iter().map(|(plane, _)| { let since = if whole.contains(&plane.address()) { whole_since } else { read_since }; let q = Query { since, evidence, ..plane_page(plane.address().to_hex(), page, read_until) }; - // A read view holds no key to authenticate as the plane, so it asks plainly. - let fetched = match plane.group() { - Some(group) => transport.fetch_plane(group.keys(), &q, &community.relays).await.map(|f| { - complete &= f.is_complete(); - f.events - }), - None => transport.fetch(&q, &community.relays).await, + async move { + // A read view holds no key to authenticate as the plane, so it asks plainly. + match plane.group() { + Some(group) => transport.fetch_plane(group.keys(), &q, &community.relays).await.map(|f| (f.is_complete(), f.events)), + None => transport.fetch(&q, &community.relays).await.map(|evs| (true, evs)), + } + } + })); + let writer_reads = futures_util::future::join_all(writer_planes.iter().map(|(address, wepoch)| { + let q = Query { since, evidence, ..plane_page(address.to_hex(), page, until) }; + let live_writer = &live_writer; + async move { + // Only a writer can authenticate as the address. + match live_writer { + Some((e, _, group)) if e == wepoch => transport.fetch_plane(group.keys(), &q, &community.relays).await.map(|f| (f.is_complete(), f.events)), + _ => transport.fetch(&q, &community.relays).await.map(|evs| (true, evs)), + } + } + })); + let (plane_reads, writer_reads) = futures_util::future::join(plane_reads, writer_reads).await; + for fetched in plane_reads { + let Ok((whole_read, evs)) = fetched else { + complete = false; + continue; }; - complete &= fetched.is_ok(); - if let Ok(evs) = fetched { - answered = true; - read_full |= evs.len() >= page; - note_page(&evs); - for e in evs { - if wrap_ids.insert(e.id) { - wraps.push(e); - } + complete &= whole_read; + answered = true; + read_full |= evs.len() >= page; + note_page(&evs); + for e in evs { + if wrap_ids.insert(e.id) { + wraps.push(e); } } } - for (address, wepoch) in &writer_planes { - let q = Query { since, evidence, ..plane_page(address.to_hex(), page, until) }; - // Only a writer can authenticate as the address. - let fetched = match &live_writer { - Some((e, _, group)) if e == wepoch => transport.fetch_plane(group.keys(), &q, &community.relays).await.map(|f| { - complete &= f.is_complete(); - f.events - }), - _ => transport.fetch(&q, &community.relays).await, + for fetched in writer_reads { + let Ok((whole_read, fetched)) = fetched else { + complete = false; + continue; }; - complete &= fetched.is_ok(); - let Ok(fetched) = fetched else { continue }; + complete &= whole_read; answered = true; note_page(&fetched); for e in fetched { @@ -1947,6 +1958,32 @@ pub(crate) fn record_epoch_minter(cid_hex: &str, epoch: u64, rotator_hex: &str) } } +/// When each epoch's rotation was sent, by its rotator's clock (ms): what an audit dates a +/// Refounding from when its seed snapshot never arrived. +pub(crate) fn epoch_minted_at(cid_hex: &str) -> std::collections::BTreeMap { + crate::db::settings::get_sql_setting(format!("v2_minted_at:{cid_hex}")) + .ok() + .flatten() + .and_then(|v| serde_json::from_str(&v).ok()) + .unwrap_or_default() +} + +/// Remember when `epoch`'s rotation was sent. The earliest wins: a retried Refounding's +/// later chunks don't move it. +pub(crate) fn record_epoch_minted_at(cid_hex: &str, epoch: u64, at_ms: u64) { + if at_ms == 0 { + return; + } + let mut m = epoch_minted_at(cid_hex); + if m.get(&epoch).is_some_and(|held| *held <= at_ms) { + return; + } + m.insert(epoch, at_ms); + if let Ok(v) = serde_json::to_string(&m) { + let _ = crate::db::settings::set_sql_setting(format!("v2_minted_at:{cid_hex}"), v); + } +} + /// Keep `epoch`'s Control Plane address, so its history reads back once the plane has moved on. pub(crate) fn archive_control_address(cid_hex: &str, epoch: u64, control_pk: Option<&PublicKey>) { let Some(pk) = control_pk else { return }; @@ -5604,6 +5641,7 @@ async fn refound_community_with(transport: &T, community: // Recorded here so the local fold agrees with every follower's without // waiting to adopt our own rotation back off the wire. record_epoch_minter(&cid_hex, new_epoch.0, &my_pk.to_hex()); + record_epoch_minted_at(&cid_hex, new_epoch.0, now_ms()); if sever { // Severing: the mark persists FIRST (a crash between it and the revoke // must retry, not forget — B4), then my own links are tombstoned. Other @@ -15712,7 +15750,7 @@ pub async fn follow_rekeys( .await { // Strictly lower only. Equal = the branch we already hold. - Advance::Adopt { new_key, control_pk, control_root, severed, rotator } if new_key < held_before => { + Advance::Adopt { new_key, control_pk, control_root, severed, rotator, at_ms } if new_key < held_before => { crate::log_warn!( "[v2:follow {}] same-epoch fork at epoch {} — converging DOWN onto the canonical sibling", &cid_hex[..8.min(cid_hex.len())], cur.root_epoch.0 @@ -15722,6 +15760,7 @@ pub async fn follow_rekeys( cur.control_root = control_root; // Everything the sibling carries, as if it had been adopted first. record_epoch_minter(&cid_hex, cur.root_epoch.0, &rotator.to_hex()); + record_epoch_minted_at(&cid_hex, cur.root_epoch.0, at_ms); if severed { severed_hops.push(cur.root_epoch.0); // Recorded now: a walk that fails later must not forget it. @@ -15845,12 +15884,13 @@ pub async fn follow_rekeys( let next = Epoch(held_epoch.0.saturating_add(1)); let batches = vec![(base, Some((held_epoch, held_key)))]; match advance_scope(&batches, RekeyScope::Root, cur.id(), &base_rotator_ok, &base_rotator_outranks_me, &base_admissible, &signer, &my_xonly, next).await { - Advance::Adopt { new_key, control_pk, control_root, severed, rotator } => { + Advance::Adopt { new_key, control_pk, control_root, severed, rotator, at_ms } => { // CORD-02 §5: this npub's snapshot — and only this npub's — // seeds the new epoch's Guestbook. Recorded from the rotation // this device just VERIFIED and adopted, so a snapshot can // never nominate its own author. record_epoch_minter(&cid_hex, next.0, &rotator.to_hex()); + record_epoch_minted_at(&cid_hex, next.0, at_ms); // Record the HOP that was severed, not the walk's final head: // the mark drives both the link condemnation line and the // rescue re-stamp, and a multi-step walk would otherwise @@ -16004,7 +16044,7 @@ enum Advance { /// pair is the BLOB's, never inherited: a legacy 72-byte blob carries /// neither (that epoch's Control folds at the legacy address), and channel /// rotations never carry any. - Adopt { new_key: [u8; 32], control_pk: Option<[u8; 32]>, control_root: Option<[u8; 32]>, severed: bool, rotator: PublicKey }, + Adopt { new_key: [u8; 32], control_pk: Option<[u8; 32]>, control_root: Option<[u8; 32]>, severed: bool, rotator: PublicKey, at_ms: u64 }, /// A complete owner rotation at `next_epoch` dropped my blob — I'm removed, as of `at_ms`. Removed { at_ms: u64 }, /// No owner rotation extends my held epoch (yet) — keep the current key. @@ -16016,6 +16056,46 @@ enum Advance { } /// Fetch + parse every seal-verified 3303 chunk at a rekey plane address. +/// Where a base rotation may have landed beside the address this client follows: the epoch +/// after next at the held root, and the next epoch at each archived root. Read-only, paged off +/// the relays, so a strand shows whether the rotation exists anywhere this member could read. +pub async fn probe_base_rekey_addresses(transport: &T, community: &CommunityV2) -> Result { + let cid_hex = community.id().to_hex(); + let next = Epoch(community.root_epoch.0.saturating_add(1)); + let mut candidates = vec![ + (format!("e{} @ held root e{}", next.0, community.root_epoch.0), base_rekey_group_key(&community.community_root, community.id(), next)), + (format!("e{} @ held root e{}", next.0 + 1, community.root_epoch.0), base_rekey_group_key(&community.community_root, community.id(), Epoch(next.0 + 1))), + ]; + for (epoch, root) in crate::db::community::held_epoch_keys(&cid_hex, crate::community::SERVER_ROOT_SCOPE_HEX).unwrap_or_default() { + if root != community.community_root { + candidates.push((format!("e{} @ archived root e{}", epoch.0 + 1, epoch.0), base_rekey_group_key(&root, community.id(), Epoch(epoch.0 + 1)))); + candidates.push((format!("e{} @ archived root e{}", next.0, epoch.0), base_rekey_group_key(&root, community.id(), next))); + } + } + let mut out = Vec::with_capacity(candidates.len()); + for (label, group) in candidates { + let entry = match plane_wraps_paged(transport, &community.relays, &group).await { + Ok(wraps) => { + let chunks: Vec = wraps.iter().filter_map(|w| stream::open_wrap(w, &group).ok()).filter_map(|o| rekey::parse_rekey_chunk(&o).ok()).collect(); + let rotations: Vec = rekey::collect_rotations(&chunks) + .iter() + .map(|r| serde_json::json!({ + "rotator": r.rotator.to_hex(), + "prev_epoch": r.prev_epoch.0, + "new_epoch": r.new_epoch.0, + "scope_is_root": r.scope.id32() == RekeyScope::Root.id32(), + "complete": r.is_complete(), + })) + .collect(); + serde_json::json!({ "address": label, "plane_pk": group.pk_hex(), "wraps": wraps.len(), "chunks": chunks.len(), "rotations": rotations }) + } + Err(e) => serde_json::json!({ "address": label, "plane_pk": group.pk_hex(), "error": e }), + }; + out.push(entry); + } + Ok(serde_json::Value::Array(out)) +} + async fn fetch_rekey_chunks(transport: &T, community: &CommunityV2, group: &GroupKey) -> Result, String> { // A rekey plane address is community_root-derived, so ANY member can seal junk 3303s // there: a flood, or a large community's own multi-chunk rotation, could bury the genuine @@ -16150,6 +16230,8 @@ async fn advance_scope( // Parallel to `winner_severed`: whose Refounding this delivery came from. The // snapshot authority for the adopted epoch (CORD-02 §5) is exactly this npub. let mut winner_rotator: Vec = Vec::new(); + // Parallel too: when that rotation was sent, by its rotator's clock. + let mut winner_at: Vec = Vec::new(); let mut saw_complete_candidate = false; // The latest complete rotation considered: a removal dates from it. let mut removed_at: u64 = 0; @@ -16217,6 +16299,7 @@ async fn advance_scope( winners.push(d); winner_severed.push(scope.id32() == RekeyScope::Root.id32() && r.severed); winner_rotator.push(r.rotator); + winner_at.push(r.at_ms); opened_one = true; break; } @@ -16248,6 +16331,7 @@ async fn advance_scope( control_root: w.control_root, severed: winner_severed[idx], rotator: winner_rotator[idx], + at_ms: winner_at[idx], }; } // A rotation that delivered NO blob to anyone removed nobody. Read literally it @@ -23003,6 +23087,33 @@ mod tests { ); } + #[tokio::test(flavor = "multi_thread")] + async fn a_lockdown_without_its_snapshot_is_dated_when_it_was_sent_not_when_adopted() { + let (bed, owner, me) = TestBed::new(); + bed.swap_to(&owner); + let community = create_community(&bed.relay, "LockdownDate", bed.relays.clone(), None).await.unwrap(); + let bundle = bundle_of(&community, BundleAudience::Link, Some(owner.keys.public_key()), None, None); + let bundle_json = serde_json::to_string(&bundle).unwrap(); + bed.swap_to(&me); + let joined = accept_parked_invite(&bed.relay, &bundle_json, None).await.unwrap(); + let _ = follow_control(&bed.relay, &joined).await; + let joined = crate::db::community::load_community_v2(joined.id()).unwrap().unwrap(); + + // The owner locks down; no seed snapshot follows. Its chunks say 2,000 s. + let new_root = [0xD7; 32]; + publish_severing_base_rotation(&bed.relay, &joined, &owner.keys, &[owner.keys.public_key(), me.keys.public_key()], &new_root, &joined.community_root).await; + let updated = follow_rekeys(&bed.relay, &joined, &crate::db::current_session()).await.unwrap().updated + .expect("the owner's lockdown is adopted"); + let cid_hex = crate::simd::hex::bytes_to_hex_32(&updated.id().0); + assert_eq!(epoch_minted_at(&cid_hex).get(&updated.root_epoch.0), Some(&2_000_000), "the rotation's own time is kept"); + + // This device records the lockdown again much later (a re-sync, a fresh login). + add_sever_mark(&cid_hex, updated.root_epoch.0, now_ms() / 1000); + let log = audit_log(&bed.relay, &updated).await.unwrap(); + let entry = log.entries.iter().find(|e| e.action == "keys_rotate").expect("the lockdown shows"); + assert_eq!(entry.at, 2_000_000, "dated when the rotator sent it, the same on every device"); + } + #[tokio::test(flavor = "multi_thread")] async fn a_severing_adopt_never_deadlocks_the_last_link_creator() { // The severance runs INSIDE the follow, which holds `follow_lock` for the diff --git a/crates/vector-core/src/community/v2/service/audit.rs b/crates/vector-core/src/community/v2/service/audit.rs index 4ab0afe30..448602e47 100644 --- a/crates/vector-core/src/community/v2/service/audit.rs +++ b/crates/vector-core/src/community/v2/service/audit.rs @@ -623,13 +623,16 @@ fn guestbook_entries(community: &CommunityV2, cid_hex: &str) -> Vec let changes = vec![json!({ "field": "nick", "old": (!old.is_empty()).then_some(old), "new": nick })]; out.push(AuditEntry { id: hex(&ev.rumor_id), at: *at_ms, actor: Some(npub(actor)), action: "member_nick_update", target: Some(member(&target.to_hex())), changes, partial: false }); } - // A Refounding whose seed snapshot never landed still shows, dated when this device adopted it. + // A Refounding whose seed snapshot never landed still shows, dated when its rotator sent it. + // An epoch adopted before that time was recorded falls back to when this device adopted it. + let minted_at = epoch_minted_at(cid_hex); for (epoch, rotator) in &minters { if rotated.contains_key(epoch) { continue; } if let (Some(secs), Ok(pk)) = (severed.get(epoch), PublicKey::from_hex(rotator)) { - rotated.insert(*epoch, (secs.saturating_mul(1000), pk)); + let at = minted_at.get(epoch).copied().unwrap_or_else(|| secs.saturating_mul(1000)); + rotated.insert(*epoch, (at, pk)); } } for (epoch, (at, rotator)) in rotated { diff --git a/crates/vector-core/src/crypto/mod.rs b/crates/vector-core/src/crypto/mod.rs index 68f5e5c45..73d441446 100644 --- a/crates/vector-core/src/crypto/mod.rs +++ b/crates/vector-core/src/crypto/mod.rs @@ -351,6 +351,7 @@ pub fn mime_from_extension(ext: &str) -> &'static str { "jpg" | "jpeg" => "image/jpeg", "gif" => "image/gif", "webp" => "image/webp", + "jxl" => "image/jxl", "svg" => "image/svg+xml", "bmp" => "image/bmp", "ico" => "image/x-icon", @@ -446,6 +447,7 @@ pub fn extension_from_mime(mime: &str) -> String { "image/jpeg" | "image/jpg" => "jpg", "image/gif" => "gif", "image/webp" => "webp", + "image/jxl" => "jxl", "image/svg+xml" => "svg", "image/bmp" | "image/x-ms-bmp" => "bmp", "image/x-icon" | "image/vnd.microsoft.icon" => "ico", @@ -728,6 +730,8 @@ pub fn mime_from_magic_bytes(bytes: &[u8]) -> &'static str { match bytes[0] { 0x89 if bytes[1..4] == [0x50, 0x4E, 0x47] => "image/png", 0xFF if bytes[1..3] == [0xD8, 0xFF] => "image/jpeg", + 0xFF if bytes[1] == 0x0A => "image/jxl", + 0x00 if bytes.len() >= 12 && bytes[1..12] == *b"\0\0\x0CJXL \r\n\x87\n" => "image/jxl", b'G' if bytes.len() >= 6 && (bytes[..6] == *b"GIF87a" || bytes[..6] == *b"GIF89a") => "image/gif", b'R' if bytes.len() > 12 && bytes[..4] == *b"RIFF" && bytes[8..12] == *b"WEBP" => "image/webp", 0x49 if bytes[1..4] == [0x49, 0x2A, 0x00] => "image/tiff", @@ -912,6 +916,24 @@ impl AtRestOpener { maybe_decrypt_blob(stored) } + /// [`Self::open_blob_or_keep`] that opens a blob it owns in place: a failed open checks the + /// tag before touching the buffer, so the fallbacks still see the stored bytes. + pub fn open_blob_owned(&mut self, mut stored: Vec) -> Vec { + if stored.len() == 32 { + return stored; + } + if stored.len() >= NONCE_LEN + TAG_LEN { + if let Some(c) = self.cipher() { + if let Ok(len) = c.open_framed_in_place(&mut stored).map(|p| p.len()) { + stored.copy_within(NONCE_LEN..NONCE_LEN + len, 0); + stored.truncate(len); + return stored; + } + } + } + maybe_decrypt_blob(&stored) + } + /// `maybe_decrypt` for one string, sharing the batch's cipher. #[allow(clippy::result_unit_err)] // maybe_decrypt's own contract, which every caller already handles pub fn open(&mut self, input: String) -> Result { diff --git a/crates/vector-core/src/db/community.rs b/crates/vector-core/src/db/community.rs index 39cbf6ec6..81f2696f0 100644 --- a/crates/vector-core/src/db/community.rs +++ b/crates/vector-core/src/db/community.rs @@ -1299,6 +1299,15 @@ fn flagged_sql(placeholders: &str, strict: bool) -> String { pub(crate) const HELD_POST: &str = "instr(tags, '[\"unauthorized\"]') > 0"; pub(crate) const WRITER_POST: &str = "instr(tags, '[\"writer\"]') > 0"; +/// A presence event's `["event-type", n]`: Some(true) for a join, Some(false) for a leave. +fn presence_kind(tags_json: &str) -> Option { + match crate::event_json::first_tag_value(tags_json, "event-type")?.as_deref() { + Some("1") => Some(true), + Some("0") => Some(false), + _ => None, + } +} + /// `strict`: Grants stamped 0 rather than now, and a post at a writer address no sign of /// presence, since a writer who left still holds a key to post there. fn member_activity(community_id: &str, capped: bool, strict: bool) -> Result, String> { @@ -1374,33 +1383,29 @@ fn member_activity(community_id: &str, capped: bool, strict: bool) -> Result(0)?, r.get::<_, i64>(1)?.max(0) as u64, r.get::<_, String>(2)?)) + // SystemEventType: 1 = MemberJoined, 0 = MemberLeft (carried in an ["event-type", n] tag). + let etype = match r.get_ref(2)? { + rusqlite::types::ValueRef::Text(b) if let Ok(tags) = std::str::from_utf8(b) => presence_kind(tags), + _ => presence_kind(&r.get::<_, String>(2)?), + }; + Ok((r.get::<_, String>(0)?, r.get::<_, i64>(1)?.max(0) as u64, etype)) }) .map_err(|e| e.to_string())? .collect::, _>>() .map_err(|e| e.to_string())?; - // The reader goes back before every presence event's tags are parsed. drop(stmt); drop(conn); - for (npub, at, tags_json) in rows { - // SystemEventType: 1 = MemberJoined, 0 = MemberLeft (carried in an ["event-type", n] tag). - let etype = serde_json::from_str::>>(&tags_json) - .ok() - .and_then(|tags| { - tags.into_iter() - .find(|t| t.first().map(|s| s == "event-type").unwrap_or(false)) - .and_then(|t| t.into_iter().nth(1)) - }); - match etype.as_deref() { - Some("1") => { + for (npub, at, etype) in rows { + match etype { + Some(true) => { let e = active.entry(npub).or_insert(0); if at > *e { *e = at; } } - Some("0") => { + Some(false) => { let e = left.entry(npub).or_insert(0); if at > *e { *e = at; } } - _ => {} + None => {} } } } @@ -3034,13 +3039,13 @@ pub fn load_community_v2(id: &CommunityId) -> Result = serde_json::from_str(&dt(o, &relays_e)).unwrap_or_default(); + let relays: Vec = serde_json::from_str(&dt(o, relays_e)).unwrap_or_default(); let mut channels = Vec::new(); { @@ -3069,12 +3074,12 @@ pub fn load_community_v2(id: &CommunityId) -> Result Result Result(&j).ok()); let banner = banner_e - .map(|s| dt(o, &s)) + .map(|s| dt(o, s)) .and_then(|j| serde_json::from_str::(&j).ok()); let stash: CommunityMetaStash = stash_e - .map(|s| dt(o, &s)) + .map(|s| dt(o, s)) .and_then(|j| serde_json::from_str(&j).ok()) .unwrap_or_default(); @@ -3125,9 +3130,7 @@ pub fn load_community_v2(id: &CommunityId) -> Result dk(o, &blob).ok().filter(|cr| { crate::community::v2::derive::control_signer_group_key(cr, id, Epoch(root_epoch as u64)).pk() == pk @@ -3141,8 +3144,8 @@ pub fn load_community_v2(id: &CommunityId) -> Result Result<(Vec Result)> = crate::crypto::open_batch(|o| { - rows.into_iter().filter_map(|(seq, body)| departure_from_body(&o.open_blob_or_keep(&body)).map(|(member, owed)| (member, (seq, owed)))).collect() + rows.into_iter().filter_map(|(seq, body)| departure_from_body(&o.open_blob_owned(body)).map(|(member, owed)| (member, (seq, owed)))).collect() }); let rows = held.values().map(|(seq, _)| *seq).collect(); Ok(DeparturesSeen { spans: std::sync::Arc::new(held.into_iter().map(|(member, (_, owed))| (member, owed.into())).collect()), rows }) @@ -6329,12 +6331,18 @@ pub fn control_wrap_ids(community_id: &str, view: &[u8; 32]) -> Result>(0)?, r.get::<_, i64>(1)?))) + .query_map(params![community_id, &view[..]], |r| { + let id = match r.get_ref(0)?.as_blob() { + Ok(b) => <[u8; 32]>::try_from(b).ok(), + Err(_) => <[u8; 32]>::try_from(r.get::<_, Vec>(0)?).ok(), + }; + Ok((id, r.get::<_, i64>(1)?)) + }) .map_err(|e| format!("control wrap ids: {e}"))?; let mut out = Vec::new(); for row in rows { let (id, at) = row.map_err(|e| format!("control wrap ids: {e}"))?; - out.push((id.try_into().map_err(|_| "control wrap ids: a wrap id is not 32 bytes".to_string())?, at.max(0) as u64)); + out.push((id.ok_or_else(|| "control wrap ids: a wrap id is not 32 bytes".to_string())?, at.max(0) as u64)); } Ok(out) } @@ -6390,7 +6398,7 @@ pub fn control_wrap_page(community_id: &str, view: &[u8; 32], below: Option<(u64 }; crate::crypto::open_batch(|o| { rows.into_iter() - .map(|(id, at, body)| Ok((id.try_into().map_err(|_| "control wrap page: a wrap id is not 32 bytes".to_string())?, at.max(0) as u64, o.open_blob_or_keep(&body)))) + .map(|(id, at, body)| Ok((id.try_into().map_err(|_| "control wrap page: a wrap id is not 32 bytes".to_string())?, at.max(0) as u64, o.open_blob_owned(body)))) .collect() }) } @@ -6409,7 +6417,7 @@ pub fn control_wrap_bodies(community_id: &str, view: &[u8; 32], ids: &[[u8; 32]] } } } - crate::crypto::open_batch(|o| Ok(sealed.iter().map(|body| o.open_blob_or_keep(body)).collect())) + crate::crypto::open_batch(|o| Ok(sealed.into_iter().map(|body| o.open_blob_owned(body)).collect())) } /// What `view` holds: bodies, refusals, and the bodies' bytes as stored. diff --git a/crates/vector-core/src/db/events.rs b/crates/vector-core/src/db/events.rs index 8ba15709c..cd528cfea 100644 --- a/crates/vector-core/src/db/events.rs +++ b/crates/vector-core/src/db/events.rs @@ -20,6 +20,17 @@ fn seal_event_fields(event: &StoredEvent, sealer: &mut crate::crypto::AtRestSeal Ok((content, preview)) } +/// A file message's caption: its stored content less the file's own URL, which NIP-17 puts there. +fn file_caption(content: &str, attachments: &[crate::types::Attachment]) -> String { + let rest = crate::community::attachments::strip_attachment_urls(content, attachments); + let bare_link = !rest.contains(char::is_whitespace) && (rest.starts_with("https://") || rest.starts_with("http://")); + let names_a_file = bare_link + && attachments.iter().any(|a| { + rest.contains(a.id.as_str()) || a.original_hash.as_deref().is_some_and(|h| !h.is_empty() && rest.contains(h)) + }); + if names_a_file { String::new() } else { rest } +} + // A stored message's text and tags are its original, written once: edits are their own rows, so a // re-save from memory (which holds the latest edit, or whatever a failed open left) never replaces them. const _: () = assert!( @@ -1265,6 +1276,8 @@ pub async fn get_events( if event.kind == event_kind::CHAT_MESSAGE || event.kind == event_kind::PRIVATE_DIRECT_MESSAGE { event.content = at_rest.open(event.content) .unwrap_or_else(|_| "[Decryption failed]".to_string()); + } else if event.kind == event_kind::FILE_ATTACHMENT { + event.content = at_rest.open_or_keep(event.content); } event }).collect()); @@ -1661,7 +1674,7 @@ async fn compose_message_views(message_events: Vec) -> Result Result Result Result, String> { .prepare("SELECT hash, file, missing_at IS NOT NULL FROM media_store") .map_err(|e| format!("list media: {e}"))?; let rows = stmt - .query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?, r.get::<_, bool>(2)?))) + .query_map([], |r| { + let hash = match r.get_ref(0)?.as_str() { + Ok(h) => hex_to_bytes_32_checked(h), + Err(_) => hex_to_bytes_32_checked(&r.get::<_, String>(0)?), + }; + Ok((hash, r.get::<_, String>(1)?, r.get::<_, bool>(2)?)) + }) .map_err(|e| format!("list media: {e}"))? .flatten() - .filter_map(|(hash, file, missing)| hex_to_bytes_32_checked(&hash).map(|h| (h, file, missing))) + .filter_map(|(hash, file, missing)| hash.map(|h| (h, file, missing))) .collect(); Ok(rows) } diff --git a/crates/vector-core/src/emoji_packs.rs b/crates/vector-core/src/emoji_packs.rs index 48572b65d..7f31ca1ff 100644 --- a/crates/vector-core/src/emoji_packs.rs +++ b/crates/vector-core/src/emoji_packs.rs @@ -975,20 +975,21 @@ pub fn load_all_packs() -> Result, String> { ORDER BY pack_addr, position ASC" ).map_err(|e| format!("prepare items: {}", e))?; - let rows = stmt.query_map([], |row| { - Ok(( - row.get::<_, String>(0)?, - PackEmoji { - shortcode: row.get(1)?, - url: row.get(2)?, - sha256: row.get(3)?, - }, - )) - }).map_err(|e| format!("query items: {}", e))?; - - for r in rows { - let (addr, emoji) = r.map_err(|e| format!("row item: {}", e))?; - if let Some(p) = packs.get_mut(&addr) { + let mut rows = stmt.query([]).map_err(|e| format!("query items: {}", e))?; + let item = |row: &rusqlite::Row| -> rusqlite::Result { + Ok(PackEmoji { shortcode: row.get(1)?, url: row.get(2)?, sha256: row.get(3)? }) + }; + // The address is only a lookup key, so it is borrowed from the row rather than copied. + while let Some(row) = rows.next().map_err(|e| format!("row item: {}", e))? { + let pack = match row.get_ref(0).map_err(|e| format!("row item: {}", e))?.as_str() { + Ok(addr) => packs.get_mut(addr), + Err(_) => { + row.get::<_, String>(0).map_err(|e| format!("row item: {}", e))?; + None + } + }; + let emoji = item(row).map_err(|e| format!("row item: {}", e))?; + if let Some(p) = pack { p.emojis.push(emoji); } } diff --git a/crates/vector-core/src/event_json.rs b/crates/vector-core/src/event_json.rs index af2347f96..82099284d 100644 --- a/crates/vector-core/src/event_json.rs +++ b/crates/vector-core/src/event_json.rs @@ -192,3 +192,145 @@ mod tests { } } } + +/// The second string of the first tag named `name` in a stored `tags` column, as +/// `serde_json::from_str::>>` and a `find` would give it, without building the +/// tags: `None` where that parse fails, `Some(None)` where the tag is absent or has no value. +pub fn first_tag_value<'a>(tags_json: &'a str, name: &str) -> Option>> { + use serde::de::{DeserializeSeed, Deserializer, SeqAccess, Visitor}; + use std::borrow::Cow; + use std::fmt; + + /// A string, borrowed where the JSON holds it unescaped. + struct Text<'de>(Cow<'de, str>); + impl<'de> serde::Deserialize<'de> for Text<'de> { + fn deserialize>(d: D) -> Result { + struct V; + impl<'de> Visitor<'de> for V { + type Value = Text<'de>; + fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.write_str("a string") + } + fn visit_borrowed_str(self, v: &'de str) -> Result { + Ok(Text(Cow::Borrowed(v))) + } + fn visit_str(self, v: &str) -> Result { + Ok(Text(Cow::Owned(v.to_owned()))) + } + } + d.deserialize_string(V) + } + } + + /// A string, checked and dropped. + struct Skip; + impl<'de> serde::Deserialize<'de> for Skip { + fn deserialize>(d: D) -> Result { + struct V; + impl Visitor<'_> for V { + type Value = Skip; + fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.write_str("a string") + } + fn visit_str(self, _: &str) -> Result { + Ok(Skip) + } + } + d.deserialize_string(V) + } + } + + struct Tag<'n, 'f, 'de> { + name: &'n str, + found: &'f mut Option>>, + } + impl<'de> DeserializeSeed<'de> for Tag<'_, '_, 'de> { + type Value = (); + fn deserialize>(self, d: D) -> Result<(), D::Error> { + d.deserialize_seq(self) + } + } + impl<'de> Visitor<'de> for Tag<'_, '_, 'de> { + type Value = (); + fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.write_str("a tag") + } + fn visit_seq>(self, mut seq: A) -> Result<(), A::Error> { + if self.found.is_none() { + if let Some(first) = seq.next_element::()? { + if first.0 == self.name { + *self.found = Some(seq.next_element::()?.map(|t| t.0)); + } + } + } + while seq.next_element::()?.is_some() {} + Ok(()) + } + } + + struct Tags<'n, 'de> { + name: &'n str, + found: Option>>, + } + impl<'de> Visitor<'de> for &mut Tags<'_, 'de> { + type Value = (); + fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.write_str("a list of tags") + } + fn visit_seq>(self, mut seq: A) -> Result<(), A::Error> { + while seq.next_element_seed(Tag { name: self.name, found: &mut self.found })?.is_some() {} + Ok(()) + } + } + + let mut tags = Tags { name, found: None }; + let mut de = serde_json::Deserializer::from_str(tags_json); + de.deserialize_seq(&mut tags).ok()?; + de.end().ok()?; + Some(tags.found.unwrap_or(None)) +} + +#[cfg(test)] +mod tag_tests { + #[test] + fn first_tag_value_reads_as_the_full_parse_does() { + let full = |s: &str| { + serde_json::from_str::>>(s) + .ok() + .map(|tags| tags.into_iter().find(|t| t.first().is_some_and(|f| f == "event-type")).and_then(|t| t.into_iter().nth(1))) + }; + const PARTS: &[&str] = &[ + "[", "]", ",", "\"event-type\"", "\"event\\u002dtype\"", "\"1\"", "\"0\"", "\"x\"", "1", "null", " ", "{}", "\"\\n\"", "\"é\"", + ]; + let mut seed = 0x1357_9bdfu64; + let mut next = move || { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + seed + }; + let mut hits = 0; + const STRS: &[&str] = &["\"event-type\"", "\"event\\u002dtype\"", "\"1\"", "\"0\"", "\"x\"", "\"é\\n\"", "1", "null"]; + for i in 0..200_000 { + let s: String = if i % 2 == 0 { + (0..1 + next() % 12).map(|_| PARTS[(next() % PARTS.len() as u64) as usize]).collect() + } else { + let tag = |next: &mut dyn FnMut() -> u64| { + let n = next() % 4; + let items: Vec<&str> = (0..n).map(|_| STRS[(next() % STRS.len() as u64) as usize]).collect(); + format!("[{}]", items.join(",")) + }; + let n = next() % 4; + let tags: Vec = (0..n).map(|_| tag(&mut next)).collect(); + format!(" [{}] ", tags.join(", ")) + }; + let want = full(&s); + hits += want.as_ref().is_some_and(|w| w.is_some()) as usize; + assert_eq!(super::first_tag_value(&s, "event-type").map(|v| v.map(|c| c.into_owned())), want, "{s:?}"); + } + for s in [r#"[["event-type","1"],["e","x"]]"#, r#"[["a"],["event-type"],["event-type","0"]]"#, r#"[["event-type","0", "z"]] "#, "[]", "[[]]"] { + assert_eq!(super::first_tag_value(s, "event-type").map(|v| v.map(|c| c.into_owned())), full(s), "{s:?}"); + } + assert!(hits > 100, "{hits}"); + } +} diff --git a/crates/vector-core/src/lib.rs b/crates/vector-core/src/lib.rs index cfd98be28..ef5cf958c 100644 --- a/crates/vector-core/src/lib.rs +++ b/crates/vector-core/src/lib.rs @@ -114,6 +114,8 @@ pub mod deep_link; pub mod golink; pub mod badges; pub mod history_gaps; +#[cfg(not(target_arch = "wasm32"))] +pub mod resume; pub mod bot_interface; pub mod webxdc; pub mod webxdc_permissions; @@ -447,6 +449,7 @@ pub mod requests; // === Message Deletion (NIP-09 against retained gift-wraps) === pub mod deletion; +pub mod search; pub mod early; pub mod self_destruct; pub mod transfer; @@ -3004,6 +3007,24 @@ impl VectorCore { Ok((count, warnings)) } + /// The newest page of a channel alone, ingested as soon as it lands: what a reader opening it + /// waits on, ahead of the deeper catch-up [`sync_community_channel_page`](Self::sync_community_channel_page) does. + pub async fn sync_community_channel_head(&self, channel_id: &str, limit: usize) -> Result { + let id = self.v2_community_for_channel(channel_id)?.ok_or_else(|| VectorError::Other("unknown community channel".into()))?; + let ch_id = crate::community::ChannelId(crate::simd::hex::hex_to_bytes_32(channel_id)); + let keyless = crate::db::community::load_community_v2(&id) + .map_err(VectorError::Other)? + .and_then(|c| c.channel(&ch_id).map(|ch| ch.private && ch.key.is_none())) + .unwrap_or(true); + if keyless { + return Ok(BackfillCount::default()); + } + Ok(Self::v2_backfill_channel_counted( + &id, channel_id, limit, 1, None, None, + crate::community::transport::Evidence::Fast, 12, + ).await) + } + /// Fill the hole in a channel's held history that a scroll up from `before_ms` is about to /// cross, with the relay pages from its top down. The count of messages that arrived; 0 when /// there is no hole there, or the relays can't be reached (it stays for the next scroll). diff --git a/crates/vector-core/src/media/mod.rs b/crates/vector-core/src/media/mod.rs index 15149f6e0..0e12adf57 100644 --- a/crates/vector-core/src/media/mod.rs +++ b/crates/vector-core/src/media/mod.rs @@ -20,6 +20,10 @@ pub trait MediaSource: Send + Sync { fn mime(&self) -> &str; /// Fill `buf` from `offset`. Fewer bytes only at the end, none past it. fn read_at(&self, offset: u64, buf: &mut [u8]) -> std::io::Result; + /// Bytes still on the network: a reader that wants all of them downloads the file. + fn remote(&self) -> bool { + false + } } /// "Keep Files on This Device": every file received is kept in the store too, not only held. @@ -43,7 +47,7 @@ pub fn url_key(kind: &str, url: &str) -> [u8; 32] { /// Kinds a chat bubble draws itself: these load for viewing without being kept. pub fn previewable(extension: &str) -> bool { - const IMAGES: [&str; 10] = ["png", "jpeg", "jpg", "gif", "webp", "svg", "bmp", "tiff", "tif", "ico"]; + const IMAGES: [&str; 11] = ["png", "jpeg", "jpg", "gif", "webp", "jxl", "svg", "bmp", "tiff", "tif", "ico"]; const AUDIO: [&str; 6] = ["wav", "mp3", "flac", "aac", "m4a", "ogg"]; const VIDEO: [&str; 3] = ["mp4", "webm", "mov"]; const MODELS: [&str; 5] = ["glb", "gltf", "stl", "obj", "fbx"]; diff --git a/crates/vector-core/src/net.rs b/crates/vector-core/src/net.rs index c175de281..5fcda4e46 100644 --- a/crates/vector-core/src/net.rs +++ b/crates/vector-core/src/net.rs @@ -118,6 +118,9 @@ struct ClientOptions { /// Never direct: a fetch decided while an anonymity network was chosen, that the user must /// never make from this device's own address. no_direct: bool, + /// HTTP/1.1 only: each request on a connection of its own, which an unread body holds back + /// by TCP alone. Over HTTP/2 it would fill the window every stream on the connection shares. + http1_only: bool, } #[derive(Clone, Debug)] @@ -167,7 +170,7 @@ pub fn build_http_client_for( Ok(HttpClient { owner: crate::db::current_session_id(), lane, - opts: ClientOptions { timeout, read_timeout, follow_redirects, no_direct: false }, + opts: ClientOptions { timeout, read_timeout, follow_redirects, no_direct: false, http1_only: false }, }) } @@ -178,7 +181,7 @@ pub fn shared_http_client() -> std::sync::Arc { std::sync::Arc::new(HttpClient { owner: crate::db::current_session_id(), lane: Lane::Shared, - opts: ClientOptions { timeout: Some(DEFAULT_SHARED_TIMEOUT), read_timeout: None, follow_redirects: true, no_direct: false }, + opts: ClientOptions { timeout: Some(DEFAULT_SHARED_TIMEOUT), read_timeout: None, follow_redirects: true, no_direct: false, http1_only: false }, }) } @@ -212,31 +215,38 @@ pub fn rebuild_shared_http_client() -> Result<(), String> { /// Only builds requests: `Req::send` executes on the client the current egress gives. fn template() -> &'static reqwest::Client { static T: std::sync::OnceLock = std::sync::OnceLock::new(); - T.get_or_init(|| client_builder().build().expect("a plain reqwest client always builds")) + T.get_or_init(|| client_builder(false).build().expect("a plain reqwest client always builds")) } -/// Ring with the webpki roots, offering h2 before HTTP/1.1, with a session store of its own. +/// Ring with the webpki roots, offering h2 before HTTP/1.1 (or HTTP/1.1 alone), with a session +/// store of its own. /// /// Built per pooled client, never cloned from a shared one: a clone shares the session store, /// and a resumed ticket would tie this account and lane to another's requests to that server. #[cfg(not(target_arch = "wasm32"))] -fn tls_config() -> rustls::ClientConfig { +fn tls_config(http1_only: bool) -> rustls::ClientConfig { let roots = rustls::RootCertStore { roots: webpki_roots::TLS_SERVER_ROOTS.to_vec() }; let mut cfg = rustls::ClientConfig::builder_with_provider(std::sync::Arc::new(rustls::crypto::ring::default_provider())) .with_safe_default_protocol_versions() .expect("ring supports TLS 1.2 and 1.3") .with_root_certificates(roots) .with_no_client_auth(); - cfg.alpn_protocols = vec![b"h2".to_vec(), b"http/1.1".to_vec()]; + cfg.alpn_protocols = if http1_only { vec![b"http/1.1".to_vec()] } else { vec![b"h2".to_vec(), b"http/1.1".to_vec()] }; cfg } #[allow(clippy::disallowed_methods)] -fn client_builder() -> reqwest::ClientBuilder { +fn client_builder(http1_only: bool) -> reqwest::ClientBuilder { #[cfg(not(target_arch = "wasm32"))] - return reqwest::Client::builder().tls_backend_preconfigured(tls_config()); + return { + let b = reqwest::Client::builder().tls_backend_preconfigured(tls_config(http1_only)); + if http1_only { b.http1_only() } else { b } + }; #[cfg(target_arch = "wasm32")] - return reqwest::Client::builder(); + return { + let _ = http1_only; + reqwest::Client::builder() + }; } impl HttpClient { @@ -284,12 +294,18 @@ impl HttpClient { pub fn without_direct(&self) -> HttpClient { HttpClient { opts: ClientOptions { no_direct: true, ..self.opts }, ..self.clone() } } + + /// The same client on HTTP/1.1 alone: for several long bodies read in turn, each left unread + /// a while (a streamed video's byte ranges). + pub fn http1_only(&self) -> HttpClient { + HttpClient { opts: ClientOptions { http1_only: true, ..self.opts }, ..self.clone() } + } } #[cfg(not(target_arch = "wasm32"))] fn build_pooled(opts: ClientOptions, proxy: Option) -> Result { use crate::transport::{budget, Op}; - let mut builder = client_builder() + let mut builder = client_builder(opts.http1_only) // Kept connections: idle ones stay a while so a burst of small // fetches to one host (an edge, a Blossom server) rides one or a // few connections, and HTTP/2 multiplexes on them where offered. @@ -340,7 +356,7 @@ fn build_pooled(opts: ClientOptions, proxy: Option) -> Result) -> Result { - client_builder().build().map_err(|e| format!("HTTP client build failed: {e}")) + client_builder(false).build().map_err(|e| format!("HTTP client build failed: {e}")) } /// The pooled client for this decision, built and cached unless the epoch moved meanwhile. @@ -1338,12 +1354,23 @@ mod tls_tests { #[test] fn clients_build_on_ring_with_h2_offered_first() { - let cfg = tls_config(); + let cfg = tls_config(false); assert_eq!(cfg.alpn_protocols, [b"h2".to_vec(), b"http/1.1".to_vec()]); - let opts = ClientOptions { timeout: None, read_timeout: None, follow_redirects: true, no_direct: false }; + let opts = ClientOptions { timeout: None, read_timeout: None, follow_redirects: true, no_direct: false, http1_only: false }; build_pooled(opts, None).expect("a pooled client builds"); template(); } + + #[test] + fn an_http1_client_offers_only_http1_and_pools_apart() { + assert_eq!(tls_config(true).alpn_protocols, [b"http/1.1".to_vec()]); + let opts = ClientOptions { timeout: None, read_timeout: None, follow_redirects: true, no_direct: false, http1_only: true }; + build_pooled(opts, None).expect("an HTTP/1.1 client builds"); + let c = build_http_client_with_options(None, None, true).unwrap(); + assert!(!c.opts.http1_only); + assert!(c.http1_only().opts.http1_only); + assert_ne!(c.opts, c.http1_only().opts, "h1 and h2 clients never share a pool"); + } } #[cfg(test)] diff --git a/crates/vector-core/src/profile/sync.rs b/crates/vector-core/src/profile/sync.rs index e3268e61f..27fb66528 100644 --- a/crates/vector-core/src/profile/sync.rs +++ b/crates/vector-core/src/profile/sync.rs @@ -126,13 +126,19 @@ impl ProfileSyncQueue { /// Add a profile to the sync queue. pub fn add(&mut self, npub: impl AsRef + Into, priority: SyncPriority, force_refresh: bool) { + self.add_at(npub, priority, force_refresh, false) + } + + /// [`Self::add`], at the front of its lane when `front`: what is on screen goes before + /// what was queued for being somewhere else. + fn add_at(&mut self, npub: impl AsRef + Into, priority: SyncPriority, force_refresh: bool, front: bool) { let key = npub.as_ref(); if self.processing.contains(key) { return; } // An entry already waiting at this priority or higher keeps its place and age: a // periodic re-add would otherwise restart the delay and never let a Low entry ripen. - if self.queued.get(key).is_some_and(|&(_, waiting)| waiting <= priority) { + if self.queued.get(key).is_some_and(|&(_, waiting)| waiting < priority || (waiting == priority && !front)) { return; } @@ -159,11 +165,16 @@ impl ProfileSyncQueue { lane.retain(|e| Self::is_live(&self.queued, e)); } } - match priority { - SyncPriority::Critical => self.critical_queue.push_back(entry), - SyncPriority::High => self.high_queue.push_back(entry), - SyncPriority::Medium => self.medium_queue.push_back(entry), - SyncPriority::Low => self.low_queue.push_back(entry), + let lane = match priority { + SyncPriority::Critical => &mut self.critical_queue, + SyncPriority::High => &mut self.high_queue, + SyncPriority::Medium => &mut self.medium_queue, + SyncPriority::Low => &mut self.low_queue, + }; + if front { + lane.push_front(entry); + } else { + lane.push_back(entry); } PROCESSOR_WAKE.notify_one(); } @@ -345,22 +356,6 @@ impl ProfileSyncHandler for NoOpProfileSyncHandler {} // load_profile — core relay fetch + STATE update // ============================================================================ -/// The newest kind-0 the relays hold for `pubkey`, or `None` when they hold none. -async fn fetch_newest_metadata(client: &Client, pubkey: PublicKey) -> Result, String> { - // `Client::fetch_metadata` is gone: fetch the newest kind-0 and parse it. - client - .fetch_events(Filter::new().author(pubkey).kind(Kind::Metadata).limit(1)) - .timeout(crate::relay_request_timeout(Duration::from_secs(15))) - .await - .map(|events| { - events - .into_iter() - .max_by_key(|e| e.created_at) - .and_then(|e| Metadata::from_json(&e.content).ok()) - }) - .map_err(|e| e.to_string()) -} - /// Our kind-0 as it stands on the relays, whole: its content's JSON object with every key it /// holds, whatever Vector makes of them, and every tag. Profiles carry what other clients /// invented (emoji in names, profile fields, identity proofs); a save edits, never rebuilds. @@ -493,21 +488,51 @@ fn metadata_view(content: &serde_json::Map) -> Metada /// /// Returns `true` if the fetch succeeded (even if nothing changed). pub async fn load_profile(npub: String, handler: &dyn ProfileSyncHandler) -> bool { - let client = match nostr_client() { - Some(c) => c, - None => return false, - }; - - // Session captured for the whole load_profile lifecycle. Relay - // fetches can sleep multi-second; we re-check before writing back - // to STATE / DB so a mid-fetch swap doesn't land account A's - // profile in account B's storage. + load_profiles(vec![npub], handler).await.first().copied().unwrap_or(false) +} - let profile_pubkey = match PublicKey::from_bech32(npub.as_str()) { - Ok(pk) => pk, - Err(_) => return false, +/// [`load_profile`] for many at once: one REQ for every profile's metadata and status, so a +/// screen of people costs a round trip, not one each. Whether each loaded, in the order given. +pub async fn load_profiles(npubs: Vec, handler: &dyn ProfileSyncHandler) -> Vec { + let Some(client) = nostr_client() else { return vec![false; npubs.len()] }; + let keys: Vec> = npubs.iter().map(|n| PublicKey::from_bech32(n.as_str()).ok()).collect(); + let authors: Vec = keys.iter().flatten().copied().collect(); + if authors.is_empty() { + return vec![false; npubs.len()]; + } + let filter = Filter::new().authors(authors).kinds([Kind::Metadata, Kind::from_u16(30315)]); + let fetched = client + .fetch_events(filter) + .timeout(crate::relay_request_timeout(Duration::from_secs(15))) + .await + .map_err(|e| e.to_string()); + let newest = |pk: &PublicKey, kind: Kind| -> Option { + fetched.as_ref().ok()?.iter().filter(|e| e.pubkey == *pk && e.kind == kind).max_by_key(|e| e.created_at).cloned() }; + let mut loaded = Vec::with_capacity(npubs.len()); + for (npub, pk) in npubs.into_iter().zip(keys) { + let Some(pk) = pk else { + loaded.push(false); + continue; + }; + let status = newest(&pk, Kind::from_u16(30315)); + let meta = match &fetched { + Ok(_) => Ok(newest(&pk, Kind::Metadata).and_then(|e| Metadata::from_json(&e.content).ok())), + Err(e) => Err(e.clone()), + }; + loaded.push(apply_fetched(npub, pk, status, meta, handler).await); + } + loaded +} +/// Folds one profile's fetched status and metadata into STATE, the DB and the UI. +async fn apply_fetched( + npub: String, + profile_pubkey: PublicKey, + status: Option, + fetch_result: Result, String>, + handler: &dyn ProfileSyncHandler, +) -> bool { let my_public_key = match my_public_key() { Some(pk) => pk, None => return false, @@ -535,36 +560,16 @@ pub async fn load_profile(npub: String, handler: &dyn ProfileSyncHandler) -> boo } } - // Fetch status (kind 30315) from relays - let status_filter = Filter::new() - .author(profile_pubkey) - .kind(Kind::from_u16(30315)) - .limit(1); - - let (status_title, status_purpose, status_url, status_emoji_tags) = match client - .fetch_events(status_filter).timeout(crate::relay_request_timeout(Duration::from_secs(15))) - .await - { - Ok(res) => { - if !res.is_empty() { - let status_event = res.first().unwrap(); - ( - clamp_status(status_event.content.clone()), - status_event.tags.first() - .and_then(|t| t.content()) - .unwrap_or_default() - .to_string(), - String::new(), - crate::types::EmojiTag::extract_from_tags(status_event.tags.iter()), - ) - } else { - (old_status_title, old_status_purpose, old_status_url, old_status_emoji_tags) - } - } - Err(_) => (old_status_title, old_status_purpose, old_status_url, old_status_emoji_tags), + let (status_title, status_purpose, status_url, status_emoji_tags) = match status { + Some(status_event) => ( + clamp_status(status_event.content.clone()), + status_event.tags.first().and_then(|t| t.content()).unwrap_or_default().to_string(), + String::new(), + crate::types::EmojiTag::extract_from_tags(status_event.tags.iter()), + ), + None => (old_status_title, old_status_purpose, old_status_url, old_status_emoji_tags), }; - let fetch_result = fetch_newest_metadata(&client, profile_pubkey).await; if fetch_result.is_ok() { let _ = crate::db::profiles::mark_profile_checked(&npub, now_secs()); } @@ -1162,16 +1167,13 @@ pub async fn start_profile_sync_processor(handler: Arc) // account A's queue work lands in account B's DB. The next // outer-loop iteration picks up the new session's queue cleanly. - for entry in &batch { - load_profile(entry.npub.clone(), handler.as_ref()).await; - - { - let owner = profile_sync_queue(); - let mut queue = owner.lock().unwrap(); + load_profiles(batch.iter().map(|e| e.npub.clone()).collect(), handler.as_ref()).await; + { + let owner = profile_sync_queue(); + let mut queue = owner.lock().unwrap(); + for entry in &batch { queue.mark_done(&entry.npub); } - - crate::rt::time::sleep(Duration::from_millis(100)).await; } // Release processing lock @@ -1181,7 +1183,7 @@ pub async fn start_profile_sync_processor(handler: Arc) queue.is_processing = false; } - crate::rt::time::sleep(Duration::from_millis(500)).await; + crate::rt::time::sleep(Duration::from_millis(100)).await; } } @@ -1218,8 +1220,9 @@ fn on_screen_need(profile: Option<&Profile>, now: u64) -> Option { (now.saturating_sub(checked) >= ON_SCREEN_FRESH.as_secs()).then_some(SyncPriority::Medium) } -/// Queue the profiles the UI has on screen (or nearly) whose last check has gone stale. Called -/// on every view, so it costs a lookup per npub and a fetch only for those that need one. +/// Queue the profiles the UI has on screen (or nearly) whose last check has gone stale, ahead of +/// what waits in their lane, the first given fetched first. Called on every view, so it costs a +/// lookup per npub and a fetch only for those that need one. pub async fn queue_visible_profiles(npubs: Vec) { const MAX_PER_CALL: usize = 200; let now = now_secs(); @@ -1237,8 +1240,9 @@ pub async fn queue_visible_profiles(npubs: Vec) { } let owner = profile_sync_queue(); let mut queue = owner.lock().unwrap(); - for (npub, priority) in picks { - queue.add(npub, priority, false); + // Reversed onto the fronts, so the first drawn is the first fetched. + for (npub, priority) in picks.into_iter().rev() { + queue.add_at(npub, priority, false, true); } } @@ -1275,8 +1279,9 @@ pub async fn queue_chat_profiles(chat_id: String, is_opening: bool) { }) .unwrap_or(false); + // A Community's members come on screen a few at a time: those drawn go first. let priority = if !has_metadata { - SyncPriority::Critical + if is_community { SyncPriority::High } else { SyncPriority::Critical } } else if is_community { continue; } else { @@ -1417,6 +1422,22 @@ mod tests { assert_eq!(queue.next_ready_in(), Some(Duration::ZERO), "the superseded high entry no longer counts"); } + #[test] + fn people_on_screen_go_first_in_the_order_drawn() { + let mut queue = ProfileSyncQueue::new(); + for i in 0..30 { + queue.add(format!("npub1joined{i}"), SyncPriority::Critical, false); + } + queue.add("npub1joined20", SyncPriority::Critical, false); + assert_eq!(queue.live(&queue.critical_queue)[20], "npub1joined20", "a plain re-add keeps its place"); + for npub in ["npub1team", "npub1joined20", "npub1member"].into_iter().rev() { + queue.add_at(npub, SyncPriority::Critical, false, true); + } + let batch: Vec = queue.get_next_batch().into_iter().map(|e| e.npub).collect(); + assert_eq!(&batch[..4], ["npub1team", "npub1joined20", "npub1member", "npub1joined0"]); + assert_eq!(batch.iter().filter(|n| *n == "npub1joined20").count(), 1, "moved, not doubled"); + } + #[test] fn re_adds_while_stalled_stay_bounded() { let mut queue = ProfileSyncQueue::new(); diff --git a/crates/vector-core/src/resume.rs b/crates/vector-core/src/resume.rs new file mode 100644 index 000000000..eeeecc24a --- /dev/null +++ b/crates/vector-core/src/resume.rs @@ -0,0 +1,519 @@ +//! Resumable attachment downloads. The ciphertext streams into the account's partial file behind +//! a durable checkpoint, so a failure, the next mirror or the next launch carries on from the last +//! byte that landed. The format is the desktop client's own, so either client resumes the other's: +//! `/partial-downloads/.part`, beside `.ckpt` holding the offset and +//! the total as two little-endian u64s (0 = not yet known). + +use std::collections::HashMap; +use std::path::{Path, PathBuf}; + +use futures_util::StreamExt; + +use crate::error::DownloadError; +use crate::types::Attachment; +use crate::DownloadStep; + +/// The account folder's directory of partial downloads. +pub const PARTIAL_DIR: &str = "partial-downloads"; + +/// How often a streamed download makes its progress durable: the bytes are synced and the +/// checkpoint moved. A resume starts from the last one, never from the file's length, which a +/// power cut can leave covering bytes that never landed. +const CHECKPOINT_EVERY: u64 = 4 * 1024 * 1024; + +/// The cap for a blob whose message declared no size. +const UNDECLARED_MAX_BYTES: u64 = 16 * 1024 * 1024 * 1024; + +/// Partials untouched this long are abandoned, not paused. +const PARTIAL_MAX_AGE: std::time::Duration = std::time::Duration::from_secs(7 * 24 * 3600); + +/// The caller stopped the transfer. +pub const CANCELLED: &str = "Download cancelled"; + +/// A partial download's durable progress, kept beside its bytes. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct Checkpoint { + /// Bytes known to be on disk. + pub offset: u64, + /// The whole file's size, once a response has said it. + pub total: Option, +} + +fn checkpoint_path(part: &Path) -> PathBuf { + part.with_extension("ckpt") +} + +/// The checkpoint beside `part`, if both it and enough bytes to back it exist. +pub fn read_checkpoint(part: &Path) -> Option { + let raw = std::fs::read(checkpoint_path(part)).ok()?; + let raw: [u8; 16] = raw.try_into().ok()?; + let offset = u64::from_le_bytes(raw[..8].try_into().ok()?); + let total = u64::from_le_bytes(raw[8..].try_into().ok()?); + let on_disk = std::fs::metadata(part).ok()?.len(); + (on_disk >= offset).then_some(Checkpoint { offset, total: (total > 0).then_some(total) }) +} + +fn write_checkpoint(part: &Path, at: Checkpoint) -> std::io::Result<()> { + let mut raw = [0u8; 16]; + raw[..8].copy_from_slice(&at.offset.to_le_bytes()); + raw[8..].copy_from_slice(&at.total.unwrap_or(0).to_le_bytes()); + let tmp = part.with_extension("ckpt.tmp"); + let mut f = std::fs::File::create(&tmp)?; + std::io::Write::write_all(&mut f, &raw)?; + f.sync_all()?; + std::fs::rename(tmp, checkpoint_path(part)) +} + +/// Forget a partial download: its bytes and its checkpoint. +pub fn discard_partial(part: &Path) { + let _ = std::fs::remove_file(part); + let _ = std::fs::remove_file(checkpoint_path(part)); +} + +/// Where the open account keeps `attachment_id`'s partial download. +pub fn part_for(attachment_id: &str) -> Result { + Ok(crate::db::current_account_dir()?.join(PARTIAL_DIR).join(format!("{attachment_id}.part"))) +} + +/// The open account's paused downloads: attachment id → how far each got. +pub fn paused() -> HashMap { + let mut out = HashMap::new(); + let Ok(dir) = crate::db::current_account_dir().map(|d| d.join(PARTIAL_DIR)) else { return out }; + let Ok(entries) = std::fs::read_dir(&dir) else { return out }; + for entry in entries.flatten() { + let path = entry.path(); + if path.extension().and_then(|e| e.to_str()) != Some("part") { + continue; + } + let Some(id) = path.file_stem().and_then(|s| s.to_str()) else { continue }; + if let Some(at) = read_checkpoint(&path).filter(|c| c.offset > 0) { + out.insert(id.to_string(), at); + } + } + out +} + +/// Remove abandoned partials and their checkpoints. +pub fn sweep_stale(dir: &Path) { + let Ok(entries) = std::fs::read_dir(dir) else { return }; + let now = web_time::SystemTime::now(); + for entry in entries.flatten() { + let stale = entry + .metadata() + .and_then(|m| m.modified()) + .map(|t| now.duration_since(t).unwrap_or_default() > PARTIAL_MAX_AGE) + .unwrap_or(false); + if stale { + let _ = std::fs::remove_file(entry.path()); + } + } +} + +/// Stream `content_url` into `part`, resuming from its checkpoint when there is one. Holds a chunk +/// at a time, never the file. On any failure the bytes so far stay behind a fresh checkpoint for +/// the next attempt, from this source or another serving the same blob. `progress` hears the bytes +/// on disk and the total once known, and stops the transfer by returning false. Returns the file's +/// length once every byte is on disk. +pub async fn download_to_file( + content_url: &str, + part: &Path, + declared: Option, + progress: &mut (dyn FnMut(u64, Option) -> bool + Send), +) -> Result { + crate::net::validate_url_not_private(content_url)?; + let crate::net::Egress { url, auth } = crate::net::egress(content_url).await; + let client = crate::net::build_http_client_with_options(None, Some(crate::net::transfer_stall()), true) + .map_err(|_| "Failed to create HTTP client")?; + fetch_into(&client, &url, auth.as_ref(), part, declared, progress).await +} + +/// [`download_to_file`] past its guard and routing: `url` is already where the bytes come from. +pub(crate) async fn fetch_into( + client: &crate::net::HttpClient, + url: &str, + auth: Option<&reqwest::header::HeaderValue>, + part: &Path, + declared: Option, + progress: &mut (dyn FnMut(u64, Option) -> bool + Send), +) -> Result { + use tokio::io::AsyncWriteExt; + // The message said how big the blob is, so a body running past that is not it. The slack + // covers senders that state the plaintext's size, 16 bytes short. + let limit = declared.filter(|&d| d > 0).map(|d| d + 64 * 1024).unwrap_or(UNDECLARED_MAX_BYTES); + if let Some(dir) = part.parent() { + std::fs::create_dir_all(dir).map_err(|_| "Failed to prepare the download")?; + } + let mut at = read_checkpoint(part).unwrap_or_default(); + // A checkpoint that already covers the whole file needs no request at all. + if at.total.is_some_and(|t| t > 0 && at.offset == t) { + return Ok(at.offset); + } + // Two passes at most: a server that answers the range with the wrong bytes is asked once more + // for the whole file. A network switch resumes from the checkpoint once the new network is + // ready, spending no pass. + let mut passes = 0; + let mut network_waits = 0u8; + while passes < 2 { + passes += 1; + if !progress(at.offset, at.total) { + return Err(CANCELLED); + } + // A signed proxied request identifies the user, so it rides the Account lane. + let mut request = match auth { + Some(v) => client.with_lane(crate::net::Lane::Account).get(url).header(reqwest::header::AUTHORIZATION, v.clone()), + None => client.get(url), + }; + if at.offset > 0 { + request = request.header(reqwest::header::RANGE, format!("bytes={}-", at.offset)); + } + let res = match request.send().await { + Ok(r) => r, + Err(e) => { + crate::log_warn!("[AttachmentDownload] request failed for {}: {}", url, e); + if e.is_transient() && network_waits < 8 && crate::net::wait_after(&e).await.is_ok() { + network_waits += 1; + passes -= 1; + continue; + } + return Err("Failed to download"); + } + }; + let status = res.status().as_u16(); + let (start, total) = match status { + 206 => { + // `bytes START-END/TOTAL`; anything else can't be trusted to line up. + let range = res.headers().get(reqwest::header::CONTENT_RANGE).and_then(|v| v.to_str().ok()).unwrap_or(""); + let parsed = range.strip_prefix("bytes ").and_then(|r| { + let (span, total) = r.split_once('/')?; + let start = span.split_once('-')?.0.parse::().ok()?; + Some((start, total.parse::().ok())) + }); + match parsed { + Some((start, total)) if start == at.offset => (start, total), + _ => { + at = Checkpoint::default(); + continue; + } + } + } + // The whole body: the server ignored the range, or none was asked. + 200 => (0, res.content_length().filter(|&n| n > 0)), + 416 if at.offset > 0 => { + // Nothing past the offset: finished if the offset is the whole file. + if at.total == Some(at.offset) { + return Ok(at.offset); + } + at = Checkpoint::default(); + continue; + } + _ => { + crate::log_debug!("[AttachmentDownload] HTTP {} for {}", status, url); + return Err("Media server returned an error status"); + } + }; + let total = total.or_else(|| res.content_length().map(|n| n + start)); + if total.is_some_and(|t| t > limit) { + return Err("File exceeds the maximum download size"); + } + let file = tokio::fs::OpenOptions::new() + .create(true) + .write(true) + .truncate(false) + .open(part) + .await + .map_err(|_| "Failed to prepare the download")?; + file.set_len(start).await.map_err(|_| "Failed to prepare the download")?; + let mut file = tokio::io::BufWriter::with_capacity(256 * 1024, file); + tokio::io::AsyncSeekExt::seek(&mut file, std::io::SeekFrom::Start(start)) + .await + .map_err(|_| "Failed to prepare the download")?; + let mut written = start; + let mut durable = Checkpoint { offset: start, total }; + let _ = write_checkpoint(part, durable); + + // Make everything so far durable; the failure path runs it too. + async fn settle(file: &mut tokio::io::BufWriter, part: &Path, at: Checkpoint) -> Result<(), &'static str> { + file.flush().await.map_err(|_| "Failed to save the download")?; + file.get_ref().sync_data().await.map_err(|_| "Failed to save the download")?; + write_checkpoint(part, at).map_err(|_| "Failed to save the download") + } + + let mut stream = res.bytes_stream(); + let mut resume = false; + while let Some(item) = stream.next().await { + let chunk = match item { + Ok(c) => c, + Err(e) => { + crate::log_warn!("[AttachmentDownload] stream interrupted for {}: {}", url, e); + let _ = settle(&mut file, part, Checkpoint { offset: written, total }).await; + if e.is_transient() && network_waits < 8 && crate::net::wait_after(&e).await.is_ok() { + network_waits += 1; + resume = true; + break; + } + return Err("Error downloading chunk"); + } + }; + if written + chunk.len() as u64 > limit { + return Err("File exceeds the maximum download size"); + } + file.write_all(&chunk).await.map_err(|_| "Failed to save the download")?; + written += chunk.len() as u64; + if written - durable.offset >= CHECKPOINT_EVERY { + durable = Checkpoint { offset: written, total }; + settle(&mut file, part, durable).await?; + } + if !progress(written, total) { + let _ = settle(&mut file, part, Checkpoint { offset: written, total }).await; + return Err(CANCELLED); + } + } + if resume { + at = Checkpoint { offset: written, total }; + passes -= 1; + continue; + } + settle(&mut file, part, Checkpoint { offset: written, total: total.or(Some(written)) }).await?; + if total.is_some_and(|t| written < t) { + return Err("Error downloading chunk"); + } + return Ok(written); + } + Err("Server did not honor range request") +} + +/// What a whole part file holds for `attachment`: its plaintext, or why this source's bytes are +/// wrong. Plaintext blobs answer to their content address and the sender's claim; encrypted ones +/// to their key. +fn open_part(part: &Path, url: &str, attachment: &Attachment) -> Result, String> { + let bytes = std::fs::read(part).map_err(|e| e.to_string())?; + if attachment.key.is_empty() || attachment.nonce.is_empty() { + let hash = crate::crypto::sha256_hex(&bytes); + return if crate::blossom::plaintext_matches(url, attachment.original_hash.as_deref(), &hash) { + Ok(bytes) + } else { + Err("plaintext blob fails its hash claim".into()) + }; + } + crate::crypto::decrypt_data_owned(bytes, &attachment.key, &attachment.nonce).map_err(|e| format!("decrypt: {e}")) +} + +impl crate::VectorCore { + /// [`download_attachment_reporting`](crate::VectorCore::download_attachment_reporting) through + /// the account's partial file: a failure, a stop or a restart leaves the bytes so far for the + /// next try, from any source serving the same blob. Walks the primary URL, its mirrors, then + /// the author's servers by content address; bytes that don't open condemn only their source. + pub async fn download_attachment_resumable bool + Send>( + &self, + attachment: &Attachment, + author_npub: Option<&str>, + mut step: F, + ) -> Result, DownloadError> { + if attachment.url.is_empty() { + return Err(DownloadError::Unusable("attachment has no URL".into())); + } + let part = part_for(&attachment.id).map_err(DownloadError::Unreachable)?; + if let Some(dir) = part.parent() { + sweep_stale(dir); + } + let declared = (attachment.size > 0).then_some(attachment.size); + let mut candidates: Vec = vec![attachment.url.clone()]; + candidates.extend(attachment.fallback_urls.iter().cloned()); + let mut last_err = String::from("download failed"); + let mut all_answered = true; + let mut hash_swap_tried = false; + // The source already given a fresh start: bytes it didn't serve can't condemn it twice. + let mut clean_retry: Option = None; + let mut i = 0; + while i < candidates.len() { + let url = candidates[i].clone(); + // Bytes already on disk came from an earlier source or launch, not this one. + let inherited = read_checkpoint(&part).is_some_and(|c| c.offset > 0); + let mut stopped = false; + let got = { + let mut progress = |bytes: u64, total: Option| { + let go = step(DownloadStep::Received { bytes, total }); + stopped |= !go; + go + }; + download_to_file(&url, &part, declared, &mut progress).await + }; + match got { + Ok(_) => {} + Err(_) if stopped => return Err(DownloadError::Cancelled), + Err(e) => { + last_err = e.to_string(); + if e != "File exceeds the maximum download size" { + all_answered &= e == "Media server returned an error status"; + } else { + // Every mirror serves the same blob: none would fit either. + discard_partial(&part); + return Err(DownloadError::TooLarge(declared.unwrap_or(0) as usize)); + } + i += 1; + if i == candidates.len() && !hash_swap_tried { + hash_swap_tried = true; + let servers = crate::blossom_servers::author_swap_servers(author_npub, false).await; + for c in crate::blossom::hash_swap_candidates(&attachment.url, &servers) { + if !candidates.contains(&c) { + candidates.push(c); + } + } + } + continue; + } + } + if !step(DownloadStep::Opening) { + return Err(DownloadError::Cancelled); + } + let (src, check, att) = (part.clone(), url.clone(), attachment.clone()); + let opened = tokio::task::spawn_blocking(move || open_part(&src, &check, &att)) + .await + .unwrap_or_else(|e| Err(e.to_string())); + match opened { + Ok(plain) => { + discard_partial(&part); + return Ok(plain); + } + Err(reason) => { + discard_partial(&part); + last_err = reason; + // Part of these bytes came from elsewhere: this source gets one clean run + // of its own before it is judged. + if inherited && clean_retry != Some(i) { + clean_retry = Some(i); + continue; + } + i += 1; + } + } + } + Err(if all_answered { DownloadError::Unusable(last_err) } else { DownloadError::Unreachable(last_err) }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::Arc; + use std::sync::atomic::{AtomicUsize, Ordering}; + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + + fn blob(n: usize) -> Vec { + (0..n).map(|i| (i * 31 % 251) as u8).collect() + } + + /// A one-file server on loopback. The first `cut` responses stop after `cut_at` bytes of the + /// body; every response honours `Range: bytes=N-`. Returns its URL and the Range starts seen. + async fn serve(body: Vec, cut: usize, cut_at: usize) -> (String, Arc>>) { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + let ranges = Arc::new(std::sync::Mutex::new(Vec::new())); + let seen = ranges.clone(); + let served = Arc::new(AtomicUsize::new(0)); + tokio::spawn(async move { + loop { + let Ok((mut sock, _)) = listener.accept().await else { return }; + let (body, seen, served) = (body.clone(), seen.clone(), served.clone()); + tokio::spawn(async move { + let mut req = vec![0u8; 4096]; + let n = sock.read(&mut req).await.unwrap_or(0); + let req = String::from_utf8_lossy(&req[..n]).to_ascii_lowercase(); + let start = req + .lines() + .find_map(|l| l.strip_prefix("range: bytes=")) + .and_then(|r| r.trim_end_matches('-').trim().trim_end_matches('-').parse::().ok()); + seen.lock().unwrap().push(start.unwrap_or(0)); + let from = start.unwrap_or(0) as usize; + let head = match start { + Some(s) => format!( + "HTTP/1.1 206 Partial Content\r\nContent-Length: {}\r\nContent-Range: bytes {}-{}/{}\r\nConnection: close\r\n\r\n", + body.len() - from, + s, + body.len() - 1, + body.len() + ), + None => format!("HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", body.len()), + }; + let _ = sock.write_all(head.as_bytes()).await; + let nth = served.fetch_add(1, Ordering::SeqCst); + let end = if nth < cut { (from + cut_at).min(body.len()) } else { body.len() }; + let _ = sock.write_all(&body[from..end]).await; + let _ = sock.shutdown().await; + }); + } + }); + (format!("http://{addr}/blob"), ranges) + } + + fn client() -> crate::net::HttpClient { + crate::net::build_http_client_with_options(None, Some(std::time::Duration::from_secs(5)), true).unwrap() + } + + #[test] + fn a_checkpoint_round_trips_and_needs_its_bytes() { + let dir = tempfile::tempdir().unwrap(); + let part = dir.path().join("abc.part"); + std::fs::write(&part, vec![7u8; 100]).unwrap(); + write_checkpoint(&part, Checkpoint { offset: 100, total: Some(400) }).unwrap(); + assert_eq!(read_checkpoint(&part), Some(Checkpoint { offset: 100, total: Some(400) })); + // A checkpoint claiming more than the file holds is not trusted. + write_checkpoint(&part, Checkpoint { offset: 200, total: None }).unwrap(); + assert_eq!(read_checkpoint(&part), None); + discard_partial(&part); + assert!(!part.exists() && !part.with_extension("ckpt").exists()); + } + + #[test] + fn the_checkpoint_file_is_the_desktop_clients_format() { + let dir = tempfile::tempdir().unwrap(); + let part = dir.path().join("abc.part"); + std::fs::write(&part, vec![0u8; 5]).unwrap(); + write_checkpoint(&part, Checkpoint { offset: 5, total: Some(9) }).unwrap(); + let raw = std::fs::read(part.with_extension("ckpt")).unwrap(); + assert_eq!(raw, [5u64.to_le_bytes(), 9u64.to_le_bytes()].concat()); + } + + #[tokio::test] + async fn a_cut_download_resumes_from_its_checkpoint() { + let body = blob(300_000); + let (url, ranges) = serve(body.clone(), 1, 120_000).await; + let dir = tempfile::tempdir().unwrap(); + let part = dir.path().join("x.part"); + let mut progress = |_: u64, _: Option| true; + // The first answer stops short: the bytes so far stay behind a checkpoint. + assert!(fetch_into(&client(), &url, None, &part, Some(body.len() as u64), &mut progress).await.is_err()); + let at = read_checkpoint(&part).expect("a checkpoint after the cut"); + assert_eq!(at.offset, 120_000); + // The next attempt asks for the rest, and the file comes out whole. + let n = fetch_into(&client(), &url, None, &part, Some(body.len() as u64), &mut progress).await.unwrap(); + assert_eq!(n, body.len() as u64); + assert_eq!(std::fs::read(&part).unwrap(), body); + assert_eq!(*ranges.lock().unwrap(), vec![0, 120_000]); + } + + #[tokio::test] + async fn a_stop_keeps_the_bytes_for_later() { + let body = blob(200_000); + let (url, _) = serve(body.clone(), 0, 0).await; + let dir = tempfile::tempdir().unwrap(); + let part = dir.path().join("y.part"); + let mut stop_early = |bytes: u64, _: Option| bytes < 50_000; + assert_eq!(fetch_into(&client(), &url, None, &part, None, &mut stop_early).await, Err(CANCELLED)); + assert!(read_checkpoint(&part).is_some_and(|c| c.offset >= 50_000)); + let mut go = |_: u64, _: Option| true; + fetch_into(&client(), &url, None, &part, None, &mut go).await.unwrap(); + assert_eq!(std::fs::read(&part).unwrap(), body); + } + + #[tokio::test] + async fn a_finished_checkpoint_needs_no_request() { + let dir = tempfile::tempdir().unwrap(); + let part = dir.path().join("z.part"); + std::fs::write(&part, vec![1u8; 10]).unwrap(); + write_checkpoint(&part, Checkpoint { offset: 10, total: Some(10) }).unwrap(); + let mut go = |_: u64, _: Option| true; + // Nothing listens there: any request would fail. + assert_eq!(fetch_into(&client(), "http://127.0.0.1:9/none", None, &part, None, &mut go).await, Ok(10)); + } +} diff --git a/crates/vector-core/src/search.rs b/crates/vector-core/src/search.rs new file mode 100644 index 000000000..cf204b6dc --- /dev/null +++ b/crates/vector-core/src/search.rs @@ -0,0 +1,906 @@ +//! On-device message search: every chat's text folded into one buffer and scanned with +//! `memchr::memmem`, so a query is a single SIMD pass with nothing sent anywhere. +//! +//! A [`Corpus`] holds plaintext, so it lives only as long as the search surface that built it. + +use std::ops::Range; + +use memchr::memmem; + +/// One searchable message. +struct Doc { + id: Box, + chat: u32, + author: Option>, + mine: bool, + at: u64, + has: Has, + mentions: Box<[Box]>, + /// Span in `Corpus::text`: the message, then its file names. + text: Range, + /// Where the message ends in `Corpus::text`, before its file names. + body: u32, + /// What renders the message as the timeline does, for the few that carry it. + look: Option>, + /// Span in `Corpus::folded`. + folded: Range, +} + +/// A message's custom emoji and text spans, with the text the spans count in when that is not +/// the searched text. +#[derive(Debug)] +struct Look { + written: Option>, + emoji: Box<[crate::types::EmojiTag]>, + spans: Box<[crate::text_spans::TextSpan]>, +} + +/// A hit's message as it was written, for drawing it as the timeline would. +#[derive(Debug, Clone, Copy)] +pub struct Source<'a> { + /// The message, with mentions named unless `spans` count in the text as sent. + pub text: &'a str, + pub emoji: &'a [crate::types::EmojiTag], + /// Color and time spans, in bytes of `text`. + pub spans: &'a [crate::text_spans::TextSpan], +} + +/// Messages to search, newest first. +#[derive(Default)] +pub struct Corpus { + chats: Vec>, + docs: Vec, + text: String, + /// Each doc folded by [`fold`], NUL-separated so a match never spans two. + folded: String, +} + +/// What [`Corpus::search`] found. +#[derive(Debug, Default, Clone, PartialEq)] +pub struct Found { + /// The newest `limit` matches. + pub hits: Vec, + /// Every match, including those past `limit`. + pub total: usize, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct Hit { + pub id: String, + pub chat: String, + pub author: Option, + pub mine: bool, + pub at: u64, + pub has: Has, + /// The message's place in the corpus, for [`Corpus::source`]. + pub doc: u32, + /// A window of the message around its first match, on one line. + pub snippet: String, + /// Each term's occurrences within `snippet`, in order. + pub marks: Vec>, +} + +/// What a message carries, for `has:` filters. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct Has(u8); + +impl Has { + pub const LINK: Has = Has(1); + pub const IMAGE: Has = Has(2); + pub const VIDEO: Has = Has(4); + pub const AUDIO: Has = Has(8); + /// Any attachment, media included. + pub const FILE: Has = Has(16); + + pub fn contains(self, other: Has) -> bool { + self.0 & other.0 == other.0 + } + + pub fn is_empty(self) -> bool { + self.0 == 0 + } + + /// From a message's text and its attachments' extensions. + pub fn of<'a>(text: &str, extensions: impl IntoIterator) -> Has { + let mut has = Has::default(); + if memmem::find(text.as_bytes(), b"https://").is_some() || memmem::find(text.as_bytes(), b"http://").is_some() { + has |= Has::LINK; + } + for ext in extensions { + has |= Has::FILE; + let mime = crate::crypto::mime_from_extension(ext); + if mime.starts_with("image/") { + has |= Has::IMAGE; + } else if mime.starts_with("video/") { + has |= Has::VIDEO; + } else if mime.starts_with("audio/") { + has |= Has::AUDIO; + } + } + has + } +} + +impl std::ops::BitOr for Has { + type Output = Has; + fn bitor(self, rhs: Has) -> Has { + Has(self.0 | rhs.0) + } +} + +impl std::ops::BitOrAssign for Has { + fn bitor_assign(&mut self, rhs: Has) { + self.0 |= rhs.0; + } +} + +/// Narrows a search. Each list matches any of its entries; the lists all have to match. +#[derive(Debug, Clone, Default, PartialEq)] +pub struct Filter { + /// Authors by npub. `from_me` counts this account's own messages too. + pub from: Vec, + pub from_me: bool, + /// Mentioned npubs. + pub mentions: Vec, + pub has: Has, + /// Chat ids: DM npubs or channel ids. + pub chats: Vec, + /// Inclusive bounds in ms. + pub after: Option, + pub before: Option, + /// Oldest first instead of newest. + pub oldest: bool, +} + +impl Filter { + pub fn is_empty(&self) -> bool { + self.from.is_empty() + && !self.from_me + && self.mentions.is_empty() + && self.has.is_empty() + && self.chats.is_empty() + && self.after.is_none() + && self.before.is_none() + } +} + +/// One message as [`load`] reads it, before it joins a [`Corpus`]. +#[derive(Debug, Clone, Default)] +pub struct Record { + pub chat: String, + pub id: String, + pub author: Option, + pub mine: bool, + pub at: u64, + pub text: String, + /// Attachments' `(extension, file name)`. + pub files: Vec<(String, String)>, + pub emoji: Vec, + /// Color and time spans, in bytes of `text`. + pub spans: Vec, +} + +/// A parsed query: whitespace-separated terms that must all appear, `"quoted phrases"` kept whole. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Query { + terms: Vec, +} + +impl Query { + /// The terms, folded. + pub fn terms(&self) -> &[String] { + &self.terms + } + + pub fn parse(input: &str) -> Self { + let mut terms = Vec::new(); + let mut rest = input; + while let Some(start) = rest.find(|c: char| !c.is_whitespace()) { + rest = &rest[start..]; + let (raw, next) = if let Some(body) = rest.strip_prefix('"') { + match body.find('"') { + Some(end) => (&body[..end], &body[end + 1..]), + None => (body, ""), + } + } else { + let end = rest.find(char::is_whitespace).unwrap_or(rest.len()); + (&rest[..end], &rest[end..]) + }; + let mut folded = String::new(); + fold_into(raw, &mut folded, None); + if !folded.trim().is_empty() && !terms.contains(&folded) { + terms.push(folded); + } + rest = next; + } + // The longest term scans the buffer; the rest only confirm its candidates. + terms.sort_by_key(|t| std::cmp::Reverse(t.len())); + Self { terms } + } + + pub fn is_empty(&self) -> bool { + self.terms.is_empty() + } +} + +/// Case and accent folding: `É` and `e` match, as do `ß`/`ss`-free lowercase forms. Scripts +/// without case (CJK, Arabic) pass through, so substring matching needs no word breaks. +pub fn fold(text: &str) -> String { + let mut out = String::with_capacity(text.len()); + fold_into(text, &mut out, None); + out +} + +/// [`fold`], appending to `out`; `map` gets, per folded byte, the source byte it came from. +fn fold_into(text: &str, out: &mut String, mut map: Option<&mut Vec>) { + for (at, ch) in text.char_indices() { + let before = out.len(); + if ch.is_ascii() { + // NUL separates documents. + out.push(if ch == '\0' { ' ' } else { ch.to_ascii_lowercase() }); + } else { + unicode_normalization::char::decompose_canonical(ch, |d| { + if !unicode_normalization::char::is_combining_mark(d) { + out.extend(d.to_lowercase()); + } + }); + } + if let Some(m) = map.as_deref_mut() { + m.extend(std::iter::repeat_n(at as u32, out.len() - before)); + } + } + if let Some(m) = map { + m.push(text.len() as u32); + } +} + +impl Corpus { + pub fn new() -> Self { + Self::default() + } + + pub fn len(&self) -> usize { + self.docs.len() + } + + pub fn is_empty(&self) -> bool { + self.docs.is_empty() + } + + /// Adds a message as `shown`: its text with mentions already named. Push newest first. + pub fn push(&mut self, record: &Record, shown: &str) { + let names = record.files.iter().map(|(_, n)| n.as_str()).filter(|n| !n.is_empty()); + let has = Has::of(&record.text, record.files.iter().map(|(e, _)| e.as_str())); + if shown.trim().is_empty() && has.is_empty() { + return; + } + let chat = match self.chats.iter().rposition(|c| **c == *record.chat) { + Some(ix) => ix as u32, + None => { + self.chats.push(record.chat.as_str().into()); + (self.chats.len() - 1) as u32 + } + }; + let t0 = self.text.len() as u32; + self.text.push_str(shown.trim()); + let body = self.text.len() as u32; + for name in names { + if self.text.len() as u32 > t0 { + self.text.push('\n'); + } + self.text.push_str(name); + } + let t1 = self.text.len() as u32; + let f0 = self.folded.len() as u32; + fold_into(&self.text[t0 as usize..], &mut self.folded, None); + let f1 = self.folded.len() as u32; + self.folded.push('\0'); + let mentions: Vec> = crate::types::extract_mentions(&record.text).into_iter().map(Into::into).collect(); + self.docs.push(Doc { + id: record.id.as_str().into(), + chat, + author: record.author.as_deref().map(Into::into), + mine: record.mine, + at: record.at, + has, + mentions: mentions.into_boxed_slice(), + text: t0..t1, + body, + look: (!record.emoji.is_empty() || !record.spans.is_empty()).then(|| { + Box::new(Look { + written: (!record.spans.is_empty()).then(|| record.text.as_str().into()), + emoji: record.emoji.clone().into_boxed_slice(), + spans: record.spans.clone().into_boxed_slice(), + }) + }), + folded: f0..f1, + }); + } + + /// Messages holding every term and passing `filter`. A query with no terms lists every + /// message the filter passes. + pub fn search(&self, query: &Query, filter: &Filter, limit: usize) -> Found { + let mut found = Found::default(); + if query.is_empty() && filter.is_empty() { + return found; + } + let chats: Vec = filter + .chats + .iter() + .filter_map(|c| self.chats.iter().position(|x| **x == **c).map(|i| i as u32)) + .collect(); + if !filter.chats.is_empty() && chats.is_empty() { + return found; + } + let passes = |d: &Doc| { + (chats.is_empty() || chats.contains(&d.chat)) + && (filter.from.is_empty() && !filter.from_me + || filter.from_me && d.mine + || d.author.as_deref().is_some_and(|a| filter.from.iter().any(|f| f == a))) + && (filter.mentions.is_empty() || d.mentions.iter().any(|m| filter.mentions.iter().any(|f| **f == **m))) + && d.has.contains(filter.has) + && filter.after.is_none_or(|a| d.at >= a) + && filter.before.is_none_or(|b| d.at <= b) + }; + // Matches as doc indices, newest first; hits are built only for those listed. + let mut matched: Vec = Vec::new(); + let mut note = |ix: usize| { + found.total += 1; + if filter.oldest || matched.len() < limit { + matched.push(ix as u32); + } + }; + match query.terms.split_first() { + None => { + for (ix, _) in self.docs.iter().enumerate().filter(|(_, d)| passes(d)) { + note(ix); + } + } + // A chat filter walks only its chats' messages. + Some(_) if !chats.is_empty() => { + let finders: Vec = query.terms.iter().map(|t| memmem::Finder::new(t.as_bytes())).collect(); + let hay = self.folded.as_bytes(); + for (ix, d) in self.docs.iter().enumerate() { + if chats.contains(&d.chat) && passes(d) { + let body = &hay[d.folded.start as usize..d.folded.end as usize]; + if finders.iter().all(|f| f.find(body).is_some()) { + note(ix); + } + } + } + } + Some((lead, rest)) => { + let finders: Vec = rest.iter().map(|t| memmem::Finder::new(t.as_bytes())).collect(); + let hay = self.folded.as_bytes(); + let lead = memmem::Finder::new(lead.as_bytes()); + let mut cursor = 0usize; + let mut doc_ix = 0usize; + while cursor < hay.len() { + let Some(pos) = lead.find(&hay[cursor..]).map(|p| p + cursor) else { break }; + // Docs are laid out in order, so the owner is at or after the last one found. + doc_ix += self.docs[doc_ix..].partition_point(|d| (d.folded.end as usize) < pos); + let Some(doc) = self.docs.get(doc_ix) else { break }; + cursor = doc.folded.end as usize + 1; + let body = &hay[doc.folded.start as usize..doc.folded.end as usize]; + if passes(doc) && finders.iter().all(|f| f.find(body).is_some()) { + note(doc_ix); + } + doc_ix += 1; + } + } + } + if filter.oldest { + let skip = matched.len().saturating_sub(limit); + matched.drain(..skip); + matched.reverse(); + } + found.hits = matched.into_iter().map(|ix| self.hit(ix, query)).collect(); + found + } + + /// The message `doc` names, as written. + pub fn source(&self, doc: u32) -> Option> { + let d = self.docs.get(doc as usize)?; + let body = &self.text[d.text.start as usize..d.body as usize]; + Some(match d.look.as_deref() { + Some(l) => Source { text: l.written.as_deref().unwrap_or(body), emoji: &l.emoji, spans: &l.spans }, + None => Source { text: body, emoji: &[], spans: &[] }, + }) + } + + fn hit(&self, ix: u32, query: &Query) -> Hit { + let doc = &self.docs[ix as usize]; + let text = &self.text[doc.text.start as usize..doc.text.end as usize]; + let (snippet, marks) = snippet(text, &query.terms, 60); + Hit { + doc: ix, + id: doc.id.to_string(), + chat: self.chats[doc.chat as usize].to_string(), + author: doc.author.as_deref().map(str::to_string), + mine: doc.mine, + at: doc.at, + has: doc.has, + snippet, + marks, + } + } +} + +/// `text` cut to about `context` characters either side of its first match, whitespace runs +/// collapsed, with every term's occurrences marked in the result. +fn snippet(text: &str, terms: &[String], context: usize) -> (String, Vec>) { + let merged = marks(text, terms); + let first = merged.first().map_or(0, |r| r.start); + let start = back_chars(text, first, context); + let end = merged.first().map_or(0, |r| r.end); + let stop = fwd_chars(text, end, context * 2); + + let mut out = String::with_capacity(stop - start + 8); + let mut marks = Vec::new(); + if start > 0 { + out.push('…'); + } + let mut open: Option = None; + let mut spans = merged.iter().peekable(); + let mut space = false; + for (i, ch) in text[start..stop].char_indices() { + let at = start + i; + while spans.peek().is_some_and(|s| s.end <= at) { + let s = spans.next().unwrap(); + if let Some(o) = open.take() { + marks.push(o..out.len()); + } + let _ = s; + } + if open.is_none() && spans.peek().is_some_and(|s| s.start <= at) { + if space { + out.push(' '); + space = false; + } + open = Some(out.len()); + } + if ch.is_whitespace() { + space = !out.is_empty() && !out.ends_with('…'); + continue; + } + if space { + out.push(' '); + space = false; + } + out.push(ch); + } + if let Some(o) = open.take() { + marks.push(o..out.len()); + } + if stop < text.len() { + out.push('…'); + } + (out, marks) +} + +/// Every occurrence of each folded term in `text`, as byte ranges of `text`, overlaps merged. +pub fn marks(text: &str, terms: &[String]) -> Vec> { + let mut folded = String::with_capacity(text.len()); + let mut map = Vec::with_capacity(text.len() + 1); + fold_into(text, &mut folded, Some(&mut map)); + let mut spans: Vec> = Vec::new(); + for term in terms.iter().filter(|t| !t.is_empty()) { + let mut from = 0; + while let Some(at) = memmem::find(&folded.as_bytes()[from..], term.as_bytes()).map(|p| p + from) { + let end = at + term.len(); + spans.push(map[at] as usize..source_end(&map, end, text)); + from = end; + } + } + spans.sort_by_key(|r| (r.start, std::cmp::Reverse(r.end))); + let mut merged: Vec> = Vec::with_capacity(spans.len()); + for s in spans { + match merged.last_mut() { + Some(last) if s.start <= last.end => last.end = last.end.max(s.end), + _ => merged.push(s), + } + } + merged +} + +/// The source byte after folded byte `end - 1`: the end of the character it came from. +fn source_end(map: &[u32], end: usize, text: &str) -> usize { + let src = map[end - 1] as usize; + src + text[src..].chars().next().map_or(0, char::len_utf8) +} + +fn back_chars(text: &str, from: usize, n: usize) -> usize { + let head = &text[..from]; + let cut = head.char_indices().rev().nth(n.saturating_sub(1)).map_or(0, |(i, _)| i); + if cut == 0 { + return 0; + } + // Start on a word where one is near. + head[cut..].find(char::is_whitespace).filter(|&w| w < 16).map_or(cut, |w| cut + w + 1).min(from) +} + +fn fwd_chars(text: &str, from: usize, n: usize) -> usize { + text[from..].char_indices().nth(n).map_or(text.len(), |(i, _)| from + i) +} + +/// `text` with each mentioned npub (`@npub1…`, `nostr:npub1…` or bare) shown as `@name`, +/// so a search for the name finds the mention. +pub fn name_mentions(text: &str, name: impl Fn(&str) -> Option) -> String { + let mentions = crate::types::extract_mentions(text); + if mentions.is_empty() { + return text.to_string(); + } + let base = text.as_ptr() as usize; + let mut out = String::with_capacity(text.len()); + let mut last = 0; + for m in mentions { + let mut start = m.as_ptr() as usize - base; + let end = start + m.len(); + if text[..start].ends_with("nostr:") { + start -= 6; + } + if text[..start].ends_with('@') { + start -= 1; + } + if start < last { + continue; + } + out.push_str(&text[last..start]); + match name(m) { + Some(n) => { + out.push('@'); + out.push_str(&n); + } + None => out.push_str(&text[start..end]), + } + last = end; + } + out.push_str(&text[last..]); + out +} + +/// Every stored message's current text (edits applied), newest first, for the account the +/// caller is bound to. Banned authors' posts are left out, as the timeline leaves them out. +#[cfg(not(target_arch = "wasm32"))] +pub fn load() -> Result, String> { + use std::collections::HashMap; + use crate::stored_event::event_kind; + + struct Row { + id: String, + kind: u16, + chat: String, + content: String, + reference: Option, + at: u64, + mine: bool, + npub: Option, + emoji: Vec, + /// Color and time span tags, checked against the content once it is open. + span_tags: Vec>, + } + + let (rows, communities, files) = { + let conn = crate::db::get_db_connection_guard_static()?; + let mut stmt = conn + .prepare( + "SELECT e.id, e.kind, c.chat_identifier, e.content, e.reference_id, e.created_at, e.tags, e.mine, e.npub \ + FROM events e JOIN chats c ON c.id = e.chat_id \ + WHERE e.kind IN (?1, ?2, ?3, ?4) \ + ORDER BY e.created_at DESC, e.received_at DESC", + ) + .map_err(|e| format!("Failed to prepare search query: {e}"))?; + let styled = ["emoji", crate::text_color::TAG, crate::text_time::TAG].map(|n| format!("[\"{n}\"")); + let rows: Vec = stmt + .query_map( + rusqlite::params![ + event_kind::CHAT_MESSAGE as i32, + event_kind::PRIVATE_DIRECT_MESSAGE as i32, + event_kind::FILE_ATTACHMENT as i32, + event_kind::MESSAGE_EDIT as i32, + ], + |r| { + let tags: String = r.get(6)?; + let secs = r.get::<_, i64>(5)? as u64; + // Only the few rows naming emoji or spans pay for parsing their tags. + let parsed: Vec> = if styled.iter().any(|n| tags.contains(n.as_str())) { + serde_json::from_str(&tags).unwrap_or_default() + } else { + Vec::new() + }; + let emoji = crate::types::EmojiTag::extract_from_stored(&parsed); + let span_tags = parsed + .into_iter() + .filter(|t| matches!(t.first().map(String::as_str), Some(crate::text_color::TAG | crate::text_time::TAG))) + .collect(); + Ok(Row { + id: r.get(0)?, + kind: r.get::<_, i32>(1)? as u16, + chat: r.get(2)?, + content: r.get(3)?, + reference: r.get(4)?, + at: secs * 1000 + ms_of(&tags), + mine: r.get::<_, i32>(7)? != 0, + npub: r.get(8)?, + emoji, + span_tags, + }) + }, + ) + .map_err(|e| format!("Failed to run search query: {e}"))? + .filter_map(Result::ok) + .collect(); + let communities: HashMap = conn + .prepare("SELECT channel_id, community_id FROM community_channels") + .and_then(|mut s| { + s.query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?))) + .map(|it| it.filter_map(Result::ok).collect()) + }) + .unwrap_or_default(); + let files: Vec<(String, String, String)> = conn + .prepare("SELECT event_id, extension, name FROM attachments ORDER BY event_id, att_index") + .and_then(|mut s| { + s.query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?, r.get::<_, String>(2)?))) + .map(|it| it.filter_map(Result::ok).collect()) + }) + .unwrap_or_default(); + (rows, communities, files) + }; + + let mut banned: HashMap<&str, std::collections::HashSet> = HashMap::new(); + for community in communities.values() { + banned.entry(community.as_str()).or_insert_with(|| { + use nostr_sdk::prelude::ToBech32; + crate::db::community::banned_set(community) + .iter() + .filter_map(|b| nostr_sdk::prelude::PublicKey::from_slice(b).ok()?.to_bech32().ok()) + .collect() + }); + } + + crate::crypto::open_batch(|at_rest| { + let mut by_event: HashMap> = HashMap::new(); + for (event, ext, name) in files { + by_event.entry(event).or_default().push((ext, at_rest.open_or_keep(name))); + } + // Newest edit per message: rows arrive newest first, so the first seen wins. + let mut edits: HashMap, Vec>)> = HashMap::new(); + for row in rows.iter().filter(|r| r.kind == event_kind::MESSAGE_EDIT) { + let Some(target) = &row.reference else { continue }; + if !edits.contains_key(target) { + if let Ok(text) = at_rest.open(row.content.clone()) { + edits.insert(target.clone(), (text, row.emoji.clone(), row.span_tags.clone())); + } + } + } + let mut out = Vec::with_capacity(rows.len()); + for row in rows.into_iter().filter(|r| r.kind != event_kind::MESSAGE_EDIT) { + let is_banned = match (&row.npub, communities.get(&row.chat)) { + (Some(author), Some(community)) => banned.get(community.as_str()).is_some_and(|b| b.contains(author)), + _ => false, + }; + if is_banned { + continue; + } + let files = by_event.remove(&row.id).unwrap_or_default(); + let (text, emoji, span_tags) = match edits.remove(&row.id) { + Some(edited) => edited, + // A file event's content is its URL, not words. + None if row.kind == event_kind::FILE_ATTACHMENT => Default::default(), + None => match at_rest.open(row.content) { + Ok(t) => (t, row.emoji, row.span_tags), + Err(_) => continue, + }, + }; + let spans = if span_tags.is_empty() { Vec::new() } else { crate::text_spans::from_stored(&span_tags, &text) }; + out.push(Record { chat: row.chat, id: row.id, author: row.npub, mine: row.mine, at: row.at, text, files, emoji, spans }); + } + Ok(out) + }) +} + +#[cfg(not(target_arch = "wasm32"))] +fn ms_of(tags: &str) -> u64 { + // `["ms","123"]` without parsing every row's whole tag list. + let Some(at) = tags.find("[\"ms\",\"") else { return 0 }; + let digits = &tags[at + 7..]; + digits[..digits.find('"').unwrap_or(0)].parse().unwrap_or(0) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn rec(chat: &str, id: &str, author: Option<&str>, mine: bool, at: u64, text: &str) -> Record { + Record { chat: chat.into(), id: id.into(), author: author.map(Into::into), mine, at, text: text.into(), ..Default::default() } + } + + fn add(c: &mut Corpus, r: Record) { + let shown = r.text.clone(); + c.push(&r, &shown); + } + + fn corpus() -> Corpus { + let mut c = Corpus::new(); + add(&mut c, rec("npub1a", "m4", Some("npub1a"), false, 4000, "Café at nine? Bring the BLUEPRINTS https://x.io")); + add(&mut c, rec("chan", "m3", Some("npub1b"), false, 3000, "the blueprints are in the shared folder")); + add(&mut c, rec("npub1a", "m2", None, true, 2000, "see you at the café")); + add(&mut c, rec("chan", "m1", Some("npub1c"), false, 1000, "東京で会いましょう")); + let mut pic = rec("chan", "m0", Some("npub1b"), false, 500, ""); + pic.files.push(("png".into(), "harbour.png".into())); + add(&mut c, pic); + c + } + + fn find(c: &Corpus, q: &str) -> Found { + c.search(&Query::parse(q), &Filter::default(), 10) + } + + fn ids(f: &Found) -> Vec<&str> { + f.hits.iter().map(|h| h.id.as_str()).collect() + } + + #[test] + fn folds_case_and_accents() { + let c = corpus(); + assert_eq!(ids(&find(&c, "CAFE")), ["m4", "m2"]); + assert_eq!(ids(&find(&c, "blueprints")), ["m4", "m3"]); + } + + #[test] + fn every_term_must_match_in_any_order() { + let c = corpus(); + assert_eq!(ids(&find(&c, "folder blueprints")), ["m3"]); + assert!(find(&c, "folder café").hits.is_empty()); + } + + #[test] + fn a_hit_names_its_source() { + let mut c = corpus(); + let mut styled = rec("chan", "m5", Some("npub1b"), false, 5000, " rainbow :grin: here "); + styled.emoji.push(crate::types::EmojiTag { shortcode: "grin".into(), url: "https://x.io/g.png".into() }); + styled.spans.push(crate::text_spans::TextSpan::Color(crate::text_color::ColorSpan { + from: 2, + to: 9, + effect: crate::text_color::Effect::Rainbow, + colors: Vec::new(), + })); + add(&mut c, styled); + let hit = &find(&c, "rainbow").hits[0]; + let src = c.source(hit.doc).unwrap(); + assert_eq!((src.text, src.emoji.len(), src.spans.len()), (" rainbow :grin: here ", 1, 1)); + let hit = &find(&c, "harbour").hits[0]; + let src = c.source(hit.doc).unwrap(); + assert_eq!((src.text, src.emoji.len()), ("", 0)); + let hit = &find(&c, "folder").hits[0]; + assert_eq!(c.source(hit.doc).unwrap().text, "the blueprints are in the shared folder"); + } + + #[test] + fn marks_fold_and_merge() { + let terms = vec!["cafe".to_string(), "fe a".to_string()]; + assert_eq!(marks("Café at nine, CAFE", &terms), [0..7, 15..19]); + assert!(marks("nothing", &["".to_string()]).is_empty()); + } + + #[test] + fn phrases_stay_whole() { + let c = corpus(); + assert_eq!(ids(&find(&c, "\"at the\"")), ["m2"]); + assert_eq!(ids(&find(&c, "at the")), ["m4", "m2"]); + } + + #[test] + fn cjk_matches_without_word_breaks() { + let c = corpus(); + assert_eq!(ids(&find(&c, "会い")), ["m1"]); + } + + fn chat(id: &str) -> Filter { + Filter { chats: vec![id.into()], ..Default::default() } + } + + #[test] + fn scope_and_limit() { + let c = corpus(); + assert_eq!(ids(&c.search(&Query::parse("the"), &chat("chan"), 10)), ["m3"]); + let f = c.search(&Query::parse("e"), &Filter::default(), 2); + assert_eq!(ids(&f), ["m4", "m3"]); + assert_eq!(f.total, 3); + assert!(c.search(&Query::parse("the"), &chat("nowhere"), 10).hits.is_empty()); + } + + #[test] + fn oldest_first_keeps_the_oldest() { + let c = corpus(); + let f = c.search(&Query::parse("e"), &Filter { oldest: true, ..Default::default() }, 2); + assert_eq!(ids(&f), ["m2", "m3"]); + assert_eq!(f.total, 3); + } + + #[test] + fn filters_alone_list_messages() { + let c = corpus(); + let from = Filter { from: vec!["npub1b".into()], ..Default::default() }; + assert_eq!(ids(&c.search(&Query::parse(""), &from, 10)), ["m3", "m0"]); + let me = Filter { from_me: true, ..Default::default() }; + assert_eq!(ids(&c.search(&Query::parse("cafe"), &me, 10)), ["m2"]); + let image = Filter { has: Has::IMAGE, ..Default::default() }; + assert_eq!(ids(&c.search(&Query::parse(""), &image, 10)), ["m0"]); + let link = Filter { has: Has::LINK, ..Default::default() }; + assert_eq!(ids(&c.search(&Query::parse(""), &link, 10)), ["m4"]); + let span = Filter { after: Some(1000), before: Some(3000), ..Default::default() }; + assert_eq!(ids(&c.search(&Query::parse(""), &span, 10)), ["m3", "m2", "m1"]); + } + + #[test] + fn file_names_are_searchable() { + let c = corpus(); + assert_eq!(ids(&find(&c, "harbour")), ["m0"]); + } + + #[test] + fn mentions_filter_and_names() { + let npub = "npub1sg6plzptd64u62a878hep2kev88swjh3tw00gjsfl8f237lmu63q0uf63m"; + let mut c = Corpus::new(); + let r = rec("chan", "a", Some("npub1x"), false, 2, &format!("ping @{npub} about lunch")); + let shown = name_mentions(&r.text, |n| (n == npub).then(|| "Alice".to_string())); + assert_eq!(shown, "ping @Alice about lunch"); + c.push(&r, &shown); + add(&mut c, rec("chan", "b", Some("npub1x"), false, 1, "lunch?")); + let f = Filter { mentions: vec![npub.into()], ..Default::default() }; + assert_eq!(ids(&c.search(&Query::parse("lunch"), &f, 10)), ["a"]); + assert_eq!(ids(&find(&c, "alice")), ["a"]); + } + + #[test] + fn no_match_across_messages() { + let mut c = Corpus::new(); + add(&mut c, rec("x", "a", None, true, 2, "end")); + add(&mut c, rec("x", "b", None, true, 1, "start")); + assert!(find(&c, "endstart").hits.is_empty()); + assert!(find(&c, "dst").hits.is_empty()); + } + + #[test] + fn marks_point_at_the_original_text() { + let c = corpus(); + let hit = &find(&c, "cafe blueprints").hits[0]; + let marked: Vec<&str> = hit.marks.iter().map(|r| &hit.snippet[r.clone()]).collect(); + assert_eq!(marked, ["Café", "BLUEPRINTS"]); + } + + #[test] + fn long_text_is_cut_around_the_match() { + let mut c = Corpus::new(); + let long = format!("{} needle {}", "lorem ipsum ".repeat(40), "dolor sit ".repeat(40)); + add(&mut c, rec("x", "a", None, true, 1, &long)); + let hit = &find(&c, "needle").hits[0]; + assert!(hit.snippet.starts_with('…') && hit.snippet.ends_with('…'), "{}", hit.snippet); + assert!(hit.snippet.chars().count() < 200); + assert_eq!(&hit.snippet[hit.marks[0].clone()], "needle"); + } + + #[test] + fn whitespace_collapses_in_snippets() { + let mut c = Corpus::new(); + add(&mut c, rec("x", "a", None, true, 1, "line one\n\n line two")); + let hit = &find(&c, "two").hits[0]; + assert_eq!(hit.snippet, "line one line two"); + assert_eq!(&hit.snippet[hit.marks[0].clone()], "two"); + } + + #[test] + fn blank_queries_find_nothing() { + let c = corpus(); + assert!(Query::parse(" ").is_empty()); + assert!(Query::parse("\"\"").is_empty()); + assert_eq!(find(&c, ""), Found::default()); + } + + #[test] + fn ms_tag_is_read() { + assert_eq!(ms_of(r#"[["p","x"],["ms","417"]]"#), 417); + assert_eq!(ms_of("[]"), 0); + } +} diff --git a/crates/vector-core/src/text_color.rs b/crates/vector-core/src/text_color.rs index 731fb4731..34fc526b1 100644 --- a/crates/vector-core/src/text_color.rs +++ b/crates/vector-core/src/text_color.rs @@ -143,6 +143,11 @@ pub fn hex(s: &str) -> Option { names().get(s.to_ascii_lowercase().as_str()).map(|h| h.to_string()) } +/// Every colour name and its `#rrggbb`, for a client's suggestions. +pub fn named() -> impl Iterator { + names().iter().map(|(&k, &v)| (k, v)) +} + /// Every colour name a sender can type: the CSS names, the basic ones tuned for the /// dark chat, and a few friendly extras. The JS side reads the same file's contents. fn names() -> &'static std::collections::HashMap<&'static str, &'static str> { @@ -213,7 +218,7 @@ fn attr<'a>(args: &'a str, name: &str) -> Option<&'a str> { } /// Byte ranges markup must not reach into: fenced blocks and inline code. -pub(crate) fn code_ranges(content: &str) -> Vec<(usize, usize)> { +pub fn code_ranges(content: &str) -> Vec<(usize, usize)> { let mut out = Vec::new(); let mut fence_start: Option = None; let mut line_start = 0; @@ -318,15 +323,8 @@ fn scan(content: &str) -> Vec { out } -/// Take the colour markup out of `content`. Returns the plain text and its spans; -/// a tag without its partner stays as typed, and markup around nothing but -/// whitespace stays too, so a send is never emptied by its own tags. -pub fn extract(content: &str) -> (String, Vec) { - if !content.contains('<') { - return (content.to_string(), Vec::new()); - } - let marks = scan(content); - // Pair opens with closes like brackets; an unmatched close is left as text. +/// Opens paired with closes like brackets (an unmatched close stays text), ordered by open. +fn pair(marks: &[Markup]) -> Vec<(usize, usize)> { let mut stack: Vec = Vec::new(); let mut pairs: Vec<(usize, usize)> = Vec::new(); for (idx, m) in marks.iter().enumerate() { @@ -338,10 +336,46 @@ pub fn extract(content: &str) -> (String, Vec) { } } } + pairs.sort_by_key(|&(o, _)| marks[o].at); + pairs +} + +/// One matched pair of colour tags, in byte ranges of the source: what a composer previews. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct MarkupPair { + pub open: std::ops::Range, + pub close: std::ops::Range, + pub effect: Effect, + pub colors: Vec, +} + +/// Every matched pair of colour tags in `content`, ordered by where each opens. +pub fn markup_pairs(content: &str) -> Vec { + if !content.contains('<') { + return Vec::new(); + } + let marks = scan(content); + pair(&marks) + .into_iter() + .filter_map(|(o, c)| { + let (effect, colors) = marks[o].open.clone()?; + Some(MarkupPair { open: marks[o].at..marks[o].end, close: marks[c].at..marks[c].end, effect, colors }) + }) + .collect() +} + +/// Take the colour markup out of `content`. Returns the plain text and its spans; +/// a tag without its partner stays as typed, and markup around nothing but +/// whitespace stays too, so a send is never emptied by its own tags. +pub fn extract(content: &str) -> (String, Vec) { + if !content.contains('<') { + return (content.to_string(), Vec::new()); + } + let marks = scan(content); + let pairs = pair(&marks); if pairs.is_empty() { return (content.to_string(), Vec::new()); } - pairs.sort_by_key(|&(o, _)| marks[o].at); let mut cut: Vec<(usize, usize)> = pairs.iter().flat_map(|&(o, c)| [(marks[o].at, marks[o].end), (marks[c].at, marks[c].end)]).collect(); cut.sort_unstable(); diff --git a/crates/vector-core/src/vcache.rs b/crates/vector-core/src/vcache.rs index 559bceb5d..a33f47626 100644 --- a/crates/vector-core/src/vcache.rs +++ b/crates/vector-core/src/vcache.rs @@ -323,7 +323,7 @@ pub fn seal_in_place(path: &Path) -> Result { /// Seal every legacy picture and video under `dir`, recursively; sidecars and markers stay as /// they are. Returns how many were sealed. pub fn seal_dir(dir: &Path) -> usize { - const MEDIA: [&str; 13] = ["png", "jpg", "jpeg", "gif", "webp", "bmp", "ico", "svg", "tif", "tiff", "mp4", "webm", "mov"]; + const MEDIA: [&str; 14] = ["png", "jpg", "jpeg", "gif", "webp", "jxl", "bmp", "ico", "svg", "tif", "tiff", "mp4", "webm", "mov"]; let Ok(entries) = std::fs::read_dir(dir) else { return 0 }; let mut sealed = 0; for entry in entries.flatten() { diff --git a/crates/vector-gpui/.cargo/config.toml b/crates/vector-gpui/.cargo/config.toml new file mode 100644 index 000000000..2936115e5 --- /dev/null +++ b/crates/vector-gpui/.cargo/config.toml @@ -0,0 +1,4 @@ +[env] +# The oldest macOS this client supports, for rustc, cc and cmake alike; bundle-macos.sh copies it +# into the app's LSMinimumSystemVersion. GPUI's Metal shaders are compiled for the same floor. +MACOSX_DEPLOYMENT_TARGET = "12.0" diff --git a/crates/vector-gpui/.gitignore b/crates/vector-gpui/.gitignore new file mode 100644 index 000000000..2f7896d1d --- /dev/null +++ b/crates/vector-gpui/.gitignore @@ -0,0 +1 @@ +target/ diff --git a/crates/vector-gpui/Cargo.lock b/crates/vector-gpui/Cargo.lock new file mode 100644 index 000000000..4ab1dfa49 --- /dev/null +++ b/crates/vector-gpui/Cargo.lock @@ -0,0 +1,15689 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "accesskit" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3b7f7f85a7e5f68090000ed7622545829afd484d210358702ae4cb97dd0c320" +dependencies = [ + "enumn", + "uuid", +] + +[[package]] +name = "accesskit_android" +version = "0.7.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e27dedd5e1932e1f52fedcde681bc2ae4213df53bad5b295103aa36b1d0ffb6" +dependencies = [ + "accesskit", + "accesskit_consumer", + "jni 0.21.1", + "log", +] + +[[package]] +name = "accesskit_atspi_common" +version = "0.19.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "023da0e5097f46df7092d5280b02efb9bbf8d93298daeced42652463e357d636" +dependencies = [ + "accesskit", + "accesskit_consumer", + "atspi-common", + "phf 0.13.1", + "serde", + "zvariant", +] + +[[package]] +name = "accesskit_consumer" +version = "0.38.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d10a236f96f87d70732e44520046785431ef01d5bcd6b041317bfadd2f88245" +dependencies = [ + "accesskit", + "hashbrown 0.16.1", +] + +[[package]] +name = "accesskit_macos" +version = "0.26.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce02dc63b43f0c9296af9ac946312a2dc8814427d7a64d2d600971dac55b6076" +dependencies = [ + "accesskit", + "accesskit_consumer", + "hashbrown 0.16.1", + "objc2 0.5.3", + "objc2-app-kit 0.2.2", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "accesskit_unix" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03e156ed3802e35eefe894ef2671bc6c889303d8a7e110b5e1b48f504b91362f" +dependencies = [ + "accesskit", + "accesskit_atspi_common", + "async-channel", + "async-executor", + "async-task", + "atspi", + "futures-lite", + "futures-util", + "serde", + "zbus 5.19.0", +] + +[[package]] +name = "accesskit_windows" +version = "0.34.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "106c2b961215864d1c2e703ee63269c25c4e80a577ffb2c1017b9c17dcdf83a1" +dependencies = [ + "accesskit", + "accesskit_consumer", + "hashbrown 0.16.1", + "static_assertions", + "windows 0.62.2", + "windows-core 0.62.2", +] + +[[package]] +name = "addr2line" +version = "0.27.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e567177890eb1617b1f774005b66b26b2377afd138a2ca37aae7d8f0c81429d4" +dependencies = [ + "gimli", +] + +[[package]] +name = "adler2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" + +[[package]] +name = "adler32" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aae1277d39aeec15cb388266ecc24b11c80469deae6067e17a1a7aa9e5c1f234" + +[[package]] +name = "aead" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d122413f284cf2d62fb1b7db97e02edb8cda96d769b16e443a4f6195e35662b0" +dependencies = [ + "crypto-common 0.1.7", + "generic-array", +] + +[[package]] +name = "aes" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0" +dependencies = [ + "cfg-if 1.0.5", + "cipher 0.4.4", + "cpufeatures 0.2.17", + "zeroize", +] + +[[package]] +name = "aes" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc0fc36d7440d015b45468ba08a21e80e056ebbd014c611c6298bb7503e04bd1" +dependencies = [ + "cipher 0.5.2", + "cpubits", + "cpufeatures 0.3.1", + "zeroize", +] + +[[package]] +name = "aes-gcm" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "831010a0f742e1209b3bcea8fab6a8e149051ba6099432c8cb2cc117dec3ead1" +dependencies = [ + "aead", + "aes 0.8.4", + "cipher 0.4.4", + "ctr 0.9.2", + "ghash 0.5.1", + "subtle", +] + +[[package]] +name = "ahash" +version = "0.7.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "891477e0c6a8957309ee5c45a6368af3ae14bb510732d2684ffa19af310920f9" +dependencies = [ + "getrandom 0.2.17", + "once_cell", + "version_check", +] + +[[package]] +name = "ahash" +version = "0.8.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75" +dependencies = [ + "cfg-if 1.0.5", + "const-random", + "once_cell", + "version_check", + "zerocopy", +] + +[[package]] +name = "aho-corasick" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" +dependencies = [ + "memchr", +] + +[[package]] +name = "aligned" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee4508988c62edf04abd8d92897fca0c2995d907ce1dfeaf369dac3716a40685" +dependencies = [ + "as-slice", +] + +[[package]] +name = "aligned-vec" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc890384c8602f339876ded803c97ad529f3842aba97f6392b3dba0dd171769b" +dependencies = [ + "equator", +] + +[[package]] +name = "alloc-no-stdlib" +version = "2.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc7bb162ec39d46ab1ca8c77bf72e890535becd1751bb45f64c597edb4c8c6b3" + +[[package]] +name = "alloc-stdlib" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e76a019e91224d279006ff972f1e984179a6e9feb050adba6ce8274aef23195" +dependencies = [ + "alloc-no-stdlib", +] + +[[package]] +name = "allocator-api2" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" + +[[package]] +name = "alsa" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed7572b7ba83a31e20d1b48970ee402d2e3e0537dcfe0a3ff4d6eb7508617d43" +dependencies = [ + "alsa-sys", + "bitflags 2.13.2", + "cfg-if 1.0.5", + "libc", +] + +[[package]] +name = "alsa-sys" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db8fee663d06c4e303404ef5f40488a53e062f89ba8bfed81f42325aafad1527" +dependencies = [ + "libc", + "pkg-config", +] + +[[package]] +name = "amplify" +version = "4.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f7fb4ac7c881e54a8e7015e399b6112a2a5bc958b6c89ac510840ff20273b31" +dependencies = [ + "amplify_derive", + "amplify_num", + "ascii", + "getrandom 0.2.17", + "getrandom 0.3.4", + "wasm-bindgen", +] + +[[package]] +name = "amplify_derive" +version = "4.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2a6309e6b8d89b36b9f959b7a8fa093583b94922a0f6438a24fb08936de4d428" +dependencies = [ + "amplify_syn", + "proc-macro2", + "quote", + "syn 1.0.109", +] + +[[package]] +name = "amplify_num" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "afed304556696656d2d71495e1e5f2c4b524a3fb6eb0f2f3778ffc482a40b8a8" +dependencies = [ + "wasm-bindgen", +] + +[[package]] +name = "amplify_syn" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7736fb8d473c0d83098b5bac44df6a561e20470375cd8bcae30516dc889fd62a" +dependencies = [ + "proc-macro2", + "quote", + "syn 1.0.109", +] + +[[package]] +name = "android_system_properties" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc" +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 = "anstream" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d" +dependencies = [ + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "is_terminal_polyfill", + "utf8parse", +] + +[[package]] +name = "anstyle" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" + +[[package]] +name = "anstyle-parse" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-query" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "anstyle-wincon" +version = "3.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" +dependencies = [ + "anstyle", + "once_cell_polyfill", + "windows-sys 0.61.2", +] + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + +[[package]] +name = "arbitrary" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bc62ac97cc33321f50863d514c3bc38a453947a8f9e781137e47c7401020aed" +dependencies = [ + "derive_arbitrary", +] + +[[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.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "84a22b5d51209f6de83d37a0b33d320acb8da88823e42a94c075140708f032a5" +dependencies = [ + "rustversion", +] + +[[package]] +name = "arg_enum_proc_macro" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ae92a5119aa49cdbcf6b9f893fe4e1d98b04ccbf82ee0584ad948a44a734dea" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "argon2" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c3610892ee6e0cbce8ae2700349fcf8f98adb0dbfbee85aec3c9179d29cc072" +dependencies = [ + "base64ct", + "blake2", + "cpufeatures 0.2.17", + "password-hash", +] + +[[package]] +name = "arrayref" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76a2e8124351fda1ef8aaaa3bbd7ebbcb486bbcd4225aca0aa0d84bb2db8fecb" + +[[package]] +name = "arrayvec" +version = "0.7.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56" + +[[package]] +name = "arti-client" +version = "0.45.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "18e7e5f663c4a5db15ba9377b98b3fff2190f64c02e608beb1292dd67b30f199" +dependencies = [ + "async-trait", + "cfg-if 1.0.5", + "derive-deftly", + "derive_builder_fork_arti", + "derive_more", + "educe", + "fs-mistrust", + "futures", + "hostname-validator", + "humantime", + "humantime-serde", + "libc", + "once_cell", + "postage", + "rand 0.10.3", + "safelog", + "serde", + "tempfile", + "thiserror 2.0.21", + "time", + "tor-async-utils", + "tor-basic-utils", + "tor-chanmgr", + "tor-circmgr", + "tor-config", + "tor-config-path", + "tor-dircommon", + "tor-dirmgr", + "tor-error", + "tor-guardmgr", + "tor-hsclient", + "tor-hscrypto", + "tor-keymgr", + "tor-linkspec", + "tor-llcrypto", + "tor-memquota", + "tor-netdir", + "tor-netdoc", + "tor-persist", + "tor-proto", + "tor-protover", + "tor-ptmgr", + "tor-rtcompat", + "tracing", + "void", + "web-time-compat", +] + +[[package]] +name = "as-raw-xcb-connection" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "175571dd1d178ced59193a6fc02dde1b972eb0bc56c892cde9beeceac5bf0f6b" + +[[package]] +name = "as-slice" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "516b6b4f0e40d50dcda9365d53964ec74560ad4284da2e7fc97122cd83174516" +dependencies = [ + "stable_deref_trait", +] + +[[package]] +name = "ascii" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d92bec98840b8f03a5ff5413de5293bfcd8bf96467cf5452609f939ec6f5de16" + +[[package]] +name = "ash" +version = "0.38.0+1.3.281" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bb44936d800fea8f016d7f2311c6a4f97aebd5dc86f09906139ec848cf3a46f" +dependencies = [ + "libloading", +] + +[[package]] +name = "ashpd" +version = "0.13.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fb8421aaa9644a5faf26735f258b669b15f063313ef8f8e2bdb28912a1a6f111" +dependencies = [ + "enumflags2", + "futures-channel", + "futures-util", + "getrandom 0.4.3", + "serde", + "serde_repr", + "wayland-backend", + "wayland-client", + "wayland-protocols", + "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.2.1", +] + +[[package]] +name = "asn1-rs" +version = "0.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7f43a50ac4fdca5df8e885c21b835997f0a1cdee65494a6847694a98652d9d8" +dependencies = [ + "asn1-rs-derive", + "asn1-rs-impl", + "displaydoc", + "nom 7.1.3", + "num-traits", + "rusticata-macros", + "thiserror 2.0.21", +] + +[[package]] +name = "asn1-rs-derive" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3109e49b1e4909e9db6515a30c633684d68cdeaa252f215214cb4fa1a5bfee2c" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", + "synstructure 0.13.2", +] + +[[package]] +name = "asn1-rs-impl" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b18050c2cd6fe86c3a76584ef5e0baf286d038cda203eb6223df2cc413565f7" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "assert_matches" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b34d609dfbaf33d6889b2b7106d3ca345eacad44200913df5ba02bfd31d2ba9" + +[[package]] +name = "async-broadcast" +version = "0.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "435a87a52755b8f27fcf321ac4f04b2802e337c8c4872923137471ec39c37532" +dependencies = [ + "event-listener", + "event-listener-strategy", + "futures-core", + "pin-project-lite", +] + +[[package]] +name = "async-channel" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "924ed96dd52d1b75e9c1a3e6275715fd320f5f9439fb5a4a11fa51f4221158d2" +dependencies = [ + "concurrent-queue", + "event-listener-strategy", + "futures-core", + "pin-project-lite", +] + +[[package]] +name = "async-compression" +version = "0.4.52" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ad47a740fb906fffdd891e8b6d5fde2511600f7bfaebd68939fa08a14999459" +dependencies = [ + "compression-codecs", + "compression-core", + "futures-io", + "pin-project-lite", +] + +[[package]] +name = "async-executor" +version = "1.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f426a31126c735126297bc5ea7a521263c9faff4f63ca415267ee625651c4f37" +dependencies = [ + "async-task", + "concurrent-queue", + "fastrand", + "futures-lite", + "pin-project-lite", + "slab", +] + +[[package]] +name = "async-fs" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8034a681df4aed8b8edbd7fbe472401ecf009251c8b40556b304567052e294c5" +dependencies = [ + "async-lock", + "blocking", + "futures-lite", +] + +[[package]] +name = "async-io" +version = "2.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "456b8a8feb6f42d237746d4b3e9a178494627745c3c56c6ea55d92ba50d026fc" +dependencies = [ + "autocfg", + "cfg-if 1.0.5", + "concurrent-queue", + "futures-io", + "futures-lite", + "parking", + "polling", + "rustix 1.1.6", + "slab", + "windows-sys 0.61.2", +] + +[[package]] +name = "async-lock" +version = "3.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0876700b0d007ad25d5508865a4259c3af9af6d296bf663a0d586d0bc3369f6f" +dependencies = [ + "event-listener", + "event-listener-strategy", + "pin-project-lite", +] + +[[package]] +name = "async-net" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b948000fad4873c1c9339d60f2623323a0cfd3816e5181033c6a5cb68b2accf7" +dependencies = [ + "async-io", + "blocking", + "futures-lite", +] + +[[package]] +name = "async-process" +version = "2.5.0" +source = "git+https://github.com/zed-industries/async-process.git?rev=0b6d6713570af61806e1e5cb40e0f757cb93fd9d#0b6d6713570af61806e1e5cb40e0f757cb93fd9d" +dependencies = [ + "async-channel", + "async-io", + "async-lock", + "async-signal", + "async-task", + "blocking", + "cfg-if 1.0.5", + "event-listener", + "futures-lite", + "rustix 1.1.6", +] + +[[package]] +name = "async-recursion" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4f8abc12baad266b1c8cec146854c195b5864b4221d4b2ca7296a7ae82d9e451" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "async-signal" +version = "0.2.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52b5aaafa020cf5053a01f2a60e8ff5dccf550f0f77ec54a4e47285ac2bab485" +dependencies = [ + "async-io", + "async-lock", + "atomic-waker", + "cfg-if 1.0.5", + "futures-core", + "futures-io", + "rustix 1.1.6", + "signal-hook-registry", + "slab", + "windows-sys 0.61.2", +] + +[[package]] +name = "async-task" +version = "4.7.1" +source = "git+https://github.com/zed-industries/async-task.git?rev=015845a19fc31752c02367567d3b8900a406f9da#015845a19fc31752c02367567d3b8900a406f9da" + +[[package]] +name = "async-trait" +version = "0.1.92" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "async-utility" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "188f83b9a198af8c336e505611edb00d6d2ac5c694241c5a4f9a12316938cfe9" +dependencies = [ + "futures-util", + "gloo-timers", + "tokio", + "wasm-bindgen-futures", +] + +[[package]] +name = "async-wsocket" +version = "0.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c713e1f14c7b82e32ea159af1c6e2f070cfadbdf23fb2512acce9af0a26f1a2" +dependencies = [ + "futures", + "futures-util", + "js-sys", + "tokio", + "tokio-happy-eyeballs", + "tokio-rustls", + "tokio-socks", + "tokio-tungstenite", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + +[[package]] +name = "async_executors" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a982d2f86de6137cc05c9db9a915a19886c97911f9790d04f174cede74be01a5" +dependencies = [ + "blanket", + "futures-core", + "futures-task", + "futures-util", + "pin-project", + "rustc_version", + "tokio", +] + +[[package]] +name = "async_io_stream" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6d7b9decdf35d8908a7e3ef02f64c5e9b1695e230154c0e8de3969142d9b94c" +dependencies = [ + "futures", + "pharos", + "rustc_version", +] + +[[package]] +name = "asynchronous-codec" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a860072022177f903e59730004fb5dc13db9275b79bb2aef7ba8ce831956c233" +dependencies = [ + "bytes", + "futures-sink", + "futures-util", + "memchr", + "pin-project-lite", +] + +[[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" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c59bdb34bc650a32731b31bd8f0829cc15d24a708ee31559e0bb34f2bc320cba" + +[[package]] +name = "atomic" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89cbf775b137e9b968e67227ef7f775587cde3fd31b0d8599dbd0f598a48340" +dependencies = [ + "bytemuck", +] + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "atspi" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c77886257be21c9cd89a4ae7e64860c6f0eefca799bb79127913052bd0eefb3d" +dependencies = [ + "atspi-common", + "atspi-proxies", +] + +[[package]] +name = "atspi-common" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20c5617155740c98003016429ad13fe43ce7a77b007479350a9f8bf95a29f63d" +dependencies = [ + "enumflags2", + "serde", + "static_assertions", + "zbus 5.19.0", + "zbus-lockstep", + "zbus-lockstep-macros", + "zbus_names", + "zvariant", +] + +[[package]] +name = "atspi-proxies" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2230e48787ed3eb4088996eab66a32ca20c0b67bbd4fd6cdfe79f04f1f04c9fc" +dependencies = [ + "atspi-common", + "serde", + "zbus 5.19.0", +] + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "av-scenechange" +version = "0.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0f321d77c20e19b92c39e7471cf986812cbb46659d2af674adc4331ef3f18394" +dependencies = [ + "aligned", + "anyhow", + "arg_enum_proc_macro", + "arrayvec", + "log", + "num-rational", + "num-traits", + "pastey 0.1.1", + "rayon", + "thiserror 2.0.21", + "v_frame", + "y4m", +] + +[[package]] +name = "av1-grain" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8cfddb07216410377231960af4fcab838eaa12e013417781b78bd95ee22077f8" +dependencies = [ + "anyhow", + "arrayvec", + "log", + "nom 8.0.0", + "num-rational", + "v_frame", +] + +[[package]] +name = "avif-serialize" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7178fe5f7d460b13895ebb9dcb28a3a6216d2df2574a0806cb51b555d297f38" +dependencies = [ + "arrayvec", +] + +[[package]] +name = "backon" +version = "1.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cffb0e931875b666fc4fcb20fee52e9bbd1ef836fd9e9e04ec21555f9f85f7ef" +dependencies = [ + "fastrand", + "gloo-timers", + "tokio", +] + +[[package]] +name = "backtrace" +version = "0.3.77" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42f4220217f3288537b83684130f42fad43320b1c3b805f1910d683d52ded24f" +dependencies = [ + "addr2line", + "cfg-if 1.0.5", + "libc", + "miniz_oxide 0.9.1", + "object", + "rustc-demangle", + "windows-link 0.2.1", +] + +[[package]] +name = "base16ct" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c7f02d4ea65f2c1853089ffd8d2787bdbc63de2f0d29dedbcf8ccdfa0ccd4cf" + +[[package]] +name = "base16ct" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd307490d624467aa6f74b0eabb77633d1f758a7b25f12bceb0b22e08d9726f6" + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + +[[package]] +name = "base64ct" +version = "1.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" + +[[package]] +name = "bech32" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "efbd3e1070bbdf4cd88a75264e18e8a26f7cb5c6949eadf0ceb85fb159cf08f8" + +[[package]] +name = "bincode" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "36eaf5d7b090263e8150820482d5d93cd964a81e4019913c972f4edcc6edb740" +dependencies = [ + "serde", + "unty", +] + +[[package]] +name = "bindgen" +version = "0.65.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfdf7b466f9a4903edc73f95d6d2bcd5baf8ae620638762244d3f60143643cc5" +dependencies = [ + "bitflags 1.3.2", + "cexpr", + "clang-sys", + "lazy_static", + "lazycell", + "log", + "peeking_take_while", + "prettyplease", + "proc-macro2", + "quote", + "regex", + "rustc-hash 1.1.0", + "shlex 1.3.0", + "syn 2.0.119", + "which 4.4.2", +] + +[[package]] +name = "bindgen" +version = "0.72.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "993776b509cfb49c750f11b8f07a46fa23e0a1386ffc01fb1e7d343efc387895" +dependencies = [ + "annotate-snippets", + "bitflags 2.13.2", + "cexpr", + "clang-sys", + "itertools 0.13.0", + "log", + "prettyplease", + "proc-macro2", + "quote", + "regex", + "rustc-hash 2.1.3", + "shlex 1.3.0", + "syn 2.0.119", +] + +[[package]] +name = "bindgen" +version = "0.73.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "787ef8ef523575546b106a58213d6e6b06198a05c2f757258c68a74273670cfa" +dependencies = [ + "bitflags 2.13.2", + "cexpr", + "clang-sys", + "proc-macro2", + "quote", + "regex", + "rustc-hash 2.1.3", + "shlex 2.0.1", + "syn 3.0.10", +] + +[[package]] +name = "bip39" +version = "2.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "90dbd31c98227229239363921e60fcf5e558e43ec69094d46fc4996f08d1d5bc" +dependencies = [ + "bitcoin_hashes 0.14.101", + "rand 0.8.8", + "rand_core 0.6.4", + "serde", + "unicode-normalization", +] + +[[package]] +name = "bit-set" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08807e080ed7f9d5433fa9b275196cfc35414f66a0c79d864dc51a0d825231a3" +dependencies = [ + "bit-vec 0.8.0", +] + +[[package]] +name = "bit-set" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "56d87354e4229f54a44f7bf2435906a4656dba36026ab6eaca629a2c436a691c" +dependencies = [ + "bit-vec 0.10.2", +] + +[[package]] +name = "bit-vec" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e764a1d40d510daf35e07be9eb06e75770908c27d411ee6c92109c9840eaaf7" + +[[package]] +name = "bit-vec" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72503af1e72be411d74ca45cd6b309878fcb35354e252fc2a3a8bda3a97082a0" + +[[package]] +name = "bit_field" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb2907cc03d08cdb1c6724ad0670ce67c4a71e1c45a6d7635224011714cfc4b1" + +[[package]] +name = "bitcoin-consensus-encoding" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9daa31138eb443d5751b207f3f64154e2bb09cd59960562ccc7a7112be38147f" +dependencies = [ + "bitcoin-internals 0.7.0", + "hex-conservative 1.3.0", + "serde", +] + +[[package]] +name = "bitcoin-internals" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d573f4cf32996a8dce612e4348cece65a241f1882ed594047c9ba348e8869fa5" + +[[package]] +name = "bitcoin-internals" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e8bea3a9f0cfece4564e37cb49a38cc245ca5184719e50d7d0dda3268722c4e2" + +[[package]] +name = "bitcoin-io" +version = "0.1.101" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb5de036369d1ac59d3c1819ebc4d850f89466f5401c571a285b6ed564a4cb78" +dependencies = [ + "bitcoin-consensus-encoding", +] + +[[package]] +name = "bitcoin_hashes" +version = "0.14.101" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bca4c7abb40c8817d77403c880988cfd484f23ab2365726afb2f798363e2c4a2" +dependencies = [ + "bitcoin-io", + "hex-conservative 0.2.3", +] + +[[package]] +name = "bitcoin_hashes" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5304e53726dbe5f93141535e102ed97b5bf4714fbecefdda8f9fb98d7fdaff0e" +dependencies = [ + "bitcoin-consensus-encoding", + "bitcoin-internals 0.6.0", + "hex-conservative 1.3.0", + "serde", +] + +[[package]] +name = "bitflags" +version = "1.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "bitstream-io" +version = "4.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7eff00be299a18769011411c9def0d827e8f2d7bf0c3dbf53633147a8867fd1f" +dependencies = [ + "no_std_io2", +] + +[[package]] +name = "bitvec" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddcec3d12c579d40898fe0a9a358a803c23e9c52ca3c425707f81c9436211837" +dependencies = [ + "funty", + "radium", + "tap", + "wyz", +] + +[[package]] +name = "blake2" +version = "0.10.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "46502ad458c9a52b69d4d4d32775c788b7a1b85e8bc9d482d92250fc0e3f8efe" +dependencies = [ + "digest 0.10.7", +] + +[[package]] +name = "blake3" +version = "1.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6d9e454fc11f76977dc803893aff6304ed33d6a26efae8696573bea74baa27ae" +dependencies = [ + "arrayvec", + "cc", + "cfg-if 1.0.5", + "constant_time_eq", + "cpufeatures 0.3.1", +] + +[[package]] +name = "blanket" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e0b121a9fe0df916e362fb3271088d071159cdf11db0e4182d02152850756eff" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "block" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d8c1fef690941d3e7788d328517591fecc684c084084702d6ff1641e993699a" + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "block-buffer" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa" +dependencies = [ + "hybrid-array", + "zeroize", +] + +[[package]] +name = "block-padding" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a8894febbff9f758034a5b8e12d87918f56dfc64a8e1fe757d65e29041538d93" +dependencies = [ + "generic-array", +] + +[[package]] +name = "block2" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c132eebf10f5cad5289222520a4a058514204aed6d791f1cf4fe8088b82d15f" +dependencies = [ + "objc2 0.5.3", +] + +[[package]] +name = "block2" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdeb9d870516001442e364c5220d3574d2da8dc765554b4a617230d33fa58ef5" +dependencies = [ + "objc2 0.6.5", +] + +[[package]] +name = "blocking" +version = "1.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a70e4329df6cb94385eed412ec92375c3cdd8a6e502493d1229b6414e4036dfa" +dependencies = [ + "async-channel", + "async-task", + "futures-io", + "futures-lite", + "piper", +] + +[[package]] +name = "brotli-decompressor" +version = "5.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a32acac15fe1967bc3986b2a6347dffc965602354ea6f450ad07e8bfd253583" +dependencies = [ + "alloc-no-stdlib", + "alloc-stdlib", +] + +[[package]] +name = "bs58" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf88ba1141d185c399bee5288d850d63b8369520c1eafc32a0430b5b6c287bf4" +dependencies = [ + "tinyvec", +] + +[[package]] +name = "bstr" +version = "1.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6bb31b46c14244e20ee9984b11bf5c992b91fb6939fea616e3512c8baecdbe5f" +dependencies = [ + "memchr", + "regex-automata", + "serde_core", +] + +[[package]] +name = "built" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c0e531d93d39c34eef561e929e8a7f86d77a5af08aac4f6d6e39976c51858e9" + +[[package]] +name = "bumpalo" +version = "3.20.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" + +[[package]] +name = "by_address" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "64fa3c856b712db6612c019f14756e64e4bcea13337a6b33b696333a9eaa2d06" + +[[package]] +name = "bytemuck" +version = "1.25.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797" +dependencies = [ + "bytemuck_derive", +] + +[[package]] +name = "bytemuck_derive" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a1f896587b6f2c069c73d2f0913e2d590c3990285cd2f0b6aa02b786b4c679c" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "byteorder" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" + +[[package]] +name = "byteorder-lite" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495" + +[[package]] +name = "bytes" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" +dependencies = [ + "serde", +] + +[[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.3" +source = "git+https://github.com/zed-industries/calloop?rev=3759371fee14c40066d64777e2a36b6ffcc22590#3759371fee14c40066d64777e2a36b6ffcc22590" +dependencies = [ + "bitflags 2.13.2", + "polling", + "rustix 1.1.6", + "slab", + "tracing", +] + +[[package]] +name = "calloop-wayland-source" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "138efcf0940a02ebf0cc8d1eff41a1682a46b431630f4c52450d6265876021fa" +dependencies = [ + "calloop", + "rustix 1.1.6", + "wayland-backend", + "wayland-client", +] + +[[package]] +name = "caret" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23a6f83e57018d15e7615a6f8e5e2c6b6b0226e24a1c562cd705f855a2bc751a" + +[[package]] +name = "cbc" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26b52a9543ae338f279b96b0b9fed9c8093744685043739079ce85cd58f289a6" +dependencies = [ + "cipher 0.4.4", +] + +[[package]] +name = "cbindgen" +version = "0.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eadd868a2ce9ca38de7eeafdcec9c7065ef89b42b32f0839278d55f35c54d1ff" +dependencies = [ + "heck 0.4.1", + "indexmap 2.14.2", + "log", + "proc-macro2", + "quote", + "serde", + "serde_json", + "syn 2.0.119", + "tempfile", + "toml 0.8.23", +] + +[[package]] +name = "cc" +version = "1.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ff2a8126fff0f8c839080d619675a585e61720bb12d2baceae45769fd66f155" +dependencies = [ + "find-msvc-tools", + "jobserver", + "libc", + "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" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6fac387a98bb7c37292057cffc56d62ecb629900026402633ae9160df93a8766" +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.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ba9e9ec16c447027685b1f897b720e18e9a8afd00bd7332c483537e38086c9f" +dependencies = [ + "smallvec", + "target-lexicon 0.13.5", +] + +[[package]] +name = "cfg-if" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4785bdd1c96b2a846b2bd7cc02e86b6b3dbf14e7e53446c4f54c92a361040822" + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "cfg_aliases" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" + +[[package]] +name = "chacha20" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3613f74bd2eac03dad61bd53dbe620703d4371614fe0bc3b9f04dd36fe4e818" +dependencies = [ + "cfg-if 1.0.5", + "cipher 0.4.4", + "cpufeatures 0.2.17", +] + +[[package]] +name = "chacha20" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" +dependencies = [ + "cfg-if 1.0.5", + "cpufeatures 0.3.1", + "rand_core 0.10.1", +] + +[[package]] +name = "chacha20poly1305" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10cd79432192d1c0f4e1a0fef9527696cc039165d729fb41b3f4f4f354c2dc35" +dependencies = [ + "aead", + "chacha20 0.9.1", + "cipher 0.4.4", + "poly1305", + "zeroize", +] + +[[package]] +name = "chrono" +version = "0.4.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" +dependencies = [ + "iana-time-zone", + "js-sys", + "num-traits", + "serde", + "wasm-bindgen", + "windows-link 0.2.1", +] + +[[package]] +name = "cipher" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad" +dependencies = [ + "crypto-common 0.1.7", + "inout 0.1.4", + "zeroize", +] + +[[package]] +name = "cipher" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e8cf2a2c93cd704877c0858356ed03480ff301ee950b43f1cbe4573b088bfa6c" +dependencies = [ + "block-buffer 0.12.1", + "crypto-common 0.2.2", + "inout 0.2.6", + "zeroize", +] + +[[package]] +name = "clang-sys" +version = "1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "157a8ba7b480713b56f4c09fd13fc3e0a22a5dfab8097ba61cbc5feef950788a" +dependencies = [ + "glob", + "libc", + "libloading", +] + +[[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" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0f78a02292a74a88ac736019ab962ece0bc380e3f977bf72e376c5d78ff0678" +dependencies = [ + "cc", +] + +[[package]] +name = "cmov" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a" + +[[package]] +name = "coarsetime" +version = "0.1.38" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eae63702c5627c75addbfb1ea9d1b3842205a6ffd43e4cce884a2a9eb1828fd7" +dependencies = [ + "libc", + "wasix", + "wasm-bindgen", +] + +[[package]] +name = "cobs" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fa961b519f0b462e3a3b4a34b64d119eeaca1d59af726fe450bbba07a9fc0a1" +dependencies = [ + "thiserror 2.0.21", +] + +[[package]] +name = "cocoa" +version = "0.20.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c49e86fc36d5704151f5996b7b3795385f50ce09e3be0f47a0cfde869681cf8" +dependencies = [ + "bitflags 1.3.2", + "block", + "core-foundation 0.7.0", + "core-graphics 0.19.2", + "foreign-types 0.3.2", + "libc", + "objc", +] + +[[package]] +name = "cocoa-foundation" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "81411967c50ee9a1fc11365f8c585f863a22a9697c89239c452292c40ba79b0d" +dependencies = [ + "bitflags 2.13.2", + "block", + "core-foundation 0.10.1", + "core-graphics-types", + "objc", +] + +[[package]] +name = "codespan-reporting" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af491d569909a7e4dee0ad7db7f5341fef5c614d5b8ec8cf765732aba3cff681" +dependencies = [ + "serde", + "termcolor", + "unicode-width", +] + +[[package]] +name = "collections" +version = "0.1.0" +source = "git+https://github.com/zed-industries/zed?rev=f8cfc7ed9e57503def9479138894f3139f5400cc#f8cfc7ed9e57503def9479138894f3139f5400cc" +dependencies = [ + "gpui_util", + "indexmap 2.14.2", + "rustc-hash 2.1.3", +] + +[[package]] +name = "color_quant" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d7b894f5411737b7867f4827955924d7c254fc9f4d91a6aad6b097804b1018b" + +[[package]] +name = "colorchoice" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" + +[[package]] +name = "combine" +version = "4.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4356eba6976435498d05a311ee9fc486da3bc81c200d3f0d7dd9703b41913f92" +dependencies = [ + "bytes", + "memchr", +] + +[[package]] +name = "compression-codecs" +version = "0.4.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "84f840cff84d10085260e460023934d0af699e71212b09b2a41452e8bd9cda43" +dependencies = [ + "compression-core", + "flate2", +] + +[[package]] +name = "compression-core" +version = "0.4.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ebdda89edc534bf8d5dd2857562633b6495557e5846552ade994b99ed13c36a" + +[[package]] +name = "concurrent-queue" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ca0197aee26d1ae37445ee532fefce43251d24cc7c166799f4d46817f1d3973" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "console_error_panic_hook" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a06aeb73f470f66dcdbf7223caeebb85984942f22f1adb2a088cf9668146bbbc" +dependencies = [ + "cfg-if 1.0.5", + "wasm-bindgen", +] + +[[package]] +name = "const-oid" +version = "0.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8" + +[[package]] +name = "const-oid" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be95d4a884358a21a199689323c29e9256b4a1b315e22f183d155422041d3a9a" + +[[package]] +name = "const-random" +version = "0.1.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87e00182fe74b066627d63b85fd550ac2998d4b0bd86bfed477a0ae4c7c71359" +dependencies = [ + "const-random-macro", +] + +[[package]] +name = "const-random-macro" +version = "0.1.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9d839f2a20b0aee515dc581a6172f2321f96cab76c1a38a4c584a194955390e" +dependencies = [ + "getrandom 0.2.17", + "once_cell", + "tiny-keccak", +] + +[[package]] +name = "constant_time_eq" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d52eff69cd5e647efe296129160853a42795992097e8af39800e1060caeea9b" + +[[package]] +name = "convert_case" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "633458d4ef8c78b72454de2d54fd6ab2e60f9e02be22f3c6104cdc8a4e0fceb9" +dependencies = [ + "unicode-segmentation", +] + +[[package]] +name = "cookie" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a373e3602691c3cdea496d2f0ee5935151e6168fe87739483c463db1b2f2f87" +dependencies = [ + "time", + "version_check", +] + +[[package]] +name = "cookie-factory" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9885fa71e26b8ab7855e2ec7cae6e9b380edff76cd052e07c683a0319d51b3a2" +dependencies = [ + "futures", +] + +[[package]] +name = "cordyceps" +version = "0.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5b9ab7e0ca1d179628fa0172b2b97203c7fa0cd81be2448bd446fb9559ca9261" +dependencies = [ + "loom", + "tracing", +] + +[[package]] +name = "core-foundation" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57d24c7a13c43e870e37c1556b74555437870a04514f7685f5b354e090567171" +dependencies = [ + "core-foundation-sys 0.7.0", + "libc", +] + +[[package]] +name = "core-foundation" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6" +dependencies = [ + "core-foundation-sys 0.8.7", + "libc", +] + +[[package]] +name = "core-foundation-sys" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b3a71ab494c0b5b860bdc8407ae08978052417070c2ced38573a9157ad75b8ac" + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + +[[package]] +name = "core-graphics" +version = "0.19.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b3889374e6ea6ab25dba90bb5d96202f61108058361f6dc72e8b03e6f8bbe923" +dependencies = [ + "bitflags 1.3.2", + "core-foundation 0.7.0", + "foreign-types 0.3.2", + "libc", +] + +[[package]] +name = "core-graphics" +version = "0.24.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa95a34622365fa5bbf40b20b75dba8dfa8c94c734aea8ac9a5ca38af14316f1" +dependencies = [ + "bitflags 2.13.2", + "core-foundation 0.10.1", + "core-graphics-types", + "foreign-types 0.5.0", + "libc", +] + +[[package]] +name = "core-graphics-types" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d44a101f213f6c4cdc1853d4b78aef6db6bdfa3468798cc1d9912f4735013eb" +dependencies = [ + "bitflags 2.13.2", + "core-foundation 0.10.1", + "libc", +] + +[[package]] +name = "core-media-sys" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "273bf3fc5bf51fd06a7766a84788c1540b6527130a0bce39e00567d6ab9f31f1" +dependencies = [ + "cfg-if 0.1.10", + "core-foundation-sys 0.7.0", + "libc", +] + +[[package]] +name = "core-models" +version = "0.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee3344d349528f449816cfa85e558c439bdca5a6d8a738cfb21e69f0b2b1952f" +dependencies = [ + "hax-lib", + "pastey 0.2.3", + "rand 0.10.3", +] + +[[package]] +name = "core-text" +version = "21.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a593227b66cbd4007b2a050dfdd9e1d1318311409c8d600dc82ba1b15ca9c130" +dependencies = [ + "core-foundation 0.10.1", + "core-graphics 0.24.0", + "foreign-types 0.5.0", + "libc", +] + +[[package]] +name = "core-video-sys" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34ecad23610ad9757664d644e369246edde1803fcb43ed72876565098a5d3828" +dependencies = [ + "cfg-if 0.1.10", + "core-foundation-sys 0.7.0", + "core-graphics 0.19.2", + "libc", + "metal", + "objc", +] + +[[package]] +name = "core_detect" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48" + +[[package]] +name = "core_maths" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77745e017f5edba1a9c1d854f6f3a52dac8a12dd5af5d2f54aecf61e43d80d30" +dependencies = [ + "libm", +] + +[[package]] +name = "coreaudio-rs" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1aae284fbaf7d27aa0e292f7677dfbe26503b0d555026f702940805a630eac17" +dependencies = [ + "bitflags 1.3.2", + "libc", + "objc2-audio-toolbox", + "objc2-core-audio", + "objc2-core-audio-types", + "objc2-core-foundation", +] + +[[package]] +name = "cosmic-text" +version = "0.19.0" +dependencies = [ + "bitflags 2.13.2", + "fontdb", + "harfrust", + "linebender_resource_handle", + "log", + "rangemap", + "rustc-hash 2.1.3", + "self_cell", + "skrifa 0.40.0", + "smol_str", + "swash", + "sys-locale", + "unicode-bidi", + "unicode-linebreak", + "unicode-script", + "unicode-segmentation", +] + +[[package]] +name = "cpal" +version = "0.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cbd307f43cc2a697e2d1f8bc7a1d824b5269e052209e28883e5bc04d095aaa3f" +dependencies = [ + "alsa", + "coreaudio-rs", + "dasp_sample", + "jni 0.21.1", + "js-sys", + "libc", + "mach2 0.4.3", + "ndk", + "ndk-context", + "num-derive", + "num-traits", + "objc2-audio-toolbox", + "objc2-core-audio", + "objc2-core-audio-types", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", + "windows 0.54.0", +] + +[[package]] +name = "cpubits" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15b85f9c39137c3a891689859392b1bd49812121d0d61c9caf00d46ed5ce06ae" + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "cpufeatures" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" +dependencies = [ + "libc", +] + +[[package]] +name = "crabgrind" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc7459e07732f6de74001fcf73a3fdfbb0f368e4fd8e2392f4a2206a065e6e95" +dependencies = [ + "bindgen 0.72.1", + "cc", + "pkg-config", +] + +[[package]] +name = "crc32fast" +version = "1.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b929dd2a135771f40afabd1073f85eed59c800b7c61901e5c254270497dad64" +dependencies = [ + "cfg-if 1.0.5", +] + +[[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" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "622f3fc73690be383c7214310406f28a90e6edeadc3cea882f9d71e495b9711a" +dependencies = [ + "crossbeam-epoch", + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-epoch" +version = "0.9.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc74980687109a3b14c72fd458107bf0baa1da1a1a805e178d15501ba9b86d9d" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-queue" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03e8bd762f7479489c70ed6c768ddca99d7296857de437a68dcb2a94365b3fae" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" + +[[package]] +name = "crunchy" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" + +[[package]] +name = "crypto-bigint" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0dc92fb57ca44df6db8059111ab3af99a63d5d0f8375d9972e319a379c6bab76" +dependencies = [ + "generic-array", + "rand_core 0.6.4", + "subtle", + "zeroize", +] + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "rand_core 0.6.4", + "typenum", +] + +[[package]] +name = "crypto-common" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" +dependencies = [ + "hybrid-array", + "rand_core 0.10.1", +] + +[[package]] +name = "cssparser" +version = "0.37.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c9cdaae01d5ed7882b04d795e7f752f46ff52d2fa3b50a20d28c464510bba98" +dependencies = [ + "cssparser-macros", + "dtoa-short", + "itoa", + "phf 0.13.1", + "smallvec", +] + +[[package]] +name = "cssparser-macros" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d045de693cb712d0b22c6a64be5b953f67b3ce00ab5ad3dd5d8b441886ab8e1a" +dependencies = [ + "quote", + "syn 3.0.10", +] + +[[package]] +name = "ctor" +version = "1.0.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "914a755b7c2d4af2bdcff7ce1739e2db9a1b81a9b07123d8015786ae03c0980d" +dependencies = [ + "link-section", + "linktime-proc-macro", +] + +[[package]] +name = "ctr" +version = "0.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0369ee1ad671834580515889b80f2ea915f23b8be8d0daa4bbaf2ac5c7590835" +dependencies = [ + "cipher 0.4.4", +] + +[[package]] +name = "ctr" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baaca1c4b237092596f64d571e9db6ce4109c4ef9742e27590f1709594461f21" +dependencies = [ + "cipher 0.5.2", +] + +[[package]] +name = "ctutils" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "261af4dc7a06ea8a527a8717d8cbba3417530d6ea14e1edb3de6b67806be474f" +dependencies = [ + "cmov", +] + +[[package]] +name = "curve25519-dalek" +version = "4.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97fb8b7c4503de7d6ae7b42ab72a5a59857b4c937ec27a3d4539dba95b5ab2be" +dependencies = [ + "cfg-if 1.0.5", + "cpufeatures 0.2.17", + "curve25519-dalek-derive", + "digest 0.10.7", + "fiat-crypto 0.2.9", + "rand_core 0.6.4", + "rustc_version", + "subtle", + "zeroize", +] + +[[package]] +name = "curve25519-dalek" +version = "5.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b5eed333089e2e1c1ac8c6c0398e5e2497b4c9926ca6d0365ed1e099afa5bc23" +dependencies = [ + "cfg-if 1.0.5", + "cpufeatures 0.3.1", + "curve25519-dalek-derive", + "digest 0.11.3", + "fiat-crypto 0.3.0", + "rand_core 0.10.1", + "rustc_version", + "serde", + "subtle", + "zeroize", +] + +[[package]] +name = "curve25519-dalek-derive" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f46882e17999c6cc590af592290432be3bce0428cb0d5f8b6715e4dc7b383eb3" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "darling" +version = "0.14.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b750cb3417fd1b327431a470f388520309479ab0bf5e323505daf0290cd3850" +dependencies = [ + "darling_core 0.14.4", + "darling_macro 0.14.4", +] + +[[package]] +name = "darling" +version = "0.21.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9cdf337090841a411e2a7f3deb9187445851f91b309c0c0a29e05f74a00a48c0" +dependencies = [ + "darling_core 0.21.3", + "darling_macro 0.21.3", +] + +[[package]] +name = "darling" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed17f5901b6630b993ca003def43f2f8ef4014fc13b047b57aad617ff32bc2ec" +dependencies = [ + "darling_core 0.24.1", + "darling_macro 0.24.1", +] + +[[package]] +name = "darling_core" +version = "0.14.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "109c1ca6e6b7f82cc233a97004ea8ed7ca123a9af07a8230878fcfda9b158bf0" +dependencies = [ + "fnv", + "ident_case", + "proc-macro2", + "quote", + "strsim 0.10.0", + "syn 1.0.109", +] + +[[package]] +name = "darling_core" +version = "0.21.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1247195ecd7e3c85f83c8d2a366e4210d588e802133e1e355180a9870b517ea4" +dependencies = [ + "fnv", + "ident_case", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "darling_core" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6837e2cf7485aaae18f86181d2f0e9a7ed297a025e220aeabf63fdebd3a2ddff" +dependencies = [ + "ident_case", + "proc-macro2", + "quote", + "strsim 0.11.1", + "syn 3.0.10", +] + +[[package]] +name = "darling_macro" +version = "0.14.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4aab4dbc9f7611d8b55048a3a16d2d010c2c8334e46304b40ac1cc14bf3b48e" +dependencies = [ + "darling_core 0.14.4", + "quote", + "syn 1.0.109", +] + +[[package]] +name = "darling_macro" +version = "0.21.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d38308df82d1080de0afee5d069fa14b0326a88c14f15c5ccda35b4a6c414c81" +dependencies = [ + "darling_core 0.21.3", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "darling_macro" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ac7135c3ef02b2f7833bbeb1be5ba7f966dcde8a87c6b87f65a778d71a02785" +dependencies = [ + "darling_core 0.24.1", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "dasp_sample" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c87e182de0887fd5361989c677c4e8f5000cd9491d6d563161a8f3a5519fc7f" + +[[package]] +name = "data-encoding" +version = "2.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06" + +[[package]] +name = "data-encoding-macro" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6a127ecbb3c4632e1525380e04c0c3fcf8dcb44d32a79ea290d8a36906edcd8" +dependencies = [ + "data-encoding", + "data-encoding-macro-internal", +] + +[[package]] +name = "data-encoding-macro-internal" +version = "0.1.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c54e03a951783e8b327515db3f2a2fd0e3bed362a96b066f341ce66ed49b4ead" +dependencies = [ + "data-encoding", + "syn 3.0.10", +] + +[[package]] +name = "data-url" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be1e0bca6c3637f992fc1cc7cbc52a78c1ef6db076dbf1059c4323d6a2048376" + +[[package]] +name = "defmt" +version = "0.3.101" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4deef977660e373c458df605a913d4ab121db0ccd18d1ad6976dff7d37cddb53" +dependencies = [ + "defmt 1.2.0", +] + +[[package]] +name = "defmt" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4a0795ac740cb54d7b3775c9c17345f6aaecf884c01733b39d6017738e0e3e1" +dependencies = [ + "bitflags 1.3.2", + "defmt-macros", +] + +[[package]] +name = "defmt-macros" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "840bb056bd99c495c9188198a258ab787c79f306d864db3e6e8451442d6d8366" +dependencies = [ + "defmt-parser", + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "defmt-parser" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "71958f69fb2de856c5dd51ac9377e986ca1aa5919f931bf5395a807277f889a0" +dependencies = [ + "thiserror 2.0.21", +] + +[[package]] +name = "der" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb" +dependencies = [ + "const-oid 0.9.6", + "pem-rfc7468 0.7.0", + "zeroize", +] + +[[package]] +name = "der" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a996a108feb8b427a6e12fcf6af4aa83409b79d72c15337d7741368131ee004" +dependencies = [ + "const-oid 0.10.3", + "pem-rfc7468 1.0.0", + "zeroize", +] + +[[package]] +name = "der-parser" +version = "10.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07da5016415d5a3c4dd39b11ed26f915f52fc4e0dc197d87908bc916e51bc1a6" +dependencies = [ + "asn1-rs", + "cookie-factory", + "displaydoc", + "nom 7.1.3", + "num-traits", + "rusticata-macros", +] + +[[package]] +name = "deranged" +version = "0.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e" +dependencies = [ + "serde_core", +] + +[[package]] +name = "derive-deftly" +version = "1.11.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "98e02cd118058400797c74550dca132b57cf2e6af0e9ea0672a83eb186fd655e" +dependencies = [ + "derive-deftly-macros", + "heck 0.5.0", +] + +[[package]] +name = "derive-deftly-macros" +version = "1.11.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba91f619216e76a5eb2515783f7ec2e271938b51aadac592f4930517f4626863" +dependencies = [ + "heck 0.5.0", + "indexmap 2.14.2", + "itertools 0.15.0", + "proc-macro-crate 3.5.0", + "proc-macro2", + "quote", + "sha3 0.12.0", + "strum", + "syn 3.0.10", + "unicode-ident", + "void", +] + +[[package]] +name = "derive_arbitrary" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b034bd7d5f032402a2479444dcc6f74e36a03f31854d41680fb240ef682a1ac" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "derive_builder_core_fork_arti" +version = "0.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24c1b715c79be6328caa9a5e1a387a196ea503740f0722ec3dd8f67a9e72314d" +dependencies = [ + "darling 0.14.4", + "proc-macro2", + "quote", + "syn 1.0.109", +] + +[[package]] +name = "derive_builder_fork_arti" +version = "0.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3eae24d595f4d0ecc90a9a5a6d11c2bd8dafe2375ec4a1ec63250e5ade7d228" +dependencies = [ + "derive_builder_macro_fork_arti", +] + +[[package]] +name = "derive_builder_macro_fork_arti" +version = "0.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69887769a2489cd946bf782eb2b1bb2cb7bc88551440c94a765d4f040c08ebf3" +dependencies = [ + "derive_builder_core_fork_arti", + "syn 1.0.109", +] + +[[package]] +name = "derive_more" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d751e9e49156b02b44f9c1815bcb94b984cdcc4396ecc32521c739452808b134" +dependencies = [ + "derive_more-impl", +] + +[[package]] +name = "derive_more-impl" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "799a97264921d8623a957f6c3b9011f3b5492f557bbb7a5a19b7fa6d06ba8dcb" +dependencies = [ + "convert_case", + "proc-macro2", + "quote", + "rustc_version", + "syn 2.0.119", + "unicode-xid", +] + +[[package]] +name = "derive_refineable" +version = "0.1.0" +source = "git+https://github.com/zed-industries/zed?rev=f8cfc7ed9e57503def9479138894f3139f5400cc#f8cfc7ed9e57503def9479138894f3139f5400cc" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "dhat" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "98cd11d84628e233de0ce467de10b8633f4ddaecafadefc86e13b84b8739b827" +dependencies = [ + "backtrace", + "lazy_static", + "mintex", + "parking_lot", + "rustc-hash 1.1.0", + "serde", + "serde_json", + "thousands", +] + +[[package]] +name = "diatomic-waker" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab03c107fafeb3ee9f5925686dbb7a73bc76e3932abb0d2b365cb64b169cf04c" + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer 0.10.4", + "const-oid 0.9.6", + "crypto-common 0.1.7", + "subtle", +] + +[[package]] +name = "digest" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" +dependencies = [ + "block-buffer 0.12.1", + "const-oid 0.10.3", + "crypto-common 0.2.2", +] + +[[package]] +name = "directories" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "16f5094c54661b38d03bd7e50df373292118db60b585c08a411c6d840017fe7d" +dependencies = [ + "dirs-sys", +] + +[[package]] +name = "dirs" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3e8aa94d75141228480295a7d0e7feb620b1a5ad9f12bc40be62411e38cce4e" +dependencies = [ + "dirs-sys", +] + +[[package]] +name = "dirs" +version = "7.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8d57d423b3c82e89b9a24ca3091fee61f456a26edbd28d26c65906f4bc1dcd8f" +dependencies = [ + "dirs-sys", +] + +[[package]] +name = "dirs-sys" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e01a3366d27ee9890022452ee61b2b63a67e6f13f58900b651ff5665f0bb1fab" +dependencies = [ + "libc", + "option-ext", + "redox_users", + "windows-sys 0.61.2", +] + +[[package]] +name = "dispatch2" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e0e367e4e7da84520dedcac1901e4da967309406d1e51017ae1abfb97adbd38" +dependencies = [ + "bitflags 2.13.2", + "block2 0.6.2", + "libc", + "objc2 0.6.5", +] + +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "dlib" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab8ecd87370524b461f8557c119c405552c396ed91fc0a8eec68679eab26f94a" +dependencies = [ + "libloading", +] + +[[package]] +name = "dlopen2" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e2c5bd4158e66d1e215c49b837e11d62f3267b30c92f1d171c4d3105e3dc4d4" +dependencies = [ + "libc", + "once_cell", + "winapi", +] + +[[package]] +name = "document-features" +version = "0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4b8a88685455ed29a21542a33abd9cb6510b6b129abadabdcef0f4c55bc8f61" +dependencies = [ + "litrs", +] + +[[package]] +name = "dom_query" +version = "0.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fac5fca71e65e94cc718a6e2af65d6e0f9c6027751c2aa562fbb5087fda639bc" +dependencies = [ + "bit-set 0.8.0", + "cssparser", + "foldhash 0.2.0", + "html5ever", + "precomputed-hash", + "selectors", + "tendril", +] + +[[package]] +name = "downcast-rs" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75b325c5dbd37f80359721ad39aca5a29fb04c89279657cffdda8736d0c0b9d2" + +[[package]] +name = "downcast-rs" +version = "2.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "117240f60069e65410b3ae1bb213295bd828f707b5bec6596a1afc8793ce0cbc" + +[[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.6", +] + +[[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.6", +] + +[[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 = "dtoa" +version = "1.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c3cf4824e2d5f025c7b531afcb2325364084a16806f6d47fbc1f5fbd9960590" + +[[package]] +name = "dtoa-short" +version = "0.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd1511a7b6a56299bd043a9c167a6d2bfb37bf84a6dfceaba651168adfb43c87" +dependencies = [ + "dtoa", +] + +[[package]] +name = "dunce" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" + +[[package]] +name = "dwrote" +version = "0.11.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e1b35532432acc8b19ceed096e35dfa088d3ea037fe4f3c085f1f97f33b4d02" +dependencies = [ + "lazy_static", + "libc", + "winapi", + "wio", +] + +[[package]] +name = "dyn-clone" +version = "1.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555" + +[[package]] +name = "ecdsa" +version = "0.16.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee27f32b5c5292967d2d4a9d7f1e0b0aed2c15daded5a60300e4abb9d8020bca" +dependencies = [ + "der 0.7.10", + "digest 0.10.7", + "elliptic-curve", + "rfc6979", + "signature 2.2.0", + "spki 0.7.3", +] + +[[package]] +name = "ed25519" +version = "2.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "115531babc129696a58c64a4fef0a8bf9e9698629fb97e9e40767d235cfbcd53" +dependencies = [ + "pkcs8 0.10.2", + "signature 2.2.0", +] + +[[package]] +name = "ed25519" +version = "3.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29fcf32e6c73d1079f83ab4d782de2d81620346a5f38c6237a86a22f8368980a" +dependencies = [ + "pkcs8 0.11.0", + "serdect", + "signature 3.0.0", +] + +[[package]] +name = "ed25519-dalek" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "70e796c081cee67dc755e1a36a0a172b897fab85fc3f6bc48307991f64e4eca9" +dependencies = [ + "curve25519-dalek 4.1.3", + "ed25519 2.2.3", + "merlin", + "rand_core 0.6.4", + "serde", + "sha2 0.10.9", + "subtle", + "zeroize", +] + +[[package]] +name = "ed25519-dalek" +version = "3.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ebaa1a2bf1290ab3bfe5a7b771d050ebffab2711c19a81691c683a5144a25de" +dependencies = [ + "curve25519-dalek 5.0.0", + "ed25519 3.0.0", + "rand_core 0.10.1", + "serde", + "sha2 0.11.1", + "signature 3.0.0", + "subtle", + "zeroize", +] + +[[package]] +name = "educe" +version = "0.4.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0f0042ff8246a363dbe77d2ceedb073339e85a804b9a47636c6e016a9a32c05f" +dependencies = [ + "enum-ordinalize", + "proc-macro2", + "quote", + "syn 1.0.109", +] + +[[package]] +name = "either" +version = "1.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" + +[[package]] +name = "elliptic-curve" +version = "0.13.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b5e6043086bf7973472e0c7dff2142ea0b680d30e18d9cc40f267efbf222bd47" +dependencies = [ + "base16ct 0.2.0", + "crypto-bigint", + "digest 0.10.7", + "ff", + "generic-array", + "group", + "hkdf", + "pkcs8 0.10.2", + "rand_core 0.6.4", + "sec1", + "subtle", + "zeroize", +] + +[[package]] +name = "embed-resource" +version = "3.0.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6168487b5e7eb2673e6efe1200b1848016e436a6ca0b8031bf04bd9d493a249f" +dependencies = [ + "cc", + "memchr", + "rustc_version", + "toml 1.2.1+spec-1.1.0", + "vswhom", + "winreg", +] + +[[package]] +name = "embedded-io" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef1a6892d9eef45c8fa6b9e0086428a2cca8491aca8f787c534a3d6d0bcb3ced" + +[[package]] +name = "embedded-io" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "edd0f118536f44f5ccd48bcb8b111bdc3de888b58c74639dfb034a357d0f206d" + +[[package]] +name = "encoding_rs" +version = "0.8.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "89253175e704ab869b04f9db224d38630e0211a53841a79181deae0889e169f5" +dependencies = [ + "cfg-if 1.0.5", + "core_detect", + "multiversion_no_op", + "rustversion", + "scopeguard", + "simdutf8", +] + +[[package]] +name = "endi" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "66b7e2430c6dff6a955451e2cfc438f09cea1965a9d6f87f7e3b90decc014099" + +[[package]] +name = "enum-assoc" +version = "1.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "378cfad7ff892555026001b3bb6c2becb98f0aafcd7ddccd5dfa506977f17c8a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "enum-ordinalize" +version = "3.1.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1bf1fa3f06bbff1ea5b1a9c7b14aa992a39657db60a2759457328d7e058f49ee" +dependencies = [ + "num-bigint", + "num-traits", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "enum_dispatch" +version = "0.3.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa18ce2bc66555b3218614519ac839ddb759a7d6720732f979ef8d13be147ecd" +dependencies = [ + "once_cell", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "enumflags2" +version = "0.7.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1027f7680c853e056ebcec683615fb6fbbc07dbaa13b4d5d9442b146ded4ecef" +dependencies = [ + "enumflags2_derive", + "serde", +] + +[[package]] +name = "enumflags2_derive" +version = "0.7.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67c78a4d8fdf9953a5c9d458f9efe940fd97a0cab0941c075a813ac594733827" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "enumn" +version = "0.1.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f9ed6b3789237c8a0c1c505af1c7eb2c560df6186f01b098c3a1064ea532f38" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "enumset" +version = "1.1.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e6bd2d7c76d078cd7a460fa169f778c42c026fe16d90e37d7a45d37181bdce5" +dependencies = [ + "enumset_derive", +] + +[[package]] +name = "enumset_derive" +version = "0.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f60587c2044cabd91c4d4c73e3912e9f1ea7d76905f31c7eec51869305dae044" +dependencies = [ + "darling 0.21.3", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "env_filter" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "900d271a03799a1ee8d1ca9b19893b48ca674a9284fefcfb85f05e74ed314217" +dependencies = [ + "log", + "regex", +] + +[[package]] +name = "env_logger" +version = "0.11.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "de671bd27a75a797dc9ae289ba1e77276e75e2026408aab65185384e2d5cd3f6" +dependencies = [ + "anstream", + "anstyle", + "env_filter", + "jiff", + "log", +] + +[[package]] +name = "equator" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4711b213838dfee0117e3be6ac926007d7f433d7bbe33595975d4190cb07e6fc" +dependencies = [ + "equator-macro", +] + +[[package]] +name = "equator-macro" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44f23cf4b44bfce11a86ace86f8a73ffdec849c9fd00a386a53d278bd9e81fb3" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "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" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc89bf99e5dc15954a60f707c1e09d7540e5cd9af85fa75caa0b510bc08c5342" +dependencies = [ + "euclid", + "svg_fmt", +] + +[[package]] +name = "euclid" +version = "0.22.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1a05365e3b1c6d1650318537c7460c6923f1abdd272ad6842baa2b509957a06" +dependencies = [ + "num-traits", +] + +[[package]] +name = "event-listener" +version = "5.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a23add41df1562121a9393cb065eab5146a1242410f23a644851e90cfd669d2" +dependencies = [ + "parking", + "pin-project-lite", +] + +[[package]] +name = "event-listener-strategy" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8be9f3dfaaffdae2972880079a491a1a8bb7cbed0b8dd7a347f668b4150a3b93" +dependencies = [ + "event-listener", + "pin-project-lite", +] + +[[package]] +name = "exr" +version = "1.74.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb29d0be702adf92c645d9b2f93472906ba83d400e59f98adb3770ce5c18c2f6" +dependencies = [ + "bit_field", + "half", + "lebe", + "miniz_oxide 0.8.9", + "multiversion", + "rayon-core", + "smallvec", + "zune-inflate", +] + +[[package]] +name = "extend" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "311a6d2f1f9d60bff73d2c78a0af97ed27f79672f15c238192a5bbb64db56d00" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "extended" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af9673d8203fcb076b19dfd17e38b3d4ae9f44959416ea532ce72415a6020365" + +[[package]] +name = "fallible-iterator" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2acce4a10f12dc2fb14a218589d4f1f62ef011b2d0cc4b3cb1bba8e94da14649" + +[[package]] +name = "fallible-streaming-iterator" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a" + +[[package]] +name = "fast-thumbhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5243a22cce29dff488db8ef03d8e0e54dd06cd3e6d98475160dff390fa414de2" + +[[package]] +name = "fast_image_resize" +version = "5.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fbc7fe45cf92b43817ff62a3723e862b85bd1d06288f63007f7645d1d2f7a060" +dependencies = [ + "cfg-if 1.0.5", + "document-features", + "num-traits", + "thiserror 2.0.21", +] + +[[package]] +name = "fastbloom" +version = "0.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef975e30683b2d965054bb0a836f8973857c4ebf6acf274fe46617cd285060d8" +dependencies = [ + "foldhash 0.2.0", + "libm", + "portable-atomic", + "siphasher", +] + +[[package]] +name = "faster-hex" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "04839bdf9d8c10f66806fad16b852fc72aab80873aebc3cb69d85b4fa41543ed" +dependencies = [ + "autocfg", + "defmt 0.3.101", + "heapless 0.8.0", + "serde", +] + +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + +[[package]] +name = "fax" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "caf1079563223d5d59d83c85886a56e586cfd5c1a26292e971a0fa266531ac5a" + +[[package]] +name = "fbxcel" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1f9e966e38cb462819635792e0a9ee1d6cc5fff9bcdbf7baefb350221a7ae3df" +dependencies = [ + "indextree", + "libflate", + "log", + "string-interner", +] + +[[package]] +name = "fdeflate" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c" +dependencies = [ + "simd-adler32", +] + +[[package]] +name = "ff" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0b50bfb653653f9ca9095b427bed08ab8d75a137839d9ad64eb11810d5b6393" +dependencies = [ + "rand_core 0.6.4", + "subtle", +] + +[[package]] +name = "ffmpeg-next" +version = "9.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "041fc1d1e9e6f62e03f52d8a2b1cc138d799defbaf7a9d69ddde78c97fb06e97" +dependencies = [ + "bitflags 2.13.2", + "ffmpeg-sys-next", + "libc", +] + +[[package]] +name = "ffmpeg-sys-next" +version = "9.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "226c264da7fce6bd034bfc0b20f87ce4ecc97b3294c407503557910c05e43588" +dependencies = [ + "bindgen 0.73.2", + "cc", + "libc", + "num_cpus", + "pkg-config", + "vcpkg", +] + +[[package]] +name = "fiat-crypto" +version = "0.2.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d" + +[[package]] +name = "fiat-crypto" +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 = "figment" +version = "0.10.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8cb01cd46b0cf372153850f4c6c272d9cbea2da513e07538405148f95bd789f3" +dependencies = [ + "atomic 0.6.1", + "serde", + "toml 0.8.23", + "uncased", + "version_check", +] + +[[package]] +name = "filedescriptor" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e40758ed24c9b2eeb76c35fb0aebc66c626084edd827e07e1552279814c6682d" +dependencies = [ + "libc", + "thiserror 1.0.69", + "winapi", +] + +[[package]] +name = "filetime" +version = "0.2.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c287a33c7f0a620c38e641e7f60827713987b3c0f26e8ddc9462cc69cf75759" +dependencies = [ + "cfg-if 1.0.5", + "libc", +] + +[[package]] +name = "find-msvc-tools" +version = "0.1.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" + +[[package]] +name = "fixedbitset" +version = "0.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5905ec755cc8386d7928353e4d356d2be3e89e81e5ca01fe630a1ca4d08dc175" + +[[package]] +name = "flate2" +version = "1.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "626d4928326b646e70f65ed36fc7cf9f206bdb68a0019ee7c6b4709da4e084c4" +dependencies = [ + "crc32fast", + "miniz_oxide 0.9.1", + "zlib-rs", +] + +[[package]] +name = "float-cmp" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "98de4bbd547a563b716d8dfa9aad1cb19bfab00f4fa09a6a4ed21dbcf44ce9c4" + +[[package]] +name = "float-ord" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ce81f49ae8a0482e4c55ea62ebbd7e5a686af544c00b9d090bba3ff9be97b3d" + +[[package]] +name = "float_next_after" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8bf7cc16383c4b8d58b9905a8509f02926ce3058053c056376248d958c9df1e8" + +[[package]] +name = "fluent-bundle" +version = "0.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "01203cb8918f5711e73891b347816d932046f95f54207710bda99beaeb423bf4" +dependencies = [ + "fluent-langneg", + "fluent-syntax", + "intl-memoizer", + "intl_pluralrules", + "rustc-hash 2.1.3", + "self_cell", + "smallvec", + "unic-langid", +] + +[[package]] +name = "fluent-langneg" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7eebbe59450baee8282d71676f3bfed5689aeab00b27545e83e5f14b1195e8b0" +dependencies = [ + "unic-langid", +] + +[[package]] +name = "fluent-syntax" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "54f0d287c53ffd184d04d8677f590f4ac5379785529e5e08b1c8083acdd5c198" +dependencies = [ + "memchr", + "thiserror 2.0.21", +] + +[[package]] +name = "fluid-let" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "749cff877dc1af878a0b31a41dd221a753634401ea0ef2f87b62d3171522485a" + +[[package]] +name = "flume" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da0e4dd2a88388a1f4ccc7c9ce104604dab68d9f408dc34cd45823d5a9069095" +dependencies = [ + "futures-core", + "futures-sink", + "nanorand", + "spin 0.9.9", +] + +[[package]] +name = "flume" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e139bc46ca777eb5efaf62df0ab8cc5fd400866427e56c68b22e414e53bd3be" +dependencies = [ + "futures-core", + "futures-sink", + "spin 0.9.9", +] + +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + +[[package]] +name = "foldhash" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" + +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + +[[package]] +name = "font-types" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5b38ad915f6dadd993ced50848a8291a543bd41ca62bc10740d5e64e2ab4cfd7" +dependencies = [ + "bytemuck", +] + +[[package]] +name = "font-types" +version = "0.12.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "835ae9d781464a79026cde387f9cbc650c9a4909d7cf7e658b127e3c35d2f35d" +dependencies = [ + "bytemuck", +] + +[[package]] +name = "fontconfig-parser" +version = "0.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbc773e24e02d4ddd8395fd30dc147524273a83e54e0f312d986ea30de5f5646" +dependencies = [ + "roxmltree 0.20.0", +] + +[[package]] +name = "fontdb" +version = "0.23.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "457e789b3d1202543297a350643cf459f836cade38934e7a4cf6a39e7cde2905" +dependencies = [ + "fontconfig-parser", + "log", + "memmap2", + "slotmap", + "tinyvec", + "ttf-parser", +] + +[[package]] +name = "foreign-types" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6f339eb8adc052cd2ca78910fda869aefa38d22d5cb648e6485e4d3fc06f3b1" +dependencies = [ + "foreign-types-shared 0.1.1", +] + +[[package]] +name = "foreign-types" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d737d9aa519fb7b749cbc3b962edcf310a8dd1f4b67c91c4f83975dbdd17d965" +dependencies = [ + "foreign-types-macros", + "foreign-types-shared 0.3.1", +] + +[[package]] +name = "foreign-types-macros" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea5190182e6915eb873ddbc16e23b711b6eb1f9c00a0d0a3a91b5f6228475225" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "foreign-types-shared" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b" + +[[package]] +name = "foreign-types-shared" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa9a19cbb55df58761df49b23516a86d432839add4af60fc256da840f66ed35b" + +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "freetype-sys" +version = "0.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e7edc5b9669349acfda99533e9e0bcf26a51862ab43b08ee7745c55d28eb134" +dependencies = [ + "cc", + "libc", + "pkg-config", +] + +[[package]] +name = "fs-mistrust" +version = "0.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b2c81a5a0e7d67644309a15694eb7f414a4d6556c64c1ece1e5969aa609c8a9" +dependencies = [ + "derive_builder_fork_arti", + "dirs 6.0.0", + "extend", + "libc", + "pwd-grp", + "serde", + "thiserror 2.0.21", + "void", + "walkdir", +] + +[[package]] +name = "fs_extra" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" + +[[package]] +name = "fslock-guard" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d10ce5036d49f8add4a11d08bc1b1afb0e3cefdd88778ab87fb4202d47b765e1" +dependencies = [ + "libc", + "thiserror 2.0.21", + "windows-sys 0.61.2", +] + +[[package]] +name = "funty" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6d5a32815ae3f33302d95fdcb2ce17862f8c65363dcfd29360480ba1001fc9c" + +[[package]] +name = "futures" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a31d2a3fbaaeb2af2368bbdd904aa8e812d3c04a1ee10d3171f52d556e5d0a3" +dependencies = [ + "futures-channel", + "futures-core", + "futures-executor", + "futures-io", + "futures-sink", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-buffered" +version = "0.2.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1bf9d35e4228d3bef48dfd0ceb615166ee3eb869a5bfc1923d7d47340a1e5684" +dependencies = [ + "cordyceps", + "diatomic-waker", + "fixedbitset", + "futures-core", + "pin-project-lite", + "spin 0.10.1", +] + +[[package]] +name = "futures-channel" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" +dependencies = [ + "futures-core", + "futures-sink", +] + +[[package]] +name = "futures-concurrency" +version = "7.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "175cd8cca9e1d45b87f18ffa75088f2099e3c4fe5e2f83e42de112560bea8ea6" +dependencies = [ + "fixedbitset", + "futures-core", + "futures-lite", + "pin-project", + "smallvec", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-executor" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "031b47cf1a3c6cc8bc2fc76cd437f521619387907d469316e7c0bc278f1f5432" +dependencies = [ + "futures-core", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-io" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" + +[[package]] +name = "futures-lite" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f78e10609fe0e0b3f4157ffab1876319b5b0db102a2c60dc4626306dc46b44ad" +dependencies = [ + "fastrand", + "futures-core", + "futures-io", + "parking", + "pin-project-lite", +] + +[[package]] +name = "futures-macro" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "futures-rustls" +version = "0.26.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a8f2f12607f92c69b12ed746fabf9ca4f5c482cba46679c1a75b874ed7c26adb" +dependencies = [ + "futures-io", + "rustls", + "rustls-pki-types", +] + +[[package]] +name = "futures-sink" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-channel", + "futures-core", + "futures-io", + "futures-macro", + "futures-sink", + "futures-task", + "memchr", + "pin-project-lite", + "slab", +] + +[[package]] +name = "g2gen" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c5a7e0eb46f83a20260b850117d204366674e85d3a908d90865c78df9a6b1dfc" +dependencies = [ + "g2poly", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "g2p" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "539e2644c030d3bf4cd208cb842d2ce2f80e82e6e8472390bcef83ceba0d80ad" +dependencies = [ + "g2gen", + "g2poly", +] + +[[package]] +name = "g2poly" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "312d2295c7302019c395cfb90dacd00a82a2eabd700429bba9c7a3f38dbbe11b" + +[[package]] +name = "gbm" +version = "0.18.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce852e998d3ca5e4a97014fb31c940dc5ef344ec7d364984525fd11e8a547e6a" +dependencies = [ + "bitflags 2.13.2", + "drm 0.14.1", + "drm-fourcc", + "gbm-sys", + "libc", + "wayland-backend", + "wayland-server", +] + +[[package]] +name = "gbm-sys" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c13a5f2acc785d8fb6bf6b7ab6bfb0ef5dad4f4d97e8e70bb8e470722312f76f" +dependencies = [ + "libc", +] + +[[package]] +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 = "generator" +version = "0.8.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea6c6a73cd1aa4f4f00c02b109fa55d3a9d6ecc2fc4f53177b74ed6ee23b0c53" +dependencies = [ + "cc", + "libc", + "log", + "rustversion", + "windows-core 0.100.0", + "windows-sys 0.61.2", +] + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", + "zeroize", +] + +[[package]] +name = "gethostname" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1bd49230192a3797a9a4d6abe9b3eed6f7fa4c8a8a4947977c6f80025f92cbd8" +dependencies = [ + "rustix 1.1.6", + "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 = [ + "cfg-if 1.0.5", + "js-sys", + "libc", + "wasi", + "wasm-bindgen", +] + +[[package]] +name = "getrandom" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" +dependencies = [ + "cfg-if 1.0.5", + "js-sys", + "libc", + "r-efi 5.3.0", + "wasip2", + "wasm-bindgen", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if 1.0.5", + "js-sys", + "libc", + "r-efi 6.0.0", + "rand_core 0.10.1", + "wasm-bindgen", +] + +[[package]] +name = "getset" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6cf442baaabe4213ce7d1239afc26c039180b6456da2cededa316ae2c8a77a77" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "ghash" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0d8a4362ccb29cb0b265253fb0a2728f592895ee6854fd9bc13f2ffda266ff1" +dependencies = [ + "opaque-debug", + "polyval 0.6.2", +] + +[[package]] +name = "ghash" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2eecf2d5dc9b66b732b97707a0210906b1d30523eb773193ab777c0c84b3e8d5" +dependencies = [ + "polyval 0.7.3", +] + +[[package]] +name = "gif" +version = "0.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee8cfcc411d9adbbaba82fb72661cc1bcca13e8bba98b364e62b2dba8f960159" +dependencies = [ + "color_quant", + "weezl", +] + +[[package]] +name = "gimli" +version = "0.34.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1033caf0b349c518623b5396bfb2cf0bddf44f0306d543a250e5743297aafd10" + +[[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" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a95dfc23a2b4a9a2f5ab41d194f8bfda3cabec42af4e39f08c339eb2a0c124d" +dependencies = [ + "khronos_api", + "log", + "xml-rs", +] + +[[package]] +name = "glam" +version = "0.30.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19fc433e8437a212d1b6f1e68c7824af3aed907da60afa994e7f542d18d12aa9" +dependencies = [ + "bytemuck", +] + +[[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" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b" + +[[package]] +name = "glob-match" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9985c9503b412198aa4197559e9a318524ebc4519c229bfa05a535828c950b9d" + +[[package]] +name = "gloo-timers" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbb143cf96099802033e0d4f4963b19fd2e0b728bcf076cd9cf7f6634f092994" +dependencies = [ + "futures-channel", + "futures-core", + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "glow" +version = "0.18.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "263218b0ba2b0715c3370fb04674f5f8aa331594b521c94ff0a8e4a8472d1386" +dependencies = [ + "js-sys", + "slotmap", + "wasm-bindgen", + "web-sys", +] + +[[package]] +name = "gltf" +version = "1.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3ce1918195723ce6ac74e80542c5a96a40c2b26162c1957a5cd70799b8cacf7" +dependencies = [ + "byteorder", + "gltf-json", + "lazy_static", + "serde_json", +] + +[[package]] +name = "gltf-derive" +version = "1.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "14070e711538afba5d6c807edb74bcb84e5dbb9211a3bf5dea0dfab5b24f4c51" +dependencies = [ + "inflections", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "gltf-json" +version = "1.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6176f9d60a7eab0a877e8e96548605dedbde9190a7ae1e80bbcc1c9af03ab14" +dependencies = [ + "gltf-derive", + "serde", + "serde_derive", + "serde_json", +] + +[[package]] +name = "glutin_wgl_sys" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c4ee00b289aba7a9e5306d57c2d05499b2e5dc427f84ac708bd2c090212cf3e" +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" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "51255ea7cfaadb6c5f1528d43e92a82acb2b96c43365989a28b2d44ee38f8795" +dependencies = [ + "ash", + "hashbrown 0.16.1", + "log", + "presser", + "thiserror 2.0.21", + "windows 0.62.2", +] + +[[package]] +name = "gpui" +version = "0.2.2" +dependencies = [ + "accesskit", + "anyhow", + "async-channel", + "async-task", + "backtrace", + "bitflags 2.13.2", + "chrono", + "collections", + "derive_more", + "embed-resource", + "etagere", + "futures", + "getrandom 0.3.4", + "gpui_macros", + "gpui_shared_string", + "gpui_util", + "heapless 0.9.3", + "http_client", + "icu_segmenter", + "image", + "inventory", + "itertools 0.14.0", + "libc", + "libwebp-sys", + "log", + "lyon", + "num_cpus", + "objc2-core-foundation", + "objc2-core-video", + "parking", + "parking_lot", + "pin-project", + "pollster 0.4.0", + "profiling", + "rand 0.9.5", + "raw-window-handle", + "refineable", + "regex", + "resvg 0.46.0", + "scheduler", + "schemars 1.2.3", + "seahash", + "serde", + "serde_json", + "slotmap", + "smallvec", + "spin 0.10.1", + "strum", + "sum_tree", + "taffy", + "thiserror 2.0.21", + "ttf-parser", + "unicode-segmentation", + "url", + "usvg 0.46.0", + "uuid", + "vector-jpeg", + "waker-fn", + "windows 0.62.2", + "zed-scap", +] + +[[package]] +name = "gpui_android" +version = "0.1.0" +dependencies = [ + "accesskit", + "accesskit_android", + "anyhow", + "calloop", + "futures", + "gpui", + "gpui_wgpu", + "jni 0.21.1", + "libc", + "log", + "ndk", + "ndk-context", + "ndk-sys", + "parking_lot", + "raw-window-handle", + "uuid", +] + +[[package]] +name = "gpui_apple" +version = "0.1.0" +dependencies = [ + "anyhow", + "async-task", + "block2 0.6.2", + "cbindgen", + "collections", + "core-foundation 0.10.1", + "core-foundation-sys 0.8.7", + "core-graphics 0.24.0", + "core-text", + "dispatch2", + "etagere", + "futures", + "gpui", + "gpui_util", + "image", + "libc", + "log", + "mach2 0.6.0", + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-core-text", + "objc2-core-video", + "objc2-foundation 0.3.2", + "objc2-metal 0.3.2", + "objc2-quartz-core 0.3.2", + "objc2-security", + "parking_lot", + "pathfinder_geometry", + "smallvec", + "thiserror 2.0.21", + "zed-font-kit", +] + +[[package]] +name = "gpui_ios" +version = "0.1.0" +source = "git+https://github.com/zed-industries/zed?rev=f8cfc7ed9e57503def9479138894f3139f5400cc#f8cfc7ed9e57503def9479138894f3139f5400cc" +dependencies = [ + "anyhow", + "block2 0.6.2", + "futures", + "gpui", + "gpui_apple", + "log", + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-foundation 0.3.2", + "objc2-quartz-core 0.3.2", + "objc2-ui-kit", + "parking_lot", + "raw-window-handle", + "uuid", +] + +[[package]] +name = "gpui_linux" +version = "0.1.0" +dependencies = [ + "accesskit", + "accesskit_unix", + "anyhow", + "as-raw-xcb-connection", + "ashpd 0.13.13", + "bytemuck", + "calloop", + "calloop-wayland-source", + "collections", + "filedescriptor", + "futures", + "gpui", + "gpui_util", + "gpui_wgpu", + "http_client", + "libc", + "log", + "notify-rust", + "oo7", + "open", + "parking_lot", + "raw-window-handle", + "smallvec", + "smol", + "strum", + "url", + "uuid", + "wayland-backend", + "wayland-client", + "wayland-cursor", + "wayland-protocols", + "wayland-protocols-plasma", + "wayland-protocols-wlr", + "x11rb", + "xkbcommon", + "zed-scap", + "zed-xim", +] + +[[package]] +name = "gpui_macos" +version = "0.1.0" +dependencies = [ + "accesskit", + "accesskit_macos", + "anyhow", + "block2 0.6.2", + "collections", + "core-foundation 0.10.1", + "core-foundation-sys 0.8.7", + "core-graphics 0.24.0", + "ctor", + "dispatch2", + "foreign-types 0.5.0", + "futures", + "gpui", + "gpui_apple", + "gpui_util", + "image", + "itertools 0.14.0", + "log", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "objc2-core-graphics", + "objc2-core-video", + "objc2-foundation 0.3.2", + "objc2-quartz-core 0.3.2", + "objc2-uniform-type-identifiers", + "objc2-user-notifications", + "parking_lot", + "raw-window-handle", + "scheduler", + "semver", + "smallvec", + "strum", + "uuid", +] + +[[package]] +name = "gpui_macros" +version = "0.1.0" +source = "git+https://github.com/zed-industries/zed?rev=f8cfc7ed9e57503def9479138894f3139f5400cc#f8cfc7ed9e57503def9479138894f3139f5400cc" +dependencies = [ + "heck 0.5.0", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "gpui_platform" +version = "0.1.0" +dependencies = [ + "anyhow", + "console_error_panic_hook", + "gpui", + "gpui_android", + "gpui_ios", + "gpui_linux", + "gpui_macos", + "gpui_web", + "gpui_windows", +] + +[[package]] +name = "gpui_shared_string" +version = "0.1.0" +source = "git+https://github.com/zed-industries/zed?rev=f8cfc7ed9e57503def9479138894f3139f5400cc#f8cfc7ed9e57503def9479138894f3139f5400cc" +dependencies = [ + "schemars 1.2.3", + "serde", + "smol_str", +] + +[[package]] +name = "gpui_util" +version = "0.1.0" +source = "git+https://github.com/zed-industries/zed?rev=f8cfc7ed9e57503def9479138894f3139f5400cc#f8cfc7ed9e57503def9479138894f3139f5400cc" +dependencies = [ + "anyhow", + "log", + "which 8.0.6", +] + +[[package]] +name = "gpui_web" +version = "0.1.0" +source = "git+https://github.com/zed-industries/zed?rev=f8cfc7ed9e57503def9479138894f3139f5400cc#f8cfc7ed9e57503def9479138894f3139f5400cc" +dependencies = [ + "anyhow", + "async-channel", + "console_error_panic_hook", + "futures", + "gpui", + "gpui_wgpu", + "http_client", + "js-sys", + "log", + "parking_lot", + "raw-window-handle", + "scheduler", + "smallvec", + "unicode-properties", + "unicode-script", + "unicode-segmentation", + "uuid", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", + "web-time", +] + +[[package]] +name = "gpui_wgpu" +version = "0.1.0" +dependencies = [ + "anyhow", + "bytemuck", + "collections", + "cosmic-text", + "etagere", + "gpui", + "gpui_util", + "itertools 0.14.0", + "log", + "parking_lot", + "profiling", + "raw-window-handle", + "smallvec", + "swash", + "unicode-bidi", + "unicode-segmentation", + "wgpu", + "zed-font-kit", +] + +[[package]] +name = "gpui_windows" +version = "0.1.0" +dependencies = [ + "accesskit", + "accesskit_windows", + "anyhow", + "collections", + "dunce", + "etagere", + "futures", + "gpui", + "gpui_util", + "image", + "itertools 0.14.0", + "log", + "parking_lot", + "rand 0.9.5", + "raw-window-handle", + "scheduler", + "smallvec", + "uuid", + "windows 0.62.2", + "windows-core 0.62.2", + "windows-numerics 0.3.1", + "windows-registry", +] + +[[package]] +name = "group" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0f9ef7462f7c099f518d754361858f86d8a07af53ba9af0fe635bbccb151a63" +dependencies = [ + "ff", + "rand_core 0.6.4", + "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" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d29020232d6aa3fb1daca64c1127cf662cf97f254ae16c18c05b8ab635fc118" +dependencies = [ + "atomic-waker", + "bytes", + "fnv", + "futures-core", + "futures-sink", + "http", + "indexmap 2.14.2", + "slab", + "tokio", + "tokio-util", + "tracing", +] + +[[package]] +name = "half" +version = "2.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b" +dependencies = [ + "cfg-if 1.0.5", + "crunchy", + "num-traits", + "zerocopy", +] + +[[package]] +name = "harfrust" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9da2e5ae821f6e96664977bf974d6d6a2d6682f9ccee23e62ec1d134246845f9" +dependencies = [ + "bitflags 2.13.2", + "bytemuck", + "core_maths", + "read-fonts 0.37.0", + "smallvec", +] + +[[package]] +name = "hash32" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d60b12902ba28e2730cd37e95b8c9223af2808df9e902d4df49588d1470606" +dependencies = [ + "byteorder", +] + +[[package]] +name = "hashbrown" +version = "0.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab5ef0d4909ef3724cc8cce6ccc8572c5c817592e9285f5464f8e86f8bd3726e" +dependencies = [ + "ahash 0.7.8", +] + +[[package]] +name = "hashbrown" +version = "0.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888" + +[[package]] +name = "hashbrown" +version = "0.14.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" + +[[package]] +name = "hashbrown" +version = "0.15.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" +dependencies = [ + "foldhash 0.1.5", +] + +[[package]] +name = "hashbrown" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100" +dependencies = [ + "allocator-api2", + "equivalent", + "foldhash 0.2.0", +] + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" +dependencies = [ + "foldhash 0.2.0", +] + +[[package]] +name = "hashlink" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "824e001ac4f3012dd16a264bec811403a67ca9deb6c102fc5049b32c4574b35f" +dependencies = [ + "hashbrown 0.16.1", +] + +[[package]] +name = "hax-lib" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "01a33cb227f97ee5c419064c31d7c55a7d895f28d8019ccdadc311cc036500c4" +dependencies = [ + "hax-lib-macros", + "num-bigint", + "num-traits", +] + +[[package]] +name = "hax-lib-macros" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "28da835a5f153e9f3d0cc1f42ee605a1cfa9093c93348193793d60a1b0908b51" +dependencies = [ + "hax-lib-macros-types", + "proc-macro-error2", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "hax-lib-macros-types" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eed327e9a28d6ee018a4a9ba842d4ee27e378c8a591d2beb6f42f32b24a02fcb" +dependencies = [ + "proc-macro2", + "quote", + "serde", + "serde_json", + "uuid", +] + +[[package]] +name = "heapless" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bfb9eb618601c89945a70e254898da93b13be0388091d42117462b265bb3fad" +dependencies = [ + "hash32", + "stable_deref_trait", +] + +[[package]] +name = "heapless" +version = "0.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25ba4bd83f9415b58b4ed8dc5714c76e626a105be4646c02630ad730ad3b5aa4" +dependencies = [ + "hash32", + "stable_deref_trait", +] + +[[package]] +name = "heck" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8" + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "hermit-abi" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e17592d60ebacc7d5e169f4663c5f84f9161cc90328abcfe8456f41e4dfcb284" + +[[package]] +name = "hex" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" + +[[package]] +name = "hex-conservative" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db3fef046dca3ca91ee1408a8c1b80ab777e80a4d308d1bf4e7adb3fcb047e08" +dependencies = [ + "arrayvec", +] + +[[package]] +name = "hex-conservative" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "271e0d19bcb473b6675739a2b536076b24a082316cb5199ad918edce10c599e8" +dependencies = [ + "arrayvec", +] + +[[package]] +name = "hkdf" +version = "0.12.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b5f8eb2ad728638ea2c7d47a21db23b7b58a72ed6a38256b8a1849f15fbbdf7" +dependencies = [ + "hmac", +] + +[[package]] +name = "hmac" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" +dependencies = [ + "digest 0.10.7", +] + +[[package]] +name = "home" +version = "0.5.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc627f471c528ff0c4a49e1d5e60450c8f6461dd6d10ba9dcd3a61d3dff7728d" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "hostname-validator" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f558a64ac9af88b5ba400d99b579451af0d39c6d360980045b91aac966d705e2" + +[[package]] +name = "html5ever" +version = "0.39.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "46a1761807faccc9a19e86944bbf40610014066306f96edcdedc2fb714bcb7b8" +dependencies = [ + "log", + "markup5ever", +] + +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "http-body" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c" +dependencies = [ + "bytes", + "http", +] + +[[package]] +name = "http-body-util" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "pin-project-lite", +] + +[[package]] +name = "http_client" +version = "0.1.0" +source = "git+https://github.com/zed-industries/zed?rev=f8cfc7ed9e57503def9479138894f3139f5400cc#f8cfc7ed9e57503def9479138894f3139f5400cc" +dependencies = [ + "anyhow", + "bytes", + "futures", + "http", + "http-body", + "parking_lot", + "serde", + "serde_json", + "serde_urlencoded", + "url", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "httpdate" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" + +[[package]] +name = "humantime" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15cdd26707701c53297e2fa6afb323d55fbc1d0810c3aec078ae3ef0424c3c15" + +[[package]] +name = "humantime-serde" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57a3db5ea5923d99402c94e9feb261dc5ee9b4efa158b0315f788cf549cc200c" +dependencies = [ + "humantime", + "serde", +] + +[[package]] +name = "hybrid-array" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17" +dependencies = [ + "typenum", + "zeroize", +] + +[[package]] +name = "hyper" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c3e324da4c95177d6291d4c8730197c0d1822f8a9766814a4a44fa5ab797c9c" +dependencies = [ + "atomic-waker", + "bytes", + "futures-channel", + "futures-core", + "h2", + "http", + "http-body", + "httparse", + "httpdate", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", + "want", +] + +[[package]] +name = "hyper-rustls" +version = "0.27.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dfa8e654703247911e29c23fbeaa261834bd9bb74efba2f9acddc37bfb127f53" +dependencies = [ + "http", + "hyper", + "hyper-util", + "rustls", + "tokio", + "tokio-rustls", + "tower-service", +] + +[[package]] +name = "hyper-util" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff" +dependencies = [ + "base64 0.23.1", + "bytes", + "futures-channel", + "futures-util", + "http", + "http-body", + "httparse", + "hyper", + "ipnet", + "libc", + "percent-encoding", + "pin-project-lite", + "socket2", + "tokio", + "tower-service", + "tracing", +] + +[[package]] +name = "iana-time-zone" +version = "0.1.65" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470" +dependencies = [ + "android_system_properties", + "core-foundation-sys 0.8.7", + "iana-time-zone-haiku", + "js-sys", + "log", + "wasm-bindgen", + "windows-core 0.62.2", +] + +[[package]] +name = "iana-time-zone-haiku" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" +dependencies = [ + "cc", +] + +[[package]] +name = "icu_collections" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe090a42a0d3140fed8c63263ed1fecc02422cb2f4bfe55cd8de2de1b8e105dd" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25d29b57c17c6528d0dc4c2141cfa2d08200465acb537a3909c8b9b8a4a984c0" +dependencies = [ + "displaydoc", + "litemap", + "serde", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_locale_fallback" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "406e9ae5b95d8aa37db6293405931b766a6172d1848daee22d70eb44aa78a43c" +dependencies = [ + "icu_locale_core", + "icu_locale_fallback_data", + "icu_provider", + "potential_utf", + "tinystr", + "zerovec", +] + +[[package]] +name = "icu_locale_fallback_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3632ebbd0c5c3637ba1a40bdf8288f2cb9d2268e73441a69d5fc73d7cfbaa87c" + +[[package]] +name = "icu_normalizer" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "404a3b8c486f205c87fe7f23ab6894d84a4ad76d6e4671ae1981ba7def87c599" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20f0088bfb7441f7a37fa0c9e20cb1e9cba1cac6b9ce8cd2a6dc44294f8e8cbc" + +[[package]] +name = "icu_properties" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ea83d991c56158f7cf898bf86436c1dfe7c07ee82fe88951f2695c9f37a379f" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b98f29af82d02b163fe50161388350e743bb3107cc8e8c2f7314cb505faddfcf" + +[[package]] +name = "icu_provider" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "413099315636c588ee8f011190b329b971a09a8fae9d157e01dcae8379468514" +dependencies = [ + "displaydoc", + "icu_locale_core", + "serde", + "stable_deref_trait", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_segmenter" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61b195dc605f81aa181bec9b3bd14e26cc71b903e4644f6af578ca9772c7a710" +dependencies = [ + "icu_collections", + "icu_locale_fallback", + "icu_provider", + "icu_segmenter_data", + "potential_utf", + "smallvec", + "utf8_iter", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_segmenter_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "913a7d294ad056474749152107309fdee3ec17d2482d1ab70fdc61a81c64b9a3" + +[[package]] +name = "ident_case" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" + +[[package]] +name = "identity-hash" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dfdd7caa900436d8f13b2346fe10257e0c05c1f1f9e351f4f5d57c03bd5f45da" + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "image" +version = "0.25.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85ab80394333c02fe689eaf900ab500fbd0c2213da414687ebf995a65d5a6104" +dependencies = [ + "bytemuck", + "byteorder-lite", + "color_quant", + "exr", + "gif", + "image-webp", + "moxcms", + "num-traits", + "png 0.18.1", + "qoi", + "ravif", + "rayon", + "tiff", + "zune-core", + "zune-jpeg", +] + +[[package]] +name = "image-webp" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "525e9ff3e1a4be2fbea1fdf0e98686a6d98b4d8f937e1bf7402245af1909e8c3" +dependencies = [ + "byteorder-lite", + "quick-error", +] + +[[package]] +name = "imagesize" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e54e57b4c48b40f7aec75635392b12b3421fa26fe8b4332e63138ed278459c" + +[[package]] +name = "imagesize" +version = "0.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65b27460c2c92b037f3f94c538ed9a3342f3fdf923606781629ccb35f82d042a" + +[[package]] +name = "imara-diff" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f01d462f766df78ab820dd06f5eb700233c51f0f4c2e846520eaf4ba6aa5c5c" +dependencies = [ + "hashbrown 0.15.5", + "memchr", +] + +[[package]] +name = "imgref" +version = "1.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e44b0a4eaa4c82f441d50a963f2d5f05a787240aeee097597033e72accfd22f" + +[[package]] +name = "indexmap" +version = "1.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bd070e393353796e801d209ad339e89596eb4c8d430d18ede6a1cced8fafbd99" +dependencies = [ + "autocfg", + "hashbrown 0.12.3", + "serde", +] + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown 0.17.1", + "serde", + "serde_core", +] + +[[package]] +name = "indextree" +version = "4.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3662f57019121dcb767b3d68df6868daf61c8e2ec8205709aea7e75b301a4ecc" +dependencies = [ + "indextree-macros", + "serde", +] + +[[package]] +name = "indextree-macros" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "275f822f43b20b95514c355642157dd8e8214ac62592969e8339d3ebcdacb808" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "inflections" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a257582fdcde896fd96463bf2d40eefea0580021c0712a0e2b028b60b47a837a" + +[[package]] +name = "inotify" +version = "0.11.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cc00ea907cab49550b7da656f80ebb97be1b997d931fbcd28d39734e17ce592" +dependencies = [ + "bitflags 2.13.2", + "inotify-sys", + "libc", +] + +[[package]] +name = "inotify-sys" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c033f80b2c113cdf91ab7a33faa9cbc014726dcad99880c8609af2a370edf37d" +dependencies = [ + "libc", +] + +[[package]] +name = "inout" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01" +dependencies = [ + "block-padding", + "generic-array", +] + +[[package]] +name = "inout" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a580c13f0ffc335ef42dd3f6b1a41b726051c5e1656d9a3aa6fddb3c5dfbbf9" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "interpolate_name" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c34819042dc3d3971c46c2190835914dfbe0c3c13f61449b2997f4e9722dfa60" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "intl-memoizer" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "310da2e345f5eb861e7a07ee182262e94975051db9e4223e909ba90f392f163f" +dependencies = [ + "type-map", + "unic-langid", +] + +[[package]] +name = "intl_pluralrules" +version = "7.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "078ea7b7c29a2b4df841a7f6ac8775ff6074020c6776d48491ce2268e068f972" +dependencies = [ + "unic-langid", +] + +[[package]] +name = "inventory" +version = "0.3.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6928282826c822ad91bf1c9a1cb90a30ba1c26770749929b4656cd6be829cd7c" +dependencies = [ + "rustversion", +] + +[[package]] +name = "ipconfig" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4d40460c0ce33d6ce4b0630ad68ff63d6661961c48b6dba35e5a4d81cfb48222" +dependencies = [ + "socket2", + "widestring", + "windows-registry", + "windows-result 0.4.1", + "windows-sys 0.61.2", +] + +[[package]] +name = "ipnet" +version = "2.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0" + +[[package]] +name = "iprange" +version = "0.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "37209be0ad225457e63814401415e748e2453a5297f9b637338f5fb8afa4ec00" +dependencies = [ + "ipnet", +] + +[[package]] +name = "iroh" +version = "1.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3689cab508af9bcef7816c1201b403595ec6aa20e7d15e1f9683bb4be4a5b17" +dependencies = [ + "backon", + "blake3", + "bytes", + "cfg_aliases", + "ctutils", + "data-encoding", + "derive_more", + "ed25519-dalek 3.0.0", + "futures-util", + "getrandom 0.4.3", + "http", + "ipnet", + "iroh-base", + "iroh-dns", + "iroh-metrics", + "iroh-relay", + "n0-error", + "n0-future", + "n0-watcher", + "netwatch", + "noq", + "noq-proto", + "noq-udp", + "papaya", + "pin-project", + "portable-atomic", + "rand 0.10.3", + "reqwest", + "rustc-hash 2.1.3", + "rustls", + "rustls-pki-types", + "serde", + "smallvec", + "strum", + "time", + "tokio", + "tokio-stream", + "tokio-util", + "tracing", + "url", + "wasm-bindgen-futures", +] + +[[package]] +name = "iroh-base" +version = "1.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "43b72366b16001af3a51574233df88ca6d62da0215807549a769e7de887da803" +dependencies = [ + "curve25519-dalek 5.0.0", + "data-encoding", + "data-encoding-macro", + "derive_more", + "ed25519-dalek 3.0.0", + "getrandom 0.4.3", + "n0-error", + "rand 0.10.3", + "serde", + "url", + "zeroize", +] + +[[package]] +name = "iroh-dns" +version = "1.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7481d0792dde1035a2b06ec06ed3cf6d01fcb1a494e6931b489e32073382048d" +dependencies = [ + "arc-swap", + "cfg_aliases", + "derive_more", + "iroh-base", + "n0-dns-resolver", + "n0-error", + "n0-future", + "portable-atomic", + "rand 0.10.3", + "rustls", + "simple-dns", + "strum", + "tokio", + "tracing", + "url", +] + +[[package]] +name = "iroh-gossip" +version = "0.101.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e1dc4b05f73e7a1b9e83b531eb63c3fd671b0af3aeb13b59c546dd7ca747515" +dependencies = [ + "blake3", + "bytes", + "data-encoding", + "derive_more", + "futures-concurrency", + "hex", + "indexmap 2.14.2", + "iroh", + "iroh-base", + "iroh-metrics", + "irpc", + "n0-error", + "n0-future", + "postcard", + "rand 0.10.3", + "serde", + "tokio", + "tokio-util", + "tracing", +] + +[[package]] +name = "iroh-metrics" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ede55536349842337f7cdc63012ec33dc637945f3259c98a0763aac364cdf09" +dependencies = [ + "iroh-metrics-derive", + "itoa", + "n0-error", + "portable-atomic", + "ryu", + "serde", + "tracing", +] + +[[package]] +name = "iroh-metrics-derive" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ae5f0c4405d1fbc9fb16ff422ca40620e93dc36c30ecaba0c2aee3992b7bd48" +dependencies = [ + "heck 0.5.0", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "iroh-relay" +version = "1.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e5589e7c1475700686603a970275687f760df853bc6525c7eb1347aa31d7230" +dependencies = [ + "blake3", + "bytes", + "cfg_aliases", + "data-encoding", + "derive_more", + "getrandom 0.4.3", + "http", + "http-body-util", + "hyper", + "hyper-util", + "iroh-base", + "iroh-dns", + "iroh-metrics", + "lru", + "n0-error", + "n0-future", + "noq", + "noq-proto", + "num_enum", + "percent-encoding", + "pin-project", + "postcard", + "rand 0.10.3", + "reqwest", + "rustls", + "rustls-pki-types", + "serde", + "serde_bytes", + "strum", + "tokio", + "tokio-rustls", + "tokio-util", + "tokio-websockets", + "tracing", + "url", + "webpki-roots 1.0.12", + "ws_stream_wasm", +] + +[[package]] +name = "irpc" +version = "0.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3623d6ff582b415904b29bbe6ebcb4a4f9a262ccdee05a45fdd003ef0950c386" +dependencies = [ + "futures-util", + "irpc-derive", + "n0-error", + "n0-future", + "serde", + "tokio", + "tokio-util", + "tracing", +] + +[[package]] +name = "irpc-derive" +version = "0.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "35c254013736de16472140d26904e6ac98e8f3887284dcf4af40f88c77411b56" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "is-docker" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "928bae27f42bc99b60d9ac7334e3a21d10ad8f1835a4e12ec3ec0464765ed1b3" +dependencies = [ + "once_cell", +] + +[[package]] +name = "is-wsl" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "173609498df190136aa7dea1a91db051746d339e18476eed5ca40521f02d7aa5" +dependencies = [ + "is-docker", + "once_cell", +] + +[[package]] +name = "is_terminal_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" + +[[package]] +name = "itertools" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186" +dependencies = [ + "either", +] + +[[package]] +name = "itertools" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285" +dependencies = [ + "either", +] + +[[package]] +name = "itertools" +version = "0.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b4baf93f58d4425749ca49a51c50ebab072c5df6994d08fed93541c331481dc" +dependencies = [ + "either", +] + +[[package]] +name = "itoa" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" + +[[package]] +name = "javascriptcore-rs" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca5671e9ffce8ffba57afc24070e906da7fc4b1ba66f2cabebf61bf2ea257fcc" +dependencies = [ + "bitflags 1.3.2", + "glib", + "javascriptcore-rs-sys", +] + +[[package]] +name = "javascriptcore-rs-sys" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af1be78d14ffa4b75b66df31840478fef72b51f8c2465d4ca7c194da9f7a5124" +dependencies = [ + "glib-sys", + "gobject-sys", + "libc", + "system-deps 6.2.2", +] + +[[package]] +name = "jiff" +version = "0.2.42" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fefca06093eeaed707a905795e68206da0edca4edef23d2a3997a3ddbee462aa" +dependencies = [ + "jiff-core", + "jiff-static", + "jiff-tzdb-platform", + "log", + "portable-atomic", + "portable-atomic-util", + "serde_core", + "windows-link 0.2.1", +] + +[[package]] +name = "jiff-core" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77a24020db0ee88d1c681d677681bd31f9f4ea189a455425223d52ce4f1508aa" +dependencies = [ + "log", +] + +[[package]] +name = "jiff-static" +version = "0.2.42" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41d3213549742662eea1a18e6c5af9be5dfbabeb7611ab71356a54928ec398f0" +dependencies = [ + "jiff-core", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "jiff-tzdb" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa8377070c6bae868759445e5a77f66d84f0b72f3a054bfb00e6d038b8282da7" + +[[package]] +name = "jiff-tzdb-platform" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "875a5a69ac2bab1a891711cf5eccbec1ce0341ea805560dcd90b7a2e925132e8" +dependencies = [ + "jiff-tzdb", +] + +[[package]] +name = "jni" +version = "0.21.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a87aa2bb7d2af34197c04845522473242e1aa17c12f4935d5856491a7fb8c97" +dependencies = [ + "cesu8", + "cfg-if 1.0.5", + "combine", + "jni-sys 0.3.1", + "log", + "thiserror 1.0.69", + "walkdir", + "windows-sys 0.45.0", +] + +[[package]] +name = "jni" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5efd9a482cf3a427f00d6b35f14332adc7902ce91efb778580e180ff90fa3498" +dependencies = [ + "cfg-if 1.0.5", + "combine", + "jni-macros", + "jni-sys 0.4.1", + "log", + "simd_cesu8", + "thiserror 2.0.21", + "walkdir", + "windows-link 0.2.1", +] + +[[package]] +name = "jni-macros" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a00109accc170f0bdb141fed3e393c565b6f5e072365c3bd58f5b062591560a3" +dependencies = [ + "proc-macro2", + "quote", + "rustc_version", + "simd_cesu8", + "syn 2.0.119", +] + +[[package]] +name = "jni-sys" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41a652e1f9b6e0275df1f15b32661cf0d4b78d4d87ddec5e0c3c20f097433258" +dependencies = [ + "jni-sys 0.4.1", +] + +[[package]] +name = "jni-sys" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6377a88cb3910bee9b0fa88d4f42e1d2da8e79915598f65fb0c7ee14c878af2" +dependencies = [ + "jni-sys-macros", +] + +[[package]] +name = "jni-sys-macros" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264" +dependencies = [ + "quote", + "syn 2.0.119", +] + +[[package]] +name = "jobserver" +version = "0.1.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3" +dependencies = [ + "getrandom 0.4.3", + "libc", +] + +[[package]] +name = "jpeg-decoder" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00810f1d8b74be64b13dbf3db89ac67740615d6c891f0e7b6179326533011a07" + +[[package]] +name = "jpegxl-src" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06f56a51e36f688517deebb0b7c10a11c598476936838938495c93764696180a" +dependencies = [ + "cmake", +] + +[[package]] +name = "js-sys" +version = "0.3.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a" +dependencies = [ + "cfg-if 1.0.5", + "futures-util", + "wasm-bindgen", +] + +[[package]] +name = "jxl-bitstream" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b480e752277e29eb4054f69546887a9b84656fe78c08f54ba5850ced98a378fe" +dependencies = [ + "tracing", +] + +[[package]] +name = "jxl-coding" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd972bcd125e776f1eb241ac50e39f956095a1c2770c64736c968f8946bd9a3c" +dependencies = [ + "jxl-bitstream", + "tracing", +] + +[[package]] +name = "jxl-color" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f316b1358c1711755b3ee8e8cb5c4a1dad12e796233088a7a513440782de80b2" +dependencies = [ + "jxl-bitstream", + "jxl-coding", + "jxl-grid", + "jxl-image", + "jxl-oxide-common", + "jxl-threadpool", + "tracing", +] + +[[package]] +name = "jxl-frame" +version = "0.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2d967c6fd669c7c01060b5022d8835fa82fd46b06ffc98b549f17600a097c2b3" +dependencies = [ + "jxl-bitstream", + "jxl-coding", + "jxl-grid", + "jxl-image", + "jxl-modular", + "jxl-oxide-common", + "jxl-threadpool", + "jxl-vardct", + "tracing", +] + +[[package]] +name = "jxl-grid" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "01671307879a033bfa52e6e8784b941aca770b3f3a7d33830b455b6844f793fb" +dependencies = [ + "tracing", +] + +[[package]] +name = "jxl-image" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c5f752d62577c702a94dbbce4045caf08cb58639e8a4d56464b40ecf33ffe565" +dependencies = [ + "jxl-bitstream", + "jxl-grid", + "jxl-oxide-common", + "tracing", +] + +[[package]] +name = "jxl-jbr" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e35d032bcec660647828527ff42c6f5776d2fd44b8357f9f6d9ac6dc07218e46" +dependencies = [ + "brotli-decompressor", + "jxl-bitstream", + "jxl-frame", + "jxl-grid", + "jxl-image", + "jxl-modular", + "jxl-oxide-common", + "jxl-threadpool", + "jxl-vardct", + "tracing", +] + +[[package]] +name = "jxl-modular" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2a2f045b24c738dd91d482be385512b512721ae08a671bd4b27bf1c47f215235" +dependencies = [ + "jxl-bitstream", + "jxl-coding", + "jxl-grid", + "jxl-oxide-common", + "jxl-threadpool", + "tracing", +] + +[[package]] +name = "jxl-oxide" +version = "0.12.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d36c662923f47586880211f3bc7c0d83fb3a9b410d278c7bde93450748abeef3" +dependencies = [ + "brotli-decompressor", + "bytemuck", + "image", + "jxl-bitstream", + "jxl-color", + "jxl-frame", + "jxl-grid", + "jxl-image", + "jxl-jbr", + "jxl-oxide-common", + "jxl-render", + "jxl-threadpool", + "tracing", +] + +[[package]] +name = "jxl-oxide-common" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b62394c5021b3a9e7e0dbb2d639d555d019090c9946c39f6d3b09d390db4157b" +dependencies = [ + "jxl-bitstream", +] + +[[package]] +name = "jxl-render" +version = "0.12.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d34386bfdb6a19b5a30cc9beb4d475d537422c31ae8c39bb69640fcce3fcaf19" +dependencies = [ + "bytemuck", + "jxl-bitstream", + "jxl-coding", + "jxl-color", + "jxl-frame", + "jxl-grid", + "jxl-image", + "jxl-modular", + "jxl-oxide-common", + "jxl-threadpool", + "jxl-vardct", + "tracing", +] + +[[package]] +name = "jxl-threadpool" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25f15eb830aa77a7f21148d72e153562a26bfe570139bd4922eab1908dd499d3" +dependencies = [ + "rayon", + "rayon-core", + "tracing", +] + +[[package]] +name = "jxl-vardct" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce72a18c6d3a47172ab6c479be2bdb56f22066b5d7092663f03b4490820b4511" +dependencies = [ + "jxl-bitstream", + "jxl-coding", + "jxl-grid", + "jxl-modular", + "jxl-oxide-common", + "jxl-threadpool", + "tracing", +] + +[[package]] +name = "keccak" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb26cec98cce3a3d96cbb7bced3c4b16e3d13f27ec56dbd62cbc8f39cfb9d653" +dependencies = [ + "cpufeatures 0.2.17", +] + +[[package]] +name = "keccak" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d8f198d1db720e4940b5a493201d199d9f24f568f8f746bd13706243a2f71598" +dependencies = [ + "cfg-if 1.0.5", + "cpufeatures 0.3.1", +] + +[[package]] +name = "khronos-egl" +version = "6.0.0" +source = "git+https://github.com/zed-industries/khronos-egl?rev=42214b36347b108fd9630ca6254b96dde59e04fe#42214b36347b108fd9630ca6254b96dde59e04fe" +dependencies = [ + "libc", + "libloading", + "pkg-config", +] + +[[package]] +name = "khronos_api" +version = "3.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e2db585e1d738fc771bf08a151420d3ed193d9d895a36df7f6f8a9456b911ddc" + +[[package]] +name = "kqueue" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8d763e5b24120b4ddf50de6c92308156765aabfbbccebf401da7cff2d70a41ea" +dependencies = [ + "kqueue-sys", + "libc", +] + +[[package]] +name = "kqueue-sys" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07293a4e297ac234359b510362495713f75ea345d5307140414f20c69ffeb087" +dependencies = [ + "bitflags 2.13.2", + "libc", +] + +[[package]] +name = "kurbo" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4b60dfc32f652b926df6192e55525b16d186c69d47876c3ead4da5cc9f8450e2" +dependencies = [ + "arrayvec", + "euclid", + "polycool", + "smallvec", +] + +[[package]] +name = "lazy_static" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" +dependencies = [ + "spin 0.9.9", +] + +[[package]] +name = "lazycell" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "830d08ce1d1d941e6b30645f1a0eb5643013d835ce3779a5fc208261dbe10f55" + +[[package]] +name = "lebe" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a79a3332a6609480d7d0c9eab957bca6b455b91bb84e66d19f5ff66294b85b8" + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "libcrux-intrinsics" +version = "0.0.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "98a0c574d4eb81d0814bc2b91e4a433d7e0b35851b1d62eb5dd95c064f1f76d0" +dependencies = [ + "core-models", + "hax-lib", +] + +[[package]] +name = "libcrux-ml-kem" +version = "0.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d8160f7d64fd2716b4fd05cc886a042f8dcda18d9206c0d506e2c67bdf97daa" +dependencies = [ + "hax-lib", + "libcrux-intrinsics", + "libcrux-platform", + "libcrux-secrets", + "libcrux-sha3", + "libcrux-traits", +] + +[[package]] +name = "libcrux-platform" +version = "0.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d9e21d7ed31a92ac539bd69a8c970b183ee883872d2d19ce27036e24cb8ecc4" +dependencies = [ + "libc", +] + +[[package]] +name = "libcrux-secrets" +version = "0.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "79054fc9037cb70d6a546cf094cea7d7df06af5e49d230ba24103d27ccc886f1" +dependencies = [ + "crabgrind", + "hax-lib", +] + +[[package]] +name = "libcrux-sha3" +version = "0.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c09f5c39afae0528e1f70a3c1e3c6ee649ec1f19dda26fc9b6ea91108fb879ef" +dependencies = [ + "hax-lib", + "libcrux-intrinsics", + "libcrux-platform", + "libcrux-traits", +] + +[[package]] +name = "libcrux-traits" +version = "0.0.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3fa7a21e8c2e8baa8b40f0b176740f2ca4baadd79d1b00e48d6b1e363c42085a" +dependencies = [ + "libcrux-secrets", + "rand 0.10.3", +] + +[[package]] +name = "libflate" +version = "1.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ff4ae71b685bbad2f2f391fe74f6b7659a34871c08b210fdc039e43bee07d18" +dependencies = [ + "adler32", + "crc32fast", + "libflate_lz77", +] + +[[package]] +name = "libflate_lz77" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a52d3a8bfc85f250440e4424db7d857e241a3aebbbe301f3eb606ab15c39acbf" +dependencies = [ + "rle-decode-fast", +] + +[[package]] +name = "libfuzzer-sys" +version = "0.4.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a9fd2f41a1cba099f79a0b6b6c35656cf7c03351a7bae8ff0f28f25270f929d2" +dependencies = [ + "arbitrary", + "cc", +] + +[[package]] +name = "libloading" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7c4b02199fee7c5d21a5ae7d8cfa79a6ef5bb2fc834d6e9058e89c825efdc55" +dependencies = [ + "cfg-if 1.0.5", + "windows-link 0.2.1", +] + +[[package]] +name = "libm" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" + +[[package]] +name = "libredox" +version = "0.1.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61ff90caf6077a803a240f62fdbe88645a890bbca49ef8174c3cb0404362171d" +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.6", + "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 = "libsqlite3-sys" +version = "0.36.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95b4103cffefa72eb8428cb6b47d6627161e51c2739fc5e3b734584157bc642a" +dependencies = [ + "cc", + "pkg-config", + "vcpkg", +] + +[[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.6", + "thiserror 2.0.21", + "tracing", + "wayland-backend", + "wayland-client", + "wayland-protocols", + "wayland-protocols-wlr", +] + +[[package]] +name = "libwebp-sys" +version = "0.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "54cd30df7c7165ce74a456e4ca9732c603e8dc5e60784558c1c6dc047f876733" +dependencies = [ + "cc", + "glob", +] + +[[package]] +name = "linebender_resource_handle" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4" + +[[package]] +name = "link-section" +version = "0.19.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39c29a617ce3df32c08497bdc1ab6e2376e0b17948ac166a2fbe5977c5954cd9" + +[[package]] +name = "linktime-proc-macro" +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" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "litemap" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" + +[[package]] +name = "litrs" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4744e383959f0db86ede514b809b1c53251889093803c05267acc7d4e7030d70" + +[[package]] +name = "lock_api" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" +dependencies = [ + "scopeguard", +] + +[[package]] +name = "lofty" +version = "0.24.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dec4feeff6c7d75093278133a06e827d7af6d2bfe20b0f331f9d10338a5ec7ca" +dependencies = [ + "byteorder", + "data-encoding", + "flate2", + "lofty_attr", + "log", + "ogg_pager", + "paste", +] + +[[package]] +name = "lofty_attr" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "458ace39169e4b83c4f77ae3d42d5d1d11c422feef590219a97c973d3b524557" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" +dependencies = [ + "serde_core", +] + +[[package]] +name = "loom" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1611ddbf89dc6ae42cfbd51fc207836140130257646eab8d6d2fb16577db2d2" +dependencies = [ + "cfg-if 1.0.5", + "generator", + "scoped-tls", + "tracing", + "tracing-subscriber", +] + +[[package]] +name = "loop9" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fae87c125b03c1d2c0150c90365d7d6bcc53fb73a9acaef207d2d065860f062" +dependencies = [ + "imgref", +] + +[[package]] +name = "lru" +version = "0.18.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef9ac18847474e638e3702b76c65d4eb93428471a74778ef0f1be711717f89b5" +dependencies = [ + "hashbrown 0.17.1", +] + +[[package]] +name = "lru-slab" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4050469837a6ff301cd14c1f8f24f88549e6d548f24f64e2148eb0f72cebc51f" + +[[package]] +name = "lyon" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bd0578bdecb7d6d88987b8b2b1e3a4e2f81df9d0ece1078623324a567904e7b7" +dependencies = [ + "lyon_algorithms", + "lyon_tessellation", +] + +[[package]] +name = "lyon_algorithms" +version = "1.0.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3a6b9d4e8b48acd531fbf1241ad9b270df6e60b6b92bdea1469f4f40899d805" +dependencies = [ + "lyon_path", + "num-traits", +] + +[[package]] +name = "lyon_geom" +version = "1.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d82dd26aa4dc0b5b70b9115de59824842bcb43cf4a28e1b1e6d0ad148c93f93e" +dependencies = [ + "arrayvec", + "euclid", + "num-traits", +] + +[[package]] +name = "lyon_path" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c463f9c428b7fc5ec885dcd39ce4aa61e29111d0e33483f6f98c74e89d8621e" +dependencies = [ + "lyon_geom", + "num-traits", +] + +[[package]] +name = "lyon_tessellation" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd4872650e70dc907dd4f7ebc449d7d657a0d2658e423b2e724970870bbbf75b" +dependencies = [ + "float_next_after", + "lyon_path", + "num-traits", +] + +[[package]] +name = "mac-addr" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3d25b0e0b648a86960ac23b7ad4abb9717601dec6f66c165f5b037f3f03065f" + +[[package]] +name = "mac-notification-sys" +version = "0.6.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd604973958ddcc11b561193c0fb96ba146506ef2f231ef2e7c35fd2cbc9beca" +dependencies = [ + "cc", + "log", + "objc2 0.6.5", + "objc2-foundation 0.3.2", + "time", + "uuid", +] + +[[package]] +name = "mach2" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d640282b302c0bb0a2a8e0233ead9035e3bed871f0b7e81fe4a1ec829765db44" +dependencies = [ + "libc", +] + +[[package]] +name = "mach2" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dae608c151f68243f2b000364e1f7b186d9c29845f7d2d85bd31b9ad77ad552b" + +[[package]] +name = "macro_rules_attribute" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b3ae8f6d608c795738406608304d30a2dfbdc8e58e44f7ba43236da5208ded3c" +dependencies = [ + "macro_rules_attribute-proc_macro", + "pastey 0.2.3", +] + +[[package]] +name = "macro_rules_attribute-proc_macro" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc04a4c58212d57930a24bf47d3fa87485264a3a054e9c10e042eb373573ad3c" + +[[package]] +name = "malloc_buf" +version = "0.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "62bb907fe88d54d8d9ce32a3cceab4218ed2f6b7d35617cafe9adf84e43919cb" +dependencies = [ + "libc", +] + +[[package]] +name = "markup5ever" +version = "0.39.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7122d987ec5f704ee56f6e5b41a7d93722e9aae27ae07cafa4036c4d3f9757de" +dependencies = [ + "log", + "tendril", + "web_atoms", +] + +[[package]] +name = "matchers" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1525a2a28c7f4fa0fc98bb91ae755d1e2d1505079e05539e35bc876b5d65ae9" +dependencies = [ + "regex-automata", +] + +[[package]] +name = "maybe-rayon" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ea1f30cedd69f0a2954655f7188c6a834246d2bcf1e315e2ac40c4b24dc9519" +dependencies = [ + "cfg-if 1.0.5", + "rayon", +] + +[[package]] +name = "md-5" +version = "0.10.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf" +dependencies = [ + "cfg-if 1.0.5", + "digest 0.10.7", +] + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "memmap2" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b0ca1155a9ecc25aa12e8313a119f32edf0255fea2f44839c4ac0a12b2ac157" +dependencies = [ + "libc", +] + +[[package]] +name = "memoffset" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a" +dependencies = [ + "autocfg", +] + +[[package]] +name = "merlin" +version = "3.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "58c38e2799fc0978b65dfff8023ec7843e2330bb462f19198840b34b6582397d" +dependencies = [ + "byteorder", + "keccak 0.1.6", + "rand_core 0.6.4", + "zeroize", +] + +[[package]] +name = "metal" +version = "0.18.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e198a0ee42bdbe9ef2c09d0b9426f3b2b47d90d93a4a9b0395c4cea605e92dc0" +dependencies = [ + "bitflags 1.3.2", + "block", + "cocoa", + "core-graphics 0.19.2", + "foreign-types 0.3.2", + "log", + "objc", +] + +[[package]] +name = "mime" +version = "0.3.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d5848f5a9e8117cf94f2f90faac24a87ff81600ff8628c1e3deaab572e76bfa1" + +[[package]] +name = "mime_guess" +version = "2.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f7c44f8e672c00fe5308fa235f821cb4198414e1c77935c1ab6948d3fd78550e" +dependencies = [ + "mime", + "unicase", +] + +[[package]] +name = "minimal-lexical" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" + +[[package]] +name = "minisign-verify" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22f9645cb765ea72b8111f36c522475d2daa0d22c957a9826437e97534bc4e9e" + +[[package]] +name = "miniz_oxide" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316" +dependencies = [ + "adler2", + "simd-adler32", +] + +[[package]] +name = "miniz_oxide" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" +dependencies = [ + "adler2", + "simd-adler32", +] + +[[package]] +name = "mintex" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c505b3e17ed6b70a7ed2e67fbb2c560ee327353556120d6e72f5232b6880d536" + +[[package]] +name = "mio" +version = "1.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1788edb87fdc09c7e26304471e2f5be8cdefb1b6930d6e3985fc02ff53bf86ee" +dependencies = [ + "libc", + "log", + "wasi", + "windows-sys 0.61.2", +] + +[[package]] +name = "moxcms" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb85c154ba489f01b25c0d36ae69a87e4a1c73a72631fc6c0eb6dde34a73e44b" +dependencies = [ + "num-traits", + "pxfm", +] + +[[package]] +name = "mozjpeg" +version = "0.10.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7891b80aaa86097d38d276eb98b3805d6280708c4e0a1e6f6aed9380c51fec9" +dependencies = [ + "arrayvec", + "bytemuck", + "libc", + "mozjpeg-sys", + "rgb", +] + +[[package]] +name = "mozjpeg-sys" +version = "2.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f0dc668bf9bf888c88e2fb1ab16a406d2c380f1d082b20d51dd540ab2aa70c1" +dependencies = [ + "cc", + "dunce", + "libc", + "nasm-rs", +] + +[[package]] +name = "multiversion" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eb8a68be21d0755f83bfe47e79b896cc732687cf1903f0e50585e8d6ecc53076" +dependencies = [ + "multiversion-macros", + "target-features", +] + +[[package]] +name = "multiversion-macros" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a05e0c3c3e4edaa21d87c645852ed0b0c3663752bcc6ec43353bd6189dce35e1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", + "target-features", +] + +[[package]] +name = "multiversion_no_op" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "743fb55ba31b18fb1ecef6bdc9aa2743314978ac084044301a7eee33fb99a20d" + +[[package]] +name = "n0-dns-resolver" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "535c99c9a786bee714155d2ee4fc2477405c2c43536e1bc6a51de09a0d1448f7" +dependencies = [ + "derive_more", + "ipconfig", + "jni 0.22.4", + "lru", + "n0-error", + "n0-future", + "ndk-context", + "rand 0.10.3", + "reqwest", + "rustc-hash 2.1.3", + "rustls", + "simple-dns", + "system-configuration", + "tokio", + "tokio-rustls", + "tracing", + "webpki-roots 1.0.12", +] + +[[package]] +name = "n0-error" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96c2215d16de3a55894583a539e6b151fb45236c3a6da45a18a40af73dc00636" +dependencies = [ + "anyhow", + "n0-error-macros", + "spez", +] + +[[package]] +name = "n0-error-macros" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6217fd5f567ce1e53f324744c14fab04899861e397539c5f3cc08bd7c1dcd2de" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "n0-future" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e2ab99dfb861450e68853d34ae665243a88b8c493d01ba957321a1e9b2312bbe" +dependencies = [ + "cfg_aliases", + "derive_more", + "futures-buffered", + "futures-lite", + "futures-util", + "js-sys", + "pin-project", + "send_wrapper", + "tokio", + "tokio-util", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-time", +] + +[[package]] +name = "n0-watcher" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "64bf1ecb076a87e0e3f5edcf726e7d29e788c273bb0161ba30666b53f085906c" +dependencies = [ + "derive_more", + "n0-error", + "n0-future", + "slotmap", +] + +[[package]] +name = "naga" +version = "30.0.0" +source = "git+https://github.com/gfx-rs/wgpu?rev=cddb2f5d80dc0009b2ef6767635140cacf90a007#cddb2f5d80dc0009b2ef6767635140cacf90a007" +dependencies = [ + "arrayvec", + "bit-set 0.11.1", + "bitflags 2.13.2", + "cfg-if 1.0.5", + "cfg_aliases", + "codespan-reporting", + "half", + "hashbrown 0.17.1", + "indexmap 2.14.2", + "libm", + "log", + "naga-types", + "num-traits", + "once_cell", + "rustc-hash 1.1.0", + "spirv", + "thiserror 2.0.21", + "unicode-ident", +] + +[[package]] +name = "naga-types" +version = "30.0.0" +source = "git+https://github.com/gfx-rs/wgpu?rev=cddb2f5d80dc0009b2ef6767635140cacf90a007#cddb2f5d80dc0009b2ef6767635140cacf90a007" +dependencies = [ + "hashbrown 0.17.1", + "indexmap 2.14.2", + "rustc-hash 1.1.0", + "thiserror 2.0.21", +] + +[[package]] +name = "nanorand" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a51313c5820b0b02bd422f4b44776fbf47961755c74ce64afc73bfad10226c3" +dependencies = [ + "getrandom 0.2.17", +] + +[[package]] +name = "nasm-rs" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "706bf8a5e8c8ddb99128c3291d31bd21f4bcde17f0f4c20ec678d85c74faa149" +dependencies = [ + "jobserver", + "log", +] + +[[package]] +name = "ndk" +version = "0.9.0" +dependencies = [ + "bitflags 2.13.2", + "jni-sys 0.3.1", + "libc", + "log", + "ndk-sys", + "num_enum", + "raw-window-handle", + "thiserror 1.0.69", +] + +[[package]] +name = "ndk-context" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27b02d87554356db9e9a873add8782d4ea6e3e58ea071a9adb9a2e8ddb884a8b" + +[[package]] +name = "ndk-sys" +version = "0.6.0+11769913" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee6cda3051665f1fb8d9e08fc35c96d5a244fb1be711a03b71118828afc9a873" +dependencies = [ + "jni-sys 0.3.1", +] + +[[package]] +name = "negentropy" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a3d66662cb5ca384d4991509755ed5a42dd8e31c4282bf881938e506fc3146ec" + +[[package]] +name = "netdev" +version = "0.45.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "096c44b66a9b09b99b4dd36b1c295ff3a492039ccecaf55466bd6ddcdba59968" +dependencies = [ + "block2 0.6.2", + "dispatch2", + "dlopen2", + "ipnet", + "jni 0.21.1", + "libc", + "mac-addr", + "ndk-context", + "netlink-packet-core 0.8.2", + "netlink-packet-route 0.31.0", + "netlink-sys 0.8.8", + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-core-wlan", + "objc2-foundation 0.3.2", + "objc2-system-configuration", + "once_cell", + "plist", + "windows-sys 0.61.2", +] + +[[package]] +name = "netdev" +version = "0.46.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3c52c2584961c68f5a6e3356797344061f818c93b8acc9cd6d7e284795e563e" +dependencies = [ + "block2 0.6.2", + "dispatch2", + "dlopen2", + "ipnet", + "jni 0.21.1", + "libc", + "mac-addr", + "ndk-context", + "netlink-packet-core 0.9.0", + "netlink-packet-route 0.33.0", + "netlink-sys 0.9.0", + "objc2-core-foundation", + "objc2-system-configuration", + "once_cell", + "plist", + "windows-sys 0.61.2", +] + +[[package]] +name = "netlink-packet-core" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b897d7bd4f0af82e68d40d0344cf37e97f9c97ddf74a098de3e4da05e96ca395" +dependencies = [ + "paste", +] + +[[package]] +name = "netlink-packet-core" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2d6e2daf9a8c2e21302714706860a0e6be02e03d17294ecc66b354ea7d4059dd" + +[[package]] +name = "netlink-packet-route" +version = "0.31.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e2288fcb784eb3defd5fb16f4c4160d5f477de192eac730f43e1d11c24d9a007" +dependencies = [ + "bitflags 2.13.2", + "libc", + "log", + "netlink-packet-core 0.8.2", +] + +[[package]] +name = "netlink-packet-route" +version = "0.33.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59d48ffc8b73a506e1ff0878528c72668f2bfbc3d875b6be890a96be5d0d5576" +dependencies = [ + "bitflags 2.13.2", + "libc", + "log", + "netlink-packet-core 0.9.0", + "zerocopy", +] + +[[package]] +name = "netlink-proto" +version = "0.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93af8261786086024cd5e96e0a991dd65ced07bbf7c233a487bbc96b971d5539" +dependencies = [ + "bytes", + "futures-channel", + "futures-util", + "log", + "netlink-packet-core 0.8.2", + "netlink-sys 0.8.8", + "thiserror 2.0.21", +] + +[[package]] +name = "netlink-sys" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd6c30ed10fa69cc491d491b85cc971f6bdeb8e7367b7cde2ee6cc878d583fae" +dependencies = [ + "bytes", + "futures-util", + "libc", + "log", + "tokio", +] + +[[package]] +name = "netlink-sys" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c99d38e00b420df49e940fe0826e667c3dad82ac68eb4c2bbf754c1c14a83a10" +dependencies = [ + "bytes", + "libc", + "log", +] + +[[package]] +name = "netwatch" +version = "0.19.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39da9cad5f23aa43401f09497d3b280e51b5feba115d9ffbf38ca35d6ff95e96" +dependencies = [ + "atomic-waker", + "bytes", + "cfg_aliases", + "derive_more", + "ipnet", + "js-sys", + "libc", + "n0-error", + "n0-future", + "n0-watcher", + "netdev 0.45.1", + "netdev 0.46.3", + "netlink-packet-core 0.8.2", + "netlink-packet-route 0.31.0", + "netlink-proto", + "netlink-sys 0.8.8", + "noq-udp", + "objc2-core-foundation", + "objc2-system-configuration", + "pin-project-lite", + "serde", + "socket2", + "time", + "tokio", + "tokio-util", + "tracing", + "web-sys", + "windows 0.62.2", + "windows-result 0.4.1", + "wmi", +] + +[[package]] +name = "new_debug_unreachable" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "650eef8c711430f1a879fdd01d4745a7deea475becfb90269c06775983bbf086" + +[[package]] +name = "no_std_io2" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "418abd1b6d34fbf6cae440dc874771b0525a604428704c76e48b29a5e67b8003" +dependencies = [ + "memchr", +] + +[[package]] +name = "nokhwa" +version = "0.10.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d63f10b450319a0ace7aa8e0e25477d1fdb345313a97e220e886175539a1dbb" +dependencies = [ + "flume 0.11.1", + "image", + "nokhwa-bindings-linux", + "nokhwa-bindings-macos", + "nokhwa-bindings-windows", + "nokhwa-core", + "paste", + "thiserror 2.0.21", +] + +[[package]] +name = "nokhwa-bindings-linux" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb67e22201a53322291740ca064b20eaaade7222ef0349f312d9b37b004e1984" +dependencies = [ + "libc", + "nokhwa-core", + "v4l", +] + +[[package]] +name = "nokhwa-bindings-macos" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f70d3908ea68324e44a6b3a0f885aa59e433fb1f6678839d09e0df7d226fb42d" +dependencies = [ + "block", + "cocoa-foundation", + "core-foundation 0.10.1", + "core-media-sys", + "core-video-sys", + "flume 0.11.1", + "nokhwa-core", + "objc", + "once_cell", +] + +[[package]] +name = "nokhwa-bindings-windows" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5be28886bad8abcec3655c1f24b965b4cb596a72b23164c910c54439ce55d2a4" +dependencies = [ + "nokhwa-core", + "once_cell", + "windows 0.62.2", +] + +[[package]] +name = "nokhwa-core" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1cba20bebd3bd9ae22f9273ade5bbe49da3e047c8512b53fbaf8b4b9c80d496" +dependencies = [ + "bytes", + "image", + "mozjpeg", + "thiserror 2.0.21", +] + +[[package]] +name = "nom" +version = "7.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a" +dependencies = [ + "memchr", + "minimal-lexical", +] + +[[package]] +name = "nom" +version = "8.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df9761775871bdef83bee530e60050f7e54b1105350d6884eb0fb4f46c2f9405" +dependencies = [ + "memchr", +] + +[[package]] +name = "nonany" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6b8866ec53810a9a4b3d434a29801e78c707430a9ae11c2db4b8b62bb9675a0" + +[[package]] +name = "noop_proc_macro" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0676bb32a98c1a483ce53e500a81ad9c3d5b3f7c920c28c24e9cb0980d0b5bc8" + +[[package]] +name = "noq" +version = "1.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6249a065adc1edbc1704a95436f38dd60476064dbc3b7c47cf279e02d1590eb5" +dependencies = [ + "bytes", + "cfg_aliases", + "derive_more", + "noq-proto", + "noq-udp", + "pin-project-lite", + "rustc-hash 2.1.3", + "rustls", + "socket2", + "thiserror 2.0.21", + "tokio", + "tokio-stream", + "tracing", + "web-time", +] + +[[package]] +name = "noq-proto" +version = "1.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c01a35be3ed37558c8db69554419f24eff8a63599b54f711bbe3863ec727c47d" +dependencies = [ + "aes-gcm", + "bytes", + "derive_more", + "enum-assoc", + "fastbloom", + "getrandom 0.4.3", + "identity-hash", + "lru-slab", + "rand 0.10.3", + "rand_pcg", + "ring", + "rustc-hash 2.1.3", + "rustls", + "rustls-pki-types", + "slab", + "sorted-index-buffer", + "thiserror 2.0.21", + "tinyvec", + "tracing", + "web-time", +] + +[[package]] +name = "noq-udp" +version = "1.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8d0160422832eea1cc11c34be04ee6d5a046452b0b46cfb14695d55a1f24c954" +dependencies = [ + "cfg_aliases", + "libc", + "socket2", + "tracing", + "windows-sys 0.61.2", +] + +[[package]] +name = "nostr" +version = "0.45.7" +source = "git+https://github.com/VectorPrivacy/nostr.git?branch=vector-v0.45.6#392a7eb2e55ffccf512c0951df83d65c38d81cab" +dependencies = [ + "aes 0.8.4", + "base64 0.22.1", + "bech32", + "bip39", + "bitcoin_hashes 1.2.0", + "cbc", + "chacha20 0.9.1", + "chacha20poly1305", + "faster-hex", + "nostr-parse", + "opaquerr", + "rand 0.10.3", + "secp256k1", + "serde", + "serde_json", + "unicode-normalization", + "universal-time", + "url", + "zeroize", +] + +[[package]] +name = "nostr-connect" +version = "0.45.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "99a90f462a73bcb95134a2f3a731c4a9c5ee5d3156bc4f4663bc114ee533bb98" +dependencies = [ + "async-utility", + "futures-core", + "nostr", + "nostr-sdk", + "opaquerr", + "tokio", + "tracing", +] + +[[package]] +name = "nostr-database" +version = "0.45.2" +source = "git+https://github.com/VectorPrivacy/nostr.git?branch=vector-v0.45.6#392a7eb2e55ffccf512c0951df83d65c38d81cab" +dependencies = [ + "nostr", + "opaquerr", +] + +[[package]] +name = "nostr-gossip" +version = "0.45.1" +source = "git+https://github.com/VectorPrivacy/nostr.git?branch=vector-v0.45.6#392a7eb2e55ffccf512c0951df83d65c38d81cab" +dependencies = [ + "nostr", + "opaquerr", +] + +[[package]] +name = "nostr-parse" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a68b8ffe088159244b40038395d4e924a1c67a0a4950992ef8ee58e10803d50b" + +[[package]] +name = "nostr-sdk" +version = "0.45.6" +source = "git+https://github.com/VectorPrivacy/nostr.git?branch=vector-v0.45.6#392a7eb2e55ffccf512c0951df83d65c38d81cab" +dependencies = [ + "async-utility", + "async-wsocket", + "faster-hex", + "futures", + "negentropy", + "nostr", + "nostr-database", + "nostr-gossip", + "nostr-parse", + "opaquerr", + "rand 0.10.3", + "tokio", + "tokio-stream", + "tracing", + "universal-time", +] + +[[package]] +name = "nostr-verify" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f27f3d7e0c21c93134365ebc9c577acf244d77347fde957a25e68b155903d141" +dependencies = [ + "getrandom 0.2.17", + "secp256k1", + "sha2 0.11.1", +] + +[[package]] +name = "notify" +version = "8.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c41a04a5f59df9322cc657286dd2d79f90816119b22c5f847607c850110205ab" +dependencies = [ + "bitflags 2.13.2", + "inotify", + "kqueue", + "libc", + "log", + "mio", + "notify-types", + "walkdir", + "windows-sys 0.61.2", +] + +[[package]] +name = "notify-rust" +version = "4.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57da5b5d3b7809bf71858da5a2818c3404ca4688c02c8abecdda0fcdec235df3" +dependencies = [ + "futures-lite", + "log", + "mac-notification-sys", + "serde", + "tauri-winrt-notification", + "zbus 6.2.1", +] + +[[package]] +name = "notify-types" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c491a384baf9fec20df565cdb8138a12809d4c7439763b566eb8114c5d59979" +dependencies = [ + "bitflags 2.13.2", +] + +[[package]] +name = "ntapi" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3b335231dfd352ffb0f8017f3b6027a4917f7df785ea2143d8af2adc66980ae" +dependencies = [ + "winapi", +] + +[[package]] +name = "nu-ansi-term" +version = "0.50.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "num" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "35bd024e8b2ff75562e5f34e7f4905839deb4b22955ef5e73d2fea1b9813cb23" +dependencies = [ + "num-bigint", + "num-complex", + "num-integer", + "num-iter", + "num-rational", + "num-traits", +] + +[[package]] +name = "num-bigint" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367" +dependencies = [ + "num-integer", + "num-traits", +] + +[[package]] +name = "num-bigint-dig" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e661dda6640fad38e827a6d4a310ff4763082116fe217f279885c97f511bb0b7" +dependencies = [ + "lazy_static", + "libm", + "num-integer", + "num-iter", + "num-traits", + "rand 0.8.8", + "smallvec", + "zeroize", +] + +[[package]] +name = "num-bigint-dig" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7f9a86e097b0d187ad0e65667c2f58b9254671e86e7dbb78036b16692eae099" +dependencies = [ + "libm", + "num-integer", + "num-iter", + "num-traits", + "once_cell", + "rand 0.9.5", + "serde", + "smallvec", + "zeroize", +] + +[[package]] +name = "num-complex" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73f88a1307638156682bada9d7604135552957b7818057dcef22705b4d509495" +dependencies = [ + "num-traits", +] + +[[package]] +name = "num-conv" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" + +[[package]] +name = "num-derive" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed3955f1a9c7c0c15e092f9c887db08b1fc683305fdf6eb6684f22555355e202" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "num-integer" +version = "0.1.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b" +dependencies = [ + "num-traits", +] + +[[package]] +name = "num-iter" +version = "0.1.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c92800bd69a1eac91786bcfe9da64a897eb72911b8dc3095decbd07429e8048b" +dependencies = [ + "num-integer", + "num-traits", +] + +[[package]] +name = "num-rational" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824" +dependencies = [ + "num-bigint", + "num-integer", + "num-traits", +] + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", + "libm", +] + +[[package]] +name = "num_cpus" +version = "1.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91df4bbde75afed763b708b7eee1e8e7651e02d97f6d5dd763e89367e957b23b" +dependencies = [ + "hermit-abi", + "libc", +] + +[[package]] +name = "num_enum" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d0bca838442ec211fa11de3a8b0e0e8f3a4522575b5c4c06ed722e005036f26" +dependencies = [ + "num_enum_derive", + "rustversion", +] + +[[package]] +name = "num_enum_derive" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "680998035259dcfcafe653688bf2aa6d3e2dc05e98be6ab46afb089dc84f1df8" +dependencies = [ + "proc-macro-crate 3.5.0", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "objc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "915b1b472bc21c53464d6c8461c9d3af805ba1ef837e1cac254428f4a77177b1" +dependencies = [ + "malloc_buf", + "objc_exception", +] + +[[package]] +name = "objc-sys" +version = "0.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdb91bdd390c7ce1a8607f35f3ca7151b65afc0ff5ff3b34fa350f7d7c7e4310" + +[[package]] +name = "objc2" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19d5490aaf8f1d7cf7688dfa9b0ce07900e168852c45cd2c03f534dfd27cfd0b" +dependencies = [ + "objc-sys", + "objc2-encode", +] + +[[package]] +name = "objc2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08849bbd4767dfae9457696856ae1c84fe4e0281bbe4a7abff2d0e06fb7981f8" +dependencies = [ + "objc2-encode", + "objc2-exception-helper", +] + +[[package]] +name = "objc2-app-kit" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4e89ad9e3d7d297152b17d39ed92cd50ca8063a89a9fa569046d41568891eff" +dependencies = [ + "bitflags 2.13.2", + "block2 0.5.1", + "libc", + "objc2 0.5.3", + "objc2-core-data 0.2.2", + "objc2-core-image 0.2.2", + "objc2-foundation 0.2.2", + "objc2-quartz-core 0.2.2", +] + +[[package]] +name = "objc2-app-kit" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d49e936b501e5c5bf01fda3a9452ff86dc3ea98ad5f283e1455153142d97518c" +dependencies = [ + "bitflags 2.13.2", + "block2 0.6.2", + "libc", + "objc2 0.6.5", + "objc2-cloud-kit", + "objc2-core-data 0.3.2", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-core-image 0.3.2", + "objc2-core-text", + "objc2-core-video", + "objc2-foundation 0.3.2", + "objc2-quartz-core 0.3.2", + "objc2-uniform-type-identifiers", +] + +[[package]] +name = "objc2-audio-toolbox" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6948501a91121d6399b79abaa33a8aa4ea7857fe019f341b8c23ad6e81b79b08" +dependencies = [ + "bitflags 2.13.2", + "libc", + "objc2 0.6.5", + "objc2-core-audio", + "objc2-core-audio-types", + "objc2-core-foundation", + "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-cloud-kit" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73ad74d880bb43877038da939b7427bba67e9dd42004a18b809ba7d87cee241c" +dependencies = [ + "bitflags 2.13.2", + "objc2 0.6.5", + "objc2-foundation 0.3.2", +] + +[[package]] +name = "objc2-core-audio" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1eebcea8b0dbff5f7c8504f3107c68fc061a3eb44932051c8cf8a68d969c3b2" +dependencies = [ + "dispatch2", + "objc2 0.6.5", + "objc2-core-audio-types", + "objc2-core-foundation", +] + +[[package]] +name = "objc2-core-audio-types" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a89f2ec274a0cf4a32642b2991e8b351a404d290da87bb6a9a9d8632490bd1c" +dependencies = [ + "bitflags 2.13.2", + "objc2 0.6.5", +] + +[[package]] +name = "objc2-core-data" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "617fbf49e071c178c0b24c080767db52958f716d9eabdf0890523aeae54773ef" +dependencies = [ + "bitflags 2.13.2", + "block2 0.5.1", + "objc2 0.5.3", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-core-data" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b402a653efbb5e82ce4df10683b6b28027616a2715e90009947d50b8dd298fa" +dependencies = [ + "bitflags 2.13.2", + "objc2 0.6.5", + "objc2-foundation 0.3.2", +] + +[[package]] +name = "objc2-core-foundation" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536" +dependencies = [ + "bitflags 2.13.2", + "block2 0.6.2", + "dispatch2", + "libc", + "objc2 0.6.5", +] + +[[package]] +name = "objc2-core-graphics" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e022c9d066895efa1345f8e33e584b9f958da2fd4cd116792e15e07e4720a807" +dependencies = [ + "bitflags 2.13.2", + "block2 0.6.2", + "dispatch2", + "libc", + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-io-surface", + "objc2-metal 0.3.2", +] + +[[package]] +name = "objc2-core-image" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "55260963a527c99f1819c4f8e3b47fe04f9650694ef348ffd2227e8196d34c80" +dependencies = [ + "block2 0.5.1", + "objc2 0.5.3", + "objc2-foundation 0.2.2", + "objc2-metal 0.2.2", +] + +[[package]] +name = "objc2-core-image" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5d563b38d2b97209f8e861173de434bd0214cf020e3423a52624cd1d989f006" +dependencies = [ + "objc2 0.6.5", + "objc2-foundation 0.3.2", +] + +[[package]] +name = "objc2-core-location" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca347214e24bc973fc025fd0d36ebb179ff30536ed1f80252706db19ee452009" +dependencies = [ + "objc2 0.6.5", + "objc2-foundation 0.3.2", +] + +[[package]] +name = "objc2-core-media" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05ec576860167a15dd9fce7fbee7512beb4e31f532159d3482d1f9c6caedf31d" +dependencies = [ + "bitflags 2.13.2", + "block2 0.6.2", + "dispatch2", + "objc2 0.6.5", + "objc2-core-audio", + "objc2-core-audio-types", + "objc2-core-foundation", + "objc2-core-video", +] + +[[package]] +name = "objc2-core-text" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0cde0dfb48d25d2b4862161a4d5fcc0e3c24367869ad306b0c9ec0073bfed92d" +dependencies = [ + "bitflags 2.13.2", + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-core-graphics", +] + +[[package]] +name = "objc2-core-video" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d425caf1df73233f29fd8a5c3e5edbc30d2d4307870f802d18f00d83dc5141a6" +dependencies = [ + "bitflags 2.13.2", + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-io-surface", + "objc2-metal 0.3.2", +] + +[[package]] +name = "objc2-core-wlan" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c71e34919aba0d701380d911702455038a8a3587467fe0141d6a71501e7ffe48" +dependencies = [ + "bitflags 2.13.2", + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-foundation 0.3.2", + "objc2-security", + "objc2-security-foundation", +] + +[[package]] +name = "objc2-encode" +version = "4.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef25abbcd74fb2609453eb695bd2f860d389e457f67dc17cafc8b8cbc89d0c33" + +[[package]] +name = "objc2-exception-helper" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c7a1c5fbb72d7735b076bb47b578523aedc40f3c439bea6dfd595c089d79d98a" +dependencies = [ + "cc", +] + +[[package]] +name = "objc2-foundation" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ee638a5da3799329310ad4cfa62fbf045d5f56e3ef5ba4149e7452dcf89d5a8" +dependencies = [ + "bitflags 2.13.2", + "block2 0.5.1", + "libc", + "objc2 0.5.3", +] + +[[package]] +name = "objc2-foundation" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272" +dependencies = [ + "bitflags 2.13.2", + "block2 0.6.2", + "libc", + "objc2 0.6.5", + "objc2-core-foundation", +] + +[[package]] +name = "objc2-io-kit" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33fafba39597d6dc1fb709123dfa8289d39406734be322956a69f0931c73bb15" +dependencies = [ + "libc", + "objc2-core-foundation", +] + +[[package]] +name = "objc2-io-surface" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "180788110936d59bab6bd83b6060ffdfffb3b922ba1396b312ae795e1de9d81d" +dependencies = [ + "bitflags 2.13.2", + "objc2 0.6.5", + "objc2-core-foundation", +] + +[[package]] +name = "objc2-metal" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dd0cba1276f6023976a406a14ffa85e1fdd19df6b0f737b063b95f6c8c7aadd6" +dependencies = [ + "bitflags 2.13.2", + "block2 0.5.1", + "objc2 0.5.3", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-metal" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0125f776a10d00af4152d74616409f0d4a2053a6f57fa5b7d6aa2854ac04794" +dependencies = [ + "bitflags 2.13.2", + "block2 0.6.2", + "dispatch2", + "objc2 0.6.5", + "objc2-foundation 0.3.2", +] + +[[package]] +name = "objc2-quartz-core" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e42bee7bff906b14b167da2bac5efe6b6a07e6f7c0a21a7308d40c960242dc7a" +dependencies = [ + "bitflags 2.13.2", + "block2 0.5.1", + "objc2 0.5.3", + "objc2-foundation 0.2.2", + "objc2-metal 0.2.2", +] + +[[package]] +name = "objc2-quartz-core" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96c1358452b371bf9f104e21ec536d37a650eb10f7ee379fff67d2e08d537f1f" +dependencies = [ + "bitflags 2.13.2", + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-foundation 0.3.2", + "objc2-metal 0.3.2", +] + +[[package]] +name = "objc2-screen-capture-kit" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "74b7c5390f477482f001bc354d6571a70db7e4f8d5288e860c45521fbce11394" +dependencies = [ + "bitflags 2.13.2", + "block2 0.6.2", + "dispatch2", + "libc", + "objc2 0.6.5", + "objc2-av-foundation", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-core-media", + "objc2-foundation 0.3.2", + "objc2-uniform-type-identifiers", +] + +[[package]] +name = "objc2-security" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "709fe137109bd1e8b5a99390f77a7d8b2961dafc1a1c5db8f2e60329ad6d895a" +dependencies = [ + "bitflags 2.13.2", + "objc2 0.6.5", + "objc2-core-foundation", +] + +[[package]] +name = "objc2-security-foundation" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef76382e9cedd18123099f17638715cc3d81dba3637d4c0d39ab69df2ef345a5" +dependencies = [ + "objc2 0.6.5", + "objc2-foundation 0.3.2", +] + +[[package]] +name = "objc2-system-configuration" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7216bd11cbda54ccabcab84d523dc93b858ec75ecfb3a7d89513fa22464da396" +dependencies = [ + "bitflags 2.13.2", + "dispatch2", + "libc", + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-security", +] + +[[package]] +name = "objc2-ui-kit" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d87d638e33c06f577498cbcc50491496a3ed4246998a7fbba7ccb98b1e7eab22" +dependencies = [ + "bitflags 2.13.2", + "block2 0.6.2", + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-foundation 0.3.2", + "objc2-quartz-core 0.3.2", +] + +[[package]] +name = "objc2-uniform-type-identifiers" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7902ac02859fc1f7045f8b598c63f1ae0cc7efeaa06a9bc9f3d9a3c955974fa4" +dependencies = [ + "objc2 0.6.5", + "objc2-foundation 0.3.2", +] + +[[package]] +name = "objc2-user-notifications" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9df9128cbbfef73cda168416ccf7f837b62737d748333bfe9ab71c245d76613e" +dependencies = [ + "bitflags 2.13.2", + "block2 0.6.2", + "objc2 0.6.5", + "objc2-core-location", + "objc2-foundation 0.3.2", +] + +[[package]] +name = "objc2-web-kit" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2e5aaab980c433cf470df9d7af96a7b46a9d892d521a2cbbb2f8a4c16751e7f" +dependencies = [ + "bitflags 2.13.2", + "block2 0.6.2", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "objc2-core-foundation", + "objc2-foundation 0.3.2", +] + +[[package]] +name = "objc_exception" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad970fb455818ad6cba4c122ad012fae53ae8b4795f86378bce65e4f6bab2ca4" +dependencies = [ + "cc", +] + +[[package]] +name = "object" +version = "0.40.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dd229a0361b9d0d4396176e02d65897f487eebeab7caa6d443855ee152ca0b9c" +dependencies = [ + "memchr", +] + +[[package]] +name = "ogg_pager" +version = "0.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d36b1d6964c3ac92b7aea701057e02b6b91143d70d83b20abf75a231a3c0216" +dependencies = [ + "byteorder", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "once_cell_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" + +[[package]] +name = "oneshot-fused-workaround" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "56892f7dcba21c5eb4181b8de221620855805891ee55ef960aad7cac3b5d88b2" +dependencies = [ + "futures", +] + +[[package]] +name = "oo7" +version = "0.6.0" +source = "git+https://github.com/zed-industries/oo7?rev=731c1215edb6905876c6137ab300428c7b8d7c13#731c1215edb6905876c6137ab300428c7b8d7c13" +dependencies = [ + "aes 0.8.4", + "ashpd 0.13.13", + "async-fs", + "async-io", + "async-lock", + "blocking", + "cbc", + "cipher 0.4.4", + "digest 0.10.7", + "endi", + "futures-lite", + "futures-util", + "getrandom 0.4.3", + "hkdf", + "hmac", + "md-5", + "num", + "num-bigint-dig 0.9.1", + "pbkdf2", + "serde", + "serde_bytes", + "sha2 0.10.9", + "subtle", + "zbus 5.19.0", + "zbus_macros 5.19.0", + "zeroize", + "zvariant", +] + +[[package]] +name = "opaque-debug" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381" + +[[package]] +name = "opaquerr" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4f933a4265d5cdad61d19bbdfc972ea5726d56cd8d3d57b8f2d3c365dd42bee9" + +[[package]] +name = "open" +version = "5.4.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8d8c8b8e725ad26404d6896eb2f064294a0a7b4f1d9120210d85544684c4ca95" +dependencies = [ + "is-wsl", + "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-probe" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e036b411754132fd6b74e94b74e9a13c5cf606fa93d1885c35860d3060820b1" + +[[package]] +name = "option-ext" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d" + +[[package]] +name = "opus" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33718946cc77d4032911d4efe03a66dbcbfbd2bb16c3da06aaeadcc637c32216" +dependencies = [ + "opusic-sys", +] + +[[package]] +name = "opusic-sys" +version = "0.7.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "986d749e9dc12035f11bf3ecc83a2a696ff7534d4143be9469a4a0faa25b9fd1" +dependencies = [ + "cmake", +] + +[[package]] +name = "ordered-float" +version = "2.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68f19d67e5a2795c94e73e0bb1cc1a7edeb2e28efd39e2e1c9b7a40c1108b11c" +dependencies = [ + "num-traits", +] + +[[package]] +name = "ordered-float" +version = "5.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f59006ce1e204c30956638535b74d317bca99477b9356dfaec54c37f6f600ab" +dependencies = [ + "num-traits", +] + +[[package]] +name = "ordered-stream" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9aa2b01e1d916879f73a53d01d1d6cee68adbb31d6d9177a8cfce093cced1d50" +dependencies = [ + "futures-core", + "pin-project-lite", +] + +[[package]] +name = "os_str_bytes" +version = "6.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e2355d85b9a3786f481747ced0e0ff2ba35213a1f9bd406ed906554d7af805a1" +dependencies = [ + "memchr", +] + +[[package]] +name = "p256" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9863ad85fa8f4460f9c48cb909d38a0d689dba1f6f6988a5e3e0d31071bcd4b" +dependencies = [ + "ecdsa", + "elliptic-curve", + "primeorder", + "sha2 0.10.9", +] + +[[package]] +name = "p384" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe42f1670a52a47d448f14b6a5c61dd78fce51856e68edaa38f7ae3a46b8d6b6" +dependencies = [ + "ecdsa", + "elliptic-curve", + "primeorder", + "sha2 0.10.9", +] + +[[package]] +name = "p521" +version = "0.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fc9e2161f1f215afdfce23677034ae137bbd45016a880c2eb3ba8eb95f085b2" +dependencies = [ + "base16ct 0.2.0", + "ecdsa", + "elliptic-curve", + "primeorder", + "rand_core 0.6.4", + "sha2 0.10.9", +] + +[[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 = "papaya" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da2442474a9404698c42509b8967f437249dbc7b50493e83020333d3943ec0ae" +dependencies = [ + "equivalent", + "seize", +] + +[[package]] +name = "parking" +version = "2.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f38d5652c16fde515bb1ecef450ab0f6a219d619a7274976324d5e377f7dceba" + +[[package]] +name = "parking_lot" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" +dependencies = [ + "cfg-if 1.0.5", + "libc", + "redox_syscall", + "smallvec", + "windows-link 0.2.1", +] + +[[package]] +name = "password-hash" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "346f04948ba92c43e8469c1ee6736c7563d71012b17d40745260fe106aac2166" +dependencies = [ + "base64ct", + "rand_core 0.6.4", + "subtle", +] + +[[package]] +name = "paste" +version = "1.0.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a" + +[[package]] +name = "pastey" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "35fb2e5f958ec131621fdd531e9fc186ed768cbe395337403ae56c17a74c68ec" + +[[package]] +name = "pastey" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ee67f1008b1ba2321834326597b8e186293b049a023cdef258527550b9935b4" + +[[package]] +name = "pathfinder_geometry" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b7b7e7b4ea703700ce73ebf128e1450eb69c3a8329199ffbfb9b2a0418e5ad3" +dependencies = [ + "log", + "pathfinder_simd", +] + +[[package]] +name = "pathfinder_simd" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4500030c302e4af1d423f36f3b958d1aecb6c04184356ed5a833bf6b60435777" +dependencies = [ + "rustc_version", +] + +[[package]] +name = "pbkdf2" +version = "0.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8ed6a7761f76e3b9f92dfb0a60a6a6477c61024b775147ff0973a02653abaf2" +dependencies = [ + "digest 0.10.7", + "hmac", +] + +[[package]] +name = "peeking_take_while" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19b17cddbe7ec3f8bc800887bab5e717348c95ea2ca0b1bf0837fb964dc67099" + +[[package]] +name = "pem-rfc7468" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88b39c9bfcfc231068454382784bb460aae594343fb030d46e9f50a645418412" +dependencies = [ + "base64ct", +] + +[[package]] +name = "pem-rfc7468" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6305423e0e7738146434843d1694d621cce767262b2a86910beab705e4493d9" +dependencies = [ + "base64ct", +] + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "pharos" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e9567389417feee6ce15dd6527a8a1ecac205ef62c2932bcf3d9f6fc5b78b414" +dependencies = [ + "futures", + "rustc_version", +] + +[[package]] +name = "phf" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c1562dc717473dbaa4c1f85a36410e03c047b2e7df7f45ee938fbef64ae7fadf" +dependencies = [ + "phf_macros 0.13.1", + "phf_shared 0.13.1", + "serde", +] + +[[package]] +name = "phf" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "010378780309880b08997fae13be7834dba947d36393bd372f2b1556deb2a2f6" +dependencies = [ + "phf_macros 0.14.0", + "phf_shared 0.14.0", + "serde", +] + +[[package]] +name = "phf_codegen" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "49aa7f9d80421bca176ca8dbfebe668cc7a2684708594ec9f3c0db0805d5d6e1" +dependencies = [ + "phf_generator 0.13.1", + "phf_shared 0.13.1", +] + +[[package]] +name = "phf_generator" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "135ace3a761e564ec88c03a77317a7c6b80bb7f7135ef2544dbe054243b89737" +dependencies = [ + "fastrand", + "phf_shared 0.13.1", +] + +[[package]] +name = "phf_generator" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aeb62e0959d5a1bebc965f4d15d9e2b7cea002b6b0f5ba8cde6cc26738467100" +dependencies = [ + "fastrand", + "phf_shared 0.14.0", +] + +[[package]] +name = "phf_macros" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "812f032b54b1e759ccd5f8b6677695d5268c588701effba24601f6932f8269ef" +dependencies = [ + "phf_generator 0.13.1", + "phf_shared 0.13.1", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "phf_macros" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5fa8d0ca26d424d27630da600c6624696e7dec8bf7b3b492b383c5dc49e5e085" +dependencies = [ + "phf_generator 0.14.0", + "phf_shared 0.14.0", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "phf_shared" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e57fef6bc5981e38c2ce2d63bfa546861309f875b8a75f092d1d54ae2d64f266" +dependencies = [ + "siphasher", +] + +[[package]] +name = "phf_shared" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6fd9027e2d9319be6349febd1db4e8d02aa544921200c9b777720ac34a3aa89" +dependencies = [ + "siphasher", +] + +[[package]] +name = "pico-args" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5be167a7af36ee22fe3115051bc51f6e6c7054c9348e28deb4f49bd6f705a315" + +[[package]] +name = "pin-project" +version = "1.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2466b2336ed02bcdca6b294417127b90ec92038d1d5c4fbeac971a922e0e0924" +dependencies = [ + "pin-project-internal", +] + +[[package]] +name = "pin-project-internal" +version = "1.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c96395f0a926bc13b1c17622aaddda1ecb55d49c8f1bf9777e4d877800a43f8b" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "piper" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c835479a4443ded371d6c535cbfd8d31ad92c5d23ae9770a61bc155e4992a3c1" +dependencies = [ + "atomic-waker", + "fastrand", + "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.6", +] + +[[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" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8ffb9f10fa047879315e6625af03c164b16962a5368d724ed16323b68ace47f" +dependencies = [ + "der 0.7.10", + "pkcs8 0.10.2", + "spki 0.7.3", +] + +[[package]] +name = "pkcs8" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7" +dependencies = [ + "der 0.7.10", + "spki 0.7.3", +] + +[[package]] +name = "pkcs8" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "451913da69c775a56034ea8d9003d27ee8948e12443eae7c038ba100a4f21cb7" +dependencies = [ + "der 0.8.3", + "spki 0.8.1", +] + +[[package]] +name = "pkg-config" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" + +[[package]] +name = "plist" +version = "1.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "327a4cb2ad49dc48adfdc9da89e22c64d488b508c67a044d71ba729e4521a285" +dependencies = [ + "base64 0.23.1", + "indexmap 2.14.2", + "quick-xml 0.42.0", + "serde", + "time", +] + +[[package]] +name = "png" +version = "0.17.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82151a2fc869e011c153adc57cf2789ccb8d9906ce52c0b39a6b5697749d7526" +dependencies = [ + "bitflags 1.3.2", + "crc32fast", + "fdeflate", + "flate2", + "miniz_oxide 0.8.9", +] + +[[package]] +name = "png" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61" +dependencies = [ + "bitflags 2.13.2", + "crc32fast", + "fdeflate", + "flate2", + "miniz_oxide 0.8.9", +] + +[[package]] +name = "polling" +version = "3.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d0e4f59085d47d8241c88ead0f274e8a0cb551f3625263c05eb8dd897c34218" +dependencies = [ + "cfg-if 1.0.5", + "concurrent-queue", + "hermit-abi", + "pin-project-lite", + "rustix 1.1.6", + "windows-sys 0.61.2", +] + +[[package]] +name = "pollster" +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 = "poly1305" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8159bd90725d2df49889a078b54f4f79e87f1f8a8444194cdca81d38f5393abf" +dependencies = [ + "cpufeatures 0.2.17", + "opaque-debug", + "universal-hash 0.5.1", +] + +[[package]] +name = "polycool" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "50596ddc09eb5ad5f75cacd40209568e66df71baf86e1499a0e99c4cff12a5a6" +dependencies = [ + "arrayvec", +] + +[[package]] +name = "polyval" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d1fe60d06143b2430aa532c94cfe9e29783047f06c0d7fd359a9a51b729fa25" +dependencies = [ + "cfg-if 1.0.5", + "cpufeatures 0.2.17", + "opaque-debug", + "universal-hash 0.5.1", +] + +[[package]] +name = "polyval" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0fa31d631f2b2cb2a544d0aa321ce847a94764d701ca2becc411138b93d49cd" +dependencies = [ + "cpubits", + "cpufeatures 0.3.1", + "universal-hash 0.6.1", +] + +[[package]] +name = "portable-atomic" +version = "1.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85" +dependencies = [ + "serde", +] + +[[package]] +name = "portable-atomic-util" +version = "0.2.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10ab3eb7f3becc3a1cbc4f2c6f20267996cfc1a6467a873763411b136a122715" +dependencies = [ + "portable-atomic", +] + +[[package]] +name = "postage" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af3fb618632874fb76937c2361a7f22afd393c982a2165595407edc75b06d3c1" +dependencies = [ + "atomic 0.5.3", + "crossbeam-queue", + "futures", + "parking_lot", + "pin-project", + "static_assertions", + "thiserror 1.0.69", +] + +[[package]] +name = "postcard" +version = "1.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6764c3b5dd454e283a30e6dfe78e9b31096d9e32036b5d1eaac7a6119ccb9a24" +dependencies = [ + "cobs", + "embedded-io 0.4.0", + "embedded-io 0.6.1", + "postcard-derive", + "serde", +] + +[[package]] +name = "postcard-derive" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e0232bd009a197ceec9cc881ba46f727fcd8060a2d8d6a9dde7a69030a6fe2bb" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "potential_utf" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" +dependencies = [ + "serde_core", + "writeable", + "zerovec", +] + +[[package]] +name = "powerfmt" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958" + +[[package]] +name = "ppv-lite86" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" +dependencies = [ + "zerocopy", +] + +[[package]] +name = "precomputed-hash" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "925383efa346730478fb4838dbe9137d2a47675ad789c546d150a6e1dd4ab31c" + +[[package]] +name = "presser" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e8cf8e6a8aa66ce33f63993ffc4ea4271eb5b0530a9002db8455ea6050c77bfa" + +[[package]] +name = "prettyplease" +version = "0.2.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b" +dependencies = [ + "proc-macro2", + "syn 2.0.119", +] + +[[package]] +name = "primal-check" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc0d895b311e3af9902528fbb8f928688abbd95872819320517cc24ca6b2bd08" +dependencies = [ + "num-integer", +] + +[[package]] +name = "primeorder" +version = "0.13.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "353e1ca18966c16d9deb1c69278edbc5f194139612772bd9537af60ac231e1e6" +dependencies = [ + "elliptic-curve", +] + +[[package]] +name = "priority-queue" +version = "2.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93980406f12d9f8140ed5abe7155acb10bb1e69ea55c88960b9c2f117445ef96" +dependencies = [ + "equivalent", + "indexmap 2.14.2", + "serde", +] + +[[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" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f" +dependencies = [ + "toml_edit 0.25.19+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-macro-error-attr2" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96de42df36bb9bba5542fe9f1a054b8cc87e172759a1868aa05c1f3acc89dfc5" +dependencies = [ + "proc-macro2", + "quote", +] + +[[package]] +name = "proc-macro-error2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11ec05c52be0a07b08061f7dd003e7d7092e0472bc731b4af7bb1ef876109802" +dependencies = [ + "proc-macro-error-attr2", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "profiling" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d595e54a326bc53c1c197b32d295e14b169e3cfeaa8dc82b529f947fba6bcf5" +dependencies = [ + "profiling-procmacros", +] + +[[package]] +name = "profiling-procmacros" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4488a4a36b9a4ba6b9334a32a39971f77c1436ec82c38707bce707699cc3bbcb" +dependencies = [ + "quote", + "syn 2.0.119", +] + +[[package]] +name = "pulldown-cmark" +version = "0.13.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3db2be46835f013dd3f4fa7f5f7402c537787b54ebb6fe2b94bbdd7e2669bb7b" +dependencies = [ + "bitflags 2.13.2", + "memchr", + "unicase", +] + +[[package]] +name = "pwd-grp" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e2023f41b5fcb7c30eb5300a5733edfaa9e0e0d502d51b586f65633fd39e40c" +dependencies = [ + "derive-deftly", + "libc", + "paste", + "thiserror 2.0.21", +] + +[[package]] +name = "pxfm" +version = "0.1.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea" + +[[package]] +name = "qoi" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f6d64c71eb498fe9eae14ce4ec935c555749aef511cca85b5568910d6e48001" +dependencies = [ + "bytemuck", +] + +[[package]] +name = "qrcodegen" +version = "1.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4339fc7a1021c9c1621d87f5e3505f2805c8c105420ba2f2a4df86814590c142" + +[[package]] +name = "quick-error" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3" + +[[package]] +name = "quick-xml" +version = "0.41.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e660451e55124f798a69a5af3f49ccfbefbd41910eefd25caf2393e1f3473ec1" +dependencies = [ + "memchr", +] + +[[package]] +name = "quick-xml" +version = "0.42.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41b1177fdf999d2321d3fb46ff47159d9c1fb9ad66a4879f8c50a0b504615e9b" +dependencies = [ + "memchr", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "radium" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc33ff2d4973d518d823d61aa239014831e521c75da58e3df4840d3f47749d09" + +[[package]] +name = "rand" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e058c7de0b26af77780c769414d6257830bb240f3c38477dbc2c16e5f54d6d4c" +dependencies = [ + "libc", + "rand_chacha 0.3.1", + "rand_core 0.6.4", +] + +[[package]] +name = "rand" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41" +dependencies = [ + "rand_chacha 0.9.0", + "rand_core 0.9.5", +] + +[[package]] +name = "rand" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af" +dependencies = [ + "chacha20 0.10.2", + "getrandom 0.4.3", + "rand_core 0.10.1", +] + +[[package]] +name = "rand_chacha" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" +dependencies = [ + "ppv-lite86", + "rand_core 0.6.4", +] + +[[package]] +name = "rand_chacha" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" +dependencies = [ + "ppv-lite86", + "rand_core 0.9.5", +] + +[[package]] +name = "rand_chacha" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3e6af7f3e25ded52c41df4e0b1af2d047e45896c2f3281792ed68a1c243daedb" +dependencies = [ + "ppv-lite86", + "rand_core 0.10.1", +] + +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" +dependencies = [ + "getrandom 0.2.17", +] + +[[package]] +name = "rand_core" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c" +dependencies = [ + "getrandom 0.3.4", +] + +[[package]] +name = "rand_core" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" + +[[package]] +name = "rand_jitter" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3fdcd80e68f0a8f9ca5ec7cfd02fd5fbb8fbe6ef4e9b90ea2f48bb929b74f88e" +dependencies = [ + "libc", + "rand_core 0.10.1", + "windows-sys 0.59.0", +] + +[[package]] +name = "rand_pcg" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "caa0f4137e1c0a72f4c651489402276c8e8e1cf081f3b0ba156d2cbeef09e86a" +dependencies = [ + "rand_core 0.10.1", +] + +[[package]] +name = "range-alloc" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca45419789ae5a7899559e9512e58ca889e41f04f1f2445e9f4b290ceccd1d08" + +[[package]] +name = "rangemap" +version = "1.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a611d15b50743feb4c76b7d03edcb0e64f399c26961e4efe6975bc398be6aa3d" + +[[package]] +name = "rav1e" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "43b6dd56e85d9483277cde964fd1bdb0428de4fec5ebba7540995639a21cb32b" +dependencies = [ + "aligned-vec", + "arbitrary", + "arg_enum_proc_macro", + "arrayvec", + "av-scenechange", + "av1-grain", + "bitstream-io", + "built", + "cfg-if 1.0.5", + "interpolate_name", + "itertools 0.14.0", + "libc", + "libfuzzer-sys", + "log", + "maybe-rayon", + "new_debug_unreachable", + "noop_proc_macro", + "num-derive", + "num-traits", + "paste", + "profiling", + "rand 0.9.5", + "rand_chacha 0.9.0", + "simd_helpers", + "thiserror 2.0.21", + "v_frame", + "wasm-bindgen", +] + +[[package]] +name = "ravif" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e52310197d971b0f5be7fe6b57530dcd27beb35c1b013f29d66c1ad73fbbcc45" +dependencies = [ + "avif-serialize", + "imgref", + "loop9", + "quick-error", + "rav1e", + "rayon", + "rgb", +] + +[[package]] +name = "raw-window-handle" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20675572f6f24e9e76ef639bc5552774ed45f1c30e2951e1e99c59888861c539" + +[[package]] +name = "raw-window-metal" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40d213455a5f1dc59214213c7330e074ddf8114c9a42411eb890c767357ce135" +dependencies = [ + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-foundation 0.3.2", + "objc2-quartz-core 0.3.2", +] + +[[package]] +name = "rayon" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fb39b166781f92d482534ef4b4b1b2568f42613b53e5b6c160e24cfbfa30926d" +dependencies = [ + "either", + "rayon-core", +] + +[[package]] +name = "rayon-core" +version = "1.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91" +dependencies = [ + "crossbeam-deque", + "crossbeam-utils", +] + +[[package]] +name = "rdrand" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "84448986e59427c795b929d8dbe12d176275c7d0887ee48098c35b7206f51bae" +dependencies = [ + "libc", + "rand_core 0.10.1", +] + +[[package]] +name = "read-fonts" +version = "0.37.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b634fabf032fab15307ffd272149b622260f55974d9fad689292a5d33df02e5" +dependencies = [ + "bytemuck", + "core_maths", + "font-types 0.11.3", +] + +[[package]] +name = "read-fonts" +version = "0.41.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "046a7d674daf459825b32f5062056d6882db0d2f5a479fbd76ccfc870ac18709" +dependencies = [ + "bytemuck", + "font-types 0.12.7", + "once_cell", +] + +[[package]] +name = "redox_syscall" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +dependencies = [ + "bitflags 2.13.2", +] + +[[package]] +name = "redox_users" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60dc65c0ff1a7ae1294b0c67b9f14baf70b644404010370171787bfac1038fc0" +dependencies = [ + "libredox", + "thiserror 2.0.21", +] + +[[package]] +name = "ref-cast" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e440fb4e4b4147295338efb76001ab9e4efc0e5839df2c47fc5ac2381d365c3" +dependencies = [ + "ref-cast-impl", +] + +[[package]] +name = "ref-cast-impl" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92ecd8964f8453721699a1ed72037b0db49ce2f5a5138486ee89bed6f67cdf3a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "refineable" +version = "0.1.0" +source = "git+https://github.com/zed-industries/zed?rev=f8cfc7ed9e57503def9479138894f3139f5400cc#f8cfc7ed9e57503def9479138894f3139f5400cc" +dependencies = [ + "derive_refineable", +] + +[[package]] +name = "regex" +version = "1.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" + +[[package]] +name = "renderdoc-sys" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19b30a45b0cd0bcca8037f3d0dc3421eaf95327a17cad11964fb8179b4fc4832" + +[[package]] +name = "reqwest" +version = "0.13.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "16a1cfa75cc186dd73d5818e510e042e40927bccc9c236b061cea97e1eb08029" +dependencies = [ + "base64 0.23.1", + "bytes", + "encoding_rs", + "futures-core", + "futures-util", + "h2", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-rustls", + "hyper-util", + "js-sys", + "log", + "mime", + "percent-encoding", + "pin-project-lite", + "rustls", + "rustls-pki-types", + "rustls-platform-verifier", + "serde", + "serde_json", + "sync_wrapper", + "tokio", + "tokio-rustls", + "tokio-util", + "tower", + "tower-http", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "wasm-streams", + "web-sys", +] + +[[package]] +name = "reseeding_rng" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ecfc8e855ab517235426ec1290bfb0745e73fa478b29619eb66a2a81be9d8716" +dependencies = [ + "rand_core 0.10.1", +] + +[[package]] +name = "resvg" +version = "0.46.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b563218631706d614e23059436526d005b50ab5f2d506b55a17eb65c5eb83419" +dependencies = [ + "gif", + "image-webp", + "log", + "pico-args", + "rgb", + "svgtypes", + "tiny-skia 0.11.4", + "usvg 0.46.0", + "zune-jpeg", +] + +[[package]] +name = "resvg" +version = "0.48.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67e3803f97b999e80cbf7c6ecdd07a8102204d92e1633cf48783720c521196bd" +dependencies = [ + "bytemuck", + "gif", + "image-webp", + "log", + "pico-args", + "rgb", + "svgtypes", + "tiny-skia 0.12.0", + "usvg 0.48.1", + "zune-jpeg", +] + +[[package]] +name = "retry-error" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d350ad359aca3414f7261cdcc763e37ccc9fa56fe40ca30a9758c28a295bcad0" +dependencies = [ + "humantime", + "web-time", +] + +[[package]] +name = "rfc6979" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dd2a808d456c4a54e300a23e9f5a67e122c3024119acbfd73e3bf664491cb2" +dependencies = [ + "hmac", + "subtle", +] + +[[package]] +name = "rgb" +version = "0.8.53" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47b34b781b31e5d73e9fbc8689c70551fd1ade9a19e3e28cfec8580a79290cc4" +dependencies = [ + "bytemuck", +] + +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if 1.0.5", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + +[[package]] +name = "rle-decode-fast" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3582f63211428f83597b51b2ddb88e2a91a9d52d12831f9d08f5e624e8977422" + +[[package]] +name = "roxmltree" +version = "0.20.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c20b6793b5c2fa6553b250154b78d6d0db37e72700ae35fad9387a46f487c97" + +[[package]] +name = "roxmltree" +version = "0.21.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9da7f59328b09405b181fee1018925fad50f157afb43c0c0f5c522c256dd5907" +dependencies = [ + "memchr", +] + +[[package]] +name = "rqrr" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8d084c50c5cfa397a081850da329566c8667b0b6c4e81da16abff1fef27de93b" +dependencies = [ + "g2p", + "lru", +] + +[[package]] +name = "rsa" +version = "0.9.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8573f03f5883dcaebdfcf4725caa1ecb9c15b2ef50c43a07b816e06799bb12d" +dependencies = [ + "const-oid 0.9.6", + "digest 0.10.7", + "num-bigint-dig 0.8.6", + "num-integer", + "num-traits", + "pkcs1", + "pkcs8 0.10.2", + "rand_core 0.6.4", + "sha2 0.10.9", + "signature 2.2.0", + "spki 0.7.3", + "subtle", + "zeroize", +] + +[[package]] +name = "rsqlite-vfs" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c51c9ae4df8a7fba42103df5c621fa3c37eccf3a3c650879e90fc48b11cc192c" +dependencies = [ + "hashbrown 0.16.1", + "thiserror 2.0.21", +] + +[[package]] +name = "rusqlite" +version = "0.38.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1c93dd1c9683b438c392c492109cb702b8090b2bfc8fed6f6e4eb4523f17af3" +dependencies = [ + "bitflags 2.13.2", + "fallible-iterator", + "fallible-streaming-iterator", + "hashlink", + "libsqlite3-sys", + "smallvec", + "sqlite-wasm-rs", + "time", +] + +[[package]] +name = "rust-embed" +version = "8.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19afa5b4b6a611de00bd1bdae6ae6f39084c9399f0679c3f52d8469cf335cc23" +dependencies = [ + "rust-embed-impl", + "rust-embed-utils", + "walkdir", +] + +[[package]] +name = "rust-embed-impl" +version = "8.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e0d8afda6374eac59e066abee06d265247ebbaf3006cf878e2879e8356e34053" +dependencies = [ + "mime_guess", + "proc-macro2", + "quote", + "rust-embed-utils", + "shellexpand", + "syn 2.0.119", + "walkdir", +] + +[[package]] +name = "rust-embed-utils" +version = "8.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d84e8ba78bd384263e5922f084cbe1b081c3b7e69add59c8fb097b879ba968a" +dependencies = [ + "sha2 0.11.1", + "walkdir", +] + +[[package]] +name = "rustc-demangle" +version = "0.1.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b74b56ffa8bb2830709a538c2cbcae9aa062db0d2a42563bfb09bdaae44020eb" + +[[package]] +name = "rustc-hash" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2" + +[[package]] +name = "rustc-hash" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" + +[[package]] +name = "rustc_version" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" +dependencies = [ + "semver", +] + +[[package]] +name = "rustfft" +version = "6.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "21db5f9893e91f41798c88680037dba611ca6674703c1a18601b01a72c8adb89" +dependencies = [ + "num-complex", + "num-integer", + "num-traits", + "primal-check", + "strength_reduce", + "transpose", +] + +[[package]] +name = "rusticata-macros" +version = "4.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "faf0c4a6ece9950b9abdb62b1cfcf2a68b3b67a10ba445b3bb85be2a293d0632" +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.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" +dependencies = [ + "bitflags 2.13.2", + "errno", + "libc", + "linux-raw-sys 0.12.1", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustls" +version = "0.23.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" +dependencies = [ + "log", + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-native-certs" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a073f5dc7469f984c52ad2752b63b0807745133b6de880b7b64c1ac4c48aec4" +dependencies = [ + "openssl-probe", + "rustls-pki-types", + "schannel", + "security-framework", +] + +[[package]] +name = "rustls-pki-types" +version = "1.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "102f35f7de7b06d8c61f1cff6592f5253e0dea431c74867aad5dfd70f44663fb" +dependencies = [ + "web-time", + "zeroize", +] + +[[package]] +name = "rustls-platform-verifier" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1167586491e2b18b8bfbb293e8180ec17c201c4f076d7cb3070ca964e7598f98" +dependencies = [ + "core-foundation 0.10.1", + "core-foundation-sys 0.8.7", + "jni 0.22.4", + "log", + "once_cell", + "rustls", + "rustls-native-certs", + "rustls-platform-verifier-android", + "rustls-webpki", + "security-framework", + "security-framework-sys", + "webpki-root-certs", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustls-platform-verifier-android" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eec689c0bc40ff2458a5977b6619cb718087084a18e02a131c599b62d05e1a5f" + +[[package]] +name = "rustls-webpki" +version = "0.103.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4443b1b6d39d7c663139942cc4558262562d2c84123bb6282ef177009ca8b281" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "rustybuzz" +version = "0.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd3c7c96f8a08ee34eff8857b11b49b07d71d1c3f4e88f8a88d4c9e9f90b1702" +dependencies = [ + "bitflags 2.13.2", + "bytemuck", + "core_maths", + "log", + "smallvec", + "ttf-parser", + "unicode-bidi-mirroring", + "unicode-ccc", + "unicode-properties", + "unicode-script", +] + +[[package]] +name = "ryu" +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 = "safelog" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73ef1d6e273fc8ce5cc1376cf498c06d23b786e80e4a7679a643bb0a838b0029" +dependencies = [ + "derive_more", + "educe", + "either", + "fluid-let", + "thiserror 2.0.21", +] + +[[package]] +name = "same-file" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "sanitize-filename" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc984f4f9ceb736a7bb755c3e3bd17dc56370af2600c9780dcc48c66453da34d" +dependencies = [ + "regex", +] + +[[package]] +name = "saturating-time" +version = "0.4.0" + +[[package]] +name = "schannel" +version = "0.1.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9cb23c424d8ee841bb4d813677ca237e2a610067d594fec130f87d6093495ab5" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "scheduler" +version = "0.1.0" +source = "git+https://github.com/zed-industries/zed?rev=f8cfc7ed9e57503def9479138894f3139f5400cc#f8cfc7ed9e57503def9479138894f3139f5400cc" +dependencies = [ + "async-task", + "backtrace", + "chrono", + "flume 0.12.0", + "futures", + "parking_lot", + "rand 0.9.5", + "web-time", +] + +[[package]] +name = "schemars" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cd191f9397d57d581cddd31014772520aa448f65ef991055d7f61582c65165f" +dependencies = [ + "dyn-clone", + "ref-cast", + "serde", + "serde_json", +] + +[[package]] +name = "schemars" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab508826f74a77ca9d5aba6ff19b522583ee3eaf28a19384ff3d0e5835fadf6e" +dependencies = [ + "dyn-clone", + "indexmap 2.14.2", + "ref-cast", + "schemars_derive", + "serde", + "serde_json", +] + +[[package]] +name = "schemars_derive" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1c3a92094fa7d61aa124645844facb6b554dfc797136d0f5fd1f890e2bffc69" +dependencies = [ + "proc-macro2", + "quote", + "serde_derive_internals", + "syn 3.0.10", +] + +[[package]] +name = "scoped-tls" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1cf6437eb19a8f4a6cc0f7dca544973b0b78843adbfeb3683d1a94a0024a294" + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "seahash" +version = "4.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c107b6f4780854c8b126e228ea8869f4d7b71260f962fefb57b996b8959ba6b" + +[[package]] +name = "sec1" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3e97a565f76233a6003f9f5c54be1d9c5bdfa3eccfb189469f11ec4901c47dc" +dependencies = [ + "base16ct 0.2.0", + "der 0.7.10", + "generic-array", + "pkcs8 0.10.2", + "subtle", + "zeroize", +] + +[[package]] +name = "secp256k1" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b50c5943d326858130af85e049f2661ba3c78b26589b8ab98e65e80ae44a1252" +dependencies = [ + "bitcoin_hashes 0.14.101", + "rand 0.8.8", + "secp256k1-sys", +] + +[[package]] +name = "secp256k1-sys" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4387882333d3aa8cb20530a17c69a3752e97837832f34f6dccc760e715001d9" +dependencies = [ + "cc", +] + +[[package]] +name = "security-framework" +version = "3.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d" +dependencies = [ + "bitflags 2.13.2", + "core-foundation 0.10.1", + "core-foundation-sys 0.8.7", + "libc", + "security-framework-sys", +] + +[[package]] +name = "security-framework-sys" +version = "2.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3" +dependencies = [ + "core-foundation-sys 0.8.7", + "libc", +] + +[[package]] +name = "seize" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5b55fb86dfd3a2f5f76ea78310a88f96c4ea21a3031f8d212443d56123fd0521" + +[[package]] +name = "selectors" +version = "0.38.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8adfa1c298912827b8a28b223b3b874357397ae706e6190acd9bf28cee99114d" +dependencies = [ + "bitflags 2.13.2", + "cssparser", + "derive_more", + "log", + "new_debug_unreachable", + "phf 0.13.1", + "phf_codegen", + "precomputed-hash", + "rustc-hash 2.1.3", + "servo_arc", + "smallvec", +] + +[[package]] +name = "self_cell" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ab42ca02749e120097e328d91d415325bdf43b1c72c4c8badf37375fe40a813" + +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" +dependencies = [ + "serde", + "serde_core", +] + +[[package]] +name = "send_wrapper" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd0b0ec5f1c1ca621c432a25813d8d60c88abe6d3e08a3eb9cf37d97a0fe3d73" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde-value" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3a1a3341211875ef120e117ea7fd5228530ae7e7036a779fdc9117be6b3282c" +dependencies = [ + "ordered-float 2.10.1", + "serde", +] + +[[package]] +name = "serde_bytes" +version = "0.11.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5d440709e79d88e51ac01c4b72fc6cb7314017bb7da9eeff678aa94c10e3ea8" +dependencies = [ + "serde", + "serde_core", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "serde_derive_internals" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f852137cce035d6a4df67ccce505ff6b3e9fd3a10e3e52b24dc71e650bb1a9bd" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "serde_ignored" +version = "0.1.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "115dffd5f3853e06e746965a20dcbae6ee747ae30b543d91b0e089668bb07798" +dependencies = [ + "serde", + "serde_core", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "foldhash 0.2.0", + "indexmap 2.14.2", + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_repr" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8d3b1629de253c70a0508c3899572da79ca359fdab27c7920ff00406df418906" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "serde_spanned" +version = "0.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf41e0cfaf7226dca15e8197172c295a782857fcb97fad1808a166870dee75a3" +dependencies = [ + "serde", +] + +[[package]] +name = "serde_spanned" +version = "1.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c187e0a369471c550af028cba56d4f4fa2a489ad28151ae95a4d340a2a8b782" +dependencies = [ + "serde_core", +] + +[[package]] +name = "serde_urlencoded" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" +dependencies = [ + "form_urlencoded", + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "serde_with" +version = "3.24.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df9adc193c780ef8f159aee8b61e2d5801aaa555e6eb0947fe45530ec506296f" +dependencies = [ + "base64 0.23.1", + "bs58", + "chrono", + "hex", + "indexmap 1.9.3", + "indexmap 2.14.2", + "jiff", + "schemars 0.9.0", + "schemars 1.2.3", + "serde_core", + "serde_json", + "serde_with_macros", + "time", +] + +[[package]] +name = "serde_with_macros" +version = "3.24.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3e17bbc68e28663bbbb90df47e058aa7eda4fb445b89fe70457bb94fbccf6e49" +dependencies = [ + "darling 0.24.1", + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "serdect" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "66cf8fedced2fcf12406bcb34223dffb92eaf34908ede12fed414c82b7f00b3e" +dependencies = [ + "base16ct 1.0.0", + "serde", +] + +[[package]] +name = "servo_arc" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "170fb83ab34de17dc69aa7c67482b22218ddb85da56546f9bd6b929e32a05930" +dependencies = [ + "stable_deref_trait", +] + +[[package]] +name = "sha1" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8" +dependencies = [ + "cfg-if 1.0.5", + "cpufeatures 0.2.17", + "digest 0.10.7", +] + +[[package]] +name = "sha1_smol" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbfa15b3dddfee50a0fff136974b3e1bde555604ba463834a7eb7deb6417705d" + +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if 1.0.5", + "cpufeatures 0.2.17", + "digest 0.10.7", +] + +[[package]] +name = "sha2" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d7069beb7d6ac7b9acd1039986e73443f24234f41074da099d6f994ac9ad19" +dependencies = [ + "cfg-if 1.0.5", + "cpufeatures 0.3.1", + "digest 0.11.3", +] + +[[package]] +name = "sha3" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77fd7028345d415a4034cf8777cd4f8ab1851274233b45f84e3d955502d93874" +dependencies = [ + "digest 0.10.7", + "keccak 0.1.6", +] + +[[package]] +name = "sha3" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc9bad02c26382724b2d2692c6f179285e4b54eeecd7968f52a50059c3c11759" +dependencies = [ + "digest 0.11.3", + "keccak 0.2.2", + "sponge-cursor", +] + +[[package]] +name = "sharded-slab" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6" +dependencies = [ + "lazy_static", +] + +[[package]] +name = "shellexpand" +version = "3.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32824fab5e16e6c4d86dc1ba84489390419a39f97699852b66480bb87d297ed8" +dependencies = [ + "bstr", + "dirs 6.0.0", + "os_str_bytes", +] + +[[package]] +name = "shlex" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "signal-hook-registry" +version = "1.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +dependencies = [ + "errno", + "libc", +] + +[[package]] +name = "signature" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de" +dependencies = [ + "digest 0.10.7", + "rand_core 0.6.4", +] + +[[package]] +name = "signature" +version = "3.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "28d567dcbaf0049cb8ac2608a76cd95ff9e4412e1899d389ee400918ca7537f5" +dependencies = [ + "rand_core 0.10.1", +] + +[[package]] +name = "simd-adler32" +version = "0.3.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" + +[[package]] +name = "simd_cesu8" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11031e251abf8611c80f460e19dbdeb54a66db918e49c65a7065b46ac7aec520" +dependencies = [ + "rustc_version", + "simdutf8", +] + +[[package]] +name = "simd_helpers" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95890f873bec569a0362c235787f3aca6e1e887302ba4840839bcc6459c42da6" +dependencies = [ + "quote", +] + +[[package]] +name = "simdutf8" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" + +[[package]] +name = "simple-dns" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b6f884fa9a8d48101774bfbd3aeb81e968dd22cffd19a372da69f183db22c1a" +dependencies = [ + "bitflags 2.13.2", +] + +[[package]] +name = "simplecss" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a9c6883ca9c3c7c90e888de77b7a5c849c779d25d74a1269b0218b14e8b136c" +dependencies = [ + "log", +] + +[[package]] +name = "siphasher" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33f4fe9184a62d842c9ef383018f3306d8ba224fd9d836f56d7288308847c256" + +[[package]] +name = "skrifa" +version = "0.40.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7fbdfe3d2475fbd7ddd1f3e5cf8288a30eb3e5f95832829570cd88115a7434ac" +dependencies = [ + "bytemuck", + "read-fonts 0.37.0", +] + +[[package]] +name = "skrifa" +version = "0.44.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "819ab7d62b1d3e72d9d9dea5650bac30424f9111364bb94928dbf5ecad1baa68" +dependencies = [ + "bytemuck", + "read-fonts 0.41.0", +] + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "slotmap" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bdd58c3c93c3d278ca835519292445cb4b0d4dc59ccfdf7ceadaab3f8aeb4038" +dependencies = [ + "serde", + "version_check", +] + +[[package]] +name = "slotmap-careful" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba7bcbd01d9b495f4509e74f660ebaf3315219b2f8a81753667ee7d6d8a199ac" +dependencies = [ + "paste", + "serde", + "slotmap", + "thiserror 2.0.21", + "void", +] + +[[package]] +name = "smallvec" +version = "1.16.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "149309498a5f7334b12ddae0cad8aba81ce785fe91755068867e017cf98fee46" + +[[package]] +name = "smol" +version = "2.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a33bd3e260892199c3ccfc487c88b2da2265080acb316cd920da72fdfd7c599f" +dependencies = [ + "async-channel", + "async-executor", + "async-fs", + "async-io", + "async-lock", + "async-net", + "async-process", + "blocking", + "futures-lite", +] + +[[package]] +name = "smol_str" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eeb7109d23f319619d4cc0de5464613c8b7b1a09db2774a58101459cf6be2f10" +dependencies = [ + "serde_core", +] + +[[package]] +name = "socket2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "sorted-index-buffer" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea06cc588e43c632923a55450401b8f25e628131571d4e1baea1bdfdb2b5ed06" + +[[package]] +name = "soup3" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "471f924a40f31251afc77450e781cb26d55c0b650842efafc9c6cbd2f7cc4f9f" +dependencies = [ + "futures-channel", + "gio", + "glib", + "libc", + "soup3-sys", +] + +[[package]] +name = "soup3-sys" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ebe8950a680a12f24f15ebe1bf70db7af98ad242d9db43596ad3108aab86c27" +dependencies = [ + "gio-sys", + "glib-sys", + "gobject-sys", + "libc", + "system-deps 6.2.2", +] + +[[package]] +name = "spake2" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c5482afe85a0b6ce956c945401598dbc527593c77ba51d0a87a586938b1b893a" +dependencies = [ + "curve25519-dalek 4.1.3", + "hkdf", + "rand_core 0.6.4", + "sha2 0.10.9", +] + +[[package]] +name = "spez" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c87e960f4dca2788eeb86bbdde8dd246be8948790b7618d656e68f9b720a86e8" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "spin" +version = "0.9.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3763264f6b73151db08c50ff20d7d8a0b8796e021cdea7ceedad07b80155fa0e" +dependencies = [ + "lock_api", +] + +[[package]] +name = "spin" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "023a211cb3138dbc438680b32560ad89f699977624c9f8dbb95a47d5b4c07dd3" +dependencies = [ + "lock_api", +] + +[[package]] +name = "spirv" +version = "0.4.0+sdk-1.4.341.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9571ea910ebd84c86af4b3ed27f9dbdc6ad06f17c5f96146b2b671e2976744f" +dependencies = [ + "bitflags 2.13.2", +] + +[[package]] +name = "spki" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d" +dependencies = [ + "base64ct", + "der 0.7.10", +] + +[[package]] +name = "spki" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ef958a98b9d5da290cfc78946e9f3e61e1e62a18db0d92cac0b83cc161491a9" +dependencies = [ + "base64ct", + "der 0.8.3", +] + +[[package]] +name = "sponge-cursor" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a0219bd7d979d58245a4f41f695e1ac9f8befdffadd7f61f1bae9e39abc6620" + +[[package]] +name = "sqlite-wasm-rs" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc3efc0da82635d7e1ced0053bbbfa8c7ab9645d0bf36ceb4f7127bb85315d75" +dependencies = [ + "cc", + "js-sys", + "rsqlite-vfs", + "wasm-bindgen", +] + +[[package]] +name = "ssh-cipher-fork-arti" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "125c5795103fc93fced42d123c8044180afc55469caa1ab56487c3c5543c898d" +dependencies = [ + "cipher 0.4.4", + "ssh-encoding-fork-arti", +] + +[[package]] +name = "ssh-encoding-fork-arti" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e0cf03c3a7ea88451ff83a129a79451fd9891d44fc76c25e916a11848b81814c" +dependencies = [ + "base64ct", + "pem-rfc7468 0.7.0", + "sha2 0.10.9", +] + +[[package]] +name = "ssh-key-fork-arti" +version = "0.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "433782176b73ea7907763dc314c4a17438a231864d4aa683ba47c07c1cf0a388" +dependencies = [ + "num-bigint-dig 0.8.6", + "p256", + "p384", + "p521", + "rand_core 0.6.4", + "rsa", + "sec1", + "sha2 0.10.9", + "signature 2.2.0", + "ssh-cipher-fork-arti", + "ssh-encoding-fork-arti", + "subtle", + "zeroize", +] + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "static_assertions" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" + +[[package]] +name = "strength_reduce" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe895eb47f22e2ddd4dabc02bce419d2e643c8e3b585c78158b349195bc24d82" + +[[package]] +name = "strict-num" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6637bab7722d379c8b41ba849228d680cc12d0a45ba1fa2b48f2a30577a06731" +dependencies = [ + "float-cmp", +] + +[[package]] +name = "string-interner" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91e2531d8525b29b514d25e275a43581320d587b86db302b9a7e464bac579648" +dependencies = [ + "cfg-if 1.0.5", + "hashbrown 0.11.2", +] + +[[package]] +name = "string_cache" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a18596f8c785a729f2819c0f6a7eae6ebeebdfffbfe4214ae6b087f690e31901" +dependencies = [ + "new_debug_unreachable", + "parking_lot", + "phf_shared 0.13.1", + "precomputed-hash", +] + +[[package]] +name = "string_cache_codegen" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "585635e46db231059f76c5849798146164652513eb9e8ab2685939dd90f29b69" +dependencies = [ + "phf_generator 0.13.1", + "phf_shared 0.13.1", + "proc-macro2", + "quote", +] + +[[package]] +name = "strsim" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623" + +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + +[[package]] +name = "strum" +version = "0.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9628de9b8791db39ceda2b119bbe13134770b56c138ec1d3af810d045c04f9bd" +dependencies = [ + "strum_macros", +] + +[[package]] +name = "strum_macros" +version = "0.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab85eea0270ee17587ed4156089e10b9e6880ee688791d45a905f5b1ca36f664" +dependencies = [ + "heck 0.5.0", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "sum_tree" +version = "0.1.0" +source = "git+https://github.com/zed-industries/zed?rev=f8cfc7ed9e57503def9479138894f3139f5400cc#f8cfc7ed9e57503def9479138894f3139f5400cc" +dependencies = [ + "heapless 0.9.3", + "rayon", + "tracing", + "ztracing", +] + +[[package]] +name = "svg_fmt" +version = "0.4.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0193cc4331cfd2f3d2011ef287590868599a2f33c3e69bc22c1a3d3acf9e02fb" + +[[package]] +name = "svgtypes" +version = "0.16.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f12b12995e3638c70618c1facb1ce65302f6a6f706b675f07c58a5d7391120e" +dependencies = [ + "kurbo", + "siphasher", +] + +[[package]] +name = "swash" +version = "0.2.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c2499c2d826531388872b2268718aed907a39bd785ab0dcfe57fab26283f92e" +dependencies = [ + "skrifa 0.44.0", + "yazi", + "zeno", +] + +[[package]] +name = "symphonia" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5773a4c030a19d9bfaa090f49746ff35c75dfddfa700df7a5939d5e076a57039" +dependencies = [ + "lazy_static", + "symphonia-bundle-flac", + "symphonia-bundle-mp3", + "symphonia-codec-aac", + "symphonia-codec-pcm", + "symphonia-codec-vorbis", + "symphonia-core", + "symphonia-format-isomp4", + "symphonia-format-ogg", + "symphonia-format-riff", + "symphonia-metadata", +] + +[[package]] +name = "symphonia-bundle-flac" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c91565e180aea25d9b80a910c546802526ffd0072d0b8974e3ebe59b686c9976" +dependencies = [ + "log", + "symphonia-core", + "symphonia-metadata", + "symphonia-utils-xiph", +] + +[[package]] +name = "symphonia-bundle-mp3" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4872dd6bb56bf5eac799e3e957aa1981086c3e613b27e0ac23b176054f7c57ed" +dependencies = [ + "lazy_static", + "log", + "symphonia-core", + "symphonia-metadata", +] + +[[package]] +name = "symphonia-codec-aac" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c263845aa86881416849c1729a54c7f55164f8b96111dba59de46849e73a790" +dependencies = [ + "lazy_static", + "log", + "symphonia-core", +] + +[[package]] +name = "symphonia-codec-pcm" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e89d716c01541ad3ebe7c91ce4c8d38a7cf266a3f7b2f090b108fb0cb031d95" +dependencies = [ + "log", + "symphonia-core", +] + +[[package]] +name = "symphonia-codec-vorbis" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f025837c309cd69ffef572750b4a2257b59552c5399a5e49707cc5b1b85d1c73" +dependencies = [ + "log", + "symphonia-core", + "symphonia-utils-xiph", +] + +[[package]] +name = "symphonia-core" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea00cc4f79b7f6bb7ff87eddc065a1066f3a43fe1875979056672c9ef948c2af" +dependencies = [ + "arrayvec", + "bitflags 1.3.2", + "bytemuck", + "lazy_static", + "log", + "rustfft", +] + +[[package]] +name = "symphonia-format-isomp4" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "243739585d11f81daf8dac8d9f3d18cc7898f6c09a259675fc364b382c30e0a5" +dependencies = [ + "encoding_rs", + "log", + "symphonia-core", + "symphonia-metadata", + "symphonia-utils-xiph", +] + +[[package]] +name = "symphonia-format-ogg" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b4955c67c1ed3aa8ae8428d04ca8397fbef6a19b2b051e73b5da8b1435639cb" +dependencies = [ + "log", + "symphonia-core", + "symphonia-metadata", + "symphonia-utils-xiph", +] + +[[package]] +name = "symphonia-format-riff" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2d7c3df0e7d94efb68401d81906eae73c02b40d5ec1a141962c592d0f11a96f" +dependencies = [ + "extended", + "log", + "symphonia-core", + "symphonia-metadata", +] + +[[package]] +name = "symphonia-metadata" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "36306ff42b9ffe6e5afc99d49e121e0bd62fe79b9db7b9681d48e29fa19e6b16" +dependencies = [ + "encoding_rs", + "lazy_static", + "log", + "symphonia-core", +] + +[[package]] +name = "symphonia-utils-xiph" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee27c85ab799a338446b68eec77abf42e1a6f1bb490656e121c6e27bfbab9f16" +dependencies = [ + "symphonia-core", + "symphonia-metadata", +] + +[[package]] +name = "syn" +version = "1.0.109" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "sync_wrapper" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" +dependencies = [ + "futures-core", +] + +[[package]] +name = "synstructure" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "synstructure" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "sys-locale" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8eab9a99a024a169fe8a903cf9d4a3b3601109bcc13bd9e3c6fff259138626c4" +dependencies = [ + "libc", +] + +[[package]] +name = "sysinfo" +version = "0.31.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "355dbe4f8799b304b05e1b0f05fc59b2a18d36645cf169607da45bde2f69a1be" +dependencies = [ + "core-foundation-sys 0.8.7", + "libc", + "memchr", + "ntapi", + "rayon", + "windows 0.57.0", +] + +[[package]] +name = "sysinfo" +version = "0.38.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92ab6a2f8bfe508deb3c6406578252e491d299cbbf3bc0529ecc3313aee4a52f" +dependencies = [ + "libc", + "memchr", + "ntapi", + "objc2-core-foundation", + "objc2-io-kit", + "windows 0.62.2", +] + +[[package]] +name = "system-configuration" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "501336eb7ba9e417300a6a0fa985721065467aa83a6dcf0422a8e43e4c0328fa" +dependencies = [ + "bitflags 2.13.2", + "core-foundation 0.10.1", + "system-configuration-sys", +] + +[[package]] +name = "system-configuration-sys" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e1d1b10ced5ca923a1fcb8d03e96b8d3268065d724548c0211415ff6ac6bac4" +dependencies = [ + "core-foundation-sys 0.8.7", + "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.10", + "heck 0.5.0", + "pkg-config", + "toml 1.2.1+spec-1.1.0", + "version-compare", +] + +[[package]] +name = "taffy" +version = "0.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c8480887e8803986d96a7173729565520d4bbb721ad6b7ad6941a22897207aa" +dependencies = [ + "serde", + "slotmap", + "smallvec", +] + +[[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" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "55937e1799185b12863d447f42597ed69d9928686b8d88a1df17376a097d8369" + +[[package]] +name = "tar" +version = "0.4.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f6221d9a6003c78398e3b239969f352578258df48c8eb051caadae0015bc840" +dependencies = [ + "filetime", + "libc", +] + +[[package]] +name = "target-features" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c1bbb9f3c5c463a01705937a24fdabc5047929ac764b2d5b9cf681c1f5041ed5" + +[[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" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f37a6c354fd28fc9e322ed9bd47e3959576dad28c9d58ea1cf888cce1c7ccb36" +dependencies = [ + "thiserror 2.0.21", + "windows 0.62.2", + "windows-version", +] + +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom 0.4.3", + "once_cell", + "rustix 1.1.6", + "windows-sys 0.61.2", +] + +[[package]] +name = "tendril" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5fed54709c5b3a53d09bb1c113ea4f5ceafd1e772ddcb0030a82e1d56c087b08" +dependencies = [ + "new_debug_unreachable", +] + +[[package]] +name = "termcolor" +version = "1.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06794f8f6c5c898b3275aebefa6b8a1cb24cd2c6c79397ab15774837a0bc5755" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "thiserror" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52" +dependencies = [ + "thiserror-impl 1.0.69", +] + +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl 2.0.21", +] + +[[package]] +name = "thiserror-impl" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "thousands" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bf63baf9f5039dadc247375c29eb13706706cfde997d0330d05aa63a77d8820" + +[[package]] +name = "thread_local" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ad99c4c6d32803332c548b1af0540b357b3f5fc0be8f6c6bfe8b2e6ae784070" +dependencies = [ + "cfg-if 1.0.5", +] + +[[package]] +name = "tiff" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63feaf3343d35b6ca4d50483f94843803b0f51634937cc2ec519fc32232bc52" +dependencies = [ + "fax", + "flate2", + "half", + "quick-error", + "weezl", + "zune-jpeg", +] + +[[package]] +name = "time" +version = "0.3.55" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134" +dependencies = [ + "deranged", + "js-sys", + "num-conv", + "powerfmt", + "serde_core", + "time-core", + "time-macros", +] + +[[package]] +name = "time-core" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109" + +[[package]] +name = "time-macros" +version = "0.2.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e689342a48d2ea927c87ea50cabf8594854bf940e9310208848d680d668ed85" +dependencies = [ + "num-conv", + "time-core", +] + +[[package]] +name = "tiny-keccak" +version = "2.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c9d3793400a45f954c52e73d068316d76b6f4e36977e3fcebb13a2721e80237" +dependencies = [ + "crunchy", +] + +[[package]] +name = "tiny-skia" +version = "0.11.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "83d13394d44dae3207b52a326c0c85a8bf87f1541f23b0d143811088497b09ab" +dependencies = [ + "arrayref", + "arrayvec", + "bytemuck", + "cfg-if 1.0.5", + "log", + "png 0.17.16", + "tiny-skia-path 0.11.4", +] + +[[package]] +name = "tiny-skia" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47ffee5eaaf5527f630fb0e356b90ebdec84d5d18d937c5e440350f88c5a91ea" +dependencies = [ + "arrayref", + "arrayvec", + "bytemuck", + "cfg-if 1.0.5", + "log", + "png 0.18.1", + "tiny-skia-path 0.12.0", +] + +[[package]] +name = "tiny-skia-path" +version = "0.11.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c9e7fc0c2e86a30b117d0462aa261b72b7a99b7ebd7deb3a14ceda95c5bdc93" +dependencies = [ + "arrayref", + "bytemuck", + "strict-num", +] + +[[package]] +name = "tiny-skia-path" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "edca365c3faccca67d06593c5980fa6c57687de727a03131735bb85f01fdeeb9" +dependencies = [ + "arrayref", + "bytemuck", + "strict-num", +] + +[[package]] +name = "tinystr" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "abc840c238154d58f9e86b2792261edfde565a17696e1cda1a449de27979801a" +dependencies = [ + "displaydoc", + "serde_core", + "zerovec", +] + +[[package]] +name = "tinyvec" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" + +[[package]] +name = "tobj" +version = "4.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6eb8e04167c1c0c76b5de63226fd733485ad63ef71e40de31e16272f47b099e2" + +[[package]] +name = "tokio" +version = "1.54.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3" +dependencies = [ + "bytes", + "libc", + "mio", + "pin-project-lite", + "signal-hook-registry", + "socket2", + "tokio-macros", + "windows-sys 0.61.2", +] + +[[package]] +name = "tokio-happy-eyeballs" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8564c32dfb6f4257f8bc6edfc178a34af97520e0b7b9815500c55eb3d092f29f" +dependencies = [ + "tokio", +] + +[[package]] +name = "tokio-macros" +version = "2.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "tokio-rustls" +version = "0.26.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9cc2678c2cdd569ef8215e2afd7954ada2ae20b4fdd2c5fe6139a3b02d105db" +dependencies = [ + "rustls", + "tokio", +] + +[[package]] +name = "tokio-socks" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7e2948f60dbe26b35f2c7fb74ac2854c1fddded0fe9d7548fcc674a246f7615" +dependencies = [ + "either", + "futures-util", + "thiserror 1.0.69", + "tokio", +] + +[[package]] +name = "tokio-stream" +version = "0.1.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a3d06f0b082ba57c26b79407372e57cf2a1e28124f78e9479fe80322cf53420b" +dependencies = [ + "futures-core", + "pin-project-lite", + "tokio", + "tokio-util", +] + +[[package]] +name = "tokio-tungstenite" +version = "0.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d25a406cddcc431a75d3d9afc6a7c0f7428d4891dd973e4d54c56b46127bf857" +dependencies = [ + "futures-util", + "log", + "rustls", + "rustls-pki-types", + "tokio", + "tokio-rustls", + "tungstenite", + "webpki-roots 0.26.11", +] + +[[package]] +name = "tokio-util" +version = "0.7.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e464cf451ba96ebfc6f9b6542f17ee8b8956e33f1e40d9690624e59d7a7f8a4b" +dependencies = [ + "bytes", + "futures-core", + "futures-io", + "futures-sink", + "futures-util", + "libc", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "tokio-websockets" +version = "0.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d52efb639344a7c6adb8e62c6f3d2c19c001ff1b79a5041ba1c6ed42e19c6aa5" +dependencies = [ + "base64 0.22.1", + "bytes", + "futures-core", + "futures-sink", + "getrandom 0.4.3", + "http", + "httparse", + "rand 0.10.3", + "ring", + "rustls-pki-types", + "sha1_smol", + "simdutf8", + "tokio", + "tokio-rustls", + "tokio-util", +] + +[[package]] +name = "toml" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc1beb996b9d83529a9e75c17a1686767d148d70663143c7854d8b4a09ced362" +dependencies = [ + "serde", + "serde_spanned 0.6.9", + "toml_datetime 0.6.11", + "toml_edit 0.22.27", +] + +[[package]] +name = "toml" +version = "1.2.1+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d5755c51863cdac711f1956baf8eb9588e060755f7d3c4c979e70ea1e1f32cd7" +dependencies = [ + "indexmap 2.14.2", + "serde_core", + "serde_spanned 1.1.3", + "toml_datetime 1.1.3+spec-1.1.0", + "toml_parser", + "toml_writer", + "winnow 1.0.5", +] + +[[package]] +name = "toml_datetime" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22cddaf88f4fbc13c51aebbf5f8eceb5c7c5a9da2ac40a13519eb5b0a0e8f11c" +dependencies = [ + "serde", +] + +[[package]] +name = "toml_datetime" +version = "1.1.3+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "173f25c883cd2176a2d8212155638c0a60d484a9d84546d270866f40f56b6e49" +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 2.14.2", + "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 2.14.2", + "toml_datetime 0.6.11", + "winnow 0.5.40", +] + +[[package]] +name = "toml_edit" +version = "0.22.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41fe8c660ae4257887cf66394862d21dbca4a6ddd26f04a3560410406a2f819a" +dependencies = [ + "indexmap 2.14.2", + "serde", + "serde_spanned 0.6.9", + "toml_datetime 0.6.11", + "toml_write", + "winnow 0.7.15", +] + +[[package]] +name = "toml_edit" +version = "0.25.19+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dd43688c4858d7264ae1cf9a9f874a67c3feb74a883b1cd7bebd6a4ea8307218" +dependencies = [ + "indexmap 2.14.2", + "toml_datetime 1.1.3+spec-1.1.0", + "toml_parser", + "winnow 1.0.5", +] + +[[package]] +name = "toml_parser" +version = "1.1.5+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c" +dependencies = [ + "winnow 1.0.5", +] + +[[package]] +name = "toml_write" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d99f8c9a7727884afe522e9bd5edbfc91a3312b36a77b5fb8926e4c31a41801" + +[[package]] +name = "toml_writer" +version = "1.2.0+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "009dbb7700f11c55ef83aebbe4c0e9cf1f1ac0844bd8d6f00dc38f302026e13a" + +[[package]] +name = "tor-async-utils" +version = "0.45.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0969a2e97472807009ea516a0b98541048d59b21afad98e1da9c577cd93d5db9" +dependencies = [ + "cfg-if 1.0.5", + "derive-deftly", + "educe", + "extend", + "futures", + "oneshot-fused-workaround", + "pin-project", + "postage", + "sync_wrapper", + "thiserror 2.0.21", + "tokio", + "tokio-util", + "tor-basic-utils", + "tor-rtcompat", + "tracing", + "void", + "web-time-compat", +] + +[[package]] +name = "tor-basic-utils" +version = "0.45.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "70c40efc7fdfd91d8e774cccaff5d8218cc6b914a5c65b04ca5719416427c9f8" +dependencies = [ + "derive-deftly", + "derive_more", + "educe", + "extend", + "getrandom 0.4.3", + "hex", + "itertools 0.15.0", + "libc", + "paste", + "rand 0.10.3", + "rand_chacha 0.10.0", + "serde", + "slab", + "smallvec", + "thiserror 2.0.21", + "tracing", + "weak-table", + "web-time-compat", +] + +[[package]] +name = "tor-bytes" +version = "0.45.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c23ad66d11cdb8052cd52f6f54cd14cc8e060fb49284a717246213500e6e911f" +dependencies = [ + "bytes", + "derive-deftly", + "digest 0.10.7", + "educe", + "getrandom 0.4.3", + "safelog", + "thiserror 2.0.21", + "tor-error", + "tor-llcrypto", + "zeroize", +] + +[[package]] +name = "tor-cell" +version = "0.45.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8bb1363898e3a5eebc3fd0bff63e00449810d4ad96699b685a8537b92929958" +dependencies = [ + "amplify", + "bitflags 2.13.2", + "bytes", + "caret", + "derive-deftly", + "derive_more", + "educe", + "itertools 0.15.0", + "paste", + "rand 0.10.3", + "smallvec", + "thiserror 2.0.21", + "tor-basic-utils", + "tor-bytes", + "tor-cert", + "tor-error", + "tor-hscrypto", + "tor-linkspec", + "tor-llcrypto", + "tor-memquota", + "tor-protover", + "tor-units", + "void", +] + +[[package]] +name = "tor-cert" +version = "0.45.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12a760ed5a0177a49d405c9ff53a17cf0348b3a297f8c228e860e880a878649c" +dependencies = [ + "caret", + "derive_builder_fork_arti", + "derive_more", + "digest 0.10.7", + "saturating-time", + "thiserror 2.0.21", + "tor-bytes", + "tor-checkable", + "tor-error", + "tor-llcrypto", + "web-time-compat", +] + +[[package]] +name = "tor-chanmgr" +version = "0.45.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e6be3bca876eda4aa9a47e77f803f2914f4c882f9affde994219146b6a88e8c" +dependencies = [ + "async-trait", + "base64ct", + "caret", + "cfg-if 1.0.5", + "derive-deftly", + "derive_more", + "educe", + "futures", + "httparse", + "oneshot-fused-workaround", + "percent-encoding", + "postage", + "rand 0.10.3", + "safelog", + "serde", + "serde_with", + "thiserror 2.0.21", + "tor-async-utils", + "tor-basic-utils", + "tor-cell", + "tor-config", + "tor-error", + "tor-keymgr", + "tor-linkspec", + "tor-llcrypto", + "tor-memquota", + "tor-netdir", + "tor-proto", + "tor-rtcompat", + "tor-socksproto", + "tor-units", + "tracing", + "url", + "void", + "web-time-compat", +] + +[[package]] +name = "tor-checkable" +version = "0.45.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bcdb5c50f28a24a4048a5ff8db5089eb1de204de80dc5ef40e04188ba66c8025" +dependencies = [ + "humantime", + "itertools 0.15.0", + "signature 2.2.0", + "thiserror 2.0.21", + "tor-llcrypto", + "web-time-compat", +] + +[[package]] +name = "tor-circmgr" +version = "0.45.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2ababd68e4bdbc4da874eef6938fdb8792f387d1722f53574a88e84a08a54af" +dependencies = [ + "amplify", + "async-trait", + "cfg-if 1.0.5", + "derive-deftly", + "derive_builder_fork_arti", + "derive_more", + "downcast-rs 2.0.2", + "dyn-clone", + "educe", + "futures", + "humantime-serde", + "itertools 0.15.0", + "once_cell", + "oneshot-fused-workaround", + "pin-project", + "rand 0.10.3", + "retry-error", + "safelog", + "serde", + "thiserror 2.0.21", + "tor-async-utils", + "tor-basic-utils", + "tor-cell", + "tor-chanmgr", + "tor-config", + "tor-dircommon", + "tor-error", + "tor-guardmgr", + "tor-linkspec", + "tor-memquota", + "tor-netdir", + "tor-netdoc", + "tor-persist", + "tor-proto", + "tor-protover", + "tor-relay-selection", + "tor-rtcompat", + "tor-units", + "tracing", + "void", + "weak-table", + "web-time-compat", +] + +[[package]] +name = "tor-config" +version = "0.45.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0ecacf2afa11dc25841514d69f0a770abf3b2c0da792ef47e5bdfdfe07bf67e" +dependencies = [ + "amplify", + "cfg-if 1.0.5", + "derive-deftly", + "derive_builder_fork_arti", + "educe", + "either", + "extend", + "figment", + "fs-mistrust", + "futures", + "humantime-serde", + "itertools 0.15.0", + "notify", + "paste", + "postage", + "regex", + "serde", + "serde-value", + "serde_ignored", + "strum", + "thiserror 2.0.21", + "toml 1.2.1+spec-1.1.0", + "tor-basic-utils", + "tor-error", + "tor-rtcompat", + "tracing", + "void", +] + +[[package]] +name = "tor-config-path" +version = "0.45.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52de46b996c648c3880ae0cc0cf8dd2cf9be4466be65e24df39790bd6e673204" +dependencies = [ + "directories", + "serde", + "shellexpand", + "thiserror 2.0.21", + "tor-error", + "tor-general-addr", +] + +[[package]] +name = "tor-consdiff" +version = "0.45.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "243ef0da7444be7f8f15ba17e3eb7c9e4359e9f93ddb68abd33984874e39cf6e" +dependencies = [ + "derive_more", + "digest 0.10.7", + "hex", + "imara-diff", + "static_assertions", + "thiserror 2.0.21", + "tor-error", + "tor-llcrypto", + "tor-netdoc", +] + +[[package]] +name = "tor-dirclient" +version = "0.45.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53c62385daf1ec5a8a7132c9da0baf5121169316d2fc3a40886a26a6074fa635" +dependencies = [ + "async-compression", + "base64ct", + "derive_more", + "futures", + "hex", + "http", + "httparse", + "httpdate", + "itertools 0.15.0", + "memchr", + "thiserror 2.0.21", + "tor-circmgr", + "tor-error", + "tor-hscrypto", + "tor-linkspec", + "tor-llcrypto", + "tor-netdoc", + "tor-proto", + "tor-rtcompat", + "tracing", + "web-time-compat", +] + +[[package]] +name = "tor-dircommon" +version = "0.45.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44132db8353536b8c79b81c9d0887053c1fe4679f0198b5f244d15a542b5bf16" +dependencies = [ + "base64ct", + "derive-deftly", + "getset", + "humantime", + "humantime-serde", + "serde", + "tor-basic-utils", + "tor-checkable", + "tor-config", + "tor-linkspec", + "tor-llcrypto", + "tor-netdoc", + "tracing", +] + +[[package]] +name = "tor-dirmgr" +version = "0.45.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b5523974c841cf2a9f85cfae6a1345572ac6e9deda1a43c2acf5301bddf8f83" +dependencies = [ + "async-trait", + "base64ct", + "derive_builder_fork_arti", + "derive_more", + "digest 0.10.7", + "educe", + "event-listener", + "fs-mistrust", + "fslock-guard", + "futures", + "hex", + "humantime", + "humantime-serde", + "itertools 0.15.0", + "memmap2", + "oneshot-fused-workaround", + "paste", + "postage", + "rand 0.10.3", + "rusqlite", + "safelog", + "scopeguard", + "serde", + "serde_json", + "signature 2.2.0", + "static_assertions", + "strum", + "thiserror 2.0.21", + "time", + "tor-async-utils", + "tor-basic-utils", + "tor-checkable", + "tor-circmgr", + "tor-config", + "tor-consdiff", + "tor-dirclient", + "tor-dircommon", + "tor-error", + "tor-guardmgr", + "tor-llcrypto", + "tor-netdir", + "tor-netdoc", + "tor-persist", + "tor-proto", + "tor-protover", + "tor-rtcompat", + "tracing", + "void", + "web-time-compat", +] + +[[package]] +name = "tor-error" +version = "0.45.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ac7221e0878a49f9eaa1adbfcbc15300699c7fc65644432706bef3cb99c5fc3" +dependencies = [ + "derive_more", + "futures", + "paste", + "retry-error", + "static_assertions", + "strum", + "thiserror 2.0.21", + "tracing", + "void", + "web-time-compat", +] + +[[package]] +name = "tor-general-addr" +version = "0.45.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b55314b3d95d4145c2d88cee46d4c623b209eceb980ac151c35ab97b2cba9de" +dependencies = [ + "derive_more", + "thiserror 2.0.21", + "void", +] + +[[package]] +name = "tor-guardmgr" +version = "0.45.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ddc6ae93e20b4e90174a915fca0be127753664886ae41722425dbd88bc4f500" +dependencies = [ + "amplify", + "base64ct", + "derive-deftly", + "derive_builder_fork_arti", + "derive_more", + "dyn-clone", + "educe", + "futures", + "humantime", + "humantime-serde", + "itertools 0.15.0", + "num_enum", + "oneshot-fused-workaround", + "pin-project", + "postage", + "rand 0.10.3", + "safelog", + "serde", + "strum", + "thiserror 2.0.21", + "tor-async-utils", + "tor-basic-utils", + "tor-config", + "tor-dircommon", + "tor-error", + "tor-linkspec", + "tor-llcrypto", + "tor-netdir", + "tor-netdoc", + "tor-persist", + "tor-proto", + "tor-protover", + "tor-relay-selection", + "tor-rtcompat", + "tor-units", + "tracing", + "web-time-compat", +] + +[[package]] +name = "tor-hsclient" +version = "0.45.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00a766e2a933e69f627ab112232634d1c5d92f8a24f694484aaf8b47f98e664e" +dependencies = [ + "async-trait", + "cfg-if 1.0.5", + "derive-deftly", + "derive_more", + "educe", + "either", + "futures", + "itertools 0.15.0", + "oneshot-fused-workaround", + "postage", + "rand 0.10.3", + "retry-error", + "safelog", + "slotmap-careful", + "strum", + "thiserror 2.0.21", + "tor-async-utils", + "tor-basic-utils", + "tor-bytes", + "tor-cell", + "tor-checkable", + "tor-circmgr", + "tor-config", + "tor-dirclient", + "tor-error", + "tor-hscrypto", + "tor-keymgr", + "tor-linkspec", + "tor-llcrypto", + "tor-memquota", + "tor-netdir", + "tor-netdoc", + "tor-persist", + "tor-proto", + "tor-protover", + "tor-rtcompat", + "tracing", + "web-time-compat", +] + +[[package]] +name = "tor-hscrypto" +version = "0.45.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f6438a115a512791dc1309ab8a70b969c89631914d8aa0cfa35cdb20d5d33b7" +dependencies = [ + "data-encoding", + "derive-deftly", + "derive_more", + "digest 0.10.7", + "hex", + "humantime", + "itertools 0.15.0", + "paste", + "rand 0.10.3", + "safelog", + "serde", + "signature 2.2.0", + "subtle", + "thiserror 2.0.21", + "tor-basic-utils", + "tor-bytes", + "tor-error", + "tor-key-forge", + "tor-llcrypto", + "tor-memquota", + "tor-units", + "void", + "web-time-compat", +] + +[[package]] +name = "tor-key-forge" +version = "0.45.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "763406a26bdb2ce8d9b1bd52bc1eb5d808a9c5b4f25ed687972e2ac869be801f" +dependencies = [ + "derive-deftly", + "derive_more", + "downcast-rs 2.0.2", + "paste", + "rand 0.10.3", + "rsa", + "signature 2.2.0", + "ssh-key-fork-arti", + "thiserror 2.0.21", + "tor-bytes", + "tor-cert", + "tor-checkable", + "tor-error", + "tor-llcrypto", +] + +[[package]] +name = "tor-keymgr" +version = "0.45.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "43f7f56a7b14d090d29e2e3c78b2fea84a6b97ad9b4b9fc13c4e09ec5ac283fa" +dependencies = [ + "amplify", + "arrayvec", + "cfg-if 1.0.5", + "derive-deftly", + "derive_builder_fork_arti", + "derive_more", + "downcast-rs 2.0.2", + "dyn-clone", + "fs-mistrust", + "glob-match", + "humantime", + "inventory", + "itertools 0.15.0", + "rand 0.10.3", + "safelog", + "serde", + "signature 2.2.0", + "ssh-key-fork-arti", + "thiserror 2.0.21", + "tor-basic-utils", + "tor-bytes", + "tor-config", + "tor-config-path", + "tor-error", + "tor-hscrypto", + "tor-key-forge", + "tor-llcrypto", + "tor-persist", + "tracing", + "visibility", + "walkdir", + "web-time-compat", + "zeroize", +] + +[[package]] +name = "tor-linkspec" +version = "0.45.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "608f77e1b9acba4304b45d2810e1d41c3899741dbdadf2f6e1e18baea29bbd5b" +dependencies = [ + "base64ct", + "by_address", + "caret", + "derive-deftly", + "derive_builder_fork_arti", + "derive_more", + "hex", + "itertools 0.15.0", + "safelog", + "serde", + "serde_with", + "strum", + "thiserror 2.0.21", + "tor-basic-utils", + "tor-bytes", + "tor-config", + "tor-llcrypto", + "tor-memquota", + "tor-protover", +] + +[[package]] +name = "tor-llcrypto" +version = "0.45.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b7b91d916be50cbbb575c468f6926cc34c3003d0162a644195bf60c00ad0247" +dependencies = [ + "aes 0.9.4", + "base64ct", + "ctr 0.10.1", + "curve25519-dalek 4.1.3", + "der-parser", + "derive-deftly", + "derive_more", + "digest 0.10.7", + "ed25519-dalek 2.2.0", + "educe", + "getrandom 0.2.17", + "getrandom 0.3.4", + "getrandom 0.4.3", + "hex", + "rand 0.10.3", + "rand_chacha 0.10.0", + "rand_core 0.10.1", + "rand_core 0.6.4", + "rand_jitter", + "rdrand", + "reseeding_rng", + "rsa", + "safelog", + "serde", + "sha1", + "sha2 0.10.9", + "sha3 0.10.9", + "signature 2.2.0", + "subtle", + "thiserror 2.0.21", + "tor-error", + "tor-memquota-cost", + "visibility", + "x25519-dalek", + "zeroize", +] + +[[package]] +name = "tor-log-ratelim" +version = "0.45.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "382fbfbe7b7a6e88165bc473362616b2360c5d07d2c66c9362c79b0f6da3d39c" +dependencies = [ + "futures", + "humantime", + "thiserror 2.0.21", + "tor-error", + "tor-rtcompat", + "tracing", + "weak-table", + "web-time-compat", +] + +[[package]] +name = "tor-memquota" +version = "0.45.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10a433d849640322ccfa68015e5ae5835471e0959e70d097833f3847f5934239" +dependencies = [ + "cfg-if 1.0.5", + "derive-deftly", + "derive_more", + "dyn-clone", + "educe", + "extend", + "futures", + "itertools 0.15.0", + "paste", + "pin-project", + "serde", + "slotmap-careful", + "static_assertions", + "sysinfo 0.38.4", + "thiserror 2.0.21", + "tor-async-utils", + "tor-basic-utils", + "tor-config", + "tor-error", + "tor-log-ratelim", + "tor-memquota-cost", + "tor-rtcompat", + "tracing", + "void", +] + +[[package]] +name = "tor-memquota-cost" +version = "0.45.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93d6db1779594e2934ea62b83baedb0b2de1f436177d3b07a497b252ca7b522d" +dependencies = [ + "derive-deftly", + "itertools 0.15.0", + "paste", + "void", +] + +[[package]] +name = "tor-netdir" +version = "0.45.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4214b180dae5f489253a2495322cf2c83f3bc7a4b246747cc6bf2ad1cba41ca1" +dependencies = [ + "async-trait", + "bitflags 2.13.2", + "derive_more", + "digest 0.10.7", + "futures", + "hex", + "humantime", + "itertools 0.15.0", + "num_enum", + "rand 0.10.3", + "serde", + "strum", + "thiserror 2.0.21", + "time", + "tor-basic-utils", + "tor-error", + "tor-hscrypto", + "tor-linkspec", + "tor-llcrypto", + "tor-netdoc", + "tor-protover", + "tor-units", + "tracing", + "typed-index-collections", + "web-time-compat", +] + +[[package]] +name = "tor-netdoc" +version = "0.45.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f0f1ef6582bab04851c78982f7a43b7f6058498338ec9ff8f6a5e2d34471c95" +dependencies = [ + "amplify", + "base64ct", + "cipher 0.5.2", + "derive-deftly", + "derive_builder_fork_arti", + "derive_more", + "digest 0.10.7", + "educe", + "enumset", + "extend", + "hex", + "hostname-validator", + "humantime", + "ipnet", + "iprange", + "itertools 0.15.0", + "memchr", + "paste", + "phf 0.14.0", + "rand 0.10.3", + "rangemap", + "saturating-time", + "serde", + "serde_with", + "signature 2.2.0", + "smallvec", + "strum", + "subtle", + "thiserror 2.0.21", + "time", + "tinystr", + "tor-basic-utils", + "tor-bytes", + "tor-cell", + "tor-cert", + "tor-checkable", + "tor-error", + "tor-hscrypto", + "tor-linkspec", + "tor-llcrypto", + "tor-protover", + "tor-units", + "void", + "web-time-compat", + "zeroize", +] + +[[package]] +name = "tor-persist" +version = "0.45.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2718cecfe2ef009ab81f0426ce64be6aa4098c04c13d9cc116b5128376f37c2e" +dependencies = [ + "derive-deftly", + "derive_more", + "extend", + "filetime", + "fs-mistrust", + "fslock-guard", + "futures", + "itertools 0.15.0", + "oneshot-fused-workaround", + "paste", + "sanitize-filename", + "serde", + "serde_json", + "thiserror 2.0.21", + "time", + "tor-async-utils", + "tor-basic-utils", + "tor-error", + "tracing", + "void", + "web-time-compat", +] + +[[package]] +name = "tor-proto" +version = "0.45.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9098bb3d88ccfcfbf3b34619df8dedf850ee1ddeba8ed70b6e78e64f3349c43e" +dependencies = [ + "amplify", + "async-trait", + "asynchronous-codec", + "bitvec", + "bytes", + "caret", + "cfg-if 1.0.5", + "cipher 0.5.2", + "coarsetime", + "derive-deftly", + "derive_builder_fork_arti", + "derive_more", + "digest 0.10.7", + "educe", + "enum_dispatch", + "futures", + "futures-util", + "hkdf", + "hmac", + "itertools 0.15.0", + "nonany", + "oneshot-fused-workaround", + "pin-project", + "postage", + "rand 0.10.3", + "rand_core 0.10.1", + "safelog", + "slotmap-careful", + "smallvec", + "static_assertions", + "strum", + "subtle", + "thiserror 2.0.21", + "tokio", + "tokio-util", + "tor-async-utils", + "tor-basic-utils", + "tor-bytes", + "tor-cell", + "tor-cert", + "tor-checkable", + "tor-config", + "tor-error", + "tor-hscrypto", + "tor-linkspec", + "tor-llcrypto", + "tor-log-ratelim", + "tor-memquota", + "tor-protover", + "tor-rtcompat", + "tor-rtmock", + "tor-units", + "tracing", + "typenum", + "visibility", + "void", + "web-time-compat", + "zeroize", +] + +[[package]] +name = "tor-protover" +version = "0.45.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be1e76606ba190039026fe949af420db546058d64de69ebc42a454a0745607b8" +dependencies = [ + "caret", + "derive-deftly", + "paste", + "serde_with", + "thiserror 2.0.21", + "tor-basic-utils", + "tor-bytes", +] + +[[package]] +name = "tor-ptmgr" +version = "0.45.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d052da1eadd9f65cc46aa367adb8b573d397acf3d0635d39351670bbe40a82f7" +dependencies = [ + "async-trait", + "cfg-if 1.0.5", + "derive-deftly", + "derive_builder_fork_arti", + "fs-mistrust", + "futures", + "itertools 0.15.0", + "oneshot-fused-workaround", + "serde", + "thiserror 2.0.21", + "tor-async-utils", + "tor-basic-utils", + "tor-chanmgr", + "tor-config", + "tor-config-path", + "tor-error", + "tor-linkspec", + "tor-proto", + "tor-rtcompat", + "tor-socksproto", + "tracing", + "web-time-compat", +] + +[[package]] +name = "tor-relay-selection" +version = "0.45.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "465cc59cd3713b1b1dcb3daafd21153509b49a91dfd19711df3143154806bc97" +dependencies = [ + "rand 0.10.3", + "serde", + "tor-basic-utils", + "tor-linkspec", + "tor-netdir", + "tor-netdoc", +] + +[[package]] +name = "tor-rtcompat" +version = "0.45.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c0c4f9845afe4a2be175091a3610cb0e76361a445f4d849d81e5bccced827dd" +dependencies = [ + "amplify", + "async-trait", + "async_executors", + "asynchronous-codec", + "cfg-if 1.0.5", + "coarsetime", + "derive_builder_fork_arti", + "derive_more", + "dyn-clone", + "educe", + "futures", + "futures-rustls", + "hex", + "libc", + "paste", + "pin-project", + "rustls", + "rustls-pki-types", + "rustls-webpki", + "socket2", + "thiserror 2.0.21", + "tokio", + "tokio-util", + "tor-error", + "tor-general-addr", + "tracing", + "void", + "web-time-compat", + "zeroize", +] + +[[package]] +name = "tor-rtmock" +version = "0.45.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8b042bfc0441618a513568cc7cd7544af146c7e3841857cc6ad39caca85528f" +dependencies = [ + "amplify", + "assert_matches", + "async-trait", + "derive-deftly", + "derive_more", + "educe", + "futures", + "humantime", + "itertools 0.15.0", + "oneshot-fused-workaround", + "pin-project", + "priority-queue", + "slotmap-careful", + "strum", + "thiserror 2.0.21", + "tor-error", + "tor-general-addr", + "tor-rtcompat", + "tracing", + "tracing-test", + "void", + "web-time-compat", +] + +[[package]] +name = "tor-socksproto" +version = "0.45.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c52feb363eefbe662c059f39969842dc001bf82dbe81849c703d5051cbd10266" +dependencies = [ + "amplify", + "caret", + "derive-deftly", + "educe", + "safelog", + "subtle", + "thiserror 2.0.21", + "tor-bytes", + "tor-error", +] + +[[package]] +name = "tor-units" +version = "0.45.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f985b939892d57ab7dfe06ad6cf54aa82808305b22b176191c54cbabab5c073d" +dependencies = [ + "derive-deftly", + "derive_more", + "serde", + "thiserror 2.0.21", + "tor-memquota", +] + +[[package]] +name = "tower" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" +dependencies = [ + "futures-core", + "futures-util", + "pin-project-lite", + "sync_wrapper", + "tokio", + "tower-layer", + "tower-service", +] + +[[package]] +name = "tower-http" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840" +dependencies = [ + "bitflags 2.13.2", + "bytes", + "futures-util", + "http", + "http-body", + "pin-project-lite", + "tower", + "tower-layer", + "tower-service", + "url", +] + +[[package]] +name = "tower-layer" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" + +[[package]] +name = "tower-service" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "log", + "pin-project-lite", + "tracing-attributes", + "tracing-core", +] + +[[package]] +name = "tracing-attributes" +version = "0.1.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", + "valuable", +] + +[[package]] +name = "tracing-log" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3" +dependencies = [ + "log", + "once_cell", + "tracing-core", +] + +[[package]] +name = "tracing-subscriber" +version = "0.3.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb7f578e5945fb242538965c2d0b04418d38ec25c79d160cd279bf0731c8d319" +dependencies = [ + "matchers", + "nu-ansi-term", + "once_cell", + "regex-automata", + "sharded-slab", + "smallvec", + "thread_local", + "tracing", + "tracing-core", + "tracing-log", +] + +[[package]] +name = "tracing-test" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19a4c448db514d4f24c5ddb9f73f2ee71bfb24c526cf0c570ba142d1119e0051" +dependencies = [ + "tracing-core", + "tracing-subscriber", + "tracing-test-macro", +] + +[[package]] +name = "tracing-test-macro" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad06847b7afb65c7866a36664b75c40b895e318cea4f71299f013fb22965329d" +dependencies = [ + "quote", + "syn 2.0.119", +] + +[[package]] +name = "transpose" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ad61aed86bc3faea4300c7aee358b4c6d0c8d6ccc36524c96e4c92ccf26e77e" +dependencies = [ + "num-integer", + "strength_reduce", +] + +[[package]] +name = "try-lock" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" + +[[package]] +name = "ttf-parser" +version = "0.25.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2df906b07856748fa3f6e0ad0cbaa047052d4a7dd609e231c4f72cee8c36f31" +dependencies = [ + "core_maths", +] + +[[package]] +name = "tungstenite" +version = "0.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8628dcc84e5a09eb3d8423d6cb682965dea9133204e8fb3efee74c2a0c259442" +dependencies = [ + "bytes", + "data-encoding", + "http", + "httparse", + "log", + "rand 0.9.5", + "rustls", + "rustls-pki-types", + "sha1", + "thiserror 2.0.21", + "utf-8", +] + +[[package]] +name = "type-map" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb30dbbd9036155e74adad6812e9898d03ec374946234fbcebd5dfc7b9187b90" +dependencies = [ + "rustc-hash 2.1.3", +] + +[[package]] +name = "typed-index-collections" +version = "3.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "898160f1dfd383b4e92e17f0512a7d62f3c51c44937b23b6ffc3a1614a8eaccd" +dependencies = [ + "bincode", + "serde", +] + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "uds_windows" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2f6fb2847f6742cd76af783a2a2c49e9375d0a111c7bef6f71cd9e738c72d6e" +dependencies = [ + "memoffset", + "tempfile", + "windows-sys 0.61.2", +] + +[[package]] +name = "uncased" +version = "0.9.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1b88fcfe09e89d3866a5c11019378088af2d24c3fbd4f0543f96b479ec90697" +dependencies = [ + "version_check", +] + +[[package]] +name = "unic-langid" +version = "0.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a28ba52c9b05311f4f6e62d5d9d46f094bd6e84cb8df7b3ef952748d752a7d05" +dependencies = [ + "unic-langid-impl", +] + +[[package]] +name = "unic-langid-impl" +version = "0.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dce1bf08044d4b7a94028c93786f8566047edc11110595914de93362559bc658" +dependencies = [ + "tinystr", +] + +[[package]] +name = "unicase" +version = "2.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "357cc3acc6a036009fd6c973ed009037c732d60d0b4f6c673e9041497482a28f" + +[[package]] +name = "unicode-bidi" +version = "0.3.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c1cb5db39152898a79168971543b1cb5020dff7fe43c8dc468b0885f5e29df5" + +[[package]] +name = "unicode-bidi-mirroring" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5dfa6e8c60bb66d49db113e0125ee8711b7647b5579dc7f5f19c42357ed039fe" + +[[package]] +name = "unicode-ccc" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce61d488bcdc9bc8b5d1772c404828b17fc481c0a582b5581e95fb233aef503e" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "unicode-linebreak" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b09c83c3c29d37506a3e260c08c03743a6bb66a9cd432c6934ab501a190571f" + +[[package]] +name = "unicode-normalization" +version = "0.1.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75cd3fb03d5288b3ba9a1ee103ac7e9cbb59f0b03d64f8ddfcc04dd42758a85d" +dependencies = [ + "tinyvec", +] + +[[package]] +name = "unicode-properties" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e70f2a8b45122e719eb623c01822704c4e0907e7e426a05927e1a1cfff5b75d0" + +[[package]] +name = "unicode-script" +version = "0.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa04c955db05429d464c74d495c1ee677e1866e783a4c3747f9c0cef7756cabf" + +[[package]] +name = "unicode-segmentation" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8" + +[[package]] +name = "unicode-vo" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1d386ff53b415b7fe27b50bb44679e2cc4660272694b7b6f3326d8480823a94" + +[[package]] +name = "unicode-width" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca718471876992059f251e33aafc334346ada08042b7661dd1fe313a9bced557" + +[[package]] +name = "unicode-xid" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" + +[[package]] +name = "universal-hash" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc1de2c688dc15305988b563c3854064043356019f97a4b46276fe734c4f07ea" +dependencies = [ + "crypto-common 0.1.7", + "subtle", +] + +[[package]] +name = "universal-hash" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f4987bdc12753382e0bec4a65c50738ffaabc998b9cdd1f952fb5f39b0048a96" +dependencies = [ + "crypto-common 0.2.2", + "ctutils", +] + +[[package]] +name = "universal-time" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47a939edecc3c5a7b83c02e5f6b3c31d2bc69eabcc9a87ab12c6d37ee6dbc856" + +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "unty" +version = "0.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6d49784317cd0d1ee7ec5c716dd598ec5b4483ea832a2dced265471cc0f690ae" + +[[package]] +name = "url" +version = "2.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", + "serde_derive", +] + +[[package]] +name = "usvg" +version = "0.46.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e419dff010bb12512b0ae9e3d2f318dfbdf0167fde7eb05465134d4e8756076f" +dependencies = [ + "base64 0.22.1", + "data-url", + "flate2", + "fontdb", + "imagesize 0.14.0", + "kurbo", + "log", + "pico-args", + "roxmltree 0.21.2", + "rustybuzz", + "simplecss", + "siphasher", + "strict-num", + "svgtypes", + "tiny-skia-path 0.11.4", + "unicode-bidi", + "unicode-script", + "unicode-vo", + "xmlwriter", +] + +[[package]] +name = "usvg" +version = "0.48.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "977d0a4abdef933f424a99fe09f95576e089b90aebc6f016a3bc813762493e91" +dependencies = [ + "data-url", + "imagesize 0.15.0", + "kurbo", + "log", + "pico-args", + "roxmltree 0.21.2", + "simplecss", + "siphasher", + "strict-num", + "svgtypes", + "tiny-skia-path 0.12.0", +] + +[[package]] +name = "utf-8" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09cc8ee72d2a9becf2f2febe0205bbed8fc6615b7cb429ad062dc7b7ddd036a9" + +[[package]] +name = "utf8_iter" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af3bd9d3e571c26fcce9d033b87ea5ab061b8d2ffe9b7a5675d810d68f03edf0" +dependencies = [ + "utf_types", +] + +[[package]] +name = "utf8parse" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" + +[[package]] +name = "utf_types" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a3b425286980a367278453f3b6d28cdcb134b574e5a35824a6ff5eebad50bb6" + +[[package]] +name = "uuid" +version = "1.29.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bed99139f7dac9b5cfe5f17be4d66dc7079a34dee1d74bcc77217119240e267c" +dependencies = [ + "getrandom 0.4.3", + "js-sys", + "serde_core", + "sha1_smol", + "wasm-bindgen", +] + +[[package]] +name = "v4l" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d8fbfea44a46799d62c55323f3c55d06df722fbe577851d848d328a1041c3403" +dependencies = [ + "bitflags 1.3.2", + "libc", + "v4l2-sys-mit", +] + +[[package]] +name = "v4l2-sys-mit" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6779878362b9bacadc7893eac76abe69612e8837ef746573c4a5239daf11990b" +dependencies = [ + "bindgen 0.65.1", +] + +[[package]] +name = "v_frame" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "666b7727c8875d6ab5db9533418d7c764233ac9c0cff1d469aec8fa127597be2" +dependencies = [ + "aligned-vec", + "num-traits", + "wasm-bindgen", +] + +[[package]] +name = "valuable" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" + +[[package]] +name = "vcpkg" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" + +[[package]] +name = "vector-calls" +version = "0.2.0" +dependencies = [ + "bytes", + "serde", + "serde_json", + "tokio", +] + +[[package]] +name = "vector-core" +version = "0.13.1" +dependencies = [ + "aes 0.9.4", + "argon2", + "arti-client", + "async-trait", + "async-wsocket", + "bip39", + "bitcoin_hashes 1.2.0", + "blake3", + "bytes", + "chacha20 0.9.1", + "ctr 0.10.1", + "curve25519-dalek 4.1.3", + "fast-thumbhash", + "foldhash 0.2.0", + "futures-util", + "getrandom 0.2.17", + "getrandom 0.4.3", + "ghash 0.6.0", + "gif", + "hkdf", + "hmac", + "http", + "image", + "iroh", + "iroh-gossip", + "js-sys", + "libc", + "libcrux-ml-kem", + "memchr", + "negentropy", + "noq-proto", + "nostr", + "nostr-connect", + "nostr-database", + "nostr-parse", + "nostr-sdk", + "nostr-verify", + "rand 0.8.8", + "reqwest", + "resvg 0.48.1", + "roxmltree 0.21.2", + "rusqlite", + "rustls", + "serde", + "serde_json", + "sha2 0.10.9", + "spake2", + "tokio", + "tokio-happy-eyeballs", + "tokio-rustls", + "tokio-socks", + "tokio-tungstenite", + "tokio-util", + "toml 0.8.23", + "tor-circmgr", + "tor-dirmgr", + "tor-guardmgr", + "tor-linkspec", + "tor-proto", + "tor-rtcompat", + "unicode-normalization", + "url", + "vector-calls", + "vector-push", + "wasm-bindgen", + "wasm-bindgen-futures", + "wasmtimer", + "web-time", + "webpki-roots 1.0.12", + "zeroize", + "zip", +] + +[[package]] +name = "vector-gpui" +version = "0.6.0-1" +dependencies = [ + "anyhow", + "arboard", + "base64 0.22.1", + "bip39", + "block2 0.6.2", + "bytemuck", + "bytes", + "chrono", + "clipboard-win", + "color_quant", + "cpal", + "crc32fast", + "dhat", + "dirs 6.0.0", + "dom_query", + "env_logger", + "fast-thumbhash", + "fast_image_resize", + "fbxcel", + "ffmpeg-next", + "flate2", + "futures", + "gif", + "glam", + "gltf", + "gpui", + "gpui_apple", + "gpui_platform", + "gpui_wgpu", + "gpui_windows", + "gtk", + "http", + "image", + "jni 0.21.1", + "jpegxl-src", + "jxl-oxide", + "libc", + "libwebp-sys", + "log", + "memchr", + "minisign-verify", + "ndk-context", + "nokhwa", + "nostr-sdk", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "objc2-foundation 0.3.2", + "objc2-metal 0.3.2", + "openh264", + "png 0.18.1", + "pollster 0.4.0", + "pulldown-cmark", + "qrcodegen", + "rand 0.8.8", + "raw-window-handle", + "rayon", + "regex", + "reqwest", + "rqrr", + "rusqlite", + "rust-embed", + "serde", + "serde_json", + "simd-adler32", + "symphonia", + "sys-locale", + "sysinfo 0.31.4", + "tar", + "tempfile", + "tobj", + "tokio", + "unicode-bidi", + "unicode-bidi-mirroring", + "unicode-linebreak", + "unicode-properties", + "unicode-segmentation", + "url", + "vector-core", + "vector-gpui-media", + "vector-i18n", + "vector-jpeg", + "vector-push", + "vector-tauri-shim", + "webkit2gtk", + "wgpu", + "windows 0.61.3", + "wry", + "x11rb", + "xcap", + "zbus 5.19.0", + "zeroize", + "zip", +] + +[[package]] +name = "vector-gpui-media" +version = "0.1.0" +dependencies = [ + "anyhow", + "async-trait", + "bitcoin_hashes 1.2.0", + "block2 0.6.2", + "bytes", + "cc", + "cpal", + "dispatch2", + "fast-thumbhash", + "futures-util", + "gdk", + "glib", + "gtk", + "http", + "http-body-util", + "hyper", + "hyper-util", + "image", + "iroh", + "iroh-gossip", + "jni 0.21.1", + "libc", + "lofty", + "log", + "memchr", + "ndk", + "ndk-context", + "nostr-sdk", + "objc2 0.6.5", + "objc2-core-audio-types", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-core-media", + "objc2-foundation 0.3.2", + "objc2-screen-capture-kit", + "objc2-user-notifications", + "opus", + "rand 0.8.8", + "rayon", + "reqwest", + "rusqlite", + "rustfft", + "secp256k1", + "serde", + "serde_json", + "sha2 0.10.9", + "symphonia", + "tokio", + "tokio-tungstenite", + "toml 0.8.23", + "url", + "vector-core", + "vector-tauri-shim", + "webkit2gtk", + "whisper-rs", + "windows 0.61.3", + "windows-core 0.61.2", + "windows-sys 0.61.2", + "zeroize", + "zip", +] + +[[package]] +name = "vector-i18n" +version = "0.1.0" +dependencies = [ + "flate2", + "fluent-bundle", + "fluent-syntax", + "intl-memoizer", + "serde", + "serde_json", + "unic-langid", +] + +[[package]] +name = "vector-jpeg" +version = "0.3.2" +dependencies = [ + "image", + "jpeg-decoder", + "memchr", +] + +[[package]] +name = "vector-push" +version = "0.1.0" +dependencies = [ + "aes-gcm", + "base64 0.22.1", + "getrandom 0.2.17", + "hkdf", + "hmac", + "nostr", + "p256", + "rand 0.8.8", + "serde", + "serde_json", + "sha2 0.10.9", +] + +[[package]] +name = "vector-tauri-shim" +version = "0.1.0" +dependencies = [ + "http", + "serde", + "serde_json", + "tokio", + "url", + "vector-tauri-shim-macros", +] + +[[package]] +name = "vector-tauri-shim-macros" +version = "0.1.0" + +[[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" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "visibility" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d674d135b4a8c1d7e813e2f8d1c9a58308aee4a680323066025e53132218bd91" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "void" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a02e4885ed3bc0f2de90ea6dd45ebcbb66dacffe03547fadbb0eeae2770887d" + +[[package]] +name = "vswhom" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be979b7f07507105799e854203b470ff7c78a1639e330a58f183b5fea574608b" +dependencies = [ + "libc", + "vswhom-sys", +] + +[[package]] +name = "vswhom-sys" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fb067e4cbd1ff067d1df46c9194b5de0e98efd2810bbc95c5d5e5f25a3231150" +dependencies = [ + "cc", + "libc", +] + +[[package]] +name = "waker-fn" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "317211a0dc0ceedd78fb2ca9a44aed3d7b9b26f81870d485c07122b4350673b7" + +[[package]] +name = "walkdir" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b" +dependencies = [ + "same-file", + "winapi-util", +] + +[[package]] +name = "want" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec4cdd0dd910afe868b7ef477227d8d538b46b3075031afee8a9f2acb0a2ed0b" +dependencies = [ + "try-lock", +] + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasip2" +version = "1.0.4+wasi-0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487" +dependencies = [ + "wit-bindgen", +] + +[[package]] +name = "wasix" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae86f02046da16a333a9129d31451423e1657737ecdafed4193838a5f54c5cfe" +dependencies = [ + "wasi", +] + +[[package]] +name = "wasm-bindgen" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0181c14ddd6c7b8b0b0132a5f1ea2f32be0d893cd3ea97b6e3b28886b8a3d1c" +dependencies = [ + "cfg-if 1.0.5", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.80" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e14e0327cb5368ad60ccb22d04a9827a693c95a926d8d125e9fa39e0baec501" +dependencies = [ + "js-sys", + "tokio", + "wasm-bindgen", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e931a02a39abdbf66966fc35902b5ed58344750a70885bed4ebb3d8eaf28ed9" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ca4b54280e455bd831e33a6b8e734baf432fe63fbc35c42ac14ce67a043a53a" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 3.0.10", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b1f9c3798725016c6ee5f2f57869ec0831e8bbc0ab0310a86e787e97f41389e" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "wasm-streams" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d1ec4f6517c9e11ae630e200b2b65d193279042e28edd4a2cda233e46670bbb" +dependencies = [ + "futures-util", + "js-sys", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + +[[package]] +name = "wasmtimer" +version = "0.4.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c62b7f338e4397a45d054c15a2b36a93d57cccdda7be11a7d7b045d47b5e70ce" +dependencies = [ + "futures", + "js-sys", + "parking_lot", + "pin-project-lite", + "slab", + "wasm-bindgen", +] + +[[package]] +name = "wayland-backend" +version = "0.3.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38a91b4eaddff87b1cd1074985e3713da4af2c49742d1b356b2c01670a67a078" +dependencies = [ + "cc", + "downcast-rs 1.2.1", + "log", + "rustix 1.1.6", + "scoped-tls", + "smallvec", + "wayland-sys", +] + +[[package]] +name = "wayland-client" +version = "0.31.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3c36a0f861ad76d0901f2800b46321410d9f73f2ea88aac0650d86c32688073" +dependencies = [ + "bitflags 2.13.2", + "rustix 1.1.6", + "wayland-backend", + "wayland-scanner", +] + +[[package]] +name = "wayland-cursor" +version = "0.31.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a52d18780be9b1314328a3de5f930b73d2200112e3849ca6cb11822793fb34d" +dependencies = [ + "rustix 1.1.6", + "wayland-client", + "xcursor", +] + +[[package]] +name = "wayland-protocols" +version = "0.32.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23d0c813de3daa2ed6520af85a3bd49b0e722a3078506899aa9686fea58dc4b6" +dependencies = [ + "bitflags 2.13.2", + "wayland-backend", + "wayland-client", + "wayland-scanner", +] + +[[package]] +name = "wayland-protocols-plasma" +version = "0.3.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b6d8cf1eb2c1c31ed1f5643c88a6e53538129d4af80030c8cabd1f9fa884d91" +dependencies = [ + "bitflags 2.13.2", + "wayland-backend", + "wayland-client", + "wayland-protocols", + "wayland-scanner", +] + +[[package]] +name = "wayland-protocols-wlr" +version = "0.3.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eb04e52f7836d7c7976c78ca0250d61e33873c34156a2a1fc9474828ec268234" +dependencies = [ + "bitflags 2.13.2", + "wayland-backend", + "wayland-client", + "wayland-protocols", + "wayland-scanner", +] + +[[package]] +name = "wayland-scanner" +version = "0.31.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "338e30461b3a2b67d70eb30a6d89f8e0c93a833e07d2ae89085cd070c4a00ac0" +dependencies = [ + "proc-macro2", + "quick-xml 0.41.0", + "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 1.2.1", + "rustix 1.1.6", + "wayland-backend", + "wayland-scanner", +] + +[[package]] +name = "wayland-sys" +version = "0.31.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d8eab23fefc9e41f8e841df4a9c707e8a8c4ed26e944ef69297184de2785e3be" +dependencies = [ + "dlib", + "libc", + "log", + "memoffset", + "once_cell", + "pkg-config", +] + +[[package]] +name = "weak-table" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "323f4da9523e9a669e1eaf9c6e763892769b1d38c623913647bfdc1532fe4549" + +[[package]] +name = "web-sys" +version = "0.3.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7d179596ff5ec0f6de4db64d54011bde6289cc49603d3a6e4ce3f329207ab88" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "web-time" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "web-time-compat" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6ab47578e1cd38415489592da29326341e272bd281f4ddbc0c10b654a425ad7" +dependencies = [ + "web-time", +] + +[[package]] +name = "web_atoms" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba8b815c1b593dc0baf78dd0f4fc8fdb2de53198fb1163738093e9a311c33fb3" +dependencies = [ + "phf 0.13.1", + "phf_codegen", + "string_cache", + "string_cache_codegen", +] + +[[package]] +name = "webkit2gtk" +version = "2.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1027150013530fb2eaf806408df88461ae4815a45c541c8975e61d6f2fc4793" +dependencies = [ + "bitflags 1.3.2", + "cairo-rs", + "gdk", + "gdk-sys", + "gio", + "gio-sys", + "glib", + "glib-sys", + "gobject-sys", + "gtk", + "gtk-sys", + "javascriptcore-rs", + "libc", + "once_cell", + "soup3", + "webkit2gtk-sys", +] + +[[package]] +name = "webkit2gtk-sys" +version = "2.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "916a5f65c2ef0dfe12fff695960a2ec3d4565359fdbb2e9943c974e06c734ea5" +dependencies = [ + "bitflags 1.3.2", + "cairo-sys-rs", + "gdk-sys", + "gio-sys", + "glib-sys", + "gobject-sys", + "gtk-sys", + "javascriptcore-rs-sys", + "libc", + "pkg-config", + "soup3-sys", + "system-deps 6.2.2", +] + +[[package]] +name = "webpki-root-certs" +version = "1.0.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "293198dcebfb821155b5092ab94b5a82ff180eddd7241df3bd6e66a4ffd1a585" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "webpki-roots" +version = "0.26.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521bc38abb08001b01866da9f51eb7c5d647a19260e00054a8c7fd5f9e57f7a9" +dependencies = [ + "webpki-roots 1.0.12", +] + +[[package]] +name = "webpki-roots" +version = "1.0.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7265c9301c16a8711c992c2d8da90ee77ef54b1ed51482d6dfeb00dc756b1297" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "webview2-com" +version = "0.39.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f89fca7a704cee10dcb3654c1dbb8941d1783132f1917358af75bec37a7d7e6" +dependencies = [ + "webview2-com-macros", + "webview2-com-sys", + "windows 0.62.2", + "windows-core 0.62.2", +] + +[[package]] +name = "webview2-com-macros" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67a921c1b6914c367b2b823cd4cde6f96beec77d30a939c8199bb377cf9b9b54" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "webview2-com-sys" +version = "0.39.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b3a07132775117d6065853d9d1178157b8c90e228de47129d6bce2c7edebedfb" +dependencies = [ + "thiserror 2.0.21", + "windows 0.62.2", + "windows-core 0.62.2", +] + +[[package]] +name = "weezl" +version = "0.1.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a28ac98ddc8b9274cb41bb4d9d4d5c425b6020c50c46f25559911905610b4a88" + +[[package]] +name = "wgpu" +version = "30.0.0" +source = "git+https://github.com/gfx-rs/wgpu?rev=cddb2f5d80dc0009b2ef6767635140cacf90a007#cddb2f5d80dc0009b2ef6767635140cacf90a007" +dependencies = [ + "arrayvec", + "bitflags 2.13.2", + "bytemuck", + "cfg-if 1.0.5", + "cfg_aliases", + "document-features", + "hashbrown 0.17.1", + "js-sys", + "log", + "naga", + "profiling", + "raw-window-handle", + "smallvec", + "static_assertions", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", + "wgpu-core", + "wgpu-hal", + "wgpu-sync", + "wgpu-types", +] + +[[package]] +name = "wgpu-core" +version = "30.0.0" +source = "git+https://github.com/gfx-rs/wgpu?rev=cddb2f5d80dc0009b2ef6767635140cacf90a007#cddb2f5d80dc0009b2ef6767635140cacf90a007" +dependencies = [ + "arrayvec", + "bit-set 0.11.1", + "bit-vec 0.10.2", + "bitflags 2.13.2", + "bytemuck", + "cfg_aliases", + "document-features", + "hashbrown 0.17.1", + "indexmap 2.14.2", + "log", + "naga", + "naga-types", + "num-traits", + "profiling", + "raw-window-handle", + "rustc-hash 1.1.0", + "scopeguard", + "smallvec", + "thiserror 2.0.21", + "wgpu-core-deps-apple", + "wgpu-core-deps-emscripten", + "wgpu-core-deps-linux-android-bsd", + "wgpu-core-deps-windows", + "wgpu-hal", + "wgpu-naga-bridge", + "wgpu-sync", + "wgpu-types", +] + +[[package]] +name = "wgpu-core-deps-apple" +version = "30.0.0" +source = "git+https://github.com/gfx-rs/wgpu?rev=cddb2f5d80dc0009b2ef6767635140cacf90a007#cddb2f5d80dc0009b2ef6767635140cacf90a007" +dependencies = [ + "wgpu-hal", +] + +[[package]] +name = "wgpu-core-deps-emscripten" +version = "30.0.0" +source = "git+https://github.com/gfx-rs/wgpu?rev=cddb2f5d80dc0009b2ef6767635140cacf90a007#cddb2f5d80dc0009b2ef6767635140cacf90a007" +dependencies = [ + "wgpu-hal", +] + +[[package]] +name = "wgpu-core-deps-linux-android-bsd" +version = "30.0.0" +source = "git+https://github.com/gfx-rs/wgpu?rev=cddb2f5d80dc0009b2ef6767635140cacf90a007#cddb2f5d80dc0009b2ef6767635140cacf90a007" +dependencies = [ + "wgpu-hal", +] + +[[package]] +name = "wgpu-core-deps-windows" +version = "30.0.0" +source = "git+https://github.com/gfx-rs/wgpu?rev=cddb2f5d80dc0009b2ef6767635140cacf90a007#cddb2f5d80dc0009b2ef6767635140cacf90a007" +dependencies = [ + "wgpu-hal", +] + +[[package]] +name = "wgpu-hal" +version = "30.0.0" +source = "git+https://github.com/gfx-rs/wgpu?rev=cddb2f5d80dc0009b2ef6767635140cacf90a007#cddb2f5d80dc0009b2ef6767635140cacf90a007" +dependencies = [ + "android_system_properties", + "arrayvec", + "ash", + "bit-set 0.11.1", + "bitflags 2.13.2", + "block2 0.6.2", + "bytemuck", + "cfg-if 1.0.5", + "cfg_aliases", + "glow", + "glutin_wgl_sys", + "gpu-allocator", + "hashbrown 0.17.1", + "js-sys", + "khronos-egl", + "libc", + "libloading", + "log", + "naga", + "naga-types", + "ndk-sys", + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-foundation 0.3.2", + "objc2-metal 0.3.2", + "objc2-quartz-core 0.3.2", + "ordered-float 5.5.1", + "profiling", + "range-alloc", + "raw-window-handle", + "raw-window-metal", + "renderdoc-sys", + "smallvec", + "static_assertions", + "thiserror 2.0.21", + "wasm-bindgen", + "wayland-sys", + "web-sys", + "wgpu-naga-bridge", + "wgpu-sync", + "wgpu-types", + "windows 0.62.2", + "windows-core 0.62.2", + "windows-result 0.4.1", +] + +[[package]] +name = "wgpu-naga-bridge" +version = "30.0.0" +source = "git+https://github.com/gfx-rs/wgpu?rev=cddb2f5d80dc0009b2ef6767635140cacf90a007#cddb2f5d80dc0009b2ef6767635140cacf90a007" +dependencies = [ + "naga", + "wgpu-types", +] + +[[package]] +name = "wgpu-sync" +version = "30.0.0" +source = "git+https://github.com/gfx-rs/wgpu?rev=cddb2f5d80dc0009b2ef6767635140cacf90a007#cddb2f5d80dc0009b2ef6767635140cacf90a007" +dependencies = [ + "cfg-if 1.0.5", + "lock_api", + "once_cell", + "parking_lot", + "portable-atomic", + "portable-atomic-util", +] + +[[package]] +name = "wgpu-types" +version = "30.0.0" +source = "git+https://github.com/gfx-rs/wgpu?rev=cddb2f5d80dc0009b2ef6767635140cacf90a007#cddb2f5d80dc0009b2ef6767635140cacf90a007" +dependencies = [ + "bitflags 2.13.2", + "bytemuck", + "js-sys", + "log", + "macro_rules_attribute", + "naga-types", + "raw-window-handle", + "static_assertions", + "web-sys", +] + +[[package]] +name = "which" +version = "4.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87ba24419a2078cd2b0f2ede2691b6c66d8e47836da3b6db8265ebad47afbfc7" +dependencies = [ + "either", + "home", + "once_cell", + "rustix 0.38.44", +] + +[[package]] +name = "which" +version = "8.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bae2f2b2b816647a1cab1acc91f5bd20812d53cb344382635ec2181940c8034f" +dependencies = [ + "libc", +] + +[[package]] +name = "whisper-rs" +version = "0.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "71ea5d2401f30f51d08126a2d133fee4c1955136519d7ac6cf6f5ac0a91e6bc8" +dependencies = [ + "libc", + "whisper-rs-sys", +] + +[[package]] +name = "whisper-rs-sys" +version = "0.14.1" +source = "git+https://github.com/VectorPrivacy/whisper-rs.git?rev=97540c4ce03944e54aa2da3381a64947b4a824cb#97540c4ce03944e54aa2da3381a64947b4a824cb" +dependencies = [ + "bindgen 0.72.1", + "cfg-if 1.0.5", + "cmake", + "fs_extra", +] + +[[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" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72069c3113ab32ab29e5584db3c6ec55d416895e60715417b5b883a357c3e471" + +[[package]] +name = "winapi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" +dependencies = [ + "winapi-i686-pc-windows-gnu", + "winapi-x86_64-pc-windows-gnu", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" + +[[package]] +name = "winapi-util" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" + +[[package]] +name = "windows" +version = "0.54.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9252e5725dbed82865af151df558e754e4a3c2c30818359eb17465f1346a1b49" +dependencies = [ + "windows-core 0.54.0", + "windows-targets 0.52.6", +] + +[[package]] +name = "windows" +version = "0.57.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12342cb4d8e3b046f3d80effd474a7a02447231330ef77d71daa6fbc40681143" +dependencies = [ + "windows-core 0.57.0", + "windows-targets 0.52.6", +] + +[[package]] +name = "windows" +version = "0.61.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9babd3a767a4c1aef6900409f85f5d53ce2544ccdfaa86dad48c91782c6d6893" +dependencies = [ + "windows-collections 0.2.0", + "windows-core 0.61.2", + "windows-future 0.2.1", + "windows-link 0.1.3", + "windows-numerics 0.2.0", +] + +[[package]] +name = "windows" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580" +dependencies = [ + "windows-collections 0.3.2", + "windows-core 0.62.2", + "windows-future 0.3.2", + "windows-numerics 0.3.1", +] + +[[package]] +name = "windows-capture" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a4df73e95feddb9ec1a7e9c2ca6323b8c97d5eeeff78d28f1eccdf19c882b24" +dependencies = [ + "parking_lot", + "rayon", + "thiserror 2.0.21", + "windows 0.61.3", + "windows-future 0.2.1", +] + +[[package]] +name = "windows-collections" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3beeceb5e5cfd9eb1d76b381630e82c4241ccd0d27f1a39ed41b2760b255c5e8" +dependencies = [ + "windows-core 0.61.2", +] + +[[package]] +name = "windows-collections" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610" +dependencies = [ + "windows-core 0.62.2", +] + +[[package]] +name = "windows-core" +version = "0.54.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12661b9c89351d684a50a8a643ce5f608e20243b9fb84687800163429f161d65" +dependencies = [ + "windows-result 0.1.2", + "windows-targets 0.52.6", +] + +[[package]] +name = "windows-core" +version = "0.57.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2ed2439a290666cd67ecce2b0ffaad89c2a56b976b736e6ece670297897832d" +dependencies = [ + "windows-implement 0.57.0", + "windows-interface 0.57.0", + "windows-result 0.1.2", + "windows-targets 0.52.6", +] + +[[package]] +name = "windows-core" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0fdd3ddb90610c7638aa2b3a3ab2904fb9e5cdbecc643ddb3647212781c4ae3" +dependencies = [ + "windows-implement 0.60.2", + "windows-interface 0.59.3", + "windows-link 0.1.3", + "windows-result 0.3.4", + "windows-strings 0.4.2", +] + +[[package]] +name = "windows-core" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" +dependencies = [ + "windows-implement 0.60.2", + "windows-interface 0.59.3", + "windows-link 0.2.1", + "windows-result 0.4.1", + "windows-strings 0.5.1", +] + +[[package]] +name = "windows-core" +version = "0.100.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "803590c6856f51d15fa2e9fabe4f4703122c8737f72ef2741b4ac09d4c2192f5" +dependencies = [ + "windows-implement 0.100.0", + "windows-interface 0.100.0", + "windows-link 0.100.0", + "windows-result 0.100.0", + "windows-strings 0.100.0", +] + +[[package]] +name = "windows-future" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc6a41e98427b19fe4b73c550f060b59fa592d7d686537eebf9385621bfbad8e" +dependencies = [ + "windows-core 0.61.2", + "windows-link 0.1.3", + "windows-threading 0.1.0", +] + +[[package]] +name = "windows-future" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb" +dependencies = [ + "windows-core 0.62.2", + "windows-link 0.2.1", + "windows-threading 0.2.1", +] + +[[package]] +name = "windows-implement" +version = "0.57.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9107ddc059d5b6fbfbffdfa7a7fe3e22a226def0b2608f72e9d552763d3e1ad7" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-implement" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-implement" +version = "0.100.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1bc1bc82e5a1b1a4d7255861b07881a0407b552f50a4d8543c0c7276fa96f6e8" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-interface" +version = "0.57.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29bee4b38ea3cde66011baa44dba677c432a78593e202392d1e9070cf2a7fca7" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-interface" +version = "0.59.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-interface" +version = "0.100.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b3f7005c3b757b9b82c2f40c0e71094ff1080adddaf3e8b6ce99b545d3c48796" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-link" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e6ad25900d524eaabdbbb96d20b4311e1e7ae1699af4fb28c17ae66c80d798a" + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-link" +version = "0.100.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b39de7c7fe78858b0144c50c3fc000bab3be17d5e9b85b1053871693c7f7415" + +[[package]] +name = "windows-numerics" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9150af68066c4c5c07ddc0ce30421554771e528bde427614c61038bc2c92c2b1" +dependencies = [ + "windows-core 0.61.2", + "windows-link 0.1.3", +] + +[[package]] +name = "windows-numerics" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26" +dependencies = [ + "windows-core 0.62.2", + "windows-link 0.2.1", +] + +[[package]] +name = "windows-registry" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02752bf7fbdcce7f2a27a742f798510f3e5ad88dbe84871e5168e2120c3d5720" +dependencies = [ + "windows-link 0.2.1", + "windows-result 0.4.1", + "windows-strings 0.5.1", +] + +[[package]] +name = "windows-result" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e383302e8ec8515204254685643de10811af0ed97ea37210dc26fb0032647f8" +dependencies = [ + "windows-targets 0.52.6", +] + +[[package]] +name = "windows-result" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "56f42bd332cc6c8eac5af113fc0c1fd6a8fd2aa08a0119358686e5160d0586c6" +dependencies = [ + "windows-link 0.1.3", +] + +[[package]] +name = "windows-result" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" +dependencies = [ + "windows-link 0.2.1", +] + +[[package]] +name = "windows-result" +version = "0.100.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44873a1ef61c85d5e2991db91fe656cfcf0731097e00dff1ac860f1cb3b752a0" +dependencies = [ + "windows-link 0.100.0", +] + +[[package]] +name = "windows-strings" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "56e6c93f3a0c3b36176cb1327a4958a0353d5d166c2a35cb268ace15e91d3b57" +dependencies = [ + "windows-link 0.1.3", +] + +[[package]] +name = "windows-strings" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" +dependencies = [ + "windows-link 0.2.1", +] + +[[package]] +name = "windows-strings" +version = "0.100.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a70b590c684f1d2854f74999896f7c0558f1bdde62f599088599e20ea1d2f60" +dependencies = [ + "windows-link 0.100.0", +] + +[[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.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets 0.52.6", +] + +[[package]] +name = "windows-sys" +version = "0.59.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" +dependencies = [ + "windows-targets 0.52.6", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +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.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm 0.52.6", + "windows_aarch64_msvc 0.52.6", + "windows_i686_gnu 0.52.6", + "windows_i686_gnullvm", + "windows_i686_msvc 0.52.6", + "windows_x86_64_gnu 0.52.6", + "windows_x86_64_gnullvm 0.52.6", + "windows_x86_64_msvc 0.52.6", +] + +[[package]] +name = "windows-threading" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b66463ad2e0ea3bbf808b7f1d371311c80e115c0b71d60efc142cafbcfb057a6" +dependencies = [ + "windows-link 0.1.3", +] + +[[package]] +name = "windows-threading" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37" +dependencies = [ + "windows-link 0.2.1", +] + +[[package]] +name = "windows-version" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4060a1da109b9d0326b7262c8e12c84df67cc0dbc9e33cf49e01ccc2eb63631" +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.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[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.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[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.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[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.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[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.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[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.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[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.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[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" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df79d97927682d2fd8adb29682d1140b343be4ac0f08fd68b7765d9c059d3945" +dependencies = [ + "memchr", +] + +[[package]] +name = "winnow" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c3b93199df0ab874cdf0c6a94f0a0dc3423fe41f1cafb62b8bd7b1deb277aef" +dependencies = [ + "memchr", +] + +[[package]] +name = "winreg" +version = "0.56.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d6f32a0ff4a9f6f01231eb2059cc85479330739333e0e58cadf03b6af2cca10" +dependencies = [ + "cfg-if 1.0.5", + "windows-sys 0.61.2", +] + +[[package]] +name = "wio" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d129932f4644ac2396cb456385cbf9e63b5b30c6e8dc4820bdca4eb082037a5" +dependencies = [ + "winapi", +] + +[[package]] +name = "wit-bindgen" +version = "0.57.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" + +[[package]] +name = "wmi" +version = "0.18.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7c81b85c57a57500e56669586496bf2abd5cf082b9d32995251185d105208b64" +dependencies = [ + "chrono", + "futures", + "log", + "serde", + "thiserror 2.0.21", + "windows 0.62.2", + "windows-core 0.62.2", +] + +[[package]] +name = "writeable" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" + +[[package]] +name = "wry" +version = "0.57.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a819957a01b3119af85e638a38d242af76dbc87d130dca67bfd0441072e21ff0" +dependencies = [ + "base64 0.22.1", + "block2 0.6.2", + "cookie", + "crossbeam-channel", + "dirs 7.0.0", + "dom_query", + "dpi", + "dunce", + "gtk", + "http", + "javascriptcore-rs", + "jni 0.21.1", + "libc", + "ndk", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "objc2-core-foundation", + "objc2-foundation 0.3.2", + "objc2-ui-kit", + "objc2-web-kit", + "once_cell", + "percent-encoding", + "raw-window-handle", + "sha2 0.10.9", + "soup3", + "tao-macros", + "thiserror 2.0.21", + "url", + "webkit2gtk", + "webkit2gtk-sys", + "webview2-com", + "windows 0.62.2", + "windows-core 0.62.2", + "windows-version", +] + +[[package]] +name = "ws_stream_wasm" +version = "0.7.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c173014acad22e83f16403ee360115b38846fe754e735c5d9d3803fe70c6abc" +dependencies = [ + "async_io_stream", + "futures", + "js-sys", + "log", + "pharos", + "rustc_version", + "send_wrapper", + "thiserror 2.0.21", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + +[[package]] +name = "wyz" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05f360fc0b24296329c78fda852a1e9ae82de9cf7b27dae4b7f62f118f77b9ed" +dependencies = [ + "tap", +] + +[[package]] +name = "x11" +version = "2.21.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "502da5464ccd04011667b11c435cb992822c2c0dbde1770c988480d312a0db2e" +dependencies = [ + "libc", + "pkg-config", +] + +[[package]] +name = "x11rb" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9993aa5be5a26815fe2c3eacfc1fde061fc1a1f094bf1ad2a18bf9c495dd7414" +dependencies = [ + "as-raw-xcb-connection", + "gethostname", + "libc", + "rustix 1.1.6", + "x11rb-protocol", + "xcursor", +] + +[[package]] +name = "x11rb-protocol" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea6fc2961e4ef194dcbfe56bb845534d0dc8098940c7e5c012a258bfec6701bd" + +[[package]] +name = "x25519-dalek" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c7e468321c81fb07fa7f4c636c3972b9100f0346e5b6a9f2bd0603a52f7ed277" +dependencies = [ + "curve25519-dalek 4.1.3", + "rand_core 0.6.4", + "serde", + "zeroize", +] + +[[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]] +name = "xcb" +version = "1.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6c2ad15e0e922856ee89afe862b8992334bbe7953adad56cd1199358cb30566" +dependencies = [ + "bitflags 2.13.2", + "libc", + "quick-xml 0.41.0", + "x11", +] + +[[package]] +name = "xcursor" +version = "0.3.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "163b33ed8786455e2fa5d72f554057ce3f3182425434f756cd39c99839d88e23" + +[[package]] +name = "xim-ctext" +version = "0.3.0" +source = "git+https://github.com/zed-industries/xim-rs.git?rev=16f35a2c881b815a2b6cdfd6687988e84f8447d8#16f35a2c881b815a2b6cdfd6687988e84f8447d8" +dependencies = [ + "encoding_rs", +] + +[[package]] +name = "xim-parser" +version = "0.2.1" +source = "git+https://github.com/zed-industries/xim-rs.git?rev=16f35a2c881b815a2b6cdfd6687988e84f8447d8#16f35a2c881b815a2b6cdfd6687988e84f8447d8" +dependencies = [ + "bitflags 2.13.2", +] + +[[package]] +name = "xkbcommon" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8d66ca9352cbd4eecbbc40871d8a11b4ac8107cfc528a6e14d7c19c69d0e1ac9" +dependencies = [ + "as-raw-xcb-connection", + "libc", + "memmap2", + "xkeysym", +] + +[[package]] +name = "xkeysym" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9cc00251562a284751c9973bace760d86c0276c471b4be569fe6b068ee97a56" + +[[package]] +name = "xml-rs" +version = "0.8.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e450f9b2ed1dff33c94c12589a87338689467b9c4f5d8a5710bd09a847d2c8a7" + +[[package]] +name = "xmlwriter" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec7a2a501ed189703dba8b08142f057e887dfc4b2cc4db2d343ac6376ba3e0b9" + +[[package]] +name = "y4m" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a5a4b21e1a62b67a2970e6831bc091d7b87e119e7f9791aef9702e3bef04448" + +[[package]] +name = "yazi" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac366ea532fa8ee6a992cec9dea525b1dc284e69702f36c2ab5fbebadc81ec86" + +[[package]] +name = "yeslogic-fontconfig-sys" +version = "6.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d8b8abf912b9a29ff112e1671c97c33636903d13a69712037190e6805af4f76" +dependencies = [ + "dlib", + "once_cell", + "pkg-config", +] + +[[package]] +name = "yoke" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "417ef3fcf6c300b7dbd25c85531a746931c02ad536f3cf4786ed1e88223340b3" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", + "synstructure 0.14.0", +] + +[[package]] +name = "zbus" +version = "5.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5db4be7c075cb421e4b7ee645541604239bd243ba7c357511f4ff3a74b555907" +dependencies = [ + "async-broadcast", + "async-executor", + "async-io", + "async-lock", + "async-process", + "async-recursion", + "async-task", + "async-trait", + "blocking", + "enumflags2", + "event-listener", + "futures-core", + "futures-lite", + "hex", + "libc", + "ordered-stream", + "rustix 1.1.6", + "serde", + "serde_repr", + "tracing", + "uds_windows", + "uuid", + "windows-sys 0.61.2", + "winnow 1.0.5", + "zbus_macros 5.19.0", + "zbus_names", + "zvariant", +] + +[[package]] +name = "zbus" +version = "6.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ddb2961d9587ef9f24ad14cde1c3bc4c5edc9f1525932a8cffdd5bd98886eb9" +dependencies = [ + "async-trait", + "bitflags 2.13.2", + "endi", + "futures-core", + "hex", + "libc", + "ordered-stream", + "rustix 1.1.6", + "serde", + "serde_repr", + "socket2", + "uds_windows", + "uuid", + "windows-sys 0.61.2", + "winnow 1.0.5", + "zbus_macros 6.2.1", + "zbus_utils", + "zcheapstr", + "zruntime", +] + +[[package]] +name = "zbus-lockstep" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6998de05217a084b7578728a9443d04ea4cd80f2a0839b8d78770b76ccd45863" +dependencies = [ + "zbus_xml", + "zvariant", +] + +[[package]] +name = "zbus-lockstep-macros" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10da05367f3a7b7553c8cdf8fa91aee6b64afebe32b51c95177957efc47ca3a0" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", + "zbus-lockstep", + "zbus_xml", + "zvariant", +] + +[[package]] +name = "zbus_macros" +version = "5.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2990635d09ade6df1868f72f8cac69a876a90981e8bd3c40b1be413f8dc88f40" +dependencies = [ + "proc-macro-crate 3.5.0", + "proc-macro2", + "quote", + "syn 3.0.10", + "zbus_names", + "zvariant", + "zvariant_utils", +] + +[[package]] +name = "zbus_macros" +version = "6.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "083b38add47c340fc12ec560124fb1d9c23acb584f7021099f85ec6587a03c54" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", + "zbus_utils", +] + +[[package]] +name = "zbus_names" +version = "4.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "812a12be4ead7a59e18ea8f047d08add0066b73bc62fc1467066a2472ae088dd" +dependencies = [ + "serde", + "winnow 1.0.5", + "zvariant", +] + +[[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.10", + "winnow 1.0.5", +] + +[[package]] +name = "zbus_xml" +version = "5.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1586c021a01ca0a9216dcd874e546382e156a5cbab5fab6cb5f10087e22682a" +dependencies = [ + "serde", + "winnow 1.0.5", + "zbus_names", + "zvariant", +] + +[[package]] +name = "zcheapstr" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "939f186d9ecebe044315a5cb6d6f78568bbc21152adc954d5a0c2f58bdbc9920" +dependencies = [ + "serde", +] + +[[package]] +name = "zed-font-kit" +version = "0.14.1-zed" +source = "git+https://github.com/zed-industries/font-kit?rev=94b0f28166665e8fd2f53ff6d268a14955c82269#94b0f28166665e8fd2f53ff6d268a14955c82269" +dependencies = [ + "bitflags 2.13.2", + "byteorder", + "core-foundation 0.10.1", + "core-graphics 0.24.0", + "core-text", + "dirs 6.0.0", + "dwrote", + "float-ord", + "freetype-sys", + "lazy_static", + "libc", + "log", + "pathfinder_geometry", + "pathfinder_simd", + "walkdir", + "winapi", + "yeslogic-fontconfig-sys", +] + +[[package]] +name = "zed-scap" +version = "0.0.8-zed" +source = "git+https://github.com/zed-industries/scap?rev=b5c86ec58dd4b6b7732bf6ac8be03d6b1f190a82#b5c86ec58dd4b6b7732bf6ac8be03d6b1f190a82" +dependencies = [ + "anyhow", + "log", + "rand 0.8.8", + "sysinfo 0.31.4", + "windows 0.61.3", + "windows-capture", + "x11", + "xcb", +] + +[[package]] +name = "zed-xim" +version = "0.4.0-zed" +source = "git+https://github.com/zed-industries/xim-rs.git?rev=16f35a2c881b815a2b6cdfd6687988e84f8447d8#16f35a2c881b815a2b6cdfd6687988e84f8447d8" +dependencies = [ + "ahash 0.8.12", + "hashbrown 0.14.5", + "log", + "x11rb", + "xim-ctext", + "xim-parser", +] + +[[package]] +name = "zeno" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6df3dc4292935e51816d896edcd52aa30bc297907c26167fec31e2b0c6a32524" + +[[package]] +name = "zerocopy" +version = "0.8.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5fe1f8f1b06191a00962174c61aa5005e0bb391a6d80d07e24d115c01a92ed8" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "863ad3ac83293fb4d740aedbfdc9240dd8d1a50c1099acd76ce80ce7c7230c7f" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", + "synstructure 0.14.0", +] + +[[package]] +name = "zeroize" +version = "1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" +dependencies = [ + "zeroize_derive", +] + +[[package]] +name = "zeroize_derive" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c50655cbb0fe3fc43170059e702f1ce5e19b84cec58dc87b037a09935c2f328" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zerotrie" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "zerovec" +version = "0.11.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f58a2799cfe9a1670c7ea8edbd52ef8edb93cb37a7f83bf31ba9e35d9dae6a40" +dependencies = [ + "serde", + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3743ddbf47738d929cd1ae2e199d40d0162979dfe31aef8ae646d2bf00bf97a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "zip" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1dcb24d0152526ae49b9b96c1dcf71850ca1e0b882e4e28ed898a93c41334744" +dependencies = [ + "arbitrary", + "crc32fast", + "crossbeam-utils", + "flate2", + "indexmap 2.14.2", + "memchr", +] + +[[package]] +name = "zlib-rs" +version = "0.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112" + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" + +[[package]] +name = "zruntime" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23ef5ed7d628cdf0af82f93dfe03330a8e37383bf7422a1d3d6eb72326680be5" +dependencies = [ + "futures-core", + "futures-io", + "rustix 1.1.6", + "socket2", + "windows-sys 0.61.2", +] + +[[package]] +name = "ztracing" +version = "0.1.0" +source = "git+https://github.com/zed-industries/zed?rev=f8cfc7ed9e57503def9479138894f3139f5400cc#f8cfc7ed9e57503def9479138894f3139f5400cc" +dependencies = [ + "tracing", + "ztracing_macro", +] + +[[package]] +name = "ztracing_macro" +version = "0.1.0" +source = "git+https://github.com/zed-industries/zed?rev=f8cfc7ed9e57503def9479138894f3139f5400cc#f8cfc7ed9e57503def9479138894f3139f5400cc" + +[[package]] +name = "zune-core" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d56377fd46368984a170bc5aac5567e52ca5da874caa60bea39fcbca78fb658b" + +[[package]] +name = "zune-inflate" +version = "0.2.54" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73ab332fe2f6680068f3582b16a24f90ad7096d5d39b974d1c0aff0125116f02" +dependencies = [ + "simd-adler32", +] + +[[package]] +name = "zune-jpeg" +version = "0.5.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27bc9d5b815bc103f142aa054f561d9187d191692ec7c2d1e2b4737f8dbd7296" +dependencies = [ + "zune-core", +] + +[[package]] +name = "zvariant" +version = "5.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "80bf6d6cd6a4b601acb64cfb8284cdc643fcfa75ef26ae3c46ec8aa4e8a1fbb7" +dependencies = [ + "endi", + "enumflags2", + "serde", + "serde_bytes", + "winnow 1.0.5", + "zcheapstr", + "zvariant_derive", + "zvariant_utils", +] + +[[package]] +name = "zvariant_derive" +version = "5.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef2672456ba1cb54b5eaec136e63135b3c7495fb938e53b28a62e633496d486d" +dependencies = [ + "proc-macro-crate 3.5.0", + "proc-macro2", + "quote", + "syn 3.0.10", + "zvariant_utils", +] + +[[package]] +name = "zvariant_utils" +version = "4.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bad0294361a320b694a328460dc73add56c306150f5cb6bfafc44446120008a3" +dependencies = [ + "proc-macro2", + "quote", + "serde", + "syn 3.0.10", + "winnow 1.0.5", +] diff --git a/crates/vector-gpui/Cargo.toml b/crates/vector-gpui/Cargo.toml new file mode 100644 index 000000000..9b2b10972 --- /dev/null +++ b/crates/vector-gpui/Cargo.toml @@ -0,0 +1,258 @@ +[package] +name = "vector-gpui" +version = "0.6.0-1" +edition = "2024" +license = "MIT" +description = "Vector on GPUI: the native-rendered client, at parity with the Tauri one." +publish = false + +# A library under a small binary, so Android can load the same client as a cdylib +# (`cargo rustc --lib --crate-type cdylib`). +[lib] +name = "vector_gpui" +path = "src/lib.rs" +doctest = false + +[[bin]] +name = "vector-gpui" +path = "src/main.rs" + +[features] +default = ["video", "tor", "i2p"] +# Measuring only: every allocation recorded with its stack; `dev:dhat` writes dhat-heap.json. +dhat-heap = ["dep:dhat", "devctl"] +# Embedded Tor (Arti) and I2P through the user's router: the networks Routing offers. +tor = ["vector-core/tor"] +i2p = ["vector-core/i2p"] +# Video attachments decode through FFmpeg: the system's, or the desktop client's selective +# static build (scripts/build-ffmpeg.sh) with FFMPEG_DIR set and `video-static`. +video = ["dep:ffmpeg-next"] +# The static build's Opus decoder resamples through swresample, so it links too. +video-static = ["video", "ffmpeg-next/static", "ffmpeg-next/software-resampling"] +# Dev builds: `dev:` commands from a second launch drive and measure the window (src/devctl.rs). +devctl = [] +# The F-Droid flavour: its store installs every update, so no in-app installer. +fdroid = ["vector-media/fdroid"] +# Test builds (Android debug APKs, which still compile optimised): a fuller log, kept in a file +# the phone's Files app can read too. +test-build = [] + +[dependencies] +dhat = { version = "0.3", optional = true } +gpui = { git = "https://github.com/zed-industries/zed", rev = "f8cfc7ed9e57503def9479138894f3139f5400cc" } +gpui_platform = { git = "https://github.com/zed-industries/zed", rev = "f8cfc7ed9e57503def9479138894f3139f5400cc", default-features = false, features = ["x11", "wayland", "font-kit"] } +vector-core = { path = "../vector-core", features = ["calls", "xdc"] } +vector-i18n = { path = "../vector-i18n" } +sys-locale = "0.3" +anyhow = "1" +unicode-segmentation = "1" +unicode-bidi = "0.3" +unicode-bidi-mirroring = "0.4" +png = "0.18" +serde = { version = "1", features = ["derive"] } +serde_json = "1" +chrono = { version = "0.4", default-features = false, features = ["clock", "std"] } +rust-embed = { version = "8", features = ["interpolate-folder-path"] } +log = "0.4" +env_logger = "0.11" +# The live account: core's runtime and the crates its API speaks in. +tokio = { version = "1.49.0", features = ["rt-multi-thread", "sync", "time", "macros", "fs"] } +futures = "0.3" +sysinfo = { version = "0.31", default-features = false, features = ["system"] } +rand = "0.8" +base64 = "0.22" +nostr-sdk = "=0.45.6" +bip39 = "2.2.2" +zeroize = "1.8" +rusqlite = { version = "0.38", features = ["bundled"] } +reqwest = { version = "0.13", default-features = false } +dirs = "6" +# The message renderer. +pulldown-cmark = { version = "0.13", default-features = false } +unicode-linebreak = "0.1" +# Attachments: decoded at the size they draw. +image = { version = "0.25", default-features = false, features = ["png", "jpeg", "gif", "webp", "bmp", "tiff", "ico"] } +fast-thumbhash = "0.2" +qrcodegen = "1.8" +# Reading QR codes off the camera. +rqrr = { version = "0.11", default-features = false } +# The desktop client's image codecs, compiled from its sources (src/simd.rs, src/shared.rs). +gif = "0.14" +libwebp-sys = "0.9" +rayon = "1.11.0" +jxl-oxide = { version = "0.12", default-features = false, features = ["image", "rayon"] } +fast_image_resize = "5.5" +crc32fast = "1.5" +simd-adler32 = "0.3" +memchr = "2" +unicode-properties = { version = "0.1", default-features = false, features = ["general-category"] } +zip = { version = "2.4", default-features = false, features = ["deflate-flate2", "flate2"] } +flate2 = { version = "1.1", default-features = false, features = ["zlib-rs"] } +# In-app updates: the release key's signature on each bundle. +minisign-verify = "0.2" +# Notification sounds: decode, resample, play. +cpal = "0.16" +symphonia = { version = "0.5.5", default-features = false, features = ["mp3", "wav", "aiff", "flac", "pcm", "aac", "isomp4", "ogg", "vorbis", "opt-simd"] } +# Calls, devices and the audio engine: the desktop client's own modules (media/). +vector-media = { package = "vector-gpui-media", path = "media" } +tauri = { package = "vector-tauri-shim", path = "tauri-shim" } +ffmpeg-next = { version = "9", default-features = false, features = ["codec", "format", "software-resampling"], optional = true } +http = "1.3" +url = "2.5.7" +# 3D model attachments: parsed here, drawn offscreen on the GPU (src/model3d). +glam = { version = "0.30", features = ["bytemuck"] } +bytemuck = { version = "1", features = ["derive"] } +gltf = { version = "1.4", default-features = false, features = ["utils", "names", "KHR_materials_emissive_strength", "KHR_texture_transform", "KHR_materials_unlit"] } +tobj = { version = "4", default-features = false } +fbxcel = { version = "0.9", features = ["tree"] } +pollster = "0.4" +# Call video: H.264 both ways (the codec WebCodecs peers send), and the camera. +openh264 = "0.9" +bytes = "1" +dom_query = "0.28" + +# Screen sharing: X11 read directly; macOS and Windows through xcap. +[target.'cfg(not(any(target_os = "linux", target_os = "android")))'.dependencies] +xcap = "0.9" + +[target.'cfg(not(target_os = "android"))'.dependencies] +arboard = { version = "3.7", default-features = false } +# The camera; Android's comes through the shell's Camera2 feed. +nokhwa = { version = "0.10", features = ["input-native"] } + +[target.'cfg(target_os = "android")'.dependencies] +jni = "0.21.1" +libc = "0.2" +ndk-context = "0.1.1" +# The VAPID key a push endpoint is asked for with. +vector-push = { path = "../vector-push", features = ["vapid"] } +# The window's own device, which 3D models draw with too. +gpui_wgpu = { git = "https://github.com/zed-industries/zed", rev = "f8cfc7ed9e57503def9479138894f3139f5400cc" } + +# The same wgpu GPUI draws with on Linux; elsewhere its default backends (Metal, DX12). +[target.'cfg(any(target_os = "linux", target_os = "freebsd"))'.dependencies.wgpu] +git = "https://github.com/gfx-rs/wgpu" +rev = "cddb2f5d80dc0009b2ef6767635140cacf90a007" +default-features = false +features = ["std", "metal", "gles", "vulkan", "wgsl", "webgpu"] + +[target.'cfg(not(any(target_os = "linux", target_os = "freebsd")))'.dependencies.wgpu] +git = "https://github.com/gfx-rs/wgpu" +rev = "cddb2f5d80dc0009b2ef6767635140cacf90a007" + +# File references on the clipboard, which GPUI writes only as text there. +[target.'cfg(target_os = "macos")'.dependencies] +tar = { version = "0.4", default-features = false } +libc = "0.2" +objc2 = "0.6" +block2 = "0.6" +objc2-metal = { version = "0.3", default-features = false, features = ["std", "MTLDevice", "MTLCommandQueue"] } +objc2-foundation = { version = "0.3", features = ["NSString", "NSArray", "NSURL", "NSEnumerator", "NSRange", "NSObjCRuntime", "NSDateFormatter", "NSFormatter", "NSLocale"] } +objc2-app-kit = { version = "0.3", features = ["NSPasteboard", "NSPasteboardItem", "NSApplication", "NSDockTile", "NSResponder", "NSWindow", "NSView", "NSButton", "NSControl", "NSSpellChecker"] } +raw-window-handle = "0.6" + +[target.'cfg(windows)'.dependencies] +clipboard-win = "5" +raw-window-handle = "0.6" +windows = { version = "0.61", features = ["Win32_Foundation", "Win32_Globalization", "Win32_Graphics_Gdi", "Win32_System_Com", "Win32_System_DataExchange", "Win32_System_LibraryLoader", "Win32_System_Threading", "Win32_UI_Shell", "Win32_UI_WindowsAndMessaging"] } + +# Elsewhere wry lays the OS webview into a GPUI window of the app's own. +[target.'cfg(not(any(target_os = "linux", target_os = "android")))'.dependencies.wry] +version = "=0.57.0" +default-features = false +features = ["os-webview"] + +# Mini Apps run in the OS webview, through the desktop client's own webview crate. +[target.'cfg(target_os = "linux")'.dependencies] +wry = { version = "=0.57.0", default-features = false, features = ["os-webview", "linux-body"] } +gtk = "0.18" +webkit2gtk = { version = "2.0", features = ["v2_40"] } +x11rb = { version = "0.13", features = ["randr"] } +zbus = { version = "5.19", features = ["blocking-api"] } +libc = "0.2" +# The windows' own device, which 3D models draw with too. +gpui_wgpu = { git = "https://github.com/zed-industries/zed", rev = "f8cfc7ed9e57503def9479138894f3139f5400cc" } + +# Its own workspace: GPUI pins dependency versions the main client must not inherit. +[workspace] +members = [".", "vendor/jpeg-decoder"] + +[profile.dev] +debug = "line-tables-only" + +[profile.dev.package."*"] +opt-level = 3 +debug = false + +# A workspace member, so "*" above doesn't reach it. +[profile.dev.package.vector-jpeg] +opt-level = 3 +debug = false + +[profile.release] +lto = "fat" +codegen-units = 1 +# Unwind: a panic in a background decoder or task ends that work, not the app. +strip = true + +# Day-to-day optimised builds: every core, incremental, close to release speed. +[profile.fastrel] +inherits = "release" +lto = false +codegen-units = 16 +incremental = true +debug = "line-tables-only" +strip = false + +[patch.crates-io] +# whisper.cpp 1.9.5 with scripts/whisper/patches, as the desktop client builds it. +whisper-rs-sys = { git = "https://github.com/VectorPrivacy/whisper-rs.git", rev = "97540c4ce03944e54aa2da3381a64947b4a824cb" } +nostr = { git = "https://github.com/VectorPrivacy/nostr.git", branch = "vector-v0.45.6" } +nostr-sdk = { git = "https://github.com/VectorPrivacy/nostr.git", branch = "vector-v0.45.6" } +nostr-database = { git = "https://github.com/VectorPrivacy/nostr.git", branch = "vector-v0.45.6" } +saturating-time = { path = "../vendor/saturating-time" } +# cosmic-text 0.19.0, reading each face's weight axis once rather than per new font match. +cosmic-text = { path = "vendor/cosmic-text" } +# ndk 0.9.0 with the desktop client's switch that opens every AAudio stream as a phone call's. +ndk = { path = "../vendor/ndk" } +async-process = { git = "https://github.com/zed-industries/async-process.git", rev = "0b6d6713570af61806e1e5cb40e0f757cb93fd9d" } +async-task = { git = "https://github.com/zed-industries/async-task.git", rev = "015845a19fc31752c02367567d3b8900a406f9da" } +calloop = { git = "https://github.com/zed-industries/calloop", rev = "3759371fee14c40066d64777e2a36b6ffcc22590" } +khronos-egl = { git = "https://github.com/zed-industries/khronos-egl", rev = "42214b36347b108fd9630ca6254b96dde59e04fe" } + + +[dev-dependencies] +# The shared simd module checks its quantiser against this reference. +color_quant = "1.1" +# The desktop's video encoder tests, built in with it. +tempfile = "3" +# The scanners that replaced regexes are tested against the patterns they replace. +regex = "1" +# JPEG thumbnails are checked against the decode, rotate, crop and resize they replaced. +jpeg-decoder = { package = "vector-jpeg", path = "vendor/jpeg-decoder" } + +# Each platform's own shaper, for the bidi test that needs no window. +[target.'cfg(target_os = "macos")'.dev-dependencies] +gpui_apple = { git = "https://github.com/zed-industries/zed", rev = "f8cfc7ed9e57503def9479138894f3139f5400cc" } +[target.'cfg(target_os = "windows")'.dev-dependencies] +gpui_windows = { git = "https://github.com/zed-industries/zed", rev = "f8cfc7ed9e57503def9479138894f3139f5400cc" } + +# gpui_linux at the same rev, plus file references on the clipboard (text/uri-list) for X11 and Wayland. +[patch."https://github.com/zed-industries/zed"] +# gpui at the same rev: animated images redraw when their next frame is due, not every vsync. +gpui = { path = "vendor/gpui" } +gpui_linux = { path = "vendor/gpui_linux" } +# gpui_macos at the same rev: the open panel takes file-type filters. +gpui_macos = { path = "vendor/gpui_macos" } +# gpui_apple at the same rev: an element's own box-shadow stays outside its box, as in CSS. +gpui_apple = { path = "vendor/gpui_apple" } +# gpui_windows at the same rev: the open dialog takes file-type filters. +gpui_windows = { path = "vendor/gpui_windows" } +# gpui_wgpu at the same rev, bringing up one GPU API (Vulkan, else GL) instead of both, and finding +# Android's system fonts. +gpui_wgpu = { path = "vendor/gpui_wgpu" } +# gpui_platform at the same rev, with Android's platform (vendor/gpui_android, ours). +gpui_platform = { path = "vendor/gpui_platform" } + +[build-dependencies] +jpegxl-src = "0.12" diff --git a/crates/vector-gpui/README.md b/crates/vector-gpui/README.md new file mode 100644 index 000000000..b2b82a73c --- /dev/null +++ b/crates/vector-gpui/README.md @@ -0,0 +1,78 @@ +# vector-gpui + +Vector drawn natively with [GPUI](https://github.com/zed-industries/zed/tree/main/crates/gpui), Zed's +GPU UI framework, instead of a webview. The goal is parity with the Tauri client: the same layout, +measurements, palette, fonts and behaviour, from the same `vector-core`. + +It is an experiment on the `gpui` branch and builds on its own (its own workspace and lockfile), so +nothing here touches the Tauri client's dependency graph. + +## Run + +```bash +cd crates/vector-gpui +cargo run -- --open # fixture data from reference/fixtures.json +cargo run -- --size 385x650 # any window size +cargo run --release # fat LTO, one codegen unit +``` + +Linux needs the usual GPUI packages: `libxkbcommon-dev libxkbcommon-x11-dev libwayland-dev +libx11-xcb-dev libvulkan-dev libfontconfig1-dev libfreetype-dev`. + +Video attachments decode through FFmpeg (the default `video` feature): the system's +(`libavcodec-dev libavformat-dev libavutil-dev clang`), or the desktop +client's selective static build with `FFMPEG_DIR` set and `--features video-static`. +`--no-default-features` draws every clip as a file. + +## Layout + +- `src/theme.rs`: the palette, as the CSS resolves it. +- `src/data.rs`: the store (vector-core's `SerializableChat` / `SlimProfile`) and the derivations the + JS makes from them (names, previews, unread counts, time labels). Each names the JS function it mirrors. +- `src/ui.rs`: the widescreen shell: window chrome, rail, chat list, chat. +- `src/composer.rs`: the message field (GPUI's input example, restyled), with IME support. +- `src/assets.rs`: icons and fonts compiled in. `icons/` *is* `src/icons`, so an icon the Tauri + client changes arrives here on the next build. +- `assets/fonts`: Rubik (static instances cut from `src/fonts/Rubik.woff2`) and Inter. + +GPUI is pinned to one Zed revision in `Cargo.toml`, and moves only on purpose. + +## Text and languages + +Every string a person reads comes from `crates/vector-i18n/locales/en-GB` through `t::`, and the +`i18n_audit` test fails on new hard-coded English. Translators work from +`crates/vector-i18n/TRANSLATING.md`. + +A right-to-left language mirrors the layout inside the GPUI fork (`gpui::layout_rtl()`), so most +screens need nothing. The exceptions: + +- `.keep_ltr()` on what reads left to right in every language: code, PIN and digit entry, + playback controls, a picture panned under the pointer. +- Message text is `Inline::dir_auto()`, so an English paragraph stays left; any other `Inline` + sits at the start edge. +- A sideways scroller reads its position with `kit::scrolled` and moves with + `kit::scroll_from_start`. +- An icon that points along the reading direction goes in `lang::MIRRORED_ICONS`. +- Counts and clocks built in code go through `lang::num` and `lang::digits`. +- A sentence styled in one piece is `kit::run_text`. One built from several elements (a link, a + hover name) puts its pieces through `kit::visual` in a `keep_ltr` row; where a piece is a + widget, the row takes `keep_ltr` only when `kit::reads_ltr`. + +`VECTOR_LANG=ar-XB` shows English mirrored, for checking a screen. + +## Parity checks + +`reference/` renders the real Tauri frontend in Chromium on the same fixtures, so the two can be +compared pixel by pixel: + +```bash +node reference/gen-fixtures.mjs # fixtures.json + deterministic ids +npm run svelte:build # (repo root) the Svelte bundle +NODE_PATH=$(npm root -g) node reference/capture.mjs /tmp/ref 1200 760 reference/open-first-chat.js +reference/shot.sh /tmp/gpui.png 1200x760 --open # Xvfb on Linux +python3 reference/compare.py /tmp/ref.png /tmp/gpui.png /tmp/diff.png +``` + +`capture.mjs` also writes every element's box, font, colour and border to `.boxes.json`, +which is where the numbers in `ui.rs` come from. `mock-tauri.js` boots the frontend through its +debug hot-reload path with the fixtures, so it needs no Rust, account or network. diff --git a/crates/vector-gpui/android/.gitignore b/crates/vector-gpui/android/.gitignore new file mode 100644 index 000000000..b8135933d --- /dev/null +++ b/crates/vector-gpui/android/.gitignore @@ -0,0 +1,7 @@ +.gradle +build +local.properties +keystore.properties +*.iml +.idea +.cxx diff --git a/crates/vector-gpui/android/app/build.gradle.kts b/crates/vector-gpui/android/app/build.gradle.kts new file mode 100644 index 000000000..e785d25eb --- /dev/null +++ b/crates/vector-gpui/android/app/build.gradle.kts @@ -0,0 +1,181 @@ +import java.util.Properties +import javax.inject.Inject +import org.gradle.process.ExecOperations + +plugins { + id("com.android.application") +} + +val crateDir = rootProject.file("..") +val cargoToml = File(crateDir, "Cargo.toml") + +/** The client's version, from its Cargo.toml. */ +fun versionName(): String = cargoToml.readLines() + .first { it.trim().startsWith("version") } + .substringAfter("=").trim().trim('"') + +/** The Tauri client's mapping, so either client updates the other: 0.6.1-2 is 60102, 0.6.1 is 60199. */ +fun versionCode(): Int { + val version = versionName() + val parts = version.substringBefore('-').substringBefore('+').split(".").map { it.toIntOrNull() ?: 0 } + val preview = version.substringAfter('-', "").substringBefore('+') + val slot = if (preview.isEmpty()) 99 else preview.toIntOrNull()?.takeIf { it in 1..98 } + ?: throw GradleException("Version '$version': a preview is a number from 1 to 98 (e.g. 0.6.0-1)") + return (parts.getOrElse(0) { 0 } * 10000 + parts.getOrElse(1) { 0 } * 100 + parts.getOrElse(2) { 0 }) * 100 + slot +} + +/** F-Droid's flavour carries nothing of Google's and no in-app updater (VECTOR_FDROID, as Tauri's). */ +val fdroid = providers.environmentVariable("VECTOR_FDROID").isPresent + +android { + namespace = "io.vectorapp" + compileSdk = 36 + // `-PvectorNdk=` picks another installed NDK (CI takes the runner's latest). + ndkVersion = findProperty("vectorNdk") as String? ?: "29.0.14206865" + defaultConfig { + // The Tauri client's id: an install updates in place and keeps its data. + applicationId = "io.vectorapp" + minSdk = 26 + targetSdk = 34 + versionCode = versionCode() + versionName = versionName() + buildConfigField("boolean", "EMBEDDED_FCM", (!fdroid).toString()) + } + buildFeatures { + buildConfig = true + } + val keystore = rootProject.file("keystore.properties") + signingConfigs { + if (keystore.exists()) { + create("release") { + val props = Properties().apply { keystore.inputStream().use { load(it) } } + keyAlias = props["keyAlias"] as String + keyPassword = props["password"] as String + storeFile = file(props["storeFile"] as String) + storePassword = props["password"] as String + } + } + } + buildTypes { + getByName("debug") { + // Beside an installed Vector rather than over it, with data of its own. + applicationIdSuffix = ".gpui" + isDebuggable = true + isJniDebuggable = true + } + getByName("release") { + if (keystore.exists()) signingConfig = signingConfigs.getByName("release") + isMinifyEnabled = true + proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro") + } + } + compileOptions { + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 + } +} + +/** Builds the client as a cdylib for each ABI with the NDK, into a jniLibs tree. */ +abstract class CargoBuild @Inject constructor(private val exec: ExecOperations) : DefaultTask() { + @get:Input abstract val abis: ListProperty + @get:Input abstract val profile: Property + @get:Input abstract val features: Property + @get:Internal abstract val crateDir: DirectoryProperty + @get:Internal abstract val ndkDir: DirectoryProperty + @get:OutputDirectory abstract val jniLibs: DirectoryProperty + + init { + // Cargo knows what is stale; Gradle never skips it. + outputs.upToDateWhen { false } + } + + @TaskAction + fun build() { + val os = System.getProperty("os.name").lowercase() + val host = when { + os.contains("mac") -> "darwin-x86_64" + os.contains("windows") -> "windows-x86_64" + else -> "linux-x86_64" + } + val ext = if (os.contains("windows")) ".cmd" else "" + val ndk = ndkDir.get().asFile + val bin = File(ndk, "toolchains/llvm/prebuilt/$host/bin") + val sysroot = File(ndk, "toolchains/llvm/prebuilt/$host/sysroot/usr/lib") + val crate = crateDir.get().asFile + val outDir = if (profile.get() == "dev") "debug" else profile.get() + for (abi in abis.get()) { + val (triple, clang, libDir) = when (abi) { + "arm64-v8a" -> Triple("aarch64-linux-android", "aarch64-linux-android", "aarch64-linux-android") + "armeabi-v7a" -> Triple("armv7-linux-androideabi", "armv7a-linux-androideabi", "arm-linux-androideabi") + "x86_64" -> Triple("x86_64-linux-android", "x86_64-linux-android", "x86_64-linux-android") + else -> throw GradleException("No Rust target for ABI $abi") + } + val key = triple.replace('-', '_') + exec.exec { + workingDir = crate + commandLine( + "cargo", "rustc", "--lib", "--crate-type", "cdylib", "--locked", + "--target", triple, "--profile", profile.get(), + "--no-default-features", "--features", features.get(), + ) + environment("ANDROID_NDK_HOME", ndk.path) + environment("ANDROID_NDK_ROOT", ndk.path) + environment("ANDROID_NDK", ndk.path) + environment("CC_$key", File(bin, "${clang}26-clang$ext").path) + environment("CXX_$key", File(bin, "${clang}26-clang++$ext").path) + environment("AR_$key", File(bin, "llvm-ar").path) + environment("CARGO_TARGET_${key.uppercase()}_LINKER", File(bin, "${clang}26-clang$ext").path) + } + val dest = jniLibs.get().dir(abi).asFile.apply { mkdirs() } + val lib = File(crate, "target/$triple/$outDir/libvector_gpui.so") + lib.copyTo(File(dest, lib.name), overwrite = true) + // C++ built through the cc crate links the shared runtime, which the APK must carry. + val cxx = File(dest, "libc++_shared.so") + if (lib.readBytes().containsAscii("libc++_shared.so")) { + File(sysroot, "$libDir/libc++_shared.so").copyTo(cxx, overwrite = true) + } else { + cxx.delete() + } + } + } + + private fun ByteArray.containsAscii(needle: String): Boolean { + val n = needle.toByteArray() + outer@ for (i in 0..size - n.size) { + for (j in n.indices) if (this[i + j] != n[j]) continue@outer + return true + } + return false + } +} + +// `-PvectorAbis=arm64-v8a,armeabi-v7a,x86_64`; a phone is arm64 unless told otherwise. +val wantedAbis = (findProperty("vectorAbis") as String? ?: "arm64-v8a").split(',').map { it.trim() } +val wantedFeatures = (findProperty("vectorFeatures") as String? ?: "tor,i2p") + if (fdroid) ",fdroid" else "" + +androidComponents { + onVariants { variant -> + val name = variant.name.replaceFirstChar { it.uppercase() } + val cargo = tasks.register("cargoBuild$name") { + abis.set(wantedAbis) + // Debug APKs still run optimised: the unoptimised client is too slow on a phone. + profile.set(if (variant.buildType == "release") "release" else "fastrel") + features.set(wantedFeatures + if (variant.buildType == "release") "" else ",test-build") + crateDir.set(rootProject.layout.projectDirectory.dir("..")) + ndkDir.set(androidComponents.sdkComponents.ndkDirectory) + jniLibs.set(layout.buildDirectory.dir("rustJniLibs/${variant.name}")) + } + variant.sources.jniLibs?.addGeneratedSourceDirectory(cargo, CargoBuild::jniLibs) + } +} + +dependencies { + implementation("androidx.activity:activity:1.9.3") + implementation("androidx.core:core:1.13.1") + // Push: UnifiedPush in every build; FCM's endpoint, through Play Services, for phones with + // no distributor app, everywhere but F-Droid. Neither needs a Firebase project. + implementation("org.unifiedpush.android:connector:3.0.10") + if (!fdroid) { + implementation("org.unifiedpush.android:embedded-fcm-distributor:3.1.0") + } +} diff --git a/crates/vector-gpui/android/app/proguard-rules.pro b/crates/vector-gpui/android/app/proguard-rules.pro new file mode 100644 index 000000000..11b08caec --- /dev/null +++ b/crates/vector-gpui/android/app/proguard-rules.pro @@ -0,0 +1,21 @@ +# The bridge is called by name from Rust over JNI. +-keep class io.vectorapp.gpui.Bridge { *; } +# The desktop client's call and permission glue, called by name from the same Rust. +-keep class io.vectorapp.CallService { *; } +-keep class io.vectorapp.IncomingCall { *; } +-keep class io.vectorapp.CallAudioRouter { *; } +-keep class io.vectorapp.PermissionHandler { *; } +-keepclassmembers class io.vectorapp.MainActivity { + native ; +} +-keep class io.vectorapp.NotificationActionReceiver { *; } +-keep class io.vectorapp.VectorNotificationService { *; } +-keep class io.vectorapp.VectorBatteryHelper { *; } +-keep class io.vectorapp.Strings { *; } +-keep class io.vectorapp.VectorFiles { *; } +-keep class io.vectorapp.BiometricUnlock { *; } +-keep class io.vectorapp.ExternalSigner { *; } +-keep class io.vectorapp.VectorUpdates { *; } +-keep class io.vectorapp.VectorPush { *; } +-keep class io.vectorapp.VectorPushService { *; } +-keep class io.vectorapp.gpui.Tilt { *; } diff --git a/crates/vector-gpui/android/app/src/main/AndroidManifest.xml b/crates/vector-gpui/android/app/src/main/AndroidManifest.xml new file mode 100644 index 000000000..7e6835cd5 --- /dev/null +++ b/crates/vector-gpui/android/app/src/main/AndroidManifest.xml @@ -0,0 +1,137 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/crates/vector-gpui/android/app/src/main/java/io/vectorapp/BiometricUnlock.kt b/crates/vector-gpui/android/app/src/main/java/io/vectorapp/BiometricUnlock.kt new file mode 100644 index 000000000..78bac64b0 --- /dev/null +++ b/crates/vector-gpui/android/app/src/main/java/io/vectorapp/BiometricUnlock.kt @@ -0,0 +1,302 @@ +package io.vectorapp + +import android.app.Activity +import android.content.Context +import android.hardware.biometrics.BiometricManager +import android.hardware.biometrics.BiometricPrompt +import android.os.Build +import android.os.CancellationSignal +import android.security.keystore.KeyGenParameterSpec +import android.security.keystore.KeyProperties +import android.util.Base64 +import androidx.annotation.RequiresApi +import org.json.JSONObject +import java.security.InvalidKeyException +import java.security.KeyStore +import java.security.UnrecoverableKeyException +import javax.crypto.AEADBadTagException +import javax.crypto.Cipher +import javax.crypto.KeyGenerator +import javax.crypto.SecretKey +import javax.crypto.spec.GCMParameterSpec + +/** + * Biometric unlock bridge. Wraps Vector's 32-byte Local Encryption vault key + * with an auth-gated AES-256-GCM key in the Android Keystore (StrongBox when + * available, TEE otherwise): + * + * - [enroll] — generate a fresh keystore key and encrypt the vault key behind + * one BiometricPrompt (the prompt doubles as proof the sensor works). + * - [unlock] — decrypt the wrapped blob behind a prompt; the plaintext bytes + * go straight back to Rust via [nativeOnBiometricKey] (never through a + * Java String/JSON) and into the GuardedKey vault. + * + * Android 11+ (API 30) only: `setAllowedAuthenticators(BIOMETRIC_STRONG | + * DEVICE_CREDENTIAL)` needs 30, and gating there removes the whole weak-vs- + * strong `canAuthenticate()` ambiguity of 29 and the negative-button rules of + * pre-30 prompts. Framework BiometricPrompt (not androidx) — MainActivity is a + * ComponentActivity, not a FragmentActivity, and the framework API needs neither a + * dependency nor a fragment host. The native callbacks wake a blocking Rust + * waiter keyed by request id, mirroring the ExternalSigner bridge. + */ +object BiometricUnlock { + + init { + System.loadLibrary("vector_gpui") + } + + /** Rust-side callback: status results (cancelled / invalidated / error / wrapped blob). */ + @JvmStatic + external fun nativeOnBiometricResult(requestId: Int, resultJson: String) + + /** Rust-side callback: the unwrapped vault-key bytes (unlock success only). */ + @JvmStatic + external fun nativeOnBiometricKey(requestId: Int, data: ByteArray) + + private const val KEYSTORE = "AndroidKeyStore" + private const val GCM_TAG_BITS = 128 + + /** Availability: "available", "none_enrolled" (no screen lock) or "unsupported". */ + @JvmStatic + fun availability(context: Context): String { + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) return "unsupported" + return try { + // A secure lockscreen is the whole requirement on R+: the prompt's + // DEVICE_CREDENTIAL path works with or without biometric sensors, + // and auth-gated keystore keys demand a lockscreen regardless. + // (BiometricManager.canAuthenticate with the combined mask reports + // NO_HARDWARE on sensorless devices/emulators even though the + // credential path is fully functional — it is NOT the truth here.) + val km = context.getSystemService(android.app.KeyguardManager::class.java) + ?: return "unsupported" + if (km.isDeviceSecure) "available" else "none_enrolled" + } catch (_: Exception) { + "unsupported" + } + } + + /** + * The OS's own localized wording for our authenticator combo ("Use + * fingerprint", "Use screen lock", ...). Android never reveals the + * credential TYPE (PIN vs pattern), but 12+ provides the right words via + * BiometricManager.getStrings; 11 falls back to a biometric-vs-lock split. + * Empty string = caller uses its default copy. + */ + @JvmStatic + fun unlockLabel(context: Context): String { + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) return "" + return try { + val bm = context.getSystemService(BiometricManager::class.java) ?: return "" + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { + val label = bm.getStrings( + BiometricManager.Authenticators.BIOMETRIC_STRONG + or BiometricManager.Authenticators.DEVICE_CREDENTIAL + )?.buttonLabel + if (!label.isNullOrEmpty()) return label.toString() + } + if (bm.canAuthenticate(BiometricManager.Authenticators.BIOMETRIC_STRONG) + == BiometricManager.BIOMETRIC_SUCCESS + ) Strings.t("android-biometric-use", "Use biometrics") else Strings.t("android-biometric-screen-lock", "Use screen lock") + } catch (_: Exception) { + "" + } + } + + /** + * Enroll: replace any key under [alias] with a fresh auth-gated one and + * encrypt [keyBytes] behind one prompt. Result: {"data": b64(iv||ct)} — the + * wrapped blob is not secret, so the JSON channel is fine for the OUTPUT. + * The key arrives as a ByteArray (never a String): JVM Strings are + * immutable and cannot be wiped, so a String parameter would strand a + * plaintext key copy in the heap until GC. Zeroed here and by the caller. + */ + @JvmStatic + fun enroll(activity: Activity, requestId: Int, alias: String, keyBytes: ByteArray) { + activity.runOnUiThread { + try { + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) { + keyBytes.fill(0) + finish(requestId, JSONObject().put("error", "requires Android 11+").toString()) + return@runOnUiThread + } + val ks = KeyStore.getInstance(KEYSTORE).apply { load(null) } + ks.deleteEntry(alias) + val secret = generateKey(alias) + val cipher = Cipher.getInstance("AES/GCM/NoPadding") + // Keystore generates the IV (randomized encryption stays at its + // required default) — never supply one on encrypt. + cipher.init(Cipher.ENCRYPT_MODE, secret) + prompt(activity, requestId, cipher, Strings.t("android-biometric-enable", "Enable Biometric Unlock")) { c -> + val ct = c.doFinal(keyBytes) + keyBytes.fill(0) + val iv = c.iv + val out = ByteArray(iv.size + ct.size) + iv.copyInto(out) + ct.copyInto(out, iv.size) + finish(requestId, JSONObject().put("data", Base64.encodeToString(out, Base64.NO_WRAP)).toString()) + } + } catch (e: Exception) { + keyBytes.fill(0) + finish(requestId, err(e)) + } + } + } + + /** + * Unlock: decrypt [wrappedB64] (12-byte IV || ct) under [alias] behind one + * prompt; success delivers raw bytes via [nativeOnBiometricKey]. ANY + * key-load/init/decrypt failure reports {"invalidated": true}: a keystore + * key invalidated by biometric/lockscreen changes throws at Cipher.init + * (before any prompt), a DB restored onto a new device finds no matching + * key, and OEM variants surface as InvalidKey/UnrecoverableKey/BadTag — + * all of them mean "this enrollment is dead, fall back to PIN", never a + * retry loop. + */ + @JvmStatic + fun unlock(activity: Activity, requestId: Int, alias: String, wrappedB64: String) { + activity.runOnUiThread { + try { + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) { + finish(requestId, JSONObject().put("error", "requires Android 11+").toString()) + return@runOnUiThread + } + val ks = KeyStore.getInstance(KEYSTORE).apply { load(null) } + val secret = ks.getKey(alias, null) as? SecretKey + if (secret == null) { + finish(requestId, JSONObject().put("invalidated", true).toString()) + return@runOnUiThread + } + val blob = Base64.decode(wrappedB64, Base64.NO_WRAP) + if (blob.size <= 12) { + finish(requestId, JSONObject().put("invalidated", true).toString()) + return@runOnUiThread + } + val iv = blob.copyOfRange(0, 12) + val ct = blob.copyOfRange(12, blob.size) + val cipher = Cipher.getInstance("AES/GCM/NoPadding") + cipher.init(Cipher.DECRYPT_MODE, secret, GCMParameterSpec(GCM_TAG_BITS, iv)) + prompt(activity, requestId, cipher, Strings.t("android-biometric-unlock", "Unlock Vector")) { c -> + val plain = c.doFinal(ct) + try { + nativeOnBiometricKey(requestId, plain) + } catch (_: Throwable) { + } + plain.fill(0) + } + } catch (e: InvalidKeyException) { + // Covers KeyPermanentlyInvalidatedException (its subclass) and + // every other unusable-key shape. + finish(requestId, JSONObject().put("invalidated", true).toString()) + } catch (e: UnrecoverableKeyException) { + finish(requestId, JSONObject().put("invalidated", true).toString()) + } catch (e: Exception) { + finish(requestId, err(e)) + } + } + } + + /** Delete the keystore key under [alias]. Safe if absent. */ + @JvmStatic + fun removeKey(alias: String) { + try { + KeyStore.getInstance(KEYSTORE).apply { load(null) }.deleteEntry(alias) + } catch (_: Exception) { + } + } + + // ------------------------------------------------------------------------ + + @RequiresApi(Build.VERSION_CODES.R) + private fun generateKey(alias: String): SecretKey { + val builder = KeyGenParameterSpec.Builder( + alias, + KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT + ) + .setBlockModes(KeyProperties.BLOCK_MODE_GCM) + .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE) + .setKeySize(256) + .setUserAuthenticationRequired(true) + .setUnlockedDeviceRequired(true) + .setInvalidatedByBiometricEnrollment(true) + // Auth-per-use, unlockable by fingerprint/face OR the device + // credential. Note: with DEVICE_CREDENTIAL authorized, the OS does + // NOT invalidate on new-biometric enrollment (the credential path + // is unaffected) — invalidation instead fires on lockscreen + // removal. Acceptable: someone who can enroll a finger already + // knows the device credential. + .setUserAuthenticationParameters( + 0, + KeyProperties.AUTH_BIOMETRIC_STRONG or KeyProperties.AUTH_DEVICE_CREDENTIAL + ) + try { + val kg = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, KEYSTORE) + kg.init(builder.setIsStrongBoxBacked(true).build()) + return kg.generateKey() + } catch (_: Exception) { + builder.setIsStrongBoxBacked(false) + } + val kg = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, KEYSTORE) + kg.init(builder.build()) + return kg.generateKey() + } + + @RequiresApi(Build.VERSION_CODES.R) + private fun prompt( + activity: Activity, + requestId: Int, + cipher: Cipher, + title: String, + op: (Cipher) -> Unit + ) { + val executor = activity.mainExecutor + val callback = object : BiometricPrompt.AuthenticationCallback() { + override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult) { + try { + op(result.cryptoObject?.cipher ?: cipher) + } catch (e: AEADBadTagException) { + // Wrapped blob and keystore key disagree (restored DB, + // alias collision) — dead enrollment, not a retryable error. + finish(requestId, JSONObject().put("invalidated", true).toString()) + } catch (e: Exception) { + finish(requestId, err(e)) + } + } + + override fun onAuthenticationError(errorCode: Int, errString: CharSequence) { + // Lockouts fall back to the Vector PIN quietly — hammering a + // throttled sensor with retries only extends the lockout. + val cancelled = errorCode == BiometricPrompt.BIOMETRIC_ERROR_USER_CANCELED + || errorCode == BiometricPrompt.BIOMETRIC_ERROR_CANCELED + || errorCode == BiometricPrompt.BIOMETRIC_ERROR_LOCKOUT + || errorCode == BiometricPrompt.BIOMETRIC_ERROR_LOCKOUT_PERMANENT + finish( + requestId, + if (cancelled) JSONObject().put("cancelled", true).toString() + else JSONObject().put("error", errString.toString()).toString() + ) + } + // onAuthenticationFailed = one bad read; the prompt stays up, no report. + } + + val prompt = BiometricPrompt.Builder(activity) + .setTitle(title) + .setAllowedAuthenticators( + BiometricManager.Authenticators.BIOMETRIC_STRONG + or BiometricManager.Authenticators.DEVICE_CREDENTIAL + ) + .build() + prompt.authenticate(BiometricPrompt.CryptoObject(cipher), CancellationSignal(), executor, callback) + } + + private fun finish(requestId: Int, json: String) { + try { + nativeOnBiometricResult(requestId, json) + } catch (_: Throwable) { + } + } + + private fun err(e: Exception): String { + val msg = (e.message ?: e.javaClass.simpleName).replace("\"", "'") + return JSONObject().put("error", msg).toString() + } +} diff --git a/crates/vector-gpui/android/app/src/main/java/io/vectorapp/BootReceiver.kt b/crates/vector-gpui/android/app/src/main/java/io/vectorapp/BootReceiver.kt new file mode 100644 index 000000000..01f65d49b --- /dev/null +++ b/crates/vector-gpui/android/app/src/main/java/io/vectorapp/BootReceiver.kt @@ -0,0 +1,15 @@ +package io.vectorapp + +import android.content.BroadcastReceiver +import android.content.Context +import android.content.Intent + +/** Back in the background after a restart, when the user keeps Vector listening. */ +class BootReceiver : BroadcastReceiver() { + override fun onReceive(context: Context, intent: Intent) { + if (intent.action != Intent.ACTION_BOOT_COMPLETED) return + if (VectorBatteryHelper.getBackgroundServiceEnabled(context)) { + context.startForegroundService(Intent(context, VectorNotificationService::class.java)) + } + } +} diff --git a/crates/vector-gpui/android/app/src/main/java/io/vectorapp/CallAudioRouter.kt b/crates/vector-gpui/android/app/src/main/java/io/vectorapp/CallAudioRouter.kt new file mode 100644 index 000000000..1fa0d59d5 --- /dev/null +++ b/crates/vector-gpui/android/app/src/main/java/io/vectorapp/CallAudioRouter.kt @@ -0,0 +1,199 @@ +package io.vectorapp + +import android.content.Context +import android.media.AudioAttributes +import android.media.AudioDeviceCallback +import android.media.AudioDeviceInfo +import android.media.AudioFocusRequest +import android.media.AudioManager +import android.os.Build +import android.os.Handler +import android.os.Looper +import android.os.PowerManager + +/** + * A call's sound as a phone call's: the communication mode, played to the earpiece, the + * speaker or a headset, and the screen dark while the phone is at the ear. Rust says when a + * call needs it and whether out loud; the user may pick another route meanwhile. + */ +object CallAudioRouter { + const val OFF = 0 + const val EAR = 1 + const val LOUD = 2 + + private const val EARPIECE = "earpiece" + private const val SPEAKER = "speaker" + private const val BLUETOOTH = "bluetooth" + private const val HEADSET = "headset" + + init { + System.loadLibrary("vector_gpui") + } + + /** `current` is empty once the call's audio is handed back. */ + @JvmStatic + external fun nativeRouteChanged(current: String, available: String) + + private val lock = Any() + private var mode = OFF + private var picked: String? = null + private var focus: AudioFocusRequest? = null + private var proximity: PowerManager.WakeLock? = null + private var devices: AudioDeviceCallback? = null + private var app: Context? = null + + @JvmStatic + fun apply(context: Context, next: Int) { + synchronized(lock) { + val am = context.getSystemService(AudioManager::class.java) ?: return + val was = mode + mode = next + if (next == OFF) { + if (was != OFF) stop(am) + return + } + if (was == OFF) start(context.applicationContext, am) + route(am) + } + } + + /** The user's pick; false if this phone has no such route now. */ + @JvmStatic + fun setRoute(context: Context, route: String): Boolean { + synchronized(lock) { + if (mode == OFF) return false + val am = context.getSystemService(AudioManager::class.java) ?: return false + if (route !in available(am)) return false + picked = route + route(am) + return true + } + } + + private fun start(context: Context, am: AudioManager) { + app = context + picked = null + val request = AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN_TRANSIENT) + .setAudioAttributes( + AudioAttributes.Builder() + .setUsage(AudioAttributes.USAGE_VOICE_COMMUNICATION) + .setContentType(AudioAttributes.CONTENT_TYPE_SPEECH) + .build() + ) + .build() + am.requestAudioFocus(request) + focus = request + am.mode = AudioManager.MODE_IN_COMMUNICATION + val callback = object : AudioDeviceCallback() { + override fun onAudioDevicesAdded(added: Array) { + synchronized(lock) { + if (mode == OFF) return + // A headset put on mid-call takes the call, as on any phone. + if (added.any { routeOf(it.type) == BLUETOOTH || routeOf(it.type) == HEADSET }) picked = null + route(am) + } + } + + override fun onAudioDevicesRemoved(removed: Array) { + synchronized(lock) { + if (mode == OFF) return + route(am) + } + } + } + am.registerAudioDeviceCallback(callback, Handler(Looper.getMainLooper())) + devices = callback + } + + @Suppress("DEPRECATION") + private fun stop(am: AudioManager) { + devices?.let { am.unregisterAudioDeviceCallback(it) } + devices = null + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { + am.clearCommunicationDevice() + } else { + am.isSpeakerphoneOn = false + if (am.isBluetoothScoOn) { + am.isBluetoothScoOn = false + am.stopBluetoothSco() + } + } + am.mode = AudioManager.MODE_NORMAL + focus?.let { am.abandonAudioFocusRequest(it) } + focus = null + holdProximity(false) + picked = null + nativeRouteChanged("", "") + } + + /** The user's pick while it lasts; else a headset, else the ear or the speaker as the call asks. */ + private fun route(am: AudioManager) { + val routes = available(am) + val current = picked?.takeIf { it in routes } ?: when { + BLUETOOTH in routes -> BLUETOOTH + HEADSET in routes -> HEADSET + mode == LOUD || EARPIECE !in routes -> SPEAKER + else -> EARPIECE + } + select(am, current) + holdProximity(current == EARPIECE) + nativeRouteChanged(current, routes.joinToString(",")) + } + + @Suppress("DEPRECATION") + private fun select(am: AudioManager, route: String) { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { + val device = am.availableCommunicationDevices.firstOrNull { routeOf(it.type) == route } + if (device != null) am.setCommunicationDevice(device) + return + } + am.isSpeakerphoneOn = route == SPEAKER + val sco = route == BLUETOOTH + if (sco != am.isBluetoothScoOn) { + try { + if (sco) am.startBluetoothSco() else am.stopBluetoothSco() + am.isBluetoothScoOn = sco + } catch (e: Exception) { + android.util.Log.w("CallAudioRouter", "bluetooth: ${e.message}") + } + } + } + + /** In the order a picker lists them. A plugged-in headset stands in for the earpiece. */ + private fun available(am: AudioManager): List { + val types = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { + am.availableCommunicationDevices.map { it.type } + } else { + am.getDevices(AudioManager.GET_DEVICES_OUTPUTS).map { it.type } + } + val found = types.mapNotNull { routeOf(it) }.toSet() + return listOf(EARPIECE, HEADSET, SPEAKER, BLUETOOTH) + .filter { it in found } + .filter { it != EARPIECE || HEADSET !in found } + } + + private fun routeOf(type: Int): String? = when (type) { + AudioDeviceInfo.TYPE_BUILTIN_EARPIECE -> EARPIECE + AudioDeviceInfo.TYPE_BUILTIN_SPEAKER -> SPEAKER + AudioDeviceInfo.TYPE_BLUETOOTH_SCO -> BLUETOOTH + AudioDeviceInfo.TYPE_WIRED_HEADSET, AudioDeviceInfo.TYPE_WIRED_HEADPHONES, AudioDeviceInfo.TYPE_USB_HEADSET -> HEADSET + else -> if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S && type == AudioDeviceInfo.TYPE_BLE_HEADSET) BLUETOOTH else null + } + + /** At the ear the screen goes dark, so a cheek can't press anything. */ + private fun holdProximity(on: Boolean) { + val held = proximity + if (!on) { + if (held?.isHeld == true) held.release(PowerManager.RELEASE_FLAG_WAIT_FOR_NO_PROXIMITY) + return + } + if (held?.isHeld == true) return + val pm = app?.getSystemService(PowerManager::class.java) ?: return + if (!pm.isWakeLockLevelSupported(PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK)) return + val lock = held ?: pm.newWakeLock(PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK, "vector:call-proximity").also { + it.setReferenceCounted(false) + proximity = it + } + lock.acquire() + } +} diff --git a/crates/vector-gpui/android/app/src/main/java/io/vectorapp/CallService.kt b/crates/vector-gpui/android/app/src/main/java/io/vectorapp/CallService.kt new file mode 100644 index 000000000..fd3a3d4c2 --- /dev/null +++ b/crates/vector-gpui/android/app/src/main/java/io/vectorapp/CallService.kt @@ -0,0 +1,204 @@ +package io.vectorapp + +import android.Manifest +import android.app.Activity +import android.app.NotificationChannel +import android.app.NotificationManager +import android.app.PendingIntent +import android.app.Service +import android.content.Context +import android.content.Intent +import android.content.pm.PackageManager +import android.content.pm.ServiceInfo +import android.os.Build +import android.os.IBinder +import android.view.WindowManager +import androidx.core.app.NotificationCompat +import androidx.core.app.Person +import androidx.core.app.ServiceCompat +import androidx.core.content.ContextCompat + +/** + * Runs for as long as a call does. Android silences a backgrounded app's microphone, and + * soon its playback, unless a foreground service of the right type holds the process. + */ +class CallService : Service() { + + companion object { + private const val CHANNEL_ID = "vector_calls" + private const val NOTIFICATION_ID = 2 + private const val ACTION_LEAVE = "io.vectorapp.ACTION_LEAVE_CALL" + private const val ACTION_MUTE = "io.vectorapp.ACTION_MUTE_CALL" + + /** The call the notification shows; null shows the plain one. */ + private data class Shown(val name: String, val avatar: String, val muted: Boolean, val video: Boolean, val since: Long, val detail: String) + + @Volatile + private var shown: Shown? = null + + @Volatile + private var running: CallService? = null + + init { + System.loadLibrary("vector_gpui") + } + + @JvmStatic + external fun nativeLeaveCall() + + @JvmStatic + external fun nativeSetMuted(on: Boolean) + + /** The call as the notification should show it, whether or not the service runs yet. */ + @JvmStatic + fun show(name: String, avatarPath: String, muted: Boolean, video: Boolean, activeMs: Long) { + shown = Shown(name, avatarPath, muted, video, System.currentTimeMillis() - activeMs, if (video) Strings.t("android-call-video", "Video call") else Strings.t("android-call-voice", "Call")) + running?.post() + } + + /** A voice Channel's call: the channel by name, its community below. */ + @JvmStatic + fun showVoice(channel: String, community: String, muted: Boolean, sinceMs: Long) { + shown = Shown(channel, "", muted, false, sinceMs, community) + running?.post() + } + + /** The call ended; its service stops with it, so nothing is reposted. */ + @JvmStatic + fun clear() { + shown = null + } + + @JvmStatic + fun channel(context: Context) { + val manager = context.getSystemService(NotificationManager::class.java) ?: return + val channel = NotificationChannel(CHANNEL_ID, Strings.t("android-channel-calls", "Calls"), NotificationManager.IMPORTANCE_LOW).apply { + description = Strings.t("android-channel-calls-about", "Shown while you're in a call") + setShowBadge(false) + } + manager.createNotificationChannel(channel) + } + + @JvmStatic + fun start(context: Context) { + try { + ContextCompat.startForegroundService(context, Intent(context, CallService::class.java)) + } catch (e: Exception) { + // Refused from the background (Android 12+): the call goes on, unheld. + android.util.Log.w("CallService", "start refused: ${e.message}") + } + } + + @JvmStatic + fun stop(context: Context) { + context.stopService(Intent(context, CallService::class.java)) + } + + /** Video on screen: the display stays lit while the call shows it. */ + @JvmStatic + fun keepScreenOn(activity: Activity, on: Boolean) { + activity.runOnUiThread { + if (on) { + activity.window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) + } else { + activity.window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) + } + } + } + } + + override fun onBind(intent: Intent?): IBinder? = null + + override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { + when (intent?.action) { + ACTION_LEAVE -> { + nativeLeaveCall() + return START_NOT_STICKY + } + ACTION_MUTE -> { + shown?.let { nativeSetMuted(!it.muted) } + return START_NOT_STICKY + } + } + Strings.init(this) + channel(this) + val notification = build() + // Listen-only (no microphone permission) can't claim the microphone type. + val mic = checkSelfPermission(Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED + val type = when { + Build.VERSION.SDK_INT < Build.VERSION_CODES.Q -> 0 + mic && Build.VERSION.SDK_INT >= Build.VERSION_CODES.R -> + ServiceInfo.FOREGROUND_SERVICE_TYPE_MICROPHONE or ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PLAYBACK + else -> ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PLAYBACK + } + try { + ServiceCompat.startForeground(this, NOTIFICATION_ID, notification, type) + running = this + } catch (e: Exception) { + android.util.Log.w("CallService", "startForeground refused: ${e.message}") + stopSelf() + } + return START_NOT_STICKY + } + + override fun onDestroy() { + if (running === this) running = null + super.onDestroy() + } + + private fun post() { + try { + getSystemService(NotificationManager::class.java)?.notify(NOTIFICATION_ID, build()) + } catch (e: Exception) { + android.util.Log.w("CallService", "update refused: ${e.message}") + } + } + + /** The phone's own call notification: who or which channel, the timer, Mute and Hang up. */ + private fun build(): android.app.Notification { + val open = PendingIntent.getActivity( + this, 0, + Intent(this, MainActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), + PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE + ) + val leave = PendingIntent.getService( + this, 1, + Intent(this, CallService::class.java).setAction(ACTION_LEAVE), + PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE + ) + val builder = NotificationCompat.Builder(this, CHANNEL_ID) + .setSmallIcon(R.drawable.ic_notification) + .setContentIntent(open) + .setOngoing(true) + .setSilent(true) + .setCategory(NotificationCompat.CATEGORY_CALL) + val call = shown ?: return builder + .setContentTitle(Strings.t("android-call-ongoing", "In a call")) + .setContentText(Strings.t("android-call-return", "Tap to return to Vector")) + .addAction(0, Strings.t("android-call-leave", "Leave"), leave) + .build() + val mute = PendingIntent.getService( + this, 2, + Intent(this, CallService::class.java).setAction(ACTION_MUTE), + PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE + ) + val person = Person.Builder().setName(call.name).setImportant(true).apply { + IncomingCall.avatar(call.avatar)?.let { setIcon(it) } + }.build() + return builder + .setContentTitle(call.name) + .setContentText(if (call.muted) Strings.t("android-call-muted", "Muted") else call.detail) + .setWhen(call.since) + .setUsesChronometer(true) + .setShowWhen(true) + .setStyle(NotificationCompat.CallStyle.forOngoingCall(person, leave).setIsVideo(call.video)) + .addAction(0, if (call.muted) Strings.t("android-call-unmute", "Unmute") else Strings.t("android-call-mute", "Mute"), mute) + .build() + } + + /** Swiped away from recents: the call ends with the app, as quitting does on desktop. */ + override fun onTaskRemoved(rootIntent: Intent?) { + nativeLeaveCall() + stopSelf() + } +} diff --git a/crates/vector-gpui/android/app/src/main/java/io/vectorapp/ExternalSigner.kt b/crates/vector-gpui/android/app/src/main/java/io/vectorapp/ExternalSigner.kt new file mode 100644 index 000000000..0e1dd29a5 --- /dev/null +++ b/crates/vector-gpui/android/app/src/main/java/io/vectorapp/ExternalSigner.kt @@ -0,0 +1,145 @@ +package io.vectorapp + +import android.app.Activity +import android.content.Context +import android.content.Intent +import android.net.Uri +import org.json.JSONObject + +/** + * NIP-55 external-signer (Amber) bridge. Two transports: + * + * - ContentResolver ([queryContentResolver]) — the silent background hot path + * for pre-authorized sign/encrypt/decrypt ops. No Activity, no UI. + * - Intent for result ([launch] + [handleActivityResult]) — pairing and the + * fallback when a ContentResolver query comes back not-pre-authorized. + * + * The native side ([nativeOnSignerResult]) wakes a blocking Rust waiter keyed + * by the request id we echo through the intent. + */ +object ExternalSigner { + const val REQUEST_CODE = 7801 + + init { + System.loadLibrary("vector_gpui") + } + + /** Rust-side callback: delivers an intent result JSON to the waiter for [requestId]. */ + @JvmStatic + external fun nativeOnSignerResult(requestId: Int, resultJson: String) + + /** + * Launch a signer intent for result. Called from Rust (JNI) on the UI Activity. + * Empty-string args are treated as absent. `get_public_key` pairing passes an + * empty [pkg] so the OS resolves the installed signer; every other op pins it. + */ + @JvmStatic + fun launch( + activity: Activity, + requestId: Int, + type: String, + data: String, + pubkey: String, + currentUser: String, + permsJson: String, + pkg: String + ) { + val intent = Intent(Intent.ACTION_VIEW, Uri.parse("nostrsigner:" + data)) + intent.putExtra("type", type) + if (pkg.isNotEmpty()) intent.setPackage(pkg) + // Set both casings: Amethyst/Amber use camelCase `pubKey`, the NIP-55 + // prose says `pubkey`; Amber reads either, so send both for max compat. + if (pubkey.isNotEmpty()) { + intent.putExtra("pubKey", pubkey) + intent.putExtra("pubkey", pubkey) + } + if (currentUser.isNotEmpty()) intent.putExtra("current_user", currentUser) + if (permsJson.isNotEmpty()) intent.putExtra("permissions", permsJson) + // Echo the request id so the result can be routed back to its waiter. + intent.putExtra("id", requestId.toString()) + activity.startActivityForResult(intent, REQUEST_CODE) + } + + /** + * Forwarded from MainActivity.onActivityResult. Packages the returned extras + * into a JSON blob and wakes the native waiter. A cancelled result (user + * declined / back) is reported as `rejected`. + */ + @JvmStatic + fun handleActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { + if (requestCode != REQUEST_CODE) return + val requestId = data?.getStringExtra("id")?.toIntOrNull() ?: -1 + val obj = JSONObject() + if (resultCode != Activity.RESULT_OK || data == null) { + obj.put("rejected", true) + } else { + data.getStringExtra("result")?.let { obj.put("result", it) } + data.getStringExtra("event")?.let { obj.put("event", it) } + data.getStringExtra("package")?.let { obj.put("package", it) } + if (data.getBooleanExtra("rejected", false)) obj.put("rejected", true) + } + try { + nativeOnSignerResult(requestId, obj.toString()) + } catch (_: Throwable) {} + } + + /** + * ContentResolver query for one op. `selection`/`selectionArgs`/`sortOrder` + * are null; the data goes in the `projection` slot (Amber overloads it as + * `[payload, counterparty, current_user]`). Returns a small JSON blob — a + * TRI-STATE the caller must not collapse: + * {"result":...,"event":...} success (read result / event) + * {"requires_approval":true} null OR empty cursor = not remembered; + * escalate to the foreground Intent. NOT a + * rejection, NOT an empty decrypt. + * {"rejected":true} a `rejected` column = a remembered reject; + * hard stop, do NOT relaunch the signer. + * {"error":"..."} IPC/exception failure. + */ + @JvmStatic + fun queryContentResolver( + context: Context, + authority: String, + arg0: String, + arg1: String, + arg2: String + ): String { + return try { + val uri = Uri.parse("content://$authority") + val projection = arrayOf(arg0, arg1, arg2) + val cursor = context.contentResolver.query(uri, projection, null, null, null) + ?: return "{\"requires_approval\":true}" + cursor.use { c -> + if (!c.moveToFirst()) return "{\"requires_approval\":true}" + // A `rejected` column is Amber's remembered-reject signal. + if (c.getColumnIndex("rejected") >= 0) return "{\"rejected\":true}" + val obj = JSONObject() + val resIdx = c.getColumnIndex("result") + if (resIdx >= 0 && !c.isNull(resIdx)) { + val s = c.getString(resIdx) + if (!s.isNullOrEmpty()) obj.put("result", s) + } + val evIdx = c.getColumnIndex("event") + if (evIdx >= 0 && !c.isNull(evIdx)) { + val s = c.getString(evIdx) + if (!s.isNullOrEmpty()) obj.put("event", s) + } + obj.toString() + } + } catch (e: Exception) { + val msg = (e.message ?: "content resolver error").replace("\"", "'") + "{\"error\":\"$msg\"}" + } + } + + /** Whether any app can handle the `nostrsigner:` scheme. */ + @JvmStatic + fun isInstalled(context: Context): Boolean { + return try { + val intent = Intent(Intent.ACTION_VIEW, Uri.parse("nostrsigner:")) + context.packageManager.queryIntentActivities(intent, 0).isNotEmpty() + } catch (_: Exception) { + false + } + } +} diff --git a/crates/vector-gpui/android/app/src/main/java/io/vectorapp/IncomingCall.kt b/crates/vector-gpui/android/app/src/main/java/io/vectorapp/IncomingCall.kt new file mode 100644 index 000000000..06a6c4a5b --- /dev/null +++ b/crates/vector-gpui/android/app/src/main/java/io/vectorapp/IncomingCall.kt @@ -0,0 +1,190 @@ +package io.vectorapp + +import android.app.Notification +import android.app.NotificationChannel +import android.app.NotificationManager +import android.app.PendingIntent +import android.content.Context +import android.content.Intent +import android.graphics.BitmapFactory +import android.media.AudioAttributes +import android.media.RingtoneManager +import android.os.Build +import androidx.core.app.NotificationCompat +import androidx.core.app.Person +import androidx.core.graphics.drawable.IconCompat + +/** + * A call ringing while Vector isn't on screen: full screen over the lock screen where the + * system allows it, a heads-up with Answer and Decline elsewhere, and a missed call once it + * stops unanswered. Rust decides when; this only shows it. + */ +object IncomingCall { + private const val RING_CHANNEL = "vector_incoming_calls" + private const val MISSED_CHANNEL = "vector_missed_calls" + private const val RING_ID = 3 + /** A little past the caller's own ring, so a lost withdrawal can't ring forever. */ + private const val RING_MS = 65_000L + + const val EXTRA_CALL_ID = "call_id" + const val EXTRA_CALL_NPUB = "call_npub" + const val EXTRA_CALL_ANSWER = "call_answer" + const val ACTION_DECLINE = "io.vectorapp.ACTION_DECLINE_CALL" + + private data class Ringing(val callId: String, val npub: String, val name: String) + + @Volatile + private var ringing: Ringing? = null + + init { + System.loadLibrary("vector_gpui") + } + + @JvmStatic + external fun nativeDecline(callId: String, npub: String) + + @JvmStatic + fun ring(context: Context, callId: String, npub: String, name: String, avatarPath: String, video: Boolean) { + Strings.init(context) + val manager = context.getSystemService(NotificationManager::class.java) ?: return + channels(context) + ringing = Ringing(callId, npub, name) + val show = activity(context, callId, npub, false, 20) + val answer = activity(context, callId, npub, true, 21) + val decline = PendingIntent.getBroadcast( + context, 22, + Intent(context, NotificationActionReceiver::class.java) + .setAction(ACTION_DECLINE) + .putExtra("chat_id", npub) + .putExtra(EXTRA_CALL_ID, callId), + PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE + ) + val person = Person.Builder().setName(name).setImportant(true).apply { + avatar(avatarPath)?.let { setIcon(it) } + }.build() + val builder = NotificationCompat.Builder(context, RING_CHANNEL) + .setSmallIcon(R.drawable.ic_notification) + .setContentTitle(name) + .setContentText(if (video) Strings.t("android-call-incoming-video", "Incoming video call") else Strings.t("android-call-incoming", "Incoming call")) + .setCategory(NotificationCompat.CATEGORY_CALL) + .setPriority(NotificationCompat.PRIORITY_MAX) + .setVisibility(NotificationCompat.VISIBILITY_PUBLIC) + .setOngoing(true) + .setAutoCancel(false) + .setTimeoutAfter(RING_MS) + .setContentIntent(show) + .setFullScreenIntent(show, true) + // The call style needs a full-screen intent the system will honour; without one, the + // same two buttons as plain actions. + val fullScreen = Build.VERSION.SDK_INT < 34 || manager.canUseFullScreenIntent() + if (fullScreen) { + builder.setStyle(NotificationCompat.CallStyle.forIncomingCall(person, decline, answer)) + } else { + builder.addAction(0, Strings.t("android-call-decline", "Decline"), decline) + .addAction(0, Strings.t("android-call-answer", "Answer"), answer) + } + val notification = builder.build() + // Rings until answered, declined or withdrawn, as a phone does. + notification.flags = notification.flags or Notification.FLAG_INSISTENT + try { + manager.notify(RING_ID, notification) + } catch (e: Exception) { + android.util.Log.w("IncomingCall", "ring refused: ${e.message}") + } + } + + /** The ring stopped: taken up, or missed (timed out, or withdrawn by the caller). */ + @JvmStatic + fun over(context: Context, callId: String, missed: Boolean) { + val r = ringing ?: return + if (r.callId != callId) return + ringing = null + Strings.init(context) + val manager = context.getSystemService(NotificationManager::class.java) ?: return + manager.cancel(RING_ID) + if (!missed) return + channels(context) + val open = PendingIntent.getActivity( + context, ("missed:" + r.npub).hashCode(), + Intent(context, MainActivity::class.java) + .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP) + .putExtra("chat_id", r.npub), + PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE + ) + val missedCall = NotificationCompat.Builder(context, MISSED_CHANNEL) + .setSmallIcon(R.drawable.ic_notification) + .setContentTitle(r.name) + .setContentText(Strings.t("android-call-missed", "Missed call")) + .setCategory(NotificationCompat.CATEGORY_MISSED_CALL) + .setAutoCancel(true) + .setContentIntent(open) + .build() + try { + manager.notify(("missed:" + r.npub).hashCode(), missedCall) + } catch (e: Exception) { + android.util.Log.w("IncomingCall", "missed call refused: ${e.message}") + } + } + + /** A call that rang here only as a push, missed by its caller's word. */ + @JvmStatic + fun missed(context: Context, callId: String, npub: String, name: String) { + if (ringing?.callId != callId) ringing = Ringing(callId, npub, name) + over(context, callId, true) + } + + /** Declined from the notification. */ + @JvmStatic + fun decline(context: Context, callId: String, npub: String) { + if (ringing?.callId == callId) ringing = null + context.getSystemService(NotificationManager::class.java)?.cancel(RING_ID) + nativeDecline(callId, npub) + } + + private fun activity(context: Context, callId: String, npub: String, answer: Boolean, request: Int): PendingIntent = + PendingIntent.getActivity( + context, request, + Intent(context, MainActivity::class.java) + .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP) + .putExtra(EXTRA_CALL_ID, callId) + .putExtra(EXTRA_CALL_NPUB, npub) + .putExtra(EXTRA_CALL_ANSWER, answer), + PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE + ) + + fun avatar(path: String): IconCompat? { + if (path.isEmpty()) return null + return try { + BitmapFactory.decodeFile(path)?.let { IconCompat.createWithBitmap(it) } + } catch (_: Exception) { + null + } + } + + @JvmStatic + fun channels(context: Context) { + val manager = context.getSystemService(NotificationManager::class.java) ?: return + run { + val ring = NotificationChannel(RING_CHANNEL, Strings.t("android-channel-ring", "Incoming calls"), NotificationManager.IMPORTANCE_HIGH).apply { + description = Strings.t("android-channel-ring-about", "Rings when someone calls you") + setSound( + RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE), + AudioAttributes.Builder() + .setUsage(AudioAttributes.USAGE_NOTIFICATION_RINGTONE) + .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION) + .build() + ) + enableVibration(true) + vibrationPattern = longArrayOf(0, 800, 600, 800, 600) + lockscreenVisibility = Notification.VISIBILITY_PUBLIC + } + manager.createNotificationChannel(ring) + } + run { + val missed = NotificationChannel(MISSED_CHANNEL, Strings.t("android-channel-missed", "Missed calls"), NotificationManager.IMPORTANCE_DEFAULT).apply { + description = Strings.t("android-channel-missed-about", "Calls you didn't answer") + } + manager.createNotificationChannel(missed) + } + } +} diff --git a/crates/vector-gpui/android/app/src/main/java/io/vectorapp/MainActivity.kt b/crates/vector-gpui/android/app/src/main/java/io/vectorapp/MainActivity.kt new file mode 100644 index 000000000..b611aa52e --- /dev/null +++ b/crates/vector-gpui/android/app/src/main/java/io/vectorapp/MainActivity.kt @@ -0,0 +1,228 @@ +package io.vectorapp + +import android.Manifest +import android.content.Intent +import android.content.pm.PackageManager +import android.content.res.Configuration +import android.net.Uri +import android.os.Build +import android.os.Bundle +import androidx.activity.ComponentActivity +import androidx.activity.result.contract.ActivityResultContracts +import androidx.core.view.ViewCompat +import androidx.core.view.WindowCompat +import androidx.core.view.WindowInsetsCompat +import io.vectorapp.gpui.Bridge +import io.vectorapp.gpui.GpuiView +import io.vectorapp.gpui.Picked + +/** The whole app: GPUI draws every pixel of [view] and hears the activity's life through [Bridge]. */ +class MainActivity : ComponentActivity() { + lateinit var view: GpuiView + private set + + private val NOTIFICATION_PERMISSION_REQUEST = 1001 + + /** The picker GPUI has open, by the id its answer goes back with; 0 is none. */ + private var pickId = 0 + private val picker = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result -> + val id = pickId + pickId = 0 + val data = result.data.takeIf { result.resultCode == RESULT_OK } + val uris = buildList { + data?.clipData?.let { clip -> for (i in 0 until clip.itemCount) add(clip.getItemAt(i).uri) } + if (isEmpty()) data?.data?.let(::add) + } + if (uris.isEmpty()) { + Bridge.nativePicked(id, null) + } else { + Thread { Bridge.nativePicked(id, Picked.copy(applicationContext, uris)) }.start() + } + } + + fun pickFiles(id: Int, multiple: Boolean, extensions: Array) { + // One picker at a time: one still open answers as cancelled. + if (pickId != 0) Bridge.nativePicked(pickId, null) + pickId = id + val types = Picked.mimeTypes(extensions) + val intent = Intent(Intent.ACTION_OPEN_DOCUMENT).apply { + addCategory(Intent.CATEGORY_OPENABLE) + type = types.singleOrNull() ?: "*/*" + if (types.size > 1) putExtra(Intent.EXTRA_MIME_TYPES, types.toTypedArray()) + putExtra(Intent.EXTRA_ALLOW_MULTIPLE, multiple) + } + try { + picker.launch(intent) + } catch (_: android.content.ActivityNotFoundException) { + pickId = 0 + Bridge.nativePicked(id, null) + } + } + + companion object { + /** The ring's notification was tapped (`answer` false) or answered. */ + @JvmStatic + external fun nativeOnCallTap(callId: String, npub: String, answer: Boolean) + /** A message notification was tapped. */ + @JvmStatic + external fun nativeOnNotificationTap(chatId: String) + /** Another app shared into Vector: the files' copies by path, and any text. */ + @JvmStatic + external fun nativeOnShare(files: Array, text: String) + } + + /** The desktop client's glue (calls, permissions) holds this activity while it lives. */ + private external fun nativeCreated() + private external fun nativeDestroyed() + private external fun nativeForeground(on: Boolean) + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + Strings.init(this) + WindowCompat.setDecorFitsSystemWindows(window, false) + view = GpuiView(this) + setContentView(view) + Bridge.attach(this) + nativeCreated() + configuration(resources.configuration) + ViewCompat.setOnApplyWindowInsetsListener(view) { _, insets -> + val bars = insets.getInsets(WindowInsetsCompat.Type.systemBars() or WindowInsetsCompat.Type.displayCutout()) + val ime = insets.getInsets(WindowInsetsCompat.Type.ime()).bottom + Bridge.nativeInsets(bars.top.toFloat(), bars.right.toFloat(), bars.bottom.toFloat(), bars.left.toFloat(), ime.toFloat()) + WindowInsetsCompat.CONSUMED + } + onBackPressedDispatcher.addCallback(this, Bridge.back) + VectorNotificationService.createChannels(this) + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU && + checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED + ) { + requestPermissions(arrayOf(Manifest.permission.POST_NOTIFICATIONS), NOTIFICATION_PERMISSION_REQUEST) + } + if (VectorBatteryHelper.getBackgroundServiceEnabled(this)) VectorBatteryHelper.startBackgroundService(this) + link(intent) + } + + override fun onNewIntent(intent: Intent) { + super.onNewIntent(intent) + link(intent) + } + + private fun link(intent: Intent?) { + intent ?: return + val callNpub = intent.getStringExtra(IncomingCall.EXTRA_CALL_NPUB) + if (!callNpub.isNullOrEmpty()) { + val callId = intent.getStringExtra(IncomingCall.EXTRA_CALL_ID) ?: "" + val answer = intent.getBooleanExtra(IncomingCall.EXTRA_CALL_ANSWER, false) + intent.removeExtra(IncomingCall.EXTRA_CALL_NPUB) + // A ringing call shows over the lock screen. + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1) { + setShowWhenLocked(true) + setTurnScreenOn(true) + } + nativeOnCallTap(callId, callNpub, answer) + return + } + intent.getStringExtra("chat_id")?.takeIf { it.isNotEmpty() }?.let { chat -> + intent.removeExtra("chat_id") + nativeOnNotificationTap(chat) + return + } + if (shared(intent)) return + intent.takeIf { it.action == Intent.ACTION_VIEW }?.dataString?.let(Bridge::nativeOpenUrl) + } + + /** The share sheet's files and text. Consumed, so a relaunch doesn't share them again. */ + private fun shared(intent: Intent): Boolean { + val action = intent.action + if (action != Intent.ACTION_SEND && action != Intent.ACTION_SEND_MULTIPLE) return false + val uris = streams(intent, action == Intent.ACTION_SEND_MULTIPLE) + val text = if (action == Intent.ACTION_SEND) intent.getStringExtra(Intent.EXTRA_TEXT) ?: "" else "" + intent.action = null + intent.removeExtra(Intent.EXTRA_STREAM) + intent.removeExtra(Intent.EXTRA_TEXT) + if (uris.isEmpty() && text.isEmpty()) return true + // Off the main thread: a shared video can take a while to copy. + val context = applicationContext + Thread { + val files = Picked.copy(context, uris) + nativeOnShare(files, text) + }.start() + return true + } + + @Suppress("DEPRECATION") + private fun streams(intent: Intent, multiple: Boolean): List = + if (multiple) { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) + intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM, Uri::class.java) ?: emptyList() + else + intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM) ?: emptyList() + } else { + val one = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) + intent.getParcelableExtra(Intent.EXTRA_STREAM, Uri::class.java) + else + intent.getParcelableExtra(Intent.EXTRA_STREAM) + listOfNotNull(one) + } + + private fun configuration(config: Configuration) { + val dark = config.uiMode and Configuration.UI_MODE_NIGHT_MASK == Configuration.UI_MODE_NIGHT_YES + Bridge.nativeConfiguration(resources.displayMetrics.density, dark) + } + + override fun onConfigurationChanged(newConfig: Configuration) { + super.onConfigurationChanged(newConfig) + configuration(newConfig) + } + + override fun onStart() { + super.onStart() + Bridge.nativeLifecycle(1) + } + + override fun onResume() { + super.onResume() + nativeForeground(true) + VectorNotificationService.clearAllMessageHistory() + Bridge.nativeLifecycle(2) + } + + override fun onPause() { + Bridge.nativeLifecycle(3) + nativeForeground(false) + super.onPause() + } + + override fun onStop() { + Bridge.nativeLifecycle(4) + super.onStop() + } + + override fun onDestroy() { + Bridge.nativeLifecycle(5) + nativeDestroyed() + super.onDestroy() + } + + // The signer app answers through the platform's own result path. + @Deprecated("ExternalSigner launches with startActivityForResult") + override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { + super.onActivityResult(requestCode, resultCode, data) + ExternalSigner.handleActivityResult(requestCode, resultCode, data) + } + + override fun onRequestPermissionsResult(requestCode: Int, permissions: Array, grantResults: IntArray) { + super.onRequestPermissionsResult(requestCode, permissions, grantResults) + PermissionHandler.handlePermissionResult(requestCode, grantResults) + } + + override fun onWindowFocusChanged(hasFocus: Boolean) { + super.onWindowFocusChanged(hasFocus) + Bridge.nativeFocus(hasFocus) + } + + override fun onTrimMemory(level: Int) { + super.onTrimMemory(level) + Bridge.nativeTrimMemory(level) + } +} diff --git a/crates/vector-gpui/android/app/src/main/java/io/vectorapp/NotificationActionReceiver.kt b/crates/vector-gpui/android/app/src/main/java/io/vectorapp/NotificationActionReceiver.kt new file mode 100644 index 000000000..1a5c8a1b4 --- /dev/null +++ b/crates/vector-gpui/android/app/src/main/java/io/vectorapp/NotificationActionReceiver.kt @@ -0,0 +1,47 @@ +package io.vectorapp + +import android.app.NotificationManager +import android.content.BroadcastReceiver +import android.content.Context +import android.content.Intent +import androidx.core.app.RemoteInput + +/** The shade's buttons: decline a ringing call, or mark a chat read or reply to it. */ +class NotificationActionReceiver : BroadcastReceiver() { + + companion object { + const val ACTION_MARK_READ = "io.vectorapp.ACTION_MARK_READ" + const val ACTION_REPLY = "io.vectorapp.ACTION_REPLY" + const val REPLY_KEY = "key_reply_text" + + init { + System.loadLibrary("vector_gpui") + } + + @JvmStatic + external fun nativeMarkAsRead(chatId: String) + @JvmStatic + external fun nativeSendReply(chatId: String, content: String) + } + + override fun onReceive(context: Context, intent: Intent) { + val chatId = intent.getStringExtra("chat_id") ?: return + when (intent.action) { + IncomingCall.ACTION_DECLINE -> { + val callId = intent.getStringExtra(IncomingCall.EXTRA_CALL_ID) ?: return + IncomingCall.decline(context, callId, chatId) + } + ACTION_MARK_READ -> { + nativeMarkAsRead(chatId) + val id = intent.getIntExtra("notification_id", -1) + if (id != -1) context.getSystemService(NotificationManager::class.java)?.cancel(id) + VectorNotificationService.clearMessageHistory(chatId) + } + ACTION_REPLY -> { + val reply = RemoteInput.getResultsFromIntent(intent)?.getCharSequence(REPLY_KEY)?.toString() ?: return + // The reply is posted back under the conversation, which clears the shade's spinner. + nativeSendReply(chatId, reply) + } + } + } +} diff --git a/crates/vector-gpui/android/app/src/main/java/io/vectorapp/NotificationDismissReceiver.kt b/crates/vector-gpui/android/app/src/main/java/io/vectorapp/NotificationDismissReceiver.kt new file mode 100644 index 000000000..1049a6e07 --- /dev/null +++ b/crates/vector-gpui/android/app/src/main/java/io/vectorapp/NotificationDismissReceiver.kt @@ -0,0 +1,13 @@ +package io.vectorapp + +import android.content.BroadcastReceiver +import android.content.Context +import android.content.Intent + +/** Clears message history for a chat when its notification is swiped away. */ +class NotificationDismissReceiver : BroadcastReceiver() { + override fun onReceive(context: Context, intent: Intent) { + val historyKey = intent.getStringExtra("history_key") ?: return + VectorNotificationService.clearMessageHistory(historyKey) + } +} diff --git a/crates/vector-gpui/android/app/src/main/java/io/vectorapp/PermissionHandler.java b/crates/vector-gpui/android/app/src/main/java/io/vectorapp/PermissionHandler.java new file mode 100644 index 000000000..0c18b76f8 --- /dev/null +++ b/crates/vector-gpui/android/app/src/main/java/io/vectorapp/PermissionHandler.java @@ -0,0 +1,31 @@ +package io.vectorapp; + +import android.content.pm.PackageManager; +import androidx.annotation.NonNull; + +public class PermissionHandler { + static { + System.loadLibrary("vector_gpui"); + } + + // Native callback method + private static native void onPermissionResult(int requestCode, boolean granted); + + // Forwarded from MainActivity.onRequestPermissionsResult — wakes the native + // blocking waiter for the RECORD_AUDIO request (voice recording). + public static void handlePermissionResult( + int requestCode, + @NonNull int[] grantResults + ) { + if (requestCode == io.vectorapp.gpui.CameraFeed.PERMISSION_REQUEST) { + io.vectorapp.gpui.CameraFeed.nativePermission( + grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED); + return; + } + if (requestCode == 9876) { // AUDIO_PERMISSION_REQUEST_CODE + boolean granted = grantResults.length > 0 && + grantResults[0] == PackageManager.PERMISSION_GRANTED; + onPermissionResult(requestCode, granted); + } + } +} \ No newline at end of file diff --git a/crates/vector-gpui/android/app/src/main/java/io/vectorapp/Strings.kt b/crates/vector-gpui/android/app/src/main/java/io/vectorapp/Strings.kt new file mode 100644 index 000000000..aff4b1cec --- /dev/null +++ b/crates/vector-gpui/android/app/src/main/java/io/vectorapp/Strings.kt @@ -0,0 +1,53 @@ +package io.vectorapp + +import android.content.Context +import org.json.JSONObject + +/** + * The shell's own text in the app's language: notifications, their channels and the system + * prompts. The app sends it whenever the language is set; it is kept so a service or receiver + * running before the app speaks the same language. English until the first send. + */ +object Strings { + private const val PREFS = "vector_strings" + private const val TABLE = "table" + + @Volatile private var app: Context? = null + @Volatile private var table: Map? = null + + /** Called from each entry point with a context, before it builds any text. */ + @JvmStatic + fun init(context: Context) { + if (app == null) app = context.applicationContext + } + + /** From the app: `json` maps each message id to its text. */ + @JvmStatic + fun set(context: Context, json: String) { + init(context) + val parsed = parse(json) ?: return + if (parsed == table) return + table = parsed + context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().putString(TABLE, json).apply() + // A channel keeps its sound and importance, but takes a new name and description. + VectorNotificationService.createChannels(context) + IncomingCall.channels(context) + CallService.channel(context) + } + + @JvmStatic + fun t(id: String, english: String): String { + val known = table ?: app?.let { load(it) }?.also { table = it } + return known?.get(id)?.takeIf { it.isNotEmpty() } ?: english + } + + private fun load(context: Context): Map? = + context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getString(TABLE, null)?.let { parse(it) } + + private fun parse(json: String): Map? = try { + val o = JSONObject(json) + o.keys().asSequence().associateWith { o.optString(it) } + } catch (_: Exception) { + null + } +} diff --git a/crates/vector-gpui/android/app/src/main/java/io/vectorapp/VectorBatteryHelper.kt b/crates/vector-gpui/android/app/src/main/java/io/vectorapp/VectorBatteryHelper.kt new file mode 100644 index 000000000..2a24d13a8 --- /dev/null +++ b/crates/vector-gpui/android/app/src/main/java/io/vectorapp/VectorBatteryHelper.kt @@ -0,0 +1,89 @@ +package io.vectorapp + +import android.content.Context +import android.content.Intent +import android.net.Uri +import android.os.PowerManager +import android.provider.Settings + +/** + * Static utility methods for battery optimization and background service control. + * Uses SharedPreferences ("vector_prefs") so BootReceiver and MainActivity can + * read the preference before any native Rust code initializes. + */ +object VectorBatteryHelper { + + private const val PREFS_NAME = "vector_prefs" + private const val KEY_BG_SERVICE_ENABLED = "background_service_enabled" + private const val KEY_BG_SERVICE_PROMPTED = "background_service_prompted" + + @JvmStatic + fun isIgnoringBatteryOptimizations(context: Context): Boolean { + val pm = context.getSystemService(Context.POWER_SERVICE) as PowerManager + return pm.isIgnoringBatteryOptimizations(context.packageName) + } + + @JvmStatic + fun requestBatteryOptimization(context: Context) { + try { + val intent = Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS).apply { + data = Uri.parse("package:${context.packageName}") + addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + } + context.startActivity(intent) + } catch (e: Exception) { + // Some OEM ROMs (MIUI, ColorOS) strip or redirect this system Activity. + // Fall back to the app's battery settings page. + try { + val fallback = Intent(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS).apply { + addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + } + context.startActivity(fallback) + } catch (_: Exception) { + android.util.Log.w("VectorBatteryHelper", "No battery optimization Activity available") + } + } + } + + @JvmStatic + fun getBackgroundServiceEnabled(context: Context): Boolean { + val prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE) + if (!prefs.contains(KEY_BG_SERVICE_ENABLED)) { + // Off for a new install; one that already holds an account ran in the background by default. + val existing = context.dataDir.listFiles()?.any { it.isDirectory && it.name.startsWith("npub1") } == true + setBackgroundServiceEnabled(context, existing) + return existing + } + return prefs.getBoolean(KEY_BG_SERVICE_ENABLED, false) + } + + @JvmStatic + fun setBackgroundServiceEnabled(context: Context, enabled: Boolean) { + val prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE) + prefs.edit().putBoolean(KEY_BG_SERVICE_ENABLED, enabled).commit() + } + + @JvmStatic + fun getBackgroundServicePrompted(context: Context): Boolean { + val prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE) + return prefs.getBoolean(KEY_BG_SERVICE_PROMPTED, false) + } + + @JvmStatic + fun setBackgroundServicePrompted(context: Context) { + val prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE) + prefs.edit().putBoolean(KEY_BG_SERVICE_PROMPTED, true).apply() + } + + @JvmStatic + fun startBackgroundService(context: Context) { + val intent = Intent(context, VectorNotificationService::class.java) + context.startForegroundService(intent) + } + + @JvmStatic + fun stopBackgroundService(context: Context) { + val intent = Intent(context, VectorNotificationService::class.java) + context.stopService(intent) + } +} diff --git a/crates/vector-gpui/android/app/src/main/java/io/vectorapp/VectorFiles.kt b/crates/vector-gpui/android/app/src/main/java/io/vectorapp/VectorFiles.kt new file mode 100644 index 000000000..6c2792bee --- /dev/null +++ b/crates/vector-gpui/android/app/src/main/java/io/vectorapp/VectorFiles.kt @@ -0,0 +1,281 @@ +package io.vectorapp + +import android.content.ClipData +import android.content.ClipboardManager +import android.content.Context +import android.content.Intent +import android.media.MediaScannerConnection +import android.net.Uri +import android.os.ParcelFileDescriptor +import androidx.core.content.FileProvider +import java.io.File + +/** + * Native file helpers bridged from Rust via JNI static calls. + * + * Intent / FileProvider / MediaScanner work lives here in type-checked Kotlin + * rather than raw JNI. Each method takes the Context as its first argument so + * the helper holds no static state. + */ +object VectorFiles { + /** + * Vector's public download directory under app-specific external *media* + * storage: /storage/emulated/0/Android/media//Vector. + * + * Chosen over /Android/data// because the media path stays browsable + * in file managers (Google hid /Android/data on Android 11+) and is + * eligible for gallery indexing — all with no runtime permission. Returns + * the absolute path, or null if external media storage is unavailable. + */ + @JvmStatic + @Suppress("DEPRECATION") // No replacement keeps this path, browsable and permission-free. + fun externalMediaDir(context: Context): String? { + val base = context.externalMediaDirs.firstOrNull { it != null } ?: return null + val dir = File(base, "Vector") + if (!dir.exists()) dir.mkdirs() + return dir.absolutePath + } + + /** + * Where the user's own copies go: the public Download/Vector, which outlives the app and + * shows in the gallery as "Vector". Android 11+ only; earlier, null (the media dir serves). + * A folder made here starts hidden when the media dir was hidden. + */ + @JvmStatic + fun publicDir(context: Context): String? { + if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.R) return null + return try { + val base = android.os.Environment.getExternalStoragePublicDirectory(android.os.Environment.DIRECTORY_DOWNLOADS) + val dir = File(base, "Vector") + if (!dir.exists()) { + if (!dir.mkdirs()) return null + val legacy = externalMediaDir(context)?.let { File(it, ".nomedia") } + if (legacy != null && legacy.exists()) File(dir, ".nomedia").createNewFile() + } + if (dir.isDirectory && dir.canWrite()) dir.absolutePath else null + } catch (_: Throwable) { + null + } + } + + /** Documents being written, held open until the writer is done: closing one is what + * tells its provider what was written, so a file manager shows its real size. */ + private val writing = java.util.concurrent.ConcurrentHashMap() + + /** + * A writable file descriptor for a document the user picked (ACTION_CREATE_DOCUMENT), + * truncated, owned by the caller from here; [finishWrite] once it's closed. -1 if it can't be opened. + */ + @JvmStatic + fun openForWrite(context: Context, uri: String): Int { + return try { + val pfd = context.contentResolver.openFileDescriptor(Uri.parse(uri), "wt") ?: return -1 + writing.put(uri, pfd)?.close() + pfd.dup().detachFd() + } catch (_: Throwable) { + -1 + } + } + + /** The caller has closed its descriptor for `uri`: let the provider record the file. */ + @JvmStatic + fun finishWrite(uri: String) { + try { + writing.remove(uri)?.close() + } catch (_: Throwable) { + } + } + + /** Remove a picked document a failed write left behind. */ + @JvmStatic + fun deleteDocument(context: Context, uri: String) { + try { + android.provider.DocumentsContract.deleteDocument(context.contentResolver, Uri.parse(uri)) + } catch (_: Throwable) { + } + } + + /** + * Ask the system MediaScanner to index a file so it shows up in the gallery + * and file managers promptly instead of after the next full scan. + */ + @JvmStatic + fun scanFile(context: Context, path: String) { + try { + MediaScannerConnection.scanFile(context, arrayOf(path), null, null) + } catch (_: Throwable) { + // Best-effort: the file is still on disk and browsable regardless. + } + } + + /** + * Batch variant of [scanFile] — indexes many files in a single scanner + * request. Used by the migration to avoid per-file JNI + connection churn + * for users with thousands of files. + */ + @JvmStatic + fun scanFiles(context: Context, paths: Array) { + try { + if (paths.isNotEmpty()) { + MediaScannerConnection.scanFile(context, paths, null, null) + } + } catch (_: Throwable) { + } + } + + /** + * Open a file with the user's chosen app via an ACTION_VIEW chooser. + * Hands out a content:// URI through the app's FileProvider with a + * temporary read grant. Returns true if an activity was launched. + */ + @JvmStatic + fun openFile(context: Context, path: String): Boolean { + return try { + val file = File(path) + if (!file.exists()) return false + val authority = context.packageName + ".fileprovider" + val uri: Uri = FileProvider.getUriForFile(context, authority, file) + + // An .apk goes to the package installer, which matches ONLY the exact + // package-archive type. Android's own MimeTypeMap has no entry for + // "apk", so the FileProvider answered application/octet-stream, no + // activity matched, and the tap looked like it did nothing at all. + if (file.extension.equals("apk", ignoreCase = true)) { + return installApk(context, uri) + } + + val mime = context.contentResolver.getType(uri) ?: "*/*" + val view = Intent(Intent.ACTION_VIEW).apply { + setDataAndType(uri, mime) + addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) + } + val chooser = Intent.createChooser(view, Strings.t("android-open-with", "Open with")).apply { + addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + } + context.startActivity(chooser) + true + } catch (_: Throwable) { + false + } + } + + /** + * Hand an .apk to the system package installer. + * + * No chooser: the installer is the only legitimate handler, and a chooser + * would invite a lookalike to sit beside it. The system owns the entire + * install UI from here — Vector only points at the file, the user decides. + * + * Since Android 8 the user must ALSO trust Vector as an install source. + * Until they do, the install intent silently does nothing, so send them to + * that toggle rather than leave another dead tap. + */ + private fun installApk(context: Context, uri: Uri): Boolean { + if (!context.packageManager.canRequestPackageInstalls()) { + val settings = Intent( + android.provider.Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, + Uri.parse("package:" + context.packageName) + ).apply { addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) } + context.startActivity(settings) + return true + } + val install = Intent(Intent.ACTION_VIEW).apply { + setDataAndType(uri, "application/vnd.android.package-archive") + addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_ACTIVITY_NEW_TASK) + } + context.startActivity(install) + return true + } + + /** + * Whether the user has trusted Vector as an install source. Always true below + * Android 8, where the setting is device-wide rather than per-app. Lets the UI + * say what will happen before the tap. + */ + @JvmStatic + fun canInstallApks(context: Context): Boolean { + return context.packageManager.canRequestPackageInstalls() + } + + /** + * Share a file through Android's share sheet (ACTION_SEND), handing out a + * content:// URI via the FileProvider with a temporary read grant. Returns + * true if the share sheet was launched. + */ + @JvmStatic + fun shareFile(context: Context, path: String): Boolean { + return try { + val file = File(path) + if (!file.exists()) return false + val authority = context.packageName + ".fileprovider" + val uri: Uri = FileProvider.getUriForFile(context, authority, file) + val mime = context.contentResolver.getType(uri) ?: "*/*" + val send = Intent(Intent.ACTION_SEND).apply { + type = mime + putExtra(Intent.EXTRA_STREAM, uri) + addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) + } + val chooser = Intent.createChooser(send, Strings.t("android-share", "Share")).apply { + addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + } + context.startActivity(chooser) + true + } catch (_: Throwable) { + false + } + } + + /** + * Put files on the system clipboard as content:// URIs (via the FileProvider) + * so they paste into apps that accept files. Mirrors [shareFile] but targets + * the clipboard instead of a share sheet. Returns true if a clip was set. + */ + @JvmStatic + fun copyFilesToClipboard(context: Context, paths: Array): Boolean { + return try { + val authority = context.packageName + ".fileprovider" + val resolver = context.contentResolver + var clip: ClipData? = null + for (p in paths) { + val file = File(p) + if (!file.exists()) continue + val uri: Uri = FileProvider.getUriForFile(context, authority, file) + if (clip == null) { + clip = ClipData.newUri(resolver, file.name, uri) + } else { + clip.addItem(ClipData.Item(uri)) + } + } + val built = clip ?: return false + val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager + clipboard.setPrimaryClip(built) + true + } catch (_: Throwable) { + false + } + } + + /** + * Return the content:// URIs of files on the clipboard. They're handed back + * verbatim (not copied to disk) so they flow through the same content-URI + * pipeline as a shared file — openFilePreview/cache_android_file read + cache + * the bytes immediately while the read grant is live. Text-only clips (no URI + * items) yield an empty array; clipboard reads require the app foregrounded + * (Android 10+), and a denial just yields an empty array. + */ + @JvmStatic + fun readClipboardFiles(context: Context): Array { + return try { + val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager + val clip = clipboard.primaryClip ?: return emptyArray() + val out = ArrayList() + for (i in 0 until clip.itemCount) { + val uri = clip.getItemAt(i).uri ?: continue + if (uri.scheme == "content") out.add(uri.toString()) + } + out.toTypedArray() + } catch (_: Throwable) { + emptyArray() + } + } +} diff --git a/crates/vector-gpui/android/app/src/main/java/io/vectorapp/VectorNotificationService.kt b/crates/vector-gpui/android/app/src/main/java/io/vectorapp/VectorNotificationService.kt new file mode 100644 index 000000000..7b64eadc8 --- /dev/null +++ b/crates/vector-gpui/android/app/src/main/java/io/vectorapp/VectorNotificationService.kt @@ -0,0 +1,255 @@ +package io.vectorapp + +import android.app.Notification +import android.app.NotificationChannel +import android.app.NotificationManager +import android.app.PendingIntent +import android.app.Service +import android.content.Context +import android.content.Intent +import android.graphics.Bitmap +import android.graphics.BitmapFactory +import android.media.AudioAttributes +import android.net.Uri +import android.os.IBinder +import androidx.core.app.NotificationCompat +import androidx.core.app.Person +import androidx.core.graphics.drawable.IconCompat + +/** + * Keeps the process, and so the client's relay connections, alive while the app is away, and + * posts its message notifications. Started with no window (at boot, or restarted), it signs in + * an account that needs no PIN and listens for it. The Tauri client's channels and ids, so an update in place + * keeps the user's channel settings. + */ +class VectorNotificationService : Service() { + + companion object { + const val SERVICE_CHANNEL_ID = "vector_service" + const val MESSAGES_CHANNEL_ID = "vector_messages_v2" + const val SERVICE_NOTIFICATION_ID = 1 + + // One row for every notification without a chat, so a replay can't pile them up. + private const val GENERIC_NOTIFICATION_ID = 0x56454331 + + /** MessagingStyle shows only what each post replays, so each chat keeps its recent lines. */ + private data class ChatMessage(val senderName: String, val senderAvatarPath: String, val body: String, val timestamp: Long) + private val chatMessageHistory = java.util.concurrent.ConcurrentHashMap>() + + init { + System.loadLibrary("vector_gpui") + } + + @JvmStatic + private external fun nativeStandby(context: Context) + + /** Called from Rust on any thread, so it reaches everything through `context`. */ + @JvmStatic + fun showMessageNotification( + context: Context, + title: String, + body: String, + avatarPath: String, + chatId: String, + senderName: String, + groupName: String, + groupAvatarPath: String, + ) { + Strings.init(context) + val manager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager + val isGroup = groupName.isNotEmpty() + val historyKey = chatId.ifEmpty { title } + + // Per chat and deterministic, so a cancel needs no state that a racing post could clear. + val notificationId = if (chatId.isNotEmpty()) chatId.hashCode() else GENERIC_NOTIFICATION_ID + // Stable request codes: a PendingIntent outlives the process, and a reused one keeps + // its old extras unless UPDATE_CURRENT replaces them. + val pendingRequestCode = notificationId * 2 + 1073741823 + + val launchIntent = Intent(context, MainActivity::class.java).apply { + flags = Intent.FLAG_ACTIVITY_SINGLE_TOP + if (chatId.isNotEmpty()) putExtra("chat_id", chatId) + } + val pendingIntent = PendingIntent.getActivity( + context, pendingRequestCode, launchIntent, + PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE + ) + val deleteIntent = Intent(context, NotificationDismissReceiver::class.java).apply { + putExtra("history_key", historyKey) + } + val deletePendingIntent = PendingIntent.getBroadcast( + context, pendingRequestCode, deleteIntent, + PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE + ) + + val history = synchronized(chatMessageHistory) { + val h = chatMessageHistory.getOrPut(historyKey) { mutableListOf() } + h.add(ChatMessage( + if (isGroup) senderName.ifEmpty { Strings.t("android-notify-someone", "Someone") } else senderName.ifEmpty { title }, + avatarPath, body, System.currentTimeMillis() + )) + while (h.size > 8) h.removeAt(0) + h.toList() + } + + val messagingStyle = NotificationCompat.MessagingStyle(Person.Builder().setName(Strings.t("android-notify-me", "Me")).build()) + if (isGroup) { + messagingStyle.setConversationTitle(groupName) + messagingStyle.setGroupConversation(true) + } + for (msg in history) { + val person = Person.Builder() + .setName(msg.senderName) + .apply { loadBitmap(msg.senderAvatarPath)?.let { setIcon(IconCompat.createWithBitmap(it)) } } + .build() + messagingStyle.addMessage(msg.body, msg.timestamp, person) + } + + val largeIcon = (if (isGroup) loadBitmap(groupAvatarPath) ?: loadBitmap(avatarPath) else loadBitmap(avatarPath)) + ?: BitmapFactory.decodeResource(context.resources, R.drawable.ic_large_icon) + + val builder = NotificationCompat.Builder(context, MESSAGES_CHANNEL_ID) + .setSmallIcon(R.drawable.ic_notification) + .setLargeIcon(largeIcon) + .setStyle(messagingStyle) + .setAutoCancel(true) + .setPriority(NotificationCompat.PRIORITY_HIGH) + .setContentIntent(pendingIntent) + .setDeleteIntent(deletePendingIntent) + .setOnlyAlertOnce(chatId.isEmpty()) + + // A notification without a chat (a locked account's) has nothing to act on. + if (chatId.isNotEmpty()) { + val markReadIntent = Intent(context, NotificationActionReceiver::class.java).apply { + action = NotificationActionReceiver.ACTION_MARK_READ + putExtra("chat_id", chatId) + putExtra("notification_id", notificationId) + } + val markReadPending = PendingIntent.getBroadcast( + context, notificationId * 2, markReadIntent, + PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE + ) + val remoteInput = androidx.core.app.RemoteInput.Builder(NotificationActionReceiver.REPLY_KEY) + .setLabel(Strings.t("android-notify-reply", "Reply")) + .build() + val replyIntent = Intent(context, NotificationActionReceiver::class.java).apply { + action = NotificationActionReceiver.ACTION_REPLY + putExtra("chat_id", chatId) + putExtra("notification_id", notificationId) + } + val replyPending = PendingIntent.getBroadcast( + context, notificationId * 2 + 1, replyIntent, + PendingIntent.FLAG_MUTABLE or PendingIntent.FLAG_UPDATE_CURRENT + ) + val replyAction = NotificationCompat.Action.Builder(R.drawable.ic_notification, Strings.t("android-notify-reply", "Reply"), replyPending) + .addRemoteInput(remoteInput) + .build() + builder.addAction(R.drawable.ic_notification, Strings.t("android-notify-mark-read", "Mark Read"), markReadPending) + builder.addAction(replyAction) + } + + manager.notify(notificationId, builder.build()) + } + + /** The user is back in the app: a later notification starts its conversation afresh. */ + @JvmStatic + fun clearAllMessageHistory() { + chatMessageHistory.clear() + } + + @JvmStatic + fun clearMessageHistory(historyKey: String) { + chatMessageHistory.remove(historyKey) + } + + @JvmStatic + fun cancelNotification(context: Context, chatId: String) { + if (chatId.isEmpty()) return + chatMessageHistory.remove(chatId) + val manager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager + manager.cancel(chatId.hashCode()) + } + + /** Every message notification and its history; the service's own row stays. */ + @JvmStatic + fun cancelAllMessageNotifications(context: Context) { + chatMessageHistory.clear() + val manager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager + for (shown in manager.activeNotifications) { + if (shown.notification.channelId == MESSAGES_CHANNEL_ID) manager.cancel(shown.tag, shown.id) + } + } + + /** Both channels, before anything posts to them. */ + @JvmStatic + fun createChannels(context: Context) { + Strings.init(context) + val manager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager + manager.createNotificationChannel( + NotificationChannel(SERVICE_CHANNEL_ID, Strings.t("android-channel-service", "Background Service"), NotificationManager.IMPORTANCE_MIN).apply { + description = Strings.t("android-channel-service-about", "Keeps Vector connected for real-time messages") + setShowBadge(false) + } + ) + // The first channel had the system sound, which a channel can never change. + manager.deleteNotificationChannel("vector_messages") + val prelude = Uri.parse("android.resource://${context.packageName}/raw/notif_prelude") + val audio = AudioAttributes.Builder() + .setUsage(AudioAttributes.USAGE_NOTIFICATION) + .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION) + .build() + manager.createNotificationChannel( + NotificationChannel(MESSAGES_CHANNEL_ID, Strings.t("android-channel-messages", "Messages"), NotificationManager.IMPORTANCE_HIGH).apply { + description = Strings.t("android-channel-messages-about", "New message notifications") + setSound(prelude, audio) + enableVibration(true) + } + ) + } + + private fun loadBitmap(path: String): Bitmap? { + if (path.isEmpty()) return null + return try { BitmapFactory.decodeFile(path) } catch (e: Exception) { null } + } + } + + private val serviceTagline: String by lazy { + listOf( + Strings.t("android-service-tagline-watch", "Keeping watch"), + Strings.t("android-service-tagline-miss", "You won't miss a thing"), + Strings.t("android-service-tagline-standby", "Standing by"), + ).random() + } + + override fun onCreate() { + super.onCreate() + createChannels(this) + } + + override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { + startForeground(SERVICE_NOTIFICATION_ID, buildServiceNotification()) + nativeStandby(applicationContext) + return START_STICKY + } + + override fun onBind(intent: Intent?): IBinder? = null + + private fun buildServiceNotification(): Notification { + val launchIntent = Intent(this, MainActivity::class.java).apply { flags = Intent.FLAG_ACTIVITY_SINGLE_TOP } + val pendingIntent = PendingIntent.getActivity( + this, 0, launchIntent, + PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE + ) + val body = android.text.SpannableStringBuilder() + .append(Strings.t("android-service-listening", "Listening for messages")) + .append(" · ") + .append(serviceTagline, android.text.style.StyleSpan(android.graphics.Typeface.ITALIC), android.text.Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) + return NotificationCompat.Builder(this, SERVICE_CHANNEL_ID) + .setContentTitle("Vector") + .setContentText(body) + .setSmallIcon(R.drawable.ic_notification) + .setOngoing(true) + .setContentIntent(pendingIntent) + .build() + } +} diff --git a/crates/vector-gpui/android/app/src/main/java/io/vectorapp/VectorPush.java b/crates/vector-gpui/android/app/src/main/java/io/vectorapp/VectorPush.java new file mode 100644 index 000000000..b00c6d349 --- /dev/null +++ b/crates/vector-gpui/android/app/src/main/java/io/vectorapp/VectorPush.java @@ -0,0 +1,87 @@ +package io.vectorapp; + +import android.app.Activity; +import android.content.Context; +import android.content.pm.PackageManager; + +import org.unifiedpush.android.connector.UnifiedPush; + +import java.util.List; + +/** + * Turning push on and off. A UnifiedPush app the user has (ntfy, Sunup, ...) is used first; + * without one, FCM's own Web Push endpoint through Play Services, by the distributor this app + * embeds, except in F-Droid's build, which embeds none. Neither involves a Firebase project. + */ +public final class VectorPush { + private static final String INSTANCE = "default"; + private static final String GSF_PACKAGE = "com.google.android.gms"; + + private static volatile boolean asking = false; + + private VectorPush() {} + + /** Ask for an endpoint, which arrives at VectorPushService. False when nothing can give one. */ + public static boolean enable(Activity activity, String vapid) { + String own = activity.getPackageName(); + List distributors = UnifiedPush.getDistributors(activity); + boolean external = false; + for (String d : distributors) { + if (!d.equals(own)) external = true; + } + String current = UnifiedPush.getAckDistributor(activity); + if (current == null) { + if (external) { + for (String d : distributors) { + if (!d.equals(own)) { + UnifiedPush.saveDistributor(activity, d); + break; + } + } + } else if (playServices(activity)) { + UnifiedPush.saveDistributor(activity, own); + } else { + return false; + } + } + asking = true; + UnifiedPush.register(activity, INSTANCE, "Vector", vapid); + return true; + } + + public static void disable(Context context) { + asking = false; + UnifiedPush.unregister(context, INSTANCE); + UnifiedPush.removeDistributor(context); + } + + /** + * `on` while the distributor that gave the endpoint is still here, `busy` while one is on its + * way, `off` when one can be asked for, else `unsupported`. + */ + public static String status(Context context, boolean registered) { + // A distributor that is gone (uninstalled, or one this build doesn't embed) is unregistered + // by the connector here, which withdraws the endpoint through VectorPushService. + if (registered && UnifiedPush.getAckDistributor(context) != null) return "on"; + if (asking) return "busy"; + for (String d : UnifiedPush.getDistributors(context)) { + if (!d.equals(context.getPackageName())) return "off"; + } + return playServices(context) ? "off" : "unsupported"; + } + + /** The distributor answered, with an endpoint or a refusal. */ + static void settled() { + asking = false; + } + + private static boolean playServices(Context context) { + if (!BuildConfig.EMBEDDED_FCM) return false; + try { + context.getPackageManager().getPackageInfo(GSF_PACKAGE, 0); + return true; + } catch (PackageManager.NameNotFoundException e) { + return false; + } + } +} diff --git a/crates/vector-gpui/android/app/src/main/java/io/vectorapp/VectorPushService.java b/crates/vector-gpui/android/app/src/main/java/io/vectorapp/VectorPushService.java new file mode 100644 index 000000000..450852ddc --- /dev/null +++ b/crates/vector-gpui/android/app/src/main/java/io/vectorapp/VectorPushService.java @@ -0,0 +1,59 @@ +package io.vectorapp; + +import android.util.Log; + +import org.unifiedpush.android.connector.FailedReason; +import org.unifiedpush.android.connector.PushService; +import org.unifiedpush.android.connector.data.PushEndpoint; +import org.unifiedpush.android.connector.data.PushMessage; + +/** + * UnifiedPush's events for this app (a distributor app's, or the embedded FCM one's), handed to + * Rust (`src/backend/push.rs`). Java rather than Kotlin: the connector is built by a newer Kotlin + * than this project's, whose metadata a Java caller never reads. + */ +public class VectorPushService extends PushService { + static { + System.loadLibrary("vector_gpui"); + } + + private static native void nativeNewEndpoint(Object context, String dataDir, String url, String p256dh, String auth); + + private static native void nativeMessage(Object context, String dataDir, byte[] content); + + private static native void nativeUnregistered(Object context, String dataDir); + + private String dataDir() { + return getApplicationContext().getDataDir().getAbsolutePath(); + } + + @Override + public void onNewEndpoint(PushEndpoint endpoint, String instance) { + // Without Web Push keys a sender can't seal for this phone. + VectorPush.settled(); + if (endpoint.getPubKeySet() == null) { + Log.w("VectorPush", "endpoint without Web Push keys"); + return; + } + nativeNewEndpoint(getApplicationContext(), dataDir(), endpoint.getUrl(), + endpoint.getPubKeySet().getPubKey(), endpoint.getPubKeySet().getAuth()); + } + + @Override + public void onMessage(PushMessage message, String instance) { + // Sealed pushes are always encrypted: one that isn't came from somewhere else. + if (!message.getDecrypted()) return; + nativeMessage(getApplicationContext(), dataDir(), message.getContent()); + } + + @Override + public void onRegistrationFailed(FailedReason reason, String instance) { + Log.w("VectorPush", "registration failed: " + reason); + VectorPush.settled(); + } + + @Override + public void onUnregistered(String instance) { + nativeUnregistered(getApplicationContext(), dataDir()); + } +} diff --git a/crates/vector-gpui/android/app/src/main/java/io/vectorapp/VectorUpdates.kt b/crates/vector-gpui/android/app/src/main/java/io/vectorapp/VectorUpdates.kt new file mode 100644 index 000000000..26e01f1a0 --- /dev/null +++ b/crates/vector-gpui/android/app/src/main/java/io/vectorapp/VectorUpdates.kt @@ -0,0 +1,114 @@ +package io.vectorapp + +import android.content.Context +import android.content.Intent +import android.content.pm.PackageManager +import android.net.Uri +import androidx.core.content.FileProvider +import java.io.File +import java.security.MessageDigest + +/** + * In-app update install, for SIDELOADED builds only. + * + * A store-installed copy is updated by its store; Rust decides that upstream + * and never calls in here. What this adds over "open the file" is the check + * below: Android refuses an update signed by a different key, and finding that + * out AFTER a download is a miserable way to learn it. + */ +object VectorUpdates { + /** + * SHA-256 of the certificate that signed the installed app, lowercase hex. + * Null if it cannot be read — callers treat that as "cannot verify". + */ + @JvmStatic + fun installedSignatureSha256(context: Context): String? = try { + val pm = context.packageManager + @Suppress("DEPRECATION") + val flags = if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.P) { + PackageManager.GET_SIGNING_CERTIFICATES + } else { + PackageManager.GET_SIGNATURES + } + @Suppress("DEPRECATION") + val info = pm.getPackageInfo(context.packageName, flags) + certDigest(signaturesOf(info)) + } catch (_: Throwable) { + null + } + + /** + * SHA-256 of the certificate that signed the APK at `path`, lowercase hex. + * Null if the file is unreadable or not a parseable package — which is + * itself a reason to refuse, so callers must not treat null as a match. + */ + @JvmStatic + fun apkSignatureSha256(context: Context, path: String): String? = try { + val pm = context.packageManager + @Suppress("DEPRECATION") + val flags = if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.P) { + PackageManager.GET_SIGNING_CERTIFICATES + } else { + PackageManager.GET_SIGNATURES + } + @Suppress("DEPRECATION") + val info = pm.getPackageArchiveInfo(path, flags) + if (info == null) null else certDigest(signaturesOf(info)) + } catch (_: Throwable) { + null + } + + @Suppress("DEPRECATION") + private fun signaturesOf(info: android.content.pm.PackageInfo): Array? { + if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.P) { + val signing = info.signingInfo ?: return null + // A rotated key reports its history; the CURRENT signer is what an + // update is judged against. + return if (signing.hasMultipleSigners()) signing.apkContentsSigners + else signing.signingCertificateHistory + } + return info.signatures + } + + private fun certDigest(sigs: Array?): String? { + val first = sigs?.firstOrNull() ?: return null + val digest = MessageDigest.getInstance("SHA-256").digest(first.toByteArray()) + return digest.joinToString("") { "%02x".format(it) } + } + + /** + * Launch the system installer for a downloaded update. + * + * Refuses unless the APK is signed by the same certificate as the running + * app: Android would reject the install anyway, and refusing here turns a + * confusing platform error into something we can explain. Returns a status + * the Rust side maps to a message. + */ + @JvmStatic + fun installUpdate(context: Context, path: String): String { + val file = File(path) + if (!file.exists()) return "missing" + + val installed = installedSignatureSha256(context) ?: return "unverifiable" + val incoming = apkSignatureSha256(context, path) ?: return "unverifiable" + if (installed != incoming) return "signature-mismatch" + + if (!context.packageManager.canRequestPackageInstalls()) { + val settings = Intent( + android.provider.Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, + Uri.parse("package:" + context.packageName) + ).apply { addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) } + context.startActivity(settings) + return "needs-permission" + } + + val authority = context.packageName + ".fileprovider" + val uri: Uri = FileProvider.getUriForFile(context, authority, file) + val install = Intent(Intent.ACTION_VIEW).apply { + setDataAndType(uri, "application/vnd.android.package-archive") + addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_ACTIVITY_NEW_TASK) + } + context.startActivity(install) + return "ok" + } +} diff --git a/crates/vector-gpui/android/app/src/main/java/io/vectorapp/gpui/Bridge.kt b/crates/vector-gpui/android/app/src/main/java/io/vectorapp/gpui/Bridge.kt new file mode 100644 index 000000000..4e0ab30b7 --- /dev/null +++ b/crates/vector-gpui/android/app/src/main/java/io/vectorapp/gpui/Bridge.kt @@ -0,0 +1,140 @@ +package io.vectorapp.gpui + +import android.content.ActivityNotFoundException +import android.content.ClipData +import android.content.ClipboardManager +import android.content.Context +import android.content.Intent +import android.net.Uri +import android.os.Bundle +import android.os.Handler +import android.os.Looper +import android.view.Surface +import android.view.View +import android.view.accessibility.AccessibilityEvent +import android.view.accessibility.AccessibilityNodeInfo +import androidx.activity.OnBackPressedCallback +import io.vectorapp.MainActivity +import java.lang.ref.WeakReference + +/** + * The JNI boundary with GPUI (crates/vector-gpui/vendor/gpui_android/src/bridge.rs). Everything + * `native*` hands an event to GPUI's thread and returns; the rest is called from that thread and + * does its UI work on the main one. + */ +object Bridge { + init { + System.loadLibrary("vector_gpui") + } + + private val main = Handler(Looper.getMainLooper()) + private var activity = WeakReference(null) + private lateinit var context: Context + + /** Back goes to GPUI only while it has somewhere to go back to. */ + val back = object : OnBackPressedCallback(false) { + override fun handleOnBackPressed() = nativeBack() + } + + fun attach(activity: MainActivity) { + this.activity = WeakReference(activity) + context = activity.applicationContext + nativeStart(context) + } + + private fun ui(action: (MainActivity) -> Unit) { + main.post { activity.get()?.let(action) } + } + + @JvmStatic external fun nativeStart(context: Context) + @JvmStatic external fun nativeSurfaceCreated(surface: Surface) + @JvmStatic external fun nativeSurfaceChanged(width: Int, height: Int) + /** Returns once GPUI has stopped drawing into the surface. */ + @JvmStatic external fun nativeSurfaceDestroyed() + /** Phase 0 down, 1 move, 2 up, 3 cancelled; `uptimeNanos` on SystemClock's uptime clock. */ + @JvmStatic external fun nativeTouch(id: Int, phase: Int, x: Float, y: Float, pressure: Float, uptimeNanos: Long) + @JvmStatic external fun nativeKey(down: Boolean, keyCode: Int, unicode: Int, base: Int, meta: Int, repeat: Int) + /** Pixels the system bars and cutouts cover, and the keyboard's height. */ + @JvmStatic external fun nativeInsets(top: Float, right: Float, bottom: Float, left: Float, ime: Float) + @JvmStatic external fun nativeConfiguration(density: Float, dark: Boolean) + /** 1 started, 2 resumed, 3 paused, 4 stopped, 5 destroyed. */ + @JvmStatic external fun nativeLifecycle(phase: Int) + @JvmStatic external fun nativeFocus(focused: Boolean) + @JvmStatic external fun nativeBack() + @JvmStatic external fun nativeTrimMemory(level: Int) + @JvmStatic external fun nativeOpenUrl(url: String) + /** The keyboard's copy of the focused field after its edit number `serial`; -1 is no composing region. */ + @JvmStatic external fun nativeImeState(text: String, selStart: Int, selEnd: Int, compStart: Int, compEnd: Int, serial: Int) + @JvmStatic external fun nativeImeAction(action: Int) + /** The picker for `id` closed: its files' cached copies, or null when cancelled. */ + @JvmStatic external fun nativePicked(id: Int, paths: Array?) + + /** GPUI's accessibility tree, served as virtual views of `host` (gpui_android/src/a11y.rs). */ + @JvmStatic external fun nativeA11yNode(host: View, id: Int): AccessibilityNodeInfo? + @JvmStatic external fun nativeA11yFocus(host: View, kind: Int): AccessibilityNodeInfo? + @JvmStatic external fun nativeA11yAction(host: View, id: Int, action: Int, arguments: Bundle?): Boolean + @JvmStatic external fun nativeA11yHover(host: View, action: Int, x: Float, y: Float): Boolean + @JvmStatic external fun nativeA11yRaise(host: View) + /** Every accessibility service is off. */ + @JvmStatic external fun nativeA11yOff() + + @JvmStatic fun a11yRaise() = ui { nativeA11yRaise(it.view) } + + @JvmStatic fun a11yChanged() = ui { + it.view.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED) + } + + @JvmStatic fun showKeyboard() = ui { it.view.showKeyboard() } + + /** The system back gesture gives way on the left edge from `top` to `bottom`, GPUI's pixels. */ + @JvmStatic fun claimLeft(top: Float, bottom: Float) = ui { it.view.claimLeft(top to bottom) } + + @JvmStatic fun releaseLeft() = ui { it.view.claimLeft(null) } + + @JvmStatic fun hideKeyboard() = ui { it.view.hideKeyboard() } + + @JvmStatic fun setBackEnabled(enabled: Boolean) { + main.post { back.isEnabled = enabled } + } + + @JvmStatic fun finish() = ui { it.finish() } + + @JvmStatic fun moveToBack() = ui { it.moveTaskToBack(true) } + + @JvmStatic fun pickFiles(id: Int, multiple: Boolean, extensions: Array) { + main.post { + val activity = activity.get() + if (activity == null) nativePicked(id, null) else activity.pickFiles(id, multiple, extensions) + } + } + + @JvmStatic fun openUrl(url: String) = ui { + try { + it.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(url))) + } catch (_: ActivityNotFoundException) { + } + } + + /** A file in the app that takes its type, through the app's FileProvider. */ + @JvmStatic fun openFile(path: String) = ui { io.vectorapp.VectorFiles.openFile(it, path) } + + @JvmStatic fun setClipboard(text: String) { + main.post { + context.getSystemService(ClipboardManager::class.java) + ?.setPrimaryClip(ClipData.newPlainText(null, text)) + } + } + + @JvmStatic fun getClipboard(): String? { + val clip = context.getSystemService(ClipboardManager::class.java)?.primaryClip ?: return null + if (clip.itemCount == 0) return null + return clip.getItemAt(0).coerceToText(context)?.toString() + } + + /** GPUI's field, after the keyboard edits up to `serial`; -1 is no composing region. */ + @JvmStatic fun setTextState(text: String, selStart: Int, selEnd: Int, compStart: Int, compEnd: Int, serial: Int) = + ui { it.view.setTextState(text, selStart, selEnd, compStart, compEnd, serial) } + + /** The focused field's keyboard, packed: bit 0 autocorrect, bit 1 suggestions, bits 2-3 caps, 4-7 action. */ + @JvmStatic fun setInputOptions(options: Int) = ui { it.view.setInputOptions(options) } +} diff --git a/crates/vector-gpui/android/app/src/main/java/io/vectorapp/gpui/CameraFeed.kt b/crates/vector-gpui/android/app/src/main/java/io/vectorapp/gpui/CameraFeed.kt new file mode 100644 index 000000000..e61a4b406 --- /dev/null +++ b/crates/vector-gpui/android/app/src/main/java/io/vectorapp/gpui/CameraFeed.kt @@ -0,0 +1,217 @@ +package io.vectorapp.gpui + +import android.annotation.SuppressLint +import android.content.Context +import android.graphics.ImageFormat +import android.hardware.camera2.CameraCaptureSession +import android.hardware.camera2.CameraCharacteristics +import android.hardware.camera2.CameraDevice +import android.hardware.camera2.CameraManager +import android.hardware.camera2.CaptureRequest +import android.media.ImageReader +import android.os.Handler +import android.os.HandlerThread +import android.util.Log +import android.util.Range +import android.util.Size +import android.view.Surface +import android.view.WindowManager + +/** + * A camera as a stream of YUV frames for Rust (crates/vector-gpui/src/callvideo/camera.rs): each + * frame's planes go to [nativeFrame] while the image is held, so Rust copies them before it is + * closed. One feed at a time, named by the id Rust gave it. + */ +object CameraFeed { + private const val TAG = "vector" + + private var thread: HandlerThread? = null + private var handler: Handler? = null + private var device: CameraDevice? = null + private var session: CameraCaptureSession? = null + private var reader: ImageReader? = null + @Volatile private var running = 0L + + @JvmStatic external fun nativeFrame( + id: Long, + y: java.nio.ByteBuffer, u: java.nio.ByteBuffer, v: java.nio.ByteBuffer, + yRow: Int, uvRow: Int, uvPixel: Int, + width: Int, height: Int, rotation: Int, + ) + + @JvmStatic external fun nativeLost(id: Long) + + /** The answer to the camera permission prompt, from MainActivity. */ + @JvmStatic external fun nativePermission(granted: Boolean) + + const val PERMISSION_REQUEST = 9877 + + /** The camera facing that way, else the first there is. */ + private fun pick(manager: CameraManager, front: Boolean): String? { + val want = if (front) CameraCharacteristics.LENS_FACING_FRONT else CameraCharacteristics.LENS_FACING_BACK + val ids = manager.cameraIdList + return ids.firstOrNull { manager.getCameraCharacteristics(it).get(CameraCharacteristics.LENS_FACING) == want } + ?: ids.firstOrNull() + } + + /** The output size nearest `width`x`height` by area, of those the camera gives as YUV. */ + private fun size(chars: CameraCharacteristics, width: Int, height: Int): Size { + val map = chars.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP) + val sizes = map?.getOutputSizes(ImageFormat.YUV_420_888)?.toList().orEmpty() + val area = width.toLong() * height + return sizes.minByOrNull { Math.abs(it.width.toLong() * it.height - area) } ?: Size(width, height) + } + + /** Degrees the sensor's picture turns clockwise to stand upright on the display as it is now. */ + private fun rotation(context: Context, chars: CameraCharacteristics, front: Boolean): Int { + val sensor = chars.get(CameraCharacteristics.SENSOR_ORIENTATION) ?: 0 + @Suppress("DEPRECATION") + val display = (context.getSystemService(Context.WINDOW_SERVICE) as WindowManager).defaultDisplay.rotation + val device = when (display) { + Surface.ROTATION_90 -> 90 + Surface.ROTATION_180 -> 180 + Surface.ROTATION_270 -> 270 + else -> 0 + } + return if (front) (sensor + device) % 360 else (sensor - device + 360) % 360 + } + + /** Opens a camera for feed `id`; false when there is none or it can't be reached. */ + @SuppressLint("MissingPermission") + @JvmStatic + @Synchronized + fun start(context: Context, id: Long, front: Boolean, width: Int, height: Int): Boolean { + stopLocked() + val manager = context.getSystemService(Context.CAMERA_SERVICE) as? CameraManager ?: return false + return try { + val cameraId = pick(manager, front) ?: return false + val chars = manager.getCameraCharacteristics(cameraId) + val facingFront = chars.get(CameraCharacteristics.LENS_FACING) == CameraCharacteristics.LENS_FACING_FRONT + val out = size(chars, width, height) + val worker = HandlerThread("camera").also { it.start() } + val handler = Handler(worker.looper) + val images = ImageReader.newInstance(out.width, out.height, ImageFormat.YUV_420_888, 3) + images.setOnImageAvailableListener({ r -> + val image = r.acquireLatestImage() ?: return@setOnImageAvailableListener + try { + if (running == id) { + val p = image.planes + nativeFrame( + id, p[0].buffer, p[1].buffer, p[2].buffer, + p[0].rowStride, p[1].rowStride, p[1].pixelStride, + image.width, image.height, rotation(context, chars, facingFront), + ) + } + } finally { + image.close() + } + }, handler) + thread = worker + this.handler = handler + reader = images + running = id + manager.openCamera(cameraId, object : CameraDevice.StateCallback() { + override fun onOpened(camera: CameraDevice) { + synchronized(CameraFeed) { + if (running != id) { + camera.close() + return + } + device = camera + } + val target = images.surface + @Suppress("DEPRECATION") + camera.createCaptureSession(listOf(target), object : CameraCaptureSession.StateCallback() { + override fun onConfigured(s: CameraCaptureSession) { + synchronized(CameraFeed) { + if (running != id) { + s.close() + return + } + session = s + } + try { + val request = camera.createCaptureRequest(CameraDevice.TEMPLATE_RECORD).apply { + addTarget(target) + set(CaptureRequest.CONTROL_AE_TARGET_FPS_RANGE, Range(15, 30)) + } + s.setRepeatingRequest(request.build(), null, handler) + } catch (e: Exception) { + Log.w(TAG, "camera request: $e") + lost(id) + } + } + + override fun onConfigureFailed(s: CameraCaptureSession) { + Log.w(TAG, "camera session failed") + lost(id) + } + }, handler) + } + + override fun onDisconnected(camera: CameraDevice) { + camera.close() + lost(id) + } + + override fun onError(camera: CameraDevice, error: Int) { + Log.w(TAG, "camera error $error") + camera.close() + lost(id) + } + }, handler) + true + } catch (e: Exception) { + Log.w(TAG, "camera: $e") + stopLocked() + false + } + } + + private fun lost(id: Long) { + val current = synchronized(CameraFeed) { running == id } + if (current) { + stop(id) + nativeLost(id) + } + } + + /** Ends feed `id`, if it is still the one running. */ + @JvmStatic + @Synchronized + fun stop(id: Long) { + if (running == id) { + stopLocked() + } + } + + /** Closes on the camera's own thread, so no frame is mid-copy when its reader goes. */ + private fun stopLocked() { + running = 0L + val s = session + val d = device + val r = reader + val t = thread + val h = handler + session = null + device = null + reader = null + thread = null + handler = null + val close = Runnable { + try { + s?.close() + } catch (_: Exception) { + } + try { + d?.close() + } catch (_: Exception) { + } + r?.close() + t?.quitSafely() + } + if (h == null || !h.post(close)) { + close.run() + } + } +} diff --git a/crates/vector-gpui/android/app/src/main/java/io/vectorapp/gpui/GpuiView.kt b/crates/vector-gpui/android/app/src/main/java/io/vectorapp/gpui/GpuiView.kt new file mode 100644 index 000000000..90b2d16cf --- /dev/null +++ b/crates/vector-gpui/android/app/src/main/java/io/vectorapp/gpui/GpuiView.kt @@ -0,0 +1,272 @@ +package io.vectorapp.gpui + +import android.annotation.SuppressLint +import android.content.Context +import android.graphics.Rect +import android.os.Build +import android.os.Bundle +import android.text.InputType +import android.text.Selection +import android.text.SpannableStringBuilder +import android.text.Spanned +import android.text.style.UnderlineSpan +import android.view.KeyEvent +import android.view.MotionEvent +import android.view.SurfaceHolder +import android.view.SurfaceView +import android.view.accessibility.AccessibilityManager +import android.view.accessibility.AccessibilityNodeInfo +import android.view.accessibility.AccessibilityNodeProvider +import android.view.inputmethod.BaseInputConnection +import android.view.inputmethod.EditorInfo +import android.view.inputmethod.InputConnection +import android.view.inputmethod.InputMethodManager + +/** + * The surface GPUI draws into, and the keyboard's way into GPUI's text fields: the keyboard edits + * [field], a copy of the focused field, and each edit goes to GPUI as the copy's new state. + */ +@SuppressLint("ViewConstructor") +class GpuiView(context: Context) : SurfaceView(context), SurfaceHolder.Callback { + val field = SpannableStringBuilder() + private val imm = context.getSystemService(InputMethodManager::class.java) + private var options = 0 + private var serial = 0 + private var reported: List? = null + private val composing = UnderlineSpan() + private val access = context.getSystemService(AccessibilityManager::class.java) + + private val nodes = object : AccessibilityNodeProvider() { + override fun createAccessibilityNodeInfo(virtualViewId: Int): AccessibilityNodeInfo? = + Bridge.nativeA11yNode(this@GpuiView, virtualViewId) + + override fun findFocus(focus: Int): AccessibilityNodeInfo? = Bridge.nativeA11yFocus(this@GpuiView, focus) + + override fun performAction(virtualViewId: Int, action: Int, arguments: Bundle?) = + Bridge.nativeA11yAction(this@GpuiView, virtualViewId, action, arguments) + } + + init { + holder.addCallback(this) + isFocusable = true + isFocusableInTouchMode = true + access?.addAccessibilityStateChangeListener { on -> if (!on) Bridge.nativeA11yOff() } + addOnLayoutChangeListener { _, _, _, _, _, _, _, _, _ -> claimEdges() } + } + + /** The rail's left-edge pull (top, bottom) in this view's pixels, while one shows. */ + private var leftPull: Pair? = null + + /** `top`..`bottom` in GPUI's pixels; none to release it. */ + fun claimLeft(span: Pair?) { + val density = resources.displayMetrics.density + leftPull = span?.let { (top, bottom) -> (top * density).toInt() to (bottom * density).toInt() } + claimEdges() + } + + /** + * Vector draws its own side swipes (the Communities rail, swipe to reply), so the system back + * gesture gives way along both side edges as far as Android allows: 200dp of height a side. On + * the left it sits on the rail's pull tab while one shows, else where a thumb swipes. + */ + private fun claimEdges() { + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q || width == 0 || height == 0) return + val density = resources.displayMetrics.density + val band = (200 * density).toInt().coerceAtMost(height) + val edge = (48 * density).toInt() + val thumb = (height * 2 / 5 - band / 2).coerceIn(0, height - band) + val left = leftPull?.let { (top, bottom) -> ((top + bottom) / 2 - band / 2).coerceIn(0, height - band) } ?: thumb + systemGestureExclusionRects = listOf( + Rect(0, left, edge, left + band), + Rect(width - edge, thumb, width, thumb + band), + ) + } + + override fun getAccessibilityNodeProvider(): AccessibilityNodeProvider = nodes + + /** Explore by touch arrives as hover; a mouse's hover, with no screen reader on, is not for it. */ + override fun dispatchHoverEvent(event: MotionEvent): Boolean { + if (access?.isTouchExplorationEnabled == true && Bridge.nativeA11yHover(this, event.action, event.x, event.y)) { + return true + } + return super.dispatchHoverEvent(event) + } + + override fun surfaceCreated(holder: SurfaceHolder) = Bridge.nativeSurfaceCreated(holder.surface) + + override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) = + Bridge.nativeSurfaceChanged(width, height) + + override fun surfaceDestroyed(holder: SurfaceHolder) = Bridge.nativeSurfaceDestroyed() + + @SuppressLint("ClickableViewAccessibility") + override fun onTouchEvent(event: MotionEvent): Boolean { + when (event.actionMasked) { + MotionEvent.ACTION_DOWN, MotionEvent.ACTION_POINTER_DOWN -> touch(event, event.actionIndex, 0) + MotionEvent.ACTION_MOVE -> for (i in 0 until event.pointerCount) { + // The samples batched since the last frame, so velocity sees every one. + for (h in 0 until event.historySize) { + Bridge.nativeTouch( + event.getPointerId(i), 1, event.getHistoricalX(i, h), event.getHistoricalY(i, h), + event.getHistoricalPressure(i, h), event.getHistoricalEventTime(h) * 1_000_000, + ) + } + touch(event, i, 1) + } + MotionEvent.ACTION_UP, MotionEvent.ACTION_POINTER_UP -> touch(event, event.actionIndex, 2) + MotionEvent.ACTION_CANCEL -> for (i in 0 until event.pointerCount) touch(event, i, 3) + else -> return false + } + return true + } + + private fun touch(event: MotionEvent, index: Int, phase: Int) { + val time = if (Build.VERSION.SDK_INT >= 34) event.eventTimeNanos else event.eventTime * 1_000_000 + Bridge.nativeTouch(event.getPointerId(index), phase, event.getX(index), event.getY(index), event.getPressure(index), time) + } + + override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean = key(true, event) || super.onKeyDown(keyCode, event) + + override fun onKeyUp(keyCode: Int, event: KeyEvent): Boolean = key(false, event) || super.onKeyUp(keyCode, event) + + private fun key(down: Boolean, event: KeyEvent): Boolean { + if (event.isSystem) return false + Bridge.nativeKey(down, event.keyCode, event.getUnicodeChar(event.metaState), event.getUnicodeChar(0), event.metaState, event.repeatCount) + return true + } + + /** A GPUI field has focus. Without one a stray key mustn't bring the keyboard back. */ + private var editing = false + + override fun onCheckIsTextEditor() = editing + + override fun onCreateInputConnection(info: EditorInfo): InputConnection? { + if (!editing) return null + val action = options shr 4 and 0xF + var type = InputType.TYPE_CLASS_TEXT + if (options and 1 != 0) type = type or InputType.TYPE_TEXT_FLAG_AUTO_CORRECT + if (options and 2 == 0) type = type or InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS + type = type or when (options shr 2 and 3) { + 1 -> InputType.TYPE_TEXT_FLAG_CAP_WORDS + 2 -> InputType.TYPE_TEXT_FLAG_CAP_SENTENCES + 3 -> InputType.TYPE_TEXT_FLAG_CAP_CHARACTERS + else -> 0 + } + // No action of its own: Enter is a key, and the field takes many lines. + if (action <= 1) type = type or InputType.TYPE_TEXT_FLAG_MULTI_LINE + info.inputType = type + info.imeOptions = EditorInfo.IME_FLAG_NO_FULLSCREEN or EditorInfo.IME_FLAG_NO_EXTRACT_UI or when (action) { + 2 -> EditorInfo.IME_ACTION_DONE + 3 -> EditorInfo.IME_ACTION_GO + 4 -> EditorInfo.IME_ACTION_NEXT + 5 -> EditorInfo.IME_ACTION_PREVIOUS + 6 -> EditorInfo.IME_ACTION_SEARCH + 7 -> EditorInfo.IME_ACTION_SEND + else -> EditorInfo.IME_ACTION_NONE + } + info.initialSelStart = Selection.getSelectionStart(field) + info.initialSelEnd = Selection.getSelectionEnd(field) + return KeyboardConnection(this) + } + + fun showKeyboard() { + if (!editing) { + editing = true + imm.restartInput(this) + } + requestFocus() + imm.showSoftInput(this, 0) + } + + fun hideKeyboard() { + imm.hideSoftInputFromWindow(windowToken, 0) + if (editing) { + editing = false + imm.restartInput(this) + } + } + + fun setInputOptions(options: Int) { + if (this.options != options) { + this.options = options + imm.restartInput(this) + } + } + + /** GPUI's field. One that predates the keyboard's latest edit is skipped: GPUI answers that edit too. */ + fun setTextState(text: String, selStart: Int, selEnd: Int, compStart: Int, compEnd: Int, serial: Int) { + if (serial < this.serial) return + val replaced = field.toString() != text + if (replaced) field.replace(0, field.length, text) + Selection.setSelection(field, selStart.coerceIn(0, field.length), selEnd.coerceIn(0, field.length)) + BaseInputConnection.removeComposingSpans(field) + if (compStart >= 0 && compEnd > compStart && compEnd <= field.length) { + field.setSpan(composing, compStart, compEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE or Spanned.SPAN_COMPOSING) + } + reported = state() + // A keyboard mid-word holds its own idea of the text, which only a restart resets. + if (replaced) imm.restartInput(this) else imm.updateSelection(this, selStart, selEnd, compStart, compEnd) + } + + private fun state(): List = listOf( + field.toString(), + Selection.getSelectionStart(field), + Selection.getSelectionEnd(field), + BaseInputConnection.getComposingSpanStart(field), + BaseInputConnection.getComposingSpanEnd(field), + ) + + /** After the keyboard's edit (or its batch of them), GPUI gets the field as it now stands. */ + fun edited() { + val now = state() + if (now == reported) return + reported = now + serial += 1 + Bridge.nativeImeState(now[0] as String, now[1] as Int, now[2] as Int, now[3] as Int, now[4] as Int, serial) + } +} + +/** The keyboard's editor over [GpuiView.field]: the platform's own, reporting each edit. */ +class KeyboardConnection(private val view: GpuiView) : BaseInputConnection(view, true) { + private var batch = 0 + + override fun getEditable() = view.field + + override fun beginBatchEdit(): Boolean { + batch += 1 + return true + } + + override fun endBatchEdit(): Boolean { + if (batch > 0) batch -= 1 + if (batch == 0) view.edited() + return batch > 0 + } + + private fun edit(result: T): T { + if (batch == 0) view.edited() + return result + } + + override fun commitText(text: CharSequence?, newCursorPosition: Int) = edit(super.commitText(text, newCursorPosition)) + + override fun setComposingText(text: CharSequence?, newCursorPosition: Int) = + edit(super.setComposingText(text, newCursorPosition)) + + override fun setComposingRegion(start: Int, end: Int) = edit(super.setComposingRegion(start, end)) + + override fun finishComposingText() = edit(super.finishComposingText()) + + override fun deleteSurroundingText(beforeLength: Int, afterLength: Int) = + edit(super.deleteSurroundingText(beforeLength, afterLength)) + + override fun deleteSurroundingTextInCodePoints(beforeLength: Int, afterLength: Int) = + edit(super.deleteSurroundingTextInCodePoints(beforeLength, afterLength)) + + override fun setSelection(start: Int, end: Int) = edit(super.setSelection(start, end)) + + override fun performEditorAction(actionCode: Int): Boolean { + Bridge.nativeImeAction(actionCode) + return true + } +} diff --git a/crates/vector-gpui/android/app/src/main/java/io/vectorapp/gpui/Picked.kt b/crates/vector-gpui/android/app/src/main/java/io/vectorapp/gpui/Picked.kt new file mode 100644 index 000000000..e565e3d86 --- /dev/null +++ b/crates/vector-gpui/android/app/src/main/java/io/vectorapp/gpui/Picked.kt @@ -0,0 +1,101 @@ +package io.vectorapp.gpui + +import android.content.Context +import android.net.Uri +import android.os.Build +import android.os.ParcelFileDescriptor +import android.system.Os +import android.provider.OpenableColumns +import android.webkit.MimeTypeMap +import java.io.File +import java.io.FileOutputStream +import java.util.UUID + +/** Documents the picker chose, where GPUI can read them by path: held in memory, or copied into the cache. */ +object Picked { + /** Past this a document is copied to the cache: one that large is a file on disk already. */ + private const val HELD_MAX = 256L * 1024 * 1024 + + private class TooLarge : Exception() + + /** Each in a folder of its own, so two picks of `photo.jpg` never collide. */ + fun copy(context: Context, uris: List): Array { + val root = File(context.cacheDir, "picked") + return uris.mapNotNull { uri -> + try { + val dir = File(root, UUID.randomUUID().toString()).apply { mkdirs() } + val name = name(context, uri) + held(context, uri, dir, name) ?: run { + val file = File(dir, name) + val input = context.contentResolver.openInputStream(uri) ?: return@mapNotNull null + input.use { source -> file.outputStream().use { source.copyTo(it) } } + file.absolutePath + } + } catch (e: Exception) { + android.util.Log.w("Picked", "copy failed", e) + null + } + }.toTypedArray() + } + + /** + * The document in a memfd named after it, reached by a link that holds only the memfd's number: + * a picture another app holds only in memory never touches disk. Null to copy it instead. + */ + private fun held(context: Context, uri: Uri, dir: File, name: String): String? { + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) return null + val size = context.contentResolver.query(uri, arrayOf(OpenableColumns.SIZE), null, null, null) + ?.use { if (it.moveToFirst() && !it.isNull(0)) it.getLong(0) else -1L } ?: -1L + if (size > HELD_MAX) return null + val fd = try { + Os.memfd_create(name, 0) + } catch (_: Exception) { + try { Os.memfd_create("file", 0) } catch (_: Exception) { return null } + } + var kept = -1 + try { + val input = context.contentResolver.openInputStream(uri) ?: return null + // Not closed: closing the stream would close the memfd. + val out = FileOutputStream(fd) + input.use { source -> + val buf = ByteArray(1 shl 16) + var total = 0L + while (true) { + val n = source.read(buf) + if (n < 0) break + total += n + if (total > HELD_MAX) throw TooLarge() + out.write(buf, 0, n) + } + } + kept = ParcelFileDescriptor.dup(fd).detachFd() + val ext = name.substringAfterLast('.', "") + val link = File(dir, if (ext.isEmpty()) "file" else "file.$ext") + Os.symlink("/proc/self/fd/$kept", link.path) + return link.absolutePath + } catch (e: Exception) { + if (e !is TooLarge) android.util.Log.w("Picked", "not held", e) + if (kept >= 0) ParcelFileDescriptor.adoptFd(kept).close() + return null + } finally { + Os.close(fd) + } + } + + /** The document's own name, with no folder in it, and an extension from its type when it has none. */ + private fun name(context: Context, uri: Uri): String { + val shown = context.contentResolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null) + ?.use { if (it.moveToFirst()) it.getString(0) else null } + val base = shown?.substringAfterLast('/')?.trimStart('.')?.takeIf { it.isNotEmpty() } ?: "file" + if (base.contains('.')) return base + val ext = MimeTypeMap.getSingleton().getExtensionFromMimeType(context.contentResolver.getType(uri)) + return if (ext.isNullOrEmpty()) base else "$base.$ext" + } + + /** The picker's types for `extensions`; any file when one has no known type. */ + fun mimeTypes(extensions: Array): List { + val map = MimeTypeMap.getSingleton() + val types = extensions.map { map.getMimeTypeFromExtension(it.lowercase()) } + return if (types.isEmpty() || types.any { it == null }) listOf("*/*") else types.filterNotNull().distinct() + } +} diff --git a/crates/vector-gpui/android/app/src/main/java/io/vectorapp/gpui/Tilt.kt b/crates/vector-gpui/android/app/src/main/java/io/vectorapp/gpui/Tilt.kt new file mode 100644 index 000000000..e2d7c5f8d --- /dev/null +++ b/crates/vector-gpui/android/app/src/main/java/io/vectorapp/gpui/Tilt.kt @@ -0,0 +1,85 @@ +package io.vectorapp.gpui + +import android.content.Context +import android.hardware.Sensor +import android.hardware.SensorEvent +import android.hardware.SensorEventListener +import android.hardware.SensorManager +import android.os.Handler +import android.os.Looper + +/** + * The phone's tilt for the badge card, as the Tauri client reads it: gravity (or the raw + * accelerometer, on every phone) against the first reading, as pitch and roll in degrees. + * Listens only while the card is open. + */ +object Tilt { + private var manager: SensorManager? = null + private var active = false + private var baseline = false + private var gx = 0.0 + private var gy = 0.0 + private var gz = 0.0 + private var baseX = 0.0 + private var baseY = 0.0 + private var lastMs = 0L + private val main = Handler(Looper.getMainLooper()) + + @JvmStatic external fun nativeTilt(rx: Float, ry: Float) + + private val listener = object : SensorEventListener { + override fun onSensorChanged(event: SensorEvent) { + val v = event.values + if (!baseline) { + gx = v[0].toDouble(); gy = v[1].toDouble(); gz = v[2].toDouble() + val m = Math.sqrt(gx * gx + gy * gy + gz * gz) + if (m < 1e-3) return + baseX = gx / m; baseY = gy / m + baseline = true + return + } + // Low-pass: gravity without the hand's motion. + val a = 0.15 + gx += (v[0] - gx) * a; gy += (v[1] - gy) * a; gz += (v[2] - gz) * a + val m = Math.sqrt(gx * gx + gy * gy + gz * gz) + if (m < 1e-3) return + val now = System.currentTimeMillis() + if (now - lastMs < 30) return + lastMs = now + var rx = -(gy / m - baseY) * 28.0 + var ry = (gx / m - baseX) * 28.0 + if (Math.abs(rx) < 0.5) rx = 0.0 + if (Math.abs(ry) < 0.5) ry = 0.0 + nativeTilt(rx.toFloat(), ry.toFloat()) + } + + override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) {} + } + + /** False when the phone has no sensor for it: the pointer keeps the tilt. */ + @JvmStatic + fun start(context: Context): Boolean { + val sm = manager ?: (context.getSystemService(Context.SENSOR_SERVICE) as? SensorManager)?.also { manager = it } + ?: return false + val sensor = sm.getDefaultSensor(Sensor.TYPE_GRAVITY) ?: sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER) + ?: return false + main.post { + if (!active) { + baseline = false + sm.registerListener(listener, sensor, SensorManager.SENSOR_DELAY_GAME, main) + active = true + } + } + return true + } + + @JvmStatic + fun stop() { + main.post { + if (active) { + manager?.unregisterListener(listener) + active = false + } + } + } +} diff --git a/crates/vector-gpui/android/app/src/main/res/drawable/ic_large_icon.png b/crates/vector-gpui/android/app/src/main/res/drawable/ic_large_icon.png new file mode 100644 index 000000000..f120814d3 Binary files /dev/null and b/crates/vector-gpui/android/app/src/main/res/drawable/ic_large_icon.png differ diff --git a/crates/vector-gpui/android/app/src/main/res/drawable/ic_launcher_background.xml b/crates/vector-gpui/android/app/src/main/res/drawable/ic_launcher_background.xml new file mode 100644 index 000000000..07d5da9cb --- /dev/null +++ b/crates/vector-gpui/android/app/src/main/res/drawable/ic_launcher_background.xml @@ -0,0 +1,170 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/crates/vector-gpui/android/app/src/main/res/drawable/ic_launcher_foreground.xml b/crates/vector-gpui/android/app/src/main/res/drawable/ic_launcher_foreground.xml new file mode 100644 index 000000000..2b068d114 --- /dev/null +++ b/crates/vector-gpui/android/app/src/main/res/drawable/ic_launcher_foreground.xml @@ -0,0 +1,30 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/crates/vector-gpui/android/app/src/main/res/drawable/ic_launcher_monochrome.xml b/crates/vector-gpui/android/app/src/main/res/drawable/ic_launcher_monochrome.xml new file mode 100644 index 000000000..4da7d21b0 --- /dev/null +++ b/crates/vector-gpui/android/app/src/main/res/drawable/ic_launcher_monochrome.xml @@ -0,0 +1,34 @@ + + + + + + + + + + + + + + diff --git a/crates/vector-gpui/android/app/src/main/res/drawable/ic_notification.xml b/crates/vector-gpui/android/app/src/main/res/drawable/ic_notification.xml new file mode 100644 index 000000000..6f535839f --- /dev/null +++ b/crates/vector-gpui/android/app/src/main/res/drawable/ic_notification.xml @@ -0,0 +1,24 @@ + + + + + + + + + + diff --git a/crates/vector-gpui/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml b/crates/vector-gpui/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml new file mode 100644 index 000000000..858386cff --- /dev/null +++ b/crates/vector-gpui/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml @@ -0,0 +1,6 @@ + + + + + + diff --git a/crates/vector-gpui/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml b/crates/vector-gpui/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml new file mode 100644 index 000000000..858386cff --- /dev/null +++ b/crates/vector-gpui/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml @@ -0,0 +1,6 @@ + + + + + + diff --git a/crates/vector-gpui/android/app/src/main/res/mipmap-hdpi/ic_launcher.png b/crates/vector-gpui/android/app/src/main/res/mipmap-hdpi/ic_launcher.png new file mode 100644 index 000000000..2fabdeda0 Binary files /dev/null and b/crates/vector-gpui/android/app/src/main/res/mipmap-hdpi/ic_launcher.png differ diff --git a/crates/vector-gpui/android/app/src/main/res/mipmap-hdpi/ic_launcher_foreground.png b/crates/vector-gpui/android/app/src/main/res/mipmap-hdpi/ic_launcher_foreground.png new file mode 100644 index 000000000..7ec1e1a43 Binary files /dev/null and b/crates/vector-gpui/android/app/src/main/res/mipmap-hdpi/ic_launcher_foreground.png differ diff --git a/crates/vector-gpui/android/app/src/main/res/mipmap-hdpi/ic_launcher_round.png b/crates/vector-gpui/android/app/src/main/res/mipmap-hdpi/ic_launcher_round.png new file mode 100644 index 000000000..2fabdeda0 Binary files /dev/null and b/crates/vector-gpui/android/app/src/main/res/mipmap-hdpi/ic_launcher_round.png differ diff --git a/crates/vector-gpui/android/app/src/main/res/mipmap-mdpi/ic_launcher.png b/crates/vector-gpui/android/app/src/main/res/mipmap-mdpi/ic_launcher.png new file mode 100644 index 000000000..bed7042a8 Binary files /dev/null and b/crates/vector-gpui/android/app/src/main/res/mipmap-mdpi/ic_launcher.png differ diff --git a/crates/vector-gpui/android/app/src/main/res/mipmap-mdpi/ic_launcher_foreground.png b/crates/vector-gpui/android/app/src/main/res/mipmap-mdpi/ic_launcher_foreground.png new file mode 100644 index 000000000..d201567e1 Binary files /dev/null and b/crates/vector-gpui/android/app/src/main/res/mipmap-mdpi/ic_launcher_foreground.png differ diff --git a/crates/vector-gpui/android/app/src/main/res/mipmap-mdpi/ic_launcher_round.png b/crates/vector-gpui/android/app/src/main/res/mipmap-mdpi/ic_launcher_round.png new file mode 100644 index 000000000..bed7042a8 Binary files /dev/null and b/crates/vector-gpui/android/app/src/main/res/mipmap-mdpi/ic_launcher_round.png differ diff --git a/crates/vector-gpui/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png b/crates/vector-gpui/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png new file mode 100644 index 000000000..21209c2e1 Binary files /dev/null and b/crates/vector-gpui/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png differ diff --git a/crates/vector-gpui/android/app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.png b/crates/vector-gpui/android/app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.png new file mode 100644 index 000000000..d4b575677 Binary files /dev/null and b/crates/vector-gpui/android/app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.png differ diff --git a/crates/vector-gpui/android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png b/crates/vector-gpui/android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png new file mode 100644 index 000000000..21209c2e1 Binary files /dev/null and b/crates/vector-gpui/android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png differ diff --git a/crates/vector-gpui/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png b/crates/vector-gpui/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png new file mode 100644 index 000000000..833273b3f Binary files /dev/null and b/crates/vector-gpui/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png differ diff --git a/crates/vector-gpui/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.png b/crates/vector-gpui/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.png new file mode 100644 index 000000000..1da80fd19 Binary files /dev/null and b/crates/vector-gpui/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.png differ diff --git a/crates/vector-gpui/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png b/crates/vector-gpui/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png new file mode 100644 index 000000000..833273b3f Binary files /dev/null and b/crates/vector-gpui/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png differ diff --git a/crates/vector-gpui/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png b/crates/vector-gpui/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png new file mode 100644 index 000000000..84823a0a8 Binary files /dev/null and b/crates/vector-gpui/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png differ diff --git a/crates/vector-gpui/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.png b/crates/vector-gpui/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.png new file mode 100644 index 000000000..d460e538d Binary files /dev/null and b/crates/vector-gpui/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.png differ diff --git a/crates/vector-gpui/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png b/crates/vector-gpui/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png new file mode 100644 index 000000000..84823a0a8 Binary files /dev/null and b/crates/vector-gpui/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png differ diff --git a/crates/vector-gpui/android/app/src/main/res/raw/notif_prelude.mp3 b/crates/vector-gpui/android/app/src/main/res/raw/notif_prelude.mp3 new file mode 100644 index 000000000..786402c63 Binary files /dev/null and b/crates/vector-gpui/android/app/src/main/res/raw/notif_prelude.mp3 differ diff --git a/crates/vector-gpui/android/app/src/main/res/values/colors.xml b/crates/vector-gpui/android/app/src/main/res/values/colors.xml new file mode 100644 index 000000000..837bbbf2d --- /dev/null +++ b/crates/vector-gpui/android/app/src/main/res/values/colors.xml @@ -0,0 +1,4 @@ + + + #FF030303 + \ No newline at end of file diff --git a/crates/vector-gpui/android/app/src/main/res/values/ic_launcher_background.xml b/crates/vector-gpui/android/app/src/main/res/values/ic_launcher_background.xml new file mode 100644 index 000000000..5d93e6ff3 --- /dev/null +++ b/crates/vector-gpui/android/app/src/main/res/values/ic_launcher_background.xml @@ -0,0 +1,4 @@ + + + #0A0B0B + diff --git a/crates/vector-gpui/android/app/src/main/res/values/strings.xml b/crates/vector-gpui/android/app/src/main/res/values/strings.xml new file mode 100644 index 000000000..e87e1fdba --- /dev/null +++ b/crates/vector-gpui/android/app/src/main/res/values/strings.xml @@ -0,0 +1,4 @@ + + Vector + Vector + \ No newline at end of file diff --git a/crates/vector-gpui/android/app/src/main/res/values/themes.xml b/crates/vector-gpui/android/app/src/main/res/values/themes.xml new file mode 100644 index 000000000..27c84820f --- /dev/null +++ b/crates/vector-gpui/android/app/src/main/res/values/themes.xml @@ -0,0 +1,10 @@ + + + + diff --git a/crates/vector-gpui/android/app/src/main/res/xml/file_paths.xml b/crates/vector-gpui/android/app/src/main/res/xml/file_paths.xml new file mode 100644 index 000000000..f92eb506f --- /dev/null +++ b/crates/vector-gpui/android/app/src/main/res/xml/file_paths.xml @@ -0,0 +1,8 @@ + + + + + + + diff --git a/crates/vector-gpui/android/app/src/main/res/xml/network_security_config.xml b/crates/vector-gpui/android/app/src/main/res/xml/network_security_config.xml new file mode 100644 index 000000000..c6261246b --- /dev/null +++ b/crates/vector-gpui/android/app/src/main/res/xml/network_security_config.xml @@ -0,0 +1,10 @@ + + + + + 127.0.0.1 + localhost + + diff --git a/crates/vector-gpui/android/build.gradle.kts b/crates/vector-gpui/android/build.gradle.kts new file mode 100644 index 000000000..cd6cd7dbb --- /dev/null +++ b/crates/vector-gpui/android/build.gradle.kts @@ -0,0 +1,5 @@ +// The GPUI client's Android app: one activity drawing the Rust client into a SurfaceView. +// The same plugin versions as the Tauri client's project (src-tauri/gen/android). +plugins { + id("com.android.application") version "9.3.1" apply false +} diff --git a/crates/vector-gpui/android/gradle.properties b/crates/vector-gpui/android/gradle.properties new file mode 100644 index 000000000..8f2e28c06 --- /dev/null +++ b/crates/vector-gpui/android/gradle.properties @@ -0,0 +1,4 @@ +org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8 +android.useAndroidX=true +android.nonTransitiveRClass=true +kotlin.code.style=official diff --git a/crates/vector-gpui/android/gradle/wrapper/gradle-wrapper.jar b/crates/vector-gpui/android/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 000000000..b1b8ef56b Binary files /dev/null and b/crates/vector-gpui/android/gradle/wrapper/gradle-wrapper.jar differ diff --git a/crates/vector-gpui/android/gradle/wrapper/gradle-wrapper.properties b/crates/vector-gpui/android/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 000000000..8d307f563 --- /dev/null +++ b/crates/vector-gpui/android/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionUrl=https\://services.gradle.org/distributions/gradle-9.6.1-bin.zip +distributionPath=wrapper/dists +zipStorePath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME diff --git a/crates/vector-gpui/android/gradlew b/crates/vector-gpui/android/gradlew new file mode 100755 index 000000000..249efbb03 --- /dev/null +++ b/crates/vector-gpui/android/gradlew @@ -0,0 +1,248 @@ +#!/bin/sh + +# +# Copyright © 2015 the original authors. +# +# 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 +# +# https://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. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# gradlew start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh gradlew +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/3d91ce3b8caaf77ad09f381f43615b715b53f72c/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/crates/vector-gpui/android/gradlew.bat b/crates/vector-gpui/android/gradlew.bat new file mode 100644 index 000000000..a51ec4f58 --- /dev/null +++ b/crates/vector-gpui/android/gradlew.bat @@ -0,0 +1,82 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem gradlew startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables, and ensure extensions are enabled +setlocal EnableExtensions + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +"%COMSPEC%" /c exit 1 + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +"%COMSPEC%" /c exit 1 + +:execute +@rem Setup the command line + + + +@rem Execute gradlew +@rem endlocal doesn't take effect until after the line is parsed and variables are expanded +@rem which allows us to clear the local environment before executing the java command +endlocal & "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* & call :exitWithErrorLevel + +:exitWithErrorLevel +@rem Use "%COMSPEC%" /c exit to allow operators to work properly in scripts +"%COMSPEC%" /c exit %ERRORLEVEL% diff --git a/crates/vector-gpui/android/scripts/emulator-smoke.sh b/crates/vector-gpui/android/scripts/emulator-smoke.sh new file mode 100755 index 000000000..bbef2b57f --- /dev/null +++ b/crates/vector-gpui/android/scripts/emulator-smoke.sh @@ -0,0 +1,79 @@ +#!/bin/sh +# Installs a debug APK on the running emulator, opens it, and keeps what it showed and logged, +# in the job's log as well as the artifact. +# Usage: scripts/emulator-smoke.sh +set -eu +apk="$1" +out="$2" +app=io.vectorapp.gpui +mkdir -p "$out" +adb install -r "$apk" +# Granted up front, so the permission prompt doesn't cover the screen being checked. +adb shell pm grant "$app" android.permission.POST_NOTIFICATIONS || true +adb logcat -c +adb shell am start -W -n "$app/io.vectorapp.MainActivity" +sleep 45 +adb exec-out screencap -p > "$out/screen.png" +pid=$(adb shell pidof "$app" || true) +echo "pid: ${pid:-not running}" +adb shell dumpsys meminfo "$app" > "$out/meminfo.txt" || true +grep -E "TOTAL PSS|TOTAL RSS|Native Heap|Graphics" "$out/meminfo.txt" || true +echo "notification channels:" +adb shell dumpsys notification | grep -oE "vector_(service|messages_v2)" | sort -u || true +adb logcat -d > "$out/logcat.txt" +echo "::group::app log" +if [ -n "$pid" ]; then adb logcat -d --pid="$pid"; else tail -400 "$out/logcat.txt"; fi +adb logcat -d -b crash || true +echo "::endgroup::" +echo "::group::test log file" +adb shell 'ls -la /sdcard/Download/Vector/ /sdcard/Android/media/io.vectorapp.gpui/ 2>/dev/null; for f in /sdcard/Download/Vector/vector-gpui-debug-*.log; do echo "== $f"; head -40 "$f"; done 2>/dev/null' || true +echo "::endgroup::" +# A tap where the login screen's first button sits, to see touches arrive. +size=$(adb shell wm size | sed 's/.*: //' | tr -d '\r') +adb shell input tap $((${size%x*} / 2)) $((${size#*x} * 36 / 100)) +sleep 8 +adb exec-out screencap -p > "$out/after-tap.png" +# Back to the start, then Login and some typing, to see the keyboard's text reach the field. +adb shell input keyevent 4 +sleep 3 +adb shell input tap $((${size%x*} / 2)) $((${size#*x} * 47 / 100)) +sleep 5 +adb shell input text "nsec1typed" +sleep 4 +adb exec-out screencap -p > "$out/typed.png" +for shot in screen after-tap typed; do + echo "::group::$shot.png" + echo "SCREEN-BEGIN $shot" + base64 -w0 "$out/$shot.png" + echo + echo "SCREEN-END" + echo "::endgroup::" +done +# Text shared in from another app reaches the running client without a crash. +echo "::group::share sheet" +adb shell am start -W -a android.intent.action.SEND -t text/plain --es android.intent.extra.TEXT "shared-text" -n "$app/io.vectorapp.MainActivity" || true +sleep 3 +echo "pid after share: $(adb shell pidof "$app" || echo none)" +adb logcat -d -b crash || true +echo "::endgroup::" +# A restart with the background on: the service comes up with no window and the process stays. +echo "::group::service after a restart" +adb shell am force-stop "$app" +adb shell run-as "$app" sh -c "'mkdir -p shared_prefs && echo \"\" > shared_prefs/vector_prefs.xml'" || true +adb logcat -c +if adb root >/dev/null 2>&1; then + adb wait-for-device + adb shell run-as "$app" cat shared_prefs/vector_prefs.xml || true + # 0x20 includes stopped packages: the force-stop leaves the app stopped, which a real boot does not. + adb shell am broadcast -f 0x20 -a android.intent.action.BOOT_COMPLETED -p "$app" || true + sleep 15 + echo "pid after boot: $(adb shell pidof "$app" || echo none)" + adb shell dumpsys activity services "$app" | grep -E "ServiceRecord|isForeground" || echo "no service" + adb logcat -d -b crash || true + adb logcat -d | grep -E "standby|UnsatisfiedLink|FATAL" || true + adb unroot >/dev/null 2>&1 || true +else + echo "no root on this image: skipped" +fi +echo "::endgroup::" +[ -n "$pid" ] diff --git a/crates/vector-gpui/android/settings.gradle.kts b/crates/vector-gpui/android/settings.gradle.kts new file mode 100644 index 000000000..c6e543e92 --- /dev/null +++ b/crates/vector-gpui/android/settings.gradle.kts @@ -0,0 +1,17 @@ +pluginManagement { + repositories { + google() + mavenCentral() + gradlePluginPortal() + } +} + +dependencyResolutionManagement { + repositories { + google() + mavenCentral() + } +} + +rootProject.name = "vector-gpui" +include(":app") diff --git a/crates/vector-gpui/assets/fonts/Inter-Bold.otf b/crates/vector-gpui/assets/fonts/Inter-Bold.otf new file mode 100644 index 000000000..58a38073e Binary files /dev/null and b/crates/vector-gpui/assets/fonts/Inter-Bold.otf differ diff --git a/crates/vector-gpui/assets/fonts/Inter-Medium.otf b/crates/vector-gpui/assets/fonts/Inter-Medium.otf new file mode 100644 index 000000000..f44f89ada Binary files /dev/null and b/crates/vector-gpui/assets/fonts/Inter-Medium.otf differ diff --git a/crates/vector-gpui/assets/fonts/Inter-Regular.otf b/crates/vector-gpui/assets/fonts/Inter-Regular.otf new file mode 100644 index 000000000..2d0bd1d64 Binary files /dev/null and b/crates/vector-gpui/assets/fonts/Inter-Regular.otf differ diff --git a/crates/vector-gpui/assets/fonts/Inter-SemiBold.otf b/crates/vector-gpui/assets/fonts/Inter-SemiBold.otf new file mode 100644 index 000000000..52c84550b Binary files /dev/null and b/crates/vector-gpui/assets/fonts/Inter-SemiBold.otf differ diff --git a/crates/vector-gpui/assets/fonts/README.md b/crates/vector-gpui/assets/fonts/README.md new file mode 100644 index 000000000..a1d1bc936 --- /dev/null +++ b/crates/vector-gpui/assets/fonts/README.md @@ -0,0 +1,10 @@ +# Fonts + +All three families are under the SIL Open Font License 1.1 (https://openfontlicense.org). + +- **Rubik** (Copyright 2015 The Rubik Project Authors): static instances cut from the variable + `src/fonts/Rubik.woff2` and `Rubik-Italic.woff2` with fontTools, at the weights the stylesheets use. +- **Inter** (Copyright 2016 The Inter Project Authors): the stylesheets name it for chrome text. +- **Vector Slot**: cut from Rubik-Regular with fontTools, holding only a blank em space (U+2003) and + four-per-em space (U+2005) on Rubik's metrics, plus `m`, which the macOS text system requires. The + composer shapes an emoji's slot in it, since Rubik lacks both spaces. diff --git a/crates/vector-gpui/assets/fonts/Rubik-Bold.ttf b/crates/vector-gpui/assets/fonts/Rubik-Bold.ttf new file mode 100644 index 000000000..df3709727 Binary files /dev/null and b/crates/vector-gpui/assets/fonts/Rubik-Bold.ttf differ diff --git a/crates/vector-gpui/assets/fonts/Rubik-BoldItalic.ttf b/crates/vector-gpui/assets/fonts/Rubik-BoldItalic.ttf new file mode 100644 index 000000000..1c592c440 Binary files /dev/null and b/crates/vector-gpui/assets/fonts/Rubik-BoldItalic.ttf differ diff --git a/crates/vector-gpui/assets/fonts/Rubik-ExtraBold.ttf b/crates/vector-gpui/assets/fonts/Rubik-ExtraBold.ttf new file mode 100644 index 000000000..fa55e67de Binary files /dev/null and b/crates/vector-gpui/assets/fonts/Rubik-ExtraBold.ttf differ diff --git a/crates/vector-gpui/assets/fonts/Rubik-Italic.ttf b/crates/vector-gpui/assets/fonts/Rubik-Italic.ttf new file mode 100644 index 000000000..94a85e247 Binary files /dev/null and b/crates/vector-gpui/assets/fonts/Rubik-Italic.ttf differ diff --git a/crates/vector-gpui/assets/fonts/Rubik-Light.ttf b/crates/vector-gpui/assets/fonts/Rubik-Light.ttf new file mode 100644 index 000000000..870d5abf5 Binary files /dev/null and b/crates/vector-gpui/assets/fonts/Rubik-Light.ttf differ diff --git a/crates/vector-gpui/assets/fonts/Rubik-Medium.ttf b/crates/vector-gpui/assets/fonts/Rubik-Medium.ttf new file mode 100644 index 000000000..353ee0224 Binary files /dev/null and b/crates/vector-gpui/assets/fonts/Rubik-Medium.ttf differ diff --git a/crates/vector-gpui/assets/fonts/Rubik-MediumItalic.ttf b/crates/vector-gpui/assets/fonts/Rubik-MediumItalic.ttf new file mode 100644 index 000000000..ccbd461e3 Binary files /dev/null and b/crates/vector-gpui/assets/fonts/Rubik-MediumItalic.ttf differ diff --git a/crates/vector-gpui/assets/fonts/Rubik-Regular.ttf b/crates/vector-gpui/assets/fonts/Rubik-Regular.ttf new file mode 100644 index 000000000..ff4501abb Binary files /dev/null and b/crates/vector-gpui/assets/fonts/Rubik-Regular.ttf differ diff --git a/crates/vector-gpui/assets/fonts/Rubik-SemiBold.ttf b/crates/vector-gpui/assets/fonts/Rubik-SemiBold.ttf new file mode 100644 index 000000000..927b4f551 Binary files /dev/null and b/crates/vector-gpui/assets/fonts/Rubik-SemiBold.ttf differ diff --git a/crates/vector-gpui/assets/fonts/Rubik-SemiBoldItalic.ttf b/crates/vector-gpui/assets/fonts/Rubik-SemiBoldItalic.ttf new file mode 100644 index 000000000..9c78b621c Binary files /dev/null and b/crates/vector-gpui/assets/fonts/Rubik-SemiBoldItalic.ttf differ diff --git a/crates/vector-gpui/assets/fonts/VectorSlot.ttf b/crates/vector-gpui/assets/fonts/VectorSlot.ttf new file mode 100644 index 000000000..5c9aa788f Binary files /dev/null and b/crates/vector-gpui/assets/fonts/VectorSlot.ttf differ diff --git a/crates/vector-gpui/assets/icons/award.svg b/crates/vector-gpui/assets/icons/award.svg new file mode 100644 index 000000000..91ab395bf --- /dev/null +++ b/crates/vector-gpui/assets/icons/award.svg @@ -0,0 +1 @@ + diff --git a/crates/vector-gpui/assets/icons/call-bluetooth.svg b/crates/vector-gpui/assets/icons/call-bluetooth.svg new file mode 100644 index 000000000..3a8001985 --- /dev/null +++ b/crates/vector-gpui/assets/icons/call-bluetooth.svg @@ -0,0 +1 @@ + diff --git a/crates/vector-gpui/assets/icons/call-headset.svg b/crates/vector-gpui/assets/icons/call-headset.svg new file mode 100644 index 000000000..09b020ec6 --- /dev/null +++ b/crates/vector-gpui/assets/icons/call-headset.svg @@ -0,0 +1 @@ + diff --git a/crates/vector-gpui/assets/icons/call-max.svg b/crates/vector-gpui/assets/icons/call-max.svg new file mode 100644 index 000000000..be1bb59ac --- /dev/null +++ b/crates/vector-gpui/assets/icons/call-max.svg @@ -0,0 +1 @@ + diff --git a/crates/vector-gpui/assets/icons/call-restore.svg b/crates/vector-gpui/assets/icons/call-restore.svg new file mode 100644 index 000000000..5acbebc74 --- /dev/null +++ b/crates/vector-gpui/assets/icons/call-restore.svg @@ -0,0 +1 @@ + diff --git a/crates/vector-gpui/assets/icons/call-screen.svg b/crates/vector-gpui/assets/icons/call-screen.svg new file mode 100644 index 000000000..638b98293 --- /dev/null +++ b/crates/vector-gpui/assets/icons/call-screen.svg @@ -0,0 +1 @@ + diff --git a/crates/vector-gpui/assets/icons/call.svg b/crates/vector-gpui/assets/icons/call.svg new file mode 100644 index 000000000..b2b30a2e0 --- /dev/null +++ b/crates/vector-gpui/assets/icons/call.svg @@ -0,0 +1,3 @@ + + + \ No newline at end of file diff --git a/crates/vector-gpui/assets/icons/cancel.svg b/crates/vector-gpui/assets/icons/cancel.svg new file mode 100644 index 000000000..af933a150 --- /dev/null +++ b/crates/vector-gpui/assets/icons/cancel.svg @@ -0,0 +1,3 @@ + + + \ No newline at end of file diff --git a/crates/vector-gpui/assets/icons/caret-down.svg b/crates/vector-gpui/assets/icons/caret-down.svg new file mode 100644 index 000000000..d18c62300 --- /dev/null +++ b/crates/vector-gpui/assets/icons/caret-down.svg @@ -0,0 +1 @@ + diff --git a/crates/vector-gpui/assets/icons/cc-caret.svg b/crates/vector-gpui/assets/icons/cc-caret.svg new file mode 100644 index 000000000..21d19ab33 --- /dev/null +++ b/crates/vector-gpui/assets/icons/cc-caret.svg @@ -0,0 +1 @@ + diff --git a/crates/vector-gpui/assets/icons/cc-clear.svg b/crates/vector-gpui/assets/icons/cc-clear.svg new file mode 100644 index 000000000..60b2ef852 --- /dev/null +++ b/crates/vector-gpui/assets/icons/cc-clear.svg @@ -0,0 +1 @@ + diff --git a/crates/vector-gpui/assets/icons/cc-plus.svg b/crates/vector-gpui/assets/icons/cc-plus.svg new file mode 100644 index 000000000..618076317 --- /dev/null +++ b/crates/vector-gpui/assets/icons/cc-plus.svg @@ -0,0 +1 @@ + diff --git a/crates/vector-gpui/assets/icons/cc-scan.svg b/crates/vector-gpui/assets/icons/cc-scan.svg new file mode 100644 index 000000000..fc63ae4b6 --- /dev/null +++ b/crates/vector-gpui/assets/icons/cc-scan.svg @@ -0,0 +1 @@ + diff --git a/crates/vector-gpui/assets/icons/cc-search.svg b/crates/vector-gpui/assets/icons/cc-search.svg new file mode 100644 index 000000000..19b2d7ff0 --- /dev/null +++ b/crates/vector-gpui/assets/icons/cc-search.svg @@ -0,0 +1 @@ + diff --git a/crates/vector-gpui/assets/icons/check-circle.svg b/crates/vector-gpui/assets/icons/check-circle.svg new file mode 100644 index 000000000..3f3eaa2d4 --- /dev/null +++ b/crates/vector-gpui/assets/icons/check-circle.svg @@ -0,0 +1,3 @@ + + + \ No newline at end of file diff --git a/crates/vector-gpui/assets/icons/check.svg b/crates/vector-gpui/assets/icons/check.svg new file mode 100644 index 000000000..181c08f26 --- /dev/null +++ b/crates/vector-gpui/assets/icons/check.svg @@ -0,0 +1,3 @@ + + + \ No newline at end of file diff --git a/crates/vector-gpui/assets/icons/chevron-down.svg b/crates/vector-gpui/assets/icons/chevron-down.svg new file mode 100644 index 000000000..7aaa240fd --- /dev/null +++ b/crates/vector-gpui/assets/icons/chevron-down.svg @@ -0,0 +1 @@ + diff --git a/crates/vector-gpui/assets/icons/chrome-close.svg b/crates/vector-gpui/assets/icons/chrome-close.svg new file mode 100644 index 000000000..d6234c7a7 --- /dev/null +++ b/crates/vector-gpui/assets/icons/chrome-close.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/crates/vector-gpui/assets/icons/chrome-help.svg b/crates/vector-gpui/assets/icons/chrome-help.svg new file mode 100644 index 000000000..798ad15a7 --- /dev/null +++ b/crates/vector-gpui/assets/icons/chrome-help.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/crates/vector-gpui/assets/icons/chrome-max.svg b/crates/vector-gpui/assets/icons/chrome-max.svg new file mode 100644 index 000000000..4934788d0 --- /dev/null +++ b/crates/vector-gpui/assets/icons/chrome-max.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/crates/vector-gpui/assets/icons/chrome-min.svg b/crates/vector-gpui/assets/icons/chrome-min.svg new file mode 100644 index 000000000..755b48e22 --- /dev/null +++ b/crates/vector-gpui/assets/icons/chrome-min.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/crates/vector-gpui/assets/icons/chrome-restore.svg b/crates/vector-gpui/assets/icons/chrome-restore.svg new file mode 100644 index 000000000..88e40c14a --- /dev/null +++ b/crates/vector-gpui/assets/icons/chrome-restore.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/crates/vector-gpui/assets/icons/circuit-new.svg b/crates/vector-gpui/assets/icons/circuit-new.svg new file mode 100644 index 000000000..39c7b0c28 --- /dev/null +++ b/crates/vector-gpui/assets/icons/circuit-new.svg @@ -0,0 +1 @@ + diff --git a/crates/vector-gpui/assets/icons/clock-snooze.svg b/crates/vector-gpui/assets/icons/clock-snooze.svg new file mode 100644 index 000000000..bf4ef944e --- /dev/null +++ b/crates/vector-gpui/assets/icons/clock-snooze.svg @@ -0,0 +1,3 @@ + + + diff --git a/crates/vector-gpui/assets/icons/clock.svg b/crates/vector-gpui/assets/icons/clock.svg new file mode 100644 index 000000000..5aa2cd610 --- /dev/null +++ b/crates/vector-gpui/assets/icons/clock.svg @@ -0,0 +1,3 @@ + + + \ No newline at end of file diff --git a/crates/vector-gpui/assets/icons/copy.svg b/crates/vector-gpui/assets/icons/copy.svg new file mode 100644 index 000000000..10095814e --- /dev/null +++ b/crates/vector-gpui/assets/icons/copy.svg @@ -0,0 +1,3 @@ + + + \ No newline at end of file diff --git a/crates/vector-gpui/assets/icons/details-toggle-open.svg b/crates/vector-gpui/assets/icons/details-toggle-open.svg new file mode 100644 index 000000000..663b09107 --- /dev/null +++ b/crates/vector-gpui/assets/icons/details-toggle-open.svg @@ -0,0 +1 @@ + diff --git a/crates/vector-gpui/assets/icons/details-toggle.svg b/crates/vector-gpui/assets/icons/details-toggle.svg new file mode 100644 index 000000000..eb1e2cf92 --- /dev/null +++ b/crates/vector-gpui/assets/icons/details-toggle.svg @@ -0,0 +1 @@ + diff --git a/crates/vector-gpui/assets/icons/disable.svg b/crates/vector-gpui/assets/icons/disable.svg new file mode 100644 index 000000000..1ecc17365 --- /dev/null +++ b/crates/vector-gpui/assets/icons/disable.svg @@ -0,0 +1,3 @@ + + + diff --git a/crates/vector-gpui/assets/icons/external-link.svg b/crates/vector-gpui/assets/icons/external-link.svg new file mode 100644 index 000000000..799363c7f --- /dev/null +++ b/crates/vector-gpui/assets/icons/external-link.svg @@ -0,0 +1 @@ + diff --git a/crates/vector-gpui/assets/icons/fingerprint.svg b/crates/vector-gpui/assets/icons/fingerprint.svg new file mode 100644 index 000000000..d996e8f08 --- /dev/null +++ b/crates/vector-gpui/assets/icons/fingerprint.svg @@ -0,0 +1 @@ + diff --git a/crates/vector-gpui/assets/icons/globe.svg b/crates/vector-gpui/assets/icons/globe.svg new file mode 100644 index 000000000..b69f30dec --- /dev/null +++ b/crates/vector-gpui/assets/icons/globe.svg @@ -0,0 +1,3 @@ + + + diff --git a/crates/vector-gpui/assets/icons/group-placeholder-dim.svg b/crates/vector-gpui/assets/icons/group-placeholder-dim.svg new file mode 100644 index 000000000..63953526c --- /dev/null +++ b/crates/vector-gpui/assets/icons/group-placeholder-dim.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/crates/vector-gpui/assets/icons/logo-mark.svg b/crates/vector-gpui/assets/icons/logo-mark.svg new file mode 100644 index 000000000..a76b6375a --- /dev/null +++ b/crates/vector-gpui/assets/icons/logo-mark.svg @@ -0,0 +1,18 @@ + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/crates/vector-gpui/assets/icons/logo-typeface.svg b/crates/vector-gpui/assets/icons/logo-typeface.svg new file mode 100644 index 000000000..e297bc364 --- /dev/null +++ b/crates/vector-gpui/assets/icons/logo-typeface.svg @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/crates/vector-gpui/assets/icons/m3d-full.svg b/crates/vector-gpui/assets/icons/m3d-full.svg new file mode 100644 index 000000000..327af31ee --- /dev/null +++ b/crates/vector-gpui/assets/icons/m3d-full.svg @@ -0,0 +1 @@ + diff --git a/crates/vector-gpui/assets/icons/m3d-pause.svg b/crates/vector-gpui/assets/icons/m3d-pause.svg new file mode 100644 index 000000000..d4536e8c9 --- /dev/null +++ b/crates/vector-gpui/assets/icons/m3d-pause.svg @@ -0,0 +1 @@ + diff --git a/crates/vector-gpui/assets/icons/m3d-play.svg b/crates/vector-gpui/assets/icons/m3d-play.svg new file mode 100644 index 000000000..f171db443 --- /dev/null +++ b/crates/vector-gpui/assets/icons/m3d-play.svg @@ -0,0 +1 @@ + diff --git a/crates/vector-gpui/assets/icons/m3d-reset.svg b/crates/vector-gpui/assets/icons/m3d-reset.svg new file mode 100644 index 000000000..83298638a --- /dev/null +++ b/crates/vector-gpui/assets/icons/m3d-reset.svg @@ -0,0 +1 @@ + diff --git a/crates/vector-gpui/assets/icons/menu-dots.svg b/crates/vector-gpui/assets/icons/menu-dots.svg new file mode 100644 index 000000000..da97b21aa --- /dev/null +++ b/crates/vector-gpui/assets/icons/menu-dots.svg @@ -0,0 +1,3 @@ + + + \ No newline at end of file diff --git a/crates/vector-gpui/assets/icons/mv-reset.svg b/crates/vector-gpui/assets/icons/mv-reset.svg new file mode 100644 index 000000000..098c9aadd --- /dev/null +++ b/crates/vector-gpui/assets/icons/mv-reset.svg @@ -0,0 +1 @@ + diff --git a/crates/vector-gpui/assets/icons/mv-reveal.svg b/crates/vector-gpui/assets/icons/mv-reveal.svg new file mode 100644 index 000000000..f23534c4a --- /dev/null +++ b/crates/vector-gpui/assets/icons/mv-reveal.svg @@ -0,0 +1 @@ + diff --git a/crates/vector-gpui/assets/icons/mv-save.svg b/crates/vector-gpui/assets/icons/mv-save.svg new file mode 100644 index 000000000..72cab4ee3 --- /dev/null +++ b/crates/vector-gpui/assets/icons/mv-save.svg @@ -0,0 +1 @@ + diff --git a/crates/vector-gpui/assets/icons/notice-go.svg b/crates/vector-gpui/assets/icons/notice-go.svg new file mode 100644 index 000000000..6926ed44b --- /dev/null +++ b/crates/vector-gpui/assets/icons/notice-go.svg @@ -0,0 +1 @@ + diff --git a/crates/vector-gpui/assets/icons/op-add.svg b/crates/vector-gpui/assets/icons/op-add.svg new file mode 100644 index 000000000..2e25012c9 --- /dev/null +++ b/crates/vector-gpui/assets/icons/op-add.svg @@ -0,0 +1 @@ + diff --git a/crates/vector-gpui/assets/icons/op-down.svg b/crates/vector-gpui/assets/icons/op-down.svg new file mode 100644 index 000000000..29c23d48d --- /dev/null +++ b/crates/vector-gpui/assets/icons/op-down.svg @@ -0,0 +1 @@ + diff --git a/crates/vector-gpui/assets/icons/op-remove.svg b/crates/vector-gpui/assets/icons/op-remove.svg new file mode 100644 index 000000000..35e49867d --- /dev/null +++ b/crates/vector-gpui/assets/icons/op-remove.svg @@ -0,0 +1 @@ + diff --git a/crates/vector-gpui/assets/icons/op-up.svg b/crates/vector-gpui/assets/icons/op-up.svg new file mode 100644 index 000000000..b5e22705d --- /dev/null +++ b/crates/vector-gpui/assets/icons/op-up.svg @@ -0,0 +1 @@ + diff --git a/crates/vector-gpui/assets/icons/pin-row.svg b/crates/vector-gpui/assets/icons/pin-row.svg new file mode 100644 index 000000000..042165c2c --- /dev/null +++ b/crates/vector-gpui/assets/icons/pin-row.svg @@ -0,0 +1,3 @@ + + + \ No newline at end of file diff --git a/crates/vector-gpui/assets/icons/pin.svg b/crates/vector-gpui/assets/icons/pin.svg new file mode 100644 index 000000000..f5d0fa800 --- /dev/null +++ b/crates/vector-gpui/assets/icons/pin.svg @@ -0,0 +1,3 @@ + + + \ No newline at end of file diff --git a/crates/vector-gpui/assets/icons/pins-close.svg b/crates/vector-gpui/assets/icons/pins-close.svg new file mode 100644 index 000000000..c87345d19 --- /dev/null +++ b/crates/vector-gpui/assets/icons/pins-close.svg @@ -0,0 +1 @@ + diff --git a/crates/vector-gpui/assets/icons/plus-thin.svg b/crates/vector-gpui/assets/icons/plus-thin.svg new file mode 100644 index 000000000..6cbca0440 --- /dev/null +++ b/crates/vector-gpui/assets/icons/plus-thin.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/crates/vector-gpui/assets/icons/qr-scan.svg b/crates/vector-gpui/assets/icons/qr-scan.svg new file mode 100644 index 000000000..3607bb17c --- /dev/null +++ b/crates/vector-gpui/assets/icons/qr-scan.svg @@ -0,0 +1,3 @@ + + + diff --git a/crates/vector-gpui/assets/icons/qr.svg b/crates/vector-gpui/assets/icons/qr.svg new file mode 100644 index 000000000..38d084724 --- /dev/null +++ b/crates/vector-gpui/assets/icons/qr.svg @@ -0,0 +1 @@ + diff --git a/crates/vector-gpui/assets/icons/rail-mail.svg b/crates/vector-gpui/assets/icons/rail-mail.svg new file mode 100644 index 000000000..7982d0280 --- /dev/null +++ b/crates/vector-gpui/assets/icons/rail-mail.svg @@ -0,0 +1,3 @@ + + + \ No newline at end of file diff --git a/crates/vector-gpui/assets/icons/request-shield.svg b/crates/vector-gpui/assets/icons/request-shield.svg new file mode 100644 index 000000000..1d8fce19b --- /dev/null +++ b/crates/vector-gpui/assets/icons/request-shield.svg @@ -0,0 +1 @@ + diff --git a/crates/vector-gpui/assets/icons/search-clear.svg b/crates/vector-gpui/assets/icons/search-clear.svg new file mode 100644 index 000000000..5f2ea8077 --- /dev/null +++ b/crates/vector-gpui/assets/icons/search-clear.svg @@ -0,0 +1 @@ + diff --git a/crates/vector-gpui/assets/icons/self-destruct-chip.svg b/crates/vector-gpui/assets/icons/self-destruct-chip.svg new file mode 100644 index 000000000..529d8b0fa --- /dev/null +++ b/crates/vector-gpui/assets/icons/self-destruct-chip.svg @@ -0,0 +1 @@ + diff --git a/crates/vector-gpui/assets/icons/self-destruct.svg b/crates/vector-gpui/assets/icons/self-destruct.svg new file mode 100644 index 000000000..8aa452d6c --- /dev/null +++ b/crates/vector-gpui/assets/icons/self-destruct.svg @@ -0,0 +1 @@ + diff --git a/crates/vector-gpui/assets/icons/shield-alert.svg b/crates/vector-gpui/assets/icons/shield-alert.svg new file mode 100644 index 000000000..755f74b62 --- /dev/null +++ b/crates/vector-gpui/assets/icons/shield-alert.svg @@ -0,0 +1 @@ + diff --git a/crates/vector-gpui/assets/icons/shield-filled.svg b/crates/vector-gpui/assets/icons/shield-filled.svg new file mode 100644 index 000000000..16c5290f9 --- /dev/null +++ b/crates/vector-gpui/assets/icons/shield-filled.svg @@ -0,0 +1,3 @@ + + + diff --git a/crates/vector-gpui/assets/icons/slash.svg b/crates/vector-gpui/assets/icons/slash.svg new file mode 100644 index 000000000..9d9744691 --- /dev/null +++ b/crates/vector-gpui/assets/icons/slash.svg @@ -0,0 +1 @@ + diff --git a/crates/vector-gpui/assets/icons/speaker_volume.svg b/crates/vector-gpui/assets/icons/speaker_volume.svg new file mode 100644 index 000000000..c8de478de --- /dev/null +++ b/crates/vector-gpui/assets/icons/speaker_volume.svg @@ -0,0 +1,3 @@ + + + diff --git a/crates/vector-gpui/assets/icons/switcher-add.svg b/crates/vector-gpui/assets/icons/switcher-add.svg new file mode 100644 index 000000000..52da51bdc --- /dev/null +++ b/crates/vector-gpui/assets/icons/switcher-add.svg @@ -0,0 +1 @@ + diff --git a/crates/vector-gpui/assets/icons/switcher-chevron.svg b/crates/vector-gpui/assets/icons/switcher-chevron.svg new file mode 100644 index 000000000..4beb24752 --- /dev/null +++ b/crates/vector-gpui/assets/icons/switcher-chevron.svg @@ -0,0 +1 @@ + diff --git a/crates/vector-gpui/assets/icons/switcher-trash.svg b/crates/vector-gpui/assets/icons/switcher-trash.svg new file mode 100644 index 000000000..8cfc05840 --- /dev/null +++ b/crates/vector-gpui/assets/icons/switcher-trash.svg @@ -0,0 +1 @@ + diff --git a/crates/vector-gpui/assets/icons/upd-latest.svg b/crates/vector-gpui/assets/icons/upd-latest.svg new file mode 100644 index 000000000..109ed6645 --- /dev/null +++ b/crates/vector-gpui/assets/icons/upd-latest.svg @@ -0,0 +1,4 @@ + + + + diff --git a/crates/vector-gpui/assets/icons/upd-outdated.svg b/crates/vector-gpui/assets/icons/upd-outdated.svg new file mode 100644 index 000000000..4048adbc0 --- /dev/null +++ b/crates/vector-gpui/assets/icons/upd-outdated.svg @@ -0,0 +1,4 @@ + + + + diff --git a/crates/vector-gpui/assets/icons/upd-preview.svg b/crates/vector-gpui/assets/icons/upd-preview.svg new file mode 100644 index 000000000..bac141d64 --- /dev/null +++ b/crates/vector-gpui/assets/icons/upd-preview.svg @@ -0,0 +1,3 @@ + + + diff --git a/crates/vector-gpui/assets/icons/video-exit-full.svg b/crates/vector-gpui/assets/icons/video-exit-full.svg new file mode 100644 index 000000000..d85db4e9c --- /dev/null +++ b/crates/vector-gpui/assets/icons/video-exit-full.svg @@ -0,0 +1 @@ + diff --git a/crates/vector-gpui/assets/icons/video-full.svg b/crates/vector-gpui/assets/icons/video-full.svg new file mode 100644 index 000000000..327af31ee --- /dev/null +++ b/crates/vector-gpui/assets/icons/video-full.svg @@ -0,0 +1 @@ + diff --git a/crates/vector-gpui/assets/icons/viewer-close.svg b/crates/vector-gpui/assets/icons/viewer-close.svg new file mode 100644 index 000000000..daf09d12c --- /dev/null +++ b/crates/vector-gpui/assets/icons/viewer-close.svg @@ -0,0 +1 @@ + diff --git a/crates/vector-gpui/assets/icons/viewer-rotate.svg b/crates/vector-gpui/assets/icons/viewer-rotate.svg new file mode 100644 index 000000000..a1066838b --- /dev/null +++ b/crates/vector-gpui/assets/icons/viewer-rotate.svg @@ -0,0 +1 @@ + diff --git a/crates/vector-gpui/assets/icons/voice-bigger.svg b/crates/vector-gpui/assets/icons/voice-bigger.svg new file mode 100644 index 000000000..c151a7b0a --- /dev/null +++ b/crates/vector-gpui/assets/icons/voice-bigger.svg @@ -0,0 +1 @@ + diff --git a/crates/vector-gpui/assets/icons/voice-smaller.svg b/crates/vector-gpui/assets/icons/voice-smaller.svg new file mode 100644 index 000000000..4ec372089 --- /dev/null +++ b/crates/vector-gpui/assets/icons/voice-smaller.svg @@ -0,0 +1 @@ + diff --git a/crates/vector-gpui/assets/icons/x-mark.svg b/crates/vector-gpui/assets/icons/x-mark.svg new file mode 100644 index 000000000..970886f09 --- /dev/null +++ b/crates/vector-gpui/assets/icons/x-mark.svg @@ -0,0 +1 @@ + diff --git a/crates/vector-gpui/build.rs b/crates/vector-gpui/build.rs new file mode 100644 index 000000000..f8443c55f --- /dev/null +++ b/crates/vector-gpui/build.rs @@ -0,0 +1,171 @@ +//! The emoji and kaomoji tables, generated from the Tauri client's own datasets +//! (`src/js/emoji.js`, `src/components/lib/kaomoji.js`), so both clients list, name and rank the same. + +use std::fmt::Write; + +fn field<'a>(line: &'a str, key: &str) -> Option<&'a str> { + let start = line.find(&format!("{key}: '"))? + key.len() + 3; + let len = line[start..].find('\'')?; + Some(&line[start..start + len]) +} + +fn main() { + // ScreenCaptureKit arrives in macOS 12.3: weakly linked, 12.0-12.2 open without native screen audio. + if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("macos") { + println!("cargo:rustc-link-arg=-Wl,-weak_framework,ScreenCaptureKit"); + } + // libjxl, statically linked, for sending JPEG XL. A docs-only check links nothing. + println!("cargo:rerun-if-env-changed=DOCS_RS"); + if std::env::var_os("DOCS_RS").is_none() { + // jpegxl-src asks MSVC for the static CRT; everything else here links the DLL one. A + // toolchain file's plain variable shadows its cache entry. + if std::env::var("CARGO_CFG_TARGET_ENV").as_deref() == Ok("msvc") { + let file = std::path::Path::new(&std::env::var("OUT_DIR").unwrap()).join("jxl-crt.cmake"); + std::fs::write(&file, "set(CMAKE_MSVC_RUNTIME_LIBRARY \"MultiThreadedDLL\")\n").unwrap(); + // SAFETY: the build script is single-threaded here. + unsafe { std::env::set_var("CMAKE_TOOLCHAIN_FILE", file.to_string_lossy().replace('\\', "/")) }; + } + jpegxl_src::build(); + } + let src = concat!(env!("CARGO_MANIFEST_DIR"), "/../../src/js/emoji.js"); + println!("cargo:rerun-if-changed={src}"); + let js = std::fs::read_to_string(src).expect("emoji dataset"); + let mut out = String::from("pub static EMOJIS: &[Emoji] = &[\n"); + for line in js.lines() { + let t = line.trim(); + if t.starts_with("// Apply") { + break; + } + let Some(emoji) = field(t, "emoji") else { + continue; + }; + let name = field(t, "name").unwrap_or("").to_lowercase(); + let display = field(t, "display").unwrap_or(""); + let shortcode = match field(t, "shortcode") { + Some(s) => s.to_string(), + None => { + let s: String = display + .to_lowercase() + .chars() + .map(|c| if c.is_ascii_alphanumeric() { c } else { '_' }) + .collect(); + let mut collapsed = String::new(); + for c in s.chars() { + if c == '_' && collapsed.ends_with('_') { + continue; + } + collapsed.push(c); + } + collapsed.trim_matches('_').to_string() + } + }; + let freq: u8 = t + .find("freq: ") + .and_then(|i| { + t[i + 6..] + .split(|c: char| !c.is_ascii_digit()) + .next()? + .parse() + .ok() + }) + .unwrap_or(99); + writeln!(out, " Emoji {{ emoji: {emoji:?}, name: {name:?}, display: {display:?}, shortcode: {shortcode:?}, freq: {freq} }},").unwrap(); + } + out.push_str("];\n"); + let dest = std::path::Path::new(&std::env::var("OUT_DIR").unwrap()).join("emoji_data.rs"); + std::fs::write(dest, out).unwrap(); + kaomoji(); + if std::env::var_os("CARGO_FEATURE_VIDEO_STATIC").is_some() { + link_ffmpeg_system_libs(); + } +} + +/// ffmpeg-sys-next links FFmpeg's own static libraries but not what they need from the +/// system (libm, frameworks); the build's pkg-config files list those. +fn link_ffmpeg_system_libs() { + println!("cargo:rerun-if-env-changed=FFMPEG_DIR"); + let dir = std::env::var("FFMPEG_DIR") + .expect("video-static needs FFMPEG_DIR=src-tauri/native-deps/ffmpeg/ (scripts/build-ffmpeg.sh)"); + let target_os = std::env::var("CARGO_CFG_TARGET_OS").unwrap_or_default(); + let mut seen = std::collections::HashSet::new(); + let pc_dir = std::path::Path::new(&dir).join("lib/pkgconfig"); + for entry in std::fs::read_dir(&pc_dir).expect("FFMPEG_DIR has no lib/pkgconfig").flatten() { + let text = std::fs::read_to_string(entry.path()).unwrap_or_default(); + for line in text.lines().filter(|l| l.starts_with("Libs:") || l.starts_with("Libs.private:")) { + let mut tokens = line.split_whitespace().skip(1); + while let Some(t) = tokens.next() { + let lib = if t == "-framework" { + tokens.next().map(|f| format!("framework={f}")) + } else if let Some(l) = t.strip_prefix("-l").or_else(|| t.strip_suffix(".lib")) { + // MSVC keeps libm and atomics in its CRT. + let crt = target_os == "windows" && matches!(l, "m" | "atomic"); + (!l.starts_with("av") && !l.starts_with("sw") && !crt).then(|| l.to_string()) + } else if t == "-pthread" && target_os == "linux" { + Some("pthread".into()) + } else { + None + }; + if let Some(lib) = lib.filter(|l| seen.insert(l.clone())) { + println!("cargo:rustc-link-lib={lib}"); + } + } + } + } +} + +/// The JS string literals on a line, unescaped. +fn literals(line: &str) -> Vec { + let mut out = Vec::new(); + let mut chars = line.chars(); + while let Some(c) = chars.next() { + if c != '\'' && c != '"' { + continue; + } + let mut s = String::new(); + while let Some(d) = chars.next() { + match d { + '\\' => s.extend(chars.next()), + d if d == c => break, + d => s.push(d), + } + } + out.push(s); + } + out +} + +fn kaomoji() { + let src = concat!( + env!("CARGO_MANIFEST_DIR"), + "/../../src/components/lib/kaomoji.js" + ); + println!("cargo:rerun-if-changed={src}"); + let js = std::fs::read_to_string(src).expect("kaomoji dataset"); + let mut out = String::from("pub static KAOMOJI: &[Category] = &[\n"); + let mut open = false; + for line in js.lines() { + let t = line.trim(); + if t.starts_with("{ name:") { + if open { + out.push_str(" ] },\n"); + } + let name = &literals(t)[0]; + writeln!(out, " Category {{ name: {name:?}, items: &[").unwrap(); + open = true; + } else if open && t.starts_with('[') { + let l = literals(t); + writeln!( + out, + " Kaomoji {{ face: {:?}, name: {:?}, tags: {:?} }},", + l[0], l[1], l[2] + ) + .unwrap(); + } + } + if open { + out.push_str(" ] },\n"); + } + out.push_str("];\n"); + let dest = std::path::Path::new(&std::env::var("OUT_DIR").unwrap()).join("kaomoji_data.rs"); + std::fs::write(dest, out).unwrap(); +} diff --git a/crates/vector-gpui/media/Cargo.toml b/crates/vector-gpui/media/Cargo.toml new file mode 100644 index 000000000..23e5120cc --- /dev/null +++ b/crates/vector-gpui/media/Cargo.toml @@ -0,0 +1,96 @@ +[package] +name = "vector-gpui-media" +version = "0.1.0" +# The desktop client's modules compile in unchanged, so this crate keeps its edition. +edition = "2021" +license = "MIT" +description = "The desktop client's audio engine, devices and call media, compiled from its sources for the GPUI client." +publish = false + +[dependencies] +sha2 = "0.10.9" +tauri = { package = "vector-tauri-shim", path = "../tauri-shim" } +vector-core = { path = "../../vector-core", features = ["calls", "xdc"] } +anyhow = "1" +serde = { version = "1", features = ["derive"] } +serde_json = "1" +log = "0.4" +tokio = { version = "1.49.0", features = ["rt-multi-thread", "sync", "time", "macros"] } +futures-util = "0.3" +cpal = "0.16" +symphonia = { version = "0.5.5", default-features = false, features = ["mp3", "wav", "aiff", "flac", "pcm", "aac", "isomp4", "ogg", "vorbis", "opt-simd"] } +opus = "0.4" +rustfft = "6.2" +rand = "0.8" +bytes = "1" +async-trait = "0.1" +lofty = "0.24" +rayon = "1" +reqwest = { version = "0.13", default-features = false, features = ["stream"] } +iroh-gossip = { version = "0.101", default-features = false, features = ["net"] } +memchr = "2" +toml = "0.8.23" +zip = { version = "2.4", default-features = false, features = ["deflate-flate2", "flate2"] } +http = "1.3" +url = "2.5.7" +fast-thumbhash = "0.2" +tokio-tungstenite = { version = "0.28", default-features = false, features = ["handshake"] } +nostr-sdk = "=0.45.6" +image = { version = "0.25.9", default-features = false, features = ["png", "jpeg", "gif", "webp", "ico", "bmp"] } +iroh = { version = "1.3", default-features = false, features = ["tls-ring", "fast-apple-datapath"] } +secp256k1 = { version = "0.30", default-features = false, features = ["std"] } +bitcoin_hashes = { version = "1.2", default-features = false, features = ["std"] } +rusqlite = { version = "0.38", features = ["bundled", "fallible_uint"] } +hyper = { version = "1", features = ["server", "http1"] } +hyper-util = { version = "0.1", features = ["tokio"] } +http-body-util = "0.1" + +[features] +default = ["whisper"] +whisper = ["dep:whisper-rs"] +# The F-Droid flavour: its store installs every update, so no in-app installer. +fdroid = [] + +[target.'cfg(target_os = "linux")'.dependencies] +libc = "0.2" +glib = "0.18" +gtk = "0.18" +gdk = "0.18" +webkit2gtk = { version = "2.0", features = ["v2_40"] } + +[target.'cfg(target_os = "macos")'.dependencies] +whisper-rs = { version = "0.15.1", features = ["metal"], optional = true } +objc2 = "0.6" +objc2-foundation = { version = "0.3", features = ["NSString", "NSArray", "NSError", "NSProcessInfo", "NSBundle", "NSDictionary", "NSSet", "NSURL"] } +objc2-user-notifications = { version = "0.3.1", features = ["block2", "UNUserNotificationCenter", "UNNotification", "UNNotificationAction", "UNNotificationAttachment", "UNNotificationCategory", "UNNotificationContent", "UNNotificationRequest", "UNNotificationResponse", "UNNotificationTrigger"] } +objc2-core-foundation = "0.3.2" +block2 = "0.6" +dispatch2 = "0.3" +objc2-screen-capture-kit = { version = "0.3.2", features = ["SCStream", "SCShareableContent", "SCError", "block2", "dispatch2", "objc2-core-media", "objc2-core-graphics"] } +objc2-core-media = { version = "0.3.2", features = ["CMSampleBuffer", "CMBlockBuffer", "objc2-core-audio-types"] } +objc2-core-audio-types = "0.3.2" +objc2-core-graphics = { version = "0.3.2", features = ["CGWindow"] } + +[target.'cfg(windows)'.dependencies] +windows = { version = "0.61", features = ["Data_Xml_Dom", "Foundation", "UI_Notifications", "Win32_Foundation", "Win32_Security", "Win32_System_Com", "Win32_System_Registry", "Win32_UI_Notifications"] } +windows-core = "0.61" +windows-sys = { version = "0.61", features = ["Win32_System_Power", "Win32_UI_WindowsAndMessaging"] } + +[build-dependencies] +cc = "1" + +# Android transcribes on the CPU too, as the Tauri client does there. +[target.'cfg(target_os = "android")'.dependencies] +whisper-rs = { version = "0.15.1", optional = true } +jni = "0.21.1" +zeroize = "1.8" +ndk-context = "0.1.1" +# AAudio streams opened as a phone call's (the patched crate, as the desktop client's). +ndk = { version = "0.9", default-features = false, features = ["audio"] } + +# Vulkan on x86-64 Windows and Linux; ARM transcribes on the CPU, as the desktop client does. +[target.'cfg(all(any(windows, target_os = "linux"), target_arch = "x86_64"))'.dependencies] +whisper-rs = { version = "0.15.1", features = ["vulkan"], optional = true } + +[target.'cfg(all(any(windows, target_os = "linux"), not(target_arch = "x86_64")))'.dependencies] +whisper-rs = { version = "0.15.1", optional = true } diff --git a/crates/vector-gpui/media/build.rs b/crates/vector-gpui/media/build.rs new file mode 100644 index 000000000..7567432cd --- /dev/null +++ b/crates/vector-gpui/media/build.rs @@ -0,0 +1,75 @@ +//! SpeexDSP for the call engine, and the slice of `audio.rs` it reads. + +/// The desktop client's call DSP and the WAV reader its audio engine leans on, from its sources. +fn main() { + println!("cargo:rustc-check-cfg=cfg(desktop)"); + println!("cargo:rustc-cfg=desktop"); + let speex = std::path::Path::new(concat!( + env!("CARGO_MANIFEST_DIR"), + "/../../../src-tauri/csrc/speexdsp" + )); + println!("cargo:rerun-if-changed={}", speex.display()); + cc::Build::new() + .include(speex) + .files( + [ + "mdf.c", + "preprocess.c", + "fftwrap.c", + "filterbank.c", + "kiss_fft.c", + "kiss_fftr.c", + ] + .iter() + .map(|f| speex.join(f)), + ) + .define("FLOATING_POINT", "1") + .define("USE_KISS_FFT", "1") + .define("EXPORT", "") + .opt_level(2) + .warnings(false) + .compile("speexdsp_calls"); + + // audio.rs is mostly Tauri commands; these functions are plain Rust. + let src = concat!( + env!("CARGO_MANIFEST_DIR"), + "/../../../src-tauri/src/audio.rs" + ); + println!("cargo:rerun-if-changed={src}"); + let rs = std::fs::read_to_string(src).expect("audio.rs"); + let mut out = String::new(); + for head in [ + "fn wav_fast_decode(", + "pub fn wav_fast_decode_for_engine(", + "fn wav_channel_count(", + "pub fn decode_for_whisper(", + "pub(crate) fn symphonia_decode_mono(", + ] { + let start = rs + .lines() + .position(|l| l.starts_with(head)) + .unwrap_or_else(|| panic!("audio.rs lost {head}")); + for line in rs.lines().skip(start) { + out.push_str(line); + out.push('\n'); + if line == "}" { + break; + } + } + } + let dest = std::path::Path::new(&std::env::var("OUT_DIR").unwrap()).join("wav.rs"); + std::fs::write(dest, out).unwrap(); + + // The Mini App bridge's guard script is a private constant of the desktop's commands. + let cmds = concat!( + env!("CARGO_MANIFEST_DIR"), + "/../../../src-tauri/src/miniapps/commands.rs" + ); + println!("cargo:rerun-if-changed={cmds}"); + let rs = std::fs::read_to_string(cmds).expect("miniapps/commands.rs"); + let open = "const INIT_SCRIPT: &str = r#\""; + let start = rs.find(open).expect("commands.rs lost INIT_SCRIPT") + open.len(); + let len = rs[start..].find("\"#;").expect("INIT_SCRIPT unterminated"); + let dest = std::path::Path::new(&std::env::var("OUT_DIR").unwrap()).join("miniapp_init.js"); + std::fs::write(dest, &rs[start..start + len]).unwrap(); +} diff --git a/crates/vector-gpui/media/src/android/background_sync.rs b/crates/vector-gpui/media/src/android/background_sync.rs new file mode 100644 index 000000000..fd6adbebc --- /dev/null +++ b/crates/vector-gpui/media/src/android/background_sync.rs @@ -0,0 +1,274 @@ +//! What the shared JNI modules take from the desktop client's background service: the process's +//! VM and application context, whether the activity is on screen, and the message notifications +//! `VectorNotificationService` posts. The client itself stays connected while the service keeps +//! the process alive, so there is no second, standalone client here. + +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Mutex, OnceLock}; + +use jni::objects::{GlobalRef, JClass, JObject, JString, JValue}; +use jni::sys::jboolean; +use jni::{JNIEnv, JavaVM}; +use nostr_sdk::prelude::ToBech32; + +pub static BG_JAVA_VM: OnceLock = OnceLock::new(); +pub static BG_APP_CONTEXT: OnceLock = OnceLock::new(); +static FOREGROUND: AtomicBool = AtomicBool::new(false); + +pub fn is_activity_in_foreground() -> bool { + FOREGROUND.load(Ordering::Acquire) +} + +/// Runs `f` with `VectorNotificationService`'s class and the application context, on any thread. +fn with_service( + what: &str, + f: impl FnOnce(&mut JNIEnv, &JClass, &JObject) -> jni::errors::Result, +) -> Option { + let (vm, context) = (BG_JAVA_VM.get()?, BG_APP_CONTEXT.get()?); + let mut env = vm.attach_current_thread().ok()?; + let context = context.as_obj(); + let out = (|| { + // The context's loader: a framework class's own is the boot loader, which has none of ours. + let loader = env.call_method(context, "getClassLoader", "()Ljava/lang/ClassLoader;", &[])?.l()?; + let name = env.new_string("io.vectorapp.VectorNotificationService")?; + let class = env + .call_method(&loader, "loadClass", "(Ljava/lang/String;)Ljava/lang/Class;", &[JValue::Object(&name)])? + .l()?; + f(&mut env, &JClass::from(class), context) + })(); + match out { + Ok(r) => Some(r), + Err(e) => { + let _ = env.exception_clear(); + log::warn!("notification {what}: {e}"); + None + } + } +} + +/// One message in its chat's notification. The caller has already applied the reader's privacy +/// choice, in their language. +pub fn post_notification_jni( + title: &str, + body: &str, + avatar_path: Option<&str>, + chat_id: Option<&str>, + sender_name: Option<&str>, + group_name: Option<&str>, + group_avatar_path: Option<&str>, +) { + if is_activity_in_foreground() { + return; + } + let avatar = notification_image(avatar_path.map(str::to_string)).unwrap_or_default(); + let group_avatar = notification_image(group_avatar_path.map(str::to_string)).unwrap_or_default(); + let texts: [&str; 7] = [ + title, + body, + &avatar, + chat_id.unwrap_or_default(), + sender_name.unwrap_or_default(), + group_name.unwrap_or_default(), + &group_avatar, + ]; + with_service("post", |env, class, context| { + let mut args = vec![JValue::Object(context)]; + let strings = texts.iter().map(|s| env.new_string(s)).collect::, _>>()?; + args.extend(strings.iter().map(JValue::from)); + env.call_static_method( + class, + "showMessageNotification", + "(Landroid/content/Context;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V", + &args, + ) + .map(drop) + }); +} + +/// The chat was read, here or elsewhere: its notification goes. +pub fn cancel_notification_jni(chat_id: &str) { + if chat_id.is_empty() { + return; + } + with_service("cancel", |env, class, context| { + let chat = env.new_string(chat_id)?; + env.call_static_method( + class, + "cancelNotification", + "(Landroid/content/Context;Ljava/lang/String;)V", + &[JValue::Object(context), JValue::Object(&chat)], + ) + .map(drop) + }); +} + +/// Every message notification, for an account leaving the phone's screen. +pub fn cancel_all_message_notifications_jni() { + with_service("cancel all", |env, class, context| { + env.call_static_method(class, "cancelAllMessageNotifications", "(Landroid/content/Context;)V", &[ + JValue::Object(context), + ]) + .map(drop) + }); +} + +/// A sealed cache file opened into a plain one the shade can read, kept until the source changes. +pub(crate) fn notification_image(path: Option) -> Option { + let path = path.filter(|p| !p.is_empty())?; + let source = std::path::Path::new(&path); + if !vector_core::vcache::is_sealed(source) { + return Some(path); + } + let dir = vector_core::db::get_app_data_dir().ok()?.join("notifications").join("avatars"); + std::fs::create_dir_all(&dir).ok()?; + let ext = source.extension().and_then(|e| e.to_str()).unwrap_or("img"); + let modified = std::fs::metadata(source).and_then(|m| m.modified()).ok()?; + let stamp = modified.duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_nanos()); + let key = vector_core::crypto::sha256_hex(format!("{path}\n{stamp}").as_bytes()); + let out = dir.join(format!("{}.{ext}", &key[..32])); + if !out.is_file() { + let bytes = vector_core::vcache::read(source).ok()?; + let tmp = dir.join(format!(".{}.{:08x}.tmp", &key[..32], rand::random::())); + if std::fs::write(&tmp, &*bytes).and_then(|_| std::fs::rename(&tmp, &out)).is_err() { + let _ = std::fs::remove_file(&tmp); + return None; + } + } + Some(out.to_string_lossy().into_owned()) +} + +fn string(env: &mut JNIEnv, s: &JString) -> String { + env.get_string(s).map(Into::into).unwrap_or_default() +} + +/// The process's VM and application context, from any context: a service can start the +/// process with no activity. +pub fn hold_context(env: &mut JNIEnv, context: &JObject) { + if BG_JAVA_VM.get().is_none() { + if let Ok(vm) = env.get_java_vm() { + let _ = BG_JAVA_VM.set(vm); + } + } + if BG_APP_CONTEXT.get().is_none() { + let app = env.call_method(context, "getApplicationContext", "()Landroid/content/Context;", &[]).and_then(|v| v.l()); + match app.and_then(|app| env.new_global_ref(app)) { + Ok(global) => { + let _ = BG_APP_CONTEXT.set(global); + } + Err(_) => { + let _ = env.exception_clear(); + } + } + } +} + +/// `MainActivity.onCreate`: the activity for calls that need one, and the process's VM and +/// application context for the rest. +#[no_mangle] +pub extern "C" fn Java_io_vectorapp_MainActivity_nativeCreated(mut env: JNIEnv, activity: JObject) { + super::utils::jni_fence("Java_io_vectorapp_MainActivity_nativeCreated", || (), move || { + super::utils::set_activity(&mut env, &activity); + hold_context(&mut env, &activity); + }) +} + +#[no_mangle] +pub extern "C" fn Java_io_vectorapp_MainActivity_nativeDestroyed(mut env: JNIEnv, activity: JObject) { + super::utils::jni_fence("Java_io_vectorapp_MainActivity_nativeDestroyed", || (), move || { + super::utils::clear_activity(&mut env, &activity); + }) +} + +/// Resumed or paused: nothing is posted while the app is on screen. +#[no_mangle] +pub extern "C" fn Java_io_vectorapp_MainActivity_nativeForeground(_env: JNIEnv, _activity: JObject, on: jboolean) { + FOREGROUND.store(on != 0, Ordering::Release); +} + +/// A tap that launched the app before the client could take it. +static PENDING_LINK: Mutex> = Mutex::new(None); + +/// Keeps `action` for the client when it isn't up yet; false when it can take it now. +pub(crate) fn hold_link(action: &vector_core::deep_link::DeepLinkAction) -> bool { + let mut pending = PENDING_LINK.lock().unwrap_or_else(|e| e.into_inner()); + if crate::notify_host::get().is_some() { + return false; + } + *pending = Some(action.clone()); + true +} + +/// The client has installed its hooks: a tap that came first is taken now. +pub(crate) fn deliver_pending_link() { + let action = PENDING_LINK.lock().unwrap_or_else(|e| e.into_inner()).take(); + if let (Some(action), Some(app)) = (action, crate::TAURI_APP.get()) { + use tauri::Emitter; + let _ = app.emit("deep_link_action", &action); + } +} + +/// A message notification was tapped: its chat opens, once the client is up to open it. +#[no_mangle] +pub extern "C" fn Java_io_vectorapp_MainActivity_nativeOnNotificationTap(mut env: JNIEnv, _class: JClass, chat_id: JString) { + super::utils::jni_fence("Java_io_vectorapp_MainActivity_nativeOnNotificationTap", || (), move || { + let chat_id = string(&mut env, &chat_id); + if chat_id.is_empty() { + return; + } + let action = vector_core::deep_link::DeepLinkAction { + action_type: "chat".into(), + target: chat_id.clone(), + ..Default::default() + }; + if let (false, Some(host)) = (hold_link(&action), crate::notify_host::get()) { + (host.open)(chat_id, None, None); + } + }) +} + +#[no_mangle] +pub extern "C" fn Java_io_vectorapp_NotificationActionReceiver_nativeMarkAsRead(mut env: JNIEnv, _class: JClass, chat_id: JString) { + super::utils::jni_fence("Java_io_vectorapp_NotificationActionReceiver_nativeMarkAsRead", || (), move || { + let chat_id = string(&mut env, &chat_id); + let Some(host) = crate::notify_host::get().filter(|_| !chat_id.is_empty()) else { return }; + // spawn-detached: a read for whichever account is live, as the notification was. + tauri::async_runtime::spawn(vector_core::db::scoped((host.mark_read)(chat_id))); + }) +} + +/// An inline reply: sent, then shown under the conversation so the shade's spinner clears. +#[no_mangle] +pub extern "C" fn Java_io_vectorapp_NotificationActionReceiver_nativeSendReply( + mut env: JNIEnv, + _class: JClass, + chat_id: JString, + content: JString, +) { + super::utils::jni_fence("Java_io_vectorapp_NotificationActionReceiver_nativeSendReply", || (), move || { + let (chat_id, content) = (string(&mut env, &chat_id), string(&mut env, &content)); + let Some(host) = crate::notify_host::get().filter(|_| !chat_id.is_empty() && !content.is_empty()) else { + return; + }; + // spawn-detached: a reply for whichever account is live, as the notification was. + tauri::async_runtime::spawn(vector_core::db::scoped(async move { + if let Err(e) = (host.reply)(chat_id.clone(), content.clone()).await { + log::warn!("notification reply: {e}"); + return; + } + let (me, avatar) = own_label().await; + post_notification_jni(&me, &content, avatar.as_deref(), Some(&chat_id), Some(&me), None, None); + })); + }) +} + +/// How the shade names our own replies: "Me", with the profile's name when it has one. +async fn own_label() -> (String, Option) { + let Some(npub) = vector_core::my_public_key().and_then(|pk| pk.to_bech32().ok()) else { + return ("Me".into(), None); + }; + let state = vector_core::STATE.lock().await; + let Some(profile) = state.get_profile(&npub) else { return ("Me".into(), None) }; + let name = [profile.display_name(), profile.name()].into_iter().find(|n| !n.is_empty()); + let label = name.map_or_else(|| "Me".to_string(), |n| format!("Me ({n})")); + (label, profile.has_avatar_cached().then(|| profile.avatar_cached().into_owned())) +} diff --git a/crates/vector-gpui/media/src/android/mod.rs b/crates/vector-gpui/media/src/android/mod.rs new file mode 100644 index 000000000..e78eaee18 --- /dev/null +++ b/crates/vector-gpui/media/src/android/mod.rs @@ -0,0 +1,28 @@ +//! The desktop client's JNI glue for calls and the microphone, compiled from its sources, over +//! the activity and services in `crates/vector-gpui/android`. + +#[path = "../../../../../src-tauri/src/android/utils.rs"] +#[allow(dead_code)] +pub mod utils; +#[path = "../../../../../src-tauri/src/android/permissions.rs"] +pub mod permissions; +#[path = "../../../../../src-tauri/src/android/call_audio.rs"] +#[allow(dead_code)] +pub mod call_audio; +#[path = "../../../../../src-tauri/src/android/call_service.rs"] +pub mod call_service; +#[path = "../../../../../src-tauri/src/android/incoming_call.rs"] +#[allow(dead_code)] +pub mod incoming_call; +#[path = "../../../../../src-tauri/src/android/storage.rs"] +#[allow(dead_code)] +pub mod storage; +#[path = "../../../../../src-tauri/src/android/biometric.rs"] +pub mod biometric; +#[path = "../../../../../src-tauri/src/android/external_signer.rs"] +pub mod external_signer; +#[path = "../../../../../src-tauri/src/android/updates.rs"] +pub mod updates; +pub mod background_sync; + +use utils::with_android_context; diff --git a/crates/vector-gpui/media/src/audio.rs b/crates/vector-gpui/media/src/audio.rs new file mode 100644 index 000000000..f1d2170ce --- /dev/null +++ b/crates/vector-gpui/media/src/audio.rs @@ -0,0 +1,45 @@ +//! What the shared audio engine and call modules read from the desktop client's `audio.rs`. + +use symphonia::core::audio::SampleBuffer; +use symphonia::core::codecs::{DecoderOptions, CODEC_TYPE_NULL}; +use symphonia::core::errors::Error as SymphoniaError; +use symphonia::core::formats::FormatOptions; +use symphonia::core::io::MediaSourceStream; +use symphonia::core::meta::MetadataOptions; +use symphonia::core::probe::Hint; + +include!(concat!(env!("OUT_DIR"), "/wav.rs")); + +/// Nothing caches the device rate here: notification sounds ask the device each time. +pub fn invalidate_device_sample_rate_cache() {} + +pub fn resample_mono_f32( + samples: Vec, + from_rate: u32, + to_rate: u32, +) -> Result, String> { + if from_rate == to_rate { + return Ok(samples); + } + Ok(crate::simd::audio::linear_resample_mono( + &samples, from_rate, to_rate, + )) +} + +pub fn resample_mono_i16(samples: &[i16], from_rate: u32, to_rate: u32) -> Result, String> { + if from_rate == to_rate { + return Ok(samples.to_vec()); + } + let bytes: Vec = samples.iter().flat_map(|s| s.to_le_bytes()).collect(); + let f = crate::simd::audio::i16_le_bytes_to_f32_mono(&bytes); + let resampled = crate::simd::audio::linear_resample_mono(&f, from_rate, to_rate); + Ok(crate::simd::audio::f32_to_i16(&resampled)) +} + +/// The host plays the chosen sound, having read whether it is muted. +pub fn play_notification_if_enabled(_: &tauri::AppHandle) -> Result<(), String> { + if let Some(h) = crate::notify_host::get() { + (h.sound)(); + } + Ok(()) +} diff --git a/crates/vector-gpui/media/src/calls/mod.rs b/crates/vector-gpui/media/src/calls/mod.rs new file mode 100644 index 000000000..bb9023b90 --- /dev/null +++ b/crates/vector-gpui/media/src/calls/mod.rs @@ -0,0 +1,65 @@ +//! Calls, on the desktop client's own media engine: its modules compiled in unchanged, with the +//! webview's video socket replaced by an in-process link (this client draws video itself). + +#[path = "../../../../../src-tauri/src/calls/aec.rs"] +pub mod aec; +#[path = "../../../../../src-tauri/src/calls/codec.rs"] +pub mod codec; +#[path = "../../../../../src-tauri/src/calls/media.rs"] +pub mod media; +#[path = "../../../../../src-tauri/src/calls/session.rs"] +pub mod session; +#[path = "../../../../../src-tauri/src/calls/share_native.rs"] +mod share_native_shared; +/// The desktop's native screen audio, offered only where ScreenCaptureKit captures sound: its +/// classes arrive in macOS 12.3, audio capture in 13, and this client runs from 12. +pub mod share_native { + use super::share_native_shared as shared; + pub use shared::{permitted, stop}; + use crate::calls::media::ShareInput; + use std::sync::Arc; + + pub fn available() -> bool { + #[cfg(target_os = "macos")] + { + use objc2::runtime::AnyClass; + shared::available() + && AnyClass::get(c"SCStreamConfiguration") + .is_some_and(|c| c.instance_method(objc2::sel!(setCapturesAudio:)).is_some()) + } + #[cfg(not(target_os = "macos"))] + shared::available() + } + + pub async fn start(share: Arc) -> Result<(), String> { + if !available() { + return Err("Screen audio needs macOS 13 or later".into()); + } + shared::start(share).await + } +} +#[path = "../../../../../src-tauri/src/calls/voice.rs"] +pub mod voice; + +pub use vector_core::calls::wire as transport; +pub use vector_core::calls::{declick, gate, jitter, rate, resample, ring, settings, stats}; +pub use vector_core::calls::{AEC_TAIL_MS, ENGINE_RATE, FRAME, FRAME_MS}; + +/// Where the session hands a video connection: the call's video track while one runs. +pub mod link { + use std::sync::Mutex; + use tokio::sync::mpsc; + pub use vector_core::calls::platform::LinkConn; + + static TAKER: Mutex>> = Mutex::new(None); + + pub fn set_taker(taker: Option>) { + *TAKER.lock().unwrap_or_else(|e| e.into_inner()) = taker; + } + + /// Hands a new link to the running track; false when no call wants one. + pub fn connect(conn: LinkConn) -> bool { + let taker = TAKER.lock().unwrap_or_else(|e| e.into_inner()).clone(); + taker.is_some_and(|t| t.try_send(conn).is_ok()) + } +} diff --git a/crates/vector-gpui/media/src/image_cache.rs b/crates/vector-gpui/media/src/image_cache.rs new file mode 100644 index 000000000..b95bc1b31 --- /dev/null +++ b/crates/vector-gpui/media/src/image_cache.rs @@ -0,0 +1,102 @@ +//! The slice of the desktop's image cache the marketplace asks for: Mini App icons on disk. + +use std::path::PathBuf; + +use tauri::{AppHandle, Manager, Runtime}; + +use crate::net::{NoOpProgressReporter, download_to_memory}; + +#[derive(Clone, Copy, PartialEq, Eq)] +pub enum ImageType { + MiniAppIcon, +} + +pub enum CacheResult { + Cached(String), + AlreadyCached(String), + Failed(String), +} + +const MAX_BYTES: u64 = 1024 * 1024; +const SVG_DIM: u32 = 256; + +fn dir(handle: &AppHandle) -> Result { + let dir = handle.path().app_data_dir().map_err(|e| e.to_string())?.join("cache").join("miniapp_icons"); + std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?; + Ok(dir) +} + +fn key(url: &str) -> String { + vector_core::crypto::sha256_hex(url.as_bytes())[..32].to_string() +} + +const EXTS: [&str; 6] = ["jpg", "png", "webp", "gif", "ico", "bmp"]; + +fn sniff(bytes: &[u8]) -> Option<&'static str> { + const SIGS: &[(&[u8], &str)] = &[ + (&[0x89, b'P', b'N', b'G'], "png"), + (&[0xFF, 0xD8, 0xFF], "jpg"), + (b"GIF8", "gif"), + (&[0x00, 0x00, 0x01, 0x00], "ico"), + (b"BM", "bmp"), + ]; + if let Some((_, ext)) = SIGS.iter().find(|(sig, _)| bytes.starts_with(sig)) { + return Some(ext); + } + if bytes.len() >= 12 && &bytes[..4] == b"RIFF" && &bytes[8..12] == b"WEBP" { + return Some("webp"); + } + let head = &bytes[..bytes.len().min(512)]; + head.windows(4).any(|w| w == b"(handle: &AppHandle, url: &str, _: ImageType) -> Option { + let dir = dir(handle).ok()?; + let key = key(url); + EXTS.iter() + .map(|ext| dir.join(format!("{key}.{ext}"))) + .find(|p| p.is_file()) + .map(|p| p.to_string_lossy().into_owned()) +} + +pub async fn cache_image(handle: &AppHandle, url: &str, kind: ImageType) -> CacheResult { + if url.is_empty() { + return CacheResult::Failed("Empty URL".into()); + } + if let Some(p) = get_cached_path(handle, url, kind) { + return CacheResult::AlreadyCached(p); + } + let bytes = match download_to_memory(url, &NoOpProgressReporter, None, MAX_BYTES).await { + Ok(b) => b, + Err(e) => return CacheResult::Failed(e.to_string()), + }; + let Some(mut ext) = sniff(&bytes) else { + return CacheResult::Failed("Invalid image".into()); + }; + // An SVG is kept as the pixels it draws. + let bytes = if ext == "svg" { + ext = "png"; + match tokio::task::spawn_blocking(move || vector_core::svg::rasterize_png(&bytes, SVG_DIM)).await { + Ok(Ok(b)) => b, + Ok(Err(e)) => return CacheResult::Failed(e.to_string()), + Err(e) => return CacheResult::Failed(e.to_string()), + } + } else { + bytes + }; + let path = match dir(handle) { + Ok(d) => d.join(format!("{}.{ext}", key(url))), + Err(e) => return CacheResult::Failed(e), + }; + match tokio::fs::write(&path, &bytes).await { + Ok(()) => CacheResult::Cached(path.to_string_lossy().into_owned()), + Err(e) => CacheResult::Failed(e.to_string()), + } +} + +pub fn remove_cached_image(handle: &AppHandle, url: &str, kind: ImageType) -> Result<(), String> { + while let Some(p) = get_cached_path(handle, url, kind) { + std::fs::remove_file(p).map_err(|e| e.to_string())?; + } + Ok(()) +} diff --git a/crates/vector-gpui/media/src/lib.rs b/crates/vector-gpui/media/src/lib.rs new file mode 100644 index 000000000..a46be6c8d --- /dev/null +++ b/crates/vector-gpui/media/src/lib.rs @@ -0,0 +1,228 @@ +//! The desktop client's audio engine, device preferences, microphone access and call media, +//! compiled from `src-tauri` as they are, over a slice of Tauri's API (`tauri-shim`). + +#[macro_use] +extern crate vector_core; + +/// The desktop's `log_error!` also toasts; here it is a log line. +macro_rules! log_error { + ($($t:tt)*) => { vector_core::log_warn!($($t)*) }; +} + +/// The desktop's global accessors, by the paths its modules name them. +pub use vector_core::{STATE, my_public_key}; +pub mod db { + pub use vector_core::db::Session; + pub use vector_core::db::events::save_pivx_payment_event; + pub use vector_core::db::miniapps::*; + pub use vector_core::db::settings::{get_sql_setting, set_sql_setting}; + pub async fn get_pivx_payments_for_chat(id: &str) -> Result, String> { + vector_core::db::events::get_pivx_payments_for_chat(id) + } +} +pub mod account_manager { + pub use vector_core::db::get_db_connection_guard_static; +} +pub mod util { + pub use vector_core::crypto::mime_from_magic_bytes; + pub use vector_core::simd::hex::{bytes_to_hex_16, bytes_to_hex_string, hex_string_to_bytes}; +} +pub use vector_core::{blossom, crypto, inbox_relays, nostr_client, stored_event}; +#[path = "../../../../src-tauri/src/pivx.rs"] +#[allow(dead_code)] +pub mod pivx; +#[path = "../../../../src-tauri/src/commands/players.rs"] +pub mod players; +#[path = "../../../../src-tauri/src/net.rs"] +#[allow(dead_code)] +pub mod net; +pub mod image_cache; +/// What `listing_icon` asks of the desktop's image module, from the image crate. +pub mod shared { + pub mod image { + use image::DynamicImage; + + pub fn decode_image(bytes: &[u8], _min_long_side: u32) -> Result { + image::load_from_memory(bytes).map_err(|e| e.to_string()) + } + pub fn resize_fit(img: &DynamicImage, w: u32, h: u32, filter: image::imageops::FilterType) -> DynamicImage { + img.resize(w, h, filter) + } + pub fn encode_png(pixels: &[u8], w: u32, h: u32) -> Result, String> { + let mut out = Vec::new(); + image::codecs::png::PngEncoder::new(&mut out) + .write_image(pixels, w, h, image::ExtendedColorType::Rgba8) + .map_err(|e| e.to_string())?; + Ok(out) + } + use image::ImageEncoder; + } +} + +#[cfg(target_os = "android")] +pub mod android; +#[allow(dead_code)] +pub mod audio; +#[path = "../../../../src-tauri/src/audio_codecs.rs"] +pub mod audio_codecs; +#[path = "../../../../src-tauri/src/audio_devices.rs"] +#[allow(dead_code, unused_imports)] +pub mod audio_devices; +#[path = "../../../../src-tauri/src/audio_engine.rs"] +#[allow(dead_code, clippy::all)] +pub mod audio_engine; +#[path = "../../../../src-tauri/src/awake.rs"] +#[allow(dead_code)] +pub mod awake; +#[allow(dead_code, unused_imports, clippy::all)] +pub mod calls; +#[path = "../../../../src-tauri/src/chapters.rs"] +#[allow(dead_code)] +pub mod chapters; +#[path = "../../../../src-tauri/src/lyrics.rs"] +#[allow(dead_code)] +pub mod lyrics; +pub mod tags; +#[path = "../../../../src-tauri/src/mic_access.rs"] +#[allow(dead_code)] +pub mod mic_access; +pub mod miniapps; +#[cfg(feature = "whisper")] +#[allow(dead_code)] +pub mod whisper { + include!("../../../../src-tauri/src/whisper.rs"); + + /// Free the cached context before exit: ggml's Metal teardown aborts while any of its buffers live. + pub fn unload() { + if let Ok(mut cache) = WHISPER_CTX_CACHE.try_lock() { + *cache = None; + } + } +} +#[path = "../../../../src-tauri/src/voice.rs"] +#[allow(dead_code, unexpected_cfgs)] +pub mod voice; + +#[path = "../../../../src-tauri/src/simd/audio.rs"] +#[allow(dead_code)] +#[doc(hidden)] +pub mod simd_audio; + +#[path = "../../../../src-tauri/src/simd/html_meta.rs"] +#[allow(dead_code)] +#[doc(hidden)] +pub mod simd_html_meta; + +pub mod simd { + pub use super::simd_audio as audio; + pub use super::simd_html_meta as html_meta; +} + +/// Where the engine's events go: set once by the host before any sound plays. +pub static TAURI_APP: std::sync::OnceLock = std::sync::OnceLock::new(); + +extern crate tauri as tauri_plugin_notification; + +/// What the host does for a notification's buttons, by the paths the desktop's notifier names. +pub mod notify_host { + use std::future::Future; + use std::pin::Pin; + use std::sync::OnceLock; + + pub type Fut = Pin + Send>>; + + pub struct Host { + pub mark_read: fn(String) -> Fut, + /// A mute of `ms`, in `set_notify_mute`'s units (negative is indefinite). + pub mute: fn(String, i64) -> Fut>, + pub reply: fn(String, String) -> Fut>, + /// The chat, at the message if there is one, for the account it was shown for. + pub open: fn(String, Option, Option), + pub sound: fn(), + } + + static HOST: OnceLock = OnceLock::new(); + + pub fn set(host: Host) { + let _ = HOST.set(host); + #[cfg(target_os = "android")] + crate::android::background_sync::deliver_pending_link(); + } + + pub(crate) fn get() -> Option<&'static Host> { + HOST.get() + } +} + +pub mod chat { + pub async fn mark_as_read_headless(chat_id: &str) -> bool { + match crate::notify_host::get() { + Some(h) => (h.mark_read)(chat_id.to_string()).await, + None => false, + } + } +} + +pub mod commands { + pub mod messaging { + /// The host recounts on the read itself. + pub async fn update_unread_counter(_: tauri::AppHandle) -> Result<(), String> { + Ok(()) + } + } + pub mod notify { + pub async fn set_notify_mute(scope_id: String, duration_ms: i64) -> Result<(), String> { + match crate::notify_host::get() { + Some(h) => (h.mute)(scope_id, duration_ms).await, + None => Err("not ready".into()), + } + } + } +} + +pub mod message { + pub async fn send_text_reply_headless(chat_id: &str, content: &str) -> Result { + match crate::notify_host::get() { + Some(h) => (h.reply)(chat_id.to_string(), content.to_string()).await, + None => Err("not ready".into()), + } + } +} + +pub mod deep_link { + #[cfg(target_os = "android")] + pub use vector_core::deep_link::DeepLinkAction; + + /// A tapped call, kept when it launched the app before the client was up to take its event. + #[cfg(target_os = "android")] + pub fn set_pending_action(action: DeepLinkAction) { + crate::android::background_sync::hold_link(&action); + } + + pub fn open_chat_from_notification( + _: &tauri::AppHandle, + chat_id: &str, + message: Option<&str>, + account: Option<&str>, + ) { + if let Some(h) = crate::notify_host::get() { + (h.open)(chat_id.to_string(), message.map(str::to_string), account.map(str::to_string)); + } + } +} + +#[path = "../../../../src-tauri/src/services/notification_service.rs"] +#[allow(dead_code)] +#[doc(hidden)] +pub mod notification_service; +#[path = "../../../../src-tauri/src/services/native_notify/mod.rs"] +#[allow(dead_code)] +#[doc(hidden)] +pub mod native_notify; + +/// The desktop's OS notifications: its notification service and one backend per platform. +pub mod services { + pub use super::native_notify; + pub use super::notification_service; + pub use super::notification_service::{show_notification_generic, strip_content_for_preview, NotificationData}; +} diff --git a/crates/vector-gpui/media/src/miniapps.rs b/crates/vector-gpui/media/src/miniapps.rs new file mode 100644 index 000000000..75569dd74 --- /dev/null +++ b/crates/vector-gpui/media/src/miniapps.rs @@ -0,0 +1,149 @@ +//! The desktop client's Mini App core, compiled from its sources: packages, the `webxdc://` +//! scheme and bridge script, permissions and the realtime channel. Windows are the host's. + +#[path = "../../../../src-tauri/src/miniapps/error.rs"] +#[allow(dead_code)] +pub mod error; +#[path = "../../../../src-tauri/src/miniapps/marketplace.rs"] +#[allow(dead_code)] +pub mod marketplace; +#[cfg(not(target_os = "android"))] +#[path = "../../../../src-tauri/src/miniapps/isolated.rs"] +#[allow(dead_code)] +mod isolated_core; +/// The desktop's loopback host, which Android doesn't run: an app needing it never opens there. +#[cfg(target_os = "android")] +mod isolated_core { + pub(crate) struct Started { + pub id: u64, + pub port: u16, + pub boot_url: url::Url, + } + pub(crate) enum StartError { + #[allow(dead_code)] + AlreadyOpen(String), + Failed(String), + } + pub(crate) async fn start(_: &tauri::AppHandle, _: &str, _: &str, _: Option<&str>) -> Result { + Err(StartError::Failed("Cross-origin isolated Mini Apps can't run on Android yet".into())) + } + pub(crate) fn origin(port: u16) -> String { + format!("http://localhost:{port}") + } + pub(crate) fn window_for_partition(_: &str, _: &str) -> Option { + None + } + pub(crate) fn stop_if(_: &str, _: u64) {} + pub(crate) fn is_live_port(_: u16) -> bool { + false + } +} +#[cfg(target_os = "linux")] +#[path = "../../../../src-tauri/src/miniapps/network_isolation.rs"] +pub mod network_isolation; +#[path = "../../../../src-tauri/src/miniapps/realtime.rs"] +#[allow(dead_code)] +pub mod realtime; +#[path = "../../../../src-tauri/src/miniapps/rt_ws.rs"] +#[allow(dead_code)] +pub mod rt_ws; +#[path = "../../../../src-tauri/src/miniapps/scheme.rs"] +#[allow(dead_code)] +pub mod scheme; +#[path = "../../../../src-tauri/src/miniapps/state.rs"] +#[allow(dead_code)] +pub mod state; + +pub use vector_core::webxdc_permissions as permissions; + +/// Runs first in every frame of a Mini App: engine shims, API removals, permission guards. +pub const INIT_SCRIPT: &str = include_str!(concat!(env!("OUT_DIR"), "/miniapp_init.js")); + +/// The bridge script `webxdc.js` the pages load, for a host that serves it itself. +pub async fn bridge_js() -> String { + let (npub, name) = scheme::get_user_info().await; + scheme::generate_webxdc_bridge_js(&npub, &name) +} + +/// Answers one `webxdc://` request from the Mini App window `label`. +pub fn serve( + label: &str, + request: http::Request>, + respond: impl FnOnce(http::Response>) + Send + 'static, +) { + let app = *crate::TAURI_APP.get().expect("TAURI_APP set at startup"); + scheme::miniapp_protocol( + tauri::UriSchemeContext::new(label, app), + request, + tauri::UriSchemeResponder::new(respond), + ); +} + +/// The process's Mini App state; the host manages it once at startup. +pub fn apps() -> &'static state::MiniAppsState { + tauri::manage(state::MiniAppsState::new()) +} + +/// The proxy every Linux Mini App webview is pointed at, so it has no network. +#[cfg(target_os = "linux")] +pub fn network_sink() -> Option<&'static url::Url> { + network_isolation::proxy_url() +} + +/// The loopback host cross-origin isolated apps are served from. +pub mod isolated { + use super::isolated_core as core; + + pub struct Started { + pub id: u64, + pub port: u16, + pub boot_url: url::Url, + } + + pub enum StartError { + /// Another window already serves this app's store. + AlreadyOpen(String), + Failed(String), + } + + pub async fn start(app: &tauri::AppHandle, label: &str, partition: &str, href: Option<&str>) -> Result { + match core::start(app, label, partition, href).await { + Ok(s) => Ok(Started { id: s.id, port: s.port, boot_url: s.boot_url }), + Err(core::StartError::AlreadyOpen(l)) => Err(StartError::AlreadyOpen(l)), + Err(core::StartError::Failed(e)) => Err(StartError::Failed(e)), + } + } + + pub fn origin(port: u16) -> String { + core::origin(port) + } + + pub fn window_for_partition(partition: &str, except_label: &str) -> Option { + core::window_for_partition(partition, except_label) + } + + pub fn stop_if(label: &str, id: u64) { + core::stop_if(label, id) + } + + /// Whether `port` serves a Mini App now. + pub fn is_live_port(port: u16) -> bool { + core::is_live_port(port) + } + + #[cfg(target_os = "macos")] + pub fn store_identifier(partition: &str) -> Option<[u8; 16]> { + core::store_identifier(partition) + } + + #[cfg(target_os = "linux")] + pub fn enable_web_storage(view: &webkit2gtk::WebView) -> usize { + core::enable_web_storage(view) + } + + /// The realtime WebSocket's port, which an isolated app reaches past its proxy. + #[cfg(target_os = "linux")] + pub fn rt_ws_port() -> Option { + super::scheme::rt_ws_port() + } +} diff --git a/crates/vector-gpui/media/src/tags.rs b/crates/vector-gpui/media/src/tags.rs new file mode 100644 index 000000000..85b01fc19 --- /dev/null +++ b/crates/vector-gpui/media/src/tags.rs @@ -0,0 +1,53 @@ +//! An audio file's tags as the player shows them: `get_audio_metadata`, with the cover art +//! kept as bytes for a native image rather than a data URI. + +use crate::audio_engine::AudioInput; + +pub struct Meta { + pub title: Option, + pub artist: Option, + pub album: Option, + pub cover: Option>, + pub lyrics: Option, + pub year: Option, + pub chapters: Vec, +} + +/// None when the file has nothing worth showing: no title, art, lyrics or chapters. +pub fn read(input: &AudioInput) -> Result, String> { + use lofty::file::TaggedFileExt; + use lofty::tag::Accessor; + + let tagged = match input { + AudioInput::File(path) => lofty::read_from_path(path), + AudioInput::Held(_) => lofty::probe::Probe::new(input.open()?) + .guess_file_type() + .map_err(|e| format!("Failed to read tags: {e}"))? + .read(), + } + .map_err(|e| format!("Failed to read tags: {e}"))?; + let Some(tag) = tagged.primary_tag().or_else(|| tagged.first_tag()) else { + return Ok(None); + }; + let title = tag.title().map(|s| s.to_string()); + let artist = tag.artist().map(|s| s.to_string()); + let album = tag.album().map(|s| s.to_string()); + let cover = tag.pictures().first().map(|p| p.data().to_vec()); + let id3 = (input.extension().as_deref() == Some("mp3")) + .then(|| { + use lofty::file::AudioFile; + let mut file = input.open().ok()?; + lofty::mpeg::MpegFile::read_from(&mut file, lofty::config::ParseOptions::new()) + .ok()? + .id3v2() + .cloned() + }) + .flatten(); + let lyrics = crate::lyrics::read(&tagged, id3.as_ref()); + let year = tag.date().map(|d| d.year); + let chapters = crate::chapters::read(input, &tagged, id3.as_ref()); + if title.is_none() && cover.is_none() && lyrics.is_none() && chapters.is_empty() { + return Ok(None); + } + Ok(Some(Meta { title, artist, album, cover, lyrics, year, chapters })) +} diff --git a/crates/vector-gpui/reference/avatars/alice.png b/crates/vector-gpui/reference/avatars/alice.png new file mode 100644 index 000000000..4595ae027 Binary files /dev/null and b/crates/vector-gpui/reference/avatars/alice.png differ diff --git a/crates/vector-gpui/reference/avatars/bob.png b/crates/vector-gpui/reference/avatars/bob.png new file mode 100644 index 000000000..934e7a0f3 Binary files /dev/null and b/crates/vector-gpui/reference/avatars/bob.png differ diff --git a/crates/vector-gpui/reference/avatars/carol.png b/crates/vector-gpui/reference/avatars/carol.png new file mode 100644 index 000000000..cc5e58252 Binary files /dev/null and b/crates/vector-gpui/reference/avatars/carol.png differ diff --git a/crates/vector-gpui/reference/avatars/dave.png b/crates/vector-gpui/reference/avatars/dave.png new file mode 100644 index 000000000..550ac0406 Binary files /dev/null and b/crates/vector-gpui/reference/avatars/dave.png differ diff --git a/crates/vector-gpui/reference/avatars/erin.png b/crates/vector-gpui/reference/avatars/erin.png new file mode 100644 index 000000000..6f2b7c2d6 Binary files /dev/null and b/crates/vector-gpui/reference/avatars/erin.png differ diff --git a/crates/vector-gpui/reference/avatars/frank.png b/crates/vector-gpui/reference/avatars/frank.png new file mode 100644 index 000000000..74091fb27 Binary files /dev/null and b/crates/vector-gpui/reference/avatars/frank.png differ diff --git a/crates/vector-gpui/reference/avatars/grace.png b/crates/vector-gpui/reference/avatars/grace.png new file mode 100644 index 000000000..8d5533ee4 Binary files /dev/null and b/crates/vector-gpui/reference/avatars/grace.png differ diff --git a/crates/vector-gpui/reference/avatars/heidi.png b/crates/vector-gpui/reference/avatars/heidi.png new file mode 100644 index 000000000..1c560bc93 Binary files /dev/null and b/crates/vector-gpui/reference/avatars/heidi.png differ diff --git a/crates/vector-gpui/reference/capture.mjs b/crates/vector-gpui/reference/capture.mjs new file mode 100644 index 000000000..4f4b750f4 --- /dev/null +++ b/crates/vector-gpui/reference/capture.mjs @@ -0,0 +1,66 @@ +// Renders the Tauri frontend with the fixtures and saves a screenshot plus element boxes. +// node capture.mjs [width] [height] [script-after-boot.js] +import { createServer } from 'http'; +import { readFileSync, existsSync, statSync, writeFileSync } from 'fs'; +import { join, extname, dirname } from 'path'; +import { fileURLToPath } from 'url'; +import { createRequire } from 'module'; +// require() honours NODE_PATH, so a global Playwright works too. +const { chromium } = createRequire(import.meta.url)('playwright'); + +const HERE = dirname(fileURLToPath(import.meta.url)); +const SRC = join(HERE, '..', '..', '..', 'src'); +const [out = 'ref', W = '385', H = '650', after] = process.argv.slice(2); +const TYPES = { '.html': 'text/html', '.js': 'text/javascript', '.css': 'text/css', '.svg': 'image/svg+xml', '.png': 'image/png', '.woff2': 'font/woff2', '.json': 'application/json', '.gif': 'image/gif', '.webp': 'image/webp' }; +const server = createServer((req, res) => { + let p = decodeURIComponent(new URL(req.url, 'http://x').pathname); + let file = p.startsWith('/__ref/') ? join(HERE, p.slice(7)) : join(SRC, p === '/' ? 'index.html' : p); + if (!existsSync(file) || statSync(file).isDirectory()) { res.writeHead(404); return res.end(); } + res.writeHead(200, { 'content-type': TYPES[extname(file)] || 'application/octet-stream' }); + res.end(readFileSync(file)); +}).listen(0); +const port = server.address().port; +const fixtures = JSON.parse(readFileSync(process.env.FIXTURES || join(HERE, 'fixtures.json'), 'utf8')); +// REQUESTS=: the last n chats lose our side, so they wait under Requests. +const requests = +process.env.REQUESTS || 0; +// CHATLIST_DEMO=1: pins and archived chats from the fixtures' demo block. +if (process.env.CHATLIST_DEMO) Object.assign(fixtures, fixtures.chatlist_demo); +// VOICE_DEMO=present|joined|video: who is in the Lounge's call, and (joined, video) our own session in it. +if (process.env.VOICE_DEMO) fixtures.voice = { + present: fixtures.voice_demo[process.env.VOICE_DEMO] || fixtures.voice_demo.present, + session: { joined: fixtures.voice_demo.session, video: fixtures.voice_demo.session_video }[process.env.VOICE_DEMO] || null, +}; +// PINS_DEMO=1: the general channel's pins. +if (process.env.PINS_DEMO) fixtures.pins = fixtures.pins_demo; +if (requests) for (const chat of fixtures.chats.slice(-requests)) chat.messages = chat.messages.filter((m) => !m.mine); + +const browser = await chromium.launch(); +const page = await browser.newPage({ viewport: { width: +W, height: +H }, deviceScaleFactor: 1 }); +await page.clock.install({ time: fixtures.now }); +await page.clock.resume(); +const logs = []; +page.on('console', (m) => { if (m.type() === 'error' || m.type() === 'warning') logs.push(`[${m.type()}] ${m.text()}`); }); +page.on('pageerror', (e) => logs.push(`[pageerror] ${e.message}`)); +await page.addInitScript(`window.__VECTOR_FIXTURES__ = ${JSON.stringify(fixtures)};`); +await page.addInitScript(`window.__OPEN_NAME__ = ${JSON.stringify(process.env.OPEN || '')};`); +await page.addInitScript(`window.__CREATOR__ = ${JSON.stringify(process.env.CREATOR || "")};`); +await page.addInitScript(`window.__TYPE__ = ${JSON.stringify(process.env.TYPE || "")};`); +await page.addInitScript(`window.__NET__ = ${JSON.stringify(process.env.NET_DEMO || "")};`); +await page.addInitScript(`window.__REF_TRANSCRIPT__ = ${JSON.stringify(!!process.env.TRANSCRIPT)};`); +await page.addInitScript(`window.__ROW__ = ${JSON.stringify(process.env.ROW || "")};`); +await page.addInitScript(`window.__MOCK_MODE__ = ${JSON.stringify(process.env.MOCK_MODE || 'app')};`); +await page.addInitScript({ path: join(HERE, 'mock-tauri.js') }); +await page.goto(`http://localhost:${port}/`); +await page.waitForTimeout(2500); +if (after) { await page.evaluate(readFileSync(after, 'utf8')); await page.waitForTimeout(+(process.env.WAIT || 1500)); } +// MOUSE=x,y[;x,y…]: pointer moves after the script, each given a moment. +for (const p of (process.env.MOUSE || '').split(';').filter(Boolean)) { const [x, y] = p.split(',').map(Number); await page.mouse.move(x, y, { steps: 4 }); await page.waitForTimeout(400); } +await page.screenshot({ path: `${out}.png` }); +const boxes = await page.evaluate(() => { + const pick = [...document.querySelectorAll('body *')].filter((e) => { const r = e.getBoundingClientRect(); const s = getComputedStyle(e); return r.width > 0 && r.height > 0 && s.visibility !== 'hidden' && s.display !== 'none' && r.bottom > 0 && r.top < innerHeight; }); + return pick.slice(0, 1500).map((e) => { const r = e.getBoundingClientRect(); const s = getComputedStyle(e); return { tag: e.tagName.toLowerCase(), id: e.id || undefined, cls: (typeof e.className === 'string' ? e.className : '') || undefined, x: +r.x.toFixed(1), y: +r.y.toFixed(1), w: +r.width.toFixed(1), h: +r.height.toFixed(1), font: `${s.fontWeight} ${s.fontSize}/${s.lineHeight} ${s.fontFamily.split(',')[0]}`, color: s.color, bg: s.backgroundColor !== 'rgba(0, 0, 0, 0)' ? s.backgroundColor : undefined, radius: s.borderRadius !== '0px' ? s.borderRadius : undefined, border: ['Top','Right','Bottom','Left'].map((d) => s['border'+d+'Width'] !== '0px' ? `${d[0]}:${s['border'+d+'Width']} ${s['border'+d+'Color']}` : '').filter(Boolean).join(' ') || undefined, opacity: s.opacity !== '1' ? s.opacity : undefined, shadow: s.boxShadow !== 'none' ? s.boxShadow : undefined, text: e.children.length === 0 ? (e.textContent || '').trim().slice(0, 40) || undefined : undefined }; }); +}); +writeFileSync(`${out}.boxes.json`, JSON.stringify(boxes, null, 0).replace(/\},\{/g, '},\n{')); +writeFileSync(`${out}.log`, [...logs, 'missed: ' + (await page.evaluate(() => window.__mockMissed.join(' ')))].join('\n')); +await browser.close(); server.close(); +console.log(`${out}.png (${boxes.length} boxes, ${logs.length} console problems)`); diff --git a/crates/vector-gpui/reference/comm-menu.js b/crates/vector-gpui/reference/comm-menu.js new file mode 100644 index 000000000..722138c7b --- /dev/null +++ b/crates/vector-gpui/reference/comm-menu.js @@ -0,0 +1,15 @@ +// Opens Vector Devs, then its header menu; window.__PICK__ names a menu item to click after. +(async () => { + const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); + const row = [...document.querySelectorAll('.ws-rail-item')].find((e) => e.textContent.includes('Vector Devs')); + row?.click(); + await sleep(600); + document.querySelector('#chatlist-community-head')?.click(); + await sleep(500); + if (window.__PICK__) { + const item = [...document.querySelectorAll('.context-menu-item, .context-menu button, [role=menuitem]')].find((e) => e.textContent.trim().startsWith(window.__PICK__)); + for (const t of ['pointerdown', 'mousedown', 'pointerup', 'mouseup']) item?.dispatchEvent(new PointerEvent(t, { bubbles: true })); + item?.click(); + await sleep(600); + } +})(); diff --git a/crates/vector-gpui/reference/compare.py b/crates/vector-gpui/reference/compare.py new file mode 100644 index 000000000..ee48baa8d --- /dev/null +++ b/crates/vector-gpui/reference/compare.py @@ -0,0 +1,23 @@ +#!/usr/bin/env python3 +"""Side-by-side of a Tauri reference render and a vector-gpui render, plus their difference. + compare.py ref.png gpui.png out.png [crop x,y,w,h]""" +import sys +from PIL import Image, ImageChops, ImageDraw + +ref, ours, out = (Image.open(p).convert('RGB') for p in sys.argv[1:3]), None, sys.argv[3] +ref, ours = list(ref) +if len(sys.argv) > 4: + x, y, w, h = map(int, sys.argv[4].split(',')) + ref, ours = ref.crop((x, y, x + w, y + h)), ours.crop((x, y, x + w, y + h)) +ours = ours.resize(ref.size) if ours.size != ref.size else ours +diff = ImageChops.difference(ref, ours).convert('L') +mask = diff.point(lambda v: 255 if v > 24 else 0) +heat = Image.composite(Image.new('RGB', ref.size, (255, 40, 120)), ref.point(lambda v: v // 3), mask) +w, h = ref.size +sheet = Image.new('RGB', (w * 3 + 20, h + 22), (40, 40, 40)) +for i, (img, label) in enumerate([(ref, 'Tauri'), (ours, 'GPUI'), (heat, 'diff')]): + sheet.paste(img, (i * (w + 10), 22)) + ImageDraw.Draw(sheet).text((i * (w + 10) + 4, 4), label, fill=(230, 230, 230)) +sheet.save(out) +off = mask.histogram()[255] +print(f'{out}: {100 * off / (w * h):.2f}% of pixels differ by more than 24/255') diff --git a/crates/vector-gpui/reference/compose-deco.js b/crates/vector-gpui/reference/compose-deco.js new file mode 100644 index 000000000..c21cca50f --- /dev/null +++ b/crates/vector-gpui/reference/compose-deco.js @@ -0,0 +1,11 @@ +// Opens OPEN and types decorated source into the composer: a tag, then each markdown style. +(async () => { + const rows = [...document.querySelectorAll('.chatlist-contact')]; + rows.find((r) => r.textContent.trim().toLowerCase().startsWith(window.__OPEN_NAME__))?.click(); + await new Promise((r) => setTimeout(r, 800)); + composerMentionLookup = () => [{ name: 'dave', npub: 'npub1v84qsqlcs56j8dmh6s22eccnpn2d87fdutxhl7rftseh67wzamhqfv9ft6' }]; + const input = domChatMessageInput; + input.focus(); + input.value = 'Hey @dave **bold** _it_ ~~gone~~ `code` ||secret|| ok'; + input.dispatchEvent(new Event('input', { bubbles: true })); +})(); diff --git a/crates/vector-gpui/reference/fixtures-invite.json b/crates/vector-gpui/reference/fixtures-invite.json new file mode 100644 index 000000000..33c2175cf --- /dev/null +++ b/crates/vector-gpui/reference/fixtures-invite.json @@ -0,0 +1,1776 @@ +{ + "now": 1794362400000, + "npub": "npub1yazve5gvw5em6um2mzg0nh2u4v4dkfas04gqh9yn72wdcssvktsqfmmmv4", + "profiles": [ + { + "id": "npub1yazve5gvw5em6um2mzg0nh2u4v4dkfas04gqh9yn72wdcssvktsqfmmmv4", + "name": "jskitty", + "display_name": "JSKitty", + "nickname": "", + "lud06": "", + "lud16": "", + "banner": "", + "avatar": "", + "about": "", + "website": "", + "nip05": "", + "status": { + "title": "", + "purpose": "", + "url": "" + }, + "last_updated": 1794362400, + "mine": true, + "bot": false, + "is_blocked": false, + "avatar_cached": "", + "banner_cached": "", + "stream_consent": false + }, + { + "id": "npub190vqdjtlpcq27xslcveglfmr4ynfwg7gmw86cnun4acakxrdd6gqnp929a", + "name": "alice", + "display_name": "Alice", + "nickname": "", + "lud06": "", + "lud16": "", + "banner": "", + "avatar": "https://example.invalid/alice.png", + "about": "", + "website": "", + "nip05": "", + "status": { + "title": "", + "purpose": "", + "url": "" + }, + "last_updated": 1794362400, + "mine": false, + "bot": false, + "is_blocked": false, + "avatar_cached": "avatars/alice.png", + "banner_cached": "", + "stream_consent": false + }, + { + "id": "npub1sxmr0k8u6trd5c6eu6trzyapzux7090ykujmsng7pdx0m8k93n5sd02fwn", + "name": "bob", + "display_name": "Bob Nakamoto", + "nickname": "", + "lud06": "", + "lud16": "", + "banner": "https://example.invalid/bob-banner.png", + "avatar": "https://example.invalid/bob.png", + "about": "Building on Nostr since 2021.\nCoffee first, relays second ⚡", + "website": "", + "nip05": "", + "status": { + "title": "Shipping v0.6 🚀", + "purpose": "general", + "url": "" + }, + "last_updated": 1794362400, + "mine": false, + "bot": false, + "is_blocked": false, + "avatar_cached": "avatars/bob.png", + "banner_cached": "media/photo.png", + "stream_consent": false + }, + { + "id": "npub1fsndjp6vylvfahjeyuxq4s2tw8s8rv2j89ge7a28fvhnhf35s86sg3uctf", + "name": "carol", + "display_name": "Carol", + "nickname": "", + "lud06": "", + "lud16": "", + "banner": "", + "avatar": "https://example.invalid/carol.png", + "about": "", + "website": "", + "nip05": "", + "status": { + "title": "", + "purpose": "", + "url": "" + }, + "last_updated": 1794362400, + "mine": false, + "bot": false, + "is_blocked": false, + "avatar_cached": "avatars/carol.png", + "banner_cached": "", + "stream_consent": false + }, + { + "id": "npub1v84qsqlcs56j8dmh6s22eccnpn2d87fdutxhl7rftseh67wzamhqfv9ft6", + "name": "dave", + "display_name": "Dave the Builder", + "nickname": "", + "lud06": "", + "lud16": "", + "banner": "", + "avatar": "https://example.invalid/dave.png", + "about": "", + "website": "", + "nip05": "", + "status": { + "title": "", + "purpose": "", + "url": "" + }, + "last_updated": 1794362400, + "mine": false, + "bot": false, + "is_blocked": false, + "avatar_cached": "avatars/dave.png", + "banner_cached": "", + "stream_consent": false + }, + { + "id": "npub10j7vkrzv4t0elnd4rmj902pge3e2gkresvd4h9u2ut3valzyjuzsz7ad26", + "name": "erin", + "display_name": "Erin", + "nickname": "", + "lud06": "", + "lud16": "", + "banner": "", + "avatar": "https://example.invalid/erin.png", + "about": "", + "website": "", + "nip05": "", + "status": { + "title": "", + "purpose": "", + "url": "" + }, + "last_updated": 1794362400, + "mine": false, + "bot": false, + "is_blocked": false, + "avatar_cached": "avatars/erin.png", + "banner_cached": "", + "stream_consent": false + }, + { + "id": "npub1wajx7kj0x9nxxa38405e3eapgu87wtvtgv8svld04p3x8u0j872qnta00x", + "name": "frank", + "display_name": "Frank", + "nickname": "", + "lud06": "", + "lud16": "", + "banner": "", + "avatar": "https://example.invalid/frank.png", + "about": "", + "website": "", + "nip05": "", + "status": { + "title": "", + "purpose": "", + "url": "" + }, + "last_updated": 1794362400, + "mine": false, + "bot": false, + "is_blocked": false, + "avatar_cached": "avatars/frank.png", + "banner_cached": "", + "stream_consent": false + }, + { + "id": "npub1uqg0688p4nqh8ca5sddhvd0c63sq6a6gdygz4k6uk76a0z2kfxaqmmg7t4", + "name": "grace", + "display_name": "Grace Hopper", + "nickname": "", + "lud06": "", + "lud16": "", + "banner": "", + "avatar": "https://example.invalid/grace.png", + "about": "", + "website": "", + "nip05": "", + "status": { + "title": "", + "purpose": "", + "url": "" + }, + "last_updated": 1794362400, + "mine": false, + "bot": false, + "is_blocked": false, + "avatar_cached": "avatars/grace.png", + "banner_cached": "", + "stream_consent": false + }, + { + "id": "npub1qk3nrfl57xffl2k29zdxd7vdtgzm8p7ee045lrpdmqsy56cz8g2qqxdt9s", + "name": "heidi", + "display_name": "Heidi", + "nickname": "", + "lud06": "", + "lud16": "", + "banner": "", + "avatar": "https://example.invalid/heidi.png", + "about": "", + "website": "", + "nip05": "", + "status": { + "title": "", + "purpose": "", + "url": "" + }, + "last_updated": 1794362400, + "mine": false, + "bot": false, + "is_blocked": false, + "avatar_cached": "avatars/heidi.png", + "banner_cached": "", + "stream_consent": false + }, + { + "id": "npub15387nevpzd0u700y2t24ym9l0zxe8fsxx2w7qn47ysn6mndn9gvqqmlahu", + "name": "vee", + "display_name": "Vee", + "nickname": "", + "lud06": "", + "lud16": "", + "banner": "", + "avatar": "https://example.invalid/alice.png", + "about": "", + "website": "", + "nip05": "", + "status": { + "title": "", + "purpose": "", + "url": "" + }, + "last_updated": 1794362400, + "mine": false, + "bot": false, + "is_blocked": false, + "avatar_cached": "avatars/alice.png", + "banner_cached": "", + "stream_consent": false + }, + { + "id": "npub17jjvuhaxxs9rt2jakz6td5c6d7a2vpfr2erqmwc9xajhmqplt03q63stmv", + "name": "mo", + "display_name": "Mo", + "nickname": "", + "lud06": "", + "lud16": "", + "banner": "", + "avatar": "https://example.invalid/grace.png", + "about": "", + "website": "", + "nip05": "", + "status": { + "title": "", + "purpose": "", + "url": "" + }, + "last_updated": 1794362400, + "mine": false, + "bot": false, + "is_blocked": false, + "avatar_cached": "avatars/grace.png", + "banner_cached": "", + "stream_consent": false + }, + { + "id": "npub19ayt3q02wpelr3hsswefdgmqh4xfeag7m2kt58xecdxc4c7ejnkq92s7dr", + "name": "lin", + "display_name": "Lin", + "nickname": "", + "lud06": "", + "lud16": "", + "banner": "", + "avatar": "https://example.invalid/bob.png", + "about": "", + "website": "", + "nip05": "", + "status": { + "title": "", + "purpose": "", + "url": "" + }, + "last_updated": 1794362400, + "mine": false, + "bot": false, + "is_blocked": false, + "avatar_cached": "avatars/bob.png", + "banner_cached": "", + "stream_consent": false + } + ], + "chats": [ + { + "id": "npub17jjvuhaxxs9rt2jakz6td5c6d7a2vpfr2erqmwc9xajhmqplt03q63stmv", + "chat_type": "DirectMessage", + "participants": [ + "npub17jjvuhaxxs9rt2jakz6td5c6d7a2vpfr2erqmwc9xajhmqplt03q63stmv" + ], + "messages": [ + { + "id": "4ea02ec455165f1c969e1dada2376504061579f9493eecd1e5c9c2db25cd6a72", + "content": "Look at this sunset", + "replied_to": "", + "preview_metadata": null, + "attachments": [ + { + "id": "3c347d8660df388374fbb5c2dcf925ad0140321118943c11980d6f654e6032cc", + "key": "", + "nonce": "", + "extension": "png", + "name": "", + "url": "https://example.invalid/photo", + "path": "media/photo.png", + "size": 170552, + "img_meta": { + "thumbhash": "U(^ /twg4<&F@NQS~xhD@CSA", + "width": 1600, + "height": 1000 + }, + "downloading": false, + "downloaded": true + } + ], + "reactions": [], + "at": 1794359280000, + "pending": false, + "failed": false, + "mine": false, + "npub": "npub17jjvuhaxxs9rt2jakz6td5c6d7a2vpfr2erqmwc9xajhmqplt03q63stmv", + "edited": false + }, + { + "id": "6c2c34d5ddfb1e38ab0a04a0cefdad531df3e6842d71bc129fc499edcaacc7d2", + "content": "", + "replied_to": "", + "preview_metadata": null, + "attachments": [ + { + "id": "a30b567bc5ffc67f0b27fb734b72684405d29cc58802f8c84fd1e697e3bed61e", + "key": "", + "nonce": "", + "extension": "png", + "name": "", + "url": "https://example.invalid/portrait", + "path": "", + "size": 24117248, + "img_meta": { + "thumbhash": "6%fXoBL7P(`cp*l1#)iQt/q;6h", + "width": 700, + "height": 1000 + }, + "downloading": false, + "downloaded": false + } + ], + "reactions": [], + "at": 1794359880000, + "pending": false, + "failed": false, + "mine": true, + "npub": "npub1yazve5gvw5em6um2mzg0nh2u4v4dkfas04gqh9yn72wdcssvktsqfmmmv4", + "edited": false + }, + { + "id": "76228bc2fc2f34503ca5c91c453e655ea233a85680896aae056e74805681e137", + "content": "", + "replied_to": "", + "preview_metadata": null, + "attachments": [ + { + "id": "3549e7ac429efad0ee75535ec93ea7ef1aa7f8b9b24d2de064a0a1d7e0017599", + "key": "", + "nonce": "", + "extension": "png", + "name": "SPOILER_sticker.png", + "url": "https://example.invalid/sticker", + "path": "media/sticker.png", + "size": 15319, + "img_meta": { + "thumbhash": "HUN*`C9p<)MJbF6vQY^LC_$qYVyrBA", + "width": 220, + "height": 220 + }, + "downloading": false, + "downloaded": true + } + ], + "reactions": [], + "at": 1794360480000, + "pending": false, + "failed": false, + "mine": false, + "npub": "npub17jjvuhaxxs9rt2jakz6td5c6d7a2vpfr2erqmwc9xajhmqplt03q63stmv", + "edited": false + }, + { + "id": "90ea00dec631e38520b6d323b806ef549167f40d914d997c85c09663648d0f2b", + "content": "The spec, and the build", + "replied_to": "", + "preview_metadata": null, + "attachments": [ + { + "id": "b336680d9d206af3b937b99b899fb1896886728823a9f96ca4b98f9227b64a92", + "key": "", + "nonce": "", + "extension": "pdf", + "name": "Vector Protocol Spec.pdf", + "url": "https://example.invalid/spec", + "path": "", + "size": 13002342, + "img_meta": null, + "downloading": false, + "downloaded": false + }, + { + "id": "1ece496bf8a0b989f1630ba7425eb5daff5054bc8c27df76be4cb7b5977e7f97", + "key": "", + "nonce": "", + "extension": "zip", + "name": "vector-0.5.1-linux.zip", + "url": "https://example.invalid/build", + "path": "media/sticker.png", + "size": 48234496, + "img_meta": null, + "downloading": false, + "downloaded": true + } + ], + "reactions": [], + "at": 1794361080000, + "pending": false, + "failed": false, + "mine": false, + "npub": "npub17jjvuhaxxs9rt2jakz6td5c6d7a2vpfr2erqmwc9xajhmqplt03q63stmv", + "edited": false + }, + { + "id": "2bdaad8f7f7f63f749a37d97e109d72300424e5ca39d1b623d8b717de7802d08", + "content": "Thanks!", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1794361980000, + "pending": false, + "failed": false, + "mine": true, + "npub": "npub1yazve5gvw5em6um2mzg0nh2u4v4dkfas04gqh9yn72wdcssvktsqfmmmv4", + "edited": false + } + ], + "last_read": "2bdaad8f7f7f63f749a37d97e109d72300424e5ca39d1b623d8b717de7802d08", + "unread_from": "", + "created_at": 1794275880, + "metadata": { + "custom_fields": {} + }, + "muted": false, + "notify": 2, + "everyone_pings": true, + "community_muted": false + }, + { + "id": "npub15387nevpzd0u700y2t24ym9l0zxe8fsxx2w7qn47ysn6mndn9gvqqmlahu", + "chat_type": "DirectMessage", + "participants": [ + "npub15387nevpzd0u700y2t24ym9l0zxe8fsxx2w7qn47ysn6mndn9gvqqmlahu" + ], + "messages": [ + { + "id": "46160c560d01fcd55bc718f8adef022d010f02cc27d8a1c9e066c8ae61f1f4b4", + "content": "Have you tried the **new** markdown? It handles *italics*, ~~strikes~~ and `inline code`.", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1794268740000, + "pending": false, + "failed": false, + "mine": false, + "npub": "npub15387nevpzd0u700y2t24ym9l0zxe8fsxx2w7qn47ysn6mndn9gvqqmlahu", + "edited": false + }, + { + "id": "29e4fd18155e79dd760d101aca6abae460e8662b34ccf9bdaf9edd8e3b7a18b6", + "content": "Lists too:\n- one\n- two\n- three", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1794268800000, + "pending": false, + "failed": false, + "mine": false, + "npub": "npub15387nevpzd0u700y2t24ym9l0zxe8fsxx2w7qn47ysn6mndn9gvqqmlahu", + "edited": false + }, + { + "id": "f5e8a64a4803fd9cf5c2f2cc23eb5a66b6126982b1394d53195b86220dda9ed3", + "content": "> quoting you here\nand replying below the quote", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [ + { + "id": "d989534175d49bdce27c894467617cf954aa81994482cb551c63b8fe08918b5a", + "reference_id": "f5e8a64a4803fd9cf5c2f2cc23eb5a66b6126982b1394d53195b86220dda9ed3", + "author_id": "npub15387nevpzd0u700y2t24ym9l0zxe8fsxx2w7qn47ysn6mndn9gvqqmlahu", + "emoji": "❤️" + }, + { + "id": "78e8fce8c1f9dce779d3287be6a7ec18f29ebbe3a0386710d569e62dbd2da183", + "reference_id": "f5e8a64a4803fd9cf5c2f2cc23eb5a66b6126982b1394d53195b86220dda9ed3", + "author_id": "npub1yazve5gvw5em6um2mzg0nh2u4v4dkfas04gqh9yn72wdcssvktsqfmmmv4", + "emoji": "❤️" + }, + { + "id": "06320cad2867c2713b524fa38138aa146bf402abd91c54d1f7eae469adc8187c", + "reference_id": "f5e8a64a4803fd9cf5c2f2cc23eb5a66b6126982b1394d53195b86220dda9ed3", + "author_id": "npub15387nevpzd0u700y2t24ym9l0zxe8fsxx2w7qn47ysn6mndn9gvqqmlahu", + "emoji": "😂" + } + ], + "at": 1794268920000, + "pending": false, + "failed": false, + "mine": true, + "npub": "npub1yazve5gvw5em6um2mzg0nh2u4v4dkfas04gqh9yn72wdcssvktsqfmmmv4", + "edited": false + }, + { + "id": "9224c65fb1c0fa757b5f2b9f069eb1ef3a888b071604a532eb0a22ddf4bbe1db", + "content": "```rust\nfn main() {\n println!(\"hello\");\n}\n```", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1794268980000, + "pending": false, + "failed": false, + "mine": true, + "npub": "npub1yazve5gvw5em6um2mzg0nh2u4v4dkfas04gqh9yn72wdcssvktsqfmmmv4", + "edited": false + }, + { + "id": "12a8715a08bb5cf5558c3e30e350beb05103f589af9ef0f894481c2c93cf58bf", + "content": "Nice! That one has a ||secret spoiler|| inside, and a [link](https://vectorapp.io).", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1794360540000, + "pending": false, + "failed": false, + "mine": false, + "npub": "npub15387nevpzd0u700y2t24ym9l0zxe8fsxx2w7qn47ysn6mndn9gvqqmlahu", + "edited": true + }, + { + "id": "f20c550ac443c1caf754848c6e70ebf4c46375e864ed7b1595b10f86f3ece07a", + "content": "# A heading\n-# and some subtext", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1794360600000, + "pending": false, + "failed": false, + "mine": false, + "npub": "npub15387nevpzd0u700y2t24ym9l0zxe8fsxx2w7qn47ysn6mndn9gvqqmlahu", + "edited": false + }, + { + "id": "45593079abe5d2bad5a8311b974a1ce700bd7933fa79e86f2ec32d0ec977b569", + "content": "Replying to that heading", + "replied_to": "f20c550ac443c1caf754848c6e70ebf4c46375e864ed7b1595b10f86f3ece07a", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1794361740000, + "pending": false, + "failed": false, + "mine": true, + "npub": "npub1yazve5gvw5em6um2mzg0nh2u4v4dkfas04gqh9yn72wdcssvktsqfmmmv4", + "edited": false, + "replied_to_content": "# A heading\n-# and some subtext", + "replied_to_npub": "npub15387nevpzd0u700y2t24ym9l0zxe8fsxx2w7qn47ysn6mndn9gvqqmlahu" + }, + { + "id": "0334355612cd1b65f5c35f87e405a17bb0d60854077fb7fde302fc92fcedd230", + "content": "This one is still sending", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1794362220000, + "pending": true, + "failed": false, + "mine": true, + "npub": "npub1yazve5gvw5em6um2mzg0nh2u4v4dkfas04gqh9yn72wdcssvktsqfmmmv4", + "edited": false + }, + { + "id": "bb49ca62931ae9d7d12f0641cacd899649c3975713d350c513db4fc027d504eb", + "content": "And this one failed", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1794362280000, + "pending": false, + "failed": true, + "mine": true, + "npub": "npub1yazve5gvw5em6um2mzg0nh2u4v4dkfas04gqh9yn72wdcssvktsqfmmmv4", + "edited": false + }, + { + "id": "c045acf2d273a786b030c9bc52f82e5208621ae4f0f7400c6ed71f088498e0d3", + "content": "👍", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [ + { + "id": "c14e0ecfd58555fc3a9db5e78aa7c771b69b7ca246b1a388a2d342ee3ccb1cc9", + "reference_id": "c045acf2d273a786b030c9bc52f82e5208621ae4f0f7400c6ed71f088498e0d3", + "author_id": "npub1yazve5gvw5em6um2mzg0nh2u4v4dkfas04gqh9yn72wdcssvktsqfmmmv4", + "emoji": "🔥" + } + ], + "at": 1794362340000, + "pending": false, + "failed": false, + "mine": false, + "npub": "npub15387nevpzd0u700y2t24ym9l0zxe8fsxx2w7qn47ysn6mndn9gvqqmlahu", + "edited": false + } + ], + "last_read": "c045acf2d273a786b030c9bc52f82e5208621ae4f0f7400c6ed71f088498e0d3", + "unread_from": "", + "created_at": 1794189540, + "metadata": { + "custom_fields": {} + }, + "muted": false, + "notify": 2, + "everyone_pings": true, + "community_muted": false + }, + { + "id": "npub190vqdjtlpcq27xslcveglfmr4ynfwg7gmw86cnun4acakxrdd6gqnp929a", + "chat_type": "DirectMessage", + "participants": [ + "npub190vqdjtlpcq27xslcveglfmr4ynfwg7gmw86cnun4acakxrdd6gqnp929a" + ], + "messages": [ + { + "id": "8151ec931604feccea39c49138f698e832871901bfe95d7e8e1278836da509cd", + "content": "Hey! It's Alice", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1794359280000, + "pending": false, + "failed": false, + "mine": false, + "npub": "npub190vqdjtlpcq27xslcveglfmr4ynfwg7gmw86cnun4acakxrdd6gqnp929a", + "edited": false + }, + { + "id": "a42ac5108869b599bcbac21069f63fb47f07452fcc4b87e89b3c06a945612d0b", + "content": "Hey, how are you doing?", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1794359400000, + "pending": false, + "failed": false, + "mine": true, + "npub": "npub1yazve5gvw5em6um2mzg0nh2u4v4dkfas04gqh9yn72wdcssvktsqfmmmv4", + "edited": false + }, + { + "id": "e9969eb8667d15372c967cfe5402b12ecb4b64a8c563088ca80237ff5ecf83d5", + "content": "Pretty good, working on something fun.", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1794359580000, + "pending": false, + "failed": false, + "mine": false, + "npub": "npub190vqdjtlpcq27xslcveglfmr4ynfwg7gmw86cnun4acakxrdd6gqnp929a", + "edited": false + }, + { + "id": "532819ebaebe89404671ee38eefd39495c7ec8342347bc31de2c67d55229ce4a", + "content": "Ooh, tell me more when you can 👀", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1794359640000, + "pending": false, + "failed": false, + "mine": true, + "npub": "npub1yazve5gvw5em6um2mzg0nh2u4v4dkfas04gqh9yn72wdcssvktsqfmmmv4", + "edited": false + }, + { + "id": "d402d566b92e2040b3378d4cad8f136f2790f973143ef12b857148cab29dea11", + "content": "Running late, save me a seat!", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1794362280000, + "pending": false, + "failed": false, + "mine": false, + "npub": "npub190vqdjtlpcq27xslcveglfmr4ynfwg7gmw86cnun4acakxrdd6gqnp929a", + "edited": false + } + ], + "last_read": "a42ac5108869b599bcbac21069f63fb47f07452fcc4b87e89b3c06a945612d0b", + "unread_from": "", + "created_at": 1794358680, + "metadata": { + "custom_fields": {} + }, + "muted": false, + "notify": 2, + "everyone_pings": true, + "community_muted": false + }, + { + "id": "npub1sxmr0k8u6trd5c6eu6trzyapzux7090ykujmsng7pdx0m8k93n5sd02fwn", + "chat_type": "DirectMessage", + "participants": [ + "npub1sxmr0k8u6trd5c6eu6trzyapzux7090ykujmsng7pdx0m8k93n5sd02fwn" + ], + "messages": [ + { + "id": "0e7dcc98d6c20f8d5560821e454650cb0f8b7e07accecf1547bde134a467624d", + "content": "Hey! It's Bob", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1794357900000, + "pending": false, + "failed": false, + "mine": false, + "npub": "npub1sxmr0k8u6trd5c6eu6trzyapzux7090ykujmsng7pdx0m8k93n5sd02fwn", + "edited": false + }, + { + "id": "a5fc3eac9107fe9b449965916d54b334233b8077a37f782d9b59e6e98e04def8", + "content": "Hey, how are you doing?", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1794358020000, + "pending": false, + "failed": false, + "mine": true, + "npub": "npub1yazve5gvw5em6um2mzg0nh2u4v4dkfas04gqh9yn72wdcssvktsqfmmmv4", + "edited": false + }, + { + "id": "a9137698d8d3fdbf27efcdc8cd372084b52d484e8db866c5455bbb3f85299b54", + "content": "Pretty good, working on something fun.", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1794358200000, + "pending": false, + "failed": false, + "mine": false, + "npub": "npub1sxmr0k8u6trd5c6eu6trzyapzux7090ykujmsng7pdx0m8k93n5sd02fwn", + "edited": false + }, + { + "id": "a6a17c7ac82f305add533b6fa9860dee624d3df3ac3745a5007ea24ca2047f6a", + "content": "Ooh, tell me more when you can 👀", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1794358260000, + "pending": false, + "failed": false, + "mine": true, + "npub": "npub1yazve5gvw5em6um2mzg0nh2u4v4dkfas04gqh9yn72wdcssvktsqfmmmv4", + "edited": false + }, + { + "id": "598b288443e42c9a93f5562409ac78c385fe4d66c95174330c4805b79fa67f52", + "content": "The new build is so much faster 🚀", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1794360900000, + "pending": false, + "failed": false, + "mine": false, + "npub": "npub1sxmr0k8u6trd5c6eu6trzyapzux7090ykujmsng7pdx0m8k93n5sd02fwn", + "edited": false + } + ], + "last_read": "598b288443e42c9a93f5562409ac78c385fe4d66c95174330c4805b79fa67f52", + "unread_from": "", + "created_at": 1794357300, + "metadata": { + "custom_fields": {} + }, + "muted": false, + "notify": 2, + "everyone_pings": true, + "community_muted": false + }, + { + "id": "npub1fsndjp6vylvfahjeyuxq4s2tw8s8rv2j89ge7a28fvhnhf35s86sg3uctf", + "chat_type": "DirectMessage", + "participants": [ + "npub1fsndjp6vylvfahjeyuxq4s2tw8s8rv2j89ge7a28fvhnhf35s86sg3uctf" + ], + "messages": [ + { + "id": "84d31f0608eb78e78d7f480dd0e99047ea64ab3546571b2cbe25aa40c5594d3e", + "content": "Hey! It's Carol", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1794348600000, + "pending": false, + "failed": false, + "mine": false, + "npub": "npub1fsndjp6vylvfahjeyuxq4s2tw8s8rv2j89ge7a28fvhnhf35s86sg3uctf", + "edited": false + }, + { + "id": "b52a4abe79e15521cfb98270bbb4df9a2180df897028e9ef5b2078fe898e3b86", + "content": "Hey, how are you doing?", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1794348720000, + "pending": false, + "failed": false, + "mine": true, + "npub": "npub1yazve5gvw5em6um2mzg0nh2u4v4dkfas04gqh9yn72wdcssvktsqfmmmv4", + "edited": false + }, + { + "id": "ccae70ef441818f6e600d906bb15f26822cd2c75f52236c669c78db9eef71d7b", + "content": "Pretty good, working on something fun.", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1794348900000, + "pending": false, + "failed": false, + "mine": false, + "npub": "npub1fsndjp6vylvfahjeyuxq4s2tw8s8rv2j89ge7a28fvhnhf35s86sg3uctf", + "edited": false + }, + { + "id": "af6f12698ed64974e2947593be116ca71c0abfbc0bd4614f55e383e3359bc386", + "content": "Ooh, tell me more when you can 👀", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1794348960000, + "pending": false, + "failed": false, + "mine": true, + "npub": "npub1yazve5gvw5em6um2mzg0nh2u4v4dkfas04gqh9yn72wdcssvktsqfmmmv4", + "edited": false + }, + { + "id": "fc9be69f77ac6387b476bf18eecac0d49e846462bf151d098b956d642c9257c4", + "content": "haha yes exactly", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1794351600000, + "pending": false, + "failed": false, + "mine": false, + "npub": "npub1fsndjp6vylvfahjeyuxq4s2tw8s8rv2j89ge7a28fvhnhf35s86sg3uctf", + "edited": false + } + ], + "last_read": "af6f12698ed64974e2947593be116ca71c0abfbc0bd4614f55e383e3359bc386", + "unread_from": "", + "created_at": 1794348000, + "metadata": { + "custom_fields": {} + }, + "muted": false, + "notify": 2, + "everyone_pings": true, + "community_muted": false + }, + { + "id": "npub1v84qsqlcs56j8dmh6s22eccnpn2d87fdutxhl7rftseh67wzamhqfv9ft6", + "chat_type": "DirectMessage", + "participants": [ + "npub1v84qsqlcs56j8dmh6s22eccnpn2d87fdutxhl7rftseh67wzamhqfv9ft6" + ], + "messages": [ + { + "id": "df3800172069679be70df9a4408362938ec13352f6965b4b6ae83e8b15ec4b7b", + "content": "Hey! It's Dave", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1794287400000, + "pending": false, + "failed": false, + "mine": false, + "npub": "npub1v84qsqlcs56j8dmh6s22eccnpn2d87fdutxhl7rftseh67wzamhqfv9ft6", + "edited": false + }, + { + "id": "b1b6970a41ecda3f826c36d4704439a99271fc68fa320d6de8a6770236bafca7", + "content": "Hey, how are you doing?", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1794287520000, + "pending": false, + "failed": false, + "mine": true, + "npub": "npub1yazve5gvw5em6um2mzg0nh2u4v4dkfas04gqh9yn72wdcssvktsqfmmmv4", + "edited": false + }, + { + "id": "256d5942571987a8f984f2a6de380b961f092da1367181c7f36815f322e092c8", + "content": "Pretty good, working on something fun.", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1794287700000, + "pending": false, + "failed": false, + "mine": false, + "npub": "npub1v84qsqlcs56j8dmh6s22eccnpn2d87fdutxhl7rftseh67wzamhqfv9ft6", + "edited": false + }, + { + "id": "0cd834c4a78e321bcf7377b9a94b89995fec1ec2c493563d6af759565ce3adb1", + "content": "Ooh, tell me more when you can 👀", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1794287760000, + "pending": false, + "failed": false, + "mine": true, + "npub": "npub1yazve5gvw5em6um2mzg0nh2u4v4dkfas04gqh9yn72wdcssvktsqfmmmv4", + "edited": false + }, + { + "id": "31fe2982dff7210a144b3af820a570e62650b652ecc1ca8a7a1c46c4360a1fcf", + "content": "Sent you the invoice", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1794290400000, + "pending": false, + "failed": false, + "mine": false, + "npub": "npub1v84qsqlcs56j8dmh6s22eccnpn2d87fdutxhl7rftseh67wzamhqfv9ft6", + "edited": false + } + ], + "last_read": "31fe2982dff7210a144b3af820a570e62650b652ecc1ca8a7a1c46c4360a1fcf", + "unread_from": "", + "created_at": 1794286800, + "metadata": { + "custom_fields": {} + }, + "muted": false, + "notify": 2, + "everyone_pings": true, + "community_muted": false + }, + { + "id": "npub10j7vkrzv4t0elnd4rmj902pge3e2gkresvd4h9u2ut3valzyjuzsz7ad26", + "chat_type": "DirectMessage", + "participants": [ + "npub10j7vkrzv4t0elnd4rmj902pge3e2gkresvd4h9u2ut3valzyjuzsz7ad26" + ], + "messages": [ + { + "id": "2dfc7f1fec2378642603513880c3d185c1d946c80fe462ddd746d9a966fee6c6", + "content": "Hey! It's Erin", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1794265800000, + "pending": false, + "failed": false, + "mine": false, + "npub": "npub10j7vkrzv4t0elnd4rmj902pge3e2gkresvd4h9u2ut3valzyjuzsz7ad26", + "edited": false + }, + { + "id": "fa66a85f397a2570a1bd24cc913ede2ae20e52760450debd2be0dc3e8264b6cf", + "content": "Hey, how are you doing?", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1794265920000, + "pending": false, + "failed": false, + "mine": true, + "npub": "npub1yazve5gvw5em6um2mzg0nh2u4v4dkfas04gqh9yn72wdcssvktsqfmmmv4", + "edited": false + }, + { + "id": "4d01f2c559d2131367694374a6d4b7c8d25406b9d288e441a97fa246b58b916e", + "content": "Pretty good, working on something fun.", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1794266100000, + "pending": false, + "failed": false, + "mine": false, + "npub": "npub10j7vkrzv4t0elnd4rmj902pge3e2gkresvd4h9u2ut3valzyjuzsz7ad26", + "edited": false + }, + { + "id": "6bb9076027cd5db478938eea32df3cd109814cd0842ee2130a86b2d30922fc5a", + "content": "Ooh, tell me more when you can 👀", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1794266160000, + "pending": false, + "failed": false, + "mine": true, + "npub": "npub1yazve5gvw5em6um2mzg0nh2u4v4dkfas04gqh9yn72wdcssvktsqfmmmv4", + "edited": false + }, + { + "id": "77ba0426a3e472fdc0b2d2037f5c274825b8c5a4b90a7b7e77c4d1b8d84d8be2", + "content": "Can you check the relay list later?", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1794268800000, + "pending": false, + "failed": false, + "mine": false, + "npub": "npub10j7vkrzv4t0elnd4rmj902pge3e2gkresvd4h9u2ut3valzyjuzsz7ad26", + "edited": false + } + ], + "last_read": "77ba0426a3e472fdc0b2d2037f5c274825b8c5a4b90a7b7e77c4d1b8d84d8be2", + "unread_from": "", + "created_at": 1794265200, + "metadata": { + "custom_fields": {} + }, + "muted": false, + "notify": 2, + "everyone_pings": true, + "community_muted": false + }, + { + "id": "npub1wajx7kj0x9nxxa38405e3eapgu87wtvtgv8svld04p3x8u0j872qnta00x", + "chat_type": "DirectMessage", + "participants": [ + "npub1wajx7kj0x9nxxa38405e3eapgu87wtvtgv8svld04p3x8u0j872qnta00x" + ], + "messages": [ + { + "id": "916d83f3c60ae97786062fd90dd4fa836778f764fec4d72b69707a9ae0497b9d", + "content": "Hey! It's Frank", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1794100200000, + "pending": false, + "failed": false, + "mine": false, + "npub": "npub1wajx7kj0x9nxxa38405e3eapgu87wtvtgv8svld04p3x8u0j872qnta00x", + "edited": false + }, + { + "id": "9f5f848bfd4eaec7636efa22c4fafc7f5ef5a3b3abcf69eecc0ca906945c821e", + "content": "Hey, how are you doing?", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1794100320000, + "pending": false, + "failed": false, + "mine": true, + "npub": "npub1yazve5gvw5em6um2mzg0nh2u4v4dkfas04gqh9yn72wdcssvktsqfmmmv4", + "edited": false + }, + { + "id": "0dd69c24d98198c02a74c49c23b00c3ebed2897d6b18bf3fa9e22377e0de17bd", + "content": "Pretty good, working on something fun.", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1794100500000, + "pending": false, + "failed": false, + "mine": false, + "npub": "npub1wajx7kj0x9nxxa38405e3eapgu87wtvtgv8svld04p3x8u0j872qnta00x", + "edited": false + }, + { + "id": "e1ea99b2aa44648632472ac1ba8b433fb7792a754edbe16bb4104676c60aeb32", + "content": "Ooh, tell me more when you can 👀", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1794100560000, + "pending": false, + "failed": false, + "mine": true, + "npub": "npub1yazve5gvw5em6um2mzg0nh2u4v4dkfas04gqh9yn72wdcssvktsqfmmmv4", + "edited": false + }, + { + "id": "701941eb2099073cce5789d43667b92d69aeed4c279da1bcc248cb18ea08a203", + "content": "gm", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1794103200000, + "pending": false, + "failed": false, + "mine": false, + "npub": "npub1wajx7kj0x9nxxa38405e3eapgu87wtvtgv8svld04p3x8u0j872qnta00x", + "edited": false + } + ], + "last_read": "701941eb2099073cce5789d43667b92d69aeed4c279da1bcc248cb18ea08a203", + "unread_from": "", + "created_at": 1794099600, + "metadata": { + "custom_fields": {} + }, + "muted": false, + "notify": 2, + "everyone_pings": true, + "community_muted": false + }, + { + "id": "npub1uqg0688p4nqh8ca5sddhvd0c63sq6a6gdygz4k6uk76a0z2kfxaqmmg7t4", + "chat_type": "DirectMessage", + "participants": [ + "npub1uqg0688p4nqh8ca5sddhvd0c63sq6a6gdygz4k6uk76a0z2kfxaqmmg7t4" + ], + "messages": [ + { + "id": "50b5f31dfb00f33f086e1ae2abc4438be0a843062a9ba57e320d341c5fbcd145", + "content": "Hey! It's Grace", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1793581800000, + "pending": false, + "failed": false, + "mine": false, + "npub": "npub1uqg0688p4nqh8ca5sddhvd0c63sq6a6gdygz4k6uk76a0z2kfxaqmmg7t4", + "edited": false + }, + { + "id": "46fdae29620a12a9aacbbc73f5fc7aeb4eb997d686bfb289be1dae882cfb61e0", + "content": "Hey, how are you doing?", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1793581920000, + "pending": false, + "failed": false, + "mine": true, + "npub": "npub1yazve5gvw5em6um2mzg0nh2u4v4dkfas04gqh9yn72wdcssvktsqfmmmv4", + "edited": false + }, + { + "id": "2ee330e99ab8daeca8dc2cc9743c0904a536ec62226660ae640c6abba3f8118a", + "content": "Pretty good, working on something fun.", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1793582100000, + "pending": false, + "failed": false, + "mine": false, + "npub": "npub1uqg0688p4nqh8ca5sddhvd0c63sq6a6gdygz4k6uk76a0z2kfxaqmmg7t4", + "edited": false + }, + { + "id": "1c13bd769a5602ef0fa2e909d49fad4cc9955d09d41a2a0fd233f53dd7b5ab59", + "content": "Ooh, tell me more when you can 👀", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1793582160000, + "pending": false, + "failed": false, + "mine": true, + "npub": "npub1yazve5gvw5em6um2mzg0nh2u4v4dkfas04gqh9yn72wdcssvktsqfmmmv4", + "edited": false + }, + { + "id": "a5bb91d4e778afed68b313afd3c981a59cf7f3a49fbf72efe8974ce87f526218", + "content": "It's easier to ask forgiveness than permission.", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1793584800000, + "pending": false, + "failed": false, + "mine": false, + "npub": "npub1uqg0688p4nqh8ca5sddhvd0c63sq6a6gdygz4k6uk76a0z2kfxaqmmg7t4", + "edited": false + } + ], + "last_read": "a5bb91d4e778afed68b313afd3c981a59cf7f3a49fbf72efe8974ce87f526218", + "unread_from": "", + "created_at": 1793581200, + "metadata": { + "custom_fields": {} + }, + "muted": false, + "notify": 2, + "everyone_pings": true, + "community_muted": false + }, + { + "id": "npub1qk3nrfl57xffl2k29zdxd7vdtgzm8p7ee045lrpdmqsy56cz8g2qqxdt9s", + "chat_type": "DirectMessage", + "participants": [ + "npub1qk3nrfl57xffl2k29zdxd7vdtgzm8p7ee045lrpdmqsy56cz8g2qqxdt9s" + ], + "messages": [ + { + "id": "4fb91cf06af8fc36e9a29cd59245441d204dc24b8c4a7f7ff5fb2d157c11c608", + "content": "Hey! It's Heidi", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1790903400000, + "pending": false, + "failed": false, + "mine": false, + "npub": "npub1qk3nrfl57xffl2k29zdxd7vdtgzm8p7ee045lrpdmqsy56cz8g2qqxdt9s", + "edited": false + }, + { + "id": "d9ff57dd878fcd98c1110de3224817685f9a9a19d453112c2dfed9216645bdd8", + "content": "Hey, how are you doing?", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1790903520000, + "pending": false, + "failed": false, + "mine": true, + "npub": "npub1yazve5gvw5em6um2mzg0nh2u4v4dkfas04gqh9yn72wdcssvktsqfmmmv4", + "edited": false + }, + { + "id": "f8c2dd42b5d4d876a4332c56e38594d68795b82589d0e981a6c30edc0f2cda00", + "content": "Pretty good, working on something fun.", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1790903700000, + "pending": false, + "failed": false, + "mine": false, + "npub": "npub1qk3nrfl57xffl2k29zdxd7vdtgzm8p7ee045lrpdmqsy56cz8g2qqxdt9s", + "edited": false + }, + { + "id": "8f59f5a85a3503d368364ff444a7e1d38ca8a0be2d207b0c41683a21f96807f5", + "content": "Ooh, tell me more when you can 👀", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1790903760000, + "pending": false, + "failed": false, + "mine": true, + "npub": "npub1yazve5gvw5em6um2mzg0nh2u4v4dkfas04gqh9yn72wdcssvktsqfmmmv4", + "edited": false + }, + { + "id": "c33c8607c4f223f4233f68b92e7fef6b309201b87fb34d1bdfa18e4e13752e76", + "content": "See you on Saturday", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1790906400000, + "pending": false, + "failed": false, + "mine": false, + "npub": "npub1qk3nrfl57xffl2k29zdxd7vdtgzm8p7ee045lrpdmqsy56cz8g2qqxdt9s", + "edited": false + } + ], + "last_read": "c33c8607c4f223f4233f68b92e7fef6b309201b87fb34d1bdfa18e4e13752e76", + "unread_from": "", + "created_at": 1790902800, + "metadata": { + "custom_fields": {} + }, + "muted": false, + "notify": 2, + "everyone_pings": true, + "community_muted": false + }, + { + "id": "npub19ayt3q02wpelr3hsswefdgmqh4xfeag7m2kt58xecdxc4c7ejnkq92s7dr", + "chat_type": "DirectMessage", + "participants": [ + "npub19ayt3q02wpelr3hsswefdgmqh4xfeag7m2kt58xecdxc4c7ejnkq92s7dr" + ], + "messages": [ + { + "id": "53b8cc19da5f56354d0281c9daa68f89304c11dc11942342d0b4553b88aefa8c", + "content": "Have a read: https://example.invalid/posts/private-by-default", + "replied_to": "", + "preview_metadata": { + "domain": "https://example.invalid/", + "og_title": "Private by default", + "og_description": "Why every message you send should be sealed before it leaves your device.\nA look at gift wraps, relays and what they can never learn.
Part one of three.", + "og_image": "https://example.invalid/og.png", + "og_url": "https://example.invalid/posts/private-by-default", + "og_type": null, + "title": null, + "description": null, + "favicon": "https://example.invalid/favicon.ico" + }, + "attachments": [], + "reactions": [], + "at": 1794101400000, + "pending": false, + "failed": false, + "mine": false, + "npub": "npub19ayt3q02wpelr3hsswefdgmqh4xfeag7m2kt58xecdxc4c7ejnkq92s7dr", + "edited": false + }, + { + "id": "eecc0a5093579f0de707c656ea2289edffb6ea722dca762b7bcfe2414090846d", + "content": "https://example.invalid/docs", + "replied_to": "", + "preview_metadata": { + "domain": "https://example.invalid/", + "og_title": null, + "og_description": null, + "og_image": null, + "og_url": null, + "og_type": null, + "title": "Docs", + "description": "Short and to the point.", + "favicon": "https://example.invalid/favicon.ico" + }, + "attachments": [], + "reactions": [], + "at": 1794102000000, + "pending": false, + "failed": false, + "mine": true, + "npub": "npub1yazve5gvw5em6um2mzg0nh2u4v4dkfas04gqh9yn72wdcssvktsqfmmmv4", + "edited": false + }, + { + "id": "97a55d29a973a83f670c1f48c92336dd35248f3f744445bd1de09275ca189bdf", + "content": "Watch this https://www.youtube.com/watch?v=dQw4w9WgXcQ", + "replied_to": "", + "preview_metadata": { + "domain": "https://www.youtube.com/", + "og_title": "A video worth watching", + "og_description": "Uploaded by somebody.", + "og_image": "https://i.ytimg.com/vi/dQw4w9WgXcQ/hqdefault.jpg", + "og_url": "https://www.youtube.com/watch?v=dQw4w9WgXcQ", + "og_type": null, + "title": null, + "description": null, + "favicon": "https://example.invalid/favicon.ico" + }, + "attachments": [], + "reactions": [], + "at": 1794102600000, + "pending": false, + "failed": false, + "mine": false, + "npub": "npub19ayt3q02wpelr3hsswefdgmqh4xfeag7m2kt58xecdxc4c7ejnkq92s7dr", + "edited": false + }, + { + "id": "abababababababababababababababababababababababababababababababab", + "content": "Come hang out with us https://vectorapp.io/invite/naddr1qvzqqqr4gupzqmjxss3dld622uu8q25gywum9qtg4w4cv4064jmg20xsac2aam5nqqxnzd3cxqmrzv3exgmr2wfesgsmew#Zk3pQ9vT2xLm8RbN4cWd7YhJ", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1794102660000, + "pending": false, + "failed": false, + "mine": false, + "npub": "npub19ayt3q02wpelr3hsswefdgmqh4xfeag7m2kt58xecdxc4c7ejnkq92s7dr", + "edited": false + } + ], + "last_read": "97a55d29a973a83f670c1f48c92336dd35248f3f744445bd1de09275ca189bdf", + "unread_from": "", + "created_at": 1794016800, + "metadata": { + "custom_fields": {} + }, + "muted": false, + "notify": 2, + "everyone_pings": true, + "community_muted": false + }, + { + "id": "a0f367a05f629b3bb09ee8f1561bf03267962217d9ff6fc7ce3b235235702bc1", + "chat_type": "Community", + "participants": [], + "messages": [ + { + "id": "7a3c760d48ddcb81b5b84767bdb6888628fe32badc3075ee364324255c1f53a1", + "content": "Welcome to the new community!", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1794360000000, + "pending": false, + "failed": false, + "mine": false, + "npub": "npub190vqdjtlpcq27xslcveglfmr4ynfwg7gmw86cnun4acakxrdd6gqnp929a", + "edited": false + }, + { + "id": "e55c72814cdc85d3ec5df9cf7d0f7856eae78a3f8e67281a81f2ef2adb3660e6", + "content": "Glad to be here 👋", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1794360600000, + "pending": false, + "failed": false, + "mine": false, + "npub": "npub1sxmr0k8u6trd5c6eu6trzyapzux7090ykujmsng7pdx0m8k93n5sd02fwn", + "edited": false + }, + { + "id": "3b5ddcbb97a2556731cd4376b27b365b56eb569277b419bc8afe248833527732", + "content": "The GPUI port is coming along nicely.", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1794361200000, + "pending": false, + "failed": false, + "mine": true, + "npub": "npub1yazve5gvw5em6um2mzg0nh2u4v4dkfas04gqh9yn72wdcssvktsqfmmmv4", + "edited": false + }, + { + "id": "1196b072a6d5283c763dea302077985c28cbe827c0b18e82d9533abd63e51100", + "content": "Can't wait to try it.", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1794361800000, + "pending": false, + "failed": false, + "mine": false, + "npub": "npub1fsndjp6vylvfahjeyuxq4s2tw8s8rv2j89ge7a28fvhnhf35s86sg3uctf", + "edited": false + } + ], + "last_read": "1196b072a6d5283c763dea302077985c28cbe827c0b18e82d9533abd63e51100", + "unread_from": "", + "created_at": 1794362400, + "metadata": { + "custom_fields": { + "community_id": "ca848c275e2117470342c641ada0ae4639dd0472ab4a5ec654a189bf1f689087", + "name": "Vector Devs", + "description": "Where Vector gets built, in the open.", + "primary_channel": "a0f367a05f629b3bb09ee8f1561bf03267962217d9ff6fc7ce3b235235702bc1", + "owner_npub": "npub1yazve5gvw5em6um2mzg0nh2u4v4dkfas04gqh9yn72wdcssvktsqfmmmv4", + "is_owner": "true", + "channel_name": "general" + } + }, + "muted": false, + "notify": 2, + "everyone_pings": true, + "community_muted": false + }, + { + "id": "d961d1281aed7b3ad2f6964aa7e59d427d8b921a8f7dd8c4c0f0a0e1422a17d1", + "chat_type": "Community", + "participants": [], + "messages": [ + { + "id": "c42822194abfc07af77d310d9fd4d35d0fba4fa68d45d753e5a99181c926caea", + "content": "CI is green again.", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1794361200000, + "pending": false, + "failed": false, + "mine": false, + "npub": "npub1sxmr0k8u6trd5c6eu6trzyapzux7090ykujmsng7pdx0m8k93n5sd02fwn", + "edited": false + }, + { + "id": "47c3066a117648de8e251a190b356d8be10c166b1ef1c10d074239a848a8a441", + "content": "Nice, merging the calls branch next.", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1794361800000, + "pending": false, + "failed": false, + "mine": true, + "npub": "npub1yazve5gvw5em6um2mzg0nh2u4v4dkfas04gqh9yn72wdcssvktsqfmmmv4", + "edited": false + } + ], + "last_read": "47c3066a117648de8e251a190b356d8be10c166b1ef1c10d074239a848a8a441", + "unread_from": "", + "created_at": 1794362400, + "metadata": { + "custom_fields": { + "community_id": "ca848c275e2117470342c641ada0ae4639dd0472ab4a5ec654a189bf1f689087", + "name": "Vector Devs", + "description": "Where Vector gets built, in the open.", + "primary_channel": "a0f367a05f629b3bb09ee8f1561bf03267962217d9ff6fc7ce3b235235702bc1", + "owner_npub": "npub1yazve5gvw5em6um2mzg0nh2u4v4dkfas04gqh9yn72wdcssvktsqfmmmv4", + "is_owner": "true", + "channel_name": "dev" + } + }, + "muted": false, + "notify": 2, + "everyone_pings": true, + "community_muted": false + }, + { + "id": "451269113943deb53e912b83f5e397cd38bdc2460928a14dbc4f766181425977", + "chat_type": "Community", + "participants": [], + "messages": [ + { + "id": "ae19a8aaa77fb5559a042d5498489758ca94951173813ea34c57d1f605f579c0", + "content": "New icons are in Figma.", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1794361800000, + "pending": false, + "failed": false, + "mine": false, + "npub": "npub1fsndjp6vylvfahjeyuxq4s2tw8s8rv2j89ge7a28fvhnhf35s86sg3uctf", + "edited": false + } + ], + "last_read": "ae19a8aaa77fb5559a042d5498489758ca94951173813ea34c57d1f605f579c0", + "unread_from": "", + "created_at": 1794362400, + "metadata": { + "custom_fields": { + "community_id": "ca848c275e2117470342c641ada0ae4639dd0472ab4a5ec654a189bf1f689087", + "name": "Vector Devs", + "description": "Where Vector gets built, in the open.", + "primary_channel": "a0f367a05f629b3bb09ee8f1561bf03267962217d9ff6fc7ce3b235235702bc1", + "owner_npub": "npub1yazve5gvw5em6um2mzg0nh2u4v4dkfas04gqh9yn72wdcssvktsqfmmmv4", + "is_owner": "true", + "channel_name": "design" + } + }, + "muted": false, + "notify": 2, + "everyone_pings": true, + "community_muted": false + }, + { + "id": "58e6267876fd6c4acb7fbc37091bb920e4f325e24df4887b8048d0ccf7137f2f", + "chat_type": "Community", + "participants": [], + "messages": [], + "last_read": "", + "unread_from": "", + "created_at": 1794362400, + "metadata": { + "custom_fields": { + "community_id": "ca848c275e2117470342c641ada0ae4639dd0472ab4a5ec654a189bf1f689087", + "name": "Vector Devs", + "description": "Where Vector gets built, in the open.", + "primary_channel": "a0f367a05f629b3bb09ee8f1561bf03267962217d9ff6fc7ce3b235235702bc1", + "owner_npub": "npub1yazve5gvw5em6um2mzg0nh2u4v4dkfas04gqh9yn72wdcssvktsqfmmmv4", + "is_owner": "true", + "channel_name": "Lounge" + } + }, + "muted": false, + "notify": 2, + "everyone_pings": true, + "community_muted": false + } + ], + "thumbs": { + "U(^ /twg4<&F@NQS~xhD@CSA": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAASCAYAAAA6yNxSAAAE+ElEQVR4Ae3AA6AkWZbG8f937o3IzKdyS2Oubdu2bdu2bdu2bWmMnpZKr54yMyLu+Xa3anqmhztr1a8+8jFf6FIKtVZq7ShRkES2ZJompnEkpwmRdDXYWHRsb804fmzBsZ05x3Z6tjeDzQ1YzJPFbGIxb2zMGxuLxmKRLObJrG90ZSJiBAbsCZzU+SwpIWpNak0ihICMpNAIT6QmIOlr0FXR10pXJ/ra6OtE3xX6Cn1N+i7pa6Orja4mfU260uhKo9ZGaAIa9gRO6vHtRgTUAqVARIKhtcY0jozDSJtGIOlqsDFPNuZicx5szgubc9icJxtz2Jgn83ljMZtYzBsb82QxS+azRt9P1DIRGrAH8Iid1GtOTESYUkyECTVsM42NYRgYh4FpmsBJV8Ri0djZhJ1NsbMpdjbN9mZhc0MsZsli3pjPJhbzxmKeLOaNWd/ou4kSI9KAvcY5Yif1+jONkIliQkaI1pJxnBjWa4b1wDiO4KQWsVg0drbMsS1xfFsc2zbbm5WNDbGYJ/NZYz5rLGaN+byxmDVmfaPWkRIDeMBekznibNSbrjFSEgHC2DBNyTCMrFcD69WacRiwk1KCxdxsb4lj24Xj24VjW2JrK9lciPnczPvGfDYxmzXms8Z81qjdBGUEDeAV5BraCG7UG86AAAnAZMI4NtbridVyYtWPDMNEZqNGMJ+L7a3KztbE8c2Jnc3C1obYWIj5LJnNGrO+MesnZrOG+gZ1gjICA+QAbQAGcKNec6ICQhI2tGbGQayWcFTMssCwNtmgBMznsLWA7QVsLWBzDptzs5jBrIe+g1ln+goqhmIoCUogQQk0oIEn6vGtnitEJrQpWReoNMKVyImOSmuNEoVZX5n3lXlXmdVKXytdVGpAkSkYuSAbXKAZFKAAAlrAFNAEGdRZnXOFyISJxG2kBXRhuoCMQDZFQVVPYUF4gTyHnJGt0CZoJCMFPEEGfTboAqYACWxoCVPiZrI1qtsCECCcJqckp45shZwK2So59WRLiEKbZrRpwThuMKwX1NIjCtnMWJNaJmqd6Gqj6ya62ihlIlSxC60VpqnQpkpmoy6PNgBhi0yYpmS9nlguO5bLjtWyZ72eaM2ECtlmwAJpAzEns2cYgq6aUhqlTJQyUctE1zW62ii1ERqwZ2Trmaae1gYyG/XixQUgQGSKaTLD0FiuBpZHM5bLgWFotAYRla6bMU4LprZgHOcs1x19J0oxEROhiVImam3U2ui6pJaJiAk80HJNm9a0NpA5Uc+eWwAChFNMDcahsVr3LJcjq9XEMCSZQlHpuxmr9YLVsGC5mtP3lVpFiUSaUIxETNTS6Lqk65JakxITMJK5prWB1gYyG/Xe+2YIgQJbtAbjaNbrxmo1sVo3xjHJDCI6+n7GbLXBYj1nNp/Rd5VSQEqkCRiJmKi10VXT9UlXTSkNaSRzINtAy5HMRj13rgMJCCDIFOMIw9BYrRvDOhknk1mI0tF3c2bzBathwWzV03WVCJAaMAIjoYlSk64zfW+6ztSSSBP2SMuBbCPpRt29VEBCKkCQGUwTDENhPSTDkEwTpAsleoZ+ztgWTG3BMPV0taAAaOACFBQTtSRdZ/oe+t6UkkQ07JHMjswRZ1KXKyEFUmACZzA1GEexXothCKYJTCGiYipSh6JiKq0VIgCEbcBIUGvS0qQhDbUmEYEtMiFT2Mk/Ah7D65d0eLWCAAAAAElFTkSuQmCC", + "6%fXoBL7P(`cp*l1#)iQt/q;6h": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABcAAAAgCAYAAAD5VeO1AAAGzUlEQVR4Ae3AA6AkWZbG8f937o3IzKdyS2Oubdu2bdu2bdu2bWmMnpZKr54yMyLu+Xa3anqmhztr1a8+7I3eyDs7O1x3w/XcePPNXHfj9Rw7fgx1laP1kouXdrmwe5GDo0MSs7m5wanTp7n22ms5dfIk89mM9WrFfffcy9Of/jSe8uSncNutz+DixQvU1WpFP5uxWq1YrVasliv6+YxoldV6xWq1YrVes16vMaZ2lWEYGIeBcRwoEYzjyDiNTOPENE5M08Q4TdS9/X2QWGxusr23x2JrE4qIrnK0XrG/v8/+/j6HyyMQEOLo6Iij5RGL5QKnGVZrVqsVq/WK9XrFer1mvV5T93cv0TKZLeZsbm/SL+Y0kugqy2HF7t4lLu1d4mi1hBCJmc/nHBxsMZ/PyZaM6zXL5ZLlcslytWK1WjGtVlT29jgCdjc22Ni5RL+xoMlEV1kOKy7t77G7v8dytSRKgGBjY4PDo0M2jhaQZhgGlssVq9Wa9XrNeljDeqCyWkHXcbhccnh4xMHBIaqFqIXlsGb/4ICDgwNW6xVRC6VWlsslq9WK1WpNKJiGgWEcGMeRaRqZpgnaRCUTMplaY5gm1uNItx5QC5brFcvVitVqzWpYU1phGAeGcWQYR8ZpZGodLRuZiW1sAECi0vXQdUQpSIGBtHFLptaYpsbYJqbWIERrSWaSaWyDAYQkIoJSCrVWWq0Emxuw2GA2X9D1PaVWFAESCaSNbdKQNsaY+wmFiAhqKXRdpe97ZrMZzGdUtrYpm5vMNzbo5wtq1xO1YicgDCRgjAHzTBIKERGoQO06+r5nPp+xWMwZhgW1bm2z2FgwX2zQz2fUriei0NIYSEOmSRvb2GCuEEIKooquq8xmM+bzOYvFgnEcqYuNDeaLBbP5nNr1RClYIg0tkykbrTVaSyKSlklmYhuACBEKuq5jNpuxsViwublJtkbt53O6fkbpOqIULJGGqTXGqTFNE+PUaNOEQmRrZCa2QRARdFGY9T2L+ZzNzQ22t7aQTe36GbXvKKWiKBiRaaaWTK0xTo2pNWhJZpI2AJKICGqp9F0H2djc3GR7e5thvaaWQu36nq7rKbVDUUDCGNtkGtvYBkASEUGJQi2FvuuYzXoWsxl9KeQ0MQ1ryGQxm1NnswVd39H1M2rXUUoFJ4pCRBBRKLXSMF3X0Xc9/axnNpuxmM/Z3Nhgc7HAU6NKyKaLwnLziLrY2KDrOmaLObPZjNIVWjbGnOj6nr6fMZsGshbm8zmLxZyNxYLNjQ02NzbY2txke3MT2cy6So1g3nWslkvqxuYWXVeZzWf08xlRgpaNRjKMC9bDmnQjs7FYzNjc2GRzY4PNjQ02NzbY2txke2uLAsxrpZOY1cJqtaJubG7S1Uo/6+lnPVGDKSeSZBgHNsYBk2ROLOYzFos589mc2WzGrJ8x63vmfU+VKACtoTR9rdRZP6N2lb7v6fqOKIEy6KaJvu/pu56p62kZdF1HLZUSQQDYOBNnYgnZyCYERUEFAQIABADmMiHEM9m4JW2aGNcDq+WS5eEhh/tzSiY1gmm9Znl0xPLwkGEYqOv1mqlNZCYtk6hBaxPr9Zr1as16vWa9WjNNA20a6WtwaT5ja2POoutQm1hubFCBaRhYHh6yPDpiHAbq7u4lai30s56u74gSNE+sVkv2D/bY39/n8HCfYVxTi2jDGmVSnHgYWO7vsTmfEzbTes3y6Ijl0RHjMFDPnj1LrYV+1tP3PaUGzY31esX+4R77+5c4PNyH9RIER4sZ4/KIcXXEan+fS9vbLPoeORlXK5ZHRyyPjhiHgXrvPfdSa2U27+lnPbUrpJP1uOLw8IDh4BIc7MF6CU7GWce9R4esjw5Z7u2xu7nJrBbIZFwuWR4dsTw6YhwG6njffYxdZTmbEfMZXV9BZpgGfHQAh3twsA/rJeQEXYX1it31inF5xOF8Tl8KbhPDcsny8JDV8ohxGKlcvAhdB/MZuZiznnVQBG2E1RKWK1ivYbWCnGAqQILgMJNcr6khPE4MqyXD4SEcHcE4UDk8gr4DJwjAUAPcIJNnkUACAAOZ0BptmpDA08Q0jjCOME0wQqU1mAJaQiYAhIACXQethzYHATlBFcx6mM2os55Z31MFKcE0sep73BpooIJAgggoBWqFroMAaoCAEPQF3KAEzHrqxpyt+ZxF31EFOU6MpdBFsCqFaRyplAKlQClQO+g6at8TRWQWpiKogrGCG9Sgznq2FnO2FnMWfUcVeJwYaqGLoK+VcRyplIBSoBQoBUql1kqpQVogM5EQgJOowXzWM5/PmM9mzPuOKnApBEaZCFNK8I958c/ms+Jt8gAAAABJRU5ErkJggg==", + "HUN*`C9p<)MJbF6vQY^LC_$qYVyrBA": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAHJUlEQVR4Ae3AA6AkWZbG8f937o3IzKdyS2Oubdu2bdu2bdu2bWmMnpZKr54yMyLu+Xa3anqmhztr1a8e/ejP2YAFCChCpRB9pfSVOuvRrIfZDGY9zHroZ9DPoOuhdKACDVhPcLCCSwdwcZ/lxX2OLh0xHq3xaDpV5t2MRb+gzGZQOioIAWCMwOIyAwjMsxkwYIMNNtiAwYANBgwYsBAAQjyTucICoApxmQEJELKQgQQMJJCGNDRDM7SESMAgQwOaIQ0JGDBgwIC5woABGxIqybPZ2ICMG7iZbKZMCZGgBmqgBjRwgzKBDCmYEqaEltCMm3EDpyGNActkM6UZSGobEzAGLCAECelGQRhhi2IhAwkk0IAJqAZVSGBIWI8wNHJotKnRpkaOiUcjNRpJi0aloSLquBwwYMACAqiBpkJMSWlJNFOmpIxJ6ZIYEroGXYMyQVTIgDFhOcByYFiNjKuRcT0xricYjTFRg8iCmuhKUo8OVoAxYAEhqIFqIbpK9JXSTURXiW6kdJVSO2rX0dUR1Q6iAwtGw2pkOFyxOlqxOhpYHw2MywFGUwgohhHcmak26sHuIQiMsQRFqATqCtFVoqtEX4muErUQtVJqpXYdtfZ0taNEJVxgMtN6Yn24Yrm/YnmwYnW4YloOeDTFQStJdqZ1SS2Vur97AIAFhCCEaqCuUrpK9JXoKtEVVCtRC1ErpVRq7ehqT41KUKDBtJ4Yjtas9pcsD5asD1aMywGPpjiYSqPVZOwatRTqwaUjACwghEqgGkRXib5S+o7oKuoKUQsqhSiFqJVaOmodqVEJCmrQhsZwNLA+XLE8WLE+WDEtRzyZ4mCKRqtmqo1SCvVof8VlIQihGkStRG/KBGWC6I3GRDVRNFQKURqlNEpp1KgUCiTkkIzLgfXhwOpoYH00Mq1GPCbFQYskK7SalCjUYdlAQAhFoCpKnwQGGQQGZCANYYiGAkpACZgiCQpKkUNjXI0My5H1amJYT0yrhqekpHEI1wkXUYqpOQkkCKESRATOirJCVnAFV8gABbZwCgQp0yIpEgHQRI7JtE6GIRkHMw6mjcaTyTSEURpVk81UqQeBFEhBUaWoUqKnlI4SHVEqisASKbDBBiOcwoAAmsnRTKOZRpgmaE1MTdCEU4TFhJCEDbWUOZJQCNVCqYVSO2rtqbWj1A7VCiWwABuTpI0NJKQFBprJ0UwTjBNMk5iaaCloAQQtg6IgMxBBrXUBEgoRtVBqpdSO2nXU2lO6ikrBJWgYOXFr2I2WxmmcQBqaydFMo5kmGBtMTWQLsMGBImguhANcqFHmIFAEUQKVSpSOKB0qPYoKUUAAJt1ohrGZ1hqtgTNxA5rJMZmGZBqTaTTTBNlATSSBCKYIlIEJqum4IkgCUUkqzR1yBVdwkIbJydCSYYJhNOOUtCnJlrgZN5OjacNEWzemIWlj4gkioQIgSKEI0kEdM0AghFrQQpQmSoM2QYQB0wRTJuupsR4b63FiHEemsdFa4mY8GU+mDY0cGm2YyDFhMpGiCgwgsKAAdTUaBAhUGjIUi0IQFpHGNUiZMRvraWQ1DKyHgWEcmcaJ1hJPxs14MjkmOSYeGh4TJigUOhkDDnCKgqiH64nLAohAUxJTEi2JKYmu4CpSZszGehpZDQPrYWA9DExTo02J09CMJ/BkPCYeEyYTKSqihbGMAzKgAnV/OYKMJQhQCdQVYmzE2FBXoIomM2VjPU2sxoH1MDCMI9M00aaEBBJowGQ8GSajBpGiKmgYEkhwwgTU/dUAgGUsQRGqQfQVjYXoC5SgBUxuDNPEehxYjyPDODJNjcyEBFIogQaagGbURLGoGAtIIMEJRVAP1iPGGLCMQ6gGmiaiq2gqUIMMaE6GnBimkWGcGKfG1BpuBoNSyIIGSiAh0oRNJ3ACCdhkmoKph8OEbYxJGQuogaaCWiNaga7gIhrJlI2hNcapMbYkm3EaLGRQggwYlCBDJKTAMmTiZpqSiqjLsWFM2iRJCmiCTMJJ2MiJS5AyE8nUzJgwGdLCgBBCCAEgAxgSIk1T0khSSVOjJygJdd2StEknDZMyTiGbwEgQFLDJEImZDBPQECkwQgghJAHGGCeQRmmKYZJoKaYUQ5oShTqkSZu0mZwkxgFgIiBCRAgCjEhBMzREI7CMASFACDBgm8zEzdBMZDLKjM0MzdSpUSKoY0LaNJuWSZOxAYGaKC2JTJQCiQQS0RApSMSzmMts09JkJtkaHo0aBI2qRlcaNSoRQW02aZjSNJvmJAUkKEWmiTSRhjCWSKBJpME8J2PSpmUytaRNjRwbNBMWhUKNRo2JUFCbIW3S0AzNkGGwURqcOI0NGDCkwAgLjDGAwYBtMs2UydSSqTVaazAmSigkUyQlCiFRDRhITNokJg3YyEYGYdJGXGGEMQaMMAbAgA0JpE1z0jJpreE0SjDgNA4TCv4RtiqpFjEcUFEAAAAASUVORK5CYII=" + }, + "communities": [ + { + "community_id": "ca848c275e2117470342c641ada0ae4639dd0472ab4a5ec654a189bf1f689087", + "name": "Vector Devs", + "description": "Where Vector gets built, in the open.", + "is_owner": true, + "has_icon": false, + "channels": [ + { + "channel_id": "a0f367a05f629b3bb09ee8f1561bf03267962217d9ff6fc7ce3b235235702bc1", + "name": "general", + "private": false, + "readable": true, + "category_id": null, + "topic": "Say hi!", + "view": "chat", + "my_permissions": null, + "restricted": false, + "can_post": true, + "public_until": null + }, + { + "channel_id": "d961d1281aed7b3ad2f6964aa7e59d427d8b921a8f7dd8c4c0f0a0e1422a17d1", + "name": "dev", + "private": false, + "readable": true, + "category_id": "e70d362ac4e73ce2887e5395680c76b7b3c93e43b69587845448f3b9d03ff48c", + "topic": "Builds, branches and bugs", + "view": "chat", + "my_permissions": null, + "restricted": false, + "can_post": true, + "public_until": null + }, + { + "channel_id": "451269113943deb53e912b83f5e397cd38bdc2460928a14dbc4f766181425977", + "name": "design", + "private": false, + "readable": true, + "category_id": "e70d362ac4e73ce2887e5395680c76b7b3c93e43b69587845448f3b9d03ff48c", + "topic": null, + "view": "chat", + "my_permissions": null, + "restricted": false, + "can_post": true, + "public_until": null + }, + { + "channel_id": "58e6267876fd6c4acb7fbc37091bb920e4f325e24df4887b8048d0ccf7137f2f", + "name": "Lounge", + "private": false, + "readable": true, + "category_id": null, + "topic": null, + "view": "voice", + "my_permissions": null, + "restricted": false, + "can_post": true, + "public_until": null + } + ], + "categories": [ + { + "category_id": "e70d362ac4e73ce2887e5395680c76b7b3c93e43b69587845448f3b9d03ff48c", + "name": "Build" + } + ], + "primary_channel": "a0f367a05f629b3bb09ee8f1561bf03267962217d9ff6fc7ce3b235235702bc1", + "owner_npub": "npub1yazve5gvw5em6um2mzg0nh2u4v4dkfas04gqh9yn72wdcssvktsqfmmmv4", + "dissolved": false, + "voice_relays": [], + "relays": [ + "wss://jskitty.com/nostr" + ], + "members": [ + "npub1yazve5gvw5em6um2mzg0nh2u4v4dkfas04gqh9yn72wdcssvktsqfmmmv4", + "npub190vqdjtlpcq27xslcveglfmr4ynfwg7gmw86cnun4acakxrdd6gqnp929a", + "npub1sxmr0k8u6trd5c6eu6trzyapzux7090ykujmsng7pdx0m8k93n5sd02fwn", + "npub1fsndjp6vylvfahjeyuxq4s2tw8s8rv2j89ge7a28fvhnhf35s86sg3uctf" + ] + } + ], + "invites": [ + { + "community_id": "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc", + "inviter_npub": "npub1v84qsqlcs56j8dmh6s22eccnpn2d87fdutxhl7rftseh67wzamhqfv9ft6", + "bundle_json": "{\"name\": \"Night Owls\", \"channels\": [{\"id\": \"dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd\", \"name\": \"general\"}], \"relays\": [\"wss://jskitty.com/nostr\"]}", + "received_at": 1794358800, + "sent_at": 1794358700, + "ends_at": 1794880800 + } + ] +} \ No newline at end of file diff --git a/crates/vector-gpui/reference/fixtures.json b/crates/vector-gpui/reference/fixtures.json new file mode 100644 index 000000000..3b369da4d --- /dev/null +++ b/crates/vector-gpui/reference/fixtures.json @@ -0,0 +1,5030 @@ +{ + "now": 1794362400000, + "npub": "npub1yazve5gvw5em6um2mzg0nh2u4v4dkfas04gqh9yn72wdcssvktsqfmmmv4", + "profiles": [ + { + "id": "npub1yazve5gvw5em6um2mzg0nh2u4v4dkfas04gqh9yn72wdcssvktsqfmmmv4", + "name": "jskitty", + "display_name": "JSKitty", + "nickname": "", + "lud06": "", + "lud16": "", + "banner": "", + "avatar": "", + "about": "", + "website": "", + "nip05": "", + "status": { + "title": "", + "purpose": "", + "url": "" + }, + "last_updated": 1794362400, + "mine": true, + "bot": false, + "is_blocked": false, + "avatar_cached": "", + "banner_cached": "", + "stream_consent": false + }, + { + "id": "npub190vqdjtlpcq27xslcveglfmr4ynfwg7gmw86cnun4acakxrdd6gqnp929a", + "name": "alice", + "display_name": "Alice", + "nickname": "", + "lud06": "", + "lud16": "", + "banner": "", + "avatar": "https://example.invalid/alice.png", + "about": "", + "website": "", + "nip05": "", + "status": { + "title": "", + "purpose": "", + "url": "" + }, + "last_updated": 1794362400, + "mine": false, + "bot": false, + "is_blocked": false, + "avatar_cached": "avatars/alice.png", + "banner_cached": "", + "stream_consent": false + }, + { + "id": "npub1sxmr0k8u6trd5c6eu6trzyapzux7090ykujmsng7pdx0m8k93n5sd02fwn", + "name": "bob", + "display_name": "Bob Nakamoto", + "nickname": "", + "lud06": "", + "lud16": "", + "banner": "https://example.invalid/bob-banner.png", + "avatar": "https://example.invalid/bob.png", + "about": "Building on Nostr since 2021.\nCoffee first, relays second \u26a1", + "website": "", + "nip05": "", + "status": { + "title": "Shipping v0.6 \ud83d\ude80", + "purpose": "general", + "url": "" + }, + "last_updated": 1794362400, + "mine": false, + "bot": false, + "is_blocked": false, + "avatar_cached": "avatars/bob.png", + "banner_cached": "media/photo.png", + "stream_consent": false + }, + { + "id": "npub1fsndjp6vylvfahjeyuxq4s2tw8s8rv2j89ge7a28fvhnhf35s86sg3uctf", + "name": "carol", + "display_name": "Carol", + "nickname": "", + "lud06": "", + "lud16": "", + "banner": "", + "avatar": "https://example.invalid/carol.png", + "about": "", + "website": "", + "nip05": "", + "status": { + "title": "", + "purpose": "", + "url": "" + }, + "last_updated": 1794362400, + "mine": false, + "bot": false, + "is_blocked": false, + "avatar_cached": "avatars/carol.png", + "banner_cached": "", + "stream_consent": false + }, + { + "id": "npub1v84qsqlcs56j8dmh6s22eccnpn2d87fdutxhl7rftseh67wzamhqfv9ft6", + "name": "dave", + "display_name": "Dave the Builder", + "nickname": "", + "lud06": "", + "lud16": "", + "banner": "", + "avatar": "https://example.invalid/dave.png", + "about": "", + "website": "", + "nip05": "", + "status": { + "title": "", + "purpose": "", + "url": "" + }, + "last_updated": 1794362400, + "mine": false, + "bot": false, + "is_blocked": false, + "avatar_cached": "avatars/dave.png", + "banner_cached": "", + "stream_consent": false + }, + { + "id": "npub10j7vkrzv4t0elnd4rmj902pge3e2gkresvd4h9u2ut3valzyjuzsz7ad26", + "name": "erin", + "display_name": "Erin", + "nickname": "", + "lud06": "", + "lud16": "", + "banner": "", + "avatar": "https://example.invalid/erin.png", + "about": "", + "website": "", + "nip05": "", + "status": { + "title": "", + "purpose": "", + "url": "" + }, + "last_updated": 1794362400, + "mine": false, + "bot": false, + "is_blocked": false, + "avatar_cached": "avatars/erin.png", + "banner_cached": "", + "stream_consent": false + }, + { + "id": "npub1wajx7kj0x9nxxa38405e3eapgu87wtvtgv8svld04p3x8u0j872qnta00x", + "name": "frank", + "display_name": "Frank", + "nickname": "", + "lud06": "", + "lud16": "", + "banner": "", + "avatar": "https://example.invalid/frank.png", + "about": "", + "website": "", + "nip05": "", + "status": { + "title": "", + "purpose": "", + "url": "" + }, + "last_updated": 1794362400, + "mine": false, + "bot": false, + "is_blocked": false, + "avatar_cached": "avatars/frank.png", + "banner_cached": "", + "stream_consent": false + }, + { + "id": "npub1uqg0688p4nqh8ca5sddhvd0c63sq6a6gdygz4k6uk76a0z2kfxaqmmg7t4", + "name": "grace", + "display_name": "Grace Hopper", + "nickname": "", + "lud06": "", + "lud16": "", + "banner": "", + "avatar": "https://example.invalid/grace.png", + "about": "", + "website": "", + "nip05": "", + "status": { + "title": "", + "purpose": "", + "url": "" + }, + "last_updated": 1794362400, + "mine": false, + "bot": false, + "is_blocked": false, + "avatar_cached": "avatars/grace.png", + "banner_cached": "", + "stream_consent": false + }, + { + "id": "npub1qk3nrfl57xffl2k29zdxd7vdtgzm8p7ee045lrpdmqsy56cz8g2qqxdt9s", + "name": "heidi", + "display_name": "Heidi", + "nickname": "", + "lud06": "", + "lud16": "", + "banner": "", + "avatar": "https://example.invalid/heidi.png", + "about": "", + "website": "", + "nip05": "", + "status": { + "title": "", + "purpose": "", + "url": "" + }, + "last_updated": 1794362400, + "mine": false, + "bot": false, + "is_blocked": false, + "avatar_cached": "avatars/heidi.png", + "banner_cached": "", + "stream_consent": false + }, + { + "id": "npub15387nevpzd0u700y2t24ym9l0zxe8fsxx2w7qn47ysn6mndn9gvqqmlahu", + "name": "vee", + "display_name": "Vee", + "nickname": "", + "lud06": "", + "lud16": "", + "banner": "", + "avatar": "https://example.invalid/alice.png", + "about": "", + "website": "", + "nip05": "", + "status": { + "title": "", + "purpose": "", + "url": "" + }, + "last_updated": 1794362400, + "mine": false, + "bot": false, + "is_blocked": false, + "avatar_cached": "avatars/alice.png", + "banner_cached": "", + "stream_consent": false + }, + { + "id": "npub17jjvuhaxxs9rt2jakz6td5c6d7a2vpfr2erqmwc9xajhmqplt03q63stmv", + "name": "mo", + "display_name": "Mo", + "nickname": "", + "lud06": "", + "lud16": "", + "banner": "", + "avatar": "https://example.invalid/grace.png", + "about": "", + "website": "", + "nip05": "", + "status": { + "title": "", + "purpose": "", + "url": "" + }, + "last_updated": 1794362400, + "mine": false, + "bot": false, + "is_blocked": false, + "avatar_cached": "avatars/grace.png", + "banner_cached": "", + "stream_consent": false + }, + { + "id": "npub19ayt3q02wpelr3hsswefdgmqh4xfeag7m2kt58xecdxc4c7ejnkq92s7dr", + "name": "lin", + "display_name": "Lin", + "nickname": "", + "lud06": "", + "lud16": "", + "banner": "", + "avatar": "https://example.invalid/bob.png", + "about": "", + "website": "", + "nip05": "", + "status": { + "title": "", + "purpose": "", + "url": "" + }, + "last_updated": 1794362400, + "mine": false, + "bot": false, + "is_blocked": false, + "avatar_cached": "avatars/bob.png", + "banner_cached": "", + "stream_consent": false + }, + { + "id": "npub1yn2tjm6cmfk54pgjxyam6q4z36lse22aa3hyeph00r887q083zkq7g4t6h", + "name": "ana", + "display_name": "Ana", + "nickname": "", + "lud06": "", + "lud16": "", + "banner": "", + "avatar": "https://example.invalid/alice.png", + "about": "", + "website": "", + "nip05": "", + "status": { + "title": "", + "purpose": "", + "url": "" + }, + "last_updated": 1794362400, + "mine": false, + "bot": false, + "is_blocked": false, + "avatar_cached": "avatars/alice.png", + "banner_cached": "", + "stream_consent": false + } + ], + "chats": [ + { + "id": "npub17jjvuhaxxs9rt2jakz6td5c6d7a2vpfr2erqmwc9xajhmqplt03q63stmv", + "chat_type": "DirectMessage", + "participants": [ + "npub17jjvuhaxxs9rt2jakz6td5c6d7a2vpfr2erqmwc9xajhmqplt03q63stmv" + ], + "messages": [ + { + "id": "4ea02ec455165f1c969e1dada2376504061579f9493eecd1e5c9c2db25cd6a72", + "content": "Look at this sunset", + "replied_to": "", + "preview_metadata": null, + "attachments": [ + { + "id": "3c347d8660df388374fbb5c2dcf925ad0140321118943c11980d6f654e6032cc", + "key": "", + "nonce": "", + "extension": "png", + "name": "", + "url": "https://example.invalid/photo", + "path": "media/photo.png", + "size": 170552, + "img_meta": { + "thumbhash": "U(^ /twg4<&F@NQS~xhD@CSA", + "width": 1600, + "height": 1000 + }, + "downloading": false, + "downloaded": true + } + ], + "reactions": [], + "at": 1794359280000, + "pending": false, + "failed": false, + "mine": false, + "npub": "npub17jjvuhaxxs9rt2jakz6td5c6d7a2vpfr2erqmwc9xajhmqplt03q63stmv", + "edited": false + }, + { + "id": "6c2c34d5ddfb1e38ab0a04a0cefdad531df3e6842d71bc129fc499edcaacc7d2", + "content": "", + "replied_to": "", + "preview_metadata": null, + "attachments": [ + { + "id": "a30b567bc5ffc67f0b27fb734b72684405d29cc58802f8c84fd1e697e3bed61e", + "key": "", + "nonce": "", + "extension": "png", + "name": "", + "url": "https://example.invalid/portrait", + "path": "", + "size": 24117248, + "img_meta": { + "thumbhash": "6%fXoBL7P(`cp*l1#)iQt/q;6h", + "width": 700, + "height": 1000 + }, + "downloading": false, + "downloaded": false + } + ], + "reactions": [], + "at": 1794359880000, + "pending": false, + "failed": false, + "mine": true, + "npub": "npub1yazve5gvw5em6um2mzg0nh2u4v4dkfas04gqh9yn72wdcssvktsqfmmmv4", + "edited": false + }, + { + "id": "76228bc2fc2f34503ca5c91c453e655ea233a85680896aae056e74805681e137", + "content": "", + "replied_to": "", + "preview_metadata": null, + "attachments": [ + { + "id": "3549e7ac429efad0ee75535ec93ea7ef1aa7f8b9b24d2de064a0a1d7e0017599", + "key": "", + "nonce": "", + "extension": "png", + "name": "SPOILER_sticker.png", + "url": "https://example.invalid/sticker", + "path": "media/sticker.png", + "size": 15319, + "img_meta": { + "thumbhash": "HUN*`C9p<)MJbF6vQY^LC_$qYVyrBA", + "width": 220, + "height": 220 + }, + "downloading": false, + "downloaded": true + } + ], + "reactions": [], + "at": 1794360480000, + "pending": false, + "failed": false, + "mine": false, + "npub": "npub17jjvuhaxxs9rt2jakz6td5c6d7a2vpfr2erqmwc9xajhmqplt03q63stmv", + "edited": false + }, + { + "id": "90ea00dec631e38520b6d323b806ef549167f40d914d997c85c09663648d0f2b", + "content": "The spec, and the build", + "replied_to": "", + "preview_metadata": null, + "attachments": [ + { + "id": "b336680d9d206af3b937b99b899fb1896886728823a9f96ca4b98f9227b64a92", + "key": "", + "nonce": "", + "extension": "pdf", + "name": "Vector Protocol Spec.pdf", + "url": "https://example.invalid/spec", + "path": "", + "size": 13002342, + "img_meta": null, + "downloading": false, + "downloaded": false + }, + { + "id": "1ece496bf8a0b989f1630ba7425eb5daff5054bc8c27df76be4cb7b5977e7f97", + "key": "", + "nonce": "", + "extension": "zip", + "name": "vector-0.5.1-linux.zip", + "url": "https://example.invalid/build", + "path": "media/sticker.png", + "size": 48234496, + "img_meta": null, + "downloading": false, + "downloaded": true + } + ], + "reactions": [], + "at": 1794361080000, + "pending": false, + "failed": false, + "mine": false, + "npub": "npub17jjvuhaxxs9rt2jakz6td5c6d7a2vpfr2erqmwc9xajhmqplt03q63stmv", + "edited": false + }, + { + "id": "fae91624685ae6d8b7c0df70b11eaae2ed785620a551bb4d56d006fb30b6840a", + "content": "Made a little fox", + "replied_to": "", + "preview_metadata": null, + "attachments": [ + { + "id": "d97044e701822bac5a62696459b27d7b375aada5de8574ed4362edbba94771f7", + "key": "", + "nonce": "", + "extension": "glb", + "name": "Fox.glb", + "url": "https://example.invalid/fox", + "path": "media/fox.glb", + "size": 162852, + "img_meta": null, + "downloading": false, + "downloaded": true + } + ], + "reactions": [], + "at": 1794361140000, + "pending": false, + "failed": false, + "mine": false, + "npub": "npub17jjvuhaxxs9rt2jakz6td5c6d7a2vpfr2erqmwc9xajhmqplt03q63stmv", + "edited": false + }, + { + "id": "2bdaad8f7f7f63f749a37d97e109d72300424e5ca39d1b623d8b717de7802d08", + "content": "Thanks!", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1794361980000, + "pending": false, + "failed": false, + "mine": true, + "npub": "npub1yazve5gvw5em6um2mzg0nh2u4v4dkfas04gqh9yn72wdcssvktsqfmmmv4", + "edited": false + } + ], + "last_read": "2bdaad8f7f7f63f749a37d97e109d72300424e5ca39d1b623d8b717de7802d08", + "unread_from": "", + "created_at": 1794275880, + "metadata": { + "custom_fields": {} + }, + "muted": false, + "notify": 2, + "everyone_pings": true, + "community_muted": false + }, + { + "id": "npub15387nevpzd0u700y2t24ym9l0zxe8fsxx2w7qn47ysn6mndn9gvqqmlahu", + "chat_type": "DirectMessage", + "participants": [ + "npub15387nevpzd0u700y2t24ym9l0zxe8fsxx2w7qn47ysn6mndn9gvqqmlahu" + ], + "messages": [ + { + "id": "46160c560d01fcd55bc718f8adef022d010f02cc27d8a1c9e066c8ae61f1f4b4", + "content": "Have you tried the **new** markdown? It handles *italics*, ~~strikes~~ and `inline code`.", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1794268740000, + "pending": false, + "failed": false, + "mine": false, + "npub": "npub15387nevpzd0u700y2t24ym9l0zxe8fsxx2w7qn47ysn6mndn9gvqqmlahu", + "edited": false + }, + { + "id": "29e4fd18155e79dd760d101aca6abae460e8662b34ccf9bdaf9edd8e3b7a18b6", + "content": "Lists too:\n- one\n- two\n- three", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1794268800000, + "pending": false, + "failed": false, + "mine": false, + "npub": "npub15387nevpzd0u700y2t24ym9l0zxe8fsxx2w7qn47ysn6mndn9gvqqmlahu", + "edited": false + }, + { + "id": "f5e8a64a4803fd9cf5c2f2cc23eb5a66b6126982b1394d53195b86220dda9ed3", + "content": "> quoting you here\nand replying below the quote", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [ + { + "id": "d989534175d49bdce27c894467617cf954aa81994482cb551c63b8fe08918b5a", + "reference_id": "f5e8a64a4803fd9cf5c2f2cc23eb5a66b6126982b1394d53195b86220dda9ed3", + "author_id": "npub15387nevpzd0u700y2t24ym9l0zxe8fsxx2w7qn47ysn6mndn9gvqqmlahu", + "emoji": "\u2764\ufe0f" + }, + { + "id": "78e8fce8c1f9dce779d3287be6a7ec18f29ebbe3a0386710d569e62dbd2da183", + "reference_id": "f5e8a64a4803fd9cf5c2f2cc23eb5a66b6126982b1394d53195b86220dda9ed3", + "author_id": "npub1yazve5gvw5em6um2mzg0nh2u4v4dkfas04gqh9yn72wdcssvktsqfmmmv4", + "emoji": "\u2764\ufe0f" + }, + { + "id": "06320cad2867c2713b524fa38138aa146bf402abd91c54d1f7eae469adc8187c", + "reference_id": "f5e8a64a4803fd9cf5c2f2cc23eb5a66b6126982b1394d53195b86220dda9ed3", + "author_id": "npub15387nevpzd0u700y2t24ym9l0zxe8fsxx2w7qn47ysn6mndn9gvqqmlahu", + "emoji": "\ud83d\ude02" + } + ], + "at": 1794268920000, + "pending": false, + "failed": false, + "mine": true, + "npub": "npub1yazve5gvw5em6um2mzg0nh2u4v4dkfas04gqh9yn72wdcssvktsqfmmmv4", + "edited": false + }, + { + "id": "9224c65fb1c0fa757b5f2b9f069eb1ef3a888b071604a532eb0a22ddf4bbe1db", + "content": "```rust\nfn main() {\n println!(\"hello\");\n}\n```", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1794268980000, + "pending": false, + "failed": false, + "mine": true, + "npub": "npub1yazve5gvw5em6um2mzg0nh2u4v4dkfas04gqh9yn72wdcssvktsqfmmmv4", + "edited": false + }, + { + "id": "12a8715a08bb5cf5558c3e30e350beb05103f589af9ef0f894481c2c93cf58bf", + "content": "Nice! That one has a ||secret spoiler|| inside, and a [link](https://vectorapp.io).", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1794360540000, + "pending": false, + "failed": false, + "mine": false, + "npub": "npub15387nevpzd0u700y2t24ym9l0zxe8fsxx2w7qn47ysn6mndn9gvqqmlahu", + "edited": true, + "edit_history": [ + { + "content": "Nice! That one has a secret inside", + "edited_at": 1794360540000 + }, + { + "content": "Nice! That one has a ||secret spoiler|| inside \ud83c\udf89", + "edited_at": 1794360660000 + }, + { + "content": "Nice! That one has a ||secret spoiler|| inside, and a [link](https://vectorapp.io).", + "edited_at": 1794360840000 + } + ] + }, + { + "id": "f20c550ac443c1caf754848c6e70ebf4c46375e864ed7b1595b10f86f3ece07a", + "content": "# A heading\n-# and some subtext", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1794360600000, + "pending": false, + "failed": false, + "mine": false, + "npub": "npub15387nevpzd0u700y2t24ym9l0zxe8fsxx2w7qn47ysn6mndn9gvqqmlahu", + "edited": false + }, + { + "id": "45593079abe5d2bad5a8311b974a1ce700bd7933fa79e86f2ec32d0ec977b569", + "content": "Replying to that heading", + "replied_to": "f20c550ac443c1caf754848c6e70ebf4c46375e864ed7b1595b10f86f3ece07a", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1794361740000, + "pending": false, + "failed": false, + "mine": true, + "npub": "npub1yazve5gvw5em6um2mzg0nh2u4v4dkfas04gqh9yn72wdcssvktsqfmmmv4", + "edited": false, + "replied_to_content": "# A heading\n-# and some subtext", + "replied_to_npub": "npub15387nevpzd0u700y2t24ym9l0zxe8fsxx2w7qn47ysn6mndn9gvqqmlahu" + }, + { + "id": "0334355612cd1b65f5c35f87e405a17bb0d60854077fb7fde302fc92fcedd230", + "content": "This one is still sending", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1794362220000, + "pending": true, + "failed": false, + "mine": true, + "npub": "npub1yazve5gvw5em6um2mzg0nh2u4v4dkfas04gqh9yn72wdcssvktsqfmmmv4", + "edited": false + }, + { + "id": "bb49ca62931ae9d7d12f0641cacd899649c3975713d350c513db4fc027d504eb", + "content": "And this one failed", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1794362280000, + "pending": false, + "failed": true, + "mine": true, + "npub": "npub1yazve5gvw5em6um2mzg0nh2u4v4dkfas04gqh9yn72wdcssvktsqfmmmv4", + "edited": false + }, + { + "id": "c011111111111111111111111111111111111111111111111111111111111111", + "content": "Colours landed: rainbow text, a **bold gradient** run and a solid one.", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1794362310000, + "pending": false, + "failed": false, + "mine": false, + "npub": "npub15387nevpzd0u700y2t24ym9l0zxe8fsxx2w7qn47ysn6mndn9gvqqmlahu", + "edited": false, + "text_spans": [ + { + "kind": "color", + "from": 16, + "to": 28, + "effect": "rainbow" + }, + { + "kind": "color", + "from": 32, + "to": 53, + "effect": "gradient", + "colors": [ + "#ff4f8b", + "#4fb3ff" + ] + }, + { + "kind": "color", + "from": 60, + "to": 69, + "effect": "solid", + "colors": [ + "#ffb020" + ] + } + ] + }, + { + "id": "c022222222222222222222222222222222222222222222222222222222222222", + "content": "/roll 20", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1794362320000, + "pending": false, + "failed": false, + "mine": true, + "npub": "npub1yazve5gvw5em6um2mzg0nh2u4v4dkfas04gqh9yn72wdcssvktsqfmmmv4", + "edited": false + }, + { + "id": "c033333333333333333333333333333333333333333333333333333333333333", + "content": "/say hello there", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1794362330000, + "pending": false, + "failed": false, + "mine": true, + "npub": "npub1yazve5gvw5em6um2mzg0nh2u4v4dkfas04gqh9yn72wdcssvktsqfmmmv4", + "edited": false, + "addressed_bots": [ + "npub15387nevpzd0u700y2t24ym9l0zxe8fsxx2w7qn47ysn6mndn9gvqqmlahu" + ] + }, + { + "id": "c045acf2d273a786b030c9bc52f82e5208621ae4f0f7400c6ed71f088498e0d3", + "content": "\ud83d\udc4d", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [ + { + "id": "c14e0ecfd58555fc3a9db5e78aa7c771b69b7ca246b1a388a2d342ee3ccb1cc9", + "reference_id": "c045acf2d273a786b030c9bc52f82e5208621ae4f0f7400c6ed71f088498e0d3", + "author_id": "npub1yazve5gvw5em6um2mzg0nh2u4v4dkfas04gqh9yn72wdcssvktsqfmmmv4", + "emoji": "\ud83d\udd25" + } + ], + "at": 1794362340000, + "pending": false, + "failed": false, + "mine": false, + "npub": "npub15387nevpzd0u700y2t24ym9l0zxe8fsxx2w7qn47ysn6mndn9gvqqmlahu", + "edited": false + }, + { + "id": "c043300000000000000000000000000000000000000000000000000000000000", + "content": "", + "replied_to": "", + "preview_metadata": null, + "attachments": [ + { + "id": "6b1d0c8f3e2a4b5c9d7e1f0a2b3c4d5e6f708192a3b4c5d6e7f8091a2b3c4d5e", + "key": "", + "nonce": "", + "extension": "mkv", + "name": "2026-11-19 02-28-56.mkv", + "url": "https://example.invalid/recording", + "path": "media/clip.mkv", + "size": 176183, + "img_meta": { + "thumbhash": "", + "width": 640, + "height": 360 + }, + "downloading": false, + "downloaded": true + } + ], + "reactions": [], + "at": 1794362390000, + "pending": false, + "failed": false, + "mine": false, + "npub": "npub15387nevpzd0u700y2t24ym9l0zxe8fsxx2w7qn47ysn6mndn9gvqqmlahu", + "edited": false + }, + { + "id": "c043350000000000000000000000000000000000000000000000000000000000", + "content": "", + "replied_to": "", + "preview_metadata": null, + "attachments": [ + { + "id": "adba5bd953d31858da35fa27f847c5b2511a3b2c2e4cde6a18716b09a2a057cf", + "key": "", + "nonce": "", + "extension": "heic", + "name": "IMG_4127.HEIC", + "url": "https://example.invalid/recording", + "path": "media/photo.heic", + "size": 6555, + "img_meta": { + "thumbhash": "", + "width": 1600, + "height": 1000 + }, + "downloading": false, + "downloaded": true + } + ], + "reactions": [], + "at": 1794362393000, + "pending": false, + "failed": false, + "mine": false, + "npub": "npub15387nevpzd0u700y2t24ym9l0zxe8fsxx2w7qn47ysn6mndn9gvqqmlahu", + "edited": false + }, + { + "id": "c043360000000000000000000000000000000000000000000000000000000000", + "content": "", + "replied_to": "", + "preview_metadata": null, + "attachments": [ + { + "id": "81e00555f1ff1708bc94ec9cc445cde14c19d6014b89725d19156a1936274e86", + "key": "", + "nonce": "", + "extension": "heics", + "name": "burst.heics", + "url": "https://example.invalid/recording", + "path": "media/sequence.heics", + "size": 2016, + "img_meta": { + "thumbhash": "", + "width": 64, + "height": 48 + }, + "downloading": false, + "downloaded": true + } + ], + "reactions": [], + "at": 1794362396000, + "pending": false, + "failed": false, + "mine": false, + "npub": "npub15387nevpzd0u700y2t24ym9l0zxe8fsxx2w7qn47ysn6mndn9gvqqmlahu", + "edited": false + }, + { + "id": "c044400000000000000000000000000000000000000000000000000000000000", + "content": "", + "replied_to": "", + "preview_metadata": null, + "attachments": [ + { + "id": "e2f2737c1e1529d75d7a55cae8489d272e3c41e5d2c278df0740aee61dd42498", + "key": "", + "nonce": "", + "extension": "mp4", + "name": "", + "url": "https://example.invalid/clip", + "path": "media/clip.mp4", + "size": 179263, + "img_meta": { + "thumbhash": "", + "width": 640, + "height": 360 + }, + "downloading": false, + "downloaded": true + } + ], + "reactions": [], + "at": 1794362400000, + "pending": false, + "failed": false, + "mine": false, + "npub": "npub15387nevpzd0u700y2t24ym9l0zxe8fsxx2w7qn47ysn6mndn9gvqqmlahu", + "edited": false + }, + { + "id": "c055500000000000000000000000000000000000000000000000000000000000", + "content": "", + "replied_to": "", + "preview_metadata": null, + "attachments": [ + { + "id": "84a0b1daf40586ed20ab02dddb247d335fa3308deb404f2189e06dcdb5532826", + "key": "", + "nonce": "", + "extension": "mov", + "name": "", + "url": "https://example.invalid/turned", + "path": "media/turned.mov", + "size": 179314, + "img_meta": { + "thumbhash": "", + "width": 360, + "height": 640 + }, + "downloading": false, + "downloaded": true + } + ], + "reactions": [], + "at": 1794362430000, + "pending": false, + "failed": false, + "mine": false, + "npub": "npub15387nevpzd0u700y2t24ym9l0zxe8fsxx2w7qn47ysn6mndn9gvqqmlahu", + "edited": false + } + ], + "last_read": "c045acf2d273a786b030c9bc52f82e5208621ae4f0f7400c6ed71f088498e0d3", + "unread_from": "", + "created_at": 1794189540, + "metadata": { + "custom_fields": {} + }, + "muted": false, + "notify": 2, + "everyone_pings": true, + "community_muted": false + }, + { + "id": "npub190vqdjtlpcq27xslcveglfmr4ynfwg7gmw86cnun4acakxrdd6gqnp929a", + "chat_type": "DirectMessage", + "participants": [ + "npub190vqdjtlpcq27xslcveglfmr4ynfwg7gmw86cnun4acakxrdd6gqnp929a" + ], + "messages": [ + { + "id": "8151ec931604feccea39c49138f698e832871901bfe95d7e8e1278836da509cd", + "content": "Hey! It's Alice", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1794359280000, + "pending": false, + "failed": false, + "mine": false, + "npub": "npub190vqdjtlpcq27xslcveglfmr4ynfwg7gmw86cnun4acakxrdd6gqnp929a", + "edited": false + }, + { + "id": "a42ac5108869b599bcbac21069f63fb47f07452fcc4b87e89b3c06a945612d0b", + "content": "Hey, how are you doing?", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1794359400000, + "pending": false, + "failed": false, + "mine": true, + "npub": "npub1yazve5gvw5em6um2mzg0nh2u4v4dkfas04gqh9yn72wdcssvktsqfmmmv4", + "edited": false + }, + { + "id": "e9969eb8667d15372c967cfe5402b12ecb4b64a8c563088ca80237ff5ecf83d5", + "content": "Pretty good, working on something fun.", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1794359580000, + "pending": false, + "failed": false, + "mine": false, + "npub": "npub190vqdjtlpcq27xslcveglfmr4ynfwg7gmw86cnun4acakxrdd6gqnp929a", + "edited": false + }, + { + "id": "532819ebaebe89404671ee38eefd39495c7ec8342347bc31de2c67d55229ce4a", + "content": "Ooh, tell me more when you can \ud83d\udc40", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1794359640000, + "pending": false, + "failed": false, + "mine": true, + "npub": "npub1yazve5gvw5em6um2mzg0nh2u4v4dkfas04gqh9yn72wdcssvktsqfmmmv4", + "edited": false + }, + { + "id": "d402d566b92e2040b3378d4cad8f136f2790f973143ef12b857148cab29dea11", + "content": "Running late, save me a seat!", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1794362280000, + "pending": false, + "failed": false, + "mine": false, + "npub": "npub190vqdjtlpcq27xslcveglfmr4ynfwg7gmw86cnun4acakxrdd6gqnp929a", + "edited": false + } + ], + "last_read": "a42ac5108869b599bcbac21069f63fb47f07452fcc4b87e89b3c06a945612d0b", + "unread_from": "", + "created_at": 1794358680, + "metadata": { + "custom_fields": {} + }, + "muted": false, + "notify": 2, + "everyone_pings": true, + "community_muted": false + }, + { + "id": "npub1sxmr0k8u6trd5c6eu6trzyapzux7090ykujmsng7pdx0m8k93n5sd02fwn", + "chat_type": "DirectMessage", + "participants": [ + "npub1sxmr0k8u6trd5c6eu6trzyapzux7090ykujmsng7pdx0m8k93n5sd02fwn" + ], + "messages": [ + { + "id": "0e7dcc98d6c20f8d5560821e454650cb0f8b7e07accecf1547bde134a467624d", + "content": "Hey! It's Bob", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1794357900000, + "pending": false, + "failed": false, + "mine": false, + "npub": "npub1sxmr0k8u6trd5c6eu6trzyapzux7090ykujmsng7pdx0m8k93n5sd02fwn", + "edited": false + }, + { + "id": "a5fc3eac9107fe9b449965916d54b334233b8077a37f782d9b59e6e98e04def8", + "content": "Hey, how are you doing?", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1794358020000, + "pending": false, + "failed": false, + "mine": true, + "npub": "npub1yazve5gvw5em6um2mzg0nh2u4v4dkfas04gqh9yn72wdcssvktsqfmmmv4", + "edited": false + }, + { + "id": "a9137698d8d3fdbf27efcdc8cd372084b52d484e8db866c5455bbb3f85299b54", + "content": "Pretty good, working on something fun.", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1794358200000, + "pending": false, + "failed": false, + "mine": false, + "npub": "npub1sxmr0k8u6trd5c6eu6trzyapzux7090ykujmsng7pdx0m8k93n5sd02fwn", + "edited": false + }, + { + "id": "a6a17c7ac82f305add533b6fa9860dee624d3df3ac3745a5007ea24ca2047f6a", + "content": "Ooh, tell me more when you can \ud83d\udc40", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1794358260000, + "pending": false, + "failed": false, + "mine": true, + "npub": "npub1yazve5gvw5em6um2mzg0nh2u4v4dkfas04gqh9yn72wdcssvktsqfmmmv4", + "edited": false + }, + { + "id": "598b288443e42c9a93f5562409ac78c385fe4d66c95174330c4805b79fa67f52", + "content": "The new build is so much faster \ud83d\ude80", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1794360900000, + "pending": false, + "failed": false, + "mine": false, + "npub": "npub1sxmr0k8u6trd5c6eu6trzyapzux7090ykujmsng7pdx0m8k93n5sd02fwn", + "edited": false + } + ], + "last_read": "598b288443e42c9a93f5562409ac78c385fe4d66c95174330c4805b79fa67f52", + "unread_from": "", + "created_at": 1794357300, + "metadata": { + "custom_fields": {} + }, + "muted": false, + "notify": 2, + "everyone_pings": true, + "community_muted": false + }, + { + "id": "npub1fsndjp6vylvfahjeyuxq4s2tw8s8rv2j89ge7a28fvhnhf35s86sg3uctf", + "chat_type": "DirectMessage", + "participants": [ + "npub1fsndjp6vylvfahjeyuxq4s2tw8s8rv2j89ge7a28fvhnhf35s86sg3uctf" + ], + "messages": [ + { + "id": "84d31f0608eb78e78d7f480dd0e99047ea64ab3546571b2cbe25aa40c5594d3e", + "content": "Hey! It's Carol", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1794348600000, + "pending": false, + "failed": false, + "mine": false, + "npub": "npub1fsndjp6vylvfahjeyuxq4s2tw8s8rv2j89ge7a28fvhnhf35s86sg3uctf", + "edited": false + }, + { + "id": "b52a4abe79e15521cfb98270bbb4df9a2180df897028e9ef5b2078fe898e3b86", + "content": "Hey, how are you doing?", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1794348720000, + "pending": false, + "failed": false, + "mine": true, + "npub": "npub1yazve5gvw5em6um2mzg0nh2u4v4dkfas04gqh9yn72wdcssvktsqfmmmv4", + "edited": false + }, + { + "id": "ccae70ef441818f6e600d906bb15f26822cd2c75f52236c669c78db9eef71d7b", + "content": "Pretty good, working on something fun.", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1794348900000, + "pending": false, + "failed": false, + "mine": false, + "npub": "npub1fsndjp6vylvfahjeyuxq4s2tw8s8rv2j89ge7a28fvhnhf35s86sg3uctf", + "edited": false + }, + { + "id": "af6f12698ed64974e2947593be116ca71c0abfbc0bd4614f55e383e3359bc386", + "content": "Ooh, tell me more when you can \ud83d\udc40", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1794348960000, + "pending": false, + "failed": false, + "mine": true, + "npub": "npub1yazve5gvw5em6um2mzg0nh2u4v4dkfas04gqh9yn72wdcssvktsqfmmmv4", + "edited": false + }, + { + "id": "f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0", + "content": "Grab this pack https://vectorapp.io/emojis/pack/naddr1qqzkymr0vfesygypkcma3lxjcmdxxk0xjcc38gghphnete9hykuy68stfn7ea3vvaypsgqqqw48qsh6h7r", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1794349020000, + "pending": false, + "failed": false, + "mine": true, + "npub": "npub1yazve5gvw5em6um2mzg0nh2u4v4dkfas04gqh9yn72wdcssvktsqfmmmv4", + "edited": false + }, + { + "id": "fc9be69f77ac6387b476bf18eecac0d49e846462bf151d098b956d642c9257c4", + "content": "haha yes exactly", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1794351600000, + "pending": false, + "failed": false, + "mine": false, + "npub": "npub1fsndjp6vylvfahjeyuxq4s2tw8s8rv2j89ge7a28fvhnhf35s86sg3uctf", + "edited": false + } + ], + "last_read": "af6f12698ed64974e2947593be116ca71c0abfbc0bd4614f55e383e3359bc386", + "unread_from": "", + "created_at": 1794348000, + "metadata": { + "custom_fields": {} + }, + "muted": false, + "notify": 2, + "everyone_pings": true, + "community_muted": false + }, + { + "id": "npub1v84qsqlcs56j8dmh6s22eccnpn2d87fdutxhl7rftseh67wzamhqfv9ft6", + "chat_type": "DirectMessage", + "participants": [ + "npub1v84qsqlcs56j8dmh6s22eccnpn2d87fdutxhl7rftseh67wzamhqfv9ft6" + ], + "messages": [ + { + "id": "df3800172069679be70df9a4408362938ec13352f6965b4b6ae83e8b15ec4b7b", + "content": "Hey! It's Dave", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1794287400000, + "pending": false, + "failed": false, + "mine": false, + "npub": "npub1v84qsqlcs56j8dmh6s22eccnpn2d87fdutxhl7rftseh67wzamhqfv9ft6", + "edited": false + }, + { + "id": "b1b6970a41ecda3f826c36d4704439a99271fc68fa320d6de8a6770236bafca7", + "content": "Hey, how are you doing?", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1794287520000, + "pending": false, + "failed": false, + "mine": true, + "npub": "npub1yazve5gvw5em6um2mzg0nh2u4v4dkfas04gqh9yn72wdcssvktsqfmmmv4", + "edited": false + }, + { + "id": "256d5942571987a8f984f2a6de380b961f092da1367181c7f36815f322e092c8", + "content": "Pretty good, working on something fun.", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1794287700000, + "pending": false, + "failed": false, + "mine": false, + "npub": "npub1v84qsqlcs56j8dmh6s22eccnpn2d87fdutxhl7rftseh67wzamhqfv9ft6", + "edited": false + }, + { + "id": "a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1", + "content": "Ask @npub10j7vkrzv4t0elnd4rmj902pge3e2gkresvd4h9u2ut3valzyjuzsz7ad26 or nostr:npub1wajx7kj0x9nxxa38405e3eapgu87wtvtgv8svld04p3x8u0j872qnta00x, they set up https://vectorapp.io/profile/npub10j7vkrzv4t0elnd4rmj902pge3e2gkresvd4h9u2ut3valzyjuzsz7ad26 last week.", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1794287730000, + "pending": false, + "failed": false, + "mine": false, + "npub": "npub1v84qsqlcs56j8dmh6s22eccnpn2d87fdutxhl7rftseh67wzamhqfv9ft6", + "edited": false + }, + { + "id": "738b726df924c6da31999c37456119362e7a3bde84378f4409be99747cafa1c8", + "content": "Pay me here: DLabsktzGMnsK5K9uRTMCF6NoYNY6ET4Bb", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1794287745000, + "pending": false, + "failed": false, + "mine": false, + "npub": "npub1v84qsqlcs56j8dmh6s22eccnpn2d87fdutxhl7rftseh67wzamhqfv9ft6", + "edited": false + }, + { + "id": "0cd834c4a78e321bcf7377b9a94b89995fec1ec2c493563d6af759565ce3adb1", + "content": "Ooh, tell me more when you can \ud83d\udc40", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1794287760000, + "pending": false, + "failed": false, + "mine": true, + "npub": "npub1yazve5gvw5em6um2mzg0nh2u4v4dkfas04gqh9yn72wdcssvktsqfmmmv4", + "edited": false + }, + { + "id": "31fe2982dff7210a144b3af820a570e62650b652ecc1ca8a7a1c46c4360a1fcf", + "content": "Sent you the invoice", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1794290400000, + "pending": false, + "failed": false, + "mine": false, + "npub": "npub1v84qsqlcs56j8dmh6s22eccnpn2d87fdutxhl7rftseh67wzamhqfv9ft6", + "edited": false + } + ], + "last_read": "31fe2982dff7210a144b3af820a570e62650b652ecc1ca8a7a1c46c4360a1fcf", + "unread_from": "", + "created_at": 1794286800, + "metadata": { + "custom_fields": {} + }, + "muted": false, + "notify": 2, + "everyone_pings": true, + "community_muted": false + }, + { + "id": "npub10j7vkrzv4t0elnd4rmj902pge3e2gkresvd4h9u2ut3valzyjuzsz7ad26", + "chat_type": "DirectMessage", + "participants": [ + "npub10j7vkrzv4t0elnd4rmj902pge3e2gkresvd4h9u2ut3valzyjuzsz7ad26" + ], + "messages": [ + { + "id": "2dfc7f1fec2378642603513880c3d185c1d946c80fe462ddd746d9a966fee6c6", + "content": "Hey! It's Erin", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1794265800000, + "pending": false, + "failed": false, + "mine": false, + "npub": "npub10j7vkrzv4t0elnd4rmj902pge3e2gkresvd4h9u2ut3valzyjuzsz7ad26", + "edited": false + }, + { + "id": "fa66a85f397a2570a1bd24cc913ede2ae20e52760450debd2be0dc3e8264b6cf", + "content": "Hey, how are you doing?", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1794265920000, + "pending": false, + "failed": false, + "mine": true, + "npub": "npub1yazve5gvw5em6um2mzg0nh2u4v4dkfas04gqh9yn72wdcssvktsqfmmmv4", + "edited": false + }, + { + "id": "4d01f2c559d2131367694374a6d4b7c8d25406b9d288e441a97fa246b58b916e", + "content": "Pretty good, working on something fun.", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1794266100000, + "pending": false, + "failed": false, + "mine": false, + "npub": "npub10j7vkrzv4t0elnd4rmj902pge3e2gkresvd4h9u2ut3valzyjuzsz7ad26", + "edited": false + }, + { + "id": "6bb9076027cd5db478938eea32df3cd109814cd0842ee2130a86b2d30922fc5a", + "content": "Ooh, tell me more when you can \ud83d\udc40", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1794266160000, + "pending": false, + "failed": false, + "mine": true, + "npub": "npub1yazve5gvw5em6um2mzg0nh2u4v4dkfas04gqh9yn72wdcssvktsqfmmmv4", + "edited": false + }, + { + "id": "77ba0426a3e472fdc0b2d2037f5c274825b8c5a4b90a7b7e77c4d1b8d84d8be2", + "content": "Can you check the relay list later?", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1794268800000, + "pending": false, + "failed": false, + "mine": false, + "npub": "npub10j7vkrzv4t0elnd4rmj902pge3e2gkresvd4h9u2ut3valzyjuzsz7ad26", + "edited": false + } + ], + "last_read": "77ba0426a3e472fdc0b2d2037f5c274825b8c5a4b90a7b7e77c4d1b8d84d8be2", + "unread_from": "", + "created_at": 1794265200, + "metadata": { + "custom_fields": {} + }, + "muted": false, + "notify": 2, + "everyone_pings": true, + "community_muted": false + }, + { + "id": "npub1wajx7kj0x9nxxa38405e3eapgu87wtvtgv8svld04p3x8u0j872qnta00x", + "chat_type": "DirectMessage", + "participants": [ + "npub1wajx7kj0x9nxxa38405e3eapgu87wtvtgv8svld04p3x8u0j872qnta00x" + ], + "messages": [ + { + "id": "916d83f3c60ae97786062fd90dd4fa836778f764fec4d72b69707a9ae0497b9d", + "content": "Hey! It's Frank", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1794100200000, + "pending": false, + "failed": false, + "mine": false, + "npub": "npub1wajx7kj0x9nxxa38405e3eapgu87wtvtgv8svld04p3x8u0j872qnta00x", + "edited": false + }, + { + "id": "a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7", + "content": "made a little game, try it: https://apps.example.org/games/chess.xdc", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1794100260000, + "pending": false, + "failed": false, + "mine": false, + "npub": "npub1wajx7kj0x9nxxa38405e3eapgu87wtvtgv8svld04p3x8u0j872qnta00x", + "edited": false + }, + { + "id": "9f5f848bfd4eaec7636efa22c4fafc7f5ef5a3b3abcf69eecc0ca906945c821e", + "content": "Hey, how are you doing?", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1794100320000, + "pending": false, + "failed": false, + "mine": true, + "npub": "npub1yazve5gvw5em6um2mzg0nh2u4v4dkfas04gqh9yn72wdcssvktsqfmmmv4", + "edited": false + }, + { + "id": "0dd69c24d98198c02a74c49c23b00c3ebed2897d6b18bf3fa9e22377e0de17bd", + "content": "Pretty good, working on something fun.", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1794100500000, + "pending": false, + "failed": false, + "mine": false, + "npub": "npub1wajx7kj0x9nxxa38405e3eapgu87wtvtgv8svld04p3x8u0j872qnta00x", + "edited": false + }, + { + "id": "e1ea99b2aa44648632472ac1ba8b433fb7792a754edbe16bb4104676c60aeb32", + "content": "Ooh, tell me more when you can \ud83d\udc40", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1794100560000, + "pending": false, + "failed": false, + "mine": true, + "npub": "npub1yazve5gvw5em6um2mzg0nh2u4v4dkfas04gqh9yn72wdcssvktsqfmmmv4", + "edited": false + }, + { + "id": "701941eb2099073cce5789d43667b92d69aeed4c279da1bcc248cb18ea08a203", + "content": "gm", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1794103200000, + "pending": false, + "failed": false, + "mine": false, + "npub": "npub1wajx7kj0x9nxxa38405e3eapgu87wtvtgv8svld04p3x8u0j872qnta00x", + "edited": false + } + ], + "last_read": "701941eb2099073cce5789d43667b92d69aeed4c279da1bcc248cb18ea08a203", + "unread_from": "", + "created_at": 1794099600, + "metadata": { + "custom_fields": {} + }, + "muted": false, + "notify": 2, + "everyone_pings": true, + "community_muted": false, + "wallpaper_path": "media/photo.png", + "wallpaper_ts": 1, + "wallpaper_blur": 5, + "wallpaper_dim": 50 + }, + { + "id": "npub1uqg0688p4nqh8ca5sddhvd0c63sq6a6gdygz4k6uk76a0z2kfxaqmmg7t4", + "chat_type": "DirectMessage", + "participants": [ + "npub1uqg0688p4nqh8ca5sddhvd0c63sq6a6gdygz4k6uk76a0z2kfxaqmmg7t4" + ], + "messages": [ + { + "id": "50b5f31dfb00f33f086e1ae2abc4438be0a843062a9ba57e320d341c5fbcd145", + "content": "Hey! It's Grace", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1793581800000, + "pending": false, + "failed": false, + "mine": false, + "npub": "npub1uqg0688p4nqh8ca5sddhvd0c63sq6a6gdygz4k6uk76a0z2kfxaqmmg7t4", + "edited": false + }, + { + "id": "46fdae29620a12a9aacbbc73f5fc7aeb4eb997d686bfb289be1dae882cfb61e0", + "content": "Hey, how are you doing?", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1793581920000, + "pending": false, + "failed": false, + "mine": true, + "npub": "npub1yazve5gvw5em6um2mzg0nh2u4v4dkfas04gqh9yn72wdcssvktsqfmmmv4", + "edited": false + }, + { + "id": "2ee330e99ab8daeca8dc2cc9743c0904a536ec62226660ae640c6abba3f8118a", + "content": "Pretty good, working on something fun.", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1793582100000, + "pending": false, + "failed": false, + "mine": false, + "npub": "npub1uqg0688p4nqh8ca5sddhvd0c63sq6a6gdygz4k6uk76a0z2kfxaqmmg7t4", + "edited": false + }, + { + "id": "1c13bd769a5602ef0fa2e909d49fad4cc9955d09d41a2a0fd233f53dd7b5ab59", + "content": "Ooh, tell me more when you can \ud83d\udc40", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1793582160000, + "pending": false, + "failed": false, + "mine": true, + "npub": "npub1yazve5gvw5em6um2mzg0nh2u4v4dkfas04gqh9yn72wdcssvktsqfmmmv4", + "edited": false + }, + { + "id": "a5bb91d4e778afed68b313afd3c981a59cf7f3a49fbf72efe8974ce87f526218", + "content": "It's easier to ask forgiveness than permission.", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1793584800000, + "pending": false, + "failed": false, + "mine": false, + "npub": "npub1uqg0688p4nqh8ca5sddhvd0c63sq6a6gdygz4k6uk76a0z2kfxaqmmg7t4", + "edited": false + } + ], + "last_read": "a5bb91d4e778afed68b313afd3c981a59cf7f3a49fbf72efe8974ce87f526218", + "unread_from": "", + "created_at": 1793581200, + "metadata": { + "custom_fields": {} + }, + "muted": false, + "notify": 2, + "everyone_pings": true, + "community_muted": false + }, + { + "id": "npub1qk3nrfl57xffl2k29zdxd7vdtgzm8p7ee045lrpdmqsy56cz8g2qqxdt9s", + "chat_type": "DirectMessage", + "participants": [ + "npub1qk3nrfl57xffl2k29zdxd7vdtgzm8p7ee045lrpdmqsy56cz8g2qqxdt9s" + ], + "messages": [ + { + "id": "4fb91cf06af8fc36e9a29cd59245441d204dc24b8c4a7f7ff5fb2d157c11c608", + "content": "Hey! It's Heidi", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1790903400000, + "pending": false, + "failed": false, + "mine": false, + "npub": "npub1qk3nrfl57xffl2k29zdxd7vdtgzm8p7ee045lrpdmqsy56cz8g2qqxdt9s", + "edited": false + }, + { + "id": "d9ff57dd878fcd98c1110de3224817685f9a9a19d453112c2dfed9216645bdd8", + "content": "Hey, how are you doing?", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1790903520000, + "pending": false, + "failed": false, + "mine": true, + "npub": "npub1yazve5gvw5em6um2mzg0nh2u4v4dkfas04gqh9yn72wdcssvktsqfmmmv4", + "edited": false + }, + { + "id": "f8c2dd42b5d4d876a4332c56e38594d68795b82589d0e981a6c30edc0f2cda00", + "content": "Pretty good, working on something fun.", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1790903700000, + "pending": false, + "failed": false, + "mine": false, + "npub": "npub1qk3nrfl57xffl2k29zdxd7vdtgzm8p7ee045lrpdmqsy56cz8g2qqxdt9s", + "edited": false + }, + { + "id": "8f59f5a85a3503d368364ff444a7e1d38ca8a0be2d207b0c41683a21f96807f5", + "content": "Ooh, tell me more when you can \ud83d\udc40", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1790903760000, + "pending": false, + "failed": false, + "mine": true, + "npub": "npub1yazve5gvw5em6um2mzg0nh2u4v4dkfas04gqh9yn72wdcssvktsqfmmmv4", + "edited": false + }, + { + "id": "e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0", + "content": "Have you seen this? :grin: nostr:note1wg33qsaurqr7da6qkg67kag3ajeny4dx5d65x433r9k732t4p49sk04fpd", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [ + { + "id": "r1", + "reference_id": "e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0", + "author_id": "npub1yazve5gvw5em6um2mzg0nh2u4v4dkfas04gqh9yn72wdcssvktsqfmmmv4", + "emoji": ":grin:", + "emoji_url": "https://ref.invalid/media/emoji-grin.png" + } + ], + "at": 1790903820000, + "pending": false, + "failed": false, + "mine": false, + "npub": "npub1qk3nrfl57xffl2k29zdxd7vdtgzm8p7ee045lrpdmqsy56cz8g2qqxdt9s", + "edited": false, + "emoji_tags": [ + { + "shortcode": "grin", + "url": "https://ref.invalid/media/emoji-grin.png" + } + ] + }, + { + "id": "e1e1e1e1e1e1e1e1e1e1e1e1e1e1e1e1e1e1e1e1e1e1e1e1e1e1e1e1e1e1e1e1", + "content": "Great write-up https://njump.me/naddr1qqx8yetvv9uj6er9wd5kwmszyq4aspkf0u8qptc6rlpn9ra8vw5jd9ererdcltz0jwhhrkccd4hfqqcyqqq823cyhyg2k", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1790903880000, + "pending": false, + "failed": false, + "mine": true, + "npub": "npub1yazve5gvw5em6um2mzg0nh2u4v4dkfas04gqh9yn72wdcssvktsqfmmmv4", + "edited": false + }, + { + "id": "e2e2e2e2e2e2e2e2e2e2e2e2e2e2e2e2e2e2e2e2e2e2e2e2e2e2e2e2e2e2e2e2", + "content": "nostr:nevent1qqsqe2cujct5qna09vjwyg0p3899j3vp8c2d8amxx3dsnjsnh03gllqzyzqmvd7clnfvdknrt8nfvvgn5ytsmeu4ujmjtwzdrc95elv7ckxwjqcyqqqgtwc9z4mnx and this one nostr:nevent1qqs0lf34s006vurtslfgfwrtp45n59s7fpq245k9ea446f7rh93p7lgrqsqqqqqpguxfpx", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1790903940000, + "pending": false, + "failed": false, + "mine": false, + "npub": "npub1qk3nrfl57xffl2k29zdxd7vdtgzm8p7ee045lrpdmqsy56cz8g2qqxdt9s", + "edited": false + }, + { + "id": "c33c8607c4f223f4233f68b92e7fef6b309201b87fb34d1bdfa18e4e13752e76", + "content": "See you on Saturday", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1790906400000, + "pending": false, + "failed": false, + "mine": false, + "npub": "npub1qk3nrfl57xffl2k29zdxd7vdtgzm8p7ee045lrpdmqsy56cz8g2qqxdt9s", + "edited": false + } + ], + "last_read": "c33c8607c4f223f4233f68b92e7fef6b309201b87fb34d1bdfa18e4e13752e76", + "unread_from": "", + "created_at": 1790902800, + "metadata": { + "custom_fields": {} + }, + "muted": false, + "notify": 2, + "everyone_pings": true, + "community_muted": false + }, + { + "id": "npub19ayt3q02wpelr3hsswefdgmqh4xfeag7m2kt58xecdxc4c7ejnkq92s7dr", + "chat_type": "DirectMessage", + "participants": [ + "npub19ayt3q02wpelr3hsswefdgmqh4xfeag7m2kt58xecdxc4c7ejnkq92s7dr" + ], + "messages": [ + { + "id": "53b8cc19da5f56354d0281c9daa68f89304c11dc11942342d0b4553b88aefa8c", + "content": "Have a read: https://example.invalid/posts/private-by-default", + "replied_to": "", + "preview_metadata": { + "domain": "https://example.invalid/", + "og_title": "Private by default", + "og_description": "Why every message you send should be sealed before it leaves your device.\nA look at gift wraps, relays and what they can never learn.
Part one of three.", + "og_image": "https://example.invalid/og.png", + "og_url": "https://example.invalid/posts/private-by-default", + "og_type": null, + "title": null, + "description": null, + "favicon": "https://example.invalid/favicon.ico" + }, + "attachments": [], + "reactions": [], + "at": 1794101400000, + "pending": false, + "failed": false, + "mine": false, + "npub": "npub19ayt3q02wpelr3hsswefdgmqh4xfeag7m2kt58xecdxc4c7ejnkq92s7dr", + "edited": false + }, + { + "id": "eecc0a5093579f0de707c656ea2289edffb6ea722dca762b7bcfe2414090846d", + "content": "https://example.invalid/docs", + "replied_to": "", + "preview_metadata": { + "domain": "https://example.invalid/", + "og_title": null, + "og_description": null, + "og_image": null, + "og_url": null, + "og_type": null, + "title": "Docs", + "description": "Short and to the point.", + "favicon": "https://example.invalid/favicon.ico" + }, + "attachments": [], + "reactions": [], + "at": 1794102000000, + "pending": false, + "failed": false, + "mine": true, + "npub": "npub1yazve5gvw5em6um2mzg0nh2u4v4dkfas04gqh9yn72wdcssvktsqfmmmv4", + "edited": false + }, + { + "id": "97a55d29a973a83f670c1f48c92336dd35248f3f744445bd1de09275ca189bdf", + "content": "Watch this https://www.youtube.com/watch?v=dQw4w9WgXcQ", + "replied_to": "", + "preview_metadata": { + "domain": "https://www.youtube.com/", + "og_title": "A video worth watching", + "og_description": "Uploaded by somebody.", + "og_image": "https://i.ytimg.com/vi/dQw4w9WgXcQ/hqdefault.jpg", + "og_url": "https://www.youtube.com/watch?v=dQw4w9WgXcQ", + "og_type": null, + "title": null, + "description": null, + "favicon": "https://example.invalid/favicon.ico" + }, + "attachments": [], + "reactions": [], + "at": 1794102600000, + "pending": false, + "failed": false, + "mine": false, + "npub": "npub19ayt3q02wpelr3hsswefdgmqh4xfeag7m2kt58xecdxc4c7ejnkq92s7dr", + "edited": false + } + ], + "last_read": "97a55d29a973a83f670c1f48c92336dd35248f3f744445bd1de09275ca189bdf", + "unread_from": "", + "created_at": 1794016800, + "metadata": { + "custom_fields": {} + }, + "muted": false, + "notify": 2, + "everyone_pings": true, + "community_muted": false + }, + { + "id": "a0f367a05f629b3bb09ee8f1561bf03267962217d9ff6fc7ce3b235235702bc1", + "chat_type": "Community", + "participants": [], + "messages": [ + { + "id": "7a3c760d48ddcb81b5b84767bdb6888628fe32badc3075ee364324255c1f53a1", + "content": "Welcome to the new community!", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1794360000000, + "pending": false, + "failed": false, + "mine": false, + "npub": "npub190vqdjtlpcq27xslcveglfmr4ynfwg7gmw86cnun4acakxrdd6gqnp929a", + "edited": false + }, + { + "id": "e55c72814cdc85d3ec5df9cf7d0f7856eae78a3f8e67281a81f2ef2adb3660e6", + "content": "Glad to be here \ud83d\udc4b", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1794360600000, + "pending": false, + "failed": false, + "mine": false, + "npub": "npub1sxmr0k8u6trd5c6eu6trzyapzux7090ykujmsng7pdx0m8k93n5sd02fwn", + "edited": false + }, + { + "id": "3b5ddcbb97a2556731cd4376b27b365b56eb569277b419bc8afe248833527732", + "content": "The GPUI port is coming along nicely.", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1794361200000, + "pending": false, + "failed": false, + "mine": true, + "npub": "npub1yazve5gvw5em6um2mzg0nh2u4v4dkfas04gqh9yn72wdcssvktsqfmmmv4", + "edited": false + }, + { + "id": "1196b072a6d5283c763dea302077985c28cbe827c0b18e82d9533abd63e51100", + "content": "Can't wait to try it.", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1794361800000, + "pending": false, + "failed": false, + "mine": false, + "npub": "npub1fsndjp6vylvfahjeyuxq4s2tw8s8rv2j89ge7a28fvhnhf35s86sg3uctf", + "edited": false + } + ], + "last_read": "1196b072a6d5283c763dea302077985c28cbe827c0b18e82d9533abd63e51100", + "unread_from": "", + "created_at": 1794362400, + "metadata": { + "custom_fields": { + "community_id": "ca848c275e2117470342c641ada0ae4639dd0472ab4a5ec654a189bf1f689087", + "name": "Vector Devs", + "description": "Where Vector gets built, in the open.", + "primary_channel": "a0f367a05f629b3bb09ee8f1561bf03267962217d9ff6fc7ce3b235235702bc1", + "owner_npub": "npub1yazve5gvw5em6um2mzg0nh2u4v4dkfas04gqh9yn72wdcssvktsqfmmmv4", + "is_owner": "true", + "channel_name": "general" + } + }, + "muted": false, + "notify": 2, + "everyone_pings": true, + "community_muted": false + }, + { + "id": "d961d1281aed7b3ad2f6964aa7e59d427d8b921a8f7dd8c4c0f0a0e1422a17d1", + "chat_type": "Community", + "participants": [], + "messages": [ + { + "id": "c42822194abfc07af77d310d9fd4d35d0fba4fa68d45d753e5a99181c926caea", + "content": "CI is green again, @everyone go pull.", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1794361200000, + "pending": false, + "failed": false, + "mine": false, + "npub": "npub1sxmr0k8u6trd5c6eu6trzyapzux7090ykujmsng7pdx0m8k93n5sd02fwn", + "edited": false + }, + { + "id": "47c3066a117648de8e251a190b356d8be10c166b1ef1c10d074239a848a8a441", + "content": "Nice, merging the calls branch next.", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1794361800000, + "pending": false, + "failed": false, + "mine": true, + "npub": "npub1yazve5gvw5em6um2mzg0nh2u4v4dkfas04gqh9yn72wdcssvktsqfmmmv4", + "edited": false + } + ], + "last_read": "47c3066a117648de8e251a190b356d8be10c166b1ef1c10d074239a848a8a441", + "unread_from": "", + "created_at": 1794362400, + "metadata": { + "custom_fields": { + "community_id": "ca848c275e2117470342c641ada0ae4639dd0472ab4a5ec654a189bf1f689087", + "name": "Vector Devs", + "description": "Where Vector gets built, in the open.", + "primary_channel": "a0f367a05f629b3bb09ee8f1561bf03267962217d9ff6fc7ce3b235235702bc1", + "owner_npub": "npub1yazve5gvw5em6um2mzg0nh2u4v4dkfas04gqh9yn72wdcssvktsqfmmmv4", + "is_owner": "true", + "channel_name": "dev" + } + }, + "muted": false, + "notify": 2, + "everyone_pings": true, + "community_muted": false + }, + { + "id": "451269113943deb53e912b83f5e397cd38bdc2460928a14dbc4f766181425977", + "chat_type": "Community", + "participants": [], + "messages": [ + { + "id": "ae19a8aaa77fb5559a042d5498489758ca94951173813ea34c57d1f605f579c0", + "content": "New icons are in Figma.", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1794361800000, + "pending": false, + "failed": false, + "mine": false, + "npub": "npub1fsndjp6vylvfahjeyuxq4s2tw8s8rv2j89ge7a28fvhnhf35s86sg3uctf", + "edited": false + } + ], + "last_read": "ae19a8aaa77fb5559a042d5498489758ca94951173813ea34c57d1f605f579c0", + "unread_from": "", + "created_at": 1794362400, + "metadata": { + "custom_fields": { + "community_id": "ca848c275e2117470342c641ada0ae4639dd0472ab4a5ec654a189bf1f689087", + "name": "Vector Devs", + "description": "Where Vector gets built, in the open.", + "primary_channel": "a0f367a05f629b3bb09ee8f1561bf03267962217d9ff6fc7ce3b235235702bc1", + "owner_npub": "npub1yazve5gvw5em6um2mzg0nh2u4v4dkfas04gqh9yn72wdcssvktsqfmmmv4", + "is_owner": "true", + "channel_name": "design" + } + }, + "muted": false, + "notify": 2, + "everyone_pings": true, + "community_muted": false + }, + { + "id": "58e6267876fd6c4acb7fbc37091bb920e4f325e24df4887b8048d0ccf7137f2f", + "chat_type": "Community", + "participants": [], + "messages": [], + "last_read": "", + "unread_from": "", + "created_at": 1794362400, + "metadata": { + "custom_fields": { + "community_id": "ca848c275e2117470342c641ada0ae4639dd0472ab4a5ec654a189bf1f689087", + "name": "Vector Devs", + "description": "Where Vector gets built, in the open.", + "primary_channel": "a0f367a05f629b3bb09ee8f1561bf03267962217d9ff6fc7ce3b235235702bc1", + "owner_npub": "npub1yazve5gvw5em6um2mzg0nh2u4v4dkfas04gqh9yn72wdcssvktsqfmmmv4", + "is_owner": "true", + "channel_name": "Lounge" + } + }, + "muted": false, + "notify": 2, + "everyone_pings": true, + "community_muted": false + }, + { + "id": "npub1yn2tjm6cmfk54pgjxyam6q4z36lse22aa3hyeph00r887q083zkq7g4t6h", + "chat_type": "DirectMessage", + "participants": [ + "npub1yn2tjm6cmfk54pgjxyam6q4z36lse22aa3hyeph00r887q083zkq7g4t6h" + ], + "messages": [ + { + "id": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "content": "send me the loop?", + "replied_to": "", + "preview_metadata": null, + "attachments": [], + "reactions": [], + "at": 1787880000000, + "pending": false, + "failed": false, + "mine": true, + "npub": "npub1yazve5gvw5em6um2mzg0nh2u4v4dkfas04gqh9yn72wdcssvktsqfmmmv4", + "edited": false, + "expiration": 1893456000 + }, + { + "id": "b02add15a54a6a91cf66fe50248abdec79f84ed022c788d67a3984fb4fcadc50", + "content": "", + "replied_to": "", + "preview_metadata": null, + "attachments": [ + { + "id": "dbf76ea440dfc079815f321b2a42d64d59bf424324f88dd32b9c2eb09093c013", + "key": "", + "nonce": "", + "extension": "wav", + "name": "", + "url": "https://example.invalid/voice", + "path": "media/voice.wav", + "size": 118444, + "img_meta": null, + "downloading": false, + "downloaded": true + } + ], + "reactions": [], + "at": 1787880600000, + "pending": false, + "failed": false, + "mine": false, + "npub": "npub1yn2tjm6cmfk54pgjxyam6q4z36lse22aa3hyeph00r887q083zkq7g4t6h", + "edited": false + }, + { + "id": "29f486453349e2b4b77608d08f98d9adb8df9e0c1e4b5c3e62fd8e3d34d0b4cd", + "content": "and the loop", + "replied_to": "", + "preview_metadata": null, + "attachments": [ + { + "id": "cc3fe8261c75abf5327a1702b25bae4f31c36a248c8bbca54be9506eaff0725d", + "key": "", + "nonce": "", + "extension": "wav", + "name": "night-loop.wav", + "url": "https://example.invalid/loop", + "path": "media/loop.wav", + "size": 192044, + "img_meta": null, + "downloading": false, + "downloaded": true + } + ], + "reactions": [], + "at": 1787881200000, + "pending": false, + "failed": false, + "mine": false, + "npub": "npub1yn2tjm6cmfk54pgjxyam6q4z36lse22aa3hyeph00r887q083zkq7g4t6h", + "edited": false, + "expiration": 1893456000 + }, + { + "id": "5b1e0c3a9d7f4e2b8a6c1d0e9f8a7b6c5d4e3f2a1b0c9d8e7f6a5b4c3d2e1f00", + "content": "this one is on repeat", + "replied_to": "", + "preview_metadata": null, + "attachments": [ + { + "id": "a7d2c9e14b3f58e06c1a2b3d4e5f60718293a4b5c6d7e8f90a1b2c3d4e5f6a7b", + "key": "", + "nonce": "", + "extension": "mp3", + "name": "golden-hour.mp3", + "url": "https://example.invalid/golden", + "path": "media/golden-hour.mp3", + "size": 42473, + "img_meta": null, + "downloading": false, + "downloaded": true + } + ], + "reactions": [], + "at": 1787881500000, + "pending": false, + "failed": false, + "mine": false, + "npub": "npub1yn2tjm6cmfk54pgjxyam6q4z36lse22aa3hyeph00r887q083zkq7g4t6h", + "edited": false + }, + { + "id": "6c2f1d4b0e8a5f3c9b7d2e1a0f9e8d7c6b5a4f3e2d1c0b9a8f7e6d5c4b3a2f10", + "content": "whole album in one file", + "replied_to": "", + "preview_metadata": null, + "attachments": [ + { + "id": "b8e3d0f25c4a69f17d2b3c4e5f6a708192a3b4c5d6e7f8091a2b3c4d5e6f7a8c", + "key": "", + "nonce": "", + "extension": "mp3", + "name": "northern-lines.mp3", + "url": "https://example.invalid/northern", + "path": "media/northern-lines.mp3", + "size": 132767, + "img_meta": null, + "downloading": false, + "downloaded": true + } + ], + "reactions": [], + "at": 1787881800000, + "pending": false, + "failed": false, + "mine": false, + "npub": "npub1yn2tjm6cmfk54pgjxyam6q4z36lse22aa3hyeph00r887q083zkq7g4t6h", + "edited": false + } + ], + "last_read": "6c2f1d4b0e8a5f3c9b7d2e1a0f9e8d7c6b5a4f3e2d1c0b9a8f7e6d5c4b3a2f10", + "unread_from": "", + "created_at": 1787796000, + "metadata": { + "custom_fields": {} + }, + "muted": false, + "notify": 2, + "everyone_pings": true, + "community_muted": false + } + ], + "thumbs": { + "U(^ /twg4<&F@NQS~xhD@CSA": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAASCAYAAAA6yNxSAAAE+ElEQVR4Ae3AA6AkWZbG8f937o3IzKdyS2Oubdu2bdu2bdu2bWmMnpZKr54yMyLu+Xa3anqmhztr1a8+8jFf6FIKtVZq7ShRkES2ZJompnEkpwmRdDXYWHRsb804fmzBsZ05x3Z6tjeDzQ1YzJPFbGIxb2zMGxuLxmKRLObJrG90ZSJiBAbsCZzU+SwpIWpNak0ihICMpNAIT6QmIOlr0FXR10pXJ/ra6OtE3xX6Cn1N+i7pa6Orja4mfU260uhKo9ZGaAIa9gRO6vHtRgTUAqVARIKhtcY0jozDSJtGIOlqsDFPNuZicx5szgubc9icJxtz2Jgn83ljMZtYzBsb82QxS+azRt9P1DIRGrAH8Iid1GtOTESYUkyECTVsM42NYRgYh4FpmsBJV8Ri0djZhJ1NsbMpdjbN9mZhc0MsZsli3pjPJhbzxmKeLOaNWd/ou4kSI9KAvcY5Yif1+jONkIliQkaI1pJxnBjWa4b1wDiO4KQWsVg0drbMsS1xfFsc2zbbm5WNDbGYJ/NZYz5rLGaN+byxmDVmfaPWkRIDeMBekznibNSbrjFSEgHC2DBNyTCMrFcD69WacRiwk1KCxdxsb4lj24Xj24VjW2JrK9lciPnczPvGfDYxmzXms8Z81qjdBGUEDeAV5BraCG7UG86AAAnAZMI4NtbridVyYtWPDMNEZqNGMJ+L7a3KztbE8c2Jnc3C1obYWIj5LJnNGrO+MesnZrOG+gZ1gjICA+QAbQAGcKNec6ICQhI2tGbGQayWcFTMssCwNtmgBMznsLWA7QVsLWBzDptzs5jBrIe+g1ln+goqhmIoCUogQQk0oIEn6vGtnitEJrQpWReoNMKVyImOSmuNEoVZX5n3lXlXmdVKXytdVGpAkSkYuSAbXKAZFKAAAlrAFNAEGdRZnXOFyISJxG2kBXRhuoCMQDZFQVVPYUF4gTyHnJGt0CZoJCMFPEEGfTboAqYACWxoCVPiZrI1qtsCECCcJqckp45shZwK2So59WRLiEKbZrRpwThuMKwX1NIjCtnMWJNaJmqd6Gqj6ya62ihlIlSxC60VpqnQpkpmoy6PNgBhi0yYpmS9nlguO5bLjtWyZ72eaM2ECtlmwAJpAzEns2cYgq6aUhqlTJQyUctE1zW62ii1ERqwZ2Trmaae1gYyG/XixQUgQGSKaTLD0FiuBpZHM5bLgWFotAYRla6bMU4LprZgHOcs1x19J0oxEROhiVImam3U2ui6pJaJiAk80HJNm9a0NpA5Uc+eWwAChFNMDcahsVr3LJcjq9XEMCSZQlHpuxmr9YLVsGC5mtP3lVpFiUSaUIxETNTS6Lqk65JakxITMJK5prWB1gYyG/Xe+2YIgQJbtAbjaNbrxmo1sVo3xjHJDCI6+n7GbLXBYj1nNp/Rd5VSQEqkCRiJmKi10VXT9UlXTSkNaSRzINtAy5HMRj13rgMJCCDIFOMIw9BYrRvDOhknk1mI0tF3c2bzBathwWzV03WVCJAaMAIjoYlSk64zfW+6ztSSSBP2SMuBbCPpRt29VEBCKkCQGUwTDENhPSTDkEwTpAsleoZ+ztgWTG3BMPV0taAAaOACFBQTtSRdZ/oe+t6UkkQ07JHMjswRZ1KXKyEFUmACZzA1GEexXothCKYJTCGiYipSh6JiKq0VIgCEbcBIUGvS0qQhDbUmEYEtMiFT2Mk/Ah7D65d0eLWCAAAAAElFTkSuQmCC", + "6%fXoBL7P(`cp*l1#)iQt/q;6h": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABcAAAAgCAYAAAD5VeO1AAAGzUlEQVR4Ae3AA6AkWZbG8f937o3IzKdyS2Oubdu2bdu2bdu2bWmMnpZKr54yMyLu+Xa3anqmhztr1a8+7I3eyDs7O1x3w/XcePPNXHfj9Rw7fgx1laP1kouXdrmwe5GDo0MSs7m5wanTp7n22ms5dfIk89mM9WrFfffcy9Of/jSe8uSncNutz+DixQvU1WpFP5uxWq1YrVasliv6+YxoldV6xWq1YrVes16vMaZ2lWEYGIeBcRwoEYzjyDiNTOPENE5M08Q4TdS9/X2QWGxusr23x2JrE4qIrnK0XrG/v8/+/j6HyyMQEOLo6Iij5RGL5QKnGVZrVqsVq/WK9XrFer1mvV5T93cv0TKZLeZsbm/SL+Y0kugqy2HF7t4lLu1d4mi1hBCJmc/nHBxsMZ/PyZaM6zXL5ZLlcslytWK1WjGtVlT29jgCdjc22Ni5RL+xoMlEV1kOKy7t77G7v8dytSRKgGBjY4PDo0M2jhaQZhgGlssVq9Wa9XrNeljDeqCyWkHXcbhccnh4xMHBIaqFqIXlsGb/4ICDgwNW6xVRC6VWlsslq9WK1WpNKJiGgWEcGMeRaRqZpgnaRCUTMplaY5gm1uNItx5QC5brFcvVitVqzWpYU1phGAeGcWQYR8ZpZGodLRuZiW1sAECi0vXQdUQpSIGBtHFLptaYpsbYJqbWIERrSWaSaWyDAYQkIoJSCrVWWq0Emxuw2GA2X9D1PaVWFAESCaSNbdKQNsaY+wmFiAhqKXRdpe97ZrMZzGdUtrYpm5vMNzbo5wtq1xO1YicgDCRgjAHzTBIKERGoQO06+r5nPp+xWMwZhgW1bm2z2FgwX2zQz2fUriei0NIYSEOmSRvb2GCuEEIKooquq8xmM+bzOYvFgnEcqYuNDeaLBbP5nNr1RClYIg0tkykbrTVaSyKSlklmYhuACBEKuq5jNpuxsViwublJtkbt53O6fkbpOqIULJGGqTXGqTFNE+PUaNOEQmRrZCa2QRARdFGY9T2L+ZzNzQ22t7aQTe36GbXvKKWiKBiRaaaWTK0xTo2pNWhJZpI2AJKICGqp9F0H2djc3GR7e5thvaaWQu36nq7rKbVDUUDCGNtkGtvYBkASEUGJQi2FvuuYzXoWsxl9KeQ0MQ1ryGQxm1NnswVd39H1M2rXUUoFJ4pCRBBRKLXSMF3X0Xc9/axnNpuxmM/Z3Nhgc7HAU6NKyKaLwnLziLrY2KDrOmaLObPZjNIVWjbGnOj6nr6fMZsGshbm8zmLxZyNxYLNjQ02NzbY2txke3MT2cy6So1g3nWslkvqxuYWXVeZzWf08xlRgpaNRjKMC9bDmnQjs7FYzNjc2GRzY4PNjQ02NzbY2txke2uLAsxrpZOY1cJqtaJubG7S1Uo/6+lnPVGDKSeSZBgHNsYBk2ROLOYzFos589mc2WzGrJ8x63vmfU+VKACtoTR9rdRZP6N2lb7v6fqOKIEy6KaJvu/pu56p62kZdF1HLZUSQQDYOBNnYgnZyCYERUEFAQIABADmMiHEM9m4JW2aGNcDq+WS5eEhh/tzSiY1gmm9Znl0xPLwkGEYqOv1mqlNZCYtk6hBaxPr9Zr1as16vWa9WjNNA20a6WtwaT5ja2POoutQm1hubFCBaRhYHh6yPDpiHAbq7u4lai30s56u74gSNE+sVkv2D/bY39/n8HCfYVxTi2jDGmVSnHgYWO7vsTmfEzbTes3y6Ijl0RHjMFDPnj1LrYV+1tP3PaUGzY31esX+4R77+5c4PNyH9RIER4sZ4/KIcXXEan+fS9vbLPoeORlXK5ZHRyyPjhiHgXrvPfdSa2U27+lnPbUrpJP1uOLw8IDh4BIc7MF6CU7GWce9R4esjw5Z7u2xu7nJrBbIZFwuWR4dsTw6YhwG6njffYxdZTmbEfMZXV9BZpgGfHQAh3twsA/rJeQEXYX1it31inF5xOF8Tl8KbhPDcsny8JDV8ohxGKlcvAhdB/MZuZiznnVQBG2E1RKWK1ivYbWCnGAqQILgMJNcr6khPE4MqyXD4SEcHcE4UDk8gr4DJwjAUAPcIJNnkUACAAOZ0BptmpDA08Q0jjCOME0wQqU1mAJaQiYAhIACXQethzYHATlBFcx6mM2os55Z31MFKcE0sep73BpooIJAgggoBWqFroMAaoCAEPQF3KAEzHrqxpyt+ZxF31EFOU6MpdBFsCqFaRyplAKlQClQO+g6at8TRWQWpiKogrGCG9Sgznq2FnO2FnMWfUcVeJwYaqGLoK+VcRyplIBSoBQoBUql1kqpQVogM5EQgJOowXzWM5/PmM9mzPuOKnApBEaZCFNK8I958c/ms+Jt8gAAAABJRU5ErkJggg==", + "HUN*`C9p<)MJbF6vQY^LC_$qYVyrBA": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAHJUlEQVR4Ae3AA6AkWZbG8f937o3IzKdyS2Oubdu2bdu2bdu2bWmMnpZKr54yMyLu+Xa3anqmhztr1a8e/ejP2YAFCChCpRB9pfSVOuvRrIfZDGY9zHroZ9DPoOuhdKACDVhPcLCCSwdwcZ/lxX2OLh0xHq3xaDpV5t2MRb+gzGZQOioIAWCMwOIyAwjMsxkwYIMNNtiAwYANBgwYsBAAQjyTucICoApxmQEJELKQgQQMJJCGNDRDM7SESMAgQwOaIQ0JGDBgwIC5woABGxIqybPZ2ICMG7iZbKZMCZGgBmqgBjRwgzKBDCmYEqaEltCMm3EDpyGNActkM6UZSGobEzAGLCAECelGQRhhi2IhAwkk0IAJqAZVSGBIWI8wNHJotKnRpkaOiUcjNRpJi0aloSLquBwwYMACAqiBpkJMSWlJNFOmpIxJ6ZIYEroGXYMyQVTIgDFhOcByYFiNjKuRcT0xricYjTFRg8iCmuhKUo8OVoAxYAEhqIFqIbpK9JXSTURXiW6kdJVSO2rX0dUR1Q6iAwtGw2pkOFyxOlqxOhpYHw2MywFGUwgohhHcmak26sHuIQiMsQRFqATqCtFVoqtEX4muErUQtVJqpXYdtfZ0taNEJVxgMtN6Yn24Yrm/YnmwYnW4YloOeDTFQStJdqZ1SS2Vur97AIAFhCCEaqCuUrpK9JXoKtEVVCtRC1ErpVRq7ehqT41KUKDBtJ4Yjtas9pcsD5asD1aMywGPpjiYSqPVZOwatRTqwaUjACwghEqgGkRXib5S+o7oKuoKUQsqhSiFqJVaOmodqVEJCmrQhsZwNLA+XLE8WLE+WDEtRzyZ4mCKRqtmqo1SCvVof8VlIQihGkStRG/KBGWC6I3GRDVRNFQKURqlNEpp1KgUCiTkkIzLgfXhwOpoYH00Mq1GPCbFQYskK7SalCjUYdlAQAhFoCpKnwQGGQQGZCANYYiGAkpACZgiCQpKkUNjXI0My5H1amJYT0yrhqekpHEI1wkXUYqpOQkkCKESRATOirJCVnAFV8gABbZwCgQp0yIpEgHQRI7JtE6GIRkHMw6mjcaTyTSEURpVk81UqQeBFEhBUaWoUqKnlI4SHVEqisASKbDBBiOcwoAAmsnRTKOZRpgmaE1MTdCEU4TFhJCEDbWUOZJQCNVCqYVSO2rtqbWj1A7VCiWwABuTpI0NJKQFBprJ0UwTjBNMk5iaaCloAQQtg6IgMxBBrXUBEgoRtVBqpdSO2nXU2lO6ikrBJWgYOXFr2I2WxmmcQBqaydFMo5kmGBtMTWQLsMGBImguhANcqFHmIFAEUQKVSpSOKB0qPYoKUUAAJt1ohrGZ1hqtgTNxA5rJMZmGZBqTaTTTBNlATSSBCKYIlIEJqum4IkgCUUkqzR1yBVdwkIbJydCSYYJhNOOUtCnJlrgZN5OjacNEWzemIWlj4gkioQIgSKEI0kEdM0AghFrQQpQmSoM2QYQB0wRTJuupsR4b63FiHEemsdFa4mY8GU+mDY0cGm2YyDFhMpGiCgwgsKAAdTUaBAhUGjIUi0IQFpHGNUiZMRvraWQ1DKyHgWEcmcaJ1hJPxs14MjkmOSYeGh4TJigUOhkDDnCKgqiH64nLAohAUxJTEi2JKYmu4CpSZszGehpZDQPrYWA9DExTo02J09CMJ/BkPCYeEyYTKSqihbGMAzKgAnV/OYKMJQhQCdQVYmzE2FBXoIomM2VjPU2sxoH1MDCMI9M00aaEBBJowGQ8GSajBpGiKmgYEkhwwgTU/dUAgGUsQRGqQfQVjYXoC5SgBUxuDNPEehxYjyPDODJNjcyEBFIogQaagGbURLGoGAtIIMEJRVAP1iPGGLCMQ6gGmiaiq2gqUIMMaE6GnBimkWGcGKfG1BpuBoNSyIIGSiAh0oRNJ3ACCdhkmoKph8OEbYxJGQuogaaCWiNaga7gIhrJlI2hNcapMbYkm3EaLGRQggwYlCBDJKTAMmTiZpqSiqjLsWFM2iRJCmiCTMJJ2MiJS5AyE8nUzJgwGdLCgBBCCAEgAxgSIk1T0khSSVOjJygJdd2StEknDZMyTiGbwEgQFLDJEImZDBPQECkwQgghJAHGGCeQRmmKYZJoKaYUQ5oShTqkSZu0mZwkxgFgIiBCRAgCjEhBMzREI7CMASFACDBgm8zEzdBMZDLKjM0MzdSpUSKoY0LaNJuWSZOxAYGaKC2JTJQCiQQS0RApSMSzmMts09JkJtkaHo0aBI2qRlcaNSoRQW02aZjSNJvmJAUkKEWmiTSRhjCWSKBJpME8J2PSpmUytaRNjRwbNBMWhUKNRo2JUFCbIW3S0AzNkGGwURqcOI0NGDCkwAgLjDGAwYBtMs2UydSSqTVaazAmSigkUyQlCiFRDRhITNokJg3YyEYGYdJGXGGEMQaMMAbAgA0JpE1z0jJpreE0SjDgNA4TCv4RtiqpFjEcUFEAAAAASUVORK5CYII=" + }, + "communities": [ + { + "community_id": "ca848c275e2117470342c641ada0ae4639dd0472ab4a5ec654a189bf1f689087", + "name": "Vector Devs", + "description": "Where Vector gets built, in the open.", + "is_owner": true, + "has_icon": true, + "channels": [ + { + "channel_id": "a0f367a05f629b3bb09ee8f1561bf03267962217d9ff6fc7ce3b235235702bc1", + "name": "general", + "private": false, + "readable": true, + "category_id": null, + "topic": "Say hi!", + "view": "chat", + "my_permissions": null, + "restricted": false, + "can_post": true, + "public_until": null + }, + { + "channel_id": "d961d1281aed7b3ad2f6964aa7e59d427d8b921a8f7dd8c4c0f0a0e1422a17d1", + "name": "dev", + "private": false, + "readable": true, + "category_id": "e70d362ac4e73ce2887e5395680c76b7b3c93e43b69587845448f3b9d03ff48c", + "topic": "Builds, branches and bugs", + "view": "chat", + "my_permissions": null, + "restricted": false, + "can_post": true, + "public_until": null + }, + { + "channel_id": "451269113943deb53e912b83f5e397cd38bdc2460928a14dbc4f766181425977", + "name": "design", + "private": false, + "readable": true, + "category_id": "e70d362ac4e73ce2887e5395680c76b7b3c93e43b69587845448f3b9d03ff48c", + "topic": null, + "view": "chat", + "my_permissions": null, + "restricted": false, + "can_post": true, + "public_until": null + }, + { + "channel_id": "58e6267876fd6c4acb7fbc37091bb920e4f325e24df4887b8048d0ccf7137f2f", + "name": "Lounge", + "private": false, + "readable": true, + "category_id": null, + "topic": null, + "view": "voice", + "my_permissions": null, + "restricted": false, + "can_post": true, + "public_until": null + } + ], + "categories": [ + { + "category_id": "e70d362ac4e73ce2887e5395680c76b7b3c93e43b69587845448f3b9d03ff48c", + "name": "Build" + } + ], + "primary_channel": "a0f367a05f629b3bb09ee8f1561bf03267962217d9ff6fc7ce3b235235702bc1", + "owner_npub": "npub1yazve5gvw5em6um2mzg0nh2u4v4dkfas04gqh9yn72wdcssvktsqfmmmv4", + "dissolved": false, + "voice_relays": [], + "relays": [ + "wss://jskitty.com/nostr", + "wss://asia.vectorapp.io/nostr" + ], + "members": [ + "npub1yazve5gvw5em6um2mzg0nh2u4v4dkfas04gqh9yn72wdcssvktsqfmmmv4", + "npub190vqdjtlpcq27xslcveglfmr4ynfwg7gmw86cnun4acakxrdd6gqnp929a", + "npub1sxmr0k8u6trd5c6eu6trzyapzux7090ykujmsng7pdx0m8k93n5sd02fwn", + "npub1fsndjp6vylvfahjeyuxq4s2tw8s8rv2j89ge7a28fvhnhf35s86sg3uctf" + ], + "icon": "media/devs-icon.png", + "banner": "media/devs-banner.png" + } + ], + "invites": [ + { + "community_id": "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc", + "inviter_npub": "npub1v84qsqlcs56j8dmh6s22eccnpn2d87fdutxhl7rftseh67wzamhqfv9ft6", + "bundle_json": "{\"name\": \"Night Owls\", \"channels\": [{\"id\": \"dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd\", \"name\": \"general\"}], \"relays\": [\"wss://jskitty.com/nostr\"]}", + "received_at": 1794358800, + "sent_at": 1794358700, + "ends_at": 1794880800 + } + ], + "audit": { + "entries": [ + { + "id": "a1", + "at": 1794362280000, + "actor": "npub1yazve5gvw5em6um2mzg0nh2u4v4dkfas04gqh9yn72wdcssvktsqfmmmv4", + "action": "member_ban", + "target": { + "kind": "member", + "npub": "npub1wajx7kj0x9nxxa38405e3eapgu87wtvtgv8svld04p3x8u0j872qnta00x" + } + }, + { + "id": "a2", + "at": 1794351600000, + "actor": "npub190vqdjtlpcq27xslcveglfmr4ynfwg7gmw86cnun4acakxrdd6gqnp929a", + "action": "channel_create", + "target": { + "kind": "channel", + "name": "design", + "view": "chat" + }, + "changes": [ + { + "field": "view", + "new": "chat" + }, + { + "field": "private", + "new": true + } + ] + }, + { + "id": "a3", + "at": 1794268800000, + "actor": "npub1yazve5gvw5em6um2mzg0nh2u4v4dkfas04gqh9yn72wdcssvktsqfmmmv4", + "action": "community_update", + "changes": [ + { + "field": "description", + "old": "", + "new": "Where Vector gets built, in the open." + }, + { + "field": "relays", + "added": [ + "wss://asia.vectorapp.io/nostr" + ], + "removed": [] + } + ] + }, + { + "id": "a4", + "at": 1794016800000, + "actor": "npub1yazve5gvw5em6um2mzg0nh2u4v4dkfas04gqh9yn72wdcssvktsqfmmmv4", + "action": "role_create", + "target": { + "kind": "role", + "name": "Mods" + }, + "changes": [ + { + "field": "name", + "new": "Mods" + }, + { + "field": "permissions", + "added": [ + 3, + 4, + 5 + ], + "removed": [] + } + ] + }, + { + "id": "a5", + "at": 1793844000000, + "actor": "npub190vqdjtlpcq27xslcveglfmr4ynfwg7gmw86cnun4acakxrdd6gqnp929a", + "action": "invite_create", + "changes": [ + { + "field": "count", + "new": 2 + } + ] + }, + { + "id": "a6", + "at": 1793584800000, + "actor": "npub1yazve5gvw5em6um2mzg0nh2u4v4dkfas04gqh9yn72wdcssvktsqfmmmv4", + "action": "member_roles_update", + "target": { + "kind": "member", + "npub": "npub190vqdjtlpcq27xslcveglfmr4ynfwg7gmw86cnun4acakxrdd6gqnp929a" + }, + "changes": [ + { + "field": "roles", + "added": [ + { + "kind": "role", + "name": "Mods" + } + ], + "removed": [] + } + ] + }, + { + "id": "a7", + "at": 1793325600000, + "actor": "npub1yazve5gvw5em6um2mzg0nh2u4v4dkfas04gqh9yn72wdcssvktsqfmmmv4", + "action": "community_create", + "changes": [ + { + "field": "name", + "new": "Vector Devs" + } + ] + } + ], + "compacted": false + }, + "roles_view": { + "is_owner": true, + "can_manage": true, + "rank": 0, + "grantable": "939518847", + "activated": true, + "everyone": "541057024", + "everyone_editable": true, + "everyone_default": "541057024", + "roles": [ + { + "role_id": "1111111111111111111111111111111111111111111111111111111111111111", + "name": "Mods", + "position": 1, + "color": 5897395, + "permissions": "67111224", + "channel_id": null, + "holders": [ + "npub190vqdjtlpcq27xslcveglfmr4ynfwg7gmw86cnun4acakxrdd6gqnp929a" + ], + "display": true, + "mentionable": true, + "manageable": true + }, + { + "role_id": "2222222222222222222222222222222222222222222222222222222222222222", + "name": "Helpers", + "position": 2, + "color": 3718648, + "permissions": "2112", + "channel_id": null, + "holders": [ + "npub1sxmr0k8u6trd5c6eu6trzyapzux7090ykujmsng7pdx0m8k93n5sd02fwn", + "npub1fsndjp6vylvfahjeyuxq4s2tw8s8rv2j89ge7a28fvhnhf35s86sg3uctf" + ], + "display": false, + "mentionable": false, + "manageable": true + }, + { + "role_id": "3333333333333333333333333333333333333333333333333333333333333333", + "name": "Designers", + "position": 3, + "color": 0, + "permissions": "65536", + "channel_id": null, + "holders": [], + "display": false, + "mentionable": false, + "manageable": true + } + ], + "channels": [ + { + "channel_id": "a0f367a05f629b3bb09ee8f1561bf03267962217d9ff6fc7ce3b235235702bc1", + "name": "general", + "private": false + }, + { + "channel_id": "d961d1281aed7b3ad2f6964aa7e59d427d8b921a8f7dd8c4c0f0a0e1422a17d1", + "name": "dev", + "private": false + }, + { + "channel_id": "451269113943deb53e912b83f5e397cd38bdc2460928a14dbc4f766181425977", + "name": "design", + "private": false + }, + { + "channel_id": "58e6267876fd6c4acb7fbc37091bb920e4f325e24df4887b8048d0ccf7137f2f", + "name": "Lounge", + "private": false + } + ], + "max_roles": 100, + "max_per_member": 64 + }, + "moderation": { + "community_id": "ca848c275e2117470342c641ada0ae4639dd0472ab4a5ec654a189bf1f689087", + "name": "Vector Devs", + "owner_npub": "npub1yazve5gvw5em6um2mzg0nh2u4v4dkfas04gqh9yn72wdcssvktsqfmmmv4", + "epoch": 3, + "report": { + "members": [ + { + "npub": "npub1yazve5gvw5em6um2mzg0nh2u4v4dkfas04gqh9yn72wdcssvktsqfmmmv4", + "verdict": "protected", + "score": 0, + "reasons": [ + "Community owner" + ], + "joined_at_ms": 1783994400000, + "invite_label": null, + "messages": 412, + "distinct": 380, + "cohort": 0, + "tenure_secs": 10368000, + "last_secs": 60, + "is_owner": true, + "is_admin": false, + "is_me": true + }, + { + "npub": "npub190vqdjtlpcq27xslcveglfmr4ynfwg7gmw86cnun4acakxrdd6gqnp929a", + "verdict": "protected", + "score": 0, + "reasons": [ + "Holds a role" + ], + "joined_at_ms": 1786586400000, + "invite_label": null, + "messages": 233, + "distinct": 220, + "cohort": 0, + "tenure_secs": 7776000, + "last_secs": 60, + "is_owner": false, + "is_admin": true, + "is_me": false + }, + { + "npub": "npub1sxmr0k8u6trd5c6eu6trzyapzux7090ykujmsng7pdx0m8k93n5sd02fwn", + "verdict": "trusted", + "score": 0, + "reasons": [ + "Long-standing member" + ], + "joined_at_ms": 1789178400000, + "invite_label": null, + "messages": 88, + "distinct": 80, + "cohort": 0, + "tenure_secs": 5184000, + "last_secs": 60, + "is_owner": false, + "is_admin": false, + "is_me": false + }, + { + "npub": "npub1fsndjp6vylvfahjeyuxq4s2tw8s8rv2j89ge7a28fvhnhf35s86sg3uctf", + "verdict": "neutral", + "score": 0, + "reasons": [ + "Joined through a link posted in a raid" + ], + "joined_at_ms": 1794189600000, + "invite_label": "Reddit", + "messages": 4, + "distinct": 4, + "cohort": 0, + "tenure_secs": 172800, + "last_secs": 60, + "is_owner": false, + "is_admin": false, + "is_me": false + }, + { + "npub": "npub1v84qsqlcs56j8dmh6s22eccnpn2d87fdutxhl7rftseh67wzamhqfv9ft6", + "verdict": "neutral", + "score": 0, + "reasons": [], + "joined_at_ms": 1793152800000, + "invite_label": null, + "messages": 12, + "distinct": 11, + "cohort": 0, + "tenure_secs": 1209600, + "last_secs": 60, + "is_owner": false, + "is_admin": false, + "is_me": false + }, + { + "npub": "npub1wajx7kj0x9nxxa38405e3eapgu87wtvtgv8svld04p3x8u0j872qnta00x", + "verdict": "suspect", + "score": 9, + "reasons": [ + "Posted the same text as 3 others", + "Joined minutes ago" + ], + "joined_at_ms": 1794362160000, + "invite_label": "Reddit", + "messages": 6, + "distinct": 1, + "cohort": 0, + "tenure_secs": 240, + "last_secs": 60, + "is_owner": false, + "is_admin": false, + "is_me": false + }, + { + "npub": "npub1qk3nrfl57xffl2k29zdxd7vdtgzm8p7ee045lrpdmqsy56cz8g2qqxdt9s", + "verdict": "suspect", + "score": 9, + "reasons": [ + "Posted the same text as 3 others", + "Joined minutes ago" + ], + "joined_at_ms": 1794362170000, + "invite_label": "Reddit", + "messages": 5, + "distinct": 1, + "cohort": 0, + "tenure_secs": 230, + "last_secs": 60, + "is_owner": false, + "is_admin": false, + "is_me": false + }, + { + "npub": "npub1uqg0688p4nqh8ca5sddhvd0c63sq6a6gdygz4k6uk76a0z2kfxaqmmg7t4", + "verdict": "suspect", + "score": 8, + "reasons": [ + "Posted the same text as 3 others" + ], + "joined_at_ms": 1794362190000, + "invite_label": null, + "messages": 7, + "distinct": 1, + "cohort": 0, + "tenure_secs": 210, + "last_secs": 60, + "is_owner": false, + "is_admin": false, + "is_me": false + }, + { + "npub": "npub10j7vkrzv4t0elnd4rmj902pge3e2gkresvd4h9u2ut3valzyjuzsz7ad26", + "verdict": "suspect", + "score": 8, + "reasons": [ + "Posted the same text as 3 others" + ], + "joined_at_ms": 1794362200000, + "invite_label": null, + "messages": 4, + "distinct": 1, + "cohort": 0, + "tenure_secs": 200, + "last_secs": 60, + "is_owner": false, + "is_admin": false, + "is_me": false + } + ], + "suspects": 4, + "trusted": 1, + "protected": 2, + "cohorts": [ + { + "sample": "FREE NOSTR AIRDROP claim now at the link in my profile", + "size": 4, + "members": [ + "npub1wajx7kj0x9nxxa38405e3eapgu87wtvtgv8svld04p3x8u0j872qnta00x", + "npub1qk3nrfl57xffl2k29zdxd7vdtgzm8p7ee045lrpdmqsy56cz8g2qqxdt9s", + "npub1uqg0688p4nqh8ca5sddhvd0c63sq6a6gdygz4k6uk76a0z2kfxaqmmg7t4", + "npub10j7vkrzv4t0elnd4rmj902pge3e2gkresvd4h9u2ut3valzyjuzsz7ad26" + ] + } + ], + "burst_size": 4, + "burst_from_ms": 1794362160000, + "burst_to_ms": 1794362200000, + "raid_detected": true + }, + "unlisted": [], + "invites": [ + { + "token": "tok1", + "label": "Reddit", + "created_at": 0, + "expires_at": null, + "join_count": 3 + }, + { + "token": "tok2", + "label": null, + "created_at": 0, + "expires_at": null, + "join_count": 0 + } + ], + "banlist_count": 2, + "banlist_max": 500, + "capabilities": { + "ban": true + }, + "channels": [ + { + "id": "a0f367a05f629b3bb09ee8f1561bf03267962217d9ff6fc7ce3b235235702bc1", + "name": "general" + }, + { + "id": "d961d1281aed7b3ad2f6964aa7e59d427d8b921a8f7dd8c4c0f0a0e1422a17d1", + "name": "dev" + }, + { + "id": "451269113943deb53e912b83f5e397cd38bdc2460928a14dbc4f766181425977", + "name": "design" + }, + { + "id": "58e6267876fd6c4acb7fbc37091bb920e4f325e24df4887b8048d0ccf7137f2f", + "name": "Lounge" + } + ] + }, + "policy_presets": { + "presets": [ + { + "id": "vector_defaults", + "name": "Vector's Defaults", + "description": "Raid detection, running here already. Open it to read every rule, or save your own version.", + "example": "a swarm of fresh accounts posting one line", + "caveat": "A Built-In Anti-Raid Policy: detects raids proactively and alerts you with a list of suspects for quick handling.", + "dials": [ + { + "key": "summary", + "label": "What these rules do", + "kind": "summary", + "hint": "Every rule that runs here, in order." + }, + { + "key": "strictness", + "label": "Sensitivity", + "kind": "strictness", + "hint": "How much it takes to trip a rule, and how confident the result is." + } + ], + "rules": [ + { + "label": "Many accounts, one line", + "detail": "3 or more separate accounts posting the same line at the same time. The shape of a raid.", + "armed": false + }, + { + "label": "Join flood", + "detail": "12 or more joins within 5 minutes.", + "armed": false + }, + { + "label": "New account", + "detail": "Joined less than 24 hours ago.", + "armed": true + }, + { + "label": "Barely posted", + "detail": "Has posted at most 2 messages.", + "armed": true + } + ], + "bytes": "{\"format\":1,\"requires\":[\"armed_by_any\"],\"name\":\"raid-detection\",\"shields\":{\"trusted\":{\"tenure_secs\":604800,\"messages\":5,\"distinct\":3,\"veteran_secs\":2592000,\"roles_trust\":true}},\"window\":{\"hours\":168,\"max_messages\":4000},\"exempt\":{\"patterns\":[],\"roles\":[],\"channels\":[]},\"rules\":[{\"id\":\"cohort\",\"match\":{\"type\":\"cohort\",\"min\":3,\"quiet_max\":2,\"short_factor\":3,\"thin_ratio\":null},\"severity\":\"severe\",\"weight\":85,\"pierces_trusted\":false,\"exempt\":{\"patterns\":[],\"roles\":[],\"channels\":[]},\"enforcement\":\"advisory\"},{\"id\":\"burst\",\"match\":{\"type\":\"join_burst\",\"gap_secs\":300,\"min\":12},\"severity\":\"major\",\"weight\":40,\"pierces_trusted\":false,\"exempt\":{\"patterns\":[],\"roles\":[],\"channels\":[]},\"enforcement\":\"advisory\"},{\"id\":\"fresh\",\"match\":{\"type\":\"tenure_lt\",\"secs\":86400},\"severity\":\"notice\",\"weight\":12,\"pierces_trusted\":false,\"armed_by\":{\"rule\":\"cohort\",\"scope\":\"subject\",\"also\":[\"burst\"]},\"exempt\":{\"patterns\":[],\"roles\":[],\"channels\":[]},\"enforcement\":\"advisory\"},{\"id\":\"quiet\",\"match\":{\"type\":\"messages_lte\",\"n\":2},\"severity\":\"notice\",\"weight\":10,\"pierces_trusted\":false,\"armed_by\":{\"rule\":\"cohort\",\"scope\":\"subject\",\"also\":[\"burst\"]},\"exempt\":{\"patterns\":[],\"roles\":[],\"channels\":[]},\"enforcement\":\"advisory\"}]}" + }, + { + "id": "scam_links", + "name": "Scam Links", + "description": "Blocks link shorteners and redirectors that scams hide behind.", + "example": "claim your airdrop at bit.ly/\u2026", + "caveat": "Only catches the shorteners on the bundled list, plus any domain you add.", + "dials": [ + { + "key": "domains", + "label": "Also block these domains", + "kind": "domainlist", + "hint": "One per line. The bundled shortener list is always included." + }, + { + "key": "allow", + "label": "Never flag these domains", + "kind": "domainlist", + "hint": "Your own links, docs, anything you trust." + } + ], + "rules": [ + { + "label": "Link domains", + "detail": "28 domains blocked, subdomains included. Trips at 1 hit in one message, then 3 hits in the window.", + "armed": false + } + ], + "bytes": "{\"format\":1,\"name\":\"Scam Links\",\"shields\":{\"trusted\":{\"tenure_secs\":604800,\"messages\":5,\"distinct\":3,\"veteran_secs\":2592000,\"roles_trust\":true}},\"window\":{\"hours\":168,\"max_messages\":4000},\"exempt\":{\"patterns\":[],\"roles\":[],\"channels\":[]},\"rules\":[{\"id\":\"shorteners\",\"match\":{\"type\":\"link\",\"patterns\":[\"bit.ly\",\"tinyurl.com\",\"t.co\",\"goo.gl\",\"ow.ly\",\"is.gd\",\"buff.ly\",\"adf.ly\",\"bit.do\",\"cutt.ly\",\"rebrand.ly\",\"shorturl.at\",\"rb.gy\",\"tiny.cc\",\"shorte.st\",\"bc.vc\",\"clck.ru\",\"soo.gd\",\"s2r.co\",\"tr.ee\",\"dub.sh\",\"e.vg\",\"paw.wf\",\"shm.to\",\"snl.ink\",\"surl.li\",\"url9.de\",\"waffl.link\"]},\"tiers\":{\"per_message\":[{\"hits\":1,\"severity\":\"severe\",\"weight\":70,\"pierces_trusted\":false}],\"per_window\":[{\"hits\":3,\"severity\":\"severe\",\"weight\":90,\"pierces_trusted\":false}]},\"pierces_trusted\":false,\"exempt\":{\"patterns\":[],\"roles\":[],\"channels\":[]},\"enforcement\":\"advisory\"}]}" + }, + { + "id": "no_spam", + "name": "No Spam", + "description": "The same message over and over, from one account or many.", + "example": "the same pitch, twelve times", + "caveat": "Counts shapes, not words: changing case, punctuation or digits does not help a spammer.", + "dials": [ + { + "key": "strictness", + "label": "Sensitivity", + "kind": "strictness", + "hint": "How much it takes to trip a rule, and how confident the result is." + } + ], + "rules": [ + { + "label": "Same message repeated", + "detail": "One account posting the same thing over and over inside 30 minutes. Case, punctuation and digits are ignored, so changing them does not help. Trips at 4 hits, then 8 hits.", + "armed": false + }, + { + "label": "Many accounts, one line", + "detail": "3 or more separate accounts posting the same line at the same time. The shape of a raid.", + "armed": false + } + ], + "bytes": "{\"format\":1,\"name\":\"No Spam\",\"shields\":{\"trusted\":{\"tenure_secs\":604800,\"messages\":5,\"distinct\":3,\"veteran_secs\":2592000,\"roles_trust\":true}},\"window\":{\"hours\":168,\"max_messages\":4000},\"exempt\":{\"patterns\":[],\"roles\":[],\"channels\":[]},\"rules\":[{\"id\":\"repeat\",\"match\":{\"type\":\"repeat\",\"normalize\":\"skeleton\",\"within_secs\":1800},\"tiers\":{\"per_window\":[{\"hits\":4,\"severity\":\"major\",\"weight\":50,\"pierces_trusted\":false},{\"hits\":8,\"severity\":\"severe\",\"weight\":85,\"pierces_trusted\":false}]},\"pierces_trusted\":false,\"exempt\":{\"patterns\":[],\"roles\":[],\"channels\":[]},\"enforcement\":\"advisory\"},{\"id\":\"cohort\",\"match\":{\"type\":\"cohort\",\"min\":3,\"quiet_max\":2,\"short_factor\":3,\"thin_ratio\":null},\"severity\":\"severe\",\"weight\":85,\"pierces_trusted\":false,\"exempt\":{\"patterns\":[],\"roles\":[],\"channels\":[]},\"enforcement\":\"advisory\"}]}" + }, + { + "id": "word_filter", + "name": "Word Filter", + "description": "Any list of words you choose, with per-channel exceptions.", + "example": "spoilers, slurs, or a scam phrase", + "caveat": "Whole words by default, so filtering \"art\" leaves \"start\" alone.", + "dials": [ + { + "key": "words", + "label": "Words to catch", + "kind": "wordlist", + "hint": "One per line. Use *word* to match inside longer words." + }, + { + "key": "exempt_channels", + "label": "Allowed in these channels", + "kind": "channels", + "hint": "The filter ignores these channels entirely." + } + ], + "rules": [ + { + "label": "Words", + "detail": "0 words on the list, matched as whole words unless you wrap them in *. Trips at 1 hit in one message, then 10 hits in the window.", + "armed": false + } + ], + "bytes": "{\"format\":1,\"name\":\"Word Filter\",\"shields\":{\"trusted\":{\"tenure_secs\":604800,\"messages\":5,\"distinct\":3,\"veteran_secs\":2592000,\"roles_trust\":true}},\"window\":{\"hours\":168,\"max_messages\":4000},\"exempt\":{\"patterns\":[],\"roles\":[],\"channels\":[]},\"rules\":[{\"id\":\"words\",\"match\":{\"type\":\"keyword\",\"patterns\":[],\"normalize\":\"fold\"},\"tiers\":{\"per_message\":[{\"hits\":1,\"severity\":\"minor\",\"weight\":10,\"pierces_trusted\":false}],\"per_window\":[{\"hits\":10,\"severity\":\"major\",\"weight\":45,\"pierces_trusted\":false}]},\"pierces_trusted\":false,\"exempt\":{\"patterns\":[],\"roles\":[],\"channels\":[]},\"enforcement\":\"advisory\"}]}" + }, + { + "id": "mass_tagging", + "name": "Mass Tagging", + "description": "One message that names a crowd, rather than a person.", + "example": "a post tagging twelve people at once", + "caveat": "Counts distinct people per message: pinging one person twenty times reads as one, because it is.", + "dials": [ + { + "key": "strictness", + "label": "Sensitivity", + "kind": "strictness", + "hint": "How much it takes to trip a rule, and how confident the result is." + }, + { + "key": "exempt_channels", + "label": "Allowed in these channels", + "kind": "channels", + "hint": "Announcement channels where tagging everyone is the point." + } + ], + "rules": [ + { + "label": "Mass tagging", + "detail": "How many DISTINCT people one message names. Tagging the same person repeatedly counts once. Trips at 6 hits in one message, then 12 hits in one message.", + "armed": false + } + ], + "bytes": "{\"format\":1,\"name\":\"Mass Tagging\",\"shields\":{\"trusted\":{\"tenure_secs\":604800,\"messages\":5,\"distinct\":3,\"veteran_secs\":2592000,\"roles_trust\":true}},\"window\":{\"hours\":168,\"max_messages\":4000},\"exempt\":{\"patterns\":[],\"roles\":[],\"channels\":[]},\"rules\":[{\"id\":\"mentions\",\"match\":{\"type\":\"mentions\"},\"tiers\":{\"per_message\":[{\"hits\":6,\"severity\":\"major\",\"weight\":50,\"pierces_trusted\":false},{\"hits\":12,\"severity\":\"severe\",\"weight\":85,\"pierces_trusted\":false}]},\"pierces_trusted\":false,\"exempt\":{\"patterns\":[],\"roles\":[],\"channels\":[]},\"enforcement\":\"advisory\"}]}" + }, + { + "id": "rate_limit", + "name": "Rate Limit", + "description": "Too many messages too quickly from one account, whatever they say.", + "example": "twelve messages in ten seconds", + "caveat": "Counts messages, not content: a fast typer in a lively channel can trip it, so preview before enabling.", + "dials": [ + { + "key": "per_secs", + "label": "Over how many seconds", + "kind": "seconds", + "hint": "The span it counts within. 10 catches a burst; 60 catches a sustained flood." + }, + { + "key": "strictness", + "label": "Sensitivity", + "kind": "strictness", + "hint": "How much it takes to trip a rule, and how confident the result is." + } + ], + "rules": [ + { + "label": "Posting too fast", + "detail": "One account's messages counted over any 10 seconds, whatever they say. Trips at 6 hits in the window, then 12 hits in the window.", + "armed": false + } + ], + "bytes": "{\"format\":1,\"name\":\"Rate Limit\",\"shields\":{\"trusted\":{\"tenure_secs\":604800,\"messages\":5,\"distinct\":3,\"veteran_secs\":2592000,\"roles_trust\":true}},\"window\":{\"hours\":168,\"max_messages\":4000},\"exempt\":{\"patterns\":[],\"roles\":[],\"channels\":[]},\"rules\":[{\"id\":\"rate\",\"match\":{\"type\":\"rate\",\"per_secs\":10},\"tiers\":{\"per_window\":[{\"hits\":6,\"severity\":\"major\",\"weight\":50,\"pierces_trusted\":false},{\"hits\":12,\"severity\":\"severe\",\"weight\":85,\"pierces_trusted\":false}]},\"pierces_trusted\":false,\"exempt\":{\"patterns\":[],\"roles\":[],\"channels\":[]},\"enforcement\":\"advisory\"}]}" + }, + { + "id": "blank", + "name": "Start from scratch", + "description": "An empty policy. Name it, add the rules you want, preview before anything runs.", + "example": "whatever this community actually needs", + "caveat": "A policy with no rules catches nothing, and the preview will tell you so.", + "dials": [ + { + "key": "name", + "label": "Policy name", + "kind": "text", + "hint": "What you will see in the list." + }, + { + "key": "rules", + "label": "Rules", + "kind": "rules", + "hint": "Add as many as you like. Any one of them can convict on its own." + }, + { + "key": "exempt_channels", + "label": "Allowed in these channels", + "kind": "channels", + "hint": "These channels are ignored entirely." + } + ], + "rules": [], + "bytes": "{\"format\":1,\"name\":\"New policy\",\"shields\":{\"trusted\":{\"tenure_secs\":604800,\"messages\":5,\"distinct\":3,\"veteran_secs\":2592000,\"roles_trust\":true}},\"window\":{\"hours\":168,\"max_messages\":4000},\"exempt\":{\"patterns\":[],\"roles\":[],\"channels\":[]},\"rules\":[]}" + } + ], + "rule_kinds": [ + { + "id": "keyword", + "label": "Words", + "description": "Someone posts a word from your list.", + "input": "wordlist", + "input_label": "Words to catch", + "input_hint": "One per line. Use *word* to match inside longer words.", + "rule": { + "id": "words", + "match": { + "type": "keyword", + "patterns": [], + "normalize": "fold" + }, + "tiers": { + "per_message": [ + { + "hits": 1, + "severity": "minor", + "weight": 10, + "pierces_trusted": false + } + ], + "per_window": [ + { + "hits": 10, + "severity": "major", + "weight": 45, + "pierces_trusted": false + } + ] + }, + "pierces_trusted": false, + "exempt": { + "patterns": [], + "roles": [], + "channels": [] + }, + "enforcement": "advisory" + } + }, + { + "id": "link", + "label": "Link domains", + "description": "Someone posts a link to a domain on your list.", + "input": "domainlist", + "input_label": "Domains to block", + "input_hint": "One per line. Matches the domain and its subdomains.", + "rule": { + "id": "links", + "match": { + "type": "link" + }, + "tiers": { + "per_message": [ + { + "hits": 1, + "severity": "severe", + "weight": 70, + "pierces_trusted": false + } + ], + "per_window": [ + { + "hits": 3, + "severity": "severe", + "weight": 90, + "pierces_trusted": false + } + ] + }, + "pierces_trusted": false, + "exempt": { + "patterns": [], + "roles": [], + "channels": [] + }, + "enforcement": "advisory" + } + }, + { + "id": "repeat", + "label": "Same message repeated", + "description": "One account posting the same thing over and over inside half an hour. Case, punctuation and digits are ignored, so changing them does not help.", + "input": "none", + "input_label": "", + "input_hint": "", + "rule": { + "id": "repeat", + "match": { + "type": "repeat", + "normalize": "skeleton", + "within_secs": 1800 + }, + "tiers": { + "per_window": [ + { + "hits": 4, + "severity": "major", + "weight": 50, + "pierces_trusted": false + }, + { + "hits": 8, + "severity": "severe", + "weight": 85, + "pierces_trusted": false + } + ] + }, + "pierces_trusted": false, + "exempt": { + "patterns": [], + "roles": [], + "channels": [] + }, + "enforcement": "advisory" + } + }, + { + "id": "mentions", + "label": "Mass tagging", + "description": "One message naming a crowd. Counts distinct people, so twenty pings at one person is one person \u2014 annoying, but not a raid.", + "input": "none", + "input_label": "", + "input_hint": "", + "rule": { + "id": "mentions", + "match": { + "type": "mentions" + }, + "tiers": { + "per_message": [ + { + "hits": 6, + "severity": "major", + "weight": 50, + "pierces_trusted": false + }, + { + "hits": 12, + "severity": "severe", + "weight": 85, + "pierces_trusted": false + } + ] + }, + "pierces_trusted": false, + "exempt": { + "patterns": [], + "roles": [], + "channels": [] + }, + "enforcement": "advisory" + } + }, + { + "id": "rate", + "label": "Posting too fast", + "description": "One account posting faster than a person reasonably types, whatever they are saying. Catches a spammer who varies their text just enough to look different every time.", + "input": "seconds", + "input_label": "Over how many seconds", + "input_hint": "The span it counts within. 10 catches a burst; 60 catches a sustained flood.", + "rule": { + "id": "rate", + "match": { + "type": "rate", + "per_secs": 10 + }, + "tiers": { + "per_window": [ + { + "hits": 6, + "severity": "major", + "weight": 50, + "pierces_trusted": false + }, + { + "hits": 12, + "severity": "severe", + "weight": 85, + "pierces_trusted": false + } + ] + }, + "pierces_trusted": false, + "exempt": { + "patterns": [], + "roles": [], + "channels": [] + }, + "enforcement": "advisory" + } + }, + { + "id": "cohort", + "label": "Many accounts, one line", + "description": "Separate accounts posting the same line at the same time. The shape of a raid.", + "input": "none", + "input_label": "", + "input_hint": "", + "rule": { + "id": "cohort", + "match": { + "type": "cohort", + "min": 3, + "quiet_max": 2, + "short_factor": 3, + "thin_ratio": null + }, + "severity": "severe", + "weight": 85, + "pierces_trusted": false, + "exempt": { + "patterns": [], + "roles": [], + "channels": [] + }, + "enforcement": "advisory" + } + } + ] + }, + "embeds": { + "note1wg33qsaurqr7da6qkg67kag3ajeny4dx5d65x433r9k732t4p49sk04fpd": { + "published_at": null, + "title": null, + "summary": null, + "image": null, + "media": [ + { + "url": "media/photo.png", + "is_video": false, + "mime": "image/png", + "width": 640, + "height": 480, + "size": null, + "duration": null, + "poster": null, + "sha256": null, + "fallbacks": [] + }, + { + "url": "media/portrait.png", + "is_video": false, + "mime": "image/png", + "width": 480, + "height": 640, + "size": null, + "duration": null, + "poster": null, + "sha256": null, + "fallbacks": [] + } + ], + "video": null, + "link": null, + "content_warning": null, + "emoji": [], + "reposted_by": null, + "reply_to": null, + "class": "post", + "kind": 1, + "id": "7272727272727272727272727272727272727272727272727272727272727272", + "author": "npub190vqdjtlpcq27xslcveglfmr4ynfwg7gmw86cnun4acakxrdd6gqnp929a", + "created_at": 1794355200, + "text": "Shipped the new relay picker today. **Tor routing** is on by default for every new account, and it is *so* much faster than I expected \ud83d\ude80", + "bech32": "note1wg33qsaurqr7da6qkg67kag3ajeny4dx5d65x433r9k732t4p49sk04fpd" + }, + "naddr1qqx8yetvv9uj6er9wd5kwmszyq4aspkf0u8qptc6rlpn9ra8vw5jd9ererdcltz0jwhhrkccd4hfqqcyqqq823cyhyg2k": { + "published_at": 1794190000, + "title": "Designing relays for privacy first", + "summary": "Why every connection in Vector goes through one transport layer, and what failing closed buys you when a network is hostile.", + "image": "media/devs-banner.png", + "media": [], + "video": null, + "link": null, + "content_warning": null, + "emoji": [], + "reposted_by": null, + "reply_to": null, + "class": "article", + "kind": 30023, + "id": "abababababababababababababababababababababababababababababababab", + "author": "npub190vqdjtlpcq27xslcveglfmr4ynfwg7gmw86cnun4acakxrdd6gqnp929a", + "created_at": 1794200000, + "text": "Every connection Vector makes goes through **one transport layer**. It decides each egress: direct, a bridge into Tor, or a refusal with no socket and no DNS.\n\nNothing falls back to direct. A preference not loaded yet refuses, and a kind that is still starting refuses too.\n\nnostr:note1wg33qsaurqr7da6qkg67kag3ajeny4dx5d65x433r9k732t4p49sk04fpd", + "bech32": "naddr1qqx8yetvv9uj6er9wd5kwmszyq4aspkf0u8qptc6rlpn9ra8vw5jd9ererdcltz0jwhhrkccd4hfqqcyqqq823cyhyg2k" + }, + "nevent1qqsqe2cujct5qna09vjwyg0p3899j3vp8c2d8amxx3dsnjsnh03gllqzyzqmvd7clnfvdknrt8nfvvgn5ytsmeu4ujmjtwzdrc95elv7ckxwjqcyqqqgtwc9z4mnx": { + "published_at": null, + "title": "Vector in five minutes", + "summary": null, + "image": "media/photo.png", + "media": [], + "video": null, + "link": "https://www.youtube.com/watch?v=aqz-KE-bpKQ", + "content_warning": null, + "emoji": [], + "reposted_by": null, + "reply_to": null, + "class": "video", + "kind": 34235, + "id": "cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd", + "author": "npub1sxmr0k8u6trd5c6eu6trzyapzux7090ykujmsng7pdx0m8k93n5sd02fwn", + "created_at": 1794300000, + "text": "A quick tour of private messaging on Nostr: accounts, Communities and calls.", + "bech32": "nevent1qqsqe2cujct5qna09vjwyg0p3899j3vp8c2d8amxx3dsnjsnh03gllqzyzqmvd7clnfvdknrt8nfvvgn5ytsmeu4ujmjtwzdrc95elv7ckxwjqcyqqqgtwc9z4mnx" + } + }, + "packs": { + "naddr1qqzkymr0vfesygypkcma3lxjcmdxxk0xjcc38gghphnete9hykuy68stfn7ea3vvaypsgqqqw48qsh6h7r": { + "id": "naddr1qqzkymr0vfesygypkcma3lxjcmdxxk0xjcc38gghphnete9hykuy68stfn7ea3vvaypsgqqqw48qsh6h7r", + "pubkey": "0000000000000000000000000000000000000000000000000000000000000000", + "identifier": "blobs", + "title": "Blob Friends", + "image_url": "https://ref.invalid/media/pack/icon.png", + "description": "Sixteen round friends for every mood.", + "emojis": [ + { + "shortcode": "blob0", + "url": "https://ref.invalid/media/pack/e0.png", + "sha256": null + }, + { + "shortcode": "blob1", + "url": "https://ref.invalid/media/pack/e1.png", + "sha256": null + }, + { + "shortcode": "blob2", + "url": "https://ref.invalid/media/pack/e2.png", + "sha256": null + }, + { + "shortcode": "blob3", + "url": "https://ref.invalid/media/pack/e3.png", + "sha256": null + }, + { + "shortcode": "blob4", + "url": "https://ref.invalid/media/pack/e4.png", + "sha256": null + }, + { + "shortcode": "blob5", + "url": "https://ref.invalid/media/pack/e5.png", + "sha256": null + }, + { + "shortcode": "blob6", + "url": "https://ref.invalid/media/pack/e6.png", + "sha256": null + }, + { + "shortcode": "blob7", + "url": "https://ref.invalid/media/pack/e7.png", + "sha256": null + }, + { + "shortcode": "blob8", + "url": "https://ref.invalid/media/pack/e8.png", + "sha256": null + }, + { + "shortcode": "blob9", + "url": "https://ref.invalid/media/pack/e9.png", + "sha256": null + }, + { + "shortcode": "blob10", + "url": "https://ref.invalid/media/pack/e10.png", + "sha256": null + }, + { + "shortcode": "blob11", + "url": "https://ref.invalid/media/pack/e11.png", + "sha256": null + }, + { + "shortcode": "blob12", + "url": "https://ref.invalid/media/pack/e12.png", + "sha256": null + }, + { + "shortcode": "blob13", + "url": "https://ref.invalid/media/pack/e13.png", + "sha256": null + }, + { + "shortcode": "blob14", + "url": "https://ref.invalid/media/pack/e14.png", + "sha256": null + }, + { + "shortcode": "blob15", + "url": "https://ref.invalid/media/pack/e15.png", + "sha256": null + } + ], + "is_own": false, + "updated_at": 1794300000, + "status": 0 + }, + "naddr1doodles": { + "id": "naddr1doodles", + "pubkey": "", + "identifier": "doodles", + "title": "My Doodles", + "image_url": "", + "description": "", + "emojis": [ + { + "shortcode": "doodle0", + "url": "https://ref.invalid/media/pack/e15.png", + "sha256": null + }, + { + "shortcode": "doodle1", + "url": "https://ref.invalid/media/pack/e14.png", + "sha256": null + }, + { + "shortcode": "doodle2", + "url": "https://ref.invalid/media/pack/e13.png", + "sha256": null + }, + { + "shortcode": "doodle3", + "url": "https://ref.invalid/media/pack/e12.png", + "sha256": null + }, + { + "shortcode": "doodle4", + "url": "https://ref.invalid/media/pack/e11.png", + "sha256": null + }, + { + "shortcode": "doodle5", + "url": "https://ref.invalid/media/pack/e10.png", + "sha256": null + }, + { + "shortcode": "doodle6", + "url": "https://ref.invalid/media/pack/e9.png", + "sha256": null + }, + { + "shortcode": "doodle7", + "url": "https://ref.invalid/media/pack/e8.png", + "sha256": null + } + ], + "is_own": true, + "updated_at": 1794300000, + "status": 0 + } + }, + "channel_perms": { + "activated": true, + "category": "e70d362ac4e73ce2887e5395680c76b7b3c93e43b69587845448f3b9d03ff48c", + "synced": null, + "can_manage": true, + "can_sync": true, + "me": "3bf0c63fcb93463407af97a5e5ee64fa883d107ef9e558472c4eb9aaaefa459d", + "everyone_support": "18446744073709551615", + "roles": [ + { + "role_id": "1111111111111111111111111111111111111111111111111111111111111111", + "name": "Mods", + "color": 5897395, + "position": 1, + "support": null + }, + { + "role_id": "2222222222222222222222222222222222222222222222222222222222222222", + "name": "Helpers", + "color": 3718648, + "position": 2, + "support": "18446744073709551615" + }, + { + "role_id": "3333333333333333333333333333333333333333333333333333333333333333", + "name": "Designers", + "color": 0, + "position": 3, + "support": "18446744073709551615" + } + ], + "overwrites": [ + { + "kind": "everyone", + "id": null, + "npub": null, + "allow": "0", + "deny": "16384", + "support": "18446744073709551615" + }, + { + "kind": "role", + "id": "1111111111111111111111111111111111111111111111111111111111111111", + "npub": null, + "allow": "16416", + "deny": "0", + "support": null + }, + { + "kind": "member", + "id": "2bd806c97f0e00af1a1fc3328fa763a9269723c8db8fac4f93af71db186d6e90", + "npub": "npub190vqdjtlpcq27xslcveglfmr4ynfwg7gmw86cnun4acakxrdd6gqnp929a", + "allow": "65536", + "deny": "131072", + "support": "18446744073709551615" + } + ], + "members": [ + { + "id": "2bd806c97f0e00af1a1fc3328fa763a9269723c8db8fac4f93af71db186d6e90", + "npub": "npub190vqdjtlpcq27xslcveglfmr4ynfwg7gmw86cnun4acakxrdd6gqnp929a", + "support": "18446744073709551615" + }, + { + "id": "81b637d8fcd2c6da6359e6963113a1170de795e4b725b84d1e0b4cfd9ec58ce9", + "npub": "npub1sxmr0k8u6trd5c6eu6trzyapzux7090ykujmsng7pdx0m8k93n5sd02fwn", + "support": "18446744073709551615" + }, + { + "id": "4c26d9074c27d89ede59270c0ac14b71e071b15239519f75474b2f3ba63481f5", + "npub": "npub1fsndjp6vylvfahjeyuxq4s2tw8s8rv2j89ge7a28fvhnhf35s86sg3uctf", + "support": "18446744073709551615" + } + ] + }, + "bot_commands": { + "npub15387nevpzd0u700y2t24ym9l0zxe8fsxx2w7qn47ysn6mndn9gvqqmlahu": [ + { + "bot": "npub15387nevpzd0u700y2t24ym9l0zxe8fsxx2w7qn47ysn6mndn9gvqqmlahu", + "commands": [ + { + "name": "roll", + "description": "Roll a die", + "args": [ + { + "name": "sides", + "type": "int", + "description": "How many sides", + "required": false + } + ] + }, + { + "name": "say", + "description": "Make the bot say something", + "args": [ + { + "name": "text", + "type": "string", + "description": "What to say", + "required": true + } + ] + }, + { + "name": "mode", + "description": "Pick a play mode", + "args": [ + { + "name": "mode", + "type": "choice", + "description": "The mode", + "required": true, + "choices": [ + "easy", + "hard", + "chaos" + ] + } + ] + } + ] + } + ] + }, + "marketplace": [ + { + "id": "chess", + "name": "Chess Club", + "description": "Classic chess against a friend, with move history and clocks.", + "version": "1.0.0", + "blossom_hash": "0000000000000000000000000000000000000000000000000000000000000000", + "download_url": "https://ref.invalid/chess.xdc", + "size": 180000, + "icon_url": "https://ref.invalid/chess.png", + "icon_mime": "image/png", + "icon_cached": "media/apps/chess.png", + "categories": [ + "game", + "multiplayer", + "board", + "strategy", + "keyboard" + ], + "changelog": "Smoother animations and a new colour theme.", + "developer": "Mira Vale", + "source_url": "https://github.com/example/chess", + "publisher": "npub1yazve5gvw5em6um2mzg0nh2u4v4dkfas04gqh9yn72wdcssvktsqfmmmv4", + "published_at": 1794276000, + "signed_at": 1794276000, + "installed": true, + "local_path": "/tmp/chess.xdc", + "installed_version": "1.0.0", + "update_available": false, + "requested_permissions": "microphone,fullscreen,clipboard-write" + }, + { + "id": "tetra", + "name": "Tetra Drop", + "description": "Stack falling blocks and clear lines. How long can you last?", + "version": "1.1.0", + "blossom_hash": "0000000000000000000000000000000000000000000000000000000000000001", + "download_url": "https://ref.invalid/tetra.xdc", + "size": 271000, + "icon_url": "https://ref.invalid/tetra.png", + "icon_mime": "image/png", + "icon_cached": "media/apps/tetra.png", + "categories": [ + "game", + "puzzle", + "arcade", + "keyboard", + "controller" + ], + "changelog": null, + "developer": "Pixel Cat", + "source_url": null, + "publisher": "npub1jskittyvector000000000000000000000000000000000000000000", + "published_at": 1793844000, + "signed_at": 1793844000, + "installed": false, + "local_path": null, + "installed_version": null, + "update_available": false, + "requested_permissions": "" + }, + { + "id": "snek", + "name": "Snek", + "description": "Eat, grow, don't bite yourself. A tiny classic, rebuilt for Vector.", + "version": "1.2.0", + "blossom_hash": "0000000000000000000000000000000000000000000000000000000000000002", + "download_url": "https://ref.invalid/snek.xdc", + "size": 362000, + "icon_url": "https://ref.invalid/snek.png", + "icon_mime": "image/png", + "icon_cached": "media/apps/snek.png", + "categories": [ + "game", + "arcade", + "retro", + "keyboard", + "mobile" + ], + "changelog": null, + "developer": null, + "source_url": "https://github.com/example/snek", + "publisher": "npub1jskittyvector000000000000000000000000000000000000000000", + "published_at": 1793412000, + "signed_at": 1793412000, + "installed": false, + "local_path": null, + "installed_version": null, + "update_available": false, + "requested_permissions": "" + }, + { + "id": "draw", + "name": "Sketch Party", + "description": "Take turns drawing and guessing with everyone in the chat.", + "version": "1.3.0", + "blossom_hash": "0000000000000000000000000000000000000000000000000000000000000003", + "download_url": "https://ref.invalid/draw.xdc", + "size": 453000, + "icon_url": "https://ref.invalid/draw.png", + "icon_mime": "image/png", + "icon_cached": "media/apps/draw.png", + "categories": [ + "game", + "multiplayer", + "party", + "drawing", + "mobile", + "keyboard" + ], + "changelog": "Smoother animations and a new colour theme.", + "developer": "Mira Vale", + "source_url": null, + "publisher": "npub1jskittyvector000000000000000000000000000000000000000000", + "published_at": 1792980000, + "signed_at": 1792980000, + "installed": false, + "local_path": null, + "installed_version": null, + "update_available": false, + "requested_permissions": "microphone" + }, + { + "id": "poll", + "name": "Quick Poll", + "description": "Ask the chat a question and watch the votes come in live.", + "version": "1.4.0", + "blossom_hash": "0000000000000000000000000000000000000000000000000000000000000004", + "download_url": "https://ref.invalid/poll.xdc", + "size": 544000, + "icon_url": "https://ref.invalid/poll.png", + "icon_mime": "image/png", + "icon_cached": "media/apps/poll.png", + "categories": [ + "app", + "productivity", + "social" + ], + "changelog": null, + "developer": "Pixel Cat", + "source_url": "https://github.com/example/poll", + "publisher": "npub1jskittyvector000000000000000000000000000000000000000000", + "published_at": 1792548000, + "signed_at": 1792548000, + "installed": true, + "local_path": "/tmp/poll.xdc", + "installed_version": "1.0.0", + "update_available": true, + "requested_permissions": "" + }, + { + "id": "notes", + "name": "Shared Notes", + "description": "A notepad everyone in the chat can edit together.", + "version": "1.5.0", + "blossom_hash": "0000000000000000000000000000000000000000000000000000000000000005", + "download_url": "https://ref.invalid/notes.xdc", + "size": 635000, + "icon_url": "https://ref.invalid/notes.png", + "icon_mime": "image/png", + "icon_cached": "media/apps/notes.png", + "categories": [ + "app", + "productivity", + "multiplayer" + ], + "changelog": null, + "developer": null, + "source_url": null, + "publisher": "npub1jskittyvector000000000000000000000000000000000000000000", + "published_at": 1792116000, + "signed_at": 1792116000, + "installed": false, + "local_path": null, + "installed_version": null, + "update_available": false, + "requested_permissions": "" + }, + { + "id": "mines", + "name": "Minefield", + "description": "Clear the board without setting off a mine.", + "version": "1.6.0", + "blossom_hash": "0000000000000000000000000000000000000000000000000000000000000006", + "download_url": "https://ref.invalid/mines.xdc", + "size": 726000, + "icon_url": "https://ref.invalid/mines.png", + "icon_mime": "image/png", + "icon_cached": "media/apps/mines.png", + "categories": [ + "game", + "puzzle", + "retro", + "keyboard" + ], + "changelog": "Smoother animations and a new colour theme.", + "developer": "Mira Vale", + "source_url": "https://github.com/example/mines", + "publisher": "npub1jskittyvector000000000000000000000000000000000000000000", + "published_at": 1791684000, + "signed_at": 1791684000, + "installed": false, + "local_path": null, + "installed_version": null, + "update_available": false, + "requested_permissions": "" + }, + { + "id": "cards", + "name": "Crazy Cards", + "description": "Match colours and numbers, then play your last card first.", + "version": "1.7.0", + "blossom_hash": "0000000000000000000000000000000000000000000000000000000000000007", + "download_url": "https://ref.invalid/cards.xdc", + "size": 817000, + "icon_url": "https://ref.invalid/cards.png", + "icon_mime": "image/png", + "icon_cached": "media/apps/cards.png", + "categories": [ + "game", + "multiplayer", + "cards", + "party", + "keyboard", + "mobile" + ], + "changelog": null, + "developer": "Pixel Cat", + "source_url": null, + "publisher": "npub1jskittyvector000000000000000000000000000000000000000000", + "published_at": 1791252000, + "signed_at": 1791252000, + "installed": false, + "local_path": null, + "installed_version": null, + "update_available": false, + "requested_permissions": "" + }, + { + "id": "racer", + "name": "Pixel Racer", + "description": "Retro top-down racing with a controller or the arrow keys.", + "version": "1.8.0", + "blossom_hash": "0000000000000000000000000000000000000000000000000000000000000008", + "download_url": "https://ref.invalid/racer.xdc", + "size": 908000, + "icon_url": "https://ref.invalid/racer.png", + "icon_mime": "image/png", + "icon_cached": "media/apps/racer.png", + "categories": [ + "game", + "racing", + "retro", + "controller", + "keyboard" + ], + "changelog": null, + "developer": null, + "source_url": "https://github.com/example/racer", + "publisher": "npub1jskittyvector000000000000000000000000000000000000000000", + "published_at": 1790820000, + "signed_at": 1790820000, + "installed": false, + "local_path": null, + "installed_version": null, + "update_available": false, + "requested_permissions": "" + } + ], + "pivx": { + "balance": 42.5, + "price": { + "currency": "usd", + "value": 0.21 + }, + "deposit_address": "DLabsktzGMnsK5K9uRTMCF6NoYNY6ET4Bb", + "promos": [ + { + "gift_code": "PIVX-7QK2M", + "address": "DA1", + "balance_piv": 25.0, + "status": "confirmed", + "created_at": 0 + }, + { + "gift_code": "PIVX-3XN8B", + "address": "DA2", + "balance_piv": 12.5, + "status": "confirmed", + "created_at": 0 + }, + { + "gift_code": "PIVX-9TR4C", + "address": "DA3", + "balance_piv": 5.0, + "status": "confirmed", + "created_at": 0 + } + ], + "currencies": [ + "AUD", + "CAD", + "EUR", + "GBP", + "JPY", + "USD" + ], + "payments": [ + { + "conversation_id": "npub17jjvuhaxxs9rt2jakz6td5c6d7a2vpfr2erqmwc9xajhmqplt03q63stmv", + "message_id": "b100000000000000000000000000000000000000000000000000000000000000", + "gift_code": "PIVX-AB12C", + "amount_piv": 10.0, + "sender": "npub17jjvuhaxxs9rt2jakz6td5c6d7a2vpfr2erqmwc9xajhmqplt03q63stmv", + "is_mine": false, + "at": 1794362040000 + }, + { + "conversation_id": "npub17jjvuhaxxs9rt2jakz6td5c6d7a2vpfr2erqmwc9xajhmqplt03q63stmv", + "message_id": "b200000000000000000000000000000000000000000000000000000000000000", + "gift_code": "PIVX-DE34F", + "amount_piv": 2.5, + "sender": "npub1yazve5gvw5em6um2mzg0nh2u4v4dkfas04gqh9yn72wdcssvktsqfmmmv4", + "is_mine": true, + "at": 1794362100000 + } + ] + }, + "chatlist_demo": { + "pinned": [ + "npub1fsndjp6vylvfahjeyuxq4s2tw8s8rv2j89ge7a28fvhnhf35s86sg3uctf", + "npub1wajx7kj0x9nxxa38405e3eapgu87wtvtgv8svld04p3x8u0j872qnta00x" + ], + "archived": { + "npub1v84qsqlcs56j8dmh6s22eccnpn2d87fdutxhl7rftseh67wzamhqfv9ft6": 1794290400000, + "npub10j7vkrzv4t0elnd4rmj902pge3e2gkresvd4h9u2ut3valzyjuzsz7ad26": 1794268800000 + } + }, + "rail_demo": [ + { + "community_id": "a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1", + "name": "Rust Club" + }, + { + "community_id": "a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2", + "name": "Nostr Devs" + }, + { + "community_id": "a3a3a3a3a3a3a3a3a3a3a3a3a3a3a3a3a3a3a3a3a3a3a3a3a3a3a3a3a3a3a3a3", + "name": "Pixel Art" + }, + { + "community_id": "a4a4a4a4a4a4a4a4a4a4a4a4a4a4a4a4a4a4a4a4a4a4a4a4a4a4a4a4a4a4a4a4", + "name": "Bookworms" + } + ], + "voice_demo": { + "present": { + "58e6267876fd6c4acb7fbc37091bb920e4f325e24df4887b8048d0ccf7137f2f": [ + { + "npub": "npub190vqdjtlpcq27xslcveglfmr4ynfwg7gmw86cnun4acakxrdd6gqnp929a", + "muted": false, + "deafened": false, + "server_muted": false, + "server_deafened": false, + "screen": false, + "camera": false, + "elsewhere": false + }, + { + "npub": "npub1sxmr0k8u6trd5c6eu6trzyapzux7090ykujmsng7pdx0m8k93n5sd02fwn", + "muted": true, + "deafened": false, + "server_muted": false, + "server_deafened": false, + "screen": false, + "camera": false, + "elsewhere": false + }, + { + "npub": "npub1fsndjp6vylvfahjeyuxq4s2tw8s8rv2j89ge7a28fvhnhf35s86sg3uctf", + "muted": true, + "deafened": true, + "server_muted": false, + "server_deafened": true, + "screen": false, + "camera": false, + "elsewhere": false + } + ] + }, + "joined": { + "58e6267876fd6c4acb7fbc37091bb920e4f325e24df4887b8048d0ccf7137f2f": [ + { + "npub": "npub1yazve5gvw5em6um2mzg0nh2u4v4dkfas04gqh9yn72wdcssvktsqfmmmv4", + "muted": false, + "deafened": false, + "server_muted": false, + "server_deafened": false, + "screen": false, + "camera": false, + "elsewhere": false + }, + { + "npub": "npub190vqdjtlpcq27xslcveglfmr4ynfwg7gmw86cnun4acakxrdd6gqnp929a", + "muted": false, + "deafened": false, + "server_muted": false, + "server_deafened": false, + "screen": false, + "camera": false, + "elsewhere": false + }, + { + "npub": "npub1sxmr0k8u6trd5c6eu6trzyapzux7090ykujmsng7pdx0m8k93n5sd02fwn", + "muted": true, + "deafened": false, + "server_muted": false, + "server_deafened": false, + "screen": false, + "camera": false, + "elsewhere": false + }, + { + "npub": "npub1fsndjp6vylvfahjeyuxq4s2tw8s8rv2j89ge7a28fvhnhf35s86sg3uctf", + "muted": true, + "deafened": true, + "server_muted": false, + "server_deafened": true, + "screen": false, + "camera": false, + "elsewhere": false + } + ] + }, + "session": { + "community_id": "ca848c275e2117470342c641ada0ae4639dd0472ab4a5ec654a189bf1f689087", + "channel_id": "58e6267876fd6c4acb7fbc37091bb920e4f325e24df4887b8048d0ccf7137f2f", + "peers": [ + { + "npub": "npub190vqdjtlpcq27xslcveglfmr4ynfwg7gmw86cnun4acakxrdd6gqnp929a", + "pubkey": "1111111111111111111111111111111111111111111111111111111111111111", + "volume": 1.0, + "connected": true, + "direct": true, + "rtt_ms": 38, + "level": 0.6, + "muted": false, + "deafened": false, + "server_muted": false, + "server_deafened": false, + "screen": false, + "camera": false + }, + { + "npub": "npub1sxmr0k8u6trd5c6eu6trzyapzux7090ykujmsng7pdx0m8k93n5sd02fwn", + "pubkey": "2222222222222222222222222222222222222222222222222222222222222222", + "volume": 1.0, + "connected": true, + "direct": true, + "rtt_ms": 64, + "level": 0.0, + "muted": true, + "deafened": false, + "server_muted": false, + "server_deafened": false, + "screen": false, + "camera": false + }, + { + "npub": "npub1fsndjp6vylvfahjeyuxq4s2tw8s8rv2j89ge7a28fvhnhf35s86sg3uctf", + "pubkey": "3333333333333333333333333333333333333333333333333333333333333333", + "volume": 1.0, + "connected": true, + "direct": false, + "rtt_ms": 120, + "level": 0.0, + "muted": true, + "deafened": true, + "server_muted": false, + "server_deafened": true, + "screen": false, + "camera": false + } + ], + "muted": false, + "deafened": false, + "audio": true, + "mic_level": 0.0, + "mic": true, + "server_muted": false, + "server_deafened": false, + "sharing": false, + "viewers": 0, + "camera": false, + "can_video": false + }, + "video": { + "58e6267876fd6c4acb7fbc37091bb920e4f325e24df4887b8048d0ccf7137f2f": [ + { + "npub": "npub1yazve5gvw5em6um2mzg0nh2u4v4dkfas04gqh9yn72wdcssvktsqfmmmv4", + "muted": false, + "deafened": false, + "server_muted": false, + "server_deafened": false, + "screen": false, + "camera": true, + "elsewhere": false + }, + { + "npub": "npub190vqdjtlpcq27xslcveglfmr4ynfwg7gmw86cnun4acakxrdd6gqnp929a", + "muted": false, + "deafened": false, + "server_muted": false, + "server_deafened": false, + "screen": true, + "camera": true, + "elsewhere": false + }, + { + "npub": "npub1sxmr0k8u6trd5c6eu6trzyapzux7090ykujmsng7pdx0m8k93n5sd02fwn", + "muted": true, + "deafened": false, + "server_muted": false, + "server_deafened": false, + "screen": false, + "camera": false, + "elsewhere": false + }, + { + "npub": "npub1fsndjp6vylvfahjeyuxq4s2tw8s8rv2j89ge7a28fvhnhf35s86sg3uctf", + "muted": true, + "deafened": true, + "server_muted": false, + "server_deafened": true, + "screen": false, + "camera": false, + "elsewhere": false + } + ] + }, + "session_video": { + "community_id": "ca848c275e2117470342c641ada0ae4639dd0472ab4a5ec654a189bf1f689087", + "channel_id": "58e6267876fd6c4acb7fbc37091bb920e4f325e24df4887b8048d0ccf7137f2f", + "peers": [ + { + "npub": "npub190vqdjtlpcq27xslcveglfmr4ynfwg7gmw86cnun4acakxrdd6gqnp929a", + "pubkey": "1111111111111111111111111111111111111111111111111111111111111111", + "volume": 1.0, + "connected": true, + "direct": true, + "rtt_ms": 38, + "level": 0.6, + "muted": false, + "deafened": false, + "server_muted": false, + "server_deafened": false, + "screen": false, + "camera": false + }, + { + "npub": "npub1sxmr0k8u6trd5c6eu6trzyapzux7090ykujmsng7pdx0m8k93n5sd02fwn", + "pubkey": "2222222222222222222222222222222222222222222222222222222222222222", + "volume": 1.0, + "connected": true, + "direct": true, + "rtt_ms": 64, + "level": 0.0, + "muted": true, + "deafened": false, + "server_muted": false, + "server_deafened": false, + "screen": false, + "camera": false + }, + { + "npub": "npub1fsndjp6vylvfahjeyuxq4s2tw8s8rv2j89ge7a28fvhnhf35s86sg3uctf", + "pubkey": "3333333333333333333333333333333333333333333333333333333333333333", + "volume": 1.0, + "connected": true, + "direct": false, + "rtt_ms": 120, + "level": 0.0, + "muted": true, + "deafened": true, + "server_muted": false, + "server_deafened": true, + "screen": false, + "camera": false + } + ], + "muted": false, + "deafened": false, + "audio": true, + "mic_level": 0.0, + "mic": true, + "server_muted": false, + "server_deafened": false, + "sharing": false, + "viewers": 0, + "camera": true, + "can_video": true + } + }, + "pins_demo": { + "a0f367a05f629b3bb09ee8f1561bf03267962217d9ff6fc7ce3b235235702bc1": [ + { + "rumor_id": "7a3c760d48ddcb81b5b84767bdb6888628fe32badc3075ee364324255c1f53a1", + "author": "2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b", + "kind": 9, + "content": "Welcome to the new community!", + "tags": [], + "epoch": null, + "ms": 1794360000000, + "created_at": 1794360000, + "wrap_hint": null, + "edited": null + }, + { + "rumor_id": "c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0", + "author": "2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b", + "kind": 9, + "content": "**Community rules**\n1. Be kind to each other\n2. No spam or self-promotion\n3. Keep it on topic", + "tags": [], + "epoch": null, + "ms": 1793000000000, + "created_at": 1793000000, + "wrap_hint": null, + "edited": null + }, + { + "rumor_id": "d1d1d1d1d1d1d1d1d1d1d1d1d1d1d1d1d1d1d1d1d1d1d1d1d1d1d1d1d1d1d1d1", + "author": "2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b", + "kind": 9, + "content": "Relay list for the meetup: wss://relay.damus.io, wss://nos.lol, wss://relay.primal.net, wss://relay.snort.social and wss://nostr.wine for anyone who wants paid", + "tags": [], + "epoch": null, + "ms": 1792000000000, + "created_at": 1792000000, + "wrap_hint": null, + "edited": null + }, + { + "rumor_id": "e2e2e2e2e2e2e2e2e2e2e2e2e2e2e2e2e2e2e2e2e2e2e2e2e2e2e2e2e2e2e2e2", + "author": "2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b", + "kind": 9, + "content": "", + "tags": [ + [ + "imeta", + "url https://blossom.example/abc", + "m application/pdf", + "name roadmap.pdf" + ] + ], + "epoch": null, + "ms": 1791000000000, + "created_at": 1791000000, + "wrap_hint": null, + "edited": null + } + ] + }, + "server_demo": { + "https://magnitude.vectorapp.io": { + "status": { + "state": "online", + "label": "Online", + "tone": "connected", + "latency_ms": 84 + }, + "stats": { + "latency_ms": 84.3, + "mbps": 23.4, + "best_mbps": 41.2, + "uploads": 37, + "bytes_total": 851443712, + "last_ok_at": null, + "last_fail_at": null, + "last_fail_kind": null, + "recent": [ + [ + 12.1, + 3145728 + ], + [ + 18.4, + 9437184 + ], + [ + 9.7, + 1048576 + ], + [ + 26.0, + 23068672 + ], + [ + 41.2, + 50331648 + ], + [ + 22.5, + 12582912 + ], + [ + 30.8, + 32505856 + ], + [ + 23.4, + 8388608 + ] + ] + }, + "info": { + "name": "Magnitude", + "software": null, + "version": null, + "description": null, + "buds": [ + 1, + 2 + ], + "extensions": [], + "max_blob": null, + "mime": [], + "capacity_used": null, + "capacity_limit": null, + "fetched_at": 0, + "caller": { + "tier": "badged", + "max_blob": 536870912, + "storage_used": 1300234240, + "storage_limit": 10737418240, + "blobs": 214, + "daily_used": 1981808640, + "daily_limit": 2147483648, + "allowed": true, + "reasons": [], + "plan_title": "Premium", + "plan_description": "Thanks for backing Vector." + } + }, + "caps": [] + }, + "https://blossom.ditto.pub": { + "status": { + "state": "untested", + "label": "Untested", + "tone": "disabled", + "latency_ms": null + }, + "stats": null, + "info": null, + "caps": [ + { + "mime_type": "image/png", + "is_encrypted": true, + "outcome": 1, + "max_accepted_size": 12582912, + "min_rejected_size": null, + "updated_at": 0 + }, + { + "mime_type": "image/jpeg", + "is_encrypted": false, + "outcome": 1, + "max_accepted_size": 5242880, + "min_rejected_size": null, + "updated_at": 0 + }, + { + "mime_type": "video/mp4", + "is_encrypted": true, + "outcome": 3, + "max_accepted_size": 0, + "min_rejected_size": 104857600, + "updated_at": 0 + }, + { + "mime_type": "application/x-msdownload", + "is_encrypted": true, + "outcome": 2, + "max_accepted_size": 0, + "min_rejected_size": null, + "updated_at": 0 + } + ] + } + }, + "net_demo": { + "i2p_config": { + "sam_port": 7656, + "sam_user": null, + "sam_auth": false, + "exit": "allow", + "outproxies": [ + { + "id": "stormycloud", + "name": "StormyCloud", + "address": "5d4s7pcvfdpftfk7npc7hllyujhufsdprtrf4o53i44rgsa2xbwa.b32.i2p", + "port": 80, + "enabled": true, + "builtin": true + }, + { + "id": "acetone", + "name": "Acetone", + "address": "proxy4uwdijqxac2bvdx4fuhem6njmiwukuk2gelejv2nzxka2xq.b32.i2p", + "port": 3128, + "enabled": true, + "builtin": true + } + ], + "defaults": [ + { + "id": "stormycloud", + "name": "StormyCloud", + "address": "5d4s7pcvfdpftfk7npc7hllyujhufsdprtrf4o53i44rgsa2xbwa.b32.i2p", + "port": 80, + "enabled": true, + "builtin": true + }, + { + "id": "acetone", + "name": "Acetone", + "address": "proxy4uwdijqxac2bvdx4fuhem6njmiwukuk2gelejv2nzxka2xq.b32.i2p", + "port": 3128, + "enabled": true, + "builtin": true + } + ], + "customized": false + }, + "clearnet": { + "view": { + "label": null, + "supported": [ + "clearnet", + "tor", + "i2p" + ], + "blocked": false, + "progress": null, + "reason": null, + "retry_in": null, + "since": 0, + "prelogin": "clearnet", + "prelogin_armed": false, + "realtime_allowed": false, + "realtime_active": false, + "call_active": false, + "config_seq": 1, + "steps": [], + "detail": null, + "kind": "clearnet", + "phase": "direct", + "ready": true + } + }, + "tor": { + "view": { + "label": "Tor", + "supported": [ + "clearnet", + "tor", + "i2p" + ], + "blocked": false, + "progress": null, + "reason": null, + "retry_in": null, + "since": 0, + "prelogin": "clearnet", + "prelogin_armed": false, + "realtime_allowed": false, + "realtime_active": false, + "call_active": false, + "config_seq": 1, + "steps": [], + "detail": { + "status": "connected", + "bootstrap_progress": 100, + "multi_circuit": true + }, + "kind": "tor", + "phase": "ready", + "ready": true + }, + "tor": { + "enabled": true, + "running": true, + "supported": true, + "status": "connected", + "bootstrap_progress": 100, + "prelogin": false, + "multi_circuit": true, + "socks_proxy": null + }, + "circuits": { + "host": null, + "hops": [], + "circuits": 4, + "hosts": 6 + } + }, + "tor_single": { + "view": { + "label": "Tor", + "supported": [ + "clearnet", + "tor", + "i2p" + ], + "blocked": false, + "progress": null, + "reason": null, + "retry_in": null, + "since": 0, + "prelogin": "clearnet", + "prelogin_armed": false, + "realtime_allowed": false, + "realtime_active": false, + "call_active": false, + "config_seq": 1, + "steps": [], + "detail": { + "status": "connected", + "bootstrap_progress": 100, + "multi_circuit": false + }, + "kind": "tor", + "phase": "ready", + "ready": true + }, + "tor": { + "enabled": true, + "running": true, + "supported": true, + "status": "connected", + "bootstrap_progress": 100, + "prelogin": false, + "multi_circuit": false, + "socks_proxy": null + }, + "circuits": { + "host": "jskitty.com", + "hops": [ + { + "position": "Guard", + "address": "185.220.101.4:443", + "fingerprint": "A1B2C3D4E5F60718293A4B5C6D7E8F9012345678", + "is_bridge": false + }, + { + "position": "Middle", + "address": "94.23.172.32:9001", + "fingerprint": "1122334455667788990011223344556677889900", + "is_bridge": false + }, + { + "position": "Exit", + "address": "199.249.230.87:443", + "fingerprint": "FFEEDDCCBBAA99887766554433221100FFEEDDCC", + "is_bridge": false + } + ], + "circuits": 1, + "hosts": 3 + } + }, + "tor_boot": { + "view": { + "label": "Tor", + "supported": [ + "clearnet", + "tor", + "i2p" + ], + "blocked": true, + "progress": 45, + "reason": null, + "retry_in": null, + "since": 0, + "prelogin": "clearnet", + "prelogin_armed": false, + "realtime_allowed": false, + "realtime_active": false, + "call_active": false, + "config_seq": 1, + "steps": [], + "detail": { + "status": "bootstrapping", + "bootstrap_progress": 45, + "multi_circuit": true + }, + "kind": "tor", + "phase": "starting", + "ready": false + }, + "tor": { + "enabled": true, + "running": false, + "supported": true, + "status": "bootstrapping 45%", + "bootstrap_progress": 45, + "prelogin": false, + "multi_circuit": true, + "socks_proxy": null + } + }, + "i2p": { + "view": { + "label": "I2P", + "supported": [ + "clearnet", + "tor", + "i2p" + ], + "blocked": false, + "progress": null, + "reason": null, + "retry_in": null, + "since": 0, + "prelogin": "clearnet", + "prelogin_armed": false, + "realtime_allowed": false, + "realtime_active": false, + "call_active": false, + "config_seq": 1, + "steps": [ + { + "id": "router", + "label": "Router", + "state": "ok", + "text": "SAM 3.3 on port 7656" + }, + { + "id": "tunnels", + "label": "Tunnels", + "state": "ok", + "text": "Ready" + }, + { + "id": "exit", + "label": "Clearnet", + "state": "ok", + "text": "Via StormyCloud" + } + ], + "detail": { + "b32": null + }, + "kind": "i2p", + "phase": "ready", + "ready": true + }, + "routes": [ + { + "url": "wss://jskitty.com/nostr", + "host": "jskitty.com", + "kind": "i2p", + "class": "twin", + "via": "nostrakjf3mw7a2xqzlh4vpcdg6ytb5neiu4rs7k2o3pqfvxhcj5kn5a.b32.i2p", + "text": "Through its I2P address", + "last_error": null + }, + { + "url": "wss://asia.vectorapp.io/nostr", + "host": "asia.vectorapp.io", + "kind": "i2p", + "class": "exit", + "via": "StormyCloud", + "text": "Through the StormyCloud outproxy", + "last_error": null + }, + { + "url": "wss://nostr.computingcache.com", + "host": "nostr.computingcache.com", + "kind": "i2p", + "class": "exit", + "via": "StormyCloud", + "text": "Through the StormyCloud outproxy", + "last_error": null + }, + { + "url": "wss://relay.example.org", + "host": "relay.example.org", + "kind": "i2p", + "class": "refused", + "via": null, + "text": "I2P-Only is on, so this server is off.", + "last_error": null + }, + { + "url": "https://magnitude.vectorapp.io", + "host": "magnitude.vectorapp.io", + "kind": "i2p", + "class": "twin", + "via": "nostrakjf3mw7a2xqzlh4vpcdg6ytb5neiu4rs7k2o3pqfvxhcj5kn5a.b32.i2p", + "text": "Through its I2P address", + "last_error": null + }, + { + "url": "https://blossom.ditto.pub", + "host": "blossom.ditto.pub", + "kind": "i2p", + "class": "blocked", + "via": null, + "text": "Blocked: The outproxy didn\u2019t answer.", + "last_error": "The outproxy didn\u2019t answer." + } + ], + "aliases": [ + { + "host": "jskitty.com", + "twins": { + "i2p": "nostrakjf3mw7a2xqzlh4vpcdg6ytb5neiu4rs7k2o3pqfvxhcj5kn5a.b32.i2p" + }, + "source": "builtin", + "check": { + "state": "ok", + "at": null, + "text": null + } + }, + { + "host": "magnitude.vectorapp.io", + "twins": { + "i2p": "nostrakjf3mw7a2xqzlh4vpcdg6ytb5neiu4rs7k2o3pqfvxhcj5kn5a.b32.i2p" + }, + "source": "user", + "check": { + "state": "ok", + "at": null, + "text": null + } + }, + { + "host": "nostr.computingcache.com", + "twins": { + "i2p": "nostrakjf3mw7a2xqzlh4vpcdg6ytb5neiu4rs7k2o3pqfvxhcj5kn5a.b32.i2p" + }, + "source": "user", + "check": { + "state": "failed", + "at": null, + "text": "This address doesn\u2019t serve nostr.computingcache.com. Vector won\u2019t use it." + } + } + ] + }, + "i2p_start": { + "view": { + "label": "I2P", + "supported": [ + "clearnet", + "tor", + "i2p" + ], + "blocked": true, + "progress": null, + "reason": null, + "retry_in": null, + "since": 0, + "prelogin": "clearnet", + "prelogin_armed": false, + "realtime_allowed": false, + "realtime_active": false, + "call_active": false, + "config_seq": 1, + "steps": [ + { + "id": "router", + "label": "Router", + "state": "ok", + "text": "SAM 3.3 on port 7656" + }, + { + "id": "tunnels", + "label": "Tunnels", + "state": "pending", + "text": "Building\u2026 12s" + }, + { + "id": "exit", + "label": "Clearnet", + "state": "pending", + "text": "Waiting\u2026" + } + ], + "detail": null, + "kind": "i2p", + "phase": "starting", + "ready": false + } + }, + "i2p_down": { + "view": { + "label": "I2P", + "supported": [ + "clearnet", + "tor", + "i2p" + ], + "blocked": true, + "progress": null, + "reason": { + "code": "router_unreachable", + "text": "Your I2P router isn\u2019t answering on port 7656." + }, + "retry_in": 8, + "since": 0, + "prelogin": "clearnet", + "prelogin_armed": false, + "realtime_allowed": false, + "realtime_active": false, + "call_active": false, + "config_seq": 1, + "steps": [ + { + "id": "router", + "label": "Router", + "state": "fail", + "text": "Not answering" + }, + { + "id": "tunnels", + "label": "Tunnels", + "state": "pending", + "text": "Waiting\u2026" + }, + { + "id": "exit", + "label": "Clearnet", + "state": "pending", + "text": "Waiting\u2026" + } + ], + "detail": null, + "kind": "i2p", + "phase": "waiting", + "ready": false + } + }, + "login_tor": { + "view": { + "label": "Tor", + "supported": [ + "clearnet", + "tor", + "i2p" + ], + "blocked": true, + "progress": 45, + "reason": null, + "retry_in": null, + "since": 0, + "prelogin": "tor", + "prelogin_armed": false, + "realtime_allowed": false, + "realtime_active": false, + "call_active": false, + "config_seq": 1, + "steps": [], + "detail": { + "status": "bootstrapping", + "bootstrap_progress": 45, + "multi_circuit": true + }, + "kind": "tor", + "phase": "starting", + "ready": false + }, + "tor": { + "enabled": true, + "running": false, + "supported": true, + "status": "bootstrapping 45%", + "bootstrap_progress": 45, + "prelogin": false, + "multi_circuit": true, + "socks_proxy": null + } + }, + "login_i2p_down": { + "view": { + "label": "I2P", + "supported": [ + "clearnet", + "tor", + "i2p" + ], + "blocked": true, + "progress": null, + "reason": { + "code": "router_unreachable", + "text": "Your I2P router isn\u2019t answering on port 7656." + }, + "retry_in": 8, + "since": 0, + "prelogin": "i2p", + "prelogin_armed": false, + "realtime_allowed": false, + "realtime_active": false, + "call_active": false, + "config_seq": 1, + "steps": [ + { + "id": "router", + "label": "Router", + "state": "fail", + "text": "Not answering" + }, + { + "id": "tunnels", + "label": "Tunnels", + "state": "pending", + "text": "Waiting\u2026" + }, + { + "id": "exit", + "label": "Clearnet", + "state": "pending", + "text": "Waiting\u2026" + } + ], + "detail": null, + "kind": "i2p", + "phase": "waiting", + "ready": false + } + }, + "login_clearnet": { + "view": { + "label": null, + "supported": [ + "clearnet", + "tor", + "i2p" + ], + "blocked": false, + "progress": null, + "reason": null, + "retry_in": null, + "since": 0, + "prelogin": "clearnet", + "prelogin_armed": false, + "realtime_allowed": false, + "realtime_active": false, + "call_active": false, + "config_seq": 1, + "steps": [], + "detail": null, + "kind": "clearnet", + "phase": "direct", + "ready": true + } + } + }, + "sync_report": { + "control": { + "root_epoch": 3, + "converged": true, + "complete": true, + "activated": true, + "authority_gapped": false, + "fold_gapped": false, + "truncated": false, + "pages_read": 4, + "editions": 27, + "would_update": true, + "healed": [], + "entities": [ + { + "entity": "9f2c41d07ab3", + "kind": 2, + "mine": false, + "served": 3, + "newest": { + "version": 5, + "age_days": 1, + "author": "owner", + "admitted": true, + "is_floor": false, + "extends_floor": true + }, + "floor": { + "version": 4, + "served": true + }, + "folds_to": null, + "refused": null, + "carried": false, + "kept": false + }, + { + "entity": "1be07c9a44d2", + "kind": 1, + "mine": false, + "served": 2, + "newest": { + "version": 2, + "age_days": 6, + "author": "3e1a90bb27c4", + "admitted": false, + "is_floor": false, + "extends_floor": false + }, + "floor": { + "version": 1, + "served": true + }, + "folds_to": null, + "refused": "unauthorized", + "carried": false, + "kept": false + }, + { + "entity": "a03d55e18f60", + "kind": 0, + "mine": false, + "served": 1, + "newest": { + "version": 9, + "age_days": 0, + "author": "owner", + "admitted": true, + "is_floor": true, + "extends_floor": null + }, + "floor": { + "version": 9, + "served": true + }, + "folds_to": null, + "refused": null, + "carried": false, + "kept": false + } + ] + }, + "epoch": { + "root_epoch": 3, + "verdict": "current", + "held": { + "epoch": 3, + "base_plane": "5c0e2a91d7f3" + } + } + }, + "relay_info": { + "wss://jskitty.com/nostr": { + "name": "JSKitty's Relay", + "icon": "avatars/grace.png", + "auth": true + }, + "wss://asia.vectorapp.io/nostr": { + "name": "Vector Asia", + "icon": null, + "auth": false + } + } +} diff --git a/crates/vector-gpui/reference/gen-fixtures.mjs b/crates/vector-gpui/reference/gen-fixtures.mjs new file mode 100644 index 000000000..a736e15b7 --- /dev/null +++ b/crates/vector-gpui/reference/gen-fixtures.mjs @@ -0,0 +1,163 @@ +// Deterministic fixture data, shared by the Tauri reference render and vector-gpui. +import { writeFileSync, readFileSync } from 'fs'; +import { createHash } from 'crypto'; + +const NOW = Date.parse('2026-11-11T02:00:00Z'); +const CHARSET = 'qpzry9x8gf2tvdw0s3jn54khce6mua7l'; +function polymod(values) { + const G = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3]; + let chk = 1; + for (const v of values) { const b = chk >> 25; chk = ((chk & 0x1ffffff) << 5) ^ v; for (let i = 0; i < 5; i++) if ((b >> i) & 1) chk ^= G[i]; } + return chk; +} +function npub(seed) { + const bytes = createHash('sha256').update(seed).digest(); + const data = []; let acc = 0, bits = 0; + for (const b of bytes) { acc = (acc << 8) | b; bits += 8; while (bits >= 5) { bits -= 5; data.push((acc >> bits) & 31); } } + if (bits) data.push((acc << (5 - bits)) & 31); + const hrp = 'npub'; + const exp = [...[...hrp].map(c => c.charCodeAt(0) >> 5), 0, ...[...hrp].map(c => c.charCodeAt(0) & 31)]; + const mod = polymod([...exp, ...data, 0, 0, 0, 0, 0, 0]) ^ 1; + const sum = [...Array(6)].map((_, i) => (mod >> (5 * (5 - i))) & 31); + return hrp + '1' + [...data, ...sum].map(d => CHARSET[d]).join(''); +} +const hex = (s) => createHash('sha256').update(s).digest('hex'); + +const me = npub('me'); +const people = [ + ['alice', 'Alice', 'Running late, save me a seat!', 2, 3], + ['bob', 'Bob Nakamoto', 'The new build is so much faster 🚀', 25, 0], + ['carol', 'Carol', 'haha yes exactly', 60 * 3, 1], + ['dave', 'Dave the Builder', 'Sent you the invoice', 60 * 20, 0], + ['erin', 'Erin', 'Can you check the relay list later?', 60 * 26, 0], + ['frank', 'Frank', 'gm', 60 * 24 * 3, 0], + ['grace', 'Grace Hopper', 'It\'s easier to ask forgiveness than permission.', 60 * 24 * 9, 0], + ['heidi', 'Heidi', 'See you on Saturday', 60 * 24 * 40, 0], +]; +const profile = (o) => ({ id: '', name: '', display_name: '', nickname: '', lud06: '', lud16: '', banner: '', avatar: '', about: '', website: '', nip05: '', + status: { title: '', purpose: '', url: '' }, last_updated: Math.floor(NOW / 1000), mine: false, bot: false, is_blocked: false, + avatar_cached: '', banner_cached: '', stream_consent: false, ...o }); +const profiles = [profile({ id: me, name: 'jskitty', display_name: 'JSKitty', mine: true })]; +const chats = []; +for (const [seed, name, last, minsAgo, unread] of people) { + const id = npub(seed); + const extra = seed === 'bob' + ? { about: 'Building on Nostr since 2021.\nCoffee first, relays second ⚡', status: { title: 'Shipping v0.6 🚀', purpose: 'general', url: '' }, + banner: 'https://example.invalid/bob-banner.png', banner_cached: 'media/photo.png' } + : {}; + profiles.push(profile({ id, name: seed, display_name: name, avatar: `https://example.invalid/${seed}.png`, avatar_cached: `avatars/${seed}.png`, ...extra })); + const at = NOW - minsAgo * 60_000; + const convo = [ + [false, `Hey! It's ${name.split(' ')[0]}`, 50], + [true, 'Hey, how are you doing?', 48], + [false, 'Pretty good, working on something fun.', 45], + [true, 'Ooh, tell me more when you can 👀', 44], + [false, last, 0], + ]; + const messages = convo.map(([mine, content, back], i) => ({ + id: hex(`${seed}-${i}`), content, replied_to: '', preview_metadata: null, attachments: [], reactions: [], + at: at - back * 60_000, pending: false, failed: false, mine, npub: mine ? me : id, edited: false, + })); + chats.push({ + id, chat_type: 'DirectMessage', participants: [id], messages, + last_read: unread ? messages[messages.length - 1 - unread].id : messages[messages.length - 1].id, + unread_from: '', created_at: Math.floor((at - 3600_000) / 1000), metadata: { custom_fields: {} }, + muted: false, notify: 2, everyone_pings: true, community_muted: false, + }); +} + +// A conversation exercising the message renderer: streaks, a reply, reactions, edits, send +// states and the markdown Vector supports. +{ + const id = npub('vee'); + profiles.push(profile({ id, name: 'vee', display_name: 'Vee', avatar: 'https://example.invalid/alice.png', avatar_cached: 'avatars/alice.png' })); + const at = NOW - 60_000; + const m = (i, mine, content, back, extra = {}) => ({ + id: hex(`vee-${i}`), content, replied_to: '', preview_metadata: null, attachments: [], reactions: [], + at: at - back * 60_000, pending: false, failed: false, mine, npub: mine ? me : id, edited: false, ...extra, + }); + const react = (msg, author, emoji) => ({ id: hex(`r-${msg}-${author}-${emoji}`), reference_id: hex(`vee-${msg}`), author_id: author, emoji }); + const messages = [ + m(0, false, 'Have you tried the **new** markdown? It handles *italics*, ~~strikes~~ and `inline code`.', 60 * 26), + m(1, false, 'Lists too:\n- one\n- two\n- three', 60 * 26 - 1), + m(2, true, '> quoting you here\nand replying below the quote', 60 * 26 - 3, { reactions: [react(2, id, '❤️'), react(2, me, '❤️'), react(2, id, '😂')] }), + m(3, true, '```rust\nfn main() {\n println!("hello");\n}\n```', 60 * 26 - 4), + m(4, false, 'Nice! That one has a ||secret spoiler|| inside, and a [link](https://vectorapp.io).', 30, { edited: true, edit_history: [ + { content: 'Nice! That one has a secret inside', edited_at: at - 30 * 60_000 }, + { content: 'Nice! That one has a ||secret spoiler|| inside 🎉', edited_at: at - 28 * 60_000 }, + { content: 'Nice! That one has a ||secret spoiler|| inside, and a [link](https://vectorapp.io).', edited_at: at - 25 * 60_000 }, + ] }), + m(5, false, '# A heading\n-# and some subtext', 29), + m(6, true, 'Replying to that heading', 10, { replied_to: hex('vee-5'), replied_to_content: '# A heading\n-# and some subtext', replied_to_npub: id }), + m(7, true, 'This one is still sending', 2, { pending: true }), + m(8, true, 'And this one failed', 1, { failed: true }), + m(9, false, '👍', 0, { reactions: [react(9, me, '🔥')] }), + ]; + chats.unshift({ + id, chat_type: 'DirectMessage', participants: [id], messages, last_read: messages[messages.length - 1].id, + unread_from: '', created_at: Math.floor((at - 86400_000 * 2) / 1000), metadata: { custom_fields: {} }, + muted: false, notify: 2, everyone_pings: true, community_muted: false, + }); +} +// Attachments in each state a bubble draws: on this device, a blur waiting on a download +// (too large to auto-download), one auto-downloading, a veiled spoiler, and file boxes. +const thumbs = {}; +{ + const tsv = readFileSync(new URL('./media/thumbs.tsv', import.meta.url), 'utf8').trim().split('\n'); + const meta = Object.fromEntries(tsv.map((l) => { const [file, w, h, hash, url] = l.split('\t'); thumbs[hash] = url; return [file, { thumbhash: hash, width: +w, height: +h }]; })); + const id = npub('mo'); + profiles.push(profile({ id, name: 'mo', display_name: 'Mo', avatar: 'https://example.invalid/grace.png', avatar_cached: 'avatars/grace.png' })); + const at = NOW - 120_000; + const att = (seed, o) => ({ id: hex(`att-${seed}`), key: '', nonce: '', extension: 'png', name: '', url: `https://example.invalid/${seed}`, + path: '', size: 0, img_meta: null, downloading: false, downloaded: false, ...o }); + const m = (i, mine, content, back, attachments) => ({ + id: hex(`mo-${i}`), content, replied_to: '', preview_metadata: null, attachments, reactions: [], + at: at - back * 60_000, pending: false, failed: false, mine, npub: mine ? me : id, edited: false, + }); + const messages = [ + m(0, false, 'Look at this sunset', 50, [att('photo', { path: 'media/photo.png', downloaded: true, size: 170552, img_meta: meta['photo.png'] })]), + m(1, true, '', 40, [att('portrait', { size: 24_117_248, img_meta: meta['portrait.png'] })]), + m(2, false, '', 30, [att('sticker', { name: 'SPOILER_sticker.png', path: 'media/sticker.png', downloaded: true, size: 15319, img_meta: meta['sticker.png'] })]), + m(3, false, 'The spec, and the build', 20, [ + att('spec', { extension: 'pdf', name: 'Vector Protocol Spec.pdf', size: 13_002_342 }), + att('build', { extension: 'zip', name: 'vector-0.5.1-linux.zip', path: 'media/sticker.png', downloaded: true, size: 48_234_496 }), + ]), + m(4, true, 'Thanks!', 5, []), + ]; + chats.unshift({ + id, chat_type: 'DirectMessage', participants: [id], messages, last_read: messages[messages.length - 1].id, + unread_from: '', created_at: Math.floor((at - 86400_000) / 1000), metadata: { custom_fields: {} }, + muted: false, notify: 2, everyone_pings: true, community_muted: false, + }); +} +// Link preview cards: a page with a picture, one with only text, and a YouTube video. +{ + const id = npub('lin'); + profiles.push(profile({ id, name: 'lin', display_name: 'Lin', avatar: 'https://example.invalid/bob.png', avatar_cached: 'avatars/bob.png' })); + const at = NOW - 86400_000 * 3; + const meta = (o) => ({ domain: 'https://example.invalid/', og_title: null, og_description: null, og_image: null, og_url: null, og_type: null, + title: null, description: null, favicon: 'https://example.invalid/favicon.ico', ...o }); + const m = (i, mine, content, back, preview_metadata = null) => ({ + id: hex(`lin-${i}`), content, replied_to: '', preview_metadata, attachments: [], reactions: [], + at: at - back * 60_000, pending: false, failed: false, mine, npub: mine ? me : id, edited: false, + }); + const messages = [ + m(0, false, 'Have a read: https://example.invalid/posts/private-by-default', 30, meta({ + og_title: 'Private by default', og_url: 'https://example.invalid/posts/private-by-default', + og_description: 'Why every message you send should be sealed before it leaves your device.\nA look at gift wraps, relays and what they can never learn.
Part one of three.', + og_image: 'https://example.invalid/og.png', + })), + m(1, true, 'https://example.invalid/docs', 20, meta({ title: 'Docs', description: 'Short and to the point.' })), + m(2, false, 'Watch this https://www.youtube.com/watch?v=dQw4w9WgXcQ', 10, meta({ + domain: 'https://www.youtube.com/', og_title: 'A video worth watching', og_url: 'https://www.youtube.com/watch?v=dQw4w9WgXcQ', + og_image: 'https://i.ytimg.com/vi/dQw4w9WgXcQ/hqdefault.jpg', og_description: 'Uploaded by somebody.', + })), + ]; + chats.push({ + id, chat_type: 'DirectMessage', participants: [id], messages, last_read: messages[messages.length - 1].id, + unread_from: '', created_at: Math.floor((at - 86400_000) / 1000), metadata: { custom_fields: {} }, + muted: false, notify: 2, everyone_pings: true, community_muted: false, + }); +} +writeFileSync(new URL('./fixtures.json', import.meta.url), JSON.stringify({ now: NOW, npub: me, profiles, chats, thumbs }, null, 1)); +console.log(`${chats.length} chats, ${profiles.length} profiles`); diff --git a/crates/vector-gpui/reference/media/album-cover.png b/crates/vector-gpui/reference/media/album-cover.png new file mode 100644 index 000000000..decaf699a Binary files /dev/null and b/crates/vector-gpui/reference/media/album-cover.png differ diff --git a/crates/vector-gpui/reference/media/apps/cards.png b/crates/vector-gpui/reference/media/apps/cards.png new file mode 100644 index 000000000..2a90c62da Binary files /dev/null and b/crates/vector-gpui/reference/media/apps/cards.png differ diff --git a/crates/vector-gpui/reference/media/apps/chess.png b/crates/vector-gpui/reference/media/apps/chess.png new file mode 100644 index 000000000..a09882e87 Binary files /dev/null and b/crates/vector-gpui/reference/media/apps/chess.png differ diff --git a/crates/vector-gpui/reference/media/apps/draw.png b/crates/vector-gpui/reference/media/apps/draw.png new file mode 100644 index 000000000..68f29bf3a Binary files /dev/null and b/crates/vector-gpui/reference/media/apps/draw.png differ diff --git a/crates/vector-gpui/reference/media/apps/mines.png b/crates/vector-gpui/reference/media/apps/mines.png new file mode 100644 index 000000000..4825e63e3 Binary files /dev/null and b/crates/vector-gpui/reference/media/apps/mines.png differ diff --git a/crates/vector-gpui/reference/media/apps/notes.png b/crates/vector-gpui/reference/media/apps/notes.png new file mode 100644 index 000000000..a2c8a8cc0 Binary files /dev/null and b/crates/vector-gpui/reference/media/apps/notes.png differ diff --git a/crates/vector-gpui/reference/media/apps/poll.png b/crates/vector-gpui/reference/media/apps/poll.png new file mode 100644 index 000000000..2361a3d6e Binary files /dev/null and b/crates/vector-gpui/reference/media/apps/poll.png differ diff --git a/crates/vector-gpui/reference/media/apps/racer.png b/crates/vector-gpui/reference/media/apps/racer.png new file mode 100644 index 000000000..77968cf41 Binary files /dev/null and b/crates/vector-gpui/reference/media/apps/racer.png differ diff --git a/crates/vector-gpui/reference/media/apps/snek.png b/crates/vector-gpui/reference/media/apps/snek.png new file mode 100644 index 000000000..101c61164 Binary files /dev/null and b/crates/vector-gpui/reference/media/apps/snek.png differ diff --git a/crates/vector-gpui/reference/media/apps/tetra.png b/crates/vector-gpui/reference/media/apps/tetra.png new file mode 100644 index 000000000..e5e32f753 Binary files /dev/null and b/crates/vector-gpui/reference/media/apps/tetra.png differ diff --git a/crates/vector-gpui/reference/media/clip.mkv b/crates/vector-gpui/reference/media/clip.mkv new file mode 100644 index 000000000..d0425a675 Binary files /dev/null and b/crates/vector-gpui/reference/media/clip.mkv differ diff --git a/crates/vector-gpui/reference/media/clip.mp4 b/crates/vector-gpui/reference/media/clip.mp4 new file mode 100644 index 000000000..373873767 Binary files /dev/null and b/crates/vector-gpui/reference/media/clip.mp4 differ diff --git a/crates/vector-gpui/reference/media/cover.png b/crates/vector-gpui/reference/media/cover.png new file mode 100644 index 000000000..5e9df6ba9 Binary files /dev/null and b/crates/vector-gpui/reference/media/cover.png differ diff --git a/crates/vector-gpui/reference/media/devs-banner.png b/crates/vector-gpui/reference/media/devs-banner.png new file mode 100644 index 000000000..a01695f07 Binary files /dev/null and b/crates/vector-gpui/reference/media/devs-banner.png differ diff --git a/crates/vector-gpui/reference/media/devs-icon.png b/crates/vector-gpui/reference/media/devs-icon.png new file mode 100644 index 000000000..ad1702280 Binary files /dev/null and b/crates/vector-gpui/reference/media/devs-icon.png differ diff --git a/crates/vector-gpui/reference/media/emoji-grin.png b/crates/vector-gpui/reference/media/emoji-grin.png new file mode 100644 index 000000000..706860c36 Binary files /dev/null and b/crates/vector-gpui/reference/media/emoji-grin.png differ diff --git a/crates/vector-gpui/reference/media/fox.glb b/crates/vector-gpui/reference/media/fox.glb new file mode 100644 index 000000000..1ef5c0d05 Binary files /dev/null and b/crates/vector-gpui/reference/media/fox.glb differ diff --git a/crates/vector-gpui/reference/media/fox.glb.txt b/crates/vector-gpui/reference/media/fox.glb.txt new file mode 100644 index 000000000..ee23d5f42 --- /dev/null +++ b/crates/vector-gpui/reference/media/fox.glb.txt @@ -0,0 +1 @@ +Fox.glb from the Khronos glTF Sample Assets: model by PixelMannen (CC0), rigging and animation by @tomkranis (CC-BY 4.0). diff --git a/crates/vector-gpui/reference/media/golden-hour.mp3 b/crates/vector-gpui/reference/media/golden-hour.mp3 new file mode 100644 index 000000000..ae917a9ef Binary files /dev/null and b/crates/vector-gpui/reference/media/golden-hour.mp3 differ diff --git a/crates/vector-gpui/reference/media/grid.heic b/crates/vector-gpui/reference/media/grid.heic new file mode 100644 index 000000000..fe6f58b16 Binary files /dev/null and b/crates/vector-gpui/reference/media/grid.heic differ diff --git a/crates/vector-gpui/reference/media/loop.wav b/crates/vector-gpui/reference/media/loop.wav new file mode 100644 index 000000000..b14bfd4d9 Binary files /dev/null and b/crates/vector-gpui/reference/media/loop.wav differ diff --git a/crates/vector-gpui/reference/media/northern-lines.mp3 b/crates/vector-gpui/reference/media/northern-lines.mp3 new file mode 100644 index 000000000..f84548918 Binary files /dev/null and b/crates/vector-gpui/reference/media/northern-lines.mp3 differ diff --git a/crates/vector-gpui/reference/media/pack/e0.png b/crates/vector-gpui/reference/media/pack/e0.png new file mode 100644 index 000000000..0e7b4c981 Binary files /dev/null and b/crates/vector-gpui/reference/media/pack/e0.png differ diff --git a/crates/vector-gpui/reference/media/pack/e1.png b/crates/vector-gpui/reference/media/pack/e1.png new file mode 100644 index 000000000..f5474ead1 Binary files /dev/null and b/crates/vector-gpui/reference/media/pack/e1.png differ diff --git a/crates/vector-gpui/reference/media/pack/e10.png b/crates/vector-gpui/reference/media/pack/e10.png new file mode 100644 index 000000000..1b2768cb1 Binary files /dev/null and b/crates/vector-gpui/reference/media/pack/e10.png differ diff --git a/crates/vector-gpui/reference/media/pack/e11.png b/crates/vector-gpui/reference/media/pack/e11.png new file mode 100644 index 000000000..4e9ff97fa Binary files /dev/null and b/crates/vector-gpui/reference/media/pack/e11.png differ diff --git a/crates/vector-gpui/reference/media/pack/e12.png b/crates/vector-gpui/reference/media/pack/e12.png new file mode 100644 index 000000000..923e0da73 Binary files /dev/null and b/crates/vector-gpui/reference/media/pack/e12.png differ diff --git a/crates/vector-gpui/reference/media/pack/e13.png b/crates/vector-gpui/reference/media/pack/e13.png new file mode 100644 index 000000000..6ba38ea1c Binary files /dev/null and b/crates/vector-gpui/reference/media/pack/e13.png differ diff --git a/crates/vector-gpui/reference/media/pack/e14.png b/crates/vector-gpui/reference/media/pack/e14.png new file mode 100644 index 000000000..3012ed144 Binary files /dev/null and b/crates/vector-gpui/reference/media/pack/e14.png differ diff --git a/crates/vector-gpui/reference/media/pack/e15.png b/crates/vector-gpui/reference/media/pack/e15.png new file mode 100644 index 000000000..18e079cbc Binary files /dev/null and b/crates/vector-gpui/reference/media/pack/e15.png differ diff --git a/crates/vector-gpui/reference/media/pack/e2.png b/crates/vector-gpui/reference/media/pack/e2.png new file mode 100644 index 000000000..2eb5162c3 Binary files /dev/null and b/crates/vector-gpui/reference/media/pack/e2.png differ diff --git a/crates/vector-gpui/reference/media/pack/e3.png b/crates/vector-gpui/reference/media/pack/e3.png new file mode 100644 index 000000000..b6b4e5b98 Binary files /dev/null and b/crates/vector-gpui/reference/media/pack/e3.png differ diff --git a/crates/vector-gpui/reference/media/pack/e4.png b/crates/vector-gpui/reference/media/pack/e4.png new file mode 100644 index 000000000..4302dff06 Binary files /dev/null and b/crates/vector-gpui/reference/media/pack/e4.png differ diff --git a/crates/vector-gpui/reference/media/pack/e5.png b/crates/vector-gpui/reference/media/pack/e5.png new file mode 100644 index 000000000..12750a4f7 Binary files /dev/null and b/crates/vector-gpui/reference/media/pack/e5.png differ diff --git a/crates/vector-gpui/reference/media/pack/e6.png b/crates/vector-gpui/reference/media/pack/e6.png new file mode 100644 index 000000000..e41d4818d Binary files /dev/null and b/crates/vector-gpui/reference/media/pack/e6.png differ diff --git a/crates/vector-gpui/reference/media/pack/e7.png b/crates/vector-gpui/reference/media/pack/e7.png new file mode 100644 index 000000000..23216079b Binary files /dev/null and b/crates/vector-gpui/reference/media/pack/e7.png differ diff --git a/crates/vector-gpui/reference/media/pack/e8.png b/crates/vector-gpui/reference/media/pack/e8.png new file mode 100644 index 000000000..bf5c841b7 Binary files /dev/null and b/crates/vector-gpui/reference/media/pack/e8.png differ diff --git a/crates/vector-gpui/reference/media/pack/e9.png b/crates/vector-gpui/reference/media/pack/e9.png new file mode 100644 index 000000000..652b52978 Binary files /dev/null and b/crates/vector-gpui/reference/media/pack/e9.png differ diff --git a/crates/vector-gpui/reference/media/pack/icon.png b/crates/vector-gpui/reference/media/pack/icon.png new file mode 100644 index 000000000..b6b4e5b98 Binary files /dev/null and b/crates/vector-gpui/reference/media/pack/icon.png differ diff --git a/crates/vector-gpui/reference/media/photo.heic b/crates/vector-gpui/reference/media/photo.heic new file mode 100644 index 000000000..9a4795c64 Binary files /dev/null and b/crates/vector-gpui/reference/media/photo.heic differ diff --git a/crates/vector-gpui/reference/media/photo.png b/crates/vector-gpui/reference/media/photo.png new file mode 100644 index 000000000..de450ded1 Binary files /dev/null and b/crates/vector-gpui/reference/media/photo.png differ diff --git a/crates/vector-gpui/reference/media/portrait.png b/crates/vector-gpui/reference/media/portrait.png new file mode 100644 index 000000000..930aca35b Binary files /dev/null and b/crates/vector-gpui/reference/media/portrait.png differ diff --git a/crates/vector-gpui/reference/media/sequence.heics b/crates/vector-gpui/reference/media/sequence.heics new file mode 100644 index 000000000..5d1f1f30a Binary files /dev/null and b/crates/vector-gpui/reference/media/sequence.heics differ diff --git a/crates/vector-gpui/reference/media/sticker.png b/crates/vector-gpui/reference/media/sticker.png new file mode 100644 index 000000000..39d8b1556 Binary files /dev/null and b/crates/vector-gpui/reference/media/sticker.png differ diff --git a/crates/vector-gpui/reference/media/thumbs.tsv b/crates/vector-gpui/reference/media/thumbs.tsv new file mode 100644 index 000000000..b3cf6043d --- /dev/null +++ b/crates/vector-gpui/reference/media/thumbs.tsv @@ -0,0 +1,3 @@ +photo.png 1600 1000 U(^ /twg4<&F@NQS~xhD@CSA data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAASCAYAAAA6yNxSAAAE+ElEQVR4Ae3AA6AkWZbG8f937o3IzKdyS2Oubdu2bdu2bdu2bWmMnpZKr54yMyLu+Xa3anqmhztr1a8+8jFf6FIKtVZq7ShRkES2ZJompnEkpwmRdDXYWHRsb804fmzBsZ05x3Z6tjeDzQ1YzJPFbGIxb2zMGxuLxmKRLObJrG90ZSJiBAbsCZzU+SwpIWpNak0ihICMpNAIT6QmIOlr0FXR10pXJ/ra6OtE3xX6Cn1N+i7pa6Orja4mfU260uhKo9ZGaAIa9gRO6vHtRgTUAqVARIKhtcY0jozDSJtGIOlqsDFPNuZicx5szgubc9icJxtz2Jgn83ljMZtYzBsb82QxS+azRt9P1DIRGrAH8Iid1GtOTESYUkyECTVsM42NYRgYh4FpmsBJV8Ri0djZhJ1NsbMpdjbN9mZhc0MsZsli3pjPJhbzxmKeLOaNWd/ou4kSI9KAvcY5Yif1+jONkIliQkaI1pJxnBjWa4b1wDiO4KQWsVg0drbMsS1xfFsc2zbbm5WNDbGYJ/NZYz5rLGaN+byxmDVmfaPWkRIDeMBekznibNSbrjFSEgHC2DBNyTCMrFcD69WacRiwk1KCxdxsb4lj24Xj24VjW2JrK9lciPnczPvGfDYxmzXms8Z81qjdBGUEDeAV5BraCG7UG86AAAnAZMI4NtbridVyYtWPDMNEZqNGMJ+L7a3KztbE8c2Jnc3C1obYWIj5LJnNGrO+MesnZrOG+gZ1gjICA+QAbQAGcKNec6ICQhI2tGbGQayWcFTMssCwNtmgBMznsLWA7QVsLWBzDptzs5jBrIe+g1ln+goqhmIoCUogQQk0oIEn6vGtnitEJrQpWReoNMKVyImOSmuNEoVZX5n3lXlXmdVKXytdVGpAkSkYuSAbXKAZFKAAAlrAFNAEGdRZnXOFyISJxG2kBXRhuoCMQDZFQVVPYUF4gTyHnJGt0CZoJCMFPEEGfTboAqYACWxoCVPiZrI1qtsCECCcJqckp45shZwK2So59WRLiEKbZrRpwThuMKwX1NIjCtnMWJNaJmqd6Gqj6ya62ihlIlSxC60VpqnQpkpmoy6PNgBhi0yYpmS9nlguO5bLjtWyZ72eaM2ECtlmwAJpAzEns2cYgq6aUhqlTJQyUctE1zW62ii1ERqwZ2Trmaae1gYyG/XixQUgQGSKaTLD0FiuBpZHM5bLgWFotAYRla6bMU4LprZgHOcs1x19J0oxEROhiVImam3U2ui6pJaJiAk80HJNm9a0NpA5Uc+eWwAChFNMDcahsVr3LJcjq9XEMCSZQlHpuxmr9YLVsGC5mtP3lVpFiUSaUIxETNTS6Lqk65JakxITMJK5prWB1gYyG/Xe+2YIgQJbtAbjaNbrxmo1sVo3xjHJDCI6+n7GbLXBYj1nNp/Rd5VSQEqkCRiJmKi10VXT9UlXTSkNaSRzINtAy5HMRj13rgMJCCDIFOMIw9BYrRvDOhknk1mI0tF3c2bzBathwWzV03WVCJAaMAIjoYlSk64zfW+6ztSSSBP2SMuBbCPpRt29VEBCKkCQGUwTDENhPSTDkEwTpAsleoZ+ztgWTG3BMPV0taAAaOACFBQTtSRdZ/oe+t6UkkQ07JHMjswRZ1KXKyEFUmACZzA1GEexXothCKYJTCGiYipSh6JiKq0VIgCEbcBIUGvS0qQhDbUmEYEtMiFT2Mk/Ah7D65d0eLWCAAAAAElFTkSuQmCC +portrait.png 700 1000 6%fXoBL7P(`cp*l1#)iQt/q;6h data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABcAAAAgCAYAAAD5VeO1AAAGzUlEQVR4Ae3AA6AkWZbG8f937o3IzKdyS2Oubdu2bdu2bdu2bWmMnpZKr54yMyLu+Xa3anqmhztr1a8+7I3eyDs7O1x3w/XcePPNXHfj9Rw7fgx1laP1kouXdrmwe5GDo0MSs7m5wanTp7n22ms5dfIk89mM9WrFfffcy9Of/jSe8uSncNutz+DixQvU1WpFP5uxWq1YrVasliv6+YxoldV6xWq1YrVes16vMaZ2lWEYGIeBcRwoEYzjyDiNTOPENE5M08Q4TdS9/X2QWGxusr23x2JrE4qIrnK0XrG/v8/+/j6HyyMQEOLo6Iij5RGL5QKnGVZrVqsVq/WK9XrFer1mvV5T93cv0TKZLeZsbm/SL+Y0kugqy2HF7t4lLu1d4mi1hBCJmc/nHBxsMZ/PyZaM6zXL5ZLlcslytWK1WjGtVlT29jgCdjc22Ni5RL+xoMlEV1kOKy7t77G7v8dytSRKgGBjY4PDo0M2jhaQZhgGlssVq9Wa9XrNeljDeqCyWkHXcbhccnh4xMHBIaqFqIXlsGb/4ICDgwNW6xVRC6VWlsslq9WK1WpNKJiGgWEcGMeRaRqZpgnaRCUTMplaY5gm1uNItx5QC5brFcvVitVqzWpYU1phGAeGcWQYR8ZpZGodLRuZiW1sAECi0vXQdUQpSIGBtHFLptaYpsbYJqbWIERrSWaSaWyDAYQkIoJSCrVWWq0Emxuw2GA2X9D1PaVWFAESCaSNbdKQNsaY+wmFiAhqKXRdpe97ZrMZzGdUtrYpm5vMNzbo5wtq1xO1YicgDCRgjAHzTBIKERGoQO06+r5nPp+xWMwZhgW1bm2z2FgwX2zQz2fUriei0NIYSEOmSRvb2GCuEEIKooquq8xmM+bzOYvFgnEcqYuNDeaLBbP5nNr1RClYIg0tkykbrTVaSyKSlklmYhuACBEKuq5jNpuxsViwublJtkbt53O6fkbpOqIULJGGqTXGqTFNE+PUaNOEQmRrZCa2QRARdFGY9T2L+ZzNzQ22t7aQTe36GbXvKKWiKBiRaaaWTK0xTo2pNWhJZpI2AJKICGqp9F0H2djc3GR7e5thvaaWQu36nq7rKbVDUUDCGNtkGtvYBkASEUGJQi2FvuuYzXoWsxl9KeQ0MQ1ryGQxm1NnswVd39H1M2rXUUoFJ4pCRBBRKLXSMF3X0Xc9/axnNpuxmM/Z3Nhgc7HAU6NKyKaLwnLziLrY2KDrOmaLObPZjNIVWjbGnOj6nr6fMZsGshbm8zmLxZyNxYLNjQ02NzbY2txke3MT2cy6So1g3nWslkvqxuYWXVeZzWf08xlRgpaNRjKMC9bDmnQjs7FYzNjc2GRzY4PNjQ02NzbY2txke2uLAsxrpZOY1cJqtaJubG7S1Uo/6+lnPVGDKSeSZBgHNsYBk2ROLOYzFos589mc2WzGrJ8x63vmfU+VKACtoTR9rdRZP6N2lb7v6fqOKIEy6KaJvu/pu56p62kZdF1HLZUSQQDYOBNnYgnZyCYERUEFAQIABADmMiHEM9m4JW2aGNcDq+WS5eEhh/tzSiY1gmm9Znl0xPLwkGEYqOv1mqlNZCYtk6hBaxPr9Zr1as16vWa9WjNNA20a6WtwaT5ja2POoutQm1hubFCBaRhYHh6yPDpiHAbq7u4lai30s56u74gSNE+sVkv2D/bY39/n8HCfYVxTi2jDGmVSnHgYWO7vsTmfEzbTes3y6Ijl0RHjMFDPnj1LrYV+1tP3PaUGzY31esX+4R77+5c4PNyH9RIER4sZ4/KIcXXEan+fS9vbLPoeORlXK5ZHRyyPjhiHgXrvPfdSa2U27+lnPbUrpJP1uOLw8IDh4BIc7MF6CU7GWce9R4esjw5Z7u2xu7nJrBbIZFwuWR4dsTw6YhwG6njffYxdZTmbEfMZXV9BZpgGfHQAh3twsA/rJeQEXYX1it31inF5xOF8Tl8KbhPDcsny8JDV8ohxGKlcvAhdB/MZuZiznnVQBG2E1RKWK1ivYbWCnGAqQILgMJNcr6khPE4MqyXD4SEcHcE4UDk8gr4DJwjAUAPcIJNnkUACAAOZ0BptmpDA08Q0jjCOME0wQqU1mAJaQiYAhIACXQethzYHATlBFcx6mM2os55Z31MFKcE0sep73BpooIJAgggoBWqFroMAaoCAEPQF3KAEzHrqxpyt+ZxF31EFOU6MpdBFsCqFaRyplAKlQClQO+g6at8TRWQWpiKogrGCG9Sgznq2FnO2FnMWfUcVeJwYaqGLoK+VcRyplIBSoBQoBUql1kqpQVogM5EQgJOowXzWM5/PmM9mzPuOKnApBEaZCFNK8I958c/ms+Jt8gAAAABJRU5ErkJggg== +sticker.png 220 220 HUN*`C9p<)MJbF6vQY^LC_$qYVyrBA data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAHJUlEQVR4Ae3AA6AkWZbG8f937o3IzKdyS2Oubdu2bdu2bdu2bWmMnpZKr54yMyLu+Xa3anqmhztr1a8e/ejP2YAFCChCpRB9pfSVOuvRrIfZDGY9zHroZ9DPoOuhdKACDVhPcLCCSwdwcZ/lxX2OLh0xHq3xaDpV5t2MRb+gzGZQOioIAWCMwOIyAwjMsxkwYIMNNtiAwYANBgwYsBAAQjyTucICoApxmQEJELKQgQQMJJCGNDRDM7SESMAgQwOaIQ0JGDBgwIC5woABGxIqybPZ2ICMG7iZbKZMCZGgBmqgBjRwgzKBDCmYEqaEltCMm3EDpyGNActkM6UZSGobEzAGLCAECelGQRhhi2IhAwkk0IAJqAZVSGBIWI8wNHJotKnRpkaOiUcjNRpJi0aloSLquBwwYMACAqiBpkJMSWlJNFOmpIxJ6ZIYEroGXYMyQVTIgDFhOcByYFiNjKuRcT0xricYjTFRg8iCmuhKUo8OVoAxYAEhqIFqIbpK9JXSTURXiW6kdJVSO2rX0dUR1Q6iAwtGw2pkOFyxOlqxOhpYHw2MywFGUwgohhHcmak26sHuIQiMsQRFqATqCtFVoqtEX4muErUQtVJqpXYdtfZ0taNEJVxgMtN6Yn24Yrm/YnmwYnW4YloOeDTFQStJdqZ1SS2Vur97AIAFhCCEaqCuUrpK9JXoKtEVVCtRC1ErpVRq7ehqT41KUKDBtJ4Yjtas9pcsD5asD1aMywGPpjiYSqPVZOwatRTqwaUjACwghEqgGkRXib5S+o7oKuoKUQsqhSiFqJVaOmodqVEJCmrQhsZwNLA+XLE8WLE+WDEtRzyZ4mCKRqtmqo1SCvVof8VlIQihGkStRG/KBGWC6I3GRDVRNFQKURqlNEpp1KgUCiTkkIzLgfXhwOpoYH00Mq1GPCbFQYskK7SalCjUYdlAQAhFoCpKnwQGGQQGZCANYYiGAkpACZgiCQpKkUNjXI0My5H1amJYT0yrhqekpHEI1wkXUYqpOQkkCKESRATOirJCVnAFV8gABbZwCgQp0yIpEgHQRI7JtE6GIRkHMw6mjcaTyTSEURpVk81UqQeBFEhBUaWoUqKnlI4SHVEqisASKbDBBiOcwoAAmsnRTKOZRpgmaE1MTdCEU4TFhJCEDbWUOZJQCNVCqYVSO2rtqbWj1A7VCiWwABuTpI0NJKQFBprJ0UwTjBNMk5iaaCloAQQtg6IgMxBBrXUBEgoRtVBqpdSO2nXU2lO6ikrBJWgYOXFr2I2WxmmcQBqaydFMo5kmGBtMTWQLsMGBImguhANcqFHmIFAEUQKVSpSOKB0qPYoKUUAAJt1ohrGZ1hqtgTNxA5rJMZmGZBqTaTTTBNlATSSBCKYIlIEJqum4IkgCUUkqzR1yBVdwkIbJydCSYYJhNOOUtCnJlrgZN5OjacNEWzemIWlj4gkioQIgSKEI0kEdM0AghFrQQpQmSoM2QYQB0wRTJuupsR4b63FiHEemsdFa4mY8GU+mDY0cGm2YyDFhMpGiCgwgsKAAdTUaBAhUGjIUi0IQFpHGNUiZMRvraWQ1DKyHgWEcmcaJ1hJPxs14MjkmOSYeGh4TJigUOhkDDnCKgqiH64nLAohAUxJTEi2JKYmu4CpSZszGehpZDQPrYWA9DExTo02J09CMJ/BkPCYeEyYTKSqihbGMAzKgAnV/OYKMJQhQCdQVYmzE2FBXoIomM2VjPU2sxoH1MDCMI9M00aaEBBJowGQ8GSajBpGiKmgYEkhwwgTU/dUAgGUsQRGqQfQVjYXoC5SgBUxuDNPEehxYjyPDODJNjcyEBFIogQaagGbURLGoGAtIIMEJRVAP1iPGGLCMQ6gGmiaiq2gqUIMMaE6GnBimkWGcGKfG1BpuBoNSyIIGSiAh0oRNJ3ACCdhkmoKph8OEbYxJGQuogaaCWiNaga7gIhrJlI2hNcapMbYkm3EaLGRQggwYlCBDJKTAMmTiZpqSiqjLsWFM2iRJCmiCTMJJ2MiJS5AyE8nUzJgwGdLCgBBCCAEgAxgSIk1T0khSSVOjJygJdd2StEknDZMyTiGbwEgQFLDJEImZDBPQECkwQgghJAHGGCeQRmmKYZJoKaYUQ5oShTqkSZu0mZwkxgFgIiBCRAgCjEhBMzREI7CMASFACDBgm8zEzdBMZDLKjM0MzdSpUSKoY0LaNJuWSZOxAYGaKC2JTJQCiQQS0RApSMSzmMts09JkJtkaHo0aBI2qRlcaNSoRQW02aZjSNJvmJAUkKEWmiTSRhjCWSKBJpME8J2PSpmUytaRNjRwbNBMWhUKNRo2JUFCbIW3S0AzNkGGwURqcOI0NGDCkwAgLjDGAwYBtMs2UydSSqTVaazAmSigkUyQlCiFRDRhITNokJg3YyEYGYdJGXGGEMQaMMAbAgA0JpE1z0jJpreE0SjDgNA4TCv4RtiqpFjEcUFEAAAAASUVORK5CYII= diff --git a/crates/vector-gpui/reference/media/turned.mov b/crates/vector-gpui/reference/media/turned.mov new file mode 100644 index 000000000..1b34ada90 Binary files /dev/null and b/crates/vector-gpui/reference/media/turned.mov differ diff --git a/crates/vector-gpui/reference/media/voice.wav b/crates/vector-gpui/reference/media/voice.wav new file mode 100644 index 000000000..12c906ed3 Binary files /dev/null and b/crates/vector-gpui/reference/media/voice.wav differ diff --git a/crates/vector-gpui/reference/mock-tauri.js b/crates/vector-gpui/reference/mock-tauri.js new file mode 100644 index 000000000..c181b363d --- /dev/null +++ b/crates/vector-gpui/reference/mock-tauri.js @@ -0,0 +1,169 @@ +// A stand-in backend for the Tauri frontend: boots it through the debug hot-reload path with +// the fixture data, so the reference render needs no Rust, no account and no network. +(() => { + const FIX = window.__VECTOR_FIXTURES__; + const answers = { + get_platform_features: { transcription: !!window.__REF_TRANSCRIPT__, notification_sounds: true, os: 'linux', is_mobile: false, debug_mode: true, media_url: null, self_update: false, share_audio: false, players: false }, + debug_hot_reload_sync: { success: true, npub: FIX.npub, profiles: FIX.profiles, chats: FIX.chats, pinned: FIX.pinned || [] }, + get_storage_info: { total_bytes: 41300000, type_distribution: { jpg: 9200000, png: 3100000, mp4: 21000000, mp3: 1400000, '/cache': 4100000, pdf: 2500000 } }, get_theme: 'vector', get_notification_settings: { global_mute: false, sound: { type: 'Default' }, mute_everyone: false }, get_encryption_status: { enabled: true, security_type: 'pin' }, audio_devices_list: { inputs: ['Built-in Microphone', 'USB Headset'], outputs: ['Built-in Speakers', 'USB Headset'], default_input: 'Built-in Microphone', default_output: 'Built-in Speakers', prefs: { input: null, output: null } }, call_audio_settings_get: { auto_gain: true, echo_cancel: true, noise_suppress: false, mic_volume: 0.8, speaker_volume: 1 }, realtime_direct_get: false, get_start_layout: { v: 1, nodes: [{ type: 'item', key: 'dm/npub190vqdjtlpcq27xslcveglfmr4ynfwg7gmw86cnun4acakxrdd6gqnp929a' }, { type: 'item', key: 'settings/audio' }, { type: 'item', key: 'requests' }, { type: 'folder', id: 'f1', name: 'Work', keys: ['dm/npub1sxmr0k8u6trd5c6eu6trzyapzux7090ykujmsng7pdx0m8k93n5sd02fwn', 'dm/npub1fsndjp6vylvfahjeyuxq4s2tw8s8rv2j89ge7a28fvhnhf35s86sg3uctf'] }] }, export_keys: { nsec: 'nsec1vl029mgpspedva04g90vltkh6fvh240zqtv9k0t9af8935ke9laqsnlfe5', seed_phrase: 'abandon ability able about above absent absorb abstract absurd abuse access accident' }, verify_credential: null, transfer_start: { id: 1, code: '7-orbit-lemon-stage', qr: 'Vector transfer code: 7-orbit-lemon-stage' }, get_archived_chats: FIX.archived || {}, list_emoji_packs: [], get_relays: [{ url: 'wss://jskitty.com/nostr', status: 'connected', is_default: true, is_custom: false, enabled: true, mode: 'both' }, { url: 'wss://asia.vectorapp.io/nostr', status: 'connected', is_default: true, is_custom: false, enabled: true, mode: 'both' }, { url: 'wss://nostr.computingcache.com', status: 'connecting', is_default: true, is_custom: false, enabled: true, mode: 'both' }, { url: 'wss://relay.ditto.pub', status: 'disabled', is_default: true, is_custom: false, enabled: false, mode: 'both' }, { url: 'wss://relay.example.org', status: 'disconnected', is_default: false, is_custom: true, enabled: true, mode: 'read' }], get_blossom_servers_config: [{ url: 'https://magnitude.vectorapp.io', is_default: true, is_custom: false, enabled: true, status: { state: 'online', label: 'Online', tone: 'connected', latency_ms: 84 } }, { url: 'https://blossom.ditto.pub', is_default: true, is_custom: false, enabled: true, status: { state: 'untested', label: 'Untested', tone: 'disabled', latency_ms: null } }, { url: 'https://blossom.primal.net', is_default: true, is_custom: false, enabled: false, status: { state: 'disabled', label: 'Disabled', tone: 'disabled', latency_ms: null } }], get_accounts: [{ npub: FIX.npub }], get_current_account: FIX.npub, + }; + const msgs = (id) => (FIX.chats.find((c) => c.id === id)?.messages || []).slice().sort((a, b) => a.at - b.at); + const fns = { + audio_load: ({ path }) => ({ id: 7, duration_ms: String(path).includes("golden") ? 9000 : 7400, waveform_fps: 20, bins: 32 }), + audio_play: () => 2400, + audio_pause: () => 2400, + audio_probe: ({ path }) => (String(path).includes("loop") ? 12000 : String(path).includes("golden") ? 9000 : String(path).includes("northern") ? 32000 : 7400), + get_audio_metadata: ({ path }) => String(path).includes("northern") + ? { title: "Northern Lines (Deluxe Edition)", artist: "Mira Vale", album: "Northern Lines (Deluxe Edition)", cover_art: "/__ref/media/album-cover.png", lyrics: null, year: 2024, + chapters: [[0, 6000, "Arrival"], [6000, 13000, "Glass Harbour"], [13000, 19000, "Signal Fire (Live)"], [19000, 25000, "Cold Front"], [25000, null, "Departure - Remastered 2024"]] + .map(([start_ms, end_ms, title]) => ({ start_ms, end_ms, title })) } + : (String(path).includes("golden") + ? { title: "Golden Hour", artist: "Mira Vale", album: "Coastlines", cover_art: "/__ref/media/cover.png", lyrics: { synced: true, lines: [ + [500, "Light on the water"], [2200, "Gold in your hair"], [4000, ""], [5200, "We drove till the coastline"], [7000, "Ran out of air"], + ].map(([at_ms, text]) => ({ at_ms, text, words: [] })) }, year: null, chapters: [] } + : null), + list_models: () => [ + ['tiny', 'Lowest Quality - Fastest', 44, 310, false], ['base', 'Base Quality - Fast', 82, 360, false], + ['small', 'Good Quality - Fast', 264, 620, true], ['medium', 'High Quality - Moderate', 823, 1320, true], + ['large-v3', 'Highest Quality - Slowest', 1080, 2400, true], + ].map(([name, display_name, size, ram_required, supports_translate]) => ({ model: { name, display_name, size, ram_required, supports_translate }, downloaded: name === 'small' && window.__TYPE__ !== 'missing' })), + get_device_memory: () => 2 * 1024 * 1024 * 1024, + reauthorize_bunker: () => 'nostrconnect://4f3c1b7a9e2d8f6c5b4a3e2d1c0b9a8f7e6d5c4b3a2918f7e6d5c4b3a291807?relay=wss%3A%2F%2Fjskitty.com%2Fnostr&secret=8c1e4a&name=Vector', + get_pending_reauth_result: null, + start_nostrconnect_session: () => 'nostrconnect://4f3c1b7a9e2d8f6c5b4a3e2d1c0b9a8f7e6d5c4b3a2918f7e6d5c4b3a291807?relay=wss%3A%2F%2Fjskitty.com%2Fnostr&secret=8c1e4a&name=Vector', + check_account_downgrade: () => (window.__TYPE__ === 'downgrade' ? { db_schema: 90, supported_schema: 87, last_app_version: '0.6.0-2' } : null), + get_bunker_status: () => (window.__SIGNER__ ? { remote_npub: window.__SIGNER__, remote_pubkey_hex: '' } : null), + get_sql_setting: (a) => ((window.__SQL__ || {})[a?.key] ?? null), + transcribe: () => ({ lang: 'ru', language: 'ru', confidence: 0.9, sections: [ + [0, 'Привет, это Ана.'], [1800, 'Я буду дома около семи,'], [4200, 'купи, пожалуйста, хлеб по дороге.'], + ].map(([at, text]) => ({ at, text, confidence: 0.9 })) }), + get_self_destruct_timer: () => (window.__TYPE__ === 'timer' ? 3600 : null), + get_synced_settings: () => ({ advanced: (window.__SQL__ || {}).advanced === 'true', players: true, streamer: { on: window.__TYPE__ === 'streamer', seed: '00112233445566778899aabbccddeeff', notif: 'none', hide_wallpapers: true } }), + get_chat_message_count: ({ chatId }) => msgs(chatId).length, + get_message_views: ({ chatId, limit = 50, offset = 0 }) => msgs(chatId).reverse().slice(offset, offset + limit), + get_messages_around: ({ chatId, anchorId, before = 0, after = 0 }) => { + const all = msgs(chatId); const i = all.findIndex((m) => m.id === anchorId); + return i < 0 ? all.slice(-before) : all.slice(Math.max(0, i - before + 1), i + after + 1); + }, + get_message_position: ({ chatId, messageId }) => { + const all = msgs(chatId); const i = all.findIndex((m) => m.id === messageId); + return i < 0 ? null : { newer: all.length - 1 - i, total: all.length }; + }, + get_message_time_at: ({ chatId, newer }) => msgs(chatId).reverse()[newer]?.at ?? null, + get_unread_counts: () => Object.fromEntries(FIX.chats.map((c) => { + const i = c.messages.findIndex((m) => m.id === c.last_read); + return [c.id, c.messages.slice(i + 1).filter((m) => !m.mine).length]; + })), + mark_as_read: ({ chatId, messageId }) => { const c = FIX.chats.find((x) => x.id === chatId); if (c && messageId) c.last_read = messageId; return null; }, + create_account: () => ({ public: FIX.npub, existing: false }), login: () => { throw 'Invalid nsec'; }, + generate_thumbhash_preview: ({ npub, msgId }) => { + const m = msgs(npub).find((x) => x.id === msgId); + const hash = m?.attachments?.find((a) => a.img_meta)?.img_meta?.thumbhash; + if (!hash || !FIX.thumbs?.[hash]) throw 'No thumbhash'; + return FIX.thumbs[hash]; + }, + voice_present: ({ channelId }) => FIX.voice?.present?.[channelId] || [], voice_state: () => FIX.voice?.session || null, voice_powers: () => ({ mute: true, deafen: true, move: true }), + get_system_events: () => [], pivx_get_chat_payments: () => [], get_message_delete_meta_bulk: () => [], + get_chat_commands: ({ chatId }) => { const b = (FIX.bot_commands || {})[chatId] || []; return { bots: b.length, commands: b, fresh: true }; }, list_communities: () => FIX.communities || [], get_community: ({ communityId }) => (FIX.communities || []).find((c) => c.community_id === communityId), get_hidden_banners: () => [], cache_community_image: ({ communityId, isBanner }) => { const c = (FIX.communities || []).find((x) => x.community_id === communityId); return (isBanner ? c?.banner : c?.icon) || null; }, + get_community_capabilities: () => Object.fromEntries(['manage_metadata','manage_channels','create_invite','kick','ban','manage_messages','manage_roles','manage_admin_role','pin_messages','control_write','moderate_members','view_audit_log','manage_nicknames','change_nickname'].map((k) => [k, true])), + get_community_members: ({ communityId }) => ((FIX.communities || []).find((c) => c.community_id === communityId)?.members || []).map((npub, i) => ({ npub, last_active: 1794275880 - i * 600 })).concat(Object.entries((FIX.unlisted || {})[communityId] || {}).map(([npub, unlisted]) => ({ npub, unlisted }))), + get_channel_pins: ({ channelId }) => ({ pins: (FIX.pins || {})[channelId] || [], sealed: false, version: 1 }), sync_community_channel: () => ({ new_messages: 0, reached_start: true, oldest_ms: null }), fill_community_gap: () => 0, + get_relay_info: ({ url }) => (FIX.relay_info || {})[url] || { name: null, icon: null, auth: false }, get_community_timeouts: (a) => (FIX.timeouts || {})[a.communityId] || {}, get_community_mentions: () => ({ anyone: true, pingers: [], roles: [] }), get_community_admins: () => [], get_community_role_graph: () => ({ roles: [], grants: [], activated: false, readers: {} }), get_community_banlist: () => (FIX.profiles || []).filter((p) => p.name === 'frank' || p.name === 'heidi').map((p) => p.id), get_channel_send_denied: (a) => ((FIX.send_denied || {})[a.channelId] || []).filter((n) => (a.npubs || []).includes(n)), check_community_raid: () => ({ detected: !!FIX.moderation, suspects: FIX.moderation ? FIX.moderation.report.suspects : 0 }), + get_community_join_order: () => [], + get_moderation_intel: () => FIX.moderation, + fetch_nostr_embed: ({ reference }) => { const e = (FIX.embeds || {})[reference]; if (!e) throw 'Not found on any relay'; return e; }, cache_url_image: ({ url }) => url, list_emoji_packs: () => Object.values(FIX.packs || {}), refresh_emoji_packs: () => Object.values(FIX.packs || {}), get_theme_slot_anchor: () => '', fetch_emoji_pack_by_naddr: ({ naddr }) => { const p = (FIX.packs || {})[naddr]; if (!p) throw 'Pack not found'; return p; }, get_or_cache_image: ({ url }) => url.replace('https://ref.invalid/', ''), + policy_presets: () => FIX.policy_presets, list_community_policies: () => ({ policies: [], using_builtin: true }), + get_community_roles_view: () => FIX.roles_view, + get_channel_permissions: () => FIX.channel_perms, + get_community_audit_log: () => FIX.audit || { entries: [], compacted: false }, + debug_v2_control_report: () => FIX.sync_report.control, + debug_v2_explain_base_rekey: () => FIX.sync_report.epoch, + create_community: ({ name }) => ({ community_id: 'f'.repeat(64), channel_id: 'e'.repeat(64), channel_name: 'general', owner_npub: FIX.npub, name }), + create_public_invite: () => 'https://vectorapp.io/invite/' + 'Ab3'.repeat(20), + list_public_invites: () => [{ url: 'https://vectorapp.io/invite/' + 'Ab3'.repeat(20), token: 'tok1', label: 'Reddit', join_count: 3 }, { url: 'https://vectorapp.io/invite/' + 'Zx9'.repeat(20), token: 'tok2', label: null, join_count: 0 }], + get_community_invite_summary: () => ({ is_public: true, creators: [{ npub: FIX.npub, count: 2 }] }), + list_community_invites: () => FIX.invites || [], + preview_public_invite: () => ({ name: 'Night Owls', description: 'Late-night builders, ships and shenanigans.', icon: null, community_id: 'c'.repeat(64) }), + get_notify_prefs: ({ communityId, scopeIds }) => [...new Set([communityId, ...(scopeIds || [])].filter(Boolean))].map((scope_id) => ({ scope_id, level: null, effective_level: scope_id === communityId ? 'mentions' : 'mentions', muted: false, mute_until: 0, suppress_everyone: false, everyone_muted_globally: false })), get_emoji_usage: () => [], + cache_android_file: ({ filePath }) => { + const name = filePath.split('/').pop(); + return { size: (window.__FILE_SIZES__ || {})[name] || 0, name, extension: name.split('.').pop() }; + }, + blossom_upload_verdict: () => ({ likely: true, reasons: [] }), + get_blossom_server_snapshot: ({ url }) => { const d = FIX.server_demo?.[url] || {}; return { info: d.info || null, stats: d.stats || null, status: d.status }; }, + get_blossom_server_info: ({ url }) => FIX.server_demo?.[url]?.info || null, + get_blossom_server_stats: ({ url }) => { const d = FIX.server_demo?.[url] || {}; return { stats: d.stats || null, status: d.status }; }, + get_blossom_server_capabilities: ({ url }) => FIX.server_demo?.[url]?.caps || [], + pivx_get_wallet_balance: () => FIX.pivx?.balance ?? 0, + pivx_get_price: () => FIX.pivx?.price ? { value: FIX.pivx.price.value, currency: FIX.pivx.price.currency } : null, + pivx_get_preferred_currency: () => (FIX.pivx?.price?.currency || 'usd').toUpperCase(), + pivx_get_currencies: () => (FIX.pivx?.currencies || []).map((c) => ({ currency: c })), + pivx_get_wallet_address: () => null, + pivx_refresh_balances: () => FIX.pivx?.promos || [], + pivx_create_promo: () => ({ gift_code: 'PIVX-NEW00', address: FIX.pivx?.deposit_address, balance_piv: 0, status: 'pending', created_at: 0 }), + pivx_get_chat_payments: ({ conversationId }) => (FIX.pivx?.payments || []).filter((p) => p.conversation_id === conversationId), + pivx_check_address_balance: () => 1, + marketplace_get_cached_apps: () => FIX.marketplace || [], marketplace_fetch_apps: () => FIX.marketplace || [], + marketplace_get_trusted_publisher: () => 'npub1jskittyvector000000000000000000000000000000000000000000', + miniapp_get_history: () => (FIX.marketplace || []).filter((a) => a.installed).map((a, i) => ({ id: i + 1, name: a.name, src_url: a.local_path, attachment_ref: a.local_path, last_opened_at: Math.floor(FIX.now / 1000) - 3600 * (i * 30 + 2), open_count: 3, categories: a.categories.join(','), marketplace_id: a.id, installed_version: a.installed_version, is_favorite: false })), + get_compression_status: () => window.__COMPRESSION__ || null, + // NET_DEMO=: one of the fixtures' transport states. + transport_set_prelogin: () => (FIX.net_demo || {})[window.__NET__]?.view || null, + transport_get_state: () => (FIX.net_demo || {})[window.__NET__]?.view || { supported: ['clearnet'], prelogin: 'clearnet', kind: 'clearnet', phase: 'direct', ready: true, steps: [], detail: null }, + tor_get_state: () => (FIX.net_demo || {})[window.__NET__]?.tor || { enabled: false, running: false, supported: false, status: 'disabled', bootstrap_progress: 0, prelogin: false, multi_circuit: true, socks_proxy: null }, + tor_get_bridges: () => ({ enabled: false, lines: '' }), + tor_get_engine: () => ({ external: false, port: null, found: null }), + tor_check_obfs4_proxy: () => ({ installed: false, path: null }), + tor_get_circuits: () => (FIX.net_demo || {})[window.__NET__]?.circuits || { host: null, hops: [], circuits: 0, hosts: 0 }, + i2p_get_config: () => (FIX.net_demo || {})[window.__NET__]?.i2p || FIX.net_demo?.i2p_config, + transport_get_aliases: () => (FIX.net_demo || {})[window.__NET__]?.aliases || [], + transport_get_routes: (a) => (a?.urls || []).map((u) => ((FIX.net_demo || {})[window.__NET__]?.routes || []).find((r) => r.url === u) || ({ url: u, host: new URL(u).hostname, kind: (FIX.net_demo || {})[window.__NET__]?.view?.kind || 'clearnet', class: 'direct', text: 'Direct' })), + file_has_metadata: () => false, + list_accounts_with_metadata: () => FIX.profiles.slice(0, 3).map((p, i) => ({ + npub: p.id, display_name: p.nickname || p.display_name || p.name || null, + avatar_url: null, avatar_cached: p.avatar_cached || null, has_encryption: false, last_active: 100 - i, + })), + get_max_account_tier: () => window.__ACCOUNT_TIER__ ?? 1, + get_my_badges: () => window.__BADGES__ || { vector: false, vector_2026: false, tier: 0, bug_hunter: 0 }, + get_invited_users: () => window.__BADGES__?.invites || 0, + check_fawkes_badge: () => !!window.__BADGES__?.vector, + check_vector_2026_badge: () => !!window.__BADGES__?.vector_2026, + get_bug_hunter_tier: () => window.__BADGES__?.bug_hunter || 0, + }; + // MOCK_MODE: 'app' (signed in), 'login' (no account) or 'unlock' (a PIN-locked account). + const MODE = window.__MOCK_MODE__ || 'app'; + if (MODE !== 'app') { + delete answers.debug_hot_reload_sync; + fns.debug_hot_reload_sync = () => { throw 'Backend not initialized - perform normal login'; }; + answers.get_encryption_and_key = MODE === 'login' + ? { account_exists: false, enabled: false, security_type: 'pin', signer_type: 'local' } + : { account_exists: true, enabled: true, security_type: 'pin', signer_type: 'local' }; + answers.get_accounts = MODE === 'login' ? [] : [{ npub: FIX.npub }]; + answers.get_current_account = MODE === 'login' ? null : FIX.npub; + } + const seen = new Set(); + window.__mockMissed = []; + const invoke = async (cmd, args) => { + if (cmd in answers) return structuredClone(answers[cmd]); + if (cmd in fns) return structuredClone(fns[cmd](args || {})); + if (!seen.has(cmd)) { seen.add(cmd); window.__mockMissed.push(cmd); } + return null; + }; + const noop = async () => {}; + const win = new Proxy({}, { get: (_, k) => k === 'label' ? 'main' : (k === 'then' ? undefined : (async () => (k.startsWith('is') ? false : (k === 'innerSize' || k === 'outerSize' ? { width: innerWidth, height: innerHeight, toLogical: () => ({ width: innerWidth, height: innerHeight }) } : (k === 'scaleFactor' ? 1 : (k.startsWith('on') || k === 'listen' ? () => {} : null)))))) }); + window.__TAURI__ = { + core: { invoke, convertFileSrc: (p) => '/__ref/' + p, Channel: class { constructor() { this.onmessage = null; } } }, + event: { listen: async () => () => {}, once: async () => () => {}, emit: noop }, + window: { getCurrentWindow: () => win, currentMonitor: async () => null, primaryMonitor: async () => null, availableMonitors: async () => [] }, + webviewWindow: { getCurrentWebviewWindow: () => win }, + webview: { getCurrentWebview: () => win }, + dpi: { PhysicalSize: class {}, LogicalSize: class { constructor(w, h) { this.width = w; this.height = h; } }, PhysicalPosition: class {}, LogicalPosition: class {} }, + app: { getVersion: async () => '0.5.1', getName: async () => 'Vector' }, + opener: { openUrl: noop, openPath: noop, revealItemInDir: noop }, + dialog: { open: async () => null, save: async () => null, message: noop, ask: async () => false, confirm: async () => false }, + process: { exit: noop, relaunch: noop }, + updater: { check: async () => null }, + notification: { isPermissionGranted: async () => false, requestPermission: async () => 'denied', sendNotification: () => {} }, + clipboardManager: { writeText: noop, readText: async () => '' }, + }; +})(); diff --git a/crates/vector-gpui/reference/onscreen-baseline.json b/crates/vector-gpui/reference/onscreen-baseline.json new file mode 100644 index 000000000..f961033c4 --- /dev/null +++ b/crates/vector-gpui/reference/onscreen-baseline.json @@ -0,0 +1,6 @@ +{ + "linux-debug": 124.9, + "linux-debug-1600x1000": 150.5, + "linux-debug-420x760": 120.5, + "darwin-release": 193.4 +} diff --git a/crates/vector-gpui/reference/open-archive.js b/crates/vector-gpui/reference/open-archive.js new file mode 100644 index 000000000..b01a42974 --- /dev/null +++ b/crates/vector-gpui/reference/open-archive.js @@ -0,0 +1,6 @@ +// Pulls past the top of the chat list to reveal Archived Chats, then unfolds it (run with CHATLIST_DEMO=1). +(() => { + const list = document.querySelector('#chat-list'); + list?.dispatchEvent(new WheelEvent('wheel', { deltaY: -200, bubbles: true })); + setTimeout(() => document.querySelector('.chatlist-archive')?.click(), 500); +})(); diff --git a/crates/vector-gpui/reference/open-attach.js b/crates/vector-gpui/reference/open-attach.js new file mode 100644 index 000000000..300cf2707 --- /dev/null +++ b/crates/vector-gpui/reference/open-attach.js @@ -0,0 +1,7 @@ +// Opens the named chat (OPEN) and its attachment panel. +(() => { + const want = window.__OPEN_NAME__; + const rows = [...document.querySelectorAll('.chatlist-contact')]; + (want ? rows.find((r) => r.textContent.trim().toLowerCase().startsWith(want)) : rows[0])?.click(); + setTimeout(() => document.getElementById('chat-input-file')?.click(), 300); +})(); diff --git a/crates/vector-gpui/reference/open-badges.js b/crates/vector-gpui/reference/open-badges.js new file mode 100644 index 000000000..f80529153 --- /dev/null +++ b/crates/vector-gpui/reference/open-badges.js @@ -0,0 +1,6 @@ +// Our own profile holding every badge, then (CARD=) the nth badge's card. +(() => { + window.__BADGES__ = { vector: true, vector_2026: true, tier: 3, bug_hunter: 2, invites: 3 }; + openProfile(); + if (window.__CARD__) setTimeout(() => document.querySelectorAll('#profile-badges img')[window.__CARD__ - 1]?.click(), 900); +})(); diff --git a/crates/vector-gpui/reference/open-call-video.js b/crates/vector-gpui/reference/open-call-video.js new file mode 100644 index 000000000..2a0db501b --- /dev/null +++ b/crates/vector-gpui/reference/open-call-video.js @@ -0,0 +1,24 @@ +// A video call with alice: their camera and screen on, ours on; window.__CALL__ is video or video-open. +(() => { + const alice = 'npub190vqdjtlpcq27xslcveglfmr4ynfwg7gmw86cnun4acakxrdd6gqnp929a'; + const mode = window.__CALL__; + setTimeout(() => { + VectorSvelte.setVideoCaps({ encode: ['h264'], decode: ['h264'] }); + VectorSvelte.setCallState({ id: 'fixture', peer: alice, outgoing: true, phase: 'active', muted: false, peer_muted: false, volume: 1, active_ms: 83000, + video_mine: { camera: true, screen: false }, video_peer: { camera: true, screen: true }, peer_decodes: ['h264'] }); + VectorSvelte.setCallAudio({ auto_gain: true, echo_cancel: true, noise_suppress: true, mic_volume: 1, speaker_volume: 1 }); + [62, 58, 64, 71, 66, 60, 59, 63, 120, 95, 70, 64, 61, 60, 58, 62, 66, 63, 61, 60].forEach((rtt, i) => { + const concealed = (i === 9 ? 3 : 0) + (i > 9 ? 3 : 0); + VectorSvelte.setCallStats({ id: 'fixture', rtt_ms: rtt, path: 'relay', bitrate_kbps: 64, received: (i + 1) * 50, concealed, net_loss: 0, + video: { camera: { fps: 30, kbps: 780, width: 1280, height: 720 }, screen: { fps: 0, kbps: 0, width: 0, height: 0 } } }); + }); + VectorSvelte.setCallLevels({ id: 'fixture', mic: 0.62, peer: 0.7 }); + }, 400); + if (mode === 'video-open') setTimeout(() => { + const row = document.querySelector('.call-pill-row'); + const r = row.getBoundingClientRect(); + const o = { bubbles: true, clientX: r.left + 60, clientY: r.top + 20, pointerId: 1, button: 0 }; + row.dispatchEvent(new PointerEvent('pointerdown', o)); + row.dispatchEvent(new PointerEvent('pointerup', o)); + }, 900); +})(); diff --git a/crates/vector-gpui/reference/open-call.js b/crates/vector-gpui/reference/open-call.js new file mode 100644 index 000000000..5a9fc9a9f --- /dev/null +++ b/crates/vector-gpui/reference/open-call.js @@ -0,0 +1,23 @@ +// A call with alice: window.__CALL__ is ringing, calling or open (active, panel open). +(() => { + const alice = 'npub190vqdjtlpcq27xslcveglfmr4ynfwg7gmw86cnun4acakxrdd6gqnp929a'; + const mode = window.__CALL__; + setTimeout(() => { + const phase = mode === 'open' ? 'active' : 'ringing'; + VectorSvelte.setCallState({ id: 'fixture', peer: alice, outgoing: mode !== 'ringing', phase, muted: false, peer_muted: false, volume: 1, active_ms: 83000 }); + VectorSvelte.setCallAudio({ auto_gain: true, echo_cancel: true, noise_suppress: true, mic_volume: 1, speaker_volume: 1 }); + if (phase !== 'active') return; + [62, 58, 64, 71, 66, 60, 59, 63, 120, 95, 70, 64, 61, 60, 58, 62, 66, 63, 61, 60].forEach((rtt, i) => { + const concealed = (i === 9 ? 3 : 0) + (i > 9 ? 3 : 0); + VectorSvelte.setCallStats({ id: 'fixture', rtt_ms: rtt, path: 'relay', bitrate_kbps: 64, received: (i + 1) * 50, concealed, net_loss: 0 }); + }); + VectorSvelte.setCallLevels({ id: 'fixture', mic: 0.62, peer: 0.7 }); + }, 400); + if (mode === 'open') setTimeout(() => { + const row = document.querySelector('.call-pill-row'); + const r = row.getBoundingClientRect(); + const o = { bubbles: true, clientX: r.left + 60, clientY: r.top + 20, pointerId: 1, button: 0 }; + row.dispatchEvent(new PointerEvent('pointerdown', o)); + row.dispatchEvent(new PointerEvent('pointerup', o)); + }, 900); +})(); diff --git a/crates/vector-gpui/reference/open-channel-editor.js b/crates/vector-gpui/reference/open-channel-editor.js new file mode 100644 index 000000000..aa5187fbe --- /dev/null +++ b/crates/vector-gpui/reference/open-channel-editor.js @@ -0,0 +1,13 @@ +// Vector Devs' #dev Channel Settings; window.__TYPE__ names a section to open. +(async () => { + const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); + const row = [...document.querySelectorAll('.ws-rail-item')].find((e) => e.textContent.includes('Vector Devs')); + row?.click(); + await sleep(600); + const com = (window.__VECTOR_FIXTURES__.communities || [])[0]; + const ch = com.channels.find((c) => c.name === (window.__CHANNEL__ || 'dev')); + openChannelEditorFor(com.community_id, { id: ch.channel_id, name: ch.name, topic: ch.topic, view: ch.view, private: ch.private }); + await sleep(700); + if (window.__TYPE__) [...document.querySelectorAll('button, [role=button], .sn-item, nav *')].find((e) => e.textContent.trim() === window.__TYPE__)?.click(); + await sleep(300); +})(); diff --git a/crates/vector-gpui/reference/open-channel.js b/crates/vector-gpui/reference/open-channel.js new file mode 100644 index 000000000..755abc82c --- /dev/null +++ b/crates/vector-gpui/reference/open-channel.js @@ -0,0 +1,4 @@ +// Opens the channel whose id is OPEN. +(async () => { + await openChat(window.__OPEN_NAME__); +})(); diff --git a/crates/vector-gpui/reference/open-chat-menu.js b/crates/vector-gpui/reference/open-chat-menu.js new file mode 100644 index 000000000..79e0415cc --- /dev/null +++ b/crates/vector-gpui/reference/open-chat-menu.js @@ -0,0 +1,10 @@ +// Opens OPEN and its header's ⋯ menu; TYPE=timer goes on to the Self-Destruct Timer picker. +(async () => { + openChat(window.__OPEN_NAME__); + await new Promise((r) => setTimeout(r, 600)); + document.querySelector('.nav-menu-btn')?.click(); + if (window.__TYPE__ !== 'timer') return; + await new Promise((r) => setTimeout(r, 400)); + hideContextMenu?.(); + openSelfDestructPicker(strOpenChat, document.querySelector('.nav-menu-btn').getBoundingClientRect()); +})(); diff --git a/crates/vector-gpui/reference/open-chat.js b/crates/vector-gpui/reference/open-chat.js new file mode 100644 index 000000000..e23e58f8c --- /dev/null +++ b/crates/vector-gpui/reference/open-chat.js @@ -0,0 +1,6 @@ +// Opens the chat named by window.__OPEN_NAME__ (set by capture.mjs from OPEN), else the first. +(() => { + const want = window.__OPEN_NAME__; + const rows = [...document.querySelectorAll('.chatlist-contact')]; + (want ? rows.find((r) => r.textContent.trim().toLowerCase().startsWith(want)) : rows[0])?.click(); +})(); diff --git a/crates/vector-gpui/reference/open-comm-settings.js b/crates/vector-gpui/reference/open-comm-settings.js new file mode 100644 index 000000000..1f7bfa30f --- /dev/null +++ b/crates/vector-gpui/reference/open-comm-settings.js @@ -0,0 +1,11 @@ +// Vector Devs' Community Settings; window.__SECTION__ names a section to open. +(async () => { + const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); + const row = [...document.querySelectorAll('.ws-rail-item')].find((e) => e.textContent.includes('Vector Devs')); + row?.click(); + await sleep(600); + const id = (window.__VECTOR_FIXTURES__.communities || [])[0].community_id; + openCommunitySettings(id); + await sleep(700); + if (window.__SECTION__) [...document.querySelectorAll('button, [role=button], .sn-item, nav *')].find((e) => e.textContent.trim() === window.__SECTION__)?.click(); +})(); diff --git a/crates/vector-gpui/reference/open-community.js b/crates/vector-gpui/reference/open-community.js new file mode 100644 index 000000000..966fe30ac --- /dev/null +++ b/crates/vector-gpui/reference/open-community.js @@ -0,0 +1,5 @@ +// Open the fixture community from the rail; window.__CH__ names a channel to open after. +(() => { + setTimeout(() => [...document.querySelectorAll('*')].find((e) => e.children.length === 0 && e.textContent.trim() === 'Vector Devs')?.closest('[class*="rail"], div')?.click(), 400); + if (window.__CH__) setTimeout(() => [...document.querySelectorAll('*')].find((e) => e.children.length === 0 && e.textContent.trim() === window.__CH__)?.click(), 1100); +})(); diff --git a/crates/vector-gpui/reference/open-crop.js b/crates/vector-gpui/reference/open-crop.js new file mode 100644 index 000000000..1f2f6d2f0 --- /dev/null +++ b/crates/vector-gpui/reference/open-crop.js @@ -0,0 +1,5 @@ +// Opens our own profile with the avatar cropper on a portrait picture. +(() => { + openProfile(); + setTimeout(() => VectorSvelte.openCropper({ src: '/__ref/media/portrait.png', aspect: 1, title: 'Crop Profile Picture', hint: 'Drag to move, or drag a corner to resize.', shape: 'round' }), 300); +})(); diff --git a/crates/vector-gpui/reference/open-edit.js b/crates/vector-gpui/reference/open-edit.js new file mode 100644 index 000000000..6b11b308d --- /dev/null +++ b/crates/vector-gpui/reference/open-edit.js @@ -0,0 +1,5 @@ +// Opens our own profile in Edit Mode. +(() => { + openProfile(); + setTimeout(() => document.getElementById('profile-edit-btn')?.click(), 300); +})(); diff --git a/crates/vector-gpui/reference/open-embed.js b/crates/vector-gpui/reference/open-embed.js new file mode 100644 index 000000000..74cc6d165 --- /dev/null +++ b/crates/vector-gpui/reference/open-embed.js @@ -0,0 +1,7 @@ +// Opens the chat named by OPEN, then expands its first Nostr article card. +(() => { + const want = window.__OPEN_NAME__; + const rows = [...document.querySelectorAll('.chatlist-contact')]; + (want ? rows.find((r) => r.textContent.trim().toLowerCase().startsWith(want)) : rows[0])?.click(); + setTimeout(() => document.querySelector('.ne-btn-primary')?.click(), 1500); +})(); diff --git a/crates/vector-gpui/reference/open-file-preview.js b/crates/vector-gpui/reference/open-file-preview.js new file mode 100644 index 000000000..7fa7591a0 --- /dev/null +++ b/crates/vector-gpui/reference/open-file-preview.js @@ -0,0 +1,9 @@ +// Opens the named chat (OPEN) and the send preview for a picture, with its compression estimate. +(() => { + window.__FILE_SIZES__ = { 'photo.png': 170552 }; + window.__COMPRESSION__ = { original_size: 170552, estimated_size: 51743, savings_percent: 69 }; + const want = window.__OPEN_NAME__; + const rows = [...document.querySelectorAll('.chatlist-contact')]; + (want ? rows.find((r) => r.textContent.trim().toLowerCase().startsWith(want)) : rows[0])?.click(); + setTimeout(() => openFilePreview('media/photo.png', strOpenChat, ''), 300); +})(); diff --git a/crates/vector-gpui/reference/open-first-chat.js b/crates/vector-gpui/reference/open-first-chat.js new file mode 100644 index 000000000..5e8001b2c --- /dev/null +++ b/crates/vector-gpui/reference/open-first-chat.js @@ -0,0 +1 @@ +document.querySelector('.chatlist-contact')?.click(); diff --git a/crates/vector-gpui/reference/open-invite-details.js b/crates/vector-gpui/reference/open-invite-details.js new file mode 100644 index 000000000..cffeaa34e --- /dev/null +++ b/crates/vector-gpui/reference/open-invite-details.js @@ -0,0 +1,10 @@ +// The fixtures' pending Community invite, opened from the Requests tab. +(async () => { + const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); + await sleep(300); + await loadCommunityInvites(); + invitesChanged(); + [...document.querySelectorAll('.cc-tab')].find((t) => t.textContent.includes('Requests'))?.click(); + await sleep(400); + document.querySelector('.chatlist-invite')?.click(); +})(); diff --git a/crates/vector-gpui/reference/open-invites.js b/crates/vector-gpui/reference/open-invites.js new file mode 100644 index 000000000..828312fcd --- /dev/null +++ b/crates/vector-gpui/reference/open-invites.js @@ -0,0 +1,8 @@ +// The Requests tab with the fixtures' pending Community invite in it. +(async () => { + const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); + await sleep(300); + await loadCommunityInvites(); + invitesChanged(); + [...document.querySelectorAll('.cc-tab')].find((t) => t.textContent.includes('Requests'))?.click(); +})(); diff --git a/crates/vector-gpui/reference/open-kaomoji.js b/crates/vector-gpui/reference/open-kaomoji.js new file mode 100644 index 000000000..a9163a69c --- /dev/null +++ b/crates/vector-gpui/reference/open-kaomoji.js @@ -0,0 +1,8 @@ +// Opens the named chat (OPEN), the composer's emoji picker, then its kaomoji mode. +(() => { + const want = window.__OPEN_NAME__; + const rows = [...document.querySelectorAll('.chatlist-contact')]; + (want ? rows.find((r) => r.textContent.trim().toLowerCase().startsWith(want)) : rows[0])?.click(); + setTimeout(() => document.getElementById('chat-input-emoji')?.click(), 600); + setTimeout(() => document.querySelector('.picker-mode-btn[data-mode="kaomoji"]')?.click(), 1000); +})(); diff --git a/crates/vector-gpui/reference/open-login-picker.js b/crates/vector-gpui/reference/open-login-picker.js new file mode 100644 index 000000000..7cdde73a6 --- /dev/null +++ b/crates/vector-gpui/reference/open-login-picker.js @@ -0,0 +1,4 @@ +// The unlock screen's account pill, then (PICK=1) its account list. +(() => { + if (window.__PICKER_OPEN__) setTimeout(() => document.getElementById('login-account-picker')?.click(), 600); +})(); diff --git a/crates/vector-gpui/reference/open-lyrics.js b/crates/vector-gpui/reference/open-lyrics.js new file mode 100644 index 000000000..e1020e893 --- /dev/null +++ b/crates/vector-gpui/reference/open-lyrics.js @@ -0,0 +1,6 @@ +// Opens OPEN and the first lyrics sheet in it. +(async () => { + openChat(window.__OPEN_NAME__); + for (let i = 0; i < 40 && !document.querySelector('[aria-label="Show lyrics"]'); i++) await new Promise((r) => setTimeout(r, 50)); + document.querySelector('[aria-label="Show lyrics"]')?.click(); +})(); diff --git a/crates/vector-gpui/reference/open-moderation.js b/crates/vector-gpui/reference/open-moderation.js new file mode 100644 index 000000000..dfa5c283b --- /dev/null +++ b/crates/vector-gpui/reference/open-moderation.js @@ -0,0 +1,9 @@ +// Vector Devs' Moderation console. +(async () => { + const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); + const row = [...document.querySelectorAll('.ws-rail-item')].find((e) => e.textContent.includes('Vector Devs')); + row?.click(); + await sleep(600); + const id = (window.__VECTOR_FIXTURES__.communities || [])[0].community_id; + openModerationPanel(id); +})(); diff --git a/crates/vector-gpui/reference/open-new-chat-invite.js b/crates/vector-gpui/reference/open-new-chat-invite.js new file mode 100644 index 000000000..26ae38bc2 --- /dev/null +++ b/crates/vector-gpui/reference/open-new-chat-invite.js @@ -0,0 +1,10 @@ +// New Message with a Community invite link pasted into its search. +(async () => { + const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); + await sleep(200); + openNewChat(); + await sleep(500); + const input = document.querySelector('#create-group-filter'); + input.value = 'https://vectorapp.io/invite/naddr1qvzqqqr4gupzqmjxss3dld622uu8q25gywum9qtg4w4cv4064jmg20xsac2aam5nqqxnzd3cxqmrzv3exgmr2wfesgsmew#Zk3pQ9vT2xLm8RbN4cWd7YhJ'; + input.dispatchEvent(new Event('input', { bubbles: true })); +})(); diff --git a/crates/vector-gpui/reference/open-new-chat.js b/crates/vector-gpui/reference/open-new-chat.js new file mode 100644 index 000000000..5be5816ae --- /dev/null +++ b/crates/vector-gpui/reference/open-new-chat.js @@ -0,0 +1,5 @@ +// The chat list's New Message panel; PICK= selects the nth contact. +(() => { + setTimeout(() => openNewChat(), 200); + if (window.__PICK__) setTimeout(() => document.querySelectorAll('#create-group-list .member-row, #create-group-list [class*=member]')[window.__PICK__ - 1]?.click(), 900); +})(); diff --git a/crates/vector-gpui/reference/open-nexus-details.js b/crates/vector-gpui/reference/open-nexus-details.js new file mode 100644 index 000000000..a60127fdb --- /dev/null +++ b/crates/vector-gpui/reference/open-nexus-details.js @@ -0,0 +1 @@ +(() => { setTimeout(async () => { await showMarketplacePanel('discover'); setTimeout(() => VectorSvelte.mktShowDetails ? VectorSvelte.mktShowDetails('chess') : document.querySelector('.nx-row')?.click(), 400); }, 400); })(); diff --git a/crates/vector-gpui/reference/open-nexus-discover.js b/crates/vector-gpui/reference/open-nexus-discover.js new file mode 100644 index 000000000..b752ffac6 --- /dev/null +++ b/crates/vector-gpui/reference/open-nexus-discover.js @@ -0,0 +1 @@ +(() => { setTimeout(() => showMarketplacePanel('discover'), 400); })(); diff --git a/crates/vector-gpui/reference/open-nexus-edit.js b/crates/vector-gpui/reference/open-nexus-edit.js new file mode 100644 index 000000000..984653eb1 --- /dev/null +++ b/crates/vector-gpui/reference/open-nexus-edit.js @@ -0,0 +1 @@ +(() => { setTimeout(async () => { await showMarketplacePanel('discover'); setTimeout(() => { VectorSvelte.mktShowDetails ? VectorSvelte.mktShowDetails('chess') : document.querySelector('.nx-row')?.click(); setTimeout(() => document.querySelector('.nx-edit')?.click(), 400); }, 400); }, 400); })(); diff --git a/crates/vector-gpui/reference/open-nexus.js b/crates/vector-gpui/reference/open-nexus.js new file mode 100644 index 000000000..ae25b2c69 --- /dev/null +++ b/crates/vector-gpui/reference/open-nexus.js @@ -0,0 +1 @@ +(() => { setTimeout(() => showMiniApps(), 400); })(); diff --git a/crates/vector-gpui/reference/open-nickname.js b/crates/vector-gpui/reference/open-nickname.js new file mode 100644 index 000000000..511669f56 --- /dev/null +++ b/crates/vector-gpui/reference/open-nickname.js @@ -0,0 +1,8 @@ +// Opens the named contact's profile (OPEN), then its More menu's Nickname popup. +(() => { + const want = window.__OPEN_NAME__; + const p = arrProfiles.find((p) => (p.nickname || p.name || '').toLowerCase().startsWith(want)); + openProfile(p); + setTimeout(() => document.getElementById('profile-option-more')?.click(), 300); + setTimeout(() => { if (!window.__MORE_ONLY__) document.querySelector('.profile-more-item')?.click(); }, 600); +})(); diff --git a/crates/vector-gpui/reference/open-npub.js b/crates/vector-gpui/reference/open-npub.js new file mode 100644 index 000000000..98d0f56df --- /dev/null +++ b/crates/vector-gpui/reference/open-npub.js @@ -0,0 +1,4 @@ +// Opens the chat whose id is OPEN (an npub), for when Streamer Mode hides the names. +(async () => { + await openChat(window.__OPEN_NAME__); +})(); diff --git a/crates/vector-gpui/reference/open-pack-creator.js b/crates/vector-gpui/reference/open-pack-creator.js new file mode 100644 index 000000000..80975e54a --- /dev/null +++ b/crates/vector-gpui/reference/open-pack-creator.js @@ -0,0 +1,12 @@ +// Opens the named chat (OPEN), the composer's emoji picker, then the pack creator: +// a new pack, or (CREATOR=edit) the first own pack's editor. +(() => { + const want = window.__OPEN_NAME__; + const rows = [...document.querySelectorAll('.chatlist-contact')]; + (want ? rows.find((r) => r.textContent.trim().toLowerCase().startsWith(want)) : rows[0])?.click(); + setTimeout(() => document.getElementById('chat-input-emoji')?.click(), 600); + setTimeout(() => { + const edit = new URLSearchParams(location.search).get('creator') === 'edit' || window.__CREATOR__ === 'edit'; + (edit ? document.querySelector('.emoji-pack-edit-pencil') : document.querySelector('.emoji-pack-tab-create'))?.click(); + }, 1400); +})(); diff --git a/crates/vector-gpui/reference/open-pack-details.js b/crates/vector-gpui/reference/open-pack-details.js new file mode 100644 index 000000000..067a7777d --- /dev/null +++ b/crates/vector-gpui/reference/open-pack-details.js @@ -0,0 +1,4 @@ +// Opens the Pack Details modal for the fixture pack, as a vector://emojis/pack link does. +(() => { + setTimeout(() => openPackDetailsModal('naddr1qqzkymr0vfesygypkcma3lxjcmdxxk0xjcc38gghphnete9hykuy68stfn7ea3vvaypsgqqqw48qsh6h7r'), 600); +})(); diff --git a/crates/vector-gpui/reference/open-picker-packs.js b/crates/vector-gpui/reference/open-picker-packs.js new file mode 100644 index 000000000..a0c1460c4 --- /dev/null +++ b/crates/vector-gpui/reference/open-picker-packs.js @@ -0,0 +1,8 @@ +// Opens the named chat (OPEN), the composer's emoji picker, then jumps to its first pack. +(() => { + const want = window.__OPEN_NAME__; + const rows = [...document.querySelectorAll('.chatlist-contact')]; + (want ? rows.find((r) => r.textContent.trim().toLowerCase().startsWith(want)) : rows[0])?.click(); + setTimeout(() => document.getElementById('chat-input-emoji')?.click(), 600); + setTimeout(() => document.querySelector('.emoji-pack-tab')?.click(), 1400); +})(); diff --git a/crates/vector-gpui/reference/open-picker.js b/crates/vector-gpui/reference/open-picker.js new file mode 100644 index 000000000..00c31bf11 --- /dev/null +++ b/crates/vector-gpui/reference/open-picker.js @@ -0,0 +1,7 @@ +// Opens the named chat (OPEN), then the composer's emoji picker. +(() => { + const want = window.__OPEN_NAME__; + const rows = [...document.querySelectorAll('.chatlist-contact')]; + (want ? rows.find((r) => r.textContent.trim().toLowerCase().startsWith(want)) : rows[0])?.click(); + setTimeout(() => document.getElementById('chat-input-emoji')?.click(), 600); +})(); diff --git a/crates/vector-gpui/reference/open-pivx-chat.js b/crates/vector-gpui/reference/open-pivx-chat.js new file mode 100644 index 000000000..d08dc246e --- /dev/null +++ b/crates/vector-gpui/reference/open-pivx-chat.js @@ -0,0 +1,5 @@ +// Opens mo's chat, where the fixtures put two PIVX payments. +(() => { + const rows = [...document.querySelectorAll('.chatlist-contact')]; + rows.find((r) => r.textContent.trim().toLowerCase().startsWith('mo'))?.click(); +})(); diff --git a/crates/vector-gpui/reference/open-pivx.js b/crates/vector-gpui/reference/open-pivx.js new file mode 100644 index 000000000..cb92b9ad2 --- /dev/null +++ b/crates/vector-gpui/reference/open-pivx.js @@ -0,0 +1,10 @@ +// Opens mo's chat, its attachment panel, then the PIVX wallet; PIVX_DIALOG clicks a dock button. +(() => { + const rows = [...document.querySelectorAll('.chatlist-contact')]; + rows.find((r) => r.textContent.trim().toLowerCase().startsWith('mo'))?.click(); + setTimeout(() => document.getElementById('chat-input-file')?.click(), 300); + setTimeout(() => [...document.querySelectorAll('#attachment-panel button, #attachment-panel div')].find((e) => e.textContent.trim() === 'Mini Apps')?.click(), 700); + setTimeout(() => document.getElementById('attachment-panel-pivx')?.click(), 1200); + const d = window.__PIVX_DIALOG__; + if (d) setTimeout(() => document.getElementById(`pivx-${d}-btn`)?.click(), 2200); +})(); diff --git a/crates/vector-gpui/reference/open-policies.js b/crates/vector-gpui/reference/open-policies.js new file mode 100644 index 000000000..a4c8d90f1 --- /dev/null +++ b/crates/vector-gpui/reference/open-policies.js @@ -0,0 +1,15 @@ +// The Policies tab; window.__PRESET__ opens that template (or 'defaults'). +(async () => { + const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); + const row = [...document.querySelectorAll('.ws-rail-item')].find((e) => e.textContent.includes('Vector Devs')); + row?.click(); + await sleep(600); + const id = (window.__VECTOR_FIXTURES__.communities || [])[0].community_id; + openModerationPanel(id); + await sleep(500); + [...document.querySelectorAll('.mod-tab, [class*="mod-tab"]')].find((e) => e.textContent.trim() === 'Policies')?.click(); + await sleep(500); + const p = window.__PRESET__; + if (p === 'defaults') [...document.querySelectorAll('button')].find((b) => b.textContent.includes('See the rules'))?.click(); + else if (p) [...document.querySelectorAll('.pol-card')].find((c) => c.textContent.includes(p))?.click(); +})(); diff --git a/crates/vector-gpui/reference/open-profile.js b/crates/vector-gpui/reference/open-profile.js new file mode 100644 index 000000000..410bcbe42 --- /dev/null +++ b/crates/vector-gpui/reference/open-profile.js @@ -0,0 +1,8 @@ +// Opens a profile: the named contact's (OPEN, via its chat), else our own. +(() => { + const want = window.__OPEN_NAME__; + if (!want) return openProfile(); + const p = arrProfiles.find((p) => (p.nickname || p.name || '').toLowerCase().startsWith(want)); + previousChatBeforeProfile = p?.id || ''; + openProfile(p); +})(); diff --git a/crates/vector-gpui/reference/open-qr.js b/crates/vector-gpui/reference/open-qr.js new file mode 100644 index 000000000..fee77db0a --- /dev/null +++ b/crates/vector-gpui/reference/open-qr.js @@ -0,0 +1,7 @@ +// Opens the named contact's profile (OPEN), then its QR overlay. +(() => { + const want = window.__OPEN_NAME__; + const p = arrProfiles.find((p) => (p.nickname || p.name || '').toLowerCase().startsWith(want)); + openProfile(p); + setTimeout(() => document.getElementById('profile-qr-btn')?.click(), 300); +})(); diff --git a/crates/vector-gpui/reference/open-request-chat.js b/crates/vector-gpui/reference/open-request-chat.js new file mode 100644 index 000000000..d49238a12 --- /dev/null +++ b/crates/vector-gpui/reference/open-request-chat.js @@ -0,0 +1,5 @@ +// A DM request opened from the Requests tab. +(() => { + setTimeout(() => [...document.querySelectorAll('.cc-tab')].find((t) => t.textContent.includes('Requests'))?.click(), 300); + setTimeout(() => document.querySelector('#chat-list .chatlist-contact')?.click(), 700); +})(); diff --git a/crates/vector-gpui/reference/open-requests.js b/crates/vector-gpui/reference/open-requests.js new file mode 100644 index 000000000..c9a06e465 --- /dev/null +++ b/crates/vector-gpui/reference/open-requests.js @@ -0,0 +1,4 @@ +// The chat list's Requests tab. +(() => { + setTimeout(() => [...document.querySelectorAll('.cc-tab')].find((t) => t.textContent.includes('Requests'))?.click(), 300); +})(); diff --git a/crates/vector-gpui/reference/open-settings-cat.js b/crates/vector-gpui/reference/open-settings-cat.js new file mode 100644 index 000000000..ce70ecd2a --- /dev/null +++ b/crates/vector-gpui/reference/open-settings-cat.js @@ -0,0 +1,5 @@ +// Settings at the category CAT names (by its nav label). +(() => { + setTimeout(() => openSettings(), 300); + setTimeout(() => [...document.querySelectorAll('.cs-section')].find((b) => b.textContent.trim().startsWith(window.__CAT__))?.click(), 800); +})(); diff --git a/crates/vector-gpui/reference/open-settings-info.js b/crates/vector-gpui/reference/open-settings-info.js new file mode 100644 index 000000000..c6a637e71 --- /dev/null +++ b/crates/vector-gpui/reference/open-settings-info.js @@ -0,0 +1,5 @@ +// The Display block's Main Menu explainer. +(() => { + setTimeout(() => openSettings(), 300); + setTimeout(() => document.querySelector('.cs-block .notif-info')?.click(), 900); +})(); diff --git a/crates/vector-gpui/reference/open-settings.js b/crates/vector-gpui/reference/open-settings.js new file mode 100644 index 000000000..4dc944993 --- /dev/null +++ b/crates/vector-gpui/reference/open-settings.js @@ -0,0 +1 @@ +(() => { setTimeout(() => openSettings(), 300); })(); diff --git a/crates/vector-gpui/reference/open-status-emoji.js b/crates/vector-gpui/reference/open-status-emoji.js new file mode 100644 index 000000000..621620e56 --- /dev/null +++ b/crates/vector-gpui/reference/open-status-emoji.js @@ -0,0 +1,6 @@ +// Opens our own profile, its Status dialog, then the dialog's emoji picker. +(() => { + openProfile(); + setTimeout(() => askForStatus(), 300); + setTimeout(() => document.getElementById('status-emoji-btn')?.click(), 700); +})(); diff --git a/crates/vector-gpui/reference/open-status.js b/crates/vector-gpui/reference/open-status.js new file mode 100644 index 000000000..9f3c23323 --- /dev/null +++ b/crates/vector-gpui/reference/open-status.js @@ -0,0 +1,5 @@ +// Opens our own profile, then its Status dialog. +(() => { + openProfile(); + setTimeout(() => askForStatus(), 300); +})(); diff --git a/crates/vector-gpui/reference/open-switcher-rail.js b/crates/vector-gpui/reference/open-switcher-rail.js new file mode 100644 index 000000000..e34a338d5 --- /dev/null +++ b/crates/vector-gpui/reference/open-switcher-rail.js @@ -0,0 +1,4 @@ +// Opens the account switcher from the widescreen rail's account chip: it drops up. +(() => { + setTimeout(() => document.querySelector('#ws-rail-account .ws-account-caret')?.click(), 300); +})(); diff --git a/crates/vector-gpui/reference/open-switcher.js b/crates/vector-gpui/reference/open-switcher.js new file mode 100644 index 000000000..86c24a47f --- /dev/null +++ b/crates/vector-gpui/reference/open-switcher.js @@ -0,0 +1,6 @@ +// Opens our own profile, then its My Profile account switcher (EDIT=1: in delete mode). +(() => { + openProfile(); + setTimeout(() => document.getElementById('my-profile-switcher')?.click(), 300); + if (window.__SWITCHER_EDIT__) setTimeout(() => document.getElementById('profile-switcher-trash-toggle')?.click(), 700); +})(); diff --git a/crates/vector-gpui/reference/open-top.js b/crates/vector-gpui/reference/open-top.js new file mode 100644 index 000000000..c1944be3b --- /dev/null +++ b/crates/vector-gpui/reference/open-top.js @@ -0,0 +1,6 @@ +// Opens OPEN scrolled to its first message. +(async () => { + openChat(window.__OPEN_NAME__); + await new Promise((r) => setTimeout(r, 1200)); + document.querySelector('.dmsg-selfdestruct')?.closest('[id]')?.scrollIntoView({ block: 'center' }); +})(); diff --git a/crates/vector-gpui/reference/open-transcript.js b/crates/vector-gpui/reference/open-transcript.js new file mode 100644 index 000000000..164ed5a85 --- /dev/null +++ b/crates/vector-gpui/reference/open-transcript.js @@ -0,0 +1,11 @@ +// Opens OPEN and transcribes its first voice message. +(async () => { + openChat(window.__OPEN_NAME__); + const sel = '.audio-transcribe-btn'; + for (let i = 0; i < 60 && !document.querySelector(sel); i++) await new Promise((r) => setTimeout(r, 50)); + document.querySelector(sel)?.click(); +})(); +setTimeout(() => { + const m = document.querySelector('.audio-transcribe-btn')?.closest('.msg, [id]'); + m?.scrollIntoView({ block: 'start' }); +}, 1200); diff --git a/crates/vector-gpui/reference/open-viewer.js b/crates/vector-gpui/reference/open-viewer.js new file mode 100644 index 000000000..13a3b01c5 --- /dev/null +++ b/crates/vector-gpui/reference/open-viewer.js @@ -0,0 +1,8 @@ +// Opens the named chat (OPEN), reveals its spoiler picture, then views it full screen. +(() => { + const want = window.__OPEN_NAME__; + const rows = [...document.querySelectorAll('.chatlist-contact')]; + (want ? rows.find((r) => r.textContent.trim().toLowerCase().startsWith(want)) : rows[0])?.click(); + setTimeout(() => document.querySelector('.spoiler-overlay')?.click(), 300); + setTimeout(() => { const i = [...document.querySelectorAll('.dmsg-image-attachment')].pop(); if (i) openImageViewer(i.dataset.full || i.src); }, 600); +})(); diff --git a/crates/vector-gpui/reference/open-voice.js b/crates/vector-gpui/reference/open-voice.js new file mode 100644 index 000000000..de85f7e57 --- /dev/null +++ b/crates/vector-gpui/reference/open-voice.js @@ -0,0 +1,5 @@ +// Opens the fixture community, then its Lounge voice channel (run with VOICE_DEMO=present|joined). +(() => { + setTimeout(() => [...document.querySelectorAll('*')].find((e) => e.children.length === 0 && e.textContent.trim() === 'Vector Devs')?.closest('[class*="rail"], div')?.click(), 400); + setTimeout(() => [...document.querySelectorAll('.chatlist-channel-name')].find((e) => e.textContent.trim() === 'Lounge')?.click(), 1100); +})(); diff --git a/crates/vector-gpui/reference/pick-command.js b/crates/vector-gpui/reference/pick-command.js new file mode 100644 index 000000000..b6d8b41c7 --- /dev/null +++ b/crates/vector-gpui/reference/pick-command.js @@ -0,0 +1,11 @@ +// Opens the first chat, types window.__TYPE__ and presses Enter to pick the command it lists. +(async () => { + document.querySelector('.chatlist-contact')?.click(); + await new Promise((r) => setTimeout(r, 800)); + const input = domChatMessageInput; + input.focus(); + input.value = window.__TYPE__ || ''; + input.dispatchEvent(new Event('input', { bubbles: true })); + await new Promise((r) => setTimeout(r, 300)); + input.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true, cancelable: true })); +})(); diff --git a/crates/vector-gpui/reference/popout-audio.js b/crates/vector-gpui/reference/popout-audio.js new file mode 100644 index 000000000..2a28f0e67 --- /dev/null +++ b/crates/vector-gpui/reference/popout-audio.js @@ -0,0 +1,9 @@ +// Plays OPEN's audio number TYPE (from 0), then opens mo so it floats. +(async () => { + const wait = (ms) => new Promise((r) => setTimeout(r, ms)); + openChat(window.__OPEN_NAME__); + for (let i = 0; i < 40 && !document.querySelector('.audio-play-btn'); i++) await wait(50); + document.querySelectorAll('.audio-play-btn')[+window.__TYPE__ || 0]?.click(); + await wait(400); + openChat('npub17jjvuhaxxs9rt2jakz6td5c6d7a2vpfr2erqmwc9xajhmqplt03q63stmv'); +})(); diff --git a/crates/vector-gpui/reference/rail-collapse.js b/crates/vector-gpui/reference/rail-collapse.js new file mode 100644 index 000000000..f8a4ccc67 --- /dev/null +++ b/crates/vector-gpui/reference/rail-collapse.js @@ -0,0 +1,2 @@ +// Collapses the widescreen rail (#ws-rail-collapse). +(() => document.querySelector('#ws-rail-collapse')?.click())(); diff --git a/crates/vector-gpui/reference/rec-state.js b/crates/vector-gpui/reference/rec-state.js new file mode 100644 index 000000000..2401c65a4 --- /dev/null +++ b/crates/vector-gpui/reference/rec-state.js @@ -0,0 +1,8 @@ +// Opens OPEN and holds the voice recorder in REC (TYPE: recording | locked | preview). +(() => { + openChat(window.__OPEN_NAME__); + const s = window.__TYPE__ || 'recording'; + VectorSvelte.setVoiceState(s); + VectorSvelte.setVoiceTimer('0:04'); + if (s === 'preview') VectorSvelte.setVoicePreview({ progress: 2600 / 7400 * 100, time: '0:02' }); +})(); diff --git a/crates/vector-gpui/reference/shot.sh b/crates/vector-gpui/reference/shot.sh new file mode 100755 index 000000000..9245ff2c1 --- /dev/null +++ b/crates/vector-gpui/reference/shot.sh @@ -0,0 +1,24 @@ +#!/bin/bash +# Renders vector-gpui under Xvfb and captures its window. +# reference/shot.sh [WxH] [app args...] +set -e +OUT=$1; SIZE=${2:-1200x760}; shift 2 || true +W0=${SIZE%x*}; H0=${SIZE#*x} +cd "$(dirname "$0")/.." +export DISPLAY=${DISPLAY:-:99} XDG_RUNTIME_DIR=${XDG_RUNTIME_DIR:-/tmp/xdg}; mkdir -p -m 700 "$XDG_RUNTIME_DIR" +pgrep -x Xvfb >/dev/null || { Xvfb "$DISPLAY" -screen 0 2400x1800x24 >/tmp/xvfb.log 2>&1 & sleep 1; } +cargo build -q ${PROFILE:+--profile $PROFILE} 2>&1 | grep -E "^error" -A20 && exit 1 || true +BIN=target/${PROFILE:-debug}/vector-gpui; [ "$PROFILE" = dev ] && BIN=target/debug/vector-gpui +TZ=UTC "$BIN" --size "$SIZE" "$@" >/tmp/vector-gpui.log 2>&1 & PID=$! +until WID=$(xdotool search --pid $PID 2>/dev/null | tail -1) && [ -n "$WID" ]; do + kill -0 $PID 2>/dev/null || { grep -m1 -A2 panicked /tmp/vector-gpui.log; exit 1; }; sleep 0.1 +done +sleep 0.5 +# Xvfb drops the frame presented before the window maps; a resize forces another. +xdotool windowsize "$WID" $((W0 + 1)) "$H0"; sleep 0.3; xdotool windowsize "$WID" "$W0" "$H0"; sleep 0.8 +# ACT: optional xdotool steps to drive the app before the capture, with $WID set. +[ -n "$ACT" ] && { eval "$ACT"; sleep 0.6; } +eval "$(xdotool getwindowgeometry --shell "$WID")" +import -window root -crop "${WIDTH}x${HEIGHT}+${X}+${Y}" +repage "$OUT" +kill $PID +echo "$OUT ${WIDTH}x${HEIGHT}" diff --git a/crates/vector-gpui/reference/tap.xdc b/crates/vector-gpui/reference/tap.xdc new file mode 100644 index 000000000..6fd8f779e Binary files /dev/null and b/crates/vector-gpui/reference/tap.xdc differ diff --git a/crates/vector-gpui/reference/timer-badge.js b/crates/vector-gpui/reference/timer-badge.js new file mode 100644 index 000000000..a59e3d5bd --- /dev/null +++ b/crates/vector-gpui/reference/timer-badge.js @@ -0,0 +1,11 @@ +// Opens OPEN with a Self-Destruct Timer on and a draft typed, so Send wears its badge. +(async () => { + openChat(window.__OPEN_NAME__); + await new Promise((r) => setTimeout(r, 800)); + const t = domChatMessageInput; + t.focus(); + t.value = 'see you soon'; + t.selectionStart = t.selectionEnd = t.value.length; + t.dispatchEvent(new Event('input', { bubbles: true })); + updateSelfDestructIndicator(strOpenChat); +})(); diff --git a/crates/vector-gpui/reference/type-composer.js b/crates/vector-gpui/reference/type-composer.js new file mode 100644 index 000000000..1905414b8 --- /dev/null +++ b/crates/vector-gpui/reference/type-composer.js @@ -0,0 +1,11 @@ +// Opens the first chat and types window.__TYPE__ into the composer, as a user would. +(async () => { + window.__BADGES__ = { vector: true, vector_2026: true, tier: 3, bug_hunter: 0 }; + document.querySelector('.chatlist-contact')?.click(); + await new Promise((r) => setTimeout(r, 800)); + const input = domChatMessageInput; + input.focus(); + input.value = window.__TYPE__ || ''; + input.setSelectionRange(input.value.length, input.value.length); + input.dispatchEvent(new Event('input', { bubbles: true })); +})(); diff --git a/crates/vector-gpui/reference/type-in-community.js b/crates/vector-gpui/reference/type-in-community.js new file mode 100644 index 000000000..bcec2256f --- /dev/null +++ b/crates/vector-gpui/reference/type-in-community.js @@ -0,0 +1,11 @@ +// Opens the fixture community, then types window.__TYPE__ into its composer. +(() => { + setTimeout(() => [...document.querySelectorAll('*')].find((e) => e.children.length === 0 && e.textContent.trim() === 'Vector Devs')?.closest('[class*="rail"], div')?.click(), 400); + setTimeout(() => { + const t = domChatMessageInput; + t.focus(); + t.value = window.__TYPE__ || '@'; + t.selectionStart = t.selectionEnd = t.value.length; + t.dispatchEvent(new Event('input', { bubbles: true })); + }, 1800); +})(); diff --git a/crates/vector-gpui/reference/type-shortcode.js b/crates/vector-gpui/reference/type-shortcode.js new file mode 100644 index 000000000..9be7b383d --- /dev/null +++ b/crates/vector-gpui/reference/type-shortcode.js @@ -0,0 +1,13 @@ +// Opens the chat named by OPEN, then types a :shortcode into its composer as a user would. +(() => { + const want = window.__OPEN_NAME__; + const rows = [...document.querySelectorAll('.chatlist-contact')]; + (want ? rows.find((r) => r.textContent.trim().toLowerCase().startsWith(want)) : rows[0])?.click(); + setTimeout(() => { + const t = domChatMessageInput; + t.focus(); + t.value = window.__TYPE__ || 'hey :sm'; + t.selectionStart = t.selectionEnd = t.value.length; + t.dispatchEvent(new Event('input', { bubbles: true })); + }, 1200); +})(); diff --git a/crates/vector-gpui/reference/wallpaper-edit.js b/crates/vector-gpui/reference/wallpaper-edit.js new file mode 100644 index 000000000..7b443a298 --- /dev/null +++ b/crates/vector-gpui/reference/wallpaper-edit.js @@ -0,0 +1,7 @@ +// Opens OPEN with a picked wallpaper staged: the edit bar over the header, the sliders above the composer. +(async () => { + const rows = [...document.querySelectorAll('.chatlist-contact')]; + rows.find((r) => r.textContent.trim().toLowerCase().startsWith(window.__OPEN_NAME__))?.click(); + await new Promise((r) => setTimeout(r, 800)); + await applyWallpaperPreview(strOpenChat, { path: 'media/portrait.png', was_animated: false, recommended_dim: 60 }); +})(); diff --git a/crates/vector-gpui/reference/xdc/icon.png b/crates/vector-gpui/reference/xdc/icon.png new file mode 100644 index 000000000..4aec0351c Binary files /dev/null and b/crates/vector-gpui/reference/xdc/icon.png differ diff --git a/crates/vector-gpui/reference/xdc/index.html b/crates/vector-gpui/reference/xdc/index.html new file mode 100644 index 000000000..b1d58fff5 --- /dev/null +++ b/crates/vector-gpui/reference/xdc/index.html @@ -0,0 +1,14 @@ + + + +

0

+ diff --git a/crates/vector-gpui/reference/xdc/manifest.toml b/crates/vector-gpui/reference/xdc/manifest.toml new file mode 100644 index 000000000..cd94cc826 --- /dev/null +++ b/crates/vector-gpui/reference/xdc/manifest.toml @@ -0,0 +1 @@ +name = "Tap Counter" diff --git a/crates/vector-gpui/scripts/bundle-appimage.sh b/crates/vector-gpui/scripts/bundle-appimage.sh new file mode 100755 index 000000000..9b1508f98 --- /dev/null +++ b/crates/vector-gpui/scripts/bundle-appimage.sh @@ -0,0 +1,67 @@ +#!/usr/bin/env bash +# The Linux updater bundle, built the way the Tauri bundler builds Vector's AppImage +# (linuxdeploy + its GTK plugin, WebKitGTK's helper processes copied in for Mini Apps). +# scripts/bundle-appimage.sh +# VECTOR_RELEASE=1 names it as a release's (Vector_…); otherwise Vector-GPUI_…. +set -euo pipefail + +bins=$(realpath "$1") +out=$(realpath -m "$2") +here=$(cd "$(dirname "$0")/.." && pwd) +repo=$(cd "$here/../.." && pwd) +version=$(sed -n 's/^version = "\(.*\)"/\1/p' "$here/Cargo.toml" | head -1) +prefix=$([ "${VECTOR_RELEASE:-}" = 1 ] && echo Vector || echo Vector-GPUI) + +case "$(uname -m)" in + x86_64) arch=x86_64; name=amd64; multiarch=x86_64-linux-gnu ;; + aarch64) arch=aarch64; name=aarch64; multiarch=aarch64-linux-gnu ;; + *) echo "unsupported arch $(uname -m)"; exit 1 ;; +esac + +tools="${TOOLS:-$out/.tools}" +mkdir -p "$tools" "$out" +fetch() { [ -s "$2" ] || curl -fsSL --retry 3 -o "$2" "$1"; chmod +x "$2"; } +fetch "https://github.com/tauri-apps/binary-releases/releases/download/apprun-old/AppRun-$arch" "$tools/AppRun-$arch" +fetch "https://github.com/tauri-apps/binary-releases/releases/download/linuxdeploy/linuxdeploy-$arch.AppImage" "$tools/linuxdeploy-$arch.AppImage" +fetch "https://raw.githubusercontent.com/linuxdeploy/linuxdeploy-plugin-gtk/master/linuxdeploy-plugin-gtk.sh" "$tools/linuxdeploy-plugin-gtk.sh" +# Keeps AppImage desktop integration tools from taking linuxdeploy for an app. +dd if=/dev/zero bs=1 count=3 seek=8 conv=notrunc of="$tools/linuxdeploy-$arch.AppImage" 2>/dev/null + +app="$out/Vector.AppDir" +rm -rf "$app" +mkdir -p "$app/usr/bin" "$app/usr/share/applications" "$app/usr/share/icons/hicolor/256x256/apps" +install -m755 "$bins/vector-gpui" "$bins/vector-gpui-miniapp" "$app/usr/bin/" +install -m644 "$repo/src-tauri/icons/128x128@2x.png" "$app/usr/share/icons/hicolor/256x256/apps/vector-gpui.png" +cat > "$app/usr/share/applications/vector-gpui.desktop" < +# VECTOR_RELEASE=1 names the files as a release's (Vector_…); otherwise Vector-GPUI_…. +# rpmbuild is optional: without it only the deb is made. +set -euo pipefail + +bins=$(realpath "$1") +out=$(realpath -m "$2") +here=$(cd "$(dirname "$0")/.." && pwd) +repo=$(cd "$here/../.." && pwd) +version=$(sed -n 's/^version = "\(.*\)"/\1/p' "$here/Cargo.toml" | head -1) +# A preview (0.6.0-1) sorts before its release in both: dpkg and rpm read `~` that way. +pkgversion=${version//-/\~} +prefix=$([ "${VECTOR_RELEASE:-}" = 1 ] && echo Vector || echo Vector-GPUI) + +case "$(uname -m)" in + x86_64) debarch=amd64 rpmarch=x86_64 ;; + aarch64) debarch=arm64 rpmarch=aarch64 ;; + *) echo "unsupported arch $(uname -m)" >&2; exit 1 ;; +esac + +# Runtime packages by soname, as Ubuntu 22.04 (the build host, so the floor) names them; later +# releases' t64 packages provide these names. +depends_of() { + case "$1" in + libc.so.6|libm.so.6|libdl.so.2|libpthread.so.0|librt.so.1|ld-linux-*.so.*) echo libc6 ;; + libgcc_s.so.1) echo libgcc-s1 ;; + libstdc++.so.6) echo libstdc++6 ;; + libxkbcommon.so.0) echo libxkbcommon0 ;; + libxkbcommon-x11.so.0) echo libxkbcommon-x11-0 ;; + libxcb.so.1) echo libxcb1 ;; + libX11.so.6) echo libx11-6 ;; + libX11-xcb.so.1) echo libx11-xcb1 ;; + libvulkan.so.1) echo libvulkan1 ;; + libasound.so.2) echo libasound2 ;; + libfontconfig.so.1) echo libfontconfig1 ;; + libfreetype.so.6) echo libfreetype6 ;; + libwayland-client.so.0) echo libwayland-client0 ;; + libwayland-cursor.so.0) echo libwayland-cursor0 ;; + libdbus-1.so.3) echo libdbus-1-3 ;; + libz.so.1) echo zlib1g ;; + libzstd.so.1) echo libzstd1 ;; + libssl.so.3|libcrypto.so.3) echo libssl3 ;; + libglib-2.0.so.0|libgobject-2.0.so.0|libgio-2.0.so.0|libgmodule-2.0.so.0) echo libglib2.0-0 ;; + libgtk-3.so.0|libgdk-3.so.0) echo libgtk-3-0 ;; + libpango-1.0.so.0|libpangocairo-1.0.so.0) echo libpango-1.0-0 ;; + libcairo.so.2) echo libcairo2 ;; + libgdk_pixbuf-2.0.so.0) echo libgdk-pixbuf-2.0-0 ;; + libwebkit2gtk-4.1.so.0) echo libwebkit2gtk-4.1-0 ;; + libjavascriptcoregtk-4.1.so.0) echo libjavascriptcoregtk-4.1-0 ;; + libsoup-3.0.so.0) echo libsoup-3.0-0 ;; + *) echo "no package known for $1: add it to depends_of in $0" >&2; return 1 ;; + esac +} + +depends=$(for b in vector-gpui vector-gpui-miniapp; do + readelf -d "$bins/$b" | sed -n 's/.*(NEEDED).*\[\(.*\)\]/\1/p' +done | sort -u | while read -r so; do depends_of "$so" || exit 1; done | sort -u | paste -sd, - | sed 's/,/, /g') + +stage=$(mktemp -d) +trap 'rm -rf "$stage"' EXIT +root="$stage/root" +install -Dm755 "$bins/vector-gpui" "$root/usr/lib/Vector/Vector" +install -Dm755 "$bins/vector-gpui-miniapp" "$root/usr/lib/Vector/vector-gpui-miniapp" +mkdir -p "$root/usr/bin" +ln -s ../lib/Vector/Vector "$root/usr/bin/Vector" +icons="$repo/src-tauri/icons" +install -Dm644 "$icons/32x32.png" "$root/usr/share/icons/hicolor/32x32/apps/Vector.png" +install -Dm644 "$icons/128x128.png" "$root/usr/share/icons/hicolor/128x128/apps/Vector.png" +install -Dm644 "$icons/128x128@2x.png" "$root/usr/share/icons/hicolor/256x256/apps/Vector.png" +install -Dm644 /dev/stdin "$root/usr/share/applications/Vector.desktop" < "$root/DEBIAN/control" </dev/null +rm -rf "$root/DEBIAN" +ls -l "$deb" + +if ! command -v rpmbuild >/dev/null; then + echo "rpmbuild not found: no rpm" >&2 + exit 0 +fi +mkdir -p "$stage/rpm"/{BUILD,RPMS,SPECS,SRPMS,SOURCES} +cat > "$stage/rpm/SPECS/vector.spec" < +# VECTOR_RELEASE=1 names it Vector, as the bundle that replaces the Tauri client; otherwise Vector GPUI. +set -euo pipefail + +bin="$1" +out="$2" +here="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +tauri="$here/../../src-tauri" +version=$(sed -n 's/^version = "\(.*\)"/\1/p' "$here/Cargo.toml" | head -1) +minos=$(sed -n 's/^MACOSX_DEPLOYMENT_TARGET = "\(.*\)"/\1/p' "$here/.cargo/config.toml") +if [ "${VECTOR_RELEASE:-}" = 1 ]; then + name="Vector" exe="Vector" prefix="Vector" +else + name="Vector GPUI" exe="vector-gpui" prefix="Vector-GPUI" +fi +app="$out/$name.app" + +rm -rf "$app" +mkdir -p "$app/Contents/MacOS" "$app/Contents/Resources" +cp "$bin" "$app/Contents/MacOS/$exe" +cp "$tauri/icons/icon.icns" "$app/Contents/Resources/icon.icns" + +# Tauri's identifier and URL scheme: an update in place keeps its data, notifications and links. +cat > "$app/Contents/Info.plist" < + + + + CFBundleIdentifierio.vectorapp + CFBundleName$name + CFBundleDisplayName$name + CFBundleExecutable$exe + CFBundleIconFileicon + CFBundlePackageTypeAPPL + CFBundleShortVersionString$version + CFBundleVersion$version + CFBundleInfoDictionaryVersion6.0 + LSMinimumSystemVersion$minos + NSHighResolutionCapable + LSApplicationCategoryTypepublic.app-category.social-networking + CFBundleURLTypes + + + CFBundleURLNameio.vectorapp + CFBundleURLSchemesvector + + + NSMicrophoneUsageDescriptionThis is required for sending Voice Messages as well as other voice activities, such as calls. + NSCameraUsageDescriptionThis is required for video calls. + NSDocumentsFolderUsageDescriptionThis is required to receive and save files. + + +PLIST + +codesign --force --sign - --entitlements "$tauri/Entitlements.plist" "$app" +codesign --verify --strict "$app" +ditto -c -k --keepParent "$app" "$out/$prefix-macOS.zip" +case "$(lipo -archs "$bin")" in + arm64) arch=aarch64 ;; + x86_64) arch=x64 ;; + *) echo "one architecture per bundle" >&2; exit 1 ;; +esac +# No AppleDouble ._ entries: the updater takes the first .app it unpacks. +COPYFILE_DISABLE=1 tar -C "$out" -czf "$out/${prefix}_$arch.app.tar.gz" "$name.app" +# The download for a first install: the app beside a link to drag it into. +dmg=$(mktemp -d) +mv "$app" "$dmg/" +ln -s /Applications "$dmg/Applications" +hdiutil create -quiet -volname "$name" -srcfolder "$dmg" -ov -format UDZO "$out/${prefix}_${version}_$arch.dmg" +rm -rf "$dmg" diff --git a/crates/vector-gpui/scripts/fdroid-build.sh b/crates/vector-gpui/scripts/fdroid-build.sh new file mode 100755 index 000000000..b70a7bf20 --- /dev/null +++ b/crates/vector-gpui/scripts/fdroid-build.sh @@ -0,0 +1,94 @@ +#!/usr/bin/env bash +# F-Droid build recipe for the GPUI client. +# +# One script for F-Droid's builder and for CI, so the published flavour and F-Droid's rebuild of +# it cannot drift (as scripts/fdroid-build.sh is for the Tauri client). Output is an UNSIGNED +# arm64 release APK of the `fdroid` feature: no in-app updater, and Gradle leaves out the +# embedded FCM distributor, so push is UnifiedPush through a distributor app. +# +# crates/vector-gpui/scripts/fdroid-build.sh prepare # network: toolchain, cargo fetch +# crates/vector-gpui/scripts/fdroid-build.sh build # cargo offline; Gradle resolves its own +set -euo pipefail +cd "$(dirname "$0")/../../.." + +export PATH="$HOME/.cargo/bin:$PATH" + +# Pinned here and in gpui-android.yaml: F-Droid's rebuild has to use the released flavour's rustc. +RUST_TOOLCHAIN=1.98.0 +export RUSTUP_TOOLCHAIN="$RUST_TOOLCHAIN" +TARGET=aarch64-linux-android + +prepare() { + rustup toolchain install "$RUST_TOOLCHAIN" --profile minimal --target "$TARGET" + # Every platform's crates: cargo resolves the whole lock even when building one target. + (cd crates/vector-gpui && cargo fetch --locked) +} + +build() { + : "${NDK_HOME:?NDK_HOME must point at the Android NDK}" + # A path dependency outside the workspace root is hashed by its absolute path into every + # mangled symbol, so the build always runs from one fixed directory. + local build_root="$HOME/vector-gpui-fdroid-build" src_tree="" + if [ "$(pwd -P)" != "$build_root" ]; then + src_tree=$(pwd -P) + rm -rf "$build_root" + mkdir -p "$build_root" + cp -a . "$build_root/" + cd "$build_root" + fi + export VECTOR_FDROID=1 + # Fat LTO over the whole client outgrows a 16 GB builder; the released flavour builds the same way. + export CARGO_PROFILE_RELEASE_LTO=thin + export CARGO_NET_OFFLINE=true + export ANDROID_NDK_HOME="$NDK_HOME" + # The NDK ships only llvm-* binutils; vendored C builds ask for a ranlib by its GNU name. + local ndk_bin + ndk_bin=$(ls -d "$NDK_HOME"/toolchains/llvm/prebuilt/*/bin | head -1) + export PATH="$ndk_bin:$PATH" + export RANLIB_aarch64_linux_android="$ndk_bin/llvm-ranlib" + export SOURCE_DATE_EPOCH="${SOURCE_DATE_EPOCH:-$(git log -1 --pretty=%ct)}" + # Reproducibility: no builder-specific paths in the library. Cargo canonicalises paths, so a + # checkout reached through a symlink bakes in the physical one: remap both spellings, and + # both spellings of HOME for the cargo caches. The std sources map to /rustc/, as a + # toolchain without rust-src embeds them. + local sysroot commit repo_logical repo_physical home_physical + sysroot=$(rustc --print sysroot) + commit=$(rustc -vV | sed -n 's/^commit-hash: //p') + repo_logical=$PWD + repo_physical=$(pwd -P) + home_physical=$(cd "$HOME" && pwd -P) + local -a remaps=( + "--remap-path-prefix=$repo_physical=/vector" + "--remap-path-prefix=$home_physical/.cargo/registry/src=/cargo/registry/src" + "--remap-path-prefix=$home_physical/.cargo/git/checkouts=/cargo/git/checkouts" + "--remap-path-prefix=$sysroot/lib/rustlib/src/rust=/rustc/$commit" + ) + if [ "$repo_logical" != "$repo_physical" ]; then + remaps+=("--remap-path-prefix=$repo_logical=/vector") + fi + if [ "$HOME" != "$home_physical" ]; then + remaps+=("--remap-path-prefix=$HOME/.cargo/registry/src=/cargo/registry/src" + "--remap-path-prefix=$HOME/.cargo/git/checkouts=/cargo/git/checkouts") + fi + export CARGO_ENCODED_RUSTFLAGS + CARGO_ENCODED_RUSTFLAGS=$(printf '%s\x1f' "${remaps[@]}") + CARGO_ENCODED_RUSTFLAGS="${CARGO_ENCODED_RUSTFLAGS%$'\x1f'}" + # C built through the cc crate embeds __FILE__ in its asserts. + export CFLAGS="-ffile-prefix-map=$repo_physical=/vector -ffile-prefix-map=$repo_logical=/vector" + export CXXFLAGS="$CFLAGS" + (cd crates/vector-gpui/android && + ./gradlew --no-daemon :app:assembleRelease -PvectorNdk="$(basename "$NDK_HOME")" -PvectorAbis=arm64-v8a) + local out=crates/vector-gpui/android/app/build/outputs/apk/release + ls -l "$out/" + if [ -n "$src_tree" ]; then + mkdir -p "$src_tree/$out" + cp -a "$out"/. "$src_tree/$out/" + fi +} + +case "${1:-all}" in + prepare) prepare ;; + build) build ;; + all) prepare; build ;; + *) echo "usage: $0 [prepare|build|all]" >&2; exit 2 ;; +esac diff --git a/crates/vector-gpui/scripts/installer.nsi b/crates/vector-gpui/scripts/installer.nsi new file mode 100644 index 000000000..9d5319479 --- /dev/null +++ b/crates/vector-gpui/scripts/installer.nsi @@ -0,0 +1,161 @@ +; Per-user installer that takes the Tauri client's place: its folder, exe name, shortcuts, +; uninstall entry and `vector://` handler (tauri-bundler's NSIS template, currentUser mode). +; /P installs with no pages, /R starts the app after; the in-app updater passes both. +; makensis -DSOURCE= -DICON= -DVERSION= -DOUTFILE= installer.nsi +Unicode true +!include "FileFunc.nsh" +!include "LogicLib.nsh" +!include "Win\COM.nsh" +!include "Win\Propkey.nsh" + +!define PRODUCTNAME "Vector" +!define MAINBINARYNAME "Vector" +!define BUNDLEID "io.vectorapp" +!define MANUFACTURER "vectorapp" +!define UNINSTKEY "Software\Microsoft\Windows\CurrentVersion\Uninstall\${PRODUCTNAME}" +!define MANUKEY "Software\${MANUFACTURER}" +!define MANUPRODUCTKEY "${MANUKEY}\${PRODUCTNAME}" +!define PLACEHOLDER "placeholder\${PRODUCTNAME}" + +Name "${PRODUCTNAME}" +OutFile "${OUTFILE}" +InstallDir "${PLACEHOLDER}" +RequestExecutionLevel user +SetCompressor /SOLID lzma +Icon "${ICON}" +UninstallIcon "${ICON}" + +Page directory +Page instfiles +UninstPage uninstConfirm +UninstPage instfiles + +Var Relaunch + +; The shell groups the window and its toasts under the identity the app registers at runtime. +!macro SetAppUserModelId shortcut + !insertmacro ComHlpr_CreateInProcInstance ${CLSID_ShellLink} ${IID_IShellLink} r0 "" + ${If} $0 P<> 0 + ${IUnknown::QueryInterface} $0 '("${IID_IPersistFile}",.r1)' + ${If} $1 P<> 0 + ${IPersistFile::Load} $1 '("${shortcut}", ${STGM_READWRITE})' + ${IUnknown::QueryInterface} $0 '("${IID_IPropertyStore}",.r2)' + ${If} $2 P<> 0 + System::Call 'Oleaut32::SysAllocString(w "${BUNDLEID}") i.r3' + System::Call '*${SYSSTRUCT_PROPERTYKEY}(${PKEY_AppUserModel_ID})p.r4' + System::Call '*${SYSSTRUCT_PROPVARIANT}(${VT_BSTR},,&i4 $3)p.r5' + ${IPropertyStore::SetValue} $2 '($4,$5)' + System::Call 'Oleaut32::SysFreeString($3)' + System::Free $4 + System::Free $5 + ${IPropertyStore::Commit} $2 "" + ${IUnknown::Release} $2 "" + ${IPersistFile::Save} $1 '("${shortcut}",1)' + ${EndIf} + ${IUnknown::Release} $1 "" + ${EndIf} + ${IUnknown::Release} $0 "" + ${EndIf} +!macroend + +Function .onInit + System::Call 'kernel32::SetErrorMode(i 0x8003)' + ${GetParameters} $0 + ClearErrors + ${GetOptions} $0 "/P" $1 + ${IfNot} ${Errors} + SetSilent silent + ${EndIf} + ClearErrors + ${GetOptions} $0 "/R" $1 + ${IfNot} ${Errors} + StrCpy $Relaunch 1 + ${EndIf} + ; No /D: wherever Vector already lives, else the Tauri default. + ${If} $INSTDIR == "${PLACEHOLDER}" + ReadRegStr $1 HKCU "${MANUPRODUCTKEY}" "" + ${If} $1 != "" + StrCpy $INSTDIR $1 + ${Else} + StrCpy $INSTDIR "$LOCALAPPDATA\${PRODUCTNAME}" + ${EndIf} + ${EndIf} +FunctionEnd + +Section + SetOutPath "$INSTDIR" + ; The copy being replaced may still be closing: its exe stays locked until it has. + StrCpy $2 0 + retry: + ClearErrors + Delete "$INSTDIR\${MAINBINARYNAME}.exe" + ${If} ${Errors} + ${AndIf} $2 < 100 + IntOp $2 $2 + 1 + Sleep 200 + Goto retry + ${EndIf} + File "/oname=${MAINBINARYNAME}.exe" "${SOURCE}" + WriteUninstaller "$INSTDIR\uninstall.exe" + ; The Tauri client's sounds: this build carries them in its exe. + Delete "$INSTDIR\resources\sounds\notif-prelude.mp3" + Delete "$INSTDIR\resources\sounds\notif-techno.mp3" + Delete "$INSTDIR\resources\sounds\claim-badge.mp3" + RMDir "$INSTDIR\resources\sounds" + RMDir "$INSTDIR\resources" + + WriteRegStr HKCU "${MANUPRODUCTKEY}" "" $INSTDIR + WriteRegStr HKCU "${UNINSTKEY}" "" $INSTDIR + WriteRegStr HKCU "${UNINSTKEY}" "MainBinaryName" "${MAINBINARYNAME}.exe" + WriteRegStr HKCU "${UNINSTKEY}" "DisplayName" "${PRODUCTNAME}" + WriteRegStr HKCU "${UNINSTKEY}" "DisplayIcon" '"$INSTDIR\${MAINBINARYNAME}.exe"' + WriteRegStr HKCU "${UNINSTKEY}" "DisplayVersion" "${VERSION}" + WriteRegStr HKCU "${UNINSTKEY}" "Publisher" "${MANUFACTURER}" + WriteRegStr HKCU "${UNINSTKEY}" "InstallLocation" '"$INSTDIR"' + WriteRegStr HKCU "${UNINSTKEY}" "UninstallString" '"$INSTDIR\uninstall.exe"' + WriteRegDWORD HKCU "${UNINSTKEY}" "NoModify" 1 + WriteRegDWORD HKCU "${UNINSTKEY}" "NoRepair" 1 + ${GetSize} "$INSTDIR" "/S=0K" $0 $1 $3 + IntFmt $0 "0x%08X" $0 + WriteRegDWORD HKCU "${UNINSTKEY}" "EstimatedSize" "$0" + + WriteRegStr HKCU "Software\Classes\vector" "URL Protocol" "" + WriteRegStr HKCU "Software\Classes\vector" "" "URL:${BUNDLEID} protocol" + WriteRegStr HKCU "Software\Classes\vector\DefaultIcon" "" '"$INSTDIR\${MAINBINARYNAME}.exe",0' + WriteRegStr HKCU "Software\Classes\vector\shell\open\command" "" '"$INSTDIR\${MAINBINARYNAME}.exe" "%1"' + + ; An update keeps the shortcuts the user has (same target); a first install makes them. + ${IfNot} ${FileExists} "$SMPROGRAMS\${PRODUCTNAME}.lnk" + CreateShortcut "$SMPROGRAMS\${PRODUCTNAME}.lnk" "$INSTDIR\${MAINBINARYNAME}.exe" + !insertmacro SetAppUserModelId "$SMPROGRAMS\${PRODUCTNAME}.lnk" + ${EndIf} + ReadRegStr $1 HKCU "${UNINSTKEY}" "Installed" + ${If} $1 == "" + ${AndIfNot} ${FileExists} "$DESKTOP\${PRODUCTNAME}.lnk" + CreateShortcut "$DESKTOP\${PRODUCTNAME}.lnk" "$INSTDIR\${MAINBINARYNAME}.exe" + !insertmacro SetAppUserModelId "$DESKTOP\${PRODUCTNAME}.lnk" + ${EndIf} + WriteRegStr HKCU "${UNINSTKEY}" "Installed" "1" + + ${If} $Relaunch == 1 + Exec '"$INSTDIR\${MAINBINARYNAME}.exe"' + ${EndIf} +SectionEnd + +Section "Uninstall" + Delete "$INSTDIR\${MAINBINARYNAME}.exe" + Delete "$INSTDIR\uninstall.exe" + RMDir "$INSTDIR" + Delete "$SMPROGRAMS\${PRODUCTNAME}.lnk" + Delete "$DESKTOP\${PRODUCTNAME}.lnk" + ReadRegStr $0 HKCU "Software\Classes\vector\shell\open\command" "" + StrCmp $0 '"$INSTDIR\${MAINBINARYNAME}.exe" "%1"' 0 +2 + DeleteRegKey HKCU "Software\Classes\vector" + ReadRegStr $0 HKCU "Software\Classes\AppUserModelId\${BUNDLEID}" "CustomActivator" + StrCmp $0 "" +2 + DeleteRegKey HKCU "Software\Classes\CLSID\$0" + DeleteRegKey HKCU "Software\Classes\AppUserModelId\${BUNDLEID}" + DeleteRegKey HKCU "${UNINSTKEY}" + DeleteRegKey HKCU "${MANUPRODUCTKEY}" + DeleteRegKey /ifempty HKCU "${MANUKEY}" +SectionEnd diff --git a/crates/vector-gpui/scripts/installer.wxs b/crates/vector-gpui/scripts/installer.wxs new file mode 100644 index 000000000..856a3fcf8 --- /dev/null +++ b/crates/vector-gpui/scripts/installer.wxs @@ -0,0 +1,142 @@ + + + + + + + + + + + + + + + + + + + + Installed AND NOT UPGRADINGPRODUCTCODE + + + + + + + + + + + + + + + + + + + + + + + + WIXUI_EXITDIALOGOPTIONALCHECKBOX = 1 and NOT Installed + + 1 + 1 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + AUTOLAUNCHAPP AND NOT Installed + + + + + diff --git a/crates/vector-gpui/scripts/macos-availability.py b/crates/vector-gpui/scripts/macos-availability.py new file mode 100755 index 000000000..2708dfad5 --- /dev/null +++ b/crates/vector-gpui/scripts/macos-availability.py @@ -0,0 +1,283 @@ +#!/usr/bin/env python3 +"""What a macOS build of the client reaches that is newer than its floor (MACOSX_DEPLOYMENT_TARGET in +.cargo/config.toml), judged by the SDK headers' availability macros: strongly linked frameworks and +C symbols (the app would not open), and Objective-C classes and selectors (a crash when called +unguarded). Only the libraries the binary loads, and what they re-export, are read. Classes and +selectors are matched by name in the binary, so each is a lead to check, with the source lines that +spell it. + scripts/macos-availability.py [--floor 12.0] [--deps] [--partial] +--deps also searches the dependencies' sources; --partial lists selectors only some of whose +declarations are newer than the floor.""" +import argparse, json, os, re, subprocess, sys +from collections import defaultdict + +here = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +repo = os.path.dirname(os.path.dirname(here)) + +ap = argparse.ArgumentParser() +ap.add_argument("binary") +ap.add_argument("--floor") +ap.add_argument("--deps", action="store_true") +ap.add_argument("--partial", action="store_true") +args = ap.parse_args() + +def floor_of_config(): + with open(os.path.join(here, ".cargo", "config.toml")) as f: + return re.search(r'^MACOSX_DEPLOYMENT_TARGET = "(.*)"', f.read(), re.M).group(1) + +def vt(s): + return tuple(int(x) for x in re.split(r"[._]", s) if x) + (0,) * 3 + +floor = vt(args.floor or floor_of_config())[:3] +sdk = subprocess.check_output(["xcrun", "--sdk", "macosx", "--show-sdk-path"], text=True).strip() +blob = open(args.binary, "rb").read() + +strong, weak = [], [] +lines = subprocess.check_output(["otool", "-l", args.binary], text=True).splitlines() +for i, l in enumerate(lines): + m = re.match(r"\s*cmd (LC_LOAD_DYLIB|LC_LOAD_WEAK_DYLIB)$", l) + if m: + name = re.match(r"\s*name (\S+)", lines[i + 2]).group(1) + (weak if m.group(1).endswith("WEAK_DYLIB") else strong).append(name) + +imports = {} # C symbol -> (weak?, library it binds from); a weakly loaded library makes its symbols weak +weak_libs = {os.path.basename(w).split(".")[0] for w in weak} +for l in subprocess.check_output(["nm", "-m", "-u", args.binary], text=True).splitlines(): + m = re.match(r"\s*\(undefined\) (weak )?external (\S+)(?: \(from (\S+)\))?", l) + if m: + imports[m.group(2).lstrip("_")] = (bool(m.group(1)) or m.group(3) in weak_libs, m.group(3)) +class_imports = {s[len("OBJC_CLASS_$_"):] for s in imports if s.startswith("OBJC_CLASS_$_")} + +root = os.path.join(sdk, "System", "Library", "Frameworks") + +def reexports(fw): + """Frameworks whose symbols `fw` re-exports, from its text stub in the SDK.""" + out = set() + for dirpath, _, files in os.walk(os.path.join(root, fw + ".framework")): + for f in files: + if f == fw + ".tbd": + text = open(os.path.join(dirpath, f), errors="replace").read() + for section in re.findall(r"^reexported-libraries:\n((?:[ -].*\n)*)", text, re.M): + out |= set(re.findall(r"(\w+)\.framework", section)) + return out + +def closure(names): + seen, todo = set(), list(names) + while todo: + fw = todo.pop() + if fw not in seen: + seen.add(fw) + todo += reexports(fw) + return seen + +loaded = {re.findall(r"(\w+)\.framework", p)[-1] for p in strong + weak if ".framework/" in p} +linked = closure(loaded) +lib_scope = {} +def scope_of(lib): + if lib not in lib_scope: + lib_scope[lib] = {"libSystem"} if lib and lib.startswith("libSystem") else closure({lib} if lib else set()) + return lib_scope[lib] + +OLD = [ + r"NS_(?:CLASS_)?AVAILABLE(?:_MAC)?\(\s*(\d+_\d+)", + r"NS_(?:CLASS_)?DEPRECATED(?:_MAC)?\(\s*(\d+_\d+)", + r"__OSX_AVAILABLE_(?:STARTING|BUT_DEPRECATED)\(\s*__MAC_(\d+_\d+)", + r"AVAILABLE_MAC_OS_X_VERSION_(\d+_\d+)_AND_LATER", + r"CF_(?:AVAILABLE|DEPRECATED)(?:_MAC)?\(\s*(\d+_\d+)", + r"__OSX_AVAILABLE\(\s*(\d+\.\d+)", + r"CG_AVAILABLE_(?:STARTING|BUT_DEPRECATED)\(\s*(\d+\.\d+)", +] +OFF_MAC = re.compile(r"API_UNAVAILABLE\([^)]*\bmacos\b|__OSX_UNAVAILABLE|NS_UNAVAILABLE_MAC|__API_UNAVAILABLE\([^)]*\bmacos\b") +AVAIL = re.compile(r"\bmacosx?\s*\(\s*(\d+(?:[._]\d+){0,2})|" + "|".join(OLD)) + +def version_in(text): + m = AVAIL.search(text) + return vt(next(g for g in m.groups() if g))[:3] if m else None + +def strip_parens(s): + while True: + t = re.sub(r"\([^()]*\)", " ", s) + if t == s: + return s + s = t + +classes = {} # class -> version +selectors = defaultdict(list) # selector -> [(version or None, container)] +c_decls = defaultdict(list) # imported C symbol -> [(version or None, framework)] +framework_min = {} # framework -> lowest annotated version + +def record_statement(stmt, container, region, fw): + if OFF_MAC.search(stmt) or (container and container[2] == "off"): + return + v = version_in(stmt) or (container and container[1]) or region + if v: + framework_min[fw] = min(framework_min.get(fw, v), v) + name = container[0] if container else None + if container and container[2] == "protocol" and stmt.startswith(("-", "+", "@property")): + return + if stmt.startswith(("-", "+")): + body = strip_parens(stmt[1:]) + keys = re.findall(r"(\w+)\s*:", body) + sel = "".join(k + ":" for k in keys) if keys else (re.match(r"\s*(\w+)", body) or [None, None])[1] + if sel: + selectors[sel].append((v, name)) + elif stmt.startswith("@property"): + attrs = re.match(r"@property\s*\(([^)]*)\)", stmt) + attrs = attrs.group(1) if attrs else "" + idents = [w for w in re.findall(r"[A-Za-z_]\w*", strip_parens(stmt[9:])) if not re.fullmatch(r"[A-Z0-9_]+", w)] + if not idents: + return + prop = idents[-1] + getter = re.search(r"getter\s*=\s*(\w+)", attrs) + selectors[getter.group(1) if getter else prop].append((v, name)) + if "readonly" not in attrs: + setter = re.search(r"setter\s*=\s*(\w+:)", attrs) + selectors[setter.group(1) if setter else "set" + prop[0].upper() + prop[1:] + ":"].append((v, name)) + else: + name = declared_name(stmt) + if name in imports: + c_decls[name].append((version_in(stmt) or region, fw)) + +MACRO_CALL = re.compile(r"\b[A-Z_][A-Z0-9_]*\s*\(") + +def declared_name(stmt): + """The symbol a C declaration exports: none for inline bodies, types and macros.""" + if re.match(r"(typedef|struct|enum|union)\b", stmt) or re.search(r"\b(static|inline|__inline__?)\b", stmt): + return None + out, i = [], 0 + while (m := MACRO_CALL.search(stmt, i)): + out.append(stmt[i:m.start()]) + depth, j = 0, m.end() - 1 + while j < len(stmt): + depth += {"(": 1, ")": -1}.get(stmt[j], 0) + if depth == 0: + break + j += 1 + i = j + 1 + s = "".join(out) + stmt[i:] + m = re.search(r"\(\s*\*\s*(\w+)\s*\)", s) or re.search(r"([A-Za-z_]\w*)\s*\(", s) + if m: + return m.group(1) + idents = re.findall(r"[A-Za-z_]\w*", s.split("=")[0].split("[")[0]) + return idents[-1] if idents else None + +def parse_header(path, fw): + try: + text = open(path, errors="replace").read() + except OSError: + return + text = re.sub(r"/\*.*?\*/", " ", text, flags=re.S) + text = re.sub(r"//[^\n]*", "", text) + container, regions, pending = None, [], "" + for raw in text.splitlines(): + s = raw.strip() + if not s or s.startswith("#"): + continue + m = re.match(r"API_AVAILABLE_BEGIN\s*\((.*)\)", s) + if m: + regions.append(version_in(m.group(1))) + continue + if s.startswith("API_AVAILABLE_END"): + regions and regions.pop() + continue + region = next((r for r in reversed(regions) if r), None) + if s.startswith("@end"): + container, pending = None, "" + continue + m = re.match(r"@(interface|protocol)\s+(\w+)(\s*\()?", s) + if m and not s.endswith(";"): + v = version_in(pending + " " + s) or region + kind = "off" if OFF_MAC.search(pending + " " + s) else m.group(1) + container = (m.group(2), v, kind) + if kind == "interface" and not m.group(3): + classes[m.group(2)] = v + pending = "" + continue + # A method or property starts its own statement; its availability follows it. + pending = s if s.startswith(("-", "+", "@property")) else pending + " " + s + if pending.rstrip().endswith((";", "}")): + record_statement(pending.strip(), container, region, fw) + pending = "" + +# Only what the binary loads can bind or answer at run time. +for dirpath, dirnames, files in os.walk(root): + if os.path.basename(dirpath) != "Headers": + continue + fw = re.findall(r"(\w+)\.framework", dirpath)[-1] + if fw not in linked: + continue + for f in files: + if f.endswith(".h"): + parse_header(os.path.join(dirpath, f), fw) +if any(os.path.basename(p).startswith("libSystem") for p in strong): + for dirpath, dirnames, files in os.walk(os.path.join(sdk, "usr", "include")): + for f in files: + if f.endswith(".h"): + parse_header(os.path.join(dirpath, f), "libSystem") + +def newer(v): + return v is not None and v > floor + +def fmt(v): + return ".".join(map(str, v[:2] if v[2] == 0 else v)) + +src_dirs = [os.path.join(here, d) for d in ("src", "media/src", "vendor")] + [os.path.join(repo, "src-tauri", "src")] +if args.deps: + meta = json.loads(subprocess.check_output( + ["cargo", "metadata", "--format-version", "1", "--filter-platform", "x86_64-apple-darwin"], cwd=here)) + skip = re.compile(r"^(objc2|block2|dispatch2|objc-sys|core-foundation|core-graphics|core-text|core-video|cocoa|icrate|coreaudio-sys|security-framework-sys|io-kit-sys)") + src_dirs += [os.path.dirname(p["manifest_path"]) for p in meta["packages"] + if p["source"] and not skip.match(p["name"])] + +def leads(rust_name, call=False): + # A selector is a method objc2 names after it: a call or a definition, not the bare word. + pattern = ["-E", rf"(\.|fn ){rust_name}\(" if call else rf"\b{rust_name}\b"] + out = subprocess.run(["grep", "-rn", "--include=*.rs"] + pattern + src_dirs, + capture_output=True, text=True).stdout.splitlines() + return [l.replace(repo + "/", "")[:160] for l in out if "/target/" not in l][:4] + +problems = 0 +print(f"floor macOS {fmt(floor)}, SDK {os.path.basename(sdk)}") +print("\n== Frameworks linked strongly whose API is all newer than the floor (the app will not open)") +for path in strong: + fw = re.findall(r"(\w+)\.framework", path) + if fw and newer(framework_min.get(fw[-1])): + problems += 1 + print(f" {fw[-1]} (from {fmt(framework_min[fw[-1]])})") +print(" weak: " + ", ".join(re.findall(r"(\w+)\.framework", " ".join(weak))) if weak else " weak: none") + +print("\n== C symbols bound strongly that are newer than the floor (the app will not open)") +# Newer only when every declaration in the library it binds from is: one without a macro is old. +for sym, (is_weak, lib) in sorted(imports.items()): + vs = [v for v, fw in c_decls.get(sym, []) if fw in scope_of(lib)] + if not is_weak and vs and all(newer(v) for v in vs): + problems += 1 + print(f" {sym} (macOS {fmt(min(vs))}, from {lib})") +for cls in sorted(class_imports): + if newer(classes.get(cls)) and not imports["OBJC_CLASS_$_" + cls][0]: + problems += 1 + print(f" class {cls} (macOS {fmt(classes[cls])})") + +print("\n== Classes newer than the floor that the binary names") +for cls, v in sorted(classes.items()): + if newer(v) and (cls.encode() + b"\0") in blob: + problems += 1 + print(f" {cls} (macOS {fmt(v)})") + for l in leads(cls): + print(" " + l) + +print("\n== Selectors newer than the floor that the binary names") +for sel, decls in sorted(selectors.items()): + vs = [d[0] for d in decls] + if not any(newer(v) for v in vs) or (sel.encode() + b"\0") not in blob: + continue + every = all(newer(v) for v in vs) + if not every and not args.partial: + continue + problems += every + owners = sorted({f"{d[1]} {fmt(d[0])}" for d in decls if newer(d[0])})[:4] + print(f" {sel}{'' if every else ' (some declarations)'}: {', '.join(owners)}") + for l in leads(sel.rstrip(":").replace(":", "_"), call=True): + print(" " + l) + +print(f"\n{problems} to look at") diff --git a/crates/vector-gpui/scripts/onscreen.py b/crates/vector-gpui/scripts/onscreen.py new file mode 100644 index 000000000..a0cc24259 --- /dev/null +++ b/crates/vector-gpui/scripts/onscreen.py @@ -0,0 +1,337 @@ +#!/usr/bin/env python3 +"""On-screen regression checks for a devctl build, driven through `dev:` commands on an X display. + + cargo build --no-default-features --features tor,i2p,video,devctl --bin vector-gpui + DISPLAY=:99 python3 scripts/onscreen.py [--bin PATH] [--fixtures FILE] [--only NAME] [--size WxH] [--lang TAG] [--update] + +Each check opens a screen from the fixtures and reads the app's own counters: a screen at rest must +draw nothing, hover and toast fades must end, a menu must close on Escape and fit the window when +opened in a corner, a chat at its newest message must follow arrivals while one scrolled up holds +still, a window in the background must stop presenting, and memory at rest must stay near the +recorded baseline (`--update` records it). Linux needs `xdotool` for focus and `xterm` for the background check; macOS brings Finder +forward for it. +""" +import argparse, json, os, shutil, subprocess, sys, tempfile, time + +HERE = os.path.dirname(os.path.abspath(__file__)) +CRATE = os.path.dirname(HERE) +ANSWER = os.path.join(tempfile.gettempdir(), "vector-devctl.json") +BASELINE = os.path.join(CRATE, "reference", "onscreen-baseline.json") +# The app's own data dir: without one a devctl build would hand `dev:` to a running Vector. +# Short, as a Unix socket path on macOS caps at 104 bytes. +DATA = os.path.join(tempfile.gettempdir(), "vfx-onscreen") +# Memory at rest may grow this much over the baseline before the check fails. +MEM_SLACK = 1.15 + +ap = argparse.ArgumentParser() +ap.add_argument("--bin", default=os.path.join(CRATE, "target", "debug", "vector-gpui")) +ap.add_argument("--fixtures", default=os.path.join(CRATE, "reference", "fixtures.json")) +ap.add_argument("--only") +ap.add_argument("--update", action="store_true") +ap.add_argument("--lang", help="a language to switch to after boot, such as ar-XB for a mirrored layout") +ap.add_argument("--size", default="1000x760", help="window size; the memory baseline is kept per size") +args = ap.parse_args() +W, H = (int(v) for v in args.size.split("x")) +env = dict(os.environ, TZ="UTC") +results = [] +MAC = sys.platform == "darwin" + + +def dev(cmd, wait=True): + """Sends `dev:`; with `wait`, returns the JSON the app writes back.""" + if wait: + try: + os.remove(ANSWER) + except OSError: + pass + subprocess.run([args.bin, "--data-dir", DATA, "dev:" + cmd], env=env, capture_output=True, timeout=30) + if not wait: + return None + for _ in range(100): + try: + with open(ANSWER) as f: + return json.load(f) + except (OSError, ValueError): + time.sleep(0.05) + raise RuntimeError(f"no answer to dev:{cmd}") + + +def frames(): + return dev("state")["frames"] + + +def at_rest(settle=2.5, span=3.0): + """Draws and presents over `span` seconds, once `settle` has let the last change land.""" + time.sleep(settle) + frames() + time.sleep(span) + f = frames() + return f["draws"], f["presents"] + + +def check(name, ok, detail=""): + results.append((name, ok, detail)) + print(f"{'PASS' if ok else 'FAIL'} {name} {detail}", flush=True) + + +def window_of(pid): + """The X window `pid` opened. macOS needs no handle: the app raises itself.""" + if MAC: + time.sleep(4) + return "app" + for _ in range(200): + r = subprocess.run(["xdotool", "search", "--pid", str(pid)], env=env, capture_output=True, text=True) + if r.stdout.split(): + return r.stdout.split()[-1] + time.sleep(0.1) + return None + + +def focus(wid): + if MAC: + dev("raise", wait=False) + elif wid: + subprocess.run(["xdotool", "windowfocus", wid], env=env, capture_output=True) + time.sleep(0.5) + + +def a11y(): + """The accessibility tree, its bounds in window points.""" + tree = dev("a11y") + scale = (tree.get("frame") or {}).get("scale_factor") or 1 + for n in tree.get("nodes", {}).values(): + if n.get("bounds"): + n["bounds"] = [v / scale for v in n["bounds"]] + return tree + + +def menus(tree): + """Every menu and menu item in an accessibility tree.""" + return [n for n in tree.get("nodes", {}).values() if "menu" in n.get("aria", {}).get("role", "").lower()] + + +def wanted(name): + return not args.only or args.only in name + + +def inside(node): + """Whether a node has bounds and they lie within the window.""" + b = node.get("bounds") + return b is not None and b[0] >= -0.5 and b[1] >= -0.5 and b[2] <= W + 0.5 and b[3] <= H + 0.5 + + +def last_text(): + """A point on the lowest text above the composer at the timeline's far side (right, or left + when mirrored), or None.""" + rtl = args.lang and args.lang.split("-")[0] in ("ar", "he", "fa", "ur") + texts = [n["bounds"] for n in a11y()["nodes"].values() + if n.get("bounds") and n["aria"].get("role") == "Label" and n["bounds"][3] < H - 60 + and (n["bounds"][2] < W / 2 if rtl else n["bounds"][0] > W / 2)] + if not texts: + return None + if rtl: + b = max(texts, key=lambda b: b[3] - b[0]) + return round(b[0] + 3), round((b[1] + b[3]) / 2) + b = max(texts, key=lambda b: b[2] + b[3]) + return round(b[2] - 3), round((b[1] + b[3]) / 2) + + +def arrive(chat, n=1): + """`n` incoming messages in `chat`, as the core would announce them.""" + for _ in range(n): + arrive.seq += 1 + msg = {"id": f"{arrive.seq:064x}", "content": f"Incoming {arrive.seq}", "replied_to": "", "preview_metadata": None, + "attachments": [], "reactions": [], "at": int(time.time() * 1000), "pending": False, "failed": False, + "mine": False, "npub": chat, "edited": False} + dev("emit:message_new:" + json.dumps({"chat_id": chat, "message": msg}, separators=(",", ":")), wait=False) + + +arrive.seq = 0xC0FFEE + + +fx = json.load(open(args.fixtures)) +# A 3D preview's turntable runs until animations sleep, by design, so its chat never rests. +spins = lambda c: any(a.get("extension") in ("glb", "gltf") for m in c["messages"] for a in m.get("attachments") or []) +chats = [c["id"] for c in fx.get("chats", []) if c.get("messages") and not spins(c)][:6] +longest = max((c for c in fx.get("chats", []) if c.get("messages")), key=lambda c: len(c["messages"]), default=None) +communities = [c["community_id"] for c in fx.get("communities", [])][:2] + +subprocess.run(["pkill", "-f", f"{args.bin} --fixtures"], capture_output=True) +shutil.rmtree(DATA, ignore_errors=True) +log = tempfile.NamedTemporaryFile("w+", prefix="onscreen-", suffix=".log", delete=False) +if MAC: + # A bare binary started from a shell may not take the front, and an occluded window draws + # nothing; a bundle LaunchServices starts may. It reads a temporary copy of the fixtures: a + # new bundle reading ~/Documents raises a privacy prompt. + stage = tempfile.mkdtemp(prefix="onscreen-app-") + ref = os.path.join(stage, "reference") + shutil.copytree(os.path.dirname(os.path.abspath(args.fixtures)), ref) + fixtures = os.path.join(ref, os.path.basename(args.fixtures)) + bundle = os.path.join(stage, "OnscreenTest.app") + os.makedirs(os.path.join(bundle, "Contents", "MacOS")) + shutil.copy2(args.bin, os.path.join(bundle, "Contents", "MacOS", "OnscreenTest")) + with open(os.path.join(bundle, "Contents", "Info.plist"), "w") as f: + f.write('' + "CFBundleExecutableOnscreenTest" + "CFBundleIdentifierio.vectorapp.onscreen-test" + "CFBundlePackageTypeAPPL" + "NSHighResolutionCapable") + subprocess.run(["codesign", "-s", "-", "--force", bundle], capture_output=True) + app = subprocess.Popen(["open", "-n", "-W", "--stdout", log.name, "--stderr", log.name, bundle, "--args", + "--fixtures", fixtures, "--size", f"{W}x{H}", "--data-dir", DATA], env=env, cwd=CRATE) + for _ in range(60): + if os.path.exists(os.path.join(DATA, "gpui.sock")): + break + time.sleep(0.5) + subprocess.run(["open", "-a", bundle]) + time.sleep(1.5) +else: + app = subprocess.Popen([args.bin, "--fixtures", args.fixtures, "--size", f"{W}x{H}", "--data-dir", DATA], + env=env, stdout=log, stderr=subprocess.STDOUT, cwd=CRATE) +try: + wid = window_of(app.pid) + focus(wid) + time.sleep(2) + check("boot", wid is not None and dev("state").get("screen") == "main", "window up, main screen") + if args.lang: + dev("lang:" + args.lang, wait=False) + time.sleep(1.5) + + if wanted("rest:chats"): + draws, presents = at_rest() + check("rest:chats", draws == 0, f"draws={draws} presents={presents}") + for i, chat in enumerate(chats): + name = f"rest:chat{i}" + if wanted(name): + dev("chat:" + chat, wait=False) + draws, presents = at_rest() + shown = dev("state").get("open") + check(name, draws == 0 and shown == chat, f"draws={draws} presents={presents} {chat[:16]}" + ("" if shown == chat else f" (open: {shown})")) + for i, com in enumerate(communities): + name = f"rest:community{i}" + if wanted(name): + dev("community:" + com, wait=False) + draws, presents = at_rest() + check(name, draws == 0, f"draws={draws} presents={presents}") + + if wanted("fade:hover") and chats: + # A hover fades in once and then holds still: the pointer resting over a row draws nothing. + dev("chat:" + chats[0], wait=False) + time.sleep(1.5) + at = last_text() + frames() + if at: + dev(f"move:{at[0]},{at[1]}", wait=False) + time.sleep(0.6) + moved = frames()["draws"] + draws, presents = at_rest() + dev("move:5,5", wait=False) + check("fade:hover", moved > 0 and draws == 0, f"at {at}: while fading={moved} then draws={draws} presents={presents}") + + if wanted("fade:toast"): + # Held ~1.6 s, then faded out over 320 ms; the window is still once it has gone. + frames() + dev("emit:show_toast:" + json.dumps("On-screen check"), wait=False) + time.sleep(0.6) + shown = frames()["draws"] + draws, presents = at_rest(settle=3) + check("fade:toast", shown > 0 and draws == 0, f"while showing={shown} then draws={draws} presents={presents}") + + if wanted("menu:escape") and chats: + dev("chat:" + chats[0], wait=False) + time.sleep(1.5) + dev(f"rclick:{W // 2 + 150},{H // 2}", wait=False) + time.sleep(0.8) + opened = len(menus(a11y())) + dev("key:escape", wait=False) + time.sleep(0.8) + left = len(menus(a11y())) + check("menu:escape", opened > 0 and left == 0, f"menus open={opened} after Escape={left}") + + if wanted("menu:clamp") and chats: + # Opened on the lowest, rightmost text above the composer, a menu must still fit the window. + at = last_text() + if at: + x, y = at + dev(f"rclick:{x},{y}", wait=False) + time.sleep(0.8) + found = menus(a11y()) + out = [n for n in found if not inside(n)] + dev("key:escape", wait=False) + time.sleep(0.5) + check("menu:clamp", found and not out, f"at {x},{y}: menus={len(found)} outside={len(out)}" + (f" first={out[0].get('bounds')}" if out else "")) + else: + check("menu:clamp", False, "no text to open a menu on") + + if longest and (wanted("scroll:follow") or wanted("scroll:hold")): + chat = longest["id"] + dev("chat:" + chat, wait=False) + time.sleep(1.5) + arrive(chat, 30) + time.sleep(1.5) + before = dev("state") + arrive(chat) + time.sleep(1.5) + after = dev("state") + if wanted("scroll:follow"): + check("scroll:follow", before["following"] and after["following"] and after["timeline_items"] > before["timeline_items"], + f"following={before['following']}->{after['following']} items={before['timeline_items']}->{after['timeline_items']}") + if wanted("scroll:hold"): + dev(f"wheel:{W // 2 + 150},{H // 2},-300,2", wait=False) + time.sleep(1.5) + held = dev("state") + arrive(chat, 3) + time.sleep(1.5) + now = dev("state") + check("scroll:hold", not held["following"] and now["scroll"] == held["scroll"] and now["timeline_items"] > held["timeline_items"], + f"following={held['following']} scroll={held['scroll']}->{now['scroll']} items={held['timeline_items']}->{now['timeline_items']}") + + if wanted("background") and (MAC or shutil.which("xterm")) and wid: + if chats: + dev("chat:" + chats[0], wait=False) + term = None + try: + if MAC: + subprocess.run(["osascript", "-e", 'tell application "Finder" to activate'], capture_output=True) + else: + term = subprocess.Popen(["xterm", "-geometry", "20x4+0+0"], env=env) + focus(window_of(term.pid)) + draws, presents = at_rest(settle=1.5) + check("background", presents == 0 and draws <= 1, f"draws={draws} presents={presents}") + finally: + if term: + term.kill() + focus(wid) + + if wanted("memory"): + if chats: + dev("chat:" + chats[0], wait=False) + time.sleep(6) + m = dev("mem") + # macOS: the kernel's footprint ledger. Linux: dirty private pages, as clean ones are mostly code. + mb = m.get("footprint", m.get("dirty")) + base = json.load(open(BASELINE)) if os.path.exists(BASELINE) else {} + key = f"{sys.platform}-{'debug' if '/debug/' in os.path.abspath(args.bin) else 'release'}" + ("" if args.size == "1000x760" else f"-{args.size}") + if args.update or key not in base: + base[key] = mb + with open(BASELINE, "w") as f: + json.dump(base, f, indent=1, sort_keys=True) + f.write("\n") + check("memory", True, f"{mb} MB recorded as the {key} baseline") + else: + check("memory", mb <= base[key] * MEM_SLACK, f"{mb} MB, baseline {base[key]} MB") +finally: + app.terminate() + try: + app.wait(5) + except subprocess.TimeoutExpired: + app.kill() + # On macOS `app` is `open -W`; the app itself is found by its data dir. + subprocess.run(["pkill", "-f", "data-dir " + DATA], capture_output=True) + log.seek(0) + panics = [l for l in log.read().splitlines() if "panicked at" in l] + check("no panics", not panics, panics[0] if panics else "") + +failed = [r for r in results if not r[1]] +print(f"\n{len(results) - len(failed)}/{len(results)} passed; app log: {log.name}") +sys.exit(1 if failed else 0) diff --git a/crates/vector-gpui/scripts/slot-font.py b/crates/vector-gpui/scripts/slot-font.py new file mode 100644 index 000000000..652a7a2b4 --- /dev/null +++ b/crates/vector-gpui/scripts/slot-font.py @@ -0,0 +1,27 @@ +# Builds assets/fonts/VectorSlot.ttf: python3 scripts/slot-font.py assets/fonts/Rubik-Regular.ttf assets/fonts/VectorSlot.ttf +import sys +from fontTools.ttLib import TTFont +from fontTools.subset import Subsetter, Options +from fontTools.pens.ttGlyphPen import TTGlyphPen +src, dst = sys.argv[1], sys.argv[2] +f = TTFont(src) +o = Options(); o.name_IDs = ['*']; o.notdef_outline = True; o.layout_features = []; o.hinting = False +s = Subsetter(o); s.populate(unicodes=[ord('m')]); s.subset(f) +upm = f['head'].unitsPerEm +glyf, hmtx = f['glyf'], f['hmtx'] +order = f.getGlyphOrder() +for name, cp, adv in [('uni2003', 0x2003, upm), ('uni2005', 0x2005, upm // 4)]: + glyf.glyphs[name] = TTGlyphPen(None).glyph() + hmtx.metrics[name] = (adv, 0) + order.append(name) + for t in f['cmap'].tables: + if t.isUnicode(): t.cmap[cp] = name +f.setGlyphOrder(order) +f['maxp'].numGlyphs = len(order) +name = f['name'] +for rec in list(name.names): + if rec.nameID in (1, 16): rec.string = 'Vector Slot' + elif rec.nameID == 4: rec.string = 'Vector Slot Regular' + elif rec.nameID == 6: rec.string = 'VectorSlot-Regular' + elif rec.nameID == 3: rec.string = 'VectorSlot-Regular' +f.save(dst) diff --git a/crates/vector-gpui/src/album.rs b/crates/vector-gpui/src/album.rs new file mode 100644 index 000000000..d69c8fd4c --- /dev/null +++ b/crates/vector-gpui/src/album.rs @@ -0,0 +1,275 @@ +//! An album in one file (`AudioSession`'s tracks): songs are places in the file, so moving +//! on inside it is gapless; the listener's way through is in order or shuffled, with repeat. + +use rand::seq::SliceRandom; + +#[derive(Clone, Copy, PartialEq, Debug)] +pub enum Repeat { + Off, + All, + One, +} + +pub struct Track { + pub start: u64, + /// None for the last: it runs to the file's end. + pub end: Option, + pub title: String, +} + +pub struct Album { + pub tracks: Vec, + /// The song under the playhead; -1 before the first. + pub track: isize, + pub shuffle: bool, + pub repeat: Repeat, + order: Vec, + order_at: isize, +} + +/// What the playhead should do after a step. +#[derive(Debug, PartialEq)] +pub enum Step { + Stay, + Seek(u64), + /// Nothing follows: stop here. + Stop(u64), +} + +impl Album { + pub fn new(chapters: &[vector_media::chapters::Chapter], pos: u64) -> Self { + let mut a = Album { + tracks: chapters + .iter() + .map(|c| Track { start: c.start_ms as u64, end: c.end_ms.map(u64::from), title: c.title.clone() }) + .collect(), + track: -1, + shuffle: false, + repeat: Repeat::Off, + order: Vec::new(), + order_at: 0, + }; + a.track = a.track_at(pos); + a.reorder(); + a + } + + pub fn track_at(&self, ms: u64) -> isize { + let mut at = -1; + for (i, t) in self.tracks.iter().enumerate() { + if t.start <= ms + 1 { + at = i as isize; + } else { + break; + } + } + at + } + + /// Where song `i` runs in a file `duration` long. + pub fn span(&self, i: isize, duration: u64) -> (u64, u64) { + match usize::try_from(i).ok().and_then(|i| self.tracks.get(i)) { + Some(t) => (t.start, t.end.unwrap_or(duration)), + None => (0, duration), + } + } + + /// The span the controls show: the current song, or the first before any. + pub fn now(&self, duration: u64) -> (u64, u64) { + self.span(self.track.max(0), duration) + } + + pub fn set_shuffle(&mut self, on: bool) { + self.shuffle = on; + self.reorder(); + } + + pub fn cycle_repeat(&mut self) { + self.repeat = match self.repeat { + Repeat::Off => Repeat::All, + Repeat::All => Repeat::One, + Repeat::One => Repeat::Off, + }; + } + + /// The tracks in order, or shuffled with the current first. + fn reorder(&mut self) { + let n = self.tracks.len(); + let cur = self.track.max(0) as usize; + let mut rest: Vec = (0..n).filter(|&i| i != cur).collect(); + if self.shuffle { + rest.shuffle(&mut rand::thread_rng()); + } + self.order = if n > 0 { std::iter::once(cur).chain(rest).collect() } else { Vec::new() }; + self.order_at = 0; + } + + fn next_index(&mut self) -> Option { + if self.tracks.is_empty() { + return None; + } + if self.shuffle { + if ((self.order_at + 1) as usize) < self.order.len() { + return Some(self.order[(self.order_at + 1) as usize]); + } + if self.repeat != Repeat::All { + return None; + } + let last = self.order.get(self.order_at.max(0) as usize).copied(); + self.reorder(); + // A fresh round never starts with the song that just ended. + if self.order.len() > 1 && self.order.first().copied() == last { + self.order.rotate_left(1); + } + self.order_at = -1; + return self.order.first().copied(); + } + let i = (self.track + 1) as usize; + if i < self.tracks.len() { + Some(i) + } else if self.repeat == Repeat::All { + Some(0) + } else { + None + } + } + + fn goto(&mut self, i: usize, keep_order: bool) -> u64 { + if self.shuffle && !keep_order { + if let Some(at) = self.order.iter().position(|&o| o == i) { + self.order_at = at as isize; + } + } + self.track = i as isize; + self.tracks[i].start + } + + /// Song `i` from its start, whatever the order was. + pub fn play_track(&mut self, i: usize) -> Option { + if i >= self.tracks.len() { + return None; + } + let ms = self.goto(i, false); + if self.shuffle { + self.reorder(); + } + Some(ms) + } + + pub fn next(&mut self) -> Option { + let n = self.next_index()?; + Some(self.goto(n, false)) + } + + /// Back to the start of the song, or near its start already, to the song before. + pub fn prev(&mut self, pos: u64, duration: u64) -> u64 { + let i = self.track.max(0) as usize; + if pos.saturating_sub(self.span(i as isize, duration).0) > 3000 { + return self.goto(i, false); + } + if self.shuffle && self.order_at > 0 { + self.order_at -= 1; + return self.goto(self.order[self.order_at as usize], true); + } + if !self.shuffle && i > 0 { + return self.goto(i - 1, false); + } + if !self.shuffle && self.repeat == Repeat::All { + return self.goto(self.tracks.len() - 1, false); + } + self.goto(i, false) + } + + /// A seek is a choice, not the song moving on: the track follows it quietly. + pub fn seeked(&mut self, ms: u64) { + self.track = self.track_at(ms); + } + + /// While playing: note the song moving on, and step in when the listener's way is not + /// simply the next song in the file. + pub fn tick(&mut self, pos: u64) -> Step { + let i = self.track_at(pos); + if i == self.track { + return Step::Stay; + } + let from = self.track; + self.track = i; + if i != from + 1 || from < 0 { + return Step::Stay; + } + if self.repeat == Repeat::One { + return Step::Seek(self.goto(from as usize, false)); + } + if self.shuffle { + match self.next_index() { + None => { + let first = self.order.first().copied().unwrap_or(0); + return Step::Stop(self.goto(first, false)); + } + Some(n) => { + self.order_at += 1; + if n as isize != i { + return Step::Seek(self.goto(n, true)); + } + } + } + } + Step::Stay + } + + /// The file ended: where to carry on from, if anywhere. + pub fn ended(&mut self) -> Option { + let last = self.track; + let n = if self.repeat == Repeat::One { usize::try_from(last).ok() } else { self.next_index() }; + match n { + Some(n) => { + if self.shuffle && self.repeat != Repeat::One { + self.order_at += 1; + } + Some(self.goto(n, true)) + } + None => { + self.track = self.track_at(0); + None + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use vector_media::chapters::Chapter; + + fn album() -> Album { + let ch = |s: u32, e: Option, t: &str| Chapter { start_ms: s, end_ms: e, title: t.into() }; + Album::new(&[ch(0, Some(1000), "a"), ch(1000, Some(2000), "b"), ch(2000, None, "c")], 0) + } + + #[test] + fn songs_follow_in_order_and_stop_at_the_end() { + let mut a = album(); + assert_eq!(a.tick(1200), Step::Stay); + assert_eq!(a.track, 1); + assert_eq!(a.next(), Some(2000)); + assert_eq!(a.ended(), None); + assert_eq!(a.track, 0); + } + + #[test] + fn repeat_one_holds_the_song() { + let mut a = album(); + a.cycle_repeat(); + a.cycle_repeat(); + assert_eq!(a.tick(1100), Step::Seek(0)); + assert_eq!(a.track, 0); + } + + #[test] + fn prev_restarts_a_song_well_under_way() { + let mut a = album(); + a.play_track(2); + assert_eq!(a.prev(5500, 9000), 2000); + assert_eq!(a.prev(2100, 9000), 1000); + } +} diff --git a/crates/vector-gpui/src/android.rs b/crates/vector-gpui/src/android.rs new file mode 100644 index 000000000..fa98b9e6f --- /dev/null +++ b/crates/vector-gpui/src/android.rs @@ -0,0 +1,245 @@ +//! The desktop client's Android glue: the media crate's, and the content URIs a share or a +//! picker hands over. + +pub use vector_media::android::*; + +#[path = "../../../src-tauri/src/android/filesystem.rs"] +#[allow(dead_code)] +pub mod filesystem; + +use std::path::PathBuf; +use std::sync::OnceLock; + +/// A folder `Context` names, by its getter. +fn folder(getter: &str) -> Option { + utils::with_android_context(|env, ctx| { + let err = |e: jni::errors::Error| format!("{e:?}"); + let dir = env.call_method(ctx, getter, "()Ljava/io/File;", &[]).and_then(|v| v.l()).map_err(err)?; + let path = env.call_method(&dir, "getAbsolutePath", "()Ljava/lang/String;", &[]).and_then(|v| v.l()).map_err(err)?; + let path: String = env.get_string(&jni::objects::JString::from(path)).map_err(err)?.into(); + Ok(PathBuf::from(path)) + }) + .ok() +} + +/// The app's data folder: where the Tauri client keeps its accounts. +pub fn data_dir() -> Option<&'static PathBuf> { + static DIR: OnceLock> = OnceLock::new(); + DIR.get_or_init(|| folder("getDataDir")).as_ref() +} + +pub fn cache_dir() -> Option<&'static PathBuf> { + static DIR: OnceLock> = OnceLock::new(); + DIR.get_or_init(|| folder("getCacheDir")).as_ref() +} + +/// The shell's own text in the app's language, kept by `io.vectorapp.Strings` for its +/// notifications, channels and prompts. +pub fn send_strings() { + use crate::t; + use jni::objects::{JClass, JValue}; + let table: [(&str, gpui::SharedString); 37] = [ + ("android-call-incoming", t::android_call_incoming()), + ("android-call-incoming-video", t::android_call_incoming_video()), + ("android-call-missed", t::android_call_missed()), + ("android-call-decline", t::android_call_decline()), + ("android-call-answer", t::android_call_answer()), + ("android-call-voice", t::android_call_voice()), + ("android-call-video", t::android_call_video()), + ("android-call-muted", t::android_call_muted()), + ("android-call-mute", t::android_call_mute()), + ("android-call-unmute", t::android_call_unmute()), + ("android-call-ongoing", t::android_call_ongoing()), + ("android-call-return", t::android_call_return()), + ("android-call-leave", t::android_call_leave()), + ("android-notify-someone", t::android_notify_someone()), + ("android-notify-me", t::android_notify_me()), + ("android-notify-reply", t::android_notify_reply()), + ("android-notify-mark-read", t::android_notify_mark_read()), + ("android-service-listening", t::android_service_listening()), + ("android-service-tagline-watch", t::android_service_tagline_watch()), + ("android-service-tagline-miss", t::android_service_tagline_miss()), + ("android-service-tagline-standby", t::android_service_tagline_standby()), + ("android-channel-ring", t::android_channel_ring()), + ("android-channel-ring-about", t::android_channel_ring_about()), + ("android-channel-missed", t::android_channel_missed()), + ("android-channel-missed-about", t::android_channel_missed_about()), + ("android-channel-calls", t::android_channel_calls()), + ("android-channel-calls-about", t::android_channel_calls_about()), + ("android-channel-messages", t::android_channel_messages()), + ("android-channel-messages-about", t::android_channel_messages_about()), + ("android-channel-service", t::android_channel_service()), + ("android-channel-service-about", t::android_channel_service_about()), + ("android-open-with", t::android_open_with()), + ("android-share", t::android_share()), + ("android-biometric-use", t::android_biometric_use()), + ("android-biometric-screen-lock", t::android_biometric_screen_lock()), + ("android-biometric-enable", t::android_biometric_enable()), + ("android-biometric-unlock", t::android_biometric_unlock()), + ]; + let json = serde_json::Value::Object(table.into_iter().map(|(k, v)| (k.to_string(), serde_json::Value::from(v.as_ref()))).collect()).to_string(); + let sent = utils::with_android_context(|env, ctx| { + let err = |e: jni::errors::Error| format!("{e:?}"); + let loader = env.call_method(ctx, "getClassLoader", "()Ljava/lang/ClassLoader;", &[]).and_then(|v| v.l()).map_err(err)?; + let name = env.new_string("io.vectorapp.Strings").map_err(err)?; + let class = env + .call_method(&loader, "loadClass", "(Ljava/lang/String;)Ljava/lang/Class;", &[JValue::Object(&name)]) + .and_then(|v| v.l()) + .map_err(err)?; + let json = env.new_string(&json).map_err(err)?; + let out = env.call_static_method(&JClass::from(class), "set", "(Landroid/content/Context;Ljava/lang/String;)V", &[JValue::Object(ctx), JValue::Object(&json)]); + if out.is_err() { + let _ = env.exception_clear(); + } + out.map(drop).map_err(err) + }); + if let Err(e) = sent { + log::warn!("android strings: {e}"); + } +} + +/// Calls a static `VectorBatteryHelper` method taking the context and maybe a flag; a void one +/// reads as false. +fn battery_helper(method: &str, sig: &str, flag: Option) -> bool { + use jni::objects::{JClass, JValue}; + utils::with_android_context(|env, ctx| { + let err = |e: jni::errors::Error| format!("{e:?}"); + let loader = env.call_method(ctx, "getClassLoader", "()Ljava/lang/ClassLoader;", &[]).and_then(|v| v.l()).map_err(err)?; + let name = env.new_string("io.vectorapp.VectorBatteryHelper").map_err(err)?; + let class = env + .call_method(&loader, "loadClass", "(Ljava/lang/String;)Ljava/lang/Class;", &[JValue::Object(&name)]) + .and_then(|v| v.l()) + .map_err(err)?; + let mut args = vec![JValue::Object(ctx)]; + args.extend(flag.map(|f| JValue::Bool(f.into()))); + let out = env.call_static_method(&JClass::from(class), method, sig, &args); + if out.is_err() { + let _ = env.exception_clear(); + } + out.map(|v| v.z().unwrap_or(false)).map_err(err) + }) + .unwrap_or(false) +} + +/// The system back gesture gives way on the screen's left edge across `span` (top, bottom), +/// else where a thumb swipes. +pub fn claim_left_edge(span: Option<(f32, f32)>) { + use jni::objects::{JClass, JValue}; + let done = utils::with_android_context(|env, ctx| { + let err = |e: jni::errors::Error| format!("{e:?}"); + let loader = env.call_method(ctx, "getClassLoader", "()Ljava/lang/ClassLoader;", &[]).and_then(|v| v.l()).map_err(err)?; + let name = env.new_string("io.vectorapp.gpui.Bridge").map_err(err)?; + let class = env + .call_method(&loader, "loadClass", "(Ljava/lang/String;)Ljava/lang/Class;", &[JValue::Object(&name)]) + .and_then(|v| v.l()) + .map_err(err)?; + let class = JClass::from(class); + let out = match span { + // i18n-exempt: JNI signature + Some((top, bottom)) => env.call_static_method(&class, "claimLeft", "(FF)V", &[JValue::Float(top), JValue::Float(bottom)]), + None => env.call_static_method(&class, "releaseLeft", "()V", &[]), + }; + if out.is_err() { + let _ = env.exception_clear(); + } + out.map(|_| ()).map_err(err) + }); + if let Err(e) = done { + log::warn!("android edge claim: {e}"); + } +} + +fn battery_flag(method: &str) -> bool { + battery_helper(method, "(Landroid/content/Context;)Z", None) +} + +/// Settings' Run in Background: whether the service keeps the client connected while away. +pub fn background_enabled() -> bool { + battery_flag("getBackgroundServiceEnabled") +} + +/// Android may stop a service it is allowed to optimise for battery. +pub fn battery_exempt() -> bool { + battery_flag("isIgnoringBatteryOptimizations") +} + +/// The system's dialog asking to let Vector run unoptimised; the answer shows on return. +pub fn request_battery_exemption() { + battery_helper("requestBatteryOptimization", "(Landroid/content/Context;)V", None); +} + +/// Remembered, and the service started or stopped to match. +pub fn set_background(on: bool) { + battery_helper("setBackgroundServiceEnabled", "(Landroid/content/Context;Z)V", Some(on)); + let method = if on { "startBackgroundService" } else { "stopBackgroundService" }; + battery_helper(method, "(Landroid/content/Context;)V", None); +} + +/// Once per install, after sign-in: whether to offer Run in Background, which notifications need +/// while the app is away. +fn offer_background() -> bool { + if battery_flag("getBackgroundServicePrompted") { + return false; + } + battery_helper("setBackgroundServicePrompted", "(Landroid/content/Context;)V", None); + true +} + +pub enum Offer { + Push, + Background, +} + +/// Once per account after sign-in: Notify When Closed, else, for a phone push can't reach, Run +/// in Background. +pub fn offer_notifications() -> Option { + use crate::backend::push::{self, Push}; + static ASKED: std::sync::Mutex> = std::sync::Mutex::new(None); + let npub = vector_core::db::get_current_account().ok()?; + { + let mut asked = ASKED.lock().unwrap_or_else(|e| e.into_inner()); + if asked.as_deref() == Some(npub.as_str()) { + return None; + } + *asked = Some(npub); + } + match push::status() { + Some(Push::Off) => { + const PROMPTED: &str = "push_prompted"; + let prompted = vector_core::db::get_sql_setting(PROMPTED.into()).ok().flatten().is_some(); + // Running in the background already brings their notifications. + if prompted || background_enabled() { + return None; + } + let _ = vector_core::db::set_sql_setting(PROMPTED.into(), "true".into()); + Some(Offer::Push) + } + None => offer_background().then_some(Offer::Background), + Some(_) => None, + } +} + +/// Test builds: `adb shell setprop debug.vector.fixtures 1` starts on the desktop's fixtures +/// (no account, no relays), as an app can't be handed `--fixtures`. Their media isn't shipped. +#[cfg(feature = "test-build")] +pub fn fixtures() -> Option { + use std::ffi::{CStr, c_char, c_int}; + unsafe extern "C" { + fn __system_property_get(name: *const c_char, value: *mut c_char) -> c_int; + } + let mut value = [0 as c_char; 92]; + // SAFETY: PROP_VALUE_MAX (92) bytes is the most the call writes, NUL included. + let on = unsafe { + __system_property_get(c"debug.vector.fixtures".as_ptr(), value.as_mut_ptr()); + CStr::from_ptr(value.as_ptr()) + } + .to_bytes() + == b"1"; + if !on { + return None; + } + let path = cache_dir()?.join("fixtures.json"); + std::fs::write(&path, include_bytes!("../reference/fixtures.json")).ok()?; + log::info!("debug.vector.fixtures: starting on fixtures"); + Some(path) +} diff --git a/crates/vector-gpui/src/applog.rs b/crates/vector-gpui/src/applog.rs new file mode 100644 index 000000000..ba4034949 --- /dev/null +++ b/crates/vector-gpui/src/applog.rs @@ -0,0 +1,235 @@ +//! The persistent log (`vector.log`, Settings > Copy Logs), shared with Tauri: vector-core's +//! persisted lines, every `log` error (GPUI's included), and panics with their backtrace. + +use std::io::Write; +use std::path::PathBuf; +use std::sync::OnceLock; + +static FILE: OnceLock = OnceLock::new(); + +/// Tauri's `append_vector_log`: one line, the file trimmed to its last 900 once past 1000. +pub fn append(line: &str) { + let Some(path) = FILE.get() else { return }; + if let Ok(existing) = std::fs::read_to_string(path) { + let lines: Vec<&str> = existing.lines().collect(); + if lines.len() > 1000 { + let _ = std::fs::write(path, lines[lines.len() - 900..].join("\n")); + } + } + if let Ok(mut f) = std::fs::OpenOptions::new().create(true).append(true).open(path) { + let _ = writeln!(f, "{line}"); + } +} + +/// env_logger on stderr as before, with errors also kept in the file. +struct Logger(env_logger::Logger); + +impl log::Log for Logger { + fn enabled(&self, meta: &log::Metadata) -> bool { + meta.level() <= log::Level::Error || self.0.enabled(meta) + } + + fn log(&self, record: &log::Record) { + if record.level() <= log::Level::Error { + append(&format!( + "[{} ERROR] {}: {}", // i18n-exempt: log format + vector_core::logging::timestamp_utc(), + record.target(), + record.args() + )); + } + if self.0.enabled(record.metadata()) { + self.0.log(record); + } + } + + fn flush(&self) { + self.0.flush(); + } +} + +pub fn init(data_dir: Option) { + if let Some(dir) = data_dir { + let _ = FILE.set(dir.join("vector.log")); + } + #[cfg(target_os = "android")] + logcat::capture(); + #[cfg(all(target_os = "android", any(debug_assertions, feature = "test-build")))] + { + use vector_media::android::storage; + if let Some(dir) = storage::public_dir().or_else(storage::external_media_dir) { + logcat::mirror::into(std::path::Path::new(&dir)); + } + } + let mut env = env_logger::Builder::from_default_env(); + // No RUST_LOG on a phone: logcat is the only place a launch that never draws can be read. + #[cfg(target_os = "android")] + env.parse_filters(if cfg!(any(debug_assertions, feature = "test-build")) { logcat::TEST_FILTER } else { "warn" }); + let env = env.build(); + let max = env.filter().max(log::LevelFilter::Error); + if log::set_boxed_logger(Box::new(Logger(env))).is_ok() { + log::set_max_level(max); + } + vector_core::logging::set_persist_sink(append); + let previous = std::panic::take_hook(); + std::panic::set_hook(Box::new(move |info| { + // A panic escaping the hook aborts on the spot, so the report can never be what kills us. + let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + let backtrace = std::backtrace::Backtrace::force_capture(); + let report = format!( + "[{} PANIC] {info}\n\nBacktrace:\n{backtrace}\n", // i18n-exempt: log format + vector_core::logging::timestamp_utc() + ); + append(&report); + // The drain thread may not outlive an abort: the report goes to the file from here. + #[cfg(all(target_os = "android", any(debug_assertions, feature = "test-build")))] + logcat::mirror::line_now(report.as_bytes()); + })); + previous(info); + })); +} + +/// Android points stdout and stderr at /dev/null: both go to logcat instead, so core's lines, +/// `log` records and the panic report can be read there. +#[cfg(target_os = "android")] +mod logcat { + use std::ffi::{c_char, c_int}; + use std::io::{BufRead, BufReader}; + use std::os::fd::FromRawFd; + + pub const TEST_FILTER: &str = "info,wgpu_core=warn,wgpu_hal=warn,naga=warn,arti_client=warn,tor_=warn"; + + #[link(name = "log")] + unsafe extern "C" { + fn __android_log_write(prio: c_int, tag: *const c_char, text: *const c_char) -> c_int; + } + + fn priority(line: &[u8]) -> c_int { + let head = &line[..line.len().min(48)]; + let has = |word: &[u8]| head.windows(word.len()).any(|w| w == word); + if has(b"ERROR") || has(b"PANIC") || has(b"panicked") { + 6 + } else if has(b"WARN") { + 5 + } else { + 4 + } + } + + pub fn capture() { + let mut fds: [c_int; 2] = [0; 2]; + // SAFETY: a fresh pipe, whose read end the drain owns. + let read = unsafe { + if libc::pipe(fds.as_mut_ptr()) != 0 { + return; + } + std::fs::File::from_raw_fd(fds[0]) + }; + let drain = std::thread::Builder::new().name("logcat".into()).spawn(move || { + let mut read = BufReader::new(read); + let mut line = Vec::with_capacity(256); + while matches!(read.read_until(b'\n', &mut line), Ok(n) if n > 0) { + if line.last() == Some(&b'\n') { + line.pop(); + } + for b in line.iter_mut().filter(|b| **b == 0) { + *b = b' '; + } + #[cfg(any(debug_assertions, feature = "test-build"))] + mirror::line(&line); + line.push(0); + // SAFETY: both strings are NUL-terminated and outlive the call. + unsafe { __android_log_write(priority(&line), c"vector".as_ptr(), line.as_ptr().cast()) }; + line.clear(); + } + }); + // SAFETY: fds 1 and 2 take the write end only once something drains it; a pipe with no + // reader would block every write once full. + unsafe { + if drain.is_ok() { + libc::dup2(fds[1], 1); + libc::dup2(fds[1], 2); + } + libc::close(fds[1]); + } + } + + /// Test builds also keep a launch's output where the phone's Files app can read it, so a + /// test build that never draws can be diagnosed without adb. + #[cfg(any(debug_assertions, feature = "test-build"))] + pub mod mirror { + use std::io::Write; + use std::path::Path; + use std::sync::Mutex; + + enum Mirror { + Waiting(Vec), + Open(std::fs::File), + Off, + } + + static MIRROR: Mutex = Mutex::new(Mirror::Waiting(Vec::new())); + const HELD: usize = 512 * 1024; + + pub(super) fn line(text: &[u8]) { + let mut mirror = MIRROR.lock().unwrap_or_else(|e| e.into_inner()); + write(&mut mirror, text); + } + + /// From a panic: a lock held by the panicking thread itself would never come back. + pub(crate) fn line_now(text: &[u8]) { + if let Ok(mut mirror) = MIRROR.try_lock() { + write(&mut mirror, text); + } + } + + fn write(mirror: &mut Mirror, text: &[u8]) { + match mirror { + Mirror::Waiting(held) if held.len() < HELD => { + held.extend_from_slice(text); + held.push(b'\n'); + } + Mirror::Open(file) => { + let _ = file.write_all(text).and_then(|()| file.write_all(b"\n")); + } + _ => {} + } + } + + const PREFIX: &str = "vector-gpui-debug-"; + const KEPT: usize = 5; + + /// From here on, and everything since launch, into a file of this launch's own in `dir`: + /// a crash's log outlives the next launch, and a reinstall, which may not reopen files an + /// earlier install made, still gets one. + pub fn into(dir: &Path) { + let mut mirror = MIRROR.lock().unwrap_or_else(|e| e.into_inner()); + let Mirror::Waiting(held) = &*mirror else { return }; + let stamp: String = vector_core::logging::timestamp_utc().chars().filter(char::is_ascii_digit).collect(); + let name = format!("{PREFIX}{}-{}.log", &stamp[..stamp.len().min(8)], &stamp[stamp.len().min(8)..]); // i18n-exempt: file name + let opened = std::fs::create_dir_all(dir) + .and_then(|()| std::fs::File::create(dir.join(&name))) + .and_then(|mut file| file.write_all(held).map(|()| file)); + *mirror = match opened { + Ok(file) => Mirror::Open(file), + Err(_) => Mirror::Off, + }; + drop(mirror); + prune(dir); + } + + /// All but the newest few launches' logs; another install's can't be removed and stay. + fn prune(dir: &Path) { + let Ok(entries) = std::fs::read_dir(dir) else { return }; + let mut logs: Vec<_> = entries + .flatten() + .map(|e| e.file_name().to_string_lossy().into_owned()) + .filter(|n| n.starts_with(PREFIX) && n.ends_with(".log")) + .collect(); + logs.sort_unstable_by(|a, b| b.cmp(a)); + for old in logs.iter().skip(KEPT) { + let _ = std::fs::remove_file(dir.join(old)); + } + } + } +} diff --git a/crates/vector-gpui/src/assets.rs b/crates/vector-gpui/src/assets.rs new file mode 100644 index 000000000..3a76e086e --- /dev/null +++ b/crates/vector-gpui/src/assets.rs @@ -0,0 +1,67 @@ +//! Compiled-in assets. `icons/` is the Tauri client's own icon folder, so an icon it adds or +//! redraws reaches this client on the next build; `ui/` holds what the Svelte markup inlines. + +use std::borrow::Cow; + +use anyhow::Result; +use gpui::{AssetSource, SharedString}; +use rust_embed::RustEmbed; + +#[derive(RustEmbed)] +#[folder = "$CARGO_MANIFEST_DIR/../../src/icons"] +struct SharedIcons; + +#[derive(RustEmbed)] +#[folder = "$CARGO_MANIFEST_DIR/assets/icons"] +struct UiIcons; + +#[derive(RustEmbed)] +#[folder = "$CARGO_MANIFEST_DIR/../../src/twemoji/svg"] +struct Twemoji; + +#[derive(RustEmbed)] +#[folder = "$CARGO_MANIFEST_DIR/assets/fonts"] +struct Fonts; + +pub struct Assets; + +impl AssetSource for Assets { + fn load(&self, path: &str) -> Result>> { + if let Some(file) = path.strip_prefix(crate::pic::SEALED) { + return Ok(Some(Cow::Owned(crate::pic::read(file)?))); + } + let file = if let Some(p) = path.strip_prefix("icons/") { + SharedIcons::get(p) + } else if let Some(p) = path.strip_prefix("ui/") { + UiIcons::get(p) + } else if let Some(p) = path.strip_prefix("twemoji/") { + Twemoji::get(p) + } else { + None + }; + Ok(file.map(|f| f.data)) + } + + fn list(&self, path: &str) -> Result> { + let names: Vec = if path.starts_with("icons") { + SharedIcons::iter() + .map(|p| format!("icons/{p}").into()) + .collect() + } else { + UiIcons::iter().map(|p| format!("ui/{p}").into()).collect() + }; + Ok(names) + } +} + +pub fn fonts() -> Vec> { + // CoreText refuses anything that isn't a font, so the folder's README must not reach it. + Fonts::iter() + .filter(|name| name.ends_with(".ttf") || name.ends_with(".otf")) + .filter_map(|name| Fonts::get(&name).map(|f| f.data)) + .collect() +} + +pub fn twemoji_names() -> impl Iterator> { + Twemoji::iter() +} diff --git a/crates/vector-gpui/src/atlas_border.rs b/crates/vector-gpui/src/atlas_border.rs new file mode 100644 index 000000000..e30e8cbd1 --- /dev/null +++ b/crates/vector-gpui/src/atlas_border.rs @@ -0,0 +1,86 @@ +//! The fork's bordered atlas tiles: what the five region writes and the padded copy put in the +//! texture, and the tile handed back. + +use gpui::{ + AtlasKey, Bounds, DevicePixels, HeadlessAtlas, ImageId, PADDED_IN_SCRATCH, PlatformAtlas, Point, RenderImageParams, Size, + edge_padded_into, write_edge_padded, +}; +use std::borrow::Cow; + +fn size(w: usize, h: usize) -> Size { + Size { width: DevicePixels(w as i32), height: DevicePixels(h as i32) } +} + +/// The border texel by texel, written the obvious way. +fn padded_by_hand(bytes: &[u8], w: usize, h: usize, bpp: usize) -> Vec { + let mut out = Vec::new(); + for y in 0..h + 2 { + for x in 0..w + 2 { + let (sx, sy) = (x.clamp(1, w) - 1, y.clamp(1, h) - 1); + out.extend_from_slice(&bytes[(sy * w + sx) * bpp..][..bpp]); + } + } + out +} + +#[test] +fn padded_writes_fill_the_tile_as_the_padded_copy_would() { + for bpp in [1, 4] { + for (w, h) in [(1, 1), (1, 9), (9, 1), (3, 2), (131, 127), (1, 20_000), (20_000, 1), (300, 200)] { + let bytes: Vec = (0..w * h * bpp).map(|i| (i * 7 + i / 251) as u8).collect(); + let want = padded_by_hand(&bytes, w, h, bpp); + let mut copy = Vec::new(); + edge_padded_into(&mut copy, &bytes, size(w, h), bpp); + assert!(copy == want, "{w}x{h}x{bpp}: padded copy"); + + let (pw, ph) = (w + 2, h + 2); + let mut scratch = Vec::new(); + let mut tile = vec![0u8; pw * ph * bpp]; + let mut covered = vec![0u8; pw * ph]; + let mut writes = 0; + write_edge_padded(&bytes, size(w, h), bpp, &mut scratch, |at, part, src| { + let (x0, y0) = (at.x.0 as usize, at.y.0 as usize); + let (rw, rh) = (part.width.0 as usize, part.height.0 as usize); + assert!(x0 + rw <= pw && y0 + rh <= ph); + assert_eq!(src.len(), rw * rh * bpp, "rows are tightly packed"); + for y in 0..rh { + let to = ((y0 + y) * pw + x0) * bpp; + tile[to..to + rw * bpp].copy_from_slice(&src[y * rw * bpp..][..rw * bpp]); + covered[(y0 + y) * pw + x0..][..rw].iter_mut().for_each(|c| *c += 1); + } + writes += 1; + Ok(()) + }) + .unwrap(); + assert!(tile == want, "{w}x{h}x{bpp}: written tile"); + assert!(covered.iter().all(|&c| c == 1), "{w}x{h}x{bpp}: every texel written once"); + let small = pw * ph * bpp <= PADDED_IN_SCRATCH; + assert_eq!(writes, if small { 1 } else { 5 }, "{w}x{h}x{bpp}"); + assert!(scratch.capacity() <= PADDED_IN_SCRATCH.max((h + 2) * bpp), "scratch stays small"); + } + } +} + +fn image_key(id: usize) -> AtlasKey { + RenderImageParams { image_id: ImageId(id), frame_index: 0 }.into() +} + +#[test] +fn padded_tiles_cover_their_pixels_alone() { + let atlas = HeadlessAtlas::default(); + let pixels = [9u8; 3 * 2 * 4]; + let tile = atlas + .get_or_insert_padded_with(image_key(1), &mut || Ok(Some((size(3, 2), Cow::Borrowed(&pixels[..]))))) + .unwrap() + .unwrap(); + assert_eq!(tile.bounds, Bounds { origin: Point { x: DevicePixels(1), y: DevicePixels(1) }, size: size(3, 2) }); + let again = atlas.get_or_insert_padded_with(image_key(1), &mut || panic!("a cache hit builds nothing")).unwrap(); + assert_eq!(again, Some(tile)); + assert_eq!(atlas.get_or_insert_with(image_key(1), &mut || Ok(None)).unwrap(), Some(tile)); + + let short = atlas + .get_or_insert_padded_with(image_key(2), &mut || Ok(Some((size(3, 2), Cow::Borrowed(&pixels[..4]))))) + .unwrap() + .unwrap(); + assert_eq!(short.bounds, Bounds { origin: Point::default(), size: size(3, 2) }); +} diff --git a/crates/vector-gpui/src/attachments.rs b/crates/vector-gpui/src/attachments.rs new file mode 100644 index 000000000..b184f8af4 --- /dev/null +++ b/crates/vector-gpui/src/attachments.rs @@ -0,0 +1,1225 @@ +//! A message's attachments (`Attachments.svelte` and its leaves): pictures, the thumbhash blur +//! a picture waits behind, and file boxes. Transfer state lives in [`Media`]; the message only +//! says whether its bytes are here. + +use crate::kit::Tipped as _; +use crate::t; +use std::f32::consts::TAU; +use std::sync::LazyLock; +use std::time::Instant; + +use gpui::{AnyElement, Bounds, FontWeight, Hsla, IntoElement, ParentElement, PathBuilder, Pixels, SharedString, Styled, canvas, div, point, prelude::*, px, svg}; +use crate::pic::img; +use vector_core::types::{Attachment, Message}; + +use crate::data; +use crate::media::{self, Media, Slot, Source, Transfer}; +use crate::theme::*; +use crate::timeline::{Act, Ctx, DANGER}; + +pub(crate) const IMAGES: [&str; 15] = [ + "png", "jpeg", "jpg", "gif", "webp", "jxl", "svg", "bmp", "tiff", "tif", "ico", "heic", "heif", "heics", "heifs", +]; +/// Pictures that wait behind their blur rather than a file box. +const BLURRED: [&str; 13] = ["png", "jpeg", "jpg", "gif", "webp", "jxl", "tiff", "tif", "ico", "heic", "heif", "heics", "heifs"]; + +const BOX_BG: u32 = 0x161616; +const BOX_BG_HOVER: u32 = 0x1d1d1d; +const BOX_LINE: u32 = 0x262626; +const BOX_LINE_HOVER: u32 = 0x363636; + +pub static EPOCH: LazyLock = LazyLock::new(Instant::now); + +#[derive(Clone, Copy, PartialEq)] +enum Phase { + Ready, + Downloading, + Idle, +} + +fn ext(att: &Attachment) -> String { + att.extension.to_ascii_lowercase() +} + +fn spoiler(att: &Attachment) -> bool { + att.name.to_uppercase().starts_with("SPOILER_") +} + +fn source(ctx: &Ctx, att: &Attachment) -> Source { + if att.resident || att.path.is_empty() { + if let Some(h) = vector_core::simd::hex::hex_to_bytes_32_checked(&att.id) { + return Source::Held(h); + } + } + let p = std::path::Path::new(&att.path); + Source::File(if p.is_absolute() { + p.to_path_buf() + } else { + ctx.store.media_root.join(p) + }) +} + +/// `.dmsg-attachments`: each attachment in the state it is in. +pub fn attachments(ctx: &Ctx, m: &Message) -> Option { + if m.attachments.is_empty() { + return None; + } + let mut media = ctx.media.borrow_mut(); + let mut col = div().mt(px(4.)).flex().flex_col().items_start(); + let mut prev_bottom = 0.; + for (i, att) in m.attachments.iter().enumerate() { + let e = ext(att); + let unsent = m.mine && att.url.is_empty(); + let ready = att.downloaded || att.resident; + let failed = media.failed.get(&att.id).cloned(); + let auto = media.auto_download.on + && !ready + && !ctx.held + && !unsent + && failed.is_none() + && !media.auto_fired.contains(&att.id) + && att.size > 0 + && att.size <= media.auto_download.limit; + if auto { + media.auto_fired.insert(att.id.clone()); + media.auto_queue.push((m.id.clone(), att.id.clone())); + } + let downloading = + media.transfers.contains_key(&att.id) || media.started.contains(&att.id) || auto; + let phase = if ready { + Phase::Ready + } else if downloading { + Phase::Downloading + } else { + Phase::Idle + }; + // Auto-download weighs a file by its size, so one sent without it asks its server. + if matches!(phase, Phase::Idle) + && att.size == 0 + && !unsent + && !ctx.held + && (att.url.starts_with("https://") || att.url.starts_with("http://")) + && media.sized.insert(att.id.clone()) + { + media.size_queue.push((m.id.clone(), att.id.clone())); + } + let (el, bottom) = match phase { + Phase::Ready if crate::audio::EXTENSIONS.contains(&e.as_str()) && !unsent => { + let input = match source(ctx, att) { + Source::Held(h) => crate::audio::AudioInputSpec::Held(h), + Source::File(p) => crate::audio::AudioInputSpec::File(p), + }; + media.audio.want_probe(&att.id, &input); + if !att.name.is_empty() { + media.audio.want_tags(&att.id, &input); + } + let transcribable = media + .audio + .tags_read(&att.id) + .map_or(att.name.is_empty(), |music| crate::transcript::supported(att, true, music)); + if transcribable && !m.mine && m.at + 60_000 > vector_core::clock::now_ms() { + media.audio.want_transcript(&att.id, &input); + } + let duration = media.audio.duration(&att.id); + let tags = media.audio.tags(&att.id).cloned(); + let (on_act, msg, aid) = (ctx.on_act.clone(), m.id.clone(), att.id.clone()); + ( + crate::audio::view( + att, + media.audio.player(&att.id), + duration, + tags.as_deref(), + media.audio.sheets.get(&att.id), + media.audio.all_tracks.contains(&att.id), + transcribable.then_some(&media.audio.transcripts), + &media.audio.narrow, + // After the message's text, in the order its attachments show. + Some(crate::select::Key { at: m.at, msg: crate::select::msg_hash(&m.id), path: [u16::MAX, i as u16 + 1, 0, 0] }), + std::rc::Rc::new(move |a, w, cx| on_act(&msg, Act::Audio(aid.clone(), a), w, cx)), + ), + 6., + ) + } + Phase::Ready + if crate::video::EXTENSIONS.contains(&e.as_str()) && !media.videos.failed(&att.id) => + { + let input = match source(ctx, att) { + Source::Held(h) => crate::audio::AudioInputSpec::Held(h), + Source::File(p) => crate::audio::AudioInputSpec::File(p), + }; + media.videos.want_probe(&att.id, &input); + match media.videos.clip(&att.id) { + Some(clip) => { + let (on_act, msg, aid) = (ctx.on_act.clone(), m.id.clone(), att.id.clone()); + let size = clip.info.as_ref().map(|i| within(ctx, crate::video::fit(i.w, i.h))); + let view = crate::video::view( + &att.id, + clip, + m.pending, + size, + (8., 8.), + std::rc::Rc::new(move |a, w, cx| on_act(&msg, Act::Video(aid.clone(), a), w, cx)), + ); + let view = if m.mine && m.pending { + let (w, h) = size.unwrap_or((crate::video::MAX_W, crate::video::MAX_H * 0.6)); + div().relative().child(view).child(upload_overlay(ctx, m, media.transfers.get(&m.id), w, h)).into_any_element() + } else { + view + }; + (view, 6.) + } + None => (video_placeholder(ctx, att), 6.), + } + } + Phase::Ready if crate::model3d::supports(&e) => (model(ctx, &mut media, m, att), 6.), + Phase::Ready if IMAGES.contains(&e.as_str()) => { + match picture(ctx, &mut media, m, att) { + Some(el) => (el, 6.), + None => (file_box(ctx, &media, m, att, FileState::Local, None), 6.), + } + } + Phase::Ready => { + if e == "xdc" && !media.xdc.contains_key(&att.id) { + media.xdc.insert(att.id.clone(), None); + let src = match source(ctx, att) { + Source::Held(h) => crate::media::Source::Held(h), + Source::File(p) => crate::media::Source::File(p), + }; + media.xdc_queue.push((att.id.clone(), src)); + } + (file_box(ctx, &media, m, att, FileState::Local, None), 6.) + } + _ if BLURRED.contains(&e.as_str()) + && let Some(el) = blur(ctx, &mut media, m, att, phase, failed.as_deref()) => + { + (el, 6.) + } + Phase::Downloading => ( + file_box(ctx, &media, m, att, FileState::Downloading, None), + 6., + ), + Phase::Idle if unsent => { + let label = if m.failed { t::file_not_sent() } else { t::file_sending() }; + ( + file_box(ctx, &media, m, att, FileState::Remote, Some(&label)), + 6., + ) + } + Phase::Idle => { + let state = if failed.is_some() { + FileState::Failed + } else { + FileState::Remote + }; + (file_box(ctx, &media, m, att, state, None), 6.) + } + }; + let top: f32 = if i == 0 { 0. } else { 4f32.max(prev_bottom) }; + col = col.child(div().mt(px(top)).max_w_full().child(el)); + prev_bottom = bottom; + } + Some(col.child(div().h(px(prev_bottom))).into_any_element()) +} + +/// `ModelAttachment.svelte`: the stage, and the file's box only when the stage can't stand +/// in for it: while it uploads, or when the model won't open here. +fn model(ctx: &Ctx, media: &mut Media, m: &Message, att: &Attachment) -> AnyElement { + let (on_act, msg, aid) = (ctx.on_act.clone(), m.id.clone(), att.id.clone()); + let on: crate::model3d::stage::OnAct = std::rc::Rc::new(move |a, w, cx| on_act(&msg, Act::Model(aid.clone(), a), w, cx)); + let src = source(ctx, att); + let ext = ext(att); + let facts = crate::model3d::stage::Facts { att: &att.id, size: att.size, ext: &ext }; + let stage = crate::model3d::stage::stage( + &mut media.models, + &facts, + move || match src { + Source::Held(h) => vector_core::media::open(&h).map(crate::model3d::Src::Held), + Source::File(p) => Some(crate::model3d::Src::File(p)), + }, + on, + ); + let failed = media.models.get(&att.id).is_some_and(|v| matches!(v.phase, crate::model3d::view::Phase::Failed(_))); + let show_file = stage.is_none() || (m.mine && m.pending) || failed; + div() + .w(px(320.)) + .max_w_full() + .flex() + .flex_col() + .gap(px(6.)) + .children(stage) + .when(show_file, |d| d.child(file_box(ctx, media, m, att, FileState::Local, None))) + .into_any_element() +} + +/// `.file-ext-badge` (`attachFileExtBadge`): the file type in a picture's corner, left off +/// one too small to carry it without covering more than a quarter of it. +pub fn ext_badge(ext: &str, w: f32, h: f32) -> Option { + let ext = ext.trim().to_uppercase(); + let (bw, bh) = (12. + 6.5 * ext.chars().count() as f32, 14.); + (!ext.is_empty() && bw <= w * 0.25 && bh <= h * 0.25).then(|| { + div() + .absolute() + .bottom(px(8.)) + .right(px(1.)) + .px(px(6.)) + .rounded(px(14.)) + .bg(ca(0, 0, 0, 0.25)) + .text_color(c(0xffffff)) + .text_size(px(10.)) + .line_height(px(14.)) + .child(ext) + .into_any_element() + }) +} + +/// A fitted size scaled down, aspect kept, to the row it sits in. +fn within(ctx: &Ctx, (w, h): (f32, f32)) -> (f32, f32) { + if ctx.content_w > 0. && w > ctx.content_w { + (ctx.content_w, h * ctx.content_w / w) + } else { + (w, h) + } +} + +/// Sized from what the sender said while the file's own header is read. +fn video_placeholder(ctx: &Ctx, att: &Attachment) -> AnyElement { + let (w, h) = within(ctx, att + .img_meta + .as_ref() + .filter(|i| i.width > 0 && i.height > 0) + .map_or((crate::video::MAX_W, 253.), |i| crate::video::fit(i.width, i.height))); + div().w(px(w)).h(px(h)).rounded(px(8.)).bg(gpui::black()).into_any_element() +} + +fn act( + ctx: &Ctx, + m: &Message, + a: Act, +) -> impl Fn(&gpui::ClickEvent, &mut gpui::Window, &mut gpui::App) + 'static { + let (on_act, id) = (ctx.on_act.clone(), m.id.clone()); + move |_, w, cx| { + cx.stop_propagation(); + on_act(&id, a.clone(), w, cx) + } +} + +/// `ImageAttachment`: the picture at its fitted size, or its blur under a Spoiler veil. +fn picture(ctx: &Ctx, media: &mut Media, m: &Message, att: &Attachment) -> Option { + let meta = att + .img_meta + .as_ref() + .filter(|i| i.width > 0 && i.height > 0); + let veiled = spoiler(att) && !media.revealed.contains(&att.id); + if veiled + && let Some(meta) = meta + && let (w, h) = within(ctx, blur_size(meta)) + && let Some(thumb) = media.thumb(&meta.thumbhash) + { + return Some( + div() + .id(SharedString::from(format!("veil-{}", att.id))) + .relative() + .w(px(w)) + .h(px(h)) + .cursor_pointer() + .on_click(act(ctx, m, Act::RevealMedia(att.id.clone()))) + .child(img(thumb).size_full().object_fit(gpui::ObjectFit::Fill).rounded(px(8.))) + .child( + div() + .absolute() + .inset_0() + .flex() + .flex_col() + .items_center() + .justify_center() + .gap(px(4.)) + .child( + svg() + .path("icons/eye-off.svg") + .size(px(22.)) + .text_color(c(0xffffff)), + ) + .child( + div() + .text_size(px(13.)) + .line_height(px(18.2)) + .font_weight(FontWeight::MEDIUM) + .text_color(c(0xffffff)) + .child(t::file_spoiler()), + ), + ) + .into_any_element(), + ); + } + let max = |w: f32, h: f32| { + ( + ((w * ctx.scale).ceil() as u32).max(1), + ((h * ctx.scale).ceil() as u32).max(1), + ) + }; + let want = match meta { + Some(i) => { + let (w, h) = within(ctx, media::fit(i.width, i.height)); + max(w, h) + } + None => max(media::MAX_W, media::MAX_H), + }; + let pending = m.mine && m.pending; + match media.image(&att.id, source(ctx, att), &ext(att), want) { + Slot::Ready { image, w, h } => { + let (fw, fh) = within(ctx, media::fit(w, h)); + let (hash, path) = match source(ctx, att) { + Source::Held(h) => (Some(h), None), + Source::File(p) => (None, Some(p)), + }; + let open = crate::viewer::Open { + image: image.clone(), + w, + h, + full: Some(crate::viewer::Full { + hash, + path, + ext: ext(att), + url: None, + }), + }; + Some( + div() + .id(SharedString::from(format!("pic-{}", att.id))) + .relative() + .when(!pending, |d| { + d.cursor_pointer().on_click(act(ctx, m, Act::View(open))) + }) + .child( + img(image) + .w(px(fw)) + .h(px(fh)) + .rounded(px(8.)) + .when(pending, |i| i.opacity(0.25)), + ) + .when(pending, |d| d.child(upload_overlay(ctx, m, media.transfers.get(&m.id), fw, fh))) + .when(!pending && media.image_types, |d| d.children(ext_badge(&ext(att), fw, fh))) + .into_any_element(), + ) + } + // Holds the size it will draw, so the row doesn't grow under the reader. + Slot::Loading => Some(match meta { + Some(i) => { + let (w, h) = within(ctx, media::fit(i.width, i.height)); + div().w(px(w)).h(px(h)).into_any_element() + } + None => div().into_any_element(), + }), + Slot::Failed => None, + } +} + +/// A blur's box: the fitted width, rounded as the `width` attribute rounds it. +fn blur_size(meta: &vector_core::types::ImageMetadata) -> (f32, f32) { + let (w, _) = media::fit(meta.width, meta.height); + let w = w.round(); + ( + w, + (w * meta.height as f32 / meta.width as f32).min(media::MAX_H), + ) +} + +/// `ThumbhashAttachment`: the blur at the size the picture will take, under its download +/// ring or a Download box. None when there is no blur, so the caller shows a file box. +fn blur( + ctx: &Ctx, + media: &mut Media, + m: &Message, + att: &Attachment, + phase: Phase, + failed: Option<&str>, +) -> Option { + let meta = att + .img_meta + .as_ref() + .filter(|i| i.width > 0 && i.height > 0)?; + let (w, h) = within(ctx, blur_size(meta)); + let thumb = media.thumb(&meta.thumbhash)?; + let downloading = phase == Phase::Downloading; + let running = media.transfers.contains_key(&att.id); + let opacity = if downloading { + if running { 0.7 } else { 0.8 } + } else { + 0.6 + }; + let overlay = if downloading { + let t = media.transfers.get(&att.id).cloned().unwrap_or_default(); + let size = 48f32.min(w.min(h) * 0.7); + let note = t.note(); + let mut o = div() + .relative() + .flex() + .items_center() + .justify_center() + .child(ring(size, t.pct)); + if h >= 118. && w >= 120. && !note.is_empty() { + o = o.child( + div() + .absolute() + .top(px(size + 7.)) + .w(px(200.)) + .flex() + .justify_center() + .text_size(px(11.)) + .line_height(px(11.)) + .text_color(white_a(0.82)) + .whitespace_nowrap() + .child(note), + ); + } + o.into_any_element() + } else if ctx.held { + held_box(w, h) + } else { + download_box(ctx, m, att, w, h, failed, media.resume_progress(&att.id, att.size)) + }; + Some( + div() + .relative() + .w(px(w)) + .h(px(h)) + .child(img(thumb).size_full().object_fit(gpui::ObjectFit::Fill).rounded(px(8.)).opacity(opacity)) + .child( + div() + .absolute() + .inset_0() + .flex() + .items_center() + .justify_center() + .child(overlay), + ) + .into_any_element(), + ) +} + +/// `.thumb-held`: a request's media waits for the chat to be accepted. +fn held_box(w: f32, h: f32) -> AnyElement { + let compact = w < 150. || h < 40.; + div() + .id("thumb-held") + .max_w(px(w * 0.94)) + .flex() + .items_center() + .gap(px(8.)) + .when(compact, |d| d.p(px(7.)).tip(t::file_accept_to_view())) + .when(!compact, |d| d.pl(px(10.)).pr(px(14.)).py(px(7.))) + .border_1() + .border_color(c(0x363636)) + .rounded(px(10.)) + .bg(ca(12, 12, 12, 0.82)) + .text_size(px(13.)) + .line_height(px(18.)) + .text_color(white_a(0.92)) + .whitespace_nowrap() + .child(svg().path("icons/shield-alert.svg").size(px(18.)).flex_shrink_0().text_color(c(PRIMARY))) + .when(!compact, |d| d.child(div().min_w_0().truncate().child(t::file_accept_to_view()))) + .into_any_element() +} + +/// `.thumb-download`: the icon tile and two lines, or the tile alone on a small blur. +fn download_box( + ctx: &Ctx, + m: &Message, + att: &Attachment, + w: f32, + h: f32, + failed: Option<&str>, + paused: Option, +) -> AnyElement { + // Every server the message names says the file is gone: nothing on this side is at fault. + let gone = failed == Some(crate::backend::attachments::GONE_EVERYWHERE); + // A failure says why even where the row won't fit: the words go under the icon. + let stacked = failed.is_some() && (w < 205. || h < 76.) && w >= 120. && h >= 140.; + let compact = (w < 205. || h < 76.) && !stacked; + let color = if failed.is_some() { + c(DANGER) + } else { + c(PRIMARY) + }; + let icon = if gone { + "icons/file-minus.svg" + } else if failed.is_some() { + "icons/refresh.svg" + } else { + "icons/download.svg" + }; + let tile_size = if compact { 40. } else { 44. }; + let tile = div() + .size(px(tile_size)) + .flex_shrink_0() + .flex() + .items_center() + .justify_center() + .border_1() + .border_color(if failed.is_some() { + c(DANGER).opacity(0.45) + } else { + c(BOX_LINE_HOVER) + }) + .rounded(px(10.)) + .child( + svg() + .path(icon) + .size(px(tile_size * 0.64)) + .text_color(color), + ); + let title = match failed { + Some(_) if gone => t::file_unavailable().to_string(), + Some(_) => t::file_download_failed().to_string(), + None if paused.is_some() => t::file_resume_download().to_string(), + None if att.extension.trim().is_empty() => t::file_download().to_string(), + None => t::file_download_type(att.extension.trim().to_uppercase()).to_string(), + }; + let sub = match failed { + Some(_) if gone => t::file_gone().to_string(), + Some(e) if !e.is_empty() => failure(e), + Some(_) => t::file_tap_retry().to_string(), + None if paused.is_some() => t::file_resume_done(paused.unwrap_or_default()).to_string(), + None if att.size > 0 => media::format_bytes(att.size), + None => t::file_unknown_size().to_string(), + }; + let base = div() + .id(SharedString::from(format!("dl-{}", att.id))) + .cursor_pointer() + .on_click(act(ctx, m, Act::Download(att.id.clone()))); + if compact { + return base + .tip(format!("{title} · {sub}")) // i18n-exempt: separator + .child( + tile.bg(ca(12, 12, 12, 0.82)) + .hover(|s| s.bg(ca(24, 24, 24, 0.88)).border_color(c(0x4a4a4a))), + ) + .into_any_element(); + } + base.max_w(px(w * 0.94)) + .flex() + .items_center() + .gap(px(12.)) + .p(px(10.)) + .border_1() + .border_color(c(BOX_LINE_HOVER)) + .rounded(px(12.)) + .bg(ca(12, 12, 12, 0.82)) + .hover(|s| s.bg(ca(24, 24, 24, 0.88)).border_color(c(0x4a4a4a))) + .when(stacked, |d| d.flex_col().gap(px(8.))) + .child(tile) + .child( + div() + .min_w_0() + .when(!stacked, |d| d.pr(px(4.))) + .when(stacked, |d| d.items_center().text_center()) + .flex() + .flex_col() + .child( + div() + .text_size(px(14.)) + .line_height(px(17.5)) + .text_color(white_a(0.92)) + .when(!stacked, |d| d.whitespace_nowrap().overflow_hidden().text_ellipsis()) + .child(title), + ) + .child( + div() + .mt(px(2.)) + .text_size(px(12.)) + .line_height(px(15.)) + .text_color(white_a(0.34)) + .when(!stacked, |d| d.whitespace_nowrap().overflow_hidden().text_ellipsis()) + .child(sub), + ), + ) + .into_any_element() +} + +/// `UploadOverlay`: over a picture or video still uploading, the ring, a line under it whenever +/// the ring can't speak for itself (on media with room for one), and the cancel, shown on hover +/// until the last byte has left. +fn upload_overlay(ctx: &Ctx, m: &Message, t: Option<&Transfer>, w: f32, h: f32) -> AnyElement { + const RING: f32 = 48.; + let note = t.map(Transfer::upload_note).filter(|n| !n.is_empty() && w >= 120. && h >= 118.); + let group = SharedString::from(format!("upload-{}", m.id)); + div() + .absolute() + .top_0() + .left_0() + .w(px(w)) + .h(px(h)) + .group(group.clone()) + .flex() + .items_center() + .justify_center() + .child( + div() + .relative() + .size(px(RING)) + .child(ring(RING, t.and_then(|t| t.pct))) + // `.media-progress-note`: hung under the ring, so the ring never moves for it. + .children(note.map(|n| { + div() + .absolute() + .top(px(RING + 7.)) + .left(px(RING / 2. - 120.)) + .w(px(240.)) + .flex() + .justify_center() + .whitespace_nowrap() + .text_size(px(11.)) + .line_height(px(13.)) + .text_color(white_a(0.82)) + .child(n) + })), + ) + .when(!t.is_some_and(Transfer::publishing), |d| { + // `.upload-cancel-btn`: fills the ring's hole. + d.child( + div().absolute().inset_0().flex().items_center().justify_center().child( + div() + .id(SharedString::from(format!("upload-cancel-{}", m.id))) + .size(px(40.)) + .rounded_full() + .bg(gpui::black().opacity(0.6)) + .flex() + .items_center() + .justify_center() + .text_size(px(16.)) + .text_color(c(0xffffff)) + .cursor_pointer() + .opacity(0.) + .group_hover(group, |s| s.opacity(1.)) + .on_click(act(ctx, m, Act::CancelUpload(m.id.clone()))) + .child("\u{2715}"), + ), + ) + }) + .into_any_element() +} + +/// `.miniapp-downloading-spinner`: a 4px ring filled to `pct` from the top, turning once +/// every two seconds. +pub fn ring(size: f32, pct: Option) -> AnyElement { + spinner( + size, + 3.5, + 2., + pct.unwrap_or(5.).clamp(0., 100.) / 100., + white_a(0.2), + c(PRIMARY), + ) +} + +/// A turning ring: `fill` of it in the accent over a `track`, one turn every `period` seconds. +pub fn spinner( + size: f32, + thickness: f32, + period: f32, + fill: f32, + track: gpui::Hsla, + color: gpui::Hsla, +) -> AnyElement { + canvas( + |_, _, _| {}, + move |bounds: Bounds, _, window, _| { + let turn = (EPOCH.elapsed().as_secs_f32() / period).fract() * TAU; + let center = bounds.center(); + let r_out = f32::from(bounds.size.width.min(bounds.size.height)) / 2.; + let r_in = r_out - thickness; + let arc = |from: f32, to: f32| -> Option> { + let steps = ((to - from).abs() / TAU * 96.).ceil().max(2.) as usize; + let at = + |r: f32, a: f32| point(center.x + px(r * a.sin()), center.y - px(r * a.cos())); + let mut pts = Vec::with_capacity(steps * 2 + 2); + for k in 0..=steps { + pts.push(at(r_out, from + (to - from) * k as f32 / steps as f32)); + } + for k in (0..=steps).rev() { + pts.push(at(r_in, from + (to - from) * k as f32 / steps as f32)); + } + let mut b = PathBuilder::fill(); + b.add_polygon(&pts, true); + b.build().ok() + }; + let split = turn + fill * TAU; + if fill < 1. + && let Some(p) = arc(split, turn + TAU) + { + window.paint_path(p, track); + } + if fill > 0. + && let Some(p) = arc(turn, split) + { + window.paint_path(p, color); + } + window.request_animation_frame(); + }, + ) + .size(px(size)) + .flex_shrink_0() + .into_any_element() +} + +#[derive(Clone, Copy, PartialEq)] +enum FileState { + Local, + Downloading, + Remote, + Failed, +} + +/// `FileBox`: icon, name and what the file is doing; the box is the action. +/// A Mini App shared as a link: nothing fetched until asked, then the attachment's own card. +#[derive(Clone)] +pub enum XdcUrl { + Probing, + Absent, + Fetching, + Failed(String), + Ready(crate::backend::xdcurl::Resolved), +} + +pub fn xdc_url_key(msg: &str, url: &str) -> String { + format!("{msg}|{url}") +} + +/// The card for a message's `.xdc` link, in the shape of an uploaded Mini App's. +pub fn xdc_url_card(ctx: &Ctx, m: &Message) -> Option { + if m.pending || m.failed || ctx.held || !m.attachments.is_empty() { + return None; + } + let url = crate::backend::xdcurl::find(&m.content)?.to_string(); + let key = xdc_url_key(&m.id, &url); + let mut media = ctx.media.borrow_mut(); + let state = match media.xdc_urls.get(&key) { + Some(s) => s.clone(), + None => { + media.xdc_urls.insert(key.clone(), XdcUrl::Probing); + media.xdc_url_queue.push((m.id.clone(), url.clone())); + XdcUrl::Probing + } + }; + let mut att = Attachment { extension: "xdc".into(), name: crate::backend::xdcurl::file_name(&url), id: url.clone(), ..Default::default() }; + let tap = |a: Act| Some(a); + let host = crate::backend::xdcurl::host(&url); + let el = match state { + XdcUrl::Ready(r) => { + att.id = format!("xdcurl:{key}"); + att.name = r.name.clone(); + att.webxdc_topic = Some(r.topic.clone()); + att.downloaded = true; + if !media.xdc.contains_key(&att.id) { + media.xdc.insert(att.id.clone(), None); + media.xdc_queue.push((att.id.clone(), crate::media::Source::File(r.path.clone()))); + } + file_box_on(ctx, &media, m, &att, FileState::Local, None, tap(Act::OpenXdcUrl(url))) + } + XdcUrl::Fetching => file_box_on(ctx, &media, m, &att, FileState::Downloading, None, None), + XdcUrl::Failed(e) => { + let label = t::file_failed_retry(failure(&e)).to_string(); + file_box_on(ctx, &media, m, &att, FileState::Failed, Some(&label), tap(Act::XdcUrl(url))) + } + XdcUrl::Probing | XdcUrl::Absent => { + let label = t::file_tap_to_load(&*host).to_string(); + file_box_on(ctx, &media, m, &att, FileState::Remote, Some(&label), tap(Act::XdcUrl(url))) + } + }; + // The trailing whitespace after Tauri's card wrapper lays a 6px line under it. + Some(div().pb(px(6.)).flex().flex_col().items_start().child(el).into_any_element()) +} + +fn file_box( + ctx: &Ctx, + media: &Media, + m: &Message, + att: &Attachment, + state: FileState, + label: Option<&str>, +) -> AnyElement { + file_box_on(ctx, media, m, att, state, label, None) +} + +/// `tap` takes over the box's click and its button: for a card no attachment backs. +fn file_box_on( + ctx: &Ctx, + media: &Media, + m: &Message, + att: &Attachment, + state: FileState, + label: Option<&str>, + tap: Option, +) -> AnyElement { + let synthetic = tap.is_some() || m.attachments.iter().all(|a| a.id != att.id); + let (icon, description) = data::file_type(&att.extension); + let mini = icon == "gift"; + let icon = if mini { "gamepad" } else { icon }; + let package = mini + .then(|| media.xdc.get(&att.id).cloned().flatten()) + .flatten() + .filter(|_| state == FileState::Local); + let title: SharedString = match &package { + Some(p) => if p.name.is_empty() { crate::t::file_type_mini_app() } else { crate::kit::one_line(&p.name).into_owned().into() }, + None if att.name.is_empty() => description.clone(), + None => crate::kit::one_line(&att.name).into_owned().into(), + }; + let live = mini.then(|| { + let key = att.webxdc_topic.clone().unwrap_or_else(|| format!("att:{}", att.id)); + media.xdc_live.get(&key).cloned().unwrap_or_default() + }); + let e = ext(att); + let kind = if e.is_empty() { + description.to_string() + } else { + format!(".{e}") + }; + let size = (att.size > 0).then(|| media::format_bytes(att.size)); + let glyph_color = if state == FileState::Failed { + c(DANGER) + } else { + white_a(0.7) + }; + let title_color = if state == FileState::Local { + c(PRIMARY) + } else { + white_a(0.92) + }; + + let uploading = m.mine && m.pending && state == FileState::Local; + let state = if uploading { + FileState::Downloading + } else { + state + }; + let text = div().flex_1().min_w_0().flex().flex_col(); + let text = if state == FileState::Downloading { + let t: Transfer = media + .transfers + .get(if uploading { &m.id } else { &att.id }) + .cloned() + .unwrap_or_default(); + let note = t.note(); + text.child( + div() + .flex() + .items_baseline() + .whitespace_nowrap() + .text_size(px(15.)) + .line_height(px(18.75)) + .child( + div() + .flex_shrink(1.) + .min_w_0() + .overflow_hidden() + .text_ellipsis() + .text_color(title_color) + .child(title), + ) + .child( + div() + .flex_shrink_0() + .flex() + .text_size(px(12.75)) + .text_color(white_a(0.34)) + .child(size.map(|s| format!(" — {s}")).unwrap_or_default()) + .child(div().ml(px(4.5)).w(px(112.)).child(if note.is_empty() { + String::new() + } else { + format!("· {note}") // i18n-exempt: separator + })), + ), + ) + .child(bar(t.pct)) + } else { + let sub = match (label, state) { + (Some(l), _) => l.to_string(), + (None, FileState::Failed) if media.failed.get(&att.id).is_some_and(|r| r == crate::backend::attachments::GONE_EVERYWHERE) => { + t::file_unavailable_gone().into() + } + (None, FileState::Failed) => { + let reason = media.failed.get(&att.id).map(|r| failure(r)).unwrap_or_default(); + match (reason.is_empty(), synthetic) { + (true, _) => t::file_download_failed_retry().into(), + // Its retry button says the rest. + (false, true) => t::file_failed(reason).into(), + (false, false) => t::file_failed_retry(reason).into(), + } + } + _ => match (media.resume_note(&att.id, att.size), &size) { + (Some(r), _) => r, + (None, Some(s)) => t::file_kind_size(&*kind, &**s).into(), + (None, None) => kind, + }, + }; + let text = text.child( + div() + .text_size(px(15.)) + .line_height(px(18.75)) + .text_color(title_color) + .whitespace_nowrap() + .overflow_hidden() + .text_ellipsis() + .child(title), + ); + match live.as_ref().filter(|_| state == FileState::Local && label.is_none()) { + Some(live) => text.child(session_line(ctx, live)), + None => text.child( + div() + .mt(px(3.)) + .text_size(px(12.)) + .line_height(px(15.)) + .text_color(white_a(0.55)) + .whitespace_nowrap() + .overflow_hidden() + .text_ellipsis() + .child(sub), + ), + } + }; + + let button = |icon: &'static str, color: Hsla, border: Hsla, a: Act| { + div() + .id(SharedString::from(format!("fb-act-{}", att.id))) + .size(px(34.)) + .flex_shrink_0() + .flex() + .items_center() + .justify_center() + .border_1() + .border_color(border) + .rounded(px(8.)) + .cursor_pointer() + .hover(|s| s.bg(white_a(0.07))) + .on_click(act(ctx, m, a)) + .child(svg().path(icon).size(px(17.)).text_color(color)) + }; + let action = match (state, label) { + (FileState::Remote, _) if synthetic => tap.clone().map(|a| button("icons/download.svg", c(PRIMARY), c(BOX_LINE_HOVER), a)), + (FileState::Failed, _) if synthetic => tap.clone().map(|a| button("icons/refresh.svg", c(DANGER), c(DANGER).opacity(0.45), a)), + _ if synthetic => None, + (_, Some(_)) => None, + (FileState::Downloading, _) if uploading => { + let done = media + .transfers + .get(&m.id) + .and_then(|t| t.pct) + .is_some_and(|p| p >= 100.); + (!done).then(|| { + button( + "icons/x.svg", + white_a(0.7), + c(BOX_LINE_HOVER), + Act::CancelUpload(m.id.clone()), + ) + }) + } + (FileState::Downloading, _) => Some(button( + "icons/x.svg", + white_a(0.7), + c(BOX_LINE_HOVER), + Act::CancelDownload(att.id.clone()), + )), + (FileState::Failed, _) => Some(button( + "icons/refresh.svg", + c(DANGER), + c(DANGER).opacity(0.45), + Act::Download(att.id.clone()), + )), + (FileState::Remote, _) => Some(button( + "icons/download.svg", + c(PRIMARY), + c(BOX_LINE_HOVER), + Act::Download(att.id.clone()), + )), + (FileState::Local, _) => None, + }; + let click = match state { + _ if synthetic => tap, + FileState::Local => Some(Act::OpenFile(att.id.clone())), + FileState::Remote | FileState::Failed if label.is_none() => { + Some(Act::Download(att.id.clone())) + } + _ => None, + }; + + div() + .id(SharedString::from(format!("fb-{}", att.id))) + .flex() + .items_center() + .when(ctx.vw > 480., |d| d.gap(px(12.)).px(px(12.)).py(px(10.))) + .when(ctx.vw <= 480., |d| d.gap(px(10.)).p(px(10.))) + .min_w(px(240.)) + .max_w(px(500f32.min(ctx.vw - 100.))) + .border_1() + .border_color(c(BOX_LINE)) + .rounded(px(12.)) + .bg(c(BOX_BG)) + .when(state != FileState::Downloading, |d| { + d.hover(|s| s.bg(c(BOX_BG_HOVER)).border_color(c(BOX_LINE_HOVER))) + .cursor_pointer() + }) + .when_some(click, |d, a| d.on_click(act(ctx, m, a))) + .child( + div() + .size(px(40.)) + .flex_shrink_0() + .flex() + .items_center() + .justify_center() + .child(match package.as_ref().and_then(|p| p.icon.clone()) { + Some(path) => img(path) + .size(px(40.)) + .rounded(px(8.)) + .object_fit(gpui::ObjectFit::Cover) + .into_any_element(), + None => svg() + .path(format!("icons/{icon}.svg")) + .size(px(32.)) + .text_color(glyph_color) + .into_any_element(), + }), + ) + .child(text) + .children(action) + .into_any_element() +} + +/// `.file-box-session`: what the Mini App is doing, and who else is in it. +fn session_line(ctx: &Ctx, live: &crate::media::XdcLive) -> AnyElement { + let players = if live.peers.is_empty() { live.count } else { live.peers.len() }; + let label = if live.active { + t::file_app_playing() + } else if players > 0 { + t::file_app_join() + } else { + t::file_app_play() + }; + let mut peers: Vec<&String> = live.peers.iter().collect(); + peers.sort(); + peers.truncate(5); + let n = peers.len(); + div() + .mt(px(3.)) + .flex() + .items_center() + .gap(px(10.)) + .text_size(px(12.)) + .line_height(px(15.)) + .whitespace_nowrap() + .child( + div() + .text_color(if live.active { c(PRIMARY) } else { white_a(0.55) }) + .child(label), + ) + .when(players > 0, |d| { + d.child( + div() + .px(px(8.)) + .py(px(2.)) + .rounded(px(10.)) + .bg(c(PRIMARY).opacity(0.15)) + .border(px(0.5)) + .border_color(c(PRIMARY).opacity(0.3)) + .text_color(c(PRIMARY)) + .text_size(px(10.2)) + .font_weight(FontWeight::MEDIUM) + .flex() + .items_center() + .child( + div() + .flex() + .items_center() + .mr(px(4.)) + .children(peers.iter().enumerate().map(|(i, npub)| { + let named = ctx.store.profiles.get(*npub).is_some_and(|p| { + !(p.nickname.is_empty() && p.name.is_empty() && p.display_name.is_empty()) + }); + div() + .id(SharedString::from(format!("xdc-peer-{npub}"))) // i18n-exempt: element id + .when(named, |d| d.tip(ctx.store.name(npub))) + .when(i > 0, |d| d.ml(px(-5.))) + .size(px(14.)) + .rounded_full() + .border_1() + .border_color(c(0x1a1a2e)) + .overflow_hidden() + .child(crate::ui::avatar(ctx.store, npub, 14.)) + .into_any_element() + })) + .when(n == 0, |d| { + d.child(svg().path("icons/group-placeholder.svg").size(px(14.))) + }), + ) + .child(t::file_app_online(players)), + ) + }) + .into_any_element() +} + +/// `.file-box-bar`: 4px, the theme colour up to the progress. +fn bar(pct: Option) -> impl IntoElement { + let fill = pct.unwrap_or(0.).clamp(0., 100.) / 100.; + div() + .mt(px(7.)) + .h(px(4.)) + .w_full() + .rounded_full() + .bg(white_a(0.12)) + .overflow_hidden() + .child( + div() + .h_full() + .w(gpui::relative(fill)) + .rounded_full() + .bg(c(PRIMARY)), + ) +} + +/// Why a download failed, in the card's few words: the server's answer by kind, else the +/// error's first line without the "failed" its card already says. +fn failure(raw: &str) -> String { + let mut text = raw.trim(); + loop { + let lower = text.to_ascii_lowercase(); + // i18n-exempt: prefixes of core's English errors + let Some(rest) = ["download failed:", "failed to download:", "failed:", "error:"] + .iter() + .find_map(|p| lower.starts_with(p).then(|| text[p.len()..].trim_start())) + else { + break; + }; + text = rest; + } + let lower = text.to_ascii_lowercase(); + let code = lower + .strip_prefix("http ") + .and_then(|r| r.get(..3)) + .and_then(|c| c.parse::().ok()); + match code { + Some(404 | 410) => return t::file_why_missing(code.unwrap_or_default()).into(), + Some(401 | 403) => return t::file_why_refused(code.unwrap_or_default()).into(), + Some(429) => return t::file_why_busy().into(), + Some(c @ 500..=599) => return t::file_why_down(c).into(), + _ => {} + } + if lower.contains("timed out") || lower.contains("timeout") { // i18n-exempt: core's English errors + return t::file_why_timeout().into(); + } + if lower.contains("dns") || lower.contains("connect") { + return t::file_why_unreachable().into(); + } + text.lines().next().unwrap_or_default().chars().take(80).collect() +} + +#[cfg(test)] +mod tests { + #[test] + fn a_failure_reads_as_its_kind_without_the_failed_its_card_says() { + // i18n-exempt: core's English errors and the shown English + assert_eq!(super::failure("download failed: HTTP 502 Bad Gateway"), "The server is down (502)"); + assert_eq!(super::failure("Failed: download failed: HTTP 404 Not Found"), "Not on the server (404)"); + assert_eq!(super::failure("operation timed out"), "The server took too long"); + assert_eq!(super::failure("download failed: checksum mismatch\nmore"), "checksum mismatch"); + } +} diff --git a/crates/vector-gpui/src/audio.rs b/crates/vector-gpui/src/audio.rs new file mode 100644 index 000000000..acc8baae3 --- /dev/null +++ b/crates/vector-gpui/src/audio.rs @@ -0,0 +1,1924 @@ +//! Audio attachments on the shared engine (`AudioPlayer.svelte`, `AudioSession`): play and +//! pause, the spectral bars, the scrub, and one player sounding at a time. + +use crate::kit::Tipped as _; +use std::cell::Cell; +use std::collections::{HashMap, HashSet}; +use std::rc::Rc; +use std::sync::{Arc, OnceLock}; +use std::time::Instant; + +use futures::channel::mpsc::{UnboundedReceiver, UnboundedSender, unbounded}; +use gpui::{ + AnyElement, App, Bounds, Corners, CursorStyle, HitboxBehavior, InteractiveElement, + IntoElement, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, ParentElement, + Pixels, RenderImage, SharedString, StatefulInteractiveElement, Styled, Window, canvas, div, fill, point, + prelude::*, px, size, svg, +}; +use vector_media::audio_engine::{AudioEngine, AudioInput}; + +use crate::t; +use crate::theme::*; + +pub const EXTENSIONS: &[&str] = &["wav", "mp3", "flac", "aac", "m4a", "ogg"]; + +/// A bar at rest: this short, lifted this far. +const REST_SCALE: f32 = 0.15; +const REST_Y: f32 = -9.; + +static EVENTS: OnceLock> = OnceLock::new(); + +/// The engine's own events (`audio_waveform`, `audio_ended`, `audio_duration`), for the UI. +pub fn engine_event(event: &str, payload: serde_json::Value) { + if let Some(tx) = EVENTS.get() { + let _ = tx.unbounded_send((event.to_string(), payload)); + } +} + +pub fn listen() -> Option> { + let (tx, rx) = unbounded(); + EVENTS.set(tx).ok().map(|_| rx) +} + +pub fn engine() -> Result<&'static AudioEngine, String> { + AudioEngine::init(); + AudioEngine::get() +} + +struct Wave { + data: Vec, + fps: f32, + bins: usize, +} + +#[derive(Clone, Copy, PartialEq)] +enum Look { + /// Never played: the stylesheet's resting dots. + Fresh, + Live, + /// Stopped: the bars settle, the played part brighter. + Settling, + Rest, +} + +pub struct Player { + pub msg: String, + path: Option, + source: Option, + pub loading: bool, + pub playing: bool, + paused_at: u64, + start_pos: u64, + started: Option, + pub duration: u64, + wave: Option, + display: Vec, + lift: f32, + look: Look, + last_seek: Option, + pub album: Option, +} + +/// Where the audio is, kept so a load can run off the UI thread. +#[derive(Clone)] +pub enum AudioInputSpec { + File(std::path::PathBuf), + Held([u8; 32]), + /// A sealed cache file, and the type of its bytes. + Sealed(std::path::PathBuf, &'static str), + /// A web video read while it downloads. + Stream(std::sync::Arc>), +} + +impl AudioInputSpec { + pub(crate) fn open(&self) -> Result { + match self { + AudioInputSpec::File(p) => { + if p.exists() { + Ok(AudioInput::File(p.clone())) + } else { + Err(t::audio_not_found().into()) + } + } + AudioInputSpec::Sealed(p, mime) => vector_core::vcache::open(p, mime) + .map(AudioInput::Held) + .ok_or_else(|| t::audio_video_not_found().into()), + AudioInputSpec::Held(h) => vector_core::media::open(h) + .map(AudioInput::Held) + .ok_or_else(|| t::audio_not_found().into()), + AudioInputSpec::Stream(s) => Ok(AudioInput::Held(s.clone())), + } + } +} + +impl Player { + fn new(msg: &str) -> Self { + Player { + msg: msg.to_string(), + path: None, + source: None, + loading: false, + playing: false, + paused_at: 0, + start_pos: 0, + started: None, + duration: 0, + wave: None, + display: Vec::new(), + lift: REST_Y, + look: Look::Fresh, + last_seek: None, + album: None, + } + } + + pub fn position(&self) -> u64 { + if !self.playing { + return self.paused_at; + } + let p = self.start_pos + self.started.map_or(0, |s| s.elapsed().as_millis() as u64); + if self.duration > 0 { p.min(self.duration) } else { p } + } + + pub fn display(&self) -> &[f32] { + &self.display + } + + fn progress(&self) -> f32 { + if self.duration == 0 { + return 0.; + } + self.position() as f32 / self.duration as f32 + } +} + +#[derive(Default)] +pub struct Audio { + players: HashMap, + /// Durations read from the file's header, before anything plays. + probed: HashMap, + probing: HashSet, + sources: HashMap, + active: Option, + /// Work a draw asked for, for the app to run. + pub queue: Vec, + /// A named file's tags: None once read and found empty. + tags: HashMap>>, + reading: HashSet, + pub sheets: HashMap, + /// Albums showing every song rather than the first few. + pub all_tracks: HashSet, + pub transcripts: crate::transcript::Transcripts, + /// Auto-transcribe is on and its model is here; None until read, and after a settings change. + pub auto_transcribe: Option, + /// Cards whose content box measured 380px or less last frame (the album's container query). + pub narrow: Rc>>, +} + +/// What a file's tags give the card. +pub struct Tags { + pub title: Option, + pub artist: Option, + pub album: Option, + pub year: Option, + pub cover: Option>, + /// The art shrunk to a few pixels: scaled up, it is the card's blurred glow. + pub glow: Option>, + /// The same for the card with its lyrics open, a taller window on the art. + pub glow_tall: Option>, + /// The art's own colour for the controls; white where the art has none. + pub accent: Option, + pub lyrics: Option, + pub chapters: Vec, +} + +#[derive(Clone, Copy, Debug)] +pub enum Act { + Toggle, + /// A scrub to this fraction; `done` on release. + Seek(f32, bool), + Lyrics, + /// The cover art, opened in the viewer. + Art, + Album(AlbumAct), + Transcribe, + CancelDownload, + /// A transcript section clicked: to this millisecond. + SeekTo(u64), + /// A lyric line clicked (play from it), or None: the reader scrolled, so hold the view. + Line(Option), +} + +#[derive(Clone, Copy, Debug)] +pub enum AlbumAct { + /// Play from the first song, or a random one. + Play(bool), + Track(usize), + Next, + Prev, + Shuffle, + Repeat, + More, + Art, +} + +/// What the app does for the audio state: the work that needs the engine or a thread. +pub enum Work { + Probe(String, AudioInputSpec), + Load(String, AudioInputSpec), + Tags(String, AudioInputSpec), + Transcribe(String, AudioInputSpec), +} + +impl Audio { + pub fn duration(&self, att: &str) -> u64 { + self.players + .get(att) + .map(|p| p.duration) + .filter(|d| *d > 0) + .or_else(|| self.probed.get(att).copied()) + .unwrap_or(0) + } + + /// A read of a named file's tags, once per file. + pub fn want_tags(&mut self, att: &str, input: &AudioInputSpec) { + if !self.tags.contains_key(att) && self.reading.insert(att.to_string()) { + self.queue.push(Work::Tags(att.to_string(), input.clone())); + } + } + + pub fn transcribed(&mut self, att: &str, res: Result) { + use crate::transcript::{Phase, Section}; + if self.transcripts.download.as_ref().is_some_and(|d| d.until.is_none()) { + self.transcripts.download_done(res.is_ok()); + } + let phase = match res { + Ok(r) => Phase::Ready { + sections: r + .sections + .into_iter() + .map(|s| Section { text: s.text.trim().to_string(), at: s.at.max(0) as u64 }) + .filter(|s| !s.text.is_empty()) + .collect(), + lang: r.lang, + language: r.language, + }, + Err(e) => Phase::Error(e), + }; + self.transcripts.landed(att, phase); + } + + /// Read, and found to be music: it has its own words, or none to transcribe. + pub fn tags_read(&self, att: &str) -> Option { + self.tags.get(att).map(|t| { + t.as_ref().is_some_and(|t| t.title.is_some() || t.artist.is_some() || t.album.is_some() || t.lyrics.is_some()) + }) + } + + pub fn tags(&self, att: &str) -> Option<&Arc> { + self.tags.get(att).and_then(|t| t.as_ref()) + } + + pub fn read_tags(&mut self, att: String, tags: Option) { + self.reading.remove(&att); + self.tags.insert(att, tags.map(Arc::new)); + } + + /// A probe for the header's duration, once per file. + pub fn want_probe(&mut self, att: &str, input: &AudioInputSpec) { + if !self.probed.contains_key(att) && self.probing.insert(att.to_string()) { + self.queue.push(Work::Probe(att.to_string(), input.clone())); + } + } + + /// `autoTranscribe`: a fresh voice message from someone else transcribes itself. + pub fn want_transcript(&mut self, att: &str, input: &AudioInputSpec) { + if self.transcripts.get(att).is_some() || self.transcripts.download.is_some() { + return; + } + let on = *self.auto_transcribe.get_or_insert_with(|| { + crate::backend::transcribe::auto_transcribe() + && crate::backend::transcribe::downloaded(&crate::backend::transcribe::choice().0) + }); + if on && self.transcripts.toggle(att).is_some() { + self.queue.push(Work::Transcribe(att.to_string(), input.clone())); + } + } + + pub fn probed(&mut self, att: String, ms: u64) { + self.probing.remove(&att); + self.probed.insert(att, ms); + } + + pub fn player(&self, att: &str) -> Option<&Player> { + self.players.get(att) + } + + pub fn act(&mut self, msg: &str, att: &str, input: AudioInputSpec, act: Act) -> Option { + match act { + Act::Toggle => { + if self.players.get(att).is_some_and(|p| p.playing || p.loading) { + self.pause(att); + None + } else { + self.play(msg, att, input) + } + } + Act::Lyrics => { + self.sheets.entry(att.to_string()).or_default().toggle(); + None + } + Act::Art => None, + Act::Line(None) => { + self.sheets.entry(att.to_string()).or_default().hold(); + None + } + Act::Line(Some(ms)) => { + self.sheets.entry(att.to_string()).or_default().release(); + let duration = self.duration(att).max(1); + let work = self.act(msg, att, input.clone(), Act::Seek(ms as f32 / duration as f32, true)); + if self.players.get(att).is_some_and(|p| p.playing || p.loading) { + work + } else { + self.play(msg, att, input) + } + } + Act::Album(a) => self.album_act(msg, att, input, a), + Act::Transcribe => { + self.transcripts.toggle(att)?; + let (model, _) = crate::backend::transcribe::choice(); + if !crate::backend::transcribe::downloaded(&model) { + self.transcripts.download = Some(crate::transcript::Download { + pct: 0, + text: t::audio_model_downloading().into(), + failed: false, + until: None, + }); + } + Some(Work::Transcribe(att.to_string(), input)) + } + Act::CancelDownload => { + crate::backend::transcribe::cancel_download(); + None + } + Act::SeekTo(ms) => { + let p = self.player_mut(msg, att); + if let Some(a) = p.album.as_mut() { + a.seeked(ms); + } + self.seek_ms(att, ms); + None + } + Act::Seek(frac, done) => { + let probed = self.probed.get(att).copied().unwrap_or(0); + let p = self.player_mut(msg, att); + if p.duration == 0 { + p.duration = probed; + } + if p.duration == 0 { + return None; + } + let (start, end) = p.album.as_ref().map_or((0, p.duration), |a| a.now(p.duration)); + let ms = start + (frac.clamp(0., 1.) * end.saturating_sub(start) as f32) as u64; + if let Some(a) = p.album.as_mut() { + a.seeked(ms); + } + if p.playing { + p.start_pos = ms; + p.started = Some(Instant::now()); + } else { + p.paused_at = ms; + if p.look == Look::Fresh { + p.look = Look::Rest; + } + } + let due = done || p.last_seek.is_none_or(|t| t.elapsed().as_millis() >= 50); + if due && let (Some(id), Ok(e)) = (p.source, engine()) { + let _ = e.seek(id, ms); + p.last_seek = Some(Instant::now()); + } + if done { + p.last_seek = None; + } + None + } + } + } + + /// The player for `att`, knowing its album once the tags have one. + fn player_mut(&mut self, msg: &str, att: &str) -> &mut Player { + let chapters = self + .tags + .get(att) + .and_then(|t| t.as_ref()) + .filter(|t| t.chapters.len() > 1) + .map(|t| t.chapters.clone()); + let p = self.players.entry(att.to_string()).or_insert_with(|| Player::new(msg)); + if p.album.is_none() + && let Some(ch) = chapters + { + p.album = Some(crate::album::Album::new(&ch, p.position())); + } + p + } + + /// Move the playhead to `ms`, playing or not. + fn seek_ms(&mut self, att: &str, ms: u64) { + let Some(p) = self.players.get_mut(att) else { return }; + if p.playing { + p.start_pos = ms; + p.started = Some(Instant::now()); + } else { + p.paused_at = ms; + if p.look == Look::Fresh { + p.look = Look::Rest; + } + } + if let (Some(id), Ok(e)) = (p.source, engine()) { + let _ = e.seek(id, ms); + } + } + + fn album_act(&mut self, msg: &str, att: &str, input: AudioInputSpec, act: AlbumAct) -> Option { + if let AlbumAct::Art = act { + return None; + } + if let AlbumAct::More = act { + if !self.all_tracks.remove(att) { + self.all_tracks.insert(att.to_string()); + } + return None; + } + let probed = self.probed.get(att).copied().unwrap_or(0); + let p = self.player_mut(msg, att); + if p.duration == 0 { + p.duration = probed; + } + let (pos, duration, playing) = (p.position(), p.duration, p.playing || p.loading); + let a = p.album.as_mut()?; + let (to, start) = match act { + AlbumAct::Play(shuffled) => { + a.set_shuffle(shuffled); + let i = if shuffled { rand::random::() % a.tracks.len().max(1) } else { 0 }; + (a.play_track(i), true) + } + AlbumAct::Track(i) => (a.play_track(i), true), + AlbumAct::Next => (a.next(), false), + AlbumAct::Prev => (Some(a.prev(pos, duration)), false), + AlbumAct::Shuffle => { + let on = !a.shuffle; + a.set_shuffle(on); + (None, false) + } + AlbumAct::Repeat => { + a.cycle_repeat(); + (None, false) + } + AlbumAct::More | AlbumAct::Art => unreachable!(), + }; + if let Some(ms) = to { + self.seek_ms(att, ms); + } + if start && !playing { self.play(msg, att, input) } else { None } + } + + fn claim(&mut self, att: &str) { + if let Some(prev) = self.active.replace(att.to_string()) + && prev != att + { + self.pause(&prev); + } + } + + pub fn play(&mut self, msg: &str, att: &str, input: AudioInputSpec) -> Option { + self.claim(att); + let probed = self.probed.get(att).copied().unwrap_or(0); + let p = self + .players + .entry(att.to_string()) + .or_insert_with(|| Player::new(msg)); + if p.duration == 0 { + p.duration = probed; + } + p.path = Some(input.clone()); + let _ = self.player_mut(msg, att); + let p = self.players.get_mut(att)?; + match p.source { + None => { + p.loading = true; + Some(Work::Load(att.to_string(), input)) + } + Some(id) => { + let Ok(e) = engine() else { return None }; + match e.play(id) { + Ok(pos) => { + p.start_pos = pos; + p.started = Some(Instant::now()); + p.playing = true; + p.look = Look::Live; + None + } + // The engine evicts paused sources past its cap: load it again where it was. + Err(_) => { + self.sources.remove(&id); + p.source = None; + p.loading = true; + Some(Work::Load(att.to_string(), input)) + } + } + } + } + } + + /// A load landed: start it, unless it was called off meanwhile. + pub fn loaded(&mut self, att: &str, res: Result<(u32, u64), String>) { + let still = self.active.as_deref() == Some(att); + let Some(p) = self.players.get_mut(att) else { + return; + }; + let was_loading = std::mem::replace(&mut p.loading, false); + let Ok((id, duration)) = res else { + if still { + self.active = None; + } + return; + }; + p.source = Some(id); + self.sources.insert(id, att.to_string()); + if duration > 0 { + p.duration = duration; + } + if !was_loading || !still { + return; + } + let Ok(e) = engine() else { return }; + if p.paused_at > 0 { + let _ = e.seek(id, p.paused_at); + } + if let Ok(pos) = e.play(id) { + p.start_pos = pos; + p.started = Some(Instant::now()); + p.playing = true; + p.look = Look::Live; + } + } + + /// The attachment sounding now, if any. + pub fn playing(&self) -> Option<&str> { + let a = self.active.as_deref()?; + self.players.get(a).is_some_and(|p| p.playing || p.loading).then_some(a) + } + + pub fn pause(&mut self, att: &str) { + if self.active.as_deref() == Some(att) { + self.active = None; + } + let Some(p) = self.players.get_mut(att) else { + return; + }; + p.loading = false; + if !p.playing { + return; + } + p.paused_at = p.position(); + p.playing = false; + p.look = Look::Settling; + if let (Some(id), Ok(e)) = (p.source, engine()) { + let _ = e.pause(id); + } + } + + /// An engine event; returns the attachment that just ended. + pub fn on_event(&mut self, name: &str, v: &serde_json::Value) -> Option { + if name == "whisper_download_progress" { + let pct = v.get("progress").and_then(|p| p.as_f64()).unwrap_or(0.) as u32; + if self.transcripts.download.as_ref().is_some_and(|d| d.until.is_none()) { + self.transcripts.progress(pct); + } + return None; + } + let id = v.get("id").and_then(|i| i.as_u64())? as u32; + let att = self.sources.get(&id)?.clone(); + let p = self.players.get_mut(&att)?; + match name { + "audio_waveform" => { + use base64::Engine; + let data = v + .get("waveform") + .and_then(|w| w.as_str()) + .and_then(|s| base64::engine::general_purpose::STANDARD.decode(s).ok())?; + p.wave = Some(Wave { + data, + fps: v.get("waveform_fps").and_then(|f| f.as_f64()).unwrap_or(30.) as f32, + bins: v.get("bins").and_then(|b| b.as_u64()).unwrap_or(64).max(1) as usize, + }); + None + } + "audio_duration" => { + if let Some(ms) = v.get("duration_ms").and_then(|d| d.as_u64()) { + p.duration = ms; + } + None + } + "audio_ended" => { + p.playing = false; + p.paused_at = 0; + if self.active.as_deref() == Some(att.as_str()) { + self.active = None; + } + // The file's end is the last song's end: the listener's way decides what follows. + if let Some(ms) = p.album.as_mut().and_then(|a| a.ended()) { + p.paused_at = ms; + let (msg, path) = (p.msg.clone(), p.path.clone()); + if let Some(input) = path + && let Some(w) = self.play(&msg, &att, input) + { + self.queue.push(w); + } + return None; + } + p.look = Look::Settling; + (!p.album.is_some()).then_some(att) + } + _ => None, + } + } + + /// One frame of the bars; true while any still moves. + pub fn tick(&mut self) -> bool { + let mut moving = self.transcripts.tick(); + let mut steps = Vec::new(); + for (att, p) in self.players.iter_mut() { + let pos = p.position(); + if p.playing + && let Some(a) = p.album.as_mut() + { + match a.tick(pos) { + crate::album::Step::Stay => {} + step => steps.push((att.clone(), step)), + } + } + } + for (att, step) in steps { + match step { + crate::album::Step::Seek(ms) => self.seek_ms(&att, ms), + crate::album::Step::Stop(ms) => { + self.pause(&att); + self.seek_ms(&att, ms); + } + crate::album::Step::Stay => {} + } + } + for (att, sheet) in self.sheets.iter_mut() { + if let Some(l) = self.tags.get(att).and_then(|t| t.as_ref()).and_then(|t| t.lyrics.as_ref()) { + let pos = self.players.get(att).map_or(0, |p| p.position()); + moving |= sheet.tick(l, pos); + } + } + for p in self.players.values_mut() { + match p.look { + Look::Live => { + moving = true; + let Some(w) = &p.wave else { continue }; + let pos = p.position(); + let offset = ((pos as f32 / 1000.) * w.fps) as usize * w.bins; + p.display.resize(w.bins, 0.); + p.lift *= 0.92; + for i in 0..w.bins { + let v = w.data.get(offset + i).map_or(0., |b| *b as f32 / 255.); + p.display[i] = smooth(p.display[i], v); + } + } + Look::Settling => { + p.lift = p.lift * 0.92 + REST_Y * 0.08; + let mut settled = (p.lift - REST_Y).abs() < 0.2; + for d in &mut p.display { + *d *= 0.94; + if *d > REST_SCALE { + settled = false; + } + } + if settled { + p.lift = REST_Y; + p.look = Look::Rest; + } else { + moving = true; + } + } + _ => {} + } + } + moving + } + +} + +/// An account swap replaces the app's media: what it was playing stops with it. +impl Drop for Audio { + fn drop(&mut self) { + if self.sources.is_empty() { + return; + } + if let Ok(e) = engine() { + for id in self.sources.keys() { + let _ = e.stop(*id); + } + } + } +} + +fn smooth(prev: f32, level: f32) -> f32 { + let target = (level * level.sqrt()).min(1.); + if target > prev { prev * 0.7 + target * 0.3 } else { prev * 0.85 + target * 0.15 } +} + +/// Runs the engine work a player asked for. +pub fn run(work: Work) -> futures::channel::oneshot::Receiver { + let (tx, rx) = futures::channel::oneshot::channel(); + std::thread::spawn(move || { + let done = match work { + Work::Probe(att, input) => WorkDone::Probed( + att, + input + .open() + .and_then(|i| vector_media::audio_engine::probe_duration(&i)) + .unwrap_or(0), + ), + Work::Load(att, input) => WorkDone::Loaded( + att, + input + .open() + .and_then(|i| engine()?.load_from_file(&i)) + .map(|r| (r.id, r.duration_ms)), + ), + Work::Transcribe(att, input) => { + let res = input.open().and_then(|i| { + tauri::async_runtime::block_on(crate::backend::transcribe::transcribe(i)) + }); + WorkDone::Transcribed(att, res) + } + Work::Tags(att, input) => WorkDone::Tags( + att, + input + .open() + .and_then(|i| vector_media::tags::read(&i)) + .ok() + .flatten() + .map(tags_from), + ), + }; + let _ = tx.send(done); + }); + rx +} + +pub enum WorkDone { + Probed(String, u64), + Loaded(String, Result<(u32, u64), String>), + Tags(String, Option), + Transcribed(String, Result), +} + +fn tags_from(m: vector_media::tags::Meta) -> Tags { + let art = m.cover.as_deref().and_then(crate::media::decode_bounded); + let cover = art.as_ref().map(|a| { + let a = a.resize_to_fill(256, 256, image::imageops::FilterType::CatmullRom); + Arc::new(RenderImage::new(vec![image::Frame::new(crate::media::to_bgra(a.into_rgba8()))])) + }); + let small = art.as_ref().map(|a| a.resize_exact(24, 24, image::imageops::FilterType::Triangle).into_rgba8()); + // `.audio-art-glow` covers 160% of the card, so a 500x150 card sees this band of the + // art, and one with its lyrics open (500x422) a taller one. + let square = art.as_ref().map(|a| a.resize_exact(256, 256, image::imageops::FilterType::Triangle).into_rgba8()); + let band = |y: u32, h: u32, out: (u32, u32)| { + square.as_ref().map(|a| { + let band = image::imageops::crop_imm(a, 48, y, 160, h).to_image(); + let small = image::imageops::resize(&band, out.0, out.1, image::imageops::FilterType::Triangle); + let mut g = image::imageops::blur(&small, 8.); + for px in g.pixels_mut() { + saturate(px, 1.4); + } + Arc::new(RenderImage::new(vec![image::Frame::new(crate::media::to_bgra(g))])) + }) + }; + let glow = band(104, 48, (100, 30)); + let glow_tall = band(60, 136, (100, 84)); + let accent = cover + .as_ref() + .map(|_| small.as_ref().and_then(art_accent).unwrap_or(gpui::hsla(0., 0., 0.949, 1.))); + Tags { + title: m.title.map(|t| crate::kit::one_line(&t).into_owned()).filter(|t| !t.is_empty()), + artist: m.artist.map(|t| crate::kit::one_line(&t).into_owned()).filter(|t| !t.is_empty()), + album: m.album.map(|t| crate::kit::one_line(&t).into_owned()).filter(|t| !t.is_empty()), + year: m.year, + cover, + glow, + glow_tall, + accent, + lyrics: m.lyrics, + chapters: m.chapters, + } +} + +fn saturate(px: &mut image::Rgba, k: f32) { + let [r, g, b, _] = px.0.map(|v| v as f32); + let l = 0.2126 * r + 0.7152 * g + 0.0722 * b; + for (i, v) in [r, g, b].into_iter().enumerate() { + px.0[i] = (l + (v - l) * k).clamp(0., 255.) as u8; + } +} + +/// `artAccent`: the weightiest hue among the art's saturated mid-tones, lifted to 68% light. +fn art_accent(px: &image::RgbaImage) -> Option { + let mut bins = [(0f32, 0f32, 0f32, 0f32); 12]; + let mut total = 0f32; + for p in px.pixels() { + let [r, g, b] = [p[0], p[1], p[2]].map(|v| v as f32 / 255.); + let (max, min) = (r.max(g).max(b), r.min(g).min(b)); + let l = (max + min) / 2.; + let sat = if max == min { 0. } else { (max - min) / (1. - (2. * l - 1.).abs()) }; + let w = sat * sat * (1. - (2. * l - 1.).abs()); + total += 1.; + if w < 0.02 { + continue; + } + let d = max - min; + let hue = if max == r { + ((g - b) / d) % 6. + } else if max == g { + (b - r) / d + 2. + } else { + (r - g) / d + 4. + }; + let bin = &mut bins[(((hue * 60. + 360.) % 360.) / 30.) as usize % 12]; + bin.0 += w; + bin.1 += p[0] as f32 * w; + bin.2 += p[1] as f32 * w; + bin.3 += p[2] as f32 * w; + } + let top = bins.iter().copied().fold((0., 0., 0., 0.), |a, b| if b.0 > a.0 { b } else { a }); + if total == 0. || top.0 / total < 0.03 { + return None; + } + let (r, g, b) = (top.1 / top.0 / 255., top.2 / top.0 / 255., top.3 / top.0 / 255.); + let (max, min) = (r.max(g).max(b), r.min(g).min(b)); + let (l, d) = ((max + min) / 2., max - min); + if d == 0. { + return None; + } + let s = d / (1. - (2. * l - 1.).abs()); + let h = if max == r { + ((g - b) / d + 6.) % 6. + } else if max == g { + (b - r) / d + 2. + } else { + (r - g) / d + 4. + }; + Some(gpui::hsla(h * 60. / 360., s.clamp(0.45, 0.85), 0.68, 1.)) +} + +/// `splitTitle`: an edition note ("Remastered 2011", "Live") set apart from the title. +pub fn split_title(t: &str) -> (String, String) { + match edition(t) { + Some((at, note)) => (t[..at].trim().to_string(), note.trim().to_string()), + None => (t.to_string(), String::new()), + } +} + +/// `(?i)\s*(?:\(([^()]*\b(?:remaster(?:ed)?|…|bonus)\b[^()]*)\)|-\s*(…|live|radio edit))\s*$`: where +/// the note starts, whitespace before it included, and the note. +fn edition(t: &str) -> Option<(usize, &str)> { + use crate::scan::{boundary, digit, lit_i}; + const WORDS: &[&str] = &["remastered", "remaster", "remix", "live", "mono", "stereo", "edit", "version", "demo", "acoustic", "deluxe", "bonus"]; + let body = t.trim_end(); + let ws_from = |i: usize| t[..i].trim_end().len(); + let paren = body.strip_suffix(')').and_then(|inner| { + let open = inner.rfind(['(', ')']).filter(|&o| inner.as_bytes()[o] == b'(')?; + let x = (open + 1, inner.len()); + let named = t[x.0..x.1].char_indices().map(|(i, _)| x.0 + i).any(|q| { + boundary(t, q) && WORDS.iter().any(|w| lit_i(t, q, w).is_some_and(|e| boundary(t, e))) + }); + named.then(|| (ws_from(open), &t[x.0..x.1])) + }); + // `(?:\d{4}\s*)?remaster(?:ed)?(?:\s*\d{4})?`, whole. + let remaster = |s: &str| { + let year = |s: &str| { + let mut cs = s.char_indices(); + (0..4).all(|_| cs.next().is_some_and(|(_, c)| digit(c))).then(|| cs.next().map_or(s.len(), |(i, _)| i)) + }; + let s = year(s).map_or(s, |n| s[n..].trim_start()); + let Some(e) = lit_i(s, 0, "remaster") else { return false }; + let rest = lit_i(s, e, "ed").map_or(&s[e..], |e| &s[e..]); + let rest = rest.trim_start(); + rest.is_empty() || year(rest) == Some(rest.len()) + }; + let dash = t.match_indices('-').find_map(|(d, _)| { + let note = t[d + 1..].trim(); + // i18n-exempt: tag words in track titles + (lit_i(note, 0, "live") == Some(note.len()) || lit_i(note, 0, "radio edit") == Some(note.len()) || remaster(note)) + .then(|| (ws_from(d), note)) + }); + match (paren, dash) { + (Some(p), Some(d)) => Some(if d.0 < p.0 { d } else { p }), + (p, d) => p.or(d), + } +} + +#[cfg(test)] +mod edition_tests { + #[test] + fn edition_matches_the_pattern_it_replaces() { + // i18n-exempt: test pattern + let re = regex::Regex::new(r"(?i)\s*(?:\(([^()]*\b(?:remaster(?:ed)?|remix|live|mono|stereo|edit|version|demo|acoustic|deluxe|bonus)\b[^()]*)\)|-\s*((?:\d{4}\s*)?remaster(?:ed)?(?:\s*\d{4})?|live|radio edit))\s*$").unwrap(); + const PARTS: &[&str] = &[ + // i18n-exempt: test input + "Song", " ", " ", "(", ")", "-", " - ", "Remastered", "remaster", "REMASTER", "ed", "2011", "201", "Live", + // i18n-exempt: test input + "live", "Radio Edit", "radio edit", "mono", "x", "liver", "\u{3000}", "ſtereo", "deluxe", "é", "edition", + ]; + let mut seed = 0x7777_1234u64; + let mut next = move || { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + seed + }; + for _ in 0..40_000 { + let s: String = (0..1 + next() % 10).map(|_| PARTS[(next() % PARTS.len() as u64) as usize]).collect(); + let want = re.captures(&s).map(|c| (c.get(0).unwrap().start(), c.get(1).or(c.get(2)).unwrap().as_str().trim())); + assert_eq!(super::edition(&s).map(|(a, n)| (a, n.trim())), want, "{s:?}"); + } + } +} + +#[cfg(test)] +mod file_fuzz { + use vector_media::audio_engine::{AudioEngine, AudioInput}; + + /// A text frame of an ID3v2.4 tag. + fn frame(id: &[u8; 4], body: &[u8]) -> Vec { + let n = body.len() as u32; + let mut f = id.to_vec(); + f.extend([((n >> 21) & 0x7f) as u8, ((n >> 14) & 0x7f) as u8, ((n >> 7) & 0x7f) as u8, (n & 0x7f) as u8, 0, 0]); + f.extend_from_slice(body); + f + } + + /// An ID3v2.4 tag with a title, art, plain and synced lyrics and a chapter, before `audio`. + fn tagged(audio: &[u8]) -> Vec { + let mut chap = b"c1\0".to_vec(); + for n in [0u32, 1000, u32::MAX, u32::MAX] { + chap.extend(n.to_be_bytes()); + } + chap.extend(frame(b"TIT2", b"\x03One")); + let mut sylt = b"\x03eng\x02\x01\0".to_vec(); + for (t, w) in [(0u32, "a"), (500, "b")] { + sylt.extend(w.as_bytes()); + sylt.push(0); + sylt.extend(t.to_be_bytes()); + } + let frames = [ + frame(b"TIT2", b"\x03Song"), + frame(b"TPE1", b"\x03Artist"), + frame(b"USLT", b"\x03eng\0[00:01.00]one\n[00:02.00]two"), + frame(b"SYLT", &sylt), + frame(b"CHAP", &chap), + frame(b"APIC", b"\x00image/png\0\x03\0\x89PNG\r\n\x1a\n"), + ] + .concat(); + let n = frames.len() as u32; + let mut t = b"ID3\x04\x00\x00".to_vec(); + t.extend([((n >> 21) & 0x7f) as u8, ((n >> 14) & 0x7f) as u8, ((n >> 7) & 0x7f) as u8, (n & 0x7f) as u8]); + t.extend(frames); + t.extend_from_slice(audio); + t + } + + fn wav() -> Vec { + let samples: Vec = (0..4000).map(|i| ((i as f32 * 0.05).sin() * 8000.) as i16).collect(); + let data: Vec = samples.iter().flat_map(|s| s.to_le_bytes()).collect(); + let mut w = b"RIFF".to_vec(); + w.extend((36 + data.len() as u32).to_le_bytes()); + w.extend(b"WAVEfmt "); + w.extend(16u32.to_le_bytes()); + w.extend(1u16.to_le_bytes()); + w.extend(1u16.to_le_bytes()); + w.extend(8000u32.to_le_bytes()); + w.extend(16000u32.to_le_bytes()); + w.extend(2u16.to_le_bytes()); + w.extend(16u16.to_le_bytes()); + w.extend(b"data"); + w.extend((data.len() as u32).to_le_bytes()); + w.extend(data); + w + } + + /// Damaged audio from anyone: tags, the duration probe and the decoder must not panic, on + /// this thread or the engine's. `AUDIOFUZZ_DIR` adds sample files as seeds. + #[test] + fn no_damaged_audio_panics() { + let mut seeds: Vec<(Vec, String)> = vec![(wav(), "wav".into()), (tagged(&[0xff, 0xfb, 0x90, 0x64, 0, 0, 0, 0]), "mp3".into())]; + if let Ok(dir) = std::env::var("AUDIOFUZZ_DIR") { + for e in std::fs::read_dir(dir).unwrap().flatten() { + let ext = e.path().extension().and_then(|x| x.to_str()).unwrap_or_default().to_ascii_lowercase(); + let mut b = std::fs::read(e.path()).unwrap(); + b.truncate(96 << 10); + if ext == "mp3" { + seeds.push((tagged(&b), ext.clone())); + } + seeds.push((b, ext)); + } + } + static PANICS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + // Overflow inside a dependency panics only with debug assertions; release wraps it. + static WRAPS: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); + let default_hook = std::panic::take_hook(); + std::panic::set_hook(Box::new(move |info| { + let at = info.location().map(|l| format!("{}:{}", l.file(), l.line())).unwrap_or_default(); + let msg = info.payload().downcast_ref::<&str>().map(|s| s.to_string()).or_else(|| info.payload().downcast_ref::().cloned()).unwrap_or_default(); + if msg.contains("with overflow") && at.contains("/.cargo/registry/") { + WRAPS.lock().unwrap_or_else(|e| e.into_inner()).push(at); + return; + } + PANICS.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + default_hook(info); + })); + let rt: &'static tokio::runtime::Runtime = Box::leak(Box::new(tokio::runtime::Runtime::new().unwrap())); + tauri::async_runtime::set(rt.handle().clone()); + AudioEngine::init(); + let dir = std::env::temp_dir().join(format!("vector-audiofuzz-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let iters: usize = std::env::var("AUDIOFUZZ_ITERS").ok().and_then(|v| v.parse().ok()).unwrap_or(40); + let mut seed: u64 = std::env::var("AUDIOFUZZ_SEED").ok().and_then(|v| v.parse().ok()).unwrap_or(0x5851_f42d_4c95_7f2d); + let mut next = move || { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + seed + }; + let mut failed = Vec::new(); + for i in 0..iters { + let (mut b, ext) = seeds[i % seeds.len()].clone(); + for _ in 0..1 + next() % 6 { + let at = (next() % b.len().max(1) as u64) as usize; + match next() % 6 { + 0 => b[at] = next() as u8, + 1 => b[at] = 0xff, + 2 => b[at] = 0, + 3 => b.truncate(at.max(12)), + 4 => b[at..].iter_mut().take(4).for_each(|x| *x = 0xff), + _ => b[at] ^= 1 << (next() % 8), + } + } + let path = dir.join(format!("case.{ext}")); + std::fs::write(&path, &b).unwrap(); + let before = PANICS.load(std::sync::atomic::Ordering::SeqCst); + let t = std::time::Instant::now(); + let input = AudioInput::File(path.clone()); + let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + let _ = vector_media::tags::read(&input); + let _ = vector_media::audio_engine::probe_duration(&input); + if let Ok(e) = AudioEngine::get() + && let Ok(r) = e.load_from_file(&input) + { + std::thread::sleep(std::time::Duration::from_millis(40)); + let _ = e.stop(r.id); + } + })); + if PANICS.load(std::sync::atomic::Ordering::SeqCst) > before || t.elapsed() > std::time::Duration::from_secs(5) { + eprintln!("case {i} ({ext}, {} bytes)", b.len()); + failed.push((ext, b)); + if failed.len() >= 3 { + break; + } + } + } + std::thread::sleep(std::time::Duration::from_millis(300)); + let _ = std::panic::take_hook(); + if let Ok(out) = std::env::var("AUDIOFUZZ_OUT") { + for (i, (ext, b)) in failed.iter().enumerate() { + std::fs::write(format!("{out}/bad-{i}.{ext}"), b).unwrap(); + } + } + let _ = std::fs::remove_dir_all(&dir); + let mut wraps = WRAPS.lock().unwrap_or_else(|e| e.into_inner()).clone(); + wraps.sort(); + wraps.dedup(); + if !wraps.is_empty() { + eprintln!("dependency overflow (wraps in release): {wraps:?}"); + } + assert!(failed.is_empty() && PANICS.load(std::sync::atomic::Ordering::SeqCst) == 0, "damaged audio panicked or stalled"); + } +} + +pub fn format_time(ms: u64) -> String { + let s = ms / 1000; + crate::lang::digits(format!("{}:{:02}", s / 60, s % 60)) +} + +/// `.audio-album.is-full`: the art beside the head, then the songs; the caller adds the +/// controls under them. +#[allow(clippy::too_many_arguments)] +fn album_view( + att: &vector_core::Attachment, + t: &Tags, + art: Option>, + album: Option<&crate::album::Album>, + playing: bool, + duration: u64, + accent: gpui::Hsla, + all: bool, + narrow: bool, + on: Rc, +) -> gpui::Div { + let art_px = if narrow { 64. } else { 128. }; + let id = &att.id; + let line = |d: gpui::Div| d.overflow_hidden().text_ellipsis().whitespace_nowrap(); + let full = t.album.clone().or(t.title.clone()).unwrap_or_else(|| crate::kit::one_line(&att.name).into_owned()); + let (main, note) = split_title(&full); + let byline = [t.artist.clone(), t.year.map(|y| y.to_string())] + .into_iter() + .flatten() + .collect::>() + .join(" \u{b7} "); + let n = t.chapters.len(); + let stats = if duration > 0 { + t::audio_album_stats(n, (duration as f64 / 60000.).round() as i64) + } else { + t::audio_album_songs(n) + }; + let shuffle_on = album.is_some_and(|a| a.shuffle); + let repeat = album.map_or(crate::album::Repeat::Off, |a| a.repeat); + let pill = |key: &str, act: AlbumAct, primary: bool, icon: &'static str, label: SharedString| { + let on = on.clone(); + div() + .id(SharedString::from(format!("album-{key}-{id}"))) + .flex() + .items_center() + .gap(px(5.)) + .pl(px(10.)) + .pr(px(14.)) + .py(px(6.)) + .rounded_full() + .text_size(px(12.3)) + .line_height(px(17.22)) + .font_weight(gpui::FontWeight::SEMIBOLD) + .cursor_pointer() + .when(primary, |d| d.bg(accent).text_color(c(0x0a0a0a)).hover(|s| s.opacity(0.92))) + .when(!primary, |d| { + d.border_1() + .border_color(c(0x363636)) + .bg(white_a(0.04)) + .text_color(white_a(0.92)) + .hover(|s| s.bg(white_a(0.09))) + }) + .on_click(move |_, w, cx| { + cx.stop_propagation(); + on(act, w, cx) + }) + .child( + svg() + .path(icon) + .size(px(if primary { 16. } else { 14. })) + .text_color(if primary { c(0x0a0a0a) } else { white_a(0.7) }), + ) + .child(label) + }; + let toggle = |key: &str, act: AlbumAct, lit: bool, icon: &'static str| { + let on = on.clone(); + let tip = match (key, repeat) { + ("shuffle", _) => t::audio_shuffle(), + (_, crate::album::Repeat::One) => t::audio_repeat_one(), + (_, crate::album::Repeat::All) => t::audio_repeat_all(), + _ => t::audio_repeat(), + }; + div() + .id(SharedString::from(format!("album-{key}-{id}"))) + .tip(tip) + .size(px(30.)) + .rounded(px(8.)) + .flex() + .items_center() + .justify_center() + .cursor_pointer() + .hover(|s| s.bg(white_a(0.07))) + .on_click(move |_, w, cx| { + cx.stop_propagation(); + on(act, w, cx) + }) + .child(svg().path(icon).size(px(16.)).text_color(if lit { accent } else { white_a(0.34) })) + }; + let head = div() + .flex_1() + .min_w_0() + .flex() + .flex_col() + .justify_center() + .gap(px(2.)) + .child( + line(div()) + .id("audio-album-title") + .tip(full.clone()) + .text_size(px(15.75)) + .line_height(px(19.7)) + .font_weight(gpui::FontWeight::SEMIBOLD) + .text_color(white_a(0.92)) + .child(main) + .when(!note.is_empty(), |d| { + d.child( + div() + .ml(px(4.7)) + .font_weight(gpui::FontWeight::NORMAL) + .opacity(0.5) + .child(note), + ) + }) + .flex(), + ) + .when(!byline.is_empty(), |d| { + d.child( + line(div()) + .id("audio-album-byline") + .tip(byline.clone()) + .text_size(px(12.)) + .line_height(px(15.)) + .text_color(white_a(0.55)) + .child(byline), + ) + }) + .child( + div() + .mt(px(1.)) + .text_size(px(11.4)) + .line_height(px(15.96)) + .text_color(white_a(0.34)) + .child(stats), + ) + .child( + div() + .mt(px(10.)) + .flex() + .items_center() + .gap(px(8.)) + .child(pill("play", AlbumAct::Play(false), true, "icons/play.svg", t::audio_play())) + .child(pill("shuffle-play", AlbumAct::Play(true), false, "icons/shuffle.svg", t::audio_shuffle())) + .child( + div() + .ml_auto() + .flex() + .gap(px(2.)) + .child(toggle("shuffle", AlbumAct::Shuffle, shuffle_on, "icons/shuffle.svg")) + .child(toggle( + "repeat", + AlbumAct::Repeat, + repeat != crate::album::Repeat::Off, + if repeat == crate::album::Repeat::One { "icons/repeat-one.svg" } else { "icons/repeat.svg" }, + )), + ), + ); + let current = album.map_or(-1, |a| a.track); + let shown = if all { n } else { n.min(4) }; + let eq = |t: f32| { + div().h(px(12.)).flex().items_end().gap(px(2.)).children((0..3).map(move |k| { + let p = ((t / 0.9 + k as f32 / 3.).fract() * std::f32::consts::TAU).cos(); + let scale = 0.3 + 0.7 * (1. - p) / 2.; + div().w(px(3.)).h(px(12. * scale)).rounded(px(1.)).bg(accent) + })) + }; + let clock = album_clock(); + let tracks = t.chapters.iter().take(shown).enumerate().map(|(i, ch)| { + let (tmain, tnote) = split_title(&ch.title); + let len = ch.end_ms.map_or(duration, u64::from).saturating_sub(ch.start_ms as u64); + let is_cur = i as isize == current; + let on = on.clone(); + div() + .id(SharedString::from(format!("album-track-{i}-{id}"))) + .w_full() + .flex() + .items_center() + .gap(px(10.)) + .px(px(6.)) + .py(px(7.)) + .rounded(px(8.)) + .text_size(px(13.2)) + .line_height(px(18.48)) + .text_color(if is_cur { accent } else { white_a(0.92) }) + .when(is_cur, |d| d.font_weight(gpui::FontWeight::SEMIBOLD)) + .cursor_pointer() + .hover(|s| s.bg(white_a(0.05))) + .on_click(move |_, w, cx| { + cx.stop_propagation(); + on(AlbumAct::Track(i), w, cx) + }) + .child( + div() + .w(px(26.)) + .flex_shrink_0() + .flex() + .justify_center() + .font_weight(gpui::FontWeight::NORMAL) + .text_color(white_a(0.34)) + .child(if is_cur && playing { + eq(clock).into_any_element() + } else { + (i + 1).to_string().into_any_element() + }), + ) + .child( + line(div().flex_1().min_w_0().flex()) + .child(tmain) + .when(!tnote.is_empty(), |d| { + d.child(div().ml(px(4.)).font_weight(gpui::FontWeight::NORMAL).opacity(0.5).child(tnote)) + }), + ) + .child( + div() + .flex_shrink_0() + .font_weight(gpui::FontWeight::NORMAL) + .text_color(white_a(0.34)) + .child(format_time(len)), + ) + }); + let more = (n > 4).then(|| { + let on = on.clone(); + div() + .id(SharedString::from(format!("album-more-{id}"))) + .w_full() + .pt(px(7.)) + .pb(px(3.)) + .flex() + .justify_center() + .text_size(px(12.)) + .line_height(px(16.8)) + .text_color(white_a(0.55)) + .cursor_pointer() + .hover(|s| s.text_color(white_a(0.92))) + .on_click(move |_, w, cx| { + cx.stop_propagation(); + on(AlbumAct::More, w, cx) + }) + .child(if all { t::audio_show_fewer() } else { t::audio_show_all(n) }) + }); + div() + .relative() + .flex() + .flex_col() + .gap(px(12.)) + .child( + div() + .flex() + .gap(px(14.)) + .when_some(art, |d, art| { + let on = on.clone(); + d.child( + div() + .id(SharedString::from(format!("album-art-{id}"))) + .aria_label(t::audio_cover_art()) + .size(px(art_px)) + .flex_shrink_0() + .rounded(px(10.)) + .cursor(gpui::CursorStyle::PointingHand) + .on_click(move |_, w, cx| { + cx.stop_propagation(); + on(AlbumAct::Art, w, cx) + }) + .bg(c(0x262626)) + .shadow(vec![gpui::BoxShadow { + color: ca(0, 0, 0, 0.35), + offset: point(px(0.), px(4.)), + blur_radius: px(14.), + spread_radius: px(0.), + inset: false, + }]) + .child(crate::pic::img(art).size_full().rounded(px(10.))), + ) + }) + .child(head), + ) + .child( + div() + .pt(px(4.)) + .border_t_1() + .border_color(white_a(0.06)) + .children(tracks.map(|t| div().pt(px(4.)).h(px(36.45)).child(t))) + .children(more.map(|m| div().pt(px(4.)).pb(px(4.1)).child(m))), + ) +} + +/// Seconds on a shared clock, for the playing song's bars. +fn album_clock() -> f32 { + static START: OnceLock = OnceLock::new(); + START.get_or_init(Instant::now).elapsed().as_secs_f32() +} + +/// `.audio-art-glow`, crossfading to the taller window as the lyrics open. +pub(crate) fn glows(tags: Option<&Tags>, open: f32) -> Vec { + let Some(t) = tags else { return Vec::new() }; + [(t.glow.clone(), 1. - open), (t.glow_tall.clone(), open)] + .into_iter() + .filter_map(|(g, w)| g.filter(|_| w > 0.).map(|g| (g, w))) + .map(|(g, w)| { + div() + .absolute() + .inset_0() + .opacity(0.22 * w) + .child(crate::pic::img(g).size_full().rounded(px(11.)).object_fit(gpui::ObjectFit::Fill)) + .into_any_element() + }) + .collect() +} + +/// The bars, painted per frame, and the scrub across them. +fn waveform( + id: SharedString, + p: Option<&Player>, + duration: u64, + accent: gpui::Hsla, + tall: f32, + span: (u64, u64), + on_seek: Rc, +) -> impl IntoElement { + let look = p.map_or(Look::Fresh, |p| p.look); + let playing = p.is_some_and(|p| p.playing); + let progress = p.map_or(0., |p| { + if span.1 > span.0 { + (p.position().saturating_sub(span.0) as f32 / (span.1 - span.0) as f32).min(1.) + } else { + p.progress() + } + }); + let at_zero = p.is_none_or(|p| p.position() == 0); + let lift = p.map_or(REST_Y, |p| p.lift); + let display: Rc<[f32]> = p.map_or_else(|| Rc::from([]), |p| Rc::from(p.display.as_slice())); + let has_wave = p.is_some_and(|p| p.wave.is_some()); + let seekable = duration > 0; + let (start, total) = if span.1 > span.0 { (span.0, span.1 - span.0) } else { (0, duration) }; + let spoken = format!("{} / {}", format_time(p.map_or(0, |p| p.position().saturating_sub(start))), format_time(total)); + div() + .id(id) + .as_slider(t::audio_seek(), spoken, progress) + .when(seekable, |d| { + let on = on_seek.clone(); + d.seek_keys(progress, 0.05, move |f, w, cx| on(f, true, w, cx)) + }) + .group("audio-waveform") + .flex_1() + .h(px(tall)) + .mx(px(8.)) + .child( + canvas( + move |bounds, window, _| { + window.insert_hitbox(bounds, HitboxBehavior::Normal) + }, + move |bounds, hitbox, window, _| { + let w = f32::from(bounds.size.width); + let n = ((w / 5.).floor() as usize).clamp(16, 64); + let gap = 2.; + let bw = ((w - gap * (n - 1) as f32) / n as f32).max(2.); + let hovered = hitbox.is_hovered(window); + let group = if playing || hovered { 1. } else { 0.8 }; + let bins = display.len().max(1); + for i in 0..n { + let at = (i as f32 + 0.5) / n as f32; + let (scale, y, opacity, glow) = match look { + Look::Fresh => (REST_SCALE, REST_Y, 1., 0.), + Look::Live if !has_wave => ( + 0.25, + -7., + if at <= progress { 0.5 } else { 0.2 }, + 0., + ), + Look::Live => { + let v = display.get(i * bins / n).copied().unwrap_or(0.); + let played = at <= progress; + let o = (0.3 + v * 0.7) * if played { 1. } else { 0.4 }; + let glow = if v > 0.7 && played { v - 0.7 } else { 0. }; + (v.max(REST_SCALE), lift, o, glow) + } + Look::Settling | Look::Rest => { + let v = display.get(i * bins / n).copied().unwrap_or(0.); + let o = if at_zero || at <= progress { 0.3 } else { 0.15 }; + (v.max(REST_SCALE), lift, o, 0.) + } + }; + let y = if y.abs() > 0.5 { y } else { 0. }; + let h = 20. * scale; + let x = f32::from(bounds.origin.x) + i as f32 * (bw + gap); + let bottom = f32::from(bounds.origin.y) + tall / 2. + 10. + y; + let rect = Bounds::new(point(px(x), px(bottom - h)), size(px(bw), px(h))); + let color = accent; + if glow > 0. { + let r = glow * 8.; + window.paint_quad( + fill( + Bounds::new( + point(px(x - r / 2.), px(bottom - h - r / 2.)), + size(px(bw + r), px(h + r)), + ), + color.opacity(0.25 * opacity * group), + ) + .corner_radii(Corners::all(px(1.5 + r / 2.))), + ); + } + window.paint_quad( + fill(rect, color.opacity(opacity * group)) + .corner_radii(Corners::all(px(1.5_f32.min(h / 2.)))), + ); + } + if !seekable { + return; + } + window.set_cursor_style(CursorStyle::PointingHand, &hitbox); + let frac = move |x: Pixels| { + f32::from(x - bounds.origin.x) / f32::from(bounds.size.width).max(1.) + }; + let dragging = Rc::new(Cell::new(false)); + { + let (dragging, on_seek, hitbox) = + (dragging.clone(), on_seek.clone(), hitbox.clone()); + window.on_mouse_event(move |e: &MouseDownEvent, phase, window, cx| { + if phase.bubble() + && e.button == MouseButton::Left + && hitbox.is_hovered(window) + { + dragging.set(true); + cx.stop_propagation(); + on_seek(frac(e.position.x), false, window, cx); + } + }); + } + { + let (dragging, on_seek) = (dragging.clone(), on_seek.clone()); + window.on_mouse_event(move |e: &MouseMoveEvent, phase, window, cx| { + if phase.bubble() && dragging.get() && e.dragging() { + on_seek(frac(e.position.x), false, window, cx); + } + }); + } + window.on_mouse_event(move |e: &MouseUpEvent, phase, window, cx| { + if phase.bubble() && dragging.replace(false) { + on_seek(frac(e.position.x), true, window, cx); + } + }); + }, + ) + .size_full(), + ) +} + +/// `.custom-audio-player`: a voice message, or a named clip with its name over the bars. +pub fn view( + att: &vector_core::Attachment, + p: Option<&Player>, + duration: u64, + tags: Option<&Tags>, + sheet: Option<&crate::lyrics::Sheet>, + all_tracks: bool, + transcripts: Option<&crate::transcript::Transcripts>, + narrow_set: &Rc>>, + select: Option, + on: Rc, +) -> AnyElement { + let narrow = narrow_set.borrow().contains(&att.id); + let probe = { + let set = narrow_set.clone(); + let id = att.id.clone(); + gpui::canvas( + move |b, window, _| { + let now = f32::from(b.size.width) - 26. <= 380.; + let mut set = set.borrow_mut(); + if now != set.contains(&id) { + if now { set.insert(id.clone()); } else { set.remove(&id); } + window.refresh(); + } + }, + |_, _, _, _| {}, + ) + .absolute() + .inset_0() + }; + let chapters = tags.map(|t| t.chapters.as_slice()).filter(|c| c.len() > 1); + let album = p.and_then(|p| p.album.as_ref()); + let span = match (album, chapters) { + (Some(a), _) => a.now(duration), + (None, Some(ch)) => (ch[0].start_ms as u64, ch[0].end_ms.map_or(duration, u64::from)), + _ => (0, duration), + }; + let track_idx = album.map_or(-1, |a| a.track); + let lyrics_btn = tags.and_then(|t| t.lyrics.as_ref()).map(|_| { + let open = sheet.is_some_and(|s| s.open); + let on = on.clone(); + div() + .id(SharedString::from(format!("audio-lyrics-{}", att.id))) + .tip(if open { t::audio_lyrics_hide() } else { t::audio_lyrics() }) + .size(px(34.)) + .ml(px(10.)) + .flex_shrink_0() + .rounded(px(8.)) + .border_1() + .border_color(c(0x363636)) + .flex() + .items_center() + .justify_center() + .cursor_pointer() + .hover(|s| s.bg(white_a(0.07))) + .on_click(move |_, w, cx| { + cx.stop_propagation(); + on(Act::Lyrics, w, cx) + }) + .child(svg().path("icons/align-left.svg").size(px(17.)).text_color(if open { + tags.and_then(|t| t.accent).unwrap_or(c(PRIMARY)) + } else { + white_a(0.7) + })) + }); + let sheet_el = tags.and_then(|t| t.lyrics.as_ref()).zip(sheet).and_then(|(l, s)| { + let on = on.clone(); + crate::lyrics::view( + &att.id, + l, + s, + p.map_or(0, |p| p.position()), + p.is_some_and(|p| p.playing), + Rc::new(move |ms, w, cx| on(Act::Line(ms), w, cx)), + ) + }); + let accent = tags.and_then(|t| t.accent).unwrap_or(c(PRIMARY)); + let art = tags.and_then(|t| t.cover.clone()); + let playing = p.is_some_and(|p| p.playing); + let loading = p.is_some_and(|p| p.loading); + let pos = p.map_or(0, |p| p.position()).min(duration.max(1)); + let pos = if duration == 0 { p.map_or(0, |p| p.position()) } else { pos }; + let id = att.id.clone(); + let toggle = on.clone(); + let on_album: Rc = { + let on = on.clone(); + Rc::new(move |a, w, cx| on(Act::Album(a), w, cx)) + }; + let seek: Rc = { + let on = on.clone(); + Rc::new(move |f, done, w, cx| on(Act::Seek(f, done), w, cx)) + }; + let icon = if loading { + "icons/loading.svg" + } else if playing { + "icons/pause.svg" + } else { + "icons/play.svg" + }; + let button = div() + .id(SharedString::from(format!("audio-play-{id}"))) + .aria_label(if playing { t::audio_pause() } else { t::audio_play() }) + .size(px(40.)) + .flex_shrink_0() + .rounded_full() + .bg(accent) + .flex() + .items_center() + .justify_center() + .cursor_pointer() + .hover(|s| s.opacity(0.93)) + .on_click(move |_, w, cx| { + cx.stop_propagation(); + toggle(Act::Toggle, w, cx) + }) + .child( + svg() + .path(icon) + .size(px(28.)) + .when(!playing && !loading, |s| s.ml(px(1.4))) + .text_color(c(0x0a0a0a)), + ); + let bars = waveform( + SharedString::from(format!("audio-wave-{id}")), + p, + duration, + accent, + if (att.name.is_empty() || art.is_some()) && chapters.is_none() { 30. } else { 20. }, + span, + seek, + ); + // `artist — track`, else the file's name. + let title = match tags.and_then(|t| t.title.as_deref()) { + Some(track) => match tags.and_then(|t| t.artist.as_deref()) { + Some(artist) => format!("{artist} \u{2014} {track}"), // i18n-exempt: two names + None => track.to_string(), + }, + None => crate::kit::one_line(&att.name).into_owned(), + }; + let now_title = chapters.and_then(|ch| ch.get(track_idx.max(0) as usize)).map(|c| split_title(&c.title).0); + let title = now_title.unwrap_or(title); + let transcript = transcripts.and_then(|t| t.get(&att.id)); + let downloading = transcripts + .and_then(|t| t.download.as_ref()) + .filter(|_| transcript.is_some_and(|t| matches!(t.phase, crate::transcript::Phase::Loading))); + let transcribe_btn = transcripts.map(|_| { + let on = on.clone(); + crate::transcript::button(&att.id, transcript, accent, Rc::new(move |w, cx| on(Act::Transcribe, w, cx))) + }); + let transcript_el = transcript.and_then(|t| { + let on = on.clone(); + crate::transcript::view( + &att.id, + t, + p.map_or(0, |p| p.position()), + p.is_some_and(|p| p.playing), + accent, + select, + Rc::new(move |ms, w, cx| on(Act::SeekTo(ms), w, cx)), + ) + }); + let middle = if let Some(d) = downloading { + let on = on.clone(); + crate::transcript::download_view(d, Rc::new(move |w, cx| on(Act::CancelDownload, w, cx))) + } else if (att.name.is_empty() || art.is_some()) && chapters.is_none() { + bars.into_any_element() + } else { + div() + .flex() + .flex_col() + .flex_1() + .min_w_0() + .gap(px(2.)) + .mx(px(8.)) + .child( + div() + .id("audio-filename") + .tip(title.clone()) + .text_size(px(12.)) + .line_height(px(15.)) + .text_color(white_a(0.92)) + .overflow_hidden() + .text_ellipsis() + .whitespace_nowrap() + .child(title), + ) + .child(div().flex().mx(px(-8.)).child(bars)) + .into_any_element() + }; + let time = div() + .min_w(px(72.)) + .flex() + .justify_end() + .whitespace_nowrap() + .text_size(px(10.8)) + .line_height(px(15.12)) + .text_color(white_a(0.55)) + .child( + div() + .text_color(if pos > 0 { white_a(0.92) } else { white_a(0.34) }) + .child(format_time(pos.saturating_sub(span.0))), + ) + .child(div().mx(px(4.)).text_color(white_a(0.34)).child("/")) + .child(format_time(span.1.saturating_sub(span.0))); + let skip = |dir: &'static str, icon: &'static str, act: AlbumAct| { + let on = on_album.clone(); + div() + .id(SharedString::from(format!("audio-{dir}-{}", att.id))) + .aria_label(if dir == "prev" { t::audio_previous() } else { t::audio_next() }) + .size(px(30.)) + .mx(px(2.)) + .flex_shrink_0() + .rounded(px(8.)) + .flex() + .items_center() + .justify_center() + .cursor_pointer() + .hover(|s| s.bg(white_a(0.07))) + .on_click(move |_, w, cx| { + cx.stop_propagation(); + on(act, w, cx) + }) + .child(svg().path(icon).size(px(20.)).text_color(white_a(0.92))) + }; + let controls = div() + .flex() + .items_center() + .keep_ltr() + .when(chapters.is_some(), |d| d.child(skip("prev", "icons/skip-back.svg", AlbumAct::Prev))) + .child(button) + .when(chapters.is_some(), |d| d.child(skip("next", "icons/skip-forward.svg", AlbumAct::Next))) + .child(middle) + .child(time) + .children(lyrics_btn) + .children(transcribe_btn); + let body = match (tags, art) { + (Some(t), art) if chapters.is_some() => album_view( + att, + t, + art, + album, + p.is_some_and(|p| p.playing), + duration, + accent, + all_tracks, + narrow, + on_album.clone(), + ) + .child(controls) + .into_any_element(), + (Some(t), Some(art)) => { + let track = t.title.clone().unwrap_or_else(|| crate::kit::one_line(&att.name).into_owned()); + let byline = [ + t.artist.clone(), + t.album.clone().filter(|a| Some(a) != t.title.as_ref()), + ] + .into_iter() + .flatten() + .collect::>() + .join(" \u{b7} "); + let line = |d: gpui::Div| d.overflow_hidden().text_ellipsis().whitespace_nowrap(); + let words = div() + .flex_1() + .flex() + .flex_col() + .justify_center() + .gap(px(2.)) + .child( + line(div()) + .id("audio-track-title") + .tip(track.clone()) + .text_size(px(15.75)) + .line_height(px(19.7)) + .font_weight(gpui::FontWeight::SEMIBOLD) + .text_color(white_a(0.92)) + .child(track), + ) + .when(!byline.is_empty(), |d| { + d.child( + line(div()) + .id("audio-track-byline") + .tip(byline.clone()) + .text_size(px(12.)) + .line_height(px(15.)) + .text_color(white_a(0.55)) + .child(byline), + ) + }); + let art_px = if narrow { 64. } else { 128. }; + let (beside, under) = if narrow { (Some(words), None) } else { (None, Some(words)) }; + div() + .relative() + .flex() + .when(narrow, |d| d.flex_col().gap(px(10.))) + .when(!narrow, |d| d.gap(px(14.))) + .child( + div() + .flex() + .gap(px(14.)) + .child( + div() + .id(SharedString::from(format!("audio-art-{}", att.id))) + .aria_label(t::audio_cover_art()) + .size(px(art_px)) + .flex_shrink_0() + .rounded(px(10.)) + .overflow_hidden() + .cursor(gpui::CursorStyle::PointingHand) + .on_click({ + let on = on.clone(); + move |_, w, cx| { + cx.stop_propagation(); + on(Act::Art, w, cx) + } + }) + .bg(c(0x262626)) + .shadow(vec![gpui::BoxShadow { + color: ca(0, 0, 0, 0.35), + offset: point(px(0.), px(4.)), + blur_radius: px(14.), + spread_radius: px(0.), + inset: false, + }]) + .child(crate::pic::img(art).size_full().rounded(px(10.))), + ) + .children(beside.map(|w| div().flex_1().min_w_0().flex().child(w.min_w_0()))), + ) + .map(|d| match under { + None => d.child(controls), + Some(w) => d.child(div().flex_1().min_w_0().flex().flex_col().child(w).child(controls)), + }) + .into_any_element() + } + _ => controls.into_any_element(), + }; + div() + .id(SharedString::from(format!("audio-{id}"))) + .relative() + .overflow_hidden() + .w(px(500.)) + .max_w_full() + .min_w(px(240.)) + .px(px(12.)) + .py(px(10.)) + .bg(c(0x161616)) + .border_1() + .border_color(c(0x262626)) + .rounded(px(12.)) + .hover(|s| s.bg(c(0x1d1d1d)).border_color(c(0x363636))) + .child(probe) + .children(glows(tags, sheet.map_or(0., |s| s.reveal()))) + .child(body) + .children(sheet_el) + .children(transcript_el) + .into_any_element() +} diff --git a/crates/vector-gpui/src/audit.rs b/crates/vector-gpui/src/audit.rs new file mode 100644 index 000000000..7a683dc32 --- /dev/null +++ b/crates/vector-gpui/src/audit.rs @@ -0,0 +1,459 @@ +//! The Audit Log in words (`lib/audit-text.js`): each entry as a sentence of plain and bold +//! parts, the details it expands to, and the family the filter groups it under. + +use gpui::SharedString; +use serde_json::Value; + +use crate::kit::{self, Choice}; +use crate::t; + +pub fn families() -> &'static [Choice] { + let c = |value: &'static str, label: SharedString| Choice { value, label: kit::interned(&label) }; + kit::choices("audit-families", || { + vec![ + c("all", t::audit_family_all()), + c("community", t::audit_family_community()), + c("roles", t::audit_family_roles()), + c("members", t::audit_family_members()), + c("channels", t::audit_family_channels()), + c("messages", t::audit_family_messages()), + c("voice", t::audit_family_voice()), + ] + }) +} + +pub fn family_of(action: &str) -> &'static str { + if action.starts_with("voice_") { + "voice" + } else if action.starts_with("message_") || action == "pins_update" { + "messages" + } else if action.starts_with("member_") || action == "banlist_update" { + "members" + } else if action.starts_with("role") || action == "everyone_update" { + "roles" + } else if action.starts_with("channel_") + || action.starts_with("category_") + || action.starts_with("overwrite_") + { + "channels" + } else { + "community" + } +} + +#[derive(Clone, Copy, PartialEq, Debug)] +pub enum Tone { + Add, + Remove, + Change, +} + +pub fn tone_of(action: &str) -> Tone { + let ends = |s: &str| action.ends_with(s); + if ends("_create") + || ends("_pin") + || matches!(action, "invite_create" | "member_unban" | "roles_activate") + { + Tone::Add + } else if ends("_delete") + || ends("_unpin") + || matches!( + action, + "member_ban" + | "member_kick" + | "member_timeout" + | "voice_disconnect" + | "voice_mute" + | "voice_deafen" + ) + { + Tone::Remove + } else { + Tone::Change + } +} + +pub fn permission_name(bit: u64) -> String { + crate::roles::groups(true) + .into_iter() + .flat_map(|(_, list)| list.iter()) + .find(|p| u64::from(p.bit) == bit) + .map_or_else(|| t::audit_permission_unknown(bit).to_string(), |p| (p.name)().to_string()) +} + +fn perms(list: &Value) -> String { + list.as_array() + .map(|a| { + a.iter() + .filter_map(Value::as_u64) + .map(permission_name) + .collect::>() + .join(", ") + }) + .unwrap_or_default() +} + +fn s<'a>(v: &'a Value, key: &str) -> Option<&'a str> { + v.get(key).and_then(Value::as_str) +} + +fn arr<'a>(v: &'a Value, key: &str) -> &'a [Value] { + v.get(key) + .and_then(Value::as_array) + .map(Vec::as_slice) + .unwrap_or(&[]) +} + +fn field<'a>(entry: &'a Value, name: &str) -> Option<&'a Value> { + arr(entry, "changes") + .iter() + .find(|c| s(c, "field") == Some(name)) +} + +fn target_name(t: Option<&Value>, member: &dyn Fn(Option<&str>) -> String) -> String { + let Some(t) = t.filter(|t| !t.is_null()) else { + return String::new(); + }; + let name = s(t, "name").filter(|n| !n.is_empty()); + match s(t, "kind").unwrap_or("") { + "everyone" => "@everyone".into(), + "role" => name + .map(|n| format!("@{n}")) + .unwrap_or_else(|| t::audit_deleted_role().into()), + "member" => member(s(t, "npub")), + "channel" => match name { + Some(n) if s(t, "view") == Some("voice") => n.into(), + Some(n) => format!("#{n}"), + None => t::audit_private_channel().into(), + }, + "category" => name.map_or_else(|| t::audit_unknown_category().into(), str::to_string), + _ => String::new(), + } +} + +/// `entry` as `(text, bold)` parts; `member` names an npub (or none) as the log shows them. +pub fn sentence(entry: &Value, member: &dyn Fn(Option<&str>) -> String) -> Vec<(String, bool)> { + let bold = |text: String| format!("{}", kit::escape(&text)); + let actor = bold(match s(entry, "actor") { + Some(a) => member(Some(a)), + None => t::audit_someone().into(), + }); + let actor = actor.as_str(); + let t_ = entry.get("target"); + let name = |x: Option<&Value>| bold(target_name(x, member)); + let new_of = |f: &str| field(entry, f).and_then(|c| c.get("new")); + let sub = |key: &str| t_.and_then(|t| t.get(key)); + let author = || bold(member(sub("author").and_then(Value::as_str))); + let count = || new_of("count").and_then(Value::as_u64).filter(|n| *n > 0).unwrap_or(1); + let target = || name(t_); + let html = match s(entry, "action").unwrap_or("") { + "community_create" => t::audit_community_create(actor), + "community_update" => t::audit_community_update(actor), + "roles_activate" => t::audit_roles_activate(actor), + "everyone_update" => t::audit_everyone_update(actor, target()), + "role_create" => t::audit_role_create(actor, target()), + "role_update" => t::audit_role_update(actor, target()), + "role_delete" => t::audit_role_delete(actor, target()), + "member_roles_update" => { + let c = field(entry, "roles"); + let added = c.map(|c| arr(c, "added")).unwrap_or(&[]); + let removed = c.map(|c| arr(c, "removed")).unwrap_or(&[]); + if added.len() == 1 && removed.is_empty() { + t::audit_member_role_give(actor, target(), name(added.first())) + } else if removed.len() == 1 && added.is_empty() { + t::audit_member_role_take(actor, target(), name(removed.first())) + } else { + t::audit_member_roles_update(actor, target()) + } + } + "member_ban" => t::audit_member_ban(actor, target()), + "member_unban" => t::audit_member_unban(actor, target()), + "banlist_update" => t::audit_banlist_update(actor), + "member_kick" => t::audit_member_kick(actor, target()), + "member_timeout" => match new_of("until").and_then(Value::as_u64) { + Some(ms) => t::audit_member_timeout_until(actor, target(), kit::escape(&when_full(ms))), + None => t::audit_member_timeout(actor, target()), + }, + "member_timeout_remove" => t::audit_member_timeout_remove(actor, target()), + "member_nick_update" => { + let nick = new_of("nick").and_then(Value::as_str).filter(|n| !n.is_empty()); + let own = t_.and_then(|t| s(t, "npub")).is_some_and(|n| Some(n) == s(entry, "actor")); + match (nick, own) { + (Some(n), true) => t::audit_nick_set_own(actor, bold(n.to_string())), + (Some(n), false) => t::audit_nick_set(actor, target(), bold(n.to_string())), + (None, true) => t::audit_nick_remove_own(actor), + (None, false) => t::audit_nick_remove(actor, target()), + } + } + "channel_create" => { + let voice = new_of("view").and_then(Value::as_str) == Some("voice"); + let private = new_of("private").and_then(Value::as_bool).unwrap_or(false); + match (private, voice) { + (false, false) => t::audit_channel_create(actor, target()), + (true, false) => t::audit_channel_create_private(actor, target()), + (false, true) => t::audit_channel_create_voice(actor, target()), + (true, true) => t::audit_channel_create_private_voice(actor, target()), + } + } + "channel_update" => t::audit_channel_update(actor, target()), + "channel_delete" => t::audit_channel_delete(actor, target()), + "category_create" => t::audit_category_create(actor, target()), + "category_update" => t::audit_category_update(actor, target()), + "category_delete" => t::audit_category_delete(actor, target()), + "overwrite_create" => t::audit_overwrite_create(actor, name(sub("in")), name(sub("for"))), + "overwrite_update" => t::audit_overwrite_update(actor, name(sub("in")), name(sub("for"))), + "overwrite_delete" => t::audit_overwrite_delete(actor, name(sub("in")), name(sub("for"))), + "channel_sync" => t::audit_channel_sync(actor, name(new_of("category")), target()), + "channel_unsync" => t::audit_channel_unsync(actor, target()), + "message_pin" => t::audit_message_pin(actor, author(), name(sub("channel"))), + "message_unpin" => t::audit_message_unpin(actor, author(), name(sub("channel"))), + "pins_update" => t::audit_pins_update(actor, target()), + "message_delete" => t::audit_message_delete(actor, author(), name(sub("channel"))), + "invite_create" => t::audit_invite_create(actor, count()), + "invite_delete" => t::audit_invite_delete(actor, count()), + "keys_rotate" if field(entry, "severed").is_some() => t::audit_keys_lockdown(actor), + "keys_rotate" => t::audit_keys_rotate(actor), + "voice_mute" => t::audit_voice_mute(actor, name(new_of("channel")), target()), + "voice_unmute" => t::audit_voice_unmute(actor, name(new_of("channel")), target()), + "voice_deafen" => t::audit_voice_deafen(actor, name(new_of("channel")), target()), + "voice_undeafen" => t::audit_voice_undeafen(actor, name(new_of("channel")), target()), + "voice_move" => t::audit_voice_move(actor, name(new_of("to")), target()), + "voice_disconnect" => t::audit_voice_disconnect(actor, name(new_of("channel")), target()), + _ => t::audit_unknown(actor), + }; + kit::runs(&html) +} + +fn view_name(v: &Value) -> String { + match v.as_str() { + Some("chat") => t::audit_view_chat().into(), + Some("voice") => t::audit_view_voice().into(), + Some("forum") => t::audit_view_forum().into(), + Some(o) => o.into(), + None => String::new(), + } +} + +fn hex_color(v: &Value) -> String { + match v.as_u64().filter(|c| *c != 0) { + Some(c) => format!("#{c:06x}"), + None => t::audit_colour_none().into(), + } +} + +fn shown(v: &Value) -> String { + match v { + Value::String(s) => s.clone(), + Value::Null => "null".into(), + o => o.to_string(), + } +} + +/// What `entry` changed, one line each; empty when the sentence says it all. +pub fn details(entry: &Value, member: &dyn Fn(Option<&str>) -> String) -> Vec { + let mut out = Vec::new(); + let action = s(entry, "action").unwrap_or(""); + let creating = action.ends_with("_create"); + let truthy = |v: Option<&Value>| match v { + None | Some(Value::Null) => false, + Some(Value::Bool(b)) => *b, + Some(Value::String(s)) => !s.is_empty(), + Some(Value::Number(n)) => n.as_f64() != Some(0.), + Some(_) => true, + }; + for c in arr(entry, "changes") { + let old = c.get("old").filter(|v| !v.is_null()); + let new = c.get("new"); + let added = arr(c, "added"); + let removed = arr(c, "removed"); + match s(c, "field").unwrap_or("") { + "name" => { + if !creating || action == "community_create" { + let new = new.map(shown).unwrap_or_default(); + out.push(match old { + Some(o) => t::audit_detail_rename(new, shown(o)), + None => t::audit_detail_name(new), + }); + } + } + "description" => out.push(if truthy(new) { t::audit_detail_description() } else { t::audit_detail_description_removed() }), + "topic" => out.push(if truthy(new) { + t::audit_detail_topic(new.map(shown).unwrap_or_default()) + } else { + t::audit_detail_topic_removed() + }), + f @ ("icon" | "banner") => out.push(match (f, new.and_then(Value::as_str)) { + ("icon", Some("removed")) => t::audit_detail_icon_removed(), + ("icon", Some("added")) => t::audit_detail_icon_added(), + ("icon", _) => t::audit_detail_icon_changed(), + (_, Some("removed")) => t::audit_detail_banner_removed(), + (_, Some("added")) => t::audit_detail_banner_added(), + _ => t::audit_detail_banner_changed(), + }), + "landing" => out.push(if new.and_then(|n| s(n, "kind")) == Some("channel") { + t::audit_detail_landing(target_name(new, member)) + } else { + t::audit_detail_landing_default() + }), + "system_messages" => out.push(match new { + Some(Value::String(o)) if o == "off" => t::audit_detail_system_off(), + Some(n) if s(n, "kind") == Some("channel") => t::audit_detail_system(target_name(new, member)), + _ => t::audit_detail_system_default(), + }), + f @ ("relays" | "voice_relays") => { + let voice = f == "voice_relays"; + out.extend(added.iter().map(|r| { + if voice { t::audit_detail_voice_relay_added(shown(r)) } else { t::audit_detail_relay_added(shown(r)) } + })); + out.extend(removed.iter().map(|r| { + if voice { t::audit_detail_voice_relay_removed(shown(r)) } else { t::audit_detail_relay_removed(shown(r)) } + })); + } + "color" => { + let now = hex_color(new.unwrap_or(&Value::Null)); + out.push(match old { + Some(o) => t::audit_detail_recolour(now, hex_color(o)), + None => t::audit_detail_colour(now), + }) + } + "permissions" => { + if !added.is_empty() { + let list = perms(&c["added"]); + out.push(if creating { t::audit_detail_permissions(list) } else { t::audit_detail_granted(list) }); + } + if !removed.is_empty() { + out.push(t::audit_detail_revoked(perms(&c["removed"]))); + } + } + "allow" => { + if !added.is_empty() { + out.push(t::audit_detail_allowed(perms(&c["added"]))); + } + if !removed.is_empty() { + out.push(t::audit_detail_unallowed(perms(&c["removed"]))); + } + } + "deny" => { + if !added.is_empty() { + out.push(t::audit_detail_denied(perms(&c["added"]))); + } + if !removed.is_empty() { + out.push(t::audit_detail_undenied(perms(&c["removed"]))); + } + } + "position" => out.push(t::audit_detail_position()), + "display" => out.push(if truthy(new) { t::audit_detail_display() } else { t::audit_detail_display_off() }), + "mentionable" => out.push(if truthy(new) { t::audit_detail_mentionable() } else { t::audit_detail_mentionable_off() }), + "view" if !creating => out.push(t::audit_detail_view( + new.map(view_name).unwrap_or_default(), + old.map(view_name).unwrap_or_default(), + )), + "private" if !creating => out.push(t::audit_detail_private()), + "category" if action == "channel_update" => out.push(if truthy(new) { + t::audit_detail_moved(target_name(new, member)) + } else { + t::audit_detail_uncategorised() + }), + "roles" => { + out.extend(added.iter().map(|r| t::audit_detail_role_added(target_name(Some(r), member)))); + out.extend(removed.iter().map(|r| t::audit_detail_role_removed(target_name(Some(r), member)))); + if let Some(held) = c.get("held").and_then(Value::as_array) { + out.push(if held.is_empty() { + t::audit_detail_no_roles() + } else { + t::audit_detail_roles(held.iter().map(|r| target_name(Some(r), member)).collect::>().join(", ")) + }); + } + } + "nick" => match ( + old.and_then(Value::as_str).filter(|s| !s.is_empty()), + new.and_then(Value::as_str).filter(|s| !s.is_empty()), + ) { + (Some(o), Some(n)) => out.push(t::audit_detail_renick(n, o)), + (Some(o), None) => out.push(t::audit_detail_nick_removed(o)), + _ => {} + }, + "banned" => { + if let Some(held) = c.get("held").and_then(Value::as_array) { + out.push(if held.is_empty() { + t::audit_detail_no_bans() + } else { + t::audit_detail_bans(held.iter().map(|m| target_name(Some(m), member)).collect::>().join(", ")) + }); + } + } + _ => {} + } + } + if entry.get("partial").and_then(Value::as_bool).unwrap_or(false) { + out.push(t::audit_detail_partial()); + } + out.into_iter().map(String::from).collect() +} + +pub fn plain_text(entry: &Value, member: &dyn Fn(Option<&str>) -> String) -> String { + sentence(entry, member) + .into_iter() + .map(|(t, _)| t) + .collect() +} + +/// When an entry happened, as a person says it. +pub fn when(ms: u64, now: u64) -> String { + let diff = now.saturating_sub(ms); + if diff < 60_000 { + return t::audit_just_now().into(); + } + if diff < 3_600_000 { + return t::audit_minutes_ago(diff / 60_000).into(); + } + let d = crate::data::local(ms); + let today = crate::data::local(now); + let days = (today.date_naive() - d.date_naive()).num_days(); + match days { + 0 => t::audit_today_at(crate::data::clock(ms)).into(), + 1 => t::audit_yesterday_at(crate::data::clock(ms)).into(), + _ if chrono::Datelike::year(&d) == chrono::Datelike::year(&today) => { + crate::dates::date(&d, crate::dates::DateStyle::DayMonth) + } + _ => crate::dates::date(&d, crate::dates::DateStyle::Medium), + } +} + +pub fn when_full(ms: u64) -> String { + crate::dates::date_time(&crate::data::local(ms), crate::dates::DateStyle::Medium, crate::dates::Clock::SHORT) +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + #[test] + fn sentences_and_details() { + let member = |n: Option<&str>| { + n.map(|n| n.chars().take(5).collect()) + .unwrap_or_else(|| "someone".into()) + }; + let e = json!({"actor": "alice", "action": "member_roles_update", "target": {"kind": "member", "npub": "bobby"}, "changes": [{"field": "roles", "added": [{"kind": "role", "name": "Mods"}], "removed": []}]}); + assert_eq!(plain_text(&e, &member), "alice gave bobby the role @Mods"); + assert_eq!(details(&e, &member), vec!["Added @Mods"]); + let e = json!({"action": "role_create", "target": {"kind": "role", "name": "Mods"}, "changes": [{"field": "name", "new": "Mods"}, {"field": "permissions", "added": [3, 4], "removed": []}]}); + assert_eq!(plain_text(&e, &member), "Someone created the role @Mods"); + assert_eq!( + details(&e, &member), + vec!["Permissions: Kick Members, Ban Members"] + ); + let e = json!({"actor": "alice", "action": "voice_mute", "target": {"kind": "member", "npub": "bobby"}, "changes": [{"field": "channel", "new": {"kind": "channel", "name": "Lounge", "view": "voice"}}]}); + assert_eq!(plain_text(&e, &member), "alice muted bobby in Lounge"); + let e = json!({"actor": "alice", "action": "overwrite_update", "target": {"for": {"kind": "role", "name": "Mods"}, "in": {"kind": "channel", "name": "dev"}}}); + assert_eq!(plain_text(&e, &member), "alice changed permissions for @Mods in #dev"); + let e = json!({"actor": "alice", "action": "channel_sync", "target": {"kind": "channel", "name": "dev"}, "changes": [{"field": "category", "new": {"kind": "category", "name": "Work"}}]}); + assert_eq!(plain_text(&e, &member), "alice synced #dev to Work"); + let e = json!({"actor": "alice", "action": "channel_update", "target": {"kind": "channel", "name": "devs"}, "changes": [{"field": "name", "old": "dev", "new": "devs"}]}); + assert_eq!(details(&e, &member), vec!["Name: dev → devs"]); + assert_eq!(tone_of("member_ban"), Tone::Remove); + assert_eq!(family_of("overwrite_update"), "channels"); + assert_eq!(when(1_000_000, 1_000_000 + 120_000), "2 minutes ago"); + } +} diff --git a/crates/vector-gpui/src/backend/account.rs b/crates/vector-gpui/src/backend/account.rs new file mode 100644 index 000000000..8cdb5b356 --- /dev/null +++ b/crates/vector-gpui/src/backend/account.rs @@ -0,0 +1,894 @@ +//! Account lifecycle: boot probe, import, create, encryption setup, unlock and connect. + +use std::sync::Mutex; + +use nostr_sdk::prelude::*; +use vector_core::db; +use vector_core::state::{self, MNEMONIC_SEED, PENDING_NSEC}; +use vector_core::{MY_SECRET_KEY, Profile, STATE, SignerKind}; +use zeroize::{Zeroize, Zeroizing}; + +/// An account created or imported, held until its security step commits it. +static PENDING_ACCOUNT: Mutex> = Mutex::new(None); +/// The npub of a keypair generated this session, armed for its one empty kind-0. +static FRESH_ACCOUNT_NPUB: Mutex> = Mutex::new(None); + +/// What boot finds on disk. +#[derive(Debug, Clone)] +pub struct BootInfo { + pub account: Option, + pub encrypted: bool, + /// "pin" or "password". + pub security_type: String, + pub signer: String, + /// The remembered account's database is newer than this build: nothing may open it. + pub downgrade: Option, + /// The remembered account's database would not open. + pub load_error: Option, +} + +#[derive(Debug, Clone)] +pub struct Account { + pub npub: String, + pub name: Option, + pub avatar: Option, + pub encrypted: bool, + pub last_active: i64, +} + +pub enum Imported { + /// A new identity, staged until its security step. + Staged(String), + /// An account already on this device: it is now the active one, to unlock. + Existing(String), +} + +/// An account on disk is real once its setup committed: a stored key, or a keyless signer's +/// identity. One abandoned before that holds neither. +pub(super) fn is_committed(npub: &str) -> bool { + if !db::get_accounts() + .unwrap_or_default() + .iter() + .any(|n| n == npub) + { + return false; + } + let Ok(path) = db::account_dir(npub).map(|d| d.join("vector.db")) else { + return false; + }; + let Ok(conn) = + rusqlite::Connection::open_with_flags(&path, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY) + else { + return false; + }; + conn.query_row( + "SELECT 1 FROM settings WHERE key IN ('pkey', 'nip55_user_pubkey') LIMIT 1", // i18n-exempt: SQL + [], + |_| Ok(()), + ) + .is_ok() +} + +/// Select the remembered account, or arm the welcome screen's network when there is none. +pub fn boot() -> BootInfo { + if let Some(npub) = db::read_active_account_file().ok().flatten() + && let Ok(Some(block)) = db::inspect_downgrade(&npub) + { + return BootInfo { + account: None, + encrypted: false, + security_type: "pin".into(), + signer: "local".into(), + downgrade: Some(block), + load_error: None, + }; + } + let mut load_error = None; + let account = match db::get_current_account() { + Ok(npub) => Some(npub), + Err(_) => match db::read_active_account_file().ok().flatten() { + Some(npub) if is_committed(&npub) => opened(&npub, &mut load_error).then_some(npub), + Some(_) => { + let _ = db::clear_active_account_file(); + None + } + // One committed account and no marker: it is the one. + None => { + let committed: Vec = db::get_accounts() + .unwrap_or_default() + .into_iter() + .filter(|n| is_committed(n)) + .collect(); + match committed.as_slice() { + [only] => opened(only, &mut load_error).then(|| only.clone()), + _ => None, + } + } + }, + }; + let Some(account) = account else { + vector_core::transport::prelogin::apply_at_boot(); + return BootInfo { + account: None, + encrypted: false, + security_type: "pin".into(), + signer: "local".into(), + downgrade: None, + load_error, + }; + }; + state::init_encryption_enabled(); + let mut encrypted = state::is_encryption_enabled_fast(); + // An account older than the `encryption_enabled` row holds ciphertext with no flag: route it to + // the PIN screen and record it, as the desktop client does (PIN predates passwords). + if !encrypted && db::get_pkey().ok().flatten().is_some_and(|k| !k.starts_with("nsec1")) { + let _ = db::set_sql_setting("encryption_enabled".into(), "true".into()); + if db::get_sql_setting("security_type".into()).ok().flatten().is_none() { + let _ = db::set_sql_setting("security_type".into(), "pin".into()); + } + state::set_encryption_enabled(true); + encrypted = true; + } + let security_type = if encrypted { + db::get_sql_setting("security_type".into()) + .ok() + .flatten() + .unwrap_or_else(|| "pin".into()) + } else { + "pin".into() + }; + let signer = db::get_signer_type().unwrap_or_else(|_| "local".into()); + BootInfo { + account: Some(account), + encrypted, + security_type, + signer, + downgrade: None, + load_error: None, + } +} + +/// A process a push started: the account the app last used, opened without a window, its +/// profiles loaded so a notification can name its sender. The window's boot finds it open. +#[cfg(target_os = "android")] +pub async fn open_headless() -> bool { + if db::get_current_account().is_ok() { + return true; + } + let Some(npub) = db::read_active_account_file().ok().flatten().filter(|n| is_committed(n)) else { + return false; + }; + // A database a newer build wrote stays shut until that build opens it. + if !matches!(db::inspect_downgrade(&npub), Ok(None)) || !opened(&npub, &mut None) { + return false; + } + state::init_encryption_enabled(); + if let Ok(profiles) = db::profiles::get_all_profiles() { + let mut state = vector_core::STATE.lock().await; + for slim in profiles { + let npub = slim.id.clone(); + state.insert_or_replace_profile(&npub, slim.to_profile()); + } + } + true +} + +/// The background service with no window: the account the app last used, signed in and +/// listening when it opens without a PIN or a signer, as the window would. False otherwise. +#[cfg(target_os = "android")] +pub async fn standby() -> bool { + // A welcome-screen sign-in owns the transport and the vault. + if vector_core::transport::prelogin::armed().is_some() || !open_headless().await { + return false; + } + let plain = !state::is_encryption_enabled_fast() + && db::get_signer_type().unwrap_or_else(|_| "local".into()) == "local" + && db::get_pkey().ok().flatten().is_some_and(|k| k.starts_with("nsec1")); + if !plain { + if state::is_encryption_enabled_fast() { + // spawn-detached: watches until any sign-in, then stops; it owns no account state. + tokio::spawn(locked_watch()); + } + return false; + } + if let Err(e) = unlock(None).await { + vector_core::log_warn!("[standby] sign-in failed: {e}"); + return false; + } + { + let _one = OPENING.lock().await; + let Some(client) = state::nostr_client() else { + return false; + }; + if client.relays().await.is_empty() { + db::current_session().scoped::().store(true, std::sync::atomic::Ordering::SeqCst); + super::network::connect_one(&client).await; + super::network::start_relay_monitor(&client); + } + } + super::sync::notifs(); + true +} + +/// The pool holds only standby's one relay: a window's sign-in adds the rest. +struct OneRelay; + +/// A PIN account can't be read without its PIN: a client with no key, on the account's own +/// network, notices gift wraps for it and says only that something came, as Tauri does. +#[cfg(target_os = "android")] +async fn locked_watch() { + use vector_core::transport::{self, prefs, prelogin}; + let Some(me) = db::get_current_account().ok().and_then(|n| PublicKey::from_bech32(&n).ok()) else { + return; + }; + transport::set_preference(prelogin::effective(&prefs::stored_kind())); + if transport::preference().is_none() { + return; + } + if transport::preference().is_some_and(|k| k != transport::Kind::Clearnet) + && let Err(e) = super::transport::start_for_active_account().await + { + vector_core::log_warn!("[standby] network start failed: {e}"); + } + super::transport::wait_for_active_network().await; + let client = vector_core::nostr_client_builder().monitor(Monitor::new(64)).build(); + super::network::add_configured_relays(&client).await; + client.connect().await; + // A relay that replays history stops at NIP-59's backdating window. + let since = vector_core::clock::timestamp().as_secs().saturating_sub(2 * 24 * 3600); + let filter = Filter::new().pubkey(me).kind(Kind::GiftWrap).since(Timestamp::from_secs(since)).limit(0); + let Ok(sub) = client.subscribe(filter).await.map(|o| o.value) else { + client.disconnect().await; + return; + }; + let mut seen = std::collections::HashSet::new(); + let mut last: Option = None; + let mut notes = client.notifications(); + while let Some(n) = futures::StreamExt::next(&mut notes).await { + // Signed in: the account's own client takes over. + if vector_core::my_public_key().is_some() { + break; + } + let ClientNotification::Event { subscription_id, event, .. } = n else { continue }; + if subscription_id != sub || !seen.insert(event.id) { + continue; + } + if seen.len() > 1000 { + seen.clear(); + } + // No ledger to tell new mail from a replay: one notice per half minute. + if last.is_none_or(|t| t.elapsed() >= std::time::Duration::from_secs(30)) { + last = Some(std::time::Instant::now()); + super::notify::pushed_unknown(); + } + } + client.disconnect().await; +} + +/// Make `npub` the account in use and open its database; why not, kept for the user. +fn opened(npub: &str, error: &mut Option) -> bool { + match db::set_current_account(npub.to_string()).and_then(|_| db::init_database(npub)) { + Ok(_) => true, + Err(e) => { + *error = Some(e); + false + } + } +} + +/// Every committed account, most recently used first. +pub fn accounts() -> Vec { + let mut out: Vec = db::get_accounts() + .unwrap_or_default() + .into_iter() + .filter(|n| is_committed(n)) + .map(|n| metadata(&n)) + .collect(); + out.sort_by_key(|a| std::cmp::Reverse(a.last_active)); + out +} + +fn metadata(npub: &str) -> Account { + let mut meta = Account { + npub: npub.to_string(), + name: None, + avatar: None, + encrypted: false, + last_active: 0, + }; + let Ok(path) = db::account_dir(npub).map(|d| d.join("vector.db")) else { + return meta; + }; + let Ok(conn) = + rusqlite::Connection::open_with_flags(&path, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY) + else { + return meta; + }; + if let Ok((nickname, display, name, avatar_cached)) = conn.query_row( + "SELECT nickname, display_name, name, avatar_cached FROM profiles WHERE npub = ?1", // i18n-exempt: SQL + [npub], + |r| { + Ok(( + r.get::<_, String>(0)?, + r.get::<_, String>(1)?, + r.get::<_, String>(2)?, + r.get::<_, String>(3)?, + )) + }, + ) { + meta.name = [nickname, display, name] + .into_iter() + .find(|s| !s.is_empty()); + meta.avatar = (!avatar_cached.is_empty()).then_some(avatar_cached); + } + let setting = |key: &str| { + // i18n-exempt: SQL + conn.query_row("SELECT value FROM settings WHERE key = ?1", [key], |r| { + r.get::<_, String>(0) + }) + .ok() + }; + meta.encrypted = state::resolve_encryption_enabled( + setting("encryption_enabled").as_deref(), + setting("security_type").as_deref(), + ); + meta.last_active = setting("last_active") + .and_then(|v| v.parse().ok()) + .unwrap_or(0); + meta +} + +pub(super) fn touch_last_active() { + let _ = db::set_sql_setting("last_active".into(), vector_core::clock::now_secs().to_string()); +} + +pub(super) fn install_client() { + let client = vector_core::nostr_client_builder() + .monitor(Monitor::new(1024)) + .build(); + state::set_nostr_client_if_absent(client); +} + +pub(super) async fn insert_own_profile(npub: &str) { + let mut profile = Profile::new(); + profile.flags.set_mine(true); + STATE.lock().await.insert_or_replace_profile(npub, profile); +} + +fn store_identity(keys: &Keys) { + MY_SECRET_KEY.store_from_keys(keys, &[&vector_core::ENCRYPTION_KEY]); + state::set_my_public_key(keys.public_key()); +} + +/// Sign in with an nsec or a BIP-39 seed phrase. +pub async fn import(mut key: String) -> Result { + let keys = if key.starts_with("nsec") { + let parsed = Keys::parse(&key).map_err(|_| crate::t::login_invalid_nsec().to_string()); + key.zeroize(); + parsed? + } else { + let phrase = Zeroizing::new(std::mem::take(&mut key)); + Keys::from_mnemonic(phrase.trim(), Some("")) + .map_err(|_| crate::t::login_invalid_seed().to_string())? + }; + *FRESH_ACCOUNT_NPUB.lock().unwrap_or_else(|e| e.into_inner()) = None; + let npub = keys.public_key().to_bech32().map_err(|e| e.to_string())?; + if is_committed(&npub) { + db::write_active_account_file(&npub)?; + return Ok(Imported::Existing(npub)); + } + if state::nostr_client().is_some() { + return Err(crate::t::login_already_signed_in().into()); + } + *PENDING_NSEC.lock().unwrap_or_else(|e| e.into_inner()) = Some(keys.secret_key().to_bech32().map_err(|e| e.to_string())?); + if let Some(stale) = MNEMONIC_SEED.lock().unwrap_or_else(|e| e.into_inner()).as_mut() { + stale.zeroize(); + } + *MNEMONIC_SEED.lock().unwrap_or_else(|e| e.into_inner()) = None; + store_identity(&keys); + drop(keys); + install_client(); + insert_own_profile(&npub).await; + *PENDING_ACCOUNT.lock().unwrap_or_else(|e| e.into_inner()) = Some(npub.clone()); + Ok(Imported::Staged(npub)) +} + +/// A new identity from a fresh 12-word phrase. +pub async fn create() -> Result { + let mnemonic = bip39::Mnemonic::generate(12).map_err(|e| e.to_string())?; + let phrase = mnemonic.to_string(); + let keys = Keys::from_mnemonic(phrase.as_str(), None).map_err(|e| e.to_string())?; + *PENDING_NSEC.lock().unwrap_or_else(|e| e.into_inner()) = Some(keys.secret_key().to_bech32().map_err(|e| e.to_string())?); + store_identity(&keys); + let npub = keys.public_key().to_bech32().map_err(|e| e.to_string())?; + drop(keys); + install_client(); + insert_own_profile(&npub).await; + *MNEMONIC_SEED.lock().unwrap_or_else(|e| e.into_inner()) = Some(phrase); + *PENDING_ACCOUNT.lock().unwrap_or_else(|e| e.into_inner()) = Some(npub.clone()); + *FRESH_ACCOUNT_NPUB.lock().unwrap_or_else(|e| e.into_inner()) = Some(npub.clone()); + Ok(npub) +} + +/// Commit the pending account: its key sealed under `password`, or kept plain without one. +pub async fn commit( + password: Option>, + security_type: &str, +) -> Result<(), String> { + if password.as_ref().is_some_and(|p| p.trim().is_empty()) { + return Err(crate::t::login_password_empty().into()); + } + // One derivation seals the key and the seed; the vault and the flag change only once the + // commit has landed, so a failed commit leaves nothing behind for a retry. + let sealed = match &password { + Some(pwd) => { + let kdf = vector_core::crypto::Kdf::fresh(); + let key = Zeroizing::new(vector_core::crypto::derive_key(pwd.as_str(), &kdf).await); + Some((key, kdf)) + } + None => None, + }; + drop(password); + commit_with(sealed, security_type, None).await +} + +/// Commit the pending account under a credential only the phone's prompt opens. Its keystore +/// key goes again if the commit fails. +#[cfg(target_os = "android")] +pub async fn commit_biometric() -> Result<(), String> { + let npub = pending().map_or_else(db::get_current_account, Ok)?; + let (wrapped, key, kdf) = super::biometric::generate_and_wrap(&npub).await?; + let out = commit_with(Some((key, kdf)), "biometric", Some(wrapped)).await; + if out.is_err() { + super::biometric::forget_keystore(&npub); + } + out +} + +/// The staged account becomes the one on disk: its database, the marker, and its network. +pub(super) async fn open_pending() -> Result<(), String> { + let pending = PENDING_ACCOUNT.lock().unwrap_or_else(|e| e.into_inner()).take(); + let Some(npub) = pending else { return Ok(()) }; + // The welcome screen's network carries on into the new account's first session. + if !super::transport::running_prelogin() { + super::transport::stop_and_join_if_running().await; + } + if let Err(e) = db::init_database(&npub) { + let _ = super::transport::sync_to_active_account().await; + return Err(e); + } + db::set_current_account(npub.clone())?; + db::write_active_account_file(&npub)?; + if let Err(e) = super::transport::sync_to_active_account().await { + vector_core::log_warn!("[Account] network start for new account failed: {e}"); + } + Ok(()) +} + +async fn commit_with( + sealed: Option<(Zeroizing<[u8; 32]>, vector_core::crypto::Kdf)>, + security_type: &str, + wrap: Option, +) -> Result<(), String> { + #[cfg(target_os = "android")] + if vector_core::signer_kind() == SignerKind::Nip55 { + return super::nip55::commit(sealed, security_type, wrap).await; + } + let nsec = Zeroizing::new( + PENDING_NSEC + .lock() + .unwrap() + .clone() + .ok_or("No pending key")?, // i18n-exempt: developer error + ); + let seed = MNEMONIC_SEED.lock().unwrap_or_else(|e| e.into_inner()).clone().map(Zeroizing::new); + let (key, kdf) = match sealed { + Some((key, kdf)) => (Some(key), Some(kdf)), + None => (None, None), + }; + let seal = |plain: &str| -> Result { + match &key { + Some(k) => vector_core::crypto::encrypt_with_key(plain, k), + None => Ok(plain.to_string()), + } + }; + let stored_key = seal(&nsec)?; + let stored_seed = seed.as_deref().map(|s| seal(s)).transpose()?; + let kdf_row = kdf.as_ref().and_then(|k| k.descriptor()); + + open_pending().await?; + let encrypted = key.is_some(); + let security = encrypted.then_some(security_type); + if vector_core::signer_kind() == SignerKind::Bunker { + let (url, remote_hex) = state::pending_bunker_setup() + .ok_or("Bunker setup state missing — re-run Connect Remote Signer")?; // i18n-exempt: matched by the re-pair offer + db::settings::commit_bunker_account_setup( + &stored_key, + encrypted, + security, + &seal(&url)?, + &remote_hex, + wrap.as_deref(), + kdf_row.as_deref(), + )?; + state::clear_pending_bunker_setup(); + } else { + db::settings::commit_account_setup( + &stored_key, + encrypted, + security, + stored_seed.as_deref(), + wrap.as_deref(), + kdf_row.as_deref(), + )?; + } + if let Some(k) = &key { + vector_core::ENCRYPTION_KEY.set(**k, &[&MY_SECRET_KEY]); + } + for slot in [&PENDING_NSEC, &MNEMONIC_SEED] { + let mut guard = slot.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(s) = guard.as_mut() { + s.zeroize(); + } + *guard = None; + } + state::set_encryption_enabled(encrypted); + touch_last_active(); + vector_core::blossom_servers::refresh_cache(); + stamp_fresh_account_profile(); + Ok(()) +} + +/// Publish an empty kind-0 tagged `client: vector` for a keypair generated moments ago, so +/// NIP-89 readers recognise it. Never for an imported or unlocked identity. +fn stamp_fresh_account_profile() { + let armed = FRESH_ACCOUNT_NPUB.lock().unwrap_or_else(|e| e.into_inner()).take(); + let Some(client) = state::nostr_client() else { + return; + }; + let current = vector_core::my_public_key().and_then(|pk| pk.to_bech32().ok()); + if armed.is_none() || armed != current { + return; + } + db::spawn_bound(async move { + let builder = + EventBuilder::new(Kind::Metadata, "{}").tag(Tag::custom("client", vec!["vector"])); + if let Ok(event) = vector_core::sign_builder(builder).await { + let relays = state::active_trusted_relays().await; + if let Err(e) = client.send_event(&event).to(relays).await { + vector_core::log_warn!("[Account] new-account profile stamp failed: {e}"); + } + } + }); +} + +/// The account staged for its security step, if any. +pub(super) fn pending() -> Option { + PENDING_ACCOUNT.lock().unwrap_or_else(|e| e.into_inner()).clone() +} + +pub(super) fn set_pending(npub: String) { + *FRESH_ACCOUNT_NPUB.lock().unwrap_or_else(|e| e.into_inner()) = None; + *PENDING_ACCOUNT.lock().unwrap_or_else(|e| e.into_inner()) = Some(npub); +} + +/// Forget an account that was started but never committed. +pub fn abandon_pending() { + *PENDING_ACCOUNT.lock().unwrap_or_else(|e| e.into_inner()) = None; + *FRESH_ACCOUNT_NPUB.lock().unwrap_or_else(|e| e.into_inner()) = None; +} + +/// What opens the stored key. +enum Opener { + Plain, + Password(Zeroizing), + /// The vault key itself, from the system's own prompt. + #[cfg_attr(not(target_os = "android"), allow(dead_code))] + Key(Zeroizing<[u8; 32]>), +} + +/// Unlock the stored account: its key opened under `password` when it is encrypted. +pub async fn unlock(password: Option>) -> Result { + open_with(password.map_or(Opener::Plain, Opener::Password)).await +} + +/// Unlock with the vault key itself. A key that does not open the stored one is refused with +/// [`super::biometric::INVALIDATED`] before the vault sees it. +#[cfg(target_os = "android")] +pub(super) async fn unlock_with_key(key: Zeroizing<[u8; 32]>) -> Result { + open_with(Opener::Key(key)).await +} + +/// The window and the background service can both open the account at boot. +static OPENING: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(()); + +async fn open_with(opener: Opener) -> Result { + let _one = OPENING.lock().await; + *FRESH_ACCOUNT_NPUB.lock().unwrap_or_else(|e| e.into_inner()) = None; + state::init_encryption_enabled(); + if let Some(pk) = vector_core::my_public_key().filter(|_| state::nostr_client().is_some()) { + return pk.to_bech32().map_err(|e| e.to_string()); + } + { + use vector_core::transport::{self, kinds, prefs, prelogin, Kind}; + let effective = prelogin::effective(&prefs::stored_kind()); + transport::set_preference(effective); + // A welcome-screen instance is kept only where its kind adopts on unlock (Tor never does: + // its guards are install-level). + let adopt = transport::host::active().is_some_and(|a| { + a.started_prelogin() + && Some(a.kind) == effective + && kinds::factory(a.kind).is_some_and(|f| { + f.adopt_on_unlock() && f.compatible(a.transport().as_ref(), &prelogin::config_for(a.kind)) + }) + }); + if !adopt { + super::transport::stop_prelogin_service().await; + } + // Started now, awaited once the key has opened: a wrong password never waits on tunnels. + if effective.is_some_and(|k| k != Kind::Clearnet) + && let Err(e) = super::transport::start_for_active_account().await + { + vector_core::log_warn!("[Login] network auto-start failed: {e}"); + } + } + + let kind = + SignerKind::from_setting_str(&db::get_signer_type().unwrap_or_else(|_| "local".into())); + let bunker = matches!(kind, SignerKind::Bunker); + #[cfg(target_os = "android")] + if matches!(kind, SignerKind::Nip55) { + return unlock_nip55(opener).await; + } + if !matches!(kind, SignerKind::Local | SignerKind::Bunker) { + return Err( + crate::t::login_external_signer().into(), + ); + } + let stored = db::get_pkey()?.ok_or_else(|| crate::t::login_no_private_key().to_string())?; + let mut nsec = match &opener { + Opener::Password(pwd) => { + // The vault takes the key only once it has opened the stored key. + let kdf = vector_core::crypto::Kdf::of_account()?; + let key = Zeroizing::new(vector_core::crypto::derive_key(pwd.as_str(), &kdf).await); + let nsec = vector_core::crypto::decrypt_with_key(&stored, &key) + .map_err(|_| "Incorrect password".to_string())?; // i18n-exempt: matched by the login screen + vector_core::crypto::install_unlocked_key(&key, &kdf)?; + match db::at_rest::upgrade_after_unlock(pwd, &key).await { + Ok(true) => { + let _ = db::at_rest::vacuum_now(); + } + Ok(false) => {} + Err(e) => vector_core::log_warn!("[Encryption] Salt upgrade deferred: {e}"), + } + nsec + } + Opener::Key(key) => { + let nsec = vector_core::crypto::decrypt_with_key(&stored, key) + .map_err(|_| super::biometric::INVALIDATED.to_string())?; + vector_core::crypto::install_unlocked_key(key, &vector_core::crypto::Kdf::of_account()?)?; + nsec + } + Opener::Plain => stored, + }; + let keys = Keys::parse(&nsec).map_err(|_| crate::t::login_invalid_stored_key().to_string())?; + nsec.zeroize(); + store_identity(&keys); + // A bunker account's stored key is only its client keypair: the identity is the signer's. + if bunker { + let remote = super::bunker::reconnect(&keys).await?; + state::set_my_public_key(remote); + } + drop(keys); + finish_unlock().await +} + +/// An account whose identity lives in a signer app on the phone: nothing secret is stored here, +/// so a credential opens only the local data, proven against the canary its setup wrote. +#[cfg(target_os = "android")] +async fn unlock_nip55(opener: Opener) -> Result { + use vector_core::crypto::{Kdf, install_unlocked_key}; + match &opener { + Opener::Password(pwd) => { + let kdf = Kdf::of_account()?; + let key = Zeroizing::new(vector_core::crypto::derive_key(pwd.as_str(), &kdf).await); + install_unlocked_key(&key, &kdf)?; + match db::at_rest::upgrade_after_unlock(pwd, &key).await { + Ok(true) => { + let _ = db::at_rest::vacuum_now(); + } + Ok(false) => {} + Err(e) => vector_core::log_warn!("[Encryption] Salt upgrade deferred: {e}"), + } + } + Opener::Key(key) => install_unlocked_key(key, &Kdf::of_account()?) + .map_err(|_| super::biometric::INVALIDATED.to_string())?, + Opener::Plain => {} + } + drop(opener); + let hex = db::get_nip55_user_pubkey()?.ok_or_else(|| crate::t::login_no_private_key().to_string())?; + let pk = PublicKey::parse(&hex).map_err(|e| e.to_string())?; + // A signer app removed since: the account still opens, and Settings offers the re-pair. + if !matches!(vector_core::nip55_is_installed(), Ok(true)) { + vector_core::set_nip55_state(vector_core::Nip55State::Missing); + } + vector_core::set_signer_kind(SignerKind::Nip55); + if let Ok(Some(package)) = db::get_nip55_signer_package() { + crate::android::external_signer::set_signer_package(package); + } + state::set_my_public_key(pk); + finish_unlock().await +} + +/// A bunker account whose signer was re-paired during unlock: the vault already holds its +/// client key and the stored link is the new pairing. +pub async fn resume_bunker_unlock() -> Result { + // owned-key: the NIP-46 client keypair, which the login session owns for its life. + let keys = MY_SECRET_KEY.to_keys().ok_or("No client keypair loaded")?; // i18n-exempt: developer error + let remote = super::bunker::reconnect(&keys).await?; + drop(keys); + state::set_my_public_key(remote); + finish_unlock().await +} + +async fn finish_unlock() -> Result { + super::transport::wait_for_active_network().await; + install_client(); + + let npub = vector_core::my_public_key() + .ok_or("no identity")? // i18n-exempt: developer error + .to_bech32() + .map_err(|e| e.to_string())?; + insert_own_profile(&npub).await; + db::init_database(&npub)?; + db::set_current_account(npub.clone())?; + touch_last_active(); + state::init_encryption_enabled(); + if let Err(e) = db::at_rest::backfill_at_rest() { + vector_core::log_warn!("[Login] community at-rest backfill deferred: {e}"); + } + vector_core::blossom_servers::refresh_cache(); + Ok(npub) +} + +/// Add the configured and discovery relays, then connect. False if already connected. +pub async fn connect() -> bool { + let _one = OPENING.lock().await; + let Some(client) = state::nostr_client() else { + return false; + }; + let one = db::current_session().scoped::().swap(false, std::sync::atomic::Ordering::SeqCst); + if !one && !client.relays().await.is_empty() { + return false; + } + super::network::add_configured_relays(&client).await; + super::network::start_relay_monitor(&client); + db::spawn_bound(async { + tokio::time::sleep(std::time::Duration::from_millis(500)).await; + super::network::reconcile_dm_relay_list().await; + }); + true +} + +/// Make `npub` the account the next boot opens. +pub fn set_active(npub: &str) -> Result<(), String> { + db::write_active_account_file(npub) +} + +/// How many accounts this device may add up to: the soft cap of its highest tier. +pub fn account_cap() -> usize { + [3, 6, 9, usize::MAX][vector_core::badges::max_account_tier().min(3) as usize] +} + +static RESET_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(()); + +/// Tear the live account down to a fresh boot: its client, database, keys and transfers. +pub async fn reset() { + let _serial = RESET_LOCK.lock().await; + super::emit("unread_total", 0); + if let Some(npub) = vector_core::my_public_key().and_then(|pk| nostr_sdk::prelude::ToBech32::to_bech32(&pk).ok()) { + super::notify::account_gone(&npub); + } + super::attachments::cancel_all(); + super::messaging::cancel_all_uploads(); + crate::miniapp::end_for_account_swap().await; + // A prompt parked on its answer wakes rather than unlocking an account no longer here. + #[cfg(target_os = "android")] + crate::android::biometric::on_session_reset(); + vector_core::VectorCore.swap_session().await; + super::market::reset().await; + if let Some(bunker) = vector_core::drain_bunker_state() { + let _ = bunker.shutdown().await; + } + state::clear_pending_bunker_setup(); + vector_core::transport::prelogin::cancel_start(); + super::transport::stop_and_join_if_running().await; + super::transport::set_account_booted(false); + db::clear_current_account_in_memory(); + abandon_pending(); + state::set_encryption_enabled(false); + state::open_processing_gate(); +} + +/// Switch to another account on this device: the next boot opens it. +pub async fn switch(npub: String) -> Result<(), String> { + super::security::refuse_if_migrating()?; + if !accounts().iter().any(|a| a.npub == npub) { + return Err(format!("Unknown account: {npub}")); // i18n-exempt: developer error + } + set_active(&npub)?; + reset().await; + Ok(()) +} + +/// Remove an account and everything it keeps on this device. True when it was the live one; +/// the marker then points at the most recent account left, if any. +pub async fn delete(npub: String) -> Result { + super::security::refuse_if_migrating()?; + if !accounts().iter().any(|a| a.npub == npub) { + return Err(format!("Unknown account: {npub}")); // i18n-exempt: developer error + } + super::notify::account_gone(&npub); + let was_active = db::get_current_account().is_ok_and(|a| a == npub); + if was_active { + let _ = db::clear_active_account_file(); + reset().await; + } else if db::read_active_account_file()?.is_some_and(|m| m == npub) { + let _ = db::clear_active_account_file(); + } + let dir = db::account_dir(&npub)?; + match std::fs::remove_dir_all(&dir) { + Err(e) if e.kind() != std::io::ErrorKind::NotFound => { + return Err(crate::t::login_remove_failed(e.to_string()).to_string()); + } + _ => {} + } + // Counted on disk, not validated: a locked database must not read as no account at all. + if db::list_account_npubs() + .map(|v| v.is_empty()) + .unwrap_or(false) + { + let _ = std::fs::remove_dir_all(db::get_download_dir()); + } + if was_active { + for next in accounts() { + if set_active(&next.npub).is_ok() { + break; + } + } + } + Ok(was_active) +} + +/// Add Profile's commit: the live account goes, and the new one starts on the welcome screen's +/// network, not the previous account's. Resolves once that network can carry a sign-in. +pub async fn enter_add_mode(kind: Option, mut opts: Option) -> Result<(), String> { + use vector_core::transport::{self, prefs, prelogin, Kind}; + super::security::refuse_if_migrating()?; + let remembered = prelogin::marker().ok().flatten().map(|c| c.kind).unwrap_or(Kind::Clearnet); + let kind = kind.unwrap_or_else(|| remembered.as_str().into()); + // Read while the current account is still live: its router's credentials carry over. + let choice = super::transport::add_account_choice(&kind, opts.as_ref()); + if let Some(o) = opts.as_mut() { + prefs::scrub_json(o); + } + let choice = choice?; + let _ = db::clear_active_account_file(); + reset().await; + if let Err(e) = super::transport::apply_prelogin(choice).await { + vector_core::log_warn!("[Transport] pre-login start for the new account failed: {e}"); + } + let Some(k) = Kind::parse(&kind).filter(|k| *k != Kind::Clearnet) else { return Ok(()) }; + // I2P connects after its start returns. + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(180); + loop { + let v = super::transport::transport_get_state(); + if v.kind == k.as_str() && v.ready { + return Ok(()); + } + if v.kind != k.as_str() || !matches!(v.phase, transport::status::Phase::Starting) || std::time::Instant::now() > deadline { + return Err(crate::t::login_net_not_yet(k.label()).to_string()); + } + tokio::time::sleep(std::time::Duration::from_millis(500)).await; + } +} diff --git a/crates/vector-gpui/src/backend/actions.rs b/crates/vector-gpui/src/backend/actions.rs new file mode 100644 index 000000000..577cc651b --- /dev/null +++ b/crates/vector-gpui/src/backend/actions.rs @@ -0,0 +1,314 @@ +//! Message actions beyond sending: reactions, edits, deletes and retries (DMs; a Community +//! channel's go through its own service). + +use std::sync::Arc; + +use nostr_sdk::prelude::{EventId, PublicKey}; +use serde_json::json; +use vector_core::sending::{SendCallback, SendConfig}; +use vector_core::{STATE, VectorCore, db}; + +use super::messaging::Callback; + +fn is_dm(chat_id: &str) -> bool { + chat_id.starts_with("npub1") +} + +fn emit_removed(id: &str, chat_id: &str) { + vector_core::emit_event( + "message_removed", + &json!({ "id": id, "chat_id": chat_id, "reason": "deleted" }), + ); +} + +pub async fn react( + chat_id: String, + reference: String, + emoji: String, + url: Option, +) -> Result<(), String> { + if !is_dm(&chat_id) { + return super::community::control( + &chat_id, + &reference, + super::community::Control::React(&emoji, url.as_deref()), + ) + .await; + } + VectorCore + .send_reaction(&chat_id, &reference, &emoji, url.as_deref()) + .await + .map(|_| ()) + .map_err(|e| e.to_string()) +} + +pub async fn edit(chat_id: String, message_id: String, content: String) -> Result<(), String> { + if !is_dm(&chat_id) { + return super::community::control( + &chat_id, + &message_id, + super::community::Control::Edit(&content), + ) + .await; + } + VectorCore + .edit_dm(&chat_id, &message_id, &content) + .await + .map(|_| ()) + .map_err(|e| e.to_string()) +} + +async fn reconcile_unread(chat_id: &str) { + let count = db::events::unread_count_for_chat(chat_id) + .await + .unwrap_or(0); + { + let mut state = STATE.lock().await; + if state.unread_seeded { + state.unread_set(chat_id, count); + } + } + vector_core::emit_event("unread_counts_stale", &json!({ "chats": [chat_id] })); +} + +/// Deletes a DM from the relays (ours by our key, theirs by asking their clients). +pub async fn delete(message_id: String) -> Result<(), String> { + let (chat_id, msg) = VectorCore + .get_message(&message_id) + .await + .ok_or_else(|| format!("Message not found (id: {message_id})"))?; // i18n-exempt: developer error + if !is_dm(&chat_id) { + return super::community::control(&chat_id, &message_id, super::community::Control::Delete) + .await; + } + let rumor_id = + EventId::from_hex(&message_id).map_err(|e| format!("Invalid message id: {e}"))?; // i18n-exempt: developer error + if msg.mine { + vector_core::delete_own_dm(&rumor_id).await?; + } else { + vector_core::delete_received_dm(&rumor_id).await?; + } + STATE.lock().await.remove_message(&message_id); + // Before the row delete: an unflushed self-echo consults this and drops itself. + vector_core::state::note_message_deleted(&message_id); + let _ = db::events::delete_event(&message_id).await; + emit_removed(&message_id, &chat_id); + reconcile_unread(&chat_id).await; + Ok(()) +} + +/// A failed send never reached the wire: local cleanup, and its uploads taken back. +pub async fn delete_failed(message_id: String) -> Result<(), String> { + remove_failed(&message_id, true).await +} + +/// Drop a failed message and the blobs it uploaded; `drop_files` also lets go of what it kept +/// to go again, which a retry still needs. +pub async fn remove_failed(message_id: &str, drop_files: bool) -> Result<(), String> { + let message_id = message_id.to_string(); + let removed = { + let mut state = STATE.lock().await; + match state.find_message(&message_id) { + Some((_, m)) if m.failed => state.remove_message(&message_id), + Some(_) => return Err("Message is not failed or does not exist".into()), // i18n-exempt: developer error + None => None, + } + }; + let (chat_id, msg) = match removed { + Some(found) => found, + None => match VectorCore.get_message(&message_id).await { + Some((c, m)) if m.failed => (c, m), + _ => return Err("Message is not failed or does not exist".into()), // i18n-exempt: developer error + }, + }; + if drop_files { + for att in &msg.attachments { + vector_core::sending::discard_retry_copy(att); + } + if let Ok(download_dir) = std::fs::canonicalize(db::get_download_dir()) { + for att in &msg.attachments { + if att.path.is_empty() { + continue; + } + if let Ok(path) = std::fs::canonicalize(&att.path) + && path.starts_with(&download_dir) + && db::attachments::hash_referenced_elsewhere(&att.id, &message_id) == Ok(false) + { + let _ = tokio::fs::remove_file(&path).await; + } + } + } + } + let _ = db::events::delete_event(&message_id).await; + emit_removed(&message_id, &chat_id); + // A message that went unconfirmed may have landed anyway: it is taken back first, and its + // uploads go only once nothing signed can still be read with them. + db::spawn_bound(async move { + vector_core::sending::abandon_failed_send(&chat_id, &message_id, &msg.attachments).await; + }); + Ok(()) +} + +pub async fn retry(receiver: String, message_id: String) -> Result { + if !receiver.starts_with("npub1") { + return super::community_files::retry(message_id).await; + } + let failed = VectorCore + .get_message(&message_id) + .await + .is_some_and(|(_, m)| m.failed); + if !failed { + return Err("Message is not failed or does not exist".into()); // i18n-exempt: developer error + } + let callback: Arc = Arc::new(Callback); + vector_core::sending::resend_failed_dm(&receiver, &message_id, &SendConfig::gui(), callback) + .await +} + +/// Takes back one of our reactions. +pub async fn unreact(reaction_id: String) -> Result<(), String> { + let found = STATE.lock().await.find_reaction(&reaction_id); + let (chat_id, message_id, author, is_community) = + found.ok_or_else(|| format!("Reaction not found (id: {reaction_id})"))?; // i18n-exempt: developer error + if author != db::get_current_account()? { + return Err(crate::t::msg_react_not_yours().into()); + } + let updated = STATE + .lock() + .await + .remove_reaction_from_message(&message_id, &reaction_id); + let _ = db::events::delete_event(&reaction_id).await; + if let Some((_, message)) = updated { + vector_core::emit_event( + "message_update", + &json!({ "old_id": message_id, "message": message, "chat_id": chat_id }), + ); + } + if is_community { + return super::community::control(&chat_id, &reaction_id, super::community::Control::Delete).await; + } + let rid = EventId::from_hex(&reaction_id).map_err(|e| format!("Invalid reaction id: {e}"))?; // i18n-exempt: developer error + let recipient = + PublicKey::parse(&chat_id).map_err(|e| format!("Invalid DM counterpart: {e}"))?; // i18n-exempt: developer error + vector_core::deletion::delete_own_reaction(&rid, recipient) + .await + .map(|_| ()) +} + +/// The account's stock emoji by decayed use, for the picker's recents. +pub fn emoji_usage() -> std::collections::HashMap { + vector_core::emoji_usage::ranked(Some(256)) + .into_iter() + .map(|u| { + if u.kind == "custom" { + (format!(":{}:", u.id), u.score) + } else { + (u.id, u.score) + } + }) + .collect() +} + +pub fn bump_custom_emoji(code: &str, url: &str) { + let _ = vector_core::emoji_usage::bump("custom", code, Some(url)); +} + +pub fn bump_emoji(emoji: &str) { + let _ = vector_core::emoji_usage::bump("unicode", emoji, None); +} + +const KAOMOJI_RECENTS: &str = "kaomoji_recents"; + +pub fn kaomoji_recents() -> Vec { + vector_core::db::settings::get_sql_setting(KAOMOJI_RECENTS.into()) + .ok() + .flatten() + .and_then(|s| serde_json::from_str(&s).ok()) + .unwrap_or_default() +} + +pub fn set_kaomoji_recents(recents: Vec) { + if let Ok(json) = serde_json::to_string(&recents) { + let _ = vector_core::db::settings::set_sql_setting(KAOMOJI_RECENTS.into(), json); + } +} + +/// A sent message's distinct emoji, in one record. +pub fn bump_emoji_batch(emoji: Vec, custom: Vec<(String, String)>) { + use vector_core::emoji_usage::EmojiUse; + let uses: Vec<_> = emoji + .into_iter() + .map(|id| EmojiUse { + kind: "unicode".into(), + id, + url: None, + }) + .chain(custom.into_iter().map(|(id, url)| EmojiUse { + kind: "custom".into(), + id, + url: Some(url), + })) + .collect(); + let _ = vector_core::emoji_usage::bump_batch(&uses); +} + +/// What the message menu's delete row offers (`get_message_delete_options`). +#[derive(Clone, Copy, Default)] +pub struct DeleteOptions { + pub mine: bool, + /// Ours, but the key that would remove it from relays isn't on this device. + pub limited: bool, + pub attachments: bool, + /// Someone else's Community message we hold the authority to hide for everyone. + pub hide: bool, +} + +pub async fn delete_options(message_id: String) -> DeleteOptions { + use vector_core::ChatType; + let resident = { + let state = STATE.lock().await; + state.find_message(&message_id).map(|(chat, msg)| { + (Some(chat.chat_type.clone()), chat.id.clone(), msg.mine, msg.npub.clone(), msg.attachments.iter().any(|a| !a.url.is_empty())) + }) + }; + let ctx = resident.or_else(|| { + db::events::event_delete_context(&message_id) + .ok() + .flatten() + .map(|(chat, mine, author)| (None, chat, mine, author, false)) + }); + let Some((chat_type, chat_id, mine, author, attachments)) = ctx else { + return DeleteOptions::default(); + }; + let community = matches!(chat_type, Some(ChatType::Community)) || chat_type.is_none(); + let hide = !mine + && community + && (|| { + let author = author.as_deref()?; + let me = vector_core::state::my_public_key()?; + let cid = db::community::community_id_for_channel(&chat_id).ok()??; + let roster = db::community::get_community_roles(&cid).ok()?; + let private = db::community::channel_is_private(&chat_id).ok().flatten().unwrap_or(false); + Some(vector_core::community::moderation::can_hide_in_channel( + vector_core::community::moderation::owner_hex(&cid).as_deref(), + &roster, + &me.to_hex(), + author, + &chat_id, + private, + )) + })() + .unwrap_or(false); + let retained = mine + && match chat_type { + Some(ChatType::DirectMessage) => EventId::from_hex(&message_id).is_ok(), + Some(ChatType::Community) => db::community::has_wrap_owner(&message_id).unwrap_or(false), + _ => db::community::has_wrap_owner(&message_id).unwrap_or(false) || EventId::from_hex(&message_id).is_ok(), + }; + DeleteOptions { mine, limited: mine && !retained, attachments, hide } +} + +/// A moderator's permanent hide of someone else's Community message. +pub async fn hide(channel_id: String, message_id: String) -> Result<(), String> { + VectorCore.hide_community_message(&channel_id, &message_id).await.map_err(|e| e.to_string()) +} diff --git a/crates/vector-gpui/src/backend/archive.rs b/crates/vector-gpui/src/backend/archive.rs new file mode 100644 index 000000000..7f27df0f0 --- /dev/null +++ b/crates/vector-gpui/src/backend/archive.rs @@ -0,0 +1,326 @@ +//! A folder, or a selection of files and folders, zipped to send as one attachment. + +use std::collections::HashSet; +use std::io::{BufWriter, Write}; +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; + +/// The entries a preview lists: at most this many, the rest counted. +const LISTED: usize = 200; +const MAX_DEPTH: u32 = 128; + +pub struct Entry { + pub path: String, + pub size: u64, + pub is_dir: bool, +} + +pub struct Zipped { + pub path: PathBuf, + pub name: String, + pub size: u64, + pub file_count: u32, + pub dir_count: u32, + pub entries: Vec, +} + +struct Item { + source: PathBuf, + name: String, + is_dir: bool, + size: u64, +} + +/// Where a send's plaintext working copies go: the account's own folder, not a shared temp dir. +pub fn work_dir() -> PathBuf { + vector_core::db::current_account_dir() + .map(|d| d.join("outgoing").join("work").join("gpui")) + .unwrap_or_else(|_| std::env::temp_dir().join("vector-gpui-work")) +} + +/// A fresh folder under `work_dir` for one send's copy. +pub fn work_slot() -> std::io::Result { + // device-clock: a folder name, never compared with a time. + let nanos = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap_or_default() + .as_nanos(); + let dir = work_dir().join(nanos.to_string()); + std::fs::create_dir_all(&dir)?; + Ok(dir) +} + +/// A working copy goes once it has sent or been dismissed. +pub fn forget(path: &Path) { + super::pasted::forget(path); + crate::picked::release(path); + let root = work_dir(); + if let Some(dir) = path.parent().filter(|d| d.starts_with(&root) && *d != root) { + let _ = std::fs::remove_dir_all(dir); + } +} + +trait WriteSeek: std::io::Write + std::io::Seek {} +impl WriteSeek for T {} + +fn walk( + current: &Path, + prefix: &str, + items: &mut Vec, + total: &mut u64, + depth: u32, +) -> Result<(), String> { + if depth > MAX_DEPTH { + return Err(crate::t::preview_zip_too_deep().into()); + } + let read = std::fs::read_dir(current) + .map_err(|e| crate::t::preview_zip_read_dir_failed(e.to_string(), current.display().to_string()).to_string())?; + for entry in read { + let entry = entry.map_err(|e| crate::t::preview_zip_read_entry_failed(e.to_string()).to_string())?; + let path = entry.path(); + // Symlinks are skipped: no traversal out of the folder, no cycles. + let Ok(meta) = std::fs::symlink_metadata(&path) else { + continue; + }; + if meta.file_type().is_symlink() { + continue; + } + let name = format!("{prefix}{}", entry.file_name().to_string_lossy()); + if meta.is_dir() { + items.push(Item { + source: path.clone(), + name: name.clone(), + is_dir: true, + size: 0, + }); + walk(&path, &format!("{name}/"), items, total, depth + 1)?; + } else if meta.is_file() { + *total += meta.len(); + items.push(Item { + source: path, + name, + is_dir: false, + size: meta.len(), + }); + } + } + Ok(()) +} + +/// `name`, or `name-1`, `name-2`… when the root already holds it, case-blind. +fn unique_root_name(name: &str, is_dir: bool, taken: &mut HashSet) -> String { + if taken.insert(name.to_lowercase()) { + return name.to_string(); + } + let path = Path::new(name); + let (stem, ext) = match (is_dir, path.file_stem(), path.extension()) { + (false, Some(stem), Some(ext)) => ( + stem.to_string_lossy().into_owned(), + Some(ext.to_string_lossy().into_owned()), + ), + _ => (name.to_string(), None), + }; + (1u32..) + .map(|n| match &ext { + Some(ext) => format!("{stem}-{n}.{ext}"), + None => format!("{stem}-{n}"), + }) + .find(|c| taken.insert(c.to_lowercase())) + .expect("an unused suffix exists") +} + +/// The archive's name: a lone folder's own, else "Archive". +pub fn archive_name(paths: &[PathBuf]) -> String { + match paths { + [only] if only.is_dir() => only + .file_name() + .and_then(|n| n.to_str()) + .map(str::to_string) + .unwrap_or_else(|| crate::t::preview_zip_folder().to_string()), + _ => crate::t::preview_zip_name().to_string(), + } +} + +fn collect(paths: &[PathBuf]) -> Result<(String, Vec, u64), String> { + let (mut items, mut total) = (Vec::new(), 0u64); + if let [only] = paths + && only.is_dir() + { + walk(only, "", &mut items, &mut total, 0)?; + if items.is_empty() { + return Err(crate::t::preview_zip_empty().into()); + } + return Ok((archive_name(paths), items, total)); + } + let mut taken = HashSet::new(); + for picked in paths { + let Some(file_name) = picked.file_name() else { + continue; + }; + if let Some(bytes) = super::pasted::get(picked) { + let name = unique_root_name(&file_name.to_string_lossy(), false, &mut taken); + total += bytes.len() as u64; + items.push(Item { source: picked.clone(), name, is_dir: false, size: bytes.len() as u64 }); + continue; + } + // The user chose these roots, so an alias is followed; the walk still skips symlinks inside. + let Ok(source) = std::fs::canonicalize(picked) else { + continue; + }; + let Ok(meta) = std::fs::metadata(&source) else { + continue; + }; + if !meta.is_dir() && !meta.is_file() { + continue; + } + let name = unique_root_name(&file_name.to_string_lossy(), meta.is_dir(), &mut taken); + if meta.is_dir() { + items.push(Item { + source: source.clone(), + name: name.clone(), + is_dir: true, + size: 0, + }); + walk(&source, &format!("{name}/"), &mut items, &mut total, 1)?; + } else { + total += meta.len(); + items.push(Item { + source, + name, + is_dir: false, + size: meta.len(), + }); + } + } + if items.is_empty() { + return Err(crate::t::preview_zip_nothing().into()); + } + Ok((crate::t::preview_zip_name().to_string(), items, total)) +} + +/// Zip `paths`, reporting whole percents into `percent`; a set `cancel` stops it and removes the partial file. +pub fn zip_paths( + paths: &[PathBuf], + cancel: &AtomicBool, + percent: &Arc, +) -> Result { + use zip::CompressionMethod; + use zip::write::SimpleFileOptions; + + let (name, items, total) = collect(paths)?; + // Zipped from picks held in memory, the zip is held there too. + let memory = items.iter().any(|i| super::pasted::get(&i.source).is_some()); + let file_name = format!("{name}.zip"); + let path = work_slot() + .map_err(|e| crate::t::preview_zip_create_failed(e.to_string()).to_string())? + .join(&file_name); + let cancelled = || cancel.load(Ordering::Relaxed); + + let mut kept = Vec::new(); + let mut run = || -> Result<(u32, u32, Vec), String> { + let out: Box = if memory { + Box::new(std::io::Cursor::new(&mut kept)) + } else { + let file = std::fs::File::create(&path) + .map_err(|e| crate::t::preview_zip_create_failed(e.to_string()).to_string())?; + Box::new(BufWriter::new(file)) + }; + let mut zw = zip::ZipWriter::new(out); + // Level 2: zlib-rs's level 1 is deflate_quick (up to ~20% larger); 2 still beats C zlib's 1. + let options = SimpleFileOptions::default() + .compression_method(CompressionMethod::Deflated) + .compression_level(Some(2)); + let (mut entries, mut files, mut dirs, mut written) = (Vec::new(), 0u32, 0u32, 0u64); + const CHUNK: usize = 512 * 1024; + for item in &items { + let rel = item.name.replace('\\', "/"); + if item.is_dir { + dirs += 1; + let dir = format!("{rel}/"); + zw.add_directory(&dir, options) + .map_err(|e| crate::t::preview_zip_add_dir_failed(e.to_string()).to_string())?; + if entries.len() < LISTED { + entries.push(Entry { + path: dir, + size: 0, + is_dir: true, + }); + } + continue; + } + if cancelled() { + return Err("Cancelled".into()); // i18n-exempt: never shown, the preview drops a cancelled zip + } + // Re-checked at zip time: a file swapped for a link since the walk is skipped. + let held = super::pasted::get(&item.source); + if held.is_none() { + match std::fs::symlink_metadata(&item.source) { + Ok(m) if m.file_type().is_symlink() => continue, + Err(_) => continue, + _ => {} + } + } + files += 1; + zw.start_file(&rel, options.large_file(item.size >= u32::MAX as u64)) + .map_err(|e| crate::t::preview_zip_start_file_failed(e.to_string()).to_string())?; + if item.size > 0 { + let data = match held { + Some(bytes) => bytes, + None => std::sync::Arc::new(std::fs::read(&item.source).map_err(|e| { + crate::t::preview_zip_read_file_failed(e.to_string(), item.source.display().to_string()).to_string() + })?), + }; + for chunk in data.chunks(CHUNK) { + if cancelled() { + return Err("Cancelled".into()); // i18n-exempt: never shown, the preview drops a cancelled zip + } + zw.write_all(chunk) + .map_err(|e| crate::t::preview_zip_write_failed(e.to_string()).to_string())?; + written += chunk.len() as u64; + if let Some(p) = (written * 100).checked_div(total) { + percent.store(p.min(100), Ordering::Relaxed); + } + } + } + if entries.len() < LISTED { + entries.push(Entry { + path: rel, + size: item.size, + is_dir: false, + }); + } + } + zw.finish() + .map_err(|e| crate::t::preview_zip_finish_failed(e.to_string()).to_string())?; + Ok((files, dirs, entries)) + }; + let done = run(); + for p in paths { + super::pasted::forget(p); + crate::picked::release(p); + } + match done { + Ok((file_count, dir_count, entries)) => { + let size = if memory { + let size = kept.len() as u64; + super::pasted::hold_at(path.clone(), kept); + size + } else { + std::fs::metadata(&path).map(|m| m.len()).unwrap_or(0) + }; + Ok(Zipped { + path, + name: file_name, + size, + file_count, + dir_count, + entries, + }) + } + Err(e) => { + forget(&path); + Err(e) + } + } +} diff --git a/crates/vector-gpui/src/backend/attachments.rs b/crates/vector-gpui/src/backend/attachments.rs new file mode 100644 index 000000000..b7c7f51de --- /dev/null +++ b/crates/vector-gpui/src/backend/attachments.rs @@ -0,0 +1,369 @@ +//! Attachment downloads: fetched, opened and held in memory; one too large to hold, or any the +//! account keeps, goes to the media store sealed. Events match the Tauri client's. + +use std::collections::HashMap; +use std::sync::{LazyLock, Mutex}; +use std::time::Instant; + +use serde_json::json; +use vector_core::{DownloadError, DownloadStep, STATE, VectorCore, db}; + +/// Running downloads by id, with whether each was asked to stop. +static ACTIVE: LazyLock>> = + LazyLock::new(|| Mutex::new(HashMap::new())); + +/// One download per attachment id; its stop retires with it. +struct Active(String); + +impl Active { + fn claim(id: &str) -> Option { + let id = id.to_ascii_lowercase(); + let mut active = ACTIVE.lock().unwrap_or_else(|e| e.into_inner()); + if active.contains_key(&id) { + return None; + } + active.insert(id.clone(), false); + Some(Active(id)) + } + + fn cancelled(&self) -> bool { + ACTIVE + .lock() + .unwrap() + .get(&self.0) + .copied() + .unwrap_or(false) + } +} + +impl Drop for Active { + fn drop(&mut self) { + ACTIVE.lock().unwrap_or_else(|e| e.into_inner()).remove(&self.0); + } +} + +/// Whether any download runs: one that read the old setting could still keep a file. +pub fn any_running() -> bool { + !ACTIVE.lock().unwrap_or_else(|e| e.into_inner()).is_empty() +} + +/// Stop every running download: the account they belong to is leaving. +pub fn cancel_all() { + ACTIVE + .lock() + .unwrap() + .values_mut() + .for_each(|stop| *stop = true); +} + +/// Stop a download at its next chunk. True when one was running, so its outcome event is owed. +pub fn cancel(attachment_id: &str) -> bool { + match ACTIVE + .lock() + .unwrap() + .get_mut(&attachment_id.to_ascii_lowercase()) + { + Some(stop) => { + *stop = true; + true + } + None => false, + } +} + +fn emit(event: &str, payload: serde_json::Value) { + vector_core::emit_event(event, &payload); +} + +/// A file that came without a size, asked of its server; the row learns it as an edit would. +pub async fn probe_size(msg_id: String, attachment_id: String) { + if VectorCore.probe_attachment_size(&msg_id, &attachment_id).await.is_none() { + return; + } + if let Some((chat_id, message)) = VectorCore.get_message(&msg_id).await { + emit("message_update", json!({ "old_id": message.id, "message": message, "chat_id": chat_id })); + } +} + +/// What a download reports once every server its message names holds no such file. +pub const GONE_EVERYWHERE: &str = "No longer on any media server"; // i18n-exempt: sentinel, matched and shown translated + +/// Whether every source the message itself names answers that it holds no such file. A guessed +/// mirror can rescue a file, never keep it in doubt, so only the named ones are asked. +async fn gone_everywhere(att: &vector_core::Attachment) -> bool { + let Ok(client) = vector_core::net::build_http_client_with_options(None, Some(vector_core::net::transfer_stall()), true) else { + return false; + }; + let mut named = att.all_urls().peekable(); + if named.peek().is_none() { + return false; + } + for url in named { + if vector_core::net::validate_url_not_private(url).is_err() { + return false; + } + let asked = vector_core::net::proxied_request(&client, reqwest::Method::GET, url).await.send(); + let Ok(Ok(res)) = tokio::time::timeout(std::time::Duration::from_secs(15), asked).await else { + return false; + }; + if !not_on_server(res).await { + return false; + } + } + true +} + +/// A 404 or 410, from the server itself or passed on by the privacy proxy from its source. +async fn not_on_server(res: vector_core::net::Resp) -> bool { + let status = res.status().as_u16(); + if matches!(status, 404 | 410) { + return true; + } + status == 502 + && res.content_length().is_some_and(|n| n <= 4096) + && res + .json::() + .await + .is_ok_and(|b| matches!(b.get("source_status").and_then(serde_json::Value::as_u64), Some(404 | 410))) +} + +fn fail(chat: &str, msg_id: &str, attachment_id: &str, reason: &str) -> bool { + vector_core::log_warn!("attachment {attachment_id} of {msg_id}: {reason}"); + emit( + "attachment_download_result", + json!({ "profile_id": chat, "msg_id": msg_id, "id": attachment_id, "success": false, "result": reason, "partial": partial(attachment_id) }), + ); + false +} + +/// The bytes a stopped download left to resume from: (bytes, total). +fn partial(attachment_id: &str) -> Option<(u64, Option)> { + let part = vector_core::resume::part_for(attachment_id).ok()?; + vector_core::resume::read_checkpoint(&part).map(|c| (c.offset, c.total)) +} + +/// Every download of this account stopped part-way, by attachment id. +pub fn paused() -> HashMap)> { + vector_core::resume::paused().into_iter().map(|(id, c)| (id, (c.offset, c.total))).collect() +} + +pub async fn download(chat: String, msg_id: String, attachment_id: String, auto: bool) -> bool { + let Some((chat_id, mut message)) = VectorCore.get_message(&msg_id).await else { + return fail(&chat, &msg_id, &attachment_id, "Message not found"); // i18n-exempt: developer error + }; + let Some(idx) = message + .attachments + .iter() + .position(|a| a.id == attachment_id) + else { + return fail(&chat, &msg_id, &attachment_id, "Attachment not found"); // i18n-exempt: developer error + }; + let attachment = message.attachments[idx].clone(); + if let Some(held) = vector_core::simd::hex::hex_to_bytes_32_checked(&attachment.id) + .filter(vector_core::media::resident) + { + emit( + "attachment_download_result", + json!({ "profile_id": chat, "msg_id": msg_id, "id": attachment_id, "success": true, "resident": true, "result": vector_core::media::MediaRef::held(&held) }), + ); + // Held already (fetched on receipt, or by another message): the row may not know yet. + if !attachment.resident { + let att = &mut message.attachments[idx]; + att.resident = true; + att.verified = true; + att.downloading = false; + emit( + "message_update", + json!({ "old_id": message.id, "message": message, "chat_id": chat_id }), + ); + } + return true; + } + let author = if message.mine { + None + } else { + message.npub.clone().or_else(|| Some(chat_id.clone())) + }; + // Too large to hold: kept, so only once asked for, unless the account keeps files. + if auto + && !vector_core::media::ram::cache().admits(attachment.size) + && !vector_core::media::keep_media() + { + emit( + "attachment_download_result", + json!({ "profile_id": chat, "msg_id": msg_id, "id": attachment_id, "success": false, "cancelled": true, "result": crate::t::file_too_large_to_hold().to_string() }), + ); + return false; + } + let Some(active) = Active::claim(&attachment_id) else { + return fail( + &chat, + &msg_id, + &attachment_id, + &crate::t::file_already_downloading(), + ); + }; + + emit( + "attachment_download_progress", + json!({ "id": attachment_id, "progress": -1, "bytesDownloaded": 0 }), + ); + let stage = |stage: &str| { + emit( + "attachment_download_stage", + json!({ "id": attachment_id, "stage": stage, "progress": null }), + ) + }; + // On each whole percent, with the average rate so far. A source that declares no length is + // measured against the size the message declared. + let started = Instant::now(); + let declared = (attachment.size > 0).then_some(attachment.size); + let mut last_pct: i64 = -1; + let mut last_bytes = 0u64; + let report = |step: DownloadStep| { + match step { + DownloadStep::Received { bytes, total } => { + if bytes == 0 { + last_pct = -1; + last_bytes = 0; + } + let secs = started.elapsed().as_secs_f64(); + let rate = (secs > 0.0 && bytes > 0).then(|| bytes as f64 / secs); + match total.or(declared).filter(|&t| t > 0) { + Some(t) => { + let pct = (bytes.saturating_mul(100) / t).min(100) as i64; + if pct > last_pct { + last_pct = pct; + emit( + "attachment_download_progress", + json!({ "id": attachment_id, "progress": pct, "bytesDownloaded": bytes, "bytesPerSec": rate }), + ); + } + } + None if bytes - last_bytes >= 256 * 1024 => { + last_bytes = bytes; + emit( + "attachment_download_progress", + json!({ "id": attachment_id, "progress": -1, "bytesDownloaded": bytes, "bytesPerSec": rate }), + ); + } + None => {} + } + } + DownloadStep::Opening => stage(if attachment.key.is_empty() { + "verifying" + } else { + "decrypting" + }), + } + !active.cancelled() + }; + // Files that go to disk anyway fetch through a checkpointed partial, so a stop resumes. + let resumable = !vector_core::media::ram::cache().admits(attachment.size) || vector_core::media::keep_media(); + let got = if resumable { + VectorCore.download_attachment_resumable(&attachment, author.as_deref(), report).await + } else { + VectorCore + .download_attachment_reporting(&attachment, author.as_deref(), 1024 * 1024 * 1024, report) + .await + }; + let bytes = match got { + Ok(b) => b, + Err(DownloadError::Cancelled) => { + emit( + "attachment_download_result", + json!({ "profile_id": chat, "msg_id": msg_id, "id": attachment_id, "success": false, "cancelled": true, "result": DownloadError::Cancelled.to_string(), "partial": partial(&attachment_id) }), + ); + return false; + } + Err(e @ (DownloadError::Unusable(_) | DownloadError::Unreachable(_))) if gone_everywhere(&attachment).await => { + vector_core::log_warn!("attachment {attachment_id} of {msg_id}: {e}, and every named server says it is gone"); + emit( + "attachment_download_result", + json!({ "profile_id": chat, "msg_id": msg_id, "id": attachment_id, "success": false, "gone": true, "result": GONE_EVERYWHERE, "partial": partial(&attachment_id) }), + ); + return false; + } + Err(e) => return fail(&chat, &msg_id, &attachment_id, &e.to_string()), + }; + stage("saving"); + let hash = vector_core::crypto::sha256_hex(&bytes); + let hash32 = vector_core::simd::hex::hex_to_bytes_32(&hash); + let mime = vector_core::crypto::mime_from_extension(&attachment.extension.to_ascii_lowercase()); + let ram = vector_core::media::ram::cache(); + let in_memory = ram.admits(bytes.len() as u64); + let keep = !in_memory || vector_core::media::keep_media(); + let bytes = if keep { + let kept = vector_core::db::blocking_bound(move || { + let r = vector_core::media::store::keep_sealed( + &bytes, + hash32, + mime, + vector_core::db::media_store::Origin::Sealed, + ); + (bytes, r) + }) + .await; + match kept { + Ok((bytes, Ok(()))) => bytes, + Ok((_, Err(e))) => return fail(&chat, &msg_id, &attachment_id, &e), + Err(e) => return fail(&chat, &msg_id, &attachment_id, &e), + } + } else { + bytes + }; + if in_memory && ram.insert(hash32, bytes, mime).is_err() && !keep { + return fail( + &chat, + &msg_id, + &attachment_id, + &crate::t::file_memory_full(), + ); + } + + { + let att = &mut message.attachments[idx]; + att.id = hash.clone(); + att.downloaded = keep; + att.verified = true; + att.resident = true; + att.downloading = false; + att.path = String::new(); + } + STATE + .lock() + .await + .update_attachment(&chat_id, &msg_id, &attachment_id, |att| { + att.set_id(hash32); + att.set_downloading(false); + att.set_verified(true); + if keep { + att.set_downloaded(true); + att.set_path(String::new()); + } + }); + + emit( + "attachment_download_result", + json!({ "profile_id": chat, "msg_id": msg_id, "old_id": attachment_id, "id": hash, "success": true, "resident": true, "result": vector_core::media::MediaRef::held(&hash32) }), + ); + emit( + "message_update", + json!({ "old_id": message.id, "message": message, "chat_id": chat_id }), + ); + let _ = db::events::save_message(&chat_id, &message).await; + true +} + +/// The bytes behind a downloaded attachment: its held copy, else its file. +pub async fn bytes(hash: Option<[u8; 32]>, path: String) -> Option> { + if let Some(h) = hash + && let Some((b, _)) = vector_core::media::held_bytes(&h).await + { + return Some(b); + } + if path.is_empty() { + return None; + } + tokio::fs::read(path).await.ok() +} diff --git a/crates/vector-gpui/src/backend/badges.rs b/crates/vector-gpui/src/backend/badges.rs new file mode 100644 index 000000000..d479b8360 --- /dev/null +++ b/crates/vector-gpui/src/backend/badges.rs @@ -0,0 +1,127 @@ +//! Profile badges: our own from the flags the post-sync refresh keeps, anyone else's looked up +//! once per session. + +use std::collections::HashMap; +use std::sync::{Arc, Mutex}; + +use futures::StreamExt; +use nostr_sdk::prelude::*; +use vector_core::badges; +use vector_core::tags::TagsExt; + +#[derive(Clone, Copy, Default, PartialEq)] +pub struct Badges { + /// Users who accepted this one's Beta invite. + pub invites: u32, + pub fawkes: bool, + /// Bug Hunter tier, 0 for none. + pub bug: u8, + pub v2026: bool, +} + +struct Seen; +fn seen() -> Arc>> { + vector_core::db::current_session().scoped::() +} + +/// Our own live looks run once per session, while the flags read false. +struct OwnChecked; +fn own_checked() -> Arc> { + vector_core::db::current_session().scoped::() +} + +/// Every badge `npub` holds. Each lookup that fails reads as not held. +pub async fn of(npub: String, mine: bool) -> Badges { + if !mine && let Some(b) = seen().lock().unwrap_or_else(|e| e.into_inner()).get(&npub).copied() { + return b; + } + let Ok(pk) = PublicKey::from_bech32(&npub) else { + return Badges::default(); + }; + let invites = invited(pk).await.unwrap_or(0); + let mut b = Badges { + invites, + ..Default::default() + }; + if mine { + b.fawkes = badges::has_vector_badge(); + b.v2026 = badges::has_vector_2026_badge(); + b.bug = badges::bug_hunter_tier(); + let first = !std::mem::replace(&mut *own_checked().lock().unwrap_or_else(|e| e.into_inner()), true); + if first { + if !b.fawkes { + b.fawkes = badges::has_fawkes_badge(&pk).await.unwrap_or(false); + badges::note_own_badge_confirmed(&pk, b.fawkes); + } + if !b.v2026 { + b.v2026 = badges::check_v2026(&pk).await.unwrap_or(false); + } + if b.bug == 0 { + b.bug = badges::fetch_bug_hunter_tier(&pk) + .await + .map(|(t, _)| t) + .unwrap_or(0); + } + } + return b; + } + b.fawkes = badges::has_fawkes_badge(&pk).await.unwrap_or(false); + b.v2026 = badges::check_v2026(&pk).await.unwrap_or(false); + b.bug = badges::fetch_bug_hunter_tier(&pk) + .await + .map(|(t, _)| t) + .unwrap_or(0); + seen().lock().unwrap_or_else(|e| e.into_inner()).insert(npub, b); + b +} + +/// How many distinct users accepted `inviter`'s invite code, read from the trusted relays. +async fn invited(inviter: PublicKey) -> Result { + let client = vector_core::state::nostr_client().ok_or("Nostr client not initialized")?; // i18n-exempt: developer error + let relays = vector_core::state::active_trusted_relays().await; + let timeout = vector_core::relay_request_timeout(std::time::Duration::from_secs(10)); + let filter = Filter::new() + .author(inviter) + .kind(Kind::ApplicationSpecificData) + .custom_tag(SingleLetterTag::LOWERCASE_D, "vector") + .limit(100); + let mut events = client + .stream_events(ReqTarget::manual( + relays.iter().map(|u| (*u, vec![filter.clone()])), + )) + .timeout(timeout) + .await + .map_err(|e| e.to_string())?; + let mut code = None; + while let Some((_, res)) = events.next().await { + let Ok(event) = res else { continue }; + if event.content == "vector_invite" + && let Some(c) = event.tags.find_kind("r").and_then(|t| t.content()) + { + code = Some(c.to_string()); + break; + } + } + let code = code.ok_or_else(|| crate::t::badge_no_invite_code().to_string())?; + let filter = Filter::new() + .kind(Kind::ApplicationSpecificData) + .custom_tag(SingleLetterTag::LOWERCASE_D, code) + .limit(1000); + let mut events = client + .stream_events(ReqTarget::manual( + relays.iter().map(|u| (*u, vec![filter.clone()])), + )) + .timeout(timeout) + .await + .map_err(|e| e.to_string())?; + let mut acceptors = std::collections::HashSet::new(); + while let Some((_, res)) = events.next().await { + let Ok(event) = res else { continue }; + if event.content == "vector_invite_accepted" + && event.tags.public_keys().any(|pk| pk == inviter) + { + acceptors.insert(event.pubkey); + } + } + Ok(acceptors.len() as u32) +} diff --git a/crates/vector-gpui/src/backend/biometric.rs b/crates/vector-gpui/src/backend/biometric.rs new file mode 100644 index 000000000..0720cf964 --- /dev/null +++ b/crates/vector-gpui/src/backend/biometric.rs @@ -0,0 +1,182 @@ +//! Unlock with the phone's fingerprint or screen lock: the vault key the Tauri client wrapped in +//! the Android Keystore, opened behind the system's own prompt. An account whose only credential +//! is that wrap has a generated PIN nobody knows, so this is its one way in. + +use vector_core::db; +#[cfg(target_os = "android")] +use vector_core::state; +#[cfg(target_os = "android")] +use zeroize::Zeroizing; + +/// Base64 of the wrapped vault key, present while the account is enrolled. +const WRAPPED_KEY_SETTING: &str = "biometric_wrapped_key"; + +/// The prompt was dismissed: the screen stays as it was. +pub const CANCELLED: &str = "BIOMETRIC_CANCELLED"; +/// The wrap no longer opens this account: a new fingerprint or screen lock, or a restored store. +pub const INVALIDATED: &str = "BIOMETRIC_INVALIDATED"; +/// Another sign-in owns this boot. +pub const UNAVAILABLE: &str = "BIOMETRIC_UNAVAILABLE"; + +pub struct Status { + /// The phone can show the prompt (Android 11+, a screen lock set). + pub supported: bool, + /// This account holds a wrapped key. + pub enrolled: bool, + /// The system's own words for the prompt ("Use fingerprint"); empty when it has none. + pub label: String, +} + +pub async fn status() -> Status { + let enrolled = db::get_sql_setting(WRAPPED_KEY_SETTING.into()).ok().flatten().is_some(); + #[cfg(target_os = "android")] + { + use crate::android::biometric as bio; + let (avail, label) = tokio::task::spawn_blocking(|| { + (bio::availability().unwrap_or_default(), bio::unlock_label().unwrap_or_default()) + }) + .await + .unwrap_or_default(); + Status { supported: avail == "available", enrolled, label } + } + #[cfg(not(target_os = "android"))] + Status { supported: false, enrolled, label: String::new() } +} + +/// Whether the phone can show the prompt, asked on the spot. +pub fn supported() -> bool { + #[cfg(target_os = "android")] + { + crate::android::biometric::availability().is_ok_and(|a| a == "available") + } + #[cfg(not(target_os = "android"))] + { + false + } +} + +/// The account unlocks only with the wrap. +pub fn is_only_credential() -> bool { + vector_core::state::is_encryption_enabled_fast() + && db::get_sql_setting("security_type".into()).ok().flatten().as_deref() == Some("biometric") +} + +#[cfg(target_os = "android")] +fn alias(npub: &str) -> String { + format!("vector_bio_{npub}") +} + +/// The keystore key behind `npub`'s wrap goes, once nothing holds a wrap it made. +#[cfg(target_os = "android")] +pub fn forget_keystore(npub: &str) { + crate::android::biometric::remove_key(&alias(npub)); +} + +/// Drops a dead wrap, unless it is the account's only credential: a keystore's passing hiccup +/// must never turn into a lost store, so that reset stays the user's call. +#[cfg(target_os = "android")] +fn forget_dead_wrap() { + if is_only_credential() { + return; + } + let _ = db::remove_setting(WRAPPED_KEY_SETTING); + if let Ok(npub) = db::get_current_account() { + forget_keystore(&npub); + } +} + +/// The current account's vault key, behind the prompt; not yet proven against the store. +#[cfg(target_os = "android")] +async fn unwrap_current() -> Result, String> { + use crate::android::biometric::{self as bio, BiometricError}; + // The wrap and its keystore alias from one account, whatever swaps meanwhile. + let alias = alias(&db::get_current_account()?); + let wrapped = db::get_sql_setting(WRAPPED_KEY_SETTING.into()) + .ok() + .flatten() + .ok_or_else(|| INVALIDATED.to_string())?; + // At launch the unlock screen can be up a moment before the activity resumes. + for _ in 0..30 { + if crate::android::background_sync::is_activity_in_foreground() { + break; + } + tokio::time::sleep(std::time::Duration::from_millis(100)).await; + } + // Parks on the prompt's answer. + let unwrapped = tokio::task::spawn_blocking(move || bio::unlock_unwrap(&alias, &wrapped)) + .await + .map_err(|e| e.to_string())?; + unwrapped.map(Zeroizing::new).map_err(|e| match e { + BiometricError::Cancelled => CANCELLED.into(), + BiometricError::Invalidated => INVALIDATED.into(), + BiometricError::Other(e) => e, + }) +} + +/// Opens the vault key behind the prompt, then unlocks as a typed PIN would. `passed` runs once +/// the prompt has, before the slower sign-in. +#[cfg(target_os = "android")] +pub async fn unlock(passed: impl FnOnce() + Send + 'static) -> Result { + if state::nostr_client().is_some() { + return Err(UNAVAILABLE.into()); + } + let session = db::current_session(); + let key = match unwrap_current().await { + Err(e) if e == INVALIDATED && session.is_live() => { + forget_dead_wrap(); + return Err(e); + } + other => other?, + }; + // A PIN typed while the sheet was up got there first. + if !session.is_live() || state::nostr_client().is_some() { + return Err(UNAVAILABLE.into()); + } + passed(); + let out = super::account::unlock_with_key(key).await; + if matches!(&out, Err(e) if e == INVALIDATED) && session.is_live() { + forget_dead_wrap(); + } + out +} + +/// The vault key behind the prompt, proven against the store: a biometric account's answer to +/// "enter your PIN". +#[cfg(target_os = "android")] +pub async fn prove() -> Result, String> { + let session = db::current_session(); + let key = unwrap_current().await?; + if !session.is_live() { + return Err(crate::t::security_account_changed().into()); + } + db::at_rest::prove_key(&key)?; + Ok(key) +} + +/// A credential nobody will ever know, derived like a typed PIN, its key wrapped behind one +/// prompt for `npub` before anything commits: a cancel leaves the account as it was. +#[cfg(target_os = "android")] +pub async fn generate_and_wrap( + npub: &str, +) -> Result<(String, Zeroizing<[u8; 32]>, vector_core::crypto::Kdf), String> { + use crate::android::biometric::{self as bio, BiometricError}; + use rand::RngCore; + let mut raw = Zeroizing::new([0u8; 32]); + rand::rngs::OsRng.fill_bytes(&mut *raw); + let secret = Zeroizing::new(vector_core::simd::hex::bytes_to_hex_32(&raw)); + drop(raw); + let kdf = vector_core::crypto::Kdf::fresh(); + let key = Zeroizing::new(vector_core::crypto::derive_key(&secret, &kdf).await); + drop(secret); + let alias = alias(npub); + let to_wrap = key.clone(); + let wrapped = tokio::task::spawn_blocking(move || bio::enroll_wrap(&alias, &to_wrap)) + .await + .map_err(|e| e.to_string())? + .map_err(|e| match e { + BiometricError::Cancelled => CANCELLED.into(), + BiometricError::Invalidated => crate::t::security_biometric_rejected().to_string(), + BiometricError::Other(e) => e, + })?; + Ok((wrapped, key, kdf)) +} diff --git a/crates/vector-gpui/src/backend/bunker.rs b/crates/vector-gpui/src/backend/bunker.rs new file mode 100644 index 000000000..6de66fec5 --- /dev/null +++ b/crates/vector-gpui/src/backend/bunker.rs @@ -0,0 +1,273 @@ +//! Remote signers (NIP-46): an account whose key lives in a signer app. Vector holds only a +//! client keypair that the signer approves; the account's identity is the signer's. + +use std::time::Duration; + +use futures::channel::mpsc::UnboundedSender; +use nostr_sdk::prelude::*; +use vector_core::state::{self, PENDING_NSEC}; +use vector_core::{BunkerConnectionState, MY_SECRET_KEY, SignerKind}; +use zeroize::{Zeroize, Zeroizing}; + +use super::account::{self, Imported}; + +/// How a pairing started from a link goes, for the screen that shows the link. +pub enum Update { + /// The signer answered; the user may still have to approve in it. + Awaiting, + Done(Result), +} + +/// Pairing meanwhile stops a switch of network for its sockets: say so rather than the raw error. +fn failed(pairing: &vector_core::signer::PairingGuard, e: String) -> String { + if pairing.aborted() { vector_core::signer::NETWORK_CHANGED.to_string() } else { e } +} + +fn relays() -> Result, String> { + // Multi-relay by design: one relay down must not lock the user out of their signer. + let relays: Vec = state::TRUSTED_RELAYS.iter().filter_map(|s| RelayUrl::parse(s).ok()).collect(); + if relays.is_empty() { Err("No trusted relays configured".into()) } else { Ok(relays) } // i18n-exempt: developer error +} + +/// Drop a pairing that never reached its security step, so the next attempt starts clean. +pub async fn cancel() { + if account::pending().is_none() && state::nostr_client().is_some() { + return; + } + if let Some(b) = vector_core::drain_bunker_state() { + let _ = b.shutdown().await; + } + MY_SECRET_KEY.clear(&[&vector_core::ENCRYPTION_KEY]); + vector_core::clear_my_public_key(); + state::clear_pending_bunker_setup(); + { + let mut g = PENDING_NSEC.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(s) = g.as_mut() { + s.zeroize(); + } + *g = None; + } + account::abandon_pending(); + if let Some(client) = vector_core::take_nostr_client() { + let _ = client.shutdown().await; + } +} + +async fn refuse_if_signed_in() -> Result<(), String> { + if state::nostr_client().is_some() && account::pending().is_some() { + cancel().await; + } + if state::nostr_client().is_some() { + return Err(crate::t::login_already_signed_in().into()); + } + Ok(()) +} + +/// The signer answered with `remote`: an account already here becomes the active one; a new one +/// is staged for its security step with the client key and link held in memory. +async fn stage(remote: PublicKey, client_keys: &Keys, url: String) -> Result { + let npub = remote.to_bech32().map_err(|e| e.to_string())?; + if account::is_committed(&npub) { + // The existing account keeps its own client key; this pairing is discarded. + if let Some(b) = vector_core::drain_bunker_state() { + let _ = b.shutdown().await; + } + vector_core::db::write_active_account_file(&npub)?; + return Ok(Imported::Existing(npub)); + } + if vector_core::bunker_signer().is_none() { + return Err(crate::t::login_signer_gone().into()); + } + let client_nsec = Zeroizing::new(client_keys.secret_key().to_bech32().map_err(|e| e.to_string())?); + *PENDING_NSEC.lock().unwrap_or_else(|e| e.into_inner()) = Some(String::clone(&client_nsec)); + state::set_pending_bunker_setup(url, remote.to_hex()); + let secret = Zeroizing::new(client_keys.secret_key().to_secret_bytes()); + MY_SECRET_KEY.set(*secret, &[&vector_core::ENCRYPTION_KEY]); + state::set_my_public_key(remote); + vector_core::set_signer_kind(SignerKind::Bunker); + account::install_client(); + account::insert_own_profile(&npub).await; + account::set_pending(npub.clone()); + vector_core::set_bunker_state(BunkerConnectionState::Online); + Ok(Imported::Staged(npub)) +} + +/// Sign in with a pasted `bunker://` link: waits while the signer approves. +pub async fn connect(url: String) -> Result { + let url = url.trim().to_string(); + if !url.to_ascii_lowercase().starts_with("bunker://") { + return Err(crate::t::login_signer_bunker().into()); + } + refuse_if_signed_in().await?; + let client_keys = Keys::generate(); + // Long enough for a signer on a phone to be unlocked and tapped. + let remote = vector_core::attempt_bunker_login(&url, client_keys.clone(), Duration::from_secs(60)).await?; + match stage(remote, &client_keys, url).await { + Ok(done) => Ok(done), + Err(e) => { + cancel().await; + Err(crate::t::login_signer_setup_failed(e.to_string()).to_string()) + } + } +} + +/// A `nostrconnect://` link for the signer to scan or paste. The pairing runs on in the +/// background and reports through `updates`. +pub async fn start_session(updates: UnboundedSender) -> Result { + refuse_if_signed_in().await?; + let client_keys = Keys::generate(); + let (nc, uri) = vector_core::build_nostrconnect_session(client_keys.clone(), relays()?, Duration::from_secs(120))?; + vector_core::set_bunker_signer(nc); + vector_core::set_bunker_state(BunkerConnectionState::Connecting); + vector_core::db::spawn_bound(async move { + let done = |r: Result| { + let _ = updates.unbounded_send(Update::Done(r)); + }; + let Some(signer) = vector_core::bunker_signer() else { return }; + let pairing = vector_core::signer::track_pairing(&signer); + let give_up = |e: String| async move { + vector_core::set_bunker_state(BunkerConnectionState::Offline); + if let Some(b) = vector_core::take_bunker_signer() { + let _ = b.shutdown().await; + } + e + }; + let storage_url = match signer.bunker_uri().await { + Ok(uri) => uri.to_string(), + Err(e) => return done(Err(give_up(failed(&pairing, e.to_string())).await)), + }; + let _ = updates.unbounded_send(Update::Awaiting); + let remote = match signer.get_public_key_async().await { + Ok(pk) => pk, + Err(e) => { + let e = failed(&pairing, crate::t::login_signer_no_pubkey_manual(e.to_string()).to_string()); + return done(Err(give_up(e).await)); + } + }; + // Abandoned meanwhile: the screen is gone. + if vector_core::bunker_signer().is_none() { + let _ = signer.shutdown().await; + return; + } + if pairing.install(signer).is_err() { + return done(Err(give_up(vector_core::signer::NETWORK_CHANGED.to_string()).await)); + } + match stage(remote, &client_keys, storage_url).await { + Ok(r) => done(Ok(r)), + Err(e) => { + cancel().await; + done(Err(e)); + } + } + }); + Ok(uri) +} + +/// Re-pair the signer of this bunker account, keeping its client key: a `nostrconnect://` link +/// for the signer, reporting through `updates`. The live signer keeps working until the new +/// pairing has proved it is the same identity. Before a session exists (an unlock the signer +/// refused) nothing is installed: the unlock runs again on the stored link. +pub async fn reauthorize(updates: UnboundedSender) -> Result { + if vector_core::db::get_signer_type().ok().as_deref() != Some("bunker") { + return Err(crate::t::login_signer_not_remote().into()); + } + let expected = vector_core::db::get_bunker_remote_pubkey() + .ok() + .flatten() + .ok_or("Bunker account missing cached remote pubkey")? // i18n-exempt: matched by the re-pair offer + .to_ascii_lowercase(); + // owned-key: the NIP-46 client keypair, which the NostrConnect session owns for its life. + let client_keys = MY_SECRET_KEY.to_keys().ok_or_else(|| crate::t::login_signer_no_client_key().to_string())?; + let (nc, uri) = vector_core::build_nostrconnect_session(client_keys, relays()?, Duration::from_secs(120))?; + let pairing = vector_core::signer::track_pairing(&nc); + let session = vector_core::db::current_session(); + vector_core::db::spawn_bound(async move { + let done = |r: Result| { + let _ = updates.unbounded_send(Update::Done(r)); + }; + let storage_url = match nc.bunker_uri().await { + Ok(uri) => uri.to_string(), + Err(e) => { + let _ = nc.shutdown().await; + return done(Err(failed(&pairing, e.to_string()))); + } + }; + let _ = updates.unbounded_send(Update::Awaiting); + let remote = match nc.get_public_key_async().await { + Ok(pk) => pk, + Err(e) => { + let _ = nc.shutdown().await; + return done(Err(failed(&pairing, crate::t::login_signer_no_pubkey(e.to_string()).to_string()))); + } + }; + if remote.to_hex() != expected { + let _ = nc.shutdown().await; + return done(Err(crate::t::login_signer_other_identity().into())); + } + if !session.is_live() { + let _ = nc.shutdown().await; + return; + } + if let Err(e) = vector_core::db::set_bunker_url(&storage_url).await { + let _ = nc.shutdown().await; + return done(Err(crate::t::login_signer_save_failed(e.to_string()).to_string())); + } + let npub = match remote.to_bech32() { + Ok(n) => n, + Err(e) => { + let _ = nc.shutdown().await; + return done(Err(e.to_string())); + } + }; + let at_unlock = state::nostr_client().is_none(); + let old = match pairing.install(nc) { + Ok(old) => old, + Err(_) => return done(Err(vector_core::signer::NETWORK_CHANGED.to_string())), + }; + if let Some(old) = old { + let _ = old.shutdown().await; + } + if at_unlock { + if let Some(b) = vector_core::take_bunker_signer() { + let _ = b.shutdown().await; + } + vector_core::set_bunker_state(BunkerConnectionState::Idle); + } else { + state::set_my_public_key(remote); + vector_core::set_signer_kind(SignerKind::Bunker); + vector_core::set_bunker_state(BunkerConnectionState::Online); + } + done(Ok(Imported::Existing(npub))); + }); + Ok(uri) +} + +/// The signer of a stored bunker account, reconnected at unlock: the identity it returns must be +/// the one on record. Returns that identity. +pub async fn reconnect(client_keys: &Keys) -> Result { + let url = vector_core::db::get_bunker_url().await?.ok_or("Bunker account missing bunker_url")?; // i18n-exempt: matched by the re-pair offer + super::transport::wait_for_active_network().await; + // An already-approved pairing: no human in the loop, so a short wait. + let remote = vector_core::attempt_bunker_login(&url, client_keys.clone(), vector_core::relay_connect_timeout(Duration::from_secs(15))) + .await + .map_err(|e| format!("Remote signer unreachable — please ensure your signer app is online and retry. ({e})"))?; // i18n-exempt: matched by the re-pair offer + let expected = vector_core::db::get_bunker_remote_pubkey()?.ok_or("Bunker account missing cached remote pubkey")?; // i18n-exempt: matched by the re-pair offer + if !remote.to_hex().eq_ignore_ascii_case(&expected) { + if let Some(b) = vector_core::take_bunker_signer() { + let _ = b.shutdown().await; + } + vector_core::set_bunker_state(BunkerConnectionState::Idle); + return Err(crate::t::login_signer_wrong_identity().into()); + } + vector_core::set_signer_kind(SignerKind::Bunker); + Ok(remote) +} + +/// The signer a bunker account is paired with, for Security settings. +pub fn status() -> Option { + if vector_core::db::get_signer_type().ok()?.as_str() != "bunker" { + return None; + } + let hex = vector_core::db::get_bunker_remote_pubkey().ok().flatten()?; + PublicKey::from_hex(&hex).ok()?.to_bech32().ok() +} diff --git a/crates/vector-gpui/src/backend/calls.rs b/crates/vector-gpui/src/backend/calls.rs new file mode 100644 index 000000000..3a38baebe --- /dev/null +++ b/crates/vector-gpui/src/backend/calls.rs @@ -0,0 +1,84 @@ +//! The call commands, as the desktop shell's: each a thin door into core's session. + +use crate::calls::session; + +/// Ring `npub`; the rest arrives as `call_state` events. A refused microphone still places it, muted. +pub async fn start(npub: String) -> Result<(), String> { + crate::mic_access::ask().await; + vector_core::db::scoped(session::start(npub, false)) + .await + .map(|_| ()) +} + +pub async fn accept() -> Result<(), String> { + crate::mic_access::ask().await; + vector_core::db::scoped(session::accept()).await +} + +pub async fn reject() -> Result<(), String> { + vector_core::db::scoped(session::reject()).await +} + +pub async fn hangup() -> Result<(), String> { + vector_core::db::scoped(session::hangup()).await +} + +pub async fn set_muted(on: bool) -> Result<(), String> { + vector_core::db::scoped(session::set_muted(on)).await +} + +pub async fn set_volume(volume: f32) -> Result<(), String> { + vector_core::db::scoped(session::set_volume(volume)).await +} + +pub async fn set_share_volume(volume: f32) -> Result<(), String> { + vector_core::db::scoped(session::set_share_volume(volume)).await +} + +/// The call the session holds, for a UI that missed its events. +pub fn status() -> Option { + session::snapshot().and_then(|s| serde_json::to_value(s).ok()) +} + +/// Off Clearnet, calls connect only once the account agrees: the network's name, or `Some(None)` +/// while the choice hasn't loaded. +pub fn off_clearnet_label() -> Option> { + use vector_core::transport::Kind; + match vector_core::transport::preference() { + Some(Kind::Clearnet) => None, + Some(k) => Some(Some(k.label().to_string())), + None => Some(None), + } +} + +pub fn allow_realtime() { + vector_core::transport::realtime::grant(); +} + +/// The engine's own microphone test: the call's capture chain, metered by `mic_level` events. +pub async fn mic_test_start() -> Result<(), String> { + if session::snapshot().is_some() { + return Err(crate::t::call_in_progress().into()); + } + crate::mic_access::require().await?; + vector_core::db::scoped(session::mic_test_start()).await +} + +pub fn mic_test_stop() { + session::mic_test_stop(); +} + +/// One of our pictures starts or stops; the codec is the first of ours the peer decodes. +pub async fn set_video(kind: vector_core::calls::wire::VideoKind, on: bool) -> Result<(), String> { + vector_core::db::scoped(session::set_video(kind, on)).await +} + +/// The panel's quality and frame rate for a picture; None leaves it to the ladder. +pub fn set_video_prefs(kind: vector_core::calls::wire::VideoKind, rung: Option, fps: Option) -> Result<(), String> { + session::set_video_prefs(kind, rung.map(|r| r as usize), fps) +} + +/// The shared screen's sound, captured by this platform itself. +pub async fn set_share_audio(on: bool) -> Result<(), String> { + vector_core::db::scoped(session::set_share_audio(on, true)).await +} diff --git a/crates/vector-gpui/src/backend/chatlist.rs b/crates/vector-gpui/src/backend/chatlist.rs new file mode 100644 index 000000000..60067c09a --- /dev/null +++ b/crates/vector-gpui/src/backend/chatlist.rs @@ -0,0 +1,105 @@ +//! The chat list's own state: pinned rows, the archive, and Mark as Unread. + +use std::collections::HashMap; + +use serde_json::json; +use vector_core::synced_prefs::{self, Pref}; +use vector_core::{STATE, db, pinned_chats}; + +/// The pinned rows as this device holds them, for the first paint. +pub fn pinned() -> Vec { + pinned_chats::load_local().chats +} + +/// Pin or unpin a row and sync it; the list as it now stands. Past the cap, the reason. +pub async fn set_pinned(id: String, pin: bool) -> Result, String> { + let client = vector_core::state::nostr_client().ok_or("Nostr client not initialized")?; // i18n-exempt: developer error + let list = if pin { + pinned_chats::pin_chat(&client, &id).await? + } else { + pinned_chats::unpin_chat(&client, &id).await? + }; + super::selfsync::emit_pinned(&list.chats); + Ok(list.chats) +} + +/// Move a pin to just before `before`, or to the end. +pub async fn move_pinned(id: String, before: Option) -> Result, String> { + let client = vector_core::state::nostr_client().ok_or("Nostr client not initialized")?; // i18n-exempt: developer error + let list = pinned_chats::move_pinned_chat(&client, &id, before.as_deref()).await?; + super::selfsync::emit_pinned(&list.chats); + Ok(list.chats) +} + +/// Archived chats: chat id → the newest message time when archived. +pub fn archived() -> HashMap { + synced_prefs::load_archive().times().into_iter().collect() +} + +/// Archive a DM as of `at` (unix ms), or bring it back when `at` is absent. +pub fn set_archived(chat_id: &str, at: Option) -> Result, String> { + let map = synced_prefs::set_archived(chat_id, at)?; + super::selfsync::emit_archive(&map); + super::prefs::publish_projection(Pref::Archive); + Ok(map.times().into_iter().collect()) +} + +/// A message at `active_at` outlived the chat's archive: forget it. +pub fn revoke_archive(chat_id: &str, active_at: u64) -> Result, String> { + let (map, changed) = synced_prefs::revoke_archive(chat_id, active_at)?; + if changed { + super::selfsync::emit_archive(&map); + } + Ok(map.times().into_iter().collect()) +} + +/// Retreat the read marker so the newest contact message surfaces again, from the full history. +/// The new marker (empty when never read), or None when there was nothing to surface. +pub async fn mark_unread(chat_id: String) -> Option { + use db::events::{UnreadMark, compute_unread_anchor}; + let (marker, hex, clear) = match compute_unread_anchor(&chat_id).await { + Ok(UnreadMark::Anchor(id)) => (vector_core::compact::encode_message_id(&id), id, false), + Ok(UnreadMark::Clear) => ([0u8; 32], String::new(), true), + Ok(UnreadMark::NoOp) | Err(_) => return None, + }; + let slim = { + let mut state = STATE.lock().await; + let idx = state.chats.iter().position(|c| c.id == chat_id)?; + state.chats[idx].mark_read_at(marker); + db::chats::SlimChatDB::from_chat(&state.chats[idx], &state.interner) + }; + let _ = db::chats::save_slim_chat(&slim); + // The upsert refuses an empty marker, so a never-read chat takes the clear path. + if clear { + let _ = db::chats::clear_chat_last_read(&chat_id); + } + let count = db::events::unread_count_for_chat(&chat_id).await.unwrap_or(0); + { + let mut state = STATE.lock().await; + if state.unread_seeded { + state.unread_set(&chat_id, count); + } + } + vector_core::emit_event("unread_counts_stale", &json!({ "chats": [chat_id] })); + Some(hex) +} + +/// Unread from `message_id` on, past our own replies, until the chat is read again. +pub async fn mark_unread_from(chat_id: String, message_id: String) -> Result { + let slim = { + let mut state = STATE.lock().await; + let idx = state.chats.iter().position(|c| c.id == chat_id).ok_or("Chat not found")?; // i18n-exempt: developer error + state.chats[idx].unread_from = vector_core::compact::encode_message_id(&message_id); + db::chats::SlimChatDB::from_chat(&state.chats[idx], &state.interner) + }; + db::chats::save_slim_chat(&slim)?; + let count = db::events::unread_count_for_chat(&chat_id).await?; + { + let mut state = STATE.lock().await; + if state.unread_seeded { + state.unread_set(&chat_id, count); + } + } + vector_core::emit_event("unread_counts_stale", &json!({ "chats": [chat_id] })); + Ok(count) +} diff --git a/crates/vector-gpui/src/backend/community.rs b/crates/vector-gpui/src/backend/community.rs new file mode 100644 index 000000000..371ed894a --- /dev/null +++ b/crates/vector-gpui/src/backend/community.rs @@ -0,0 +1,1706 @@ +//! Concord Communities: summaries, rosters, channel history and sends, and the catch-up that +//! pages every held channel behind the live subscription. + +use std::sync::atomic::{AtomicBool, Ordering}; +use std::time::Duration; + +use futures::stream::{self, StreamExt}; +use nostr_sdk::prelude::*; +use serde_json::{Value, json}; +use vector_core::community::transport::LiveTransport; +use vector_core::community::v2::community::CommunityV2; +use vector_core::community::v2::realtime; +use vector_core::community::v2::volley::{self, PaintTarget}; +use vector_core::community::{ChannelId, CommunityId}; +use vector_core::sending::SendCallback; +use vector_core::simd::hex::bytes_to_hex_32; +use vector_core::{Message, STATE, VectorCore, db}; + +use super::messaging::Callback; + +fn id32(hex: &str) -> Result<[u8; 32], String> { + if hex.len() != 64 { + return Err(format!("invalid id: {hex}")); // i18n-exempt: developer error + } + Ok(vector_core::simd::hex::hex_to_bytes_32(hex)) +} + +fn is_held(community_id: &str) -> bool { + id32(community_id) + .is_ok_and(|b| db::community::community_held(&CommunityId(b)).unwrap_or(false)) +} + +fn load(community_id: &str) -> Result { + db::community::load_community_v2(&CommunityId(id32(community_id)?))? + .ok_or_else(|| crate::t::community_not_found().to_string()) +} + +/// `list_communities`' shape, which `data::Community` reads. +pub fn summarize(c: &CommunityV2) -> Value { + let me = vector_core::my_public_key(); + let mine = VectorCore::my_channel_permissions(c); + let owner = c.owner().ok(); + json!({ + "community_id": bytes_to_hex_32(&c.identity.community_id.0), + "name": c.name, + "description": c.description.clone().unwrap_or_default(), + "is_owner": matches!((me, owner), (Some(m), Some(o)) if m == o), + "has_icon": c.icon.is_some(), + "channels": c.layout().1.into_iter().map(|(ch, cat)| json!({ + "channel_id": bytes_to_hex_32(&ch.id.0), + "name": ch.name, + "private": ch.private, + "readable": !ch.private || ch.key.is_some(), + "category_id": cat.map(|k| bytes_to_hex_32(&k.id)), + "topic": ch.topic(), + "view": ch.view().as_str(), + "my_permissions": mine.get(&ch.id.0).map(|p| p.to_string()), + "restricted": ch.restricted(), + "can_post": vector_core::community::v2::service::can_post(c, &ch.id), + "public_until": ch.public_until(), + })).collect::>(), + "categories": VectorCore::categories_json(c), + "primary_channel": c.primary_channel().map(|ch| bytes_to_hex_32(&ch.id.0)), + "owner_npub": owner.and_then(|pk| pk.to_bech32().ok()), + "dissolved": c.dissolved, + "relays": c.relays, + "voice_relays": c.voice_relays(), + "system_channel": c.system_lines_target().map(|ch| bytes_to_hex_32(&ch.id.0)), + "landing_channel": c.landing_channel().map(|ch| bytes_to_hex_32(&ch.id.0)), + }) +} + +pub fn list() -> Vec { + db::community::list_community_ids() + .unwrap_or_default() + .iter() + .filter_map(|id| db::community::load_community_v2(id).ok().flatten()) + .map(|c| summarize(&c)) + .collect() +} + +/// The roster as npubs, and which of them hold the admin role. +pub async fn members(community_id: String) -> (Vec, Vec) { + let (members, admins, _) = roster_only(community_id).await; + (members, admins) +} + +/// The roster panel's read: counted members, admins, and who posts outside the Guestbook +/// (npub → `no_join` | `departed`), shown but never counted. +pub async fn roster( + community_id: String, +) -> (Vec, Vec, std::collections::HashMap, Option) { + let (members, admins, unlisted) = roster_only(community_id.clone()).await; + let graph = is_held(&community_id).then(|| VectorCore.community_role_graph(&community_id).ok()).flatten(); + (members, admins, unlisted, graph) +} + +/// [`roster`] without the role graph. +pub async fn roster_only(community_id: String) -> (Vec, Vec, std::collections::HashMap) { + let mut members = Vec::new(); + let mut unlisted = std::collections::HashMap::new(); + for m in VectorCore.get_community_members(&community_id).await { + let Some(npub) = m.get("npub").and_then(Value::as_str) else { continue }; + match m.get("unlisted").and_then(Value::as_str) { + Some(why) => { + unlisted.insert(npub.to_string(), why.to_string()); + } + None => members.push(npub.to_string()), + } + } + let admins = if is_held(&community_id) { + VectorCore + .community_roles(&community_id) + .ok() + .and_then(|r| r.get("admins").cloned()) + .and_then(|a| serde_json::from_value::>(a).ok()) + .unwrap_or_default() + } else { + Vec::new() + }; + (members, admins, unlisted) +} + +/// A channel's newest page, or the page before `before_ms`; whether its start is reached. +pub async fn sync_channel(channel_id: String, before_ms: Option) -> Result { + use vector_core::community::cache; + let is_older = before_ms.is_some(); + let Some(_claim) = cache::claim_page_fetch(&channel_id, is_older) else { + // Not "more remains" at once: a caller paging on would spin while the holder runs. + tokio::time::sleep(Duration::from_millis(300)).await; + return Ok(false); + }; + let community_id = + db::community::community_id_for_channel(&channel_id)?.ok_or_else(|| crate::t::community_unknown_channel().to_string())?; + if !is_held(&community_id) { + return Ok(true); + } + const LIMIT: usize = 50; + let before = before_ms.map(|m| m / 1000); + let count = + db::scoped(VectorCore.sync_community_channel_page(&channel_id, LIMIT, before, None)) + .await + .map(|(c, _)| c) + .unwrap_or_default(); + Ok(if is_older { + vector_core::community::reached_history_start(&channel_id, before, &count) + } else { + count.new_messages < LIMIT + }) +} + +/// The channel just opened: its newest page alone first, ahead of every background walk, so the +/// reader sees the latest messages before the deeper catch-up behind it; then that catch-up. +pub async fn sync_focused(channel_id: String) -> Result { + set_focus(&channel_id); + let community_id = + db::community::community_id_for_channel(&channel_id)?.ok_or_else(|| crate::t::community_unknown_channel().to_string())?; + if !is_held(&community_id) { + return Ok(true); + } + { + let _first = vector_core::community::cache::foreground(); + let _ = db::scoped(VectorCore.sync_community_channel_head(&channel_id, 50)).await; + } + sync_channel(channel_id, None).await +} + +struct Focus; + +fn focus() -> std::sync::Arc>> { + db::current_session().scoped::>>() +} + +/// The channel on screen, which a sweep reads before the rest. +fn set_focus(channel_id: &str) { + *focus().lock().unwrap_or_else(|e| e.into_inner()) = Some(channel_id.to_string()); +} + +/// Background walks of `channels`, a few at a time, each after any foreground fetch and the +/// channel on screen first. +async fn walk_channels(mut channels: Vec) { + let on_screen = focus().lock().unwrap_or_else(|e| e.into_inner()).clone(); + if let Some(at) = on_screen.and_then(|f| channels.iter().position(|c| *c == f)) { + let ch = channels.remove(at); + channels.insert(0, ch); + } + stream::iter(channels) + .map(|cid| async move { + vector_core::community::cache::after_foreground().await; + if !db::session_stopped() { + let _ = sync_channel(cid, None).await; + } + }) + .buffer_unordered(WINDOW) + .collect::>() + .await; +} + +/// `fill_community_gap`: the hole a scroll up from `before_ms` is about to cross, filled from the +/// relays first, or the database read below it would step straight across. 0 when there is none. +pub async fn fill_gap(channel_id: String, before_ms: u64) -> usize { + let Some(_claim) = vector_core::community::cache::claim_page_fetch(&channel_id, true) else { + return 0; + }; + db::scoped(async move { VectorCore.fill_community_gap(&channel_id, before_ms).await.unwrap_or(0) }).await +} + +/// One relay page of a channel's history older than `before_ms`, for a walk back to a point: +/// whether it reached the start, how many messages were new here, and the oldest it reached (ms). +pub async fn walk_channel(channel_id: String, before_ms: u64) -> Result<(bool, usize, Option), String> { + use vector_core::community::cache; + let Some(_claim) = cache::claim_page_fetch(&channel_id, true) else { + return Ok((false, 0, None)); + }; + let community_id = + db::community::community_id_for_channel(&channel_id)?.ok_or_else(|| crate::t::community_unknown_channel().to_string())?; + if !is_held(&community_id) { + return Ok((true, 0, None)); + } + const LIMIT: usize = 50; + let before = Some(before_ms / 1000); + let count = db::scoped(VectorCore.sync_community_channel_page(&channel_id, LIMIT, before, None)) + .await + .map(|(c, _)| c) + .unwrap_or_default(); + let start = vector_core::community::reached_history_start(&channel_id, before, &count); + Ok((start, count.new_messages, count.next_before.map(|s| s * 1000))) +} + +/// The optimistic bubble carries the real id: the rumor is built before it shows. +pub async fn send(channel_id: String, content: String, replied_to: String, bot: Option) -> Result<(), String> { + db::scoped(async move { + let reply = (!replied_to.is_empty()).then_some(replied_to); + let community_id = db::community::community_id_for_channel(&channel_id)? + .ok_or_else(|| crate::t::community_unknown_channel().to_string())?; + let (content, role_mentions) = + vector_core::community::mentions::resolve_in(&community_id, &content); + let (content, text_spans) = vector_core::text_spans::extract_own(&content); + let mut extra_tags: Vec = vector_core::text_spans::to_nostr_tags(&text_spans) + .into_iter() + .collect(); + extra_tags.extend(vector_core::community::mentions::to_tags(&role_mentions)); + // Names the chosen bot, so only it runs a command two bots share. + let bot = bot.as_deref().and_then(|b| PublicKey::parse(b).ok()); + extra_tags.extend(bot.map(|pk| vector_core::bot_interface::bot_tag(&pk))); + let addressed_bots: Vec = bot.and_then(|pk| pk.to_bech32().ok()).into_iter().collect(); + + let author = vector_core::my_public_key().ok_or("Public key not set")?; // i18n-exempt: developer error + let community = load(&community_id)?; + let ch = ChannelId(id32(&channel_id)?); + let channel = community + .channel(&ch) + .ok_or_else(|| crate::t::community_channel_not_found().to_string())?; + let (_, epoch) = community.channel_secret(channel); + let ms = vector_core::clock::now_ms(); + + let emoji_tags = vector_core::emoji_packs::resolve_outbound_emoji_tags(&content); + let emoji_pairs: Vec<(&str, &str)> = emoji_tags + .iter() + .map(|t| (t.shortcode.as_str(), t.url.as_str())) + .collect(); + let reply_owned = match reply.as_deref() { + Some(parent) => { + let author_hex = STATE + .lock() + .await + .find_message(parent) + .and_then(|(_, m)| m.npub.as_deref().and_then(|n| PublicKey::parse(n).ok())) + .map(|pk| pk.to_hex()) + .unwrap_or_default(); + Some((parent.to_string(), author_hex)) + } + None => None, + }; + let reply_ref = reply_owned + .as_ref() + .map(|(id, a)| (id.as_str(), a.as_str())); + let expiry = vector_core::self_destruct::resolve_send_expiry(&channel_id); + if let Some(exp) = expiry { + extra_tags.push(Tag::expiration(Timestamp::from_secs(exp))); + } + let rumor = vector_core::community::v2::chat::build_message_rumor( + author, + &ch, + epoch, + &content, + reply_ref, + &emoji_pairs, + extra_tags.clone(), + ms, + ); + let rumor = vector_core::community::v2::service::outbound_rumor(&community, &ch, rumor); + let message_id = rumor.id.ok_or("inner rumor has no id")?.to_hex(); // i18n-exempt: developer error + + let mut pending = Message { + id: message_id.clone(), + content: content.clone(), + at: ms, + pending: true, + mine: true, + npub: author.to_bech32().ok(), + replied_to: reply.clone().unwrap_or_default(), + emoji_tags: emoji_tags.clone(), + text_spans, + role_mentions, + addressed_bots, + expiration: expiry, + ..Default::default() + }; + let _ = db::events::populate_reply_context(&mut pending).await; + STATE + .lock() + .await + .add_message_to_chat(&channel_id, &pending); + Callback.on_pending(&channel_id, &pending); + + let transport = LiveTransport::with_timeout(Duration::from_secs(12)); + let sent = vector_core::community::v2::service::try_send_chat_message_at( + &transport, + &community, + &ch, + &content, + reply_ref, + &emoji_pairs, + extra_tags, + ms, + ) + .await; + match sent { + Ok(sent_id) => { + let row = { + let mut state = STATE.lock().await; + if sent_id != message_id { + state.remove_message(&message_id); + state.find_message(&sent_id).map(|(_, m)| m) + } else { + state + .update_message(&message_id, |m| m.set_pending(false)) + .map(|(_, m)| m) + } + }; + if let Some(msg) = row { + Callback.on_sent(&channel_id, &message_id, &msg); + Callback.on_persist(&channel_id, &msg); + } + Ok(()) + } + Err(unsent) => { + // Failed under the id it was signed with when an epoch rolled since the precompute. + if let Some(msg) = vector_core::community::v2::service::mark_unsent(&channel_id, &message_id, &unsent).await { + Callback.on_failed(&channel_id, &message_id, &msg); + } + Err(unsent.error) + } + } + }) + .await +} + +pub enum Control<'a> { + /// An emoji, and its picture when it is a custom one. + React(&'a str, Option<&'a str>), + Edit(&'a str), + Delete, +} + +/// Reactions, edits and deletes. The service's echo is silent, so the UI hears it here. +pub async fn control(channel_id: &str, target: &str, op: Control<'_>) -> Result<(), String> { + match op { + Control::React(emoji, url) => { + vector_core::badges::check_new_reaction_allowance(target, emoji).await?; + VectorCore + .send_community_reaction(channel_id, target, emoji, url) + .await + .map_err(|e| e.to_string())?; + } + Control::Edit(content) => { + VectorCore + .edit_community_message(channel_id, target, content) + .await + .map_err(|e| e.to_string())?; + } + Control::Delete => { + VectorCore + .delete_community_message_in(channel_id, target) + .await + .map_err(|e| e.to_string())?; + vector_core::emit_event( + "message_removed", + &json!({ "id": target, "chat_id": channel_id, "reason": "deleted" }), + ); + return Ok(()); + } + } + if let Some((_, msg)) = STATE.lock().await.find_message(target) { + vector_core::traits::emit_message_replaced(channel_id, target, &msg); + } + Ok(()) +} + +// ── Catch-up ──────────────────────────────────────────────────────────────── + +/// Channels paged at once. +const WINDOW: usize = 6; +/// The paint asks from a little before each channel's newest held message. +const SINCE_SLACK_SECS: u64 = 3600; + +static IN_FLIGHT: AtomicBool = AtomicBool::new(false); +static RERUN: AtomicBool = AtomicBool::new(false); + +/// Sweep every held channel, or queue one more behind a sweep already going: a relay that came +/// up mid-run may hold what that run never asked it for. +pub fn request() { + if IN_FLIGHT.swap(true, Ordering::SeqCst) { + RERUN.store(true, Ordering::SeqCst); + return; + } + db::spawn_bound(run()); +} + +fn rerun() -> std::pin::Pin + Send>> { + Box::pin(run()) +} + +/// Relays back since the last pass, and whether one is ours (it also holds the Community List). +struct Reconnected; +struct Resyncing; + +/// A burst of reconnects becomes one catch-up, scoped to the Communities on those relays. One +/// that lands mid-pass queues for the next. +pub fn reconnected(relay: String, ours: bool) { + let session = db::current_session(); + let pending = session.scoped::, bool)>>(); + { + let mut p = pending.lock().unwrap_or_else(|e| e.into_inner()); + if !p.0.contains(&relay) { + p.0.push(relay); + } + p.1 |= ours; + } + let busy = session.scoped::(); + if busy.swap(true, Ordering::AcqRel) { + return; + } + db::spawn_bound(async move { + loop { + tokio::time::sleep(Duration::from_millis(1500)).await; + let (relays, ours) = { + let mut p = pending.lock().unwrap_or_else(|e| e.into_inner()); + (std::mem::take(&mut p.0), std::mem::take(&mut p.1)) + }; + if !relays.is_empty() && !db::session_stopped() { + // The pool re-sends the DM sub on reconnect, not this targeted one. + if let Some(client) = vector_core::state::nostr_client() { + realtime::refresh_subscription(&client).await; + } + resync(relays, ours).await; + } + busy.store(false, Ordering::Release); + let queued = !pending.lock().unwrap_or_else(|e| e.into_inner()).0.is_empty(); + if !queued || db::session_stopped() || busy.swap(true, Ordering::AcqRel) { + break; + } + } + }); +} + +/// Only the gap: each channel's latest page is floored at its newest cursor. +async fn resync(relays: Vec, ours: bool) { + use vector_core::inbox_relays::normalize_relay_url; + let back: std::collections::HashSet = relays.iter().map(|r| normalize_relay_url(r)).collect(); + let uses = |list: &[String]| list.iter().any(|r| back.contains(&normalize_relay_url(r))); + let mut channels: Vec = Vec::new(); + for id in db::community::list_community_ids().unwrap_or_default() { + let Ok(Some(c)) = db::community::load_community_v2(&id) else { + continue; + }; + if !uses(&c.relays) { + continue; + } + // Its control, guestbook and rekeys may have moved in the gap too. + realtime::enqueue_follow(c.id()); + channels.extend(c.channels.iter().map(|ch| bytes_to_hex_32(&ch.id.0))); + } + if ours { + db::spawn_bound(ingest_list()); + } + walk_channels(channels).await; +} + +async fn run() { + RERUN.store(false, Ordering::SeqCst); + sweep().await; + IN_FLIGHT.store(false, Ordering::SeqCst); + if RERUN.swap(false, Ordering::SeqCst) && !db::session_stopped() { + IN_FLIGHT.store(true, Ordering::SeqCst); + db::spawn_bound(rerun()); + } +} + +async fn sweep() { + db::spawn_bound(ingest_list()); + let _ = db::community::purge_expired_pending_invites(); + let Ok(ids) = db::community::list_community_ids() else { + return; + }; + let last = db::events::get_all_chats_last_messages() + .await + .unwrap_or_default(); + let activity = |cid: &str| { + last.get(cid) + .and_then(|v| v.first().map(|m| m.at)) + .unwrap_or(0) + }; + + let session = db::current_session(); + let mut held: Vec = Vec::new(); + let mut targets: Vec<(PaintTarget, u64)> = Vec::new(); + for id in ids { + let Ok(Some(c)) = db::community::load_community_v2(&id) else { + continue; + }; + VectorCore.register_v2_chats(&c, &session).await; + if c.dissolved { + continue; + } + held.push(CommunityId(id.0)); + for ch in &c.channels { + let hex = bytes_to_hex_32(&ch.id.0); + let at = activity(&hex); + let since = (at > 0).then(|| { + (at / 1000) + .saturating_sub(SINCE_SLACK_SECS) + .max(vector_core::history_gaps::proven(&hex, c.channel_secret(ch).1 .0).unwrap_or(0)) + }); + targets.push(( + PaintTarget { + community_id: CommunityId(id.0), + channel_hex: hex, + since, + }, + at, + )); + } + } + super::emit("communities_changed", ()); + let on_screen = focus().lock().unwrap_or_else(|e| e.into_inner()).clone(); + targets.sort_by_key(|t| (on_screen.as_deref() != Some(t.0.channel_hex.as_str()), std::cmp::Reverse(t.1))); + let channels: Vec = targets.iter().map(|(t, _)| t.channel_hex.clone()).collect(); + vector_core::community::cache::after_foreground().await; + volley::paint_all(targets.into_iter().map(|(t, _)| t).collect()).await; + for id in &held { + realtime::enqueue_follow(id); + } + walk_channels(channels).await; + if let Some(client) = vector_core::state::nostr_client() { + realtime::force_refresh_subscription(&client).await; + } +} + +/// Memberships joined or left on another device. +async fn ingest_list() { + use vector_core::community::v2::service as v2; + let Some(client) = vector_core::state::nostr_client() else { + return; + }; + let bootstrap: Vec = client + .relays() + .await + .keys() + .map(|r| r.to_string()) + .collect(); + let transport = LiveTransport::with_timeout(Duration::from_secs(12)); + let Ok(outcome) = v2::sync_community_list(&transport, &bootstrap).await else { + return; + }; + let session = db::current_session(); + for c in &outcome.joined { + VectorCore.register_v2_chats(c, &session).await; + realtime::enqueue_follow(c.id()); + } + if !outcome.joined.is_empty() || !outcome.removed.is_empty() { + super::emit("communities_changed", ()); + } + realtime::refresh_subscription(&client).await; +} + +// ── Lifecycle and layout ──────────────────────────────────────────────────── + +fn channel_ids(community_id: &str) -> Vec { + load(community_id) + .map(|c| { + c.channels + .iter() + .map(|ch| bytes_to_hex_32(&ch.id.0)) + .collect() + }) + .unwrap_or_default() +} + +async fn reregister(community_id: &str) { + if let Ok(c) = load(community_id) { + VectorCore + .register_v2_chats(&c, &db::current_session()) + .await; + } + super::emit("communities_changed", ()); +} + +/// A new channel with another's settings and permission rules, under its own name. +pub async fn duplicate_channel(community_id: String, channel_id: String, name: String) -> Result { + db::scoped_result(async move { + let id = VectorCore + .duplicate_channel(&community_id, &channel_id, name.trim()) + .await + .map_err(|e| e.to_string()); + super::emit("communities_changed", ()); + id + }) + .await +} + +/// The new channel's id. +pub async fn create_channel( + community_id: String, + name: String, + private: bool, + category_id: Option, + voice: bool, +) -> Result { + db::scoped_result(async move { + let name = name.trim().to_string(); + if name.is_empty() { + return Err(crate::t::community_channel_needs_name().into()); + } + let community = load(&community_id)?; + let transport = LiveTransport::with_timeout(Duration::from_secs(20)); + let category = category_id.as_deref().map(id32).transpose()?; + let channel_id = vector_core::community::v2::service::create_channel_in( + &transport, &community, &name, private, category, + ) + .await?; + let hex = bytes_to_hex_32(&channel_id.0); + if voice { + VectorCore + .edit_channel_details(&community_id, &hex, &name, None, "voice") + .await + .map_err(|e| e.to_string())?; + } + reregister(&community_id).await; + Ok(hex) + }) + .await +} + +pub async fn create_category(community_id: String, name: String) -> Result<(), String> { + db::scoped(async move { + VectorCore + .create_category(&community_id, name.trim()) + .await + .map_err(|e| e.to_string())?; + reregister(&community_id).await; + Ok(()) + }) + .await +} + +async fn teardown_local(id: &str, channels: &[String], relays: &[String]) { + let _ = db::community::delete_community_retain_keys(id); + if let Some(client) = vector_core::state::nostr_client() { + realtime::refresh_subscription(&client).await; + } + STATE + .lock() + .await + .chats + .retain(|c| !channels.contains(&c.id)); + for ch in channels { + let _ = db::chats::delete_chat(ch); + } + vector_core::community::transport::prune_unneeded_community_relays(relays).await; +} + +/// Leave as a member, or dissolve it as its owner. +pub async fn leave_or_delete(community_id: String, owner: bool) -> Result<(), String> { + db::scoped(async move { + let channels = channel_ids(&community_id); + let relays = load(&community_id).map(|c| c.relays).unwrap_or_default(); + if owner { + if is_held(&community_id) + && !db::community::get_community_dissolved(&community_id).unwrap_or(false) + { + VectorCore + .dissolve_community(&community_id) + .await + .map_err(|e| e.to_string())?; + } + } else { + VectorCore + .leave_community_now(&community_id) + .await + .map_err(|e| e.to_string())?; + } + teardown_local(&community_id, &channels, &relays).await; + super::rail::forget(community_id.clone()).await; + super::emit("communities_changed", ()); + Ok(()) + }) + .await +} + +/// Every channel read to its newest message, muted ones too: unmuting one later shows only +/// what arrived since. +pub async fn mark_read(community_id: String) { + for ch in channel_ids(&community_id) { + super::messaging::mark_caught_up(ch.clone()).await; + STATE.lock().await.unread_clear(&ch); + } + vector_core::emit_event("unread_counts_stale", &json!({ "chats": [] })); +} + +/// A new single-channel Community on the account's relays: its id and its channel's. +pub async fn create_community(name: String) -> Result<(String, String), String> { + db::scoped_result(async move { + let relays: Vec = vector_core::state::active_trusted_relays() + .await + .iter() + .map(|s| s.to_string()) + .collect(); + if relays.is_empty() { + return Err(crate::t::community_no_relays().into()); + } + let session = db::current_session(); + let transport = LiveTransport::with_timeout(Duration::from_secs(12)); + let community = vector_core::community::v2::service::create_community_on_roles_v2( + &transport, + name.trim(), + relays, + None, + ) + .await?; + let channel_id = community + .channels + .first() + .map(|ch| bytes_to_hex_32(&ch.id.0)) + .ok_or("created community has no channel")?; // i18n-exempt: developer error + VectorCore.register_v2_chats(&community, &session).await; + if let Some(client) = vector_core::state::nostr_client() { + realtime::refresh_subscription(&client).await; + } + super::emit("communities_changed", ()); + Ok((bytes_to_hex_32(&community.id().0), channel_id)) + }) + .await +} + +/// A shareable link anyone can join by. +pub async fn create_public_invite( + community_id: String, + label: Option, +) -> Result { + db::scoped(async move { + VectorCore + .create_public_invite(&community_id, None, label) + .await + .map_err(|e| e.to_string()) + }) + .await +} + +pub struct InviteLinks { + pub mine: Vec, + /// Anyone's link keeps the Community joinable, not only ours. + pub public: bool, + /// Other creators and how many live links each holds. + pub others: Vec<(String, usize)>, +} + +pub async fn invite_links(community_id: String) -> InviteLinks { + db::scoped(async move { + let mine = db::community::list_public_invites(&community_id).unwrap_or_default(); + let public = db::community::get_community_invite_registry(&community_id) + .map(|r| !r.is_empty()) + .unwrap_or(!mine.is_empty()); + let me = vector_core::my_public_key().map(|k| k.to_hex()); + let others = db::community::get_invite_link_sets(&community_id) + .unwrap_or_default() + .into_iter() + .filter(|s| !s.locators.is_empty() && Some(&s.creator_hex) != me.as_ref()) + .filter_map(|s| { + Some(( + PublicKey::from_hex(&s.creator_hex).ok()?.to_bech32().ok()?, + s.locators.len(), + )) + }) + .collect(); + InviteLinks { + mine, + public, + others, + } + }) + .await +} + +/// Whether this account's links changed on its other devices. +pub async fn sync_invites(community_id: String) -> bool { + db::scoped(async move { VectorCore.sync_public_invites(&community_id).await.unwrap_or(false) }).await +} + +pub async fn revoke_invite(community_id: String, token: String) -> Result<(), String> { + db::scoped(async move { + VectorCore + .revoke_public_invite(&community_id, &token) + .await + .map_err(|e| e.to_string()) + }) + .await +} + +/// Who can't be invited: the banned (as npubs). +pub fn banned(community_id: &str) -> Vec { + VectorCore + .get_community_banned(community_id) + .into_iter() + .map(|h| { + PublicKey::from_hex(&h) + .ok() + .and_then(|pk| pk.to_bech32().ok()) + .unwrap_or(h) + }) + .collect() +} + +pub async fn invite(community_id: String, npub: String) -> Result<(), String> { + db::scoped(async move { + VectorCore + .invite_to_community(&community_id, &npub) + .await + .map(|_| ()) + .map_err(|e| e.to_string()) + }) + .await +} + +/// Invites parked for consent, newest first. +pub async fn pending_invites() -> Vec { + db::scoped(async move { + db::community::list_pending_invites() + .unwrap_or_default() + .into_iter() + .map(|i| crate::data::RawInvite { + community_id: i.community_id, + bundle_json: i.bundle_json, + inviter_npub: i.inviter_npub, + received_at: i.received_at, + sent_at: i.sent_at, + ends_at: i.ends_at, + }) + .collect() + }) + .await +} + +pub async fn accept_invite(community_id: String) -> Result<(), String> { + db::scoped(async move { + VectorCore + .accept_pending_invite(&community_id) + .await + .map_err(|e| e.to_string())?; + super::emit("communities_changed", ()); + Ok(()) + }) + .await +} + +pub async fn decline_invite(community_id: String) -> Result<(), String> { + db::scoped(async move { + VectorCore + .decline_community_invite(&community_id) + .await + .map(|_| ()) + .map_err(|e| e.to_string()) + }) + .await +} + +#[derive(Clone, Debug)] +pub struct InvitePreview { + pub community_id: String, + pub name: String, + pub description: String, + /// The logo as a local file, when it has one that loads. + pub icon: Option, +} + +/// What an invite link leads to, read off its bundle (or our copy, once joined). +pub async fn preview_invite(url: String) -> Result { + db::scoped(async move { + vector_core::community::v2::invite::parse_invite_link(&url).map_err(|e| e.to_string())?; + let transport = LiveTransport::with_timeout(Duration::from_secs(12)); + let bundle = + vector_core::community::v2::service::fetch_public_bundle_for_preview(&transport, &url).await?; + let community_id = bundle.community_id.clone(); + let logo = |c: &CommunityV2| c.icon.as_ref().map(|i| i.to_community_image()); + if let Ok(local) = load(&community_id) { + let icon = match logo(&local) { + Some(img) => super::images::community_image(&img, false).await.ok(), + None => None, + }; + return Ok(InvitePreview { + community_id, + name: crate::kit::one_line(&local.name).into_owned(), + description: local.description.clone().unwrap_or_default(), + icon, + }); + } + let folded = + vector_core::community::v2::service::preview_bundle(&transport, &bundle).await?; + let icon = match logo(&folded) { + Some(img) => super::images::community_image(&img, false).await.ok(), + None => None, + }; + Ok(InvitePreview { + community_id, + name: crate::kit::one_line(&folded.name).into_owned(), + description: folded.description.clone().unwrap_or_default(), + icon, + }) + }) + .await +} + +/// Joins by link: the Community's id. +pub async fn join_by_link(url: String) -> Result { + db::scoped(async move { + let joined = VectorCore + .join_community(&url) + .await + .map_err(|e| e.to_string())?; + let id = joined + .get("community_id") + .or_else(|| joined.get("id")) + .and_then(Value::as_str) + .ok_or("join returned no community id")? // i18n-exempt: developer error + .to_string(); + if let Ok(c) = load(&id) { + VectorCore + .register_v2_chats(&c, &db::current_session()) + .await; + } + super::emit("communities_changed", ()); + Ok(id) + }) + .await +} + +/// What this account may do here: `get_community_capabilities`' flags. +pub fn capabilities(community_id: &str) -> std::collections::HashSet { + VectorCore + .community_capabilities(community_id) + .ok() + .and_then(|v| v.as_object().cloned()) + .map(|o| { + o.into_iter() + .filter(|(_, v)| v.as_bool() == Some(true)) + .map(|(k, _)| k) + .collect() + }) + .unwrap_or_default() +} + +pub async fn edit_metadata( + community_id: String, + name: Option, + description: Option, +) -> Result<(), String> { + db::scoped(async move { + VectorCore + .edit_community_metadata(&community_id, name.as_deref(), description.as_deref()) + .await + .map_err(|e| e.to_string())?; + super::emit("communities_changed", ()); + Ok(()) + }) + .await +} + +pub async fn set_voice_relays( + community_id: String, + relays: Vec, +) -> Result, String> { + db::scoped(async move { + VectorCore + .set_voice_relays(&community_id, &relays) + .await + .map_err(|e| e.to_string()) + }) + .await +} + +/// Send a community's Join/Leave lines to a chat channel, or `None` to turn them off. +pub async fn set_system_channel(community_id: String, channel_id: Option) -> Result<(), String> { + db::scoped(async move { + VectorCore + .set_system_channel(&community_id, channel_id.as_deref()) + .await + .map_err(|e| e.to_string()) + }) + .await +} + +/// Choose the channel new members open first, or `None` for the default. +pub async fn set_landing_channel(community_id: String, channel_id: Option) -> Result<(), String> { + db::scoped(async move { + VectorCore + .set_landing_channel(&community_id, channel_id.as_deref()) + .await + .map_err(|e| e.to_string()) + }) + .await +} + +/// Whether each new relay can hold the Community, and what would make the move worse. +pub async fn check_relays( + community_id: String, + relays: Vec, +) -> Result, String> { + db::scoped(async move { + VectorCore + .check_community_relays(&community_id, &relays) + .await + .map_err(|e| e.to_string()) + }) + .await +} + +/// Hand the Community and its history to `relays`, then announce it: the moved list and its gaps. +pub async fn move_relays( + community_id: String, + relays: Vec, +) -> Result<(Vec, Vec), String> { + db::scoped(async move { + let moved = VectorCore + .move_community_relays(&community_id, &relays) + .await + .map_err(|e| e.to_string())?; + super::emit("communities_changed", ()); + Ok((moved.relays, moved.warnings)) + }) + .await +} + +pub async fn set_banned( + community_id: String, + npubs: Vec, + banned: bool, +) -> Result<(), String> { + db::scoped(async move { + let refs: Vec<&str> = npubs.iter().map(String::as_str).collect(); + VectorCore + .set_members_banned(&community_id, &refs, banned) + .await + .map_err(|e| e.to_string())?; + if banned { + VectorCore::invalidate_raid_report(&community_id); + } + // A ban hides messages retroactively, which the incremental unread cache can't derive. + for ch in load(&community_id) + .ok() + .map(|c| { + c.channels + .iter() + .map(|ch| bytes_to_hex_32(&ch.id.0)) + .collect::>() + }) + .unwrap_or_default() + { + let count = db::events::unread_count_for_chat(&ch).await.unwrap_or(0); + let mut state = STATE.lock().await; + if state.unread_seeded { + state.unread_set(&ch, count); + } + } + if db::session_is_live() { + if let Some(client) = vector_core::state::nostr_client() { + realtime::refresh_subscription(&client).await; + } + } + super::emit("community_refreshed", community_id); + Ok(()) + }) + .await +} + +/// `get_community_audit_log`: newest first, as JSON the Audit Log reads. +pub async fn audit_log(community_id: String) -> Result { + db::scoped(async move { + let log = VectorCore + .community_audit_log(&community_id) + .await + .map_err(|e| e.to_string())?; + serde_json::to_value(log).map_err(|e| e.to_string()) + }) + .await +} + +/// The Sync Report's two reads, each failing alone: the control fold and the epoch walk. +pub async fn sync_report(community_id: String) -> (Result, Result) { + db::scoped(async move { + let c = match load(&community_id) { + Ok(c) => c, + Err(e) => return (Err(e.clone()), Err(e)), + }; + let transport = vector_core::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(12)); + let (control, mut epoch, probe) = tokio::join!( + vector_core::community::v2::service::debug_control_report(&c), + vector_core::community::v2::service::explain_epoch_state(&transport, &c), + vector_core::community::v2::service::probe_base_rekey_addresses(&transport, &c), + ); + if let Ok(Value::Object(o)) = &mut epoch { + o.insert("addresses".into(), probe.unwrap_or_else(|e| serde_json::json!({ "error": e }))); + } + (control, epoch) + }) + .await +} + +/// `get_community_roles_view`: everything the role editor needs, read locally. +pub fn roles_view(community_id: &str) -> Result { + VectorCore + .community_roles_view(community_id) + .map_err(|e| e.to_string()) +} + +/// What one save of the role editor publishes: the dragged order, then the open role. +pub struct RoleSave { + pub order: Option>, + pub everyone: Option, + pub role: Option, +} + +pub struct RoleWrite { + pub id: Option, + pub name: String, + pub color: u32, + pub permissions: String, + pub channel_id: Option, + pub display: bool, + pub mentionable: bool, +} + +/// Publishes `save`; returns the role to reopen (a role created here, by its new id). +pub async fn save_roles(community_id: String, save: RoleSave) -> Result, String> { + db::scoped(async move { + let id = community_id.as_str(); + if let Some(order) = save.order { + VectorCore + .reorder_roles(id, &order) + .await + .map_err(|e| e.to_string())?; + } + if let Some(perms) = save.everyone { + VectorCore + .set_everyone_permissions(id, &perms) + .await + .map_err(|e| e.to_string())?; + } + let Some(r) = save.role else { return Ok(None) }; + let role_id = match r.id { + Some(role_id) => { + VectorCore + .edit_role_shown( + id, + &role_id, + &r.name, + r.color, + &r.permissions, + r.channel_id.as_deref(), + Some(r.display), + Some(r.mentionable), + ) + .await + .map_err(|e| e.to_string())?; + role_id + } + None => { + let role_id = VectorCore + .create_role( + id, + &r.name, + r.color, + &r.permissions, + r.channel_id.as_deref(), + ) + .await + .map_err(|e| e.to_string())?; + // Creation takes no flags: a role made shown or mentionable gets them right after. + if r.display || r.mentionable { + VectorCore + .edit_role_shown( + id, + &role_id, + &r.name, + r.color, + &r.permissions, + r.channel_id.as_deref(), + Some(r.display), + Some(r.mentionable), + ) + .await + .map_err(|e| e.to_string())?; + } + role_id + } + }; + super::emit("community_refreshed", community_id.clone()); + Ok(Some(role_id)) + }) + .await +} + +pub async fn delete_role(community_id: String, role_id: String) -> Result<(), String> { + db::scoped(async move { + VectorCore + .delete_role(&community_id, &role_id) + .await + .map_err(|e| e.to_string()) + }) + .await +} + +pub async fn activate_roles(community_id: String, everyone: String) -> Result<(), String> { + db::scoped(async move { + VectorCore + .activate_roles_v2(&community_id, &everyone) + .await + .map(|_| ()) + .map_err(|e| e.to_string()) + }) + .await +} + +/// Give a role to `add` and take it from `remove`, each member's whole set rewritten; returns +/// the first failure, having tried them all. +pub async fn set_role_holders( + community_id: String, + role_id: String, + held: Vec<(String, Vec)>, + add: Vec, + remove: Vec, +) -> Result<(), String> { + db::scoped(async move { + let mut first = None; + for npub in add.iter().chain(&remove) { + let current = held + .iter() + .find(|(n, _)| n == npub) + .map(|(_, r)| r.clone()) + .unwrap_or_default(); + let next: Vec = if add.contains(npub) { + let mut v = current; + if !v.contains(&role_id) { + v.push(role_id.clone()); + } + v + } else { + current.into_iter().filter(|r| *r != role_id).collect() + }; + if let Err(e) = VectorCore.set_member_roles(&community_id, npub, next).await { + first.get_or_insert(e.to_string()); + } + } + super::emit("community_refreshed", community_id.clone()); + first.map_or(Ok(()), Err) + }) + .await +} + +/// `setMemberRole`: give (`on`) or take one role, the member's set re-read right before the +/// write since a Grant replaces it whole. +pub async fn set_member_role(community_id: String, npub: String, role_id: String, on: bool) -> Result<(), String> { + db::scoped(async move { + let view = roles_view(&community_id)?; + let mut held: Vec = view["roles"] + .as_array() + .into_iter() + .flatten() + .filter(|r| r["holders"].as_array().is_some_and(|h| h.iter().any(|x| x.as_str() == Some(npub.as_str())))) + .filter_map(|r| r["role_id"].as_str().map(String::from)) + .collect(); + held.retain(|r| *r != role_id); + if on { + held.push(role_id); + } + VectorCore.set_member_roles(&community_id, &npub, held).await.map_err(|e| e.to_string())?; + super::emit("community_refreshed", community_id); + Ok(()) + }) + .await +} + +/// `get_channel_send_denied`: which of `npubs` can't send in the channel. +pub fn send_denied(community_id: &str, channel_id: &str, npubs: &[String]) -> std::collections::HashSet { + VectorCore.channel_send_denied(community_id, channel_id, npubs).unwrap_or_default().into_iter().collect() +} + +/// `get_channel_react_denied`: which of `npubs` can't react in the channel. +pub fn react_denied(community_id: &str, channel_id: &str, npubs: &[String]) -> std::collections::HashSet { + VectorCore.channel_react_denied(community_id, channel_id, npubs).unwrap_or_default().into_iter().collect() +} + +/// `get_community_timeouts`: npub → { from, until }. +pub fn timeouts(community_id: &str) -> serde_json::Value { + VectorCore.community_timeouts(community_id).unwrap_or_default() +} + +/// Time a member out for `seconds` (at most 28 days); 0 lifts it. +pub async fn timeout(community_id: String, npub: String, seconds: u64) -> Result<(), String> { + db::scoped(async move { VectorCore.timeout_member(&community_id, &npub, seconds).await.map_err(|e| e.to_string()) }).await +} + +/// A cooperative kick: they can rejoin with a new invite. +pub async fn kick(community_id: String, npub: String) -> Result<(), String> { + db::scoped(async move { VectorCore.kick_member(&community_id, &npub).await.map_err(|e| e.to_string()) }).await +} + +/// `get_community_nicknames`: npub → nickname. +pub fn nicknames(community_id: &str) -> std::collections::HashMap { + VectorCore + .community_nicknames(community_id) + .ok() + .and_then(|v| serde_json::from_value(v).ok()) + .unwrap_or_default() +} + +/// Sets `npub`'s nickname in a community; "" clears it. +pub async fn set_nickname( + community_id: String, + npub: String, + nickname: String, +) -> Result<(), String> { + db::scoped(async move { + VectorCore + .set_community_nickname(&community_id, &npub, &nickname) + .await + .map_err(|e| e.to_string()) + }) + .await +} + +async fn refresh_if_live() { + if db::session_is_live() { + if let Some(client) = vector_core::state::nostr_client() { + realtime::refresh_subscription(&client).await; + } + } +} + +pub fn moderation_intel(community_id: &str) -> Result { + VectorCore + .community_moderation_intel(community_id) + .map_err(|e| e.to_string()) +} + +/// `(detected, suspects)` for the menu's raid pip. +pub fn check_raid(community_id: &str) -> (bool, usize) { + let v = VectorCore + .check_community_raid(community_id) + .unwrap_or(Value::Null); + ( + v["detected"].as_bool().unwrap_or(false), + v["suspects"].as_u64().unwrap_or(0) as usize, + ) +} + +/// Re-founds onto `retain`, reporting `(done, total)` of the kick sweep. +pub async fn refound( + community_id: String, + retain: Vec, + progress: impl Fn(usize, usize) + Sync, +) -> Result { + db::scoped(async move { + let refs: Vec<&str> = retain.iter().map(String::as_str).collect(); + let summary = VectorCore + .purge_and_refound(&community_id, &refs, &progress) + .await + .map_err(|e| e.to_string())?; + VectorCore::invalidate_raid_report(&community_id); + refresh_if_live().await; + super::emit("community_refreshed", community_id); + Ok(summary) + }) + .await +} + +pub async fn revoke_all_invites(community_id: String) -> Result<(usize, usize), String> { + db::scoped(async move { + let out = VectorCore + .revoke_all_public_invites(&community_id) + .await + .map_err(|e| e.to_string())?; + refresh_if_live().await; + Ok(out) + }) + .await +} + +pub fn policy_presets() -> Result { + VectorCore.policy_presets().map_err(|e| e.to_string()) +} + +pub fn policies(community_id: &str) -> Result { + VectorCore + .list_community_policies(community_id) + .map_err(|e| e.to_string()) +} + +pub fn preview_policy(community_id: &str, bytes: &str) -> Result { + VectorCore + .preview_community_policy(community_id, bytes) + .map_err(|e| e.to_string()) +} + +pub fn set_policy( + community_id: &str, + policy_id: &str, + bytes: &str, + enabled: bool, +) -> Result { + VectorCore + .set_community_policy(community_id, policy_id, bytes, enabled) + .map_err(|e| e.to_string()) +} + +pub fn delete_policy(community_id: &str, policy_id: &str) -> Result<(), String> { + VectorCore + .delete_community_policy(community_id, policy_id) + .map_err(|e| e.to_string()) +} + +/// A joined community's logo or banner as a local file; None when it has none. +pub async fn image(community_id: String, banner: bool) -> Result, String> { + let Some(img) = db::community::community_image(&community_id, banner)? else { + return Ok(None); + }; + super::images::community_image(&img, banner).await.map(Some) +} + +/// Uploads `path` (cropped to `crop`) as the logo or banner and publishes it; `progress` gets percent. +pub async fn set_image( + community_id: String, + path: std::path::PathBuf, + banner: bool, + crop: Option, + progress: impl Fn(u8) + Send + Sync + 'static, +) -> Result<(), String> { + db::scoped(async move { + let session = db::current_session(); + let community = load(&community_id)?; + let raw = tokio::fs::read(&path) + .await + .map_err(|e| format!("read image: {e}"))?; // i18n-exempt: developer error + if vector_core::svg::looks_like_svg(&raw) { + return Err(vector_core::community::SVG_REFUSED.into()); + } + let (bytes, ext) = tokio::task::spawn_blocking(move || { + crate::backend::upload::prepared(raw, banner, crop) + }) + .await + .map_err(|e| e.to_string())??; + let hash = vector_core::crypto::sha256_hex(&bytes); + let params = vector_core::crypto::generate_encryption_params(); + let encrypted = vector_core::crypto::encrypt_data(&bytes, ¶ms)?; + let signer = vector_core::signer::active_signer().map_err(|e| format!("signer: {e}"))?; // i18n-exempt: developer error + let servers = vector_core::state::get_blossom_servers(); + if servers.is_empty() { + return Err(crate::t::community_no_media_servers().into()); + } + let on: vector_core::blossom::ProgressCallback = std::sync::Arc::new(move |pct, _| { + progress(pct.unwrap_or(0)); + Ok(()) + }); + let url = vector_core::blossom::upload_blob_with_progress_and_failover( + signer, + servers, + std::sync::Arc::new(encrypted), + Some("application/octet-stream"), + true, + on, + None, + None, + None, + ) + .await? + .url; + super::images::precache(&url, &bytes, banner); + let mut extra = serde_json::Map::new(); + extra.insert("ext".into(), Value::String(ext.into())); + let img_ref = vector_core::community::v2::control::ImageRef { + url, + key: params.key, + nonce: params.nonce, + hash, + extra, + }; + let mut meta = community.metadata(); + if banner { + meta.banner = Some(img_ref.clone()); + } else { + meta.icon = Some(img_ref.clone()); + } + let transport = LiveTransport::with_timeout(Duration::from_secs(12)); + vector_core::community::v2::service::edit_community_metadata(&transport, &community, &meta) + .await?; + if let Some(updated) = vector_core::community::v2::service::persist_community_image( + community.id(), + Some(img_ref), + banner, + ) + .await + { + VectorCore.register_v2_chats(&updated, &session).await; + } + super::emit("community_refreshed", community_id); + Ok(()) + }) + .await +} + +pub async fn remove_image(community_id: String, banner: bool) -> Result<(), String> { + db::scoped(async move { + VectorCore + .remove_community_image(&community_id, banner) + .await + .map_err(|e| e.to_string())?; + super::emit("community_refreshed", community_id); + Ok(()) + }) + .await +} + +pub fn hidden_banners() -> Vec { + vector_core::synced_prefs::load_hidden_banners().ids +} + +pub fn set_banner_hidden(community_id: &str, hidden: bool) -> Result, String> { + vector_core::synced_prefs::set_banner_hidden(community_id, hidden).map(|l| l.ids) +} + +/// `get_channel_permissions`: a channel's or Category's overwrites, read locally. +pub fn channel_permissions(community_id: &str, channel_id: &str) -> Result { + VectorCore + .channel_permissions_view(community_id, channel_id) + .map_err(|e| e.to_string()) +} + +/// What one Save of Channel Settings publishes: the details, then the open overwrite. +pub struct ChannelSave { + pub details: Option, + /// (kind, target id, allow, deny), bits as decimal strings. + pub overwrite: Option<(String, Option, String, String)>, +} + +pub struct ChannelDetails { + pub name: String, + pub topic: Option, + pub view: String, + pub category: bool, +} + +pub async fn save_channel(community_id: String, channel_id: String, save: ChannelSave) -> Result<(), String> { + db::scoped(async move { + let (id, ch) = (community_id.as_str(), channel_id.as_str()); + if let Some(d) = save.details { + if d.category { + VectorCore.rename_category(id, ch, &d.name).await.map_err(|e| e.to_string())?; + } else { + VectorCore + .edit_channel_details(id, ch, &d.name, d.topic.as_deref(), &d.view) + .await + .map_err(|e| e.to_string())?; + } + } + if let Some((kind, target, allow, deny)) = save.overwrite { + VectorCore + .set_channel_overwrite(id, ch, &kind, target.as_deref(), &allow, &deny) + .await + .map_err(|e| e.to_string())?; + } + reregister(id).await; + Ok(()) + }) + .await +} + +pub async fn set_channel_private(community_id: String, channel_id: String, private: bool) -> Result<(), String> { + db::scoped(async move { + VectorCore + .set_channel_private(&community_id, &channel_id, private) + .await + .map_err(|e| e.to_string())?; + reregister(&community_id).await; + Ok(()) + }) + .await +} + +/// Sync a channel to `category`'s permissions, or (none) back to its own. +pub async fn set_channel_sync(community_id: String, channel_id: String, category: Option) -> Result<(), String> { + db::scoped(async move { + VectorCore + .set_channel_sync(&community_id, &channel_id, category.as_deref()) + .await + .map_err(|e| e.to_string())?; + reregister(&community_id).await; + Ok(()) + }) + .await +} + +/// The primary channel anchors the community's row and history, so it can't go. +pub async fn delete_channel(community_id: String, channel_id: String) -> Result<(), String> { + db::scoped_result(async move { + let community = load(&community_id)?; + let ch = ChannelId(id32(&channel_id)?); + if community.primary_channel().is_some_and(|p| p.id.0 == ch.0) { + return Err(crate::t::community_first_channel().to_string()); + } + let name = community + .channel(&ch) + .map(|c| c.name.clone()) + .ok_or_else(|| crate::t::community_channel_not_found().to_string())?; + let transport = LiveTransport::with_timeout(Duration::from_secs(12)); + vector_core::community::v2::service::delete_channel(&transport, &community, &ch, &name).await?; + reregister(&community_id).await; + Ok(()) + }) + .await +} + +/// Move a channel into a Category (`None`: uncategorized) at `index` among its channels. +pub async fn move_channel(community_id: String, channel_id: String, category_id: Option, index: usize) -> Result<(), String> { + db::scoped(async move { + VectorCore + .move_channel(&community_id, &channel_id, category_id.as_deref(), index) + .await + .map_err(|e| e.to_string())?; + reregister(&community_id).await; + Ok(()) + }) + .await +} + +/// Move a Category to `index` among the Categories (0 is the top). +pub async fn move_category(community_id: String, category_id: String, index: usize) -> Result<(), String> { + db::scoped(async move { + VectorCore + .move_category(&community_id, &category_id, index) + .await + .map_err(|e| e.to_string())?; + reregister(&community_id).await; + Ok(()) + }) + .await +} + +pub async fn delete_category(community_id: String, category_id: String) -> Result<(), String> { + db::scoped(async move { + VectorCore + .delete_category(&community_id, &category_id) + .await + .map_err(|e| e.to_string())?; + reregister(&community_id).await; + Ok(()) + }) + .await +} + +/// `get_channel_pins`: `{pins, sealed, version}` from the locally folded head. +pub fn channel_pins(community_id: &str, channel_id: &str) -> Result { + VectorCore.get_channel_pins(community_id, channel_id).map_err(|e| e.to_string()) +} + +pub async fn set_pinned(community_id: String, channel_id: String, message_id: String, on: bool) -> Result<(), String> { + db::scoped(async move { + let res = if on { + VectorCore.pin_community_message(&community_id, &channel_id, &message_id).await + } else { + VectorCore.unpin_community_message(&community_id, &channel_id, &message_id).await + }; + res.map_err(|e| e.to_string()) + }) + .await +} + +/// `fetch_pinned_attachment`: the pin's file from the proof alone, `{path, mime, name}`. +pub async fn pinned_attachment(community_id: String, channel_id: String, message_id: String) -> Result { + db::scoped(async move { + VectorCore + .fetch_pinned_attachment(&community_id, &channel_id, &message_id) + .await + .map_err(|e| e.to_string()) + }) + .await +} diff --git a/crates/vector-gpui/src/backend/community_files.rs b/crates/vector-gpui/src/backend/community_files.rs new file mode 100644 index 000000000..7442ef95f --- /dev/null +++ b/crates/vector-gpui/src/backend/community_files.rs @@ -0,0 +1,529 @@ +//! Files and voice notes into a Community channel (`send_community_files`): every attachment +//! rides one message, each in its own imeta, sealed under a fresh key only members can open. + +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::time::Duration; + +use nostr_sdk::prelude::ToBech32; +use vector_core::community::transport::LiveTransport; +use vector_core::community::CommunityId; +use vector_core::sending::{FileSource, Sealed, SendCallback}; +use vector_core::Message; + +use super::messaging::Callback; +use crate::message::types::CachedCompressedImage; + +const IMAGE_EXTS: &[&str] = &["png", "jpg", "jpeg", "gif", "webp", "jxl", "tiff", "tif", "ico"]; + +struct Prepared { + attachment: vector_core::types::Attachment, + plain: FileSource, + mime: String, +} + +fn id32(hex: &str) -> Result<[u8; 32], String> { + if hex.len() != 64 { + return Err(format!("expected 64 hex chars, got {}", hex.len())); // i18n-exempt: developer error + } + Ok(vector_core::simd::hex::hex_to_bytes_32(hex)) +} + +/// Send `path` (named `name_override` when not empty) to `channel` with an optional caption. +pub async fn send_file( + channel: String, + content: String, + path: PathBuf, + name_override: String, + compress: bool, + keep_metadata: bool, + replied_to: String, + precompressed: Option, +) -> Result, String> { + let prepared = prepare(&path, &name_override, compress, keep_metadata, precompressed).await?; + dispatch(channel, content, replied_to, vec![prepared]).await +} + +/// Bytes in hand sent as they are, under `name`. +pub async fn send_bytes(channel: String, bytes: Vec, name: String) -> Result<(), String> { + let prepared = prepare_bytes(bytes, &name, false, false, None).await?; + dispatch(channel, String::new(), String::new(), vec![prepared]).await.map(|_| ()) +} + +/// A voice note: a nameless WAV, which members draw as a waveform. +pub async fn send_voice(channel: String, wav: Vec, replied_to: String) -> Result<(), String> { + let mut prepared = prepare_bytes(wav, "voice-message.wav", false, false, None).await?; + prepared.attachment.name = String::new(); + dispatch(channel, String::new(), replied_to, vec![prepared]).await.map(|_| ()) +} + +async fn prepare( + path: &Path, + name_override: &str, + compress: bool, + keep_metadata: bool, + precompressed: Option, +) -> Result { + let name = if name_override.is_empty() { + path.file_name().and_then(|n| n.to_str()).unwrap_or("").to_string() + } else { + vector_core::crypto::sanitize_filename(name_override) + }; + let extension = Path::new(&name) + .extension() + .and_then(|e| e.to_str()) + .unwrap_or("") + .to_lowercase(); + if let Some(pc) = smaller_video(&extension, compress, precompressed.as_ref()) { + let name = crate::message::video_compression::renamed(&name, &pc.extension); + let bytes = Arc::try_unwrap(pc.bytes.clone()).unwrap_or_else(|a| (*a).clone()); + return prepare_bytes(bytes, &name, false, false, None).await; + } + if let Some(b) = super::pasted::get(path) { + let bytes = Arc::try_unwrap(b).unwrap_or_else(|a| (*a).clone()); + return prepare_bytes(bytes, &name, compress, keep_metadata, precompressed).await; + } + if !IMAGE_EXTS.contains(&extension.as_str()) { + return prepare_path(path.to_path_buf(), name).await; + } + let source = path.to_path_buf(); + let bytes = tokio::task::spawn_blocking(move || { + vector_core::vcache::read(&source).map(|b| b.to_vec()) + }) + .await + .map_err(|e| e.to_string())? + .map_err(|e| format!("read attachment: {e}"))?; // i18n-exempt: developer error + prepare_bytes(bytes, &name, compress, keep_metadata, precompressed).await +} + +/// The preview's encode of a video, when it came out smaller; otherwise the original streams. +pub(crate) fn smaller_video<'a>( + extension: &str, + compress: bool, + precompressed: Option<&'a CachedCompressedImage>, +) -> Option<&'a CachedCompressedImage> { + precompressed.filter(|pc| { + compress + && crate::message::video_compression::is_video_extension(extension) + && !pc.is_original_on_disk() + && pc.compressed_size < pc.original_size + }) +} + +/// A file that needs no processing: hashed where it lies and sealed file to file. +async fn prepare_path(path: PathBuf, name: String) -> Result { + let extension = Path::new(&name) + .extension() + .and_then(|e| e.to_str()) + .unwrap_or("bin") + .to_lowercase(); + let source = path.clone(); + let (hash, len) = tokio::task::spawn_blocking(move || vector_core::crypto::stream::hash_file(&source)) + .await + .map_err(|e| e.to_string())??; + if len == 0 { + return Err(crate::t::community_empty_attachment().into()); + } + Ok(stage(FileSource::Path(path), len, hash, extension, name, None)) +} + +async fn prepare_bytes( + bytes: Vec, + file_name: &str, + compress: bool, + keep_metadata: bool, + precompressed: Option, +) -> Result { + if bytes.is_empty() { + return Err(crate::t::community_empty_attachment().into()); + } + let sent_as = Path::new(file_name) + .extension() + .and_then(|e| e.to_str()) + .unwrap_or("bin") + .to_lowercase(); + let mut extension = sent_as.clone(); + let is_image = IMAGE_EXTS.contains(&extension.as_str()); + let (bytes, img_meta, extension, hash) = tokio::task::spawn_blocking(move || { + let (bytes, img_meta) = if is_image { + let processed = crate::message::process_image_for_send( + Arc::new(bytes), + &extension, + compress, + keep_metadata, + precompressed, + )?; + crate::message::compression::forget_fitted(); + extension = processed.extension; + (Arc::try_unwrap(processed.bytes).unwrap_or_else(|a| (*a).clone()), processed.img_meta) + } else { + (bytes, None) + }; + let hash = vector_core::crypto::sha256_hex(&bytes); + Ok::<_, String>((bytes, img_meta, extension, hash)) + }) + .await + .map_err(|e| e.to_string())??; + let len = bytes.len() as u64; + // A compressed picture's name follows its new format, so the receiver opens it as one. + let name = if extension == sent_as { + file_name.to_string() + } else { + crate::message::video_compression::renamed(file_name, &extension) + }; + Ok(stage(FileSource::Bytes(Arc::new(bytes)), len, hash, extension, name, img_meta)) +} + +/// The optimistic attachment; nothing is sealed or uploaded until the bubble is up. +fn stage( + plain: FileSource, + plain_len: u64, + hash_hex: String, + extension: String, + name: String, + img_meta: Option, +) -> Prepared { + let params = match &plain { + FileSource::Sealed { key, nonce, .. } => vector_core::crypto::EncryptionParams { + key: key.clone(), + nonce: nonce.clone(), + }, + _ => vector_core::crypto::generate_encryption_params(), + }; + let mime = vector_core::crypto::mime_from_extension(&extension).to_string(); + let hash = vector_core::simd::hex::hex_to_bytes_32(&hash_hex); + match &plain { + FileSource::Bytes(bytes) => { + let _ = vector_core::media::ram::insert(hash, bytes.to_vec(), &mime); + } + FileSource::Path(path) | FileSource::Saved(path) => { + vector_core::media::pending::plain(hash, path.clone(), &mime) + } + FileSource::Sealed { path, key, nonce, .. } => { + vector_core::media::pending::sealed(hash, path.clone(), key, nonce, &mime) + } + } + // Minted at send so every member joins one realtime topic; it rides the imeta. + let webxdc_topic = extension.eq_ignore_ascii_case("xdc").then(|| { + let sender = vector_core::state::my_public_key() + .map(|pk| pk.to_hex()) + .unwrap_or_default(); + vector_core::webxdc::mint_topic_id(&hash_hex, &sender) + }); + let attachment = vector_core::types::Attachment { + id: hash_hex.clone(), + key: params.key, + nonce: params.nonce, + extension, + name, + url: String::new(), + path: String::new(), + // AES-GCM's 16-byte tag: the sealed size is known before sealing. + size: plain_len + 16, + img_meta, + downloading: false, + downloaded: false, + verified: true, + resident: vector_core::media::resident(&hash), + webxdc_topic, + group_id: None, + original_hash: Some(hash_hex), + fallback_urls: Vec::new(), + }; + Prepared { attachment, plain, mime } +} + +async fn mark_failed(channel: &str, pending_id: &str) { + let failed = { + let mut state = vector_core::state::STATE.lock().await; + state.update_message(pending_id, |m| { + m.set_failed(true); + m.set_pending(false); + }) + }; + if let Some((_, msg)) = failed { + Callback.on_failed(channel, pending_id, &msg); + } +} + +/// The bubble first, then each upload with progress and cancel, then one sealed message; +/// the echo replaces the bubble. Returns a sent Mini App's realtime topic. +async fn dispatch( + channel: String, + content: String, + replied_to: String, + prepared: Vec, +) -> Result, String> { + vector_core::db::scoped(async move { + let reply = (!replied_to.is_empty()).then_some(replied_to); + let author = vector_core::my_public_key().ok_or("Public key not set")?; // i18n-exempt: developer error + let my_npub = author.to_bech32().ok(); + let community_id = vector_core::db::community::community_id_for_channel(&channel)? + .ok_or_else(|| crate::t::community_unknown_channel().to_string())?; + let (content, _) = vector_core::community::mentions::resolve_in(&community_id, &content); + let (content, text_spans) = vector_core::text_spans::extract_own(&content); + let community = vector_core::db::community::load_community_v2(&CommunityId(id32(&community_id)?))? + .ok_or_else(|| crate::t::community_not_found().to_string())?; + let ch = vector_core::community::ChannelId(id32(&channel)?); + if community.channel(&ch).is_none() { + return Err(crate::t::community_channel_not_found().to_string()); + } + + let ms = vector_core::clock::now_ms(); + // device-clock: a local id, never compared with a time. + let nanos = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap_or_default() + .as_nanos(); + let pending_id = format!("pending-{nanos}"); + let emoji_tags = vector_core::emoji_packs::resolve_outbound_emoji_tags(&content); + let self_destruct = vector_core::self_destruct::chat_duration_secs(&channel); + let mut pending = Message { + id: pending_id.clone(), + content: content.clone(), + at: ms, + pending: true, + mine: true, + npub: my_npub, + replied_to: reply.clone().unwrap_or_default(), + emoji_tags: emoji_tags.clone(), + text_spans: text_spans.clone(), + attachments: prepared.iter().map(|p| p.attachment.clone()).collect(), + expiration: None, + ..Default::default() + }; + let _ = vector_core::db::events::populate_reply_context(&mut pending).await; + vector_core::state::STATE.lock().await.add_message_to_chat(&channel, &pending); + Callback.on_pending(&channel, &pending); + let cancel = Callback.cancel_token(&pending_id); + + let signer = vector_core::signer::active_signer().map_err(|e| crate::t::community_signer_unavailable(e.to_string()).to_string())?; + let servers = vector_core::state::get_blossom_servers(); + if servers.is_empty() { + mark_failed(&channel, &pending_id).await; + return Err(crate::t::community_no_media_servers().to_string()); + } + + let mut uploaded = Vec::with_capacity(prepared.len()); + for Prepared { mut attachment, plain, mime } in prepared { + let sealed = match vector_core::sending::seal_or_reuse( + plain, + &attachment.id, + &attachment.key, + &attachment.nonce, + &pending_id, + Arc::new(Callback), + cancel.clone(), + ) + .await + { + Ok(s) => s, + Err(e) => { + mark_failed(&channel, &pending_id).await; + return Err(e); + } + }; + let (encrypted, sealed_file) = match sealed { + // A live blob already holds it: no upload, only a background mirror if it's someone else's. + Sealed::Reused(r) => { + let foreign = !r.mine; + (attachment.key, attachment.nonce, attachment.url, attachment.size) = + (r.key, r.nonce, r.url, r.size); + { + let adopted = vector_core::compact::CompactAttachment::from_attachment(&attachment); + let mut state = vector_core::state::STATE.lock().await; + state.update_attachment(&channel, &pending_id, &attachment.id, |a| *a = adopted.clone()); + } + Callback.on_upload_complete(&channel, &pending_id, &attachment.id, &attachment.url); + if foreign { + let (signer, url) = (signer.clone(), attachment.url.clone()); + vector_core::db::spawn_bound(async move { + let _ = vector_core::blossom::mirror_blob_to_servers( + signer, + &url, + vector_core::state::get_blossom_servers(), + 1, + Duration::from_secs(8), + &[], + ) + .await; + }); + } + uploaded.push(attachment); + continue; + } + Sealed::Body(body, guard) => (body, guard), + }; + let pid = pending_id.clone(); + let progress: vector_core::blossom::ProgressCallback = Arc::new(move |pct, bytes| { + Callback.on_upload_progress(&pid, pct.unwrap_or(0), bytes.unwrap_or(0)) + }); + let body = encrypted.clone(); + let accepted = match vector_core::blossom::upload_body_with_progress_and_failover( + signer.clone(), + servers.clone(), + encrypted, + Some(mime.as_str()), + true, + progress, + Some(3), + Some(Duration::from_secs(2)), + cancel.clone(), + ) + .await + { + Ok(a) => a, + Err(e) => { + if !cancel.as_ref().is_some_and(|c| c.load(std::sync::atomic::Ordering::Relaxed)) { + vector_core::sending::keep_for_retry( + &body, + sealed_file, + &attachment.id, + &attachment.key, + &attachment.nonce, + &pending_id, + &mime, + ); + } + mark_failed(&channel, &pending_id).await; + return Err(crate::t::community_upload_failed(e.to_string()).to_string()); + } + }; + if vector_core::media::keep_media() + && vector_core::sending::keep_sent( + &body, + &attachment.id, + &attachment.key, + &attachment.nonce, + attachment.size.saturating_sub(16), + &mime, + ) + { + attachment.downloaded = true; + } + attachment.url = accepted.url.clone(); + { + let mut state = vector_core::state::STATE.lock().await; + let url = accepted.url.clone(); + state.update_attachment(&channel, &pending_id, &attachment.id, |a| { + a.url = url.clone().into_boxed_str(); + }); + } + Callback.on_upload_complete(&channel, &pending_id, &attachment.id, &accepted.url); + // BUD-04 mirrors ride the imeta as fallbacks; none never fails the send. + let mirrors = vector_core::blossom::mirror_blob_to_servers( + signer.clone(), + &accepted.url, + servers.clone(), + 2, + Duration::from_secs(5), + std::slice::from_ref(&accepted.server), + ) + .await; + if !mirrors.is_empty() { + attachment.fallback_urls = mirrors.clone(); + let mut state = vector_core::state::STATE.lock().await; + state.update_attachment(&channel, &pending_id, &attachment.id, |a| { + a.set_fallback_urls(mirrors.iter().map(|s| s.as_str().into())); + }); + } + uploaded.push(attachment); + } + + let mut tags: Vec<_> = uploaded + .iter() + .map(vector_core::community::attachments::attachment_to_imeta) + .collect(); + tags.extend(vector_core::text_spans::to_nostr_tags(&text_spans)); + let quote = match reply.as_deref() { + Some(parent) => { + let author = { + let st = vector_core::state::STATE.lock().await; + st.find_message(parent) + .and_then(|(_, m)| m.npub.as_deref().and_then(|n| nostr_sdk::prelude::PublicKey::parse(n).ok())) + .map(|pk| pk.to_hex()) + .unwrap_or_default() + }; + Some((parent.to_string(), author)) + } + None => None, + }; + let quote_ref = quote.as_ref().map(|(id, a)| (id.as_str(), a.as_str())); + let emoji: Vec<(&str, &str)> = emoji_tags.iter().map(|t| (t.shortcode.as_str(), t.url.as_str())).collect(); + if let Some(exp) = self_destruct.and_then(vector_core::self_destruct::expiry_after) { + tags.push(nostr_sdk::prelude::Tag::expiration(nostr_sdk::prelude::Timestamp::from_secs(exp))); + } + let transport = LiveTransport::with_timeout(Duration::from_secs(12)); + let sent = vector_core::community::v2::service::try_send_chat_message( + &transport, &community, &ch, &content, quote_ref, &emoji, tags, + ) + .await; + match sent { + Ok(real_id) => { + let echoed = { + let mut state = vector_core::state::STATE.lock().await; + state.remove_message(&pending_id); + // Our own plaintexts are on hand: the echo must not fetch them back. + for local in &uploaded { + state.update_attachment(&channel, &real_id, &local.id, |a| { + a.set_verified(local.verified); + a.set_downloading(false); + if local.downloaded { + a.set_downloaded(true); + a.set_path(local.path.clone()); + } + }); + } + state.find_message(&real_id).map(|(_, m)| m.clone()) + }; + if let Some(msg) = echoed { + Callback.on_sent(&channel, &pending_id, &msg); + Callback.on_persist(&channel, &msg); + } + Ok(uploaded.iter().find_map(|a| a.webxdc_topic.clone())) + } + Err(unsent) => { + // Signed and kept: the bubble becomes that message, so a retry sends it again + // as itself and a delete takes it back, with the files it names left alone. + if let Some(msg) = vector_core::community::v2::service::mark_unsent(&channel, &pending_id, &unsent).await { + Callback.on_failed(&channel, &pending_id, &msg); + } + Err(unsent.error) + } + } + }) + .await +} + +// i18n-exempt: sentinel, matched and shown translated +pub const RETRY_FILE_MISSING: &str = "This file is no longer on this device. Attach it again to send it."; + +/// `retry_failed_community_message`: republish the retained wrap, else send the files again from +/// whatever this device still holds of them. False when there was nothing to go again from. +pub async fn retry(message_id: String) -> Result { + vector_core::db::scoped(async move { + let failed = { + let state = vector_core::state::STATE.lock().await; + state.find_message(&message_id).map(|(chat, m)| (chat.id().to_string(), m)) + }; + if !failed.as_ref().is_some_and(|(_, m)| m.failed) { + return Err("Message is not failed or does not exist".into()); // i18n-exempt: developer error + } + if vector_core::community::v2::service::retry_unconfirmed(&message_id).await { + return Ok(true); + } + let Some((channel, msg)) = failed.filter(|(_, m)| !m.attachments.is_empty()) else { + return Ok(false); + }; + let mut prepared = Vec::with_capacity(msg.attachments.len()); + for att in &msg.attachments { + let source = vector_core::sending::retry_source(att).ok_or(RETRY_FILE_MISSING)?; + let plain_len = att.size.saturating_sub(16); + prepared.push(stage(source, plain_len, att.id.clone(), att.extension.clone(), att.name.clone(), att.img_meta.clone())); + } + super::actions::remove_failed(&message_id, false).await?; + dispatch(channel, msg.content, msg.replied_to, prepared).await?; + Ok(true) + }) + .await +} diff --git a/crates/vector-gpui/src/backend/device.rs b/crates/vector-gpui/src/backend/device.rs new file mode 100644 index 000000000..68118a08f --- /dev/null +++ b/crates/vector-gpui/src/backend/device.rs @@ -0,0 +1,41 @@ +//! This device's own preferences (the Tauri client keeps these in `localStorage`): a JSON +//! map in the data directory, never synced and never per account. + +use std::path::PathBuf; +use std::sync::Mutex; + +use serde_json::{Map, Value}; + +static STORE: Mutex, Map)>> = Mutex::new(None); + +/// Load the map from `dir`; without one (fixtures) it lives in memory only. +pub fn init(dir: Option) { + let path = dir.map(|d| d.join("device.json")); + let map = path + .as_ref() + .and_then(|p| std::fs::read(p).ok()) + .and_then(|b| serde_json::from_slice::>(&b).ok()) + .unwrap_or_default(); + *STORE.lock().unwrap_or_else(|e| e.into_inner()) = Some((path, map)); +} + +pub fn get(key: &str) -> Option { + let guard = STORE.lock().unwrap_or_else(|e| e.into_inner()); + guard + .as_ref()? + .1 + .get(key) + .and_then(|v| v.as_str()) + .map(String::from) +} + +pub fn set(key: &str, value: impl Into) { + let mut guard = STORE.lock().unwrap_or_else(|e| e.into_inner()); + let (path, map) = guard.get_or_insert_with(|| (None, Map::new())); + map.insert(key.to_string(), Value::String(value.into())); + if let Some(path) = path { + if let Ok(bytes) = serde_json::to_vec(map) { + let _ = std::fs::write(path, bytes); + } + } +} diff --git a/crates/vector-gpui/src/backend/embedvideo.rs b/crates/vector-gpui/src/backend/embedvideo.rs new file mode 100644 index 000000000..48aa6b516 --- /dev/null +++ b/crates/vector-gpui/src/backend/embedvideo.rs @@ -0,0 +1,358 @@ +//! A Nostr event's video as something the player can open: fetched once (through the account's +//! network, like any media), checked to really be a video and to match the event's hash, then +//! held in memory or kept sealed in the cache. + +use std::collections::HashSet; +use std::path::{Path, PathBuf}; +use std::sync::{LazyLock, Mutex}; + +use serde_json::json; + +/// Larger than any clip a chat bubble should hold; a longer video belongs in a player. +const MAX_VIDEO_BYTES: u64 = 1024 * 1024 * 1024; +const CACHE_MAX_BYTES: u64 = 2 * 1024 * 1024 * 1024; +const MAX_ATTEMPTS: u32 = 3; +const CANCELLED: &str = "Download cancelled"; // i18n-exempt: sentinel, never shown + +/// Videos downloading, and those asked to stop at their next chunk. +static RUNNING: LazyLock>> = LazyLock::new(Default::default); +static STOP: LazyLock>> = LazyLock::new(Default::default); + +pub enum Fetched { + Held([u8; 32]), + /// A sealed cache file, and the type its bytes are. + Sealed(PathBuf, &'static str), +} + +pub fn is_cancel(e: &str) -> bool { + e == CANCELLED +} + +/// Stop the download of `url` at its next chunk. False when none is running. +pub fn cancel(url: &str) -> bool { + if !RUNNING.lock().unwrap_or_else(|e| e.into_inner()).contains(url) { + return false; + } + STOP.lock().unwrap_or_else(|e| e.into_inner()).insert(url.to_string()); + true +} + +fn stopped(url: &str) -> bool { + STOP.lock().unwrap_or_else(|e| e.into_inner()).contains(url) +} + +fn progress(url: &str, pct: i64) { + vector_core::emit_event("embed_video_progress", &json!({ "url": url, "progress": pct })); +} + +fn dir() -> Result { + let dir = vector_core::db::get_app_data_dir()?.join("cache").join("embed_videos"); + std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?; + Ok(dir) +} + +/// A file is reused only for the same link AND the same promised hash: another event naming +/// the link with a different hash must not be handed bytes that were never checked against it. +fn stem(url: &str, sha256: Option<&str>) -> String { + let key = format!("{url}\n{}", sha256.unwrap_or("").to_ascii_lowercase()); + vector_core::crypto::sha256_hex(key.as_bytes())[..32].to_string() +} + +fn kind(head: &[u8]) -> Option<&'static str> { + if head.len() >= 12 && &head[4..8] == b"ftyp" { + // i18n-exempt: MP4 brand + Some(if &head[8..12] == b"qt " { "mov" } else { "mp4" }) + } else if head.starts_with(&[0x1A, 0x45, 0xDF, 0xA3]) { + Some("webm") + } else { + None + } +} + +fn mime(ext: &str) -> &'static str { + match ext { + "webm" => "video/webm", + "mov" => "video/quicktime", + _ => "video/mp4", + } +} + +fn cached(dir: &Path, stem: &str) -> Option { + ["mp4", "webm", "mov"] + .into_iter() + .map(|ext| (dir.join(format!("{stem}.{ext}")), ext)) + .find(|(p, _)| vector_core::vcache::readable(p)) + .map(|(p, ext)| Fetched::Sealed(p, mime(ext))) +} + +/// The video's opening, enough for its first frame, fetched as byte ranges rather than the +/// whole file. The whole file, when it is already here, does as well. +pub async fn preview(url: String, sha256: Option) -> Result { + if !url.starts_with("https://") { + return Err(crate::t::embed_video_not_web().into()); + } + let dir = dir()?; + let stem = stem(&url, sha256.as_deref()); + let whole = vector_core::media::url_key("embed-video", &stem); + if vector_core::media::resident(&whole) { + return Ok(Fetched::Held(whole)); + } + if let Some(done) = cached(&dir, &stem) { + return Ok(done); + } + let named = format!("{stem}-poster"); + let held = vector_core::media::url_key("embed-poster", &stem); + if vector_core::media::resident(&held) { + return Ok(Fetched::Held(held)); + } + if let Some(done) = cached(&dir, &named) { + return Ok(done); + } + let poster = vector_core::video_poster::fetch(&url).await?; + if !vector_core::media::keep_media() { + vector_core::media::ram::insert(held, poster.bytes, mime(poster.ext)).map_err(|_| crate::t::embed_video_memory_show().to_string())?; + return Ok(Fetched::Held(held)); + } + let path = dir.join(format!("{named}.{}", poster.ext)); + vector_core::vcache::write(&path, &poster.bytes)?; + Ok(Fetched::Sealed(path, mime(poster.ext))) +} + +pub enum Playable { + Fetched(Fetched), + Stream(std::sync::Arc>), +} + +/// Played while it downloads where the host serves byte ranges; a video already here, or a +/// host that serves only whole files, goes the whole-file way. +pub async fn play(url: String, size: Option, sha256: Option, fallbacks: Vec) -> Result { + if !url.starts_with("https://") { + return Err(crate::t::embed_video_not_web().into()); + } + let dir = dir()?; + let stem = stem(&url, sha256.as_deref()); + let held = vector_core::media::url_key("embed-video", &stem); + if vector_core::media::resident(&held) { + return Ok(Playable::Fetched(Fetched::Held(held))); + } + if let Some(done) = cached(&dir, &stem) { + return Ok(Playable::Fetched(done)); + } + match super::stream::open(super::stream::Web::new(&url)?, sha256.clone()).await { + Ok(s) => return Ok(Playable::Stream(s)), + Err(super::stream::Open::NoRanges) => {} + Err(super::stream::Open::Failed(e)) => log::warn!("[video] streaming {url}: {e}"), + } + fetch(url, size, sha256, fallbacks).await.map(Playable::Fetched) +} + +pub async fn fetch(url: String, size: Option, sha256: Option, fallbacks: Vec) -> Result { + if !url.starts_with("https://") { + return Err(crate::t::embed_video_not_web().into()); + } + let dir = dir()?; + let stem = stem(&url, sha256.as_deref()); + let held = vector_core::media::url_key("embed-video", &stem); + let ready = |dir: &Path| vector_core::media::resident(&held).then_some(Fetched::Held(held)).or_else(|| cached(dir, &stem)); + if let Some(done) = ready(&dir) { + return Ok(done); + } + if !RUNNING.lock().unwrap_or_else(|e| e.into_inner()).insert(url.clone()) { + return Err(crate::t::embed_video_downloading().into()); + } + STOP.lock().unwrap_or_else(|e| e.into_inner()).remove(&url); + let result = async { + let declared = match size.filter(|n| *n > 0) { + Some(n) => Some(n), + None => vector_core::net::get_remote_file_size(&url).await, + }; + if declared.is_some_and(|n| n > MAX_VIDEO_BYTES) { + return Err(crate::t::embed_video_too_large().to_string()); + } + // Attachment rules: held in memory when it fits and the account doesn't keep media. + let in_memory = !vector_core::media::keep_media() && declared.is_some_and(|n| vector_core::media::ram::cache().admits(n)); + let mirrors: Vec<&str> = fallbacks.iter().map(String::as_str).filter(|u| u.starts_with("https://")).take(3).collect(); + let expected = sha256.as_deref().map(str::to_ascii_lowercase); + let limit = declared.unwrap_or(MAX_VIDEO_BYTES).saturating_add(64 * 1024); + let mut last = crate::t::embed_video_download_failed().to_string(); + for source in std::iter::once(url.as_str()).chain(mirrors) { + for attempt in 1..=MAX_ATTEMPTS { + let got = if in_memory { + hold(&url, source, held, limit, expected.as_deref()).await + } else { + keep(&url, source, &dir, &stem, limit, expected.as_deref()).await + }; + match got { + Ok(done) => return Ok(done), + Err(Fail::Cancelled) => return Err(CANCELLED.to_string()), + // The bytes arrived and were wrong: another attempt at this host fetches the same. + Err(Fail::Refused(e)) => { + last = e; + break; + } + Err(Fail::Dropped(e)) => { + last = e; + if attempt < MAX_ATTEMPTS { + tokio::time::sleep(std::time::Duration::from_secs(2 * attempt as u64)).await; + } + } + } + } + } + Err(last) + } + .await; + RUNNING.lock().unwrap_or_else(|e| e.into_inner()).remove(&url); + STOP.lock().unwrap_or_else(|e| e.into_inner()).remove(&url); + if result.is_ok() { + progress(&url, 100); + tokio::task::spawn_blocking(move || prune(&dir)); + } + result +} + +enum Fail { + Cancelled, + /// Not the video the event names, or the host refused it. + Refused(String), + /// The connection failed or dropped: worth another try. + Dropped(String), +} + +/// One streamed GET of `source`, each chunk handed to `sink`. Reports progress under `url`. +async fn stream(url: &str, source: &str, limit: u64, mut sink: impl FnMut(u64, &[u8]) -> Result<(), String>) -> Result { + vector_core::net::validate_url_not_private(source).map_err(|e| Fail::Refused(e.to_string()))?; + let client = vector_core::net::build_http_client_with_options(None, Some(vector_core::net::transfer_stall()), true).map_err(Fail::Dropped)?; + let mut resp = vector_core::net::proxied_request(&client, reqwest::Method::GET, source) + .await + .send() + .await + .map_err(|e| Fail::Dropped(e.to_string()))?; + if !resp.status().is_success() { + return Err(Fail::Refused(crate::t::embed_video_server_error().into())); + } + let total = resp.content_length().filter(|&n| n > 0); + if total.is_some_and(|t| t > limit) { + return Err(Fail::Refused(crate::t::embed_video_too_large().into())); + } + progress(url, if total.is_some() { 0 } else { -1 }); + let mut at = 0u64; + let mut last = -1; + while let Some(chunk) = resp.chunk().await.map_err(|e| Fail::Dropped(e.to_string()))? { + if stopped(url) { + return Err(Fail::Cancelled); + } + if at + chunk.len() as u64 > limit { + return Err(Fail::Refused(crate::t::embed_video_too_large().into())); + } + sink(at, &chunk).map_err(Fail::Refused)?; + at += chunk.len() as u64; + if let Some(t) = total { + let pct = (at * 100 / t).min(99) as i64; + if pct > last { + last = pct; + progress(url, pct); + } + } + } + if total.is_some_and(|t| at < t) { + return Err(Fail::Dropped(crate::t::embed_video_ended_early().into())); + } + Ok(at) +} + +fn verify(head: &[u8], hash: Option, expected: Option<&str>) -> Result<&'static str, Fail> { + let ext = kind(head).ok_or_else(|| Fail::Refused(crate::t::embed_video_not_video().into()))?; + if let (Some(want), Some(got)) = (expected, hash) + && got != want + { + return Err(Fail::Refused(crate::t::embed_video_fingerprint().into())); + } + Ok(ext) +} + +async fn hold(url: &str, source: &str, key: [u8; 32], limit: u64, expected: Option<&str>) -> Result { + let mut body = Vec::new(); + stream(url, source, limit, |_, chunk| { + body.extend_from_slice(chunk); + Ok(()) + }) + .await?; + let check = expected.is_some(); + let (body, hash) = tokio::task::spawn_blocking(move || { + let hash = check.then(|| vector_core::crypto::sha256_hex(&body)); + (body, hash) + }) + .await + .map_err(|e| Fail::Refused(e.to_string()))?; + let ext = verify(&body[..body.len().min(12)], hash, expected)?; + vector_core::media::ram::insert(key, body, mime(ext)).map_err(|_| Fail::Refused(crate::t::embed_video_memory_play().into()))?; + Ok(Fetched::Held(key)) +} + +/// Streamed into a sealed part file, so no byte of it is ever plain on disk; kept by a rename. +async fn keep(url: &str, source: &str, dir: &Path, stem: &str, limit: u64, expected: Option<&str>) -> Result { + use std::io::Write; + let part = dir.join(format!("{stem}.part")); + let fail = |e: std::io::Error| Fail::Refused(e.to_string()); + let sealer = vector_core::vcache::Sealer::for_part(&part).map_err(Fail::Refused)?; + let file = std::fs::OpenOptions::new().create(true).write(true).truncate(true).open(&part).map_err(fail)?; + file.set_len(vector_core::vcache::HEADER_LEN).map_err(fail)?; + let mut out = std::io::BufWriter::with_capacity(256 * 1024, file); + std::io::Seek::seek(&mut out, std::io::SeekFrom::Start(vector_core::vcache::HEADER_LEN)).map_err(fail)?; + let mut head = Vec::with_capacity(12); + let mut hasher = expected.map(|_| vector_core::crypto::sha256::Sha256::new()); + let streamed = stream(url, source, limit, |at, chunk| { + if head.len() < 12 { + head.extend_from_slice(&chunk[..chunk.len().min(12 - head.len())]); + } + if let Some(h) = hasher.as_mut() { + h.update(chunk); + } + let mut sealed = chunk.to_vec(); + sealer.seal_at(at, &mut sealed)?; + out.write_all(&sealed).map_err(|e| e.to_string()) + }) + .await; + let finished = streamed.and_then(|_| { + out.flush().map_err(fail)?; + let hash = hasher.map(|h| h.finalize().iter().map(|b| format!("{b:02x}")).collect::()); + let ext = verify(&head, hash, expected)?; + let path = dir.join(format!("{stem}.{ext}")); + std::fs::rename(&part, &path).map_err(fail)?; + Ok(Fetched::Sealed(path, mime(ext))) + }); + if finished.is_err() { + let _ = std::fs::remove_file(&part); + } + finished +} + +/// Oldest videos go first once the folder is past its cap, down to 80%. +fn prune(dir: &Path) { + let Ok(rd) = std::fs::read_dir(dir) else { return }; + let mut entries: Vec<(PathBuf, std::time::SystemTime, u64)> = rd + .flatten() + .filter_map(|e| { + let m = e.metadata().ok()?; + let p = e.path(); + let video = matches!(p.extension().and_then(|x| x.to_str()), Some("mp4" | "webm" | "mov")); + (m.is_file() && video).then(|| (p, m.modified().unwrap_or(std::time::UNIX_EPOCH), m.len())) + }) + .collect(); + let mut total: u64 = entries.iter().map(|(_, _, n)| n).sum(); + if total <= CACHE_MAX_BYTES { + return; + } + entries.sort_by_key(|(_, t, _)| *t); + // The newest stays: it is about to play. + entries.pop(); + for (p, _, n) in entries { + if total <= CACHE_MAX_BYTES * 8 / 10 { + break; + } + if std::fs::remove_file(&p).is_ok() { + total = total.saturating_sub(n); + } + } +} diff --git a/crates/vector-gpui/src/backend/events.rs b/crates/vector-gpui/src/backend/events.rs new file mode 100644 index 000000000..fe418cefc --- /dev/null +++ b/crates/vector-gpui/src/backend/events.rs @@ -0,0 +1,231 @@ +//! Live inbound events. Core persists them; these hooks keep read state and tell the UI. + +use serde_json::json; +use vector_core::{InboundEventHandler, Message, STATE, db}; + +pub struct Handler; + +/// The open chat reads what arrives in it. +async fn auto_mark_if_active(chat_id: &str, msg_id: &str) -> bool { + if vector_core::state::get_active_chat().as_deref() != Some(chat_id) { + return false; + } + // Seen only when the window is in front and the chat at its newest: an arrival while away + // or scrolled up stays unread until the user is back (`onWindowResumed`). + if !(super::notify::focused() && super::notify::pinned()) { + return false; + } + let slim = { + let mut state = STATE.lock().await; + let Some(chat) = state.chats.iter_mut().find(|c| c.id == chat_id) else { + return false; + }; + // A "Mark as Unread" ends only by the user's own read, never a background one. + if chat.unread_from != [0u8; 32] { + return false; + } + chat.mark_read_at(vector_core::compact::encode_message_id(msg_id)); + state + .get_chat(chat_id) + .map(|c| db::chats::SlimChatDB::from_chat(c, &state.interner)) + }; + let Some(slim) = slim else { return false }; + let _ = db::chats::save_slim_chat(&slim); + vector_core::emit_event( + "chat_mark_read", + &json!({ "chat_id": chat_id, "last_read": msg_id }), + ); + true +} + +async fn refresh_unread(chat_id: &str, marked: bool) { + if marked { + STATE.lock().await.unread_clear(chat_id); + } else { + let count = db::events::unread_count_for_chat(chat_id) + .await + .unwrap_or(0); + let mut state = STATE.lock().await; + if state.unread_seeded { + state.unread_set(chat_id, count); + } + } + vector_core::emit_event("unread_counts_stale", &json!({ "chats": [chat_id] })); +} + +impl InboundEventHandler for Handler { + fn on_dm_received(&self, chat_id: &str, msg: &Message, is_new: bool) { + if !is_new { + return; + } + let (chat_id, msg) = (chat_id.to_string(), msg.clone()); + db::spawn_bound(async move { + if msg.mine { + // Answered from another device: read here too. + super::messaging::mark_as_read(chat_id.clone(), None).await; + return; + } + let marked = auto_mark_if_active(&chat_id, &msg.id).await; + refresh_unread(&chat_id, marked).await; + super::notify::direct(&chat_id, &msg).await; + }); + } + + fn on_file_received(&self, chat_id: &str, msg: &Message, is_new: bool) { + self.on_dm_received(chat_id, msg, is_new); + } + + fn on_community_invite(&self, community_id: &str) { + vector_core::emit_event( + "community_invite_received", + &json!({ "community_id": community_id }), + ); + } + + fn on_community_message(&self, chat_id: &str, msg: &Message, is_new: bool) { + vector_core::traits::emit_message_new(chat_id, msg); + let (chat_id, msg) = (chat_id.to_string(), msg.clone()); + db::spawn_bound(async move { + let marked = auto_mark_if_active(&chat_id, &msg.id).await; + refresh_unread(&chat_id, marked).await; + if is_new { + super::notify::community(&chat_id, &msg).await; + } + }); + } + + fn on_community_update(&self, chat_id: &str, target_id: &str, msg: &Message) { + vector_core::traits::emit_message_replaced(chat_id, target_id, msg); + } + + fn on_community_removed(&self, chat_id: &str, target_id: &str) { + vector_core::emit_event( + "message_removed", + &json!({ "id": target_id, "chat_id": chat_id, "reason": "deleted" }), + ); + } + + fn on_community_typing(&self, chat_id: &str, npub: &str, until: u64) { + let (chat_id, npub) = (chat_id.to_string(), npub.to_string()); + db::spawn_bound(async move { + let typers = STATE + .lock() + .await + .update_typing_and_get_active(&chat_id, &npub, until); + vector_core::emit_event( + "typing-update", + &json!({ "conversation_id": chat_id, "typers": typers }), + ); + }); + } + + fn on_community_presence(&self, p: &vector_core::Presence<'_>) { + let (chat_id, npub, event_id) = (p.channel_id.to_string(), p.npub.to_string(), p.event_id.to_string()); + let invited_by = p.invited_by.map(str::to_string); + let invited_label = p.invited_label.map(str::to_string); + let (joined, created_at, shown) = (p.joined, p.created_at, p.shown); + db::spawn_bound(async move { + presence(&chat_id, &npub, joined, &event_id, created_at, invited_by.as_deref(), invited_label.as_deref(), shown).await; + }); + } + + fn on_voice_presence(&self, channel_id: &str) { + vector_core::emit_event("voice_presence", &json!({ "channel_id": channel_id })); + } + + fn on_community_webxdc(&self, chat_id: &str, npub: &str, topic_id: &str, node_addr: Option<&str>, event_id: &str, created_at: u64) { + self.on_webxdc_signal(chat_id, npub, topic_id, node_addr, event_id, created_at); + } + + fn on_webxdc_signal(&self, contact: &str, npub: &str, topic_id: &str, node_addr: Option<&str>, event_id: &str, created_at: u64) { + let (chat, npub, topic, event_id) = (contact.to_string(), npub.to_string(), topic_id.to_string(), event_id.to_string()); + let addr = node_addr.map(str::to_string); + db::spawn_bound(async move { + crate::miniapp::on_peer_signal(&chat, &npub, &topic, addr.as_deref(), &event_id, created_at).await; + }); + } + + fn on_community_dissolved(&self, community_id: &str) { + vector_core::emit_event( + "community_refreshed", + &json!({ "community_id": community_id }), + ); + } + + fn on_subscription_ready(&self, _communities: usize) { + super::community::request(); + } + + fn on_community_refreshed(&self, community_id: &str) { + let session = db::current_session(); + let community_id = community_id.to_string(); + db::spawn_bound(async move { + let id = vector_core::community::CommunityId(vector_core::simd::hex::hex_to_bytes_32( + &community_id, + )); + if let Ok(Some(c)) = db::community::load_community_v2(&id) { + vector_core::VectorCore + .register_v2_chats(&c, &session) + .await; + } + vector_core::emit_event( + "community_refreshed", + &json!({ "community_id": community_id }), + ); + }); + } + + fn on_community_self_removed(&self, community_id: &str) { + vector_core::emit_event("community_kicked", &json!({ "community_id": community_id })); + } +} + +/// A Community join or leave, saved as its system line and shown. The save dedups by event id, +/// so relay replays and our own echo stay silent. +/// A line that isn't `shown` is still kept: the member list reads it. +#[allow(clippy::too_many_arguments)] +async fn presence( + channel_id: &str, + npub: &str, + joined: bool, + event_id: &str, + created_at: u64, + invited_by: Option<&str>, + invited_label: Option<&str>, + shown: bool, +) { + use vector_core::stored_event::SystemEventType; + let et = if joined { SystemEventType::MemberJoined } else { SystemEventType::MemberLeft }; + let note = invited_by.map(|by| match invited_label { + Some(l) if !l.is_empty() => format!("{by}|{l}"), + _ => by.to_string(), + }); + let inserted = db::events::save_system_event_at(event_id, channel_id, et, npub, note.as_deref(), created_at, invited_by, invited_label) + .await + .unwrap_or(false); + if !inserted { + return; + } + let nameless = STATE.lock().await.get_profile(npub).is_none_or(|p| { + p.nickname().is_empty() && p.display_name().is_empty() && p.name().is_empty() + }); + // Behind whoever is on screen, which the drawn rows queue first. + if nameless { + vector_core::profile::sync::queue_profile_sync(npub.to_string(), vector_core::profile::sync::SyncPriority::Medium, false); + } + if !shown { + return; + } + vector_core::emit_event( + "system_event", + &json!({ + "conversation_id": channel_id, + "event_id": event_id, + "event_type": et.as_u8(), + "member_pubkey": npub, + "invited_by": invited_by.and_then(vector_core::community::inviter_npub), + "invited_label": invited_label, + "created_at_ms": created_at.saturating_mul(1000), + }), + ); +} diff --git a/crates/vector-gpui/src/backend/gifs.rs b/crates/vector-gpui/src/backend/gifs.rs new file mode 100644 index 000000000..bc1088b91 --- /dev/null +++ b/crates/vector-gpui/src/backend/gifs.rs @@ -0,0 +1,201 @@ +//! The GIF picker's service, asked through the privacy setting's egress (`commands/gifs.rs`). + +use std::path::PathBuf; +use std::sync::LazyLock; + +const SERVICE: &str = "https://gifverse.net"; +const LISTING_MAX: usize = 1024 * 1024; +const PREVIEW_MAX: usize = 8 * 1024 * 1024; +const PREVIEW_CACHE_MAX: u64 = 64 * 1024 * 1024; + +/// Previews in flight at once; nothing else shares this lane. +static PREVIEW_LANE: LazyLock = + LazyLock::new(|| tokio::sync::Semaphore::new(6)); + +#[derive(Clone)] +pub struct Gif { + pub id: String, + pub title: String, + pub thumbhash: Option, +} + +async fn fetch(url: &str, max: usize) -> Result>, String> { + let client = vector_core::net::build_http_client(std::time::Duration::from_secs(20))?; + let mut resp = vector_core::net::proxied_request(&client, reqwest::Method::GET, url) + .await + .send() + .await + .map_err(|e| e.to_string())?; + if !resp.status().is_success() { + return Ok(None); + } + let mut body = Vec::new(); + while let Some(chunk) = resp.chunk().await.map_err(|e| e.to_string())? { + if body.len() + chunk.len() > max { + return Ok(None); + } + body.extend_from_slice(&chunk); + } + Ok(Some(body)) +} + +/// Dev builds: `VECTOR_GIF_DIR` serves the picker from local `.gif` files, offline. +#[cfg(feature = "devctl")] +fn local_dir() -> Option { + std::env::var_os("VECTOR_GIF_DIR").map(PathBuf::from) +} + +/// One page of `trending` or `search`; the path is fixed here, the caller picks only the query. +pub async fn listing(query: String) -> Result, String> { + #[cfg(feature = "devctl")] + if let Some(dir) = local_dir() { + let first = query.contains("offset=0"); + let mut ids: Vec = std::fs::read_dir(dir) + .map_err(|e| e.to_string())? + .flatten() + .filter_map(|e| e.file_name().into_string().ok()) + .filter_map(|n| n.strip_suffix(".gif").map(str::to_string)) + .filter(|_| first) + .collect(); + ids.sort(); + return Ok(ids.into_iter().map(|id| Gif { title: id.clone(), id, thumbhash: None }).collect()); + } + let body = fetch(&format!("{SERVICE}/api/v1/{query}"), LISTING_MAX) + .await + .map_err(|e| format!("gif service: {e}"))? // i18n-exempt: developer error + .ok_or("gif service: no usable answer")?; // i18n-exempt: developer error + let json: serde_json::Value = + serde_json::from_slice(&body).map_err(|_| "gif service: answer is not JSON")?; // i18n-exempt: developer error + let results = json + .get("results") + .and_then(|r| r.as_array()) + .cloned() + .unwrap_or_default(); + Ok(results + .iter() + .filter_map(|g| { + let id = g.get("i")?.as_str()?.to_string(); + let s = |k: &str| { + g.get(k) + .and_then(|v| v.as_str()) + .filter(|s| !s.is_empty()) + .map(str::to_string) + }; + Some(Gif { + id, + title: s("ti").unwrap_or_default(), + thumbhash: s("th"), + }) + }) + .collect()) +} + +/// `encodeURIComponent`. +fn encode(s: &str) -> String { + let mut out = String::with_capacity(s.len()); + for b in s.bytes() { + if b.is_ascii_alphanumeric() || b"-_.!~*'()".contains(&b) { + out.push(b as char); + } else { + out.push_str(&format!("%{b:02X}")); + } + } + out +} + +pub fn trending(offset: usize, limit: usize) -> String { + format!("trending?limit={limit}&offset={offset}&sort=popular") +} + +pub fn search(q: &str, offset: usize, limit: usize) -> String { + let q = encode(q); + format!("search?q={q}&limit={limit}&offset={offset}&sort=relevant") +} + +/// What a picked GIF sends: the service's original. +pub fn original_url(id: &str) -> String { + format!("{SERVICE}/media/{id}/original.gif") +} + +fn preview_dir() -> Option { + let dir = vector_core::db::get_app_data_dir() + .ok()? + .join("cache") + .join("gif_previews"); + std::fs::create_dir_all(&dir).ok()?; + Some(dir) +} + +/// A GIF's animated preview, kept sealed in the cache. +pub async fn preview(id: String) -> Option> { + #[cfg(feature = "devctl")] + if let Some(dir) = local_dir() { + return std::fs::read(dir.join(format!("{id}.gif"))).ok(); + } + let url = original_url(&encode(&id)); + let dir = preview_dir()?; + let path = dir.join(format!( + "{}.gif", + vector_core::crypto::sha256_hex(url.as_bytes()) + )); + let read = |path: PathBuf| async move { + tokio::task::spawn_blocking(move || { + vector_core::vcache::read(&path).ok().map(|b| b.to_vec()) + }) + .await + .ok() + .flatten() + }; + if vector_core::vcache::readable(&path) { + return read(path).await; + } + let _permit = PREVIEW_LANE.acquire().await.ok()?; + if vector_core::vcache::readable(&path) { + return read(path).await; + } + let body = fetch(&url, PREVIEW_MAX).await.ok()??; + if !body.starts_with(b"GIF8") { + return None; + } + let (write_path, bytes) = (path.clone(), body); + tokio::task::spawn_blocking(move || { + let _ = vector_core::vcache::write(&write_path, &bytes); + prune(&dir); + bytes + }) + .await + .ok() +} + +/// Oldest previews go first once the folder is past its cap, down to 80%. +fn prune(dir: &std::path::Path) { + let Ok(rd) = std::fs::read_dir(dir) else { + return; + }; + let mut entries: Vec<_> = rd + .flatten() + .filter_map(|e| { + let m = e.metadata().ok()?; + m.is_file().then(|| { + ( + e.path(), + m.modified().unwrap_or(std::time::UNIX_EPOCH), + m.len(), + ) + }) + }) + .collect(); + let mut total: u64 = entries.iter().map(|(_, _, n)| n).sum(); + if total <= PREVIEW_CACHE_MAX { + return; + } + entries.sort_by_key(|(_, t, _)| *t); + for (p, _, n) in entries { + if total <= PREVIEW_CACHE_MAX * 8 / 10 { + break; + } + if std::fs::remove_file(&p).is_ok() { + total = total.saturating_sub(n); + } + } +} diff --git a/crates/vector-gpui/src/backend/images.rs b/crates/vector-gpui/src/backend/images.rs new file mode 100644 index 000000000..ba2e5c5f2 --- /dev/null +++ b/crates/vector-gpui/src/backend/images.rs @@ -0,0 +1,356 @@ +//! Profile pictures kept on disk, so the UI only ever draws local files. + +use std::path::PathBuf; +use std::sync::LazyLock; + +use vector_core::{STATE, SlimProfile, db}; + +const MAX_BYTES: usize = 10 * 1024 * 1024; +static DOWNLOADS: LazyLock = + LazyLock::new(|| tokio::sync::Semaphore::new(4)); + +#[derive(Clone, Copy)] +enum Kind { + Avatar, + Banner, + Emoji, + PackIcon, +} + +impl Kind { + fn dir(self) -> &'static str { + match self { + Kind::Avatar => "avatars", + Kind::Banner => "banners", + Kind::Emoji => "emojis", + Kind::PackIcon => "emoji_pack_icons", + } + } + + fn max_bytes(self) -> usize { + match self { + Kind::Emoji | Kind::PackIcon => 1024 * 1024, + _ => MAX_BYTES, + } + } + + fn svg_dim(self) -> u32 { + match self { + Kind::Avatar => 512, + Kind::Banner => 2048, + Kind::Emoji | Kind::PackIcon => 256, + } + } +} + +fn cache_dir(kind: Kind) -> Option { + let dir = db::get_app_data_dir().ok()?.join("cache").join(kind.dir()); + std::fs::create_dir_all(&dir).ok()?; + Some(dir) +} + +fn cache_key(url: &str) -> String { + vector_core::crypto::sha256_hex(url.as_bytes())[..32].to_string() +} + +fn sniff(bytes: &[u8]) -> Option<&'static str> { + const SIGS: &[(&[u8], &str)] = &[ + (&[0x89, b'P', b'N', b'G'], "png"), + (&[0xFF, 0xD8, 0xFF], "jpg"), + (b"GIF8", "gif"), + (&[0xFF, 0x0A], "jxl"), + (&[0x00, 0x00, 0x00, 0x0C, b'J', b'X', b'L', b' '], "jxl"), + ]; + if let Some((_, ext)) = SIGS.iter().find(|(sig, _)| bytes.starts_with(sig)) { + return Some(ext); + } + if bytes.len() >= 12 && &bytes[..4] == b"RIFF" && &bytes[8..12] == b"WEBP" { + return Some("webp"); + } + let head = &bytes[..bytes.len().min(512)]; + head.windows(4).any(|w| w == b" Option { + cached(url, Kind::Avatar) +} + +fn cached(url: &str, kind: Kind) -> Option { + let dir = cache_dir(kind)?; + let key = cache_key(url); + // Every extension the desktop client writes a cache file with. + ["jpg", "png", "webp", "gif", "ico", "svg", "bmp", "jxl"] + .iter() + .map(|ext| dir.join(format!("{key}.{ext}"))) + .find(|p| vector_core::vcache::readable(p)) + .map(|p| p.to_string_lossy().into_owned()) +} + +async fn fetch(url: &str, max: usize) -> Result, String> { + let client = vector_core::net::shared_http_client(); + let mut resp = vector_core::net::proxied_request(&client, reqwest::Method::GET, url) + .await + .send() + .await + .map_err(|e| e.to_string())?; + if !resp.status().is_success() { + return Err(format!("HTTP {}", resp.status())); // i18n-exempt: stored and matched + } + // Sized once from the header: grown by doubling, a big picture churns twice its size. + let declared = resp.content_length().map_or(0, |n| n as usize); + if declared > max { + return Err(TOO_LARGE.into()); + } + let mut out = Vec::with_capacity(declared); + while let Some(chunk) = resp.chunk().await.map_err(|e| e.to_string())? { + if out.len() + chunk.len() > max { + return Err(TOO_LARGE.into()); + } + out.extend_from_slice(&chunk); + } + Ok(out) +} + +/// A failure reason in the reader's language. The English is what's stored and matched. +pub fn shown_reason(reason: &str) -> String { + use crate::t; + match reason { + TOO_LARGE => t::emoji_why_too_large().into(), + INVALID => t::emoji_why_invalid().into(), + NO_CACHE => t::emoji_why_no_cache().into(), + BAD_URL => t::emoji_why_bad_url().into(), + INTEGRITY => t::emoji_why_integrity().into(), + other => other.to_string(), + } +} + +// i18n-exempt: stored and matched; shown through `shown_reason` +const TOO_LARGE: &str = "Image too large"; +// i18n-exempt: stored and matched; shown through `shown_reason` +const INVALID: &str = "Invalid image"; +// i18n-exempt: stored and matched; shown through `shown_reason` +const NO_CACHE: &str = "No cache directory"; +// i18n-exempt: stored and matched; shown through `shown_reason` +const BAD_URL: &str = "Invalid emoji URL"; +// i18n-exempt: stored and matched; shown through `shown_reason` +const INTEGRITY: &str = "community image failed integrity check"; + +/// How long a failure is believed (`unavailable_for`): a day for a file that is gone, too large +/// or not a picture; an hour for a server error; not at all for a fetch that got no answer. +/// Without it every launch downloads every broken avatar and banner again. +fn unavailable_for(reason: &str) -> Option { + // i18n-exempt: stored reasons + if reason.contains("too large") || reason.contains("HTTP 404") || reason.contains("HTTP 410") || reason.starts_with("Invalid") { + Some(24 * 3600) + } else if reason.starts_with("HTTP ") { // i18n-exempt: stored reasons + Some(3600) + } else { + None + } +} + +/// The desktop client's marker: a folder beside the pictures, never among them. +fn unavailable_marker(url: &str, kind: Kind) -> Option { + let dir = cache_dir(kind)?.join("unavailable"); + std::fs::create_dir_all(&dir).ok()?; + Some(dir.join(cache_key(url))) +} + +fn unavailable(url: &str, kind: Kind) -> Option { + let path = unavailable_marker(url, kind)?; + let v: serde_json::Value = serde_json::from_slice(&std::fs::read(&path).ok()?).ok()?; + let (at, for_secs) = (v.get("at")?.as_u64()?, v.get("for")?.as_u64()?); + if vector_core::clock::now_secs().saturating_sub(at) >= for_secs { + let _ = std::fs::remove_file(&path); + return None; + } + Some(v.get("reason")?.as_str()?.to_string()) +} + +fn remember_unavailable(url: &str, kind: Kind, reason: &str) { + let (Some(for_secs), Some(path)) = (unavailable_for(reason), unavailable_marker(url, kind)) else { return }; + let marker = serde_json::json!({ "reason": reason, "at": vector_core::clock::now_secs(), "for": for_secs }); + let _ = std::fs::write(path, marker.to_string()); +} + +async fn cache(url: &str, kind: Kind) -> Result { + if let Some(path) = cached(url, kind) { + return Ok(path); + } + let _permit = DOWNLOADS.acquire().await.map_err(|e| e.to_string())?; + vector_core::net::validate_url_not_private(url)?; + if let Some(reason) = unavailable(url, kind) { + return Err(reason); + } + let fetched = fetch(url, kind.max_bytes()) + .await + .and_then(|b| sniff(&b).map(|ext| (b, ext)).ok_or_else(|| INVALID.to_string())); + let (bytes, mut ext) = fetched.inspect_err(|reason| remember_unavailable(url, kind, reason))?; + // An SVG is kept as the pixels it draws. + let bytes = if ext == "svg" { + ext = "png"; + let dim = kind.svg_dim(); + tokio::task::spawn_blocking(move || vector_core::svg::rasterize_png(&bytes, dim)) + .await + .map_err(|e| e.to_string())?? + } else { + bytes + }; + let path = cache_dir(kind) + .ok_or(NO_CACHE)? + .join(format!("{}.{ext}", cache_key(url))); + vector_core::vcache::write(&path, &bytes)?; + Ok(path.to_string_lossy().into_owned()) +} + +/// A custom emoji (or a pack's icon) on disk, or why it can't be. +pub async fn emoji(url: String, icon: bool) -> Result { + if !url.starts_with("https://") { + return Err(BAD_URL.into()); + } + cache(&url, if icon { Kind::PackIcon } else { Kind::Emoji }).await +} + +pub async fn cache_profile_images(npub: &str, avatar_url: &str, banner_url: &str) { + let avatar = if avatar_url.is_empty() { + None + } else { + cache(avatar_url, Kind::Avatar).await.ok() + }; + let banner = if banner_url.is_empty() { + None + } else { + cache(banner_url, Kind::Banner).await.ok() + }; + if avatar.is_none() && banner.is_none() { + return; + } + let slim: Option = { + let mut state = STATE.lock().await; + let Some(id) = state.interner.lookup(npub) else { + return; + }; + // Blocked while the download ran: nothing is kept. + if state + .get_profile_by_id(id) + .is_some_and(|p| p.flags.is_blocked()) + { + return; + } + let changed = state.get_profile_mut_by_id(id).is_some_and(|p| { + let mut changed = false; + if let Some(a) = &avatar { + if *p.avatar_cached() != **a { + p.set_avatar_cached(a); + changed = true; + } + } + if let Some(b) = &banner { + if *p.banner_cached() != **b { + p.set_banner_cached(b); + changed = true; + } + } + changed + }); + if changed { + state.serialize_profile(id) + } else { + None + } + }; + if let Some(slim) = slim { + vector_core::emit_event("profile_update", &slim); + let _ = db::profiles::set_profile(&slim); + } +} + +/// Every profile whose pictures have no local copy yet. +pub async fn cache_all_profile_images() { + let pending: Vec<(String, String, String)> = { + let state = STATE.lock().await; + state + .profiles + .iter() + .filter(|p| { + (!p.avatar().is_empty() && !p.has_avatar_cached()) + || (!p.banner().is_empty() && !p.has_banner_cached()) + }) + .filter_map(|p| { + Some(( + state.interner.resolve(p.id)?.to_string(), + p.avatar().to_string(), + p.banner().to_string(), + )) + }) + .collect() + }; + for (npub, avatar, banner) in pending { + cache_profile_images(&npub, &avatar, &banner).await; + } +} + +/// Keep bytes we already hold (our own upload) under `url`, so it shows without a download. +pub fn precache(url: &str, bytes: &[u8], banner: bool) { + precache_as(url, bytes, if banner { Kind::Banner } else { Kind::Avatar }); +} + +/// An emoji or pack logo we just uploaded. +pub fn precache_emoji(url: &str, bytes: &[u8], icon: bool) { + precache_as(url, bytes, if icon { Kind::PackIcon } else { Kind::Emoji }); +} + +fn precache_as(url: &str, bytes: &[u8], kind: Kind) { + if cached(url, kind).is_some() { + return; + } + let (Some(ext), Some(dir)) = (sniff(bytes), cache_dir(kind)) else { + return; + }; + let rendered; + let (bytes, ext) = if ext == "svg" { + let Ok(png) = vector_core::svg::rasterize_png(bytes, kind.svg_dim()) else { + return; + }; + rendered = png; + (&rendered[..], "png") + } else { + (bytes, ext) + }; + let _ = vector_core::vcache::write(&dir.join(format!("{}.{ext}", cache_key(url))), bytes); +} + +/// A community's logo or banner: downloaded, decrypted and checked against its committed hash. +pub async fn community_image( + image: &vector_core::community::CommunityImage, + banner: bool, +) -> Result { + let kind = if banner { Kind::Banner } else { Kind::Avatar }; + if let Some(path) = cached(&image.url, kind) { + return Ok(path); + } + let _permit = DOWNLOADS.acquire().await.map_err(|e| e.to_string())?; + vector_core::net::validate_url_not_private(&image.url)?; + // Other clients upload banner crops uncompressed. + let encrypted = fetch( + &image.url, + if banner { 16 * 1024 * 1024 } else { MAX_BYTES }, + ) + .await?; + let plain = vector_core::crypto::decrypt_data_owned(encrypted, &image.key, &image.nonce)?; + if !vector_core::crypto::sha256_hex(&plain).eq_ignore_ascii_case(&image.hash) { + return Err(INTEGRITY.into()); + } + if vector_core::svg::looks_like_svg(&plain) { + return Err(vector_core::community::SVG_REFUSED.into()); + } + let ext = sniff(&plain) + .filter(|e| *e != "svg") + .ok_or(INVALID)?; + let path = cache_dir(kind) + .ok_or(NO_CACHE)? + .join(format!("{}.{ext}", cache_key(&image.url))); + vector_core::vcache::write(&path, &plain)?; + Ok(path.to_string_lossy().into_owned()) +} diff --git a/crates/vector-gpui/src/backend/inline.rs b/crates/vector-gpui/src/backend/inline.rs new file mode 100644 index 000000000..7fe171b25 --- /dev/null +++ b/crates/vector-gpui/src/backend/inline.rs @@ -0,0 +1,182 @@ +//! Pictures linked in messages (`cache_url_image`): fetched through the privacy egress, held in +//! memory like an attachment unless the account keeps media, and then kept only sealed. + +use std::path::PathBuf; +use std::sync::LazyLock; + +use serde_json::json; + +const MAX_BYTES: usize = 1024 * 1024 * 1024; +static DOWNLOADS: LazyLock = + LazyLock::new(|| tokio::sync::Semaphore::new(4)); + +const SIGNATURES: &[(&[u8], &str)] = &[ + (&[0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A], "png"), + (&[0xFF, 0xD8, 0xFF], "jpg"), + (&[0xFF, 0x0A], "jxl"), + (&[0x00, 0x00, 0x00, 0x0C, b'J', b'X', b'L', b' '], "jxl"), + (b"GIF8", "gif"), + (b"RIFF", "webp"), + (b"BM", "bmp"), + (&[0x00, 0x00, 0x01, 0x00], "ico"), +]; + +/// The format the bytes are, judged by them alone. +pub fn sniff(bytes: &[u8]) -> Option<&'static str> { + if bytes.len() < 8 { + return None; + } + for (sig, ext) in SIGNATURES { + if bytes.starts_with(sig) { + if *ext == "webp" && (bytes.len() < 12 || &bytes[8..12] != b"WEBP") { + continue; + } + return Some(ext); + } + } + let head = &bytes[..bytes.len().min(512)]; + (head.windows(4).any(|w| w == b" Option { + let dir = vector_core::db::get_app_data_dir() + .ok()? + .join("cache") + .join("inline_images"); + std::fs::create_dir_all(&dir).ok()?; + Some(dir) +} + +fn cache_stem(url: &str) -> String { + vector_core::crypto::sha256_hex(url.as_bytes())[..32].to_string() +} + +fn kept(url: &str) -> Option { + let (dir, stem) = (cache_dir()?, cache_stem(url)); + ["png", "jpg", "gif", "webp", "jxl", "bmp", "ico"] + .iter() + .map(|e| dir.join(format!("{stem}.{e}"))) + .find(|p| vector_core::vcache::readable(p)) +} + +fn progress(url: &str, pct: i64) { + vector_core::emit_event( + "inline_image_progress", + &json!({ "url": url, "progress": pct }), + ); +} + +async fn fetch(url: &str) -> Result, String> { + let timeout = vector_core::net::tor_http_timeout(std::time::Duration::from_secs(10)); + let client = vector_core::net::build_http_client_with_options( + Some(timeout), + Some(vector_core::net::transfer_stall()), + true, + )?; + let mut resp = vector_core::net::proxied_request(&client, reqwest::Method::GET, url) + .await + .send() + .await + .map_err(|e| e.to_string())?; + if !resp.status().is_success() { + return Err(format!("HTTP {}", resp.status())); // i18n-exempt: developer error + } + let total = resp.content_length().filter(|&n| n > 0); + if total.is_some_and(|n| n as usize > MAX_BYTES) { + return Err("too large".into()); // i18n-exempt: developer error + } + let mut body = Vec::with_capacity(total.unwrap_or(0).min(MAX_BYTES as u64) as usize); + let mut last = -1; + while let Some(chunk) = resp.chunk().await.map_err(|e| e.to_string())? { + if body.len() + chunk.len() > MAX_BYTES { + return Err("too large".into()); // i18n-exempt: developer error + } + body.extend_from_slice(&chunk); + if let Some(t) = total { + let pct = (body.len() as u64 * 100 / t).min(100) as i64; + if pct > last { + last = pct; + progress(url, pct); + } + } + } + Ok(body) +} + +/// [`image`] when this device already holds it: never a download. +pub async fn held_image(url: &str) -> Option> { + if !url.to_ascii_lowercase().starts_with("https://") { + return None; + } + let held = vector_core::media::url_key("inline-image", url); + if vector_core::media::resident(&held) + && let Some((bytes, _)) = vector_core::media::held_bytes(&held).await + { + return Some(bytes); + } + let path = kept(url)?; + tokio::task::spawn_blocking(move || vector_core::vcache::read(&path).ok().map(|b| b.to_vec())) + .await + .ok() + .flatten() +} + +/// The picture a message links to, as bytes ready to decode, or `None` when it isn't one. +pub async fn image(url: String) -> Option> { + if !url.to_ascii_lowercase().starts_with("https://") + || vector_core::net::validate_url_not_private(&url).is_err() + { + return None; + } + if let Some(bytes) = held_image(&url).await { + return Some(bytes); + } + let held = vector_core::media::url_key("inline-image", &url); + let _permit = DOWNLOADS.acquire().await.ok()?; + let bytes = fetch(&url).await.ok()?; + let mut ext = sniff(&bytes)?; + // An SVG is kept as the pixels it draws. + let bytes = if ext == "svg" { + ext = "png"; + tokio::task::spawn_blocking(move || vector_core::svg::rasterize_png(&bytes, 2048)) + .await + .ok()? + .ok()? + } else { + bytes + }; + if vector_core::media::keep_media() { + let path = cache_dir()?.join(format!("{}.{ext}", cache_stem(&url))); + tokio::task::spawn_blocking(move || { + vector_core::vcache::write(&path, &bytes) + .ok() + .map(|_| bytes) + }) + .await + .ok() + .flatten() + } else { + let mime = vector_core::crypto::mime_from_extension(ext); + vector_core::media::ram::insert(held, bytes.clone(), mime).ok()?; + Some(bytes) + } +} + +#[cfg(test)] +mod tests { + #[test] + fn jpeg_xl_is_recognised_and_decoded() { + let bytes = include_bytes!("../testdata/stripe.jxl"); + assert_eq!(super::sniff(bytes), Some("jxl")); + assert_eq!(vector_core::crypto::mime_from_magic_bytes(bytes), "image/jxl"); + jxl_oxide::integration::register_image_decoding_hook(); + let (img, w, h) = crate::media::decode(bytes, "jxl", (1000, 1000)).expect("decodes"); + assert_eq!((w, h), (64, 48)); + let frame = img.as_bytes(0).expect("one frame"); + // BGRA: the stripe on row 10 is green, the rest red-pink. + let px = |x: usize, y: usize| &frame[(y * 64 + x) * 4..][..4]; + assert_eq!(px(5, 10), [0, 255, 0, 255]); + assert_eq!(px(5, 20), [90, 30, 200, 255]); + } +} diff --git a/crates/vector-gpui/src/backend/install.rs b/crates/vector-gpui/src/backend/install.rs new file mode 100644 index 000000000..773e2b518 --- /dev/null +++ b/crates/vector-gpui/src/backend/install.rs @@ -0,0 +1,479 @@ +//! In-app updates: the release's bundle for this platform, checked against the same minisign key +//! the Tauri updater trusts, then put in place of the running app. + +use std::path::{Path, PathBuf}; + +/// The release signing key (`plugins.updater.pubkey` in src-tauri/tauri.conf.json). +const PUBKEY: &str = "dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IDQwRUU4N0Y0RTFEN0VCRTQKUldUazY5Zmg5SWZ1UUk0bEhjRlc2cWZsRWJpb3BSNXVjaFBKYzdmZzF4VENuREkrbEV4aFoxTXgK"; + +#[derive(Clone, Debug)] +pub struct Asset { + pub url: String, + pub check: Check, +} + +/// What vouches for the downloaded bundle. +#[derive(Clone, Debug)] +pub enum Check { + /// Base64 of the minisign `.sig` file, as the manifest carries it. + Minisign(String), + /// Android installs it only over a copy signed by the same certificate. + SigningCertificate, +} + +/// What came of an install. +pub enum Installed { + /// In place: start it, and make way. + Restart, + /// The system has it and asks the user; this copy carries on meanwhile. + Handed(String), +} + +/// How this copy was installed, as the Tauri updater names it in a manifest key: an update +/// arrives as the same kind of bundle, so each install upgrades in place. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Kind { + App, + AppImage, + Deb, + Rpm, + Nsis, + Msi, + Apk, +} + +impl Kind { + fn name(self) -> &'static str { + match self { + Kind::App => "app", + Kind::AppImage => "appimage", + Kind::Deb => "deb", + Kind::Rpm => "rpm", + Kind::Nsis => "nsis", + Kind::Msi => "msi", + Kind::Apk => "apk", + } + } +} + +/// The manifest entries for `kind`, best first: its own, then the one the 0.5 test builds read +/// for the three kinds they shipped as. +fn keys_for(kind: Kind) -> Vec { + let os = match std::env::consts::OS { + "macos" => "darwin", + other => other, + }; + let base = format!("{os}-{}", std::env::consts::ARCH); + let mut keys = vec![format!("{base}-{}", kind.name())]; + if matches!(kind, Kind::App | Kind::AppImage | Kind::Nsis) { + keys.push(format!("{base}-gpui")); + } + keys +} + +pub fn asset(manifest: &serde_json::Value) -> Option { + match kind()? { + Kind::Apk => apk_for(manifest), + kind => asset_for(manifest, kind), + } +} + +/// The release's APK for this build's ABI: installing another ABI's would fail or ship dead code. +fn apk_name() -> &'static str { + match std::env::consts::ARCH { + "aarch64" => "Vector-arm64-v8a.apk", + "arm" => "Vector-armeabi-v7a.apk", + "x86_64" => "Vector-x86_64.apk", + _ => "Vector.apk", + } +} + +/// Under the tag of the version the manifest names, so the APK is the release that was offered. +fn apk_for(manifest: &serde_json::Value) -> Option { + let version = super::updates::Version::parse(manifest.get("version")?.as_str()?)?; + Some(Asset { + url: super::updates::release_file(version, apk_name()), + check: Check::SigningCertificate, + }) +} + +fn asset_for(manifest: &serde_json::Value, kind: Kind) -> Option { + let platforms = manifest.get("platforms")?; + keys_for(kind).iter().find_map(|key| { + let p = platforms.get(key)?; + Some(Asset { + url: p.get("url")?.as_str()?.to_string(), + check: Check::Minisign(p.get("signature")?.as_str()?.to_string()), + }) + }) +} + +/// Whether the running copy can be replaced in place. +pub fn supported() -> bool { + kind().is_some() +} + +fn kind() -> Option { + target().map(|(kind, _)| kind) +} + +/// The store that installed this copy, by its own name, when it can open Vector's page: a copy +/// a store signed only ever updates from that store. Previews never come from one. +pub fn store() -> Option { + #[cfg(target_os = "android")] + { + static STORE: std::sync::OnceLock> = std::sync::OnceLock::new(); + STORE + .get_or_init(|| { + use crate::android::updates as up; + if super::updates::Version::current().preview.is_some() { + return None; + } + let pkg = up::get_installer_package().ok().flatten()?; + if !up::resolves_market_link(&pkg).unwrap_or(false) { + return None; + } + Some(match pkg.as_str() { + "com.android.vending" => "Google Play".to_string(), // i18n-exempt: brand + _ => up::get_app_label(&pkg) + .ok() + .flatten() + .unwrap_or_else(|| crate::t::settings_update_your_store().to_string()), + }) + }) + .clone() + } + #[cfg(not(target_os = "android"))] + None +} + +/// Vector's page in the store that installed this copy, on its own Update control; `false` when +/// the store can't take it. +pub fn open_store() -> bool { + #[cfg(target_os = "android")] + { + use crate::android::updates as up; + let Ok(Some(pkg)) = up::get_installer_package() else { return false }; + up::open_url_in_app(&pkg, "market://details?id=io.vectorapp").unwrap_or(false) // i18n-exempt: URI + } + #[cfg(not(target_os = "android"))] + false +} + +/// What the update replaces: the `.app` bundle, the AppImage, or the install folder. +fn target() -> Option<(Kind, PathBuf)> { + if cfg!(target_os = "android") { + // A sideload carries the release key, so the next release installs over it. + let sideload = !cfg!(feature = "fdroid") && store().is_none(); + return sideload.then(|| (Kind::Apk, std::env::temp_dir())); + } + let exe = std::env::current_exe().ok()?; + if cfg!(target_os = "macos") { + return exe.ancestors().find(|p| p.extension().is_some_and(|e| e == "app")).map(|p| (Kind::App, p.to_path_buf())); + } + if cfg!(target_os = "linux") { + if let Some(image) = std::env::var_os("APPIMAGE").map(PathBuf::from).filter(|p| p.is_file()) { + return Some((Kind::AppImage, image)); + } + return linux_package(&exe).map(|kind| (kind, exe)); + } + let dir = exe.parent()?.to_path_buf(); + // The NSIS installer leaves its uninstaller beside the exe; the MSI installs per machine. + if dir.join("uninstall.exe").is_file() { + return Some((Kind::Nsis, dir)); + } + let under = ["ProgramW6432", "ProgramFiles"].iter().filter_map(std::env::var_os).any(|p| dir.starts_with(p)); + under.then_some((Kind::Msi, dir)) +} + +/// Which package manager owns `exe`, when one of the `vector` packages put it there. +fn linux_package(exe: &Path) -> Option { + if !exe.starts_with("/usr") { + return None; + } + let listed = std::fs::read_to_string("/var/lib/dpkg/info/vector.list") + .is_ok_and(|list| list.lines().any(|line| Path::new(line) == exe)); + if listed { + return Some(Kind::Deb); + } + let owned = std::process::Command::new("rpm") + .args(["-qf", "--quiet"]) + .arg(exe) + .stdout(std::process::Stdio::null()) + .stderr(std::process::Stdio::null()) + .status() + .is_ok_and(|s| s.success()); + owned.then_some(Kind::Rpm) +} + +fn verify(bytes: &[u8], signature: &str) -> Result<(), String> { + verify_with(PUBKEY, bytes, signature) +} + +fn verify_with(pubkey: &str, bytes: &[u8], signature: &str) -> Result<(), String> { + use base64::Engine; + let b64 = base64::engine::general_purpose::STANDARD; + let text = |s: &str| { + b64.decode(s.trim()).ok().and_then(|b| String::from_utf8(b).ok()).ok_or_else(|| crate::t::settings_update_bad_signature().to_string()) + }; + let key = minisign_verify::PublicKey::decode(&text(pubkey)?).map_err(|_| crate::t::settings_update_bad_key().to_string())?; + let sig = minisign_verify::Signature::decode(&text(signature)?).map_err(|_| crate::t::settings_update_bad_signature().to_string())?; + key.verify(bytes, &sig, false).map_err(|_| crate::t::settings_update_signature_mismatch().to_string()) +} + +/// Download and verify the bundle, reporting `(received, total)`; the checked file's path. +pub async fn download(asset: Asset, progress: impl Fn(u64, u64)) -> Result { + let client = vector_core::net::build_http_client_with_options(None, Some(vector_core::net::transfer_stall()), true)?; + let mut resp = client.get(&asset.url).send().await.map_err(|e| crate::t::settings_update_download_failed(e.to_string()).to_string())?; + if !resp.status().is_success() { + return Err(crate::t::settings_update_download_http(resp.status().to_string()).to_string()); + } + let total = resp.content_length().unwrap_or(0); + let name = asset.url.rsplit('/').next().filter(|n| !n.is_empty()).unwrap_or("update").to_string(); + let dir = std::env::temp_dir().join("io.vectorapp.gpui-update"); + std::fs::create_dir_all(&dir).map_err(|e| crate::t::settings_update_folder_failed(e.to_string()).to_string())?; + let path = dir.join(name); + let file_failed = |e: std::io::Error| crate::t::settings_update_file_failed(e.to_string()).to_string(); + // A minisign check needs the whole bundle; an APK streams to a part file, never handed on + // half written. + let part = path.with_extension("part"); + let (mut bytes, mut file) = match asset.check { + Check::Minisign(_) => (Vec::with_capacity(total as usize), None), + Check::SigningCertificate => (Vec::new(), Some(std::fs::File::create(&part).map_err(file_failed)?)), + }; + let (mut got, mut shown) = (0u64, 0u64); + while let Some(chunk) = resp.chunk().await.map_err(|e| crate::t::settings_update_download_interrupted(e.to_string()).to_string())? { + match file.as_mut() { + Some(f) => std::io::Write::write_all(f, &chunk).map_err(file_failed)?, + None => bytes.extend_from_slice(&chunk), + } + got += chunk.len() as u64; + if got - shown >= 256 * 1024 || got == total { + shown = got; + progress(got, total); + } + } + match (&asset.check, file) { + (Check::Minisign(signature), _) => { + verify(&bytes, signature)?; + std::fs::write(&path, &bytes).map_err(file_failed)?; + } + (Check::SigningCertificate, Some(f)) => { + f.sync_all().map_err(file_failed)?; + drop(f); + std::fs::rename(&part, &path).map_err(file_failed)?; + } + (Check::SigningCertificate, None) => unreachable!(), + } + Ok(path) +} + +/// Put the verified bundle in place. On Windows the installer takes over and the app must quit. +pub fn install(bundle: &Path) -> Result { + let (kind, target) = target().ok_or_else(|| crate::t::settings_update_manual().to_string())?; + match kind { + Kind::Deb => install_package(bundle, &target, "dpkg", "-i"), + Kind::Rpm => install_package(bundle, &target, "rpm", "-U"), + Kind::Msi => install_msi(bundle), + Kind::App | Kind::AppImage | Kind::Nsis => install_at(bundle, &target), + Kind::Apk => return install_apk(bundle).map(Installed::Handed), + } + .map(|()| Installed::Restart) +} + +/// The system installer, once the APK's signing certificate matches this copy's. +#[cfg(all(target_os = "android", not(feature = "fdroid")))] +fn install_apk(apk: &Path) -> Result { + let status = crate::android::updates::install_update(&apk.to_string_lossy())?; + match status.as_str() { + "ok" => Ok(crate::t::settings_update_confirm_install().into()), + "needs-permission" => Ok(crate::t::settings_update_allow_installs().into()), + "signature-mismatch" => { + let _ = std::fs::remove_file(apk); + Err(crate::t::settings_update_other_key().into()) + } + "unverifiable" => { + let _ = std::fs::remove_file(apk); + Err(crate::t::settings_update_unverifiable().into()) + } + other => Err(crate::t::settings_update_install_failed(other).into()), + } +} + +#[cfg(not(all(target_os = "android", not(feature = "fdroid"))))] +fn install_apk(_: &Path) -> Result { + Err(crate::t::settings_update_unsupported().into()) +} + +/// The package manager runs as root once this process has gone, through polkit's prompt, then +/// starts the app again whether or not it took the update. +fn install_package(bundle: &Path, exe: &Path, tool: &str, arg: &str) -> Result<(), String> { + std::process::Command::new("/bin/sh") + .arg("-c") + .arg(format!("while kill -0 {} 2>/dev/null; do sleep 0.2; done; pkexec {tool} {arg} \"$1\"; rm -f \"$1\"; exec \"$2\"", std::process::id())) // i18n-exempt: shell + .arg("vector-update") + .arg(bundle) + .arg(exe) + .spawn() + .map(|_| ()) + .map_err(|e| crate::t::settings_update_installer_failed(e.to_string()).to_string()) +} + +/// msiexec waits for this process to let go of its files; AUTOLAUNCHAPP starts the app after. +fn install_msi(bundle: &Path) -> Result<(), String> { + std::process::Command::new("msiexec.exe") + .arg("/i") + .arg(bundle) + .args(["/passive", "AUTOLAUNCHAPP=True"]) // i18n-exempt: msiexec property + .spawn() + .map(|_| ()) + .map_err(|e| crate::t::settings_update_installer_failed(e.to_string()).to_string()) +} + +#[cfg(target_os = "linux")] +fn install_at(bundle: &Path, appimage: &Path) -> Result<(), String> { + use std::os::unix::fs::PermissionsExt; + let staged = appimage.with_extension("update"); + std::fs::copy(bundle, &staged).map_err(|e| crate::t::settings_update_stage_failed(e.to_string()).to_string())?; + std::fs::set_permissions(&staged, std::fs::Permissions::from_mode(0o755)).map_err(|e| e.to_string())?; + std::fs::rename(&staged, appimage).map_err(|e| crate::t::settings_update_replace_failed(e.to_string()).to_string())?; + let _ = std::fs::remove_file(bundle); + Ok(()) +} + +#[cfg(target_os = "macos")] +fn install_at(bundle: &Path, app: &Path) -> Result<(), String> { + let parent = app.parent().ok_or_else(|| crate::t::settings_update_no_folder().to_string())?; + let staging = parent.join(".vector-update"); + let _ = std::fs::remove_dir_all(&staging); + std::fs::create_dir_all(&staging).map_err(|e| crate::t::settings_update_stage_failed(e.to_string()).to_string())?; + let file = std::fs::File::open(bundle).map_err(|e| e.to_string())?; + tar::Archive::new(flate2::read::GzDecoder::new(file)) + .unpack(&staging) + .map_err(|e| crate::t::settings_update_unpack_failed(e.to_string()).to_string())?; + let fresh = std::fs::read_dir(&staging) + .map_err(|e| e.to_string())? + .filter_map(Result::ok) + .map(|e| e.path()) + .find(|p| p.extension().is_some_and(|e| e == "app")) + .ok_or_else(|| crate::t::settings_update_empty().to_string())?; + // Swapped by rename, so a failure part way leaves the old app where it was. + let old = staging.join("previous.app"); + std::fs::rename(app, &old).map_err(|e| crate::t::settings_update_replace_failed(e.to_string()).to_string())?; + if let Err(e) = std::fs::rename(&fresh, app) { + let _ = std::fs::rename(&old, app); + return Err(crate::t::settings_update_replace_failed(e.to_string()).to_string()); + } + let _ = std::fs::remove_dir_all(&staging); + let _ = std::fs::remove_file(bundle); + Ok(()) +} + +#[cfg(windows)] +fn install_at(bundle: &Path, dir: &Path) -> Result<(), String> { + // NSIS (scripts/installer.nsi): no pages, start the app again when done, into this copy's + // folder. `/D=` must come last and unquoted. + std::process::Command::new(bundle) + .args(["/P".into(), "/R".into(), format!("/D={}", dir.display())]) + .spawn() + .map(|_| ()) + .map_err(|e| crate::t::settings_update_installer_failed(e.to_string()).to_string()) +} + +#[cfg(not(any(target_os = "linux", target_os = "macos", windows)))] +fn install_at(_: &Path, _: &Path) -> Result<(), String> { + Err(crate::t::settings_update_unsupported().into()) +} + +/// Start the installed copy once this process has gone, so it isn't handed back to us as a +/// second instance. Installers and package managers start it themselves. +pub fn relaunch() -> Result<(), String> { + #[cfg(unix)] + { + let (kind, target) = target().ok_or_else(|| crate::t::settings_update_nothing_to_start().to_string())?; + if !matches!(kind, Kind::App | Kind::AppImage) { + return Ok(()); + } + // i18n-exempt: shell + let start = if cfg!(target_os = "macos") { "open -n \"$1\"" } else { "exec \"$1\"" }; + std::process::Command::new("/bin/sh") + .arg("-c") + .arg(format!("while kill -0 {} 2>/dev/null; do sleep 0.2; done; {start}", std::process::id())) // i18n-exempt: shell + .arg("vector-relaunch") + .arg(target) + .spawn() + .map(|_| ()) + .map_err(|e| e.to_string()) + } + #[cfg(not(unix))] + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_release_key_decodes() { + use base64::Engine; + let text = String::from_utf8(base64::engine::general_purpose::STANDARD.decode(PUBKEY).unwrap()).unwrap(); + assert!(minisign_verify::PublicKey::decode(&text).is_ok()); + } + + const TEST_KEY: &str = "dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IHRlc3QKUldRQkFnTUVCUVlIQ0FPaEI3L3p6aEMrSFhEZEdPZEx3SmxuNU5Zd202VU5YeDNjaG1RU1ZURzQK"; + const TEST_SIG: &str = "dW50cnVzdGVkIGNvbW1lbnQ6IHNpZ25hdHVyZSBmcm9tIHRhdXJpIHNlY3JldCBrZXkKUlVRQkFnTUVCUVlIQ0hxcStvenNSbDhVTG5LMGN0Q3ZJYnFPNXFrd3BMcGt6TmJTRW9CZE1YV0JDMnNYWlFIODVBbkg3RWlOUlFqbzNMMEVnNkZQaWNvMHRPeTFkOGxjcWdrPQp0cnVzdGVkIGNvbW1lbnQ6IHRpbWVzdGFtcDowCWZpbGU6YnVuZGxlCnZwSzJNcU9hQ1QrUFcvTUpvNjhIbkJXKzB4RHdaNXFCM0I3anl6aWpJUlhxSDZWTEtwY0ZpbEFBWFNKaWZ0aXZ4QkVrUFlYQ0pTM1c2V21maUVSR0NBPT0K"; + + #[test] + fn a_signed_bundle_verifies_and_a_changed_one_does_not() { + assert!(verify_with(TEST_KEY, b"vector update bundle", TEST_SIG).is_ok()); + assert!(verify_with(TEST_KEY, b"vector update bundle!", TEST_SIG).is_err()); + // Signed by another key than the release's. + assert!(verify(b"vector update bundle", TEST_SIG).is_err()); + } + + #[test] + fn a_bad_signature_is_refused() { + use base64::Engine; + let sig = "untrusted comment: signature\nRUTk69fh9IfuQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=\ntrusted comment: x\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n"; + let b64 = base64::engine::general_purpose::STANDARD.encode(sig); + assert!(verify(b"bundle", &b64).is_err()); + assert!(verify(b"bundle", "not base64!").is_err()); + } + + #[cfg(target_os = "linux")] + #[test] + fn an_appimage_is_replaced_whole_and_left_runnable() { + use std::os::unix::fs::PermissionsExt; + let dir = std::env::temp_dir().join(format!("vector-install-test-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let (app, bundle) = (dir.join("Vector.AppImage"), dir.join("new.AppImage")); + std::fs::write(&app, b"old").unwrap(); + std::fs::write(&bundle, b"new").unwrap(); + install_at(&bundle, &app).unwrap(); + assert_eq!(std::fs::read(&app).unwrap(), b"new"); + assert_eq!(std::fs::metadata(&app).unwrap().permissions().mode() & 0o777, 0o755); + assert!(!bundle.exists() && !app.with_extension("update").exists()); + std::fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn each_install_takes_the_bundle_of_its_own_kind() { + let base = format!("{}-{}", if cfg!(target_os = "macos") { "darwin" } else { std::env::consts::OS }, std::env::consts::ARCH); + let entry = |name: &str| serde_json::json!({"url": format!("https://x/{name}"), "signature": "c2ln"}); + let m = serde_json::json!({"platforms": { + base.clone(): entry("bare"), + format!("{base}-appimage"): entry("appimage"), + format!("{base}-deb"): entry("deb"), + format!("{base}-msi"): entry("msi"), + format!("{base}-gpui"): entry("gpui"), + }}); + let url = |kind| asset_for(&m, kind).map(|a| a.url); + assert_eq!(url(Kind::AppImage).as_deref(), Some("https://x/appimage")); + assert_eq!(url(Kind::Deb).as_deref(), Some("https://x/deb")); + assert_eq!(url(Kind::Msi).as_deref(), Some("https://x/msi")); + // A 0.5 manifest has only the test builds' entry. + assert_eq!(url(Kind::Nsis).as_deref(), Some("https://x/gpui")); + // Never another kind's bundle, nor the bare entry older clients read. + assert_eq!(url(Kind::Rpm), None); + } +} diff --git a/crates/vector-gpui/src/backend/langpacks.rs b/crates/vector-gpui/src/backend/langpacks.rs new file mode 100644 index 000000000..382ee42d4 --- /dev/null +++ b/crates/vector-gpui/src/backend/langpacks.rs @@ -0,0 +1,344 @@ +//! Downloadable languages: the index Vector's key signs, and the packs it pins by hash. Both are +//! fetched on the shared lane, so a download says which language, never whose device, and both +//! are kept per device beside its settings. + +use std::collections::HashMap; +use std::path::PathBuf; +use std::sync::atomic::{AtomicU32, Ordering}; +use std::sync::{Arc, Mutex, OnceLock, RwLock}; + +use nostr_sdk::prelude::{Event, Kind, PublicKey}; +use vector_i18n::index::{D_TAG, Entry, Index, KIND}; + +/// The key this build trusts first. A throwaway test key until the real one is made: see +/// "Publishing" in crates/vector-i18n/TRANSLATING.md. +const SIGNER: &str = "f4ee7a33d3d5335c6c020122901570c269ecf95a6345778a351c4c4473c33c94"; +const INDEX_URL: &str = "https://github.com/VectorPrivacy/Vector/releases/download/languages/index.json"; +/// Packs by hash, after the Blossom servers. +const MIRROR: &str = "https://github.com/VectorPrivacy/Vector/releases/download/languages"; +const MAX_INDEX: usize = 512 << 10; +/// Successive keys followed in one fetch. +const MAX_HOPS: usize = 4; +const DAY_SECS: u64 = 24 * 60 * 60; +/// A successor the pinned key handed over to. +const SIGNER_KEY: &str = "language_signer"; +const CHECKED_KEY: &str = "language_checked"; +const INDEX_FILE: &str = "index.json"; + +static DIR: OnceLock = OnceLock::new(); +static INDEX: RwLock> = RwLock::new(None); +/// Each installed pack's hash, by tag, to tell when the index has a newer one. +static INSTALLED: Mutex>> = Mutex::new(None); +static UPDATING: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + +/// One round of background updates at a time. +pub fn begin_updates() -> bool { + !UPDATING.swap(true, Ordering::AcqRel) +} + +pub fn end_updates() { + UPDATING.store(false, Ordering::Release); +} + +#[derive(Clone)] +struct Cached { + index: Arc, + /// The signed event's `created_at`: an older index is never taken over it. + at: u64, +} + +fn now() -> u64 { + vector_core::clock::now_secs() +} + +fn sha256_hex(bytes: &[u8]) -> String { + vector_core::crypto::sha256_hex(bytes) +} + +fn trusted() -> PublicKey { + super::device::get(SIGNER_KEY) + .and_then(|k| PublicKey::from_hex(&k).ok()) + .unwrap_or_else(|| PublicKey::from_hex(SIGNER).expect("the pinned key is a key")) +} + +/// The packs folder, and the index cached there. Fixtures have no folder: a devctl build reads +/// an unsigned index from `VECTOR_LANG_INDEX` so the Language page can be shown. +pub fn init(dir: Option) { + let Some(dir) = dir else { + #[cfg(feature = "devctl")] + if let Some(index) = std::env::var_os("VECTOR_LANG_INDEX") + .and_then(|p| std::fs::read_to_string(p).ok()) + .and_then(|s| Index::parse(&s).ok()) + { + *INDEX.write().unwrap_or_else(|e| e.into_inner()) = Some(Cached { index: Arc::new(index), at: 0 }); + } + return; + }; + if let Some((index, at, _)) = std::fs::read_to_string(dir.join(INDEX_FILE)).ok().and_then(|raw| verify(&raw, &trusted()).ok()) { + *INDEX.write().unwrap_or_else(|e| e.into_inner()) = Some(Cached { index: Arc::new(index), at }); + } + let _ = DIR.set(dir); +} + +/// A pack read from disk or just downloaded. +pub fn note_installed(tag: &str, bytes: &[u8]) { + INSTALLED.lock().unwrap_or_else(|e| e.into_inner()).get_or_insert_with(HashMap::new).insert(tag.to_string(), sha256_hex(bytes)); +} + +fn any_installed() -> bool { + INSTALLED.lock().unwrap_or_else(|e| e.into_inner()).as_ref().is_some_and(|m| !m.is_empty()) +} + +/// The newest index this device holds. +pub fn index() -> Option> { + INDEX.read().unwrap_or_else(|e| e.into_inner()).as_ref().map(|c| c.index.clone()) +} + +/// Whether a background check is worth its network contact: a pack is installed and a day has +/// passed. A device that never chose a language never asks. +pub fn due() -> bool { + DIR.get().is_some() + && any_installed() + && super::device::get(CHECKED_KEY).and_then(|s| s.parse::().ok()).is_none_or(|at| now().saturating_sub(at) >= DAY_SECS) +} + +/// Whether the index was fetched within `secs`. +pub fn fresh(secs: u64) -> bool { + index().is_some() && super::device::get(CHECKED_KEY).and_then(|s| s.parse::().ok()).is_some_and(|at| now().saturating_sub(at) < secs) +} + +/// The packs installed here that the index has a newer build of. +pub fn updates() -> Vec { + let Some(index) = index() else { return vec![] }; + let installed = INSTALLED.lock().unwrap_or_else(|e| e.into_inner()); + let Some(installed) = installed.as_ref() else { return vec![] }; + index.usable().filter(|e| installed.get(&e.tag).is_some_and(|sha| *sha != e.sha256)).cloned().collect() +} + +/// The index in `raw` (a JSON array of events) that `trusted` vouches for, following each +/// handover to the newest key: `(index, created_at, the key that signed it)`. +fn verify(raw: &str, trusted: &PublicKey) -> Result<(Index, u64, PublicKey), String> { + let invalid = || crate::t::language_index_invalid().to_string(); + let values: Vec = serde_json::from_str(raw).map_err(|_| invalid())?; + let events: Vec = values.iter().filter_map(|v| vector_core::event_json::event(&v.to_string()).ok()).collect(); + let mut key = *trusted; + let mut best = None; + for _ in 0..MAX_HOPS { + let Some(ev) = events + .iter() + .filter(|e| e.pubkey == key && e.kind == Kind::Custom(KIND) && e.tags.identifier().as_deref() == Some(D_TAG)) + .filter(|e| e.verify().is_ok()) + .max_by_key(|e| e.created_at) + else { + break; + }; + let index = Index::parse(&ev.content).map_err(|_| invalid())?; + let next = index.next.as_deref().and_then(|n| PublicKey::from_hex(n).ok()).filter(|n| *n != key); + best = Some((index, ev.created_at.as_secs(), key)); + match next { + Some(n) => key = n, + None => break, + } + } + best.ok_or_else(|| crate::t::language_index_unsigned().to_string()) +} + +/// Fetches the index, keeping the one held when the fetched one is older. The release is asked +/// first; Vector's relays carry the same signed events for networks that can't reach it. +pub async fn refresh() -> Result, String> { + let dir = DIR.get().ok_or_else(|| crate::t::language_pack_unsaved().to_string())?.clone(); + let trusted = trusted(); + let fetched = match from_release().await.and_then(|raw| verify(&raw, &trusted).map(|v| (v, raw))) { + Ok(v) => v, + Err(e) => { + vector_core::log_debug!("[Languages] release: {e}; asking relays"); + from_relays(trusted).await.and_then(|raw| verify(&raw, &trusted).map(|v| (v, raw))).map_err(|_| e)? + } + }; + let ((index, at, signer), raw) = fetched; + super::device::set(CHECKED_KEY, now().to_string()); + let mut held = INDEX.write().unwrap_or_else(|e| e.into_inner()); + if let Some(c) = held.as_ref().filter(|c| c.at > at) { + return Ok(c.index.clone()); + } + if signer != trusted { + super::device::set(SIGNER_KEY, signer.to_hex()); + } + write_atomic(&dir.join(INDEX_FILE), raw.as_bytes()); + let index = Arc::new(index); + *held = Some(Cached { index: index.clone(), at }); + Ok(index) +} + +async fn from_release() -> Result { + let client = vector_core::net::shared_http_client(); + let mut resp = client.get(INDEX_URL).send().await.map_err(|e| e.to_string())?; + if !resp.status().is_success() { + return Err(crate::t::language_index_status(resp.status().as_u16()).to_string()); + } + let mut body = Vec::new(); + while let Some(chunk) = resp.chunk().await.map_err(|e| e.to_string())? { + if body.len() + chunk.len() > MAX_INDEX { + return Err(crate::t::language_index_invalid().to_string()); + } + body.extend_from_slice(&chunk); + } + String::from_utf8(body).map_err(|_| crate::t::language_index_invalid().to_string()) +} + +/// The newest index event of `trusted` and of each successor it names, from Vector's relays, +/// in the release's shape. A scratch client: no account, no authenticator. +async fn from_relays(trusted: PublicKey) -> Result { + use nostr_sdk::prelude::{ClientBuilder, Filter}; + use vector_core::ClientRelayExt as _; + let client = vector_core::apply_transport(ClientBuilder::new(), vector_core::transport::Lane::Shared).build(); + for url in vector_core::state::TRUSTED_RELAYS { + let _ = client.add_managed_relay(*url).await; + } + client.connect().await; + let timeout = vector_core::relay_request_timeout(std::time::Duration::from_secs(8)); + let mut events = vec![]; + let mut key = trusted; + for _ in 0..MAX_HOPS { + let filter = Filter::new().kind(Kind::Custom(KIND)).author(key).identifier(D_TAG); + let Ok(got) = client.fetch_events(filter).timeout(timeout).await else { break }; + let Some(ev) = got.into_iter().filter(|e| e.verify().is_ok()).max_by_key(|e| e.created_at) else { break }; + let next = Index::parse(&ev.content).ok().and_then(|i| i.next).and_then(|n| PublicKey::from_hex(&n).ok()).filter(|n| *n != key); + events.push(serde_json::from_str::(&ev.as_json()).map_err(|e| e.to_string())?); + match next { + Some(n) => key = n, + None => break, + } + } + client.shutdown().await; + if events.is_empty() { + return Err(crate::t::language_index_unsigned().to_string()); + } + Ok(serde_json::Value::Array(events).to_string()) +} + +fn write_atomic(path: &std::path::Path, bytes: &[u8]) -> bool { + let tmp = path.with_extension("part"); + let ok = std::fs::create_dir_all(path.parent().unwrap_or(path)).is_ok() && std::fs::write(&tmp, bytes).is_ok() && std::fs::rename(&tmp, path).is_ok(); + if !ok { + let _ = std::fs::remove_file(&tmp); + } + ok +} + +/// Fetches `entry` from the first source that has it, checks it against the index's hash and +/// size, and keeps it. `progress` runs 0 to 1000 as it arrives. +pub async fn download(entry: Entry, progress: Arc) -> Result { + let dir = DIR.get().ok_or_else(|| crate::t::language_pack_unsaved().to_string())?.clone(); + let sources = vector_core::blossom_servers::DEFAULT_BLOSSOM_SERVERS + .iter() + .map(|s| format!("{}/{}", s.trim_end_matches('/'), entry.sha256)) + .chain([format!("{MIRROR}/{}.vpack", entry.sha256)]); + let mut last = String::new(); + for url in sources { + progress.store(0, Ordering::Relaxed); + match fetch(&url, &entry, &progress).await { + Ok(bytes) => { + let pack = vector_i18n::Pack::from_bytes(&bytes)?; + if pack.tag != entry.tag { + return Err(crate::t::language_pack_mismatch().to_string()); + } + if !write_atomic(&crate::lang::pack_path(&dir, &entry.tag), &bytes) { + return Err(crate::t::language_pack_unsaved().to_string()); + } + note_installed(&entry.tag, &bytes); + return Ok(pack); + } + Err(e) => { + vector_core::log_debug!("[Languages] {url}: {e}"); + last = e; + } + } + } + Err(last) +} + +async fn fetch(url: &str, entry: &Entry, progress: &AtomicU32) -> Result, String> { + let client = vector_core::net::build_http_client_with_options(None, Some(vector_core::net::transfer_stall()), true)?; + let mut resp = client.get(url).send().await.map_err(|e| e.to_string())?; + if !resp.status().is_success() { + return Err(resp.status().to_string()); + } + let size = entry.size.max(1); + let mut body = Vec::with_capacity(entry.size.min(4 << 20) as usize); + while let Some(chunk) = resp.chunk().await.map_err(|e| e.to_string())? { + if (body.len() + chunk.len()) as u64 > entry.size { + return Err(crate::t::language_pack_mismatch().to_string()); + } + body.extend_from_slice(&chunk); + progress.store((body.len() as u64 * 1000 / size) as u32, Ordering::Relaxed); + } + if body.len() as u64 != entry.size || sha256_hex(&body) != entry.sha256 { + return Err(crate::t::language_pack_mismatch().to_string()); + } + Ok(body) +} + +#[cfg(test)] +mod tests { + use super::*; + use nostr_sdk::prelude::{EventBuilder, FinalizeEvent as _, Keys, Tag}; + + fn signed(keys: &Keys, index: &Index, at: u64) -> serde_json::Value { + let ev = EventBuilder::new(Kind::Custom(KIND), index.to_json()) + .tag(Tag::identifier(D_TAG)) + .custom_created_at(nostr_sdk::prelude::Timestamp::from_secs(at)) + .finalize(keys) + .unwrap(); + serde_json::from_str(&ev.as_json()).unwrap() + } + + fn index(tag: &str) -> Index { + Index { + format: vector_i18n::index::INDEX_FORMAT, + packs: vec![Entry { + tag: tag.into(), + name: tag.into(), + english_name: tag.into(), + rtl: false, + coverage: 100, + format: 1, + size: 1, + sha256: "0".repeat(64), + english: String::new(), + }], + next: None, + } + } + + #[test] + fn only_the_trusted_key_and_its_successors_are_believed() { + let (pinned, next, stranger) = (Keys::generate(), Keys::generate(), Keys::generate()); + let raw = |v: Vec| serde_json::to_string(&v).unwrap(); + + let (i, at, by) = verify(&raw(vec![signed(&pinned, &index("es"), 10)]), &pinned.public_key()).unwrap(); + assert_eq!((i.packs[0].tag.as_str(), at, by), ("es", 10, pinned.public_key())); + + assert!(verify(&raw(vec![signed(&stranger, &index("es"), 10)]), &pinned.public_key()).is_err(), "anyone else's index is ignored"); + + let mut forged = signed(&pinned, &index("es"), 10); + forged["content"] = index("de").to_json().into(); + assert!(verify(&raw(vec![forged]), &pinned.public_key()).is_err(), "a changed index fails its signature"); + + let handover = Index { next: Some(next.public_key().to_hex()), ..index("es") }; + let both = raw(vec![signed(&pinned, &handover, 10), signed(&next, &index("fr"), 11)]); + let (i, _, by) = verify(&both, &pinned.public_key()).unwrap(); + assert_eq!((i.packs[0].tag.as_str(), by), ("fr", next.public_key()), "a handover moves to the successor's index"); + + let alone = raw(vec![signed(&pinned, &handover, 10)]); + assert_eq!(verify(&alone, &pinned.public_key()).unwrap().2, pinned.public_key(), "until the successor signs one, the handover itself stands"); + + let newer = raw(vec![signed(&pinned, &index("es"), 10), signed(&pinned, &index("de"), 20)]); + assert_eq!(verify(&newer, &pinned.public_key()).unwrap().0.packs[0].tag, "de", "the newest of a key's indexes"); + } + + #[test] + fn the_pinned_key_parses() { + assert!(PublicKey::from_hex(SIGNER).is_ok()); + } +} diff --git a/crates/vector-gpui/src/backend/market.rs b/crates/vector-gpui/src/backend/market.rs new file mode 100644 index 000000000..e7a330367 --- /dev/null +++ b/crates/vector-gpui/src/backend/market.rs @@ -0,0 +1,255 @@ +//! The Nexus over the desktop's marketplace core: the catalogue, installs, updates and plays. + +use vector_media::miniapps::marketplace::{self as mk, MARKETPLACE_STATE}; + +pub use mk::MarketplaceApp; + +fn handle() -> Result { + vector_media::TAURI_APP.get().copied().ok_or_else(|| crate::t::miniapp_store_not_ready().to_string()) +} + +/// Tags are relay data: one spelling of each, so every page and count agrees. Names show on one line. +fn tidy(mut apps: Vec) -> Vec { + for app in &mut apps { + if let std::borrow::Cow::Owned(name) = crate::kit::one_line(&app.name) { + app.name = name; + } + let mut seen = Vec::with_capacity(app.categories.len()); + for c in &app.categories { + let c = c.trim().to_lowercase(); + if !c.is_empty() && !seen.contains(&c) { + seen.push(c); + } + } + app.categories = seen; + } + apps +} + +/// One listing as the catalogue holds it now, for a caller that can't wait on it. +pub fn find(id: &str) -> Option { + let app = MARKETPLACE_STATE.try_read().ok()?.get_app(id).cloned()?; + tidy(vec![app]).pop() +} + +/// Every listing's id and whether it's installed, for the start menu's search. +pub fn ids() -> Vec<(String, String, bool)> { + MARKETPLACE_STATE + .try_read() + .map(|s| s.get_apps().into_iter().map(|a| (a.id, crate::kit::one_line(&a.name).into_owned(), a.installed || a.local_path.is_some())).collect()) + .unwrap_or_default() +} + +pub async fn cached() -> Vec { + tidy(MARKETPLACE_STATE.read().await.get_apps()) +} + +/// `initMarketplace`'s network leg: fetch, read install status off disk, then the merged list. +pub async fn refresh() -> Result, String> { + mk::fetch_marketplace_apps(true).await?; + mk::sync_install_status_from_disk(&handle()?).await; + Ok(cached().await) +} + +/// Installs are shared by every account: clearing the Apps slice uninstalls them, unless saved. +pub async fn sweep_installs() { + use tauri::Manager; + let Ok(h) = handle() else { return }; + if let Ok(root) = h.path().app_data_dir() { + for e in std::fs::read_dir(root.join("miniapps").join("marketplace")).into_iter().flatten().flatten() { + let name = e.file_name().to_string_lossy().into_owned(); + let file = e.metadata().is_ok_and(|m| m.is_file()); + if file && !name.starts_with('.') && name.to_lowercase().ends_with(".xdc") && !vector_core::db::saved::is_saved(&e.path().to_string_lossy()).unwrap_or(true) { + let _ = std::fs::remove_file(e.path()); + } + } + } + mk::sync_install_status_from_disk(&h).await; +} + +pub async fn install(id: String) -> Result { + mk::install_marketplace_app(&handle()?, &id).await +} + +pub async fn update(id: String) -> Result { + mk::update_marketplace_app(&handle()?, &id).await +} + +pub async fn uninstall(id: String, name: String) -> Result<(), String> { + mk::uninstall_marketplace_app(&handle()?, &id, &name).await +} + +/// `marketplace_open_app`: install when missing, then play it alone. +pub async fn open(id: String) -> Result<(), String> { + let h = handle()?; + let path = match mk::check_app_installed(&h, &id).await { + Some(p) => p, + None => mk::install_marketplace_app(&h, &id).await?, + }; + crate::miniapp::open(path, String::new(), String::new(), None, None).await +} + +pub async fn installed_path(id: String) -> Option { + mk::check_app_installed(&handle().ok()?, &id).await +} + +/// One play-history entry per Nexus app: `(id, last played ms, opens)`, newest first. +pub fn plays() -> Vec<(String, i64, i64)> { + let history = vector_core::db::miniapps::get_miniapps_history(None).unwrap_or_default(); + let mut seen: Vec<(String, i64, i64)> = Vec::new(); + for e in history { + let Some(id) = e.marketplace_id else { continue }; + let at = e.last_opened_at * 1000; + let count = e.open_count as i64; + match seen.iter_mut().find(|s| s.0 == id) { + Some(had) => { + had.2 += count; + had.1 = had.1.max(at); + } + None => seen.push((id, at, count)), + } + } + seen.sort_by(|a, b| b.1.cmp(&a.1)); + seen +} + +pub async fn preload() { + mk::preload_marketplace_cache().await; +} + +pub async fn reset() { + MARKETPLACE_STATE.write().await.clear_for_session_reset(); +} + +/// What a launch asks the permission prompt about. +pub enum Ask { + App(String), + File(String), +} + +/// A first launch's prompt: the bundle hash it's keyed by, and `(id, label, description)` rows. +pub struct Prompt { + pub hash: String, + pub name: String, + pub items: Vec<(String, String, String)>, +} + +/// `checkMiniAppPermissions` / `checkChatMiniAppPermissions`: a prompt only on an app's first +/// launch of this bundle, and only when it asks for anything. +pub async fn prompt_for(ask: Ask) -> Option { + let app = match ask { + Ask::App(id) => MARKETPLACE_STATE.read().await.get_app(&id).cloned()?, + Ask::File(path) => { + let hash = crate::miniapp::info(path).await.ok()?.hash; + if vector_core::db::miniapps::has_miniapp_permission_prompt(&hash).unwrap_or(true) { + return None; + } + MARKETPLACE_STATE.read().await.get_app_by_hash(&hash).cloned()? + } + }; + prompt_of(&app, |h| vector_core::db::miniapps::has_miniapp_permission_prompt(h).unwrap_or(true)) +} + +pub fn prompt_of(app: &MarketplaceApp, prompted: impl Fn(&str) -> bool) -> Option { + if app.requested_permissions.trim().is_empty() || app.blossom_hash.is_empty() || prompted(&app.blossom_hash) { + return None; + } + let items: Vec<_> = permission_rows(&app.requested_permissions, "") + .into_iter() + .map(|(id, label, sub, _)| (id, label, sub)) + .collect(); + Some(Prompt { hash: app.blossom_hash.clone(), name: app.name.clone(), items }) +} + +/// The requested permissions this build knows, in request order: `(id, label, description, granted)`. +pub fn permission_rows(requested: &str, granted: &str) -> Vec<(String, String, String, bool)> { + let known = vector_core::webxdc_permissions::get_all_permission_info(); + let granted: Vec<&str> = granted.split(',').filter(|s| !s.is_empty()).collect(); + requested + .split(',') + .map(str::trim) + .filter(|s| !s.is_empty()) + .filter_map(|id| { + let info = known.iter().find(|p| p.id == id)?; + let say = |s: &str| crate::coretext::say(s).into_owned(); + Some((id.to_string(), say(&info.label), say(&info.description), granted.contains(&id))) + }) + .collect() +} + +pub fn granted(hash: &str) -> Result { + vector_core::db::miniapps::get_miniapp_granted_permissions(hash) +} + +pub fn set_permissions(hash: &str, perms: &[(String, bool)]) -> Result<(), String> { + let refs: Vec<(&str, bool)> = perms.iter().map(|(p, g)| (p.as_str(), *g)).collect(); + vector_core::db::miniapps::set_miniapp_permissions(hash, &refs) +} + +pub fn set_permission(hash: &str, perm: &str, granted: bool) -> Result<(), String> { + vector_core::db::miniapps::set_miniapp_permission(hash, perm, granted) +} + +pub fn revoke_permissions(hash: &str) -> Result<(), String> { + vector_core::db::miniapps::revoke_all_miniapp_permissions(hash) +} + +/// The publish form's fields, owned so they cross into the backend. +pub struct Listing { + pub id: String, + pub name: String, + pub description: String, + pub version: String, + pub categories: Vec, + pub changelog: Option, + pub developer: Option, + pub source: Option, + pub permissions: Option, +} + +impl Listing { + fn borrow<'a>(&'a self, version: &'a str) -> vector_core::webxdc::MarketplaceListing<'a> { + vector_core::webxdc::MarketplaceListing { + app_id: &self.id, + name: &self.name, + description: &self.description, + version: if version.is_empty() { &self.version } else { version }, + categories: self.categories.iter().map(String::as_str).collect(), + changelog: self.changelog.as_deref(), + developer: self.developer.as_deref(), + source_url: self.source.as_deref(), + permissions: self.permissions.as_deref(), + released_at: None, + } + } +} + +pub fn trusted_publisher() -> &'static str { + mk::TRUSTED_PUBLISHER +} + +/// `marketplace_publish_app`: upload the package, then sign its listing. +pub async fn publish(file: String, listing: Listing) -> Result { + let signer = vector_core::signer::active_signer().map_err(|e| format!("Failed to get signer: {e}"))?; // i18n-exempt: developer error + let servers = vector_core::state::get_blossom_servers(); + mk::publish_to_marketplace(signer, &file, &listing.borrow(""), servers).await +} + +/// `marketplace_edit_listing`: a new listing over the package it already names. +pub async fn edit_listing(listing: Listing) -> Result, String> { + let session = vector_core::db::current_session(); + let current = MARKETPLACE_STATE.read().await.get_app(&listing.id).cloned().ok_or_else(|| crate::t::miniapp_listing_not_found().to_string())?; + let edited = vector_core::webxdc::edit_marketplace_listing(¤t, &listing.borrow(¤t.version)).await?; + if !session.is_live() { + return Err(crate::t::miniapp_edit_account_changed().into()); + } + let apps = { + let mut state = MARKETPLACE_STATE.write().await; + state.upsert_app(edited); + state.get_apps() + }; + if let Err(e) = vector_core::db::miniapps::save_marketplace_cache(&apps) { + log::warn!("[Marketplace] Failed to cache the edited listing: {e}"); + } + Ok(tidy(apps)) +} diff --git a/crates/vector-gpui/src/backend/mediaport.rs b/crates/vector-gpui/src/backend/mediaport.rs new file mode 100644 index 000000000..108186d20 --- /dev/null +++ b/crates/vector-gpui/src/backend/mediaport.rs @@ -0,0 +1,392 @@ +//! Kept files over time: old downloads moved into Vector's store, or kept files written out +//! plain for an account that keeps them unencrypted. Paced, a file at a time, and each file is +//! whole in one place or the other, so a launch that cuts it short picks up on the next. + +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::time::Duration; + +use vector_core::STATE; +use vector_core::media::import::{self, Elsewhere, Moved, OnDisk}; + +static MOVING: AtomicBool = AtomicBool::new(false); +static STOP: AtomicBool = AtomicBool::new(false); + +/// Source bytes a second: slow enough to go unnoticed. +const RATE: f64 = 12.0 * 1024.0 * 1024.0; +/// Originals go a batch at a time, after the rows that replace them are synced. +const BATCH: usize = 32; + +fn pace(len: u64) -> Duration { + Duration::from_secs_f64(len as f64 / RATE).max(Duration::from_millis(150)) +} + +fn progress(done: usize, total: usize, plain: bool) { + vector_core::traits::emit_event( + "media_import_progress", + &serde_json::json!({ "done": done, "total": total, "plain": plain }), + ); +} + +/// After the boot paint: the store and the rows that point into it are checked, loaded messages +/// drop files that went missing while closed, stale outgoing work goes, and the port starts. +pub async fn after_boot() { + vector_core::media::store::check(); + settle_owed(import::settle).await; + vector_core::sending::sweep_outgoing(); + if let Ok(Ok(missing)) = vector_core::db::blocking_bound(missing_downloads).await { + reconcile_missing(&missing).await; + } + start(Duration::from_secs(60)); +} + +/// Rows whose file is gone, cleared in the database; returns their event ids. +fn missing_downloads() -> Result, String> { + let mut affected: Vec = Vec::new(); + for (event_id, hash, path) in vector_core::db::attachments::downloaded_attachment_paths()? { + let present = if path.is_empty() { + vector_core::simd::hex::hex_to_bytes_32_checked(&hash) + .is_some_and(|h| vector_core::media::store::holds(&h)) + } else { + Path::new(&path).exists() + }; + if !present { + let _ = vector_core::db::attachments::clear_attachment_download(&event_id, &hash); + if !affected.contains(&event_id) { + affected.push(event_id); + } + } + } + Ok(affected) +} + +async fn reconcile_missing(affected: &[String]) { + if affected.is_empty() { + return; + } + let affected: std::collections::HashSet<&str> = affected.iter().map(String::as_str).collect(); + let mut updates = Vec::new(); + { + let mut state = STATE.lock().await; + for ci in 0..state.chats.len() { + let mut ids = Vec::new(); + for m in state.chats[ci].messages.iter_mut() { + if m.attachments.is_empty() || !affected.contains(m.id_hex().as_str()) { + continue; + } + let mut changed = false; + for att in m.attachments.iter_mut().filter(|a| a.downloaded()) { + let present = if att.has_path() { + Path::new(&*att.path()).exists() + } else { + vector_core::media::store::holds(att.id()) + }; + if !present { + att.set_downloaded(false); + att.set_downloading(false); + att.set_path(String::new()); + changed = true; + } + } + if changed { + ids.push(m.id_hex()); + } + } + let chat_id = state.chats[ci].id().to_string(); + for hex in ids { + if let Some(m) = state.chats[ci].messages.find_by_hex_id(&hex) { + updates.push((chat_id.clone(), m.to_message(&state.interner))); + } + } + } + } + emit_updates(updates).await; +} + +async fn emit_updates(updates: Vec<(String, vector_core::Message)>) { + for (chat, mut m) in updates { + let old = m.id.clone(); + vector_core::traits::emit_message_update(&chat, &old, &mut m).await; + } +} + +/// This account's old downloads (rows older versions left unmarked included), and what other +/// accounts show. +pub fn find_old_downloads() -> (Result, String>, Option) { + if let Err(e) = import::reclaim_unmarked() { + log::warn!("couldn't check downloads left unmarked: {e}"); + } + (import::on_disk(), import::elsewhere()) +} + +/// Old downloads still in the download folder that would go with Keep Files: (files, bytes). +pub async fn old_downloads() -> (u64, u64) { + let Ok((Ok(files), Some(shown))) = vector_core::db::blocking_bound(find_old_downloads).await else { + return (0, 0); + }; + let goes: Vec<_> = files.iter().filter(|f| !shown.shows(f)).collect(); + let bytes = goes.iter().filter_map(|f| std::fs::metadata(&f.path).ok()).map(|m| m.len()).sum(); + (goes.len() as u64, bytes) +} + +/// Delete the originals a move owes; those that can't be judged yet stay owed. +async fn settle_owed(settle: F) +where + F: FnOnce() -> Result + Send + 'static, +{ + if let Ok(Err(e)) = vector_core::db::blocking_bound(settle).await { + log::warn!("originals stay owed for now: {e}"); + } +} + +/// Move this account's files the way its settings say, after `delay`. One run at a time. +pub fn start(delay: Duration) { + if MOVING.swap(true, Ordering::AcqRel) { + return; + } + STOP.store(false, Ordering::Release); + vector_core::db::spawn_bound(async move { + struct Done; + impl Drop for Done { + fn drop(&mut self) { + MOVING.store(false, Ordering::Release); + } + } + let _done = Done; + let stopped = || STOP.load(Ordering::Acquire) || !vector_core::db::writes_to_live_account(); + let at = tokio::time::Instant::now() + delay; + while tokio::time::Instant::now() < at && !stopped() { + tokio::time::sleep(Duration::from_secs(1)).await; + } + if stopped() || !vector_core::media::keep_media() { + return; + } + if vector_core::media::keep_unencrypted() { + return move_out(&stopped).await; + } + move_in(&stopped).await; + }); +} + +/// Stop between files. False when it is still in one after a while. +pub async fn stop() -> bool { + STOP.store(true, Ordering::Release); + for _ in 0..150 { + if !MOVING.load(Ordering::Acquire) { + return true; + } + tokio::time::sleep(Duration::from_millis(100)).await; + } + false +} + +/// The port picks up again after a clear, if this account keeps files. +pub fn resume() { + if vector_core::media::keep_media() { + start(Duration::ZERO); + } +} + +async fn move_in(stopped: &impl Fn() -> bool) { + settle_owed(import::settle).await; + let Ok((Ok(files), elsewhere)) = vector_core::db::blocking_bound(find_old_downloads).await else { + return; + }; + let elsewhere = Arc::new(elsewhere); + let mut owed: Vec = Vec::new(); + for (i, item) in files.iter().enumerate() { + if stopped() { + break; + } + let len = std::fs::metadata(&item.path).map_or(0, |m| m.len()); + let (file, others) = (item.clone(), elsewhere.clone()); + match vector_core::db::blocking_bound(move || import::move_in(&file, others.as_ref().as_ref())).await { + Ok(Ok((outcome, events))) => { + if outcome == Moved::Moved { + owed.push(item.path.clone()); + } + let updates = import::reflect(&mut *STATE.lock().await, item, outcome, &events); + emit_updates(updates).await; + } + Ok(Err(e)) => log::warn!("couldn't move a file in: {e}"), + Err(_) => break, + } + if owed.len() >= BATCH { + let (batch, others) = (std::mem::take(&mut owed), elsewhere.clone()); + settle_owed(move || import::settle_batch(&batch, others.as_ref().as_ref())).await; + } + progress(i + 1, files.len(), false); + tokio::time::sleep(pace(len)).await; + } + if !owed.is_empty() { + settle_owed(move || import::settle_batch(&owed, elsewhere.as_ref().as_ref())).await; + } + progress(files.len(), files.len(), false); +} + +async fn move_out(stopped: &impl Fn() -> bool) { + let Ok(Ok(kept)) = vector_core::db::blocking_bound(vector_core::db::attachments::kept_names).await else { + return; + }; + for (i, (hash, name, _)) in kept.iter().enumerate() { + if stopped() { + break; + } + let len = vector_core::media::open(hash).map_or(0, |src| src.len()); + let (hash, name) = (*hash, name.clone()); + match vector_core::db::blocking_bound(move || unseal(&hash, &name)).await { + Ok(Ok(path)) => reflect_unsealed(&hash, &path.to_string_lossy()).await, + Ok(Err(e)) => log::warn!("couldn't keep a file unencrypted: {e}"), + Err(_) => break, + } + progress(i + 1, kept.len(), true); + tokio::time::sleep(pace(len)).await; + } + progress(kept.len(), kept.len(), true); +} + +/// A Save on a phone: a plain copy in Vector's public folder, where the gallery and file managers +/// find it. Answers that folder as a file manager names it. +#[cfg(target_os = "android")] +pub async fn save_public(hash: [u8; 32], name: String) -> Result { + let dir = vector_core::db::get_public_dir(); + let at = dir.clone(); + let path = vector_core::db::blocking_bound(move || place_plain(&hash, &name, &at)).await??.0; + let spelled = path.to_string_lossy().into_owned(); + vector_core::db::saved::mark(&spelled)?; + vector_media::android::storage::scan_file(&spelled); + let dir = dir.to_string_lossy(); + Ok(["/Download", "/Android"].iter().find_map(|s| dir.find(s)).map_or(dir.to_string(), |i| dir[i + 1..].to_string())) +} + +/// A kept file made plain in the public folder: its rows point at that copy, then the store lets +/// go of its own. +fn unseal(hash: &[u8; 32], name: &str) -> Result { + let (path, wrote) = place_plain(hash, name, &vector_core::db::get_public_dir())?; + let spelled = path.to_string_lossy().into_owned(); + if wrote { + vector_core::db::saved::unmark(&spelled)?; + } + vector_core::db::attachments::out_of_store(&vector_core::simd::hex::bytes_to_hex_string(hash), &spelled)?; + vector_core::db::sync_wal()?; + vector_core::media::store::forget(hash); + Ok(path) +} + +/// A plain copy of a kept file in `dir`; one there already holding these bytes is used as is. +/// Returns where it is, and whether this wrote it. +fn place_plain(hash: &[u8; 32], name: &str, dir: &Path) -> Result<(PathBuf, bool), String> { + let src = vector_core::media::open(hash).ok_or_else(|| crate::t::file_not_on_device().to_string())?; + let hex = vector_core::simd::hex::bytes_to_hex_string(hash); + let holds = |path: &Path| vector_core::crypto::stream::hash_file(path).is_ok_and(|(h, _)| h == hex); + std::fs::create_dir_all(dir).map_err(|e| crate::t::file_save_failed(e.to_string()).to_string())?; + let name = file_name(name, &hex, src.mime()); + let candidate = dir.join(&name); + if holds(&candidate) { + return Ok((candidate, false)); + } + let dest = vector_core::crypto::resolve_unique_filename(dir, &name); + copy_out(&*src, &dest)?; + // The store's keystream checks no tag: the copy proves its bytes. + if !holds(&dest) { + let _ = std::fs::remove_file(&dest); + return Err(crate::t::file_save_mismatch().into()); + } + Ok((dest, true)) +} + +/// The sender's name, else the hash and type. +fn file_name(name: &str, hex: &str, mime: &str) -> String { + let name = vector_core::crypto::sanitize_filename(name); + if !name.is_empty() { + return name; + } + let ext = vector_core::crypto::extension_from_mime(mime); + if ext.is_empty() { hex[..12].to_string() } else { format!("{}.{ext}", &hex[..12]) } +} + +/// A chunk at a time, beside `dest` first, then into place: never whole in memory. +fn copy_out(src: &dyn vector_core::media::MediaSource, dest: &Path) -> Result<(), String> { + use std::io::Write; + let name = dest.file_name().and_then(|n| n.to_str()).unwrap_or("file"); + let tmp = dest.with_file_name(format!(".{name}.{:08x}.saving", rand::random::())); + let result = (|| -> std::io::Result<()> { + let mut options = std::fs::OpenOptions::new(); + options.write(true).create(true).truncate(true); + #[cfg(unix)] + std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600); + let mut out = std::io::BufWriter::with_capacity(1 << 20, options.open(&tmp)?); + let mut buf = zeroize::Zeroizing::new(vec![0u8; 1 << 20]); + let mut at = 0u64; + while at < src.len() { + let n = src.read_at(at, &mut buf)?; + if n == 0 { + return Err(std::io::ErrorKind::UnexpectedEof.into()); + } + out.write_all(&buf[..n])?; + at += n as u64; + } + out.into_inner().map_err(|e| e.into_error())?.sync_all()?; + std::fs::rename(&tmp, dest) + })(); + result.map_err(|e| { + let _ = std::fs::remove_file(&tmp); + crate::t::file_save_failed(e.to_string()).to_string() + }) +} + +/// Loaded messages show a kept file from its plain copy. +async fn reflect_unsealed(hash: &[u8; 32], path: &str) { + let mut updates = Vec::new(); + { + let mut state = STATE.lock().await; + for ci in 0..state.chats.len() { + let mut ids = Vec::new(); + for m in state.chats[ci].messages.iter_mut() { + let mut changed = false; + for att in m.attachments.iter_mut().filter(|a| a.id() == hash && a.downloaded() && a.path().is_empty()) { + att.set_path(path.to_string()); + changed = true; + } + if changed { + ids.push(m.id_hex()); + } + } + let chat_id = state.chats[ci].id().to_string(); + for hex in ids { + if let Some(m) = state.chats[ci].messages.find_by_hex_id(&hex) { + updates.push((chat_id.clone(), m.to_message(&state.interner))); + } + } + } + } + emit_updates(updates).await; +} + +/// Keep Unencrypted on or off: what is kept moves, paced, out to plain files or back in. +pub async fn set_keep_unencrypted(on: bool) -> Result<(), String> { + vector_core::db::scoped(async move { + if on && !vector_core::media::keep_media() { + return Err(crate::t::settings_storage_keep_first().into()); + } + if super::attachments::any_running() || !stop().await { + return Err(crate::t::settings_storage_change_later().into()); + } + vector_core::db::set_sql_setting("keep_unencrypted".into(), on.to_string())?; + start(Duration::ZERO); + Ok(()) + }) + .await +} + +/// Where kept-unencrypted files go, as the user's file manager names it. +pub fn public_folder() -> String { + let dir = vector_core::db::get_public_dir(); + std::env::var_os(if cfg!(windows) { "USERPROFILE" } else { "HOME" }) + .map(PathBuf::from) + .and_then(|home| dir.strip_prefix(home).ok().map(Path::to_path_buf)) + .unwrap_or(dir) + .to_string_lossy() + .into_owned() +} diff --git a/crates/vector-gpui/src/backend/messaging.rs b/crates/vector-gpui/src/backend/messaging.rs new file mode 100644 index 000000000..da82c9027 --- /dev/null +++ b/crates/vector-gpui/src/backend/messaging.rs @@ -0,0 +1,503 @@ +//! Reading history, marking read and sending. + +use std::collections::HashMap; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, LazyLock, Mutex}; + +use serde_json::json; +use vector_core::sending::{SendCallback, SendConfig}; +use vector_core::{Message, STATE, db}; + +/// Cancel flags for uploads in flight, by pending id. +/// Cancelled uploads whose failure is still to persist: the row goes instead. +static CANCELLED: Mutex> = Mutex::new(Vec::new()); +static UPLOAD_CANCEL: LazyLock>>> = + LazyLock::new(Default::default); +/// A failure's reason, from `on_failed_reason` to the `on_failed` that follows it. +static FAIL_REASONS: LazyLock>> = LazyLock::new(Default::default); + +/// Stop every running upload and forget the failures: the account they belong to is leaving. +pub fn cancel_all_uploads() { + let mut uploads = UPLOAD_CANCEL.lock().unwrap_or_else(|e| e.into_inner()); + uploads + .values() + .for_each(|flag| flag.store(true, std::sync::atomic::Ordering::Release)); + uploads.clear(); + FAIL_REASONS.lock().unwrap_or_else(|e| e.into_inner()).clear(); +} + +pub fn cancel_upload(pending_id: &str) { + if let Some(flag) = UPLOAD_CANCEL.lock().unwrap_or_else(|e| e.into_inner()).get(pending_id) { + flag.store(true, Ordering::Relaxed); + } +} + +/// The optimistic bubble, upload progress, then its sent or failed update: the desktop's. +#[derive(Clone, Copy)] +pub struct Callback; + +impl SendCallback for Callback { + fn on_pending(&self, chat_id: &str, msg: &Message) { + if !msg.attachments.is_empty() { + UPLOAD_CANCEL + .lock() + .unwrap() + .insert(msg.id.clone(), Arc::new(AtomicBool::new(false))); + } + vector_core::traits::emit_message_new(chat_id, msg); + } + + fn cancel_token(&self, pending_id: &str) -> Option> { + UPLOAD_CANCEL.lock().unwrap_or_else(|e| e.into_inner()).get(pending_id).cloned() + } + + fn on_upload_progress( + &self, + pending_id: &str, + percentage: u8, + bytes_sent: u64, + ) -> Result<(), String> { + if self + .cancel_token(pending_id) + .is_some_and(|f| f.load(Ordering::Relaxed)) + { + return Err("Upload cancelled".into()); // i18n-exempt: sentinel, matched by the send path + } + vector_core::emit_event( + "attachment_upload_progress", + &json!({ "id": pending_id, "progress": percentage, "bytesSent": bytes_sent }), + ); + Ok(()) + } + + fn on_upload_stage(&self, pending_id: &str, stage: &str, pct: Option) { + vector_core::emit_event( + "attachment_upload_stage", + &json!({ "id": pending_id, "stage": stage, "progress": pct }), + ); + } + + fn on_upload_complete(&self, chat_id: &str, pending_id: &str, attachment_id: &str, url: &str) { + vector_core::emit_event( + "attachment_update", + &json!({ "chat_id": chat_id, "message_id": pending_id, "attachment_id": attachment_id, "url": url }), + ); + } + + fn on_sent(&self, chat_id: &str, old_id: &str, msg: &Message) { + UPLOAD_CANCEL.lock().unwrap_or_else(|e| e.into_inner()).remove(old_id); + if old_id.starts_with("pending-") && old_id != msg.id { + let pending_id = old_id.to_string(); + db::spawn_bound(async move { + let _ = db::events::delete_event(&pending_id).await; + }); + } + vector_core::traits::emit_message_replaced(chat_id, old_id, msg); + } + + fn on_failed_reason(&self, _chat_id: &str, old_id: &str, reason: &str) { + FAIL_REASONS + .lock() + .unwrap() + .insert(old_id.to_string(), reason.to_string()); + } + + fn on_failed(&self, chat_id: &str, old_id: &str, msg: &Message) { + let cancelled = UPLOAD_CANCEL + .lock() + .unwrap() + .remove(old_id) + .is_some_and(|f| f.load(Ordering::Relaxed)); + if cancelled { + FAIL_REASONS.lock().unwrap_or_else(|e| e.into_inner()).remove(old_id); + CANCELLED.lock().unwrap_or_else(|e| e.into_inner()).push(old_id.to_string()); + return; + } + let reason = FAIL_REASONS.lock().unwrap_or_else(|e| e.into_inner()).remove(old_id); + vector_core::emit_event( + "message_update", + &json!({ "old_id": old_id, "message": msg, "chat_id": chat_id, "reason": reason }), + ); + } + + fn on_persist(&self, chat_id: &str, msg: &Message) { + let cancelled = { + let mut c = CANCELLED.lock().unwrap_or_else(|e| e.into_inner()); + c.iter().position(|id| *id == msg.id).map(|at| c.swap_remove(at)) + }; + if let Some(id) = cancelled { + let chat_id = chat_id.to_string(); + db::spawn_bound(async move { + STATE.lock().await.remove_message(&id); + let _ = db::events::delete_event(&id).await; + vector_core::emit_event("message_removed", &json!({ "id": id, "chat_id": chat_id, "reason": "cancelled" })); + }); + return; + } + let (chat_id, msg) = (chat_id.to_string(), msg.clone()); + db::spawn_bound(async move { + let _ = db::events::save_message(&chat_id, &msg).await; + }); + } +} + +/// Send `content` to a DM; `replied_to` quotes a message when not empty. +/// `bot` names the bot a `/` command is for; only a Community message carries the tag. +pub async fn send(receiver: String, content: String, replied_to: String, bot: Option) -> Result<(), String> { + if !receiver.starts_with("npub1") { + return super::community::send(receiver, content, replied_to, bot).await; + } + let config = SendConfig { + expiration: vector_core::self_destruct::resolve_send_expiry(&receiver), + ..SendConfig::gui() + }; + let reply = (!replied_to.is_empty()).then_some(replied_to.as_str()); + vector_core::sending::send_dm(&receiver, &content, reply, &config, Arc::new(Callback)) + .await + .map(|_| ()) +} + +/// A page of a chat's messages, newest first, as the timeline renders them. +pub async fn message_views( + chat_id: String, + limit: usize, + offset: usize, +) -> Result, String> { + let id = db::id_cache::get_chat_id_by_identifier(&chat_id)?; + db::events::get_message_views(id, limit, offset).await +} + +/// Messages newer than `id` and the chat's total, for the scrollbar. +pub fn message_position(chat_id: &str, id: &str) -> Option<(usize, usize)> { + let chat = db::id_cache::get_chat_id_by_identifier(chat_id).ok()?; + db::events::get_message_position(chat, id).ok().flatten().map(|p| (p.newer, p.total)) +} + +/// When the message `newer` places from the newest was sent (ms). +pub fn message_time_at(chat_id: &str, newer: usize) -> Option { + let chat = db::id_cache::get_chat_id_by_identifier(chat_id).ok()?; + db::events::get_message_time_at(chat, newer).ok().flatten() +} + +pub fn message_count(chat_id: &str) -> usize { + db::id_cache::get_chat_id_by_identifier(chat_id) + .and_then(db::events::get_chat_message_count) + .unwrap_or(0) +} + +/// The chat the user has open: what arrives there is read on arrival. +pub fn set_active_chat(chat_id: Option) { + vector_core::state::set_active_chat(chat_id); +} + +pub async fn mark_as_read(chat_id: String, message_id: Option) -> bool { + let slim = { + let mut state = STATE.lock().await; + let Some(idx) = state.chats.iter().position(|c| c.id == chat_id) else { + return false; + }; + let changed = match &message_id { + Some(id) => { + state.chats[idx].mark_read_at(vector_core::compact::encode_message_id(id)); + true + } + None => state.chats[idx].set_as_read(), + }; + if !changed { + return false; + } + state.unread_clear(&chat_id); + let last_read = vector_core::compact::decode_message_id(&state.chats[idx].last_read); + (db::chats::SlimChatDB::from_chat(&state.chats[idx], &state.interner), last_read) + }; + let (slim, last_read) = slim; + let _ = db::chats::save_slim_chat(&slim); + super::notify::read(&chat_id); + // The UI's copy of the marker follows, so a reopened chat draws no stale NEW line. + vector_core::emit_event("chat_mark_read", &json!({ "chat_id": chat_id, "last_read": last_read })); + vector_core::emit_event("unread_counts_stale", &json!({ "chats": [chat_id] })); + true +} + +/// An explicit read covers the whole history: the marker is the newest contact message in the +/// database, as a channel never opened holds none in memory. +pub async fn mark_caught_up(chat_id: String) -> bool { + match db::events::newest_contact_message_id(&chat_id).await { + Ok(Some(id)) => mark_as_read(chat_id, Some(id)).await, + _ => mark_as_read(chat_id, None).await, + } +} + +/// Unread counts per chat, from the database: boot holds only each chat's last message. +pub async fn unread_counts() -> HashMap { + let counts = db::events::unread_counts().await.unwrap_or_default(); + let state = STATE.lock().await; + state + .chats + .iter() + .filter_map(|c| { + let n = counts.get(&c.id).copied().unwrap_or(0); + (n > 0).then(|| (c.id.clone(), n as u32)) + }) + .collect() +} + +/// A chat as state holds it, for one the UI hasn't seen yet. +pub async fn chat_snapshot(chat_id: String) -> Option { + let state = STATE.lock().await; + state + .get_chat(&chat_id) + .map(|c| c.to_serializable(&state.interner)) +} + +/// A file DM's settings: the chat's self-destruct lifespan rides along and is stamped once +/// the upload is done, so the clock starts at publish. +fn file_send_config(receiver: &str) -> SendConfig { + SendConfig { + self_destruct_secs: vector_core::self_destruct::chat_duration_secs(receiver), + ..SendConfig::gui() + } +} + +const IMAGE_EXTS: &[&str] = &["png", "jpg", "jpeg", "gif", "webp", "jxl", "tiff", "tif", "ico"]; + +/// Send a picked file to a DM. An image is compressed (reusing `precompressed`, the preview's +/// own run, when it fits the choice) or stripped of metadata; anything else streams from disk. +pub async fn send_file( + receiver: String, + replied_to: String, + path: std::path::PathBuf, + name_override: String, + compress: bool, + keep_metadata: bool, + precompressed: Option, +) -> Result<(), String> { + if !receiver.starts_with("npub1") { + return super::community_files::send_file( + receiver, + String::new(), + path, + name_override, + compress, + keep_metadata, + replied_to, + precompressed, + ) + .await + .map(|_| ()); + } + let reply = (!replied_to.is_empty()).then_some(replied_to.as_str()); + let config = file_send_config(&receiver); + let extension = path + .extension() + .and_then(|e| e.to_str()) + .unwrap_or("") + .to_lowercase(); + let mut name = path + .file_name() + .and_then(|n| n.to_str()) + .unwrap_or("") + .to_string(); + if !name_override.is_empty() { + let clean = vector_core::crypto::sanitize_filename(&name_override); + if !clean.is_empty() { + name = clean; + } + } + if let Some(pc) = super::community_files::smaller_video(&extension, compress, precompressed.as_ref()) { + let name = crate::message::video_compression::renamed(&name, &pc.extension); + return vector_core::sending::send_file_dm_with_meta( + &receiver, + pc.bytes.clone(), + &name, + &pc.extension, + None, + None, + reply, + &config, + Arc::new(Callback), + ) + .await + .map(|_| ()); + } + let pasted = super::pasted::get(&path); + if !IMAGE_EXTS.contains(&extension.as_str()) { + let source = match pasted { + Some(b) if !b.is_empty() => vector_core::sending::FileSource::Bytes(b), + Some(_) => return Err(crate::t::file_empty().into()), + None => path_source(&path)?, + }; + return vector_core::sending::send_file_dm_from( + &receiver, + source, + &name, + &extension, + None, + None, + reply, + &config, + Arc::new(Callback), + ) + .await + .map(|_| ()); + } + let (ext, file) = (extension.clone(), path.clone()); + let processed = tokio::task::spawn_blocking(move || { + let bytes = match pasted { + Some(b) => b, + None => Arc::new(std::fs::read(&file).map_err(|e| crate::t::file_read_failed(e.to_string()).to_string())?), + }; + let out = crate::message::process_image_for_send( + bytes, + &ext, + compress, + keep_metadata, + precompressed, + ); + crate::message::compression::forget_fitted(); + out + }) + .await + .map_err(|e| e.to_string())??; + // A compressed file's name follows its new format, so the receiver opens it as one. + if processed.extension != extension { + name = crate::message::video_compression::renamed(&name, &processed.extension); + } + vector_core::sending::send_file_dm_with_meta( + &receiver, + processed.bytes, + &name, + &processed.extension, + processed.img_meta, + None, + reply, + &config, + Arc::new(Callback), + ) + .await + .map(|_| ()) +} + +fn path_source(path: &std::path::Path) -> Result { + match std::fs::metadata(path) { + Ok(m) if m.len() > 0 => Ok(vector_core::sending::FileSource::Path(path.to_path_buf())), + Ok(_) => Err(crate::t::file_empty().into()), + Err(e) => Err(crate::t::file_metadata_failed(e.to_string()).to_string()), + } +} + +/// Media Vector holds (a Mini App kept from a chat), sent from its bytes under `name`. +pub async fn send_held(receiver: String, hash: [u8; 32], name: String) -> Result<(), String> { + let src = vector_core::media::open(&hash).ok_or_else(|| crate::t::file_not_on_device().to_string())?; + let bytes = tokio::task::spawn_blocking(move || vector_core::media::read_all(&*src)) + .await + .map_err(|e| e.to_string())? + .map_err(|e| crate::t::file_read_failed(e.to_string()).to_string())?; + let name = vector_core::crypto::sanitize_filename(&name); + if !receiver.starts_with("npub1") { + return super::community_files::send_bytes(receiver, bytes, name).await; + } + let extension = std::path::Path::new(&name) + .extension() + .and_then(|e| e.to_str()) + .unwrap_or("") + .to_lowercase(); + let config = file_send_config(&receiver); + vector_core::sending::send_file_dm_with_meta(&receiver, Arc::new(bytes), &name, &extension, None, None, None, &config, Arc::new(Callback)) + .await + .map(|_| ()) +} + +/// The preview's background compression of a picked image. +pub fn precompress( + path: &std::path::Path, +) -> Result { + crate::message::precompress(path) +} + +/// Whether a picked image carries strip-worthy metadata (location, camera, date). +pub fn has_metadata(path: &std::path::Path) -> bool { + let ext = path + .extension() + .and_then(|e| e.to_str()) + .unwrap_or("") + .to_lowercase(); + if let Some(b) = super::pasted::get(path) { + return crate::shared::image::image_bytes_have_metadata(&b, &ext); + } + if matches!(ext.as_str(), "jpg" | "jpeg" | "png") { + return std::fs::File::open(path) + .ok() + .and_then(|mut f| crate::shared::image::header_has_metadata(&mut f, &ext)) + .unwrap_or(false); + } + std::fs::read(path).is_ok_and(|b| crate::shared::image::image_bytes_have_metadata(&b, &ext)) +} + +/// `before` messages up to and including `anchor`, then `after` past it, oldest first. +pub async fn messages_around( + chat_id: String, + anchor: String, + before: usize, + after: usize, +) -> Result, String> { + let id = db::id_cache::get_chat_id_by_identifier(&chat_id)?; + db::events::get_messages_around(id, &anchor, before, after).await +} + +/// The stopped recording, encoded once and sent as a nameless `.wav`. +pub async fn send_voice(receiver: String, replied_to: String) -> Result<(), String> { + let pending = vector_media::voice::AudioRecorder::global() + .take_pending() + .ok_or("No pending recording")?; // i18n-exempt: developer error + let _ = vector_media::audio_engine::AudioEngine::get().map(|e| e.stop(pending.source_id)); + let wav = tokio::task::spawn_blocking(move || pending.encode_wav()) + .await + .map_err(|e| e.to_string())??; + if !receiver.starts_with("npub1") { + return super::community_files::send_voice(receiver, wav, replied_to).await; + } + let reply = (!replied_to.is_empty()).then_some(replied_to.as_str()); + let config = file_send_config(&receiver); + vector_core::sending::send_file_dm_with_meta( + &receiver, + Arc::new(wav), + "", + "wav", + None, + None, + reply, + &config, + Arc::new(Callback), + ) + .await + .map(|_| ()) +} + +/// The open chat's bot commands, as the `/` picker lists them. +pub async fn chat_commands(chat: String) -> crate::commands::Snapshot { + let snap = vector_core::VectorCore.get_chat_commands(&chat).await; + crate::commands::Snapshot { + bots: snap.bots, + commands: snap.commands.iter().flat_map(|b| crate::commands::bot_commands(&b.bot, &b.commands)).collect(), + fresh: snap.fresh, + } +} + +/// `get_system_events`: a chat's saved system lines, oldest first. +pub fn system_lines(chat_id: &str) -> Vec { + let tag = |e: &vector_core::StoredEvent, k: &str| e.tags.iter().find(|t| t.len() >= 2 && t[0] == k).map(|t| t[1].clone()); + vector_core::db::events::get_system_events_for_chat(chat_id) + .unwrap_or_default() + .into_iter() + .map(|e| crate::data::SysLine { + kind: tag(&e, "event-type").and_then(|t| t.parse().ok()).unwrap_or(255), + npub: tag(&e, "member").unwrap_or_default(), + via: tag(&e, "invited-label") + .filter(|l| !l.is_empty()) + .zip(tag(&e, "invited-by").as_deref().and_then(vector_core::community::inviter_npub)), + at: e.created_at * 1000, + id: e.id, + }) + .collect() +} diff --git a/crates/vector-gpui/src/backend/mic.rs b/crates/vector-gpui/src/backend/mic.rs new file mode 100644 index 000000000..04008042a --- /dev/null +++ b/crates/vector-gpui/src/backend/mic.rs @@ -0,0 +1,41 @@ +//! Settings → Calls: the devices, the voice processing switches and volumes, Direct Connection, +//! and the microphone test. + +use vector_core::calls::settings::{self, AudioSettings}; + +pub use crate::audio_devices::{DeviceList, DevicePrefs}; + +pub fn audio_settings() -> AudioSettings { + settings::load() +} + +pub fn set_audio_settings(s: AudioSettings) -> Result<(), String> { + settings::set(s) +} + +pub fn devices() -> DeviceList { + crate::audio_devices::load(); + crate::audio_devices::list() +} + +/// The engine follows the change, a running test included. +pub fn set_devices(prefs: DevicePrefs) -> Result<(), String> { + crate::audio_devices::set(prefs) +} + +pub fn direct() -> bool { + vector_core::transport::realtime::direct() +} + +pub async fn set_direct(on: bool) -> Result<(), String> { + vector_core::transport::realtime::set_direct(on).await +} + +/// The call's own capture chain (gain, echo, noise), metered by `mic_level` events until stopped. +pub async fn test_start() -> Result<(), String> { + super::calls::mic_test_start().await +} + +pub fn test_stop() { + super::calls::mic_test_stop(); +} diff --git a/crates/vector-gpui/src/backend/mod.rs b/crates/vector-gpui/src/backend/mod.rs new file mode 100644 index 000000000..17c9a8eb1 --- /dev/null +++ b/crates/vector-gpui/src/backend/mod.rs @@ -0,0 +1,281 @@ +//! The live account, on vector-core. Core runs on its own tokio runtime; the UI hears back +//! through [`UiEvent`]s and awaits each call's result through a one-shot channel. + +pub mod account; +pub mod actions; +pub mod archive; +pub mod pasted; +pub mod attachments; +pub mod chatlist; +pub mod badges; +pub mod bunker; +pub mod embedvideo; +pub mod stream; +pub mod xdcurl; +pub mod calls; +pub mod community; +pub mod community_files; +pub mod device; +pub mod events; +pub mod gifs; +pub mod images; +pub mod inline; +pub mod market; +pub mod mediaport; +pub mod pivx; +pub mod rail; +pub mod voice; +pub mod messaging; +pub mod mic; +pub mod network; +pub mod notify; +pub mod packs; +pub mod prefs; +pub mod push; +pub mod security; +pub mod biometric; +pub mod nip55; +pub mod selfsync; +pub mod sound; +#[cfg(target_os = "android")] +mod standby; +pub mod storage; +pub mod transcribe; +pub mod sync; +pub mod transfer; +pub mod transport; +pub mod unfurl; +pub mod install; +pub mod langpacks; +pub mod updates; +pub mod upload; + +use std::future::Future; +use std::path::PathBuf; +use std::sync::{Arc, OnceLock}; + +use futures::channel::{mpsc, oneshot}; +use vector_core::{SerializableChat, SlimProfile}; + +static RT: OnceLock = OnceLock::new(); +static SINK: OnceLock> = OnceLock::new(); + +/// What the backend tells the UI. +pub enum UiEvent { + /// An event core (or this backend) emitted, by the name the Tauri frontend listens for. + Core(String, serde_json::Value), + /// The account's chats and profiles, loaded from its database: the list can paint. + Booted(Boot), +} + +pub struct Boot { + pub npub: String, + pub chats: Vec, + pub profiles: Vec, +} + +pub(crate) fn send(ev: UiEvent) { + if let Some(tx) = SINK.get() { + let _ = tx.unbounded_send(ev); + } +} + +/// For events this shell emits itself rather than through core. +pub(crate) fn emit(event: &str, payload: impl serde::Serialize) { + if let Ok(v) = serde_json::to_value(payload) { + send(UiEvent::Core(event.to_string(), v)); + } +} + +struct Emitter; + +impl vector_core::EventEmitter for Emitter { + fn emit(&self, event: &str, payload: serde_json::Value) { + // Every way a message leaves a chat ends in `message_removed`. + if event == "message_removed" + && let Some(id) = payload.get("id").and_then(|v| v.as_str()) + { + notify::deleted(id); + } + if event == "unread_counts_stale" { + notify::recount(); + } + send(UiEvent::Core(event.to_string(), payload)); + } +} + +/// Where accounts live: the Tauri client's own folder (its app_data_dir), so either client +/// resumes the other's accounts. `--data-dir` points it anywhere else. +pub fn default_data_dir() -> PathBuf { + #[cfg(target_os = "android")] + if let Some(dir) = crate::android::data_dir() { + return dir.clone(); + } + dirs::data_dir() + .unwrap_or_else(std::env::temp_dir) + .join("io.vectorapp") +} + +/// Core and its runtime, once per process: on Android a push can start the process, and open +/// its account, before there is a window. +pub(crate) fn core(data_dir: PathBuf) -> &'static tokio::runtime::Runtime { + static CORE: OnceLock<()> = OnceLock::new(); + CORE.get_or_init(|| { + // Every session starts blocked until its stored network is loaded, as on desktop. + vector_core::transport::strict_boot(); + vector_core::net::set_app_version(env!("CARGO_PKG_VERSION")); + vector_core::db::set_app_version(env!("CARGO_PKG_VERSION").to_string()); + #[cfg(not(target_os = "android"))] + if let Some(dl) = dirs::download_dir() { + vector_core::db::set_download_dir(dl.join("vector")); + } + // The Tauri client's folders: the app's media folder, and Download/Vector from Android 11. + #[cfg(target_os = "android")] + { + use vector_media::android::storage; + if let Some(dir) = storage::external_media_dir() { + vector_core::db::set_download_dir(dir.into()); + } + if let Some(dir) = storage::public_dir() { + vector_core::db::set_public_dir(dir.into()); + } + } + let _ = std::fs::create_dir_all(&data_dir); + device::init(Some(data_dir.clone())); + vector_core::VectorCore::init(vector_core::CoreConfig { + data_dir, + event_emitter: Some(Box::new(Emitter)), + }) + .expect("vector-core init"); + vector_core::requests::enable_shield(); + }); + let rt = RT.get_or_init(|| { + tokio::runtime::Builder::new_multi_thread() + .thread_name("vector-core") + .enable_all() + .build() + .expect("tokio runtime") + }); + tauri::async_runtime::set(rt.handle().clone()); + rt +} + +/// Start core: the runtime, the emitter, the profile processor and the remembered account. +pub fn start(data_dir: PathBuf) -> mpsc::UnboundedReceiver { + let (tx, rx) = mpsc::unbounded(); + let _ = SINK.set(tx); + let rt = core(data_dir); + tauri::set_local_data_dir(models_home()); + if let Ok(dir) = vector_core::db::get_app_data_dir() { + tauri::set_data_dir(dir.clone()); + } + let _ = vector_media::TAURI_APP.set(tauri::AppHandle::new(engine_sink)); + notify::install(); + { + let _guard = rt.enter(); + // Calls take the engine as they find it and register for device changes once, here. + vector_media::audio_engine::AudioEngine::init(); + crate::calls::session::install(); + } + crate::miniapp::init(|n| match n { + crate::miniapp::Notice::Failed(e) => emit("show_toast", serde_json::Value::String(e)), + crate::miniapp::Notice::Refused(msg, code) => emit("player_refused", serde_json::json!({ "msg": msg, "code": code })), + crate::miniapp::Notice::Browse(url) => emit("player_browse", serde_json::Value::String(url)), + crate::miniapp::Notice::Opened | crate::miniapp::Notice::Closed => {} + }); + { + let _guard = rt.enter(); + transport::spawn_ready_listener(); + } + // spawn-detached: the sweep expires messages for whichever account is live, as on desktop. + rt.spawn(vector_core::self_destruct::run_sweeper_loop()); + // spawn-detached: the processor serves whichever account is live, as on desktop. + rt.spawn(vector_core::profile::sync::start_profile_sync_processor( + Arc::new(sync::ProfileHandler), + )); + // spawn-detached: housekeeping for whichever account is live, on the desktop's 45 s beat. + rt.spawn(async { + let mut beat = tokio::time::interval(std::time::Duration::from_secs(45)); + loop { + beat.tick().await; + maintenance().await; + } + }); + rx +} + +/// Retry profiles that never loaded, then let go of what sat idle: decoded sounds, the +/// Whisper model, and messages of chats the timeline isn't showing (it pages from the +/// database, so core keeps only each chat's tail). +async fn maintenance() { + vector_core::profile::sync::sync_all_profiles().await; + let mut freed = false; + if let Ok(engine) = vector_media::audio_engine::AudioEngine::get() { + freed |= engine.evict_idle() > 0; + } + freed |= vector_media::whisper::check_ctx_ttl(); + freed |= vector_core::STATE.lock().await.trim_unheld_chats() > 0; + if freed { + crate::trim::soon(); + } +} + +fn engine_sink(event: &str, payload: serde_json::Value) { + if (event.starts_with("audio_") && event != "audio_devices_changed") || event.starts_with("whisper_") { + crate::audio::engine_event(event, payload); + } else { + emit(event, payload); + } +} + +/// Without core (fixtures), the shared audio engine still needs a runtime and its events. +pub fn fixture_runtime() { + static AUDIO_RT: OnceLock = OnceLock::new(); + let rt = AUDIO_RT.get_or_init(|| { + tokio::runtime::Builder::new_multi_thread() + .worker_threads(1) + .thread_name("vector-audio") + .enable_all() + .build() + .expect("tokio runtime") + }); + tauri::async_runtime::set(rt.handle().clone()); + tauri::set_local_data_dir(models_home()); + tauri::set_data_dir(std::env::temp_dir().join("vector-gpui-fixtures")); + let _ = vector_media::TAURI_APP.set(tauri::AppHandle::new(crate::audio::engine_event)); +} + +/// The desktop client's local data folder: Whisper models live under it, so one download +/// serves both clients. +fn models_home() -> PathBuf { + #[cfg(target_os = "android")] + if let Some(dir) = crate::android::data_dir() { + return dir.clone(); + } + dirs::data_local_dir().unwrap_or_else(std::env::temp_dir).join("io.vectorapp") +} + +/// Run `fut` on core's runtime; the receiver resolves with its output. Like a Tauri command, +/// the call is unbound: account work it starts binds itself with `db::spawn_bound`. Without a +/// backend (fixtures) the receiver closes unanswered. +pub fn run(fut: F) -> oneshot::Receiver +where + T: Send + 'static, + F: Future + Send + 'static, +{ + let (tx, rx) = oneshot::channel(); + if let Some(rt) = RT.get() { + // spawn-detached: an unbound UI call, the equivalent of a Tauri command. + rt.spawn(async move { + let _ = tx.send(fut.await); + }); + } else if cfg!(feature = "devctl") && std::env::var_os("VECTOR_GIF_DIR").is_some() { + // Fixtures have no runtime; the offline GIF source still needs its futures run. + std::thread::spawn(move || { + if let Ok(rt) = tokio::runtime::Builder::new_current_thread().enable_all().build() { + let _ = tx.send(rt.block_on(fut)); + } + }); + } + rx +} diff --git a/crates/vector-gpui/src/backend/network.rs b/crates/vector-gpui/src/backend/network.rs new file mode 100644 index 000000000..4afa46bf2 --- /dev/null +++ b/crates/vector-gpui/src/backend/network.rs @@ -0,0 +1,1017 @@ +//! Relays: the pool this account connects to, their logs and health, and the DM relay list. +#![allow(dead_code)] + +use std::collections::{HashMap, VecDeque}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, RwLock}; +use std::time::Duration; + +use nostr_sdk::prelude::*; +use serde_json::{Value, json}; +use vector_core::inbox_relays::normalize_relay_url; +use vector_core::state::{self, TRUSTED_RELAYS as DEFAULT_RELAYS}; +use vector_core::{ClientRelayExt, db}; + +// Relays +// ============================================================================ + +#[derive(serde::Serialize, Clone, Default)] +pub struct RelayMetrics { + pub ping_ms: Option, + bytes_up: u64, + bytes_down: u64, + pub last_check: Option, + events_received: u64, + events_sent: u64, +} + +#[derive(serde::Serialize, Clone)] +pub struct RelayLog { + pub timestamp: u64, + pub level: String, + pub message: String, +} + +#[derive(serde::Serialize, serde::Deserialize, Clone)] +pub struct CustomRelay { + url: String, + enabled: bool, + #[serde(default = "default_relay_mode")] + mode: String, +} + +fn default_relay_mode() -> String { + "both".to_string() +} + +pub struct RelayMetricsKey; +pub struct RelayLogsKey; +pub struct MonitorStarted; + +fn relay_metrics() -> Arc>> { + db::current_session().scoped::() +} + +fn relay_logs() -> Arc>>> { + db::current_session().scoped::() +} + +fn log_key(url: &str) -> String { + url.trim().trim_end_matches('/').to_lowercase() +} + +fn now_secs() -> u64 { + vector_core::clock::now_secs() +} + +fn add_relay_log(url: &str, level: &str, message: &str) { + let log = RelayLog { + timestamp: now_secs(), + level: level.to_string(), + message: message.to_string(), + }; + if let Ok(mut logs) = relay_logs().write() { + let entries = logs.entry(log_key(url)).or_default(); + entries.push_front(log); + entries.truncate(10); + } +} + +fn update_relay_metrics(url: &str, f: impl FnOnce(&mut RelayMetrics)) { + if let Ok(mut metrics) = relay_metrics().write() { + f(metrics.entry(log_key(url)).or_default()); + } +} + +pub fn is_default_relay(url: &str) -> bool { + let normalized = url.trim().trim_end_matches('/'); + DEFAULT_RELAYS + .iter() + .any(|r| r.eq_ignore_ascii_case(normalized)) +} + +/// A default relay or one the account added. +pub fn is_own_relay(url: &str) -> bool { + use vector_core::transport::aliases::normalize_host; + let Ok(host) = normalize_host(url) else { return false }; + let same = |u: &str| normalize_host(u).is_ok_and(|h| h == host); + DEFAULT_RELAYS.iter().any(|d| same(d)) || load_custom_relays().unwrap_or_default().iter().any(|c| same(&c.url)) +} + +fn validate_relay_url(url: &str) -> Result { + vector_core::transport::validate_relay_url(url) +} + +fn capabilities_for_mode(mode: &str) -> RelayCapabilities { + match mode { + "read" => RelayCapabilities::READ, + "write" => RelayCapabilities::WRITE, + _ => RelayCapabilities::READ | RelayCapabilities::WRITE, + } +} + +fn status_label(status: RelayStatus) -> &'static str { + match status { + RelayStatus::Initialized => "initialized", + RelayStatus::Pending => "pending", + RelayStatus::Connecting => "connecting", + RelayStatus::Connected => "connected", + RelayStatus::Disconnected => "disconnected", + RelayStatus::Terminated => "terminated", + RelayStatus::Shutdown => "shutdown", + RelayStatus::Banned => "banned", + RelayStatus::Sleeping => "sleeping", + } +} + +fn load_json_setting(key: &str) -> Result { + if db::get_current_account().is_err() { + return Ok(T::default()); + } + match db::get_sql_setting(key.to_string())? { + Some(json) => { + serde_json::from_str(&json).map_err(|e| format!("Failed to parse {key}: {e}")) // i18n-exempt: developer error + } + None => Ok(T::default()), + } +} + +fn save_json_setting(key: &str, value: &T) -> Result<(), String> { + if db::get_current_account().is_err() { + return Err("No account selected".to_string()); // i18n-exempt: developer error + } + let json = + serde_json::to_string(value).map_err(|e| format!("Failed to serialize {key}: {e}"))?; // i18n-exempt: developer error + db::set_sql_setting(key.to_string(), json) +} + +fn load_custom_relays() -> Result, String> { + load_json_setting("custom_relays") +} + +fn save_custom_relays(relays: &[CustomRelay]) -> Result<(), String> { + save_json_setting("custom_relays", relays) +} + +fn disabled_default_relays() -> Result, String> { + load_json_setting("disabled_default_relays") +} + +fn save_disabled_default_relays(relays: &[String]) -> Result<(), String> { + save_json_setting("disabled_default_relays", relays) +} + +/// Enabled defaults plus enabled customs as (url, mode): what the pool should hold. +fn desired_enabled_relays() -> Vec<(String, String)> { + let disabled = disabled_default_relays().unwrap_or_default(); + let mut out: Vec<(String, String)> = DEFAULT_RELAYS + .iter() + .filter(|d| !disabled.iter().any(|x| x.eq_ignore_ascii_case(d))) + .map(|d| (d.to_string(), default_relay_mode())) + .collect(); + out.extend( + load_custom_relays() + .unwrap_or_default() + .into_iter() + .filter(|c| c.enabled) + .map(|c| (c.url, c.mode)), + ); + out +} + +/// Add to the pool and connect. An already-pooled url (a community or +/// discovery relay) is promoted in place to READ+WRITE, keeping its socket. +async fn add_relay(client: &Client, url: &str, caps: RelayCapabilities) -> Result<(), String> { + let newly_added = client + .add_managed_relay(url) + .capabilities(caps) + .await + .map_err(|e| e.to_string())?; + if !newly_added { + if let Ok(parsed) = RelayUrl::parse(url) { + if let Some(relay) = client.relays().all().await.get(&parsed) { + relay + .capabilities() + .add(RelayCapabilities::READ | RelayCapabilities::WRITE); + } + } + } + if let Err(e) = client.connect_relay(url).await { + vector_core::log_warn!("[Relay] connect_relay({url}) failed: {e}"); + } + Ok(()) +} + +/// Removing a url that is also a Discovery Relay demotes it rather than +/// evicting it: nothing re-adds a lost Discovery Relay until the next connect. +async fn restore_discovery_role(client: &Client, url: &str) { + let norm = normalize_relay_url(url); + if !state::discovery_relay_iter().any(|d| normalize_relay_url(d) == norm) { + return; + } + if client + .add_managed_relay(url) + .capabilities(vector_core::discovery_relay_capabilities()) + .await + .is_ok() + { + let _ = client.connect_relay(url).await; + } +} + +pub async fn get_relays() -> Result { + let client = state::nostr_client().ok_or("Nostr client not initialized")?; // i18n-exempt: developer error + let customs = load_custom_relays().unwrap_or_default(); + let disabled = disabled_default_relays().unwrap_or_default(); + let pool = client.relays().await; + let status_of = |url: &str| { + pool.iter() + .find(|(u, _)| { + u.as_str() + .trim_end_matches('/') + .eq_ignore_ascii_case(url.trim_end_matches('/')) + }) + .map(|(_, r)| status_label(r.status())) + .unwrap_or("disabled") + }; + + let mut infos: Vec = DEFAULT_RELAYS + .iter() + .map(|url| { + json!({ + "url": url, + "status": status_of(url), + "is_default": true, + "is_custom": false, + "enabled": !disabled.iter().any(|d| d.eq_ignore_ascii_case(url)), + "mode": "both", + }) + }) + .collect(); + infos.extend(customs.iter().map(|c| { + json!({ + "url": c.url, + "status": status_of(&c.url), + "is_default": false, + "is_custom": true, + "enabled": c.enabled, + "mode": c.mode, + }) + })); + Ok(Value::Array(infos)) +} + +pub async fn toggle_default_relay(url: String, enabled: bool) -> Result { + if !is_default_relay(&url) { + return Err(crate::t::relay_not_default().to_string()); + } + let normalized = url.trim().trim_end_matches('/').to_string(); + let mut disabled = disabled_default_relays()?; + if enabled { + disabled.retain(|d| !d.eq_ignore_ascii_case(&normalized)); + } else if !disabled.iter().any(|d| d.eq_ignore_ascii_case(&normalized)) { + disabled.push(normalized.clone()); + } + save_disabled_default_relays(&disabled)?; + + if let Some(client) = state::nostr_client() { + if enabled { + if let Err(e) = add_relay(&client, &normalized, capabilities_for_mode("both")).await { + vector_core::log_warn!("[Relay] Failed to enable default relay: {e}"); + } + } else if client.remove_relay(&normalized).await.is_ok() { + restore_discovery_role(&client, &normalized).await; + } + vector_core::inbox_relays::republish_inbox_relays_debounced(); + } + Ok(true) +} + +pub async fn add_custom_relay(url: String, mode: Option) -> Result { + let normalized = validate_relay_url(&url)?; + let mode = mode.unwrap_or_else(default_relay_mode); + if !["read", "write", "both"].contains(&mode.as_str()) { + return Err("Invalid mode. Must be 'read', 'write', or 'both'".to_string()); // i18n-exempt: developer error + } + let mut relays = load_custom_relays()?; + if relays + .iter() + .any(|r| r.url.eq_ignore_ascii_case(&normalized)) + { + return Err(crate::t::relay_exists().to_string()); + } + if is_default_relay(&normalized) { + return Err(crate::t::relay_is_default().to_string()); + } + let relay = CustomRelay { + url: normalized, + enabled: true, + mode, + }; + relays.push(relay.clone()); + save_custom_relays(&relays)?; + + if let Some(client) = state::nostr_client() { + if !client.relays().await.is_empty() { + match add_relay(&client, &relay.url, capabilities_for_mode(&relay.mode)).await { + Ok(()) => vector_core::inbox_relays::republish_inbox_relays_debounced(), + Err(e) => vector_core::log_warn!("[Relay] Failed to add relay to pool: {e}"), + } + } + } + Ok(relay) +} + +pub async fn remove_custom_relay(url: String) -> Result { + let mut relays = load_custom_relays()?; + let before = relays.len(); + relays.retain(|r| !r.url.eq_ignore_ascii_case(&url)); + if relays.len() == before { + return Ok(false); + } + save_custom_relays(&relays)?; + if let Some(client) = state::nostr_client() { + if client.remove_relay(&url).await.is_ok() { + restore_discovery_role(&client, &url).await; + } + } + vector_core::inbox_relays::republish_inbox_relays_debounced(); + Ok(true) +} + +pub async fn toggle_custom_relay(url: String, enabled: bool) -> Result { + let mut relays = load_custom_relays()?; + let relay = relays + .iter_mut() + .find(|r| r.url.eq_ignore_ascii_case(&url)) + .ok_or_else(|| crate::t::relay_not_found().to_string())?; + relay.enabled = enabled; + let mode = relay.mode.clone(); + save_custom_relays(&relays)?; + + if let Some(client) = state::nostr_client() { + if enabled { + if let Err(e) = add_relay(&client, &url, capabilities_for_mode(&mode)).await { + vector_core::log_warn!("[Relay] Failed to enable relay: {e}"); + } + } else if client.remove_relay(&url).await.is_ok() { + restore_discovery_role(&client, &url).await; + } + vector_core::inbox_relays::republish_inbox_relays_debounced(); + } + Ok(true) +} + +pub async fn update_relay_mode(url: String, mode: String) -> Result { + if !["read", "write", "both"].contains(&mode.as_str()) { + return Err("Invalid mode. Must be 'read', 'write', or 'both'".to_string()); // i18n-exempt: developer error + } + let mut relays = load_custom_relays()?; + let relay = relays + .iter_mut() + .find(|r| r.url.eq_ignore_ascii_case(&url)) + .ok_or_else(|| crate::t::relay_not_found().to_string())?; + relay.mode = mode.clone(); + let enabled = relay.enabled; + save_custom_relays(&relays)?; + + if enabled { + if let Some(client) = state::nostr_client() { + let _ = client.remove_relay(&url).await; + if let Err(e) = add_relay(&client, &url, capabilities_for_mode(&mode)).await { + vector_core::log_warn!("[Relay] Failed to update relay mode: {e}"); + restore_discovery_role(&client, &url).await; + } + } + vector_core::inbox_relays::republish_inbox_relays_debounced(); + } + Ok(true) +} + +/// Pool the user's relays (defaults minus disabled, plus enabled customs) and +/// the Discovery Relays, then connect. +pub async fn add_configured_relays(client: &Client) { + let disabled = disabled_default_relays().unwrap_or_default(); + for url in DEFAULT_RELAYS + .iter() + .filter(|d| disabled.iter().any(|x| x.eq_ignore_ascii_case(d))) + { + add_relay_log(url, "info", "Skipped (disabled by user)"); // i18n-exempt: relay log, copied for bug reports + } + let wanted = desired_enabled_relays(); + for (url, mode) in &wanted { + match client + .add_managed_relay(url.as_str()) + .capabilities(capabilities_for_mode(mode)) + .await + { + Ok(_) => add_relay_log(url, "info", &format!("Added to relay pool (mode: {mode})")), // i18n-exempt: relay log, copied for bug reports + Err(e) => { + vector_core::log_warn!("[Relay] add {url} failed: {e}"); + add_relay_log(url, "error", &format!("Failed to add: {e}")); // i18n-exempt: relay log, copied for bug reports + } + } + } + // A discovery add must not pin a user relay to GOSSIP|PING. + for url in state::discovery_relay_iter() { + let norm = normalize_relay_url(url); + if wanted.iter().any(|(u, _)| normalize_relay_url(u) == norm) { + continue; + } + let _ = client + .add_managed_relay(url) + .capabilities(vector_core::discovery_relay_capabilities()) + .await; + } + client.connect().await; +} + +/// One relay for a window-less service, as Tauri's background sync: a custom relay that reads +/// first, then the enabled defaults, each given the connect budget before the next is tried. +/// One socket wakes the radio far less than the whole pool, and senders reach every inbox relay. +#[cfg(target_os = "android")] +pub async fn connect_one(client: &Client) -> bool { + let disabled = disabled_default_relays().unwrap_or_default(); + let mut candidates: Vec<(String, RelayCapabilities)> = load_custom_relays() + .unwrap_or_default() + .into_iter() + .filter(|c| c.enabled && c.mode != "write") + .map(|c| (c.url, capabilities_for_mode(&c.mode))) + .collect(); + for url in DEFAULT_RELAYS.iter().filter(|d| !disabled.iter().any(|x| x.eq_ignore_ascii_case(d))) { + if !candidates.iter().any(|(c, _)| c.eq_ignore_ascii_case(url)) { + candidates.push((url.to_string(), capabilities_for_mode(&default_relay_mode()))); + } + } + if candidates.is_empty() { + let caps = capabilities_for_mode(&default_relay_mode()); + candidates.extend(DEFAULT_RELAYS.iter().map(|u| (u.to_string(), caps))); + } + let polls = vector_core::relay_connect_timeout(Duration::from_secs(10)).as_millis() / 500; + for (url, caps) in candidates { + if client.add_managed_relay(url.as_str()).capabilities(caps).await.is_err() { + continue; + } + client.connect().await; + for _ in 0..polls { + vector_core::rt::time::sleep(Duration::from_millis(500)).await; + if client.relays().await.values().any(|r| r.status() == RelayStatus::Connected) { + add_relay_log(&url, "info", "Background: the one relay while no window is open"); // i18n-exempt: relay log, copied for bug reports + return true; + } + } + let _ = client.remove_relay(url.as_str()).await; + } + false +} + +/// The Relays tab IS the kind 10050 list: apply a newer published copy +/// locally, then merge-publish any outbound diff. +pub async fn reconcile_dm_relay_list() { + let Some(client) = state::nostr_client() else { + return; + }; + let fetched = match vector_core::inbox_relays::fetch_own_inbox_list(&client).await { + Ok(f) => f, + Err(e) => { + vector_core::log_warn!("[Relay] DM relay list sync skipped: {e}"); + return; + } + }; + + if let Some((remote, remote_ts)) = fetched.clone() { + let (ours, declined) = local_relay_view(); + // Entries both published and enabled here are co-owned, else a disable + // on this device could never propagate. + let shared: Vec = ours + .iter() + .filter(|u| { + let n = normalize_relay_url(u); + remote.iter().any(|r| normalize_relay_url(r) == n) + }) + .cloned() + .collect(); + vector_core::inbox_relays::note_contributed(&shared); + + let plan = + vector_core::inbox_relays::plan_inbound_reconcile(&remote, remote_ts, &ours, &declined); + if plan.adopt.is_empty() && plan.revive.is_empty() && plan.retire.is_empty() { + vector_core::inbox_relays::note_list_seen(remote_ts); + } else { + apply_inbound_reconcile(&client, plan, remote_ts).await; + } + } + + // Publish the stored list, not pool state: the pool can hold a DM + // recipient's relays and miss an adoptee whose connect failed. + let (ours_now, _) = local_relay_view(); + if let Err(e) = + vector_core::inbox_relays::publish_inbox_relays_synced(&client, fetched, Some(ours_now)) + .await + { + vector_core::log_warn!("[Relay] Failed to publish inbox relays: {e}"); + } +} + +/// (enabled, disabled) relay urls from the stores the Relays tab edits. +fn local_relay_view() -> (Vec, Vec) { + let customs = load_custom_relays().unwrap_or_default(); + let mut declined = disabled_default_relays().unwrap_or_default(); + let mut ours: Vec = DEFAULT_RELAYS + .iter() + .filter(|d| !declined.iter().any(|x| x.eq_ignore_ascii_case(d))) + .map(|s| s.to_string()) + .collect(); + for c in customs { + if c.enabled { + ours.push(c.url); + } else { + declined.push(c.url); + } + } + (ours, declined) +} + +/// Mutate the stores in one load-mutate-save pass, reconcile the pool, then +/// record only what was applied as our contribution: retire fires solely for +/// contributed entries, so over-claiming would resurrect a dropped relay. +async fn apply_inbound_reconcile( + client: &Client, + plan: vector_core::inbox_relays::InboundReconcile, + remote_ts: u64, +) { + let norm = normalize_relay_url; + let mut customs = load_custom_relays().unwrap_or_default(); + let mut disabled = disabled_default_relays().unwrap_or_default(); + let (mut customs_dirty, mut defaults_dirty) = (false, false); + let (mut adopted, mut revived, mut retired) = (Vec::new(), Vec::new(), Vec::new()); + + for url in plan.adopt.iter().filter_map(|u| validate_relay_url(u).ok()) { + if customs.iter().any(|c| norm(&c.url) == norm(&url)) { + continue; + } + customs.push(CustomRelay { + url: url.clone(), + enabled: true, + mode: default_relay_mode(), + }); + customs_dirty = true; + adopted.push(url); + } + for url in &plan.revive { + let n = norm(url); + if let Some(pos) = disabled.iter().position(|d| norm(d) == n) { + revived.push(disabled.remove(pos)); + defaults_dirty = true; + } else if let Some(c) = customs.iter_mut().find(|c| norm(&c.url) == n && !c.enabled) { + c.enabled = true; + customs_dirty = true; + revived.push(c.url.clone()); + } + } + for url in &plan.retire { + let n = norm(url); + if let Some(d) = DEFAULT_RELAYS.iter().find(|d| norm(d) == n) { + if !disabled.iter().any(|x| norm(x) == n) { + disabled.push(d.to_string()); + defaults_dirty = true; + retired.push(url.clone()); + } + } else if let Some(c) = customs.iter_mut().find(|c| norm(&c.url) == n && c.enabled) { + c.enabled = false; + customs_dirty = true; + retired.push(url.clone()); + } + } + + if customs_dirty { + let _ = save_custom_relays(&customs); + } + if defaults_dirty { + let _ = save_disabled_default_relays(&disabled); + } + + for url in &adopted { + if let Err(e) = add_relay(client, url, capabilities_for_mode("both")).await { + vector_core::log_warn!("[Relay] Adopted relay add failed for {url}: {e}"); + } + add_relay_log(url, "info", "Adopted from your DM relay list"); // i18n-exempt: relay log, copied for bug reports + } + for url in &revived { + let mode = customs + .iter() + .find(|c| norm(&c.url) == norm(url)) + .map(|c| c.mode.clone()) + .unwrap_or_else(default_relay_mode); + let _ = add_relay(client, url, capabilities_for_mode(&mode)).await; + } + for url in &retired { + let _ = client.remove_relay(url.as_str()).await; + restore_discovery_role(client, url).await; + add_relay_log( + url, + "info", + "Disabled (removed from your DM relay list elsewhere)", // i18n-exempt: relay log, copied for bug reports + ); + } + + adopted.extend(revived); + vector_core::inbox_relays::note_contributed(&adopted); + vector_core::inbox_relays::note_list_seen(remote_ts); + vector_core::emit_event("relay_list_updated", &()); +} + +/// Status events, logs, ping metrics and the pool reconcile loop for this +/// session. Catch-up and zombie probing are `listen()`'s. +pub fn start_relay_monitor(client: &Client) { + if db::current_session() + .scoped::() + .swap(true, Ordering::SeqCst) + { + return; + } + vector_core::live_subs::set_catch_up(super::sync::catch_up); + + if let Some(monitor) = client.monitor() { + let mut rx = monitor.subscribe(); + db::spawn_bound(async move { + while let Ok(MonitorNotification::StatusChanged { relay_url, status }) = rx.recv().await + { + let url = relay_url.to_string(); + let level = match status { + RelayStatus::Disconnected | RelayStatus::Terminated => "warn", + RelayStatus::Banned => "error", + _ => "info", + }; + add_relay_log( + &url, + level, + &format!("Status changed to {}", status_label(status)), // i18n-exempt: relay log, copied for bug reports + ); + vector_core::emit_event( + "relay_status_change", + &json!({ "url": url, "status": status_label(status) }), + ); + + // A reconnected socket carries no live subscriptions: Vector owns reconnects. + if status == RelayStatus::Connected + && let Some(c) = state::nostr_client() + { + vector_core::resubscribe_relay_after_reconnect(&c, &relay_url).await; + let (has_read, has_gossip) = match c.relay(&relay_url).await { + Ok(Some(r)) => (r.capabilities().has_read(), r.capabilities().has_gossip()), + _ => (false, false), + }; + super::sync::relay_connected(url, has_read, has_gossip); + } + } + }); + } + + // A relay that sent nothing since the last look must answer a probe, or its socket + // is redialled: a phone's sockets can die without closing. + db::spawn_bound(async { + vector_core::rt::time::sleep(Duration::from_secs(30)).await; + let mut heard: HashMap = HashMap::new(); + while !db::session_stopped() { + if let Some(client) = state::nostr_client() { + for (url, relay) in client.relays().await { + if relay.status() != RelayStatus::Connected { + continue; + } + let received = relay.stats().bytes_received(); + if heard + .insert(url.clone(), received) + .is_some_and(|before| received > before) + { + update_relay_metrics(url.as_str(), |m| m.last_check = Some(now_secs())); + continue; + } + let start = std::time::Instant::now(); + // An id no event can have: the relay answers with a bare EOSE. + let probe_filter = Filter::new().id(EventId::from_byte_array([0; 32])); + let budget = vector_core::relay_request_timeout(Duration::from_secs(8)); + let probe = vector_core::rt::time::timeout( + budget + Duration::from_secs(2), + client + .fetch_events(ReqTarget::single(url.to_string(), [probe_filter])) + .timeout(budget), + ) + .await; + heard.insert(url.clone(), relay.stats().bytes_received()); + if matches!(probe, Ok(Ok(_))) { + let ping = start.elapsed().as_millis() as u64; + update_relay_metrics(url.as_str(), |m| { + m.ping_ms = Some(ping); + m.last_check = Some(now_secs()); + }); + } else { + add_relay_log(url.as_str(), "warn", "Health check failed; reconnecting"); // i18n-exempt: relay log, copied for bug reports + relay.disconnect(); + let _ = relay + .try_connect() + .timeout(vector_core::relay_connect_timeout(Duration::from_secs(8))) + .await; + } + } + } + vector_core::rt::time::sleep(Duration::from_secs(60)).await; + } + }); + + // nostr-sdk auto-reconnect is off, so a dropped relay can leave the pool + // for good; re-add what's missing and revive what's dead or wedged. + db::spawn_bound(async { + let norm = |u: &str| u.trim_end_matches('/').to_ascii_lowercase(); + let mut pending_since: HashMap = HashMap::new(); + vector_core::rt::time::sleep(Duration::from_secs(8)).await; + while !db::session_stopped() { + if let Some(client) = state::nostr_client() { + let pooled: Vec = client + .relays() + .await + .keys() + .map(|k| norm(k.as_str())) + .collect(); + for (url, mode) in desired_enabled_relays() { + if pooled.contains(&norm(&url)) + || client + .add_managed_relay(url.as_str()) + .capabilities(capabilities_for_mode(&mode)) + .await + .is_err() + { + continue; + } + add_relay_log( + &url, + "info", + "Reconcile: re-added missing relay; connecting...", // i18n-exempt: relay log, copied for bug reports + ); + if let Ok(Some(relay)) = client.relay(url.as_str()).await { + let _ = relay.try_connect().timeout(Duration::from_secs(8)).await; + } + } + + // A relay can sit in Pending with nothing driving it; forcing + // Terminated makes it connectable again. + let all = client.relays().all().await; + pending_since.retain(|k, _| all.keys().any(|u| norm(u.as_str()) == *k)); + for (url, relay) in all { + let key = norm(url.as_str()); + if relay.status() != RelayStatus::Pending { + pending_since.remove(&key); + continue; + } + let since = *pending_since + .entry(key.clone()) + .or_insert_with(std::time::Instant::now); + if since.elapsed() >= Duration::from_secs(15) { + add_relay_log(url.as_str(), "warn", "Wedged in Pending; forcing reconnect"); // i18n-exempt: relay log, copied for bug reports + relay.disconnect(); + let _ = relay.try_connect().timeout(Duration::from_secs(5)).await; + pending_since.insert(key, std::time::Instant::now()); + } + } + + for (_, relay) in client.relays().await { + if matches!( + relay.status(), + RelayStatus::Terminated | RelayStatus::Sleeping + ) { + let _ = relay.try_connect().timeout(Duration::from_secs(5)).await; + } + } + } + vector_core::rt::time::sleep(Duration::from_secs(10)).await; + } + }); +} + +// ============================================================================ +// Blossom +// ============================================================================ + +/// A relay as the Network list shows it. +#[derive(Clone)] +pub struct RelayRow { + pub url: String, + pub status: &'static str, + pub is_default: bool, + pub enabled: bool, + pub mode: String, +} + +pub async fn relay_rows() -> Vec { + let customs = load_custom_relays().unwrap_or_default(); + let disabled = disabled_default_relays().unwrap_or_default(); + let pool = match state::nostr_client() { + Some(c) => c.relays().await, + None => Default::default(), + }; + let status_of = |url: &str| { + pool.iter() + .find(|(u, _)| { + u.as_str() + .trim_end_matches('/') + .eq_ignore_ascii_case(url.trim_end_matches('/')) + }) + .map(|(_, r)| status_label(r.status())) + .unwrap_or("disconnected") + }; + let mut out: Vec = DEFAULT_RELAYS + .iter() + .map(|url| { + let enabled = !disabled.iter().any(|d| d.eq_ignore_ascii_case(url)); + RelayRow { + url: url.to_string(), + status: if enabled { status_of(url) } else { "disabled" }, + is_default: true, + enabled, + mode: "both".into(), + } + }) + .collect(); + out.extend(customs.into_iter().map(|c| RelayRow { + status: if c.enabled { + status_of(&c.url) + } else { + "disabled" + }, + url: c.url, + is_default: false, + enabled: c.enabled, + mode: c.mode, + })); + out +} + +pub fn relay_metrics_of(url: &str) -> RelayMetrics { + relay_metrics() + .read() + .ok() + .and_then(|m| m.get(&log_key(url)).cloned()) + .unwrap_or_default() +} + +pub fn relay_logs_of(url: &str) -> Vec { + relay_logs() + .read() + .ok() + .and_then(|l| l.get(&log_key(url)).map(|l| l.iter().cloned().collect())) + .unwrap_or_default() +} + +// Media servers +// ============================================================================ + +use vector_core::blossom_servers as bs; + +fn probe_server(url: String) { + db::spawn_bound(async move { + if state::nostr_client().is_none() { + return; + } + let Ok(signer) = vector_core::signer::active_signer() else { + return; + }; + if vector_core::blossom_info::refresh_all( + signer.clone(), + vec![url.clone()], + Duration::from_secs(60), + ) + .await + > 0 + { + vector_core::traits::emit_event("blossom_info_updated", &()); + } + if let Ok(n) = vector_core::blossom::probe_servers_for_octet_stream(signer, vec![url]).await + && n > 0 + { + vector_core::traits::emit_event("blossom_capabilities_updated", &()); + } + }); +} + +pub fn server_rows() -> Vec { + bs::list_all_servers() +} + +pub async fn add_server(url: String) -> Result<(), String> { + db::scoped(async move { + let normalized = bs::validate_url(&url)?; + if bs::is_default_server(&normalized) { + return Err(crate::t::server_is_default().to_string()); + } + let key = normalized.to_lowercase(); + let mut customs = bs::load_custom_blossom_servers()?; + if customs + .iter() + .any(|c| c.url.trim_end_matches('/').to_lowercase() == key) + { + return Err(crate::t::server_exists().to_string()); + } + customs.push(bs::CustomBlossomServer { + url: normalized.clone(), + enabled: true, + }); + bs::save_custom_blossom_servers(&customs)?; + bs::refresh_cache(); + bs::republish_blossom_servers_debounced(); + probe_server(normalized); + Ok(()) + }) + .await +} + +pub async fn remove_server(url: String) -> Result { + db::scoped(async move { + let target = url.trim().trim_end_matches('/').to_lowercase(); + let mut customs = bs::load_custom_blossom_servers()?; + let before = customs.len(); + customs.retain(|c| c.url.trim_end_matches('/').to_lowercase() != target); + if customs.len() == before { + return Ok(false); + } + bs::save_custom_blossom_servers(&customs)?; + let _ = vector_core::blossom_capabilities::purge_server(&url); + bs::refresh_cache(); + bs::republish_blossom_servers_debounced(); + Ok(true) + }) + .await +} + +/// Enable or disable a server, default or custom; re-enabling probes it afresh. +pub async fn toggle_server(url: String, enabled: bool) -> Result<(), String> { + db::scoped(async move { + let key = url.trim().trim_end_matches('/').to_lowercase(); + if bs::is_default_server(&url) { + let mut disabled = bs::load_disabled_default_blossom_servers()?; + if enabled { + disabled.retain(|d| d.trim_end_matches('/').to_lowercase() != key); + } else if !disabled + .iter() + .any(|d| d.trim_end_matches('/').to_lowercase() == key) + { + disabled.push(key); + } + bs::save_disabled_default_blossom_servers(&disabled)?; + } else { + let mut customs = bs::load_custom_blossom_servers()?; + customs + .iter_mut() + .find(|c| c.url.trim_end_matches('/').to_lowercase() == key) + .ok_or_else(|| crate::t::server_not_found().to_string())? + .enabled = enabled; + bs::save_custom_blossom_servers(&customs)?; + } + bs::refresh_cache(); + bs::republish_blossom_servers_debounced(); + if enabled { + probe_server(url); + } else { + let _ = vector_core::blossom_capabilities::purge_server(&url); + } + Ok(()) + }) + .await +} + +/// What a media server's dialog paints before asking the network: the held document, this +/// device's history with it, and the status they imply. +pub async fn server_snapshot(url: String, enabled: bool) -> (Option, Option, vector_core::blossom_stats::ServerStatus) { + db::scoped(async move { + let info = vector_core::blossom_info::cached(&url).and_then(|i| serde_json::to_value(i).ok()); + let stats = vector_core::blossom_stats::stats_for(&url).and_then(|s| serde_json::to_value(s).ok()); + (info, stats, vector_core::blossom_stats::status_for(&url, enabled)) + }) + .await +} + +/// The server's information document for this account, refetched past half a minute. +pub async fn server_info(url: String) -> Result, String> { + db::scoped(async move { + let signer = vector_core::signer::active_signer()?; + let info = vector_core::blossom_info::refresh(&signer, &url, Duration::from_secs(30)).await?; + Ok(info.and_then(|i| serde_json::to_value(i).ok())) + }) + .await +} + +pub async fn server_stats(url: String, enabled: bool) -> (Option, vector_core::blossom_stats::ServerStatus) { + db::scoped(async move { + let stats = vector_core::blossom_stats::stats_for(&url).and_then(|s| serde_json::to_value(s).ok()); + (stats, vector_core::blossom_stats::status_for(&url, enabled)) + }) + .await +} + +/// What uploads have taught us this server takes. +pub async fn server_caps(url: String) -> Result, String> { + db::scoped(async move { + let list = vector_core::blossom_capabilities::list_for_server(&url)?; + Ok(list.into_iter().filter_map(|c| serde_json::to_value(c).ok()).collect()) + }) + .await +} diff --git a/crates/vector-gpui/src/backend/nip55.rs b/crates/vector-gpui/src/backend/nip55.rs new file mode 100644 index 000000000..89708313c --- /dev/null +++ b/crates/vector-gpui/src/backend/nip55.rs @@ -0,0 +1,110 @@ +//! Accounts whose identity lives in a signer app on the phone (NIP-55, such as Amber): nothing +//! secret is stored here, and every signature is the signer app's. + +use nostr_sdk::prelude::*; +use vector_core::db; +#[cfg(target_os = "android")] +use zeroize::Zeroizing; + +/// A signer app this device can sign with is installed. +pub fn installed() -> bool { + matches!(vector_core::nip55_is_installed(), Ok(true)) +} + +/// The paired identity while this account signs through a signer app, and whether that app is +/// still installed. +pub fn status() -> Option<(String, bool)> { + if db::get_signer_type().ok()?.as_str() != "nip55" { + return None; + } + let hex = db::get_nip55_user_pubkey().ok().flatten()?; + let npub = PublicKey::from_hex(&hex).ok()?.to_bech32().ok()?; + Some((npub, installed())) +} + +/// Pair with the signer app, then stage the account for its security step, as a key import +/// would. An identity already on this device becomes the one to unlock instead. +#[cfg(target_os = "android")] +pub async fn login() -> Result { + use super::account::{self, Imported}; + super::security::refuse_if_migrating()?; + if !installed() { + return Err(crate::t::login_signer_app_missing().into()); + } + if vector_core::state::nostr_client().is_some() { + return Err(crate::t::login_already_signed_in().into()); + } + let (pk, package) = vector_core::nip55_pair().await?; + let npub = pk.to_bech32().map_err(|e| e.to_string())?; + if account::is_committed(&npub) { + db::write_active_account_file(&npub)?; + return Ok(Imported::Existing(npub)); + } + vector_core::set_pending_nip55_setup(pk.to_hex(), package.clone()); + vector_core::set_signer_kind(vector_core::SignerKind::Nip55); + crate::android::external_signer::set_signer_package(package); + vector_core::state::set_my_public_key(pk); + account::install_client(); + account::insert_own_profile(&npub).await; + account::set_pending(npub.clone()); + Ok(Imported::Staged(npub)) +} + +/// The staged signer-app account's commit: a key, when it has one, opens only the local data, +/// proven later by the canary it seals. +#[cfg(target_os = "android")] +pub(super) async fn commit( + sealed: Option<(Zeroizing<[u8; 32]>, vector_core::crypto::Kdf)>, + security_type: &str, + wrap: Option, +) -> Result<(), String> { + let (hex, package) = vector_core::pending_nip55_setup().ok_or_else(|| crate::t::login_signer_setup_lost().to_string())?; + super::account::open_pending().await?; + let canary = sealed + .as_ref() + .map(|(key, _)| vector_core::crypto::encrypt_with_key(db::at_rest::NIP55_PIN_CANARY, key)) + .transpose()?; + let kdf_row = sealed.as_ref().and_then(|(_, kdf)| kdf.descriptor()); + let encrypted = sealed.is_some(); + db::commit_nip55_account_setup( + &hex, + &package, + encrypted, + encrypted.then_some(security_type), + wrap.as_deref(), + canary.as_deref(), + kdf_row.as_deref(), + )?; + vector_core::clear_pending_nip55_setup(); + if let Some((key, _)) = &sealed { + vector_core::ENCRYPTION_KEY.set(**key, &[&vector_core::MY_SECRET_KEY]); + } + vector_core::state::set_encryption_enabled(encrypted); + super::account::touch_last_active(); + vector_core::blossom_servers::refresh_cache(); + Ok(()) +} + +/// Pair with the signer app again, as after it was reinstalled or its permission revoked. A +/// different identity is refused: this account's data must never mix with another's. +#[cfg(target_os = "android")] +pub async fn reauthorize() -> Result<(), String> { + if vector_core::signer_kind() != vector_core::SignerKind::Nip55 { + return Err(crate::t::settings_signer_not_offline().into()); + } + if !installed() { + vector_core::set_nip55_state(vector_core::Nip55State::Missing); + return Err(crate::t::settings_signer_app_missing().into()); + } + let expected = db::get_nip55_user_pubkey()? + .ok_or_else(|| crate::t::login_signer_setup_lost().to_string())? + .to_ascii_lowercase(); + let (pk, package) = vector_core::nip55_pair().await?; + if pk.to_hex() != expected { + return Err(crate::t::settings_signer_other_identity().into()); + } + db::set_nip55_signer_package(&package)?; + crate::android::external_signer::set_signer_package(package); + vector_core::set_nip55_state(vector_core::Nip55State::Ready); + Ok(()) +} diff --git a/crates/vector-gpui/src/backend/notify.rs b/crates/vector-gpui/src/backend/notify.rs new file mode 100644 index 000000000..9ecaf5b66 --- /dev/null +++ b/crates/vector-gpui/src/backend/notify.rs @@ -0,0 +1,388 @@ +//! OS notifications for what arrives while Vector isn't in front, through the desktop client's +//! notifier and its native backends. Which messages ring follows the desktop's event handlers. + +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::OnceLock; + +use serde_json::json; +use vector_core::notify::{self, MessageClass}; +use vector_core::{Message, STATE, VectorCore, db}; +use vector_media::services::native_notify; +use vector_media::services::{NotificationData, strip_content_for_preview}; + +static FOCUSED: AtomicBool = AtomicBool::new(true); + +static PINNED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(true); + +/// The open chat shows its newest message: only then has an arrival been seen. +pub fn set_pinned(pinned: bool) { + PINNED.store(pinned, Ordering::Relaxed); +} + +pub fn pinned() -> bool { + PINNED.load(Ordering::Relaxed) +} + +pub fn set_focused(focused: bool) { + FOCUSED.store(focused, Ordering::Relaxed); +} + +pub fn focused() -> bool { + FOCUSED.load(Ordering::Relaxed) +} + +/// Hooks the notifier up to this client. macOS and Windows register with the OS here, on the +/// main thread, so a click that launches Vector finds it; Linux waits for its first message. +pub fn install() { + // The Tauri client's identity: this client replaces it, so its toast clicks land here. + // i18n-exempt: the product name + tauri::set_config(tauri::Config { identifier: "io.vectorapp".into(), product_name: Some("Vector".into()) }); + tauri::set_window(tauri::WindowHooks { + focused: || FOCUSED.load(Ordering::Relaxed), + reveal: || super::emit("notify_reveal", serde_json::Value::Null), + }); + vector_media::notify_host::set(vector_media::notify_host::Host { + mark_read: |chat| Box::pin(mark_read(chat)), + mute: |chat, ms| Box::pin(super::prefs::set_notify_mute(chat, ms)), + reply: |chat, text| Box::pin(reply(chat, text)), + open: |chat, message, account| { + super::emit( + "deep_link_action", + json!({ "action_type": "chat", "target": chat, "message": message, "account": account }), + ) + }, + sound: ring, + }); + #[cfg(not(target_os = "linux"))] + init(); +} + +fn init() { + static DONE: OnceLock<()> = OnceLock::new(); + DONE.get_or_init(|| { + if let Some(app) = vector_media::TAURI_APP.get() { + native_notify::init(app); + } + }); +} + +/// The freedesktop server's signals arrive on the thread that subscribed, which must run a +/// GLib main loop. +fn ready() { + #[cfg(target_os = "linux")] + { + static DONE: OnceLock<()> = OnceLock::new(); + DONE.get_or_init(|| { + let (tx, rx) = std::sync::mpsc::channel(); + let posted = crate::miniapp::on_glib(move || { + init(); + let _ = tx.send(()); + }); + if posted.is_ok() { + let _ = rx.recv_timeout(std::time::Duration::from_secs(5)); + } + }); + } +} + +async fn mark_read(chat_id: String) -> bool { + super::messaging::mark_as_read(chat_id, None).await +} + +async fn reply(chat_id: String, text: String) -> Result { + if chat_id.starts_with("npub1") { + super::messaging::send(chat_id, text, String::new(), None).await?; + } else { + super::community::send(chat_id.clone(), text, String::new(), None).await?; + mark_read(chat_id).await; + } + Ok(String::new()) +} + +fn ring() { + if super::prefs::sql("notif_global_mute").as_deref() == Some("true") { + return; + } + let sound = super::prefs::sql("notif_sound").unwrap_or_default(); + super::sound::play(super::sound::Sound::parse(&sound)); +} + +/// Core's privacy transform, with its English placeholders said in the reader's language. +fn hide(data: &mut NotificationData, privacy: notify::ContentPrivacy) { + use notify::ContentPrivacy as P; + data.apply_content_privacy(privacy); + match privacy { + P::Full => {} + P::HideSender if data.group_name.is_some() => {} + P::HideSender => data.title = crate::coretext::say(&data.title).into_owned(), + P::HideContent | P::HideAll => data.body = crate::coretext::say(&data.body).into_owned(), + } +} + +/// The desktop notifier's path, applying privacy here: it would apply it again in English. +fn show(mut data: NotificationData) { + if FOCUSED.load(Ordering::Relaxed) { + return; + } + ready(); + hide(&mut data, notify::ContentPrivacy::load()); + // The phone's message channel carries its own sound. + #[cfg(target_os = "android")] + crate::android::background_sync::post_notification_jni( + &data.title, + &data.body, + data.avatar_path.as_deref(), + data.chat_id.as_deref(), + data.sender_name.as_deref(), + data.group_name.as_deref(), + data.group_avatar_path.as_deref(), + ); + #[cfg(not(target_os = "android"))] + { + ring(); + if let Err(e) = native_notify::show(&data) { + log::warn!("notification: {e}"); + } + } +} + +fn file_body(msg: &Message) -> String { + let ext = msg.attachments.first().map(|a| a.extension.as_str()).unwrap_or("file"); + crate::t::chats_preview_sent(crate::data::file_type(ext).1.as_ref()).into() +} + +/// A new DM or file from someone else, unless the chat is set quieter than everything. +pub async fn direct(chat_id: &str, msg: &Message) { + let rings = STATE + .lock() + .await + .get_chat(chat_id) + .is_none_or(|c| notify::ring_for_chat(c) == notify::NotifyLevel::All); + if !rings { + return; + } + let gate = notify::StreamGate::load(); + let (name, body, avatar) = { + let state = STATE.lock().await; + let sender = notify::sender(&state, &gate, chat_id, &crate::t::notify_new_message()); + let body = if msg.attachments.is_empty() { + strip_content_for_preview(¬ify::resolve_mentions(&msg.content, &state, &gate)) + } else { + file_body(msg) + }; + (sender.name, body, sender.avatar) + }; + show( + NotificationData::direct_message(name, body, avatar, chat_id.to_string()) + .with_message_id(msg.id.clone()) + .with_expiry(msg.expiration), + ); +} + +/// What a contact's push says, for a phone whose connection was down: their words when their +/// app sealed some in, else that they wrote. +#[cfg(target_os = "android")] +pub async fn pushed(npub: &str, text: String) { + let (name, avatar) = known_as(npub).await; + let body = if text.is_empty() { crate::t::core_notify_sent_you_a_message().to_string() } else { text }; + show(NotificationData::direct_message(name, body, avatar, npub.to_string())); +} + +/// A push no contact here vouches for: that something arrived, and nothing it claims. +#[cfg(target_os = "android")] +pub fn pushed_unknown() { + crate::android::background_sync::post_notification_jni( + &crate::t::notify_new_message(), + &crate::t::notify_you_have_a_new_message(), + None, + None, + None, + None, + None, + ); +} + +/// The name and picture `npub` goes by here; a stranger by the start of their npub. +#[cfg(target_os = "android")] +pub async fn known_as(npub: &str) -> (String, Option) { + let gate = notify::StreamGate::load(); + let fallback = format!("{}…", &npub[..npub.len().min(14)]); + let state = STATE.lock().await; + let sender = notify::sender(&state, &gate, npub, &fallback); + (sender.name, sender.avatar) +} + +/// A Community message rings by its channel's level: everything, or only a ping (an +/// @mention, a reply to us, a standing Role mention, or an allowed @everyone). A blocked or +/// DM-muted sender, or a post its readers collapse, never rings. +pub async fn community(chat_id: &str, msg: &Message) { + if msg.mine { + return; + } + let sender_npub = msg.npub.as_deref().unwrap_or_default(); + if sender_npub.is_empty() { + return; + } + let Some(community_id) = db::community::community_id_for_channel(chat_id).ok().flatten() else { + return; + }; + if VectorCore.post_silenced(&community_id, chat_id, sender_npub) { + return; + } + let everyone = msg.mentions_everyone() + && notify::everyone_allowed(Some(&community_id)) + && VectorCore + .member_has_permission(&community_id, sender_npub, vector_core::community::roles::Permissions::MENTION_EVERYONE) + .unwrap_or(false); + let role = VectorCore.role_mentions_ping_me(&community_id, sender_npub, &msg.content, &msg.role_mentions); + let reply = !msg.replied_to.is_empty() && db::events::is_own_event(&msg.replied_to); + let class = if everyone { + MessageClass::Everyone + } else if msg.mentions_me() || reply || role { + MessageClass::Mention + } else { + MessageClass::Normal + }; + let rings = { + let state = STATE.lock().await; + let Some(chat) = state.get_chat(chat_id) else { return }; + let quiet = state.get_profile(sender_npub).is_some_and(|p| p.flags.is_blocked()) + || state.get_chat(sender_npub).is_some_and(notify::muted_for_chat); + !quiet && notify::passes(notify::ring_for_chat(chat), class) + }; + if !rings { + return; + } + let gate = notify::StreamGate::load(); + let nickname = VectorCore.member_nickname(&community_id, sender_npub); + let (sender, community_name, avatar, content) = { + let state = STATE.lock().await; + let notify::Sender { name, avatar } = notify::sender_in(&state, &gate, sender_npub, &crate::t::notify_someone(), nickname); + let community_name = state + .get_chat(chat_id) + .and_then(|c| c.metadata.get_name().map(str::to_string)) + .unwrap_or_else(|| crate::t::community_unnamed().into()); + let content = if msg.attachments.is_empty() { + strip_content_for_preview(¬ify::resolve_mentions(&msg.content, &state, &gate)) + } else { + file_body(msg) + }; + (name, community_name, avatar, content) + }; + let icon = db::community::community_image(&community_id, false) + .ok() + .flatten() + .and_then(|icon| super::images::cached_avatar(&icon.url)); + show( + NotificationData::community_message(sender, community_name, content, avatar, icon, chat_id.to_string()) + .with_message_id(msg.id.clone()) + .with_sender(sender_npub.to_string()) + .with_expiry(msg.expiration), + ); +} + +/// What the dock or taskbar badge shows: chats that ring for everything, as on desktop. +pub fn recount() { + let Some(rt) = super::RT.get() else { return }; + let _runtime = rt.enter(); + db::spawn_bound(async { + if !STATE.lock().await.unread_seeded { + let counts = db::events::unread_counts().await.unwrap_or_default(); + STATE.lock().await.unread_seed(counts); + } + let total = STATE.lock().await.sum_unread(); + vector_core::emit_event("unread_total", &json!(total)); + }); +} + +/// The chat was read: its notifications go. +pub fn read(chat_id: &str) { + #[cfg(target_os = "android")] + crate::android::background_sync::cancel_notification_jni(chat_id); + native_notify::remove_chat(chat_id); +} + +pub fn deleted(message_id: &str) { + native_notify::remove_message(message_id); +} + +pub fn blocked(npub: &str) { + // The phone's shade keeps one notification per chat, and a DM's chat is its sender. + #[cfg(target_os = "android")] + crate::android::background_sync::cancel_notification_jni(npub); + native_notify::remove_sender(npub); +} + +/// The account is leaving this machine's screen: its notifications leave with it. +pub fn account_gone(npub: &str) { + #[cfg(target_os = "android")] + crate::android::background_sync::cancel_all_message_notifications_jni(); + native_notify::remove_account(npub); +} + +/// A reply typed into a notification before its account was logged in. +pub fn logged_in() { + native_notify::flush_pending_reply(); +} + +#[cfg(test)] +mod privacy_tests { + use super::*; + use vector_core::notify::ContentPrivacy as P; + + fn dm() -> NotificationData { + // i18n-exempt: test fixture + NotificationData::direct_message("Alice".into(), "see you at 8".into(), None, "npub1x".into()) + } + + fn group() -> NotificationData { + // i18n-exempt: test fixture + NotificationData::community_message("Alice".into(), "Book Club".into(), "see you at 8".into(), None, None, "chan".into()) + } + + /// In English it says exactly what core's own transform says, and every placeholder it + /// puts on screen has a translation. + #[test] + fn hidden_previews_match_core_and_are_translated() { + for privacy in [P::Full, P::HideContent, P::HideSender, P::HideAll] { + for make in [dm, group] { + let (mut ours, mut core) = (make(), make()); + hide(&mut ours, privacy); + core.apply_content_privacy(privacy); + assert_eq!((&ours.title, &ours.body, &ours.sender_name), (&core.title, &core.body, &core.sender_name)); + let placeholder = match privacy { + P::Full => None, + P::HideSender if core.group_name.is_some() => None, + P::HideSender => Some(core.title.clone()), + P::HideContent | P::HideAll => Some(core.body.clone()), + }; + if let Some(p) = placeholder { + assert!(matches!(crate::coretext::say(&p), std::borrow::Cow::Owned(_)), "no translation for {p:?}"); + } + } + } + } +} + +#[cfg(all(test, target_os = "linux"))] +mod tests { + use super::*; + + /// Needs a session bus with a notification server; run under `dbus-launch` beside one. + #[test] + #[ignore] + fn shows_and_retracts_through_the_session_bus() { + let rt = tokio::runtime::Runtime::new().unwrap(); + tauri::async_runtime::set(rt.handle().clone()); + tauri::set_data_dir(std::env::temp_dir().join(format!("vector-notify-{}", std::process::id()))); + let _ = vector_media::TAURI_APP.set(tauri::AppHandle::new(|_, _| {})); + install(); + set_focused(false); + let chat = "npub1qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq".to_string(); + // i18n-exempt: test fixture + show(NotificationData::direct_message("Alice".into(), "hi **there**".into(), None, chat.clone()).with_message_id("ab".into())); + std::thread::sleep(std::time::Duration::from_secs(1)); + read(&chat); + std::thread::sleep(std::time::Duration::from_secs(1)); + } +} diff --git a/crates/vector-gpui/src/backend/packs.rs b/crates/vector-gpui/src/backend/packs.rs new file mode 100644 index 000000000..3916c435c --- /dev/null +++ b/crates/vector-gpui/src/backend/packs.rs @@ -0,0 +1,235 @@ +//! Making and deleting our own emoji packs: the uploads, the publish, the cleanup. + +use std::sync::Arc; + +use vector_core::emoji_packs::{self, EmojiPack, PackEmoji}; + +use crate::shared::image::{UploadImageKind, prepare_upload_image, upload_mime_for}; + +pub const MAX_EMOJI_BYTES: usize = 256 * 1024; + +/// What the picker accepts: web formats as they are, and what the image crate reads, as PNG. +pub const IMPORT_EXTS: &[&str] = &[ + "png", "jpg", "jpeg", "gif", "webp", "tiff", "tif", "bmp", "ico", "jxl", +]; + +/// A picked file as the creator will hold it: web-safe bytes, never an SVG. +pub fn import(path: &std::path::Path) -> Result, String> { + let bytes = std::fs::read(path).map_err(|e| e.to_string())?; + if matches!( + vector_core::crypto::mime_from_magic_bytes(&bytes), + "image/png" | "image/jpeg" | "image/gif" | "image/webp" + ) { + return Ok(bytes); + } + let mut reader = image::ImageReader::new(std::io::Cursor::new(&bytes)) + .with_guessed_format() + .map_err(|e| format!("sniff: {e}"))?; // i18n-exempt: developer error + reader.limits(vector_core::crypto::bounded_image_limits()); + let img = reader + .decode() + .map_err(|_| crate::t::packs_image_unreadable().to_string())?; + let mut png = Vec::new(); + img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png) + .map_err(|e| format!("png encode: {e}"))?; // i18n-exempt: developer error + Ok(png) +} + +/// The picture's canvas size, animated or not. +pub fn dims(bytes: &[u8]) -> Option<(u32, u32)> { + image::ImageReader::new(std::io::Cursor::new(bytes)) + .with_guessed_format() + .ok()? + .into_dimensions() + .ok() +} + +/// Upload one emoji or pack logo; the URL it landed at, its bytes kept as the local copy. +pub async fn upload(bytes: Arc>, icon: bool) -> Result { + if bytes.len() > MAX_EMOJI_BYTES { + return Err(crate::t::packs_file_too_large(MAX_EMOJI_BYTES / 1024, bytes.len() / 1024).to_string()); + } + if bytes.is_empty() { + return Err(crate::t::packs_file_empty().into()); + } + vector_core::state::nostr_client().ok_or("Nostr client not initialised")?; // i18n-exempt: developer error + let signer = + vector_core::signer::active_signer().map_err(|e| format!("Failed to get signer: {e}"))?; // i18n-exempt: developer error + let servers = vector_core::blossom_servers::compute_enabled_servers(); + if servers.is_empty() { + return Err(crate::t::packs_no_media_servers().into()); + } + let source = bytes.clone(); + let prepared = + tokio::task::spawn_blocking(move || prepare_upload_image(&source, UploadImageKind::Emoji)) + .await + .map_err(|e| e.to_string())??; + let mime = upload_mime_for(prepared.extension); + let data = Arc::new(prepared.bytes); + // Emojis are tiny: a server silent for 10s is treated as dead and failed over. + let stall = vector_core::net::tor_http_timeout(std::time::Duration::from_secs(10)); + let url = vector_core::blossom::upload_blob_with_failover( + signer, + servers, + data.clone(), + Some(mime), + Some(stall), + ) + .await?; + super::images::precache_emoji(&url, &data, icon); + Ok(url) +} + +fn new_identifier() -> String { + use rand::{Rng, distributions::Alphanumeric, thread_rng}; + thread_rng() + .sample_iter(&Alphanumeric) + .take(12) + .map(char::from) + .collect() +} + +/// Publish the pack (`identifier` keeps an edit on the same coordinate). +pub async fn publish( + identifier: Option, + title: String, + image_url: String, + emojis: Vec<(String, String)>, +) -> Result { + let emojis: Vec = emojis + .into_iter() + .filter(|(s, u)| !s.trim().is_empty() && !u.trim().is_empty()) + .map(|(shortcode, url)| PackEmoji { + shortcode: shortcode.trim().into(), + url: url.trim().into(), + sha256: None, + }) + .collect(); + if emojis.is_empty() { + return Err(crate::t::packs_needs_emoji().into()); + } + let pack = EmojiPack { + id: String::new(), + pubkey: String::new(), + identifier: identifier + .filter(|s| !s.trim().is_empty()) + .unwrap_or_else(new_identifier), + title: title.trim().into(), + image_url: image_url.trim().into(), + description: String::new(), + emojis, + is_own: true, + updated_at: 0, + status: emoji_packs::PACK_STATUS_ACTIVE, + }; + emoji_packs::publish_pack(&pack).await +} + +pub async fn delete_blob(url: String) -> Result<(), String> { + vector_core::state::nostr_client().ok_or("Nostr client not initialised")?; // i18n-exempt: developer error + let signer = + vector_core::signer::active_signer().map_err(|e| format!("Failed to get signer: {e}"))?; // i18n-exempt: developer error + vector_core::blossom::delete_blob_by_url(signer, &url).await +} + +/// Tombstone our own pack and drop it locally. +pub async fn delete(id: String) -> Result<(), String> { + emoji_packs::delete_own_pack(&id).await +} + +/// The URLs whose host definitively deleted the file (404/410), past the warm local cache. +pub async fn gone(urls: Vec) -> Vec { + use futures::StreamExt; + let mut deduped: Vec = Vec::new(); + for u in urls { + if deduped.len() < 64 && !deduped.contains(&u) { + deduped.push(u); + } + } + futures::stream::iter(deduped.into_iter().map(|url| async move { + let gone = vector_core::net::validate_url_not_private(&url).is_ok() + && matches!( + vector_core::net::remote_status(&url, std::time::Duration::from_secs(10)).await, + Some(404 | 410) + ); + gone.then_some(url) + })) + .buffer_unordered(6) + .filter_map(|u| async move { u }) + .collect() + .await +} + +/// `THEME_EMOJI_PACKS`: the pack a theme pins, outside the equip slots and the kind-10030 list. +const THEME_PACKS: &[(&str, &str)] = &[( + "vector", + "naddr1qqxx7mt2f945yvj0fdg8x3czyzu0jtnpuuw5tp4wdlnfwrmnm58ahzgpp9vfut6p00h5gkam4ykg6qcyqqq82nsstfm4j", +)]; + +/// The picker's packs in display order, each cut to the display cap. +pub struct Equipped { + pub packs: Vec, + /// Where the theme's pinned pack sits, when it is not a subscription. + pub theme: Option, + /// The theme pins a pack this account has never cached: fetch it, then load again. + pub fetch: Option, +} + +/// Cache-only, so the rail paints before any relay answers. +pub async fn equipped(refresh: bool) -> Result { + let mut packs = if refresh { + emoji_packs::refresh_subscribed_packs().await? + } else { + emoji_packs::load_all_packs()? + }; + let cap = emoji_packs::effective_display_cap(); + for p in &mut packs { + p.emojis.truncate(cap); + } + let theme = super::prefs::sql("theme").unwrap_or_else(|| "vector".into()); + let naddr = THEME_PACKS + .iter() + .find(|(t, _)| *t == theme) + .map(|(_, n)| *n) + .filter(|n| !packs.iter().any(|p| p.id == *n)); + let cached = naddr + .and_then(|n| emoji_packs::parse_naddr(n).ok()) + .and_then(|a| emoji_packs::load_cached_pack(&a.to_addr_string()).ok().flatten()) + .filter(|p| !p.emojis.is_empty()); + let Some(mut pin) = cached else { + emoji_packs::set_theme_emoji_tags(Vec::new()); + return Ok(Equipped { + packs, + theme: None, + fetch: naddr.map(str::to_string), + }); + }; + pin.emojis.truncate(cap); + emoji_packs::set_theme_emoji_tags( + pin.emojis + .iter() + .map(|e| (e.shortcode.clone(), e.url.clone())) + .collect(), + ); + let anchor = emoji_packs::get_theme_slot_anchor().unwrap_or_default(); + let at = if anchor.is_empty() { + 0 + } else { + packs.iter().position(|p| p.id == anchor).map_or(0, |i| i + 1) + }; + packs.insert(at, pin); + Ok(Equipped { + packs, + theme: Some(at), + fetch: None, + }) +} + +/// Fetches the theme's pack into the cache; true when there is now one to show. +pub async fn fetch_theme(naddr: String) -> bool { + emoji_packs::get_or_fetch_theme_pack(&naddr) + .await + .ok() + .flatten() + .is_some_and(|p| !p.emojis.is_empty()) +} diff --git a/crates/vector-gpui/src/backend/pasted.rs b/crates/vector-gpui/src/backend/pasted.rs new file mode 100644 index 000000000..5c4ea24f0 --- /dev/null +++ b/crates/vector-gpui/src/backend/pasted.rs @@ -0,0 +1,71 @@ +//! A pasted picture has no file of its own: it's held in memory under a path that is never +//! written, so the preview and the send read it without a plain copy touching disk. + +use std::collections::HashMap; +use std::path::{Path, PathBuf}; +use std::sync::{Arc, Mutex}; + +struct Pasted; +type Held = Mutex>>>; + +fn held() -> Arc { + vector_core::db::current_session().scoped::() +} + +/// `bytes` held under a fresh `pasted_image.` path. +pub fn hold(bytes: Vec, ext: &str) -> PathBuf { + hold_named(bytes, &format!("pasted_image.{ext}")) +} + +/// `bytes` held under a fresh path ending in `name`. +pub fn hold_named(bytes: Vec, name: &str) -> PathBuf { + let path = slot().join(name); + hold_at(path.clone(), bytes); + path +} + +/// `bytes` held under `path`, which is never written. +pub fn hold_at(path: PathBuf, bytes: Vec) { + held().lock().unwrap_or_else(|e| e.into_inner()).insert(path, Arc::new(bytes)); +} + +fn slot() -> PathBuf { + static SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let n = SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + super::archive::work_dir().join(format!("pasted-{n}")) +} + +pub fn get(path: &Path) -> Option>> { + held().lock().unwrap_or_else(|e| e.into_inner()).get(path).cloned() +} + +pub fn forget(path: &Path) { + held().lock().unwrap_or_else(|e| e.into_inner()).remove(path); +} + +/// What a preview or send reads: the held bytes, else the file (sealed or plain). +pub fn read(path: &Path) -> std::io::Result>> { + if let Some(b) = get(path) { + return Ok(b); + } + vector_core::vcache::read(path).map(|mut b| Arc::new(std::mem::take(&mut *b))).map_err(std::io::Error::other) +} + +pub fn len(path: &Path) -> Option { + get(path).map(|b| b.len() as u64).or_else(|| std::fs::metadata(path).ok().map(|m| m.len())) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_pasted_picture_is_read_from_memory_and_never_written() { + let path = hold(vec![7; 12], "png"); + assert!(!path.exists() && !path.parent().unwrap().exists()); + assert_eq!(len(&path), Some(12)); + assert_eq!(*read(&path).unwrap(), vec![7; 12]); + super::super::archive::forget(&path); + assert!(get(&path).is_none() && read(&path).is_err()); + } +} diff --git a/crates/vector-gpui/src/backend/pivx.rs b/crates/vector-gpui/src/backend/pivx.rs new file mode 100644 index 000000000..f0970479a --- /dev/null +++ b/crates/vector-gpui/src/backend/pivx.rs @@ -0,0 +1,111 @@ +//! The PIVX wallet over the desktop's promo-code wallet (`pivx.rs`): balances, deposits, +//! sends into a chat, claims and withdrawals. + +use vector_media::pivx as px; + +pub use px::PivxPromo; + +fn handle() -> Result { + vector_media::TAURI_APP.get().copied().ok_or_else(|| crate::t::pivx_not_ready().to_string()) +} + +pub async fn balance() -> Result { + px::pivx_get_wallet_balance(handle()?).await +} + +pub async fn promos(force: bool) -> Result, String> { + px::pivx_refresh_balances(handle()?, Some(force)).await +} + +pub async fn create_promo() -> Result { + px::pivx_create_promo(handle()?).await +} + +pub async fn send_amount(receiver: String, amount: f64) -> Result { + px::pivx_send_payment(handle()?, receiver, amount).await +} + +pub async fn send_promo(receiver: String, code: String) -> Result { + px::pivx_send_existing_promo(handle()?, receiver, code).await +} + +pub async fn withdraw(address: String, amount: f64) -> Result { + px::pivx_withdraw(handle()?, address, amount).await +} + +pub async fn claim(code: String) -> Result { + px::pivx_claim_from_message(handle()?, code).await +} + +pub async fn address_balance(address: String, force: bool) -> Result { + px::pivx_check_address_balance(address, Some(force)).await +} + +pub async fn chat_payments(chat: String) -> Result, String> { + px::pivx_get_chat_payments(handle()?, chat).await +} + +pub fn wallet_address() -> Option { + px::pivx_get_wallet_address(handle().ok()?).ok().flatten() +} + +pub fn set_wallet_address(address: String) -> Result<(), String> { + px::pivx_set_wallet_address(handle()?, address) +} + +pub fn currency() -> Option { + px::pivx_get_preferred_currency(handle().ok()?).ok().flatten() +} + +pub fn set_currency(currency: String) -> Result<(), String> { + px::pivx_set_preferred_currency(handle()?, currency) +} + +/// `fetchPivxCurrencies`: the common fiat codes the oracle prices, sorted. +pub async fn currencies() -> Vec { + const FIAT: &[&str] = &[ + "USD", "EUR", "GBP", "CAD", "AUD", "JPY", "CHF", "CNY", "INR", "RUB", "BRL", "MXN", "KRW", "SGD", "HKD", + "SEK", "NOK", "DKK", "PLN", "CZK", "HUF", "TRY", "ZAR", "AED", "SAR", "THB", "MYR", "IDR", "PHP", "VND", + "NZD", "ILS", "ARS", "CLP", "COP", "PEN", "NGN", "KES", "EGP", "PKR", "BDT", "TWD", "RON", "BGN", "HRK", + "ISK", "UAH", + ]; + let mut list: Vec = px::pivx_get_currencies() + .await + .unwrap_or_default() + .into_iter() + .map(|c| c.currency.to_uppercase()) + .filter(|c| FIAT.contains(&c.as_str())) + .collect(); + list.sort(); + list.dedup(); + list +} + +pub async fn price(currency: String) -> Option { + px::pivx_get_price(currency).await.ok().map(|c| c.value).filter(|v| *v > 0.) +} + +/// `detectDefaultCurrency`: the locale's region, else USD. +pub fn default_currency() -> String { + let locale = sys_locale::get_locale().unwrap_or_default(); + let region = locale.split(['.', '@']).next().unwrap_or("").split(['_', '-']).nth(1).unwrap_or("").to_uppercase(); + let euro = [ + "IE", "DE", "FR", "ES", "IT", "NL", "BE", "AT", "PT", "FI", "GR", "SK", "SI", "EE", "LV", "LT", "MT", "CY", + "LU", "MC", "SM", "VA", "AD", "ME", "XK", + ]; + if euro.contains(®ion.as_str()) { + return "EUR".into(); + } + let map: &[(&str, &str)] = &[ + ("US", "USD"), ("CA", "CAD"), ("AU", "AUD"), ("NZ", "NZD"), ("GB", "GBP"), ("UK", "GBP"), ("JP", "JPY"), + ("CN", "CNY"), ("HK", "HKD"), ("TW", "TWD"), ("KR", "KRW"), ("IN", "INR"), ("SG", "SGD"), ("MY", "MYR"), + ("TH", "THB"), ("ID", "IDR"), ("PH", "PHP"), ("VN", "VND"), ("PK", "PKR"), ("BD", "BDT"), ("RU", "RUB"), + ("UA", "UAH"), ("PL", "PLN"), ("CZ", "CZK"), ("HU", "HUF"), ("RO", "RON"), ("BG", "BGN"), ("HR", "HRK"), + ("RS", "RSD"), ("CH", "CHF"), ("SE", "SEK"), ("NO", "NOK"), ("DK", "DKK"), ("IS", "ISK"), ("TR", "TRY"), + ("IL", "ILS"), ("AE", "AED"), ("SA", "SAR"), ("QA", "QAR"), ("KW", "KWD"), ("BH", "BHD"), ("OM", "OMR"), + ("EG", "EGP"), ("ZA", "ZAR"), ("NG", "NGN"), ("KE", "KES"), ("GH", "GHS"), ("MX", "MXN"), ("BR", "BRL"), + ("AR", "ARS"), ("CL", "CLP"), ("CO", "COP"), ("PE", "PEN"), ("VE", "VES"), ("NI", "NIO"), ("CR", "CRC"), + ("PA", "PAB"), ("DO", "DOP"), ("GT", "GTQ"), + ]; + map.iter().find(|(r, _)| *r == region).map_or("USD", |(_, c)| c).to_string() +} diff --git a/crates/vector-gpui/src/backend/prefs.rs b/crates/vector-gpui/src/backend/prefs.rs new file mode 100644 index 000000000..ee0b6aa60 --- /dev/null +++ b/crates/vector-gpui/src/backend/prefs.rs @@ -0,0 +1,347 @@ +//! The account's own lists that sync across devices, and the profile actions that change them. +//! Each synced list is a projection of local state, republished whenever that state changes. + +use serde_json::json; +use vector_core::db; +use vector_core::notify; +use vector_core::state::STATE; +use vector_core::synced_prefs::{self, IdList, NicknameMap, Pref}; + +/// Publish `pref`'s projection behind the caller: the UI has already moved. +pub fn publish_projection(pref: Pref) { + // Archiving calls this from the UI thread, outside any runtime. + let _runtime = match tokio::runtime::Handle::try_current() { + Ok(_) => None, + Err(_) => match super::RT.get() { + Some(rt) => Some(rt.enter()), + None => return, + }, + }; + db::spawn_bound(async move { + let Some(client) = vector_core::state::nostr_client() else { + return; + }; + // Never publish a list not yet reconciled with the relay copy. + if !synced_prefs::is_hydrated(pref) { + return; + } + if pref == Pref::Settings { + match synced_prefs::publish_settings(&client, true).await { + Ok(Some(json)) => super::emit( + "synced_settings_updated", + synced_prefs::SyncedSettings::from_json(&json).view(), + ), + Ok(None) => {} + Err(e) => eprintln!("[SyncedPrefs] publishing {} failed: {e}", pref.d_tag()), + } + return; + } + let json = match pref { + Pref::Blocks => { + let mut l = IdList::default(); + for p in vector_core::profile::sync::get_blocked_users().await { + let _ = l.add(&p.id); + } + l.to_json() + } + Pref::Mutes => { + // The same predicate `apply_mutes` reads with, so an inherited mute stays inherited. + let mut l = IdList::default(); + let state = STATE.lock().await; + for c in state + .chats + .iter() + .filter(|c| notify::legacy_muted_for_chat(c)) + { + let _ = l.add(&c.id); + } + drop(state); + for id in db::v1_purge::purged_muted_chats() { + let _ = l.add(&id); + } + l.to_json() + } + Pref::Notify => notify::to_wire().to_json(), + Pref::Nicknames => { + let mut m = NicknameMap::default(); + let state = STATE.lock().await; + for p in state.profiles.iter().filter(|p| !p.nickname().is_empty()) { + if let Some(npub) = state.interner.resolve(p.id) { + let _ = m.set(npub, p.nickname()); + } + } + drop(state); + m.to_json() + } + _ => return, + }; + if let Err(e) = synced_prefs::publish_raw(&client, pref, &json).await { + eprintln!("[SyncedPrefs] publishing {} failed: {e}", pref.d_tag()); + } + }); +} + +/// Bring `chats.muted` in line with what the notify chain resolves to, persisting and +/// surfacing only the rows that moved. +async fn reconcile_mirror() { + // An unloaded cache answers "default" for every scope: acting on it would clear every mute. + if !notify::is_loaded() { + notify::warm(); + if !notify::is_loaded() { + return; + } + } + let (changed, slims, resolved) = { + let mut state = STATE.lock().await; + let now = notify::now_ms(); + let mut moved: Vec<(String, bool)> = Vec::new(); + let mut rows = Vec::with_capacity(state.chats.len()); + for i in 0..state.chats.len() { + let want = notify::resolve( + &state.chats[i].id, + state.chats[i].metadata.community_id(), + now, + ); + if state.chats[i].muted != want.muted { + state.chats[i].muted = want.muted; + moved.push((state.chats[i].id.clone(), want.muted)); + } + rows.push(json!({ + "id": state.chats[i].id, + "muted": want.muted, + "notify": want.ring.as_u8(), + "everyone": notify::everyone_pings_for_chat(&state.chats[i]), + "community_muted": notify::community_muted_for_chat(&state.chats[i]), + })); + } + let slims: Vec<_> = state + .chats + .iter() + .filter(|c| moved.iter().any(|(id, _)| id == &c.id)) + .map(|c| db::chats::SlimChatDB::from_chat(c, &state.interner)) + .collect(); + (moved, slims, rows) + }; + for slim in slims { + let _ = db::chats::save_slim_chat(&slim); + } + for (chat_id, muted) in &changed { + vector_core::traits::emit_event_json( + "chat_muted", + json!({ "chat_id": chat_id, "value": muted }), + ); + } + vector_core::traits::emit_event_json("notify_prefs_changed", json!({ "chats": resolved })); +} + +/// Adopting a sibling's list: bring the mirror and the counts along, publishing nothing back. +pub(crate) async fn reconcile_local() { + reconcile_mirror().await; + reseed_unread().await; + vector_core::emit_event("unread_counts_stale", &json!({ "chats": [] })); +} + +async fn reseed_unread() { + let counts = db::events::unread_counts().await.unwrap_or_default(); + STATE.lock().await.unread_seed(counts); +} + +/// Mute or unmute a chat for good; the new state. +pub async fn toggle_mute(chat_id: String) -> Option { + db::scoped(async move { + { + let mut state = STATE.lock().await; + // Muting someone known only from a community: the DM row holds the mute. + if state.get_chat(&chat_id).is_none() { + if !chat_id.starts_with("npub1") { + return None; + } + state.create_dm_chat(&chat_id); + } + } + let now = notify::now_ms(); + let muted = !notify::prefs(&chat_id).muted_at(now); + let until = if muted { + notify::MUTE_FOREVER + } else { + notify::MUTE_OFF + }; + notify::set_mute(&chat_id, until).ok()?; + reconcile_mirror().await; + reseed_unread().await; + publish_projection(Pref::Notify); + publish_projection(Pref::Mutes); + Some(muted) + }) + .await +} + +/// One notify scope as a menu needs it: what it stores, and what its chain resolves to. +#[derive(Clone, Debug, Default)] +pub struct NotifyView { + pub scope_id: String, + /// Stored here alone; `None` inherits. + pub level: Option<&'static str>, + pub effective_level: &'static str, + pub mute_until: i64, + pub muted: bool, + pub suppress_everyone: Option, + pub everyone_muted_globally: bool, +} + +/// The community first (when there is one), then each scope resolved against it. +pub fn notify_views(community_id: Option, scopes: Vec) -> Vec { + notify::warm(); + let now = notify::now_ms(); + let cid = community_id.as_deref(); + let view = |scope: &str, community: Option<&str>| { + let stored = notify::prefs(scope); + let resolved = notify::resolve(scope, community, now); + NotifyView { + scope_id: scope.to_string(), + level: stored.level.map(|l| l.as_str()), + effective_level: resolved.level.as_str(), + mute_until: stored.mute_until, + muted: resolved.muted, + suppress_everyone: stored.suppress_everyone, + everyone_muted_globally: !notify::everyone_allowed(None), + } + }; + let mut out: Vec = cid.map(|id| view(id, None)).into_iter().collect(); + out.extend( + scopes + .iter() + .filter(|s| Some(s.as_str()) != cid) + .map(|s| view(s, cid)), + ); + out +} + +async fn reconcile_notify() { + reconcile_mirror().await; + reseed_unread().await; + vector_core::emit_event("unread_counts_stale", &json!({ "chats": [] })); + publish_projection(Pref::Notify); +} + +/// `level` is "all", "mentions" or "nothing"; `None` inherits. +pub async fn set_notify_level(scope_id: String, level: Option<&'static str>) -> Result<(), String> { + let parsed = match level { + None => None, + Some(s) => { + Some(notify::NotifyLevel::from_label(s).ok_or_else(|| format!("unknown level: {s}"))?) // i18n-exempt: developer error + } + }; + db::scoped(async move { + notify::set_level(&scope_id, parsed)?; + reconcile_notify().await; + Ok(()) + }) + .await +} + +/// 0 unmutes; a negative length mutes until turned back on. +pub async fn set_notify_mute(scope_id: String, duration_ms: i64) -> Result<(), String> { + let until = match duration_ms { + 0 => notify::MUTE_OFF, + d if d < 0 => notify::MUTE_FOREVER, + d => notify::now_ms().saturating_add(d), + }; + db::scoped(async move { + notify::set_mute(&scope_id, until)?; + reconcile_notify().await; + publish_projection(Pref::Mutes); + Ok(()) + }) + .await +} + +pub async fn set_suppress_everyone( + community_id: String, + suppress: Option, +) -> Result<(), String> { + db::scoped(async move { + notify::set_suppress_everyone(&community_id, suppress)?; + reconcile_notify().await; + Ok(()) + }) + .await +} + +pub async fn block(npub: String) -> bool { + let ok = vector_core::profile::sync::block_user(npub.clone(), &super::sync::ProfileHandler).await; + if ok { + super::notify::blocked(&npub); + reseed_unread().await; + publish_projection(Pref::Blocks); + } + ok +} + +pub async fn unblock(npub: String) -> bool { + let ok = vector_core::profile::sync::unblock_user(npub, &super::sync::ProfileHandler).await; + if ok { + reseed_unread().await; + publish_projection(Pref::Blocks); + } + ok +} + +pub async fn set_nickname(npub: String, nickname: String) -> bool { + let ok = vector_core::profile::sync::set_nickname(npub, nickname, &super::sync::ProfileHandler) + .await; + if ok { + publish_projection(Pref::Nicknames); + } + ok +} + +/// Fetch a profile now, ahead of the background queue. +pub fn refresh(npub: String) { + vector_core::profile::sync::refresh_profile_now(npub); +} + +/// Let a DM request in without answering it. +pub async fn accept(npub: String) -> Result<(), String> { + vector_core::profile::sync::accept_chat(npub).await +} + +/// The request senders whose pictures show anyway: a Community we hold counts them. +pub async fn request_mutuals() -> Vec { + vector_core::requests::request_mutuals().await +} + +/// The account's boolean settings, each with its default when never set. +pub fn sql_bools(keys: &[(&'static str, bool)]) -> Vec { + keys.iter() + .map( + |(key, default)| match vector_core::db::settings::get_sql_setting(key.to_string()) { + Ok(Some(v)) => v == "true" || v == "1", + _ => *default, + }, + ) + .collect() +} + +pub fn set_sql(key: &'static str, value: String) { + let _ = vector_core::db::settings::set_sql_setting(key.to_string(), value); +} + +pub fn sql(key: &'static str) -> Option { + vector_core::db::settings::get_sql_setting(key.to_string()) + .ok() + .flatten() +} + +pub fn synced_settings() -> synced_prefs::SyncedSettings { + synced_prefs::load_settings() +} + +/// One synced-settings edit, published behind the caller. +pub fn edit_synced( + edit: impl FnOnce() -> Result, +) -> Result { + let settings = edit()?; + publish_projection(Pref::Settings); + Ok(settings) +} diff --git a/crates/vector-gpui/src/backend/push.rs b/crates/vector-gpui/src/backend/push.rs new file mode 100644 index 000000000..999dc054a --- /dev/null +++ b/crates/vector-gpui/src/backend/push.rs @@ -0,0 +1,233 @@ +//! Notify When Closed on the phone (`VectorPushService.java`, `VectorPush.java`). UnifiedPush +//! hands over an endpoint, through a distributor app or the embedded FCM one, and each message +//! decrypted. The endpoint becomes this account's sealed-push device, the same as a browser's +//! subscription, so every Vector contact's app can wake this phone. + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[cfg_attr(not(target_os = "android"), allow(dead_code))] +pub enum Push { + Off, + /// Asked for; the endpoint is on its way. + Busy, + On, +} + +/// This phone's push, or None when nothing on it can deliver one. +pub fn status() -> Option { + #[cfg(target_os = "android")] + { + let registered = vector_core::push::device().is_some(); + let out = phone::status(registered); + match out.as_deref() { + Some("on") => Some(Push::On), + Some("busy") => Some(Push::Busy), + Some("off") => Some(Push::Off), + None if registered => Some(Push::On), + _ => None, + } + } + #[cfg(not(target_os = "android"))] + None +} + +/// Ask for an endpoint: a distributor app the user has, else FCM's own through Play Services. +#[cfg(target_os = "android")] +pub fn enable() -> Result<(), String> { + let vapid = phone::vapid_public()?; + if phone::enable(&vapid)? { + Ok(()) + } else { + Err(crate::t::settings_push_unavailable().into()) + } +} + +/// Every contact holding this phone's ticket is told to forget it. +#[cfg(target_os = "android")] +pub async fn disable() -> Result<(), String> { + vector_core::push::disable().await?; + let _ = vector_core::db::remove_setting(phone::VAPID_KEY); + phone::disable(); + Ok(()) +} + +#[cfg(target_os = "android")] +mod phone { + use jni::objects::{JByteArray, JClass, JObject, JString, JValue}; + use jni::JNIEnv; + use vector_core::db; + + use crate::android::utils::{jni_fence, with_android_activity, with_android_context}; + + /// The VAPID key a registration was asked for with, kept until the endpoint arrives. + pub(super) const VAPID_KEY: &str = "push_native_vapid"; + const ORIGIN: &str = "https://vectorapp.io"; + + /// This account's VAPID public key, made on first use. + pub(super) fn vapid_public() -> Result { + let secret = match db::get_sql_setting(VAPID_KEY.into())? { + Some(s) => s, + None => { + let (secret, _) = vector_push::vapid::generate(); + db::set_sql_setting(VAPID_KEY.into(), secret.clone())?; + secret + } + }; + vector_push::vapid::public_key(&secret).map_err(|e| e.to_string()) + } + + fn helper<'a>(env: &mut JNIEnv<'a>, ctx: &JObject<'a>) -> Result, String> { + let err = |e: jni::errors::Error| format!("{e:?}"); + let loader = env.call_method(ctx, "getClassLoader", "()Ljava/lang/ClassLoader;", &[]).and_then(|v| v.l()).map_err(err)?; + let name = env.new_string("io.vectorapp.VectorPush").map_err(err)?; + let class = env + .call_method(&loader, "loadClass", "(Ljava/lang/String;)Ljava/lang/Class;", &[JValue::Object(&name)]) + .and_then(|v| v.l()) + .map_err(err)?; + Ok(JClass::from(class)) + } + + pub(super) fn status(registered: bool) -> Option { + with_android_context(|env, ctx| { + let class = helper(env, ctx)?; + let out = env + .call_static_method( + &class, + "status", + "(Landroid/content/Context;Z)Ljava/lang/String;", + &[JValue::Object(ctx), JValue::Bool(registered.into())], + ) + .and_then(|v| v.l()) + .map_err(|e| format!("{e:?}"))?; + env.get_string(&JString::from(out)).map(Into::into).map_err(|e| format!("{e:?}")) + }) + .ok() + } + + pub(super) fn enable(vapid: &str) -> Result { + with_android_activity(|env, activity| { + let class = helper(env, activity)?; + let key = env.new_string(vapid).map_err(|e| format!("{e:?}"))?; + env.call_static_method( + &class, + "enable", + "(Landroid/app/Activity;Ljava/lang/String;)Z", + &[JValue::Object(activity), JValue::Object(&key)], + ) + .and_then(|v| v.z()) + .map_err(|e| format!("{e:?}")) + }) + } + + pub(super) fn disable() { + let _ = with_android_context(|env, ctx| { + let class = helper(env, ctx)?; + env.call_static_method(&class, "disable", "(Landroid/content/Context;)V", &[JValue::Object(ctx)]) + .map(drop) + .map_err(|e| format!("{e:?}")) + }); + } + + /// A process the push started cold has no window, no context kept and no account open: the + /// context is kept, and the account the app last used opened. + fn ready(env: &mut JNIEnv, context: &JObject) -> Option<&'static tokio::runtime::Runtime> { + crate::android::background_sync::hold_context(env, context); + crate::android::incoming_call::install(); + let rt = crate::backend::core(crate::android::data_dir()?.clone()); + rt.block_on(crate::backend::account::open_headless()).then_some(rt) + } + + fn string(env: &mut JNIEnv, s: &JString) -> String { + env.get_string(s).map(String::from).unwrap_or_default() + } + + #[unsafe(no_mangle)] + pub extern "C" fn Java_io_vectorapp_VectorPushService_nativeNewEndpoint( + mut env: JNIEnv, + _class: JClass, + context: JObject, + _data_dir: JString, + url: JString, + p256dh: JString, + auth: JString, + ) { + jni_fence("Java_io_vectorapp_VectorPushService_nativeNewEndpoint", || (), move || { + let Some(rt) = ready(&mut env, &context) else { return }; + let (endpoint, p256dh, auth) = (string(&mut env, &url), string(&mut env, &p256dh), string(&mut env, &auth)); + let Ok(Some(vapid)) = db::get_sql_setting(VAPID_KEY.into()) else { + log::warn!("push: an endpoint arrived with no VAPID key asked for"); + return; + }; + if endpoint.is_empty() || p256dh.is_empty() || auth.is_empty() { + return; + } + // Same endpoint and keys: the ticket every contact holds still names this device. + let id = match vector_core::push::device() { + Some(d) if d.endpoint == endpoint && d.p256dh == p256dh && d.auth == auth => d.id, + _ => format!("{:016x}", rand::random::()), + }; + let device = vector_core::push::Device { id, endpoint, p256dh, auth, vapid, origin: ORIGIN.into() }; + let _rt = rt.enter(); + db::spawn_bound(async move { + match vector_core::push::adopt(device).await { + Ok(()) => crate::backend::emit("push_state", serde_json::json!({ "push": "on" })), + Err(e) => log::warn!("push: endpoint not taken: {e}"), + } + }); + }) + } + + #[unsafe(no_mangle)] + pub extern "C" fn Java_io_vectorapp_VectorPushService_nativeMessage( + mut env: JNIEnv, + _class: JClass, + context: JObject, + _data_dir: JString, + content: JByteArray, + ) { + jni_fence("Java_io_vectorapp_VectorPushService_nativeMessage", || (), move || { + let Ok(bytes) = env.convert_byte_array(&content) else { return }; + let Some(rt) = ready(&mut env, &context) else { return }; + rt.block_on(db::scoped(deliver(bytes))); + }) + } + + /// What a push says, in the words this account has for its sender. One no contact here + /// vouches for (another account's, or forged) shows nothing it claims. + async fn deliver(bytes: Vec) { + use crate::android::incoming_call; + use crate::backend::notify; + let Some((npub, notice)) = vector_core::push::receive(&bytes) else { + notify::pushed_unknown(); + return; + }; + match notice.kind.as_str() { + "call" | "video_call" => { + let (name, avatar) = notify::known_as(&npub).await; + incoming_call::ring_now(¬ice.msg, &npub, &name, avatar.as_deref(), notice.kind == "video_call"); + } + "missed_call" => { + let (name, _) = notify::known_as(&npub).await; + incoming_call::missed(¬ice.msg, &npub, &name); + } + _ => notify::pushed(&npub, notice.text).await, + } + } + + #[unsafe(no_mangle)] + pub extern "C" fn Java_io_vectorapp_VectorPushService_nativeUnregistered( + mut env: JNIEnv, + _class: JClass, + context: JObject, + _data_dir: JString, + ) { + jni_fence("Java_io_vectorapp_VectorPushService_nativeUnregistered", || (), move || { + let Some(rt) = ready(&mut env, &context) else { return }; + rt.block_on(db::scoped(async { + if let Err(e) = vector_core::push::disable().await { + log::warn!("push: unregistered, but tickets not withdrawn: {e}"); + } + crate::backend::emit("push_state", serde_json::json!({ "push": "off" })); + })); + }) + } +} diff --git a/crates/vector-gpui/src/backend/rail.rs b/crates/vector-gpui/src/backend/rail.rs new file mode 100644 index 000000000..5f303dd92 --- /dev/null +++ b/crates/vector-gpui/src/backend/rail.rs @@ -0,0 +1,54 @@ +//! The community rail's arrangement, synced across the account's own devices (`vector/rail`). +//! Every edit commits locally at once; the publish waits for the dragging to stop. + +use vector_core::rail_layout::{self, RailDrag, RailDrop, RailLayout}; +use vector_core::synced_prefs::{self, Pref}; + +pub fn load() -> RailLayout { + synced_prefs::load_rail() +} + +/// A drag let go. `live` is the rail as painted: the drop lands on what the user saw, and a +/// rail never arranged stores nothing until its first drag fixes the order. +pub async fn drop(source: RailDrag, target: RailDrop, live: Vec) -> Result { + edit(move |l| { + let base = l.merged_with(&live); + let mut next = base.clone(); + next.apply_drop(&source, &target, &rail_layout::new_folder_id())?; + if next != base { + *l = next; + } + Ok(()) + }) + .await +} + +/// A community left: a rejoin lands fresh rather than back in its old folder. +pub async fn forget(community_id: String) { + let _ = edit(move |l| { + if l.contains(&community_id) { + l.remove_key(&community_id); + } + Ok(()) + }) + .await; +} + +/// Load, change, commit only if something moved. Refused until the relay copy is read, or a +/// fresh login could publish a flat rail over one arranged on another device. +pub async fn edit(f: impl FnOnce(&mut RailLayout) -> Result<(), String> + Send + 'static) -> Result { + vector_core::db::scoped(async move { + if !synced_prefs::is_hydrated(Pref::Rail) { + return Err(crate::t::start_communities_syncing().to_string()); + } + let (layout, changed) = synced_prefs::edit_layout(Pref::Rail, f)?; + if changed { + vector_core::traits::emit_event_json( + "rail_layout_updated", + serde_json::to_value(&layout).unwrap_or_default(), + ); + } + Ok(layout) + }) + .await +} diff --git a/crates/vector-gpui/src/backend/security.rs b/crates/vector-gpui/src/backend/security.rs new file mode 100644 index 000000000..de2becdd1 --- /dev/null +++ b/crates/vector-gpui/src/backend/security.rs @@ -0,0 +1,219 @@ +//! Local Encryption: turning it on or off, changing the credential, and showing the keys. The +//! sweep itself is core's `db::at_rest`; this holds the account still while it runs. + +use std::sync::atomic::{AtomicBool, Ordering}; + +use vector_core::db::{self, at_rest}; +use vector_core::state; +use zeroize::Zeroizing; + +pub use at_rest::MigrationProgress; + +static MIGRATING: AtomicBool = AtomicBool::new(false); + +/// One migration at a time: a second over the same vault would split it between two keys. +struct Migrating; + +impl Migrating { + fn enter() -> Result { + MIGRATING + .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire) + .map_err(|_| crate::t::security_migration_running().to_string())?; + Ok(Self) + } +} + +impl Drop for Migrating { + fn drop(&mut self) { + MIGRATING.store(false, Ordering::Release); + } +} + +/// A swap mid-sweep would pull the connection out from under its transaction. +pub fn refuse_if_migrating() -> Result<(), String> { + if MIGRATING.load(Ordering::Acquire) { + Err(crate::t::security_wait_for_change().into()) + } else { + Ok(()) + } +} + +/// Whether the account is encrypted, and with a `pin` or a `password`. +pub fn status() -> (bool, String) { + let on = state::is_encryption_enabled_fast(); + let kind = if on { + db::get_sql_setting("security_type".into()).ok().flatten() + } else { + None + }; + (on, kind.unwrap_or_else(|| "pin".into())) +} + +pub async fn verify(credential: Zeroizing) -> Result<(), String> { + at_rest::prove_credential(&credential).await.map(drop) +} + +/// The key from the user's own proof, never the vault: the typed credential, or the phone's +/// prompt for an account that has none. +pub(super) async fn prove(credential: Option>) -> Result, String> { + if !state::is_encryption_enabled_fast() { + return Err(crate::t::security_not_enabled().into()); + } + #[cfg(target_os = "android")] + if super::biometric::is_only_credential() { + return super::biometric::prove().await; + } + let credential = credential + .filter(|c| !c.is_empty()) + .ok_or(at_rest::CREDENTIAL_REQUIRED)?; + at_rest::prove_credential(&credential).await +} + +/// Inbound events wait at the gate while a sweep holds the store. +fn sweep(run: impl FnOnce() -> Result) -> Result { + state::close_processing_gate(); + let result = run(); + state::open_processing_gate(); + result +} + +pub async fn enable( + credential: Zeroizing, + kind: String, + progress: impl Fn(MigrationProgress), +) -> Result<(), String> { + if state::is_encryption_enabled_fast() { + return Err(crate::t::security_already_enabled().into()); + } + let session = db::current_session(); + let kdf = vector_core::crypto::Kdf::fresh(); + let key = Zeroizing::new(vector_core::crypto::derive_key(&credential, &kdf).await); + drop(credential); + let _one = Migrating::enter()?; + if !session.is_live() { + return Err(crate::t::security_account_changed().into()); + } + if state::is_encryption_enabled_fast() { + return Err(crate::t::security_already_enabled().into()); + } + sweep(|| at_rest::enable(&key, &kdf, &kind, None, None, &progress)) +} + +pub async fn disable( + credential: Option>, + progress: impl Fn(MigrationProgress), +) -> Result<(), String> { + let session = db::current_session(); + let biometric = super::biometric::is_only_credential(); + let key = prove(credential).await?; + let _one = Migrating::enter()?; + if !session.is_live() { + return Err(crate::t::security_account_changed().into()); + } + sweep(|| at_rest::disable(&key, &progress))?; + if biometric { + forget_keystore(); + } + Ok(()) +} + +/// The keystore key of a wrap the store no longer holds. +fn forget_keystore() { + #[cfg(target_os = "android")] + if let Ok(npub) = db::get_current_account() { + super::biometric::forget_keystore(&npub); + } +} + +/// Turn encryption on under a credential only the phone's prompt opens. +#[cfg(target_os = "android")] +pub async fn enable_biometric(progress: impl Fn(MigrationProgress)) -> Result<(), String> { + if state::is_encryption_enabled_fast() { + return Err(crate::t::security_already_enabled().into()); + } + let session = db::current_session(); + let npub = db::get_current_account()?; + let (wrapped, key, kdf) = super::biometric::generate_and_wrap(&npub).await?; + let out = (|| { + let _one = Migrating::enter()?; + if !session.is_live() { + return Err(crate::t::security_account_changed().to_string()); + } + if state::is_encryption_enabled_fast() { + return Err(crate::t::security_already_enabled().into()); + } + sweep(|| at_rest::enable(&key, &kdf, "biometric", Some(&wrapped), None, &progress)) + })(); + if out.is_err() { + super::biometric::forget_keystore(&npub); + } + out +} + +/// Move a typed credential's account onto the phone's prompt, re-sealing in one transaction. +#[cfg(target_os = "android")] +pub async fn switch_to_biometric( + credential: Zeroizing, + progress: impl Fn(MigrationProgress), +) -> Result<(), String> { + let session = db::current_session(); + let old_key = prove(Some(credential)).await?; + let npub = db::get_current_account()?; + let (wrapped, new_key, kdf) = super::biometric::generate_and_wrap(&npub).await?; + let out = (|| { + let _one = Migrating::enter()?; + if !session.is_live() { + return Err(crate::t::security_account_changed().to_string()); + } + sweep(|| at_rest::rekey(&old_key, &new_key, &kdf, "biometric", Some(&wrapped), &progress)) + })(); + if out.is_err() { + super::biometric::forget_keystore(&npub); + } + out +} + +/// Re-seal everything under a new credential, all in one transaction. +pub async fn rekey( + old: Zeroizing, + new: Zeroizing, + kind: String, + progress: impl Fn(MigrationProgress), +) -> Result<(), String> { + let session = db::current_session(); + let _one = Migrating::enter()?; + let biometric = super::biometric::is_only_credential(); + let old_key = prove(Some(old)).await?; + let kdf = vector_core::crypto::Kdf::fresh(); + let new_key = Zeroizing::new(vector_core::crypto::derive_key(&new, &kdf).await); + drop(new); + if !session.is_live() { + return Err(crate::t::security_account_changed().into()); + } + sweep(|| at_rest::rekey(&old_key, &new_key, &kdf, &kind, None, &progress))?; + if biometric { + forget_keystore(); + } + Ok(()) +} + +/// The account's nsec and seed phrase. An encrypted account opens them with a key from the +/// user's proof, so the live session alone can't read them out. +pub async fn export( + credential: Option>, +) -> Result<(Zeroizing, Option>), String> { + if vector_core::is_keyless() { + return Err(crate::t::security_export_external().into()); + } + let session = db::current_session(); + let key = if state::is_encryption_enabled_fast() { + Some(prove(credential).await?) + } else { + None + }; + let secrets = at_rest::open_identity_secrets(key.as_deref())?; + if !session.is_live() { + return Err(crate::t::security_export_account_changed().into()); + } + Ok(secrets) +} diff --git a/crates/vector-gpui/src/backend/selfsync.rs b/crates/vector-gpui/src/backend/selfsync.rs new file mode 100644 index 000000000..c63955876 --- /dev/null +++ b/crates/vector-gpui/src/backend/selfsync.rs @@ -0,0 +1,214 @@ +//! Cross-device sync for the account's own lists: one open subscription to them (the relay +//! replays the stored copy on connect and reconnect, then streams edits), and a reconcile of +//! the synced prefs at login, before the user can change them. + +use nostr_sdk::prelude::*; +use vector_core::synced_prefs::{self, ArchiveMap, IdList, NicknameMap, NotifyMap, Pref, SyncedSettings}; +use vector_core::{STATE, db, notify, pinned_chats, rail_layout::RailLayout}; + +/// Subscribe, reconcile, then route what arrives for the session's life. +pub fn start() { + db::spawn_bound(async { + let Some(client) = vector_core::state::nostr_client() else { return }; + let Some(me) = vector_core::my_public_key() else { return }; + let mut notifications = client.notifications(); + let ids = subscribe(&client, me).await; + hydrate().await; + let mut last: std::collections::HashMap = std::collections::HashMap::new(); + loop { + let Some(n) = futures::StreamExt::next(&mut notifications).await else { break }; + let ClientNotification::Event { subscription_id, event, .. } = n else { continue }; + if !ids.contains(&subscription_id) || event.pubkey != me { + continue; + } + // Several relays deliver one edit: one update, one sweep. + let key = match event.tags.identifier() { + Some(d) => format!("{}:{d}", event.kind.as_u16()), + None => event.kind.as_u16().to_string(), + }; + if last.get(&key) == Some(&event.id) { + continue; + } + last.insert(key, event.id); + route(*event); + if db::session_stopped() { + break; + } + } + }); +} + +async fn subscribe(client: &Client, me: PublicKey) -> Vec { + let filters = [ + Filter::new() + .author(me) + .kind(Kind::Custom(vector_core::stored_event::event_kind::APPLICATION_SPECIFIC)) + .identifiers(synced_prefs::live_d_tags()), + Filter::new().author(me).kind(Kind::Custom(vector_core::community::v2::kind::COMMUNITY_LIST_FRAG)), + Filter::new().author(me).kind(Kind::Custom(10030)), + ]; + let mut ids = Vec::new(); + for f in filters { + match client.subscribe(f.clone()).await { + Ok(out) => { + vector_core::live_subs::keep_output(&out, vec![f]); + ids.push(out.value); + } + Err(e) => vector_core::log_warn!("[self-sync] subscribe failed: {e:?}"), + } + } + ids +} + +fn route(event: Event) { + let kind = event.kind.as_u16(); + if kind == vector_core::stored_event::event_kind::APPLICATION_SPECIFIC { + let d = event.tags.identifier().unwrap_or_default().to_string(); + db::spawn_bound(async move { + if d == pinned_chats::PINNED_D_TAG { + let Some(me) = vector_core::my_public_key() else { return }; + match pinned_chats::ingest_remote_event(&me, &event).await { + Ok(list) => emit_pinned(&list.chats), + Err(e) => vector_core::log_warn!("[PinnedChats] ingest failed: {e}"), + } + } else if Pref::from_d_tag(&d).is_some() { + ingest_prefs(event).await; + } + }); + } else if kind == vector_core::community::v2::kind::COMMUNITY_LIST_FRAG { + super::community::request(); + } else if kind == 10030 { + db::spawn_bound(async { + if vector_core::emoji_packs::refresh_subscribed_packs().await.is_ok() { + vector_core::emit_event("emoji_packs_updated", &()); + } + }); + } +} + +pub fn emit_pinned(chats: &[String]) { + vector_core::traits::emit_event_json("pinned_chats_updated", serde_json::json!(chats)); +} + +pub fn emit_archive(map: &ArchiveMap) { + vector_core::traits::emit_event_json("archived_chats_updated", serde_json::json!(map.times())); +} + +/// Reconcile the synced lists at login. The subscription delivers them too, but it races the +/// user: acting first would publish this device's emptier view over a sibling's. +async fn hydrate() { + let Some(client) = vector_core::state::nostr_client() else { return }; + for (pref, json) in synced_prefs::hydrate_all(&client).await { + apply(pref, &json).await; + } +} + +async fn ingest_prefs(event: Event) { + let Some(me) = vector_core::my_public_key() else { return }; + let Some((pref, json)) = synced_prefs::ingest_remote(&me, &event).await else { return }; + apply(pref, &json).await; +} + +async fn apply(pref: Pref, json: &str) { + match pref { + Pref::Blocks => apply_blocks(IdList::from_json(json)).await, + Pref::Mutes => apply_mutes(IdList::from_json(json)).await, + Pref::Nicknames => apply_nicknames(NicknameMap::from_json(json)).await, + Pref::Notify => match notify::apply_wire(&NotifyMap::from_json(json)) { + Ok(moved) if moved.is_empty() => {} + Ok(_) => super::prefs::reconcile_local().await, + Err(e) => vector_core::log_warn!("[SyncedPrefs] applying notify failed: {e}"), + }, + Pref::Rail => emit_layout("rail_layout_updated", json), + Pref::Start => emit_layout("start_layout_updated", json), + Pref::Banners => vector_core::traits::emit_event_json( + "hidden_banners_updated", + serde_json::json!({ "ids": IdList::from_json(json).ids }), + ), + Pref::Archive => emit_archive(&ArchiveMap::from_json(json)), + Pref::Settings => { + vector_core::traits::emit_event_json("synced_settings_updated", SyncedSettings::from_json(json).view()) + } + } +} + +fn emit_layout(event: &str, json: &str) { + vector_core::traits::emit_event_json(event, serde_json::to_value(RailLayout::from_json(json)).unwrap_or_default()); +} + +/// Block what the list names, unblock what it omits, through the core mutators. +async fn apply_blocks(list: IdList) { + let handler = &super::sync::ProfileHandler; + let currently: Vec = + vector_core::profile::sync::get_blocked_users().await.into_iter().map(|p| p.id).collect(); + for npub in list.ids.iter().filter(|n| !currently.contains(n)) { + if vector_core::profile::sync::block_user(npub.clone(), handler).await { + super::notify::blocked(npub); + } + } + for npub in currently.iter().filter(|n| !list.contains(n)) { + vector_core::profile::sync::unblock_user(npub.clone(), handler).await; + } + super::prefs::reconcile_local().await; +} + +/// Mirror the mute list onto chat rows. It names chats only, so a community-scope mute survives. +async fn apply_mutes(list: IdList) { + vector_core::db::v1_purge::retain_purged_mutes(|id| list.contains(id)); + let chats: Vec<(String, bool, bool)> = { + let mut state = STATE.lock().await; + for id in list.ids.iter().filter(|id| id.starts_with("npub1")) { + if state.get_chat(id).is_none() { + state.create_dm_chat(id); + } + } + state + .chats + .iter() + .map(|c| { + ( + c.id.clone(), + notify::legacy_muted_for_chat(c), + notify::prefs(&c.id).mute_until != notify::MUTE_OFF, + ) + }) + .collect() + }; + let mut changed = false; + for (id, already, owns) in chats { + let want = list.contains(&id); + if want == already { + continue; + } + if want { + changed |= notify::set_mute(&id, notify::MUTE_FOREVER).is_ok(); + } else if owns { + changed |= notify::set_mute(&id, notify::MUTE_OFF).is_ok(); + } + } + if changed { + super::prefs::reconcile_local().await; + } +} + +/// Set what the map names, clear what it omits. +async fn apply_nicknames(map: NicknameMap) { + let handler = &super::sync::ProfileHandler; + let existing: Vec<(String, String)> = { + let state = STATE.lock().await; + state + .profiles + .iter() + .filter(|p| !p.nickname().is_empty()) + .filter_map(|p| state.interner.resolve(p.id).map(|n| (n.to_string(), p.nickname().to_string()))) + .collect() + }; + for (npub, nick) in map.names.iter() { + if !existing.iter().any(|(n, v)| n == npub && v == nick) { + vector_core::profile::sync::set_nickname(npub.clone(), nick.clone(), handler).await; + } + } + for (npub, _) in existing.iter().filter(|(n, _)| !map.names.contains_key(n)) { + vector_core::profile::sync::set_nickname(npub.clone(), String::new(), handler).await; + } +} diff --git a/crates/vector-gpui/src/backend/sound.rs b/crates/vector-gpui/src/backend/sound.rs new file mode 100644 index 000000000..db24b74fd --- /dev/null +++ b/crates/vector-gpui/src/backend/sound.rs @@ -0,0 +1,290 @@ +//! Notification sounds (`audio.rs` on desktop): the bundled pair decoded once, a custom pick +//! stored pre-resampled as `name_RATE.raw`, each played as a one-shot on the default output. + +use std::path::{Path, PathBuf}; +use std::sync::Mutex; +use std::time::{Duration, Instant}; + +use cpal::traits::{DeviceTrait, HostTrait, StreamTrait}; +use symphonia::core::audio::SampleBuffer; +use symphonia::core::codecs::{CODEC_TYPE_NULL, DecoderOptions}; +use symphonia::core::errors::Error as SymErr; +use symphonia::core::formats::FormatOptions; +use symphonia::core::io::MediaSourceStream; +use symphonia::core::meta::MetadataOptions; +use symphonia::core::probe::Hint; + +const PRELUDE: &[u8] = include_bytes!("../../../../src-tauri/resources/sounds/notif-prelude.mp3"); +const TECHNO: &[u8] = include_bytes!("../../../../src-tauri/resources/sounds/notif-techno.mp3"); +const MAX_BYTES: u64 = 1024 * 1024; +const MAX_SECS: f32 = 10.0; +/// Decoded samples stay this long after their last play, for a burst of messages. +const TTL: Duration = Duration::from_secs(600); + +/// The stored `notif_sound` value: default, techno, none, or `custom:`. +#[derive(Clone, PartialEq)] +pub enum Sound { + Default, + Techno, + None, + Custom(PathBuf), +} + +impl Sound { + pub fn parse(v: &str) -> Self { + match v { + "techno" => Sound::Techno, + "none" => Sound::None, + v => v + .strip_prefix("custom:") + .map(|p| Sound::Custom(p.into())) + .unwrap_or(Sound::Default), + } + } +} + +struct Cached { + sound: Sound, + rate: u32, + samples: std::sync::Arc>, + used: Instant, +} + +// Keyed by the sound itself, so it holds nothing an account owns. +static CACHE: Mutex> = Mutex::new(None); + +fn device_rate() -> Result<(cpal::Device, cpal::SupportedStreamConfig), String> { + let device = cpal::default_host() + .default_output_device() + .ok_or("No output device found")?; // i18n-exempt: logged only + let config = device + .default_output_config() + .map_err(|e| format!("Failed to get output config: {e}"))?; // i18n-exempt: logged only + Ok((device, config)) +} + +fn decode(bytes: Vec, ext: Option<&str>) -> Result<(Vec, u32), String> { + let mss = MediaSourceStream::new(Box::new(std::io::Cursor::new(bytes)), Default::default()); + let mut hint = Hint::new(); + if let Some(ext) = ext { + hint.with_extension(ext); + } + let probed = symphonia::default::get_probe() + .format( + &hint, + mss, + &FormatOptions::default(), + &MetadataOptions::default(), + ) + .map_err(|e| format!("Failed to probe audio format: {e}"))?; // i18n-exempt: logged only + let mut format = probed.format; + let track = format + .tracks() + .iter() + .find(|t| t.codec_params.codec != CODEC_TYPE_NULL) + .ok_or("No supported audio tracks found")?; // i18n-exempt: logged only + let id = track.id; + let mut rate = track + .codec_params + .sample_rate + .ok_or("Unknown sample rate")?; // i18n-exempt: logged only + let mut decoder = symphonia::default::get_codecs() + .make(&track.codec_params, &DecoderOptions::default()) + .map_err(|e| format!("Failed to create decoder: {e}"))?; // i18n-exempt: logged only + let mut out = Vec::new(); + let mut buf: Option> = None; + let mut channels = 1; + loop { + let packet = match format.next_packet() { + Ok(p) => p, + Err(SymErr::ResetRequired) => { + decoder.reset(); + continue; + } + Err(_) => break, + }; + if packet.track_id() != id { + continue; + } + match decoder.decode(&packet) { + Ok(decoded) => { + let b = buf.get_or_insert_with(|| { + let spec = *decoded.spec(); + if spec.rate > 0 { + rate = spec.rate; + } + channels = spec.channels.count().max(1); + SampleBuffer::new(decoded.capacity() as u64, spec) + }); + b.copy_interleaved_ref(decoded); + if channels > 1 { + out.extend( + b.samples() + .chunks_exact(channels) + .map(|c| c.iter().sum::() / channels as f32), + ); + } else { + out.extend_from_slice(b.samples()); + } + } + Err(SymErr::DecodeError(_)) => continue, + Err(_) => break, + } + } + Ok((out, rate)) +} + +fn resample(samples: Vec, from: u32, to: u32) -> Vec { + if from == to { + samples + } else { + crate::simd::audio::linear_resample_mono(&samples, from, to) + } +} + +fn load_raw(path: &Path) -> Result, String> { + let bytes = vector_core::vcache::read(path).map_err(|e| format!("Failed to read cache file: {e}"))?; // i18n-exempt: logged only + if bytes.len() % 4 != 0 { + return Err("Invalid cache file size".into()); // i18n-exempt: logged only + } + Ok(bytes + .chunks_exact(4) + .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])) + .collect()) +} + +fn samples_for(sound: &Sound, rate: u32) -> Result, String> { + let bundled = + |bytes: &[u8]| decode(bytes.to_vec(), Some("mp3")).map(|(s, r)| resample(s, r, rate)); + match sound { + Sound::None => Ok(Vec::new()), + Sound::Default => bundled(PRELUDE), + Sound::Techno => bundled(TECHNO), + // A custom file gone missing falls back to the default rather than silence. + Sound::Custom(path) if !path.exists() => bundled(PRELUDE), + Sound::Custom(path) => { + let stored = path + .file_stem() + .and_then(|s| s.to_str()) + .and_then(|s| s.rsplit('_').next()) + .and_then(|r| r.parse().ok()) + .ok_or("Invalid cache filename format")?; // i18n-exempt: logged only + Ok(resample(load_raw(path)?, stored, rate)) + } + } +} + +/// Play `sound` once, off the caller's thread. +pub fn play(sound: Sound) { + if sound == Sound::None { + return; + } + // spawn-detached: plays bytes in hand on the audio device; owns no account state. + std::thread::spawn(move || { + if let Err(e) = play_now(&sound) { + log::warn!("notification sound: {e}"); + } + }); +} + +fn play_now(sound: &Sound) -> Result<(), String> { + let (device, config) = device_rate()?; + let rate = config.sample_rate().0; + let samples = { + let mut cache = CACHE.lock().map_err(|_| "cache poisoned")?; // i18n-exempt: logged only + if cache.as_ref().is_some_and(|c| c.used.elapsed() > TTL) { + *cache = None; + } + match cache + .as_mut() + .filter(|c| c.sound == *sound && c.rate == rate) + { + Some(c) => { + c.used = Instant::now(); + c.samples.clone() + } + None => { + let samples = std::sync::Arc::new(samples_for(sound, rate)?); + *cache = Some(Cached { + sound: sound.clone(), + rate, + samples: samples.clone(), + used: Instant::now(), + }); + samples + } + } + }; + if samples.is_empty() { + return Err("No audio data decoded".into()); // i18n-exempt: logged only + } + let channels = config.channels() as usize; + let total = samples.len(); + let mut at = 0usize; + let err = |e| log::warn!("notification stream: {e}"); + let stream_config: cpal::StreamConfig = config.config(); + macro_rules! build { + ($t:ty, $conv:expr) => { + device.build_output_stream( + &stream_config, + move |out: &mut [$t], _| { + for frame in out.chunks_mut(channels) { + let s = samples.get(at).copied().unwrap_or(0.0); + at += 1; + frame.fill($conv(s)); + } + }, + err, + None, + ) + }; + } + let stream = match config.sample_format() { + cpal::SampleFormat::F32 => build!(f32, |s: f32| s), + cpal::SampleFormat::I16 => { + build!(i16, |s: f32| (s.clamp(-1., 1.) * i16::MAX as f32) as i16) + } + cpal::SampleFormat::U16 => build!(u16, |s: f32| ((s.clamp(-1., 1.) + 1.) + * 0.5 + * u16::MAX as f32) as u16), + f => return Err(format!("Unsupported sample format {f:?}")), // i18n-exempt: logged only + } + .map_err(|e| format!("Failed to open output: {e}"))?; // i18n-exempt: logged only + stream.play().map_err(|e| format!("Failed to play: {e}"))?; // i18n-exempt: logged only + let secs = (total as f32 / rate as f32).min(MAX_SECS); + std::thread::sleep(Duration::from_secs_f32(secs + 0.15)); + Ok(()) +} + +/// Forget decoded samples, for a sound that changed or went quiet. +pub fn purge() { + if let Ok(mut c) = CACHE.lock() { + *c = None; + } +} + +/// Import a picked file: at most 1MB and 10 seconds, stored resampled for this device. +pub fn import(source: &Path, sounds_dir: &Path) -> Result { + let meta = std::fs::metadata(source).map_err(|e| format!("Failed to read file: {e}"))?; // i18n-exempt: logged only + if meta.len() > MAX_BYTES { + return Err("FILE_TOO_LARGE".into()); + } + let (_, config) = device_rate()?; + let rate = config.sample_rate().0; + let bytes = std::fs::read(source).map_err(|e| format!("Failed to read file: {e}"))?; // i18n-exempt: logged only + let (samples, from) = decode(bytes, source.extension().and_then(|e| e.to_str()))?; + if samples.len() as f32 / from as f32 > MAX_SECS { + return Err("AUDIO_TOO_LONG".into()); + } + let samples = resample(samples, from, rate); + let stem = source + .file_stem() + .ok_or("Invalid filename")? // i18n-exempt: logged only + .to_string_lossy(); + std::fs::create_dir_all(sounds_dir) + .map_err(|e| format!("Failed to create sounds cache dir: {e}"))?; // i18n-exempt: logged only + let dest = sounds_dir.join(format!("{stem}_{rate}.raw")); + let bytes: Vec = samples.iter().flat_map(|s| s.to_le_bytes()).collect(); + vector_core::vcache::write(&dest, &bytes).map_err(|e| format!("Failed to write cache file: {e}"))?; // i18n-exempt: logged only + Ok(dest) +} diff --git a/crates/vector-gpui/src/backend/standby.rs b/crates/vector-gpui/src/backend/standby.rs new file mode 100644 index 000000000..fae4e20fe --- /dev/null +++ b/crates/vector-gpui/src/backend/standby.rs @@ -0,0 +1,26 @@ +//! The background service started with no window: at boot, or when Android restarts it. + +use jni::objects::{JClass, JObject}; +use jni::JNIEnv; + +use crate::android::utils::jni_fence; + +#[unsafe(no_mangle)] +pub extern "C" fn Java_io_vectorapp_VectorNotificationService_nativeStandby(mut env: JNIEnv, _class: JClass, context: JObject) { + jni_fence("Java_io_vectorapp_VectorNotificationService_nativeStandby", || (), move || { + // A window signs in for itself, whatever its login screen is showing. + if crate::android::utils::with_android_activity(|_, _| Ok(())).is_ok() { + return; + } + crate::android::background_sync::hold_context(&mut env, &context); + crate::android::incoming_call::install(); + let Some(dir) = crate::android::data_dir() else { return }; + let rt = super::core(dir.clone()); + // spawn-detached: signs in whichever account is active; what it starts binds to that session. + rt.spawn(async { + if super::account::standby().await { + log::info!("standby: listening without a window"); + } + }); + }) +} diff --git a/crates/vector-gpui/src/backend/storage.rs b/crates/vector-gpui/src/backend/storage.rs new file mode 100644 index 000000000..b422ce5af --- /dev/null +++ b/crates/vector-gpui/src/backend/storage.rs @@ -0,0 +1,320 @@ +//! Storage (`commands/system.rs` on desktop): what this account's files and the shared caches +//! weigh by type, and clearing them, all of it or one slice of the chart. + +use std::collections::{HashMap, HashSet}; +use std::path::Path; + +use vector_core::media::import::{self, OnDisk}; + +/// The caches Clear sweeps: every image cache kind and the resampled sounds. +fn cache_kinds() -> impl Iterator { + vector_core::vcache::KINDS.iter().copied().chain(["sounds"]) +} + +fn dir_size(path: &Path) -> u64 { + std::fs::read_dir(path) + .into_iter() + .flatten() + .flatten() + .map(|e| match e.metadata() { + Ok(m) if m.is_file() => m.len(), + Ok(m) if m.is_dir() => dir_size(&e.path()), + _ => 0, + }) + .sum() +} + +/// The type a plain file is charted and cleared as: its name's extension, else its message's. +fn plain_ext(item: &OnDisk) -> String { + Path::new(&item.path) + .extension() + .map(|e| e.to_string_lossy().to_lowercase()) + .unwrap_or_else(|| item.extension.to_lowercase()) +} + +/// Bytes by type: an extension, `/cache`, or `/ai_models`. +pub fn distribution() -> HashMap { + let mut out: HashMap = HashMap::new(); + for item in import::on_disk().unwrap_or_default() { + if vector_core::db::saved::is_saved(&item.path).unwrap_or(true) { + continue; + } + if let Ok(meta) = std::fs::metadata(&item.path) { + *out.entry(plain_ext(&item)).or_default() += meta.len(); + } + } + for (mime, _, bytes) in vector_core::db::media_store::totals().unwrap_or_default() { + let ext = vector_core::crypto::extension_from_mime(&mime); + *out.entry(if ext.is_empty() { "bin".into() } else { ext }) + .or_default() += bytes; + } + if let Ok(root) = vector_core::db::get_app_data_dir() { + let cache: u64 = cache_kinds() + .map(|k| dir_size(&root.join("cache").join(k))) + .sum(); + if cache > 0 { + *out.entry("/cache".into()).or_default() += cache; + } + } + out +} + +fn total() -> u64 { + distribution().values().sum() +} + +/// Forget the kept copies loaded messages show, of `exts` or all; their messages repaint. +async fn clear_kept(exts: Option<&HashSet>) -> Result<(), String> { + let mut changed: Vec<(String, vector_core::Message)> = Vec::new(); + { + let mut state = vector_core::STATE.lock().await; + for ci in 0..state.chats.len() { + let mut ids = Vec::new(); + for message in state.chats[ci].messages.iter_mut() { + let mut touched = false; + for att in &mut message.attachments { + if !att.downloaded() || att.has_path() { + continue; + } + if let Some(set) = exts { + let ext = vector_core::crypto::extension_from_mime( + vector_core::crypto::mime_from_extension(att.extension()), + ); + if !set.contains(&ext) { + continue; + } + } + vector_core::media::store::forget(att.id()); + att.set_downloaded(false); + att.set_downloading(false); + att.set_path(String::new()); + touched = true; + } + if touched { + ids.push(*message.id()); + } + } + let chat_id = state.chats[ci].id().to_string(); + for id in ids { + let hex = vector_core::simd::hex::bytes_to_hex_32(&id); + if let Some(m) = state.chats[ci].messages.find_by_hex_id(&hex) { + changed.push((chat_id.clone(), m.to_message(&state.interner))); + } + } + } + } + let mut by_chat: HashMap> = HashMap::new(); + for (chat, m) in &changed { + by_chat.entry(chat.clone()).or_default().push(m.clone()); + } + for (chat, msgs) in by_chat { + vector_core::db::events::save_chat_messages(&chat, &msgs).await?; + } + for (chat, mut m) in changed { + let old = m.id.clone(); + vector_core::traits::emit_message_update(&chat, &old, &mut m).await; + } + Ok(()) +} + +/// Let go of this account's plain files that `matches`, unless another account or a Save has them. +async fn release_downloads(matches: impl Fn(&OnDisk) -> bool) { + let Ok((Ok(files), elsewhere)) = vector_core::db::blocking_bound(|| { + let _ = import::reclaim_unmarked(); + (import::on_disk(), import::elsewhere()) + }) + .await + else { + return; + }; + let elsewhere = std::sync::Arc::new(elsewhere); + for item in files.into_iter().filter(|i| matches(i)) { + let (file, others) = (item.clone(), elsewhere.clone()); + match vector_core::db::blocking_bound(move || { + import::release(&file, others.as_ref().as_ref()) + }) + .await + { + Ok(Ok(events)) => { + let updates = + import::reflect_released(&mut *vector_core::STATE.lock().await, &item, &events); + for (chat, mut m) in updates { + let old = m.id.clone(); + vector_core::traits::emit_message_update(&chat, &old, &mut m).await; + } + } + Ok(Err(e)) => log::warn!("couldn't let a download go: {e}"), + Err(_) => return, + } + } +} + +fn clear_caches() { + if let Ok(root) = vector_core::db::get_app_data_dir() { + for kind in cache_kinds() { + let _ = std::fs::remove_dir_all(root.join("cache").join(kind)); + } + } + super::sound::purge(); +} + +/// Delete what no account on this device shows and nobody saved. Returns the bytes freed. +async fn clear_unclaimed() -> u64 { + let Ok(Some(shown)) = vector_core::db::blocking_bound(import::elsewhere).await else { + return 0; + }; + let dir = vector_core::db::get_download_dir(); + let Ok(files) = vector_core::db::blocking_bound(move || import::unclaimed(&dir, &shown)).await + else { + return 0; + }; + files + .into_iter() + .filter(|(p, _)| std::fs::remove_file(p).is_ok()) + .map(|(_, len)| len) + .sum() +} + +/// Everything: this account's files, what no account claims, and the caches. Returns bytes freed. +pub async fn clear_all() -> Result { + vector_core::db::scoped(async { + let before = total(); + if !super::mediaport::stop().await { + return Err(crate::t::settings_storage_clear_busy().into()); + } + clear_kept(None).await?; + vector_core::db::blocking_bound(|| vector_core::media::store::forget_where(|_| true)) + .await?; + release_downloads(|_| true).await; + let unclaimed = clear_unclaimed().await; + clear_caches(); + let _ = vector_core::db::miniapps::prune_dangling_miniapp_history(); + super::mediaport::resume(); + Ok(before.saturating_sub(total()) + unclaimed) + }) + .await +} + +/// One slice: `cache`, or the files of `exts`. Returns bytes freed. +pub async fn clear_category(category: &str, exts: Vec) -> Result { + let category = category.to_string(); + vector_core::db::scoped(async move { + let before = total(); + if category == "cache" { + clear_caches(); + } else { + let set: HashSet = exts.iter().map(|e| e.to_lowercase()).collect(); + if set.is_empty() { + return Err(crate::t::settings_storage_no_types().into()); + } + if !super::mediaport::stop().await { + return Err(crate::t::settings_storage_clear_busy().into()); + } + clear_kept(Some(&set)).await?; + let kept = set.clone(); + vector_core::db::blocking_bound(move || { + vector_core::media::store::forget_where(|mime| { + kept.contains(&vector_core::crypto::extension_from_mime(mime)) + }) + }) + .await?; + let apps = set.contains("xdc"); + release_downloads(move |item| set.contains(&plain_ext(item))).await; + super::mediaport::resume(); + if apps { + super::market::sweep_installs().await; + } + let _ = vector_core::db::miniapps::prune_dangling_miniapp_history(); + } + Ok(before.saturating_sub(total())) + }) + .await +} + +/// What turning Keep Files off would delete: (files, bytes), old downloads included, and +/// whether a download is running. +pub async fn kept_summary() -> (u64, u64, bool) { + let (mut files, mut bytes) = + vector_core::db::blocking_bound(vector_core::media::store::kept_files) + .await + .unwrap_or((0, 0)); + if let Ok(root) = vector_core::db::get_app_data_dir() { + for kind in ["inline_images", "embed_videos"] { + for e in std::fs::read_dir(root.join("cache").join(kind)) + .into_iter() + .flatten() + .flatten() + { + if let Some(m) = e.metadata().ok().filter(|m| m.is_file()) { + files += 1; + bytes += m.len(); + } + } + } + } + let (old, old_bytes) = super::mediaport::old_downloads().await; + (files + old, bytes + old_bytes, super::attachments::any_running()) +} + + +/// Keep Files on or off. Off deletes what it kept, so a file is kept or held, never both. +pub async fn set_keep_media(on: bool) -> Result<(), String> { + vector_core::db::scoped(async move { + let set = |on: bool| vector_core::db::set_sql_setting("keep_media".into(), on.to_string()); + if on { + set(true)?; + super::mediaport::start(std::time::Duration::ZERO); + return Ok(()); + } + if super::attachments::any_running() || !super::mediaport::stop().await { + return Err(crate::t::settings_storage_keep_busy().into()); + } + set(false)?; + if super::attachments::any_running() { + let _ = set(true); + return Err(crate::t::settings_storage_keep_busy().into()); + } + vector_core::db::set_sql_setting("keep_unencrypted".into(), "false".into())?; + clear_kept(None).await?; + vector_core::db::blocking_bound(|| vector_core::media::store::forget_where(|_| true)) + .await?; + if let Ok(root) = vector_core::db::get_app_data_dir() { + for kind in ["inline_images", "embed_videos"] { + let _ = std::fs::remove_dir_all(root.join("cache").join(kind)); + } + } + release_downloads(|_| true).await; + Ok(()) + }) + .await +} + +/// Auto-download (enabled, limit), migrating the pre-split single limit where 0 meant off. +pub fn auto_download() -> (bool, u64) { + const DEFAULT: u64 = 10_485_760; + const MIN: u64 = 1_048_576; + let get = |k: &str| { + vector_core::db::get_sql_setting(k.to_string()) + .ok() + .flatten() + }; + let limit = get("max_auto_download_bytes").and_then(|v| v.parse::().ok()); + match get("auto_download_enabled").as_deref() { + Some("true") => (true, limit.filter(|l| *l > 0).unwrap_or(DEFAULT)), + Some("false") => (false, limit.filter(|l| *l > 0).unwrap_or(DEFAULT)), + _ => { + let (on, limit) = match limit { + Some(0) => (false, MIN), + Some(l) => (true, l), + None => (true, DEFAULT), + }; + let _ = + vector_core::db::set_sql_setting("auto_download_enabled".into(), on.to_string()); + let _ = vector_core::db::set_sql_setting( + "max_auto_download_bytes".into(), + limit.to_string(), + ); + (on, limit) + } + } +} diff --git a/crates/vector-gpui/src/backend/stream.rs b/crates/vector-gpui/src/backend/stream.rs new file mode 100644 index 000000000..b8d11b7f0 --- /dev/null +++ b/crates/vector-gpui/src/backend/stream.rs @@ -0,0 +1,1092 @@ +//! An unencrypted web video played while it downloads, as a browser does: a connection per +//! region a decoder reads reads on from where it needs bytes, about ten seconds ahead (more on a +//! slow or uneven link), and pauses when that is in hand. The decoder's reads wait for the bytes +//! they need; a read elsewhere (a seek, the sound's own position) opens a connection there. + +use std::collections::BTreeMap; +use std::future::Future; +use std::sync::{Arc, Condvar, Mutex, Weak}; +use std::time::{Duration, Instant}; + +const CHUNK: u64 = 256 * 1024; +/// The first request: the header, and for most clips their first seconds. +const HEAD: u64 = 2 * CHUNK; +/// Before the clip's length (so its bitrate) is known. +const DEFAULT_WINDOW: u64 = 8 * 1024 * 1024; +const BASE_SECS: f64 = 10.; +const MAX_SECS: f64 = 30.; +/// Kept behind a read head for the decoder's short backward reads. +const KEEP_BEHIND: u64 = 2 * 1024 * 1024; +/// How long a head keeps the lowest offset its reader touched. +const HEAD_SPAN: Duration = Duration::from_secs(2); +/// A head its reader has read elsewhere for this long is gone. +const HEAD_LIFE: Duration = Duration::from_secs(3); +/// A reader that has read nothing at all for this long is gone, its heads with it. +const READER_LIFE: Duration = Duration::from_secs(30); +const READ_TIMEOUT: Duration = Duration::from_secs(45); +const ATTEMPTS: u32 = 4; +/// A connection that brings nothing for this long is dropped and opened again where it was. +const NO_PROGRESS: Duration = Duration::from_secs(6); +/// Connections kept open at once, each reading its own region. +const CONNS: usize = 3; +/// How far short of a gap a connection may be and still read on to it, in chunks. +const READ_THROUGH: u64 = 4; +/// Unread this long, a connection may have been closed by the host. +const PARKED: Duration = Duration::from_secs(5); +/// A read at least this far from a reader's heads starts a new one, however small the window. +const REGION: u64 = 8 * 1024 * 1024; + +/// One answer to a range request. +pub struct Got { + pub bytes: Vec, + /// The whole file's size, when the host says. + pub total: Option, + /// A 206: the host honoured the range. + pub ranged: bool, +} + +/// The bytes of an open connection, as they come; `None` at the file's end. +pub trait Body: Send + 'static { + fn next(&mut self) -> impl Future>, String>> + Send; +} + +/// Where byte ranges come from: the web, or memory in a test. +pub trait Ranges: Send + Sync + 'static { + type Body: Body; + fn get(&self, start: u64, end: u64) -> impl Future> + Send; + /// The file from `start` on. + fn from(&self, start: u64) -> impl Future> + Send; +} + +pub enum Open { + /// The host serves only whole files: download it the old way. + NoRanges, + Failed(String), +} + +/// Where one reader is reading in one region of the file. Each decoder reads on a thread of its +/// own, and one reader can need two distant regions at once: a file that stores its sound far +/// from its picture. +struct Head { + reader: Option, + /// The lowest offset it read this span: a demuxer hops between its tracks' samples, and + /// the bytes at the low end are still wanted while it reads the high. + at: u64, + /// Where it read last: a seek forward lands here before the span's low end moves. + last: u64, + span: Instant, + seen: Instant, + waiting: bool, +} + +struct State { + chunks: BTreeMap>, + heads: Vec, + error: Option, + duration_ms: Option, + /// Smoothed throughput (bytes/s) and time to first byte (s). + rate: Option, + latency: Option, + /// In-order hash of what arrived, while nothing was skipped. + hashed: u64, + hasher: Option, + /// The picture's decoder, when the player names it: the playhead whatever the others read. + lead: Option, + /// The connections open or opening: a task each, which ends once its slot is gone. + conns: Vec, + next_conn: u64, + /// Failed connections in a row, and when the next may open. + failures: u32, + retry_at: Option, +} + +/// One connection's place: the chunk it fills next, and when it last read. +struct Slot { + id: u64, + chunk: u64, + used: Instant, +} + +/// What a connection does next. +enum Want { + Read, + /// Past every window but still in a reader's way: unread, the host held back by TCP. + Park, + Close, +} + +pub struct Stream { + len: u64, + mime: &'static str, + expected: Option, + ranges: Arc, + state: Mutex, + arrived: Condvar, + moved: Arc, +} + +fn kind(head: &[u8]) -> Option<&'static str> { + if head.len() >= 12 && &head[4..8] == b"ftyp" { + Some(if &head[8..12] == b"qt " { "video/quicktime" } else { "video/mp4" }) // i18n-exempt: MP4 brand + } else if head.starts_with(&[0x1A, 0x45, 0xDF, 0xA3]) { + Some("video/webm") + } else { + None + } +} + +pub async fn open(ranges: R, expected: Option) -> Result>, Open> { + let t0 = Instant::now(); + let first = ranges.get(0, HEAD).await.map_err(Open::Failed)?; + let took = t0.elapsed().as_secs_f64().max(1e-3); + let total = match first.total { + Some(t) if first.ranged => t, + _ => return Err(Open::NoRanges), + }; + let mime = kind(&first.bytes).ok_or_else(|| Open::Failed(crate::t::embed_video_not_video().into()))?; + let s = Arc::new(Stream { + len: total, + mime, + expected: expected.map(|e| e.to_ascii_lowercase()), + ranges: Arc::new(ranges), + state: Mutex::new(State { + chunks: BTreeMap::new(), + heads: vec![Head { reader: None, at: 0, last: 0, span: Instant::now(), seen: Instant::now(), waiting: false }], + error: None, + duration_ms: None, + rate: Some(first.bytes.len() as f64 / took), + latency: Some(took * CHUNK as f64 / HEAD as f64), + hashed: 0, + hasher: None, + lead: None, + conns: Vec::new(), + next_conn: 0, + failures: 0, + retry_at: None, + }), + arrived: Condvar::new(), + moved: Arc::new(tokio::sync::Notify::new()), + }); + { + let mut st = s.state.lock().unwrap_or_else(|e| e.into_inner()); + st.hasher = s.expected.as_ref().map(|_| vector_core::crypto::sha256::Sha256::new()); + s.store(&mut st, 0, first.bytes); + } + let weak = Arc::downgrade(&s); + // spawn-detached: fills one web video's byte window; ends when the player lets it go. + tokio::spawn(fetch_loop(weak)); + Ok(s) +} + +impl Stream { + fn chunks(&self) -> u64 { + self.len.div_ceil(CHUNK) + } + + /// Bytes to hold ahead of the read head: ten seconds of the clip, more while the link can't + /// keep twice its bitrate or answers slowly. + fn window(&self, st: &State) -> u64 { + let Some(bitrate) = st.duration_ms.filter(|d| *d > 0).map(|d| self.len as f64 * 1000. / d as f64) else { + return DEFAULT_WINDOW; + }; + let mut secs = BASE_SECS; + if let Some(rate) = st.rate { + secs *= (2. * bitrate / rate.max(1.)).clamp(1., 3.); + } + if let Some(lat) = st.latency { + secs += lat * 4.; + } + ((bitrate * secs.min(MAX_SECS)) as u64).max(2 * CHUNK) + } + + /// The clip's length, which gives its bitrate and so the window's size in bytes. + pub fn set_duration(&self, ms: u64) { + self.state.lock().unwrap_or_else(|e| e.into_inner()).duration_ms = Some(ms); + self.moved.notify_one(); + } + + /// Bytes already here past `head`, up to the first gap. + fn held_past(&self, st: &State, head: u64) -> u64 { + let mut i = head / CHUNK; + while st.chunks.contains_key(&i) { + i += 1; + } + (i * CHUNK).min(self.len).saturating_sub(head) + } + + /// The reader furthest back: the picture at the playhead. The sound's decoder reads as far + /// ahead as its window allows, so it waits at the download's edge even with plenty in hand. + fn playhead(st: &State) -> Option> { + if let Some(lead) = st.lead + && st.heads.iter().any(|h| h.reader == Some(lead)) + { + return Some(Some(lead)); + } + // Two readers can share a span's low end; the one whose last read is further back leads. + st.heads.iter().min_by_key(|h| (h.at, h.last)).map(|h| h.reader) + } + + /// The thread decoding the picture: in a file that keeps its sound apart, the sound's + /// decoder can sit lower in one region while far ahead in time. + pub fn lead(&self, reader: std::thread::ThreadId) { + self.state.lock().unwrap_or_else(|e| e.into_inner()).lead = Some(reader); + } + + /// Only the playhead's reader waiting holds playback. + fn playhead_waits(st: &State) -> bool { + let p = Self::playhead(st); + st.heads.iter().any(|h| Some(h.reader) == p && h.waiting) + } + + /// Seconds of the clip already here past the playhead's reader, in its region nearest a gap. + pub fn ahead_secs(&self) -> Option { + let st = self.state.lock().unwrap_or_else(|e| e.into_inner()); + let d = st.duration_ms.filter(|d| *d > 0)?; + let p = Self::playhead(&st)?; + let mine: Vec<&Head> = st.heads.iter().filter(|h| h.reader == p).collect(); + let held = |h: &&Head| self.held_past(&st, h.at).min(self.held_past(&st, h.last)); + // A region in hand to the file's end (the index a demuxer reads there) can't run dry. + let open = |h: &&&Head| h.at + self.held_past(&st, h.at) < self.len; + let held = mine.iter().filter(open).map(held).min().or_else(|| mine.iter().map(held).max())?; + Some(held as f64 * d as f64 / 1000. / self.len as f64) + } + + /// Everything past every reader to the end is here. + pub fn complete_ahead(&self) -> bool { + let st = self.state.lock().unwrap_or_else(|e| e.into_inner()); + !st.heads.is_empty() && st.heads.iter().all(|h| (h.at / CHUNK..self.chunks()).all(|i| st.chunks.contains_key(&i))) + } + + /// The player moved: until the readers read again, nothing counts as buffered. + pub fn sought(&self) { + let mut st = self.state.lock().unwrap_or_else(|e| e.into_inner()); + st.heads.retain(|h| h.waiting); + self.moved.notify_one(); + } + + fn touch(&self, st: &mut State, offset: u64, waiting: bool) { + let now = Instant::now(); + let me = std::thread::current().id(); + let near = self.window(st).max(REGION); + let before = st.heads.len(); + // The opening's stand-in head goes once a real reader shows up. A head lapses once its + // reader reads on elsewhere: one blocked, or holding still (a full frame queue, playback + // not started), still needs every region it was reading. + let blocked: Vec<_> = st.heads.iter().filter(|h| h.waiting).map(|h| h.reader).collect(); + let latest = |r: Option| { + if r == Some(me) { now } else { st.heads.iter().filter(|h| h.reader == r).map(|h| h.seen).max().unwrap_or(now) } + }; + let keep: Vec = st + .heads + .iter() + .map(|h| { + let last = latest(h.reader); + h.reader.is_some() + && (blocked.contains(&h.reader) || now.duration_since(h.seen) < HEAD_LIFE || (last.duration_since(h.seen) < HEAD_LIFE && now.duration_since(last) < READER_LIFE)) + }) + .collect(); + let mut keep = keep.into_iter(); + st.heads.retain(|_| keep.next().unwrap_or(false)); + let pruned = st.heads.len() < before; + let dist = |h: &Head| offset.abs_diff(h.at).min(offset.abs_diff(h.last)); + let mine = st.heads.iter().enumerate().filter(|(_, h)| h.reader == Some(me) && dist(h) <= near).min_by_key(|(_, h)| dist(h)).map(|(i, _)| i); + // A thread blocks on one read at a time: its other regions aren't waiting. + for h in st.heads.iter_mut().filter(|h| h.reader == Some(me)) { + h.waiting = false; + } + match mine.map(|i| &mut st.heads[i]) { + Some(h) => { + if now.duration_since(h.span) > HEAD_SPAN { + (h.at, h.span) = (offset, now); + } else { + h.at = h.at.min(offset); + } + (h.last, h.seen, h.waiting) = (offset, now, waiting); + } + None => st.heads.push(Head { reader: Some(me), at: offset, last: offset, span: now, seen: now, waiting }), + } + if pruned { + self.evict(st); + } + } + + #[cfg(test)] + pub fn ranges(&self) -> &R { + &self.ranges + } + + /// What a stuck read was waiting on: the heads, the connections and the gaps they chase. + #[cfg(test)] + fn dump(&self) -> String { + let st = self.state.lock().unwrap_or_else(|e| e.into_inner()); + let heads: Vec = st.heads.iter().map(|h| format!("{:?}@{}..{}{}", h.reader, h.at / CHUNK, h.last / CHUNK, if h.waiting { " waiting" } else { "" })).collect(); // i18n-exempt: diagnostic log + let conns: Vec = st.conns.iter().map(|c| format!("#{}@{} read {:?} ago", c.id, c.chunk, c.used.elapsed())).collect(); // i18n-exempt: diagnostic log + format!("heads {heads:?}, conns {conns:?}, gaps {:?}, failures {}, window {} chunks", self.gaps(&st), st.failures, self.window(&st) / CHUNK) // i18n-exempt: diagnostic log + } + + /// A read is waiting on the network. + pub fn starving(&self) -> bool { + Self::playhead_waits(&self.state.lock().unwrap_or_else(|e| e.into_inner())) + } + + pub fn error(&self) -> Option { + self.state.lock().unwrap_or_else(|e| e.into_inner()).error.clone() + } + + fn store(&self, st: &mut State, first: u64, bytes: Vec) { + for (k, part) in bytes.chunks(CHUNK as usize).enumerate() { + let i = first + k as u64; + st.chunks.entry(i).or_insert_with(|| part.to_vec()); + } + self.hash_along(st); + self.evict(st); + self.arrived.notify_all(); + } + + /// Hashed only while every byte arrives in order; a mismatch stops the clip. + fn hash_along(&self, st: &mut State) { + let Some(want) = self.expected.as_ref() else { return }; + if st.hasher.is_none() { + return; + } + while st.hashed < self.len + && let Some(c) = st.chunks.get(&(st.hashed / CHUNK)) + { + if let Some(h) = st.hasher.as_mut() { + h.update(c); + } + st.hashed += c.len() as u64; + } + if st.hashed >= self.len + && let Some(h) = st.hasher.take() + { + let got: String = h.finalize().iter().map(|b| format!("{b:02x}")).collect(); + if &got != want { + st.error = Some(crate::t::embed_video_fingerprint().into()); + } + } + } + + /// What no reader needs goes: far behind each, or past twice the window ahead. The opening + /// stays, as players re-read the header on a seek. + fn evict(&self, st: &mut State) { + let behind = KEEP_BEHIND / CHUNK; + let ahead = self.window(st).div_ceil(CHUNK) * 2 + 1; + let unhashed = st.hasher.is_some().then(|| st.hashed / CHUNK); + let heads: Vec = st.heads.iter().flat_map(|h| [h.at / CHUNK, h.last / CHUNK]).collect(); + let needed = |i: u64| i < HEAD / CHUNK || heads.iter().any(|&h| i + behind >= h && i <= h + ahead); + let drop: Vec = st.chunks.keys().copied().filter(|&i| !needed(i)).collect(); + for i in drop { + st.chunks.remove(&i); + // A hole now precedes chunks not yet hashed: the in-order hash can't finish. + if unhashed.is_some_and(|h| i >= h) { + st.hasher = None; + } + } + } + + /// The chunks to fetch next, a reader's first gap each: a waiting read (the playhead's + /// first), then the playhead's regions, least in hand first, then the other readers'. + fn gaps(&self, st: &State) -> Vec { + let window = self.window(st); + let gap = |from: u64| { + let end = ((from + window).div_ceil(CHUNK)).min(self.chunks()); + (from / CHUNK..end).find(|i| !st.chunks.contains_key(i)) + }; + let p = Self::playhead(st); + let mut heads: Vec<&Head> = st.heads.iter().collect(); + heads.sort_by_key(|h| (!h.waiting, Some(h.reader) != p, self.held_past(st, h.at))); + let mut out: Vec = Vec::new(); + for g in heads.into_iter().filter_map(|h| if h.waiting { gap(h.last).or_else(|| gap(h.at)) } else { gap(h.at) }) { + if !out.contains(&g) { + out.push(g); + } + } + out + } + + /// Whether connection `id`, about to fill `chunk`, reads on, waits, or goes. + fn want(&self, st: &State, id: u64, chunk: u64) -> Want { + if chunk >= self.chunks() || !st.conns.iter().any(|c| c.id == id) { + return Want::Close; + } + let have = |k: u64| st.chunks.contains_key(&k); + // Another connection just ahead has everything between: from here it would read the same. + if have(chunk) && st.conns.iter().any(|o| o.id != id && o.chunk > chunk && o.chunk <= chunk + READ_THROUGH + 1 && (chunk..o.chunk).all(have)) { + return Want::Close; + } + let window = self.window(st).div_ceil(CHUNK); + let (mut inside, mut beyond) = (false, false); + for h in &st.heads { + let lo = (h.at / CHUNK).saturating_sub(1); + let hi = h.at.max(h.last) / CHUNK + window; + inside |= chunk >= lo && chunk < hi; + beyond |= chunk >= hi && chunk < hi + window; + } + let end = (chunk + READ_THROUGH + 1).min(self.chunks()); + if inside && (chunk..end).any(|k| !have(k)) { + Want::Read + } else if beyond && !have(chunk) { + Want::Park + } else { + Want::Close + } + } + + /// A smoothed throughput (bytes/s) or time to first byte (s) sample. + fn measured(&self, rate: Option, latency: Option) { + let mut st = self.state.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(r) = rate { + st.rate = Some(st.rate.map_or(r, |old| old * 0.7 + r * 0.3)); + } + if let Some(l) = latency { + st.latency = Some(st.latency.map_or(l, |old| old * 0.7 + l * 0.3)); + } + } + + fn fail(&self, e: String) { + self.state.lock().unwrap_or_else(|e| e.into_inner()).error = Some(e); + self.arrived.notify_all(); + } +} + +/// Opens a connection at each reader's gap no open one covers, without waiting on any: a slow +/// host answering one range must not hold up another the playhead needs. +async fn fetch_loop(weak: Weak>) { + loop { + let Some(s) = weak.upgrade() else { return }; + { + let mut st = s.state.lock().unwrap_or_else(|e| e.into_inner()); + if st.error.is_some() { + return; + } + if st.retry_at.is_none_or(|t| Instant::now() >= t) { + let top: Vec = s.gaps(&st).into_iter().take(CONNS).collect(); + let covers = |c: &Slot, g: u64| c.chunk <= g && g - c.chunk <= READ_THROUGH; + for &g in &top { + if st.conns.iter().any(|c| covers(c, g)) { + continue; + } + if st.conns.len() >= CONNS { + let spare = st.conns.iter().enumerate().filter(|(_, c)| !top.iter().any(|&t| covers(c, t))).min_by_key(|(_, c)| c.used).map(|(i, _)| i); + let Some(i) = spare else { break }; + st.conns.swap_remove(i); + } + let id = st.next_conn; + st.next_conn += 1; + st.conns.push(Slot { id, chunk: g, used: Instant::now() }); + // spawn-detached: one connection of a web video; it holds the stream only weakly and ends when the stream or its slot goes. + tokio::spawn(connection(weak.clone(), s.ranges.clone(), id, g)); + } + } + } + let moved = s.moved.clone(); + drop(s); + let _ = tokio::time::timeout(Duration::from_millis(100), moved.notified()).await; + } +} + +/// One range read on while a reader needs it, storing each chunk as it fills. +async fn connection(weak: Weak>, ranges: Arc, id: u64, start: u64) { + let opened = Instant::now(); + let opening = tokio::time::timeout(NO_PROGRESS, ranges.from(start * CHUNK)).await; + drop(ranges); + let mut body = match opening { + Ok(Ok(body)) => body, + Ok(Err(e)) => return failed(&weak, id, e), + Err(_) => return failed(&weak, id, crate::t::embed_video_host_silent().into()), + }; + let (mut chunk, mut buf, mut used, mut answered) = (start, Vec::new(), opened, false); + // Bytes and time spent waiting on the body since the last rate sample. + let mut tally = (0usize, Duration::ZERO); + loop { + let Some(s) = weak.upgrade() else { return }; + let want = s.want(&s.state.lock().unwrap_or_else(|e| e.into_inner()), id, chunk); + match want { + Want::Read => {} + Want::Park => { + drop(s); + tokio::time::sleep(Duration::from_millis(100)).await; + continue; + } + Want::Close => return s.state.lock().unwrap_or_else(|e| e.into_inner()).conns.retain(|c| c.id != id), + } + drop(s); + // One left unread a while may have been closed by the host: that is no failure. + let parked = used.elapsed() > PARKED; + let t0 = Instant::now(); + let piece = tokio::time::timeout(NO_PROGRESS, body.next()).await; + let waited = t0.elapsed(); + used = Instant::now(); + let Some(s) = weak.upgrade() else { return }; + let bytes = match piece { + Ok(Ok(Some(bytes))) => bytes, + Ok(Ok(None)) => return s.state.lock().unwrap_or_else(|e| e.into_inner()).conns.retain(|c| c.id != id), + Ok(Err(_)) | Err(_) if parked => return s.state.lock().unwrap_or_else(|e| e.into_inner()).conns.retain(|c| c.id != id), + Ok(Err(e)) => return failed(&weak, id, e), + Err(_) => return failed(&weak, id, crate::t::embed_video_host_stalled().into()), + }; + if !answered { + answered = true; + s.measured(None, Some(opened.elapsed().as_secs_f64())); + } else if !parked { + tally = (tally.0 + bytes.len(), tally.1 + waited); + } + if tally.0 as u64 >= CHUNK { + s.measured(Some(tally.0 as f64 / tally.1.as_secs_f64().max(1e-3)), None); + tally = (0, Duration::ZERO); + } + buf.extend_from_slice(&bytes); + let mut st = s.state.lock().unwrap_or_else(|e| e.into_inner()); + st.failures = 0; + loop { + let need = (s.len - (chunk * CHUNK).min(s.len)).min(CHUNK) as usize; + if need == 0 || buf.len() < need { + break; + } + let rest = buf.split_off(need); + let whole = std::mem::replace(&mut buf, rest); + s.store(&mut st, chunk, whole); + chunk += 1; + } + if let Some(c) = st.conns.iter_mut().find(|c| c.id == id) { + (c.chunk, c.used) = (chunk, used); + } + } +} + +/// A failed connection: the next waits a little, and a few in a row stop the clip. +fn failed(weak: &Weak>, id: u64, e: String) { + let Some(s) = weak.upgrade() else { return }; + let mut st = s.state.lock().unwrap_or_else(|e| e.into_inner()); + st.conns.retain(|c| c.id != id); + st.failures += 1; + if st.failures >= ATTEMPTS { + drop(st); + s.fail(e); + return; + } + st.retry_at = Some(Instant::now() + Duration::from_millis(500 * st.failures as u64)); +} + +impl vector_core::media::MediaSource for Stream { + fn len(&self) -> u64 { + self.len + } + + fn mime(&self) -> &str { + self.mime + } + + fn remote(&self) -> bool { + true + } + + fn read_at(&self, offset: u64, buf: &mut [u8]) -> std::io::Result { + if offset >= self.len || buf.is_empty() { + return Ok(0); + } + let want = buf.len().min((self.len - offset) as usize); + let mut st = self.state.lock().unwrap_or_else(|e| e.into_inner()); + self.touch(&mut st, offset, false); + self.moved.notify_one(); + let mut done = 0usize; + let mut waited = Duration::ZERO; + while done < want { + let at = offset + done as u64; + let (i, off) = (at / CHUNK, (at % CHUNK) as usize); + if let Some(c) = st.chunks.get(&i) { + let n = (c.len() - off).min(want - done); + buf[done..done + n].copy_from_slice(&c[off..off + n]); + done += n; + continue; + } + if let Some(e) = &st.error { + return Err(std::io::Error::other(e.clone())); + } + if waited >= READ_TIMEOUT { + return Err(std::io::Error::new(std::io::ErrorKind::TimedOut, crate::t::embed_video_stopped_loading().to_string())); + } + self.touch(&mut st, at, true); + self.moved.notify_one(); + let step = Duration::from_millis(250); + st = self.arrived.wait_timeout(st, step).unwrap_or_else(|e| e.into_inner()).0; + waited += step; + } + if waited > Duration::ZERO { + self.touch(&mut st, offset + done as u64, false); + } + Ok(done) + } +} + +/// Ranges of a web video, through the account's transport like any other media. +pub struct Web { + url: String, + client: vector_core::net::HttpClient, +} + +impl Web { + pub fn new(url: &str) -> Result { + vector_core::net::validate_url_not_private(url).map_err(str::to_string)?; + // Ranges left unread hold the host back by TCP; on a shared HTTP/2 connection they would + // fill the window the range being read needs. + let client = vector_core::net::build_http_client_with_options(None, Some(vector_core::net::transfer_stall()), true)?.http1_only(); + Ok(Self { url: url.to_string(), client }) + } +} + +pub struct WebBody(vector_core::net::Resp); + +impl Body for WebBody { + async fn next(&mut self) -> Result>, String> { + self.0.chunk().await.map(|b| b.map(|b| b.to_vec())).map_err(|e| e.to_string()) + } +} + +impl Ranges for Web { + type Body = WebBody; + + async fn from(&self, start: u64) -> Result { + let resp = vector_core::net::proxied_request(&self.client, reqwest::Method::GET, &self.url) + .await + .header(reqwest::header::RANGE, format!("bytes={start}-")) + .send() + .await + .map_err(|e| e.to_string())?; + match resp.status() { + reqwest::StatusCode::PARTIAL_CONTENT => Ok(WebBody(resp)), + s if s.is_success() => Err(crate::t::embed_video_no_ranges().into()), + s => Err(crate::t::embed_video_host_status(s.to_string()).to_string()), + } + } + + async fn get(&self, start: u64, end: u64) -> Result { + let resp = vector_core::net::proxied_request(&self.client, reqwest::Method::GET, &self.url) + .await + .header(reqwest::header::RANGE, format!("bytes={start}-{}", end - 1)) + .send() + .await + .map_err(|e| e.to_string())?; + let status = resp.status(); + if status != reqwest::StatusCode::PARTIAL_CONTENT { + // A whole file isn't read here: the caller falls back to downloading it. + return if status.is_success() { + Ok(Got { bytes: Vec::new(), total: resp.content_length(), ranged: false }) + } else { + Err(crate::t::embed_video_host_status(status.to_string()).to_string()) + }; + } + let total = resp + .headers() + .get(reqwest::header::CONTENT_RANGE) + .and_then(|v| v.to_str().ok()) + .and_then(|v| v.rsplit('/').next()) + .and_then(|t| t.parse().ok()); + let bytes = resp.bytes().await.map_err(|e| e.to_string())?; + if bytes.len() as u64 != end - start { + return Err(crate::t::embed_video_short_range().into()); + } + Ok(Got { bytes: bytes.into(), total, ranged: true }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::io::{Read, Seek, SeekFrom}; + use vector_core::media::MediaSource; + + /// A file in memory, served as ranges at `bps` bytes a second after `latency`. + struct Mem { + bytes: Arc>, + ranged: bool, + bps: Option, + latency: Duration, + served: Arc, + opened: std::sync::atomic::AtomicU32, + /// The offset of every piece served, to find a byte fetched twice. + pieces: Arc>>, + /// A range from this offset on takes this much longer to answer. + slow_from: Option<(u64, Duration)>, + } + + struct MemBody { + bytes: Arc>, + at: usize, + bps: Option, + served: Arc, + pieces: Arc>>, + } + + impl Body for MemBody { + async fn next(&mut self) -> Result>, String> { + let end = (self.at + 64 * 1024).min(self.bytes.len()); + if self.at >= end { + return Ok(None); + } + let part = self.bytes[self.at..end].to_vec(); + if let Some(bps) = self.bps { + tokio::time::sleep(Duration::from_secs_f64(part.len() as f64 / bps)).await; + } + self.pieces.lock().unwrap_or_else(|e| e.into_inner()).push(self.at as u64); + self.at = end; + self.served.fetch_add(part.len() as u64, std::sync::atomic::Ordering::Relaxed); + Ok(Some(part)) + } + } + + impl Ranges for Mem { + type Body = MemBody; + + async fn from(&self, start: u64) -> Result { + self.opened.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + tokio::time::sleep(self.latency).await; + if let Some((at, extra)) = self.slow_from + && start >= at + { + tokio::time::sleep(extra).await; + } + Ok(MemBody { bytes: self.bytes.clone(), at: start as usize, bps: self.bps, served: self.served.clone(), pieces: self.pieces.clone() }) + } + + async fn get(&self, start: u64, end: u64) -> Result { + tokio::time::sleep(self.latency).await; + if !self.ranged { + return Ok(Got { bytes: Vec::new(), total: Some(self.bytes.len() as u64), ranged: false }); + } + let part = self.bytes[start as usize..(end as usize).min(self.bytes.len())].to_vec(); + if let Some(bps) = self.bps { + tokio::time::sleep(Duration::from_secs_f64(part.len() as f64 / bps)).await; + } + self.served.fetch_add(part.len() as u64, std::sync::atomic::Ordering::Relaxed); + Ok(Got { bytes: part, total: Some(self.bytes.len() as u64), ranged: true }) + } + } + + fn video(len: usize) -> Vec { + let mut v: Vec = (0..len).map(|i| (i * 31 % 251) as u8).collect(); + v[4..12].copy_from_slice(b"ftypisom"); + v + } + + fn mem(bytes: Vec) -> Mem { + Mem { bytes: Arc::new(bytes), ranged: true, bps: None, latency: Duration::ZERO, served: Default::default(), opened: Default::default(), pieces: Default::default(), slow_from: None } + } + + fn sha(b: &[u8]) -> String { + vector_core::crypto::sha256_hex(b) + } + + fn rt() -> tokio::runtime::Runtime { + tokio::runtime::Builder::new_multi_thread().worker_threads(2).enable_all().build().unwrap() + } + + #[test] + fn reads_the_whole_file_in_order_and_checks_its_hash() { + let rt = rt(); + let v = video(5 * 1024 * 1024 + 123); + let s = rt.block_on(open(mem(v.clone()), Some(sha(&v)))).ok().unwrap(); + s.set_duration(20_000); + let src: Arc = s.clone(); + let mut r = vector_core::media::reader(src); + let mut out = Vec::new(); + r.read_to_end(&mut out).unwrap(); + assert_eq!(out, v); + assert!(s.error().is_none()); + } + + #[test] + fn a_wrong_hash_stops_the_clip_once_every_byte_is_in() { + let rt = rt(); + let v = video(1024 * 1024); + let s = rt.block_on(open(mem(v.clone()), Some("00".repeat(32)))).ok().unwrap(); + let src: Arc = s.clone(); + let mut r = vector_core::media::reader(src); + let mut out = Vec::new(); + assert!(r.read_to_end(&mut out).is_err() || s.error().is_some()); + } + + #[test] + fn seeks_read_the_right_bytes_and_keep_memory_bounded() { + let rt = rt(); + let v = video(40 * 1024 * 1024); + let s = rt.block_on(open(mem(v.clone()), None)).ok().unwrap(); + s.set_duration(80_000); + let src: Arc = s.clone(); + let mut r = vector_core::media::reader(src); + for at in [30 * 1024 * 1024u64, 1024, 20 * 1024 * 1024, 39 * 1024 * 1024, 5_000_000] { + r.seek(SeekFrom::Start(at)).unwrap(); + let mut b = vec![0u8; 300_000]; + r.read_exact(&mut b).unwrap(); + assert_eq!(&b[..], &v[at as usize..at as usize + 300_000]); + } + // Past a head's life, a read leaves only its own window held. + std::thread::sleep(HEAD_LIFE + Duration::from_millis(200)); + r.seek(SeekFrom::Start(5_000_000)).unwrap(); + r.read_exact(&mut [0u8; 1024]).unwrap(); + std::thread::sleep(Duration::from_millis(300)); + let held: u64 = s.state.lock().unwrap_or_else(|e| e.into_inner()).chunks.values().map(|c| c.len() as u64).sum(); + // Window (10 s of a 4 Mbit/s clip ≈ 5 MB) twice, plus what sits behind and the opening. + assert!(held < 16 * 1024 * 1024, "held {held}"); + } + + #[test] + fn a_seek_moves_its_readers_head_and_waiting_there_starves() { + let rt = rt(); + let v = video(40 * 1024 * 1024); + let mut m = mem(v.clone()); + m.bps = Some(1024. * 1024.); + let s = rt.block_on(open(m, None)).ok().unwrap(); + s.set_duration(80_000); + let src: Arc = s.clone(); + let far = 30 * 1024 * 1024usize; + let (went, gone) = std::sync::mpsc::channel(); + let reader = std::thread::spawn(move || { + let mut r = vector_core::media::reader(src); + r.read_exact(&mut [0u8; 1024]).unwrap(); + went.send(()).unwrap(); + r.seek(SeekFrom::Start(far as u64)).unwrap(); + let mut b = vec![0u8; 4096]; + r.read_exact(&mut b).unwrap(); + b + }); + gone.recv().unwrap(); + let t0 = Instant::now(); + while !s.starving() && t0.elapsed() < Duration::from_secs(5) { + std::thread::sleep(Duration::from_millis(5)); + } + assert!(s.starving(), "a read blocked at the new spot holds playback"); + assert_eq!(s.state.lock().unwrap_or_else(|e| e.into_inner()).heads.iter().filter(|h| h.waiting).count(), 1, "only the read at the new spot waits"); + assert_eq!(&reader.join().unwrap()[..], &v[far..far + 4096]); + assert!(!s.starving()); + s.sought(); + assert_eq!(s.ahead_secs(), None); + assert!(!s.complete_ahead()); + } + + #[test] + fn a_host_slow_to_answer_pays_its_delay_once() { + let rt = rt(); + let mut m = mem(video(40 * 1024 * 1024)); + m.latency = Duration::from_secs(1); + let s = rt.block_on(open(m, None)).ok().unwrap(); + s.set_duration(80_000); + std::thread::sleep(Duration::from_millis(2500)); + // One connection reads on: the window is in hand after a single round trip. + let held: u64 = s.state.lock().unwrap_or_else(|e| e.into_inner()).chunks.values().map(|c| c.len() as u64).sum(); + assert!(held >= 5 * 1024 * 1024, "held {held}"); + assert_eq!(s.ranges().opened.load(std::sync::atomic::Ordering::Relaxed), 1); + } + + #[test] + fn a_reader_in_two_distant_regions_fetches_each_byte_once() { + let rt = rt(); + let gap = 90 * 1024 * 1024u64; + let v = video(120 * 1024 * 1024); + let mut m = mem(v.clone()); + m.bps = Some(4. * 1024. * 1024.); + m.latency = Duration::from_millis(200); + let pieces = m.pieces.clone(); + let s = rt.block_on(open(m, None)).ok().unwrap(); + s.set_duration(120_000); + let src: Arc = s.clone(); + // The sound for each moment sits 90 MB before its picture; the demuxer reads them in turn. + let read = |a: u64, len: u64| { + let mut r = vector_core::media::reader(src.clone()); + let mut b = vec![0u8; 256 * 1024]; + let mut off = 0; + while off < len { + for at in [a + off, a + gap + off] { + r.seek(SeekFrom::Start(at)).unwrap(); + r.read_exact(&mut b).unwrap_or_else(|e| panic!("{e} at {at}: {}", s.dump())); + assert_eq!(&b[..], &v[at as usize..at as usize + b.len()]); + } + off += b.len() as u64; + } + }; + let t0 = Instant::now(); + read(1024 * 1024, 6 * 1024 * 1024); + s.sought(); + read(20 * 1024 * 1024, 6 * 1024 * 1024); + assert!(t0.elapsed() < Duration::from_secs(20), "took {:?}", t0.elapsed()); + let mut seen = pieces.lock().unwrap_or_else(|e| e.into_inner()).clone(); + let all = seen.len(); + seen.sort_unstable(); + seen.dedup(); + assert_eq!(seen.len(), all, "a piece was fetched twice"); + assert!(s.ranges().opened.load(std::sync::atomic::Ordering::Relaxed) <= 6); + } + + #[test] + fn the_playheads_range_never_waits_behind_a_slow_answer_elsewhere() { + let rt = rt(); + let v = video(60 * 1024 * 1024); + let mut m = mem(v.clone()); + m.slow_from = Some((40 * 1024 * 1024, Duration::from_secs(3))); + let s = rt.block_on(open(m, None)).ok().unwrap(); + s.set_duration(120_000); + let src: Arc = s.clone(); + // Another reader asks far ahead, where the host takes seconds to answer. + let far = src.clone(); + let other = std::thread::spawn(move || { + let mut r = vector_core::media::reader(far); + r.seek(SeekFrom::Start(50 * 1024 * 1024)).unwrap(); + r.read_exact(&mut [0u8; 4096]).unwrap(); + }); + std::thread::sleep(Duration::from_millis(200)); + let t0 = Instant::now(); + let at = 10 * 1024 * 1024usize; + let mut r = vector_core::media::reader(src); + r.seek(SeekFrom::Start(at as u64)).unwrap(); + let mut b = vec![0u8; 4096]; + r.read_exact(&mut b).unwrap(); + assert_eq!(&b[..], &v[at..at + 4096]); + assert!(t0.elapsed() < Duration::from_secs(1), "waited {:?}", t0.elapsed()); + other.join().unwrap(); + } + + #[test] + fn a_reader_ahead_of_the_playhead_waiting_doesnt_hold_playback() { + let rt = rt(); + let mut m = mem(video(60 * 1024 * 1024)); + m.bps = Some(1024. * 1024.); + let s = rt.block_on(open(m, None)).ok().unwrap(); + s.set_duration(120_000); + let src: Arc = s.clone(); + let (went, gone) = std::sync::mpsc::channel(); + // The sound's decoder: it starts where the picture does, then reads to the download's edge. + let ahead = src.clone(); + let sound = std::thread::spawn(move || { + let mut r = vector_core::media::reader(ahead); + r.read_exact(&mut [0u8; 1024]).unwrap(); + went.send(()).unwrap(); + r.seek(SeekFrom::Start(6 * 1024 * 1024)).unwrap(); + r.read_exact(&mut [0u8; 1024]).unwrap(); + }); + gone.recv().unwrap(); + let mut r = vector_core::media::reader(src); + r.read_exact(&mut [0u8; 1024]).unwrap(); + let t0 = Instant::now(); + while !s.state.lock().unwrap_or_else(|e| e.into_inner()).heads.iter().any(|h| h.waiting) && t0.elapsed() < Duration::from_secs(5) { + std::thread::sleep(Duration::from_millis(5)); + } + assert!(s.state.lock().unwrap_or_else(|e| e.into_inner()).heads.iter().any(|h| h.waiting), "the sound waits at the edge"); + assert!(!s.starving(), "the picture has its bytes: playback goes on"); + sound.join().unwrap(); + } + + #[test] + fn a_reader_holding_still_keeps_its_bytes() { + let rt = rt(); + let v = video(40 * 1024 * 1024); + let s = rt.block_on(open(mem(v), None)).ok().unwrap(); + s.set_duration(80_000); + let src: Arc = s.clone(); + // The picture's decoder reads, then holds still while its frame queue is full. + let at = 1024 * 1024u64; + let mut r = vector_core::media::reader(src.clone()); + r.seek(SeekFrom::Start(at)).unwrap(); + r.read_exact(&mut [0u8; 1024]).unwrap(); + // The sound's decoder reads on far away meanwhile. + let sound = std::thread::spawn(move || { + let mut r = vector_core::media::reader(src); + let t0 = Instant::now(); + let mut off = 20 * 1024 * 1024u64; + while t0.elapsed() < HEAD_LIFE + Duration::from_secs(1) { + r.seek(SeekFrom::Start(off)).unwrap(); + r.read_exact(&mut [0u8; 1024]).unwrap(); + off += 16 * 1024; + std::thread::sleep(Duration::from_millis(100)); + } + }); + sound.join().unwrap(); + assert!(s.state.lock().unwrap_or_else(|e| e.into_inner()).chunks.contains_key(&(at / CHUNK)), "the bytes it reads next were dropped"); + } + + #[test] + fn the_named_picture_reader_is_the_playhead() { + let rt = rt(); + let mut m = mem(video(60 * 1024 * 1024)); + m.bps = Some(1024. * 1024.); + let s = rt.block_on(open(m, None)).ok().unwrap(); + s.set_duration(120_000); + let src: Arc = s.clone(); + s.lead(std::thread::current().id()); + let mut r = vector_core::media::reader(src.clone()); + r.seek(SeekFrom::Start(2 * 1024 * 1024)).unwrap(); + r.read_exact(&mut [0u8; 1024]).unwrap(); + // The sound's decoder reads lower in the file, then waits at the download's edge. + let sound = std::thread::spawn(move || { + let mut r = vector_core::media::reader(src); + r.read_exact(&mut [0u8; 1024]).unwrap(); + r.seek(SeekFrom::Start(7 * 1024 * 1024)).unwrap(); + r.read_exact(&mut [0u8; 1024]).unwrap(); + }); + let t0 = Instant::now(); + while !s.state.lock().unwrap_or_else(|e| e.into_inner()).heads.iter().any(|h| h.waiting) && t0.elapsed() < Duration::from_secs(5) { + std::thread::sleep(Duration::from_millis(5)); + } + assert!(s.state.lock().unwrap_or_else(|e| e.into_inner()).heads.iter().any(|h| h.waiting), "the sound waits at the edge"); + assert!(!s.starving(), "the picture has its bytes: playback goes on"); + sound.join().unwrap(); + } + + #[test] + fn an_index_at_the_files_end_doesnt_hold_back_playback() { + let rt = rt(); + let v = video(40 * 1024 * 1024); + let s = rt.block_on(open(mem(v.clone()), None)).ok().unwrap(); + s.set_duration(80_000); + let src: Arc = s.clone(); + let mut r = vector_core::media::reader(src); + r.read_exact(&mut [0u8; 1024]).unwrap(); + r.seek(SeekFrom::Start(v.len() as u64 - 4096)).unwrap(); + r.read_exact(&mut [0u8; 4096]).unwrap(); + r.seek(SeekFrom::Start(2048)).unwrap(); + r.read_exact(&mut [0u8; 1024]).unwrap(); + std::thread::sleep(Duration::from_millis(500)); + let ahead = s.ahead_secs().unwrap(); + assert!(ahead > 5., "ahead {ahead:.2}s"); + } + + #[test] + fn a_host_without_ranges_falls_back() { + let rt = rt(); + let mut m = mem(video(1024 * 1024)); + m.ranged = false; + assert!(matches!(rt.block_on(open(m, None)), Err(Open::NoRanges))); + } + + #[test] + fn a_slow_link_grows_the_window() { + let rt = rt(); + let v = video(20 * 1024 * 1024); + // 20 MB over 40 s is 512 KB/s; served at 400 KB/s with 300 ms latency. + let mut m = mem(v.clone()); + m.bps = Some(400. * 1024.); + m.latency = Duration::from_millis(300); + let s = rt.block_on(open(m, None)).ok().unwrap(); + s.set_duration(40_000); + std::thread::sleep(Duration::from_secs(6)); + let st = s.state.lock().unwrap_or_else(|e| e.into_inner()); + let bitrate = 20. * 1024. * 1024. / 40.; + let w = s.window(&st) as f64 / bitrate; + assert!(w > BASE_SECS * 1.5, "window {w:.1}s, rate {:?}", st.rate); + } + + #[test] + fn stops_fetching_when_the_player_lets_go() { + let rt = rt(); + let v = video(30 * 1024 * 1024); + let mut m = mem(v); + m.bps = Some(2. * 1024. * 1024.); + let s = rt.block_on(open(m, None)).ok().unwrap(); + s.set_duration(60_000); + std::thread::sleep(Duration::from_millis(500)); + let weak = Arc::downgrade(&s); + drop(s); + std::thread::sleep(Duration::from_millis(2500)); + assert!(weak.upgrade().is_none()); + } +} diff --git a/crates/vector-gpui/src/backend/sync.rs b/crates/vector-gpui/src/backend/sync.rs new file mode 100644 index 000000000..956f73930 --- /dev/null +++ b/crates/vector-gpui/src/backend/sync.rs @@ -0,0 +1,436 @@ +//! Boot hydration, history catch-up, the live subscription and profile persistence. + +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::time::Duration; + +use vector_core::dm_catchup::{self, Opts, Report}; +use vector_core::event_handler::{BatchingPersist, commit_prepared_event}; +use vector_core::{CatchUp, STATE, SlimProfile, VectorCore, db, state}; + +use super::{Boot, UiEvent, events::Handler}; + +pub struct ProfileHandler; + +impl vector_core::ProfileSyncHandler for ProfileHandler { + fn on_profile_fetched(&self, slim: &SlimProfile, avatar_url: &str, banner_url: &str) { + let slim = slim.clone(); + let (avatar, banner) = (avatar_url.to_string(), banner_url.to_string()); + db::spawn_bound(async move { + let _ = db::profiles::set_profile(&slim); + super::images::cache_profile_images(&slim.id, &avatar, &banner).await; + }); + } + + fn forget_images(&self, images: Vec) { + for img in images { + let _ = std::fs::remove_file(&img.path); + } + } +} + +/// Load chats and profiles from the database into state, then hand them to the UI. +async fn hydrate() { + let Ok(npub) = db::get_current_account() else { + return; + }; + let mut state = STATE.lock().await; + if !state.db_loaded { + if let Ok(profiles) = db::profiles::get_all_profiles() { + state.merge_db_profiles(profiles, &npub); + } + // Before the first paint, so a blocked profile's pictures never show. + let (slims, images) = state.forget_blocked_imagery(); + vector_core::profile::sync::persist_forgotten_imagery(&ProfileHandler, slims, images); + let mut last_messages = db::events::get_all_chats_last_messages() + .await + .unwrap_or_default(); + if let Ok(slim_chats) = db::chats::get_all_chats() { + let mut known: std::collections::HashSet = + state.profiles.iter().map(|p| p.id).collect(); + for slim in slim_chats { + let mut chat = slim.to_chat(&mut state.interner); + let chat_id = chat.id().to_string(); + for &handle in chat.participants() { + if known.insert(handle) { + if let Some(p) = state.interner.resolve(handle).map(str::to_string) { + state.insert_or_replace_profile(&p, vector_core::Profile::new()); + } + } + } + if let Some(existing) = state.chats.iter_mut().find(|c| c.id == chat_id) { + // Made before its row loaded: take the stored read markers, or its next save + // would overwrite them. + if existing.last_read == [0u8; 32] { + existing.last_read = chat.last_read; + } + if existing.unread_from == [0u8; 32] { + existing.unread_from = chat.unread_from; + } + continue; + } + for message in last_messages.remove(&chat_id).unwrap_or_default() { + chat.internal_add_message(message, &mut state.interner); + } + state.chats.push(chat); + } + state + .chats + .sort_by_key(|c| std::cmp::Reverse(c.last_message_time())); + } + state.shrink_after_load(); + state.db_loaded = true; + let _ = db::id_cache::preload_id_caches(); + } + let chats = state + .chats + .iter() + .map(|c| c.to_serializable(&state.interner)) + .collect(); + let profiles = state + .profiles + .iter() + .map(|p| SlimProfile::from_profile(p, &state.interner)) + .collect(); + drop(state); + super::send(UiEvent::Booted(Boot { + npub, + chats, + profiles, + })); + db::spawn_bound(super::images::cache_all_profile_images()); +} + +/// Paint from the database, then catch up behind it. `init` is a login. +pub async fn fetch_messages(init: bool) { + if init { + super::transport::set_account_booted(true); + vector_core::transport::prelogin::commit(); + super::notify::logged_in(); + hydrate().await; + db::spawn_bound(super::market::preload()); + db::spawn_bound(super::mediaport::after_boot()); + } + db::spawn_bound(async move { + super::emit("sync_progress", serde_json::json!({ "mode": "Syncing" })); // i18n-exempt: event payload + let synced = db::current_session().scoped::(); + synced.store(false, Ordering::SeqCst); + if dms(false).await.reached_none() { + watch_unreachable(); + } + synced.store(true, Ordering::SeqCst); + super::emit("sync_finished", ()); + if init { + db::spawn_bound(merge_media_servers()); + db::spawn_bound(vector_core::badges::refresh_own()); + db::spawn_bound(vector_core::profile::sync::stamp_vector_client_after_sync()); + } + }); +} + +/// Warn that the relays are unreachable once none has connected in a long grace: a slow +/// network is not an offline one. +fn watch_unreachable() { + use nostr_sdk::prelude::RelayStatus; + let Some(pool) = state::nostr_client() else { return }; + db::spawn_bound(async move { + let grace = vector_core::relay_connect_timeout(Duration::from_secs(30)); + let deadline = std::time::Instant::now() + grace; + loop { + let relays = pool.relays().await; + if relays.values().any(|r| r.status() == RelayStatus::Connected) { + return; + } + if std::time::Instant::now() >= deadline { + vector_core::emit_event( + "show_toast", + &crate::t::network_relays_unreachable(relays.len()), + ); + return; + } + tokio::time::sleep(Duration::from_secs(1)).await; + } + }); +} + +/// The account's published media servers (kind 10063), merged in after the first sync. +async fn merge_media_servers() { + use vector_core::{blossom, blossom_info, blossom_servers}; + let (Some(client), Some(me)) = (state::nostr_client(), vector_core::my_public_key()) else { + return; + }; + if let Err(e) = blossom_servers::fetch_and_merge_own_list(&client, me).await { + vector_core::log_warn!("[BlossomServers] list fetch failed: {e}"); + } + let Ok(signer) = vector_core::signer::active_signer() else { + return; + }; + let servers = state::get_blossom_servers(); + if blossom_info::refresh_all(signer.clone(), servers.clone(), Duration::from_secs(60)).await > 0 + { + vector_core::emit_event("blossom_info_updated", &()); + } + if let Ok(n) = blossom::probe_servers_for_octet_stream(signer, servers).await { + if n > 0 { + vector_core::emit_event("blossom_capabilities_updated", &()); + } + } +} + +/// Start the live DM subscription. Runs for the session's life. +/// The session's live subscription is up. +struct Listening; + +/// Once per session: a window logging in finds the background service's already listening. +pub fn notifs() { + if db::current_session().scoped::().swap(true, Ordering::SeqCst) { + return; + } + db::spawn_bound(async { + if let Err(e) = VectorCore + .listen_with(Arc::new(Handler), CatchUp::External) + .await + { + vector_core::log_warn!("[GPUI] live subscription ended: {e}"); + } + db::current_session().scoped::().store(false, Ordering::SeqCst); + }); +} + +// ── Catch-up ──────────────────────────────────────────────────────────────── + +/// The login's DM sync has finished: until then it covers every relay itself. +struct Synced; +/// Relays that have connected at least once this session: only a reconnect can drop events. +struct SeenConnected; +/// Relays that came back mid-sync, caught up once it ends. +struct AfterSync; +/// When Connected last refolded the held Communities. +struct LastRefold; + +fn syncing() -> bool { + !db::current_session().scoped::().load(Ordering::SeqCst) +} + +/// A relay's socket came up. What it can have missed depends on what it is to us: DMs only +/// where we read, Community planes only on a Community relay. Someone else's inbox, dialled for +/// one send, is neither. +pub fn relay_connected(url: String, has_read: bool, has_gossip: bool) { + refold_held(); + let session = db::current_session(); + let reconnect = !session + .scoped::>>() + .lock() + .unwrap_or_else(|e| e.into_inner()) + .insert(url.clone()); + let discovery_only = !has_read && { + let norm = vector_core::inbox_relays::normalize_relay_url(&url); + let same = |d: &str| vector_core::inbox_relays::normalize_relay_url(d) == norm; + state::discovery_relay_iter().any(same) && !state::TRUSTED_RELAYS.iter().any(|d| same(d)) + }; + let todo = Owed::of(Seen { has_read, has_gossip, reconnect, syncing: syncing(), discovery_only }); + let after_sync = session.scoped::>>(); + if todo.dms_after_sync && after_sync.lock().unwrap_or_else(|e| e.into_inner()).insert(url.clone()) { + let url = url.clone(); + db::spawn_bound(async move { + let deadline = std::time::Instant::now() + Duration::from_secs(15 * 60); + while syncing() { + if db::session_stopped() || std::time::Instant::now() > deadline { + return; + } + tokio::time::sleep(Duration::from_secs(2)).await; + } + after_sync.lock().unwrap_or_else(|e| e.into_inner()).remove(&url); + if !db::session_stopped() { + dms_from(vec![url]).await; + } + }); + } + if todo.dms_now { + let url = url.clone(); + db::spawn_bound(async move { + dms_from(vec![url]).await; + }); + } + if todo.communities { + super::community::reconnected(url, has_read); + } +} + +/// What a relay that just came up is to us. +#[derive(Clone, Copy)] +struct Seen { + has_read: bool, + has_gossip: bool, + reconnect: bool, + syncing: bool, + /// A discovery relay that isn't also one we read or a default: it holds no planes. + discovery_only: bool, +} + +/// What a relay that came up can have missed, and so is asked for. +#[derive(Debug, PartialEq)] +struct Owed { + /// Its DMs once the login's sync ends: the sync may already have passed it. + dms_after_sync: bool, + dms_now: bool, + /// Plane fetches dial their relays themselves, so only a reconnect drops Community events. + communities: bool, +} + +impl Owed { + fn of(s: Seen) -> Self { + Self { + dms_after_sync: s.has_read && s.syncing && s.reconnect, + dms_now: s.has_read && !s.syncing, + communities: !s.syncing && s.reconnect && (s.has_read || s.has_gossip) && !s.discovery_only, + } + } +} + +/// A `limit(0)` subscription never replays what a relay missed while down: each Connected +/// refolds the held Communities and re-tracks the subscription at their current epochs, once +/// per burst. +fn refold_held() { + let last = db::current_session().scoped::(); + let now = vector_core::clock::now_ms(); + let before = last.load(Ordering::SeqCst); + if now.saturating_sub(before) < 3000 || last.compare_exchange(before, now, Ordering::SeqCst, Ordering::SeqCst).is_err() { + return; + } + db::spawn_bound(async { + for c in vector_core::community::v2::realtime::load_held_v2() { + vector_core::community::v2::realtime::enqueue_follow(c.id()); + } + if let Some(c) = state::nostr_client() { + vector_core::community::v2::realtime::refresh_subscription(&c).await; + } + }); +} + +/// What a dropped live subscription or a stretch away missed. +pub fn catch_up(what: vector_core::live_subs::CatchUp) { + use vector_core::live_subs::CatchUp; + db::spawn_bound(async move { + let Some(client) = state::nostr_client() else { return }; + match what { + CatchUp::Relay(url) => { + let has_read = matches!(client.relay(&url).await, Ok(Some(r)) if r.capabilities().has_read()); + if has_read { + dms_from(vec![url.clone()]).await; + } + super::community::reconnected(url, has_read); + } + CatchUp::All { .. } => { + if syncing() { + return; + } + for (url, relay) in client.relays().await { + super::community::reconnected(url.to_string(), relay.capabilities().has_read()); + } + retrying(Opts { is_new: true, only: None, bootstrap: false }).await; + } + } + }); +} + +/// What `relays` hold that we missed: news, so it notifies. +async fn dms_from(relays: Vec) { + retrying(Opts { is_new: true, only: Some(relays), bootstrap: false }).await; +} + +async fn retrying(opts: Opts) -> Report { + let (is_new, bootstrap) = (opts.is_new, opts.bootstrap); + let report = dm_pass(opts).await; + if !report.complete() { + let first = report.clone(); + db::spawn_bound(async move { + dm_catchup::retry_incomplete(&first, |relays| { + dm_pass(Opts { is_new, only: (!relays.is_empty()).then_some(relays), bootstrap }) + }) + .await; + }); + } + report +} + +struct Bootstrapping; + +/// Catch up on DMs: each read relay's window since its cursor, retried behind it until held. +/// A relay with no cursor yet then reconciles its whole history once, in the background. +pub async fn dms(is_new: bool) -> Report { + let report = retrying(Opts { is_new, only: None, bootstrap: false }).await; + bootstrap_cursorless().await; + dm_catchup::start_safety_net(|| { + dm_pass(Opts { + is_new: true, + only: None, + bootstrap: false, + }) + }); + report +} + +async fn dm_pass(opts: Opts) -> Report { + let batcher = BatchingPersist::new(&Handler); + dm_catchup::catch_up(&opts, &batcher, |prepared, is_new| { + commit_prepared_event(prepared, is_new, &batcher) + }) + .await +} + +async fn bootstrap_cursorless() { + let Some(client) = state::nostr_client() else { + return; + }; + let fresh: Vec = client + .relays() + .await + .into_iter() + .filter(|(url, relay)| { + relay.capabilities().has_read() + && vector_core::negentropy::reconcile_cursor(url.as_str()).is_none() + }) + .map(|(url, _)| url.to_string()) + .collect(); + let busy = db::current_session().scoped::(); + if fresh.is_empty() || busy.swap(true, Ordering::SeqCst) { + return; + } + db::spawn_bound(async move { + dm_pass(Opts { + is_new: false, + only: Some(fresh), + bootstrap: true, + }) + .await; + busy.store(false, Ordering::SeqCst); + }); +} + +#[cfg(test)] +mod tests { + use super::{Owed, Seen}; + + fn seen(has_read: bool, has_gossip: bool, reconnect: bool, syncing: bool) -> Seen { + Seen { has_read, has_gossip, reconnect, syncing, discovery_only: false } + } + + #[test] + fn a_relay_is_asked_only_for_what_it_can_have_missed() { + // A read relay's first connect after the sync: its DMs, not its Communities. + assert_eq!(Owed::of(seen(true, false, false, false)), Owed { dms_after_sync: false, dms_now: true, communities: false }); + // Its reconnect: both. + assert_eq!(Owed::of(seen(true, false, true, false)), Owed { dms_after_sync: false, dms_now: true, communities: true }); + // Back mid-sync: its DMs once the sync ends, nothing now. + assert_eq!(Owed::of(seen(true, false, true, true)), Owed { dms_after_sync: true, dms_now: false, communities: false }); + // A Community relay we don't read: its planes on a reconnect only. + assert_eq!(Owed::of(seen(false, true, true, false)), Owed { dms_after_sync: false, dms_now: false, communities: true }); + assert_eq!(Owed::of(seen(false, true, false, false)), Owed { dms_after_sync: false, dms_now: false, communities: false }); + // Someone else's inbox, dialled for one send. + assert_eq!(Owed::of(seen(false, false, true, false)), Owed { dms_after_sync: false, dms_now: false, communities: false }); + // A discovery relay holds no planes. + let indexer = Seen { discovery_only: true, ..seen(false, true, true, false) }; + assert_eq!(Owed::of(indexer), Owed { dms_after_sync: false, dms_now: false, communities: false }); + } +} diff --git a/crates/vector-gpui/src/backend/transcribe.rs b/crates/vector-gpui/src/backend/transcribe.rs new file mode 100644 index 000000000..bcb391c04 --- /dev/null +++ b/crates/vector-gpui/src/backend/transcribe.rs @@ -0,0 +1,134 @@ +//! Whisper on the desktop client's module: the account's model choice, the download, and a +//! transcription of an attachment off the UI thread. + +use vector_media::whisper; + +pub const DEFAULT_MODEL: &str = "small"; + +fn app() -> Result { + vector_media::TAURI_APP.get().copied().ok_or_else(|| "Audio engine not started".to_string()) // i18n-exempt: developer error +} + +fn setting(key: &str) -> Option { + vector_core::db::settings::get_sql_setting(key.to_string()).ok().flatten().filter(|v| !v.is_empty()) +} + +/// The account's chosen model and whether it translates to English. +pub fn choice() -> (String, bool) { + let model = setting("whisper_model_name").unwrap_or_else(|| DEFAULT_MODEL.to_string()); + let translate = setting("whisper_auto_translate").as_deref() == Some("true"); + (model, translate) +} + +pub fn auto_transcribe() -> bool { + setting("whisper_auto_transcribe").as_deref() == Some("true") +} + +pub fn downloaded(model: &str) -> bool { + fixture().is_some() || app().is_ok_and(|a| whisper::is_model_downloaded(&a, model)) +} + +/// A model as the Voice page lists it. +#[derive(Clone)] +pub struct Model { + pub name: &'static str, + pub display: &'static str, + /// Megabytes on disk, and of memory it needs to run. + pub size: usize, + pub ram: usize, + pub translate: bool, + pub downloaded: bool, +} + +pub fn models() -> Vec { + let fixture = fixture().is_some(); + let app = app().ok(); + whisper::MODELS + .iter() + .map(|m| Model { + name: m.name, + display: m.display_name, + size: m.size, + ram: m.ram_required, + translate: m.supports_translate, + downloaded: if fixture { + m.name == DEFAULT_MODEL && std::env::var("VECTOR_TRANSCRIPT").is_ok_and(|v| v != "missing") + } else { + app.as_ref().is_some_and(|a| whisper::is_model_downloaded(a, m.name)) + }, + }) + .collect() +} + +/// This device's memory in megabytes, which bounds the models it can run. +pub fn memory_mb() -> u64 { + if fixture().is_some() { + return 2048; + } + let mut sys = sysinfo::System::new(); + sys.refresh_memory(); + sys.total_memory() / (1024 * 1024) +} + +pub fn set(key: &'static str, value: impl ToString) { + let _ = vector_core::db::settings::set_sql_setting(key.to_string(), value.to_string()); +} + +pub async fn download(model: String) -> Result<(), String> { + let app = app()?; + whisper::download_whisper_model(&app, &model).await.map(|_| ()).map_err(|e| e.to_string()) +} + +pub async fn delete(model: String) -> bool { + match app() { + Ok(app) => whisper::delete_whisper_model(app, model).await, + Err(_) => false, + } +} + +pub fn cancel_download() { + tauri::async_runtime::spawn(whisper::cancel_whisper_download()); +} + +/// Transcribe a file, downloading the model first if it isn't here. +pub async fn transcribe(input: vector_media::audio_engine::AudioInput) -> Result { + if let Some(r) = fixture() { + return Ok(r); + } + let app = app()?; + let (model, translate) = choice(); + let audio = tokio::task::spawn_blocking(move || vector_media::audio::decode_for_whisper(&input)) + .await + .map_err(|e| e.to_string())??; + whisper::transcribe(&app, &model, translate, audio).await.map_err(|e| e.to_string()) +} + +/// Dictation: the recording held for the preview, as one line of text. +pub async fn transcribe_recording() -> Result { + let r = match fixture() { + Some(r) => r, + None => { + let app = app()?; + let (model, _) = choice(); + let audio = vector_media::voice::AudioRecorder::global().pending_for_whisper()?; + whisper::transcribe(&app, &model, false, audio).await.map_err(|e| e.to_string())? + } + }; + Ok(r.sections.iter().map(|s| s.text.trim()).filter(|t| !t.is_empty()).collect::>().join(" ")) +} + +/// `VECTOR_TRANSCRIPT`: a canned transcript for reference renders, which have no model. +fn fixture() -> Option { + std::env::var_os("VECTOR_TRANSCRIPT")?; + let section = |at: i64, text: &str| whisper::TranscriptionSection { text: text.into(), at, confidence: 0.9 }; + Some(whisper::TranscriptionResult { + sections: vec![ + section(0, "Привет, это Ана."), + section(1800, "Я буду дома около семи,"), + section(4200, "купи, пожалуйста, хлеб по дороге."), + ], + lang: "ru".into(), + language: "ru".into(), + confidence: 0.9, + }) +} diff --git a/crates/vector-gpui/src/backend/transfer.rs b/crates/vector-gpui/src/backend/transfer.rs new file mode 100644 index 000000000..e6c6de234 --- /dev/null +++ b/crates/vector-gpui/src/backend/transfer.rs @@ -0,0 +1,91 @@ +//! Device transfer: sign this account in on another device, or this device in from another. The +//! protocol is core's; this adds the proof that opens the key, and the sign-in at the far end. + +use vector_core::transfer::service; +use vector_core::transfer::session::{ApproveError, Bundle, Role}; +use zeroize::Zeroizing; + + +pub struct Started { + pub id: u64, + pub code: Option, + pub qr: Option, +} + +/// `send` when this device holds the account; `code` to join the other device's code. +pub async fn start(send: bool, code: Option) -> Result { + let identity = if send { + if vector_core::is_keyless() { + return Err(crate::t::transfer_signer_account().into()); + } + Some(vector_core::state::my_public_key().ok_or_else(|| crate::t::transfer_sign_in_first().to_string())?) + } else { + None + }; + let role = if send { Role::Sender } else { Role::Receiver }; + let s = service::start(role, code.as_deref(), identity).await?; + Ok(Started { + id: s.id, + code: s.code, + qr: s.qr, + }) +} + +/// Sender: the number from the new device's screen. `Err(Some(n))` when wrong, `n` tries left. +pub async fn check_number(number: String) -> Result<(), Result> { + service::check_number(&number).await.map_err(|e| match e { + ApproveError::WrongNumber { tries_left } => Ok(tries_left as u32), + _ => Err(crate::t::transfer_not_waiting().to_string()), + }) +} + +/// Sender: hand the account over, its key opened under the user's own proof. +pub async fn approve(credential: Option>) -> Result<(), String> { + if vector_core::is_keyless() || !service::sender_is_current() { + return Err(crate::t::transfer_not_waiting().into()); + } + let session = vector_core::db::current_session(); + let key = if vector_core::state::is_encryption_enabled_fast() { + Some(super::security::prove(credential).await?) + } else { + None + }; + let (nsec, seed) = vector_core::db::at_rest::open_identity_secrets(key.as_deref())?; + if !session.is_live() { + return Err(crate::t::transfer_account_changed().into()); + } + let bundle = Bundle::from_stored(&nsec, seed.as_deref().map(|s| s.as_str())); + service::approve(bundle).await.map_err(|e| match e { + ApproveError::NotYours => { + crate::t::transfer_key_mismatch().to_string() + } + _ => crate::t::transfer_not_waiting().to_string(), + }) +} + +pub fn deny() { + service::deny(); +} + +pub fn cancel() { + service::cancel(); +} + +/// Receiver: sign in with the account that arrived. It stays held until this succeeds, so a +/// failed sign-in can be tried again. +pub async fn finish(add: Option<(Option, Option)>) -> Result { + let bundle = service::received().ok_or("Nothing has arrived to sign in with")?; // i18n-exempt: matched by the transfer screen + let nsec = bundle.nsec.clone(); + let seed = bundle.seed.clone().map(Zeroizing::new); + drop(bundle); + if let Some((kind, opts)) = add { + super::account::enter_add_mode(kind, opts).await?; + } + let imported = super::account::import(nsec).await?; + if matches!(imported, super::account::Imported::Staged(_)) { + *vector_core::state::MNEMONIC_SEED.lock().unwrap_or_else(|e| e.into_inner()) = seed.map(|s| s.to_string()); + super::account::connect().await; + } + service::forget_received(); + Ok(imported) +} diff --git a/crates/vector-gpui/src/backend/transport.rs b/crates/vector-gpui/src/backend/transport.rs new file mode 100644 index 000000000..9ec41548e --- /dev/null +++ b/crates/vector-gpui/src/backend/transport.rs @@ -0,0 +1,1320 @@ +//! The network lifecycle: one switch for every kind, in failsafe order, with Tor's and I2P's own +//! settings. The desktop client's `commands/transport.rs`, `tor.rs` and `i2p.rs`. +//! +//! Tightening (into Tor, I2P, …) refuses in memory first, then persists, then starts the +//! kind; loosening (into Clearnet) persists first and stops the kind before anything may go +//! direct. Every step runs under one lifecycle lock, for the live session only. + +use std::sync::atomic::{AtomicBool, Ordering}; +use std::time::Duration; + +use serde_json::Value; +use vector_core::transport::aliases::{self, AliasEntry, AliasSource}; +use vector_core::transport::prelogin::{self, PreloginChoice}; +use vector_core::transport::status::{self, RouteView, TransportStateView}; +use vector_core::transport::{self, host, i2p_config, Kind, StartCtx}; + +/// One start or stop at a time across the welcome screen and the account paths. +static LIFECYCLE: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(()); + +/// An account has booted in this session: the welcome screen's choice no longer applies. +static ACCOUNT_BOOTED: AtomicBool = AtomicBool::new(false); + +/// A relay list or dialog never asks for more routes than this at once. +const MAX_ROUTES: usize = 512; + +pub fn set_account_booted(booted: bool) { + ACCOUNT_BOOTED.store(booted, Ordering::Release); +} + +pub fn account_booted() -> bool { + ACCOUNT_BOOTED.load(Ordering::Acquire) +} + +/// A command bound to an account that is no longer on screen acts on nothing. +pub fn ensure_live() -> Result<(), String> { + if vector_core::db::current_session_id() == vector_core::db::live_session_id() { + Ok(()) + } else { + Err(crate::t::account_changed().into()) + } +} + +/// Is the running instance the welcome screen's (install-level dirs) rather than an account's? +pub fn running_prelogin() -> bool { + host::active().is_some_and(|a| a.started_prelogin()) +} + +fn parse_kind(kind: &str) -> Result { + let k = Kind::parse(kind).ok_or_else(|| format!("Unknown network: {kind}"))?; // i18n-exempt: developer error + if !k.compiled() { + return Err(status::not_in_build(k).text); + } + Ok(k) +} + +/// The inputs a kind's start takes: Tor its directories and bridges, others their config. Only +/// for `owner` while it is the live session: the dirs and config are the live account's. +async fn start_ctx(kind: Kind, prelogin: bool, owner: u64) -> Result { + if owner != vector_core::db::live_session_id() { + return Err(crate::t::account_changed().into()); + } + match kind { + #[cfg(feature = "tor")] + Kind::Tor => { + let engine = prelogin::config_for(Kind::Tor) + .downcast_ref::() + .cloned() + .unwrap_or_default(); + if engine.external { + return Ok(StartCtx { + owner, + started_prelogin: prelogin, + dirs: None, + config: std::sync::Arc::new(vector_core::tor::TorStartConfig { bridges: Vec::new(), engine }), + }); + } + let (dirs, bridges) = if prelogin { + (vector_core::tor::prelogin_dirs()?, Vec::new()) + } else { + (tor_data_dirs().await?, read_saved_bridges()) + }; + Ok(StartCtx { + owner, + started_prelogin: prelogin, + dirs: Some(dirs), + config: std::sync::Arc::new(vector_core::tor::TorStartConfig { bridges, engine }), + }) + } + _ => Ok(StartCtx { owner, started_prelogin: prelogin, dirs: None, config: prelogin::config_for(kind) }), + } +} + +/// Start `kind` for `owner` (the session the caller acts for) and install it. Refused unless +/// `owner` is live; a start that lands once it no longer is shuts itself down. `prelogin` is the +/// welcome screen's generation the start was wanted at: another pick drops it mid-flight, so a +/// network nobody chose stops contacting anything. Ok(false): superseded, nothing installed. +async fn start_kind(kind: Kind, prelogin: Option, owner: u64) -> Result { + let factory = transport::kinds::factory(kind).ok_or_else(|| status::not_in_build(kind).text)?; + let ctx = start_ctx(kind, prelogin.is_some(), owner).await?; + let inst = match prelogin { + Some(generation) => tokio::select! { + started = factory.start(ctx) => started?, + _ = prelogin::superseded(generation) => return Ok(false), + }, + None => factory.start(ctx).await?, + }; + if owner != vector_core::db::live_session_id() { + inst.shutdown().await; + return Err(crate::t::account_changed().into()); + } + // Landed after the choice moved on: installing it would only cut the sockets of the network + // in use, twice. + if transport::preference() != Some(kind) || prelogin.is_some_and(|g| g != prelogin::generation()) { + inst.shutdown().await; + return Ok(false); + } + host::activate(inst, owner, prelogin.is_some())?; + Ok(true) +} + +/// Stop the installed instance; a pre-login one is joined so its directories are free. +async fn stop_active() { + let join = running_prelogin(); + host::deactivate(join).await; +} + +/// An instance of `kind` owned by the live session that can serve the config it would start +/// with now (I2P: the same router). +fn running_compatible(kind: Kind) -> bool { + let live = vector_core::db::live_session_id(); + host::active().is_some_and(|a| { + a.kind == kind + && a.owner() == live + && transport::kinds::factory(kind).is_some_and(|f| f.compatible(a.transport().as_ref(), &prelogin::config_for(kind))) + }) +} + +/// The view of the live session, emitted and returned by every command here. +fn view() -> TransportStateView { + status::view() +} + +fn emit_view() { + vector_core::traits::emit_event("transport_state", &view()); +} + +/// Match the installed instance to the live account's preference: keep one it owns and can +/// serve, replace anything else. A kind that reports ready later is waited for (bounded) so the +/// first sync runs on a connected network. +pub async fn sync_to_active_account() -> Result<(), String> { + start_for_active_account().await?; + wait_for_active_network().await; + Ok(()) +} + +/// [`sync_to_active_account`] without the wait: a kind that starts in the background (I2P) +/// builds its tunnels while sign-in does its own work. +pub async fn start_for_active_account() -> Result<(), String> { + { + let _serial = LIFECYCLE.lock().await; + // The account on screen when the lock was taken: a swap during the stop below must not + // get this start. + let owner = vector_core::db::live_session_id(); + match transport::preference() { + None => { + host::deactivate(true).await; + return Err(crate::t::routing_pref_not_loaded().into()); + } + Some(Kind::Clearnet) => { + if host::active().is_some() { + stop_active().await; + } + } + Some(k) => { + if !running_compatible(k) { + stop_active().await; + start_kind(k, None, owner).await?; + } + } + } + } + vector_core::net::forget_clients(); + Ok(()) +} + +/// Wait for the live account's network when it is still coming up, within its start budget. +pub async fn wait_for_active_network() { + let starting = transport::preference().is_some_and(|k| k != Kind::Clearnet) + && host::active().is_some_and(|a| !a.transport().ready()); + if starting { + wait_until_ready(&vector_core::db::live_session()).await; + } +} + +/// How long sign-in waits on a router that isn't answering at all. +const ROUTER_GRACE: Duration = Duration::from_secs(10); + +/// Hold sign-in until the network is up, within its start budget. A router that turned Vector +/// down, or that stays silent, needs the user rather than more time: sign-in then continues +/// blocked, and the Ready listener reconnects once it answers. +async fn wait_until_ready(session: &vector_core::db::Session) { + let start = std::time::Instant::now(); + let deadline = start + transport::budget(transport::Op::Startup, Duration::ZERO); + let mut silent_since: Option = None; + loop { + let left = deadline.saturating_duration_since(std::time::Instant::now()); + if transport::wait_ready(left.min(Duration::from_secs(2))).await.is_ok() || left.is_zero() { + return; + } + if session.stopped() || !session.is_live() { + return; + } + let code = transport::preference().and_then(status::reason_for).map(|r| r.code); + match code.as_deref() { + Some(c) if c.starts_with("sam_") => return, + Some("router_unreachable") => { + if silent_since.get_or_insert_with(std::time::Instant::now).elapsed() >= ROUTER_GRACE { + return; + } + } + _ => silent_since = None, + } + } +} + +/// Stop whatever runs, returning at once; the instance finishes its shutdown on its own. +#[allow(dead_code)] +pub fn stop_if_running() { + if let Some(a) = host::uninstall() { + // spawn-detached: finishes the uninstalled instance's own shutdown. + drop(vector_core::transport::spawn_on(async move { a.transport().shutdown().await })); + } +} + +/// Stop whatever runs and wait until the bridge holds none of it (logout wipes its dirs next). +pub async fn stop_and_join_if_running() { + host::deactivate(true).await; +} + +/// Android background teardown: Tor restarts per pause; other kinds keep their router sessions +/// for the life of the process, so a resume finds them up. +#[allow(dead_code)] +pub async fn stop_tor_if_running() { + if host::active().is_some_and(|a| a.kind == Kind::Tor) { + host::deactivate(true).await; + } +} + +/// Stop the welcome screen's instance, waiting out a start still in flight so it can't land +/// after an account's own has taken over. +pub async fn stop_prelogin_service() { + prelogin::cancel_start(); + let _serial = LIFECYCLE.lock().await; + if running_prelogin() { + host::deactivate(true).await; + } +} + +/// Cycle the main client's relays onto the current circuits (New circuit, bridges, circuit mode). +#[cfg_attr(not(feature = "tor"), allow(dead_code))] +pub async fn switch_relay_transport() { + transport::cycle::cycle_all(transport::cycle::CycleScope::Circuits).await; +} + +/// The stored kind of the account picked on the unlock screen, or nothing when none is picked. +fn picked_account_stored() -> transport::prefs::StoredKind { + if vector_core::db::get_current_account().is_ok() { + transport::prefs::stored_kind() + } else { + transport::prefs::StoredKind::Absent + } +} + +/// What the welcome screen picked for `kind` before: the armed choice, else the remembered one. +fn remembered_opts(kind: Kind) -> Option { + prelogin::armed() + .filter(|c| c.kind == kind) + .or_else(|| prelogin::marker().ok().flatten().filter(|c| c.kind == kind)) + .map(|c| c.opts) +} + +/// A welcome-screen choice with only the options its kind reads; ones left out keep the earlier +/// pick. SAM credentials stay in memory until an account commits; the marker never holds them. +pub fn prelogin_choice(kind: &str, opts: Option<&Value>) -> Result { + let k = parse_kind(kind)?; + let mut choice = PreloginChoice::new(k); + if k == Kind::I2p { + let port = match opts.and_then(|o| o.get("sam_port")).filter(|v| !v.is_null()) { + Some(v) => Some(i2p_config::validate_port(v.as_i64().unwrap_or(0))?), + None => remembered_opts(k) + .and_then(|o| o.get("sam_port").and_then(Value::as_i64)) + .and_then(|p| i2p_config::validate_port(p).ok()), + }; + if let Some(p) = port { + choice.opts = serde_json::json!({ "sam_port": p }); + } + let given = opts.filter(|o| o.get("sam_user").is_some() || o.get("sam_password").is_some()); + choice.auth = match given { + Some(o) => { + let text = |key: &str| o.get(key).and_then(Value::as_str); + i2p_config::validate_sam_auth(text("sam_user"), text("sam_password"))? + .map(|(user, password)| prelogin::Credentials { user, password: password.into() }) + } + // Left out: the ones given before, for the same router only. + None => prelogin::armed() + .filter(|c| c.kind == k && c.opts.get("sam_port").and_then(Value::as_u64) == port.map(u64::from)) + .and_then(|c| c.auth), + }; + } + Ok(choice) +} + +/// Add Profile's choice: the account being left lends its SAM login to a new account on the same +/// router, unless the choice brings its own. +pub fn add_account_choice(kind: &str, opts: Option<&Value>) -> Result { + let brings_own = opts.is_some_and(|o| o.get("sam_user").is_some() || o.get("sam_password").is_some()); + if Kind::parse(kind) != Some(Kind::I2p) || brings_own { + return prelogin_choice(kind, opts); + } + let saved = prelogin::config_for(Kind::I2p); + let Some(cfg) = saved.downcast_ref::() else { return prelogin_choice(kind, opts) }; + let (Some(user), Some(password)) = (cfg.sam_user.as_ref(), cfg.sam_password.as_ref()) else { return prelogin_choice(kind, opts) }; + let chosen = opts.and_then(|o| o.get("sam_port")).and_then(Value::as_u64); + if chosen.is_some_and(|p| p != u64::from(cfg.sam_port)) { + return prelogin_choice(kind, opts); + } + let mut choice = prelogin_choice(kind, Some(&serde_json::json!({ "sam_port": cfg.sam_port })))?; + choice.auth = Some(prelogin::Credentials { user: user.clone(), password: password.clone() }); + Ok(choice) +} + +/// Match the transport to the welcome screen's choice while no account is signed in. +pub async fn apply_prelogin(choice: PreloginChoice) -> Result<(), String> { + // Another network: whatever starts for the last pick stops now, before this queues behind it. + if choice.kind != Kind::Clearnet && prelogin::armed().is_some_and(|a| a.kind != choice.kind) { + prelogin::cancel_start(); + } + // Read before queueing on the lock: a cancel issued while this waits must still count. + let generation = prelogin::generation(); + if choice.kind == Kind::Clearnet { + prelogin::disarm(); + prelogin::cancel_start(); + #[cfg(feature = "tor")] + vector_core::tor::clear_last_bootstrap_error(); + // Leaving takes effect now, never behind a stalled start: with the preference off the + // starting kind nothing can use it, and a censored network must not hold the user here. + transport::set_preference(prelogin::effective(&picked_account_stored())); + match LIFECYCLE.try_lock() { + Ok(_serial) => { + if running_prelogin() { + host::deactivate(true).await; + } + } + // A start in flight stops itself on the moved generation; this clears one that + // landed just before the cancel. + Err(_) => { + vector_core::db::spawn_bound(async { + let _serial = LIFECYCLE.lock().await; + if running_prelogin() && host::active().map(|a| a.kind) != transport::preference() { + host::deactivate(true).await; + } + }); + } + } + return Ok(()); + } + let kind = choice.kind; + prelogin::arm(choice); + let effective = prelogin::effective(&picked_account_stored()); + transport::set_preference(effective); + if effective != Some(kind) { + // The picked account stored another kind: its own starts at unlock. + let _serial = LIFECYCLE.lock().await; + if host::active().is_some_and(|a| a.started_prelogin() && a.kind != effective.unwrap_or(Kind::Clearnet)) { + host::deactivate(true).await; + } + return Ok(()); + } + #[cfg(feature = "tor")] + if kind == Kind::Tor { + // No account yet, so no saved circuit mode: the default. + vector_core::tor::set_multi_circuit(true); + } + let _serial = LIFECYCLE.lock().await; + if prelogin::generation() != generation { + return Ok(()); + } + if running_compatible(kind) { + return Ok(()); + } + let owner = vector_core::db::live_session_id(); + if host::active().is_some() { + host::deactivate(true).await; + } + start_kind(kind, Some(generation), owner).await?; + Ok(()) +} + +/// The welcome screen's choice: remembered for the install unless `remember` is false (Add +/// Profile keeps its own), then applied. +pub async fn set_prelogin(kind: &str, remember: Option, opts: Option<&Value>) -> Result<(), String> { + if account_booted() { + return Err(crate::t::routing_change_before_login().into()); + } + if vector_core::signer::pairing_pending() { + return Err(crate::t::routing_finish_signer().into()); + } + let choice = prelogin_choice(kind, opts)?; + if remember != Some(false) { + prelogin::set_marker(Some(&choice))?; + } + let applied = apply_prelogin(choice).await; + emit_view(); + applied +} + +/// Leaving Add Profile after its commit: the account being returned to keeps its own choice. +pub async fn prelogin_abandon() { + prelogin::disarm(); + stop_prelogin_service().await; +} + +/// The live network state. Cheap; safe to poll. +pub fn transport_get_state() -> TransportStateView { + view() +} + +/// Switch the live account's network. Tor awaits its bootstrap; other kinds return once started. +pub async fn transport_set(kind: String, keep_realtime: Option) -> Result { + vector_core::db::scoped_result(set_kind(kind, keep_realtime)).await +} + +async fn set_kind(kind: String, keep_realtime: Option) -> Result { + let k = parse_kind(&kind)?; + let _serial = LIFECYCLE.lock().await; + ensure_live()?; + if status::call_active() { + return Err(crate::t::routing_end_call().into()); + } + let live = vector_core::db::live_session_id(); + let current = transport::preference(); + if current == Some(k) && (k == Kind::Clearnet || host::active().is_some_and(|a| a.kind == k && a.owner() == live)) { + return Ok(view()); + } + + if k == Kind::Clearnet { + // Loosening: nothing changes unless the choice is saved, and the old kind stops before + // anything may go direct. + transport::prefs::persist_kind(Kind::Clearnet)?; + stop_active().await; + // The preference below is the live session's: never another account's. + ensure_live()?; + #[cfg(feature = "tor")] + vector_core::tor::clear_last_bootstrap_error(); + transport::set_preference(Some(Kind::Clearnet)); + transport::cycle::cycle_all(transport::cycle::CycleScope::Switch).await; + transport::cycle::cycle_all(transport::cycle::CycleScope::Kick).await; + emit_view(); + return Ok(view()); + } + + // Tightening: refuse in memory before anything slow, so no socket outlives the decision. + transport::set_preference(Some(k)); + // NIP-46 clients dial outside the guarded sockets the bump just closed: shut them before + // anything below can sign. + vector_core::signer::suspend_bunker().await; + let saved = transport::prefs::persist_kind(k); + if keep_realtime != Some(true) { + vector_media::miniapps::apps().realtime.end_all_for_switch().await; + } + transport::cycle::cycle_all(transport::cycle::CycleScope::Switch).await; + stop_active().await; + let started = start_kind(k, None, live).await; + emit_view(); + started?; + saved.map_err(|_| crate::t::routing_save_failed().to_string())?; + Ok(view()) +} + +/// The user accepted that calls and multiplayer Mini Apps connect outside the network in use, +/// for this account and network. +pub fn transport_allow_realtime() -> TransportStateView { + transport::realtime::grant(); + view() +} + +/// The welcome screen's network: only before sign-in. I2P takes `{ "sam_port": 7656 }`. +pub async fn transport_set_prelogin(kind: String, remember: Option, mut opts: Option) -> Result { + let set = set_prelogin(&kind, remember, opts.as_ref()).await; + if let Some(o) = opts.as_mut() { + transport::prefs::scrub_json(o); + } + set?; + Ok(view()) +} + +/// Leaving the welcome screen's choice behind (Add Profile backed out after its commit). +pub async fn transport_prelogin_abandon() { + prelogin_abandon().await; +} + +/// Try the chosen network again now. `newIdentity`: unlinkable from here on (I2P: new +/// addresses; Tor: new circuits). +pub async fn transport_retry(new_identity: Option) -> Result { + vector_core::db::scoped_result(retry(new_identity.unwrap_or(false))).await +} + +async fn retry(new_identity: bool) -> Result { + let owner = vector_core::db::current_session_id(); + let welcome = { + let _serial = LIFECYCLE.lock().await; + ensure_live()?; + let Some(k) = transport::preference().filter(|k| *k != Kind::Clearnet) else { return Ok(view()) }; + if !k.compiled() { + return Err(status::not_in_build(k).text); + } + let live = vector_core::db::live_session_id(); + match host::active().filter(|a| a.kind == k && a.owner() == live) { + Some(a) => { + let t = a.transport().clone(); + if !new_identity { + kick(k); + } else if k == Kind::Tor { + t.new_identity().await; + switch_relay_transport().await; + } else { + // spawn-detached: the instance's own router work, on the runtime that owns its sockets; awaited. + let _ = transport::spawn_on(async move { t.new_identity().await }).await; + } + None + } + // Nothing running for the chosen kind (a failed start): start it the way it began. + None => { + let signed_in = vector_core::db::get_current_account().is_ok() && vector_core::state::my_public_key().is_some(); + match prelogin::armed().filter(|c| c.kind == k && !account_booted() && !signed_in) { + Some(choice) => Some(choice), + None => { + stop_active().await; + start_kind(k, None, owner).await?; + None + } + } + } + } + }; + if let Some(choice) = welcome { + apply_prelogin(choice).await?; + } + emit_view(); + Ok(view()) +} + +/// Wake a kind that is waiting between attempts. +fn kick(kind: Kind) { + #[cfg(feature = "i2p")] + if kind == Kind::I2p { + if let Some(t) = vector_core::i2p::active() { + t.retry_now(); + } + } + #[cfg(not(feature = "i2p"))] + let _ = kind; +} + +/// How each URL is reached on the live account's network right now. +pub fn transport_get_routes(urls: Vec) -> Vec { + urls.iter().take(MAX_ROUTES).map(|u| transport::route_view(u)).collect() +} + +/// Every server the account gave an address on another network. +pub fn transport_get_aliases() -> Vec { + aliases::table().entries() +} + +/// Set (or with no address, remove) a server's address on `kind`. A new I2P address is checked +/// as soon as I2P is up. +pub async fn transport_set_alias(host: String, kind: String, address: Option) -> Result, String> { + vector_core::db::scoped_result(set_alias(host, kind, address)).await +} + +async fn set_alias(host: String, kind: String, address: Option) -> Result, String> { + let k = Kind::parse(&kind).ok_or_else(|| format!("Unknown network: {kind}"))?; // i18n-exempt: developer error + let address = address.as_deref().map(str::trim).filter(|a| !a.is_empty()).map(str::to_string); + let entry = { + let _serial = LIFECYCLE.lock().await; + ensure_live()?; + aliases::set(&host, k, address.as_deref(), AliasSource::User)? + }; + #[cfg(any(feature = "tor", feature = "i2p"))] + if entry.is_some() { + vector_core::transport::twins::check_pending(); + } + emit_view(); + revive_relays(); + Ok(entry) +} + +/// Check a server's address on the network in use now: a TLS handshake for its own name through it. +pub async fn transport_check_alias(host: String) -> Result { + vector_core::db::scoped_result(check_alias(host)).await +} + +async fn check_alias(host: String) -> Result { + ensure_live()?; + #[cfg(any(feature = "tor", feature = "i2p"))] + { + let session = vector_core::db::current_session(); + // spawn-detached: pinned to the caller's account by with_session and awaited; runs where the network's sockets live. + let checked = transport::spawn_on(vector_core::db::with_session(session, async move { + vector_core::transport::twins::check_alias(&host).await + })) + .await + .map_err(|e| e.to_string())?; + emit_view(); + checked + } + #[cfg(not(any(feature = "tor", feature = "i2p")))] + { + let _ = host; + Err(crate::t::routing_alias_needs_network().into()) + } +} + +/// Ask one of the user's own relays for its address on the network in use (NIP-11), then check +/// it. Nothing is saved: the user decides. +pub async fn transport_find_alias(url: String) -> Result { + vector_core::db::scoped_result(find_alias(url)).await +} + +async fn find_alias(url: String) -> Result { + ensure_live()?; + if !super::network::is_own_relay(&url) { + return Err(crate::t::routing_alias_own_relays().into()); + } + #[cfg(any(feature = "tor", feature = "i2p"))] + { + let session = vector_core::db::current_session(); + // spawn-detached: pinned to the caller's account by with_session and awaited; runs where the network's sockets live. + let found = transport::spawn_on(vector_core::db::with_session(session, async move { + vector_core::transport::twins::find_alias(&url).await + })) + .await + .map_err(|e| e.to_string())??; + serde_json::to_value(found).map_err(|e| e.to_string()) + } + #[cfg(not(any(feature = "tor", feature = "i2p")))] + { + let _ = url; + Err(crate::t::routing_alias_needs_network().into()) + } +} + +/// Save the I2P router's port and credentials, then move a running I2P onto that router. +/// `auth`: `None` keeps the saved credentials, `Some(None)` clears them. +pub(crate) async fn set_i2p_router(port: i64, auth: Option>) -> Result { + let _serial = LIFECYCLE.lock().await; + ensure_live()?; + i2p_config::set_router(port, auth)?; + let restarted = restart_if_incompatible(Kind::I2p).await; + emit_view(); + restarted?; + Ok(view()) +} + +/// Use Vector's own Tor or one already running here (`port` None finds it); a running Tor moves +/// onto the chosen engine. +#[cfg(feature = "tor")] +pub(crate) async fn set_tor_engine(external: bool, port: Option) -> Result { + let _serial = LIFECYCLE.lock().await; + ensure_live()?; + transport::tor_config::set(external, port)?; + let restarted = restart_if_incompatible(Kind::Tor).await; + emit_view(); + restarted?; + Ok(view()) +} + +/// Under the lifecycle lock: a running instance of the live account's `kind` that no longer +/// serves its config is replaced. +async fn restart_if_incompatible(kind: Kind) -> Result<(), String> { + if transport::preference() != Some(kind) || running_compatible(kind) { + return Ok(()); + } + let live = vector_core::db::live_session_id(); + if !host::active().is_some_and(|a| a.kind == kind && a.owner() == live) { + return Ok(()); + } + stop_active().await; + start_kind(kind, None, live).await.map(|_| ()) +} + +/// I2P-Only on (`Off`) or off (`Allow`). Turning it on cuts every outproxy connection first. +pub(crate) async fn set_i2p_exit(mode: transport::ExitPolicy) -> Result { + let saved = { + let _serial = LIFECYCLE.lock().await; + ensure_live()?; + i2p_config::set_exit(mode) + }; + emit_view(); + saved?; + if mode == transport::ExitPolicy::Allow { + revive_relays(); + } + Ok(view()) +} + +/// Save the outproxy list (`None` restores the built-in one). Removing or turning one off cuts +/// its connections first. +pub(crate) async fn set_i2p_outproxies(list: Option>) -> Result { + let saved = { + let _serial = LIFECYCLE.lock().await; + ensure_live()?; + i2p_config::set_outproxies(list) + }; + emit_view(); + if saved.is_ok() { + revive_relays(); + } + saved +} + +/// A routing change may have opened relays the old rules refused, which no revival pass tries +/// while refused: kick them now, off the lock. +fn revive_relays() { + if matches!(transport::state(), transport::TransportState::Active { .. }) { + // spawn-detached: revives the live session's relays; reads no other account state. + tauri::async_runtime::spawn(transport::cycle::cycle_all(transport::cycle::CycleScope::Kick)); + } +} + +/// Revive relays whenever the live account's network becomes usable: its instance reports ready, +/// or a blocked account lands on Clearnet (its network loaded after a client was built). Runs on +/// the app's runtime: relay tasks are spawned on the runtime that connects them. +pub fn spawn_ready_listener() { + fn usable() -> bool { + matches!(transport::state(), transport::TransportState::Clearnet | transport::TransportState::Active { .. }) + } + // spawn-detached: process-lifetime listener; each event is checked against the live session. + tauri::async_runtime::spawn(async { + let mut rx = host::subscribe(); + let mut was_usable = usable(); + loop { + let kick = match rx.recv().await { + Ok(host::TransportEvent::Ready { instance, owner, .. }) => { + host::active().is_some_and(|a| a.id() == instance) && owner == vector_core::db::live_session_id() + } + Ok(_) => usable() && !was_usable, + Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => usable() && !was_usable, + Err(tokio::sync::broadcast::error::RecvError::Closed) => return, + }; + was_usable = usable(); + if kick { + // spawn-detached: revives the live session's relays; reads no other account state. + tauri::async_runtime::spawn(transport::cycle::cycle_all(transport::cycle::CycleScope::Kick)); + } + } + }); +} + +// Tor's own settings. + +use serde::Serialize; + +/// State surfaced to the frontend for the Tor toggle UI. +#[derive(Debug, Serialize)] +pub struct TorState { + /// Whether the live account's network is Tor. May not match `running` until bootstrap + /// completes or fails. + pub enabled: bool, + /// Is Tor the installed, connected network? + pub running: bool, + /// Whether the Vector build was compiled with Tor support at all. + pub supported: bool, + /// Human-readable status. "disabled" / "bootstrapping NN%" / "connected" / + /// "failed: ". Empty string when nothing meaningful to show. + pub status: String, + /// Bootstrap progress 0..=100. Live values from Arti's bootstrap_events() + /// stream while bootstrap is running. 100 once running. The frontend + /// drives the comet-trail radial progress bar from this. + pub bootstrap_progress: u8, + /// The welcome screen's Tor choice (install-wide), which the next account inherits. + pub prelogin: bool, + /// Each host on its own circuit (default), or one shared circuit. + pub multi_circuit: bool, + /// For display only: the bridge address, which needs credentials. + pub socks_proxy: Option, +} + +/// Read the user's saved bridge lines (newline-separated). Returns an empty +/// Vec when bridges aren't enabled, or when the setting is missing/empty. +/// +/// Resilience: if any saved line is an obfs4 line but `obfs4proxy` is no +/// longer installed (user uninstalled it between sessions), auto-flip the +/// `tor_bridges_enabled` SQLite flag to false and return an empty Vec. +/// That way Tor still starts (direct, no bridges) and the user isn't stuck +/// in a "Starting…" failsafe state on the next launch. The bridge +/// LINES are preserved so they can re-enable them after reinstalling. +#[cfg(feature = "tor")] +pub(crate) fn read_saved_bridges() -> Vec { + let enabled = matches!( + vector_core::db::settings::get_sql_setting("tor_bridges_enabled".to_string()), + Ok(Some(ref v)) if v == "1" || v == "true" + ); + if !enabled { + return Vec::new(); + } + let lines: Vec = match vector_core::db::settings::get_sql_setting("tor_bridges".to_string()) { + Ok(Some(blob)) => blob + .lines() + .map(|l| l.trim().to_string()) + .filter(|l| !l.is_empty()) + .collect(), + _ => Vec::new(), + }; + + let needs_obfs4 = lines.iter().any(|l| l.to_ascii_lowercase().starts_with("obfs4 ")); // i18n-exempt: bridge line syntax + if needs_obfs4 && vector_core::tor::resolve_obfs4proxy().is_none() { + vector_core::log_warn!("[Tor] obfs4 bridges configured but obfs4proxy not found — auto-disabling bridges; falling back to direct Tor."); + // Persist the disable so the bridges UI agrees on next read. + let _ = vector_core::db::settings::set_sql_setting( + "tor_bridges_enabled".to_string(), + "0".to_string(), + ); + return Vec::new(); + } + + lines +} + +/// The account's own Tor directories, seeding an empty cache from the install-level one. +#[cfg(feature = "tor")] +pub(crate) async fn tor_data_dirs() -> Result<(std::path::PathBuf, std::path::PathBuf), String> { + let account = vector_core::db::get_current_account()?; + let base = vector_core::db::account_dir(&account)?.join("tor"); + let state = base.join("state"); + let cache = base.join("cache"); + std::fs::create_dir_all(&state).map_err(|e| format!("create state dir: {e}"))?; // i18n-exempt: developer error + std::fs::create_dir_all(&cache).map_err(|e| format!("create cache dir: {e}"))?; // i18n-exempt: developer error + // Never while a service may still be writing the install cache; the copy is MBs of disk I/O. + if !vector_core::tor::is_active() && !vector_core::tor::is_bootstrapping() && !running_prelogin() { + let dst = cache.clone(); + let _ = tokio::task::spawn_blocking(move || vector_core::tor::seed_cache_from_prelogin(&dst)).await; + } + Ok((state, cache)) +} + +/// The welcome screen's Tor switch: remember the choice for this install and bring the +/// transport in line. Only while no account is signed in. +pub async fn tor_set_prelogin(enabled: bool, remember: Option) -> Result { + if account_booted() { + return Err(crate::t::routing_tor_before_login().to_string()); + } + #[cfg(feature = "tor")] + { + use vector_core::transport::prelogin; + let marker_is_tor = matches!(prelogin::marker(), Ok(Some(ref c)) if c.kind == Kind::Tor); + let armed_is_tor = prelogin::armed().is_some_and(|c| c.kind == Kind::Tor); + // Off turns off only Tor: a welcome screen set to another network keeps it. + if enabled { + set_prelogin(Kind::Tor.as_str(), remember, None).await?; + } else if marker_is_tor || armed_is_tor { + let remember = if marker_is_tor { remember } else { Some(false) }; + set_prelogin(Kind::Clearnet.as_str(), remember, None).await?; + } + } + #[cfg(not(feature = "tor"))] + { + let _ = remember; + if enabled { + return Err("This Vector build was compiled without the `tor` feature.".to_string()) // i18n-exempt: developer build; + } + } + Ok(tor_get_state()) +} + +/// Leaving Add Profile after its commit: the account being returned to keeps its own choice. +pub async fn tor_prelogin_abandon() { + prelogin_abandon().await; +} + +#[cfg(feature = "tor")] +fn current_status_string() -> String { + use vector_core::tor::TorStatus; + // While the instance is bootstrapping nothing is installed yet: the flag covers that gap so + // the UI renders "bootstrapping" instead of falling back to "disabled". + if vector_core::tor::is_bootstrapping() { + return format!("bootstrapping {}%", vector_core::tor::bootstrap_progress()); // i18n-exempt: status protocol + } + if let Some(t) = vector_core::tor::external::active() { + use vector_core::transport::Transport; + return if t.ready() { "connected".into() } else { "waiting for Tor".into() }; // i18n-exempt: status protocol + } + match vector_core::tor::current().map(|s| s.status()) { + // Nothing installed: never started, or the last start failed. Surface the failure so + // the toggle unlocks instead of looping on "Starting…". + None => match vector_core::tor::last_bootstrap_error() { + Some(e) => format!("failed: {e}"), // i18n-exempt: status protocol + None => "disabled".to_string(), + }, + Some(TorStatus::Disabled) => "disabled".to_string(), + Some(TorStatus::Bootstrapping(p)) => format!("bootstrapping {p}%"), // i18n-exempt: status protocol + Some(TorStatus::Connected) => "connected".to_string(), + Some(TorStatus::Failed(e)) => format!("failed: {e}"), // i18n-exempt: status protocol + } +} + +#[cfg(not(feature = "tor"))] +fn current_status_string() -> String { + "disabled".to_string() +} + +/// One circuit hop, surfaced to the frontend's Advanced panel. Mirrors +/// `vector_core::tor::CircuitHop` so the bare (no-`tor`-feature) build can +/// still expose the type without dragging the whole arti dep tree along. +#[derive(Debug, Serialize)] +pub struct CircuitHopOut { + pub position: String, + pub address: String, + pub fingerprint: String, + pub is_bridge: bool, +} + +/// Result of checking whether the obfs4 pluggable transport binary is +/// available on the system. Frontend uses this to show inline install +/// guidance when the user is configuring obfs4 bridges. +#[derive(Debug, Serialize)] +pub struct Obfs4ProxyStatus { + /// `true` if `obfs4proxy` (or `lyrebird`) was found on this system. + pub installed: bool, + /// Resolved path when installed. + pub path: Option, +} + +/// Detect whether `obfs4proxy` is installed and reachable. Cheap (no spawn, +/// just file-existence checks against PATH + common install dirs). +pub fn tor_check_obfs4_proxy() -> Obfs4ProxyStatus { + #[cfg(feature = "tor")] + { + match vector_core::tor::resolve_obfs4proxy() { + Some(p) => Obfs4ProxyStatus { + installed: true, + path: Some(p.to_string_lossy().to_string()), + }, + None => Obfs4ProxyStatus { + installed: false, + path: None, + }, + } + } + #[cfg(not(feature = "tor"))] + { + Obfs4ProxyStatus { installed: false, path: None } + } +} + +/// Bridge configuration surfaced to the frontend. +#[derive(Debug, Serialize)] +pub struct BridgesState { + /// Has the user enabled bridges? + pub enabled: bool, + /// Saved bridge lines, newline-separated (textarea content). + pub lines: String, +} + +/// Read the user's bridge configuration. Cheap; safe to call freely. +pub fn tor_get_bridges() -> BridgesState { + let enabled = matches!( + vector_core::db::settings::get_sql_setting("tor_bridges_enabled".to_string()), + Ok(Some(ref v)) if v == "1" || v == "true" + ); + let lines = vector_core::db::settings::get_sql_setting("tor_bridges".to_string()) + .ok() + .flatten() + .unwrap_or_default(); + BridgesState { enabled, lines } +} + +/// Persist a new bridge configuration and, if Tor is currently running, +/// reconfigure the service to pick up the new bridges. The call awaits bootstrap +/// before returning, just like `tor_set_enabled`. Lines are stored verbatim +/// (whitespace preserved per textarea); `read_saved_bridges` trims and skips +/// empty entries at start time. +pub async fn tor_set_bridges(enabled: bool, lines: String) -> Result { + // Pre-validate before mutating SQLite or the running TorClient — if we + // wrote the persisted state first and then errored on reconfigure, the + // saved-vs-runtime state would drift silently. + #[cfg(feature = "tor")] + if enabled { + let any_obfs4 = lines + .lines() + .any(|l| l.trim().to_ascii_lowercase().starts_with("obfs4 ")); // i18n-exempt: bridge line syntax + if any_obfs4 && vector_core::tor::resolve_obfs4proxy().is_none() { + return Err(vector_core::tor::obfs4proxy_missing_error()); + } + } + + vector_core::db::settings::set_sql_setting( + "tor_bridges_enabled".to_string(), + if enabled { "1" } else { "0" }.to_string(), + )?; + vector_core::db::settings::set_sql_setting( + "tor_bridges".to_string(), + lines.clone(), + )?; + + #[cfg(feature = "tor")] + { + // The welcome screen's service runs on install-level dirs: move to the account's own. + if running_prelogin() && vector_core::tor::is_active() { + stop_prelogin_service().await; + return tor_set_enabled(true).await.map(|_| tor_get_bridges()); + } + // Reconfigure the live TorClient in place: it keeps its already-acquired state-dir lock, + // which a stop+start would contend for. Relay sockets then cycle onto the new guard. + if let Some(svc) = vector_core::tor::current() { + let (state_dir, cache_dir) = tor_data_dirs().await?; + let bridges = read_saved_bridges(); + svc.reconfigure_bridges(state_dir, cache_dir, &bridges).await?; + switch_relay_transport().await; + } + } + + Ok(tor_get_bridges()) +} + +/// Return the current circuit's hop list. Used by the Settings "Advanced" +/// panel to show a Tor Browser–style circuit display. +/// +/// `force_new = false`: returns whatever circuit Vector's traffic is +/// currently on (near-instant; uses the active isolation token). +/// `force_new = true`: rotates the global isolation token, builds the +/// matching new circuit, then cycles every relay socket so existing +/// connections drop and re-establish through the new path. End result: +/// the displayed hops are exactly the path your relays + HTTP traffic +/// are now riding. +pub async fn tor_get_circuits(force_new: Option) -> Result { + let force_new = force_new.unwrap_or(false); + #[cfg(feature = "tor")] + { + if force_new { + // Every token rotates, then every relay socket reconnects onto a fresh circuit. + vector_core::tor::rotate_circuits(); + switch_relay_transport().await; + } + // A running Tor builds its own circuits: rotating is all Vector does with them. + if vector_core::tor::external::active().is_some() { + return Ok(CircuitOut { host: None, hops: Vec::new(), circuits: 0, hosts: 0 }); + } + let (circuits, hosts) = vector_core::tor::active_circuits(); + // Multi-circuit has no one circuit to show: the count is the view, and it builds nothing. + if vector_core::tor::multi_circuit() { + return Ok(CircuitOut { host: None, hops: Vec::new(), circuits, hosts }); + } + // Hard cap so the UI can't get stuck on "Building circuit…" if Arti + // can't find an exit (consensus stale, all candidate exits down, etc.). + let (host, hops) = tokio::time::timeout( + std::time::Duration::from_secs(20), + vector_core::tor::current_circuit_hops(), + ) + .await + .map_err(|_| crate::t::routing_circuit_timeout().to_string())??; + Ok(CircuitOut { host, hops: hops.into_iter().map(hop_out).collect(), circuits, hosts }) + } + #[cfg(not(feature = "tor"))] + { + let _ = force_new; + Err("This Vector build was compiled without the `tor` feature.".to_string()) // i18n-exempt: developer build + } +} + +/// The circuit view: in single-circuit mode its hops and the host that last rode it (None before +/// any traffic); in both modes how many circuits are open and how many hosts they serve. +#[derive(Debug, Serialize)] +pub struct CircuitOut { + pub host: Option, + pub hops: Vec, + pub circuits: usize, + pub hosts: usize, +} + +#[cfg(feature = "tor")] +fn hop_out(h: vector_core::tor::CircuitHop) -> CircuitHopOut { + CircuitHopOut { position: h.position, address: h.address, fingerprint: h.fingerprint, is_bridge: h.is_bridge } +} + +/// The circuit one relay or server is on, for its info dialog: present only while Tor carries +/// traffic to it and that circuit is still open. +pub fn tor_get_host_circuit(url: String) -> Result>, String> { + #[cfg(feature = "tor")] + { + if !vector_core::tor::is_active() { + return Ok(None); + } + let Some(host) = url::Url::parse(&url).ok().and_then(|u| u.host_str().map(str::to_string)) else { + return Ok(None); + }; + match vector_core::tor::host_circuit_hops(&host) { + Some(hops) => Ok(Some(hops?.into_iter().map(hop_out).collect())), + None => Ok(None), + } + } + #[cfg(not(feature = "tor"))] + { + let _ = url; + Ok(None) + } +} + +/// Multi-circuit (each host on its own circuit) or one shared circuit. Live streams move at once: +/// every token rotates and every relay socket reconnects. +pub async fn tor_set_multi_circuit(enabled: bool) -> Result { + vector_core::db::settings::set_sql_setting( + "tor_multi_circuit".to_string(), + if enabled { "1" } else { "0" }.to_string(), + )?; + #[cfg(feature = "tor")] + { + vector_core::tor::set_multi_circuit(enabled); + vector_core::tor::rotate_circuits(); + if vector_core::tor::is_active() { + switch_relay_transport().await; + } + } + Ok(tor_get_state()) +} + +/// Which Tor engine the account uses, and where a running Tor was found. +#[derive(Debug, Serialize)] +pub struct TorEngineView { + /// A Tor already running here rather than Vector's own. + pub external: bool, + /// The port the user fixed; `None` finds it. + pub port: Option, + /// Where a running Tor answers now, if anywhere. + pub found: Option, +} + +/// The engine setting, and a look for a running Tor on the ports it would use. +pub async fn tor_get_engine() -> TorEngineView { + let cfg = vector_core::transport::tor_config::current(); + #[cfg(feature = "tor")] + let found = match vector_core::tor::external::active().and_then(|t| t.port()) { + Some(p) => Some(p), + None => { + let ports = cfg.ports(); + // spawn-detached: two loopback probes on the runtime that owns transport sockets; awaited. + vector_core::transport::spawn_on(async move { vector_core::tor::external::detect(&ports).await }).await.ok().flatten() + } + }; + #[cfg(not(feature = "tor"))] + let found = None; + TorEngineView { external: cfg.external, port: cfg.port, found } +} + +/// Use a Tor already running here (`port` 0 or absent finds it) or Vector's own. +pub async fn tor_set_engine(external: bool, port: Option) -> Result { + let port = match port { + None | Some(0) => None, + Some(p) => Some(vector_core::transport::i2p_config::validate_port(p)?), + }; + #[cfg(feature = "tor")] + { + vector_core::db::scoped_result(set_tor_engine(external, port)).await?; + Ok(tor_get_engine().await) + } + #[cfg(not(feature = "tor"))] + { + let _ = (external, port); + Err(vector_core::transport::status::not_in_build(Kind::Tor).text) + } +} + +/// Read the current Tor state. Cheap, safe to poll from the UI. +pub fn tor_get_state() -> TorState { + let enabled = vector_core::transport::preference() == Some(Kind::Tor); + let running = { + #[cfg(feature = "tor")] + { vector_core::tor::is_active() } + #[cfg(not(feature = "tor"))] + { false } + }; + let supported = cfg!(feature = "tor"); + let bootstrap_progress = { + #[cfg(feature = "tor")] + { if running { 100 } else { vector_core::tor::bootstrap_progress() } } + #[cfg(not(feature = "tor"))] + { 0u8 } + }; + let socks_proxy = { + #[cfg(feature = "tor")] + { vector_core::tor::proxy_url() } + #[cfg(not(feature = "tor"))] + { None } + }; + let prelogin = { + #[cfg(feature = "tor")] + { vector_core::tor::prelogin_preference() } + #[cfg(not(feature = "tor"))] + { false } + }; + let multi_circuit = { + #[cfg(feature = "tor")] + { vector_core::tor::multi_circuit() } + #[cfg(not(feature = "tor"))] + { true } + }; + TorState { + enabled, + prelogin, + multi_circuit, + running, + supported, + status: current_status_string(), + bootstrap_progress, + socks_proxy, + } +} + +/// The legacy Tor toggle. On switches the account to Tor; off returns to Clearnet only when +/// Tor is the account's network, so it never turns another network off. Mini App sessions are +/// kept, as this toggle always did. +pub async fn tor_set_enabled(enabled: bool) -> Result { + #[cfg(feature = "tor")] + { + if enabled { + transport_set("tor".into(), Some(true)).await?; + } else if vector_core::transport::preference() == Some(Kind::Tor) { + transport_set("clearnet".into(), Some(true)).await?; + } + } + #[cfg(not(feature = "tor"))] + { + if enabled { + // i18n-exempt: developer build + return Err("This Vector build was compiled without the `tor` feature. Re-build with `--features tor` to enable Tor support.".to_string()); + } + } + Ok(tor_get_state()) +} + +// I2P's own settings. + +use vector_core::transport::i2p_config::{I2pConfigView, OutproxyInput}; +use vector_core::transport::ExitPolicy; + +/// What the router test reports: a HELLO, no session. +#[derive(Clone, Debug, PartialEq, Eq, Serialize)] +pub struct RouterTestView { + pub ok: bool, + pub version: Option, + pub text: String, +} + +/// The I2P settings in effect: the account's, or on the welcome screen the router it picked. The +/// SAM password never leaves core. +pub fn i2p_get_config() -> I2pConfigView { + let cfg = vector_core::transport::prelogin::config_for(vector_core::transport::Kind::I2p); + i2p_config::view_of(&cfg.downcast_ref::().cloned().unwrap_or_default()) +} + +/// Save the router's port and SAM credentials (`None` keeps the saved ones, `Some(None)` clears +/// them); a running I2P moves onto that router. +pub async fn i2p_set_router(port: i64, auth: Option>) -> Result { + vector_core::db::scoped_result(set_i2p_router(port, auth)).await +} + +/// Ask whatever answers on `port` for a SAM HELLO. Without credentials given, the saved ones, +/// but only for the saved router's port: they never go to whatever else listens. +pub async fn i2p_test_router(port: i64, user: Option, password: Option) -> Result { + let port = i2p_config::validate_port(port)?; + let given = i2p_config::validate_sam_auth(user.as_deref(), password.as_deref())?; + #[cfg(feature = "i2p")] + { + let auth = match given { + Some((u, p)) => Some(vector_core::i2p::sam::SamAuth::new(&u, &zeroize::Zeroizing::new(p))), + None => saved_auth_for(port), + }; + // spawn-detached: one loopback HELLO on the runtime that owns router sockets; awaited. + let r = vector_core::transport::spawn_on(async move { vector_core::i2p::sam::test_router(port, auth.as_ref()).await }) + .await + .map_err(|e| e.to_string())?; + Ok(RouterTestView { ok: r.ok, version: r.version, text: r.text }) + } + #[cfg(not(feature = "i2p"))] + { + let _ = (port, given); + Err(vector_core::transport::status::not_in_build(vector_core::transport::Kind::I2p).text) + } +} + +/// The saved SAM credentials, when `port` is the saved router's. +#[cfg(feature = "i2p")] +fn saved_auth_for(port: u16) -> Option { + let cfg = vector_core::transport::prelogin::config_for(vector_core::transport::Kind::I2p); + let cfg = cfg.downcast_ref::()?; + if cfg.sam_port != port { + return None; + } + match (cfg.sam_user.as_deref(), cfg.sam_password.as_deref()) { + (Some(u), Some(p)) => Some(vector_core::i2p::sam::SamAuth::new(u, p)), + _ => None, + } +} + +/// I2P-Only: `"off"` reaches only I2P servers and the I2P addresses the user added; `"allow"` +/// reaches everything else through the outproxies. +pub async fn i2p_set_exit(mode: String) -> Result { + let mode = match mode.as_str() { + "allow" => ExitPolicy::Allow, + "off" => ExitPolicy::Off, + _ => return Err(format!("Unknown I2P-Only mode: {mode}")), // i18n-exempt: developer error + }; + vector_core::db::scoped_result(set_i2p_exit(mode)).await +} + +/// Save the outproxy list in the order given; `null` restores the built-in list. +pub async fn i2p_set_outproxies(list: Option>) -> Result { + vector_core::db::scoped_result(set_i2p_outproxies(list)).await +} + diff --git a/crates/vector-gpui/src/backend/unfurl.rs b/crates/vector-gpui/src/backend/unfurl.rs new file mode 100644 index 000000000..e19d7d32d --- /dev/null +++ b/crates/vector-gpui/src/backend/unfurl.rs @@ -0,0 +1,359 @@ +//! Link previews (`fetch_msg_metadata`): through the user's Magnitude server when the privacy +//! setting is on; off it, or off Clearnet, the page's `` is read here. + +use serde_json::{Value, json}; +use vector_core::types::SiteMetadata; +use vector_core::{Message, STATE, VectorCore, db, proxy}; + +#[path = "../../../../src-tauri/src/simd/html_meta.rs"] +#[allow(dead_code, unsafe_op_in_unsafe_fn)] +mod html_meta; + +const INVITE_PREFIXES: [&str; 2] = [ + "https://vectorapp.io/invite", + "https://www.vectorapp.io/invite", +]; + +/// Links in the order they start, overlapping ones included, read lazily: a message of +/// nothing but `https://` names one link per byte, each running to its end. +fn https_urls(text: &str) -> impl Iterator { + const DELIMITERS: &[u8] = b" \t\n\r\"<>)]}|"; + let mut from = 0; + std::iter::from_fn(move || loop { + let start = from + text.get(from..)?.find("https://")?; + from = start + 1; + let rest = &text.as_bytes()[start..]; + let mut end = rest + .iter() + .position(|b| DELIMITERS.contains(b)) + .unwrap_or(rest.len()); + while end > 0 && matches!(rest[end - 1], b'.' | b',' | b':' | b';') { + end -= 1; + } + if end > "https://".len() { + return Some(&text[start..start + end]); + } + }) +} + +fn off_clearnet() -> bool { + vector_core::transport::preference() + .is_some_and(|k| k != vector_core::transport::Kind::Clearnet) +} + +async fn site_metadata(url: &str) -> Result { + // A network-native page is reached inside its network; Magnitude could only fail on it. + let native = reqwest::Url::parse(url) + .ok() + .and_then(|u| u.host_str().map(proxy::is_network_native)) + .unwrap_or(false); + if !proxy::enabled() || native { + return fetch_head(url, true).await; + } + match proxy::server_offering(proxy::UNFURL_EXT).await { + Some(server) => unfurl_via(&server, url).await, + // Allowed only because the address is hidden: a switch to Clearnet meanwhile fails it. + None if off_clearnet() => fetch_head(url, false).await, + None => Err("no configured server offers link previews".into()), // i18n-exempt: developer error + } +} + +async fn unfurl_via(server: &str, url: &str) -> Result { + let client = vector_core::net::build_http_client(std::time::Duration::from_secs(20))?; + let endpoint = reqwest::Url::parse_with_params(&format!("{server}/unfurl"), [("url", url)]) + .map_err(|e| e.to_string())?; + let response = client + .get(endpoint) + .send() + .await + .map_err(|e| e.to_string())?; + let status = response.status(); + let body: Value = response.json().await.map_err(|e| e.to_string())?; + if !status.is_success() { + return Err(format!("unfurl refused: {status}")); // i18n-exempt: developer error + } + let proxy_server = proxy::server_offering(proxy::PROXY_EXT).await; + Ok(from_answer(&body, url, proxy_server.as_deref())) +} + +/// Magnitude's answer as the message keeps it; a picture with no proxy to fetch it is dropped. +fn from_answer(body: &Value, asked: &str, proxy_server: Option<&str>) -> SiteMetadata { + let p = body.get("preview").cloned().unwrap_or(Value::Null); + let s = |k: &str| p.get(k).and_then(Value::as_str).map(str::to_string); + let final_url = body + .get("url") + .and_then(Value::as_str) + .unwrap_or(asked) + .to_string(); + let domain = reqwest::Url::parse(&final_url) + .map(|u| format!("{}/", u.origin().ascii_serialization())) + .unwrap_or_else(|_| final_url.clone()); + let via_proxy = |u: Option| -> Option { + let u = u?; + match proxy_server { + Some(srv) if proxy::wants_proxy(&u) => Some(proxy::proxy_url(srv, &u)), + Some(_) => Some(u), + None => None, + } + }; + let image = p + .get("image") + .and_then(|i| i.get("url")) + .and_then(Value::as_str) + .map(str::to_string); + SiteMetadata { + domain, + og_title: s("title"), + og_description: s("description"), + og_image: via_proxy(image), + og_url: s("canonical").or(Some(final_url)), + og_type: s("kind"), + title: s("title"), + description: s("description"), + favicon: via_proxy(s("favicon")), + } +} + +fn client(timeout: u64, direct: bool) -> Result { + let c = vector_core::net::build_http_client(std::time::Duration::from_secs(timeout))?; + Ok(if direct { c } else { c.without_direct() }) +} + +/// http upgraded, protocol- and path-relative resolved against the page's origin. +fn normalize_url(url: &str, domain: &str) -> String { + if url.starts_with("https://") { + url.to_string() + } else if let Some(rest) = url.strip_prefix("http://") { + format!("https://{rest}") + } else if url.starts_with("//") { + format!("https:{url}") + } else { + let base = domain.trim_end_matches('/'); + if url.starts_with('/') { + format!("{base}{url}") + } else { + format!("{base}/{url}") + } + } +} + +async fn fetch_twitter(url: &str, direct: bool) -> Result { + let encoded = url + .replace('&', "%26") + .replace('?', "%3F") + .replace('=', "%3D"); + let response = client(10, direct)? + .get(format!("https://publish.twitter.com/oembed?url={encoded}")) + .send() + .await + .map_err(|e| e.to_string())?; + if !response.status().is_success() { + return Err(format!("oEmbed: {}", response.status())); // i18n-exempt: developer error + } + let data: Value = response.json().await.map_err(|e| e.to_string())?; + let author = data["author_name"].as_str().unwrap_or("Twitter"); // i18n-exempt: stored link preview metadata, as Tauri writes it + let text = html_meta::extract_first_p_inner_html(data["html"].as_str().unwrap_or("")) + .map(|h| h.split("`, read up to its close and no further than 512 KB. +async fn fetch_head(url: &str, direct: bool) -> Result { + vector_core::net::validate_url_not_private(url).map_err(|e| e.to_string())?; + if url.contains("twitter.com") || url.contains("x.com") { + return fetch_twitter(url, direct).await; + } + let domain = match reqwest::Url::parse(url) { + Ok(u) => format!("{}/", u.origin().ascii_serialization()), + Err(_) => format!("{}/", url.trim_end_matches('/')), + }; + const MAX_HEAD: usize = 512 * 1024; + let mut response = client(15, direct)? + .get(url) + .header("Range", "bytes=0-32768") // i18n-exempt: HTTP header + .send() + .await + .map_err(|e| e.to_string())?; + let mut html = Vec::new(); + while let Some(data) = response.chunk().await.map_err(|e| e.to_string())? { + let from = html.len().saturating_sub(6); + html.extend_from_slice(&data); + if let Some(end) = html_meta::find_closing_head(&html, from) { + html.truncate(end); + break; + } + if html.len() >= MAX_HEAD { + html.truncate(MAX_HEAD); + break; + } + } + let html = String::from_utf8_lossy(&html).into_owned(); + let parsed = html_meta::extract_html_meta(&html); + let base = domain.trim_end_matches('/'); + let candidates: Vec<(String, &str)> = parsed + .favicons + .iter() + .map(|f| (normalize_url(&f.href, &domain), f.rel.as_ref())) + .collect(); + let favicon = candidates + .iter() + .find(|(_, rel)| rel.eq_ignore_ascii_case("apple-touch-icon")) + .or_else(|| candidates.iter().find(|(u, _)| u.ends_with(".png"))) + .or_else(|| { + candidates.iter().find(|(_, rel)| { + rel.eq_ignore_ascii_case("icon") || rel.eq_ignore_ascii_case("shortcut icon") // i18n-exempt: HTML attribute value + }) + }) + .map(|(u, _)| u.clone()) + .unwrap_or_else(|| format!("{base}/favicon.ico")); + Ok(SiteMetadata { + domain: domain.clone(), + og_title: parsed.og_title.map(|c| c.into_owned()), + og_description: parsed.og_description.map(|c| c.into_owned()), + og_image: parsed.og_image.map(|u| normalize_url(&u, &domain)), + og_url: parsed + .og_url + .map(|u| normalize_url(&u, &domain)) + .or(Some(url.to_string())), + og_type: parsed.og_type.map(|c| c.into_owned()), + title: parsed.title.map(|c| c.into_owned()), + description: parsed.description.map(|c| c.into_owned()), + favicon: Some(favicon), + }) +} + +/// The first of a message's first three links that has a card, stored on the message. +pub async fn fetch_msg_metadata(chat_id: String, msg_id: String) -> bool { + let Some((_, message)) = VectorCore.get_message(&msg_id).await else { + return false; + }; + let text = vector_core::net::strip_md_link_claims(&message.content); + for url in https_urls(&text).take(3) { + if INVITE_PREFIXES.iter().any(|p| url.starts_with(p)) + || vector_core::golink::is_go_url(url) + { + continue; + } + // A link to a Nostr post, article or video gets its own card from relays. + if vector_core::nostr_embed::EmbedRef::from_url(url).is_some() { + continue; + } + let Ok(metadata) = site_metadata(url).await else { + continue; + }; + let has_content = metadata.og_title.is_some() + || metadata.og_description.is_some() + || metadata.og_image.is_some() + || metadata.title.is_some() + || metadata.description.is_some(); + if !has_content { + continue; + } + let resident = STATE + .lock() + .await + .update_message_in_chat(&chat_id, &msg_id, |m| { + m.set_preview_metadata(Some(metadata.clone())) + }); + let msg = resident.unwrap_or_else(|| Message { + preview_metadata: Some(metadata), + ..message.clone() + }); + vector_core::emit_event( + "message_update", + &json!({ "old_id": msg_id, "message": msg, "chat_id": chat_id }), + ); + let _ = db::events::save_message(&chat_id, &msg).await; + return true; + } + false +} + +#[cfg(test)] +mod tests { + use super::https_urls; + + /// The scan as it was: every link collected before any is used. + fn eager(text: &str) -> Vec { + const DELIMITERS: &[u8] = b" \t\n\r\"<>)]}|"; + let mut urls = Vec::new(); + let mut from = 0; + while let Some(i) = text[from..].find("https://") { + let start = from + i; + let rest = text[start..].as_bytes(); + let mut end = rest.iter().position(|b| DELIMITERS.contains(b)).unwrap_or(rest.len()); + while end > 0 && matches!(rest[end - 1], b'.' | b',' | b':' | b';') { + end -= 1; + } + if end > "https://".len() { + urls.push(text[start..start + end].to_string()); + } + from = start + 1; + } + urls + } + + #[test] + fn lazy_links_are_the_links_found_eagerly() { + const PARTS: &[&str] = &["https://", "http://", "a.io", "/x", " ", "\n", ".", ",", ":", ";", ")", "]", "|", "\"", "<", "é", "日本", "[a](", "https://b.c/https://d.e"]; + let mut seed = 0x9e37_79b9_7f4a_7c15u64; + let mut next = || { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + seed + }; + for _ in 0..20_000 { + let text: String = (0..next() % 24).map(|_| PARTS[(next() % PARTS.len() as u64) as usize]).collect(); + let lazy: Vec<&str> = https_urls(&text).collect(); + assert_eq!(lazy, eager(&text), "{text:?}"); + } + } + + /// The scanner hands out `&str`s cut from bytes unchecked: every cut must land on a character. + #[test] + fn page_heads_of_any_shape_scan_to_whole_characters() { + use super::html_meta::{extract_first_p_inner_html, extract_html_meta}; + const PARTS: &[&str] = &[ + "<", ">", "/", "", "", "", "

", "

", "", " ", "\n", "=", "\"", "'", + "property=", "name=", "content=", "rel=", "href=", "og:title", "og:image", "description", "icon", "apple-touch-icon", + "&", "😀", "😀", "�", "�", "&#x;", "&", ";", "é", "日本語", "😀", "\u{301}", "a", + ]; + let ok = |c: &Option>| c.as_ref().is_none_or(|s| std::str::from_utf8(s.as_bytes()).is_ok()); + let mut seed = 0x2545_f491_4f6c_dd1du64; + let mut next = || { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + seed + }; + for _ in 0..20_000 { + let html: String = (0..next() % 48).map(|_| PARTS[(next() % PARTS.len() as u64) as usize]).collect(); + let m = extract_html_meta(&html); + for f in [&m.og_title, &m.og_description, &m.og_image, &m.og_url, &m.og_type, &m.title, &m.description] { + assert!(ok(f), "{html:?}"); + } + assert!(m.favicons.iter().all(|f| std::str::from_utf8(f.href.as_bytes()).is_ok() && std::str::from_utf8(f.rel.as_bytes()).is_ok()), "{html:?}"); + assert!(ok(&extract_first_p_inner_html(&html)), "{html:?}"); + } + } + + #[test] + fn a_message_of_bare_schemes_reads_only_the_links_it_uses() { + let text = "https://".repeat(20_000); + let t = std::time::Instant::now(); + assert_eq!(https_urls(&text).take(3).count(), 3); + assert!(t.elapsed() < std::time::Duration::from_secs(1), "{:?}", t.elapsed()); + } +} diff --git a/crates/vector-gpui/src/backend/updates.rs b/crates/vector-gpui/src/backend/updates.rs new file mode 100644 index 000000000..485e5dac0 --- /dev/null +++ b/crates/vector-gpui/src/backend/updates.rs @@ -0,0 +1,196 @@ +//! Release checks: the same `latest.json` manifests the Tauri updater reads, fetched over the +//! shared lane. Previews follow `0.4.2-1 < 0.4.2-2 < 0.4.2`, so a preview rides onto its release. + +use std::cmp::Ordering; + +const STABLE_MANIFEST: &str = + "https://github.com/VectorPrivacy/Vector/releases/latest/download/latest.json"; +const PREVIEW_MANIFEST: &str = + "https://github.com/VectorPrivacy/Vector/releases/download/preview/latest.json"; +const MAX_MANIFEST: usize = 1 << 20; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Version { + pub core: [u64; 3], + /// The preview number; `None` is a release. + pub preview: Option, +} + +impl Version { + pub fn parse(s: &str) -> Option { + let s = s.trim().trim_start_matches('v'); + let (core, pre) = match s.split_once('-') { + Some((c, p)) => (c, Some(p.parse().ok()?)), + None => (s, None), + }; + let mut parts = core.split('.').map(|p| p.parse::().ok()); + let core = [parts.next()??, parts.next()??, parts.next()??]; + if parts.next().is_some() { + return None; + } + Some(Self { core, preview: pre }) + } + + pub fn current() -> Self { + Self::parse(env!("CARGO_PKG_VERSION")).unwrap_or(Self { + core: [0, 0, 0], + preview: None, + }) + } + + /// `v0.4.2` or `v0.4.2 Preview 1`: a bare `-1` reads as though it were older. + pub fn display(&self) -> String { + let [a, b, c] = self.core; + match self.preview { + Some(n) => crate::t::version_preview(n, format!("{a}.{b}.{c}")).to_string(), + None => format!("v{a}.{b}.{c}"), + } + } +} + +impl Ord for Version { + fn cmp(&self, other: &Self) -> Ordering { + self.core + .cmp(&other.core) + .then_with(|| match (self.preview, other.preview) { + (None, None) => Ordering::Equal, + (None, Some(_)) => Ordering::Greater, + (Some(_), None) => Ordering::Less, + (Some(a), Some(b)) => a.cmp(&b), + }) + } +} + +impl PartialOrd for Version { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } +} + +pub struct Release { + pub version: Version, + pub notes: String, + /// This build's bundle, when the release ships one and this copy can replace itself. + pub asset: Option, +} + +/// A stable follower never takes a preview, whatever the manifest says. +pub fn newer(latest: Version, current: Version, preview_channel: bool) -> bool { + (preview_channel || latest.preview.is_none()) && latest > current +} + +/// Whether this device follows previews: its own choice, else the channel of the build. +pub fn beta() -> bool { + // A store only ever carries releases. + if super::install::store().is_some() { + return false; + } + match super::device::get("beta_updates").as_deref() { + Some("true") => true, + Some("false") => false, + _ => Version::current().preview.is_some(), + } +} + +pub fn set_beta(on: bool) { + super::device::set("beta_updates", if on { "true" } else { "false" }); +} + +/// The newer release on the followed channel, if there is one. +pub async fn check(preview_channel: bool) -> Result, String> { + let url = if preview_channel { + PREVIEW_MANIFEST + } else { + STABLE_MANIFEST + }; + let client = vector_core::net::shared_http_client(); + let mut resp = client.get(url).send().await.map_err(|e| e.to_string())?; + if !resp.status().is_success() { + return Err(crate::t::settings_update_server_status(resp.status().to_string()).to_string()); + } + let mut body = Vec::new(); + while let Some(chunk) = resp.chunk().await.map_err(|e| e.to_string())? { + if body.len() + chunk.len() > MAX_MANIFEST { + return Err(crate::t::settings_update_manifest_large().into()); + } + body.extend_from_slice(&chunk); + } + let manifest: serde_json::Value = + serde_json::from_slice(&body).map_err(|e| crate::t::settings_update_manifest_invalid(e.to_string()).to_string())?; + let Some(version) = manifest + .get("version") + .and_then(|v| v.as_str()) + .and_then(Version::parse) + else { + return Ok(None); + }; + if !newer(version, Version::current(), preview_channel) { + return Ok(None); + } + let notes = manifest + .get("notes") + .and_then(|v| v.as_str()) + .unwrap_or("") + .trim() + .to_string(); + let asset = super::install::supported().then(|| super::install::asset(&manifest)).flatten(); + Ok(Some(Release { version, notes, asset })) +} + +/// The release's tag: `v0.4.2`, or `v0.4.2-1` for a preview. +fn tag(version: Version) -> String { + let [a, b, c] = version.core; + match version.preview { + Some(n) => format!("v{a}.{b}.{c}-{n}"), + None => format!("v{a}.{b}.{c}"), + } +} + +/// Where a release is installed from when this copy can't update itself. +pub fn release_page(version: Version) -> String { + format!("https://github.com/VectorPrivacy/Vector/releases/tag/{}", tag(version)) +} + +/// One file the release carries. +pub fn release_file(version: Version, name: &str) -> String { + format!("https://github.com/VectorPrivacy/Vector/releases/download/{}/{name}", tag(version)) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn v(s: &str) -> Version { + Version::parse(s).unwrap() + } + + #[test] + fn previews_rank_below_their_release() { + assert!(v("0.4.1") < v("0.4.2-1")); + assert!(v("0.4.2-1") < v("0.4.2-2")); + assert!(v("0.4.2-2") < v("0.4.2")); + assert!(v("0.4.10") > v("0.4.9")); + } + + #[test] + fn stable_never_takes_a_preview() { + assert!(!newer(v("0.5.2-1"), v("0.5.1"), false)); + assert!(newer(v("0.5.2-1"), v("0.5.1"), true)); + assert!(newer(v("0.5.2"), v("0.5.2-3"), false)); + assert!(!newer(v("0.5.1"), v("0.5.1"), true)); + } + + #[test] + fn malformed_versions_never_parse() { + for s in ["", "0.5", "0.5.1.2", "0.5.x", "0.5.1-rc"] { + assert!(Version::parse(s).is_none(), "{s}"); + } + assert_eq!(v("v0.5.1-2").display(), "v0.5.1 Preview 2"); + } + + #[test] + fn release_files_sit_under_their_own_tag() { + assert_eq!(release_file(v("0.6.0"), "a.apk"), "https://github.com/VectorPrivacy/Vector/releases/download/v0.6.0/a.apk"); + assert_eq!(release_page(v("0.6.0-2")), "https://github.com/VectorPrivacy/Vector/releases/tag/v0.6.0-2"); + } +} diff --git a/crates/vector-gpui/src/backend/upload.rs b/crates/vector-gpui/src/backend/upload.rs new file mode 100644 index 000000000..c02836be1 --- /dev/null +++ b/crates/vector-gpui/src/backend/upload.rs @@ -0,0 +1,97 @@ +//! Our own profile pictures: prepared as the desktop client prepares them, then uploaded. + +use std::path::PathBuf; +use std::sync::Arc; + +use vector_core::image_crop::CropRect; + +use crate::shared::image::{UploadImageKind, prepare_upload_image, upload_mime_for}; + +/// Only these upload as a profile picture: the picker can't filter, so a renamed file is caught here. +pub const PICTURE_EXTS: &[&str] = &["png", "jpeg", "jpg", "gif", "webp"]; + +pub fn picture_ext(path: &std::path::Path) -> Option { + let ext = path.extension()?.to_str()?.to_lowercase(); + PICTURE_EXTS.contains(&ext.as_str()).then_some(ext) +} + +/// The picture exactly as it will upload: cropped, shrunk and re-encoded. +pub fn prepared( + bytes: Vec, + banner: bool, + crop: Option, +) -> Result<(Vec, &'static str), String> { + let source = match crop { + Some(c) => crate::crop::crop_drawn(bytes, c)?, + None => bytes, + }; + let kind = if banner { + UploadImageKind::Banner + } else { + UploadImageKind::Avatar + }; + let p = prepare_upload_image(&source, kind)?; + Ok((p.bytes, p.extension)) +} + +/// Upload a picked picture and point our profile at it; the URL it landed at. +pub async fn picture( + path: PathBuf, + banner: bool, + crop: Option, +) -> Result { + let bytes = tokio::fs::read(&path) + .await + .map_err(|_| crate::t::profile_image_load_failed().to_string())?; + picture_ext(&path).ok_or_else(|| crate::t::profile_image_type().to_string())?; + let (bytes, ext) = tokio::task::spawn_blocking(move || prepared(bytes, banner, crop)) + .await + .map_err(|e| e.to_string())??; + let bytes = Arc::new(bytes); + + vector_core::state::nostr_client().ok_or_else(|| crate::t::profile_not_connected().to_string())?; + let signer = + vector_core::signer::active_signer().map_err(|e| crate::t::profile_signer_unavailable(e.to_string()).to_string())?; + let progress: vector_core::blossom::ProgressCallback = Arc::new(|_, _| Ok(())); + let url = vector_core::blossom::upload_blob_with_progress_and_failover( + signer, + vector_core::state::get_blossom_servers(), + bytes.clone(), + Some(upload_mime_for(ext)), + false, + progress, + None, + None, + None, + ) + .await? + .url; + + super::images::precache(&url, &bytes, banner); + if let Some(me) = vector_core::state::my_public_key() + .and_then(|k| nostr_sdk::prelude::ToBech32::to_bech32(&k).ok()) + { + if banner { + super::images::cache_profile_images(&me, "", &url).await; + } else { + super::images::cache_profile_images(&me, &url, "").await; + } + } + let (avatar, banner_url) = if banner { + (String::new(), url.clone()) + } else { + (url.clone(), String::new()) + }; + if !vector_core::profile::sync::update_profile( + String::new(), + avatar, + banner_url, + String::new(), + &super::sync::ProfileHandler, + ) + .await + { + return Err(crate::t::profile_broadcast_failed().into()); + } + Ok(url) +} diff --git a/crates/vector-gpui/src/backend/voice.rs b/crates/vector-gpui/src/backend/voice.rs new file mode 100644 index 000000000..7077d7173 --- /dev/null +++ b/crates/vector-gpui/src/backend/voice.rs @@ -0,0 +1,63 @@ +//! Voice Channel calls, through the core's session: join, leave, who is in each call, and a +//! moderator's directives. + +use nostr_sdk::prelude::*; +use serde_json::Value; +use vector_core::calls::voice; +use vector_core::db; + +/// Join a voice Channel's call, leaving any other. +pub async fn join(community_id: String, channel_id: String) -> Result { + crate::mic_access::ask().await; + let state = db::scoped(async move { voice::join(&community_id, &channel_id).await }).await?; + serde_json::to_value(state).map_err(|e| e.to_string()) +} + +pub async fn leave() { + db::scoped(voice::leave()).await +} + +pub fn state() -> Option { + voice::snapshot().and_then(|s| serde_json::to_value(s).ok()) +} + +pub fn present(channel_id: &str) -> Value { + serde_json::to_value(voice::in_call(channel_id)).unwrap_or_default() +} + +pub fn set_muted(on: bool) -> Result<(), String> { + voice::set_muted(on) +} + +pub fn set_deafened(on: bool) -> Result<(), String> { + voice::set_deafened(on) +} + +pub fn set_volume(npub: &str, volume: f32) -> Result<(), String> { + let pk = PublicKey::from_bech32(npub).map_err(|e| e.to_string())?; + voice::set_peer_volume(&pk, volume) +} + +/// What this account may do to `npub` here: (mute, deafen, move). +pub fn powers(community_id: &str, npub: &str) -> (bool, bool, bool) { + let Ok(pk) = PublicKey::from_bech32(npub) else { return (false, false, false) }; + let p = voice::powers(community_id, &pk); + (p.mute, p.deafen, p.move_) +} + +pub async fn moderate(community_id: String, channel_id: String, npub: String, action: &'static str, to: Option) -> Result<(), String> { + let pk = PublicKey::from_bech32(&npub).map_err(|e| e.to_string())?; + db::scoped(async move { voice::moderate(&community_id, &channel_id, &pk, action, to.as_deref()).await }).await +} + +/// Our camera or screen to the voice call, or stopped. +pub async fn set_video(kind: vector_core::calls::wire::VideoKind, on: bool) -> Result<(), String> { + vector_core::db::scoped(async move { vector_core::calls::voice::set_video(kind, on) }).await +} + +/// Which of a member's pictures this device shows. +pub async fn watch(npub: String, screen: bool, camera: bool) -> Result<(), String> { + let member = nostr_sdk::prelude::PublicKey::parse(&npub).map_err(|e| e.to_string())?; + let want = vector_core::calls::wire::Tracks { camera, screen }; + vector_core::db::scoped(async move { vector_core::calls::voice::watch(&member, want) }).await +} diff --git a/crates/vector-gpui/src/backend/xdcurl.rs b/crates/vector-gpui/src/backend/xdcurl.rs new file mode 100644 index 000000000..045eecfcc --- /dev/null +++ b/crates/vector-gpui/src/backend/xdcurl.rs @@ -0,0 +1,204 @@ +//! A Mini App shared as an `.xdc` link: fetched once on a tap, checked to open, kept by its +//! content hash. Each message stays pinned to the version it first resolved to, so its card, +//! bytes and realtime topic never drift; a newer message revalidates against the server. + +use std::path::PathBuf; + +use serde_json::json; +use vector_core::db::settings::{get_sql_setting, set_sql_setting}; +use vector_media::miniapps::state::MiniAppPackage; +use vector_media::net::{self, ProgressReporter}; + +#[derive(Clone)] +pub struct Resolved { + pub path: PathBuf, + pub topic: String, + pub name: String, +} + +/// The first `.xdc` link in `text`: from an `http` to the next space, quote or angle bracket. +/// One pass, whatever the text repeats. +pub fn find(text: &str) -> Option<&str> { + let ci = |s: &[u8], at: usize, word: &[u8]| s.get(at..at + word.len()).is_some_and(|w| w.eq_ignore_ascii_case(word)); + text.split(|c: char| c.is_whitespace() || matches!(c, '"' | '\'' | '<' | '>')).find_map(|token| { + let b = token.as_bytes(); + // The query or fragment the path at `start` ends at: it only moves on. + let mut query = None; + (0..b.len()).filter(|&i| ci(b, i, b"http")).find_map(|start| { + let q = match query { + Some(q) if q >= start => q, + _ => *query.insert(b[start..].iter().position(|&c| c == b'?' || c == b'#').map_or(b.len(), |i| start + i)), + }; + let path = &b[start..q]; + ((ci(path, 0, b"https://") || ci(path, 0, b"http://")) + && path.len() > "https://.xdc".len() + && ci(path, path.len() - 4, b".xdc")) + .then(|| &token[start..]) + }) + }) +} + +/// The link's file name, for the card before it is fetched. +pub fn file_name(url: &str) -> String { + let raw = url.split(['?', '#']).next().unwrap_or("").rsplit('/').next().filter(|s| !s.is_empty()).unwrap_or("app.xdc"); + url::form_urlencoded::parse(raw.replace('+', "%2B").as_bytes()) + .next() + .map(|(k, _)| k.into_owned()) + .filter(|s| !s.is_empty()) + .unwrap_or_else(|| raw.to_string()) +} + +pub fn host(url: &str) -> String { + url::Url::parse(url).ok().and_then(|u| u.host_str().map(str::to_string)).unwrap_or_default() +} + +struct Progress<'a> { + url: &'a str, +} + +impl ProgressReporter for Progress<'_> { + fn report_progress(&self, pct: Option, _: Option, _: Option) -> Result<(), &'static str> { + vector_core::emit_event("webxdc_url_progress", &json!({ "url": self.url, "progress": pct.unwrap_or(0) })); + Ok(()) + } + + fn report_complete(&self) -> Result<(), &'static str> { + vector_core::emit_event("webxdc_url_progress", &json!({ "url": self.url, "progress": 100 })); + Ok(()) + } +} + +fn hex(bytes: &[u8]) -> String { + vector_core::simd::hex::bytes_to_hex_string(bytes) +} + +/// A latch's hash becomes a path component, so it is checked to be one. +fn read_latch(raw: &str) -> Option<(String, String)> { + let v: serde_json::Value = serde_json::from_str(raw).ok()?; + let hash = v.get("hash")?.as_str()?.to_string(); + let name = v.get("name").and_then(|n| n.as_str()).map(str::to_string).unwrap_or_else(|| crate::t::miniapp_unnamed().to_string()); + (hash.len() == 64 && hash.bytes().all(|b| b.is_ascii_hexdigit())).then_some((hash, name)) +} + +/// ETag, else Last-Modified. None means a re-post cannot prove the cache is current. +async fn validator(url: &str) -> Option { + let client = vector_core::net::build_http_client_with_options(Some(std::time::Duration::from_secs(20)), Some(std::time::Duration::from_secs(10)), true).ok()?; + let res = vector_core::net::proxied_request(&client, reqwest::Method::HEAD, url).await.send().await.ok()?; + let headers = res.headers(); + headers.get("etag").or_else(|| headers.get("last-modified"))?.to_str().ok().map(str::to_string) +} + +/// The package `msg_id`'s link resolved to. Without `download` this only reads what is here. +pub async fn resolve(url: String, msg_id: String, download: bool) -> Result, String> { + vector_core::db::scoped(async move { + let dir = vector_core::db::get_app_data_dir()?.join("miniapps").join("url"); + let url_key = format!("xdcurl:{}", hex(&vector_core::crypto::sha256::digest(url.as_bytes()))); + let msg_key = format!("xdcmsg:{}", hex(&vector_core::crypto::sha256::digest(format!("{url}|{msg_id}").as_bytes()))); + let topic = vector_core::webxdc::derive_url_topic_id(&url, &msg_id); + let found = |hash: &str, name: String| { + let path = dir.join(format!("{hash}.xdc")); + path.exists().then(|| Resolved { path, topic: topic.clone(), name }) + }; + if let Some((hash, name)) = get_sql_setting(msg_key.clone()).ok().flatten().as_deref().and_then(read_latch) + && let Some(done) = found(&hash, name) + { + return Ok(Some(done)); + } + if !download { + return Ok(None); + } + let lower = url.split(['?', '#']).next().unwrap_or("").to_ascii_lowercase(); + if !(lower.starts_with("http://") || lower.starts_with("https://")) || !lower.ends_with(".xdc") { + return Err(crate::t::miniapp_not_a_link().into()); + } + vector_core::net::validate_url_not_private(&url).map_err(|e| e.to_string())?; + let current = validator(&url).await; + // The same link changes between posts while an app is being built: reuse only what the + // server vouches is unchanged. + if let (Some(saved), Some(cur)) = (get_sql_setting(url_key.clone()).ok().flatten(), current.as_deref()) { + let stored = serde_json::from_str::(&saved).ok().and_then(|v| v.get("etag")?.as_str().map(str::to_string)); + if stored.as_deref().is_some_and(|s| !s.is_empty() && s == cur) + && let Some((hash, name)) = read_latch(&saved) + && let Some(done) = found(&hash, name.clone()) + { + let _ = set_sql_setting(msg_key, json!({ "hash": hash, "name": name }).to_string()); + return Ok(Some(done)); + } + } + let bytes = net::download_with_reporter(&url, &Progress { url: &url }, None).await.map_err(str::to_string)?; + let fallback = lower.rsplit('/').next().unwrap_or("app.xdc").to_string(); + // The opener's own gates, before anything is kept: a latch must never pin a package that + // can't open. + let (bytes, manifest) = tokio::task::spawn_blocking(move || { + MiniAppPackage::validate_bytes_openable(&bytes).map_err(|e| e.to_string())?; + let (manifest, _) = MiniAppPackage::load_info_from_bytes(&bytes, &fallback).map_err(|e| e.to_string())?; + Ok::<_, String>((bytes, manifest)) + }) + .await + .map_err(|e| e.to_string())??; + let hash = hex(&vector_core::crypto::sha256::digest(&bytes)); + std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?; + let path = dir.join(format!("{hash}.xdc")); + let tmp = dir.join(format!("{hash}.xdc.tmp-{}", std::process::id())); + std::fs::write(&tmp, &bytes).map_err(|e| e.to_string())?; + std::fs::rename(&tmp, &path).map_err(|e| e.to_string())?; + let name = if manifest.name.is_empty() { lower.rsplit('/').next().unwrap_or("app.xdc").to_string() } else { manifest.name.clone() }; + let _ = set_sql_setting(url_key, json!({ "hash": hash, "name": name, "etag": current.unwrap_or_default() }).to_string()); + let _ = set_sql_setting(msg_key, json!({ "hash": hash, "name": name }).to_string()); + Ok(Some(Resolved { path, topic, name })) + }) + .await +} + +#[cfg(test)] +mod tests { + #[test] + fn finds_the_first_mini_app_link() { + assert_eq!(super::find("try https://x.org/games/chess.xdc now"), Some("https://x.org/games/chess.xdc")); + assert_eq!(super::find("https://x.org/a.xdc?v=2"), Some("https://x.org/a.xdc?v=2")); + assert_eq!(super::find("https://x.org/a.xdcz"), None); + assert_eq!(super::find("no link here.xdc"), None); + assert_eq!(super::file_name("https://x.org/My%20App.xdc#top"), "My App.xdc"); + } + + /// The scan before it was one pass: it rescanned to the next space from every `http`. + fn find_by_rescanning(text: &str) -> Option<&str> { + let lower = text.to_ascii_lowercase(); + let mut from = 0; + while let Some(i) = lower[from..].find("http") { + let start = from + i; + let rest = &text[start..]; + let end = rest.find(|c: char| c.is_whitespace() || matches!(c, '"' | '\'' | '<' | '>')).unwrap_or(rest.len()); + let candidate = &rest[..end]; + let path = candidate.split(['?', '#']).next().unwrap_or("").to_ascii_lowercase(); + if (path.starts_with("https://") || path.starts_with("http://")) && path.ends_with(".xdc") && path.len() > "https://.xdc".len() { + return Some(candidate); + } + from = start + 4; + } + None + } + + #[test] + fn one_pass_finds_what_rescanning_found() { + let parts = ["http", "HTTPS://", "https://", "http://", "x.org/", "a", ".xdc", ".XDC", "?", "#", " ", "\u{a0}", "\"", "<", ">", "'", "東", "é", "xdc", "."]; + let mut seed = 0x9e37_79b9_7f4a_7c15u64; + for _ in 0..40_000 { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + let mut r = seed; + let s: String = (0..(r % 12) as usize) + .map(|_| { + r = r.rotate_left(5) ^ 0x2545_f491_4f6c_dd1d; + parts[(r % parts.len() as u64) as usize] + }) + .collect(); + assert_eq!(super::find(&s), find_by_rescanning(&s), "{s:?}"); + } + let long = "https://".repeat(20_000); + let t = std::time::Instant::now(); + assert_eq!(super::find(&long), None); + assert!(t.elapsed() < std::time::Duration::from_secs(1)); + } +} diff --git a/crates/vector-gpui/src/badge.rs b/crates/vector-gpui/src/badge.rs new file mode 100644 index 000000000..f5e3fcec4 --- /dev/null +++ b/crates/vector-gpui/src/badge.rs @@ -0,0 +1,80 @@ +//! The unread count on the app's icon: the dock badge on macOS, an overlay on the Windows +//! taskbar button, and the Unity launcher count Linux docks and panels read. + +use gpui::Window; + +pub fn set(window: &Window, count: u32) { + platform::set(window, count); +} + +#[cfg(target_os = "macos")] +mod platform { + use objc2::MainThreadMarker; + use objc2_app_kit::NSApplication; + use objc2_foundation::NSString; + + pub fn set(_: &gpui::Window, count: u32) { + let Some(mtm) = MainThreadMarker::new() else { return }; + let label = (count > 0).then(|| NSString::from_str(&count.to_string())); + NSApplication::sharedApplication(mtm).dockTile().setBadgeLabel(label.as_deref()); + } +} + +#[cfg(windows)] +mod platform { + use raw_window_handle::{HasWindowHandle, RawWindowHandle}; + use windows::Win32::Foundation::HWND; + use windows::Win32::System::Com::{CLSCTX_INPROC_SERVER, CoCreateInstance}; + use windows::Win32::UI::Shell::{ITaskbarList3, TaskbarList}; + use windows::Win32::UI::WindowsAndMessaging::{CreateIconFromResourceEx, DestroyIcon, HICON, LR_DEFAULTCOLOR}; + use windows::core::{HSTRING, PCWSTR}; + + const DOT: &[u8] = include_bytes!("../../../src-tauri/icons/icon_badge_notification.png"); + + pub fn set(window: &gpui::Window, count: u32) { + let Ok(handle) = HasWindowHandle::window_handle(window) else { return }; + let RawWindowHandle::Win32(raw) = handle.as_raw() else { return }; + let hwnd = HWND(raw.hwnd.get() as *mut _); + // SAFETY: COM is up on GPUI's thread, and the window outlives the call. + unsafe { + let Ok(list) = CoCreateInstance::<_, ITaskbarList3>(&TaskbarList, None, CLSCTX_INPROC_SERVER) else { return }; + if list.HrInit().is_err() { + return; + } + if count == 0 { + let _ = list.SetOverlayIcon(hwnd, HICON::default(), PCWSTR::null()); + return; + } + let Ok(icon) = CreateIconFromResourceEx(DOT, true, 0x0003_0000, 16, 16, LR_DEFAULTCOLOR) else { return }; + let label = HSTRING::from(&*crate::t::badge_unread()); + let _ = list.SetOverlayIcon(hwnd, icon, PCWSTR(label.as_ptr())); + let _ = DestroyIcon(icon); + } + } +} + +#[cfg(target_os = "linux")] +mod platform { + use gtk::gio; + use gtk::glib::{self, ToVariant}; + + pub fn set(_: &gpui::Window, count: u32) { + let Ok(bus) = gio::bus_get_sync(gio::BusType::Session, gio::Cancellable::NONE) else { return }; + let props = glib::VariantDict::new(None); + props.insert("count", i64::from(count)); + props.insert("count-visible", count > 0); + let args = glib::Variant::tuple_from_iter(["application://Vector.desktop".to_variant(), props.end()]); + let _ = bus.emit_signal( + None, + "/com/canonical/unity/launcherentry/vector", + "com.canonical.Unity.LauncherEntry", + "Update", // i18n-exempt: D-Bus signal name + Some(&args), + ); + } +} + +#[cfg(not(any(target_os = "macos", windows, target_os = "linux")))] +mod platform { + pub fn set(_: &gpui::Window, _: u32) {} +} diff --git a/crates/vector-gpui/src/badgecard.rs b/crates/vector-gpui/src/badgecard.rs new file mode 100644 index 000000000..766825b20 --- /dev/null +++ b/crates/vector-gpui/src/badgecard.rs @@ -0,0 +1,346 @@ +//! The badge card (`ui/BadgeCard.svelte`): a badge, what earned it and what it grants, tilting +//! under the pointer. Depth is parallax: each layer drifts by its height above the card. + +use gpui::prelude::*; +use gpui::{ + AnyElement, App, FontWeight, HighlightStyle, MouseButton, Pixels, Point, SharedString, + StyledText, Window, div, linear_color_stop, linear_gradient, point, px, svg, +}; + +use crate::backend::badges::Badges; +use crate::profile::Badge; +use crate::t; +use crate::theme::*; + +#[derive(Clone, Copy)] +pub enum Run { + Plain, + Bold, + /// The faint italic aside under a description. + Aside, +} + +pub struct Card { + pub svg: SharedString, + pub title: SharedString, + pub subtitle: Option, + /// Paragraphs of runs, each with the space below it. + pub desc: Vec<(Vec<(String, Run)>, f32)>, + /// Bug Hunter's tier rail: the held tier of three. + pub tier: Option, + pub access: SharedString, + /// The pointer over the card, from its centre, each axis in -1..1. + pub tilt: Point, + pub opened: std::time::Instant, +} + +impl Card { + pub fn of(which: Badge, b: Badges) -> Self { + let p = |s: &str| (s.to_string(), Run::Plain); + let (svg, title, subtitle, desc, tier, access): ( + String, + _, + _, + Vec<(Vec<(String, Run)>, f32)>, + _, + _, + ) = match which { + Badge::Inviter => ( + "icons/vector_badge_placeholder.svg".into(), + t::badge_inviter(), + None, + vec![(bold_runs(&t::badge_inviter_text(b.invites)), 0.)], + None, + SharedString::default(), + ), + Badge::Fawkes => ( + "icons/fawkes_mask.svg".into(), + t::badge_fawkes(), + None, + vec![ + (vec![p(&t::badge_fawkes_text())], 21.), + (vec![(t::badge_fawkes_aside().to_string(), Run::Aside)], 0.), + ], + None, + t::badge_full_access(), + ), + Badge::BugHunter => ( + format!("icons/bughunter_{}.svg", b.bug.clamp(1, 3)), + t::badge_bug_hunter(), + Some(t::badge_tier(b.bug).to_string()), + vec![(vec![p(&t::badge_bug_hunter_text())], 0.)], + Some(b.bug), + if b.bug >= 3 { + t::badge_full_access() + } else { + t::badge_partial_access() + }, + ), + Badge::V2026 => ( + "icons/vforvector2026.svg".into(), + t::badge_fawkes(), + Some(t::badge_v2026_edition().to_string()), + vec![ + (vec![p(&t::badge_v2026_text())], 10.), + (vec![p(&t::badge_v2026_quote())], 0.), + ], + None, + t::badge_partial_access(), + ), + }; + Self { + svg: svg.into(), + title, + subtitle, + desc, + tier, + access, + tilt: Point::default(), + opened: std::time::Instant::now(), + } + } +} + +/// A message's `` spans as bold runs, the rest plain. +fn bold_runs(text: &str) -> Vec<(String, Run)> { + let mut runs = Vec::new(); + let mut rest = text; + while let Some(open) = rest.find("") { + let after = &rest[open + 3..]; + let close = after.find("").unwrap_or(after.len()); + if open > 0 { + runs.push((rest[..open].to_string(), Run::Plain)); + } + runs.push((after[..close].to_string(), Run::Bold)); + rest = after.get(close + 4..).unwrap_or(""); + } + if !rest.is_empty() { + runs.push((rest.to_string(), Run::Plain)); + } + runs +} + +fn paragraph(runs: &[(String, Run)]) -> AnyElement { + let mut text = String::new(); + let mut highlights = Vec::new(); + let mut aside = false; + for (t, kind) in runs { + let start = text.len(); + text.push_str(t); + match kind { + Run::Plain => {} + Run::Bold => highlights.push(( + start..text.len(), + HighlightStyle { + font_weight: Some(FontWeight::BOLD), + color: Some(c(0xf6f6f6)), + ..Default::default() + }, + )), + Run::Aside => aside = true, + } + } + let line = div().w_full().text_center(); + if aside { + return line + .text_size(px(13.)) + .italic() + .opacity(0.5) + .child(text) + .into_any_element(); + } + line.child(StyledText::new(text).with_highlights(highlights)) + .into_any_element() +} + +pub enum Ev { + Close, + Pointer(Point), + Leave, +} + +pub fn view( + card: &Card, + window: &Window, + cx: &App, + on: impl Fn(Ev, &mut Window, &mut App) + Clone + 'static, +) -> AnyElement { + // Layer heights above the card (`translateZ`), as drift per unit of tilt. + let drift = |z: f32| point(px(card.tilt.x * z * 0.12), px(card.tilt.y * z * 0.12)); + let shift = |d: gpui::Div, z: f32| { + let o = drift(z); + d.relative().left(o.x).top(o.y) + }; + let t = (card.opened.elapsed().as_secs_f32() / 0.42).min(1.); + let ease = 1. - (1. - t).powi(3); + let tiers = card.tier.map(|held| { + let mut row = div() + .mt(px(18.)) + .flex() + .items_center() + .justify_center() + .gap(px(8.)); + for n in 1..=3u8 { + let filled = n <= held; + row = row.child( + div() + .size(px(40.)) + .flex_shrink_0() + .when(!filled, |d| d.opacity(0.35)) + .child( + crate::kit::sharp_svg(format!("icons/bughunter_{n}.svg"), 40., window, cx) + .grayscale(!filled), + ), + ); + if n < 3 { + row = row.child( + div() + .w(px(20.)) + .h(px(3.)) + .rounded(px(2.)) + .flex_shrink_0() + .bg(if held >= n + 1 { + c(ACCENT) + } else { + white_a(0.15) + }), + ); + } + } + shift(row, 12.) + }); + let access = (!card.access.is_empty()).then(|| { + shift( + div() + .mt(px(20.)) + .flex() + .items_center() + .justify_center() + .gap(px(7.)) + .text_color(c(ACCENT)) + .text_size(px(15.)) + .line_height(px(16.)) + .font_weight(FontWeight::MEDIUM) + .child( + svg() + .path("ui/award.svg") + .size(px(16.)) + .flex_shrink_0() + .text_color(c(ACCENT)), + ) + .child(card.access.clone()), + 14., + ) + }); + let glare = { + // .badge-card-glare: a soft light where the pointer catches the card. + let strength = (card.tilt.x.abs() + card.tilt.y.abs()).min(1.); + div() + .absolute() + .left(gpui::relative(0.5 + card.tilt.x * 0.5)) + .top(gpui::relative(0.5 + card.tilt.y * 0.5)) + .size(px(1.)) + .rounded_full() + .shadow(vec![gpui::BoxShadow { + color: gpui::white().opacity(0.07 * strength), + offset: point(px(0.), px(0.)), + blur_radius: px(160.), + spread_radius: px(60.), + inset: false, + }]) + }; + let close = on.clone(); + let track = on.clone(); + let leave = on; + div() + .absolute() + .inset_0() + .flex() + .items_center() + .justify_center() + .bg(gpui::black().opacity(0.72 * ease)) + .occlude() + .on_mouse_down(MouseButton::Left, move |_, w, cx| close(Ev::Close, w, cx)) + .child( + div() + .id("badge-card") + .relative() + .w(px(358.)) + .pt(px(36.)) + .px(px(28.)) + .pb(px(28.)) + .rounded(px(22.)) + .overflow_hidden() + .border_1() + .border_color(c(0x393b3c)) + .bg(linear_gradient( + 160., + linear_color_stop(c(0x171717), 0.), + linear_color_stop(c(0x16181a), 1.), + )) + .shadow(vec![gpui::BoxShadow { + color: gpui::black().opacity(0.6), + offset: point(px(0.), px(24.)), + blur_radius: px(70.), + spread_radius: px(0.), + inset: false, + }]) + .opacity(ease) + .top(px(10. * (1. - ease))) + .font_family(INTER) + .text_size(px(14.)) + .line_height(px(21.)) + .text_color(c(0xb2b2b2)) + .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) + .on_mouse_move(move |e, w, cx| track(Ev::Pointer(e.position), w, cx)) + .on_hover(move |hovered, w, cx| { + if !*hovered { + leave(Ev::Leave, w, cx) + } + }) + .child(glare) + .child( + shift(div().flex().justify_center().mb(px(18.)), 46.) + .child(crate::kit::sharp_svg(card.svg.clone(), 172., window, cx)), + ) + .child( + shift( + div() + .w_full() + .text_center() + .font_weight(FontWeight::BOLD) + .text_size(px(20.)) + .line_height(px(24.)) + .text_color(c(0xffffff)) + .mb(px(10.)), + 26., + ) + .child(card.title.clone()), + ) + .children(card.subtitle.clone().map(|s| { + shift( + div() + .w_full() + .mt(px(-4.)) + .mb(px(12.)) + .flex() + .justify_center() + .text_size(px(13.)) + .line_height(px(24.)) + .text_color(c(0x8a8a8a)), + 22., + ) + .child(crate::kit::spaced(&s, 0.78)) + })) + .child( + shift(div().w_full().flex().flex_col(), 14.).children( + card.desc + .iter() + .map(|(runs, gap)| div().mb(px(*gap)).child(paragraph(runs))), + ), + ) + .children(tiers) + .children(access), + ) + .into_any_element() +} diff --git a/crates/vector-gpui/src/bakes.rs b/crates/vector-gpui/src/bakes.rs new file mode 100644 index 000000000..d1e5ce1b2 --- /dev/null +++ b/crates/vector-gpui/src/bakes.rs @@ -0,0 +1,136 @@ +//! Pictures kept on disk at the size they're drawn, as raw BGRA a first frame can read whole: +//! sealed like the cache they come from, so no plain pixels sit in the app's folders. + +use std::path::{Path, PathBuf}; + +/// FNV-1a of a path: the stem every bake of one source starts with. +pub fn source_hash(path: &Path) -> u64 { + let mut h: u64 = 0xcbf2_9ce4_8422_2325; + for b in path.as_os_str().as_encoded_bytes() { + h = (h ^ u64::from(*b)).wrapping_mul(0x0100_0000_01b3); + } + h +} + +/// `dir`'s bake for `tag` at `w`×`h`. +pub fn file(dir: &Path, tag: &str, (w, h): (u32, u32)) -> PathBuf { + dir.join(format!("{tag}{w}x{h}.bgra")) +} + +/// A bake as written: its size, then its pixels. One left unsealed is dropped. +pub fn load(file: &Path, (w, h): (u32, u32)) -> Option { + if !vector_core::vcache::is_sealed(file) { + let _ = std::fs::remove_file(file); + return None; + } + let mut bytes = vector_core::vcache::read(file).ok()?; + let (head, px) = bytes.split_at_checked(8)?; + let size = (u32::from_le_bytes(head[..4].try_into().ok()?), u32::from_le_bytes(head[4..].try_into().ok()?)); + if size != (w, h) || px.len() as u64 != u64::from(w) * u64::from(h) * 4 { + return None; + } + bytes.drain(..8); + image::RgbaImage::from_raw(w, h, std::mem::take(&mut *bytes)) +} + +/// `tag`'s newest bake in `dir` at any size, and that size. +pub fn newest(dir: &Path, tag: &str) -> Option<(PathBuf, (u32, u32))> { + std::fs::read_dir(dir) + .ok()? + .flatten() + .filter_map(|e| { + let name = e.file_name().into_string().ok()?; + let (w, h) = name.strip_prefix(tag)?.strip_suffix(".bgra")?.split_once('x')?; + let at = e.metadata().and_then(|m| m.modified()).ok()?; + Some((at, e.path(), (w.parse().ok()?, h.parse().ok()?))) + }) + .max_by_key(|(at, _, _)| *at) + .map(|(_, f, size)| (f, size)) +} + +/// Written sealed, whole or not at all; then `tag`'s sizes past the newest `keep` go. Without the +/// cache key nothing is kept. +pub fn store(file: &Path, img: &image::RgbaImage, tag: &str, keep: usize) { + let Some(dir) = file.parent() else { return }; + let mut bytes = zeroize::Zeroizing::new(Vec::with_capacity(8 + img.as_raw().len())); + bytes.extend_from_slice(&img.width().to_le_bytes()); + bytes.extend_from_slice(&img.height().to_le_bytes()); + bytes.extend_from_slice(img.as_raw()); + let written = std::fs::create_dir_all(dir).map_err(|e| e.to_string()).and_then(|_| vector_core::vcache::write(file, &bytes)); + if let Err(e) = written { + vector_core::log_warn!("[Bakes] not kept: {e}"); + return; + } + let Ok(entries) = std::fs::read_dir(dir) else { return }; + let mut sizes: Vec<(std::time::SystemTime, PathBuf)> = entries + .flatten() + .filter(|e| e.file_name().to_str().is_some_and(|n| n.starts_with(tag) && n.ends_with(".bgra"))) + .map(|e| (e.metadata().and_then(|m| m.modified()).unwrap_or(std::time::UNIX_EPOCH), e.path())) + .collect(); + sizes.sort_by(|a, b| b.0.cmp(&a.0)); + for (_, old) in sizes.into_iter().skip(keep) { + let _ = std::fs::remove_file(old); + } +} + +/// Everything in `dir` that no `tags` entry starts, gone; a write in flight is left be. +pub fn sweep(dir: &Path, tags: &[String]) { + let Ok(entries) = std::fs::read_dir(dir) else { return }; + for e in entries.flatten() { + let Some(name) = e.file_name().to_str().map(str::to_string) else { continue }; + if name.ends_with(".vtmp") { + continue; + } + if !tags.iter().any(|t| name.starts_with(t.as_str())) { + let _ = std::fs::remove_file(e.path()); + } + } +} + +/// `src` covering `w`×`h`, centred, scaled up `over` so a blurred edge falls outside. +pub fn cover(src: &image::RgbaImage, (w, h): (u32, u32), over: f32) -> image::RgbaImage { + let (sw, sh) = (src.width() as f32, src.height() as f32); + let scale = (w as f32 / sw).max(h as f32 / sh) * over; + let (cw, ch) = ((w as f32 / scale).min(sw), (h as f32 / scale).min(sh)); + let (cx, cy) = (((sw - cw) / 2.) as u32, ((sh - ch) / 2.) as u32); + let crop = image::imageops::crop_imm(src, cx, cy, (cw.round() as u32).max(1), (ch.round() as u32).max(1)).to_image(); + gpui::resample(&crop, w, h, image::imageops::FilterType::Triangle) +} + +/// A process-wide data folder for tests, so the cache key exists and bakes are sealed. +#[cfg(test)] +pub fn test_data_dir() { + static DIR: std::sync::OnceLock = std::sync::OnceLock::new(); + DIR.get_or_init(|| { + let dir = std::env::temp_dir().join(format!("vector-gpui-test-{}", std::process::id())); + let _ = std::fs::create_dir_all(&dir); + vector_core::db::set_app_data_dir(dir.clone()); + dir + }); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_bake_is_sealed_and_an_unsealed_one_is_dropped() { + test_data_dir(); + let dir = std::env::temp_dir().join(format!("vector-bakes-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let img = image::RgbaImage::from_pixel(3, 2, image::Rgba([1, 2, 3, 255])); + let f = file(&dir, "abc-", (3, 2)); + store(&f, &img, "abc-", 2); + assert!(vector_core::vcache::is_sealed(&f)); + assert!(!std::fs::read(&f).unwrap().windows(4).any(|w| w == [1, 2, 3, 255])); + assert_eq!(load(&f, (3, 2)).unwrap().as_raw(), img.as_raw()); + assert_eq!(newest(&dir, "abc-").map(|(_, s)| s), Some((3, 2))); + let plain = file(&dir, "old-", (1, 1)); + std::fs::write(&plain, [1u8, 0, 0, 0, 1, 0, 0, 0, 9, 9, 9, 9]).unwrap(); + assert!(load(&plain, (1, 1)).is_none()); + assert!(!plain.exists()); + sweep(&dir, &[]); + assert!(!f.exists()); + let _ = std::fs::remove_dir_all(&dir); + } +} diff --git a/crates/vector-gpui/src/banner.rs b/crates/vector-gpui/src/banner.rs new file mode 100644 index 000000000..604900a31 --- /dev/null +++ b/crates/vector-gpui/src/banner.rs @@ -0,0 +1,105 @@ +//! Community banners as sealed bakes at the list's drawn size: an open reads its banner whole in +//! the first frame, and none is held in memory while its Community is closed. + +use std::path::{Path, PathBuf}; +use std::sync::Arc; + +use gpui::RenderImage; + +use crate::bakes; +use crate::data::Store; + +/// Sizes kept per banner: the list's width moves rarely. +const KEEP: usize = 2; + +/// The banner's pixels at `width` points (the list draws at 238:70). +pub fn size(width: f32) -> (u32, u32) { + let w = (width * 2.).round().max(1.); + (w as u32, ((w * 70. / 238.).round() as u32).max(1)) +} + +fn tag(path: &Path) -> String { + format!("{:016x}-", bakes::source_hash(path)) +} + +/// The account's banner bakes. +pub fn dir(npub: &str) -> Option { + vector_core::db::account_dir(npub).ok().map(|d| d.join(".bakes").join("banners")) +} + +/// The banner at `path` for a list `width` wide, read from its bake on first sight; `None` +/// while it has none. +pub fn shown(store: &Store, path: &Path, width: f32) -> Option> { + let mut slot = store.banner_shown.borrow_mut(); + if let Some((_, image)) = slot.as_ref().filter(|(p, _)| p == path) { + return image.clone(); + } + let image = store.banner_bakes.as_deref().and_then(|dir| read(dir, path, size(width))).map(Arc::new); + if let Some((_, Some(old))) = slot.replace((path.to_path_buf(), image.clone())) { + store.banner_retired.borrow_mut().push(old); + } + image +} + +/// Its bake at `want`, else its newest at any size for the GPU to stretch. +fn read(dir: &Path, path: &Path, want: (u32, u32)) -> Option { + let tag = tag(path); + let exact = bakes::file(dir, &tag, want); + let (file, size) = if exact.exists() { (exact, want) } else { bakes::newest(dir, &tag)? }; + Some(RenderImage::new(vec![image::Frame::new(bakes::load(&file, size)?)])) +} + +/// Bakes `show` lacks at `want`, and every bake no banner in `all` still has, gone. Disk only; +/// whether anything was baked. +pub fn bake_all(dir: PathBuf, show: Vec, all: Vec, want: (u32, u32)) -> bool { + let _trim = crate::trim::OnDrop; + let mut baked = false; + for path in show { + let tag = tag(&path); + let file = bakes::file(&dir, &tag, want); + if file.exists() { + continue; + } + let Ok(bytes) = crate::pic::read(&path) else { continue }; + // A moving banner keeps to the decoder that animates it. + if bytes.starts_with(b"GIF8") { + continue; + } + let ext = crate::backend::inline::sniff(&bytes).unwrap_or("png"); + let Some((pic, ..)) = crate::media::decode(&bytes, ext, (want.0 * 2, want.0 * 2)) else { continue }; + if pic.frame_count() > 1 { + continue; + } + let px = pic.size(0); + let Some(src) = pic.as_bytes(0).and_then(|b| image::RgbaImage::from_raw(px.width.0 as u32, px.height.0 as u32, b.to_vec())) else { continue }; + bakes::store(&file, &bakes::cover(&src, want, 1.), &tag, KEEP); + baked = true; + } + bakes::sweep(&dir, &all.iter().map(|p| tag(p)).collect::>()); + baked +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_banner_bakes_sealed_at_its_size_and_goes_with_its_picture() { + bakes::test_data_dir(); + let root = std::env::temp_dir().join(format!("vector-banner-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&root); + std::fs::create_dir_all(&root).unwrap(); + let src = root.join("b.png"); + image::RgbaImage::from_pixel(952, 280, image::Rgba([200, 40, 40, 255])).save(&src).unwrap(); + let dir = root.join("bakes"); + let want = size(239.); + assert!(bake_all(dir.clone(), vec![src.clone()], vec![src.clone()], want)); + assert!(!bake_all(dir.clone(), vec![src.clone()], vec![src.clone()], want), "baked once"); + let img = read(&dir, &src, want).expect("read back"); + assert_eq!(img.size(0).width.0 as u32, want.0); + assert!(read(&dir, &src, size(300.)).is_some(), "another width stretches the newest"); + bake_all(dir.clone(), Vec::new(), Vec::new(), want); + assert!(read(&dir, &src, want).is_none(), "a banner no Community shows takes its bakes"); + let _ = std::fs::remove_dir_all(&root); + } +} diff --git a/crates/vector-gpui/src/bin/vector-gpui-miniapp.rs b/crates/vector-gpui/src/bin/vector-gpui-miniapp.rs new file mode 100644 index 000000000..01cfed09c --- /dev/null +++ b/crates/vector-gpui/src/bin/vector-gpui-miniapp.rs @@ -0,0 +1,353 @@ +//! Linux Mini App windows: WebKitGTK webviews in a process of their own, so the app never +//! loads WebKit and a crashed page takes only its windows down. Driven over stdin/stdout by +//! `miniapp/host_proc.rs`; it exits when the app closes the pipe. + +#[cfg(not(target_os = "linux"))] +fn main() {} + +#[cfg(target_os = "linux")] +#[path = "../miniapp/wire.rs"] +mod wire; + +#[cfg(target_os = "linux")] +fn main() { + host::run(); +} + +#[cfg(target_os = "linux")] +mod host { + use std::cell::{Cell, RefCell}; + use std::collections::HashMap; + use std::rc::Rc; + use std::sync::Mutex; + use std::sync::atomic::{AtomicU64, Ordering}; + + use gtk::glib; + use gtk::prelude::*; + use wry::http::{Request, Response}; + use wry::{RequestAsyncResponder, WebContext, WebViewBuilder, WebViewBuilderExtUnix, WebViewExtUnix}; + + use crate::wire::{self, FromHost, Open, ToHost}; + + const PLAYER: &str = "player"; + const CRASHED: &str = "Mini App Crashed Unexpectedly"; + + struct Window { + window: gtk::Window, + view: wry::WebView, + /// An isolated app's data store; it must outlive the view. + _context: Option, + } + + thread_local! { + static OPEN: RefCell> = RefCell::new(HashMap::new()); + static SHARED: std::cell::Cell<*mut WebContext> = const { std::cell::Cell::new(std::ptr::null_mut()) }; + } + + /// The store every non-isolated app shares: the Tauri client's (its webviews default to + /// app_local_data_dir), so their storage carries over between the clients. + fn shared_context() -> &'static mut WebContext { + SHARED.with(|c| { + if c.get().is_null() { + let dir = dirs::data_local_dir().map(|d| d.join("io.vectorapp")); + c.set(Box::into_raw(Box::new(WebContext::new(dir)))); + } + // SAFETY: leaked once on the GTK thread; each builder's borrow ends at its build. + unsafe { &mut *c.get() } + }) + } + + static OUT: Mutex> = Mutex::new(None); + static PENDING: Mutex>> = Mutex::new(None); + static NEXT: AtomicU64 = AtomicU64::new(1); + + fn send(msg: &FromHost, body: &[u8]) { + if let Ok(mut out) = OUT.lock() + && let Some(out) = out.as_mut() + && wire::write(&mut out.lock(), msg, body).is_err() + { + std::process::exit(0); + } + } + + fn warn(what: &str) { + eprintln!("[MiniApp host] {what}"); + } + + /// Before GTK or any thread starts, as the desktop client does. + fn webkit_env() { + let user_chose = std::env::var_os("WEBKIT_DISABLE_DMABUF_RENDERER").is_some() + || std::env::var_os("WEBKIT_DMABUF_RENDERER_FORCE_SHM").is_some(); + // SAFETY: single-threaded here; the getters read the linked WebKitGTK's version. + unsafe { + if !user_chose { + // DMA-BUF hand-off garbles on some GPUs; shared memory keeps acceleration on 2.54+. + let webkit = (webkit2gtk::ffi::webkit_get_major_version(), webkit2gtk::ffi::webkit_get_minor_version()); + if webkit >= (2, 54) { + std::env::set_var("WEBKIT_DMABUF_RENDERER_FORCE_SHM", "1"); + } else { + std::env::set_var("WEBKIT_DISABLE_DMABUF_RENDERER", "1"); + } + } + // WebKitGTK keeps SharedArrayBuffer off even in a cross-origin isolated page unless JSC enables it. + std::env::set_var("JSC_useSharedArrayBuffer", "1"); + } + } + + pub fn run() { + webkit_env(); + if let Err(e) = gtk::init() { + warn(&format!("GTK unavailable: {e}")); + std::process::exit(2); + } + *OUT.lock().unwrap_or_else(|e| e.into_inner()) = Some(std::io::stdout()); + *PENDING.lock().unwrap_or_else(|e| e.into_inner()) = Some(HashMap::new()); + let ctx = glib::MainContext::default(); + std::thread::Builder::new() + .name("miniapp-pipe".into()) + .spawn(move || { + let mut input = std::io::stdin().lock(); + while let Ok((msg, body)) = wire::read::(&mut input) { + if let ToHost::Reply { id, status, headers } = msg { + reply(id, status, headers, body); + continue; + } + ctx.invoke(move || handle(msg)); + } + std::process::exit(0); + }) + .expect("pipe thread"); + gtk::main(); + } + + fn reply(id: u64, status: u16, headers: Vec<(String, String)>, body: Vec) { + let Some(responder) = PENDING.lock().ok().and_then(|mut p| p.as_mut()?.remove(&id)) else { return }; + let mut r = Response::builder().status(status); + for (k, v) in headers { + r = r.header(k, v); + } + match r.body(body) { + Ok(r) => responder.respond(r), + Err(_) => responder.respond(Response::builder().status(500).body(Vec::new()).unwrap()), + } + } + + fn handle(msg: ToHost) { + match msg { + ToHost::Open(spec) => { + let label = spec.label.clone(); + if let Err(error) = build(spec) { + warn(&format!("window failed: {error}")); + send(&FromHost::Failed { label, error }, &[]); + } + } + ToHost::Player { title, url, size, init } => player(title, url, size, init), + ToHost::Focus { label, navigate } => with(&label, |o| { + if let Some(url) = navigate { + let _ = o.view.load_url(&url); + } + o.window.show(); + o.window.present(); + }), + ToHost::Eval { label, js } => with(&label, |o| { + let _ = o.view.evaluate_script(&js); + }), + ToHost::Destroy { label } => with(&label, |o| unsafe { o.window.destroy() }), + ToHost::Close { label } => with(&label, |o| o.window.close()), + ToHost::Reply { .. } => {} + } + } + + fn with(label: &str, f: impl FnOnce(&Window)) { + OPEN.with(|o| { + if let Some(open) = o.borrow().get(label) { + f(open); + } + }) + } + + fn serve(label: &str, request: Request>, responder: RequestAsyncResponder) { + let id = NEXT.fetch_add(1, Ordering::Relaxed); + if let Ok(mut p) = PENDING.lock() + && let Some(p) = p.as_mut() + { + p.insert(id, responder); + } + let (parts, body) = request.into_parts(); + let headers = parts + .headers + .iter() + .filter_map(|(k, v)| Some((k.to_string(), v.to_str().ok()?.to_string()))) + .collect(); + let msg = FromHost::Serve { + id, + label: label.to_string(), + method: parts.method.to_string(), + uri: parts.uri.to_string(), + headers, + }; + send(&msg, &body); + } + + fn build(spec: Open) -> Result<(), String> { + let window = gtk::Window::new(gtk::WindowType::Toplevel); + window.set_title(&spec.title); + window.set_default_size(480, 640); + window.set_size_request(320, 480); + let body = gtk::Box::new(gtk::Orientation::Vertical, 0); + window.add(&body); + + let (own_scheme, own_host) = origin(&spec.url); + let ipc_label = spec.label.clone(); + let scheme_label = spec.label.clone(); + let mut context = spec.isolated.as_ref().map(|i| WebContext::new(Some(i.data_dir.clone()))); + let mut builder = match context.as_mut() { + Some(c) => WebViewBuilder::new_with_web_context(c), + None => WebViewBuilder::new_with_web_context(shared_context()), + }; + let blank_first = spec.isolated.is_some(); + builder = builder + .with_initialization_script_for_main_only(spec.init.clone(), false) + .with_asynchronous_custom_protocol("webxdc".into(), move |_, request, responder| { + serve(&scheme_label, request, responder); + }) + .with_ipc_handler(move |request| { + send(&FromHost::Ipc { label: ipc_label.clone(), body: request.into_body() }, &[]); + }) + .with_navigation_handler(move |url| { + let ok = origin(&url) == (own_scheme.clone(), own_host.clone()) || (blank_first && url == "about:blank"); + if !ok { + warn(&format!("blocked navigation to {url}")); + } + ok + }) + .with_devtools(cfg!(debug_assertions)) + .with_url(if blank_first { "about:blank" } else { &spec.url }); + if let Some((host, port)) = spec.proxy.as_ref().filter(|_| !blank_first) { + builder = builder.with_proxy_config(wry::ProxyConfig::Socks5(wry::ProxyEndpoint { + host: host.clone(), + port: port.to_string(), + })); + } + let view = builder.build_gtk(&body).map_err(|e| e.to_string())?; + // Blank first: the null proxy, with this origin exempt, must be in place before the app runs. + if let Some(i) = &spec.isolated { + use webkit2gtk::{NetworkProxyMode, NetworkProxySettings, WebContextExt, WebViewExt, WebsiteDataManagerExt}; + let inner = view.webview(); + vector_media::miniapps::isolated::enable_web_storage(&inner); + let Some(manager) = inner.context().and_then(|c| c.website_data_manager()) else { + unsafe { window.destroy() }; + return Err("could not isolate the Mini App's network".into()); + }; + let hosts: Vec<&str> = i.bypass.iter().map(String::as_str).collect(); + let mut settings = NetworkProxySettings::new(Some(i.sink.as_str()), &hosts); + manager.set_network_proxy_settings(NetworkProxyMode::Custom, Some(&mut settings)); + view.load_url(&i.boot_url).map_err(|e| e.to_string())?; + } + + // A crashed page would leave a blank window: it goes, and the app says why. + { + use webkit2gtk::WebViewExt; + let label = spec.label.clone(); + let w = window.clone(); + view.webview().connect_web_process_terminated(move |_, _| { + send(&FromHost::Failed { label: label.clone(), error: CRASHED.into() }, &[]); + unsafe { w.destroy() }; + }); + } + + // A first close leaves the page instead, so unload handlers can send a last update. + let leaving = Rc::new(Cell::new(false)); + let label = spec.label.clone(); + let farewell = spec.farewell.clone(); + window.connect_delete_event(move |w, _| { + if leaving.replace(true) { + return glib::Propagation::Proceed; + } + with(&label, |open| { + let _ = open.view.load_url(&farewell); + }); + w.hide(); + let w = w.clone(); + glib::timeout_add_local_once(std::time::Duration::from_millis(300), move || { + w.close(); + }); + glib::Propagation::Stop + }); + let label = spec.label.clone(); + window.connect_destroy(move |_| { + OPEN.with(|o| o.borrow_mut().remove(&label)); + send(&FromHost::Closed { label: label.clone() }, &[]); + }); + window.show_all(); + window.present(); + OPEN.with(|o| o.borrow_mut().insert(spec.label, Window { window, view, _context: context })); + Ok(()) + } + + fn player(title: String, url: String, size: (f32, f32), init: String) { + let reused = OPEN.with(|o| match o.borrow().get(PLAYER) { + Some(open) => { + let _ = open.view.load_url(&url); + open.window.set_title(&title); + open.window.resize(size.0 as i32, size.1 as i32); + open.window.present(); + true + } + None => false, + }); + if reused { + return; + } + if let Err(error) = build_player(&title, &url, size, init) { + warn(&format!("player window failed: {error}")); + send(&FromHost::Failed { label: PLAYER.into(), error }, &[]); + } + } + + /// Its own ephemeral context: no Mini App's null proxy, and nothing kept between plays. + fn build_player(title: &str, url: &str, size: (f32, f32), init: String) -> Result<(), String> { + let window = gtk::Window::new(gtk::WindowType::Toplevel); + window.set_title(title); + window.set_default_size(size.0 as i32, size.1 as i32); + let body = gtk::Box::new(gtk::Orientation::Vertical, 0); + window.add(&body); + let own = origin(url); + let view = WebViewBuilder::new() + .with_incognito(true) + .with_initialization_script_for_main_only(init, true) + .with_ipc_handler(|request| send(&FromHost::Player { body: request.into_body() }, &[])) + // The page, and the provider frame it embeds: nothing else loads. + .with_navigation_handler(move |url| origin(&url) == own || provider_frame(&url)) + .with_new_window_req_handler(|url, _| { + send(&FromHost::Browse { url }, &[]); + wry::NewWindowResponse::Deny + }) + .with_url(url) + .build_gtk(&body) + .map_err(|e| e.to_string())?; + window.connect_destroy(|_| { + OPEN.with(|o| o.borrow_mut().remove(PLAYER)); + send(&FromHost::Closed { label: PLAYER.into() }, &[]); + }); + window.show_all(); + window.present(); + OPEN.with(|o| o.borrow_mut().insert(PLAYER.into(), Window { window, view, _context: None })); + Ok(()) + } + + /// A YouTube or SoundCloud embed over https: the frame a player page holds. + fn provider_frame(url: &str) -> bool { + url::Url::parse(url).is_ok_and(|u| u.scheme() == "https" && matches!(u.host_str(), Some("www.youtube-nocookie.com" | "w.soundcloud.com"))) + } + + fn origin(url: &str) -> (String, String) { + match url::Url::parse(url) { + Ok(u) => ( + u.scheme().to_string(), + format!("{}:{:?}", u.host_str().unwrap_or(""), u.port_or_known_default()), + ), + Err(_) => (String::new(), String::new()), + } + } +} diff --git a/crates/vector-gpui/src/call.rs b/crates/vector-gpui/src/call.rs new file mode 100644 index 000000000..6205145ea --- /dev/null +++ b/crates/vector-gpui/src/call.rs @@ -0,0 +1,1504 @@ +//! `CallOverlay.svelte`: a ring card while a call comes in, otherwise a pill that floats above +//! every pane, drags anywhere, remembers where it was left, and opens into volume, the voice +//! meter, the processing switches and a plain-language view of the connection. + +use crate::kit::Tipped as _; +use std::cell::Cell; +use std::collections::VecDeque; +use std::rc::Rc; +use std::sync::Arc; +use std::time::{Duration, Instant}; + +use gpui::{ + AnimationExt, AnyElement, App, Bounds, BoxShadow, Hsla, InteractiveElement, IntoElement, + ParentElement, Pixels, Point, SharedString, StatefulInteractiveElement, Styled, Window, canvas, + div, point, prelude::FluentBuilder, px, svg, RenderImage, +}; +use serde_json::Value; + +use crate::data::Store; +use crate::t; +use crate::theme::{ACCENT, c, ca, white_a}; + +const HISTORY: usize = 60; +/// The Vector theme's `--danger-color`. +pub(crate) const DANGER: u32 = 0xff2ea9; +const OPEN_W: f32 = 300.; +const PILL_MAX_W: f32 = 320.; +/// How long an ended call stays up to read why. +pub const ENDED_LINGER: Duration = Duration::from_millis(2500); + +#[derive(Clone, Copy, PartialEq, Debug)] +pub enum Phase { + Ringing, + Connecting, + Active, + Ended, +} + +#[derive(Clone, Copy, PartialEq, Debug)] +pub enum Quality { + Excellent, + Good, + Fair, + Poor, +} + +impl Quality { + pub(crate) fn color(self) -> Hsla { + match self { + Quality::Excellent => c(0x59fcb3), + Quality::Good => c(0xfce459), + Quality::Fair => c(0xfca559), + Quality::Poor => c(DANGER), + } + } + + pub(crate) fn label(self) -> SharedString { + match self { + Quality::Excellent => t::call_quality_excellent(), + Quality::Good => t::call_quality_good(), + Quality::Fair => t::call_quality_fair(), + Quality::Poor => t::call_quality_poor(), + } + } +} + +pub(crate) fn grade(lost: f32, rtt: f32) -> Quality { + if lost < 0.5 && rtt < 150. { + Quality::Excellent + } else if lost < 2. && rtt < 300. { + Quality::Good + } else if lost < 5. && rtt < 500. { + Quality::Fair + } else { + Quality::Poor + } +} + +#[derive(Clone, Default)] +pub struct Stats { + pub rtt_ms: u32, + pub path: String, + pub bitrate_kbps: u32, + pub net_loss: f32, + pub received: u64, + pub concealed: u64, +} + +#[derive(Clone, Copy)] +struct Sample { + rtt: f32, + lost: f32, +} + +#[derive(Clone, Copy)] +pub(crate) struct Drag { + pub(crate) start: Point, + pub(crate) origin: Point, + pub(crate) moved: bool, +} + +/// The one call, mirrored from the backend's `call_state` events. +pub struct Call { + pub id: Option, + pub peer: String, + pub outgoing: bool, + pub phase: Option, + pub reason: Option, + pub muted: bool, + pub peer_muted: bool, + pub mic_off: bool, + pub volume: f32, + active_ms: u64, + received_at: Instant, + pub video_offered: bool, + peer_away: bool, + stalled: bool, + stats: Option, + history: VecDeque, + quality: Option, + levels: (f32, f32), + pub expanded: bool, + pub pos: Option>, + pub ended_at: Option, + /// The graph sample under the pointer. + pub hover: Option, + pill: Rc>>>, + slider: Rc>>>, + graph: Rc>>>, + drag: Rc>>, + sliding: Rc>, + /// What each side sends on video, camera then screen. + pub video_mine: [bool; 2], + pub video_peer: [bool; 2], + /// The peer named a decoder, so video can go their way at all. + pub peer_decodes: bool, + pub paused_by_peer: bool, + video_stats: [Option<(u32, u32, u32, u32)>; 2], + /// One of their pictures filling the window. + pub maximized: Option, + /// The full view's controls show until then. + pub max_controls: Option, + /// The panel's quality and frame rate per picture; None is adaptive. + pub prefs: [(Option, Option); 2], + /// The panel's open dropdown: the picture, and whether it is the frame rate. + pub pref_open: Option<(usize, bool)>, + pub share_audio_mine: bool, + /// This platform captures a screen's sound itself. + pub share_audio_native: bool, + pub share_audio_denied: bool, + /// Their screen's sound comes with their share; it has a volume of its own. + pub share_audio_peer: bool, + pub share_volume: f32, + share_slider: Rc>>>, + share_sliding: Rc>, +} + +impl Default for Call { + fn default() -> Self { + Self { + id: None, + peer: String::new(), + outgoing: false, + phase: None, + reason: None, + muted: false, + peer_muted: false, + mic_off: false, + volume: 1., + active_ms: 0, + received_at: Instant::now(), + video_offered: false, + peer_away: false, + stalled: false, + stats: None, + history: VecDeque::new(), + quality: None, + levels: (0., 0.), + expanded: false, + pos: None, + ended_at: None, + hover: None, + pill: Rc::default(), + slider: Rc::default(), + graph: Rc::default(), + drag: Rc::default(), + sliding: Rc::default(), + video_mine: [false; 2], + video_peer: [false; 2], + peer_decodes: false, + paused_by_peer: false, + video_stats: [None; 2], + maximized: None, + max_controls: None, + prefs: [(None, None); 2], + pref_open: None, + share_audio_mine: false, + share_audio_native: false, + share_audio_denied: false, + share_audio_peer: false, + share_volume: 1., + share_slider: Rc::default(), + share_sliding: Rc::default(), + } + } +} + +fn phase_of(s: &str) -> Option { + Some(match s { + "ringing" => Phase::Ringing, + "connecting" => Phase::Connecting, + "active" => Phase::Active, + "ended" => Phase::Ended, + _ => return None, + }) +} + +impl Call { + /// `s` is the backend's CallState, or null when there is no call. + pub fn apply_state(&mut self, s: &Value) { + if s.is_null() { + self.clear(); + return; + } + let str_of = |k: &str| { + s.get(k) + .and_then(Value::as_str) + .unwrap_or_default() + .to_string() + }; + let bool_of = |k: &str| s.get(k).and_then(Value::as_bool).unwrap_or(false); + let id = str_of("id"); + if self.id.as_deref() != Some(id.as_str()) { + self.stats = None; + self.history.clear(); + self.quality = None; + self.levels = (0., 0.); + self.hover = None; + self.video_stats = [None; 2]; + self.maximized = None; + self.prefs = [(None, None); 2]; + } + self.id = Some(id); + self.peer = str_of("peer"); + self.outgoing = bool_of("outgoing"); + let was = self.phase; + self.phase = s.get("phase").and_then(Value::as_str).and_then(phase_of); + self.reason = s.get("reason").and_then(Value::as_str).map(str::to_string); + self.muted = bool_of("muted"); + self.peer_muted = bool_of("peer_muted"); + self.mic_off = bool_of("mic_off"); + self.volume = s.get("volume").and_then(Value::as_f64).unwrap_or(1.) as f32; + self.active_ms = s.get("active_ms").and_then(Value::as_u64).unwrap_or(0); + self.received_at = Instant::now(); + self.video_offered = bool_of("video_offered"); + self.peer_away = bool_of("peer_away"); + self.stalled = bool_of("stalled"); + let tracks = |k: &str| { + let t = s.get(k); + let on = |n: &str| t.and_then(|t| t.get(n)).and_then(Value::as_bool).unwrap_or(false); + [on("camera"), on("screen")] + }; + self.video_mine = tracks("video_mine"); + self.video_peer = tracks("video_peer"); + self.peer_decodes = s.get("peer_decodes").and_then(Value::as_array).is_some_and(|a| !a.is_empty()); + self.paused_by_peer = bool_of("paused_by_peer"); + self.share_audio_mine = bool_of("share_audio_mine"); + self.share_audio_native = bool_of("share_audio_native"); + self.share_audio_denied = bool_of("share_audio_denied"); + self.share_audio_peer = bool_of("share_audio_peer"); + self.share_volume = s.get("share_volume").and_then(Value::as_f64).unwrap_or(1.) as f32; + if self.maximized.is_some_and(|k| !self.video_peer[k]) { + self.maximized = None; + } + self.ended_at = (self.phase == Some(Phase::Ended)).then(Instant::now); + // On a phase change only: a mute or volume update mid-ring keeps the details open. + if self.phase != was && self.phase != Some(Phase::Active) && self.phase != Some(Phase::Ended) { + self.expanded = false; + } + } + + pub fn clear(&mut self) { + self.id = None; + self.video_mine = [false; 2]; + self.video_peer = [false; 2]; + self.maximized = None; + self.phase = None; + self.stats = None; + self.history.clear(); + self.quality = None; + self.expanded = false; + self.ended_at = None; + } + + /// An ended call is gone once it has been up long enough to read. + pub fn expire(&mut self) -> bool { + if self.ended_at.is_some_and(|t| t.elapsed() >= ENDED_LINGER) { + self.clear(); + return true; + } + false + } + + /// The mic's level while a call is up, for the audio settings' meter. + pub fn live_mic(&self) -> Option { + (self.id.is_some() && self.phase.is_some_and(|p| p != Phase::Ended)).then_some(self.levels.0) + } + + pub fn apply_level(&mut self, l: &Value) { + if l.get("id").and_then(Value::as_str) != self.id.as_deref() { + return; + } + let f = |k: &str| l.get(k).and_then(Value::as_f64).unwrap_or(0.) as f32; + self.levels = (f("mic"), f("peer")); + } + + /// One stats line a second: lost audio for this second is what the speaker filled in, over what arrived. + pub fn apply_stats(&mut self, st: &Value) { + if st.get("id").and_then(Value::as_str) != self.id.as_deref() { + return; + } + let u = |k: &str| st.get(k).and_then(Value::as_u64).unwrap_or(0); + let next = Stats { + rtt_ms: u("rtt_ms") as u32, + path: st + .get("path") + .and_then(Value::as_str) + .unwrap_or_default() + .to_string(), + bitrate_kbps: u("bitrate_kbps") as u32, + net_loss: st.get("net_loss").and_then(Value::as_f64).unwrap_or(0.) as f32, + received: u("received"), + concealed: u("concealed"), + }; + let mut lost = 0.; + if let Some(prev) = &self.stats + && next.received > prev.received + { + lost = 100. * next.concealed.saturating_sub(prev.concealed) as f32 + / (next.received - prev.received) as f32; + } + self.history.push_back(Sample { + rtt: next.rtt_ms as f32, + lost: lost.max(0.), + }); + if self.history.len() > HISTORY { + self.history.pop_front(); + } + self.stats = Some(next); + for (i, k) in ["camera", "screen"].iter().enumerate() { + let t = st.get("video").and_then(|v| v.get(k)); + let n = |f: &str| t.and_then(|t| t.get(f)).and_then(Value::as_u64).unwrap_or(0) as u32; + self.video_stats[i] = t.map(|_| (n("width"), n("height"), n("fps"), n("kbps"))); + } + let recent: Vec<_> = self.history.iter().rev().take(10).collect(); + let n = recent.len() as f32; + self.quality = (n > 0.).then(|| { + grade( + recent.iter().map(|r| r.lost).sum::() / n, + recent.iter().map(|r| r.rtt).sum::() / n, + ) + }); + } + + pub fn quality(&self) -> Option { + self.quality + } + + pub fn video_stats(&self, k: usize) -> Option<(u32, u32, u32, u32)> { + self.video_stats[k] + } + + pub fn live(&self) -> bool { + self.phase == Some(Phase::Active) + } + + /// Ringing for us, which takes the ring card rather than the pill. + pub fn incoming(&self) -> bool { + self.id.is_some() && self.phase == Some(Phase::Ringing) && !self.outgoing + } + + fn status(&self) -> String { + match self.phase { + Some(Phase::Ringing) => if self.outgoing { t::call_calling() } else { t::call_incoming() }.into(), + Some(Phase::Connecting) => t::call_connecting().into(), + Some(Phase::Active) if self.peer_away => t::call_peer_away().into(), + Some(Phase::Active) if self.stalled => t::call_reconnecting().into(), + Some(Phase::Active) => { + clock(self.active_ms + self.received_at.elapsed().as_millis() as u64) + } + Some(Phase::Ended) => reason_text(self.reason.as_deref()).into(), + None => String::new(), + } + } + + fn lost_pct(&self) -> f32 { + let recent: Vec<_> = self.history.iter().rev().take(10).collect(); + if recent.is_empty() { + return 0.; + } + recent.iter().map(|r| r.lost).sum::() / recent.len() as f32 + } +} + +fn reason_text(reason: Option<&str>) -> SharedString { + match reason { + Some("rejected") => t::call_ended_declined(), + Some("busy") => t::call_ended_busy(), + Some("no_answer") => t::call_ended_no_answer(), + Some("missed") => t::call_ended_missed(), + Some("connect_failed") => t::call_ended_connect_failed(), + Some("disconnected") => t::call_ended_disconnected(), + Some("audio_failed") => t::call_ended_audio_failed(), + Some("send_failed") => t::call_ended_send_failed(), + Some("answered_elsewhere") => t::call_ended_elsewhere(), + _ => t::call_ended(), + } +} + +pub fn clock(ms: u64) -> String { + let s = ms / 1000; + let m = s / 60; + let h = m / 60; + crate::lang::digits(if h > 0 { + format!("{h}:{:02}:{:02}", m % 60, s % 60) + } else { + format!("{:02}:{:02}", m % 60, s % 60) + }) +} + +fn lost_word(v: f32) -> SharedString { + if v < 0.05 { + t::call_graph_lost_none() + } else if v < 1. { + t::call_graph_lost_under_one() + } else { + t::call_graph_lost_percent(shown_pct(v)) + } +} + +/// One decimal under 10, whole above. +fn shown_pct(v: f32) -> f64 { + let v = f64::from(v); + if v < 10. { (v * 10.).round() / 10. } else { v.round() } +} + +#[derive(Clone, Copy, Debug)] +pub enum Switch { + AutoGain, + EchoCancel, + NoiseSuppress, +} + +#[derive(Clone, Debug)] +pub enum Act { + Accept, + Reject, + Hangup, + Mic, + Toggle, + Move(Point), + Moved, + Volume(f32), + ShareVolume(f32), + Audio(Switch, bool), + Hover(Option), + /// One of our pictures on or off: camera 0, screen 1. + Video(usize, bool), + Maximize(Option), + WakeControls, + /// A picture's quality (false) or frame rate (true), None for adaptive. + Pref(usize, bool, Option), + PrefOpen(Option<(usize, bool)>), + ChangeScreen, + ShareAudio(bool), + /// Where a phone plays the call. + Route(String), +} + +/// The pictures this frame shows, from the video worker. +#[derive(Default)] +pub struct Seen { + pub peer: [Option<(Arc, u32, u32)>; 2], + pub mine: [Option>; 2], + pub dec_fps: [u32; 2], + /// This device encodes and the peer decodes. + pub can_send: bool, +} + +pub type OnAct = Rc; + +/// The processing switches as the panel shows them. +pub struct Processing { + pub auto_gain: bool, + pub echo_cancel: bool, + pub noise_suppress: bool, +} + +pub(crate) fn accent_mix(pct: f32) -> Hsla { + let mut a = c(ACCENT); + a.a = pct.clamp(0., 1.); + a +} + +/// The phone glyph; hung up, it turns about its own box. +pub(crate) fn phone(size: f32, color: Hsla, down: bool) -> impl IntoElement { + let s = svg().path("ui/call.svg").size(px(size)).text_color(color); + if down { + s.with_transformation(gpui::Transformation::rotate(gpui::radians( + 135f32.to_radians(), + ))) + } else { + s + } +} + +pub(crate) fn round_btn(id: &'static str, size: f32) -> gpui::Stateful { + div() + .id(id) + .size(px(size)) + .flex_shrink_0() + .rounded_full() + .flex() + .items_center() + .justify_center() + .cursor_pointer() +} + +/// `.call-btn`: 34px, a faint wash; on, the accent's. +pub(crate) fn call_btn(id: &'static str, on_state: bool) -> gpui::Stateful { + round_btn(id, 34.) + .bg(if on_state { + accent_mix(0.22) + } else { + white_a(0.08) + }) + .text_color(if on_state { c(ACCENT) } else { white_a(0.88) }) + .hover(move |d| { + d.bg(if on_state { + accent_mix(0.30) + } else { + white_a(0.14) + }) + .text_color(if on_state { c(ACCENT) } else { c(0xffffff) }) + }) +} + +fn mic_btn(call: &Call, on: &OnAct) -> impl IntoElement { + let off = call.muted || call.mic_off; + let o = on.clone(); + call_btn("call-mic", off) + .tip(if call.mic_off { + t::call_mic_off() + } else if call.muted { + t::call_unmute() + } else { + t::call_mute() + }) + .on_mouse_down(gpui::MouseButton::Left, |_, _, cx| cx.stop_propagation()) + .on_click(move |_, w, cx| o(Act::Mic, w, cx)) + .child( + svg() + .path(if off { + "icons/mic-off.svg" + } else { + "icons/mic-on.svg" + }) + .size(px(18.7)) + .text_color(if off { c(ACCENT) } else { white_a(0.88) }), + ) +} + +fn route_btn(id: &'static str, on: &OnAct) -> Option { + let o = on.clone(); + crate::route::button(id, move |r, w, cx| o(Act::Route(r), w, cx)) +} + +fn hangup_btn(on: &OnAct) -> impl IntoElement { + let o = on.clone(); + round_btn("call-hangup", 34.) + .tip(t::call_hang_up()) + .bg(c(DANGER)) + .hover(|d| d.bg(c(0xff4db6))) + .on_mouse_down(gpui::MouseButton::Left, |_, _, cx| cx.stop_propagation()) + .on_click(move |_, w, cx| o(Act::Hangup, w, cx)) + .child(phone(20., c(0xffffff), true)) +} + +/// The ring card over everything while a call comes in. +fn ring(call: &Call, store: &Store, on: &OnAct) -> AnyElement { + let (decline, accept) = (on.clone(), on.clone()); + let pulse = round_btn("call-accept", 60.) + .tip(t::call_accept()) + .bg(c(ACCENT)) + .on_click(move |_, w, cx| accept(Act::Accept, w, cx)) + .child(phone(28., c(0x111111), false)) + .with_animation( + "call-ring-pulse", + gpui::Animation::new(Duration::from_millis(1200)).repeat(), + |d, t| { + let (spread, alpha) = if t < 0.5 { + let k = ease_in_out(t * 2.); + (12. * k, 0.45 * (1. - k)) + } else { + let k = ease_in_out((t - 0.5) * 2.); + (12. * (1. - k), 0.45 * k) + }; + d.shadow(vec![BoxShadow { + color: accent_mix(alpha), + offset: point(px(0.), px(0.)), + blur_radius: px(0.), + spread_radius: px(spread), + inset: false, + }]) + }, + ); + div() + .id("call-ring-overlay") + .absolute() + .inset_0() + .occlude() + .bg(ca(0, 0, 0, 0.7)) + .flex() + .items_center() + .justify_center() + .child( + div() + .flex() + .flex_col() + .items_center() + .gap(px(8.)) + .min_w(px(306.)) + .pt(px(28.)) + .px(px(32.)) + .pb(px(24.)) + .rounded(px(20.)) + .bg(c(0x1b1b1b)) + .border_1() + .border_color(white_a(0.08)) + .child(crate::ui::avatar(store, &call.peer, 84.)) + .child( + div() + .mt(px(8.)) + .max_w(px(400.)) + .truncate() + .text_size(px(18.)) + .font_weight(gpui::FontWeight::SEMIBOLD) + .text_color(c(0xffffff)) + .child(store.name(&call.peer)), + ) + .child(div().text_size(px(13.)).text_color(c(0xb2b2b2)).child( + if call.video_offered { t::call_incoming_video() } else { t::call_incoming() }, + )) + .child( + div() + .flex() + .gap(px(40.)) + .mt(px(18.)) + .child( + round_btn("call-decline", 60.) + .tip(t::call_decline()) + .bg(c(DANGER)) + .on_click(move |_, w, cx| decline(Act::Reject, w, cx)) + .child(phone(28., c(0xffffff), true)), + ) + .child(pulse), + ), + ) + .into_any_element() +} + +fn ease_in_out(t: f32) -> f32 { + let t = t.clamp(0., 1.); + t * t * (3. - 2. * t) +} + +fn section(title: SharedString) -> impl IntoElement { + div() + .mt(px(6.)) + .pt(px(10.)) + .border_t_1() + .border_color(c(0x262626)) + .text_size(px(11.)) + .font_weight(gpui::FontWeight::SEMIBOLD) + .text_color(c(ACCENT)) + .child(title.to_uppercase()) +} + +pub(crate) fn label(text: impl Into) -> impl IntoElement { + div() + .w(px(84.)) + .flex_shrink_0() + .text_size(px(12.5)) + .text_color(white_a(0.8)) + .child(text.into()) +} + +fn value(text: impl Into) -> gpui::Div { + let text = text.into(); + div() + .flex() + .items_center() + .gap(px(5.)) + .text_size(px(13.)) + .font_weight(gpui::FontWeight::MEDIUM) + .text_color(c(0xffffff)) + .when(!text.is_empty(), |d| d.child(text)) +} + +pub(crate) fn hint(text: impl Into) -> impl IntoElement { + div() + .text_size(px(11.)) + .font_weight(gpui::FontWeight::NORMAL) + .text_color(c(0x8a8a8a)) + .child(text.into()) +} + +pub(crate) fn dot(q: Quality) -> impl IntoElement { + div() + .size(px(7.)) + .flex_shrink_0() + .rounded_full() + .bg(q.color()) +} + +/// The neon toggle at the panel's 0.8 scale. +fn switch( + id: &'static str, + label_text: SharedString, + on_state: bool, + which: Switch, + on: &OnAct, +) -> impl IntoElement { + div() + .flex() + .items_center() + .justify_between() + .py(px(2.)) + .text_size(px(12.5)) + .text_color(c(0xf6f6f6)) + .child(label_text) + .child(toggle(id, on_state, Act::Audio(which, !on_state), on)) +} + +/// The neon toggle itself; a tap sends `act`. +pub(crate) fn toggle(id: &'static str, on_state: bool, act: Act, on: &OnAct) -> impl IntoElement { + let o = on.clone(); + div() + .id(id) + .relative() + .flex_shrink_0() + .w(px(40.)) + .h(px(19.2)) + .rounded(px(9.6)) + .cursor_pointer() + .bg(if on_state { + gpui::linear_gradient( + 90., + gpui::linear_color_stop(c(0x33db98), 0.), + gpui::linear_color_stop(c(0x00ff9d), 1.), + ) + } else { + c(0x1a1a1a).into() + }) + .on_click(move |_, w, cx| o(act.clone(), w, cx)) + .child( + div() + .absolute() + .top(px(1.6)) + .left(px(if on_state { 22.4 } else { 1.6 })) + .size(px(16.)) + .rounded_full() + .bg(if on_state { c(0xffffff) } else { c(0x333333) }), + ) +} + +/// `VoiceMeter`: the gradient spans the track, the level uncovers as much as it reaches. +fn meter(level: f32, active: bool) -> impl IntoElement { + let level = level.clamp(0., 1.); + div() + .flex_1() + .h(px(8.)) + .rounded(px(4.)) + .bg(c(0x1a1a1a)) + .overflow_hidden() + .child( + div() + .h_full() + .w(gpui::relative(level)) + .overflow_hidden() + .rounded(px(4.)) + .child( + div() + .h_full() + .w(gpui::relative(if level > 0. { 1. / level } else { 0. })) + .flex() + .when(!active, |d| d.opacity(0.35)) + .child( + div() + .h_full() + .w(gpui::relative(0.8)) + .bg(gpui::linear_gradient( + 90., + gpui::linear_color_stop(c(0x6ed99e), 0.), + gpui::linear_color_stop(c(0xf7e470), 1.), + )), + ) + .child(div().h_full().flex_1().bg(gpui::linear_gradient( + 90., + gpui::linear_color_stop(c(0xf7e470), 0.), + gpui::linear_color_stop(c(0xea6662), 1.), + ))), + ), + ) +} + +/// Their volume, 0 to 200%: an 8px track, the accent to the value, a 14px thumb. +fn volume_slider(call: &Call, on: &OnAct) -> impl IntoElement { + slider("call-volume", t::call_their_volume(), call.volume, call.slider.clone(), call.sliding.clone(), Act::Volume, on) +} + +/// The sound of their shared screen, 0 to 200%, while it comes with the share. +fn share_slider(call: &Call, on: &OnAct) -> impl IntoElement { + slider("call-share-volume", t::call_their_screen(), call.share_volume, call.share_slider.clone(), call.share_sliding.clone(), Act::ShareVolume, on) +} + +fn slider( + id: &'static str, + name: gpui::SharedString, + volume: f32, + bounds: Rc>>>, + dragging: Rc>, + act: fn(f32) -> Act, + on: &OnAct, +) -> impl IntoElement { + let pct = (volume / 2.).clamp(0., 1.); + let at = |b: Bounds, x: Pixels| { + let v = crate::kit::track_frac(b, x, px(0.)) * 200.; + (v / 5.).round() * 5. / 100. + }; + let down = { + let (on, bounds, dragging) = (on.clone(), bounds.clone(), dragging.clone()); + move |e: &gpui::MouseDownEvent, w: &mut Window, cx: &mut App| { + cx.stop_propagation(); + let Some(b) = bounds.get() else { return }; + dragging.set(true); + on(act(at(b, e.position.x)), w, cx); + } + }; + let track = { + let (on, bounds, dragging) = (on.clone(), bounds.clone(), dragging.clone()); + let record = bounds.clone(); + canvas( + move |b, _, _| record.set(Some(b)), + move |_, _, window, _| { + if !dragging.get() { + return; + } + let (on, bounds, d) = (on.clone(), bounds.clone(), dragging.clone()); + window.on_mouse_event(move |e: &gpui::MouseMoveEvent, phase, w, cx| { + if phase != gpui::DispatchPhase::Bubble || !d.get() { + return; + } + if !e.dragging() { + d.set(false); + return; + } + if let Some(b) = bounds.get() { + on(act(at(b, e.position.x)), w, cx); + } + }); + let d = dragging.clone(); + window.on_mouse_event(move |_: &gpui::MouseUpEvent, _, _, _| d.set(false)); + }, + ) + .absolute() + .inset_0() + }; + div() + .flex() + .items_center() + .gap(px(10.)) + .pt(px(8.)) + .child(label(name.clone())) + .child( + div() + .id(id) + .as_slider(name, t::percent((volume * 100.).round()), pct) + .slider_keys(pct, 0.025, { + let on = on.clone(); + move |f, w, cx| on(act((f * 40.).round() / 20.), w, cx) + }) + .relative() + .flex_1() + .min_w_0() + .h(px(16.)) + .cursor_pointer() + .on_mouse_down(gpui::MouseButton::Left, down) + .child(track) + .child( + div() + .absolute() + .left_0() + .right_0() + .top(px(4.)) + .h(px(8.)) + .rounded(px(4.)) + .bg(white_a(0.1)) + .child( + div() + .h_full() + .rounded_l(px(4.)) + .bg(c(ACCENT)) + .w(gpui::relative(pct)), + ), + ) + .child( + div() + .absolute() + .top(px(1.)) + .left(gpui::relative(pct)) + .child( + div() + .ml(px(-14. * pct)) + .size(px(14.)) + .rounded_full() + .bg(c(0xffffff)) + .shadow(vec![BoxShadow { + color: ca(0, 0, 0, 0.3), + offset: point(px(0.), px(1.)), + blur_radius: px(4.), + spread_radius: px(0.), + inset: false, + }]), + ), + ), + ) + .child( + value(format!("{}%", (volume * 100.).round() as i32)) + .w(px(40.)) + .flex_shrink_0() + .justify_end(), + ) +} + +const GRAPH_H: f32 = 72.; +const GRAPH_HEAD: f32 = 34.; + +/// Delay as a line, lost audio as bars, over the last minute; the sample under the pointer reads out. +fn graph(call: &Call, on: &OnAct) -> AnyElement { + let hist: Vec = call.history.iter().copied().collect(); + if hist.len() < 2 { + return div() + .h(px(GRAPH_H)) + .rounded(px(8.)) + .bg(white_a(0.04)) + .flex() + .items_center() + .justify_center() + .text_size(px(11.5)) + .text_color(c(0x8a8a8a)) + .child(t::call_graph_measuring()) + .into_any_element(); + } + let max_rtt = hist.iter().map(|r| r.rtt).fold(200f32, f32::max); + let hover = call.hover.filter(|i| *i < hist.len()); + let n = 60usize; + let off = n - hist.len(); + let record = call.graph.clone(); + let samples = hist.clone(); + let plot = canvas( + move |b, _, _| record.set(Some(b)), + move |b, _, window, _| { + let w = f32::from(b.size.width); + let step = w / (n - 1) as f32; + let at = |i: usize, r: &Sample| { + let x = (off + i) as f32 * step; + let y = GRAPH_H - 2. - (r.rtt / max_rtt) * (GRAPH_H - GRAPH_HEAD - 6.); + (x, y) + }; + let mut lost = c(0xfca559); + lost.a = 0.85; + for (i, r) in samples.iter().enumerate() { + let hgt = + ((r.lost / 10.) * (GRAPH_H - GRAPH_HEAD - 4.)).min(GRAPH_H - GRAPH_HEAD - 4.); + if hgt <= 0.5 { + continue; + } + let (x, _) = at(i, r); + let bw = (step - 0.5).max(1.5); + window.paint_quad(gpui::fill( + Bounds::new( + b.origin + point(px(x - step / 2.), px(GRAPH_H - 2. - hgt)), + gpui::size(px(bw), px(hgt)), + ), + lost, + )); + } + let mut path = gpui::PathBuilder::stroke(px(1.5)); + for (i, r) in samples.iter().enumerate() { + let (x, y) = at(i, r); + let p = b.origin + point(px(x), px(y)); + if i == 0 { + path.move_to(p) + } else { + path.line_to(p) + } + } + if let Ok(p) = path.build() { + window.paint_path(p, c(ACCENT)); + } + if let Some(i) = hover { + let (x, y) = at(i, &samples[i]); + window.paint_quad( + gpui::fill( + Bounds::new( + b.origin + point(px(x - 3.), px(y - 3.)), + gpui::size(px(6.), px(6.)), + ), + c(0xffffff), + ) + .corner_radii(px(3.)), + ); + } + }, + ) + .size_full(); + let pick = { + let (on, bounds) = (on.clone(), call.graph.clone()); + let len = hist.len(); + move |e: &gpui::MouseMoveEvent, w: &mut Window, cx: &mut App| { + let Some(b) = bounds.get() else { return }; + let step = f32::from(b.size.width) / (n - 1) as f32; + let x = f32::from(e.position.x - b.origin.x); + let i = + ((x / step).round() as isize - off as isize).clamp(0, len as isize - 1) as usize; + on(Act::Hover(Some(i)), w, cx); + } + }; + let leave = { + let on = on.clone(); + move |hovered: &bool, w: &mut Window, cx: &mut App| { + if !*hovered { + on(Act::Hover(None), w, cx); + } + } + }; + let readout = |i: usize| { + let r = hist[i]; + let ago = hist.len() - 1 - i; + div() + .flex() + .gap(px(3.)) + .child( + div() + .font_weight(gpui::FontWeight::SEMIBOLD) + .text_color(c(ACCENT)) + .child(t::call_delay_ms(r.rtt as u32)), + ) + .child(format!( + "· {} · {}", + lost_word(r.lost), + if ago == 0 { t::call_graph_now() } else { t::call_graph_ago(ago) } + )) + }; + let legend = match hover { + Some(i) => div() + .text_size(px(11.5)) + .text_color(c(0xf6f6f6)) + .child(readout(i)) + .into_any_element(), + None => div() + .flex() + .justify_between() + .w_full() + .child( + div() + .flex() + .items_center() + .gap(px(5.)) + .child(div().w(px(10.)).h(px(3.)).rounded(px(2.)).bg(c(ACCENT))) + .child(t::call_graph_delay(max_rtt as u32)), + ) + .child( + div() + .flex() + .items_center() + .gap(px(5.)) + .child(div().w(px(10.)).h(px(7.)).rounded(px(2.)).bg(c(0xfca559))) + .child(t::call_graph_lost()), + ) + .into_any_element(), + }; + div() + .flex() + .flex_col() + .gap(px(4.)) + .child( + div() + .id("call-graph") + .relative() + .h(px(GRAPH_H)) + .rounded(px(8.)) + .bg(white_a(0.04)) + .on_mouse_move(pick) + .on_hover(leave) + .child(plot), + ) + .child( + div() + .flex() + .min_h(px(14.)) + .text_size(px(10.5)) + .text_color(c(0x8a8a8a)) + .child(legend), + ) + .into_any_element() +} + +fn panel(call: &Call, proc_: &Processing, seen: &Seen, on: &OnAct) -> impl IntoElement { + let live = call.live(); + let stats = call.stats.as_ref(); + let lost = call.lost_pct(); + let lost_text = if lost < 0.05 { + t::call_lost_none() + } else if lost < 1. { + t::call_lost_under_one() + } else { + t::percent(shown_pct(lost)) + }; + let path = match stats.map(|s| s.path.as_str()) { + Some("relay") => t::call_via_relay(), + Some("direct") => t::call_direct(), + _ => SharedString::default(), + }; + let bitrate = stats.map(|s| s.bitrate_kbps).filter(|b| *b > 0); + let bitrate_hint = match (stats.map(|s| s.net_loss).unwrap_or(0.), bitrate) { + (l, _) if l >= 4. => t::call_bitrate_lowered(), + (_, Some(b)) if b >= 64 => t::call_bitrate_full(), + _ => SharedString::default(), + }; + let row = |id: &'static str, l: SharedString, tip: Option, v: AnyElement| { + div() + .flex() + .items_center() + .child(div().id(id).when_some(tip, |d, t| d.tip(t)).child(label(l))) + .child(v) + }; + div() + .id("call-panel") + .flex() + .flex_col() + .gap(px(10.)) + .pt(px(6.)) + .px(px(14.)) + .pb(px(14.)) + .cursor_default() + .on_mouse_down(gpui::MouseButton::Left, |_, _, cx| cx.stop_propagation()) + .child(volume_slider(call, on)) + .when(call.share_audio_peer, |d| d.child(share_slider(call, on))) + .when(!call.muted && !call.mic_off, |d| { + d.child( + div() + .flex() + .items_center() + .child(label(t::call_your_voice())) + .child(meter(call.levels.0, live)), + ) + }) + .children(crate::callpics::panel_blocks(call, on)) + .child(section(t::call_processing())) + .child( + div() + .flex() + .flex_col() + .gap(px(6.)) + .child(switch( + "call-agc", + t::call_auto_gain(), + proc_.auto_gain, + Switch::AutoGain, + on, + )) + .child(switch( + "call-aec", + t::call_echo_cancel(), + proc_.echo_cancel, + Switch::EchoCancel, + on, + )) + .child(switch( + "call-ns", + t::call_noise_suppress(), + proc_.noise_suppress, + Switch::NoiseSuppress, + on, + )), + ) + .child(section(t::call_connection())) + .child( + div() + .flex() + .flex_col() + .gap(px(6.)) + .child(row( + "call-row-quality", + t::call_quality(), + None, + match call.quality { + Some(q) => value("").child(dot(q)).child(q.label()).into_any_element(), + None => value(t::call_measuring()).into_any_element(), + }, + )) + .child(row( + "call-row-delay", + t::call_delay(), + None, + value(stats.map(|s| t::call_delay_ms(s.rtt_ms)).unwrap_or_else(|| "…".into())) + .when(!path.is_empty(), |d| d.child(hint(path))) + .into_any_element(), + )) + .child(row("call-row-lost", t::call_lost(), Some(t::call_lost_tip()), value(lost_text).into_any_element())) + .child(row( + "call-row-bitrate", + t::call_bitrate(), + Some(t::call_bitrate_tip()), + value(bitrate.map(|b| t::call_bitrate_kbps(b)).unwrap_or_else(|| "…".into())) + .when(!bitrate_hint.is_empty(), |d| d.child(hint(bitrate_hint))) + .into_any_element(), + )) + .children(crate::callpics::peer_lines(call, seen)), + ) + .child(graph(call, on)) +} + +/// The pill: its row drags or, tapped, opens the panel. +fn pill(call: &Call, store: &Store, proc_: &Processing, seen: &Seen, win: gpui::Size, top: f32, on: &OnAct) -> AnyElement { + let live = call.live(); + let ended = call.phase == Some(Phase::Ended); + let talk = if live && !call.peer_muted { + ((call.levels.1 - 0.3) / 0.55).clamp(0., 1.) + } else { + 0. + }; + let ring = vec![ + BoxShadow { + color: accent_mix(0.12 + talk * 0.88), + offset: point(px(0.), px(0.)), + blur_radius: px(0.), + spread_radius: px(2.), + inset: false, + }, + BoxShadow { + color: accent_mix(talk * 0.7), + offset: point(px(0.), px(0.)), + blur_radius: px(talk * 12.), + spread_radius: px(0.), + inset: false, + }, + ]; + let status = div() + .flex() + .items_center() + .gap(px(5.)) + .h(px(13.2)) + .text_size(px(11.5)) + .line_height(px(13.2)) + .text_color(c(0xb2b2b2)) + .when_some(call.quality.filter(|_| live), |d, q| d.child(div().id("call-pill-quality").tip(q.label()).child(dot(q)))) + .child(div().truncate().child(if live && call.peer_muted { + t::call_status_muted(call.status()) + } else { + call.status().into() + })); + let drag = call.drag.clone(); + let bounds = call.pill.clone(); + let down = move |e: &gpui::MouseDownEvent, _: &mut Window, _: &mut App| { + if let Some(b) = bounds.get() { + drag.set(Some(Drag { + start: e.position, + origin: b.origin, + moved: false, + })); + } + }; + let watch = { + let (drag, record, on) = (call.drag.clone(), call.pill.clone(), on.clone()); + canvas( + move |b, _, _| record.set(Some(b)), + move |_, _, window, _| { + if drag.get().is_none() { + return; + } + let (d, o) = (drag.clone(), on.clone()); + window.on_mouse_event(move |e: &gpui::MouseMoveEvent, phase, w, cx| { + let Some(mut g) = d.get() else { return }; + if phase != gpui::DispatchPhase::Bubble { + return; + } + let delta = e.position - g.start; + if !g.moved && f32::from(delta.x).hypot(f32::from(delta.y)) < 4. { + return; + } + g.moved = true; + d.set(Some(g)); + o(Act::Move(g.origin + delta), w, cx); + }); + let (d, o) = (drag.clone(), on.clone()); + window.on_mouse_event(move |_: &gpui::MouseUpEvent, phase, w, cx| { + if phase != gpui::DispatchPhase::Bubble { + return; + } + if let Some(g) = d.take() { + o(if g.moved { Act::Moved } else { Act::Toggle }, w, cx); + } + }); + }, + ) + .absolute() + .inset_0() + }; + let row = div() + .id("call-pill-row") + .tip(t::call_open_channel()) + .relative() + .flex() + .items_center() + .gap(px(8.)) + .pt(px(6.)) + .pb(px(6.)) + .pl(px(6.)) + .pr(px(8.)) + .bg(c(0x262626)) + .rounded_t(px(15.)) + .when(!call.expanded, |d| d.rounded_b(px(15.))) + .cursor_grab() + .when(call.expanded, |d| d.border_b_1().border_color(c(0x333333))) + .on_mouse_down(gpui::MouseButton::Left, down) + .child( + div() + .flex() + .flex_shrink_0() + .rounded_full() + .shadow(ring) + .child(crate::ui::avatar(store, &call.peer, 30.)), + ) + .child( + div() + .flex() + .flex_col() + .flex_1() + .min_w_0() + .child( + div() + .truncate() + .text_size(px(13.)) + .line_height(px(15.)) + .font_weight(gpui::FontWeight::SEMIBOLD) + .text_color(c(0xf6f6f6)) + .child(store.name(&call.peer)), + ) + .child(status), + ) + .when(!ended, |d| d.children(crate::callpics::buttons(call, seen, on)).children(route_btn("call-route", on)).child(mic_btn(call, on)).child(hangup_btn(on))); + let pictures = crate::callpics::showing(call); + let wide = (f32::from(win.width) - 24.).min(480.); + let body = div() + .id("call-pill") + .relative() + .flex() + .flex_col() + .when(pictures, |d| d.w(px(wide + 2.))) + .when(!pictures && call.expanded, |d| d.w(px(OPEN_W))) + .when(!pictures && !call.expanded, |d| d.max_w(px(PILL_MAX_W))) + .rounded(px(16.)) + .bg(ca(20, 20, 20, 0.95)) + .border_1() + .border_color(c(0x333333)) + .shadow(vec![BoxShadow { + color: ca(0, 0, 0, 0.4), + offset: point(px(0.), px(8.)), + blur_radius: px(32.), + spread_radius: px(0.), + inset: false, + }]) + .overflow_hidden() + .occlude() + .when(ended, |d| d.opacity(0.7)) + .child(watch) + .child(row) + .when(pictures && crate::callpics::max_open(call).is_none(), |d| { + let max_h = (f32::from(win.height) * 0.5).min(420.); + d.child(crate::callpics::pictures(call, store, seen, wide, max_h, on)) + }) + .when(call.expanded && !ended, |d| d.child(panel(call, proc_, seen, on))); + match call.pos { + Some(p) => div() + .absolute() + .left(p.x) + .top(p.y) + .child(body) + .into_any_element(), + None => div() + .absolute() + .top(px(top)) + .left_0() + .right_0() + .flex() + .justify_center() + .child(body) + .into_any_element(), + } +} + +/// Kept on screen for a pill of `size`: off the chrome strip and 8px from every edge. +pub fn clamp( + p: Point, + size: gpui::Size, + window: gpui::Size, + chrome: f32, +) -> Point { + let top = chrome + 8.; + let x = f32::from(p.x) + .min(f32::from(window.width - size.width) - 8.) + .max(8.); + let y = f32::from(p.y) + .min(f32::from(window.height - size.height) - 8.) + .max(top); + point(px(x), px(y)) +} + +impl Call { + pub fn at(pos: Option>) -> Self { + Self { + pos, + ..Default::default() + } + } + + pub fn pill_size(&self) -> gpui::Size { + self.pill + .get() + .map(|b| b.size) + .unwrap_or(gpui::size(px(PILL_MAX_W), px(48.))) + } +} + +/// The overlay for the call in progress, if there is one. +pub fn render( + call: &Call, + store: &Store, + proc_: &Processing, + seen: &Seen, + win: gpui::Size, + chrome: f32, + on: &OnAct, +) -> Option { + call.id.as_ref()?; + call.phase?; + Some(if call.incoming() { + gpui::deferred(ring(call, store, on)) + .with_priority(15) + .into_any_element() + } else if let Some(max) = crate::callpics::maximized(call, seen, chrome, mic_btn(call, on).into_any_element(), hangup_btn(on).into_any_element(), on) { + gpui::deferred(div().absolute().inset_0().child(max)).with_priority(7).into_any_element() + } else { + gpui::deferred( + div() + .absolute() + .inset_0() + .child(pill(call, store, proc_, seen, win, chrome + 10., on)), + ) + .with_priority(7) + .into_any_element() + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn clock_reads_like_the_desktop() { + assert_eq!(clock(0), "00:00"); + assert_eq!(clock(65_000), "01:05"); + assert_eq!(clock(3_725_000), "1:02:05"); + } + + #[test] + fn lost_audio_is_concealed_over_received() { + let mut call = Call::default(); + call.apply_state(&serde_json::json!({ "id": "a", "peer": "p", "phase": "active" })); + call.apply_stats( + &serde_json::json!({ "id": "a", "rtt_ms": 40, "received": 100, "concealed": 0 }), + ); + call.apply_stats( + &serde_json::json!({ "id": "a", "rtt_ms": 40, "received": 150, "concealed": 5 }), + ); + assert!((call.history.back().unwrap().lost - 10.).abs() < 1e-4); + assert_eq!(call.quality, Some(Quality::Poor)); + call.apply_stats(&serde_json::json!({ "id": "other", "rtt_ms": 900 })); + assert_eq!(call.history.len(), 2); + } +} diff --git a/crates/vector-gpui/src/callpics.rs b/crates/vector-gpui/src/callpics.rs new file mode 100644 index 000000000..4e45e7626 --- /dev/null +++ b/crates/vector-gpui/src/callpics.rs @@ -0,0 +1,500 @@ +//! The video half of `CallOverlay.svelte`: their pictures with ours in a corner, one of theirs +//! filling the window, and each of our pictures' quality controls in the panel. + +use crate::kit::Tipped as _; +use std::time::Instant; + +use gpui::{AnyElement, InteractiveElement, SharedString, IntoElement, ObjectFit, ParentElement, StatefulInteractiveElement, Styled, StyledImage, div, prelude::FluentBuilder, px, svg}; +use crate::pic::img; + +use crate::call::{Act, Call, OnAct, Quality, Seen, call_btn, dot, label, toggle}; +use crate::data::Store; +use crate::t; +use crate::theme::{ACCENT, c, ca, white_a}; + +type Label = fn() -> SharedString; + +const QUALITY: [&[(Label, u32)]; 2] = [ + &[(t::call_rung_low, 1), (t::call_rung_medium, 3), (t::call_rung_high, 5), (t::call_rung_best, 6)], + &[(t::call_rung_low, 1), (t::call_rung_medium, 3), (t::call_rung_high, 5), (t::call_rung_best, 7), (t::call_rung_ultra, 8)], +]; +const FPS: [&[u32]; 2] = [&[15, 30], &[5, 10, 15, 30, 60]]; +const BLOCK_TITLE: [Label; 2] = [t::call_camera_quality, t::call_screen_quality]; +const WAITING: [Label; 2] = [t::call_waiting_camera, t::call_waiting_screen]; + +pub fn showing(call: &Call) -> bool { + call.live() && call.video_mine.iter().chain(call.video_peer.iter()).any(|&b| b) +} + +/// Of their pictures the screen leads and the camera sits inset; alone, either leads. +fn lead(call: &Call) -> Option { + if call.video_peer[1] { + Some(1) + } else if call.video_peer[0] { + Some(0) + } else { + None + } +} + +pub fn max_open(call: &Call) -> Option { + call.maximized.filter(|&k| call.live() && call.video_peer[k]) +} + +fn picture(seen: &Seen, k: usize, fit: ObjectFit) -> Option { + seen.peer[k].as_ref().map(|(image, _, _)| img(image.clone()).absolute().inset_0().size_full().object_fit(fit).into_any_element()) +} + +fn video_btn(id: &'static str, k: usize, call: &Call, enabled: bool, on: &OnAct) -> impl IntoElement { + let state = call.video_mine[k]; + let o = on.clone(); + call_btn(id, state) + .tip(match (k, state) { + (0, true) => t::call_camera_off(), + (0, false) => t::call_camera_on(), + (_, true) => t::call_screen_stop(), + (_, false) => t::call_screen_share(), + }) + .when(!enabled, |d| d.opacity(0.35).cursor_default()) + .on_mouse_down(gpui::MouseButton::Left, |_, _, cx| cx.stop_propagation()) + .when(enabled, |d| d.on_click(move |_, w, cx| o(Act::Video(k, !state), w, cx))) + .child(if k == 0 { + svg().path("icons/video.svg").size(px(18.7)).text_color(if state { c(ACCENT) } else { white_a(0.88) }) + } else { + svg().path("ui/call-screen.svg").size(px(20.)).text_color(if state { c(ACCENT) } else { white_a(0.88) }) + }) +} + +/// The camera and screen buttons, in the pill's row while the call can carry video. +pub fn buttons(call: &Call, seen: &Seen, on: &OnAct) -> Vec { + if !call.live() || !seen.can_send { + return Vec::new(); + } + vec![ + video_btn("call-camera", 0, call, true, on).into_any_element(), + video_btn("call-screen", 1, call, true, on).into_any_element(), + ] +} + +fn small_btn(id: &'static str, icon: &'static str) -> gpui::Stateful { + div() + .id(id) + .absolute() + .size(px(34.)) + .rounded_full() + .flex() + .items_center() + .justify_center() + .bg(ca(0, 0, 0, 0.55)) + .text_color(white_a(0.88)) + .hover(|d| d.bg(white_a(0.14)).text_color(c(0xffffff))) + .cursor_pointer() + .on_mouse_down(gpui::MouseButton::Left, |_, _, cx| cx.stop_propagation()) + .child(svg().path(icon).size(px(20.)).text_color(white_a(0.88))) +} + +fn mine(call: &Call, seen: &Seen, k: usize) -> AnyElement { + let (w, h) = if k == 1 { (112., 70.75) } else { (112., 84.5) }; + let unseen = call.paused_by_peer; + div() + .relative() + .w(px(w)) + .h(px(h)) + .flex_none() + .rounded(px(8.)) + .border_1() + .border_color(c(0x444444)) + .bg(c(0x111111)) + .overflow_hidden() + .children(seen.mine[k].as_ref().map(|image| { + img(image.clone()) + .size_full() + .object_fit(if k == 1 { ObjectFit::Contain } else { ObjectFit::Cover }) + .grayscale(unseen) + .opacity(if unseen { 0.45 } else { 1. }) + })) + .when(unseen, |d| { + d.child(svg().path("icons/eye-off.svg").absolute().top(px(6.)).right(px(6.)).size(px(18.)).text_color(white_a(0.9))) + }) + .into_any_element() +} + +/// Their pictures above the panel, ours in the bottom corner. +pub fn pictures(call: &Call, store: &Store, seen: &Seen, w: f32, max_h: f32, on: &OnAct) -> AnyElement { + let lead = lead(call); + let inset = (call.video_peer[0] && call.video_peer[1]).then_some(0); + let aspect = lead + .and_then(|k| seen.peer[k].as_ref()) + .map(|(_, pw, ph)| *pw as f32 / (*ph).max(1) as f32) + .unwrap_or(16. / 9.); + let h = (w / aspect).min(max_h).round(); + let idle = |d: gpui::Div| { + d.absolute() + .inset_0() + .flex() + .flex_col() + .items_center() + .justify_center() + .gap(px(10.)) + .text_size(px(13.)) + .text_color(c(0xb2b2b2)) + }; + let name = store.name(&call.peer); + div() + .id("call-pictures") + .relative() + .w(px(w)) + .h(px(h)) + .flex_none() + .bg(c(0x000000)) + .overflow_hidden() + .cursor_default() + .on_mouse_down(gpui::MouseButton::Left, |_, _, cx| cx.stop_propagation()) + .map(|d| match lead { + Some(k) => { + let o = on.clone(); + d.children(picture(seen, k, ObjectFit::Contain)) + .when(seen.peer[k].is_none(), |d| d.child(idle(div()).child(WAITING[k]()))) + .child(small_btn("call-picture-max", "ui/call-max.svg").tip(t::call_fill_window()).top(px(8.)).right(px(8.)).on_click(move |_, w, cx| o(Act::Maximize(Some(k)), w, cx))) + .when(k == 1, |d| { + d.child( + div() + .absolute() + .top(px(8.)) + .left(px(8.)) + .px(px(8.)) + .py(px(3.)) + .rounded_full() + .bg(ca(0, 0, 0, 0.55)) + .text_size(px(11.)) + .line_height(px(24.)) + .text_color(c(0xdddddd)) + .child(t::call_sharing_screen(&name)), + ) + }) + } + None => d.child(idle(div()).child(crate::ui::avatar(store, &call.peer, 64.)).child(t::call_their_camera_off())), + }) + .children(inset.map(|k| { + let iw = (w * 0.26).min(150.); + let o = on.clone(); + div() + .id("call-picture-inset") + .tip(t::call_fill_with_camera()) + .absolute() + .bottom(px(8.)) + .left(px(8.)) + .w(px(iw)) + .h(px(((iw - 2.) * 0.75 + 2.).round())) + .rounded(px(8.)) + .border_1() + .border_color(c(0x444444)) + .bg(c(0x111111)) + .overflow_hidden() + .cursor_pointer() + .on_click(move |_, w, cx| o(Act::Maximize(Some(k)), w, cx)) + .children(picture(seen, k, ObjectFit::Cover)) + })) + .child( + div() + .absolute() + .bottom(px(8.)) + .right(px(8.)) + .flex() + .flex_row_reverse() + .gap(px(6.)) + .when(call.video_mine[1], |d| d.child(mine(call, seen, 1))) + .when(call.video_mine[0], |d| d.child(mine(call, seen, 0))), + ) + .into_any_element() +} + +/// One of their pictures over everything; their other one rides along the bottom. +pub fn maximized(call: &Call, seen: &Seen, chrome: f32, mic: AnyElement, hangup: AnyElement, on: &OnAct) -> Option { + let k = max_open(call)?; + let other = 1 - k; + let other = call.video_peer[other].then_some(other); + let controls = call.max_controls.is_some_and(|t| t > Instant::now()); + let quality = call.quality().filter(|q| matches!(q, Quality::Fair | Quality::Poor)); + let (wake, back, swap) = (on.clone(), on.clone(), on.clone()); + let restore = on.clone(); + let strip = div() + .absolute() + .bottom(px(16.)) + .left_0() + .right_0() + .flex() + .justify_center() + .child( + div() + .id("call-max-strip") + .flex() + .gap(px(10.)) + .px(px(12.)) + .py(px(8.)) + .rounded_full() + .bg(ca(20, 20, 20, 0.85)) + .border_1() + .border_color(c(0x333333)) + .when(!controls, |d| d.opacity(0.)) + .child(video_btn("call-max-camera", 0, call, seen.can_send, on)) + .child(video_btn("call-max-screen", 1, call, seen.can_send, on)) + .child(mic) + .child(hangup), + ); + Some( + div() + .id("call-max") + .absolute() + .top(px(chrome)) + .left_0() + .right_0() + .bottom_0() + .bg(c(0x000000)) + .occlude() + .on_mouse_move(move |_, w, cx| wake(Act::WakeControls, w, cx)) + .on_click(move |e, w, cx| { + if e.click_count() == 2 { + back(Act::Maximize(None), w, cx); + } + }) + .children(picture(seen, k, ObjectFit::Contain)) + .children(quality.map(|q| { + div() + .absolute() + .top(px(12.)) + .left(px(12.)) + .flex() + .items_center() + .gap(px(6.)) + .px(px(10.)) + .py(px(4.)) + .rounded_full() + .bg(ca(0, 0, 0, 0.6)) + .text_size(px(12.)) + .text_color(c(0xdddddd)) + .child(dot(q)) + .child(q.label()) + })) + .child( + div() + .id("call-max-restore") + .tip(t::call_restore()) + .absolute() + .top(px(12.)) + .right(px(12.)) + .size(px(32.)) + .p(px(6.)) + .rounded(px(8.)) + .bg(ca(0, 0, 0, 0.85)) + .cursor_pointer() + .when(!controls, |d| d.opacity(0.)) + .on_click(move |_, w, cx| restore(Act::Maximize(None), w, cx)) + .child(svg().path("ui/call-restore.svg").size_full().text_color(c(0xffffff))), + ) + .children(other.map(|o| { + div().absolute().bottom(px(if controls { 72. } else { 16. })).left_0().right_0().flex().justify_center().child( + div() + .id("call-max-other") + .tip(t::call_swap()) + .w(px(320.)) + .h(px(201.)) + .rounded(px(10.)) + .border_1() + .border_color(c(0x555555)) + .bg(c(0x111111)) + .overflow_hidden() + .cursor_pointer() + .on_click(move |_, w, cx| swap(Act::Maximize(Some(o)), w, cx)) + .children(picture(seen, o, ObjectFit::Contain)), + ) + })) + .child(strip) + .into_any_element(), + ) +} + +fn compact_select(id: (&'static str, usize), label_text: String, open: bool, choices: Vec<(String, Option)>, field: (usize, bool), on: &OnAct) -> AnyElement { + let (o, p) = (on.clone(), on.clone()); + div() + .relative() + .child( + div() + .id(gpui::ElementId::NamedInteger(id.0.into(), id.1 as u64)) + .flex() + .items_center() + .justify_between() + .gap(px(6.)) + .h(px(22.)) + .min_w(px(96.)) + .px(px(6.)) + .py(px(3.)) + .rounded(px(6.)) + .border_1() + .border_color(c(0x333333)) + .bg(c(0x262626)) + .text_size(px(12.)) + .line_height(px(14.4)) + .text_color(c(0xffffff)) + .cursor_pointer() + .on_click(move |_, w, cx| o(Act::PrefOpen(if open { None } else { Some(field) }), w, cx)) + .child(label_text) + .child(svg().path("ui/caret-down.svg").w(px(8.)).h(px(5.)).text_color(c(0xaaaaaa))), + ) + .when(open, |d| { + d.child( + gpui::deferred( + div() + .absolute() + .top(px(24.)) + .left_0() + .min_w(px(96.)) + .py(px(4.)) + .rounded(px(6.)) + .border_1() + .border_color(c(0x333333)) + .bg(c(0x262626)) + .occlude() + .children(choices.into_iter().enumerate().map(|(i, (text, v))| { + let p = p.clone(); + div() + .id(i) + .px(px(8.)) + .py(px(4.)) + .text_size(px(12.)) + .text_color(c(0xffffff)) + .cursor_pointer() + .hover(|d| d.bg(c(0x333333))) + .on_click(move |_, w, cx| p(Act::Pref(field.0, field.1, v), w, cx)) + .child(text) + })), + ) + .with_priority(20), + ) + }) + .into_any_element() +} + +/// Our pictures' quality blocks in the panel, each while it is on. +pub fn panel_blocks(call: &Call, on: &OnAct) -> Vec { + (0..2) + .filter(|&k| call.live() && call.video_mine[k]) + .map(|k| { + let note = call + .video_stats(k) + .filter(|s| s.0 > 0) + .map(|(w, h, fps, kbps)| t::call_video_stats(fps, kbps, format!("{w}×{h}"))) + .unwrap_or_default(); + let (rung, fps) = call.prefs[k]; + let mut q: Vec<(String, Option)> = vec![(t::call_adaptive().into(), None)]; + q.extend(QUALITY[k].iter().map(|(l, r)| (l().into(), Some(*r)))); + let q_label = q.iter().find(|(_, v)| *v == rung).map(|(l, _)| l.clone()).unwrap_or_else(|| t::call_adaptive().into()); + let mut f: Vec<(String, Option)> = vec![(t::call_adaptive().into(), None)]; + f.extend(FPS[k].iter().map(|r| (t::call_fps(*r).into(), Some(*r)))); + let f_label = f.iter().find(|(_, v)| *v == fps).map(|(l, _)| l.clone()).unwrap_or_else(|| t::call_adaptive().into()); + let row = |l: SharedString, v: AnyElement| div().flex().items_center().child(label(l)).child(v); + div() + .flex() + .flex_col() + .gap(px(10.)) + .child( + div() + .mt(px(6.)) + .pt(px(10.)) + .border_t_1() + .border_color(c(0x262626)) + .flex() + .items_baseline() + .justify_between() + .gap(px(8.)) + .text_size(px(11.)) + .child(div().font_weight(gpui::FontWeight::SEMIBOLD).text_color(c(ACCENT)).child(BLOCK_TITLE[k]().to_uppercase())) + .child(div().truncate().text_color(c(0x8a8a8a)).child(note)), + ) + .child( + div() + .flex() + .flex_col() + .gap(px(6.)) + .child(row(t::call_quality(), compact_select(("call-q", k), q_label, call.pref_open == Some((k, false)), q, (k, false), on))) + .child(row(t::call_frame_rate(), compact_select(("call-f", k), f_label, call.pref_open == Some((k, true)), f, (k, true), on))) + .when(k == 1, |d| { + let change = on.clone(); + d.child(row( + t::call_window(), + div() + .id("call-change-screen") + .px(px(10.)) + .py(px(3.)) + .rounded(px(6.)) + .border_1() + .border_color(c(0x333333)) + .bg(c(0x262626)) + .hover(|d| d.bg(c(0x333333))) + .text_size(px(12.)) + .text_color(c(0xffffff)) + .cursor_pointer() + .on_click(move |_, w, cx| change(Act::ChangeScreen, w, cx)) + .child(t::call_window_change()) + .into_any_element(), + )) + .child(row( + t::call_sound(), + if call.share_audio_native { + div() + .flex() + .flex_1() + .items_center() + .justify_between() + .gap(px(8.)) + .text_size(px(12.5)) + .text_color(c(0xf6f6f6)) + .child(div().flex().items_center().gap(px(8.)).child(if call.share_audio_mine { t::call_sound_sharing() } else { t::call_sound_not_shared() }).when( + call.share_audio_denied && !call.share_audio_mine, + |d| { + d.child( + div() + .px(px(7.)) + .py(px(1.)) + .rounded_full() + .border_1() + .border_color(ca(255, 196, 0, 0.45)) + .bg(ca(255, 196, 0, 0.12)) + .text_color(c(0xffc400)) + .text_size(px(10.5)) + .font_weight(gpui::FontWeight::SEMIBOLD) + .child(t::call_sound_permission()), + ) + }, + )) + .child(toggle("call-share-audio", call.share_audio_mine, Act::ShareAudio(!call.share_audio_mine), on)) + .into_any_element() + } else { + div().truncate().text_size(px(12.)).text_color(c(0xb2b2b2)).child(t::call_sound_unavailable()).into_any_element() + }, + )) + }), + ) + .into_any_element() + }) + .collect() +} + +/// The Connection grid's lines for what they send. +pub fn peer_lines(call: &Call, seen: &Seen) -> Vec { + [t::call_their_camera(), t::call_their_screen()] + .into_iter() + .enumerate() + .filter_map(|(k, l)| { + let (_, w, h) = seen.peer[k].as_ref().filter(|_| call.video_peer[k])?; + Some( + div() + .flex() + .items_center() + .child(label(l)) + .child(div().truncate().text_size(px(12.)).text_color(c(0xb2b2b2)).child(t::call_video_size(seen.dec_fps[k], format!("{w}×{h}")))) + .into_any_element(), + ) + }) + .collect() +} diff --git a/crates/vector-gpui/src/callvideo/camera.rs b/crates/vector-gpui/src/callvideo/camera.rs new file mode 100644 index 000000000..826538da3 --- /dev/null +++ b/crates/vector-gpui/src/callvideo/camera.rs @@ -0,0 +1,335 @@ +//! The camera, on its own thread: each frame it gives is turned into I420 at once, from +//! whichever format the device speaks, and handed to the link worker. On Android the shell's +//! Camera2 feed stands in for nokhwa. + +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::mpsc::Sender; +#[cfg(not(target_os = "android"))] +use std::time::Duration; + +#[cfg(not(target_os = "android"))] +use nokhwa::pixel_format::RgbFormat; +#[cfg(not(target_os = "android"))] +use nokhwa::utils::{CameraFormat, CameraIndex, FrameFormat, RequestedFormat, RequestedFormatType, Resolution}; +use vector_core::calls::wire::VideoKind; + +#[cfg(not(target_os = "android"))] +use super::yuv::I420; +use super::In; +#[cfg(not(target_os = "android"))] +use super::clock_us; + +pub struct Capture { + pub(super) stop: Arc, + /// What else ends the source, where a flag alone doesn't. + pub(super) release: Option>, +} + +impl Drop for Capture { + fn drop(&mut self) { + self.stop.store(true, Ordering::Relaxed); + if let Some(release) = self.release.take() { + release(); + } + } +} + +/// The camera a call shows: the one facing the user, where a phone has both. +pub fn open(kind: VideoKind, to: Sender) -> Result { + open_facing(kind, true, to) +} + +/// The camera facing away, for reading a code held in front of it. +pub fn open_back(kind: VideoKind, to: Sender) -> Result { + open_facing(kind, false, to) +} + +#[cfg(target_os = "android")] +fn open_facing(kind: VideoKind, front: bool, to: Sender) -> Result { + android::open(kind, front, to) +} + +/// macOS asks once for the camera; the other systems gate it in their own settings. +#[cfg(not(target_os = "android"))] +fn permitted() -> Result<(), String> { + #[cfg(target_os = "macos")] + { + if nokhwa::nokhwa_check() { + return Ok(()); + } + let (tx, rx) = std::sync::mpsc::channel(); + nokhwa::nokhwa_initialize(move |ok| { + let _ = tx.send(ok); + }); + match rx.recv_timeout(Duration::from_secs(120)) { + Ok(true) => Ok(()), + Ok(false) => Err(crate::t::call_camera_blocked().into()), + Err(_) => Err(crate::t::call_camera_silent().into()), + } + } + #[cfg(not(target_os = "macos"))] + Ok(()) +} + +#[cfg(not(target_os = "android"))] +fn to_i420(frame: &nokhwa::Buffer) -> Option { + let res = frame.resolution(); + let (w, h) = (res.width() as usize, res.height() as usize); + let raw = frame.buffer(); + match frame.source_frame_format() { + FrameFormat::YUYV => I420::from_yuyv(raw, w, h), + FrameFormat::NV12 => I420::from_nv12(raw, w, h), + FrameFormat::RAWRGB => I420::from_rgb(raw, w, h, w * 3, 3, false), + FrameFormat::RAWBGR => I420::from_rgb(raw, w, h, w * 3, 3, true), + FrameFormat::GRAY => { + let mut pic = I420::new(w, h); + let (pw, ph) = (pic.w, pic.h); + for row in 0..ph { + pic.data[row * pw..(row + 1) * pw].copy_from_slice(raw.get(row * w..row * w + pw)?); + } + pic.data[pw * ph..].fill(128); + Some(pic) + } + FrameFormat::MJPEG => { + let img = frame.decode_image::().ok()?; + let (iw, ih) = (img.width() as usize, img.height() as usize); + I420::from_rgb(img.as_raw(), iw, ih, iw * 3, 3, false) + } + } +} + +/// Opens the first camera at 1280x720, 30 fps or the nearest it offers; the error is the +/// user's to read. +#[cfg(not(target_os = "android"))] +fn open_facing(kind: VideoKind, _front: bool, to: Sender) -> Result { + let stop = Arc::new(AtomicBool::new(false)); + let (ready_tx, ready_rx) = std::sync::mpsc::channel::>(); + let flag = Arc::clone(&stop); + std::thread::Builder::new() + .name("camera".into()) + .spawn(move || { + if let Err(e) = permitted() { + let _ = ready_tx.send(Err(e)); + return; + } + let want = CameraFormat::new(Resolution::new(1280, 720), FrameFormat::MJPEG, 30); + let req = RequestedFormat::new::(RequestedFormatType::Closest(want)); + let mut cam = match nokhwa::Camera::new(CameraIndex::Index(0), req) { + Ok(c) => c, + Err(e) => { + log::warn!("camera: {e}"); + let _ = ready_tx.send(Err(crate::t::call_camera_open_failed().into())); + return; + } + }; + if let Err(e) = cam.open_stream() { + log::warn!("camera stream: {e}"); + let _ = ready_tx.send(Err(crate::t::call_camera_open_failed().into())); + return; + } + let _ = ready_tx.send(Ok(())); + let mut failures = 0; + while !flag.load(Ordering::Relaxed) { + match cam.frame() { + Ok(frame) => { + failures = 0; + let ts_us = clock_us(); + if let Some(pic) = to_i420(&frame) + && to.send(In::Frame { kind, pic, ts_us }).is_err() + { + break; + } + } + Err(e) => { + failures += 1; + if failures > 50 { + log::warn!("camera lost: {e}"); + let _ = to.send(In::SourceLost(kind)); + break; + } + std::thread::sleep(Duration::from_millis(20)); + } + } + } + let _ = cam.stop_stream(); + }) + .map_err(|e| e.to_string())?; + match ready_rx.recv_timeout(Duration::from_secs(150)) { + Ok(Ok(())) => Ok(Capture { stop, release: None }), + Ok(Err(e)) => Err(e), + Err(_) => { + stop.store(true, Ordering::Relaxed); + Err(crate::t::call_camera_silent().into()) + } + } +} + +/// Camera2 through the shell's `CameraFeed`: frames arrive on its camera thread with their +/// planes borrowed, are copied upright into I420 there, and go to the feed's sender. +#[cfg(target_os = "android")] +mod android { + use std::collections::HashMap; + use std::sync::atomic::{AtomicBool, AtomicI64, Ordering}; + use std::sync::mpsc::Sender; + use std::sync::{Arc, Condvar, Mutex}; + use std::time::Duration; + + use jni::JNIEnv; + use jni::objects::{JByteBuffer, JClass, JObject, JValue}; + use jni::sys::{jboolean, jint, jlong}; + use vector_core::calls::wire::VideoKind; + + use super::super::yuv::I420; + use super::super::{In, clock_us}; + use super::Capture; + use crate::android::utils::{with_android_activity, with_android_context}; + + const PERMISSION: &str = "android.permission.CAMERA"; + const PERMISSION_REQUEST: jint = 9877; + + static NEXT: AtomicI64 = AtomicI64::new(1); + static FEEDS: Mutex)>>> = Mutex::new(None); + static ANSWER: Mutex>, Condvar)>>> = Mutex::new(None); + + fn feeds(f: impl FnOnce(&mut HashMap)>) -> R) -> R { + let mut g = FEEDS.lock().unwrap_or_else(|e| e.into_inner()); + f(g.get_or_insert_with(HashMap::new)) + } + + fn err(e: jni::errors::Error) -> String { + format!("{e:?}") + } + + fn feed_class<'a>(env: &mut JNIEnv<'a>, ctx: &JObject<'a>) -> Result, String> { + let loader = env.call_method(ctx, "getClassLoader", "()Ljava/lang/ClassLoader;", &[]).and_then(|v| v.l()).map_err(err)?; + let name = env.new_string("io.vectorapp.gpui.CameraFeed").map_err(err)?; + let class = env + .call_method(&loader, "loadClass", "(Ljava/lang/String;)Ljava/lang/Class;", &[JValue::Object(&name)]) + .and_then(|v| v.l()) + .map_err(err)?; + Ok(JClass::from(class)) + } + + fn granted() -> bool { + with_android_context(|env, ctx| { + let name = env.new_string(PERMISSION).map_err(err)?; + let status = env.call_method(ctx, "checkSelfPermission", "(Ljava/lang/String;)I", &[JValue::Object(&name)]).and_then(|v| v.i()).map_err(err)?; + Ok(status == 0) + }) + .unwrap_or(false) + } + + /// Asks once if not yet allowed, and waits for the answer. + fn permitted() -> Result<(), String> { + if granted() { + return Ok(()); + } + let answer = Arc::new((Mutex::new(None), Condvar::new())); + *ANSWER.lock().unwrap_or_else(|e| e.into_inner()) = Some(Arc::clone(&answer)); + with_android_activity(|env, activity| { + let name = env.new_string(PERMISSION).map_err(err)?; + let list = env.new_object_array(1, "java/lang/String", JObject::from(name)).map_err(err)?; + env.call_method(activity, "requestPermissions", "([Ljava/lang/String;I)V", &[JValue::Object(&JObject::from(list)), JValue::Int(PERMISSION_REQUEST)]) + .map_err(err)?; + Ok(()) + }) + .map_err(|e| { + log::warn!("camera permission: {e}"); + String::from(crate::t::call_camera_blocked()) + })?; + let (lock, cvar) = &*answer; + let guard = lock.lock().unwrap_or_else(|e| e.into_inner()); + let (guard, _) = cvar.wait_timeout_while(guard, Duration::from_secs(120), |a| a.is_none()).unwrap_or_else(|e| e.into_inner()); + match *guard { + Some(true) => Ok(()), + Some(false) => Err(crate::t::call_camera_blocked().into()), + None => Err(crate::t::call_camera_silent().into()), + } + } + + pub fn open(kind: VideoKind, front: bool, to: Sender) -> Result { + permitted()?; + let id = NEXT.fetch_add(1, Ordering::Relaxed); + feeds(|f| f.insert(id, (kind, to))); + let started = with_android_context(|env, ctx| { + let class = feed_class(env, ctx)?; + env.call_static_method( + &class, + "start", + "(Landroid/content/Context;JZII)Z", + &[JValue::Object(ctx), JValue::Long(id), JValue::Bool(front.into()), JValue::Int(1280), JValue::Int(720)], + ) + .and_then(|v| v.z()) + .map_err(err) + }); + if !matches!(started, Ok(true)) { + if let Err(e) = started { + log::warn!("camera: {e}"); + } + feeds(|f| f.remove(&id)); + return Err(crate::t::call_camera_open_failed().into()); + } + let release = move || { + feeds(|f| f.remove(&id)); + let _ = with_android_context(|env, ctx| { + let class = feed_class(env, ctx)?; + env.call_static_method(&class, "stop", "(J)V", &[JValue::Long(id)]).map(drop).map_err(err) + }); + }; + Ok(Capture { stop: Arc::new(AtomicBool::new(false)), release: Some(Box::new(release)) }) + } + + /// A plane's bytes, borrowed for as long as the shell holds its image. + fn plane<'a>(env: &JNIEnv<'a>, buf: &JByteBuffer<'a>) -> Option<&'a [u8]> { + let ptr = env.get_direct_buffer_address(buf).ok()?; + let len = env.get_direct_buffer_capacity(buf).ok()?; + // SAFETY: a direct buffer of the Image the shell closes only after this call returns. + (!ptr.is_null()).then(|| unsafe { std::slice::from_raw_parts(ptr, len) }) + } + + #[unsafe(no_mangle)] + #[allow(non_snake_case, clippy::too_many_arguments)] + pub extern "system" fn Java_io_vectorapp_gpui_CameraFeed_nativeFrame<'a>( + env: JNIEnv<'a>, + _class: JClass<'a>, + id: jlong, + y: JByteBuffer<'a>, + u: JByteBuffer<'a>, + v: JByteBuffer<'a>, + y_row: jint, + uv_row: jint, + uv_pixel: jint, + width: jint, + height: jint, + rotation: jint, + ) { + let Some((kind, to)) = feeds(|f| f.get(&id).cloned()) else { return }; + let (Some(yb), Some(ub), Some(vb)) = (plane(&env, &y), plane(&env, &u), plane(&env, &v)) else { return }; + let ts_us = clock_us(); + let Some(pic) = I420::from_planes(yb, ub, vb, y_row.max(0) as usize, uv_row.max(0) as usize, uv_pixel.max(0) as usize, width.max(0) as usize, height.max(0) as usize) else { return }; + let pic = pic.turned(rotation); + if to.send(In::Frame { kind, pic, ts_us }).is_err() { + feeds(|f| f.remove(&id)); + } + } + + #[unsafe(no_mangle)] + #[allow(non_snake_case)] + pub extern "system" fn Java_io_vectorapp_gpui_CameraFeed_nativeLost<'a>(_env: JNIEnv<'a>, _class: JClass<'a>, id: jlong) { + if let Some((kind, to)) = feeds(|f| f.remove(&id)) { + log::warn!("camera lost"); + let _ = to.send(In::SourceLost(kind)); + } + } + + #[unsafe(no_mangle)] + #[allow(non_snake_case)] + pub extern "system" fn Java_io_vectorapp_gpui_CameraFeed_nativePermission<'a>(_env: JNIEnv<'a>, _class: JClass<'a>, granted: jboolean) { + if let Some(answer) = ANSWER.lock().unwrap_or_else(|e| e.into_inner()).take() { + let (lock, cvar) = &*answer; + *lock.lock().unwrap_or_else(|e| e.into_inner()) = Some(granted != 0); + cvar.notify_all(); + } + } +} diff --git a/crates/vector-gpui/src/callvideo/mod.rs b/crates/vector-gpui/src/callvideo/mod.rs new file mode 100644 index 000000000..e964a76e1 --- /dev/null +++ b/crates/vector-gpui/src/callvideo/mod.rs @@ -0,0 +1,269 @@ +//! Video on a call, in process: the link the call's video track hands frames over, a worker +//! that encodes ours and decodes theirs with OpenH264, and the camera. What the UI draws is +//! the newest picture of each track, already BGRA. + +mod camera; +pub mod screen; +mod vp8; +mod worker; +pub mod yuv; + +use std::collections::HashMap; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::mpsc::Sender; +use std::sync::{Arc, Mutex, MutexGuard, OnceLock}; +use std::thread::JoinHandle; +use std::time::Instant; + +use bytes::Bytes; +use futures::channel::mpsc::{UnboundedReceiver, UnboundedSender, unbounded}; +use gpui::RenderImage; +use tokio::sync::mpsc; +pub use vector_core::calls::wire::VideoKind; +use vector_media::calls::link::{self, LinkConn}; + +pub use camera::{Capture, open_back as open_back_camera}; +use yuv::I420; + +/// Frames queued each way before the oldest are dropped, as the webview's socket has. +const LINK_DEPTH: usize = 8; + +pub enum In { + Link(Bytes), + LinkClosed, + Close, + Frame { kind: VideoKind, pic: I420, ts_us: u64 }, + Capture { kind: VideoKind, fps: u32, kbps: u32 }, + Stop(VideoKind), + SourceLost(VideoKind), + /// A voice call member's picture is on screen (their key, hex; the track's index), or gone. + Want((String, usize)), + Unwant((String, usize)), +} + +/// Microseconds on one clock for every capture. +pub fn clock_us() -> u64 { + static START: OnceLock = OnceLock::new(); + START.get_or_init(Instant::now).elapsed().as_micros() as u64 +} + +/// The UI's nudge: one wake in flight at a time, however many pictures land meanwhile. +#[derive(Clone)] +pub struct Wake { + tx: UnboundedSender<()>, + pending: Arc, +} + +impl Wake { + pub fn ping(&self) { + if !self.pending.swap(true, Ordering::AcqRel) { + let _ = self.tx.unbounded_send(()); + } + } +} + +pub struct Pic { + pub image: Arc, + pub w: u32, + pub h: u32, +} + +impl Pic { + fn new(w: u32, h: u32, bgra: Vec) -> Option { + let buf = image::RgbaImage::from_raw(w, h, bgra)?; + Some(Self { image: Arc::new(RenderImage::new(vec![image::Frame::new(buf)])), w, h }) + } +} + +#[derive(Default)] +pub struct Pictures { + pub open: bool, + /// The peer's camera and screen in a call of two. + pub peer: [Option; 2], + /// Our own, as the corner thumbnails show them. + pub mine: [Option; 2], + pub dec_fps: [u32; 2], + /// A voice call's members' pictures, by their key (hex) and track. + pub members: HashMap<(String, usize), Pic>, + /// Captures that ended from outside (a camera unplugged). + pub lost: Vec, + /// Replaced pictures, for the window to let go of. + pub retired: Vec>, +} + +pub struct Video { + pics: Arc>, + wake: Wake, + wake_rx: Option>, + tx: Option>, + worker: Option>, + /// The call (or voice Channel) the link is open for. + link_for: Option, + captures: [Option; 2], + pub starting: [bool; 2], +} + +impl Default for Video { + fn default() -> Self { + let (tx, rx) = unbounded(); + Self { + pics: Arc::default(), + wake: Wake { tx, pending: Arc::default() }, + wake_rx: Some(rx), + tx: None, + worker: None, + link_for: None, + captures: [None, None], + starting: [false; 2], + } + } +} + +/// What this device encodes and decodes, told to the core for every offer and answer. +pub fn announce_caps() { + vector_media::calls::session::set_video_caps(vec!["h264".into()], vp8::decode_caps()); +} + +impl Video { + pub fn take_wake(&mut self) -> Option<(UnboundedReceiver<()>, Arc)> { + self.wake_rx.take().map(|rx| (rx, Arc::clone(&self.wake.pending))) + } + + pub fn pics(&self) -> MutexGuard<'_, Pictures> { + self.pics.lock().unwrap_or_else(|e| e.into_inner()) + } + + pub fn link_open(&self) -> bool { + self.worker.as_ref().is_some_and(|w| !w.is_finished()) && self.pics().open + } + + /// The link follows `key`: open while it names a call that can take video, closed when it + /// changes or goes. True when the link closed under us, so our pictures stopped. + pub fn follow(&mut self, key: Option<&str>) -> bool { + let dead = self.worker.as_ref().is_some_and(|w| w.is_finished()); + if self.link_for.as_deref() == key && !dead { + return false; + } + if self.link_for.as_deref() == key && dead { + // The core dropped the link; whatever we capture goes nowhere now. + self.worker = None; + self.tx = None; + let had = self.captures.iter().any(Option::is_some); + self.captures = [None, None]; + return had; + } + let had = self.captures.iter().any(Option::is_some); + self.close(); + if let Some(k) = key + && self.open() + { + self.link_for = Some(k.to_string()); + } + had && key.is_none() + } + + fn open(&mut self) -> bool { + let (core_tx, mut core_rx) = mpsc::channel::(LINK_DEPTH); + let (us_tx, us_rx) = mpsc::channel::(LINK_DEPTH); + if !link::connect(LinkConn { to_web: core_tx, from_web: us_rx }) { + return false; + } + let (tx, rx) = std::sync::mpsc::channel(); + let fwd = tx.clone(); + let spawned = std::thread::Builder::new().name("video-link".into()).spawn(move || { + while let Some(b) = core_rx.blocking_recv() { + if fwd.send(In::Link(b)).is_err() { + return; + } + } + let _ = fwd.send(In::LinkClosed); + }); + if spawned.is_err() { + return false; + } + let w = worker::Worker::new(rx, us_tx, Arc::clone(&self.pics), self.wake.clone()); + let Ok(handle) = std::thread::Builder::new().name("video".into()).spawn(move || w.run()) else { return false }; + self.tx = Some(tx); + self.worker = Some(handle); + true + } + + fn close(&mut self) { + self.captures = [None, None]; + self.starting = [false; 2]; + if let Some(tx) = self.tx.take() { + let _ = tx.send(In::Close); + } + self.worker = None; + self.link_for = None; + } + + /// Opening a camera can wait on a system prompt: the caller runs this off the UI thread. + pub fn camera_opener(&self, kind: VideoKind) -> Option Result + Send + 'static> { + let tx = self.tx.clone()?; + Some(move || camera::open(kind, tx)) + } + + pub fn screen_opener(&self, target: screen::Target) -> Option Result + Send + 'static> { + let tx = self.tx.clone()?; + Some(move || screen::open(target, tx)) + } + + /// Another window or screen for a share already running; the send never stops. + pub fn replace(&mut self, kind: VideoKind, cap: Capture) { + self.captures[kind.index()] = Some(cap); + } + + pub fn attach(&mut self, kind: VideoKind, cap: Capture) { + let i = kind.index(); + self.starting[i] = false; + let (fps, kbps) = if kind == VideoKind::Screen { (15, 1000) } else { (30, 800) }; + if let Some(tx) = &self.tx { + let _ = tx.send(In::Capture { kind, fps, kbps }); + } + self.captures[i] = Some(cap); + } + + pub fn stop(&mut self, kind: VideoKind) { + self.captures[kind.index()] = None; + if let Some(tx) = &self.tx { + let _ = tx.send(In::Stop(kind)); + } + } + + pub fn capturing(&self, kind: VideoKind) -> bool { + self.captures[kind.index()].is_some() + } + + pub fn want(&self, peer: String, kind: VideoKind, on: bool) { + if let Some(tx) = &self.tx { + let key = (peer, kind.index()); + let _ = tx.send(if on { In::Want(key) } else { In::Unwant(key) }); + } + } +} + +impl Video { + /// Pictures from files, for the parity renders: their camera and screen, then ours. + pub fn show_fixture( + &self, + peer: [Option; 2], + mine: [Option; 2], + members: Vec<((String, usize), image::RgbaImage)>, + ) { + let pic = |img: image::RgbaImage| { + let (w, h) = img.dimensions(); + let mut raw = img.into_raw(); + raw.chunks_exact_mut(4).for_each(|p| p.swap(0, 2)); + Pic::new(w, h, raw) + }; + let mut p = self.pics(); + p.peer = peer.map(|i| i.and_then(pic)); + p.mine = mine.map(|i| i.and_then(pic)); + p.dec_fps = [30, 15]; + p.members = members + .into_iter() + .filter_map(|(k, i)| Some((k, pic(i)?))) + .collect(); + } +} diff --git a/crates/vector-gpui/src/callvideo/screen.rs b/crates/vector-gpui/src/callvideo/screen.rs new file mode 100644 index 000000000..61d7d910f --- /dev/null +++ b/crates/vector-gpui/src/callvideo/screen.rs @@ -0,0 +1,281 @@ +//! The screen as a picture source: what can be shared (every monitor, every window), a +//! thumbnail of each for the picker, and a capture thread for the one chosen. X11 is read +//! straight off the server; macOS and Windows go through `xcap`; Android lists none yet. + +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, AtomicU32, Ordering}; +use std::sync::mpsc::Sender; +use std::time::{Duration, Instant}; + +use vector_core::calls::wire::VideoKind; + +use super::yuv::I420; +use super::{Capture, In, clock_us}; + +/// The frame rate the ladder wants of the screen; the capture loop paces itself by it. +pub static FPS: AtomicU32 = AtomicU32::new(15); + +const THUMB_W: u32 = 320; + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum Target { + Monitor(u32), + Window(u32), +} + +pub struct Source { + pub target: Target, + pub name: String, + /// A small BGRA picture of it, as it looks now. + pub thumb: Option<(u32, u32, Vec)>, +} + +/// One grab: packed 4-byte pixels, BGRX or RGBA. +struct Grab { + w: usize, + h: usize, + stride: usize, + bgr: bool, + data: Vec, +} + +impl Grab { + fn i420(&self) -> Option { + I420::from_rgb(&self.data, self.w, self.h, self.stride, 4, self.bgr) + } + + fn thumb(&self) -> Option<(u32, u32, Vec)> { + let pic = self.i420()?; + let tw = (THUMB_W as usize).min(pic.w) & !1; + let th = ((pic.h * tw) / pic.w.max(1)).max(2) & !1; + let small = pic.scale(tw, th); + let (y, u, v) = small.planes(); + Some((small.w as u32, small.h as u32, super::yuv::to_bgra(y, u, v, (small.w, small.w / 2), small.w, small.h))) + } +} + +#[cfg(target_os = "linux")] +mod imp { + use super::{Grab, Target}; + use x11rb::connection::Connection; + use x11rb::protocol::randr::ConnectionExt as _; + use x11rb::protocol::xproto::{AtomEnum, ConnectionExt as _, ImageFormat, Window}; + use x11rb::rust_connection::RustConnection; + + pub struct Session { + conn: RustConnection, + root: Window, + } + + fn err(e: impl std::fmt::Display) -> String { + e.to_string() + } + + impl Session { + pub fn open() -> Result { + if std::env::var_os("DISPLAY").is_none() { + return Err(crate::t::call_share_unavailable().into()); + } + let (conn, n) = x11rb::connect(None).map_err(|_| crate::t::call_share_unavailable().to_string())?; + let root = conn.setup().roots[n].root; + Ok(Self { conn, root }) + } + + fn atom(&self, name: &str) -> Option { + Some(self.conn.intern_atom(false, name.as_bytes()).ok()?.reply().ok()?.atom) + } + + fn rects(&self) -> Vec<(u32, String, (i16, i16, u16, u16))> { + let Ok(Ok(r)) = self.conn.randr_get_monitors(self.root, true).map(|c| c.reply()) else { + let g = self.conn.get_geometry(self.root).ok().and_then(|c| c.reply().ok()); + return g.map(|g| vec![(0, crate::t::call_share_entire_screen().into(), (0, 0, g.width, g.height))]).unwrap_or_default(); + }; + r.monitors + .iter() + .enumerate() + .map(|(i, m)| { + let name = self + .conn + .get_atom_name(m.name) + .ok() + .and_then(|c| c.reply().ok()) + .map(|n| String::from_utf8_lossy(&n.name).into_owned()) + .unwrap_or_else(|| crate::t::call_share_screen(i + 1).to_string()); + (i as u32, name, (m.x, m.y, m.width, m.height)) + }) + .collect() + } + + fn name_of(&self, w: Window) -> Option { + let utf8 = self.atom("UTF8_STRING")?; + let net = self.atom("_NET_WM_NAME")?; + let read = |prop: u32, ty: u32| { + let r = self.conn.get_property(false, w, prop, ty, 0, 1024).ok()?.reply().ok()?; + (!r.value.is_empty()).then(|| String::from_utf8_lossy(&r.value).into_owned()) + }; + read(net, utf8).or_else(|| read(AtomEnum::WM_NAME.into(), AtomEnum::STRING.into())) + } + + pub fn list(&self) -> Vec<(Target, String)> { + let mut out: Vec<(Target, String)> = self.rects().into_iter().map(|(i, name, _)| (Target::Monitor(i), name)).collect(); + if out.len() == 1 { + out[0].1 = crate::t::call_share_entire_screen().into(); + } + let Some(list) = self.atom("_NET_CLIENT_LIST") else { return out }; + let Ok(Ok(r)) = self.conn.get_property(false, self.root, list, AtomEnum::WINDOW, 0, 4096).map(|c| c.reply()) else { return out }; + for w in r.value32().into_iter().flatten() { + let Some(g) = self.conn.get_geometry(w).ok().and_then(|c| c.reply().ok()) else { continue }; + if g.width < 32 || g.height < 32 { + continue; + } + if let Some(name) = self.name_of(w) { + out.push((Target::Window(w), name)); + } + } + out + } + + pub fn grab(&self, t: Target) -> Result { + let (drawable, (x, y, w, h)) = match t { + Target::Monitor(i) => (self.root, self.rects().into_iter().find(|r| r.0 == i).ok_or_else(|| crate::t::call_share_screen_gone().to_string())?.2), + Target::Window(w) => { + let g = self.conn.get_geometry(w).map_err(err)?.reply().map_err(|_| crate::t::call_share_window_closed().to_string())?; + (w, (0, 0, g.width, g.height)) + } + }; + let img = self.conn.get_image(ImageFormat::Z_PIXMAP, drawable, x, y, w, h, !0).map_err(err)?.reply().map_err(err)?; + let (w, h) = (w as usize, h as usize); + if img.data.len() < w * h * 4 { + return Err(crate::t::call_share_pixel_format().into()); + } + Ok(Grab { w, h, stride: img.data.len() / h, bgr: true, data: img.data }) + } + } +} + +#[cfg(target_os = "android")] +mod imp { + use super::{Grab, Target}; + + pub struct Session; + + impl Session { + pub fn open() -> Result { + Err(crate::t::call_share_unavailable().to_string()) + } + + pub fn list(&self) -> Vec<(Target, String)> { + Vec::new() + } + + pub fn grab(&self, _t: Target) -> Result { + Err(crate::t::call_share_unavailable().to_string()) + } + } +} + +#[cfg(not(any(target_os = "linux", target_os = "android")))] +mod imp { + use super::{Grab, Target}; + + pub struct Session; + + fn grab_of(img: image::RgbaImage) -> Grab { + let (w, h) = (img.width() as usize, img.height() as usize); + Grab { w, h, stride: w * 4, bgr: false, data: img.into_raw() } + } + + impl Session { + pub fn open() -> Result { + Ok(Self) + } + + pub fn list(&self) -> Vec<(Target, String)> { + let mut out = Vec::new(); + if let Ok(ms) = xcap::Monitor::all() { + let one = ms.len() == 1; + for (i, m) in ms.iter().enumerate() { + let Ok(id) = m.id() else { continue }; + let name = if one { crate::t::call_share_entire_screen().into() } else { m.friendly_name().or_else(|_| m.name()).unwrap_or_else(|_| crate::t::call_share_screen(i + 1).to_string()) }; + out.push((Target::Monitor(id), name)); + } + } + if let Ok(ws) = xcap::Window::all() { + for w in ws { + if w.is_minimized().unwrap_or(true) || w.width().unwrap_or(0) < 32 || w.height().unwrap_or(0) < 32 { + continue; + } + let (Ok(id), Ok(title)) = (w.id(), w.title()) else { continue }; + if title.is_empty() { + continue; + } + let app = w.app_name().unwrap_or_default(); + out.push((Target::Window(id), if app.is_empty() || app == title { title } else { crate::t::call_share_window(&*app, &*title).to_string() })); + } + } + out + } + + pub fn grab(&self, t: Target) -> Result { + match t { + Target::Monitor(id) => { + let m = xcap::Monitor::all().map_err(|e| e.to_string())?.into_iter().find(|m| m.id().ok() == Some(id)).ok_or_else(|| crate::t::call_share_screen_gone().to_string())?; + m.capture_image().map(grab_of).map_err(|e| e.to_string()) + } + Target::Window(id) => { + let w = xcap::Window::all().map_err(|e| e.to_string())?.into_iter().find(|w| w.id().ok() == Some(id)).ok_or_else(|| crate::t::call_share_window_closed().to_string())?; + w.capture_image().map(grab_of).map_err(|e| e.to_string()) + } + } + } + } +} + +/// Everything that can be shared, each with a thumbnail. Slow (a grab apiece): call it off +/// the UI thread. +pub fn sources() -> Result, String> { + let s = imp::Session::open()?; + Ok(s.list() + .into_iter() + .map(|(target, name)| Source { target, name, thumb: s.grab(target).ok().and_then(|g| g.thumb()) }) + .collect()) +} + +/// Shares `target` until the capture is dropped; a source that disappears ends it. +pub fn open(target: Target, to: Sender) -> Result { + let first = imp::Session::open()?.grab(target)?; + drop(first); + let stop = Arc::new(AtomicBool::new(false)); + let flag = Arc::clone(&stop); + std::thread::Builder::new() + .name("screen".into()) + .spawn(move || { + let Ok(s) = imp::Session::open() else { return }; + let mut failures = 0; + while !flag.load(Ordering::Relaxed) { + let t0 = Instant::now(); + match s.grab(target) { + Ok(g) => { + failures = 0; + if let Some(pic) = g.i420() + && to.send(In::Frame { kind: VideoKind::Screen, pic, ts_us: clock_us() }).is_err() + { + break; + } + } + Err(e) => { + failures += 1; + if failures > 10 { + log::warn!("screen capture ended: {e}"); + let _ = to.send(In::SourceLost(VideoKind::Screen)); + break; + } + } + } + let gap = Duration::from_secs_f32(1. / FPS.load(Ordering::Relaxed).clamp(1, 60) as f32); + std::thread::sleep(gap.saturating_sub(t0.elapsed())); + } + }) + .map_err(|e| e.to_string())?; + Ok(Capture { stop, release: None }) +} diff --git a/crates/vector-gpui/src/callvideo/vp8.rs b/crates/vector-gpui/src/callvideo/vp8.rs new file mode 100644 index 000000000..85f6e10de --- /dev/null +++ b/crates/vector-gpui/src/callvideo/vp8.rs @@ -0,0 +1,207 @@ +//! VP8 pictures from peers whose encoder offers nothing else, decoded by FFmpeg's own VP8 +//! decoder. Named in our caps only where the FFmpeg we run with carries one. + +#[cfg(feature = "video")] +mod imp { + use ffmpeg_next as ffmpeg; + + pub struct Vp8 { + dec: ffmpeg::decoder::Video, + frame: ffmpeg::frame::Video, + } + + fn codec() -> Option { + static OK: std::sync::OnceLock = std::sync::OnceLock::new(); + if !*OK.get_or_init(|| ffmpeg::init().is_ok()) { + return None; + } + ffmpeg::decoder::find(ffmpeg::codec::Id::VP8) + } + + pub fn available() -> bool { + codec().is_some() + } + + impl Vp8 { + pub fn new() -> Result { + let codec = codec().ok_or("no VP8 decoder in this FFmpeg")?; // i18n-exempt: developer error + let dec = ffmpeg::codec::context::Context::new_with_codec(codec) + .decoder() + .video() + .map_err(|e| e.to_string())?; + Ok(Self { dec, frame: ffmpeg::frame::Video::empty() }) + } + + /// One frame in, its picture as (width, height, BGRA) once the decoder has one. + pub fn decode(&mut self, data: &[u8], max_px: usize) -> Result)>, String> { + self.dec.send_packet(&ffmpeg::Packet::copy(data)).map_err(|e| e.to_string())?; + match self.dec.receive_frame(&mut self.frame) { + Ok(()) => {} + Err(ffmpeg::Error::Other { errno }) if errno == ffmpeg::error::EAGAIN => return Ok(None), + Err(e) => return Err(e.to_string()), + } + let f = &self.frame; + if f.format() != ffmpeg::format::Pixel::YUV420P { + return Err(format!("unexpected VP8 pixel format {:?}", f.format())); // i18n-exempt: developer error + } + let (w, h) = (f.width() as usize, f.height() as usize); + if w == 0 || h == 0 || w * h > max_px { + return Ok(None); + } + let bgra = super::super::yuv::to_bgra(f.data(0), f.data(1), f.data(2), (f.stride(0), f.stride(1)), w, h); + Ok(Some((w as u32, h as u32, bgra))) + } + } +} + +#[cfg(not(feature = "video"))] +mod imp { + pub struct Vp8; + + pub fn available() -> bool { + false + } + + impl Vp8 { + pub fn new() -> Result { + Err("built without FFmpeg".into()) // i18n-exempt: developer error + } + + pub fn decode(&mut self, _: &[u8], _: usize) -> Result)>, String> { + Err("built without FFmpeg".into()) // i18n-exempt: developer error + } + } +} + +pub use imp::{Vp8, available}; + +/// The codecs we take, H.264 always. +pub fn decode_caps() -> Vec { + let mut caps = vec!["h264".to_string()]; + if available() { + caps.push("vp8".into()); + } + caps +} + +#[cfg(all(test, feature = "video"))] +mod tests { + use ffmpeg_next as ffmpeg; + use ffmpeg::format::Pixel; + + #[test] + fn decodes_raw_vp8_frames_to_bgra() { + if !super::available() { + eprintln!("no VP8 decoder in this FFmpeg; skipped"); + return; + } + let Some(codec) = ffmpeg::encoder::find(ffmpeg::codec::Id::VP8) else { + eprintln!("no VP8 encoder to make frames with; skipped"); + return; + }; + let (w, h) = (64u32, 48u32); + let mut enc = ffmpeg::codec::context::Context::new_with_codec(codec).encoder().video().unwrap(); + enc.set_width(w); + enc.set_height(h); + enc.set_format(Pixel::YUV420P); + enc.set_time_base((1, 30)); + enc.set_bit_rate(400_000); + let mut enc = enc.open().unwrap(); + let mut dec = super::Vp8::new().unwrap(); + let mut seen = Vec::new(); + let drain = |enc: &mut ffmpeg::encoder::Video, dec: &mut super::Vp8, seen: &mut Vec<(u32, u32, Vec)>| { + let mut pkt = ffmpeg::Packet::empty(); + while enc.receive_packet(&mut pkt).is_ok() { + if let Some(pic) = dec.decode(pkt.data().unwrap(), 1 << 24).unwrap() { + seen.push(pic); + } + } + }; + for i in 0..6 { + let mut f = ffmpeg::frame::Video::new(Pixel::YUV420P, w, h); + let ys = f.stride(0); + for (n, b) in f.data_mut(0).iter_mut().enumerate() { + *b = if (n % ys) < (w as usize) / 2 { 40 } else { 220 }; + } + f.data_mut(1).fill(128); + f.data_mut(2).fill(128); + f.set_pts(Some(i)); + enc.send_frame(&f).unwrap(); + drain(&mut enc, &mut dec, &mut seen); + } + enc.send_eof().unwrap(); + drain(&mut enc, &mut dec, &mut seen); + assert!(seen.len() >= 3, "only {} pictures came back", seen.len()); + let (pw, ph, bgra) = seen.last().unwrap(); + assert_eq!((*pw, *ph), (w, h)); + let px = |x: usize, y: usize| bgra[(y * w as usize + x) * 4 + 1]; + assert!(px(8, 24) < 80 && px(56, 24) > 180, "left {} right {}", px(8, 24), px(56, 24)); + } + + fn packets(w: u32, h: u32, n: i64) -> Vec> { + let codec = ffmpeg::encoder::find(ffmpeg::codec::Id::VP8).unwrap(); + let mut enc = ffmpeg::codec::context::Context::new_with_codec(codec).encoder().video().unwrap(); + enc.set_width(w); + enc.set_height(h); + enc.set_format(Pixel::YUV420P); + enc.set_time_base((1, 30)); + enc.set_bit_rate(200_000); + let mut enc = enc.open().unwrap(); + let mut out = Vec::new(); + let mut drain = |enc: &mut ffmpeg::encoder::Video| { + let mut pkt = ffmpeg::Packet::empty(); + while enc.receive_packet(&mut pkt).is_ok() { + out.push(pkt.data().unwrap().to_vec()); + } + }; + for i in 0..n { + let mut f = ffmpeg::frame::Video::new(Pixel::YUV420P, w, h); + for (k, b) in f.data_mut(0).iter_mut().enumerate() { + *b = (k as i64 * 7 + i * 13) as u8; + } + f.data_mut(1).fill(90); + f.data_mut(2).fill(160); + f.set_pts(Some(i)); + enc.send_frame(&f).unwrap(); + drain(&mut enc); + } + enc.send_eof().unwrap(); + drain(&mut enc); + out + } + + /// A peer's frames, damaged or changing size: refused or shown, never a panic. + /// `VP8FUZZ_ITERS` runs more. + #[test] + fn damaged_vp8_frames_never_panic() { + if !super::available() || ffmpeg::encoder::find(ffmpeg::codec::Id::VP8).is_none() { + return; + } + let streams = [packets(64, 48, 8), packets(33, 17, 4), packets(2, 2, 2)]; + let iters: usize = std::env::var("VP8FUZZ_ITERS").ok().and_then(|v| v.parse().ok()).unwrap_or(60); + let mut seed = 0x0dd5_eed5_u64; + let mut next = move || { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + seed + }; + for _ in 0..iters { + let mut dec = super::Vp8::new().unwrap(); + for _ in 0..12 { + let s = &streams[(next() % 3) as usize]; + let mut p = s[(next() % s.len() as u64) as usize].clone(); + for _ in 0..next() % 6 { + let at = (next() % p.len() as u64) as usize; + match next() % 4 { + 0 => p[at] = next() as u8, + 1 => p.truncate(at.max(1)), + 2 => p[at] ^= 1 << (next() % 8), + _ => p.extend((0..next() % 64).map(|_| next() as u8)), + } + } + let _ = dec.decode(&p, 1 << 20); + } + } + } +} diff --git a/crates/vector-gpui/src/callvideo/worker.rs b/crates/vector-gpui/src/callvideo/worker.rs new file mode 100644 index 000000000..cc2962433 --- /dev/null +++ b/crates/vector-gpui/src/callvideo/worker.rs @@ -0,0 +1,582 @@ +//! One video link's life, on its own thread: our captures encoded and sent, the peer's frames +//! decoded into pictures for the UI, a stats line a second. Each track (camera, screen) has +//! its own encoder and decoder; a voice call's members each have theirs. + +use std::collections::HashMap; +use std::sync::mpsc::{Receiver, RecvTimeoutError}; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant}; + +use bytes::Bytes; +use openh264::OpenH264API; +use openh264::decoder::Decoder; +use openh264::encoder::{BitRate, Encoder, EncoderConfig, FrameRate, FrameType, RateControlMode, UsageType, VuiConfig}; +use openh264::formats::{YUVSlices, YUVSource}; +use tokio::sync::mpsc; +use vector_core::calls::link::{FromLink, KIND_CONTROL, KIND_FRAME, KIND_PEER_FRAME, ToLink}; +use vector_core::calls::wire::{VIDEO_HEADER_LEN, VIDEO_KEY, VIDEO_SCREEN, VideoCodec, VideoHeader, VideoKind}; + +use super::yuv::{self, I420}; +use super::{In, Pic, Pictures, Wake}; + +const PEER_TAG_LEN: usize = 32; +const MAX_FRAME: usize = 1024 * 1024; +const MAX_DECODE_PX: usize = 4096 * 2304; +/// Our own thumbnail is a corner tile: a 320-wide picture at 15 fps is all it shows. +const PREVIEW_W: usize = 320; +const PREVIEW_GAP: Duration = Duration::from_millis(66); + +const KINDS: [VideoKind; 2] = [VideoKind::Camera, VideoKind::Screen]; + +#[derive(Clone, Copy)] +struct Spec { + fps: u32, + kbps: u32, + target: (u32, u32), + max_h: u32, +} + +#[derive(Clone, Copy)] +struct Rate { + kbps: u32, + width: u32, + height: u32, + fps: u32, +} + +struct Outgoing { + kind: VideoKind, + spec: Option, + enc: Option, + enc_size: (usize, usize), + seq: u32, + skip_next: bool, + force_key: bool, + last_sent: Option, + frames: u32, + bytes: u64, + preview_at: Option, + rate: Option, +} + +impl Outgoing { + fn new(kind: VideoKind) -> Self { + Self { kind, spec: None, enc: None, enc_size: (0, 0), seq: 0, skip_next: false, force_key: true, last_sent: None, frames: 0, bytes: 0, preview_at: None, rate: None } + } + + /// The rung's size for a camera, turned for one held upright; at most the rung's height + /// for a screen. Always even, never upscaled. + fn target(&self, cw: usize, ch: usize) -> (usize, usize) { + let Some(c) = self.spec else { return (0, 0) }; + let (mut w, mut h) = (cw, ch); + if self.kind == VideoKind::Screen { + if c.max_h > 0 && ch > c.max_h as usize { + w = (cw as f32 * c.max_h as f32 / ch as f32).round() as usize; + h = c.max_h as usize; + } + } else if c.target.0 > 0 && c.target.1 > 0 { + let (tw, th) = if (ch > cw) == (c.target.1 > c.target.0) { (c.target.0, c.target.1) } else { (c.target.1, c.target.0) }; + let (tw, th) = (tw as usize, th as usize); + if cw > tw || ch > th { + let s = (tw as f32 / cw as f32).min(th as f32 / ch as f32); + w = (cw as f32 * s).round() as usize; + h = (ch as f32 * s).round() as usize; + } + } + (w & !1, h & !1) + } + + fn configure(&mut self, w: usize, h: usize) { + self.enc = None; + let Some(spec) = self.spec else { return }; + let screen = self.kind == VideoKind::Screen; + let cfg = EncoderConfig::new() + .bitrate(BitRate::from_bps(spec.kbps.max(50) * 1000)) + .max_frame_rate(FrameRate::from_hz(spec.fps.max(1) as f32)) + .rate_control_mode(RateControlMode::Bitrate) + .usage_type(if screen { UsageType::ScreenContentRealTime } else { UsageType::CameraVideoRealTime }) + .vui(VuiConfig::bt601()) + .num_threads(if w * h > 1280 * 720 { 4 } else { 2 }); + match Encoder::with_api_config(OpenH264API::from_source(), cfg) { + Ok(e) => { + self.enc = Some(e); + self.enc_size = (w, h); + self.force_key = true; + } + Err(e) => log::warn!("video encoder: {e}"), + } + } +} + +/// A peer's picture decoder, for the codec its frames name. +enum Dec { + H264(Decoder), + Vp8(super::vp8::Vp8), +} + +impl Dec { + fn codec(&self) -> VideoCodec { + match self { + Dec::H264(_) => VideoCodec::H264, + Dec::Vp8(_) => VideoCodec::Vp8, + } + } +} + +#[derive(Default)] +struct Incoming { + dec: Option, + need_key: bool, + frames: u32, +} + +impl Incoming { + fn reset(&mut self) { + self.dec = None; + self.need_key = true; + } +} + +pub struct Worker { + rx: Receiver, + to_core: mpsc::Sender, + pics: Arc>, + wake: Wake, + codec: Option, + paused: bool, + out: [Outgoing; 2], + inn: [Incoming; 2], + members: HashMap<(String, usize), Incoming>, + dec_errors: u32, +} + +impl Worker { + pub fn new(rx: Receiver, to_core: mpsc::Sender, pics: Arc>, wake: Wake) -> Self { + Self { + rx, + to_core, + pics, + wake, + codec: None, + paused: false, + out: [Outgoing::new(VideoKind::Camera), Outgoing::new(VideoKind::Screen)], + inn: [Incoming { need_key: true, ..Default::default() }, Incoming { need_key: true, ..Default::default() }], + members: HashMap::new(), + dec_errors: 0, + } + } + + fn send(&self, b: Vec) -> bool { + self.to_core.try_send(Bytes::from(b)).is_ok() + } + + fn control(&self, msg: &FromLink) { + let mut out = vec![KIND_CONTROL]; + if serde_json::to_writer(&mut out, msg).is_ok() { + let _ = self.to_core.blocking_send(Bytes::from(out)); + } + } + + pub fn run(mut self) { + self.control(&FromLink::Caps { encode: vec!["h264".into()], decode: super::vp8::decode_caps() }); + self.pics().open = true; + self.wake.ping(); + let mut next_stats = Instant::now() + Duration::from_secs(1); + 'outer: loop { + let wait = next_stats.saturating_duration_since(Instant::now()); + let first = match self.rx.recv_timeout(wait) { + Ok(m) => Some(m), + Err(RecvTimeoutError::Timeout) => None, + Err(RecvTimeoutError::Disconnected) => break, + }; + // Of the captures queued meanwhile only the newest of each track is encoded: a + // backlog means the machine is behind, and old frames would never send in time. + let mut frames: [Option<(I420, u64)>; 2] = [None, None]; + let mut msgs = first.into_iter().collect::>(); + while let Ok(m) = self.rx.try_recv() { + msgs.push(m); + } + for m in msgs { + match m { + In::Frame { kind, pic, ts_us } => frames[kind.index()] = Some((pic, ts_us)), + In::Link(b) => self.on_link(&b), + In::LinkClosed | In::Close => break 'outer, + In::Capture { kind, fps, kbps } => self.start_capture(kind, fps, kbps), + In::Stop(kind) => { + let o = &mut self.out[kind.index()]; + o.spec = None; + o.enc = None; + o.rate = None; + self.pics().mine[kind.index()] = None; + self.wake.ping(); + } + In::SourceLost(kind) => { + self.pics().lost.push(kind); + self.wake.ping(); + } + In::Want(peer) => { + self.members.insert(peer.clone(), Incoming { need_key: true, ..Default::default() }); + self.control(&FromLink::LostFrom { peer: peer.0, kind: KINDS[peer.1] }); + } + In::Unwant(key) => { + self.members.remove(&key); + } + } + } + for (i, f) in frames.into_iter().enumerate() { + if let Some((pic, ts)) = f { + self.on_captured(i, pic, ts); + } + } + if Instant::now() >= next_stats { + next_stats = Instant::now() + Duration::from_secs(1); + self.stats(); + } + } + let mut guard = self.pics(); + let p = &mut *guard; + p.open = false; + for slot in p.peer.iter_mut().chain(p.mine.iter_mut()) { + if let Some(old) = slot.take() { + p.retired.push(old.image); + } + } + p.retired.extend(p.members.drain().map(|(_, v)| v.image)); + drop(guard); + self.wake.ping(); + } + + fn pics(&self) -> std::sync::MutexGuard<'_, Pictures> { + self.pics.lock().unwrap_or_else(|e| e.into_inner()) + } + + fn start_capture(&mut self, kind: VideoKind, fps: u32, kbps: u32) { + let o = &mut self.out[kind.index()]; + o.spec = Some(Spec { fps, kbps, target: (0, 0), max_h: 0 }); + o.force_key = true; + o.seq = 0; + o.last_sent = None; + o.enc = None; + if let Some(r) = o.rate { + self.set_rate(kind, r); + } + } + + fn set_rate(&mut self, kind: VideoKind, r: Rate) { + let o = &mut self.out[kind.index()]; + o.rate = Some(r); + let Some(spec) = o.spec.as_mut() else { return }; + let changed = spec.kbps != r.kbps || spec.fps != r.fps; + spec.kbps = r.kbps; + spec.fps = r.fps; + if kind == VideoKind::Screen { + spec.max_h = r.height; + super::screen::FPS.store(r.fps, std::sync::atomic::Ordering::Relaxed); + } else { + spec.target = (r.width, r.height); + } + if changed && o.enc.is_some() { + let (w, h) = o.enc_size; + o.configure(w, h); + } + } + + fn on_link(&mut self, msg: &[u8]) { + match msg.first() { + Some(&KIND_FRAME) => { + let frame = &msg[1..]; + if frame.len() < VIDEO_HEADER_LEN { + return; + } + let i = if frame[12] & VIDEO_SCREEN != 0 { 1 } else { 0 }; + self.decode(None, i, frame); + } + Some(&KIND_PEER_FRAME) => { + let body = &msg[1..]; + if body.len() < PEER_TAG_LEN + VIDEO_HEADER_LEN { + return; + } + let i = if body[PEER_TAG_LEN + 12] & VIDEO_SCREEN != 0 { 1 } else { 0 }; + let Ok(tag) = <&[u8; 32]>::try_from(&body[..PEER_TAG_LEN]) else { return }; + let hex = vector_core::simd::hex::bytes_to_hex_32(tag); + // Nobody looks at this picture: decoding it would be wasted. + if !self.members.contains_key(&(hex.clone(), i)) { + return; + } + self.decode(Some(hex), i, &body[PEER_TAG_LEN..]); + } + Some(&KIND_CONTROL) => { + let Ok(c) = serde_json::from_slice::(&msg[1..]) else { return }; + match c { + ToLink::Rate { kind, kbps, width, height, fps } => self.set_rate(kind, Rate { kbps, width, height, fps }), + ToLink::Skip { kind } => self.out[kind.index()].skip_next = true, + ToLink::Keyframe { kind } => self.out[kind.index()].force_key = true, + ToLink::Peer { tracks } => { + let mut p = self.pics.lock().unwrap_or_else(|e| e.into_inner()); + for k in KINDS { + if !tracks.has(k) { + self.inn[k.index()].reset(); + if let Some(old) = p.peer[k.index()].take() { + p.retired.push(old.image); + } + } + } + drop(p); + self.wake.ping(); + } + ToLink::Pause { on } => self.paused = on, + ToLink::Codec { codec } => { + if self.codec != Some(codec) { + self.codec = Some(codec); + for o in &mut self.out { + o.enc = None; + } + } + } + } + } + _ => {} + } + } + + fn on_captured(&mut self, i: usize, pic: I420, ts_us: u64) { + let paused = self.paused; + let codec = self.codec; + let o = &mut self.out[i]; + let Some(spec) = o.spec else { return }; + // Our own thumbnail shows even while the peer looks away. + if o.preview_at.is_none_or(|t| t.elapsed() >= PREVIEW_GAP) { + o.preview_at = Some(Instant::now()); + let pw = PREVIEW_W.min(pic.w); + let ph = ((pic.h * pw) / pic.w.max(1)) & !1; + let small = pic.scale(pw, ph.max(2)); + let (y, u, v) = small.planes(); + let bgra = yuv::to_bgra(y, u, v, (small.w, small.w / 2), small.w, small.h); + if let Some(p) = Pic::new(small.w as u32, small.h as u32, bgra) { + let mut g = self.pics.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(old) = g.mine[i].replace(p) { + g.retired.push(old.image); + } + drop(g); + self.wake.ping(); + } + } + if paused || o.skip_next || codec != Some(VideoCodec::H264) { + o.skip_next = false; + return; + } + let min_gap = (1e6 / spec.fps.max(1) as f64 * 0.9) as u64; + if o.last_sent.is_some_and(|l| ts_us.saturating_sub(l) < min_gap) { + return; + } + o.last_sent = Some(ts_us); + let (w, h) = o.target(pic.w, pic.h); + if w == 0 || h == 0 { + return; + } + let pic = if (w, h) == (pic.w, pic.h) { pic } else { pic.scale(w, h) }; + if o.enc.is_none() || o.enc_size != (w, h) { + o.configure(w, h); + } + let force = std::mem::take(&mut o.force_key); + let Some(enc) = o.enc.as_mut() else { return }; + if force { + enc.force_intra_frame(); + } + let (py, pu, pv) = pic.planes(); + let src = YUVSlices::new((py, pu, pv), (pic.w, pic.h), (pic.w, pic.w / 2, pic.w / 2)); + let Ok(bits) = enc.encode_at(&src, openh264::Timestamp::from_millis(ts_us / 1000)) else { + o.force_key = true; + return; + }; + let key = matches!(bits.frame_type(), FrameType::IDR); + if matches!(bits.frame_type(), FrameType::Skip | FrameType::Invalid) { + return; + } + let mut buf = vec![0u8; 1 + VIDEO_HEADER_LEN]; + buf[0] = KIND_FRAME; + bits.write_vec(&mut buf); + let len = buf.len() - 1 - VIDEO_HEADER_LEN; + if len == 0 || buf.len() > MAX_FRAME { + return; + } + let flags = if key { VIDEO_KEY } else { 0 } | if o.kind == VideoKind::Screen { VIDEO_SCREEN } else { 0 }; + VideoHeader { seq: o.seq, ts_us, flags, codec: VideoCodec::H264 }.write(&mut buf[1..1 + VIDEO_HEADER_LEN]); + o.seq = o.seq.wrapping_add(1); + o.frames += 1; + o.bytes += len as u64; + if !self.send(buf) { + // A frame the peer never gets breaks its chain: start the next one afresh. + self.out[i].force_key = true; + } + } + + fn lost(&self, member: &Option, i: usize) { + match member { + Some(peer) => self.control(&FromLink::LostFrom { peer: peer.clone(), kind: KINDS[i] }), + None => self.control(&FromLink::Lost { kind: KINDS[i] }), + } + } + + fn decode(&mut self, member: Option, i: usize, frame: &[u8]) { + let Some(h) = VideoHeader::parse(frame) else { return }; + let key = h.flags & VIDEO_KEY != 0; + let takes = match h.codec { + VideoCodec::H264 => true, + VideoCodec::Vp8 => super::vp8::available(), + }; + if !takes { + // Only what our caps name; a peer that sends another anyway is told so once. + if key { + self.control(&FromLink::Unsupported { codec: h.codec, peer: member.clone() }); + } + return; + } + let slot = match &member { + Some(m) => match self.members.get_mut(&(m.clone(), i)) { + Some(s) => s, + None => return, + }, + None => &mut self.inn[i], + }; + if slot.dec.as_ref().is_some_and(|d| d.codec() != h.codec) { + slot.reset(); + } + if slot.dec.is_none() { + if !key { + slot.need_key = true; + return; + } + let made = match h.codec { + VideoCodec::Vp8 => super::vp8::Vp8::new().map(Dec::Vp8), + _ => Decoder::new().map(Dec::H264).map_err(|e| e.to_string()), + }; + match made { + Ok(d) => slot.dec = Some(d), + Err(e) => { + log::warn!("video decoder: {e}"); + return; + } + } + } + if slot.need_key && !key { + // Waiting on a keyframe nobody asked for is waiting on luck; the core + // rate-limits the request. + self.lost(&member, i); + return; + } + slot.need_key = false; + let picture = match slot.dec.as_mut().expect("decoder just made") { + Dec::H264(dec) => match dec.decode(&frame[VIDEO_HEADER_LEN..]) { + Ok(Some(yuv)) => { + let (w, h) = yuv.dimensions(); + if w * h > MAX_DECODE_PX || w == 0 || h == 0 { + None + } else { + let (ys, us, _) = yuv.strides(); + Some(Ok(Pic::new(w as u32, h as u32, yuv::to_bgra(yuv.y(), yuv.u(), yuv.v(), (ys, us), w, h)))) + } + } + Ok(None) => return, + Err(e) => Some(Err(e.to_string())), + }, + Dec::Vp8(dec) => match dec.decode(&frame[VIDEO_HEADER_LEN..], MAX_DECODE_PX) { + Ok(Some((w, h, bgra))) => Some(Ok(Pic::new(w, h, bgra))), + Ok(None) => return, + Err(e) => Some(Err(e)), + }, + }; + match picture { + Some(Ok(Some(pic))) => { + slot.frames += 1; + let mut p = self.pics.lock().unwrap_or_else(|e| e.into_inner()); + let old = match &member { + Some(m) => p.members.insert((m.clone(), i), pic), + None => p.peer[i].replace(pic), + }; + if let Some(old) = old { + p.retired.push(old.image); + } + drop(p); + self.wake.ping(); + } + Some(Err(e)) => { + slot.reset(); + self.dec_errors += 1; + if self.dec_errors >= 8 { + log::warn!("video decode: {e}"); + self.control(&FromLink::Unsupported { codec: h.codec, peer: member.clone() }); + self.dec_errors = 0; + } else { + self.lost(&member, i); + } + } + _ => { + slot.reset(); + self.lost(&member, i); + } + } + } + + fn stats(&mut self) { + let mut fps = [0; 2]; + for (i, o) in self.out.iter_mut().enumerate() { + if o.spec.is_some() { + let (w, h) = o.enc_size; + let msg = FromLink::Stats { kind: KINDS[i], fps: o.frames, kbps: (o.bytes * 8 / 1000) as u32, width: w as u32, height: h as u32 }; + let mut out = vec![KIND_CONTROL]; + if serde_json::to_writer(&mut out, &msg).is_ok() { + let _ = self.to_core.try_send(Bytes::from(out)); + } + } + o.frames = 0; + o.bytes = 0; + fps[i] = std::mem::take(&mut self.inn[i].frames); + } + let mut p = self.pics(); + if p.dec_fps != fps { + p.dec_fps = fps; + drop(p); + self.wake.ping(); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn gradient(w: usize, h: usize, t: usize) -> I420 { + let rgb: Vec = (0..w * h).flat_map(|i| [((i % w + t) % 256) as u8, ((i / w) % 256) as u8, 90]).collect(); + I420::from_rgb(&rgb, w, h, w * 3, 3, false).unwrap() + } + + #[test] + fn our_frames_decode_back_through_the_link() { + let (to_core, mut core_rx) = mpsc::channel::(64); + let (_tx, rx) = std::sync::mpsc::channel(); + let (wtx, _wrx) = futures::channel::mpsc::unbounded(); + let pics = Arc::new(Mutex::new(Pictures::default())); + let mut w = Worker::new(rx, to_core, Arc::clone(&pics), Wake { tx: wtx, pending: Arc::default() }); + w.codec = Some(VideoCodec::H264); + w.start_capture(VideoKind::Camera, 30, 800); + w.set_rate(VideoKind::Camera, Rate { kbps: 800, width: 640, height: 360, fps: 30 }); + for t in 0..10 { + w.on_captured(0, gradient(1280, 720, t * 4), t as u64 * 40_000); + } + let mut sent = Vec::new(); + while let Ok(b) = core_rx.try_recv() { + sent.push(b); + } + assert!(sent.len() >= 8, "{} frames", sent.len()); + let first = VideoHeader::parse(&sent[0][1..]).unwrap(); + assert!(first.flags & VIDEO_KEY != 0, "the first frame is a keyframe"); + assert_eq!(&sent[0][1 + VIDEO_HEADER_LEN..1 + VIDEO_HEADER_LEN + 4], &[0, 0, 0, 1], "Annex B"); + for b in &sent { + w.on_link(b); + } + let p = pics.lock().unwrap_or_else(|e| e.into_inner()); + let pic = p.peer[0].as_ref().expect("decoded"); + assert_eq!((pic.w, pic.h), (640, 360)); + } +} diff --git a/crates/vector-gpui/src/callvideo/yuv.rs b/crates/vector-gpui/src/callvideo/yuv.rs new file mode 100644 index 000000000..f9d349564 --- /dev/null +++ b/crates/vector-gpui/src/callvideo/yuv.rs @@ -0,0 +1,357 @@ +//! Planar 4:2:0 pictures and the conversions around them: what a camera hands over into I420 for +//! the encoder, and what the decoder gives back into the BGRA a `RenderImage` paints. BT.601 +//! limited range both ways, the matrix WebCodecs peers assume when the stream names none. + +use rayon::prelude::*; + +/// Even width and height, planes packed without padding. +#[derive(Clone)] +pub struct I420 { + pub w: usize, + pub h: usize, + pub data: Vec, +} + +#[inline(always)] +fn luma(r: i32, g: i32, b: i32) -> u8 { + (((66 * r + 129 * g + 25 * b + 128) >> 8) + 16) as u8 +} + +#[inline(always)] +fn chroma(r: i32, g: i32, b: i32) -> (u8, u8) { + let u = ((-38 * r - 74 * g + 112 * b + 128) >> 8) + 128; + let v = ((112 * r - 94 * g - 18 * b + 128) >> 8) + 128; + (u.clamp(0, 255) as u8, v.clamp(0, 255) as u8) +} + +impl I420 { + pub fn new(w: usize, h: usize) -> Self { + let (w, h) = (w & !1, h & !1); + Self { w, h, data: vec![0; w * h * 3 / 2] } + } + + pub fn planes(&self) -> (&[u8], &[u8], &[u8]) { + let (ys, cs) = (self.w * self.h, (self.w / 2) * (self.h / 2)); + let (y, rest) = self.data.split_at(ys); + let (u, v) = rest.split_at(cs); + (y, u, &v[..cs]) + } + + fn planes_mut(&mut self) -> (&mut [u8], &mut [u8], &mut [u8]) { + let (ys, cs) = (self.w * self.h, (self.w / 2) * (self.h / 2)); + let (y, rest) = self.data.split_at_mut(ys); + let (u, v) = rest.split_at_mut(cs); + (y, u, v) + } + + /// Packed RGB, three bytes a pixel, `stride` bytes a row. + pub fn from_rgb(src: &[u8], w: usize, h: usize, stride: usize, bpp: usize, bgr: bool) -> Option { + let mut out = Self::new(w, h); + if out.w == 0 || out.h == 0 || src.len() < stride * (h - 1) + w * bpp { + return None; + } + let (ow, oh) = (out.w, out.h); + let (ri, bi) = if bgr { (2, 0) } else { (0, 2) }; + let (y, u, v) = out.planes_mut(); + y.par_chunks_mut(ow * 2) + .zip(u.par_chunks_mut(ow / 2)) + .zip(v.par_chunks_mut(ow / 2)) + .enumerate() + .for_each(|(row, ((yy, uu), vv))| { + let r0 = &src[row * 2 * stride..]; + let r1 = &src[(row * 2 + 1) * stride..]; + for x in 0..ow / 2 { + let mut acc = [0i32; 3]; + for (dy, line) in [r0, r1].iter().enumerate() { + for dx in 0..2 { + let p = &line[(x * 2 + dx) * bpp..]; + let (r, g, b) = (p[ri] as i32, p[1] as i32, p[bi] as i32); + yy[dy * ow + x * 2 + dx] = luma(r, g, b); + acc[0] += r; + acc[1] += g; + acc[2] += b; + } + } + let (cu, cv) = chroma(acc[0] >> 2, acc[1] >> 2, acc[2] >> 2); + uu[x] = cu; + vv[x] = cv; + } + }); + let _ = oh; + Some(out) + } + + /// YUYV 4:2:2, the webcam's own raw format. + pub fn from_yuyv(src: &[u8], w: usize, h: usize) -> Option { + let mut out = Self::new(w, h); + let stride = w * 2; + if out.w == 0 || out.h == 0 || src.len() < stride * h { + return None; + } + let ow = out.w; + let (y, u, v) = out.planes_mut(); + y.par_chunks_mut(ow * 2) + .zip(u.par_chunks_mut(ow / 2)) + .zip(v.par_chunks_mut(ow / 2)) + .enumerate() + .for_each(|(row, ((yy, uu), vv))| { + let r0 = &src[row * 2 * stride..]; + let r1 = &src[(row * 2 + 1) * stride..]; + for x in 0..ow / 2 { + let (a, b) = (&r0[x * 4..x * 4 + 4], &r1[x * 4..x * 4 + 4]); + yy[x * 2] = a[0]; + yy[x * 2 + 1] = a[2]; + yy[ow + x * 2] = b[0]; + yy[ow + x * 2 + 1] = b[2]; + uu[x] = ((a[1] as u16 + b[1] as u16 + 1) >> 1) as u8; + vv[x] = ((a[3] as u16 + b[3] as u16 + 1) >> 1) as u8; + } + }); + Some(out) + } + + /// YUV_420_888 into I420: luma rows at `y_row`, chroma at `uv_row` with `uv_pixel` bytes + /// between samples (1 planar, 2 interleaved). + #[allow(clippy::too_many_arguments)] + pub fn from_planes(y: &[u8], u: &[u8], v: &[u8], y_row: usize, uv_row: usize, uv_pixel: usize, w: usize, h: usize) -> Option { + let mut out = Self::new(w, h); + let (ow, oh) = (out.w, out.h); + if ow == 0 || oh == 0 || uv_pixel == 0 { + return None; + } + let (cw, ch) = (ow / 2, oh / 2); + let (ys, cs) = (ow * oh, cw * ch); + let (yp, rest) = out.data.split_at_mut(ys); + let (up, vp) = rest.split_at_mut(cs); + for row in 0..oh { + yp[row * ow..(row + 1) * ow].copy_from_slice(y.get(row * y_row..row * y_row + ow)?); + } + for row in 0..ch { + let (us, vs) = (u.get(row * uv_row..)?, v.get(row * uv_row..)?); + if uv_pixel == 1 { + up[row * cw..(row + 1) * cw].copy_from_slice(us.get(..cw)?); + vp[row * cw..(row + 1) * cw].copy_from_slice(vs.get(..cw)?); + } else { + let last = (cw - 1) * uv_pixel; + if us.len() <= last || vs.len() <= last { + return None; + } + for x in 0..cw { + up[row * cw + x] = us[x * uv_pixel]; + vp[row * cw + x] = vs[x * uv_pixel]; + } + } + } + Some(out) + } + + /// Turned clockwise by `degrees` (0, 90, 180 or 270). + pub fn turned(self, degrees: i32) -> Self { + let pic = self; + let (w, h) = (pic.w, pic.h); + let (nw, nh) = match degrees { + 90 | 270 => (h, w), + 180 => (w, h), + _ => return pic, + }; + let mut out = Self::new(nw, nh); + let turn_plane = |src: &[u8], dst: &mut [u8], w: usize, h: usize| { + for y in 0..h { + for x in 0..w { + let (dx, dy, dw) = match degrees { + 90 => (h - 1 - y, x, h), + 180 => (w - 1 - x, h - 1 - y, w), + _ => (y, w - 1 - x, h), + }; + dst[dy * dw + dx] = src[y * w + x]; + } + } + }; + let (sy, su, sv) = pic.planes(); + let (ys, cs) = (nw * nh, (nw / 2) * (nh / 2)); + let (dy, rest) = out.data.split_at_mut(ys); + let (du, dv) = rest.split_at_mut(cs); + turn_plane(sy, dy, w, h); + turn_plane(su, du, w / 2, h / 2); + turn_plane(sv, &mut dv[..cs], w / 2, h / 2); + out + } + + /// NV12: the luma plane, then U and V interleaved. + pub fn from_nv12(src: &[u8], w: usize, h: usize) -> Option { + let mut out = Self::new(w, h); + if out.w == 0 || out.h == 0 || src.len() < w * h + w * (h / 2) { + return None; + } + let (ow, oh) = (out.w, out.h); + let (y, u, v) = out.planes_mut(); + for row in 0..oh { + y[row * ow..(row + 1) * ow].copy_from_slice(&src[row * w..row * w + ow]); + } + let uv = &src[w * h..]; + for row in 0..oh / 2 { + let line = &uv[row * w..]; + for x in 0..ow / 2 { + u[row * ow / 2 + x] = line[x * 2]; + v[row * ow / 2 + x] = line[x * 2 + 1]; + } + } + Some(out) + } + + /// Bilinear, to any even size. + pub fn scale(&self, w: usize, h: usize) -> Self { + let mut out = Self::new(w, h); + if out.w == self.w && out.h == self.h { + out.data.copy_from_slice(&self.data); + return out; + } + let (sy, su, sv) = self.planes(); + let (ow, oh) = (out.w, out.h); + let (dy, du, dv) = out.planes_mut(); + scale_plane(sy, self.w, self.h, dy, ow, oh); + scale_plane(su, self.w / 2, self.h / 2, du, ow / 2, oh / 2); + scale_plane(sv, self.w / 2, self.h / 2, dv, ow / 2, oh / 2); + out + } +} + +fn scale_plane(src: &[u8], sw: usize, sh: usize, dst: &mut [u8], dw: usize, dh: usize) { + if sw == 0 || sh == 0 || dw == 0 || dh == 0 { + return; + } + // A steep shrink averages a box first, so a 4K screen at 720p doesn't shimmer. + let fx = ((sw << 16) / dw) as u32; + let fy = ((sh << 16) / dh) as u32; + let box_x = (sw / dw).max(1); + let box_y = (sh / dh).max(1); + dst.par_chunks_mut(dw).enumerate().for_each(|(y, row)| { + let syf = ((y as u32 * fy) + (fy >> 1)).saturating_sub(1 << 15); + let (y0, wy) = ((syf >> 16) as usize, (syf & 0xffff) >> 8); + let y0 = y0.min(sh - 1); + let y1 = (y0 + 1).min(sh - 1); + for (x, out) in row.iter_mut().enumerate() { + if box_x > 1 || box_y > 1 { + let (bx, by) = (x * sw / dw, y * sh / dh); + let mut acc = 0u32; + let mut n = 0u32; + for yy in by..(by + box_y).min(sh) { + let line = &src[yy * sw..]; + for xx in bx..(bx + box_x).min(sw) { + acc += line[xx] as u32; + n += 1; + } + } + *out = (acc / n.max(1)) as u8; + continue; + } + let sxf = ((x as u32 * fx) + (fx >> 1)).saturating_sub(1 << 15); + let (x0, wx) = ((sxf >> 16) as usize, (sxf & 0xffff) >> 8); + let x0 = x0.min(sw - 1); + let x1 = (x0 + 1).min(sw - 1); + let a = src[y0 * sw + x0] as u32 * (256 - wx) + src[y0 * sw + x1] as u32 * wx; + let b = src[y1 * sw + x0] as u32 * (256 - wx) + src[y1 * sw + x1] as u32 * wx; + *out = ((a * (256 - wy) + b * wy + 32768) >> 16) as u8; + } + }); +} + +/// A decoded picture's planes, as the decoder strides them, into straight BGRA. +pub fn to_bgra(y: &[u8], u: &[u8], v: &[u8], strides: (usize, usize), w: usize, h: usize) -> Vec { + let mut out = vec![0u8; w * h * 4]; + let (ys, cs) = strides; + out.par_chunks_mut(w * 4).enumerate().for_each(|(row, line)| { + let yl = &y[row * ys..]; + let ul = &u[(row / 2) * cs..]; + let vl = &v[(row / 2) * cs..]; + for x in 0..w { + let c = (yl[x] as i32 - 16) * 298; + let d = ul[x / 2] as i32 - 128; + let e = vl[x / 2] as i32 - 128; + let px = &mut line[x * 4..x * 4 + 4]; + px[0] = ((c + 516 * d + 128) >> 8).clamp(0, 255) as u8; + px[1] = ((c - 100 * d - 208 * e + 128) >> 8).clamp(0, 255) as u8; + px[2] = ((c + 409 * e + 128) >> 8).clamp(0, 255) as u8; + px[3] = 255; + } + }); + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_colour_survives_the_round_trip() { + let (w, h) = (8, 4); + let rgb: Vec = (0..w * h).flat_map(|_| [200u8, 40, 90]).collect(); + let pic = I420::from_rgb(&rgb, w, h, w * 3, 3, false).unwrap(); + let (y, u, v) = pic.planes(); + let bgra = to_bgra(y, u, v, (w, w / 2), w, h); + let (b, g, r) = (bgra[0] as i32, bgra[1] as i32, bgra[2] as i32); + assert!((r - 200).abs() <= 3 && (g - 40).abs() <= 3 && (b - 90).abs() <= 3, "{r} {g} {b}"); + } + + #[test] + fn scaling_keeps_a_flat_field_flat() { + let mut pic = I420::new(64, 48); + pic.data.iter_mut().for_each(|b| *b = 120); + for (w, h) in [(32, 24), (16, 12), (100, 70)] { + let s = pic.scale(w, h); + assert!(s.data.iter().all(|&b| b == 120), "{w}x{h}"); + } + } + + /// A 4x2 picture whose every sample names its place, padded rows as a camera pads them. + fn camera_planes(uv_pixel: usize) -> (Vec, Vec, Vec, usize, usize) { + let (y_row, uv_row) = (8, 8); + let mut y = vec![0xEE; y_row * 2]; + for r in 0..2 { + for x in 0..4 { + y[r * y_row + x] = (r * 4 + x) as u8; + } + } + let (mut u, mut v) = (vec![0xEE; uv_row], vec![0xEE; uv_row]); + for x in 0..2 { + u[x * uv_pixel] = 100 + x as u8; + v[x * uv_pixel] = 200 + x as u8; + } + (y, u, v, y_row, uv_row) + } + + #[test] + fn camera_planes_gather_planar_and_interleaved_alike() { + for uv_pixel in [1, 2] { + let (y, u, v, y_row, uv_row) = camera_planes(uv_pixel); + let pic = I420::from_planes(&y, &u, &v, y_row, uv_row, uv_pixel, 4, 2).unwrap(); + let (py, pu, pv) = pic.planes(); + assert_eq!(py, &[0, 1, 2, 3, 4, 5, 6, 7], "pixel stride {uv_pixel}"); + assert_eq!(pu, &[100, 101]); + assert_eq!(pv, &[200, 201]); + } + } + + #[test] + fn camera_planes_short_of_a_row_are_refused() { + let (y, u, v, y_row, uv_row) = camera_planes(2); + assert!(I420::from_planes(&y[..y_row + 3], &u, &v, y_row, uv_row, 2, 4, 2).is_none()); + assert!(I420::from_planes(&y, &u[..2], &v, y_row, uv_row, 2, 4, 2).is_none()); + } + + #[test] + fn turning_goes_clockwise_and_back() { + let (y, u, v, y_row, uv_row) = camera_planes(1); + let pic = I420::from_planes(&y, &u, &v, y_row, uv_row, 1, 4, 2).unwrap(); + let right = pic.clone().turned(90); + assert_eq!((right.w, right.h), (2, 4)); + // The left column, read bottom to top, becomes the top row. + assert_eq!(&right.planes().0[..2], &[4, 0]); + assert_eq!(right.planes().1, &[100, 101]); + let upside = pic.clone().turned(180); + assert_eq!(upside.planes().0, &[7, 6, 5, 4, 3, 2, 1, 0]); + let back = right.turned(270); + assert_eq!(back.data, pic.data); + assert_eq!(pic.clone().turned(0).data, pic.data); + } +} diff --git a/crates/vector-gpui/src/chaneditor.rs b/crates/vector-gpui/src/chaneditor.rs new file mode 100644 index 000000000..947e71a8c --- /dev/null +++ b/crates/vector-gpui/src/chaneditor.rs @@ -0,0 +1,1371 @@ +//! Channel Settings (`community/ChannelEditor.svelte`): Community Settings' layout over one +//! channel or Category. Overview holds the name, topic and view; Permissions holds one +//! overwrite per role or member, each bit allowed, denied or inherited. A Category has +//! Permissions alone. Edits wait behind one save bar, and a close with any pending is refused. + +use std::rc::Rc; + +use gpui::prelude::*; +use gpui::{AnyElement, App, Entity, FontWeight, ScrollHandle, SharedString, Window, div, px, svg}; +use serde_json::Value; + +use crate::kit::Tipped as _; +use crate::commsettings::{block, field_head, heading, hint, input_box, lede, save_btn, short_npub, tab_strip, text_btn}; +use crate::composer::TextInput; +use crate::data::Store; +use crate::settings::{Anchor, Category, Label, NavOn, anchor}; +use crate::t; +use crate::theme::*; + +pub const NAME_MAX: usize = 64; +pub const TOPIC_MAX: usize = 1024; +const PICK_MAX: usize = 100; +const DEFAULT_TINT: u32 = 0x99aab5; + +pub struct Perm { + pub bit: u32, + pub name: Label, + pub desc: Label, +} + +const fn perm(bit: u32, name: Label, desc: Label) -> Perm { + Perm { bit, name, desc } +} + +pub const CHANNEL: &[Perm] = &[ + perm(13, t::channel_editor_perm_view, t::channel_editor_perm_view_desc), + perm(14, t::channel_editor_perm_send, t::channel_editor_perm_send_desc), + perm(15, t::channel_editor_perm_threads, t::channel_editor_perm_threads_desc), + perm(16, t::channel_editor_perm_attach, t::channel_editor_perm_attach_desc), + perm(17, t::channel_editor_perm_react, t::channel_editor_perm_react_desc), + perm(18, t::channel_editor_perm_history, t::channel_editor_perm_history_desc), + perm(5, t::channel_editor_perm_manage, t::channel_editor_perm_manage_desc), +]; + +pub const VOICE: &[Perm] = &[ + perm(19, t::channel_editor_perm_connect, t::channel_editor_perm_connect_desc), + perm(20, t::channel_editor_perm_speak, t::channel_editor_perm_speak_desc), + perm(21, t::channel_editor_perm_video, t::channel_editor_perm_video_desc), + perm(22, t::channel_editor_perm_priority, t::channel_editor_perm_priority_desc), + perm(23, t::channel_editor_perm_mute, t::channel_editor_perm_mute_desc), + perm(24, t::channel_editor_perm_deafen, t::channel_editor_perm_deafen_desc), + perm(25, t::channel_editor_perm_move, t::channel_editor_perm_move_desc), + perm(26, t::channel_editor_perm_timeout, t::channel_editor_perm_timeout_desc), +]; + +const GROUPS: [(&str, Label, Label, &[Perm]); 2] = [ + ("perm-channel", t::channel_editor_section_perm_channel, t::channel_editor_section_perm_channel_keys, CHANNEL), + ("perm-voice", t::channel_editor_section_perm_voice, t::channel_editor_section_perm_voice_keys, VOICE), +]; + +const VIEWS: [(&str, Label, Label); 2] = [ + ("chat", t::channel_editor_view_chat, t::channel_editor_view_chat_desc), + ("voice", t::channel_editor_view_voice, t::channel_editor_view_voice_desc), +]; + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum Tri { + Deny, + Inherit, + Allow, +} + +pub struct Role { + pub id: String, + pub name: String, + pub color: u32, + pub position: i64, + /// The bits this account may set on it; `None` where it may set none. + pub support: Option, +} + +pub struct Overwrite { + /// `everyone`, `role:` or `member:`. + pub key: String, + pub npub: Option, + pub allow: u64, + pub deny: u64, + pub support: Option, +} + +/// `get_channel_permissions`, parsed. +#[derive(Default)] +pub struct Perms { + pub activated: bool, + pub can_manage: bool, + pub synced: bool, + pub category: Option, + /// Whether syncing with the category, or stopping, swaps only rules this account may set. + pub can_sync: bool, + /// This account's key, as hex. + pub me: String, + pub everyone_support: Option, + pub roles: Vec, + pub overwrites: Vec, + /// (hex, npub) of everyone a member overwrite can name. + pub members: Vec<(String, String)>, + /// What this account may set on each of `members`, by hex; absent where it may set none. + pub member_support: std::collections::HashMap, +} + +fn bits(v: &Value) -> u64 { + held(v).unwrap_or(0) +} + +/// A bit set that may be null. +fn held(v: &Value) -> Option { + v.as_str().and_then(|s| s.parse().ok()).or_else(|| v.as_u64()) +} + +impl Perms { + pub fn parse(v: &Value) -> Self { + let str_of = |v: &Value| v.as_str().map(String::from); + Self { + activated: v["activated"].as_bool().unwrap_or(false), + can_manage: v["can_manage"].as_bool().unwrap_or(false), + synced: !v["synced"].is_null() && v["synced"] != Value::Bool(false), + category: str_of(&v["category"]), + can_sync: v["can_sync"].as_bool().unwrap_or(false), + me: str_of(&v["me"]).unwrap_or_default(), + everyone_support: held(&v["everyone_support"]), + roles: v["roles"] + .as_array() + .into_iter() + .flatten() + .map(|r| Role { + id: str_of(&r["role_id"]).unwrap_or_default(), + name: str_of(&r["name"]).map(|n| crate::kit::one_line(&n).into_owned()).unwrap_or_default(), + color: r["color"].as_u64().unwrap_or(0) as u32, + position: r["position"].as_i64().unwrap_or(0), + support: held(&r["support"]), + }) + .collect(), + overwrites: v["overwrites"] + .as_array() + .into_iter() + .flatten() + .map(|o| { + let kind = o["kind"].as_str().unwrap_or("everyone"); + Overwrite { + key: match o["id"].as_str() { + Some(id) if kind != "everyone" => format!("{kind}:{id}"), + _ => "everyone".into(), + }, + npub: str_of(&o["npub"]), + allow: bits(&o["allow"]), + deny: bits(&o["deny"]), + support: held(&o["support"]), + } + }) + .collect(), + members: v["members"] + .as_array() + .into_iter() + .flatten() + .filter_map(|m| Some((str_of(&m["id"])?, str_of(&m["npub"])?))) + .collect(), + member_support: v["members"] + .as_array() + .into_iter() + .flatten() + .filter_map(|m| Some((str_of(&m["id"])?, held(&m["support"])?))) + .collect(), + } + } + + /// What this account may set for `key`: the bits from its roles strictly above it, while + /// Manage Roles is among them. The backend judges a save by the same rule. + pub fn support(&self, key: &str) -> Option { + if key == "everyone" { + return self.everyone_support; + } + match key.split_once(':') { + Some(("role", id)) => self.roles.iter().find(|r| r.id == id)?.support, + Some((_, id)) => match self.overwrites.iter().find(|o| o.key == key) { + Some(o) => o.support, + None => self.member_support.get(id).copied(), + }, + None => None, + } + } + + /// A save restates the whole rule, so one bit this account can't vouch for leaves it as is. + pub fn editable(&self, key: &str) -> bool { + let Some(held) = self.support(key) else { return false }; + let (allow, deny) = self.stored(key); + (allow | deny) & !held == 0 + } + + pub fn stored(&self, key: &str) -> (u64, u64) { + self.overwrites + .iter() + .find(|o| o.key == key) + .map_or((0, 0), |o| (o.allow, o.deny)) + } + + fn open(&self) -> bool { + self.activated && self.can_manage + } +} + +pub struct Saved { + pub name: String, + pub topic: String, + pub view: String, +} + +pub struct ChannelEditor { + pub community: String, + pub channel: String, + pub is_category: bool, + pub primary: bool, + pub section: &'static str, + pub anchor: Option<&'static str>, + pub search: Entity, + pub scroll: ScrollHandle, + pub name: Entity, + pub topic: Entity, + pub view: String, + pub private: bool, + pub saved: Saved, + pub perms: Option, + pub target: String, + pub draft: (u64, u64), + pub busy: bool, + pub error: Option, + /// A refused close or switch: the bar says why until this passes. + pub warn_until: Option, + pub warn_switch: bool, + pub adding: bool, + pub add_closed: Option, + pub add_query: Entity, +} + +const LOCK_BITS: [u32; 3] = [14, 17, 19]; + +pub enum Act { + Close, + Section(&'static str), + Anchor(&'static str, &'static str), + /// The wheel moved on from an anchor jumped to. + Scrolled, + ClearSearch, + View(&'static str), + Private(bool), + Sync(bool), + Target(String), + Bit(u32, Tri), + Lock(bool), + ToggleAdd, + CloseAdd, + Pick(String), + Reset, + Save, + Delete, +} + +fn click_wheel(on: &OnAct) -> impl Fn(&gpui::ScrollEvent, &mut Window, &mut App) + 'static { + let on = on.clone(); + move |_, w, cx| on(Act::Scrolled, w, cx) +} + +pub type OnAct = Rc; + +fn click(on: &OnAct, act: impl Fn() -> Act + 'static) -> impl Fn(&gpui::ClickEvent, &mut Window, &mut App) + 'static { + let on = on.clone(); + move |_, w, cx| on(act(), w, cx) +} + +pub struct Target { + pub key: String, + pub label: String, + pub color: Option, + /// A member's npub, empty where it isn't known. + pub member: Option, + pub set: bool, +} + +/// Who a member target names: their name, else the start of their key. +fn member_label(store: &Store, npub: Option<&str>, hex: &str) -> String { + match npub { + Some(n) if store.profiles.get(n).is_some_and(|p| !p.name.is_empty() || !p.display_name.is_empty() || !p.nickname.is_empty()) => store.name(n), + Some(n) => short_npub(n), + None => format!("{}…", &hex[..hex.len().min(10)]), + } +} + +impl ChannelEditor { + pub fn overview_dirty(&self, cx: &App) -> bool { + let name = self.name.read(cx).text() != self.saved.name; + if self.is_category { + return name; + } + name || self.topic.read(cx).text() != self.saved.topic || self.view != self.saved.view + } + + pub fn overwrite_dirty(&self) -> bool { + self.perms.as_ref().is_some_and(|p| p.stored(&self.target) != self.draft) + } + + pub fn dirty(&self, cx: &App) -> bool { + self.overview_dirty(cx) || self.overwrite_dirty() + } + + pub fn warn(&self) -> bool { + self.warn_until.is_some_and(|t| std::time::Instant::now() < t) + } + + pub fn valid(&self, cx: &App) -> bool { + let name = self.name.read(cx).text(); + !name.trim().is_empty() + && name.len() <= NAME_MAX + && (self.is_category || self.topic.read(cx).text().len() <= TOPIC_MAX) + } + + fn perms_open(&self) -> bool { + self.perms.as_ref().is_some_and(Perms::open) + } + + fn syncable(&self) -> bool { + self.perms_open() + && !self.is_category + && self.perms.as_ref().is_some_and(|p| p.synced || p.category.is_some()) + } + + pub fn bit(&self, bit: u32) -> Tri { + let b = 1u64 << bit; + if self.draft.0 & b != 0 { + Tri::Allow + } else if self.draft.1 & b != 0 { + Tri::Deny + } else { + Tri::Inherit + } + } + + pub fn set_bit(&mut self, bit: u32, to: Tri) { + let b = 1u64 << bit; + let (mut allow, mut deny) = self.draft; + allow &= !b; + deny &= !b; + match to { + Tri::Allow => allow |= b, + Tri::Deny => deny |= b, + Tri::Inherit => {} + } + self.draft = (allow, deny); + } + + /// Whether @everyone may post, react and join calls nowhere here, so every write takes the + /// channel's writer key and nothing anyone else sends reaches its readers. + pub fn locked(&self) -> bool { + let deny = if self.target == "everyone" { + self.draft.1 + } else { + self.perms.as_ref().map_or(0, |p| p.stored("everyone").1) + }; + LOCK_BITS.iter().all(|b| deny & (1 << b) != 0) + } + + pub fn can_lock(&self) -> bool { + let Some(p) = self.perms.as_ref() else { return false }; + let held = p.support("everyone").unwrap_or(0); + p.editable("everyone") && LOCK_BITS.iter().all(|b| held & (1 << b) != 0) + } + + pub fn can_touch(&self, bit: u32) -> bool { + let Some(p) = self.perms.as_ref() else { return false }; + let b = 1u64 << bit; + p.editable(&self.target) && p.support(&self.target).is_some_and(|held| held & b == b) + } + + /// Why the open target can't be changed, when it can't. + pub fn read_only_why(&self) -> Option { + let p = self.perms.as_ref()?; + if self.target.is_empty() || p.editable(&self.target) { + return None; + } + Some(if p.support(&self.target).is_some() { + t::channel_editor_why_support() + } else if self.target == "everyone" { + t::channel_editor_why_everyone() + } else if self.target.strip_prefix("member:") == Some(p.me.as_str()) { + t::channel_editor_why_self() + } else if self.target.starts_with("member:") { + t::channel_editor_why_member() + } else { + t::channel_editor_why_role() + }) + } + + /// A private channel opens only to a role's or a member's allow, whatever @everyone says. + fn closed_to_everyone(&self, bit: u32) -> bool { + self.private && self.target == "everyone" && bit == 13 + } + + /// The targets with an overwrite here, @everyone last, plus whichever is open. + pub fn targets(&self, store: &Store) -> Vec { + let Some(p) = self.perms.as_ref() else { return Vec::new() }; + let mut keys: Vec<&str> = vec!["everyone"]; + for k in p.overwrites.iter().map(|o| o.key.as_str()).chain([self.target.as_str()]) { + if !keys.contains(&k) { + keys.push(k); + } + } + let mut out: Vec<(f64, Target)> = keys + .into_iter() + .map(|key| { + let (allow, deny) = p.stored(key); + let set = allow != 0 || deny != 0; + if key == "everyone" { + return (f64::INFINITY, Target { key: key.into(), label: "@everyone".into(), color: None, member: None, set: true }); + } + let (kind, id) = key.split_once(':').unwrap_or((key, "")); + if kind == "role" { + let role = p.roles.iter().find(|r| r.id == id); + return ( + role.map_or(1e9, |r| r.position as f64), + Target { + key: key.into(), + label: role.map_or_else(|| t::channel_editor_deleted_role().to_string(), |r| r.name.clone()), + color: Some(role.map_or(0, |r| r.color)), + member: None, + set, + }, + ); + } + let npub = p + .overwrites + .iter() + .find(|o| o.key == key) + .and_then(|o| o.npub.clone()) + .or_else(|| p.members.iter().find(|m| m.0 == id).map(|m| m.1.clone())); + (2e9, Target { key: key.into(), label: member_label(store, npub.as_deref(), id), color: None, member: Some(npub.unwrap_or_default()), set }) + }) + .collect(); + out.sort_by(|a, b| a.0.total_cmp(&b.0)); + out.into_iter().map(|(_, t)| t).collect() + } + + pub fn sections(&self) -> Vec { + let activated = self.perms.as_ref().is_some_and(|p| p.activated); + let mut overview = vec![anchor("ch-name", t::channel_editor_section_name, t::channel_editor_section_name_keys)]; + if !self.is_category { + overview.push(anchor("ch-topic", t::channel_editor_section_topic, t::channel_editor_section_topic_keys)); + overview.push(anchor("ch-view", t::channel_editor_section_view, t::channel_editor_section_view_keys)); + if activated { + overview.push(anchor("ch-private", t::channel_editor_section_private, t::channel_editor_section_private_keys)); + } + } + let mut permissions: Vec = Vec::new(); + if self.syncable() { + permissions.push(anchor("ch-sync", t::channel_editor_section_sync, t::channel_editor_section_sync_keys)); + } + let own = self.perms_open() && !self.perms.as_ref().is_some_and(|p| p.synced); + if own { + permissions.push(anchor("ch-lock", t::channel_editor_section_lock, t::channel_editor_section_lock_keys)); + } + // A synced channel shows only its category's link. + if !(self.perms_open() && self.perms.as_ref().is_some_and(|p| p.synced)) { + permissions.push(anchor("ch-targets", t::channel_editor_section_targets, t::channel_editor_section_targets_keys)); + } + if own { + permissions.extend(GROUPS.iter().map(|(id, title, keys, _)| anchor(id, *title, *keys))); + } + vec![ + Category { id: "overview", label: t::channel_editor_page_overview, icon: "info", danger: false, anchors: overview }, + Category { id: "permissions", label: t::channel_editor_page_permissions, icon: "shield-filled", danger: false, anchors: permissions }, + ] + } + + /// Roles without rules here yet, then members, each matching the picker's query. + pub fn addable(&self, store: &Store, cx: &App) -> (Vec<&Role>, Vec<(String, String, String)>) { + let Some(p) = self.perms.as_ref() else { return (Vec::new(), Vec::new()) }; + let q = self.add_query.read(cx).text().trim().to_lowercase(); + let taken = |key: String| key == self.target || p.overwrites.iter().any(|o| o.key == key); + let roles = p + .roles + .iter() + .filter(|r| r.support.is_some() && !taken(format!("role:{}", r.id))) + .filter(|r| q.is_empty() || r.name.to_lowercase().contains(&q)) + .collect(); + let mut members: Vec<(String, String, String)> = p + .members + .iter() + .filter(|(id, _)| p.member_support.contains_key(id) && !taken(format!("member:{id}"))) + .filter_map(|(id, npub)| { + let named = store.profiles.get(npub.as_str()).is_some_and(|p| !p.name.is_empty() || !p.display_name.is_empty() || !p.nickname.is_empty()); + let name = if named { store.name(npub) } else { String::new() }; + // i18n-exempt: a search haystack, never shown + (q.is_empty() || format!("{name} {npub}").to_lowercase().contains(&q)).then(|| (id.clone(), npub.clone(), name)) + }) + .collect(); + members.sort_by(|a, b| { + let ka = if a.2.is_empty() { &a.1 } else { &a.2 }; + let kb = if b.2.is_empty() { &b.1 } else { &b.2 }; + ka.cmp(kb) + }); + (roles, members) + } +} + +fn perm_text(name: impl IntoElement, desc: impl Into) -> gpui::Div { + div() + .flex_1() + .min_w_0() + .flex() + .flex_col() + .gap(px(2.)) + .child(div().text_size(px(14.5)).line_height(px(24.)).text_color(c(0xe8e8e8)).child(name)) + .child(div().text_size(px(12.5)).line_height(px(17.5)).text_color(c(0x7a7a7a)).child(desc.into())) +} + +fn overview(m: &ChannelEditor, narrow: bool, on: &OnAct, cx: &App) -> Vec { + let editable = !m.busy; + let name_len = m.name.read(cx).text().len(); + let name_warn = name_len > NAME_MAX || m.name.read(cx).text().trim().is_empty(); + let mut out = vec![block( + true, + div() + .child(heading(t::channel_editor_section_name())) + .child(field_head( + if m.is_category { t::channel_editor_category_name() } else { t::channel_editor_channel_name() }, + Some((name_len, NAME_MAX, name_warn)), + )) + .child(input_box(&m.name, 42., editable)), + ) + .into_any_element()]; + if m.is_category { + return out; + } + let topic_len = m.topic.read(cx).text().len(); + out.push( + block( + false, + div() + .child(heading(t::channel_editor_section_topic())) + .child(field_head(t::channel_editor_topic_hint(), Some((topic_len, TOPIC_MAX, topic_len > TOPIC_MAX)))) + .child( + div() + .h(px(114.)) + .px(px(13.)) + .py(px(11.)) + .rounded(px(10.)) + .border_1() + .border_color(c(0x2c2c2c)) + .bg(c(0x111111)) + .overflow_hidden() + .when(!editable, |d| d.opacity(0.6)) + .child(m.topic.clone()), + ), + ) + .into_any_element(), + ); + let views = div().flex().when(narrow, |d| d.flex_col()).gap(px(8.)).children(VIEWS.iter().map(|&(id, name, desc)| { + let on_ = m.view == id; + div() + .id(SharedString::from(format!("ce-view-{id}"))) + .map(|d| if narrow { d.w_full() } else { d.w(px((596. - 16.) / 3.)) }) + .min_w_0() + .when(!narrow, |d| d.min_h(px(78.))) + .px(px(12.)) + .py(px(10.)) + .flex() + .flex_col() + .gap(px(3.)) + .rounded(px(10.)) + .border_1() + .font_weight(FontWeight::SEMIBOLD) + .when(on_, |d| d.border_color(c(PRIMARY)).bg(c(0x0f1d17))) + .when(!on_, |d| d.border_color(c(0x262626)).bg(c(0x0c0c0c)).hover(|d| d.bg(c(0x131313)))) + .when(!editable, |d| d.opacity(0.6)) + .when(editable, |d| d.cursor_pointer().on_click(click(on, move || Act::View(id)))) + .child(div().text_size(px(14.5)).line_height(px(18.)).text_color(c(0xe8e8e8)).child(name())) + .child(div().text_size(px(12.5)).line_height(px(17.5)).text_color(c(0x7a7a7a)).child(desc())) + })); + out.push( + block(false, div().child(heading(t::channel_editor_section_view())).child(lede(t::channel_editor_opens_as_lede())).child(views)) + .into_any_element(), + ); + if m.perms.as_ref().is_some_and(|p| p.activated) { + let private = m.private; + let toggle_on = on.clone(); + out.push( + block( + false, + div().child(heading(t::channel_editor_section_private())).child( + div() + .py(px(12.)) + .flex() + .items_center() + .gap(px(16.)) + .child(perm_text( + div() + .flex() + .items_center() + .gap(px(6.)) + .child(svg().path("icons/locked.svg").size(px(13.)).text_color(c(0xe8e8e8))) + .child(t::channel_editor_private()), + if m.saved.view == "voice" { t::channel_editor_private_voice() } else { t::channel_editor_private_text() }, + )) + .child(div().flex_shrink_0().when(m.busy, |d| d.opacity(0.4)).child(crate::settings::toggle( + "ce-private", + private, + false, + move |_, w, cx| toggle_on(Act::Private(!private), w, cx), + ))), + ), + ) + .into_any_element(), + ); + } + out +} + +fn tri(m: &ChannelEditor, p: &Perm, live: bool, on: &OnAct) -> impl IntoElement { + let state = m.bit(p.bit); + let bit = p.bit; + let cell = |to: Tri, first: bool| { + let lit = state == to; + let (bg, fg) = match (to, lit) { + (Tri::Deny, true) => (c(0x42132f), c(crate::timeline::DANGER)), + (Tri::Inherit, true) => (c(0x1b1b1b), c(0xcfcfcf)), + (Tri::Allow, true) => (c(0x0f3a29), c(PRIMARY)), + _ => (c(0x0c0c0c), c(0x6f6f6f)), + }; + let glyph: AnyElement = match to { + Tri::Deny => svg().path("icons/x.svg").size(px(12.)).text_color(fg).into_any_element(), + Tri::Allow => svg().path("icons/check.svg").size(px(12.)).text_color(fg).into_any_element(), + Tri::Inherit => div().font_weight(FontWeight::SEMIBOLD).text_size(px(13.)).line_height(px(13.)).text_color(fg).child("/").into_any_element(), + }; + div() + .id(SharedString::from(format!("ce-tri-{bit}-{to:?}"))) + .w(px(30.)) + .h(px(26.)) + .flex() + .items_center() + .justify_center() + .bg(bg) + .when(!first, |d| d.border_l_1().border_color(c(0x262626))) + .when(live, |d| d.cursor_pointer().on_click(click(on, move || Act::Bit(bit, to)))) + .child(glyph) + }; + div() + .flex() + .flex_shrink_0() + .rounded(px(8.)) + .border_1() + .border_color(c(0x262626)) + .overflow_hidden() + .child(cell(Tri::Deny, true)) + .child(cell(Tri::Inherit, false)) + .child(cell(Tri::Allow, false)) +} + +fn dot(color: u32) -> impl IntoElement { + div() + .size(px(12.)) + .flex_shrink_0() + .rounded_full() + .bg(c(if color == 0 { DEFAULT_TINT } else { color })) + .border_1() + .border_color(white_a(0.15)) +} + +fn add_picker(m: &ChannelEditor, store: &Store, on: &OnAct, cx: &App) -> AnyElement { + let (roles, members) = m.addable(store, cx); + let label = |text: SharedString| { + div() + .px(px(8.)) + .pt(px(10.)) + .pb(px(4.)) + .text_size(px(11.)) + .line_height(px(13.)) + .font_weight(FontWeight::BOLD) + .text_color(c(0x7a7a7a)) + .child(text.to_uppercase()) + }; + let row = |id: SharedString, lead: AnyElement, name: String, sub: Option, key: String| { + let group = id.clone(); + div() + .id(id) + .group(group.clone()) + .h(px(38.)) + .px(px(8.)) + .flex() + .items_center() + .gap(px(10.)) + .rounded(px(8.)) + .cursor_pointer() + .hover(|d| d.bg(c(0x1c1c1c))) + .on_click(click(on, move || Act::Pick(key.clone()))) + .child(div().w(px(22.)).flex_shrink_0().flex().items_center().justify_center().child(lead)) + .child(div().min_w_0().truncate().text_size(px(14.)).font_weight(FontWeight::MEDIUM).text_color(c(0xe6e6e6)).child(name)) + .children(sub.map(|s| div().flex_1().min_w_0().truncate().text_size(px(12.)).text_color(c(0x6a6a6a)).child(s))) + .child( + svg() + .path("icons/plus.svg") + .ml_auto() + .size(px(14.)) + .flex_shrink_0() + .text_color(c(ACCENT)) + .invisible() + .group_hover(group, |d| d.visible()), + ) + }; + let mut list = div().id("ce-add-list").flex_1().min_h_0().overflow_y_scroll().px(px(6.)).pt(px(4.)).pb(px(8.)); + let empty = roles.is_empty() && members.is_empty(); + if !roles.is_empty() { + list = list.child(label(t::channel_editor_roles())); + for r in roles { + list = list.child(row( + SharedString::from(format!("ce-add-role-{}", r.id)), + dot(r.color).into_any_element(), + r.name.clone(), + None, + format!("role:{}", r.id), + )); + } + } + if !members.is_empty() { + list = list.child(label(t::channel_editor_members())); + let more = members.len().saturating_sub(PICK_MAX); + for (id, npub, name) in members.into_iter().take(PICK_MAX) { + let veiled = store.stream_hidden(&npub); + let shown = if name.is_empty() { short_npub(&npub) } else { name.clone() }; + let sub = (!name.is_empty() && !veiled).then(|| short_npub(&npub)); + list = list.child(row( + SharedString::from(format!("ce-add-member-{id}")), + crate::ui::avatar(store, &npub, 22.).into_any_element(), + shown, + sub, + format!("member:{id}"), + )); + } + if more > 0 { + list = list.child(div().px(px(8.)).py(px(14.)).text_center().text_size(px(13.)).text_color(c(0x7a7a7a)).child(t::channel_editor_search_more(more))); + } + } + if empty { + let q = m.add_query.read(cx).text().trim().to_string(); + list = list.child(div().px(px(8.)).py(px(14.)).text_center().text_size(px(13.)).text_color(c(0x7a7a7a)).child(t::channel_editor_no_match(q))); + } + let close = on.clone(); + gpui::deferred( + div() + .id("ce-add-pop") + .absolute() + .top(px(40.)) + .right_0() + .w(px(360.)) + .max_h(px(380.)) + .flex() + .flex_col() + .rounded(px(14.)) + .border_1() + .border_color(c(0x2c2e2f)) + .bg(c(0x101010)) + .shadow(vec![gpui::BoxShadow { + color: ca(0, 0, 0, 0.6), + offset: gpui::point(px(0.), px(18.)), + blur_radius: px(50.), + spread_radius: px(0.), + inset: false, + }]) + .overflow_hidden() + .occlude() + .on_click(|_, _, cx| cx.stop_propagation()) + .on_mouse_down_out(move |_, w, cx| close(Act::CloseAdd, w, cx)) + .child( + div().flex_none().p(px(10.)).border_b_1().border_color(c(0x1f1f1f)).child( + div() + .relative() + .h(px(36.)) + .pl(px(34.)) + .pr(px(12.)) + .flex() + .items_center() + .rounded(px(9.)) + .border_1() + .border_color(c(0x262626)) + .bg(c(0x161616)) + .child(svg().path("icons/search.svg").absolute().left(px(12.)).top(px(10.)).size(px(14.)).text_color(c(0x7a7a7a))) + .child(div().flex_1().min_w_0().child(m.add_query.clone())), + ), + ) + .child(list), + ) + .with_priority(13) + .into_any_element() +} + +fn permissions(m: &ChannelEditor, store: &Store, on: &OnAct, cx: &App) -> Vec { + let Some(p) = m.perms.as_ref() else { + return vec![block(true, div().child(heading(t::channel_editor_section_targets())).child(hint(t::channel_editor_loading()))).into_any_element()]; + }; + if !p.open() { + return vec![block( + true, + div().child(heading(t::channel_editor_section_targets())).child(lede(if p.activated { + t::channel_editor_needs_manage_roles() + } else { + t::channel_editor_not_activated() + })), + ) + .into_any_element()]; + } + let mut out = Vec::new(); + if m.syncable() { + let synced = p.synced; + out.push( + block( + true, + div().child(heading(t::channel_editor_section_sync())).child( + div() + .mb(px(12.)) + .flex() + .items_center() + .justify_between() + .gap(px(12.)) + .child( + div().flex_1().min_w_0().text_size(px(14.)).line_height(px(21.)).text_color(c(0x9a9a9a)).child(match (synced, p.can_sync) { + (true, true) => t::channel_editor_synced(), + (true, false) => t::channel_editor_synced_held(), + (false, true) => t::channel_editor_own(), + (false, false) => t::channel_editor_own_held(), + }), + ) + .child( + div() + .id("ce-sync") + .h(px(34.)) + .px(px(14.)) + .flex_shrink_0() + .flex() + .items_center() + .rounded(px(8.)) + .font_weight(FontWeight::MEDIUM) + .text_size(px(14.)) + .text_color(c(PRIMARY)) + .when(m.busy || !p.can_sync, |d| d.opacity(0.45)) + .when(!m.busy && p.can_sync, |d| d.cursor_pointer().hover(|d| d.underline()).on_click(click(on, move || Act::Sync(!synced)))) + .child(if synced { t::channel_editor_stop_sync() } else { t::channel_editor_sync() }), + ), + ), + ) + .into_any_element(), + ); + } + if p.synced { + return out; + } + let locked = m.locked(); + let can_lock = m.can_lock() && !m.busy; + out.push( + block( + out.is_empty(), + div().child(heading(t::channel_editor_section_lock())).child( + div() + .mb(px(12.)) + .flex() + .items_center() + .justify_between() + .gap(px(12.)) + .child(div().flex_1().min_w_0().text_size(px(14.)).line_height(px(21.)).text_color(c(0x9a9a9a)).child(if locked { + t::channel_editor_locked() + } else { + t::channel_editor_lock_note() + })) + .child( + div() + .id("ce-lock") + .h(px(34.)) + .px(px(14.)) + .flex_shrink_0() + .flex() + .items_center() + .rounded(px(8.)) + .font_weight(FontWeight::MEDIUM) + .text_size(px(14.)) + .text_color(c(PRIMARY)) + .when(!can_lock, |d| d.opacity(0.45)) + .when(can_lock, |d| d.cursor_pointer().hover(|d| d.underline()).on_click(click(on, move || Act::Lock(!locked)))) + .child(if locked { + t::channel_editor_unlock() + } else if m.is_category { + t::channel_editor_lock_category() + } else { + t::channel_editor_lock_channel() + }), + ), + ), + ) + .into_any_element(), + ); + let first = out.is_empty(); + let targets = m.targets(store); + let (roles, members) = m.addable(store, cx); + let can_add = p.roles.iter().any(|r| !targets.iter().any(|t| t.key == format!("role:{}", r.id))) + || p.members.iter().any(|(id, _)| !targets.iter().any(|t| t.key == format!("member:{id}"))); + drop((roles, members)); + let open_label = targets.iter().find(|t| t.key == m.target).map(|t| t.label.clone()); + let head = div() + .relative() + .mb(px(20.)) + .flex() + .items_center() + .justify_between() + .gap(px(12.)) + .child(div().text_size(px(24.)).line_height(px(28.)).font_weight(FontWeight::BOLD).text_color(c(0xffffff)).child(t::channel_editor_section_targets())) + .when(can_add, |d| { + d.child( + div() + .id("ce-add") + .h(px(34.)) + .px(px(14.)) + .flex() + .items_center() + .gap(px(6.)) + .rounded(px(8.)) + .bg(c(PRIMARY)) + .font_weight(FontWeight::SEMIBOLD) + .text_size(px(14.)) + .text_color(c(0x000000)) + .when(m.busy, |d| d.opacity(0.45)) + .when(!m.busy, |d| d.cursor_pointer().hover(|d| d.opacity(0.92)).on_click(click(on, || Act::ToggleAdd))) + .child(svg().path("icons/plus.svg").size(px(12.)).text_color(c(0x000000))) + .child(t::channel_editor_add()), + ) + }) + .when(m.adding, |d| d.child(add_picker(m, store, on, cx))); + let mut rows = div().mb(px(10.)).rounded(px(12.)).border_1().border_color(c(0x262626)).overflow_hidden(); + for (i, t) in targets.iter().enumerate() { + let on_ = t.key == m.target; + let key = t.key.clone(); + rows = rows.child( + div() + .id(SharedString::from(format!("ce-target-{}", t.key))) + .h(px(if i == 0 { 46. } else { 47. })) + .pl(px(8.)) + .pr(px(14.)) + .flex() + .items_center() + .gap(px(12.)) + .bg(c(if on_ { 0x171717 } else { 0x0c0c0c })) + .when(i > 0, |d| d.border_t_1().border_color(c(0x1e1e1e))) + .when(!on_, |d| d.hover(|d| d.bg(c(0x131313)))) + .when(!m.busy, |d| d.cursor_pointer().on_click(click(on, move || Act::Target(key.clone())))) + .child(match t.member.as_deref() { + Some(npub) => div() + .size(px(18.)) + .flex_shrink_0() + .flex() + .items_center() + .justify_center() + .child(if npub.is_empty() { + svg().path("icons/user-circle.svg").size(px(16.)).text_color(c(0x6f6f6f)).into_any_element() + } else { + crate::ui::avatar(store, npub, 18.).into_any_element() + }) + .into_any_element(), + None => dot(t.color.unwrap_or(DEFAULT_TINT)).into_any_element(), + }) + .child( + div() + .min_w_0() + .truncate() + .text_size(px(14.)) + .line_height(px(24.)) + .when(on_, |d| d.font_weight(FontWeight::MEDIUM)) + .text_color(c(if on_ { 0xffffff } else { 0xe8e8e8 })) + .child(t.label.clone()), + ) + .child(div().ml_auto().flex().items_center().gap(px(12.)).when(!t.set, |d| { + d.child(div().flex_shrink_0().text_size(px(12.5)).line_height(px(24.)).text_color(c(0x6f6f6f)).child(t::channel_editor_no_rules())) + }).when(!p.editable(&t.key), |d| { + // A target whose rules come from above you: shown, never editable. + d.child( + div() + .id(SharedString::from(format!("ce-lock-{}", t.key))) + .tip(t::channel_editor_cant_change()) + .size(px(14.)) + .flex_shrink_0() + .child(svg().path("icons/locked.svg").size(px(14.)).text_color(c(0x6f6f6f))), + ) + }).child(div().size(px(16.)).flex_shrink_0().flex().items_center().justify_center().when(on_, |d| { + d.child(svg().path("icons/check.svg").size(px(16.)).text_color(c(PRIMARY))) + }))), + ); + } + out.push( + block( + first, + div() + .child(head) + .child(lede(if m.is_category { t::channel_editor_category_targets() } else { t::channel_editor_targets() })) + .child(rows), + ) + .into_any_element(), + ); + let why = m.read_only_why(); + for (gi, (_, title, _, perms)) in GROUPS.into_iter().enumerate() { + let mut list = div().flex().flex_col(); + for (i, perm) in perms.iter().enumerate() { + let closed = m.closed_to_everyone(perm.bit); + let live = m.can_touch(perm.bit) && !closed && !m.busy; + list = list.child( + div() + .py(px(6.)) + .flex() + .items_center() + .gap(px(12.)) + .when(i > 0, |d| d.border_t_1().border_color(c(0x1a1a1a))) + .when(!m.can_touch(perm.bit) || closed, |d| d.opacity(0.5)) + .child(perm_text((perm.name)(), if closed { t::channel_editor_perm_closed() } else { (perm.desc)() })) + .child(tri(m, perm, live, on)), + ); + } + out.push( + block( + false, + div() + .child( + div() + .mb(px(20.)) + .flex() + .text_size(px(24.)) + .line_height(px(28.)) + .font_weight(FontWeight::BOLD) + .text_color(c(0xffffff)) + .child(title()) + .children(open_label.clone().map(|l| { + div().ml(px(7.)).font_weight(FontWeight::NORMAL).text_color(c(0x8a8a8a)).child(t::channel_editor_for(l)) + })), + ) + .children(why.clone().filter(|_| gi == 0).map(lede)) + .child(list), + ) + .into_any_element(), + ); + } + out +} + +fn save_bar(m: &ChannelEditor, on: &OnAct, cx: &App) -> Option { + let dirty = m.dirty(cx); + if !dirty && !m.busy && m.error.is_none() { + return None; + } + let warn = m.warn() && dirty; + let open = m.perms.as_ref().map(|_| m.targets_label(cx)).flatten(); + let (text, err): (SharedString, bool) = if m.busy { + (t::channel_editor_saving(), false) + } else if warn { + ( + match (m.warn_switch, open) { + (true, Some(target)) => t::channel_editor_save_first(target), + (true, None) => t::channel_editor_save_first_unnamed(), + (false, _) => t::channel_editor_save_before_closing(), + }, + true, + ) + } else if let Some(e) = m.error.as_deref() { + (crate::coretext::say(e).into_owned().into(), true) + } else { + (t::channel_editor_unsaved(), false) + }; + let live = !m.busy && dirty; + Some( + div() + .absolute() + .bottom(px(22.)) + .left_0() + .right_0() + .flex() + .justify_center() + .px(px(22.)) + .child( + div() + .w_full() + .max_w(px(600.)) + .flex() + .items_center() + .gap(px(16.)) + .pl(px(18.)) + .pr(px(10.)) + .py(px(10.)) + .rounded(px(12.)) + .border_1() + .border_color(if warn { c(crate::timeline::DANGER) } else { c(0x2c2c2c) }) + .bg(c(0x151515)) + .shadow(vec![gpui::BoxShadow { + color: ca(0, 0, 0, 0.55), + offset: gpui::point(px(0.), px(10.)), + blur_radius: px(30.), + spread_radius: px(0.), + inset: false, + }]) + .child( + div() + .flex_1() + .min_w_0() + .text_size(px(14.)) + .line_height(px(24.)) + .text_color(if err { c(crate::timeline::DANGER) } else { c(0xe6e6e6) }) + .child(text), + ) + .child( + div() + .flex() + .gap(px(6.)) + .child(text_btn("ce-reset", t::channel_editor_reset(), live, click(on, || Act::Reset))) + .child(save_btn("ce-save", t::channel_editor_save(), live && m.valid(cx), click(on, || Act::Save))), + ), + ) + .into_any_element(), + ) +} + +impl ChannelEditor { + fn targets_label(&self, _cx: &App) -> Option { + let p = self.perms.as_ref()?; + Some(match self.target.split_once(':') { + None => "@everyone".into(), + Some(("role", id)) => p.roles.iter().find(|r| r.id == id).map_or_else(|| t::channel_editor_deleted_role().to_string(), |r| r.name.clone()), + Some((_, id)) => p + .members + .iter() + .find(|m| m.0 == id) + .map_or_else(|| format!("{}…", &id[..id.len().min(10)]), |m| short_npub(&m.1)), + }) + } +} + +/// `vw`: under 760 it is Community Settings' phone sheet, the sections a strip of tabs. +pub fn view(m: &ChannelEditor, store: &Store, vw: f32, on: &OnAct, cx: &App) -> impl IntoElement + use<> { + let compact = vw <= 760.; + let sections = m.sections(); + let section = sections.iter().find(|s| s.id == m.section).unwrap_or(§ions[0]); + // The anchor jumped to, until a wheel moves on; else the block crossing the middle, or + // the last once the bottom is reached. + let active = m.anchor.filter(|a| section.anchors.iter().any(|x| x.id == *a)).unwrap_or_else(|| { + let last = section.anchors.len().saturating_sub(1); + let h = &m.scroll; + let (view, y) = (h.bounds(), -h.offset().y); + let mid = view.top() + y + view.size.height / 2.; + let mut at = (0..=last).take_while(|&i| h.bounds_for_item(i).is_some_and(|b| b.top() <= mid)).last().unwrap_or(0); + let max = h.max_offset().y; + if max > px(0.) && y >= max - px(2.) { + at = last; + } + section.anchors[at].id + }); + let glyph = if m.is_category { + "icons/folder.svg" + } else if m.saved.view == "voice" { + "icons/volume-max.svg" + } else if m.private { + "icons/locked.svg" + } else { + "icons/channel-hash.svg" + }; + let title: SharedString = if m.saved.name.is_empty() { + if m.is_category { t::channel_editor_category() } else { t::channel_editor_channel() } + } else { + m.saved.name.clone().into() + }; + let head = div() + .mx(px(10.)) + .mb(px(17.)) + .pb(px(16.)) + .border_b_1() + .border_color(c(0x262626)) + .flex() + .items_center() + .gap(px(8.)) + .child(div().ml(px(-4.)).size(px(24.)).flex_shrink_0().child(svg().path(glyph).size_full().text_color(c(0xffffff)))) + .child(div().min_w_0().truncate().font_weight(FontWeight::BOLD).text_size(px(14.)).line_height(px(17.)).text_color(c(0xffffff)).child(title)) + .into_any_element(); + let footer = (m.is_category || !m.primary).then(|| { + let what = if m.is_category { t::channel_editor_delete_category() } else { t::channel_editor_delete_channel() }; + div() + .mt(px(12.)) + .pt(px(16.)) + .px(px(8.)) + .border_t_1() + .border_color(c(0x262626)) + .child( + div() + .id("ce-delete") + .h(px(38.)) + .px(px(11.)) + .flex() + .items_center() + .gap(px(12.)) + .rounded(px(8.)) + .font_weight(FontWeight::SEMIBOLD) + .text_size(px(15.)) + .line_height(px(18.)) + .text_color(c(crate::timeline::DANGER)) + .hover(|d| d.bg(c(0x151515))) + .when(m.busy, |d| d.opacity(0.45)) + .when(!m.busy, |d| d.cursor_pointer().on_click(click(on, || Act::Delete))) + .child(svg().path("icons/trash.svg").size(px(17.)).flex_shrink_0().text_color(c(crate::timeline::DANGER))) + .child(div().min_w_0().truncate().child(what)), + ) + .into_any_element() + }); + let (a, b, d) = (on.clone(), on.clone(), on.clone()); + let nav_on = NavOn { + section: Rc::new(move |id, w, cx| a(Act::Section(id), w, cx)), + anchor: Rc::new(move |(s, x), w, cx| b(Act::Anchor(s, x), w, cx)), + clear: Rc::new(move |_, w, cx| d(Act::ClearSearch, w, cx)), + }; + let nav = if compact { + let pick = on.clone(); + let trash = (m.is_category || !m.primary).then(|| { + div() + .id("ce-delete") + .h(px(38.)) + .px(px(11.)) + .flex() + .items_center() + .rounded(px(8.)) + .hover(|d| d.bg(c(0x151515))) + .when(m.busy, |d| d.opacity(0.45)) + .when(!m.busy, |d| d.cursor_pointer().on_click(click(on, || Act::Delete))) + .child(svg().path("icons/trash.svg").size(px(17.)).text_color(c(crate::timeline::DANGER))) + .into_any_element() + }); + tab_strip(§ions, section.id, Rc::new(move |id, w, cx| pick(Act::Section(id), w, cx)), trash) + } else { + crate::settings::section_nav(§ions, section.id, &[], active, &m.search, head, footer, 249., 0x0b0b0b, &nav_on, cx) + }; + let blocks = match section.id { + "overview" => overview(m, vw <= 520., on, cx), + _ => permissions(m, store, on, cx), + }; + let close = on.clone(); + let main = div() + .flex_1() + .min_w_0() + .h_full() + .relative() + .flex() + .flex_col() + .child( + div() + .h(px(50.)) + .flex_shrink_0() + .pl(px(28.)) + .pr(px(18.)) + .flex() + .items_center() + .justify_between() + .border_b_1() + .border_color(c(0x171717)) + .child(div().text_size(px(16.)).line_height(px(19.)).text_color(c(0xffffff)).child((section.label)())) + .child( + div() + .id("ce-close") + .mt(px(2.)) + .flex() + .flex_col() + .items_center() + .gap(px(2.)) + .cursor_pointer() + .group("ce-close") + .on_click(move |_, w, cx| close(Act::Close, w, cx)) + .child( + div() + .size(px(32.)) + .rounded_full() + .border_1() + .border_color(c(0x4a4a4a)) + .flex() + .items_center() + .justify_center() + .font_weight(FontWeight::SEMIBOLD) + .text_size(px(12.)) + .text_color(c(0x9a9a9a)) + .group_hover("ce-close", |d| d.text_color(c(0xffffff)).border_color(c(0x6a6a6a))) + .child("✕"), + ) + .child(div().font_weight(FontWeight::SEMIBOLD).text_size(px(9.)).line_height(px(10.)).text_color(c(0x9a9a9a)).child("ESC")), // i18n-exempt: key name + ), + ) + .child( + div() + .id(SharedString::from(format!("ce-scroll-{}", section.id))) + .flex_1() + .min_h_0() + .overflow_y_scroll() + .track_scroll(&m.scroll) + .when(m.anchor.is_some(), |d| d.on_scroll(click_wheel(on))) + .pt(px(12.)) + .pb(px(140.)) + .when(m.busy, |d| d.opacity(0.6)) + .when(compact, |d| d.pt(px(4.))) + .children(blocks.into_iter().enumerate().map(|(i, b)| { + let b = crate::kit::rise(("ce-content-in", i), b, 300, (0., 8., 1.), crate::kit::bezier(0.22, 1., 0.36, 1.)); + div().w_full().map(|d| if compact { d.px(px(18.)) } else { d.max_w(px(720.)).mx_auto().px(px(62.)) }).child(b) + })), + ) + .children(save_bar(m, on, cx)); + let card = div() + .id("ce-card") + .w_full() + .h_full() + .flex() + .when(compact, |d| d.flex_col()) + .when(!compact, |d| d.max_w(px(1182.)).max_h(px(862.)).rounded(px(18.)).border_1().border_color(c(0x2c2e2f))) + .bg(c(0x050505)) + .overflow_hidden() + .font_family(RUBIK) + .occlude() + .on_click(|_, _, cx| cx.stop_propagation()) + .child(nav) + .child(main); + let dismiss = on.clone(); + gpui::deferred( + div() + .id("ce-overlay") + .absolute() + .inset_0() + .bg(ca(0, 0, 0, 0.85)) + .flex() + .items_center() + .justify_center() + .when(!compact, |d| d.p(px(25.))) + .occlude() + .on_click(move |_, w, cx| dismiss(Act::Close, w, cx)) + .child(card), + ) + .with_priority(12) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn perms_parse_and_targets_sort() { + let v = serde_json::json!({ + "activated": true, "can_manage": true, "synced": null, "category": "ab", + "everyone_support": "18446744073709551615", + "roles": [{"role_id": "r2", "name": "Low", "color": 0, "position": 2}, {"role_id": "r1", "name": "High", "color": 5, "position": 1}], + "overwrites": [ + {"kind": "everyone", "id": null, "allow": "0", "deny": "16384"}, + {"kind": "role", "id": "r2", "allow": "16384", "deny": "0"}, + {"kind": "role", "id": "r1", "allow": "0", "deny": "0"}, + ], + "members": [], + }); + let p = Perms::parse(&v); + assert!(p.open() && !p.synced); + assert_eq!(p.support("everyone"), Some(u64::MAX)); + assert!(p.editable("everyone") && p.support("role:r1").is_none() && !p.editable("role:r1")); + assert_eq!(p.stored("everyone"), (0, 1 << 14)); + assert_eq!(p.stored("role:r2"), (1 << 14, 0)); + } +} diff --git a/crates/vector-gpui/src/chrome.rs b/crates/vector-gpui/src/chrome.rs new file mode 100644 index 000000000..3f0fc1b60 --- /dev/null +++ b/crates/vector-gpui/src/chrome.rs @@ -0,0 +1,31 @@ +//! The window's own title strip on every OS, as the desktop client draws it (`decorations: false`). + +/// macOS: a titled window under transparent chrome, since GPUI's untitled one can't resize, +/// minimise or close. Elsewhere none: the strip is all there is. +pub fn titlebar() -> Option { + if cfg!(target_os = "macos") { + Some(gpui::TitlebarOptions { title: None, appears_transparent: true, traffic_light_position: None }) + } else { + None + } +} + +/// The traffic lights go: the strip's own buttons stand in for them. +#[cfg(target_os = "macos")] +pub fn hide_native_controls(window: &gpui::Window) { + use objc2_app_kit::{NSView, NSWindowButton}; + use raw_window_handle::{HasWindowHandle, RawWindowHandle}; + let Ok(handle) = HasWindowHandle::window_handle(window) else { return }; + let RawWindowHandle::AppKit(h) = handle.as_raw() else { return }; + // SAFETY: AppKit's handle is the window's live content view, used on the main thread. + let view: &NSView = unsafe { h.ns_view.cast().as_ref() }; + let Some(ns_window) = view.window() else { return }; + for kind in [NSWindowButton::CloseButton, NSWindowButton::MiniaturizeButton, NSWindowButton::ZoomButton] { + if let Some(button) = ns_window.standardWindowButton(kind) { + button.setHidden(true); + } + } +} + +#[cfg(not(target_os = "macos"))] +pub fn hide_native_controls(_: &gpui::Window) {} diff --git a/crates/vector-gpui/src/cmdform.rs b/crates/vector-gpui/src/cmdform.rs new file mode 100644 index 000000000..62b1b45cd --- /dev/null +++ b/crates/vector-gpui/src/cmdform.rs @@ -0,0 +1,588 @@ +//! The structured command composer (`CommandComposer.svelte`): one pill per argument in +//! place of the draft, so quoting is the code's job and never the user's. + +use crate::kit::Tipped as _; +use gpui::{AnyElement, App, Context, Entity, EventEmitter, FocusHandle, Focusable, FontWeight, InteractiveElement, IntoElement, KeyDownEvent, ParentElement, Render, SharedString, StatefulInteractiveElement, Styled, Window, div, prelude::*, px}; +use crate::pic::img; + +use crate::commands::{Arg, ArgType, Cmd, arg_error}; +use crate::composer::{CancelInput, Edge, InputChanged, Look, Nav, SendText, TextInput}; +use crate::theme::*; + +/// A member a user argument can name. +#[derive(Clone)] +pub struct Member { + pub npub: String, + pub name: String, + pub avatar: Option, +} + +enum Field { + Text(Entity), + /// A choice or bool: a trigger that opens a drop-up. + Pick { focus: FocusHandle, value: String }, +} + +struct Part { + arg: Arg, + field: Field, + /// A user argument's picked member. + npub: Option, +} + +struct Menu { + part: usize, + /// (value, label, avatar); an empty value skips an optional argument. + options: Vec<(String, String, Option>)>, + active: usize, +} + +pub enum Event { + /// The assembled `/name args` text, for the send path. + Submit(String), + Exit, +} + +impl EventEmitter for CommandForm {} + +pub struct CommandForm { + pub cmd: Cmd, + pub chat: String, + parts: Vec, + pub invalid: Option, + pub focused: Option, + menu: Option
, + members: Vec, +} + +fn input_look(resolved: bool) -> Look { + Look { + family: INTER, + size: px(13.), + line_height: px(16.9), + color: if resolved { c(PRIMARY) } else { gpui::white() }, + weight: if resolved { FontWeight::SEMIBOLD } else { FontWeight::MEDIUM }, + placeholder: white_a(0.38), + ..Look::default() + } +} + +/// `assembleCommandText`: values with spaces or quotes quoted, so they re-parse whole. +pub fn assemble(name: &str, values: &[String]) -> String { + let mut out = format!("/{name}"); + for v in values { + out.push(' '); + if v.is_empty() || v.contains(|c: char| c.is_whitespace() || c == '"') { + out.push('"'); + out.push_str(&v.replace('\\', "\\\\").replace('"', "\\\"")); + out.push('"'); + } else { + out.push_str(v); + } + } + out +} + +impl CommandForm { + pub fn new(cmd: Cmd, chat: String, members: Vec, window: &mut Window, cx: &mut Context) -> Self { + let n = cmd.args.len(); + let parts = cmd + .args + .iter() + .enumerate() + .map(|(i, a)| { + let field = match a.kind { + ArgType::Choice | ArgType::Bool => Field::Pick { focus: cx.focus_handle(), value: String::new() }, + _ => { + let placeholder = if a.kind == ArgType::User { "npub1…" } else { "" }; + let max = if a.kind == ArgType::User { 70 } else { 1024 }; + let grow = a.kind == ArgType::String && i + 1 == n; + let input = cx.new(|cx| { + let t = TextInput::new(placeholder, cx).edges().keep_on_submit().max_chars(max).with_look(input_look(false)); + if grow { t.multiline(px(160.)) } else { t } + }); + cx.subscribe_in(&input, window, move |f, _, _: &SendText, w, cx| f.on_enter(i, w, cx)).detach(); + cx.subscribe_in(&input, window, |_, _, _: &CancelInput, _, cx| cx.emit(Event::Exit)).detach(); + cx.subscribe_in(&input, window, move |f, _, e: &Edge, w, cx| f.on_edge(i, *e, w, cx)).detach(); + cx.subscribe_in(&input, window, move |f, _, nav: &Nav, w, cx| f.on_nav(i, *nav, w, cx)).detach(); + cx.subscribe_in(&input, window, move |f, _, _: &InputChanged, w, cx| f.on_changed(i, w, cx)).detach(); + Field::Text(input) + } + }; + Part { arg: a.clone(), field, npub: None } + }) + .collect(); + Self { cmd, chat, parts, invalid: None, focused: None, menu: None, members } + } + + pub fn current_hint(&self) -> String { + self.focused.and_then(|i| self.parts.get(i)).map(|p| p.arg.description.clone()).unwrap_or_default() + } + + fn value(&self, i: usize, cx: &App) -> String { + let p = &self.parts[i]; + match &p.field { + Field::Pick { value, .. } => value.clone(), + Field::Text(t) => match &p.npub { + Some(n) => n.clone(), + None => t.read(cx).text().trim().to_string(), + }, + } + } + + pub fn focus(&mut self, i: usize, at_end: bool, window: &mut Window, cx: &mut Context) { + let Some(p) = self.parts.get(i) else { return }; + self.focused = Some(i); + match &p.field { + Field::Text(t) => { + window.focus(&t.focus_handle(cx), cx); + t.update(cx, |t, cx| { + let pos = if at_end { t.text().len() } else { 0 }; + t.set_caret(pos, cx); + }); + } + Field::Pick { focus, .. } => { + window.focus(focus, cx); + self.open_choices(i); + } + } + cx.notify(); + } + + fn close_menu(&mut self, cx: &mut Context) { + if let Some(m) = self.menu.take() + && let Some(Part { field: Field::Text(t), .. }) = self.parts.get(m.part) + { + t.update(cx, |t, _| t.set_nav(false)); + } + } + + fn open_choices(&mut self, i: usize) { + let p = &self.parts[i]; + let Field::Pick { value, .. } = &p.field else { return }; + let mut options = Vec::new(); + if !p.arg.required { + options.push((String::new(), "(skip)".to_string(), None)); + } + let values: Vec = if p.arg.kind == ArgType::Bool { vec!["true".into(), "false".into()] } else { p.arg.choices.clone() }; + options.extend(values.into_iter().map(|v| (v.clone(), v, None))); + if options.is_empty() { + return; + } + let active = options.iter().position(|o| o.0 == *value).unwrap_or(0); + self.menu = Some(Menu { part: i, options, active }); + } + + fn open_members(&mut self, i: usize, cx: &mut Context) { + let Some(Part { field: Field::Text(t), .. }) = self.parts.get(i) else { return }; + let q = t.read(cx).text().to_lowercase(); + let options: Vec<_> = self + .members + .iter() + .filter(|m| m.name.to_lowercase().contains(&q) || m.npub.to_lowercase().contains(&q)) + .take(6) + .map(|m| (m.npub.clone(), m.name.clone(), Some(m.avatar.clone()))) + .collect(); + let open = !options.is_empty(); + self.menu = open.then_some(Menu { part: i, options, active: 0 }); + t.update(cx, |t, _| t.set_nav(open)); + } + + fn pick(&mut self, k: usize, window: &mut Window, cx: &mut Context) { + let Some(menu) = self.menu.take() else { return }; + let Some((v, label, _)) = menu.options.get(k).cloned() else { return }; + let i = menu.part; + match &mut self.parts[i].field { + Field::Pick { value, .. } => *value = v, + Field::Text(t) => { + let t = t.clone(); + t.update(cx, |t, cx| { + t.set_nav(false); + t.set_text(&label, cx); + t.set_look(input_look(true), cx); + }); + self.parts[i].npub = Some(v); + } + } + self.invalid = None; + if i + 1 < self.parts.len() { + self.focus(i + 1, false, window, cx); + } + cx.notify(); + } + + fn on_enter(&mut self, i: usize, window: &mut Window, cx: &mut Context) { + let m = window.modifiers(); + if i + 1 == self.parts.len() || m.control || m.platform { + self.submit(window, cx); + } else { + self.focus(i + 1, false, window, cx); + } + } + + fn on_edge(&mut self, i: usize, e: Edge, window: &mut Window, cx: &mut Context) { + match e { + Edge::Empty if i == 0 => cx.emit(Event::Exit), + Edge::Empty | Edge::Start if i > 0 => self.focus(i - 1, true, window, cx), + Edge::End if i + 1 < self.parts.len() => self.focus(i + 1, false, window, cx), + _ => {} + } + } + + fn on_nav(&mut self, i: usize, nav: Nav, window: &mut Window, cx: &mut Context) { + let Some(menu) = self.menu.as_mut().filter(|m| m.part == i) else { return }; + let n = menu.options.len(); + match nav { + Nav::Up => menu.active = (menu.active + n - 1) % n, + Nav::Down => menu.active = (menu.active + 1) % n, + Nav::Pick => { + let k = menu.active; + return self.pick(k, window, cx); + } + Nav::Close => self.close_menu(cx), + } + cx.notify(); + } + + fn on_changed(&mut self, i: usize, _: &mut Window, cx: &mut Context) { + self.invalid = None; + self.focused = Some(i); + let p = &mut self.parts[i]; + if p.arg.kind == ArgType::User { + if p.npub.take().is_some() + && let Field::Text(t) = &p.field + { + t.update(cx, |t, cx| t.set_look(input_look(false), cx)); + } + self.open_members(i, cx); + } else if matches!(p.arg.kind, ArgType::Int | ArgType::Number) + && let Field::Text(t) = &p.field + { + let int = p.arg.kind == ArgType::Int; + t.update(cx, |t, cx| { + let raw = t.text().to_string(); + let mut out = String::new(); + let mut dot = false; + for ch in raw.chars() { + let keep = ch.is_ascii_digit() || (ch == '-' && out.is_empty()) || (ch == '.' && !int && !std::mem::replace(&mut dot, true)); + if keep { + out.push(ch); + } + } + if out != raw { + t.set_text(&out, cx); + } + }); + } + cx.notify(); + } + + fn on_pick_key(&mut self, i: usize, e: &KeyDownEvent, window: &mut Window, cx: &mut Context) { + let key = e.keystroke.key.as_str(); + let open = self.menu.as_ref().is_some_and(|m| m.part == i); + cx.stop_propagation(); + match key { + "up" | "down" if open => { + let m = self.menu.as_mut().expect("menu"); + let n = m.options.len(); + m.active = (m.active + if key == "down" { 1 } else { n - 1 }) % n; + } + "enter" | "space" if open => { + let k = self.menu.as_ref().map_or(0, |m| m.active); + return self.pick(k, window, cx); + } + "escape" if open => self.menu = None, + "up" | "down" | "space" => self.open_choices(i), + "backspace" | "delete" => { + let Field::Pick { value, .. } = &mut self.parts[i].field else { return }; + if !value.is_empty() { + value.clear(); + } else { + self.menu = None; + if i == 0 { + return cx.emit(Event::Exit); + } + return self.focus(i - 1, true, window, cx); + } + } + "enter" if i + 1 == self.parts.len() || e.keystroke.modifiers.control || e.keystroke.modifiers.platform => { + return self.submit(window, cx); + } + "enter" | "right" if i + 1 < self.parts.len() => return self.focus(i + 1, false, window, cx), + "left" if i > 0 => return self.focus(i - 1, true, window, cx), + "escape" => return cx.emit(Event::Exit), + "tab" => { + self.menu = None; + return cx.propagate(); + } + _ => return cx.propagate(), + } + cx.notify(); + } + + /// Validates every part and sends, or marks the first bad one. + pub fn submit(&mut self, window: &mut Window, cx: &mut Context) { + let values: Vec = (0..self.parts.len()).map(|i| self.value(i, cx)).collect(); + for (i, v) in values.iter().enumerate() { + let a = &self.parts[i].arg; + if (v.is_empty() && a.required) || (!v.is_empty() && arg_error(a, v).is_some()) { + self.invalid = Some(i); + self.focus(i, true, window, cx); + return; + } + } + let last = values.iter().rposition(|v| !v.is_empty()).map_or(0, |i| i + 1); + cx.emit(Event::Submit(assemble(&self.cmd.name, &values[..last]))); + } +} + +impl Render for CommandForm { + fn render(&mut self, window: &mut Window, cx: &mut Context) -> impl IntoElement { + let n = self.parts.len(); + let focused = self + .parts + .iter() + .position(|p| match &p.field { + Field::Text(t) => t.focus_handle(cx).contains_focused(window, cx), + Field::Pick { focus, .. } => focus.contains_focused(window, cx), + }); + if focused.is_some() && focused != self.focused { + self.focused = focused; + } + let pills = self.parts.iter().enumerate().map(|(i, p)| { + let grow = p.arg.kind == ArgType::String && i + 1 == n; + let on = focused == Some(i); + let name = div() + .flex_shrink_0() + .text_size(px(11.)) + .line_height(px(24.)) + .font_weight(FontWeight::SEMIBOLD) + .text_color(if on { gpui::white() } else { white_a(0.55) }) + .child(p.arg.name.to_lowercase()) + .when(p.arg.required, |d| d.child(div().text_color(c(0xff5d5d)).child("*"))) + .flex(); + let field: AnyElement = match &p.field { + Field::Text(t) => { + let chars = t.read(cx).text().chars().count().max(if p.arg.kind == ArgType::User { 6 } else { 0 }); + let w = (chars as f32 * 7.4 + 26.).clamp(72., 34. * 7.4); + let tip = p.arg.description.clone(); + div() + .id(SharedString::from(format!("cmd-field-{i}"))) + .when(!tip.is_empty(), |d| d.tip(tip)) + .bg(ca(0, 0, 0, 0.35)) + .rounded(px(7.)) + .px(px(8.)) + .py(px(2.)) + .min_w(px(60.)) + .when(on, |d| d.border_1().border_color(c(PRIMARY)).px(px(7.)).py(px(1.))) + .when(grow, |d| d.flex_1().min_w_0()) + .when(!grow, |d| d.w(px(w))) + .child(t.clone()) + .into_any_element() + } + Field::Pick { focus, value } => { + let focus = focus.clone(); + let tip = if value.is_empty() { p.arg.description.clone() } else { value.clone() }; + div() + .id(SharedString::from(format!("cmd-pick-{i}"))) + .when(!tip.is_empty(), |d| d.tip(tip)) + .track_focus(&focus) + .relative() + .flex() + .items_center() + .h(px(21.)) + .min_w(px(72.)) + .max_w(px(22. * 7.4)) + .pl(px(8.)) + .pr(px(20.)) + .rounded(px(7.)) + .bg(ca(0, 0, 0, 0.35)) + .when(on, |d| d.border_1().border_color(c(PRIMARY)).pl(px(7.)).pr(px(19.))) + .cursor_pointer() + .text_size(px(13.)) + .text_color(if value.is_empty() { white_a(0.4) } else { gpui::white() }) + .child(div().truncate().child(if value.is_empty() { "…".to_string() } else { value.clone() })) + .child( + gpui::svg() + .path("icons/chevron-down.svg") + .absolute() + .right(px(6.)) + .size(px(9.)) + .text_color(white_a(0.55)), + ) + .on_key_down(cx.listener(move |f, e: &KeyDownEvent, w, cx| f.on_pick_key(i, e, w, cx))) + .on_mouse_down( + gpui::MouseButton::Left, + cx.listener(move |f, _, w, cx| { + cx.stop_propagation(); + if f.menu.as_ref().is_some_and(|m| m.part == i) { + f.menu = None; + f.focused = Some(i); + if let Some(Part { field: Field::Pick { focus, .. }, .. }) = f.parts.get(i) { + w.focus(focus, cx); + } + cx.notify(); + } else { + f.focus(i, false, w, cx); + } + }), + ) + .into_any_element() + } + }; + let menu = self.menu.as_ref().filter(|m| m.part == i).map(|m| { + let rows = m.options.iter().enumerate().map(|(k, (v, label, face))| { + div() + .id(SharedString::from(format!("cmd-opt-{k}"))) + .tip(label.clone()) + .flex() + .items_center() + .gap(px(8.)) + .px(px(14.)) + .py(px(6.)) + .text_size(px(13.)) + .text_color(if v.is_empty() { white_a(0.4) } else { white_a(0.9) }) + .cursor_pointer() + .when(k == m.active, |d| d.bg(white_a(0.08))) + .hover(|d| d.bg(white_a(0.08))) + .on_mouse_down( + gpui::MouseButton::Left, + cx.listener(move |f, _, w, cx| { + cx.stop_propagation(); + f.pick(k, w, cx) + }), + ) + .children(face.as_ref().map(|a| match a { + Some(p) => crate::pic::img_face(p.clone(), 18.).object_fit(gpui::ObjectFit::Cover).size(px(18.)).rounded_full().flex_shrink_0().into_any_element(), + None => img("icons/user-placeholder.svg").size(px(18.)).rounded_full().flex_shrink_0().into_any_element(), + })) + .child(div().truncate().max_w(px(40. * 7.)).child(label.clone())) + }); + gpui::deferred( + div() + .absolute() + .bottom_full() + .left_0() + .mb(px(6.)) + .min_w(px(112.)) + .bg(c(0x0a0a0a)) + .border_1() + .border_color(c(PRIMARY)) + .rounded(px(10.)) + .overflow_hidden() + .children(rows), + ) + .with_priority(4) + }); + div() + .relative() + .flex() + .items_center() + .gap(px(6.)) + .pl(px(8.)) + .pr(px(3.)) + .py(px(2.)) + .rounded(px(10.)) + .bg(white_a(0.07)) + .border_1() + .border_color(if self.invalid == Some(i) { c(0xff5d5d) } else { white_a(0.1) }) + .max_w_full() + .when(grow, |d| d.flex_1().min_w(px(150.))) + .when(!grow, |d| d.flex_shrink_0()) + .child(name) + .child(div().relative().when(grow, |d| d.flex_1().min_w_0()).child(field).children(menu)) + }); + div() + .flex() + .flex_wrap() + .items_center() + .content_center() + .gap(px(5.)) + .min_h(px(45.)) + .w_full() + .min_w_0() + .pl(px(12.)) + .pr(px(10.)) + .py(px(6.)) + .children(pills) + } +} + +/// `#chat-command-bar`: "Using /cmd with Bot", the focused argument's description, Cancel. +pub fn strip(form: &CommandForm, bot: (SharedString, Option), on_cancel: impl Fn(&mut Window, &mut App) + 'static) -> AnyElement { + let html = crate::t::command_using(crate::kit::escape(&bot.0), crate::kit::escape(&format!("/{}", form.cmd.name))); + let (before, name, after) = crate::kit::around(&html, "bot"); + let accent = gpui::HighlightStyle { color: Some(c(PRIMARY)), font_weight: Some(FontWeight::SEMIBOLD), ..Default::default() }; + let words = |text: &str| { + let text = text.trim_matches(['\u{a0}', ' ']); + (!text.is_empty()).then(|| { + div() + .flex_shrink_0() + .whitespace_nowrap() + .text_size(px(13.5)) + .text_color(white_a(0.85)) + .child(crate::kit::run_text(text, accent)) + }) + }; + let sentence = div() + .flex() + .items_center() + .gap(px(8.)) + .min_w_0() + .when(crate::kit::reads_ltr(&html), |d| d.keep_ltr()) + .children(words(&before)) + .child( + div() + .flex() + .items_center() + .gap(px(5.)) + .min_w_0() + .text_size(px(13.)) + .font_weight(FontWeight::SEMIBOLD) + .text_color(c(PRIMARY)) + .child(match bot.1 { + Some(p) => crate::pic::img_face(p, 16.).object_fit(gpui::ObjectFit::Cover).size(px(16.)).rounded_full().flex_shrink_0().into_any_element(), + None => img("icons/user-placeholder.svg").size(px(16.)).rounded_full().flex_shrink_0().into_any_element(), + }) + .child(div().min_w_0().truncate().child(crate::kit::untag(&name).0)), + ) + .children(words(&after)); + div() + .size_full() + .flex() + .items_center() + .gap(px(8.)) + .child(sentence) + .child( + div() + .flex_1() + .min_w_0() + .truncate() + .text_right() + .text_size(px(12.)) + .text_color(white_a(0.45)) + .child(form.current_hint()), + ) + .child( + div() + .id("command-cancel") + .absolute() + .right(px(10.5 - 44.)) + .size(px(24.)) + .p(px(3.)) + .cursor_pointer() + .on_click(move |_, w, cx| on_cancel(w, cx)) + .child(gpui::svg().path("icons/cancel.svg").size(px(18.)).text_color(c(crate::timeline::DANGER))), + ) + .into_any_element() +} + +#[cfg(test)] +mod tests { + #[test] + fn assembles_quoted() { + let v = |s: &[&str]| s.iter().map(|x| x.to_string()).collect::>(); + assert_eq!(super::assemble("say", &v(&["hi there", "a\"b", "x"])), r#"/say "hi there" "a\"b" x"#); + assert_eq!(super::assemble("roll", &v(&["", "6"])), r#"/roll "" 6"#); + } +} diff --git a/crates/vector-gpui/src/commands.rs b/crates/vector-gpui/src/commands.rs new file mode 100644 index 000000000..ee50f7b50 --- /dev/null +++ b/crates/vector-gpui/src/commands.rs @@ -0,0 +1,950 @@ +//! The `/` command picker (`command-picker.js`, `CommandPopup.svelte`): the sectioned list +//! while the name is being typed, then the armed command's hint row. + +use crate::kit::Tipped as _; +use std::rc::Rc; + +use gpui::{AnyElement, App, FontWeight, Hsla, InteractiveElement, IntoElement, ParentElement, SharedString, StatefulInteractiveElement, Styled, Window, div, prelude::*, px}; +use crate::pic::img; + +use crate::textcolor; +use crate::t; +use crate::theme::*; + +pub const SYSTEM: &str = "system"; +const RECENTS_CAP: usize = 8; + +#[derive(Clone, Debug, PartialEq)] +pub enum ArgType { + String, + Int, + Number, + Bool, + User, + Choice, + Color, +} + +#[derive(Clone, Debug)] +pub struct Arg { + pub name: String, + pub kind: ArgType, + pub required: bool, + pub description: String, + pub choices: Vec, +} + +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum Builtin { + Effect, + Time, + Face(&'static str), + Coinflip, +} + +#[derive(Clone, Debug)] +pub struct Cmd { + /// `system`, or the bot's npub. + pub bot: String, + pub name: String, + pub description: String, + pub args: Vec, + pub builtin: Option, + pub aliases: &'static [&'static str], +} + +impl Cmd { + pub fn is_system(&self) -> bool { + self.bot == SYSTEM + } + + fn key(&self) -> String { + format!("{}:{}", self.bot, self.name) + } +} + +fn arg(name: &str, kind: ArgType, required: bool, description: String) -> Arg { + Arg { name: name.into(), kind, required, description, choices: Vec::new() } +} + +/// Commands built into Vector, listed after every bot's; a bot declaring the same name wins. +pub fn system_commands(effects: bool) -> Vec { + let w = textcolor::color_word(); + let sys = |name: &str, description: String, args: Vec, builtin, aliases| Cmd { + bot: SYSTEM.into(), + name: name.into(), + description, + args, + builtin: Some(builtin), + aliases, + }; + let ws = format!("{w}s"); + let text = || arg("text", ArgType::String, true, t::command_text_arg(w).into()); + let message = || arg("message", ArgType::String, false, t::command_message_arg().into()); + let mut out = Vec::new(); + if effects { + out.push(sys("rainbow", t::command_rainbow(ws.as_str()).into(), vec![text()], Builtin::Effect, &[])); + out.push(sys( + "gradient", + t::command_gradient(w).into(), + vec![ + arg("from", ArgType::Color, true, t::command_gradient_from(w).into()), + arg("to", ArgType::Color, true, t::command_gradient_to(w).into()), + text(), + ], + Builtin::Effect, + &[], + )); + out.push(sys( + w, + t::command_colour(w).into(), + vec![arg(w, ArgType::Color, true, t::command_colour_arg(w).into()), text()], + Builtin::Effect, + &[], + )); + } + out.push(sys( + "time", + t::command_time().into(), + vec![arg("when", ArgType::String, true, t::command_time_arg().into())], + Builtin::Time, + &[], + )); + out.push(sys("shrug", t::command_face("¯\\_(ツ)_/¯").into(), vec![message()], Builtin::Face("¯\\_(ツ)_/¯"), &[])); + out.push(sys( + "flip", + t::command_face("(╯°□°)╯︵ ┻━┻").into(), + vec![message()], + Builtin::Face("(╯°□°)╯︵ ┻━┻"), + &["tableflip"], + )); + out.push(sys("unflip", t::command_face("┬─┬ノ( º _ ºノ)").into(), vec![message()], Builtin::Face("┬─┬ノ( º _ ºノ)"), &[])); + out.push(sys("coinflip", t::command_coinflip().into(), Vec::new(), Builtin::Coinflip, &[])); + out +} + +/// The text a builtin with a fixed output sends. +fn builtin_text(b: Builtin, rest: &str) -> Option { + match b { + Builtin::Face(face) if rest.is_empty() => Some(face.into()), + Builtin::Face(face) => Some(format!("{rest} {face}")), // i18n-exempt: the text, then the face + // Decided on the sender's device, as any dice roll in a chat is. + Builtin::Coinflip => { + let heads = rand::random::(); + Some(if heads { t::command_coinflip_heads() } else { t::command_coinflip_tails() }.into()) + } + _ => None, + } +} + +/// A bot's command set, as a manifest declares it. +pub fn bot_commands(bot: &str, specs: &[vector_core::bot_interface::CommandSpec]) -> Vec { + use vector_core::bot_interface::ArgType as T; + specs + .iter() + .map(|c| Cmd { + bot: bot.into(), + name: c.name.clone(), + description: crate::kit::one_line(&c.description).into_owned(), + args: c + .args + .iter() + .map(|a| Arg { + name: a.name.clone(), + kind: match a.arg_type { + T::String => ArgType::String, + T::Int => ArgType::Int, + T::Number => ArgType::Number, + T::Bool => ArgType::Bool, + T::User => ArgType::User, + T::Choice => ArgType::Choice, + }, + required: a.required, + description: crate::kit::one_line(&a.description).into_owned(), + choices: a.choices.clone(), + }) + .collect(), + builtin: None, + aliases: &[], + }) + .collect() +} + +/// One shell-style token from `s[i..]`: its value and where it ends; `Err` on an open quote. +fn next_token(s: &str, i: usize) -> Option> { + let rest = &s[i..]; + let start = i + (rest.len() - rest.trim_start().len()); + if start >= s.len() { + return None; + } + let mut out = String::new(); + if s[start..].starts_with('"') { + let mut it = s[start + 1..].char_indices().peekable(); + while let Some((k, c)) = it.next() { + match c { + '\\' if matches!(it.peek(), Some((_, '"' | '\\'))) => out.push(it.next().map_or(c, |x| x.1)), + '"' => return Some(Ok((out, start + 1 + k + 1))), + c => out.push(c), + } + } + return Some(Err(())); + } + let len = s[start..].find(char::is_whitespace).unwrap_or(s.len() - start); + Some(Ok((s[start..start + len].to_string(), start + len))) +} + +/// Positional parse of what follows the name; an unquoted trailing string swallows the rest. +fn parse_args(cmd: &Cmd, rest: &str) -> Option> { + let mut out = Vec::new(); + let mut cursor = 0; + for (i, a) in cmd.args.iter().enumerate() { + let remainder = rest[cursor..].trim_start(); + if remainder.is_empty() { + break; + } + let value = if i + 1 == cmd.args.len() && a.kind == ArgType::String && !remainder.starts_with('"') { + cursor = rest.len(); + remainder.trim_end().to_string() + } else { + match next_token(rest, cursor) { + None => break, + Some(Err(())) => return None, + Some(Ok((v, next))) => { + cursor = next; + v + } + } + }; + if value.is_empty() && !a.required { + continue; + } + out.push((a.name.clone(), value)); + } + Some(out) +} + +/// Why `v` doesn't fit `a`, naming the argument. +pub fn arg_error(a: &Arg, v: &str) -> Option { + let n = a.name.as_str(); + if v.len() > 1024 { + return Some(t::command_arg_too_long(n)); + } + let bad = match a.kind { + ArgType::Int => { + let d = v.strip_prefix(['+', '-']).unwrap_or(v); + (d.is_empty() || !d.bytes().all(|b| b.is_ascii_digit())).then(|| t::command_arg_whole_number(n)) + } + ArgType::Number => (v.trim().is_empty() || !v.trim().parse::().is_ok_and(f64::is_finite)).then(|| t::command_arg_number(n)), + // i18n-exempt: accepted input words + ArgType::Bool => (!["true", "false", "yes", "no", "1", "0"].contains(&v.to_lowercase().as_str())).then(|| t::command_arg_bool(n)), + ArgType::User => (!v.starts_with("npub1") || v.len() > 70).then(|| t::command_arg_user(n)), + ArgType::Choice => (!a.choices.iter().any(|c| c == v)).then(|| t::command_arg_choice(a.choices.join(", "), n)), + ArgType::Color => vector_core::text_color::hex(v).is_none().then(|| t::command_arg_colour(textcolor::color_word(), n)), + ArgType::String => None, + }; + bad +} + +fn validate(cmd: &Cmd, parsed: &[(String, String)]) -> Option { + for a in &cmd.args { + match parsed.iter().find(|(n, _)| *n == a.name) { + None if a.required => return Some(t::command_arg_missing(a.name.as_str()).into()), + None => {} + Some((_, v)) => { + if let Some(e) = arg_error(a, v) { + return Some(e.into()); + } + } + } + } + None +} + +/// What a send does with its text. +#[derive(Debug, PartialEq)] +pub enum Route { + /// Ordinary chat text, unknown `/words` included. + Plain, + /// A known command with bad arguments: the send is refused and the draft kept. + Error(String), + /// A builtin rewrote the text. + Text(String), + /// A bot's command, tagged to it. + Bot(String), +} + +pub struct Row { + pub index: usize, + pub cmd: Cmd, + pub show_bot: bool, +} + +pub struct Section { + pub key: String, + pub title: SharedString, + pub avatar: Option, + pub refreshing: bool, + pub rows: Vec, +} + +pub struct Hint { + pub cmd: Cmd, + pub current: usize, + pub preview: Option>, + pub choices: Vec<(String, Option)>, +} + +pub enum View { + Loading(String), + List { sections: Vec
, active: usize, count: usize }, + Hint(Hint), +} + +/// A chat's bot commands as the backend last answered. +#[derive(Clone, Default)] +pub struct Snapshot { + pub bots: usize, + pub commands: Vec, + pub fresh: bool, +} + +#[derive(Default)] +pub struct Picker { + pub view: Option, + pub active: usize, + /// The explicitly picked command: (chat, bot, name). + pub armed: Option<(String, String, String)>, + pub suppressed: Option, + pub recents: Vec, +} + +pub struct Ctx<'a> { + pub chat: &'a str, + pub snapshot: Option<&'a Snapshot>, + pub loading: bool, + pub effects: bool, + pub bot_name: &'a dyn Fn(&str) -> (SharedString, Option), +} + +impl Ctx<'_> { + fn all(&self) -> Vec { + let mut out: Vec = self.snapshot.map(|s| s.commands.clone()).unwrap_or_default(); + out.extend(system_commands(self.effects)); + out + } +} + +impl Picker { + pub fn is_list(&self) -> bool { + matches!(self.view, Some(View::List { .. } | View::Loading(_))) + } + + pub fn is_hint(&self) -> bool { + matches!(self.view, Some(View::Hint(_))) + } + + pub fn close(&mut self) { + self.view = None; + self.active = 0; + } + + fn resolve(&self, ctx: &Ctx, name: &str) -> Option { + let all = ctx.all(); + let prefer = self.armed.as_ref().filter(|a| a.2 == name).map(|a| a.1.clone()); + let named: Vec<&Cmd> = all.iter().filter(|c| c.name == name).collect(); + if let Some(c) = prefer.and_then(|b| named.iter().find(|c| c.bot == b)) { + return Some((*c).clone()); + } + if let Some(c) = named.first() { + return Some((*c).clone()); + } + let word = textcolor::color_word(); + all.iter() + .find(|c| c.is_system() && ((["color", "colour"].contains(&name) && c.name == word) || c.aliases.contains(&name))) + .cloned() + } + + /// Whether `/name` runs Vector's own command here. + pub fn system_owns(&self, ctx: &Ctx, name: &str) -> bool { + self.resolve(ctx, name).is_some_and(|c| c.is_system()) + } + + fn bump(&mut self, cmd: &Cmd) { + let key = cmd.key(); + self.recents.retain(|k| *k != key); + self.recents.insert(0, key); + self.recents.truncate(RECENTS_CAP); + } + + /// Re-read the draft: the list while the name is typed, the hint once past it. + pub fn on_input(&mut self, ctx: &Ctx, text: &str) { + if !text.starts_with('/') { + self.armed = None; + self.suppressed = None; + return self.close(); + } + if self.armed.as_ref().is_some_and(|a| a.0 != ctx.chat) { + self.armed = None; + } + if self.suppressed.as_deref().is_some_and(|s| s != text) { + self.suppressed = None; + } + let Some(end) = text.find(char::is_whitespace) else { + self.active = 0; + return self.render(ctx, &text[1..]); + }; + let name = &text[1..end]; + match self.resolve(ctx, name) { + Some(c) if c.builtin == Some(Builtin::Time) => self.close(), + Some(c) if self.suppressed.as_deref() != Some(text) => self.hint(c, &text[end..]), + _ => self.close(), + } + } + + fn render(&mut self, ctx: &Ctx, query: &str) { + let q = query.to_lowercase(); + let mut matches: Vec = ctx.all().into_iter().filter(|c| c.name.contains(&q)).collect(); + matches.sort_by_key(|c| !c.name.starts_with(&q)); + if matches.is_empty() { + let snap = ctx.snapshot; + if snap.is_none() || (ctx.loading && snap.is_some_and(|s| s.bots != 0)) { + let n = snap.map_or(0, |s| s.bots); + let label = if n > 0 { + t::command_loading_bots(n).into() + } else { + t::command_finding_bots().into() + }; + self.view = Some(View::Loading(label)); + } else { + self.close(); + } + return; + } + let recent: Vec = self + .recents + .iter() + .filter_map(|k| matches.iter().find(|c| c.key() == *k).cloned()) + .collect(); + let mut sections = Vec::new(); + let mut count = 0; + let mut section = |key: String, title: SharedString, avatar, cmds: Vec, show_bot, refreshing| { + let rows = cmds + .into_iter() + .map(|cmd| { + count += 1; + Row { index: count - 1, cmd, show_bot } + }) + .collect(); + sections.push(Section { key, title, avatar, refreshing, rows }); + }; + if !recent.is_empty() { + section("recent".into(), t::command_recent(), None, recent, true, false); + } + let refreshing = ctx.snapshot.is_some_and(|s| !s.fresh); + let mut bots: Vec = Vec::new(); + for c in &matches { + if !bots.contains(&c.bot) { + bots.push(c.bot.clone()); + } + } + for bot in bots { + let cmds: Vec = matches.iter().filter(|c| c.bot == bot).cloned().collect(); + let (title, avatar) = if bot == SYSTEM { + ("Vector".into(), Some(Face::Mark)) // i18n-exempt: the app's name + } else { + let (name, path) = (ctx.bot_name)(&bot); + (name, Some(path.map_or(Face::Placeholder, Face::Path))) + }; + let refresh = refreshing && bot != SYSTEM; + section(bot, title, avatar, cmds, false, refresh); + } + if self.active >= count { + self.active = 0; + } + self.view = Some(View::List { sections, active: self.active, count }); + } + + fn hint(&mut self, cmd: Cmd, rest: &str) { + let mut filled = 0; + let mut cursor = 0; + let mut partial = String::new(); + while filled < cmd.args.len() { + let Some(Ok((v, next))) = next_token(rest, cursor) else { break }; + if next >= rest.len() && !rest.ends_with(char::is_whitespace) { + partial = v; + break; + } + cursor = next; + filled += 1; + } + let current = filled.min(cmd.args.len().saturating_sub(1)); + let preview = cmd.is_system().then(|| { + let mut typed = Vec::new(); + let mut at = 0; + while typed.len() < 2 { + let Some(Ok((v, next))) = next_token(rest, at) else { break }; + typed.push(v); + at = next; + } + textcolor::effect_preview(&cmd.name, &typed) + }); + let choices = match cmd.args.get(current).map(|a| &a.kind) { + Some(ArgType::Choice) => cmd.args[current].choices.iter().map(|c| (c.clone(), None)).collect(), + Some(ArgType::Color) => textcolor::color_choices(&partial).into_iter().map(|(n, c)| (n, Some(c))).collect(), + _ => Vec::new(), + }; + self.view = Some(View::Hint(Hint { cmd, current, preview: preview.flatten(), choices })); + } + + pub fn move_active(&mut self, ctx: &Ctx, text: &str, by: isize) { + if let Some(View::List { count, .. }) = self.view + && count > 0 + { + self.active = (self.active as isize + by).rem_euclid(count as isize) as usize; + self.on_input(ctx, text); + } + } + + pub fn row(&self, i: usize) -> Option { + let Some(View::List { sections, .. }) = &self.view else { return None }; + sections.iter().flat_map(|s| &s.rows).find(|r| r.index == i).map(|r| r.cmd.clone()) + } + + /// A pick: the text the draft becomes, and whether that is the send. + pub fn select(&mut self, chat: &str, cmd: &Cmd) -> (String, bool) { + self.suppressed = None; + self.close(); + self.armed = Some((chat.into(), cmd.bot.clone(), cmd.name.clone())); + if cmd.args.is_empty() { + return (format!("/{}", cmd.name), true); + } + (format!("/{} ", cmd.name), false) + } + + /// The hint's choice in place of the word being typed. + pub fn insert_choice(text: &str, value: &str) -> String { + let base = if text.ends_with(char::is_whitespace) { + text.to_string() + } else { + let cut = text.rfind(char::is_whitespace).map_or(0, |i| i + 1); + text[..cut].to_string() + }; + let base = if base.starts_with('/') { base } else if text.ends_with(' ') { text.into() } else { format!("{text} ") }; // i18n-exempt: joins typed text + format!("{base}{value} ") // i18n-exempt: joins typed text + } + + pub fn first_choice(&self) -> Option { + match &self.view { + Some(View::Hint(h)) => h.choices.first().map(|c| c.0.clone()), + _ => None, + } + } + + pub fn suppress(&mut self, text: &str) { + self.suppressed = Some(text.into()); + self.close(); + } + + /// Send-time routing (`routeForSend`). + pub fn route(&mut self, ctx: &Ctx, text: &str) -> Route { + let Some(rest) = text.strip_prefix('/') else { return Route::Plain }; + if rest.starts_with('"') { + return Route::Plain; + } + let Some(Ok((name, next))) = next_token(rest, 0) else { return Route::Plain }; + if name.is_empty() { + return Route::Plain; + } + let Some(cmd) = self.resolve(ctx, &name) else { return Route::Plain }; + let after = &rest[next..]; + if let Some(t) = cmd.builtin.and_then(|b| builtin_text(b, after.trim())) { + self.bump(&cmd); + self.armed = None; + self.close(); + return Route::Text(t); + } + if cmd.builtin == Some(Builtin::Effect) { + let picked = self.armed.as_ref().is_some_and(|a| a.0 == ctx.chat && a.1 == SYSTEM && a.2 == cmd.name); + return match textcolor::command(text) { + Some(c) if c.body.is_ok() => { + self.bump(&cmd); + self.armed = None; + self.close(); + textcolor::command_to_markup(text).map_or(Route::Plain, Route::Text) + } + Some(c) if picked => Route::Error(format!("/{} {}", cmd.name, c.body.err().unwrap_or_default())), + _ => Route::Plain, + }; + } + if cmd.is_system() { + return Route::Plain; + } + let Some(parsed) = parse_args(&cmd, after) else { + return Route::Error(t::command_unclosed_quote(name).into()); + }; + if let Some(e) = validate(&cmd, &parsed) { + return Route::Error(t::command_error(name, e).into()); + } + self.bump(&cmd); + self.armed = None; + self.close(); + Route::Bot(cmd.bot) + } +} + +const PANEL_BG: u32 = 0x0a0a0a; + +fn arg_chip(label: &str, optional: bool, current: bool) -> gpui::Div { + div() + .flex_shrink_0() + .px(px(6.)) + .py(px(1.)) + .rounded(px(4.)) + .text_size(px(12.)) + .line_height(px(24.)) + .when(current, |d| d.bg(c(PRIMARY)).text_color(c(PANEL_BG)).font_weight(FontWeight::SEMIBOLD)) + .when(!current, |d| d.bg(ca(255, 255, 255, 0.08)).text_color(ca(255, 255, 255, 0.75))) + .when(optional && !current, |d| d.opacity(0.55)) + .child(label.to_string()) +} + +#[derive(Clone)] +pub enum Face { + /// Vector's own commands wear the logo mark, a tall shape rather than a face. + Mark, + Path(std::path::PathBuf), + Placeholder, +} + +fn avatar(face: &Face) -> AnyElement { + let base = |i: gpui::Stateful| i.size(px(16.)).flex_shrink_0(); + match face { + Face::Mark => base(img("icons/vector-mark.svg")).object_fit(gpui::ObjectFit::Contain).into_any_element(), + Face::Path(p) => base(crate::pic::img_face(p.clone(), 40.).object_fit(gpui::ObjectFit::Cover)).rounded_full().into_any_element(), + Face::Placeholder => base(img("icons/user-placeholder.svg")).rounded_full().into_any_element(), + } +} + +fn spinner(size: f32) -> AnyElement { + let thick = if size < 12. { 1.5 } else { 2. }; + div() + .size(px(size)) + .flex_shrink_0() + .child(crate::attachments::spinner(size, thick, 0.8, 0.25, ca(255, 255, 255, 0.15), c(PRIMARY))) + .into_any_element() +} + +/// `.command-selector`, anchored above the composer. +pub fn view( + p: &Picker, + bot_face: &dyn Fn(&str) -> (SharedString, Option), + pick: Rc, + choose: Rc, + vw: f32, +) -> Option { + let narrow = vw <= 520.; + let view = p.view.as_ref()?; + let panel = div() + .id("command-selector") + .absolute() + .bottom(px(-1.)) + // `AnchoredPanel`'s `viewportInset`: 10px clear of a phone's edges. + .when(vw < 900., |d| d.left(px(10.))) + .when(vw >= 900., |d| d.left_0()) + .w_full() + .max_w(px(422f32.min(vw - 18.))) + .max_h(px(328.)) + .overflow_y_scroll() + // The wheel belongs to the list, never the chat behind it. + .occlude() + .bg(c(PANEL_BG)) + .border_1() + .border_color(c(PRIMARY)) + .rounded(px(12.)) + .shadow(vec![gpui::BoxShadow { + color: ca(0, 0, 0, 0.5), + offset: gpui::point(px(0.), px(-8.)), + blur_radius: px(32.), + spread_radius: px(0.), + inset: false, + }]) + .on_mouse_down(gpui::MouseButton::Left, |_, _, cx| cx.stop_propagation()); + let body: AnyElement = match view { + View::Loading(label) => panel + .min_h(px(56.)) + .flex() + .items_center() + .justify_center() + .child( + div() + .flex() + .items_center() + .gap(px(10.)) + .px(px(12.)) + .py(px(10.)) + .text_size(px(13.)) + .text_color(ca(255, 255, 255, 0.65)) + .child(spinner(14.)) + .child(label.clone()), + ) + .into_any_element(), + View::List { sections, active, .. } => panel + .pb(px(6.)) + .children(sections.iter().map(|s| { + let header = div() + .flex() + .items_center() + .gap(px(6.)) + .px(px(12.)) + .pt(px(8.)) + .pb(px(4.)) + .bg(c(PANEL_BG)) + .text_size(px(11.)) + .line_height(px(24.)) + .font_weight(FontWeight::SEMIBOLD) + .text_color(c(PRIMARY)) + .children(s.avatar.as_ref().map(avatar)) + .child(div().opacity(0.7).min_w_0().truncate().child(s.title.to_uppercase())) + .when(s.refreshing, |d| { + d.child( + div() + .ml_auto() + .flex() + .items_center() + .gap(px(5.)) + .text_size(px(10.)) + .font_weight(FontWeight::MEDIUM) + .text_color(ca(255, 255, 255, 0.42)) + .child(spinner(9.)) + .child(t::command_checking_updates()), + ) + }); + div().flex().flex_col().child(header).children(s.rows.iter().map(|r| { + let i = r.index; + let pick = pick.clone(); + let on = i == *active; + let (face, tip) = if !r.show_bot { + (None, None) + } else if r.cmd.is_system() { + (Some(avatar(&Face::Mark)), Some(SharedString::from("Vector"))) // i18n-exempt: the app's name + } else { + let (name, path) = bot_face(&r.cmd.bot); + (Some(avatar(&path.map_or(Face::Placeholder, Face::Path))), Some(name)) + }; + div() + .id(SharedString::from(format!("cmd-{}", r.cmd.key()))) + .when_some(tip, |d, t| d.tip(t)) + .relative() + .flex() + .flex_wrap() + .items_center() + .gap_x(px(8.)) + .gap_y(px(2.)) + .px(px(12.)) + .py(px(8.)) + .min_w_0() + .cursor_pointer() + .text_size(px(14.)) + .line_height(px(24.)) + .text_color(ca(255, 255, 255, 0.9)) + .when(on, |d| d.bg(ca(255, 255, 255, 0.08))) + .hover(|d| d.bg(ca(255, 255, 255, 0.08))) + .when(on, |d| { + d.child( + div() + .absolute() + .left_0() + .top(px(4.)) + .bottom(px(4.)) + .w(px(3.)) + .rounded_r(px(3.)) + .bg(c(PRIMARY)), + ) + }) + .on_mouse_down(gpui::MouseButton::Left, move |_, w, cx| { + cx.stop_propagation(); + pick(i, w, cx) + }) + .children(face) + .child( + div() + .flex_shrink_0() + .font_weight(FontWeight::SEMIBOLD) + .text_color(gpui::white()) + .child(format!("/{}", r.cmd.name)), + ) + .children(r.cmd.args.iter().map(|a| arg_chip(&a.name, !a.required, false))) + .when(!r.cmd.description.is_empty(), |d| { + d.child( + div() + .min_w_0() + .map(|d| { + if narrow { + d.flex_basis(gpui::relative(1.)).mt(px(-1.)).line_height(px(15.)).line_clamp(2).text_ellipsis() + } else { + d.flex_1().truncate().text_right() + } + }) + .text_size(px(12.)) + .text_color(ca(255, 255, 255, 0.45)) + .child(r.cmd.description.clone()), + ) + }) + })) + })) + .into_any_element(), + View::Hint(h) => { + let cur = h.cmd.args.get(h.current); + panel + .child( + div() + .flex() + .items_center() + .gap(px(6.)) + .px(px(12.)) + .pt(px(8.)) + .pb(px(6.)) + .text_size(px(14.)) + .line_height(px(24.)) + .min_w_0() + .child( + div() + .flex_shrink_0() + .font_weight(FontWeight::SEMIBOLD) + .text_color(gpui::white()) + .child(format!("/{}", h.cmd.name)), + ) + .children(h.cmd.args.iter().enumerate().map(|(i, a)| { + arg_chip(&a.name, !a.required, i == h.current) + .id(SharedString::from(format!("hint-arg-{i}"))) + .when(!a.description.is_empty(), |d| d.tip(a.description.clone())) + })) + .when(!h.cmd.description.is_empty(), |d| { + d.child( + div() + .ml_auto() + .pl(px(8.)) + .min_w_0() + .truncate() + .text_size(px(12.)) + .text_color(ca(255, 255, 255, 0.45)) + .child(h.cmd.description.clone()), + ) + }), + ) + .children(h.preview.as_ref().map(|stops| { + let n = stops.len().max(2) - 1; + div().h(px(4.)).mx(px(12.)).mb(px(6.)).rounded(px(2.)).flex().overflow_hidden().children( + stops.windows(2).map(|w| { + div().flex_1().h_full().bg(gpui::linear_gradient( + 90., + gpui::linear_color_stop(w[0], 0.), + gpui::linear_color_stop(w[1], 1.), + )) + }).collect::>(), + ).when(n == 0, |d| d) + })) + .children(cur.filter(|a| !a.description.is_empty()).map(|a| { + div() + .flex() + .items_baseline() + .gap(px(6.)) + .px(px(12.)) + .pb(px(8.)) + .text_size(px(12.)) + .line_height(px(24.)) + .text_color(ca(255, 255, 255, 0.6)) + .child(div().flex_shrink_0().font_weight(FontWeight::SEMIBOLD).text_color(c(PRIMARY)).child(a.name.clone())) + .child(a.description.clone()) + })) + .when(!h.choices.is_empty(), |d| { + d.child(div().flex().flex_wrap().gap(px(6.)).px(px(12.)).pt(px(2.)).pb(px(8.)).children( + h.choices.iter().map(|(v, color)| { + let choose = choose.clone(); + let value = v.clone(); + div() + .id(SharedString::from(format!("choice-{v}"))) + .flex() + .items_center() + .px(px(8.)) + .py(px(2.)) + .rounded(px(10.)) + .bg(ca(255, 255, 255, 0.08)) + .border_1() + .border_color(ca(255, 255, 255, 0.12)) + .text_size(px(12.)) + .line_height(px(16.)) + .text_color(ca(255, 255, 255, 0.85)) + .cursor_pointer() + .hover(|d| d.bg(c(PRIMARY)).text_color(c(PANEL_BG))) + .on_mouse_down(gpui::MouseButton::Left, move |_, w, cx| { + cx.stop_propagation(); + choose(value.clone(), w, cx) + }) + .children(color.map(|c| div().size(px(8.)).mr(px(5.)).rounded_full().bg(c))) + .child(v.clone()) + }), + )) + }) + .into_any_element() + } + }; + Some(body) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn ctx<'a>(f: &'a dyn Fn(&str) -> (SharedString, Option)) -> Ctx<'a> { + Ctx { chat: "c", snapshot: None, loading: false, effects: true, bot_name: f } + } + + #[test] + fn routes_builtins() { + let f = |_: &str| (SharedString::from(""), None); + let ctx = ctx(&f); + let mut p = Picker::default(); + assert_eq!(p.route(&ctx, "/shrug ok"), Route::Text("ok ¯\\_(ツ)_/¯".into())); + assert_eq!(p.route(&ctx, "/tableflip"), Route::Text("(╯°□°)╯︵ ┻━┻".into())); + assert_eq!(p.route(&ctx, "/rainbow hi"), Route::Text("hi".into())); + assert_eq!(p.route(&ctx, "/color me impressed"), Route::Plain); + assert_eq!(p.route(&ctx, "/nope x"), Route::Plain); + assert_eq!(p.recents, vec!["system:rainbow", "system:flip", "system:shrug"]); + p.armed = Some(("c".into(), SYSTEM.into(), "gradient".into())); + assert!(matches!(p.route(&ctx, "/gradient red x"), Route::Error(_))); + } + + #[test] + fn lists_and_hints() { + let f = |_: &str| (SharedString::from(""), None); + let ctx = ctx(&f); + let mut p = Picker::default(); + p.on_input(&ctx, "/fl"); + let Some(View::List { sections, .. }) = &p.view else { panic!() }; + let names: Vec<&str> = sections[0].rows.iter().map(|r| r.cmd.name.as_str()).collect(); + assert_eq!(names, ["flip", "unflip", "coinflip"]); + p.on_input(&ctx, "/gradient re"); + let Some(View::Hint(h)) = &p.view else { panic!() }; + assert_eq!(h.current, 0); + assert_eq!(h.choices[0].0, "red"); + p.on_input(&ctx, "/time fri"); + assert!(p.view.is_none()); + assert_eq!(Picker::insert_choice("/gradient re", "red"), "/gradient red "); + } + + #[test] + fn parses_quoted_args() { + let cmd = Cmd { + bot: "b".into(), + name: "say".into(), + description: String::new(), + args: vec![arg("who", ArgType::String, true, String::new()), arg("what", ArgType::String, true, String::new())], + builtin: None, + aliases: &[], + }; + let got = parse_args(&cmd, r#" "a \"b\"" rest of it "#).unwrap(); + assert_eq!(got, vec![("who".into(), "a \"b\"".into()), ("what".into(), "rest of it".into())]); + assert!(parse_args(&cmd, " \"open").is_none()); + } +} diff --git a/crates/vector-gpui/src/commsettings.rs b/crates/vector-gpui/src/commsettings.rs new file mode 100644 index 000000000..a4d71f661 --- /dev/null +++ b/crates/vector-gpui/src/commsettings.rs @@ -0,0 +1,2254 @@ +//! Community Settings (`community/CommunitySettings.svelte`): the settings layout in a card over +//! the app. Overview, Relays and Bans edit a draft behind one save bar; closing with unsaved +//! changes is refused, and the bar says why. + +use crate::kit::Tipped as _; +use std::collections::HashSet; +use std::rc::Rc; + +use gpui::prelude::*; +use gpui::{AnimationExt as _, AnyElement, App, Entity, FontWeight, ScrollHandle, SharedString, Window, div, px, svg}; +use crate::pic::img; + +use crate::composer::TextInput; +use crate::data::Store; +use crate::t; +use crate::settings::{Anchor, Category, NavOn, anchor}; +use crate::theme::*; + +pub const NAME_MAX: usize = 32; +pub const DESCRIPTION_MAX: usize = 500; +pub const RELAYS_MAX: usize = 5; +pub const VOICE_RELAYS_MAX: usize = 8; +pub const BANS_MAX: usize = 500; +/// A dropdown's list draws over the card, which is itself deferred at 12. +pub const LIST_PRIORITY: usize = 13; + +pub struct Saved { + pub name: String, + pub description: String, + pub relays: Vec, + pub voice: Vec, + /// The chat channel Join/Leave lines go to, `None` while they're off. + pub lines: Option, + /// The channel new members open first, `None` for the default. + pub landing: Option, +} + +/// A channel the System Messages and Landing Channel pickers offer. +pub struct PickChannel { + pub id: &'static str, + pub name: &'static str, + pub private: bool, + pub chat: bool, +} + +#[derive(Default)] +pub struct Audit { + pub loaded: bool, + pub loading: bool, + pub error: Option, + pub entries: Vec, + pub compacted: bool, + pub action: &'static str, + pub open: HashSet, + pub shown: usize, + pub filter_open: bool, +} + +pub const AUDIT_PAGE: usize = 50; + +/// The Sync Report: how this device reads the community's control plane. +#[derive(Default)] +pub struct Report { + pub loading: bool, + pub error: Option, + pub data: Option, + pub text: SharedString, +} + +/// A picked image awaiting Save: the file, the part to upload, and what shows meanwhile. +pub struct Pick { + pub path: std::path::PathBuf, + pub crop: Option, + pub preview: std::sync::Arc, + pub natural: (u32, u32), + /// The crop cut out of `preview`, so corners can round it. + pub cut: Option>, +} + +impl Pick { + pub fn set_crop(&mut self, crop: vector_core::image_crop::CropRect) { + self.cut = cut_out(&self.preview, self.natural, &crop); + self.crop = Some(crop); + } +} + +fn cut_out( + image: &gpui::RenderImage, + natural: (u32, u32), + r: &vector_core::image_crop::CropRect, +) -> Option> { + let size = image.size(0); + let (pw, ph) = (size.width.0 as u32, size.height.0 as u32); + let k = pw as f32 / natural.0.max(1) as f32; + let x = ((r.x as f32 * k) as u32).min(pw.saturating_sub(1)); + let y = ((r.y as f32 * k) as u32).min(ph.saturating_sub(1)); + let w = ((r.w as f32 * k).round() as u32).clamp(1, pw - x); + let h = ((r.h as f32 * k).round() as u32).clamp(1, ph - y); + let src = image.as_bytes(0)?; + let mut out = Vec::with_capacity((w * h * 4) as usize); + for row in y..y + h { + let at = ((row * pw + x) * 4) as usize; + out.extend_from_slice(src.get(at..at + (w * 4) as usize)?); + } + let buf = image::RgbaImage::from_raw(w, h, out)?; + Some(std::sync::Arc::new(gpui::RenderImage::new(vec![image::Frame::new(buf)]))) +} + +pub struct CommSettings { + pub community: String, + pub section: &'static str, + pub anchor: Option<&'static str>, + pub search: Entity, + pub scroll: ScrollHandle, + pub caps: HashSet, + pub saved: Saved, + pub name: Entity, + pub description: Entity, + pub relays: Vec, + pub voice: Vec, + pub lines: Option, + pub landing: Option, + pub pick: Vec, + /// The picker open, by name. + pub open_select: Option<&'static str>, + pub relay_input: Entity, + pub voice_input: Entity, + pub relay_edit: Option<(usize, Entity)>, + pub relay_error: Option, + pub voice_error: Option, + pub bans: Vec, + pub ban_query: Entity, + pub ban_sel: HashSet, + pub unbanning: bool, + pub audit: Audit, + pub advanced: bool, + pub report: Option, + pub roles: crate::roles::Roles, + pub role_name: Entity, + pub role_query: Entity, + pub role_hex: Option>, + pub audit_query: Entity, + pub saving: bool, + /// Upload percent while an image saves. + pub progress: Option, + pub icon_pick: Option, + pub icon_removed: bool, + pub banner_pick: Option, + pub banner_removed: bool, + /// A refused close: the bar says why until this passes. + pub warn_until: Option, +} + +pub enum Act { + ExplainAuth, + PickIcon, + PickBanner, + RemoveIcon, + RemoveBanner, + Close, + Section(&'static str), + Anchor(&'static str, &'static str), + /// The wheel moved on from an anchor jumped to. + Scrolled, + ClearSearch, + AddRelay, + RemoveRelay(usize), + EditRelay(usize), + CommitEdit, + CancelEdit, + AddVoice, + RemoveVoice(usize), + Select(&'static str), + Lines(&'static str), + Landing(&'static str), + Ban(String), + BanAll, + ClearBans, + Unban, + Reset, + Save, + Learn, + AuditRefresh, + AuditToggle(String), + AuditMore, + AuditFilter, + AuditPick(&'static str), + SyncReport, + ReportClose, + ReportCopy, + Role(crate::roles::Act), +} + +pub type OnAct = Rc; + +pub(crate) fn click( + on: &OnAct, + act: impl Fn() -> Act + 'static, +) -> impl Fn(&gpui::ClickEvent, &mut Window, &mut App) + 'static { + let on = on.clone(); + move |_, w, cx| on(act(), w, cx) +} + +impl CommSettings { + pub fn can(&self, cap: &str) -> bool { + self.caps.contains(cap) + } + + pub fn overview_dirty(&self, cx: &App) -> bool { + self.name.read(cx).text() != self.saved.name + || self.description.read(cx).text() != self.saved.description + || self.icon_pick.is_some() + || self.banner_pick.is_some() + || self.icon_removed + || self.banner_removed + || self.lines != self.saved.lines + || self.landing != self.saved.landing + } + + pub fn roles_dirty(&self, cx: &App) -> bool { + self.roles.order.is_some() || self.roles.edit_dirty(self.role_name.read(cx).text()) + } + + pub fn dirty(&self, cx: &App) -> bool { + self.overview_dirty(cx) + || self.relays != self.saved.relays + || self.voice != self.saved.voice + || self.roles_dirty(cx) + } + + pub fn warn(&self) -> bool { + self.warn_until + .is_some_and(|t| std::time::Instant::now() < t) + } + + pub fn sections(&self) -> Vec { + let section = |id, label, icon, anchors: Vec| Category { + id, + label, + icon, + danger: false, + anchors, + }; + let mut out = vec![ + section( +"overview", t::community_settings_page_overview, "info", + vec![ + anchor("identity", t::community_settings_section_identity, t::community_settings_section_identity_keys), + anchor("banner", t::community_settings_section_banner, t::community_settings_section_banner_keys), + anchor("description", t::community_settings_section_description, t::community_settings_section_description_keys), + anchor("system-messages", t::community_settings_section_system_messages, t::community_settings_section_system_messages_keys), + anchor("landing-channel", t::community_settings_section_landing_channel, t::community_settings_section_landing_channel_keys), + ], + ), + section( +"relays", t::community_settings_page_relays, "globe", + vec![ + anchor("relay-list", t::community_settings_section_relay_list, t::community_settings_section_relay_list_keys), + anchor("voice-relays", t::community_settings_section_voice_relays, t::community_settings_section_voice_relays_keys), + ], + ), + ]; + if self.can("manage_roles") { + out.push(section( +"roles", t::community_settings_page_roles, "shield-filled", + crate::roles::anchors(&self.roles), + )); + } + if self.can("ban") { + out.push(section( +"bans", t::community_settings_page_bans, "x-user", + vec![anchor("ban-list", t::community_settings_section_ban_list, t::community_settings_section_ban_list_keys)], + )); + } + if self.can("view_audit_log") { + out.push(section( +"audit", t::community_settings_page_audit, "clock", + vec![anchor("audit-list", t::community_settings_section_audit_list, t::community_settings_section_audit_list_keys)], + )); + } + out + } +} + +/// `relayAddress`: `raw` as a relay the list can hold, or why not. +pub fn relay_address(raw: &str, list: &[String], except: Option) -> Result { + let mut text = raw.trim().to_string(); + if text.is_empty() { + return Err(String::new()); + } + if !text.contains("://") { + text = format!("wss://{text}"); + } + let (scheme, rest) = text.split_once("://").unwrap_or(("", "")); + let host = rest + .split(['/', ':', '?', '#']) + .next() + .unwrap_or("") + .to_ascii_lowercase(); + if host.is_empty() || host.contains(char::is_whitespace) { + return Err(t::community_settings_relay_invalid().into()); + } + let native = host.ends_with(".onion") || host.ends_with(".i2p"); + let scheme = scheme.to_ascii_lowercase(); + if !(scheme == "wss" || (scheme == "ws" && native)) { + return Err(t::community_settings_relay_scheme().into()); + } + let address = text.trim_end_matches('/').to_string(); + let same = |a: &String| a.trim_end_matches('/').eq_ignore_ascii_case(&address); + if list + .iter() + .enumerate() + .any(|(i, r)| Some(i) != except && same(r)) + { + return Err(t::community_settings_relay_listed().into()); + } + Ok(address) +} + +/// A voice relay as the list holds it (`https://host/`), or why not. +pub fn voice_address(raw: &str, list: &[String]) -> Result { + let mut text = raw.trim().to_string(); + if text.is_empty() { + return Err(String::new()); + } + if !text.contains("://") { + text = format!("https://{text}"); + } + let (scheme, rest) = text.split_once("://").unwrap_or(("", "")); + if !scheme.eq_ignore_ascii_case("https") { + return Err(t::community_settings_voice_relay_scheme().into()); + } + if rest.split(['/', '?', '#']).next().unwrap_or("").is_empty() { + return Err(t::community_settings_relay_invalid().into()); + } + let normal = format!("{}/", text.trim_end_matches('/')); + if list.contains(&normal) { + return Err(t::community_settings_relay_listed().into()); + } + if list.len() >= VOICE_RELAYS_MAX { + return Err(t::community_settings_voice_relays_max(VOICE_RELAYS_MAX).into()); + } + Ok(normal) +} + +pub(crate) fn heading(text: impl Into) -> impl IntoElement { + div() + .mb(px(20.)) + .text_size(px(24.)) + .line_height(px(28.)) + .font_weight(FontWeight::BOLD) + .text_color(c(0xffffff)) + .child(text.into()) +} + +pub(crate) fn lede(text: impl Into) -> impl IntoElement { + div() + .mt(px(-8.)) + .mb(px(18.)) + .text_size(px(14.)) + .line_height(px(21.)) + .text_color(c(0x9a9a9a)) + .child(text.into()) +} + +pub(crate) fn hint(text: impl Into) -> gpui::Div { + div() + .text_size(px(12.5)) + .line_height(px(18.125)) + .text_color(c(0x7a7a7a)) + .child(text.into()) +} + +thread_local! { + /// While Community Settings builds, its scroll: each block notes where it sits in it. + static SCROLL: std::cell::RefCell> = const { std::cell::RefCell::new(None) }; + /// Each block's top in the scrolled content, in order, as last laid out. + static TOPS: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; +} + +/// Where the `ix`th block of the open section starts in its scroll. +pub fn block_top(ix: usize) -> Option { + TOPS.with(|t| t.borrow().get(ix).copied()) +} + +pub(crate) fn block(first: bool, body: impl IntoElement) -> impl IntoElement { + let mark = SCROLL.with(|s| s.borrow().clone()).map(|h| { + gpui::canvas( + move |b, _, _| TOPS.with(|t| t.borrow_mut().push(b.origin.y - h.bounds().top() - h.offset().y)), + |_, _, _, _| {}, + ) + .absolute() + .top_0() + .left_0() + .size_0() + }); + div() + .relative() + .pt(px(30.)) + .pb(px(34.)) + .when(!first, |d| d.border_t_1().border_color(c(0x262626))) + .child(body) + .children(mark) +} + +pub(crate) fn field_head( + label: impl Into, + count: Option<(usize, usize, bool)>, +) -> impl IntoElement { + div() + .mb(px(8.)) + .flex() + .items_center() + .justify_between() + .child( + div() + .font_weight(FontWeight::MEDIUM) + .text_size(px(13.)) + .line_height(px(24.)) + .text_color(c(0xcfcfcf)) + .child(label.into()), + ) + .children(count.map(|(n, max, warn)| { + div() + .text_size(px(12.)) + .line_height(px(24.)) + .text_color(if warn { + c(crate::timeline::DANGER) + } else { + c(0x6f6f6f) + }) + .child(format!("{n}/{max}")) + })) +} + +pub(crate) fn input_box(input: &Entity, h: f32, editable: bool) -> gpui::Div { + div() + .h(px(h)) + .px(px(13.)) + .rounded(px(10.)) + .border_1() + .border_color(c(0x2c2c2c)) + .bg(c(0x111111)) + .flex() + .items_center() + .overflow_hidden() + .when(!editable, |d| d.opacity(0.6)) + .child(div().flex_1().min_w_0().child(input.clone())) +} + +pub(crate) fn save_btn( + id: impl Into, + label: impl Into, + live: bool, + on: impl Fn(&gpui::ClickEvent, &mut Window, &mut App) + 'static, +) -> impl IntoElement { + div() + .id(id.into()) + .h(px(34.)) + .px(px(14.)) + .flex_shrink_0() + .rounded(px(8.)) + .bg(c(PRIMARY)) + .flex() + .items_center() + .justify_center() + .font_weight(FontWeight::SEMIBOLD) + .text_size(px(14.)) + .text_color(c(0x000000)) + .when(!live, |d| d.opacity(0.45)) + .when(live, |d| { + d.cursor_pointer().hover(|d| d.opacity(0.9)).on_click(on) + }) + .child(label.into()) +} + +fn edit_veil() -> gpui::Div { + div() + .absolute() + .inset_0() + .flex() + .items_center() + .justify_center() + .bg(ca(0, 0, 0, 0.55)) + .invisible() + .child( + svg() + .path("icons/edit.svg") + .size(px(22.)) + .text_color(c(0xffffff)), + ) +} + +fn new_tag() -> gpui::Div { + div() + .absolute() + .right(px(6.)) + .bottom(px(6.)) + .px(px(7.)) + .py(px(1.)) + .rounded(px(8.)) + .bg(c(PRIMARY)) + .text_color(c(0x000000)) + .font_weight(FontWeight::BOLD) + .text_size(px(10.)) + .line_height(px(16.)) + .child(t::community_settings_new()) +} + +fn remove_btn( + id: &'static str, + label: SharedString, + on: impl Fn(&gpui::ClickEvent, &mut Window, &mut App) + 'static, +) -> impl IntoElement { + div() + .id(id) + .px(px(6.)) + .py(px(2.)) + .text_size(px(12.5)) + .line_height(px(24.)) + .text_color(c(0x8a8a8a)) + .cursor_pointer() + .hover(|d| d.text_color(c(crate::timeline::DANGER))) + .on_click(on) + .child(label) +} + +/// A pick's crop, drawn at `width` like `.banner-art` with a rect. +pub fn cut(p: &Pick, width: f32, height: f32, radius: f32) -> AnyElement { + if let Some(cut) = &p.cut { + return img(cut.clone()) + .w(px(width)) + .h(px(height)) + .rounded(px(radius)) + .object_fit(gpui::ObjectFit::Cover) + .into_any_element(); + } + let (nw, nh) = (p.natural.0.max(1) as f32, p.natural.1.max(1) as f32); + let (x, y, w) = match p.crop { + Some(r) => (r.x as f32, r.y as f32, r.w.max(1) as f32), + None => { + let w = nw.min(nh * width / height); + ((nw - w) / 2., (nh - w * height / width) / 2., w) + } + }; + let k = width / w; + div() + .relative() + .w(px(width)) + .h(px(height)) + .overflow_hidden() + .rounded(px(radius)) + .bg(c(0x484848)) + .child( + img(p.preview.clone()) + .absolute() + .left(px(-x * k)) + .top(px(-y * k)) + .w(px(nw * k)) + .h(px(nh * k)), + ) + .into_any_element() +} + +fn overview(m: &CommSettings, store: &Store, compact: bool, on: &OnAct, cx: &App) -> AnyElement { + let editable = m.can("manage_metadata"); + let name_len = m.name.read(cx).text().chars().count(); + let desc_len = m.description.read(cx).text().chars().count(); + let saved_icon = (!m.icon_removed) + .then(|| store.icon(&m.community)) + .flatten(); + let has_icon = m.icon_pick.is_some() || saved_icon.is_some(); + let icon: AnyElement = match (&m.icon_pick, saved_icon) { + (Some(p), _) => cut(p, 88., 88., 24.), + (None, Some(path)) => img(path) + .size_full() + .rounded(px(24.)) + .object_fit(gpui::ObjectFit::Cover) + .into_any_element(), + (None, None) => img("icons/group-placeholder.svg") + .size_full() + .rounded(px(24.)) + .into_any_element(), + }; + let saved_banner = (!m.banner_removed) + .then(|| store.banner(&m.community)) + .flatten(); + let has_banner = m.banner_pick.is_some() || saved_banner.is_some(); + let banner: AnyElement = match (&m.banner_pick, saved_banner) { + (Some(p), _) => cut(p, 238., 70., 12.), + (None, Some(path)) => crate::community::banner_art(path, 238.) + .rounded(px(12.)) + .into_any_element(), + (None, None) => div() + .w(px(238.)) + .h(px(70.)) + .rounded(px(12.)) + .border_1() + .border_dashed() + .border_color(c(0x333333)) + .flex() + .items_center() + .justify_center() + .gap(px(10.)) + .text_color(white_a(0.45)) + .when(editable, |d| { + d.group_hover("cs-banner", |d| { + d.border_color(c(0x555555)).text_color(white_a(0.7)) + }) + }) + .child( + svg() + .path("icons/image.svg") + .size(px(24.)) + .text_color(white_a(0.45)), + ) + .child( + div() + .flex() + .flex_col() + .gap(px(2.)) + .child( + div() + .text_size(px(12.5)) + .line_height(px(15.)) + .child(if editable { t::community_settings_add_banner() } else { t::community_settings_no_banner() }), + ) + .when(editable, |d| { + d.child( + div() + .text_size(px(11.)) + .line_height(px(13.2)) + .opacity(0.7) + .child("(952 × 280)"), + ) + }), + ) + .into_any_element(), + }; + div() + .child(block( + true, + div().child(heading(t::community_settings_section_identity())).child( + div() + .flex() + .when(compact, |d| d.flex_col()) + .items_start() + .gap(px(22.)) + .child( + div() + .flex() + .flex_col() + .items_center() + .gap(px(6.)) + .flex_shrink_0() + .child( + div() + .id("cs-icon") + .when(editable, |d| d.tip(t::community_settings_change_icon())) + .group("cs-icon") + .relative() + .size(px(88.)) + .rounded(px(24.)) + .overflow_hidden() + .bg(c(0x161616)) + .child(icon) + .when(editable, |d| d.cursor_pointer().on_click(click(on, || Act::PickIcon)).child(edit_veil().group_hover("cs-icon", |d| d.visible()))) + .when(m.icon_pick.is_some(), |d| d.child(new_tag())), + ) + .when(editable && has_icon, |d| d.child(remove_btn("cs-icon-x", t::community_settings_remove(), click(on, || Act::RemoveIcon)))), + ) + .child( + div() + .when(compact, |d| d.w_full().max_w(px(442.))) + .when(!compact, |d| d.flex_1()) + .min_w_0() + .flex() + .flex_col() + .child(field_head(t::community_settings_name(), Some((name_len, NAME_MAX, name_len == 0)))) + .child(input_box(&m.name, 42., editable)) + .child(hint(t::community_settings_icon_hint()).mt(px(10.))), + ), + ), + )) + .child(block( + false, + div().child(heading(t::community_settings_section_banner())).child( + div() + .flex() + .flex_col() + .items_start() + .gap(px(10.)) + .child( + div() + .id("cs-banner") + .when(editable, |d| d.tip(if has_banner { t::community_settings_change_banner() } else { t::community_settings_add_banner() })) + .group("cs-banner") + .relative() + .w(px(238.)) + .rounded(px(12.)) + .overflow_hidden() + .bg(c(0x161616)) + .child(banner) + .when(editable, |d| d.cursor_pointer().on_click(click(on, || Act::PickBanner))) + .when(editable && has_banner, |d| d.child(edit_veil().group_hover("cs-banner", |d| d.visible()))) + .when(m.banner_pick.is_some(), |d| d.child(new_tag())), + ) + .when(editable && has_banner, |d| d.child(remove_btn("cs-banner-x", t::community_settings_remove_banner(), click(on, || Act::RemoveBanner)))), + ), + )) + .child(block( + false, + div() + .child(heading(t::community_settings_section_description())) + .child(field_head(t::community_settings_description_hint(), Some((desc_len, DESCRIPTION_MAX, false)))) + .child( + div() + .h(px(136.5)) + .px(px(13.)) + .py(px(11.)) + .rounded(px(10.)) + .border_1() + .border_color(c(0x2c2c2c)) + .bg(c(0x111111)) + .overflow_hidden() + .when(!editable, |d| d.opacity(0.6)) + .child(m.description.clone()), + ), + )) + .child(block( + false, + div().child(heading(t::community_settings_section_system_messages())).child(channel_select( + m, + "cs-lines", + t::community_settings_system_messages(), + t::community_settings_system_messages_hint(), + on, + )), + )) + .child(block( + false, + div().child(heading(t::community_settings_section_landing_channel())).child(channel_select( + m, + "cs-landing", + t::community_settings_landing(), + t::community_settings_landing_hint(), + on, + )), + )) + .into_any_element() +} + +/// The System Messages or Landing Channel picker: its label, the `.vselect-fill`, a hint. +fn channel_select(m: &CommSettings, id: &'static str, label: SharedString, help: SharedString, on: &OnAct) -> AnyElement { + let editable = m.can("manage_metadata"); + let lines = id == "cs-lines"; + let mut choices = Vec::with_capacity(m.pick.len() + 1); + let mut marks: Vec<(&'static str, &'static str)> = Vec::with_capacity(m.pick.len() + 1); + if !lines { + choices.push(crate::kit::Choice { value: "", label: crate::kit::interned(&t::community_settings_landing_first()) }); + marks.push(("", "icons/list.svg")); + } + // A joiner holds no private channel's key on arrival. + for ch in m.pick.iter().filter(|ch| if lines { ch.chat } else { !ch.private }) { + choices.push(crate::kit::Choice { value: ch.id, label: ch.name }); + marks.push((ch.id, if ch.private { "icons/locked.svg" } else { "icons/channel-hash.svg" })); + } + if lines { + choices.push(crate::kit::Choice { value: "", label: crate::kit::interned(&t::community_settings_system_messages_off()) }); + marks.push(("", "icons/eye-off.svg")); + } + let lead = move |v: &'static str| { + let icon: &'static str = marks.iter().find(|(id, _)| *id == v).map_or("icons/channel-hash.svg", |(_, i)| *i); + div() + .size(px(18.)) + .flex_shrink_0() + .flex() + .items_center() + .justify_center() + .child(svg().path(icon).size(px(18.)).text_color(c(0xb2b2b2))) + .into_any_element() + }; + let value = if lines { m.lines.as_deref() } else { m.landing.as_deref() }.unwrap_or(""); + let (toggle, pick) = (on.clone(), on.clone()); + let select = crate::kit::select_look( + id, + f32::INFINITY, + 14., + &choices, + &[], + value, + editable && m.open_select == Some(id), + crate::kit::SelectLook { lead: Some(Rc::new(lead)), priority: LIST_PRIORITY, ..Default::default() }, + move |w, cx| { + if editable { + toggle(Act::Select(id), w, cx) + } + }, + move |v, w, cx| pick(if lines { Act::Lines(v) } else { Act::Landing(v) }, w, cx), + ); + div() + .flex() + .flex_col() + .child(div().font_weight(FontWeight::MEDIUM).text_size(px(13.)).line_height(px(15.4)).text_color(c(0xcfcfcf)).child(label)) + .child(div().when(!editable, |d| d.opacity(0.45)).child(select)) + .child(hint(help).mt(px(10.))) + .into_any_element() +} + +fn relay_row( + first: bool, + icon: &'static str, + url: &str, + editing: Option<&Entity>, + actions: Vec, + info: Option<(crate::relayinfo::Meta, &OnAct)>, +) -> impl IntoElement { + let name = info.as_ref().and_then(|(m, _)| m.name.clone()); + let auth = info.as_ref().filter(|(m, _)| m.auth).map(|(_, on)| (*on).clone()); + let pic = info.as_ref().and_then(|(m, _)| m.icon.clone()); + let (scheme, rest) = match url.find("://") { + Some(i) => (&url[..i + 3], url[i + 3..].trim_end_matches('/')), + None => ("", url), + }; + div() + .h(px(if first { 46. } else { 47. })) + .px(px(16.)) + .flex() + .items_center() + .gap(px(12.)) + .bg(c(0x0c0c0c)) + .when(!first, |d| d.border_t_1().border_color(c(0x1e1e1e))) + .child(match pic { + Some(pic) => crate::pic::img(pic) + .size(px(22.)) + .mx(px(-3.)) + .flex_shrink_0() + .rounded(px(5.)) + .object_fit(gpui::ObjectFit::Cover) + .into_any_element(), + None => svg() + .path(icon) + .size(px(16.)) + .flex_shrink_0() + .text_color(c(0x7a7a7a)) + .into_any_element(), + }) + .when_some(editing, |d, input| { + d.child( + div() + .flex_1() + .min_w_0() + .h(px(30.)) + .px(px(8.)) + .flex() + .items_center() + .rounded(px(6.)) + .border_1() + .border_color(c(ACCENT)) + .bg(c(0x050505)) + .overflow_hidden() + .child(input.clone()), + ) + }) + .when(editing.is_none(), |d| { + let sub = name.is_some(); + d.child( + div() + .flex_1() + .min_w_0() + .flex() + .flex_col() + .children(name.map(|n| { + div() + .truncate() + .text_size(px(14.)) + .line_height(px(18.)) + .font_weight(FontWeight::SEMIBOLD) + .text_color(c(0xe8e8e8)) + .child(n) + })) + .child( + div() + .truncate() + .text_size(px(if sub { 12. } else { 14. })) + .line_height(px(if sub { 16. } else { 24. })) + .text_color(c(if sub { 0x9a9a9a } else { 0xe8e8e8 })) + .child( + gpui::StyledText::new(format!("{scheme}{rest}")).with_highlights([( + 0..scheme.len(), + gpui::HighlightStyle { + color: Some(c(0x6a6a6a)), + ..Default::default() + }, + )]), + ), + ), + ) + .when_some(auth, |d, on| { + d.child( + div() + .id("cs-relay-auth") + .tip(t::community_settings_auth_tip()) + .h(px(22.)) + .px(px(8.)) + .flex_shrink_0() + .flex() + .items_center() + .gap(px(4.)) + .rounded(px(11.)) + .border_1() + .border_color(ca(242, 184, 75, 0.35)) + .bg(ca(242, 184, 75, 0.1)) + .hover(|d| d.bg(ca(242, 184, 75, 0.18))) + .cursor_pointer() + .text_size(px(11.)) + .font_weight(FontWeight::BOLD) + .text_color(c(0xf2b84b)) + .on_click(click(&on, || Act::ExplainAuth)) + .child(svg().path("icons/locked.svg").size(px(11.)).text_color(c(0xf2b84b))) + .child(crate::kit::spaced(crate::t::community_settings_relay_auth().to_uppercase(), 0.44)), + ) + }) + }) + .children(actions) +} + +fn relay_action( + id: SharedString, + icon: &'static str, + on: impl Fn(&gpui::ClickEvent, &mut Window, &mut App) + 'static, +) -> AnyElement { + div() + .id(id) + .size(px(26.)) + .flex_shrink_0() + .rounded(px(6.)) + .flex() + .items_center() + .justify_center() + .cursor_pointer() + .hover(|d| d.bg(white_a(0.06))) + .on_click(on) + .child(svg().path(icon).size(px(14.)).text_color(c(0x7a7a7a))) + .into_any_element() +} + +fn add_row( + id: &'static str, + input: &Entity, + full: bool, + live: bool, + on: impl Fn(&gpui::ClickEvent, &mut Window, &mut App) + 'static, +) -> impl IntoElement { + div() + .mt(px(12.)) + .flex() + .gap(px(8.)) + .child(input_box(input, 35., !full).px(px(12.)).flex_1()) + .child(save_btn(id, t::community_settings_add(), live && !full, on).into_any_element()) +} + +fn relays(m: &CommSettings, on: &OnAct, cx: &App) -> AnyElement { + let editable = m.can("manage_metadata"); + let many = m.relays.len() > 1; + let list = div() + .rounded(px(12.)) + .border_1() + .border_color(c(0x262626)) + .overflow_hidden() + .children(m.relays.iter().enumerate().map(|(i, url)| { + let editing = m + .relay_edit + .as_ref() + .filter(|(at, _)| *at == i) + .map(|(_, input)| input); + let mut actions = Vec::new(); + if editable && editing.is_none() { + actions.push(relay_action( + SharedString::from(format!("cs-relay-e-{i}")), + "icons/edit.svg", + click(on, move || Act::EditRelay(i)), + )); + if many { + actions.push(relay_action( + SharedString::from(format!("cs-relay-x-{i}")), + "icons/x.svg", + click(on, move || Act::RemoveRelay(i)), + )); + } + } + let info = crate::relayinfo::get(url).map(|m| (m, on)); + relay_row(i == 0, "icons/globe.svg", url, editing, actions, info) + })) + .when(m.relays.is_empty(), |d| { + d.child(hint(t::community_settings_no_relays()).mx(px(16.)).my(px(14.))) + }); + let voice = div() + .rounded(px(12.)) + .border_1() + .border_color(c(0x262626)) + .overflow_hidden() + .map(|d| { + if m.voice.is_empty() { + d.child( + div() + .mx(px(16.)) + .my(px(14.)) + .flex() + .items_center() + .gap(px(4.)) + .child(hint(t::community_settings_iroh_relays())) + .child( + div() + .id("cs-iroh") + .cursor_pointer() + .font_weight(FontWeight::SEMIBOLD) + .text_size(px(12.5)) + .line_height(px(18.125)) + .text_color(c(ACCENT)) + .hover(|d| d.underline()) + .on_click(click(on, || Act::Learn)) + .child(t::community_settings_learn_more()), + ), + ) + } else { + d.children(m.voice.iter().enumerate().map(|(i, url)| { + let actions = if editable { + vec![relay_action( + SharedString::from(format!("cs-voice-x-{i}")), + "icons/x.svg", + click(on, move || Act::RemoveVoice(i)), + )] + } else { + Vec::new() + }; + relay_row(i == 0, "icons/volume-max.svg", url, None, actions, None) + })) + } + }); + let relay_text = !m.relay_input.read(cx).text().trim().is_empty(); + let voice_text = !m.voice_input.read(cx).text().trim().is_empty(); + div() + .child(block( + true, + div() + .child(heading(t::community_settings_section_relay_list())) + .child(lede(t::community_settings_relays_lede())) + .child(list) + .when(editable, |d| { + d.child(add_row("cs-relay-add", &m.relay_input, m.relays.len() >= RELAYS_MAX, relay_text, click(on, || Act::AddRelay))) + .children(m.relay_error.as_deref().map(|e| hint(crate::coretext::say(e).into_owned()).mt(px(10.)).text_color(c(crate::timeline::DANGER)))) + .child(hint(t::community_settings_relays_hint()).mt(px(10.))) + }), + )) + .child(block( + false, + div() + .child(heading(t::community_settings_section_voice_relays())) + .child(lede(t::community_settings_voice_relays_lede())) + .child(voice) + .when(editable, |d| { + d.child(add_row("cs-voice-add", &m.voice_input, m.voice.len() >= VOICE_RELAYS_MAX, voice_text, click(on, || Act::AddVoice))) + .children(m.voice_error.as_deref().map(|e| hint(crate::coretext::say(e).into_owned()).mt(px(10.)).text_color(c(crate::timeline::DANGER)))) + }), + )) + .into_any_element() +} + +/// `MemberRow`: avatar, name and key hint, with `trailing` at the end. +pub(crate) fn member_row( + store: &Store, + npub: &str, + prefix: &str, + trailing: AnyElement, + on_click: Option>, +) -> gpui::Stateful { + let named = store.profiles.get(npub).is_some_and(|p| { + !p.name.is_empty() || !p.display_name.is_empty() || !p.nickname.is_empty() + }); + let name = if named { + store.name(npub) + } else { + short_npub(npub) + }; + div() + .id(SharedString::from(format!("{prefix}-{npub}"))) + .group(SharedString::from(format!("{prefix}-{npub}"))) + .h(px(35.)) + .px(px(10.)) + .flex() + .items_center() + .rounded(px(6.)) + .hover(|d| d.bg(ca(255, 255, 255, 0.085))) + .when_some(on_click, |d, f| d.cursor_pointer().on_click(f)) + .child(div().mr(px(10.)).child(crate::ui::avatar(store, npub, 25.))) + .child( + div() + .flex_1() + .min_w_0() + .flex() + .items_center() + .gap(px(12.)) + .child( + div() + .truncate() + .text_size(px(14.)) + .line_height(px(24.)) + .text_color(c(0xf7f4f4)) + .child(name), + ) + .when(named, |d| { + d.child( + div() + .flex_shrink_0() + .text_size(px(11.5)) + .line_height(px(24.)) + .text_color(c(0x6a6a6a)) + .child(short_npub(npub)), + ) + }), + ) + .child(trailing) +} + +pub(crate) fn short_npub(npub: &str) -> String { + if npub.len() < 20 || !npub.is_ascii() { + return npub.to_string(); + } + format!("{}…{}", &npub[..12], &npub[npub.len() - 6..]) +} + +pub(crate) fn indicator(on: bool) -> impl IntoElement { + div() + .size(px(22.)) + .flex_shrink_0() + .rounded(px(4.)) + .border_2() + .border_color(if on { c(PRIMARY) } else { white_a(0.28) }) + .when(on, |d| { + d.bg(c(PRIMARY)) + .flex() + .items_center() + .justify_center() + .child( + svg() + .path("icons/check.svg") + .size(px(14.)) + .text_color(c(0x000000)), + ) + }) +} + +pub fn ban_rows(m: &CommSettings, store: &Store, cx: &App) -> Vec { + let q = m.ban_query.read(cx).text().trim().to_lowercase(); + m.bans + .iter() + .filter(|n| { + q.is_empty() + || format!("{} {}", store.name(n), n) + .to_lowercase() + .contains(&q) + }) + .cloned() + .collect() +} + +fn bans(m: &CommSettings, store: &Store, on: &OnAct, cx: &App) -> AnyElement { + let rows = ban_rows(m, store, cx); + let shown_sel = rows.iter().filter(|n| m.ban_sel.contains(*n)).count(); + let all = !rows.is_empty() && shown_sel == rows.len(); + let querying = !m.ban_query.read(cx).text().trim().is_empty(); + let list = if rows.is_empty() { + div() + .py(px(4.)) + .text_center() + .text_size(px(12.5)) + .line_height(px(18.)) + .text_color(white_a(0.4)) + .child(if querying { t::community_settings_no_matches() } else { t::community_settings_no_bans() }) + .into_any_element() + } else { + div() + .child( + div() + .id("cs-bans-all") + .h(px(34.)) + .px(px(10.)) + .flex() + .items_center() + .rounded(px(6.)) + .cursor_pointer() + .hover(|d| d.bg(ca(255, 255, 255, 0.085))) + .on_click(click(on, || Act::BanAll)) + .child( + div() + .flex_1() + .text_size(px(13.)) + .line_height(px(24.)) + .text_color(c(0x9a9a9a)) + .child(match (all, querying) { + (false, false) => t::community_settings_select_all(rows.len()), + (true, false) => t::community_settings_deselect_all(rows.len()), + (false, true) => t::community_settings_select_matches(rows.len()), + (true, true) => t::community_settings_deselect_matches(rows.len()), + }), + ) + .child(indicator(all)), + ) + .children(rows.into_iter().map(|npub| { + let picked = m.ban_sel.contains(&npub); + let id = npub.clone(); + member_row( + store, + &npub, + "cs-ban", + indicator(picked).into_any_element(), + Some(Box::new(click(on, move || Act::Ban(id.clone())))), + ) + })) + .into_any_element() + }; + block( + true, + div() + .child(heading(t::community_settings_section_ban_list())) + .child(lede(t::community_settings_bans_lede())) + .child( + div() + .flex() + .items_center() + .gap(px(14.)) + .child(search_box(&m.ban_query)) + .child(div().text_size(px(12.)).line_height(px(24.)).text_color(if m.bans.len() >= BANS_MAX { c(crate::timeline::DANGER) } else { c(0x6f6f6f) }).child(t::community_settings_bans_count(m.bans.len(), BANS_MAX))), + ) + .child(div().mt(px(8.)).when(m.unbanning, |d| d.opacity(0.5)).child(list)), + ) + .into_any_element() +} + +fn audit_member(store: &Store) -> impl Fn(Option<&str>) -> String + '_ { + move |npub| match npub { + None => "someone".into(), + Some(n) if store.profiles.contains_key(n) => store.name(n), + Some(n) => short_npub(n), + } +} + +pub fn audit_rows<'a>(m: &'a CommSettings, store: &Store, cx: &App) -> Vec<&'a serde_json::Value> { + let q = m.audit_query.read(cx).text().trim().to_lowercase(); + let member = audit_member(store); + m.audit + .entries + .iter() + .filter(|e| { + m.audit.action == "all" + || crate::audit::family_of(e["action"].as_str().unwrap_or("")) == m.audit.action + }) + .filter(|e| { + q.is_empty() + || crate::audit::plain_text(e, &member) + .to_lowercase() + .contains(&q) + }) + .collect() +} + +fn audit(m: &CommSettings, store: &Store, on: &OnAct, cx: &App) -> AnyElement { + use crate::audit::{Tone, details, sentence, tone_of, when}; + let a = &m.audit; + let member = audit_member(store); + let rows = audit_rows(m, store, cx); + let querying = !m.audit_query.read(cx).text().trim().is_empty() || a.action != "all"; + let now = store.now_ms(); + let pick = on.clone(); + let toggle = on.clone(); + let list: AnyElement = if a.loading && a.entries.is_empty() { + audit_empty(t::community_settings_audit_reading()).into_any_element() + } else if let Some(e) = a.error.as_deref().filter(|_| a.entries.is_empty()) { + hint(crate::coretext::say(e).into_owned()) + .my(px(18.)) + .text_center() + .text_color(c(crate::timeline::DANGER)) + .into_any_element() + } else { + let mut list = div() + .mt(px(6.)) + .mb(px(12.)) + .flex() + .flex_col() + .gap(px(2.)) + .when(a.loading, |d| d.opacity(0.55)); + if rows.is_empty() { + list = list.child(audit_empty(if querying { t::community_settings_no_matches() } else { t::community_settings_audit_empty() })); + } + for e in rows.iter().take(a.shown) { + let id = e["id"].as_str().unwrap_or("").to_string(); + let lines = details(e, &member); + let open = a.open.contains(&id); + let badge = match tone_of(e["action"].as_str().unwrap_or("")) { + Tone::Add => c(ACCENT), + Tone::Remove => c(crate::timeline::DANGER), + Tone::Change => c(0xfbbf24), + }; + let actor = e["actor"].as_str(); + let mut text = String::new(); + let mut bold = Vec::new(); + for (part, b) in sentence(e, &member) { + if b { + bold.push(( + text.len()..text.len() + part.len(), + gpui::HighlightStyle { + color: Some(c(0xffffff)), + font_weight: Some(FontWeight::SEMIBOLD), + ..Default::default() + }, + )); + } + text.push_str(&part); + } + let openable = !lines.is_empty(); + let on = on.clone(); + let key = id.clone(); + list = list.child( + div() + .id(SharedString::from(format!("audit-{id}"))) + .flex() + .items_center() + .gap(px(12.)) + .px(px(12.)) + .py(px(10.)) + .rounded(px(8.)) + .when(open, |d| d.bg(white_a(0.04))) + .when(openable, |d| { + d.cursor_pointer() + .hover(|d| d.bg(white_a(0.04))) + .on_click(move |_, w, cx| on(Act::AuditToggle(key.clone()), w, cx)) + }) + .child( + div() + .relative() + .size(px(32.)) + .flex_shrink_0() + .child(match actor { + Some(n) => crate::ui::avatar(store, n, 32.), + None => img("icons/group-placeholder.svg") + .size(px(32.)) + .rounded_full() + .into_any_element(), + }) + .child( + div() + .absolute() + .right(px(-2.)) + .bottom(px(-2.)) + .size(px(14.)) + .rounded_full() + .border_2() + .border_color(c(0x050505)) + .bg(badge), + ), + ) + .child( + div() + .flex_1() + .min_w_0() + .child( + div() + .text_size(px(14.)) + .line_height(px(19.6)) + .text_color(white_a(0.7)) + .child(gpui::StyledText::new(text).with_highlights(bold)), + ) + .child( + div() + .id("audit-when") + .tip(crate::audit::when_full(e["at"].as_u64().unwrap_or(0))) + .mt(px(2.)) + .text_size(px(12.)) + .line_height(px(24.)) + .text_color(white_a(0.38)) + .child(when(e["at"].as_u64().unwrap_or(0), now)), + ), + ) + .when(openable, |d| { + d.child( + div() + .size(px(18.)) + .flex_shrink_0() + .flex() + .items_center() + .justify_center() + .child( + svg() + .path("icons/chevron-down.svg") + .size(px(10.)) + .text_color(white_a(0.38)) + .with_transformation(crate::kit::turn( + format!("audit-caret-{id}"), + open, + std::f32::consts::PI, + 0.15, + crate::kit::css_ease(), + )), + ), + ) + }), + ); + if open && openable { + list = list.child( + div() + .ml(px(56.)) + .mb(px(6.)) + .pt(px(2.)) + .pr(px(12.)) + .pb(px(8.)) + .flex() + .flex_col() + .gap(px(4.)) + .text_size(px(13.)) + .line_height(px(18.2)) + .text_color(white_a(0.6)) + .children(lines.into_iter().map(|l| div().child(l))), + ); + } + } + let more = rows.len() > a.shown; + div() + .child(list) + .when(more, |d| d.child(div().flex().justify_center().mb(px(12.)).child(text_btn("audit-more", t::community_settings_show_more(), true, click(on, || Act::AuditMore))))) + .when(a.compacted, |d| d.child(hint(t::community_settings_audit_compacted()))) + .into_any_element() + }; + let filter = crate::kit::select_look( + "audit-filter", + 170., + 14., + crate::audit::families(), + &[], + a.action, + a.filter_open, + crate::kit::SelectLook { priority: LIST_PRIORITY, ..Default::default() }, + move |w, cx| toggle(Act::AuditFilter, w, cx), + move |v, w, cx| pick(Act::AuditPick(v), w, cx), + ); + block( + true, + div() + .child( + div() + .mb(px(20.)) + .flex() + .items_center() + .justify_between() + .gap(px(12.)) + .child( + div() + .text_size(px(24.)) + .line_height(px(28.)) + .font_weight(FontWeight::BOLD) + .text_color(c(0xffffff)) + .child(t::community_settings_section_audit_list()), + ) + .child( + div() + .flex() + .gap(px(4.)) + .when(m.advanced, |d| { + d.child(text_btn( + "audit-report", + t::community_settings_sync_report(), + !m.report.as_ref().is_some_and(|r| r.loading), + click(on, || Act::SyncReport), + )) + }) + .child(text_btn( + "audit-refresh", + t::community_settings_refresh(), + !a.loading, + click(on, || Act::AuditRefresh), + )), + ), + ) + .child(lede(t::community_settings_audit_lede())) + .child( + div() + .flex() + .items_center() + .gap(px(14.)) + .child(search_box(&m.audit_query)) + .child(div().w(px(170.)).flex_shrink_0().child(filter)), + ) + .child(div().mt(px(8.)).child(list)), + ) + .into_any_element() +} + +fn audit_empty(text: SharedString) -> impl IntoElement { + div() + .my(px(18.)) + .text_center() + .text_size(px(12.5)) + .line_height(px(18.)) + .text_color(white_a(0.4)) + .child(text) +} + +pub(crate) fn search_box(input: &Entity) -> impl IntoElement { + div() + .flex_1() + .h(px(41.)) + .relative() + .flex() + .items_center() + .pl(px(44.)) + .pr(px(12.)) + .rounded(px(8.)) + .border_1() + .border_color(ca(57, 57, 57, 0.5)) + .overflow_hidden() + .child( + svg() + .path("icons/search.svg") + .absolute() + .left(px(12.)) + .top(px(8.)) + .size(px(24.)) + .text_color(white_a(0.4)), + ) + .child(div().flex_1().min_w_0().child(input.clone())) +} + +fn save_bar(m: &CommSettings, on: &OnAct, cx: &App) -> Option { + let dirty = m.dirty(cx); + let warn = m.warn() && dirty; + let unban = !warn && m.section == "bans" && !m.ban_sel.is_empty(); + if !unban && !dirty { + return None; + } + let n = m.ban_sel.len(); + let (text, actions): (SharedString, Vec) = if unban { + let label = if n == m.bans.len() && n > 1 { t::community_settings_unban_all() } else { t::community_settings_unban(n) }; + ( + if m.unbanning { t::community_settings_unbanning(n) } else { t::community_settings_selected(n) }, + vec![ + text_btn( + "cs-clear-bans", + t::community_settings_clear(), + !m.unbanning, + click(on, || Act::ClearBans), + ), + save_btn("cs-unban", label, !m.unbanning, click(on, || Act::Unban)) + .into_any_element(), + ], + ) + } else { + let name_empty = m.name.read(cx).text().trim().is_empty(); + ( + if m.saving { + m.progress.map(t::community_settings_saving_progress).unwrap_or_else(t::community_settings_saving) + } else if warn { + t::community_settings_save_before_closing() + } else { + t::community_settings_unsaved() + }, + vec![ + text_btn("cs-reset", t::community_settings_reset(), !m.saving, click(on, || Act::Reset)), + save_btn( + "cs-save", + t::community_settings_save(), + !m.saving && !name_empty, + click(on, || Act::Save), + ) + .into_any_element(), + ], + ) + }; + // `cs-shake`, from the refusal that lit the warning. + let shaken = m.warn_until.filter(|_| warn).map(|t| { + use std::hash::{Hash, Hasher}; + let mut h = std::collections::hash_map::DefaultHasher::new(); + t.hash(&mut h); + let key = h.finish(); + (SharedString::from(format!("cs-shake-{key}")), t) + }); + Some( + div() + .absolute() + .bottom(px(22.)) + .left_0() + .right_0() + .flex() + .justify_center() + .px(px(22.)) + .child( + div() + .relative() + .w_full() + .max_w(px(600.)) + .flex() + .items_center() + .gap(px(16.)) + .pl(px(18.)) + .pr(px(10.)) + .py(px(10.)) + .rounded(px(12.)) + .border_1() + .border_color(if warn { + c(crate::timeline::DANGER) + } else { + c(0x2c2c2c) + }) + .bg(c(0x151515)) + .shadow(vec![gpui::BoxShadow { + color: ca(0, 0, 0, 0.55), + offset: gpui::point(px(0.), px(10.)), + blur_radius: px(30.), + spread_radius: px(0.), + inset: false, + }]) + .child( + div() + .flex_1() + .min_w_0() + .text_size(px(14.)) + .line_height(px(24.)) + .text_color(if warn { + c(crate::timeline::DANGER) + } else { + c(0xe6e6e6) + }) + .child(text), + ) + .child(div().flex().gap(px(6.)).children(actions)) + .map(|bar| match shaken { + Some((id, _)) => bar + .with_animation(id, gpui::Animation::new(std::time::Duration::from_millis(420)), |d, t| { + d.left(px(shake(t))) + }) + .into_any_element(), + None => bar.into_any_element(), + }), + ) + // `.cs-savebar.visible`: up from below its own height, the fade quicker than the rise. + .with_animation("cs-bar-in", gpui::Animation::new(std::time::Duration::from_millis(320)), |d, t| { + let rise = crate::kit::bezier(0.22, 1., 0.36, 1.)(t); + let fade = crate::kit::bezier(0.25, 0.1, 0.25, 1.)((t * 1.6).min(1.)); + d.relative().top(px(78. * (1. - rise))).opacity(fade) + }) + .into_any_element(), + ) +} + +/// `cs-shake`'s offset at `t` of its run, each step eased on its own as CSS keyframes are. +fn shake(t: f32) -> f32 { + const STOPS: [f32; 11] = [0., -1., 3., -5., 5., -5., 5., -5., 3., -1., 0.]; + let at = (t * 10.).min(9.999); + let i = at as usize; + let k = crate::kit::bezier(0.36, 0.07, 0.19, 0.97)(at - i as f32); + STOPS[i] + (STOPS[i + 1] - STOPS[i]) * k +} + +pub(crate) fn text_btn( + id: &'static str, + label: impl Into, + live: bool, + on: impl Fn(&gpui::ClickEvent, &mut Window, &mut App) + 'static, +) -> AnyElement { + div() + .id(id) + .h(px(34.)) + .px(px(14.)) + .rounded(px(8.)) + .flex() + .items_center() + .font_weight(FontWeight::MEDIUM) + .text_size(px(14.)) + .text_color(c(0xcfcfcf)) + .when(!live, |d| d.opacity(0.45)) + .when(live, |d| { + d.cursor_pointer() + .hover(|d| d.bg(white_a(0.06)).text_color(c(0xffffff))) + .on_click(on) + }) + .child(label.into()) + .into_any_element() +} + +/// `compact` is the phone sheet (760px or less): full window, the sections a strip of tabs. +pub fn view(m: &CommSettings, store: &Store, compact: bool, on: &OnAct, cx: &App) -> impl IntoElement + use<> { + let sections = m.sections(); + let section = sections + .iter() + .find(|s| s.id == m.section) + .unwrap_or(§ions[0]); + // The anchor jumped to, until a wheel moves on; else the block crossing the middle, or + // the last once the bottom is reached. + let active = m.anchor.filter(|a| section.anchors.iter().any(|x| x.id == *a)).unwrap_or_else(|| { + let last = section.anchors.len().saturating_sub(1); + let h = &m.scroll; + let (view, y) = (h.bounds(), -h.offset().y); + let mid = y + view.size.height / 2.; + let mut at = (0..=last).take_while(|&i| block_top(i).is_some_and(|t| t <= mid)).last().unwrap_or(0); + let max = h.max_offset().y; + if max > px(0.) && y >= max - px(2.) { + at = last; + } + section.anchors[at].id + }); + let name = store + .community(&m.community) + .map(|c| c.name.clone()) + .filter(|n| !n.is_empty()) + .unwrap_or_else(|| t::community_settings_unnamed().into()); + let head = div() + .mx(px(10.)) + .mb(px(17.)) + .pb(px(16.)) + .border_b_1() + .border_color(c(0x262626)) + .flex() + .items_center() + .gap(px(8.)) + .child(crate::community::logo(store, &m.community, 28., 8.)) + .child( + div() + .min_w_0() + .truncate() + .font_weight(FontWeight::BOLD) + .text_size(px(14.)) + .line_height(px(17.)) + .text_color(c(0xffffff)) + .child(name), + ) + .into_any_element(); + let (a, b, d) = (on.clone(), on.clone(), on.clone()); + let nav_on = NavOn { + section: Rc::new(move |id, w, cx| a(Act::Section(id), w, cx)), + anchor: Rc::new(move |(s, x), w, cx| b(Act::Anchor(s, x), w, cx)), + clear: Rc::new(move |_, w, cx| d(Act::ClearSearch, w, cx)), + }; + let nav = if compact { + let pick = on.clone(); + tab_strip(§ions, section.id, Rc::new(move |id, w, cx| pick(Act::Section(id), w, cx)), None) + } else { + crate::settings::section_nav( + §ions, + section.id, + &[], + active, + &m.search, + head, + None, + 249., + 0x0b0b0b, + &nav_on, + cx, + ) + }; + TOPS.with(|t| t.borrow_mut().clear()); + SCROLL.with(|s| *s.borrow_mut() = Some(m.scroll.clone())); + let body = match section.id { + "overview" => overview(m, store, compact, on, cx), + "relays" => relays(m, on, cx), + "bans" => bans(m, store, on, cx), + "roles" => crate::roles::view(m, store, on, cx), + _ => audit(m, store, on, cx), + }; + SCROLL.with(|s| *s.borrow_mut() = None); + let wheel = on.clone(); + let close = on.clone(); + let main = div() + .flex_1() + .min_w_0() + .h_full() + .relative() + .flex() + .flex_col() + .child( + div() + .h(px(50.)) + .flex_shrink_0() + .pl(px(28.)) + .pr(px(18.)) + .flex() + .items_center() + .justify_between() + .border_b_1() + .border_color(c(0x171717)) + .child( + div() + .text_size(px(16.)) + .line_height(px(19.)) + .text_color(c(0xffffff)) + .child((section.label)()), + ) + .child( + div() + .id("cs-close") + .mt(px(2.)) + .flex() + .flex_col() + .items_center() + .gap(px(2.)) + .cursor_pointer() + .group("cs-close") + .on_click(move |_, w, cx| close(Act::Close, w, cx)) + .child( + div() + .size(px(32.)) + .rounded_full() + .border_1() + .border_color(c(0x4a4a4a)) + .flex() + .items_center() + .justify_center() + .font_weight(FontWeight::SEMIBOLD) + .text_size(px(12.)) + .text_color(c(0x9a9a9a)) + .group_hover("cs-close", |d| { + d.text_color(c(0xffffff)).border_color(c(0x6a6a6a)) + }) + .child("✕"), + ) + .child( + div() + .font_weight(FontWeight::SEMIBOLD) + .text_size(px(9.)) + .line_height(px(10.)) + .text_color(c(0x9a9a9a)) + .child("ESC"), // i18n-exempt: key name + ), + ), + ) + .child( + div() + .id(SharedString::from(format!("cs-scroll-{}", section.id))) + .flex_1() + .min_h_0() + .overflow_y_scroll() + .track_scroll(&m.scroll) + .when(m.anchor.is_some(), |d| d.on_scroll(move |_, w, cx| wheel(Act::Scrolled, w, cx))) + .child( + div() + .w_full() + .when(!compact, |d| d.max_w(px(720.)).mx_auto().px(px(62.)).pt(px(12.))) + .when(compact, |d| d.px(px(18.)).pt(px(4.))) + .pb(px(140.)) + .child(crate::kit::rise("cs-content-in", body, 300, (0., 8., 1.), crate::kit::bezier(0.22, 1., 0.36, 1.))), + ), + ) + .children(save_bar(m, on, cx)); + let card = div() + .id("cs-card") + .w_full() + .h_full() + .flex() + .when(compact, |d| d.flex_col()) + .when(!compact, |d| d.max_w(px(1182.)).max_h(px(862.)).rounded(px(18.)).border_1().border_color(c(0x2c2e2f))) + .bg(c(0x050505)) + .overflow_hidden() + .font_family(RUBIK) + .occlude() + .on_click(|_, _, cx| cx.stop_propagation()) + .child(nav) + .child(main); + let report = m.report.as_ref().map(|r| sync_report(r, on)); + let dismiss = on.clone(); + gpui::deferred( + div() + .id("cs-overlay") + .absolute() + .inset_0() + .bg(ca(0, 0, 0, 0.85)) + .flex() + .items_center() + .justify_center() + .when(!compact, |d| d.p(px(25.))) + .occlude() + .on_click(move |_, w, cx| dismiss(Act::Close, w, cx)) + .child(crate::kit::pop("cs-pop", card, 160)) + .children(report), + ) + .with_priority(12) +} + +/// `.cs-nav` on a phone: the sections side by side in a strip that scrolls. +pub(crate) fn tab_strip( + sections: &[Category], + current: &str, + pick: Rc, + tail: Option, +) -> AnyElement { + let mut strip = div() + .id("cs-tabs") + .flex() + .gap(px(6.)) + .py(px(10.)) + .px(px(12.)) + .overflow_x_scroll(); + for s in sections { + let here = s.id == current; + let id = s.id; + let pick = pick.clone(); + strip = strip.child( + div() + .id(SharedString::from(format!("cs-tab-{id}"))) + .flex_shrink_0() + .h(px(38.)) + .px(px(11.)) + .flex() + .items_center() + .gap(px(12.)) + .rounded(px(8.)) + .text_size(px(15.)) + .line_height(px(18.)) + .whitespace_nowrap() + .cursor_pointer() + .when(here, |d| d.bg(c(0x1b1b1b)).text_color(c(0xffffff))) + .when(!here, |d| d.text_color(c(0xb2b2b2)).hover(|d| d.bg(c(0x141414)))) + .on_click(move |_, w, cx| pick(id, w, cx)) + .child( + svg() + .path(SharedString::from(format!("icons/{}.svg", s.icon))) + .size(px(17.)) + .flex_shrink_0() + .text_color(if here { white_a(0.5) } else { c(0x5b6060) }), + ) + .child((s.label)()), + ); + } + div() + .flex_shrink_0() + .bg(c(0x0b0b0b)) + .border_b_1() + .border_color(c(0x262626)) + .child(strip.children(tail.map(|t| div().ml_auto().flex_shrink_0().child(t)))) + .into_any_element() +} + +// i18n-exempt: Sync Report findings stay in the copied report's English +const REPORT_KINDS: &[(u64, &str)] = &[ + (0, "community"), + (1, "role"), + (2, "channel"), + (3, "grant"), + (4, "banlist"), + (8, "invite links"), // i18n-exempt: report English + (10, "dissolved"), + (11, "pins"), + (13, "role"), + (14, "permissions"), + (15, "category"), + (16, "tenure"), + (17, "channel sync"), // i18n-exempt: report English + (18, "writers"), +]; + +fn kind_name(k: &serde_json::Value) -> String { + let n = k.as_u64().unwrap_or(u64::MAX); + REPORT_KINDS.iter().find(|(id, _)| *id == n).map(|(_, s)| s.to_string()).unwrap_or_else(|| format!("kind {k}")) // i18n-exempt: report English +} + +fn truthy(v: &serde_json::Value) -> bool { + match v { + serde_json::Value::Null => false, + serde_json::Value::Bool(b) => *b, + serde_json::Value::Number(n) => n.as_f64().is_some_and(|f| f != 0.0), + serde_json::Value::String(s) => !s.is_empty(), + _ => true, + } +} + +/// Refused, held back, or not this device's newest. +pub fn report_flagged(data: &serde_json::Value) -> Vec<&serde_json::Value> { + let ver = |v: &serde_json::Value| v["version"].as_f64(); + data["control"]["entities"] + .as_array() + .map(|ents| { + ents.iter() + .filter(|e| { + let newest = &e["newest"]; + let has = truthy(newest); + truthy(&e["refused"]) + || truthy(&e["carried"]) + || truthy(&e["kept"]) + || truthy(&e["mine"]) + || (has && !truthy(&newest["admitted"])) + || (has + && truthy(&e["floor"]) + && ver(newest) > ver(&e["floor"]) + && !(truthy(&e["folds_to"]) && ver(&e["folds_to"]) >= ver(newest))) + }) + .collect() + }) + .unwrap_or_default() +} + +fn report_row(e: &serde_json::Value) -> String { + let v = |x: &serde_json::Value| x["version"].as_u64().map(|n| n.to_string()).unwrap_or_else(|| "–".into()); + let shown = |x: &serde_json::Value| x.as_str().map(str::to_string).unwrap_or_else(|| x.to_string()); + let mut out = format!( + // i18n-exempt: report English + " {}{} · held v{} · newest v{}", + shown(&e["entity"]), + if truthy(&e["mine"]) { " (yours)" } else { "" }, // i18n-exempt: report English + v(&e["floor"]), + v(&e["newest"]), + ); + if truthy(&e["newest"]) { + out += &format!(" by {}", shown(&e["newest"]["author"])); // i18n-exempt: report English + } + if truthy(&e["refused"]) { + out += &format!(" · refused: {}", shown(&e["refused"])); // i18n-exempt: report English + } + if truthy(&e["carried"]) { + out += "· kept, refused"; // i18n-exempt: report English + } + if truthy(&e["kept"]) { + out += "· kept"; // i18n-exempt: report English + } + if truthy(&e["newest"]) && !truthy(&e["newest"]["admitted"]) { + out += "· not admitted"; // i18n-exempt: report English + } + out +} + +fn report_chip(text: impl Into, bad: bool) -> impl IntoElement { + let tone = if bad { c(crate::timeline::DANGER) } else { white_a(0.14) }; + div() + .px(px(10.)) + .py(px(4.)) + .rounded_full() + .border_1() + .border_color(tone) + .text_size(px(12.)) + .line_height(px(24.)) + .text_color(if bad { tone } else { white_a(0.8) }) + .child(text.into()) +} + +fn report_label(text: SharedString) -> impl IntoElement { + div() + .mt(px(16.)) + .mb(px(6.)) + .text_size(px(11.)) + .line_height(px(24.)) + .font_weight(FontWeight::BOLD) + .text_color(white_a(0.45)) + .child(crate::kit::spaced(text.to_uppercase(), 11. * 0.12)) +} + +fn sync_report(r: &Report, on: &OnAct) -> AnyElement { + let shown = |x: &serde_json::Value| x.as_str().map(str::to_string).unwrap_or_else(|| x.to_string()); + let mut body = div() + .id("sr-body") + .flex_1() + .min_h_0() + .overflow_y_scroll() + .px(px(18.)) + .py(px(14.)); + if r.loading { + body = body.child(div().p(px(2.)).mb(px(11.)).text_size(px(12.5)).line_height(px(18.)).text_color(white_a(0.4)).child(t::community_settings_report_reading())); + } else if let Some(err) = &r.error { + body = body.child(div().text_size(px(13.)).text_color(c(crate::timeline::DANGER)).child(crate::coretext::say(err).into_owned())); + } else if let Some(d) = &r.data { + let ctl = &d["control"]; + let ep = &d["epoch"]; + let mut chips = div().flex().flex_wrap().gap(px(6.)).child(report_chip( + format!("{} {}", shown(&d["client"]), shown(&d["version"])), + false, + )); + if truthy(ctl) && !truthy(&ctl["error"]) { + let settled = truthy(&ctl["converged"]); + let cut = truthy(&ctl["truncated"]); + chips = chips + .child(report_chip(format!("Epoch {}", shown(&ctl["root_epoch"])), false)) // i18n-exempt: report English + .child(report_chip(if settled { "Authority settled" } else { "Authority unsettled" }, !settled)) // i18n-exempt: report English + .child(report_chip(if cut { "Read cut short" } else { "Read whole" }, cut)) // i18n-exempt: report English + .child(report_chip( + // i18n-exempt: report English + format!("{} edits, {} pages", shown(&ctl["editions"]), shown(&ctl["pages_read"])), + false, + )) + .when(truthy(&ctl["would_update"]), |d| d.child(report_chip("Unsaved changes", true))); // i18n-exempt: report English + } else if truthy(&ctl["error"]) { + chips = chips.child(report_chip(format!("Control: {}", shown(&ctl["error"])), true)); // i18n-exempt: report English + } + if truthy(&ep["error"]) { + chips = chips.child(report_chip(format!("Epoch: {}", shown(&ep["error"])), true)); // i18n-exempt: report English + } + body = body.child(chips); + let flagged = report_flagged(d); + if !flagged.is_empty() { + body = body.child(report_label(t::community_settings_report_flagged())).child( + div().pl(px(18.)).flex().flex_col().children(flagged.into_iter().map(|e| { + div() + .relative() + .text_size(px(13.)) + .line_height(px(22.)) + .text_color(white_a(0.85)) + .child(div().absolute().left(px(-12.)).child("•")) + .child( + div() + .flex() + .flex_wrap() + .child(div().font_weight(FontWeight::BOLD).child(kind_name(&e["kind"]))) + .child(report_row(e)), + ) + })), + ); + } + body = body.child(report_label(t::community_settings_report_full())).child( + div() + .id("sr-pre") + .max_h(px(342.)) + .overflow_scroll() + .px(px(12.)) + .py(px(10.)) + .rounded(px(10.)) + .border_1() + .border_color(white_a(0.08)) + .bg(c(0x070707)) + .font_family(MONO) + .text_size(px(11.)) + .line_height(px(16.)) + .text_color(c(0xf6f6f6)) + .whitespace_nowrap() + .child(r.text.clone()), + ); + } + let close = on.clone(); + let card = div() + .id("sr-card") + .w_full() + .max_w(px(720.)) + .max_h_full() + .flex() + .flex_col() + .rounded(px(18.)) + .border_1() + .border_color(c(0x2c2e2f)) + .bg(c(0x101010)) + .overflow_hidden() + .occlude() + .on_click(|_, _, cx| cx.stop_propagation()) + .child( + div() + .flex() + .items_start() + .justify_between() + .gap(px(12.)) + .pt(px(16.)) + .px(px(18.)) + .pb(px(12.)) + .border_b_1() + .border_color(ca(57, 57, 57, 0.5)) + .child( + div() + .child(div().text_size(px(17.)).line_height(px(24.)).font_weight(FontWeight::SEMIBOLD).text_color(c(0xf6f6f6)).child(t::community_settings_sync_report())) + .child( + div() + .mt(px(4.)) + .text_size(px(13.)) + .line_height(px(24.)) + .text_color(white_a(0.55)) + .child(t::community_settings_report_lede()), + ), + ) + .child( + div() + .id("sr-close") + .flex() + .flex_col() + .items_center() + .gap(px(2.)) + .cursor_pointer() + .group("sr-close") + .on_click(move |_, w, cx| close(Act::ReportClose, w, cx)) + .child( + div() + .size(px(30.)) + .rounded_full() + .border(px(1.5)) + .border_color(c(0x4a4a4a)) + .flex() + .items_center() + .justify_center() + .text_size(px(12.)) + .text_color(c(0x9a9a9a)) + .group_hover("sr-close", |d| d.text_color(c(0xffffff)).border_color(c(0x9a9a9a))) + .child("✕"), + ), + ), + ) + .child(body) + .child( + div() + .flex() + .justify_end() + .gap(px(8.)) + .px(px(18.)) + .py(px(12.)) + .border_t_1() + .border_color(ca(57, 57, 57, 0.5)) + .child(text_btn("sr-done", t::community_settings_report_close(), true, click(on, || Act::ReportClose))) + .child(save_btn("sr-copy", t::community_settings_report_copy(), !r.text.is_empty(), click(on, || Act::ReportCopy))), + ); + let dismiss = on.clone(); + div() + .id("sr-overlay") + .absolute() + .inset_0() + .bg(ca(0, 0, 0, 0.7)) + .flex() + .items_center() + .justify_center() + .p(px(16.)) + .occlude() + .on_click(move |_, w, cx| { + cx.stop_propagation(); + dismiss(Act::ReportClose, w, cx) + }) + .child(card) + .into_any_element() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn relay_addresses() { + let list = vec!["wss://a.example".to_string()]; + assert_eq!( + relay_address("relay.example.com/", &list, None).as_deref(), + Ok("wss://relay.example.com") + ); + assert!(relay_address("ws://plain.example", &list, None).is_err()); + assert_eq!( + relay_address("ws://abc.onion", &list, None).as_deref(), + Ok("ws://abc.onion") + ); + assert_eq!( + relay_address("WSS://A.example/", &list, None), + Err("That relay is already listed.".into()) + ); + assert_eq!( + voice_address("relay.example.com", &[]).as_deref(), + Ok("https://relay.example.com/") + ); + assert!(voice_address("http://relay.example.com", &[]).is_err()); + } +} diff --git a/crates/vector-gpui/src/community.rs b/crates/vector-gpui/src/community.rs new file mode 100644 index 000000000..41be667e5 --- /dev/null +++ b/crates/vector-gpui/src/community.rs @@ -0,0 +1,1634 @@ +//! Communities: the rail's rows, a Community's channel pane, its channel header and the +//! member panel beside the conversation. + +use crate::kit::Tipped as _; +use std::collections::HashSet; +use std::rc::Rc; + +use gpui::prelude::*; +use gpui::{AnyElement, App, Entity, FontWeight, SharedString, Window, div, px, svg}; +use crate::pic::img; + +use crate::composer::TextInput; +use crate::data::{Channel, Community, Store}; +use crate::t; +use crate::theme::*; + +pub enum Act { + /// A member list's warning mark: why they're listed apart. + Unlisted(String), + Open(String), + /// Back to Messages. + Home, + /// Right-click on the Messages door. + MessagesMenu(gpui::Point), + /// An unread DM from the rail. + Dm(String), + Channel(String), + /// A voice channel's chat, without joining its call. + ChannelChat(String), + /// A Category or member section folded or unfolded. + Fold(String), + Panel, + /// The Community's own menu, hung off its header. + HeadMenu, + BannerMenu(gpui::Point), + ChannelMenu(String, gpui::Point), + /// A Category's "+": a new channel inside it. + AddChannel(String), + Create, + /// A rail folder opened or shut. + RailFolder(String), + /// Right-click on a rail row: a community's key, or a folder's id. + RailMenu(Option, Option, gpui::Point), + RailDrop( + vector_core::rail_layout::RailDrag, + vector_core::rail_layout::RailDrop, + ), + /// Invite People, for the open Community. + Invite, + CategoryMenu(String, gpui::Point), + /// The channel list's empty space. + ChannelsMenu(gpui::Point), + /// The open channel's ⋯. + ChatMenu, + /// Search this channel. + Search, + /// The member pane's search. + Find(crate::search::Act), + EditChannel(String), + /// A member tapped: their mini profile, beside what was painted under the key. + Member(String, SharedString), + /// A member right-clicked: their menu. + MemberMenu(String, gpui::Point), + /// A roster section head's menu: a role's carries its id. + SectionMenu(String, gpui::Point), + /// A manager dropped a dragged channel: before or after another, or into a Category's top. + DropChannel(String, DropAt), + /// A manager dropped a dragged Category before (`true`) or after another. + DropCategory(String, String, bool), +} + +/// Where a dragged channel lands. +#[derive(Clone, Debug)] +pub enum DropAt { + Before(String), + After(String), + /// The top of this Category. + Into(String), +} + +/// A channel row being moved by a manager. +#[derive(Clone)] +pub struct ChannelDrag { + id: String, + name: SharedString, +} + +/// A Category heading being moved by a manager. +#[derive(Clone)] +pub struct CategoryDrag { + id: String, + name: SharedString, +} + +/// What follows the pointer while a channel or Category moves. +struct DragGhost(SharedString); + +impl gpui::Render for DragGhost { + fn render(&mut self, _: &mut Window, _: &mut gpui::Context) -> impl IntoElement { + div() + .w(px(200.)) + .h(px(32.)) + .px(px(10.)) + .flex() + .items_center() + .rounded(px(6.)) + .bg(c(0x161616)) + .opacity(0.92) + .shadow_lg() + .text_size(px(15.)) + .text_color(c(0xffffff)) + .child(div().truncate().child(self.0.clone())) + } +} + +/// A drop half over a row or heading: its top or bottom, lit with the accent edge while +/// something of type `D` hovers it. +fn drop_half(top: bool, on: &OnAct, act: impl Fn(&D) -> Act + 'static) -> gpui::Div { + let zone = div().absolute().left_0().right_0().h(gpui::relative(0.5)); + let zone = if top { zone.top_0() } else { zone.bottom_0() }; + let on = on.clone(); + zone.drag_over::(move |d, _, _, _| if top { d.border_t_2() } else { d.border_b_2() }.border_color(c(PRIMARY))) + .on_drop(move |d: &D, w, cx| on(act(d), w, cx)) +} + +pub type OnAct = Rc; + +/// The open Community and what its panes hold. +pub struct View { + pub id: String, + pub members: Vec, + pub admins: Vec, + /// Seen posting outside the Guestbook: npub → `no_join` | `departed`. Listed, never counted. + pub unlisted: std::collections::HashMap, + /// No roster yet, cached or read. + pub loading: bool, + pub panel: bool, + pub search: Entity, + /// What the member pane's field finds beyond members: the Community's messages. + pub find: crate::search::Search, + pub folded: HashSet, + pub scroll: gpui::ScrollHandle, +} + +struct GraphRole { + id: String, + name: String, + position: i64, + color: u32, + channel: Option, + display: bool, +} + +/// `get_community_role_graph`: every role with its rank, who holds which, and on the new roles +/// each Private Channel's readers. +#[derive(Default)] +pub struct Graph { + activated: bool, + roles: Vec, + grants: std::collections::HashMap>, + readers: std::collections::HashMap>, +} + +impl Graph { + pub fn parse(v: &serde_json::Value) -> Self { + let text = |v: &serde_json::Value| v.as_str().map(str::to_string); + let list = |v: &serde_json::Value| v.as_array().into_iter().flatten().filter_map(text).collect::>(); + Graph { + activated: v["activated"].as_bool().unwrap_or(false), + roles: v["roles"] + .as_array() + .into_iter() + .flatten() + .filter_map(|r| { + Some(GraphRole { + id: text(&r["role_id"])?, + name: text(&r["name"]).map(|n| crate::kit::one_line(&n).into_owned()).unwrap_or_default(), + position: r["position"].as_i64().unwrap_or(i64::MAX), + color: r["color"].as_u64().unwrap_or(0) as u32, + channel: text(&r["channel_id"]).map(|c| c.to_ascii_lowercase()), + display: r["display"].as_bool().unwrap_or(false), + }) + }) + .collect(), + grants: v["grants"] + .as_array() + .into_iter() + .flatten() + .filter_map(|g| Some((text(&g["npub"])?, list(&g["role_ids"])))) + .collect(), + readers: v["readers"] + .as_object() + .into_iter() + .flatten() + .map(|(k, v)| (k.to_ascii_lowercase(), list(v).into_iter().collect())) + .collect(), + } + } + + /// Heads a section: on the new roles only a role shown separately; rank still counts them all. + fn heads(&self, r: &GraphRole) -> bool { + !self.activated || r.display + } + + /// Their highest role (lowest position) among those `pick` admits. + fn highest(&self, npub: &str, pick: impl Fn(&GraphRole) -> bool) -> Option<&GraphRole> { + self.grants + .get(npub)? + .iter() + .filter_map(|id| self.roles.iter().find(|r| &r.id == id)) + .filter(|r| pick(r)) + .min_by_key(|r| r.position) + } + + /// Who may read Private Channel `channel`: the owner, and on the old roles the holders of a + /// role scoped to it. + pub fn readers(&self, channel: &str, owner: Option<&str>) -> HashSet { + let mut out: HashSet = owner.map(str::to_string).into_iter().collect(); + if self.activated { + out.extend(self.readers.get(channel).into_iter().flatten().cloned()); + } else { + let access: HashSet<&str> = + self.roles.iter().filter(|r| r.channel.as_deref() == Some(channel)).map(|r| r.id.as_str()).collect(); + out.extend(self.grants.iter().filter(|(_, ids)| ids.iter().any(|i| access.contains(i.as_str()))).map(|(n, _)| n.clone())); + } + out + } +} + +const OWNER: u32 = 0xfce459; +const LABEL: u32 = 0x8a8a8a; + +/// The community's logo, or the group placeholder until it has one. +pub fn logo(store: &Store, id: &str, size: f32, radius: f32) -> gpui::Stateful { + match store.icon(id) { + Some(path) => crate::pic::img_face(path, size).object_fit(gpui::ObjectFit::Cover).face(), + None => img("icons/group-placeholder.svg"), + } + .size(px(size)) + .aspect_ratio(1.) + .rounded(px(radius)) + .flex_shrink_0() +} + +/// `.banner-art`: a banner cut to the 238 x 70 template at `width`, grey until it paints. +pub fn banner_art(path: std::path::PathBuf, width: f32) -> gpui::Stateful { + crate::pic::img_fit(path, width) + .w(px(width)) + .h(px(width * 70. / 238.)) + .aspect_ratio(238. / 70.) + .bg(c(0x484848)) + .object_fit(gpui::ObjectFit::Cover) +} + +fn click( + on: &OnAct, + act: impl Fn() -> Act + 'static, +) -> impl Fn(&gpui::ClickEvent, &mut Window, &mut App) + 'static { + let on = on.clone(); + move |_, window, cx| on(act(), window, cx) +} + +fn icon(path: &'static str, size: f32, color: gpui::Hsla) -> gpui::Svg { + svg() + .path(path) + .size(px(size)) + .flex_shrink_0() + .text_color(color) +} + +fn channel_glyph(ch: &Channel) -> &'static str { + if ch.is_voice() { + "icons/volume-max.svg" + } else if ch.private { + "icons/locked.svg" + } else { + "icons/channel-hash.svg" + } +} + +fn channel_unread(store: &Store, ch: &Channel) -> usize { + store + .chat(&ch.channel_id) + .map(|chat| store.unread_count(chat)) + .unwrap_or(0) +} + +fn channel_row( + store: &Store, + ch: &Channel, + open: bool, + owner: bool, + on: &OnAct, +) -> impl IntoElement { + let id = ch.channel_id.clone(); + let group = SharedString::from(format!("ch-{}", ch.channel_id)); + let muted = store.chat(&ch.channel_id).is_some_and(|chat| chat.muted); + let unread = !open && !muted && channel_unread(store, ch) > 0; + // A number only for someone calling your name; a room set to Nothing is silent here too. + let pings = store + .chat(&ch.channel_id) + .filter(|chat| !open && chat.notify < 2) + .map_or(0, |chat| crate::pings::count(store, chat)); + let ink = if open || unread { + c(0xffffff) + } else if muted { + white_a(0.3) + } else { + white_a(0.55) + }; + let action = |path: &'static str, act: Option Act>>| { + let tip = match path { + "icons/add-user.svg" => Some(t::community_channel_invite()), + "icons/settings.svg" => Some(t::community_channel_edit()), + "icons/chat-bubble.svg" => Some(t::community_channel_chat()), + _ => None, + }; + div() + .id(path) + .when_some(tip, |d, t| d.tip(t)) + .when_some(act, |d, act| { + let on = on.clone(); + d.on_click(move |_, w, cx| { + cx.stop_propagation(); + on(act(), w, cx) + }) + }) + .size(px(18.)) + .flex() + .items_center() + .justify_center() + .flex_shrink_0() + .opacity(0.6) + .child(icon(path, 14., c(0xffffff))) + }; + // Zero width until hovered, so the name runs full width meanwhile. Width, not display: a + // hover flip between prepaint and paint would paint children that were never prepainted. + let actions = div() + .id("channel-actions") + .flex() + .items_center() + .gap(px(8.)) + .flex_shrink_0() + .overflow_hidden() + .when(!open, |d| d.max_w(px(0.)).ml(px(-8.)).group_hover(group.clone(), |d| d.max_w(px(80.)).ml(px(0.)))) + .when(owner && !ch.private, |d| d.child(action("icons/add-user.svg", Some(Rc::new(|| Act::Invite))))) + .when(owner, |d| { + let gear = ch.channel_id.clone(); + d.child(action("icons/settings.svg", Some(Rc::new(move || Act::EditChannel(gear.clone()))))) + }) + .when(ch.is_voice(), |d| { + let chat = ch.channel_id.clone(); + d.child(action("icons/chat-bubble.svg", Some(Rc::new(move || Act::ChannelChat(chat.clone()))))) + }); + div() + .id(SharedString::from(format!( + "chatlist-channel-{}", + ch.channel_id + ))) + .role(gpui::Role::Button) + .when_some(ch.topic.clone().filter(|t| !t.is_empty()), |d, t| d.tip(t)) + .group(group.clone()) + .mx(px(8.)) + .h(px(32.)) + .flex_shrink_0() + .rounded(px(4.)) + .flex() + .items_center() + .gap(px(8.)) + .px(px(8.)) + .cursor_pointer() + .text_color(ink) + .when(open, |d| d.bg(white_a(0.09))) + .when(!open, |d| { + d.hover(|d| d.bg(white_a(0.045)).text_color(c(0xffffff))) + }) + .on_click(click(on, move || Act::Channel(id.clone()))) + .on_mouse_down(gpui::MouseButton::Right, { + let (on, id) = (on.clone(), ch.channel_id.clone()); + move |e, w, cx| { + cx.stop_propagation(); + on(Act::ChannelMenu(id.clone(), e.position), w, cx) + } + }) + // A manager moves channels: dragged onto another's top or bottom half. + .when(owner, |d| { + let (above, below) = (ch.channel_id.clone(), ch.channel_id.clone()); + d.relative() + .on_drag(ChannelDrag { id: ch.channel_id.clone(), name: ch.name.clone().into() }, |d: &ChannelDrag, _, _, cx| { + cx.new(|_| DragGhost(d.name.clone())) + }) + .child(drop_half(true, on, move |d: &ChannelDrag| Act::DropChannel(d.id.clone(), DropAt::Before(above.clone())))) + .child(drop_half(false, on, move |d: &ChannelDrag| Act::DropChannel(d.id.clone(), DropAt::After(below.clone())))) + }) + .child(icon(channel_glyph(ch), 18., ink)) + .child( + div() + .flex_1() + .min_w_0() + .truncate() + .text_size(px(15.)) + .line_height(px(24.)) + .when(unread, |d| d.font_weight(FontWeight::MEDIUM)) + .child(ch.name.clone()), + ) + .when(pings > 0, |d| d.child(crate::pings::channel_pill(pings))) + .when(owner || ch.is_voice(), |d| d.child(actions)) +} + +/// `.chatlist-community-head-alert`: pulses, since noticing a raid late costs the community. +fn raid_pip() -> impl IntoElement { + const SPAN: f32 = 1.9; + // Its ring is gone for the last 30% of the beat, so that stretch is one still frame. + let mut times = crate::sprite::times(SPAN * 0.7, 20.); + times.push(SPAN * 0.7); + // A ring, not a box-shadow spread: GPUI keeps a shadow's corner radius as the spread grows. + // Two device pixels a point: the sidebar has no window to ask, and a 22pt pip shows no loss. + let strip = crate::sprite::strip("raid-pulse", 2., 22, ×, SPAN, |t, buf, k| { + let p = t / SPAN; + if p < 0.7 { + let e = gpui::ease_out_quint()(p / 0.7); + crate::sprite::disc(buf, 11. * k, 11. * k, (4. + 7. * e) * k, crate::timeline::DANGER, 0.7 * (1. - e)); + } + crate::sprite::disc(buf, 11. * k, 11. * k, 4. * k, crate::timeline::DANGER, 1.); + }); + div().relative().size(px(8.)).flex_shrink_0().child( + gpui::img(gpui::ImageSource::Render(strip)).id("raid-pulse").absolute().left(px(-7.)).top(px(-7.)).size(px(22.)), + ) +} + +/// `#chats` over a Community: its head, then its channels by Category. +pub fn sidebar( + store: &Store, + view: &View, + com: &Community, + open: Option<&str>, + raid: bool, + on: &OnAct, + (voice, on_voice, anchors): (&crate::voice::Voice, &crate::voice::OnAct, &crate::kit::Anchors), + width: f32, + slim: bool, +) -> AnyElement { + let row = |ch: &Channel| { + let open = open == Some(ch.channel_id.as_str()); + let row = channel_row(store, ch, open, com.is_owner, on).into_any_element(); + if !ch.is_voice() || (voice.present(&ch.channel_id).is_empty() && voice.joining.as_deref() != Some(ch.channel_id.as_str())) { + return vec![row]; + } + let who = crate::voice::members(voice, store, &com.community_id, &ch.channel_id, on_voice, anchors); + vec![row, who] + }; + let head = div() + .id("chatlist-community-head") + .motion_live() + .h(px(61.)) + .flex_shrink_0() + .flex() + .items_center() + .gap(px(10.)) + .px(px(12.)) + .bg(c(0x171717)) + .border_b_1() + .border_color(c(DIVIDER)) + .cursor_pointer() + .hover(|d| d.bg(white_a(0.045))) + .on_click(click(on, || Act::HeadMenu)) + .on_mouse_down(gpui::MouseButton::Right, { + let on = on.clone(); + move |_, w, cx| on(Act::HeadMenu, w, cx) + }) + .child(logo(store, &com.community_id, 36., 11.)) + .child( + div() + .flex_1() + .min_w_0() + .flex() + .flex_col() + .gap(px(2.)) + .child( + div() + .truncate() + .font_family(RUBIK) + .font_weight(FontWeight::SEMIBOLD) + .text_size(px(15.)) + .line_height(px(18.)) + .text_color(c(0xffffff)) + .child(com.name.clone()), + ) + .child( + div() + .flex() + .items_center() + .gap(px(2.5)) + .text_size(px(12.)) + .line_height(px(14.)) + .text_color(white_a(0.42)) + .child(icon("icons/users-multi.svg", 13., white_a(0.42))) + .child(match view.members.len() { + _ if view.loading => SharedString::default(), + n => t::community_member_count(n), + }), + ), + ) + .when(raid, |d| d.child(raid_pip())) + .child( + div() + .size(px(30.)) + .flex() + .items_center() + .justify_center() + .child(icon("icons/chevron-down.svg", 19.5, white_a(0.4))), + ); + + let banner = store + .banner(&com.community_id) + .filter(|_| !store.hidden_banners.contains(&com.community_id)) + .map(|path| { + div() + .id("ws-banner") + .flex_none() + .border_b_1() + .border_color(c(0x1f1f1f)) + .on_mouse_down(gpui::MouseButton::Right, { + let on = on.clone(); + move |e, w, cx| on(Act::BannerMenu(e.position), w, cx) + }) + .child(match crate::banner::shown(store, &path, width) { + Some(image) => gpui::img(image) + .w(px(width)) + .h(px(width * 70. / 238.)) + .object_fit(gpui::ObjectFit::Cover) + .into_any_element(), + None => banner_art(path, width).into_any_element(), + }) + }); + let head = div() + .flex_none() + .flex() + .flex_col() + .child(head) + .children(banner); + + let owner = com.is_owner; + let loose: Vec<&Channel> = com + .channels + .iter() + .filter(|ch| ch.category_id.is_none() && ch.visible()) + .collect(); + let mut sections = Vec::new(); + if !loose.is_empty() { + sections.push( + div() + .pt(px(10.)) + .pb(px(2.)) + .flex() + .flex_col() + .gap(px(2.)) + .children(loose.iter().flat_map(|ch| row(ch))) + .into_any_element(), + ); + } + for cat in &com.categories { + let inside: Vec<&Channel> = com + .channels + .iter() + .filter(|ch| ch.category_id.as_deref() == Some(cat.category_id.as_str()) && ch.visible()) + .collect(); + let closed = view.folded.contains(&cat.category_id); + let key = cat.category_id.clone(); + let head = div() + .flex() + .items_center() + .gap(px(4.)) + .pt(px(10.)) + .pb(px(4.)) + .px(px(12.)) + .child( + div() + .id(SharedString::from(format!("cat-{}", cat.category_id))) + .flex_1() + .min_w_0() + .h(px(28.)) + .px(px(4.)) + .rounded(px(6.)) + .flex() + .items_center() + .gap(px(2.)) + .cursor_pointer() + .on_click(click(on, move || Act::Fold(key.clone()))) + .on_mouse_down(gpui::MouseButton::Right, { + let (on, id) = (on.clone(), cat.category_id.clone()); + move |e, w, cx| { + cx.stop_propagation(); + on(Act::CategoryMenu(id.clone(), e.position), w, cx) + } + }) + // A manager's heading is the Category's handle, and the top of it for a channel. + .when(owner, |d| { + let (above, below, into) = (cat.category_id.clone(), cat.category_id.clone(), cat.category_id.clone()); + let on_into = on.clone(); + d.relative() + .on_drag(CategoryDrag { id: cat.category_id.clone(), name: cat.name.clone().into() }, |d: &CategoryDrag, _, _, cx| { + cx.new(|_| DragGhost(d.name.clone())) + }) + .drag_over::(|d, _, _, _| d.bg(white_a(0.09))) + .on_drop(move |d: &ChannelDrag, w, cx| on_into(Act::DropChannel(d.id.clone(), DropAt::Into(into.clone())), w, cx)) + .child(drop_half(true, on, move |d: &CategoryDrag| Act::DropCategory(d.id.clone(), above.clone(), true))) + .child(drop_half(false, on, move |d: &CategoryDrag| Act::DropCategory(d.id.clone(), below.clone(), false))) + }) + .child( + crate::kit::spaced_cut(cat.name.to_uppercase(), 0.99) + .font_weight(FontWeight::BOLD) + .text_size(px(11.)) + .line_height(px(24.)) + .text_color(c(LABEL)), + ) + .child( + div() + .flex_none() + .size(px(18.)) + .flex() + .items_center() + .justify_center() + .child(icon("icons/chevron-down.svg", 11.7, white_a(0.38)).with_transformation(crate::kit::turn( + format!("caret-cat-{}", cat.category_id), + closed, + -std::f32::consts::FRAC_PI_2, + 0.15, + crate::kit::css_ease(), + ))), + ), + ) + .when(owner, |d| { + let key = cat.category_id.clone(); + d.child( + div() + .id(SharedString::from(format!("cat-add-{}", cat.category_id))) + .tip(t::community_add_channel_to(cat.name.as_str())) + .flex_none() + .size(px(22.)) + .rounded(px(6.)) + .flex() + .items_center() + .justify_center() + .cursor_pointer() + .hover(|d| d.bg(white_a(0.045))) + .on_click(click(on, move || Act::AddChannel(key.clone()))) + .child(icon("icons/plus.svg", 14.3, white_a(0.38))), + ) + }); + sections.push( + div() + .when(!sections.is_empty(), |d| d.mt(px(14.))) + .child(head) + .when(!closed, |d| { + d.child(div().pb(px(2.)).flex().flex_col().gap(px(2.)).children( + inside.iter().flat_map(|ch| row(ch)), + )) + }) + .into_any_element(), + ); + } + div() + .w(px(width)) + .flex_shrink_0() + .h_full() + .flex() + .flex_col() + .when(!slim, |d| d.bg(c(LIST_BG)).border_r_1()) + .border_color(c(DIVIDER)) + .child(head) + .child( + div() + .id("community-channels") + .flex_1() + .min_h_0() + .overflow_y_scroll() + .edge_fade(px(24.)) + .pb(px(if slim { 16. } else { 8. })) + .on_mouse_down(gpui::MouseButton::Right, { + let on = on.clone(); + move |e, w, cx| on(Act::ChannelsMenu(e.position), w, cx) + }) + .children(sections), + ) + .into_any_element() +} + +/// The conversation header over a channel: its glyph and name, its topic past a hairline, +/// then the menu and the member panel's toggle. +pub fn header( + ch: &Channel, + panel: bool, + probe: Rc>>>, + pins: Option, + on: &OnAct, +) -> impl IntoElement { + div() + .h(px(61.)) + .flex_shrink_0() + .map(|d| crate::theme::chat_header_ground(d, false)) + .flex() + .items_center() + .pl(px(20.)) + .pr(px(10.)) + .child( + div() + .flex_1() + .min_w_0() + .mt(px(5.)) + .flex() + .items_center() + .gap(px(12.)) + .child( + div() + .flex() + .items_center() + .min_w_0() + .gap(px(8.)) + .child(icon(channel_glyph(ch), 19., white_a(0.45)).flex_none()) + .child( + div() + .min_w_0() + .truncate() + .font_family(RUBIK) + .font_weight(FontWeight::BOLD) + .text_size(px(18.72)) + .line_height(px(24.)) + .text_color(c(TEXT)) + .child(ch.name.clone()), + ), + ) + .children(ch.topic.clone().filter(|t| !t.is_empty()).map(|topic| { + div() + .flex_1() + .min_w_0() + .pl(px(12.)) + .border_l_1() + .border_color(white_a(0.15)) + .opacity(0.8) + .truncate() + .text_size(px(13.5)) + .line_height(px(18.)) + .text_color(white_a(0.5)) + .child(crate::kit::one_line(&topic).into_owned()) + })), + ) + .child(crate::search::button(click(on, || Act::Search))) + .children(pins.map(crate::pins::button)) + .child( + div() + .id("chat-menu") + .tip(t::community_chat_options()) + .relative() + .size(px(40.)) + .flex() + .items_center() + .justify_center() + .cursor_pointer() + .on_click(click(on, || Act::ChatMenu)) + .child( + gpui::canvas(move |b, _, _| probe.set(Some(b)), |_, _, _, _| {}) + .absolute() + .size_full(), + ) + .child(icon("ui/menu-dots.svg", 28., c(ICON_MUTED))), + ) + .child( + div() + .id("details-toggle") + .tip(if panel { t::community_details_hide() } else { t::community_details_show() }) + .aria_expanded(panel) + .ml(px(4.)) + .size(px(32.)) + .rounded(px(6.)) + .flex() + .items_center() + .justify_center() + .cursor_pointer() + .text_color(c(ICON_MUTED)) + .hover(|d| d.bg(white_a(0.045))) + .on_click(click(on, || Act::Panel)) + .child(icon( + if panel { + "ui/details-toggle-open.svg" + } else { + "ui/details-toggle.svg" + }, + 22.8, + c(ICON_MUTED), + )), + ) +} + +/// The slim layout's channel header: the community's face and `#name` centred over the topic, +/// as a DM's is, with only the channel's menu. +pub fn slim_header( + store: &Store, + com: &Community, + ch: &Channel, + probe: Rc>>>, + on: &OnAct, +) -> impl IntoElement { + let face = match store.icon(&com.community_id) { + Some(path) => crate::pic::img_face(path, 22.).object_fit(gpui::ObjectFit::Cover).size(px(22.)).rounded_full().flex_shrink_0().into_any_element(), + None => img("icons/group-placeholder.svg").size(px(22.)).rounded_full().flex_shrink_0().into_any_element(), + }; + let topic = ch.topic.clone().filter(|t| !t.is_empty()); + div() + .h(px(61.)) + .flex_shrink_0() + .relative() + .map(|d| crate::theme::chat_header_ground(d, false)) + .flex() + .justify_center() + .child( + div() + .id("slim-chat-title") + .cursor_pointer() + .on_click(click(on, || Act::Panel)) + .pt(px(if topic.is_some() { 8. } else { 18. })) + .max_w(gpui::relative(0.6)) + .flex() + .flex_col() + .items_center() + .child( + div() + .flex() + .items_center() + .gap(px(6.)) + .child(face) + .child( + div() + .truncate() + .font_family(RUBIK) + .font_weight(FontWeight::BOLD) + .text_size(px(18.72)) + .line_height(px(24.)) + .text_color(c(TEXT)) + .child(if ch.is_voice() { ch.name.clone() } else { format!("#{}", ch.name) }), + ), + ) + .children(topic.map(|t| { + div() + .max_w_full() + .truncate() + .opacity(0.8) + .text_size(px(14.)) + .line_height(px(24.)) + .text_color(c(TEXT)) + .child(t) + })), + ) + .child( + div() + .id("chat-menu") + .absolute() + .right(px(10.)) + .top(px(10.)) + .size(px(40.)) + .flex() + .items_center() + .justify_center() + .cursor_pointer() + .on_click(click(on, || Act::ChatMenu)) + .child(gpui::canvas(move |b, _, _| probe.set(Some(b)), |_, _, _, _| {}).absolute().size_full()) + .child(icon("ui/menu-dots.svg", 28., c(ICON_MUTED))), + ) +} + +/// The roster's search: `body.ws`'s slim pill, else the boxed field. +pub fn member_search_look(slim: bool) -> crate::composer::Look { + crate::composer::Look { + family: INTER, + weight: FontWeight::MEDIUM, + size: px(if slim { 16. } else { 13. }), + line_height: px(if slim { 20. } else { 16. }), + color: c(0xffffff), + placeholder: c(0x757575), + ..Default::default() + } +} + +fn status_line(text: &str) -> AnyElement { + let slim = crate::theme::is_slim(); + let look = if slim { + crate::inline::Look::new(INTER, 12., 16.2, white_a(0.38)) + } else { + crate::inline::Look::new(INTER, 11.5, 15.5, white_a(0.38)) + }; + crate::inline::inline(crate::preview::atoms(text, usize::MAX, &look), look) + .single_line() + .held() + .into_any_element() +} + +fn member_row(store: &Store, cid: &str, npub: &str, owner: bool, colour: Option, unlisted: Option<&str>, on: &OnAct, anchors: &crate::kit::Anchors) -> impl IntoElement { + let status = store + .profiles + .get(npub) + .map(crate::profile::status_title) + .filter(|t| !t.is_empty()); + let key = SharedString::from(format!("roster:{npub}")); + let (tap, k, n) = (on.clone(), key.clone(), npub.to_string()); + let (menu, m) = (on.clone(), npub.to_string()); + // Phone widths keep the base roster row; `body.ws` tightens it around a larger avatar. + let slim = crate::theme::is_slim(); + div() + .id(SharedString::from(format!("member-{npub}"))) + .motion_host() + .h(px(if slim { 46. } else { 40. })) + .rounded(px(6.)) + .flex() + .items_center() + .px(px(if slim { 10. } else { 8. })) + .cursor_pointer() + .hover(|d| d.bg(white_a(0.045))) + .on_click(move |_, w, cx| tap(Act::Member(n.clone(), k.clone()), w, cx)) + .on_mouse_down(gpui::MouseButton::Right, move |e, w, cx| { + cx.stop_propagation(); + menu(Act::MemberMenu(m.clone(), e.position), w, cx) + }) + .child( + div() + .relative() + .child(crate::ui::avatar(store, npub, if slim { 25. } else { 32. })) + .child(crate::kit::anchor(anchors, key)), + ) + .child( + div() + .ml(px(if slim { 10. } else { 12. })) + .flex_1() + .min_w_0() + .flex() + .flex_col() + .child( + div() + .flex() + .items_center() + .gap(px(4.)) + .child( + div() + .truncate() + .font_weight(if slim { FontWeight::NORMAL } else { FontWeight::SEMIBOLD }) + .text_size(px(14.)) + .line_height(px(if slim { 24. } else { 18. })) + .text_color(c(colour.unwrap_or(0xf7f4f4))) + .child(store.name_in(npub, Some(cid))), + ) + .when(owner, |d| { + d.child( + div() + .id("rank") + .ml(px(5.)) + .flex() + .tip(t::community_owner()) + .child(icon("icons/crown.svg", 15., c(OWNER))), + ) + }) + .when(store.profiles.get(npub).is_some_and(|p| p.bot) && !store.stream_hidden(npub), |d| { + d.child( + div() + .id("bot") + .flex() + .tip(t::community_bot()) + .child(svg().path("icons/bot.svg").size(px(14.)).flex_shrink_0().text_color(c(0x5b6060))), + ) + }) + .children(crate::timeline::timeout_mark(store, Some(cid), npub)) + .children(unlisted.map(|why| { + let label = if why == "departed" { t::community_departed() } else { t::community_unannounced() }; + let (tap, why) = (on.clone(), why.to_string()); + div() + .id("unlisted") + .flex() + .p(px(8.)) + .m(px(-8.)) + .cursor_pointer() + .tip(label) + .on_click(move |_, w, cx| { + cx.stop_propagation(); + tap(Act::Unlisted(why.clone()), w, cx) + }) + .child(icon("icons/vector_warning.svg", 14., c(0xfbbf24))) + })), + ) + .children(status.map(|s| { + div() + .truncate() + .text_size(px(if slim { 12. } else { 11.5 })) + .line_height(px(if slim { 16.2 } else { 15.5 })) + .text_color(white_a(0.38)) + .child(if crate::profile::status_has_emoji(store, npub) { + let look = if slim { + crate::inline::Look::new(INTER, 12., 16.2, white_a(0.38)) + } else { + crate::inline::Look::new(INTER, 11.5, 15.5, white_a(0.38)) + }; + crate::profile::status(store, npub, look).held().into_any_element() + } else { + status_line(&s) + }) + })), + ) +} + +/// Members listed above the messages while the pane searches. +const MINI_MEMBERS: usize = 5; + +/// The roster's sections, filtered by the search, by rank, or why there are none. +pub fn roster( + d: E, + store: &Store, + open: &str, + view: &View, + com: &Community, + on: &OnAct, + anchors: &crate::kit::Anchors, + visible: Option<(f32, f32)>, + cx: &App, +) -> E { + let finding = !view.search.read(cx).text().trim().is_empty(); + let query = view.find.parsed.words.trim().to_lowercase(); + let owner = com.owner_npub.as_deref(); + let matches = |n: &&String| { + query.is_empty() + || store + .name_in(n, Some(&com.community_id)) + .to_lowercase() + .contains(&query) + || n.contains(&query) + }; + let is_admin = |n: &str| owner == Some(n) || view.admins.iter().any(|a| a == n); + let graph = store.role_graphs.get(&com.community_id); + // A Private Channel lists only who may read it; unscoped until the graph lands. + let scope = graph + .zip(com.channel(open).filter(|ch| ch.private)) + .map(|(g, ch)| g.readers(&ch.channel_id.to_ascii_lowercase(), owner)); + let everyone = || { + view.members + .iter() + .chain(view.unlisted.keys().filter(|n| !view.members.contains(n))) + .filter(|n| scope.as_ref().is_none_or(|s| s.contains(n.as_str()))) + }; + let named = |n: &str| { + store.profiles.get(n).is_some_and(|p| !p.name.is_empty() || !p.display_name.is_empty()) + || store.nicknames.get(&com.community_id).is_some_and(|k| k.contains_key(n)) + }; + // Owner, then admins, then members; names A to Z and bare keys last, the same in every channel. + let key = |n: &&String| { + let tier = if owner == Some(n.as_str()) { 0 } else if is_admin(n) { 1 } else { 2 }; + let unnamed = !store.stream_hidden(n) && !named(n); + (tier, unnamed, store.name_in(n, Some(&com.community_id)).to_lowercase()) + }; + let mut everyone: Vec<&String> = everyone().filter(matches).collect(); + everyone.sort_by_cached_key(key); + if finding { + let colour = |n: &str| graph.filter(|g| g.activated).and_then(|g| g.highest(n, |r| r.color != 0)).map(|r| r.color); + let people = if query.is_empty() || !view.find.parsed.tokens.is_empty() { Vec::new() } else { everyone }; + let rows = people + .iter() + .take(MINI_MEMBERS) + .map(|n| member_row(store, &com.community_id, n, owner == Some(n.as_str()), colour(n), view.unlisted.get(n.as_str()).map(String::as_str), on, anchors).into_any_element()) + .collect(); + let find: crate::search::OnAct = { + let on = on.clone(); + Rc::new(move |a, w, cx| on(Act::Find(a), w, cx)) + }; + return d.children(crate::search::mini(&view.find, store, open, rows, people.len(), &find)); + } + let mut order: Vec<(String, String)> = Vec::new(); + if let Some(g) = graph { + let mut heads: Vec<&GraphRole> = g.roles.iter().filter(|r| g.heads(r)).collect(); + heads.sort_by_key(|r| r.position); + order.extend(heads.into_iter().map(|r| (format!("sec-role:{}", r.id), r.name.clone()))); + } + if order.is_empty() && !graph.is_some_and(|g| g.activated) { + order.push(("sec-admin".into(), t::community_section_admin().into())); + } + order.push(("sec-members".into(), t::community_section_members().into())); + let mut buckets: Vec> = vec![Vec::new(); order.len()]; + for n in everyone { + // A role the graph no longer defines must not drop its holder off the roster. + let want = match graph.and_then(|g| g.highest(n, |r| g.heads(r))) { + Some(r) => format!("sec-role:{}", r.id), + None if is_admin(n) => "sec-admin".into(), + None => "sec-members".into(), + }; + let ix = order.iter().position(|(k, _)| *k == want).unwrap_or(order.len() - 1); + buckets[ix].push(n); + } + let colour = |n: &str| graph.filter(|g| g.activated).and_then(|g| g.highest(n, |r| r.color != 0)).map(|r| r.color); + // Rows outside the viewport (plus a screen of slack) are spacers: a big roster otherwise + // rebuilds and lays out every member on each frame. + let row_h = if crate::theme::is_slim() { 46. } else { 40. }; + let top = std::cell::Cell::new(0f32); + let section = |key: String, label: String, list: Vec<&String>| { + let closed = view.folded.contains(&key); + let rows_at = top.get() + if top.get() > 0. { 12. } else { 0. } + 36.; + if !list.is_empty() { + top.set(rows_at + if closed { 0. } else { list.len() as f32 * row_h }); + } + let (skip, take) = match visible { + Some((from, height)) => { + let lo = ((from - height - rows_at) / row_h).floor().max(0.) as usize; + let hi = ((from + 2. * height - rows_at) / row_h).ceil().max(0.) as usize; + (lo.min(list.len()), hi.min(list.len()).saturating_sub(lo.min(list.len()))) + } + None => (0, list.len()), + }; + let after = list.len() - skip - take; + (!list.is_empty()).then(|| { + div() + .child( + div() + .id(SharedString::from(key.clone())) + .h(px(36.)) + .rounded(px(6.)) + .flex() + .items_start() + .pt(px(4.)) + .px(px(if crate::theme::is_slim() { 6. } else { 8. })) + .gap(px(6.)) + .cursor_pointer() + .on_click(click(on, { let key = key.clone(); move || Act::Fold(key.clone()) })) + .on_mouse_down(gpui::MouseButton::Right, { + let (on, key) = (on.clone(), key.clone()); + move |e, w, cx| { + cx.stop_propagation(); + on(Act::SectionMenu(key.clone(), e.position), w, cx) + } + }) + .child( + crate::kit::spaced_cut(label.to_uppercase(), 0.99) + .font_weight(FontWeight::BOLD) + .text_size(px(11.)) + .line_height(px(24.)) + .text_color(c(LABEL)), + ) + .child( + div() + .flex_none() + .font_weight(FontWeight::SEMIBOLD) + .text_size(px(11.)) + .line_height(px(24.)) + .text_color(white_a(0.32)) + .child(list.iter().filter(|n| !view.unlisted.contains_key(n.as_str())).count().to_string()), + ) + .child( + div() + .flex_none() + .ml_auto() + .w(px(16.)) + .h(px(24.)) + .flex() + .items_center() + .justify_center() + .child(icon("icons/chevron-down.svg", 10.4, white_a(0.32)).with_transformation(crate::kit::turn( + format!("caret-{key}"), + closed, + -std::f32::consts::FRAC_PI_2, + 0.15, + crate::kit::css_ease(), + ))), + ), + ) + .when(!closed, |d| { + d.when(skip > 0, |d| d.child(div().h(px(skip as f32 * row_h)))) + .children(list.into_iter().skip(skip).take(take).map(|n| { + member_row(store, &com.community_id, n, owner == Some(n.as_str()), colour(n), view.unlisted.get(n.as_str()).map(String::as_str), on, anchors) + })) + .when(after > 0, |d| d.child(div().h(px(after as f32 * row_h)))) + }) + }) + }; + let sections: Vec<_> = order + .into_iter() + .zip(buckets) + .filter_map(|((key, label), list)| section(key, label, list)) + .enumerate() + .map(|(i, s)| s.when(i > 0, |d| d.mt(px(12.)))) + .collect(); + if !sections.is_empty() { + return d.children(sections); + } + let (text, italic) = match (view.loading, query.is_empty()) { + (true, true) => (t::community_members_loading(), false), + (_, true) => (t::community_members_quiet(), true), + _ => (t::community_members_no_matches(), true), + }; + d.child( + div() + .mt(px(16.)) + .p(px(14.)) + .text_center() + .text_size(if italic { px(16.) } else { px(12.5) }) + .line_height(px(if italic { 24. } else { 18. })) + .text_color(c(TEXT)) + .opacity(if italic { 0.5 } else { 0.4 }) + .when(italic, |d| d.italic()) + .child(text), + ) +} + +/// `#group-overview`: the search over the roster. +pub fn members_panel( + store: &Store, + open: &str, + view: &View, + com: &Community, + on: &OnAct, + anchors: &crate::kit::Anchors, + cx: &App, +) -> impl IntoElement { + div() + .id("group-overview") + .w(px(240.)) + .flex_shrink_0() + .h_full() + .flex() + .flex_col() + .bg(c(0x070707)) + .border_l_1() + .border_color(c(DIVIDER)) + .child( + div() + .h(px(61.)) + .flex_shrink_0() + .map(|d| crate::theme::chat_header_ground(d, false)) + .flex() + .items_center() + .px(px(14.)) + .child( + div() + .relative() + .w_full() + .h(px(32.)) + .rounded_full() + .border_1() + .border_color(c(DIVIDER)) + .flex() + .items_center() + .pl(px(37.)) + .pr(px(12.)) + .child( + icon("icons/search.svg", 16., white_a(0.4)) + .absolute() + .left(px(13.)) + .top(px(7.)), + ) + .child(div().flex_1().min_w_0().child(view.search.clone())), + ), + ) + .child( + div() + .id("member-roster") + .flex_1() + .min_h_0() + .overflow_y_scroll() + .track_scroll(&view.scroll) + .px(px(8.)) + .map(|d| { + let height = f32::from(view.scroll.bounds().size.height); + let visible = (height > 0.).then(|| (-f32::from(view.scroll.offset().y), height)); + roster(d, store, open, view, com, on, anchors, visible, cx) + }), + ) +} + +/// An author's name colour in a channel: their topmost coloured role, on the new roles. +pub fn author_colour(store: &Store, chat_id: &str, npub: &str) -> Option { + let g = store.role_graphs.get(&store.community_of(chat_id)?.community_id)?; + g.activated.then(|| g.highest(npub, |r| r.color != 0)).flatten().map(|r| r.color) +} + +/// The Owner chip after an author's name in a channel; on the new roles the name's colour stands instead. +pub fn author_badge(store: &Store, chat_id: &str, npub: &str) -> Option { + let com = store.community_of(chat_id)?; + if store.role_graphs.get(&com.community_id).is_some_and(|g| g.activated) { + return None; + } + let owner = com.owner_npub.as_deref() == Some(npub); + owner.then(|| { + crate::kit::spaced(t::community_owner().to_uppercase(), 0.5) + .flex_shrink_0() + .pt(px(2.75)) + .pb(px(1.25)) + .px(px(5.)) + .rounded(px(3.)) + .bg(c(OWNER)) + .font_family(RUBIK) + .font_weight(FontWeight::SEMIBOLD) + .text_size(px(9.)) + .line_height(px(9.)) + .text_color(c(0x000000)) + .into_any_element() + }) +} + +type Click = Box; + +/// `InviteRow.svelte`: a pending invite, shaped like the Community row it becomes. +pub fn invite_row( + inv: &crate::data::Invite, + open: Click, + accept: Click, + decline: Click, +) -> impl IntoElement { + let button = |id: String, icon_path: &'static str, tip: SharedString, ink: gpui::Hsla, on: Click| { + div() + .id(SharedString::from(id)) + .tip(tip) + .size(px(28.)) + .flex_shrink_0() + .rounded_full() + .border_2() + .border_color(ink) + .flex() + .items_center() + .justify_center() + .cursor_pointer() + .hover(|d| d.bg(white_a(0.04))) + .on_click(move |e, w, cx| { + cx.stop_propagation(); + on(e, w, cx) + }) + .child(svg().path(icon_path).size(px(16.)).text_color(ink)) + }; + div() + .id(SharedString::from(format!( + "community-invite-{}", + inv.community_id + ))) + .mx(px(7.)) + .mb(px(4.)) + .h(px(50.)) + .flex_shrink_0() + .bg(white_a(0.05)) + .flex() + .items_center() + .pl(px(5.)) + .pr(px(15.)) + .cursor_pointer() + .on_click(open) + .child( + crate::pic::img("icons/group-placeholder.svg") + .size(px(40.)) + .rounded(px(7.56)) + .flex_shrink_0(), + ) + .child( + div() + .w(px(99.)) + .flex_shrink_0() + .pl(px(10.)) + .flex() + .flex_col() + .font_family(RUBIK) + .child( + div() + .flex() + .items_center() + .gap(px(6.)) + .child( + div() + .min_w_0() + .truncate() + .text_size(px(15.)) + .line_height(px(20.)) + .text_color(c(0xffffff)) + .child(inv.name.clone()), + ) + .child( + svg() + .path("icons/users-multi.svg") + .size(px(14.)) + .flex_shrink_0() + .text_color(white_a(0.55)), + ), + ) + .child( + div() + .mt(px(-4.)) + .truncate() + .text_size(px(13.)) + .line_height(px(18.)) + .text_color(white_a(0.85)) + .child(t::community_invite_card()), + ), + ) + .child( + div() + .ml_auto() + .flex() + .gap(px(8.)) + .child(button( + format!("invite-accept-{}", inv.community_id), + "icons/check.svg", + t::community_invite_accept(), + c(ACCENT), + accept, + )) + .child(button( + format!("invite-decline-{}", inv.community_id), + "icons/x.svg", + t::community_invite_decline(), + c(crate::timeline::DANGER), + decline, + )), + ) +} + +/// `InviteDetails.svelte`: who sent a pending invite, when, and until when. +pub fn invite_details( + store: &Store, + inv: &crate::data::Invite, + close: Click, + accept: Click, + decline: Click, +) -> impl IntoElement { + let now = (store.now_ms() / 1000) as i64; + let person = |npub: &String| { + div() + .id(SharedString::from(format!("invite-person-{npub}"))) + .tip(npub.clone()) + .flex() + .items_center() + .gap(px(8.)) + .min_w_0() + .child(crate::ui::avatar(store, npub, 22.)) + .child(div().truncate().child(store.name(npub))) + }; + let owner = inv + .owner + .as_deref() + .and_then(|h| nostr_sdk::prelude::PublicKey::from_hex(h).ok()) + .and_then(|k| nostr_sdk::prelude::ToBech32::to_bech32(&k).ok()) + .filter(|o| *o != inv.inviter); + let sent = if inv.sent_at > 0 { + (t::community_invite_sent(), inv.sent_at) + } else { + (t::community_invite_received(), inv.received_at) + }; + let row = |first: bool, label: SharedString, value: AnyElement| { + div() + .h(px(42.)) + .px(px(14.)) + .flex() + .items_center() + .justify_between() + .gap(px(12.)) + .when(!first, |d| { + d.h(px(43.)).border_t_1().border_color(c(0x1e1e1e)) + }) + .text_size(px(14.)) + .line_height(px(24.)) + .text_color(c(0xe8e8e8)) + .child(div().flex_shrink_0().text_color(white_a(0.5)).child(label)) + .child(value) + }; + let button = |id: &'static str, label: SharedString, primary: bool, on: Click| { + div() + .id(id) + .flex_1() + .h(px(42.)) + .rounded(px(8.)) + .border_1() + .flex() + .items_center() + .justify_center() + .font_weight(FontWeight::SEMIBOLD) + .text_size(px(16.)) + .cursor_pointer() + .hover(|d| d.opacity(0.85)) + .map(|d| { + if primary { + d.border_color(gpui::transparent_black()) + .bg(c(ACCENT)) + .text_color(c(0x000000)) + } else { + d.border_color(c(crate::timeline::DANGER)) + .text_color(c(0xffffff)) + } + }) + .on_click(on) + .child(label) + }; + let card = div() + .id("invite-details") + .w_full() + .max_w(px(422.)) + .p(px(21.)) + .rounded(px(16.)) + .border_1() + .border_color(c(0x262626)) + .bg(ca(20, 20, 20, 0.95)) + .shadow(vec![gpui::BoxShadow { + color: ca(0, 0, 0, 0.4), + offset: gpui::point(px(0.), px(8.)), + blur_radius: px(32.), + spread_radius: px(0.), + inset: false, + }]) + .occlude() + .on_click(|_, _, cx| cx.stop_propagation()) + .flex() + .flex_col() + .child( + div() + .flex() + .flex_col() + .items_center() + .child( + img("icons/group-placeholder.svg") + .size(px(72.)) + .rounded_full(), + ) + .child( + div() + .mt(px(12.)) + .max_w_full() + .truncate() + .font_weight(FontWeight::BOLD) + .text_size(px(20.)) + .line_height(px(24.)) + .text_color(c(0xffffff)) + .child(inv.name.clone()), + ) + .child( + div() + .mt(px(4.)) + .text_size(px(13.)) + .line_height(px(24.)) + .text_color(white_a(0.5)) + .child(t::community_invite_card()), + ), + ) + .child( + div() + .mt(px(15.)) + .rounded(px(12.)) + .border_1() + .border_color(c(0x262626)) + .flex() + .flex_col() + .child(row(true, t::community_invite_from(), person(&inv.inviter).into_any_element())) + .children(owner.map(|o| row(false, t::community_invite_owner(), person(&o).into_any_element()))) + .child(row( + false, + sent.0, + div() + .id("invite-sent") + .tip(crate::texttime::full(sent.1, false)) + .child(crate::util::relative_time(sent.1, now)) + .into_any_element(), + )) + .child(row( + false, + t::community_invite_expires(), + div() + .id("invite-ends") + .tip(crate::texttime::full(inv.ends_at, false)) + .child(crate::util::relative_time(inv.ends_at, now)) + .into_any_element(), + )), + ) + .child( + div() + .mt(px(25.)) + .flex() + .gap(px(10.)) + .child(button("invite-decline", t::community_invite_decline_short(), false, decline)) + .child(button("invite-accept", t::community_invite_accept_short(), true, accept)), + ); + gpui::deferred( + div() + .id("invite-details-overlay") + .absolute() + .inset_0() + .px(px(19.)) + .bg(ca(0, 0, 0, 0.85)) + .flex() + .items_center() + .justify_center() + .occlude() + .on_click(close) + .child(crate::kit::pop("pop-dialog", card, 160)), + ) + .with_priority(13) +} + +#[cfg(test)] +mod tests { + use super::Graph; + + fn graph(activated: bool) -> Graph { + Graph::parse(&serde_json::json!({ + "activated": activated, + "roles": [ + {"role_id": "core", "name": "Core", "position": 1, "color": 0x59fcb3, "channel_id": null, "display": true}, + {"role_id": "art", "name": "Art", "position": 3, "color": 0xffb35c, "channel_id": "ABCD", "display": false}, + {"role_id": "mod", "name": "Mods", "position": 2, "color": 0, "channel_id": null, "display": true}, + ], + "grants": [ + {"npub": "a", "role_ids": ["art", "core"]}, + {"npub": "b", "role_ids": ["mod", "art"]}, + {"npub": "c", "role_ids": ["art"]}, + ], + "readers": {"ABCD": ["b"]}, + })) + } + + #[test] + fn highest_role_picks_the_lowest_position() { + let g = graph(true); + assert_eq!(g.highest("a", |r| g.heads(r)).map(|r| r.id.as_str()), Some("core")); + assert_eq!(g.highest("b", |r| g.heads(r)).map(|r| r.id.as_str()), Some("mod")); + assert!(g.highest("c", |r| g.heads(r)).is_none()); + // A colourless role passes its colour down to the next one. + assert_eq!(g.highest("b", |r| r.color != 0).map(|r| r.color), Some(0xffb35c)); + } + + #[test] + fn private_readers_follow_the_roles_in_use() { + let owner = Some("o"); + let new = graph(true).readers("abcd", owner); + assert_eq!(new, ["o", "b"].iter().map(|s| s.to_string()).collect()); + let old = graph(false).readers("abcd", owner); + assert_eq!(old, ["o", "a", "b", "c"].iter().map(|s| s.to_string()).collect()); + // The old roles head a section with every role, shown separately or not. + let g = graph(false); + assert_eq!(g.highest("c", |r| g.heads(r)).map(|r| r.id.as_str()), Some("art")); + } +} diff --git a/crates/vector-gpui/src/composer.rs b/crates/vector-gpui/src/composer.rs new file mode 100644 index 000000000..8a470a9f3 --- /dev/null +++ b/crates/vector-gpui/src/composer.rs @@ -0,0 +1,3110 @@ +//! The message composer's text field: GPUI's own input (zed `crates/gpui/examples/input.rs`, +//! Apache-2.0), grown to wrap and take newlines, restyled as `#chat-input.rich-composer` and +//! wired to send on Enter. + +use std::ops::Range; + +use gpui::{ + App, Bounds, ClipboardItem, Context, CursorStyle, ElementId, ElementInputHandler, Entity, + EntityInputHandler, EventEmitter, FocusHandle, Focusable, GlobalElementId, KeyBinding, + LayoutId, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, PaintQuad, Pixels, Point, + ScrollHandle, SharedString, Style, TextRun, UTF16Selection, UnderlineStyle, Window, + WrappedLine, actions, div, fill, point, prelude::*, px, relative, size, +}; +use unicode_segmentation::*; + +use gpui::Hsla; + +use crate::theme::*; + +/// What a keystroke edit was, for joining it to the undo step before. +#[derive(Clone, Copy, PartialEq)] +enum Keyed { + Type, + Delete, +} + +/// The undo step a run of keystrokes is filling. +#[derive(Clone, Copy)] +struct Run { + kind: Keyed, + from: usize, + end: usize, + at: std::time::Instant, + spaced: bool, +} + +actions!( + text_input, + [ + Backspace, + Delete, + Left, + Right, + SelectLeft, + SelectRight, + SelectAll, + Home, + End, + ShowCharacterPalette, + Paste, + Cut, + Copy, + Send, + Cancel, + Newline, + Up, + Down, + SelectUp, + SelectDown, + Tab, + TabBack, + Undo, + Redo, + WordLeft, + WordRight, + SelectWordLeft, + SelectWordRight, + DeleteWordLeft, + DeleteWordRight, + SelectHome, + SelectEnd, + Bold, + Italic, + Code, + Strike, + SendNow, + ] +); + +pub struct TextInput { + focus_handle: FocusHandle, + content: SharedString, + placeholder: SharedString, + selected_range: Range, + selection_reversed: bool, + marked_range: Option>, + last_layout: Option, + last_bounds: Option>, + /// Wraps and takes newlines, scrolling past this height. + multiline: Option, + center: bool, + right: bool, + scroll: ScrollHandle, + /// How far a one-line field's text is scrolled left to keep the caret in view. + hscroll: std::cell::Cell, + /// The caret moved: scroll it into view on the next paint. + reveal: bool, + is_selecting: bool, + /// The right-click edit menu, open at this window point. + menu: Option>, + look: Look, + /// Enter keeps the text (a login field's caller reads and clears it). + clear_on_submit: bool, + submit_empty: bool, + /// Draws stock emoji as Twemoji art, as the rich composer does. + twemoji: bool, + /// Typing and pasting stop at this many characters. + max_chars: Option, + /// The emoji drawn as art, for the content they were found in. + subs: std::cell::RefCell<(SharedString, std::rc::Rc<[Sub]>)>, + /// An autocomplete is open: its keys go to it as `Nav`. + nav: bool, + /// A tap outside leaves it focused: its frame decides instead. + held: bool, + edges: bool, + colors: Option, + chip: bool, + /// Markdown and tags styled in place, with the names a tag may carry. + decorated: Option>, + /// The name a pasted `@npub1…` shows as. + npub_label: Option String>>, + /// Pack emoji by shortcode, drawn as their art. + customs: std::rc::Rc>, + /// The decorated spans drawn on a chip, in display offsets: (range, fill, radius, side pad). + chips: std::cell::RefCell, Hsla, f32, f32)>>, + /// Earlier states for Undo, and what Undo took back for Redo. + undo: Vec<(SharedString, Range)>, + redo: Vec<(SharedString, Range)>, + /// The last edit was typing a word character, and when. + typed: Option, + /// The open undo step that the next keystroke may join. + run: Option, + /// The edit under way is a Backspace or Delete keystroke. + deleting: bool, + /// The edit under way is the app's own (a paste, an emoji, a mention): a step of its own. + alone: bool, + /// Checked for spelling, as the webview's `spellcheck` does. + spell: Option, +} + +/// The misspelled words, for the content they were found in. +#[derive(Default)] +struct Spelling { + text: SharedString, + words: Vec>, + /// When the text next gets checked, and whether a wait for it is running. + due: Option, + waiting: bool, + /// The word being typed at this caret was left unmarked, until the caret leaves it. + held: Option, + /// The misspelled word the edit menu opened on, and its guesses. + menu: Option<(Range, Vec)>, + /// Corrects a misspelled word as a space or punctuation ends it (the Autocorrect setting). + autocorrect: bool, + /// The text a correction left, and the word it replaced: undoing it keeps that word. + corrected: Option<(SharedString, String)>, + /// Words whose correction was undone, left alone from then on, as macOS does. + kept: std::collections::HashSet, +} + +/// Whether `c` belongs to a word autocorrect looks at. +fn wordy(c: char) -> bool { + c.is_alphanumeric() || c == '\'' || c == '\u{2019}' +} + +/// The word `ended` closes in `text`, when a correction may touch it: plain prose, not a link, +/// tag, mention, shortcode or number. +fn word_before(text: &str, ended: usize) -> Option> { + let head = &text[..ended]; + let start = head.char_indices().rev().take_while(|&(_, c)| wordy(c)).last().map(|(i, _)| i)?; + let word = &text[start..ended]; + let token_start = head.rfind(char::is_whitespace).map_or(0, |i| i + 1); + let lead = &text[token_start..start]; + let plain = word.chars().any(char::is_alphabetic) && !word.chars().any(|c| c.is_ascii_digit()); + let opener = lead.chars().all(|c| matches!(c, '(' | '[' | '"' | '\'' | '\u{201C}' | '\u{2018}' | '*' | '_' | '~')); + (plain && opener).then_some(start..ended) +} + +/// The best guesses only, so the menu stays short. +const SPELL_GUESSES: usize = 6; + +/// How long typing pauses before the text is checked. +const SPELL_WAIT: std::time::Duration = std::time::Duration::from_millis(300); + +/// The words still standing after `old` became `new`: those clear of the edit, shifted past it. +/// A word the edit touches goes, and comes back when the text is checked. +fn carry_words(old: &str, new: &str, words: &[Range]) -> Vec> { + let mut pre = old.bytes().zip(new.bytes()).take_while(|(a, b)| a == b).count(); + while !old.is_char_boundary(pre) || !new.is_char_boundary(pre) { + pre -= 1; + } + let room = old.len().min(new.len()) - pre; + let mut suf = old.bytes().rev().zip(new.bytes().rev()).take(room).take_while(|(a, b)| a == b).count(); + while !old.is_char_boundary(old.len() - suf) || !new.is_char_boundary(new.len() - suf) { + suf -= 1; + } + let (old_end, new_end) = (old.len() - suf, new.len() - suf); + let wordy = |c: Option| c.is_some_and(|c| c.is_alphanumeric() || c == '\''); + let joins_before = wordy(new[pre..].chars().next()); + let joins_after = wordy(new[..new_end].chars().next_back()); + words + .iter() + .filter_map(|r| { + if r.end < pre || (r.end == pre && !joins_before) { + Some(r.clone()) + } else if r.start > old_end || (r.start == old_end && !joins_after) { + Some(r.start - old_end + new_end..r.end - old_end + new_end) + } else { + None + } + }) + .collect() +} + +/// Dots along `x0..x1`, as WebKit draws a misspelling: whole dots only, centred, the gap at +/// its 9.457/13.247 of a dot. +fn spell_dots(x0: Pixels, x1: Pixels) -> impl Iterator { + const DOT: f32 = 3.; + let gap = DOT * 9.457 / 13.247; + let w = f32::from(x1 - x0); + let n = ((w + gap) / (DOT + gap)).floor().max(0.) as usize; + let lead = (w - (n as f32 * DOT + n.saturating_sub(1) as f32 * gap)) / 2.; + (0..n).map(move |i| x0 + px(lead + i as f32 * (DOT + gap))) +} + +/// A key an open autocomplete takes from the field. +#[derive(Clone, Copy, PartialEq, Eq)] +pub enum Nav { + Up, + Down, + Pick, + Close, +} + +/// Content drawn as something else: an emoji as art (`src`) over a placeholder, or a pasted +/// `@npub1…` as the person's name, which the caret steps over whole. +struct Sub { + content: Range, + display: Range, + src: Option, + label: Option, +} + +/// Each `@npub1…` mention outside code, as `cmpTokenize` finds them. +fn npub_mentions(text: &str) -> Vec> { + const BECH: &[u8] = b"023456789acdefghjklmnpqrstuvwxyz"; + let code: Vec> = crate::decorate::tokenize(text, &[]) + .into_iter() + .filter(|(_, d)| matches!(d, crate::decorate::Deco::Code | crate::decorate::Deco::CodeMark)) + .map(|(r, _)| r) + .collect(); + let b = text.as_bytes(); + let mut out = Vec::new(); + let mut i = 0; + while let Some(at) = text[i..].find("@npub1").map(|o| i + o) { + let end = at + 6 + 58; + let ok = b.len() >= end && b[at + 6..end].iter().all(|c| BECH.contains(c)); + if ok && !code.iter().any(|r| r.start <= at && at < r.end) { + out.push(at..end); + i = end; + } else { + i = at + 1; + } + } + out +} + +/// What an emoji's art occupies in the drawn text: 1.25em (`.cmp-twemoji`), an em space and a quarter-em. +const EMOJI_SLOT: &str = "\u{2003}\u{2005}"; + +/// Rubik has no em or quarter-em space, so a fallback font would pick the slot's width and lift the +/// line; `assets/fonts/VectorSlot.ttf` has only those two, at exactly 1em and 0.25em, on Rubik's metrics. +const SLOT_FAMILY: &str = "Vector Slot"; // i18n-exempt: font name + +/// Shapes each emoji slot in [`SLOT_FAMILY`]. +fn slot_runs(runs: Vec, slots: &[Range]) -> Vec { + if slots.is_empty() { + return runs; + } + let mut out = Vec::with_capacity(runs.len() + slots.len() * 2); + let mut at = 0; + for run in runs { + let end = at + run.len; + let mut from = at; + for s in slots.iter().filter(|s| s.start < end && s.end > at) { + let (a, b) = (s.start.max(at), s.end.min(end)); + if a > from { + out.push(TextRun { len: a - from, ..run.clone() }); + } + let mut slot = TextRun { len: b - a, ..run.clone() }; + slot.font.family = SLOT_FAMILY.into(); + slot.font.weight = gpui::FontWeight::NORMAL; + slot.font.style = gpui::FontStyle::Normal; + out.push(slot); + from = b; + } + if end > from { + out.push(TextRun { len: end - from, ..run }); + } + at = end; + } + out +} + +/// How a field draws: the composer's, or a login field's. +#[derive(Clone)] +pub struct Look { + pub family: &'static str, + pub weight: gpui::FontWeight, + pub size: Pixels, + pub line_height: Pixels, + pub color: Hsla, + pub placeholder: Hsla, + /// Shows a bullet per character, as a password field does. + pub masked: bool, + /// The size bullets take once something is typed. + pub masked_size: Option, +} + +impl Default for Look { + fn default() -> Self { + Self { + family: RUBIK, + weight: gpui::FontWeight::NORMAL, + size: px(15.), + line_height: px(21.), + color: white_a(0.85), + placeholder: white_a(0.38), + masked: false, + masked_size: None, + } + } +} + +const BULLET: &str = "\u{2022}"; + +/// The drawn text as shaped: each hard line with its byte start and top. +struct Layout { + text: SharedString, + lines: Vec<(usize, Pixels, Para)>, + line_height: Pixels, + /// The field's width, which a right-to-left paragraph's rows are set against. + width: Pixels, + /// Centred within this width, each visual row on its own. + align: Option, + right: bool, +} + +/// A hard line as shaped. +enum Para { + /// GPUI's own wrapping, which keeps glyphs in byte order: text with no right-to-left run. + Plain(WrappedLine), + Bidi(BidiPara), +} + +/// A line broken into rows in reading order, each shaped behind a mark that fixes the +/// paragraph's direction, so every row is reordered on its own as a browser does. +struct BidiPara { + rows: Vec, + rtl: bool, + len: usize, +} + +struct Row { + /// Bytes of the hard line. + range: Range, + line: gpui::ShapedLine, + /// Glyph clusters left to right. + cells: Vec, +} + +/// A glyph cluster: the row bytes it draws, where, and which way its text runs. +#[derive(Clone)] +struct Cell { + range: Range, + x: Pixels, + w: Pixels, + rtl: bool, +} + +const LRM: &str = "\u{200e}"; +const RLM: &str = "\u{200f}"; + +/// `dir="auto"` while the UI reads right to left; left to right otherwise, as Tauri's textarea. +fn para_rtl(line: &str) -> bool { + gpui::layout_rtl() + && line + .chars() + .find_map(|ch| match unicode_bidi::bidi_class(ch) { + unicode_bidi::BidiClass::L => Some(false), + unicode_bidi::BidiClass::R | unicode_bidi::BidiClass::AL => Some(true), + _ => None, + }) + .unwrap_or(true) +} + +fn needs_bidi(line: &str) -> bool { + crate::inline::has_rtl(line) || para_rtl(line) +} + +/// `runs` cut to `range`, the first widened over a `lead`-byte mark. +fn clip_runs(runs: &[TextRun], range: Range, lead: usize) -> Vec { + let mut out = Vec::new(); + let mut at = 0; + for run in runs { + let (s, e) = (at.max(range.start), (at + run.len).min(range.end)); + at += run.len; + if s < e { + out.push(TextRun { len: e - s, ..run.clone() }); + } + } + match out.first_mut() { + Some(first) => first.len += lead, + None => { + if let Some(run) = runs.last() { + out.push(TextRun { len: lead, ..run.clone() }); + } + } + } + out +} + +/// The clusters of a line shaped behind a `lead`-byte mark, left to right, in its own bytes. +fn cells(line: &gpui::ShapedLine, lead: usize) -> Vec { + let text = line.text.as_str(); + let levels = unicode_bidi::BidiInfo::new(text, None).levels; + let glyphs: Vec<(usize, Pixels)> = line + .runs + .iter() + .flat_map(|r| r.glyphs.iter().map(|g| (g.index, g.position.x))) + .collect(); + let mut starts: Vec = glyphs.iter().map(|g| g.0).filter(|&i| i >= lead).collect(); + starts.sort_unstable(); + starts.dedup(); + // A shaper may fold the mark into the first letter's cluster. + let mark_alone = starts.first() == Some(&lead); + // Glyphs come in either visual order, so each cluster starts at its leftmost glyph. + let mut left: std::collections::BTreeMap = std::collections::BTreeMap::new(); + for &(raw, x) in &glyphs { + let index = if raw < lead && !mark_alone { lead } else { raw }; + if index >= lead && index < text.len() { + left.entry(index).and_modify(|l| *l = (*l).min(x)).or_insert(x); + } + } + let mut out: Vec = left + .into_iter() + .map(|(index, x)| { + let end = starts.get(starts.partition_point(|&s| s <= index)).copied().unwrap_or(text.len()); + Cell { + range: index - lead..end - lead, + x, + w: px(0.), + rtl: levels.get(index).is_some_and(|l| l.is_rtl()), + } + }) + .collect(); + out.sort_by(|a, b| f32::from(a.x).total_cmp(&f32::from(b.x))); + for k in 0..out.len() { + let next = out.get(k + 1).map_or(line.width, |n| n.x); + out[k].w = (next - out[k].x).max(px(0.)); + } + out +} + +impl Row { + fn width(&self) -> Pixels { + self.line.width + } + + /// Where the caret before row byte `k` sits: the leading edge of what follows it, else the + /// trailing edge of what precedes it. + fn caret_x(&self, k: usize) -> Pixels { + if let Some(c) = self.cells.iter().find(|c| c.range.start == k) { + return if c.rtl { c.x + c.w } else { c.x }; + } + if let Some(c) = self.cells.iter().find(|c| c.range.contains(&k)) { + let f = (k - c.range.start) as f32 / c.range.len() as f32; + return if c.rtl { c.x + c.w * (1. - f) } else { c.x + c.w * f }; + } + if let Some(c) = self.cells.iter().find(|c| c.range.end == k) { + return if c.rtl { c.x } else { c.x + c.w }; + } + px(0.) + } + + /// The row byte nearest `x`: the cluster under it, before or after by which half. + fn index_at(&self, x: Pixels) -> usize { + let Some(c) = self.cells.iter().find(|c| x < c.x + c.w).or(self.cells.last()) else { + return 0; + }; + if c.rtl == (x < c.x + c.w / 2.) { c.range.end } else { c.range.start } + } + + /// The stretches `range` (row bytes) covers, left to right. + fn spans(&self, range: Range) -> Vec<(Pixels, Pixels)> { + let mut hit: Vec<(Pixels, Pixels)> = self + .cells + .iter() + .filter(|c| c.range.start < range.end && range.start < c.range.end) + .map(|c| (c.x, c.x + c.w)) + .collect(); + hit.sort_by(|a, b| f32::from(a.0).total_cmp(&f32::from(b.0))); + let mut out: Vec<(Pixels, Pixels)> = Vec::with_capacity(hit.len()); + for (a, b) in hit { + match out.last_mut() { + Some(last) if a <= last.1 + px(0.5) => last.1 = last.1.max(b), + _ => out.push((a, b)), + } + } + out + } +} + +impl BidiPara { + fn shape(text: &str, runs: &[TextRun], font_size: Pixels, wrap: Option, window: &Window) -> Self { + let rtl = para_rtl(text); + let mark = if rtl { RLM } else { LRM }; + let shape = |range: Range| { + let line = window.text_system().shape_line( + format!("{mark}{}", &text[range.clone()]).into(), + font_size, + &clip_runs(runs, range.clone(), mark.len()), + None, + ); + let cells = cells(&line, mark.len()); + Row { range, line, cells } + }; + let whole = shape(0..text.len()); + let Some(wrap) = wrap.filter(|w| whole.width() > *w) else { + return Self { rows: vec![whole], rtl, len: text.len() }; + }; + // Break in reading order: after the last space that fits, else before the cluster + // that overflows. + let mut order = whole.cells.clone(); + order.sort_by_key(|c| c.range.start); + let mut breaks = Vec::new(); + let (mut row_start, mut w, mut last_space) = (0, px(0.), None::<(usize, Pixels)>); + for c in &order { + let space = text[c.range.clone()].chars().all(char::is_whitespace); + if !space && w + c.w > wrap && c.range.start > row_start { + match last_space.take().filter(|(b, _)| *b > row_start) { + Some((b, wb)) => { + breaks.push(b); + row_start = b; + w -= wb; + } + None => { + breaks.push(c.range.start); + row_start = c.range.start; + w = px(0.); + } + } + } + w += c.w; + if space { + last_space = Some((c.range.end, w)); + } + } + let mut rows = Vec::with_capacity(breaks.len() + 1); + let mut at = 0; + for b in breaks.into_iter().chain([text.len()]) { + rows.push(shape(at..b)); + at = b; + } + Self { rows, rtl, len: text.len() } + } + + /// The row a caret before line byte `k` sits on: a break starts the next row. + fn row_of(&self, k: usize) -> usize { + self.rows + .iter() + .position(|r| k < r.range.end) + .unwrap_or(self.rows.len().saturating_sub(1)) + } +} + +impl Para { + fn len(&self) -> usize { + match self { + Para::Plain(l) => l.len(), + Para::Bidi(b) => b.len, + } + } + + fn height(&self, line_height: Pixels) -> Pixels { + match self { + Para::Plain(l) => l.size(line_height).height, + Para::Bidi(b) => line_height * b.rows.len().max(1) as f32, + } + } + + fn width(&self) -> Pixels { + match self { + Para::Plain(l) => l.width(), + Para::Bidi(b) => b.rows.iter().map(Row::width).fold(px(0.), Pixels::max), + } + } +} + +impl Layout { + fn shape( + text: SharedString, + runs: &[TextRun], + font_size: Pixels, + wrap: Option, + width: Pixels, + line_height: Pixels, + window: &Window, + ) -> Self { + let shaped = window + .text_system() + .shape_text(text.clone(), font_size, runs, wrap, None) + .unwrap_or_default(); + let mut lines = Vec::with_capacity(shaped.len()); + let (mut start, mut y) = (0, px(0.)); + for line in shaped { + let len = line.len(); + let hard = &text[start..start + len]; + let para = if needs_bidi(hard) { + let runs = clip_runs(runs, start..start + len, 0); + Para::Bidi(BidiPara::shape(hard, &runs, font_size, wrap, window)) + } else { + Para::Plain(line) + }; + let h = para.height(line_height); + lines.push((start, y, para)); + start += len + 1; + y += h; + } + Self { + text, + lines, + line_height, + width, + align: None, + right: false, + } + } + + fn has_bidi(&self) -> bool { + self.lines.iter().any(|(_, _, p)| matches!(p, Para::Bidi(_))) + } + + /// Whether the hard line holding `index` reads right to left. + fn rtl_at(&self, index: usize) -> bool { + matches!(self.line_at(index), Some((_, _, Para::Bidi(b))) if b.rtl) + } + + /// How far a centred row sits right of the left edge. + fn shift(&self, line: &WrappedLine, row: usize) -> Pixels { + let Some(aw) = self.align else { return px(0.) }; + let x = |b: &gpui::WrapBoundary| { + line.unwrapped_layout.runs[b.run_ix].glyphs[b.glyph_ix] + .position + .x + }; + let start = if row == 0 { + px(0.) + } else { + line.wrap_boundaries.get(row - 1).map(x).unwrap_or(px(0.)) + }; + let end = line + .wrap_boundaries + .get(row) + .map(x) + .unwrap_or(line.unwrapped_layout.width); + let room = (aw - (end - start)).max(px(0.)); + if self.right { room } else { room / 2. } + } + + /// How far a reordered row sits right of the left edge. + fn row_x(&self, para: &BidiPara, row: &Row) -> Pixels { + let room = (self.align.unwrap_or(self.width) - row.width()).max(px(0.)); + match self.align { + Some(_) if self.right => room, + Some(_) => room / 2., + None if para.rtl => room, + None => px(0.), + } + } + + fn height(&self) -> Pixels { + self.lines + .last() + .map(|(_, y, l)| *y + l.height(self.line_height)) + .unwrap_or(self.line_height) + .max(self.line_height) + } + + fn first_width(&self) -> Pixels { + self.lines.first().map(|(_, _, l)| l.width()).unwrap_or_default() + } + + fn line_at(&self, index: usize) -> Option<&(usize, Pixels, Para)> { + self.lines + .iter() + .rev() + .find(|(start, _, _)| *start <= index) + } + + /// The char boundary after `index`. + fn after(&self, index: usize) -> usize { + index + self.text.get(index..).and_then(|t| t.chars().next()).map_or(0, char::len_utf8) + } + + /// Where `index` sits, from the text's top left. + fn position(&self, index: usize) -> Point { + let Some((start, y, para)) = self.line_at(index) else { + return point(px(0.), px(0.)); + }; + let local = index.saturating_sub(*start).min(para.len()); + match para { + Para::Plain(line) => { + let p = line + .position_for_index(local, self.line_height) + .unwrap_or(point(line.width(), px(0.))); + let row = (p.y / self.line_height).floor() as usize; + point(p.x + self.shift(line, row), p.y + *y) + } + Para::Bidi(b) => { + let r = b.row_of(local); + let Some(row) = b.rows.get(r) else { + return point(self.row_x(b, &b.rows[0]), *y); + }; + let x = self.row_x(b, row) + row.caret_x(local - row.range.start); + point(x, *y + self.line_height * r as f32) + } + } + } + + fn index_at(&self, p: Point) -> usize { + let Some((start, y, para)) = self + .lines + .iter() + .rev() + .find(|(_, y, _)| *y <= p.y) + .or(self.lines.first()) + else { + return 0; + }; + let h = para.height(self.line_height); + let ly = (p.y - *y).clamp(px(0.), (h - px(1.)).max(px(0.))); + match para { + Para::Plain(line) => { + let shift = self.shift(line, (ly / self.line_height).floor() as usize); + let local = point((p.x - shift).max(px(0.)), ly); + let i = match line.closest_index_for_position(local, self.line_height) { + Ok(i) | Err(i) => i, + }; + start + i.min(line.len()) + } + Para::Bidi(b) => { + let r = ((ly / self.line_height).floor() as usize).min(b.rows.len().saturating_sub(1)); + let Some(row) = b.rows.get(r) else { return *start }; + start + row.range.start + row.index_at(p.x - self.row_x(b, row)) + } + } + } + + /// The stretches `range` covers, `(left, right, top)` row by row. A range running on past + /// a row's end fills it to `full`, as a selection across lines does. + fn spans(&self, range: Range, full: Pixels) -> Vec<(Pixels, Pixels, Pixels)> { + let mut out = Vec::new(); + if range.is_empty() { + return out; + } + for (start, y, para) in &self.lines { + let end = start + para.len(); + if range.end <= *start || range.start > end { + continue; + } + let (a, b) = (range.start.max(*start), range.end.min(end)); + match para { + Para::Plain(_) => { + let (pa, pb) = (self.position(a), self.position(b)); + let on = range.end > end; + let row = |p: Point| ((p.y - *y) / self.line_height).round() as usize; + for r in row(pa)..=row(pb) { + let top = *y + self.line_height * r as f32; + let x0 = if r == row(pa) { pa.x } else { px(0.) }; + let x1 = if r == row(pb) && !on { pb.x } else { full }; + if x1 > x0 { + out.push((x0, x1, top)); + } + } + } + Para::Bidi(bp) => { + for (r, row) in bp.rows.iter().enumerate() { + let (ra, rb) = (row.range.start + start, row.range.end + start); + if b <= ra || a >= rb { + continue; + } + let x = self.row_x(bp, row); + let top = *y + self.line_height * r as f32; + for (x0, x1) in row.spans(a.max(ra) - ra..b.min(rb) - ra) { + out.push((x + x0, x + x1, top)); + } + } + } + } + } + out + } +} + +impl TextInput { + /// Whether the caret's line reads right to left, where ← and → swap meaning. + fn rtl_caret(&self) -> bool { + self.last_layout.as_ref().is_some_and(|l| l.rtl_at(self.to_display(self.cursor_offset()))) + } + + fn left(&mut self, _: &Left, window: &mut Window, cx: &mut Context) { + if self.rtl_caret() { self.forth(window, cx) } else { self.back(window, cx) } + } + + fn right(&mut self, _: &Right, window: &mut Window, cx: &mut Context) { + if self.rtl_caret() { self.back(window, cx) } else { self.forth(window, cx) } + } + + fn back(&mut self, window: &mut Window, cx: &mut Context) { + if self.edges && self.selected_range == (0..0) { + return cx.emit(Edge::Start); + } + if self.selected_range.is_empty() { + self.move_to(self.previous_boundary(self.cursor_offset()), window, cx); + } else { + self.move_to(self.selected_range.start, window, cx) + } + } + + fn forth(&mut self, window: &mut Window, cx: &mut Context) { + let end = self.content.len(); + if self.edges && self.selected_range == (end..end) { + return cx.emit(Edge::End); + } + if self.selected_range.is_empty() { + self.move_to(self.next_boundary(self.selected_range.end), window, cx); + } else { + self.move_to(self.selected_range.end, window, cx) + } + } + + fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context) { + let at = self.cursor_offset(); + let to = if self.rtl_caret() { self.next_boundary(at) } else { self.previous_boundary(at) }; + self.select_to(to, window, cx); + } + + fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context) { + let at = self.cursor_offset(); + let to = if self.rtl_caret() { self.previous_boundary(at) } else { self.next_boundary(at) }; + self.select_to(to, window, cx); + } + + fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context) { + self.move_to(0, window, cx); + self.select_to(self.content.len(), window, cx) + } + + fn home(&mut self, _: &Home, window: &mut Window, cx: &mut Context) { + self.move_to(0, window, cx); + } + + fn end(&mut self, _: &End, window: &mut Window, cx: &mut Context) { + self.move_to(self.content.len(), window, cx); + } + + fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context) { + if self.edges && self.content.is_empty() { + return cx.emit(Edge::Empty); + } + if self.selected_range.is_empty() { + self.deleting = true; + let prev = self.previous_boundary(self.cursor_offset()); + if self.cursor_offset() == prev { + window.play_system_bell(); + return; + } + self.select_to(prev, window, cx) + } + self.replace_text_in_range(None, "", window, cx) + } + + fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context) { + if self.edges && self.content.is_empty() { + return cx.emit(Edge::Empty); + } + if self.selected_range.is_empty() { + self.deleting = true; + let next = self.next_boundary(self.cursor_offset()); + if self.cursor_offset() == next { + window.play_system_bell(); + return; + } + self.select_to(next, window, cx) + } + self.replace_text_in_range(None, "", window, cx) + } + + fn on_mouse_down( + &mut self, + event: &MouseDownEvent, + window: &mut Window, + cx: &mut Context, + ) { + self.is_selecting = true; + self.menu = None; + window.request_virtual_keyboard(); + let at = self.index_for_mouse_position(event.position); + if event.modifiers.shift { + self.select_to(at, window, cx); + return; + } + let span = match event.click_count { + 0 | 1 => return self.move_to(at, window, cx), + 2 if !self.look.masked => self.word_around(at), + 2 => 0..self.content.len(), + _ => self.line_around(at), + }; + // A word or line stays picked: a drag after the press doesn't fold it back to a caret. + self.is_selecting = false; + self.selected_range = span; + self.selection_reversed = false; + window.notify_text_selection_changed(&self.focus_handle); + cx.notify(); + } + + /// The run under `offset`: word characters, punctuation or spaces, as a double-click picks. + fn word_around(&self, offset: usize) -> Range { + let class = crate::select::word_class; + let here = self.content[offset..] + .chars() + .next() + .filter(|&c| c != '\n') + .or_else(|| self.content[..offset].chars().next_back()) + .map(class); + let Some(want) = here else { return offset..offset }; + let start = self.content[..offset] + .char_indices() + .rev() + .take_while(|&(_, c)| c != '\n' && class(c) == want) + .last() + .map_or(offset, |(i, _)| i); + let end = self.content[offset..] + .char_indices() + .find(|&(_, c)| c == '\n' || class(c) != want) + .map_or(self.content.len(), |(i, _)| offset + i); + self.out_of_sub(start, false)..self.out_of_sub(end, true) + } + + /// The line holding `offset`, without its break. + fn line_around(&self, offset: usize) -> Range { + let start = self.content[..offset].rfind('\n').map_or(0, |i| i + 1); + let end = self.content[offset..].find('\n').map_or(self.content.len(), |i| offset + i); + start..end + } + + /// Right-click: the edit menu at the press, with the caret moved there unless it lands in + /// the selection. + fn on_right_down(&mut self, event: &MouseDownEvent, window: &mut Window, cx: &mut Context) { + window.focus(&self.focus_handle, cx); + let at = self.index_for_mouse_position(event.position); + let word = self + .spell + .as_ref() + .filter(|s| s.text == self.content) + .and_then(|s| s.words.iter().find(|r| r.start <= at && at <= r.end).cloned()); + if let Some(word) = word { + // A misspelled word is picked whole, as WebKit does, so a guess replaces it. + let guesses = crate::spell::backend().guesses(&self.content, word.clone()).into_iter().take(SPELL_GUESSES).collect(); + self.selected_range = word.clone(); + self.selection_reversed = false; + window.notify_text_selection_changed(&self.focus_handle); + if let Some(sp) = self.spell.as_mut() { + sp.menu = Some((word, guesses)); + } + } else { + if let Some(sp) = self.spell.as_mut() { + sp.menu = None; + } + if !(self.selected_range.start <= at && at <= self.selected_range.end) { + self.move_to(at, window, cx); + } + } + self.menu = Some(event.position); + cx.stop_propagation(); + cx.notify(); + } + + fn edit_menu(&self) -> Vec { + use crate::kit::MenuItem; + let picked = !self.selected_range.is_empty() && !self.look.masked; + let mut items = Vec::new(); + if let Some((_, guesses)) = self.spell.as_ref().and_then(|s| s.menu.as_ref()) { + if guesses.is_empty() { + items.push(MenuItem::new(crate::t::composer_spell_no_guesses(), "").disabled(true)); + } + items.extend(guesses.iter().map(|g| MenuItem::new(g.clone(), ""))); + items.push(MenuItem::divider()); + items.push(MenuItem::new(crate::t::composer_spell_ignore(), "")); + items.push(MenuItem::new(crate::t::composer_spell_learn(), "")); + items.push(MenuItem::divider()); + } + items.extend([ + MenuItem::new(crate::t::composer_cut(), "").disabled(!picked), + MenuItem::new(crate::t::composer_copy(), "").disabled(!picked), + MenuItem::new(crate::t::composer_paste(), ""), + MenuItem::divider(), + MenuItem::new(crate::t::composer_select_all(), "").disabled(self.content.is_empty()), + ]); + items + } + + fn on_edit_menu(&mut self, ix: usize, window: &mut Window, cx: &mut Context) { + self.menu = None; + let spell = self.spell.as_mut().and_then(|s| s.menu.take()); + let ix = match spell { + Some((word, guesses)) => { + // Guesses (or the one "No Guesses Found"), a divider, Ignore, Learn, a divider. + let shown = guesses.len().max(1); + let still = self.content.get(word.clone()).is_some(); + match ix.checked_sub(shown) { + None if still && ix < guesses.len() => { + self.marked_range = None; + self.selected_range = word; + self.write(&guesses[ix], window, cx); + return; + } + Some(1) | Some(2) if still => { + let w = self.content[word].to_string(); + if ix - shown == 1 { + crate::spell::backend().ignore(&w); + } else { + crate::spell::backend().learn(&w); + } + let caret = self.selected_range.end; + self.selected_range = caret..caret; + self.spell_check(); + cx.notify(); + return; + } + Some(n) if n >= 4 => n - 4, + _ => return cx.notify(), + } + } + None => ix, + }; + match ix { + 0 => self.cut(&Cut, window, cx), + 1 => self.copy(&Copy, window, cx), + 2 => self.paste(&Paste, window, cx), + 4 => self.select_all(&SelectAll, window, cx), + _ => {} + } + cx.notify(); + } + + fn on_mouse_up(&mut self, _: &MouseUpEvent, _window: &mut Window, _: &mut Context) { + self.is_selecting = false; + } + + fn on_mouse_move( + &mut self, + event: &MouseMoveEvent, + window: &mut Window, + cx: &mut Context, + ) { + if self.is_selecting { + self.select_to(self.index_for_mouse_position(event.position), window, cx); + } + } + + fn show_character_palette( + &mut self, + _: &ShowCharacterPalette, + window: &mut Window, + _: &mut Context, + ) { + window.show_character_palette(); + } + + fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context) { + let files = crate::fileclip::read(cx); + if !files.is_empty() { + cx.emit(Pasted::Paths(files)); + return; + } + let item = cx.read_from_clipboard(); + if item.as_ref().and_then(|i| i.text()).is_none() { + for entry in item.iter().flat_map(|i| i.entries()) { + match entry { + gpui::ClipboardEntry::Image(img) => { + cx.emit(Pasted::Image { + bytes: img.bytes.clone(), + ext: img.format.extension(), + }); + return; + } + gpui::ClipboardEntry::ExternalPaths(paths) => { + if !paths.paths().is_empty() { + cx.emit(Pasted::Paths(paths.paths().to_vec())); + return; + } + } + _ => {} + } + } + } + if let Some(text) = item.and_then(|item| item.text()) { + let text = if self.multiline.is_some() { + let text = text.replace("\r\n", "\n"); + // Styled copies keep their styling as markdown, so what shows here is what sends. + crate::paste_md::clipboard_html() + .and_then(|html| crate::paste_md::html_to_markdown(&html, &text)) + .unwrap_or(text) + } else { + text.replace('\n', " ") + }; + self.write(&text, window, cx); + } + } + + fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context) { + if self.selected_range.is_empty() { + // Nothing picked here: a selection in the messages may want it. + return cx.propagate(); + } + cx.write_to_clipboard(ClipboardItem::new_string( + self.content[self.selected_range.clone()].to_string(), + )); + } + fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context) { + if !self.selected_range.is_empty() { + cx.write_to_clipboard(ClipboardItem::new_string( + self.content[self.selected_range.clone()].to_string(), + )); + self.replace_text_in_range(None, "", window, cx) + } + } + + fn move_to(&mut self, offset: usize, window: &Window, cx: &mut Context) { + self.selected_range = offset..offset; + self.selection_reversed = false; + self.reveal = true; + window.notify_text_selection_changed(&self.focus_handle); + cx.notify() + } + + fn cursor_offset(&self) -> usize { + if self.selection_reversed { + self.selected_range.start + } else { + self.selected_range.end + } + } + + fn index_for_mouse_position(&self, position: Point) -> usize { + if self.content.is_empty() { + return 0; + } + + let (Some(bounds), Some(layout)) = (self.last_bounds.as_ref(), self.last_layout.as_ref()) + else { + return 0; + }; + if position.y < bounds.top() { + return 0; + } + if position.y > bounds.bottom() { + return self.content.len(); + } + self.from_display(layout.index_at(position - bounds.origin)) + } + + fn select_to(&mut self, offset: usize, window: &Window, cx: &mut Context) { + self.reveal = true; + if self.selection_reversed { + self.selected_range.start = offset + } else { + self.selected_range.end = offset + }; + if self.selected_range.end < self.selected_range.start { + self.selection_reversed = !self.selection_reversed; + self.selected_range = self.selected_range.end..self.selected_range.start; + } + window.notify_text_selection_changed(&self.focus_handle); + cx.notify() + } + + fn offset_from_utf16(&self, offset: usize) -> usize { + let mut utf8_offset = 0; + let mut utf16_count = 0; + + for ch in self.content.chars() { + if utf16_count >= offset { + break; + } + utf16_count += ch.len_utf16(); + utf8_offset += ch.len_utf8(); + } + + utf8_offset + } + + fn offset_to_utf16(&self, offset: usize) -> usize { + let mut utf16_offset = 0; + let mut utf8_count = 0; + + for ch in self.content.chars() { + if utf8_count >= offset { + break; + } + utf8_count += ch.len_utf8(); + utf16_offset += ch.len_utf16(); + } + + utf16_offset + } + + fn range_to_utf16(&self, range: &Range) -> Range { + self.offset_to_utf16(range.start)..self.offset_to_utf16(range.end) + } + + fn range_from_utf16(&self, range_utf16: &Range) -> Range { + self.offset_from_utf16(range_utf16.start)..self.offset_from_utf16(range_utf16.end) + } + + fn previous_boundary(&self, offset: usize) -> usize { + let at = self + .content + .grapheme_indices(true) + .rev() + .find_map(|(idx, _)| (idx < offset).then_some(idx)) + .unwrap_or(0); + self.out_of_sub(at, false) + } + + fn next_boundary(&self, offset: usize) -> usize { + let at = self + .content + .grapheme_indices(true) + .find_map(|(idx, _)| (idx > offset).then_some(idx)) + .unwrap_or(self.content.len()); + self.out_of_sub(at, true) + } + + /// Keep the state before an edit for Undo. Typing joins while it runs on from the same spot, + /// until a space after a word; deleting joins while it eats on from where it was. + fn remember(&mut self, keyed: Option<(Keyed, Range, &str)>) { + let now = std::time::Instant::now(); + let joins = match (&keyed, self.run) { + (Some((kind, range, text)), Some(run)) if run.kind == *kind && now.duration_since(run.at).as_millis() < 1000 => match kind { + Keyed::Type => range.is_empty() && range.start == run.end && !(text.starts_with(char::is_whitespace) && !run.spaced), + Keyed::Delete => range.end == run.from || range.start == run.from, + }, + _ => false, + }; + if !joins { + self.undo.push((self.content.clone(), self.selected_range.clone())); + if self.undo.len() > 200 { + self.undo.remove(0); + } + } + self.run = keyed.as_ref().map(|(kind, range, text)| Run { + kind: *kind, + from: range.start, + end: range.start + text.len(), + at: now, + spaced: text.ends_with(char::is_whitespace), + }); + self.typed = matches!(&keyed, Some((Keyed::Type, _, text)) if !text.chars().any(char::is_whitespace)).then_some(now); + self.redo.clear(); + } + + /// Text the app puts in, an undo step of its own. + fn write(&mut self, text: &str, window: &mut Window, cx: &mut Context) { + self.alone = true; + self.replace_text_in_range(None, text, window, cx); + } + + fn forget(&mut self) { + self.undo.clear(); + self.redo.clear(); + self.typed = None; + self.run = None; + } + + fn restore(&mut self, (content, sel): (SharedString, Range), window: &Window, cx: &mut Context) { + self.content = content; + self.selected_range = sel.start.min(self.content.len())..sel.end.min(self.content.len()); + self.selection_reversed = false; + self.marked_range = None; + self.typed = None; + self.run = None; + self.reveal = true; + window.notify_text_input_changed(&self.focus_handle); + cx.emit(InputChanged); + cx.notify(); + } + + fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context) { + if let Some(sp) = self.spell.as_mut() + && let Some((after, word)) = sp.corrected.take() + && after == self.content + { + sp.kept.insert(word); + } + if let Some(prev) = self.undo.pop() { + self.redo.push((self.content.clone(), self.selected_range.clone())); + self.restore(prev, window, cx); + } + } + + fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context) { + if let Some(next) = self.redo.pop() { + self.undo.push((self.content.clone(), self.selected_range.clone())); + self.restore(next, window, cx); + } + } + + /// Where the word before `offset` starts: past spaces, then a run of word characters or + /// of punctuation. + fn word_start(&self, offset: usize) -> usize { + let s = &self.content[..offset]; + let mut it = s.char_indices().rev().skip_while(|(_, c)| c.is_whitespace()).peekable(); + let Some(&(mut at, first)) = it.peek() else { return 0 }; + let word = crate::select::word_class(first); + for (i, c) in it { + if c.is_whitespace() || crate::select::word_class(c) != word { + break; + } + at = i; + } + self.out_of_sub(at, false) + } + + fn word_end(&self, offset: usize) -> usize { + let s = &self.content[offset..]; + let mut it = s.char_indices().skip_while(|(_, c)| c.is_whitespace()).peekable(); + let Some(&(_, first)) = it.peek() else { return self.content.len() }; + let word = crate::select::word_class(first); + let mut end = self.content.len(); + for (i, c) in it { + if c.is_whitespace() || crate::select::word_class(c) != word { + end = offset + i; + break; + } + } + self.out_of_sub(end, true) + } + + /// The next word edge leftward on screen: back in the text, forward on a right-to-left line. + fn word_leftward(&self) -> usize { + let at = self.cursor_offset(); + if self.rtl_caret() { self.word_end(at) } else { self.word_start(at) } + } + + fn word_rightward(&self) -> usize { + let at = self.cursor_offset(); + if self.rtl_caret() { self.word_start(at) } else { self.word_end(at) } + } + + fn word_left(&mut self, _: &WordLeft, window: &mut Window, cx: &mut Context) { + self.move_to(self.word_leftward(), window, cx); + } + + fn word_right(&mut self, _: &WordRight, window: &mut Window, cx: &mut Context) { + self.move_to(self.word_rightward(), window, cx); + } + + fn select_word_left(&mut self, _: &SelectWordLeft, window: &mut Window, cx: &mut Context) { + self.select_to(self.word_leftward(), window, cx); + } + + fn select_word_right(&mut self, _: &SelectWordRight, window: &mut Window, cx: &mut Context) { + self.select_to(self.word_rightward(), window, cx); + } + + fn delete_word_left(&mut self, _: &DeleteWordLeft, window: &mut Window, cx: &mut Context) { + if self.selected_range.is_empty() { + self.deleting = true; + self.select_to(self.word_start(self.cursor_offset()), window, cx); + } + self.replace_text_in_range(None, "", window, cx) + } + + fn delete_word_right(&mut self, _: &DeleteWordRight, window: &mut Window, cx: &mut Context) { + if self.selected_range.is_empty() { + self.deleting = true; + self.select_to(self.word_end(self.cursor_offset()), window, cx); + } + self.replace_text_in_range(None, "", window, cx) + } + + fn select_home(&mut self, _: &SelectHome, window: &mut Window, cx: &mut Context) { + self.select_to(0, window, cx); + } + + fn select_end(&mut self, _: &SelectEnd, window: &mut Window, cx: &mut Context) { + self.select_to(self.content.len(), window, cx); + } + + /// A formatting shortcut: markdown written into the composer's text, as on desktop. + fn mark(&mut self, mark: &str, window: &mut Window, cx: &mut Context) { + if self.decorated.is_none() || self.marked_range.is_some() { + return cx.propagate(); + } + let (text, sel) = crate::marks::toggle(&self.content, self.selected_range.clone(), mark); + self.remember(None); + self.restore((text.into(), sel), window, cx); + } + + fn reset(&mut self, window: &Window, cx: &mut Context) { + self.forget(); + self.content = "".into(); + self.selected_range = 0..0; + self.selection_reversed = false; + self.marked_range = None; + self.last_layout = None; + self.last_bounds = None; + self.is_selecting = false; + window.notify_text_input_changed(&self.focus_handle); + cx.emit(InputChanged); + cx.notify(); + } +} + +impl EntityInputHandler for TextInput { + fn text_for_range( + &mut self, + range_utf16: Range, + actual_range: &mut Option>, + _window: &mut Window, + _cx: &mut Context, + ) -> Option { + let range = self.range_from_utf16(&range_utf16); + actual_range.replace(self.range_to_utf16(&range)); + Some(self.content[range].to_string()) + } + + fn selected_text_range( + &mut self, + _ignore_disabled_input: bool, + _window: &mut Window, + _cx: &mut Context, + ) -> Option { + Some(UTF16Selection { + range: self.range_to_utf16(&self.selected_range), + reversed: self.selection_reversed, + }) + } + + fn set_selected_text_range( + &mut self, + range_utf16: Range, + window: &mut Window, + cx: &mut Context, + ) { + self.selected_range = self.range_from_utf16(&range_utf16); + self.selection_reversed = false; + window.notify_text_selection_changed(&self.focus_handle); + cx.notify(); + } + + fn text_length_utf16( + &mut self, + _window: &mut Window, + _cx: &mut Context, + ) -> Option { + Some(self.content.encode_utf16().count()) + } + + fn marked_text_range( + &self, + _window: &mut Window, + _cx: &mut Context, + ) -> Option> { + self.marked_range + .as_ref() + .map(|range| self.range_to_utf16(range)) + } + + fn unmark_text(&mut self, window: &mut Window, cx: &mut Context) { + self.marked_range = None; + window.notify_text_input_changed(&self.focus_handle); + cx.notify(); + } + + fn replace_text_in_range( + &mut self, + range_utf16: Option>, + new_text: &str, + window: &mut Window, + cx: &mut Context, + ) { + let range = range_utf16 + .as_ref() + .map(|range_utf16| self.range_from_utf16(range_utf16)) + .or(self.marked_range.clone()) + .unwrap_or(self.selected_range.clone()); + let new_text = match self.max_chars { + Some(max) => { + let kept = self.content[..range.start].chars().count() + + self.content[range.end..].chars().count(); + let room = max.saturating_sub(kept); + new_text + .char_indices() + .nth(room) + .map_or(new_text, |(at, _)| &new_text[..at]) + } + None => new_text, + }; + let (deleting, alone) = (std::mem::take(&mut self.deleting), std::mem::take(&mut self.alone)); + let keyed = if alone || self.marked_range.is_some() { + None + } else if new_text.is_empty() { + deleting.then_some(Keyed::Delete) + } else { + (new_text.graphemes(true).count() == 1).then_some(Keyed::Type) + }; + self.remember(keyed.map(|k| (k, range.clone(), new_text))); + + self.content = + (self.content[0..range.start].to_owned() + new_text + &self.content[range.end..]) + .into(); + self.selected_range = range.start + new_text.len()..range.start + new_text.len(); + self.selection_reversed = false; + let composing = self.marked_range.take().is_some(); + self.reveal = true; + if range.is_empty() && !composing { + self.autocorrect(range.start, new_text); + } + window.notify_text_input_changed(&self.focus_handle); + cx.emit(InputChanged); + cx.notify(); + } + + fn replace_and_mark_text_in_range( + &mut self, + range_utf16: Option>, + new_text: &str, + new_selected_range_utf16: Option>, + window: &mut Window, + cx: &mut Context, + ) { + let range = range_utf16 + .as_ref() + .map(|range_utf16| self.range_from_utf16(range_utf16)) + .or(self.marked_range.clone()) + .unwrap_or(self.selected_range.clone()); + + self.content = + (self.content[0..range.start].to_owned() + new_text + &self.content[range.end..]) + .into(); + if !new_text.is_empty() { + self.marked_range = Some(range.start..range.start + new_text.len()); + } else { + self.marked_range = None; + } + let insertion_start_utf16 = self.offset_to_utf16(range.start); + let inserted_length_utf16 = new_text.encode_utf16().count(); + self.selected_range = new_selected_range_utf16 + .map(|selected| { + self.range_from_utf16( + &(insertion_start_utf16 + selected.start.min(inserted_length_utf16) + ..insertion_start_utf16 + selected.end.min(inserted_length_utf16)), + ) + }) + .unwrap_or_else(|| range.start + new_text.len()..range.start + new_text.len()); + self.selection_reversed = false; + + window.notify_text_input_changed(&self.focus_handle); + cx.notify(); + } + + fn bounds_for_range( + &mut self, + range_utf16: Range, + bounds: Bounds, + _window: &mut Window, + _cx: &mut Context, + ) -> Option> { + let layout = self.last_layout.as_ref()?; + if self.look.masked || layout.text != self.content { + return None; + } + let range = self.range_from_utf16(&range_utf16); + if layout.has_bidi() { + let spans = layout.spans(range.clone(), px(0.)); + let (x0, x1, y) = match (spans.first(), spans.iter().rfind(|s| s.2 == spans[0].2)) { + (Some(f), Some(l)) => (f.0, l.1, f.2), + _ => { + let p = layout.position(range.start); + (p.x, p.x, p.y) + } + }; + return Some(Bounds::from_corners(bounds.origin + point(x0, y), bounds.origin + point(x1, y + layout.line_height))); + } + let (a, b) = (layout.position(range.start), layout.position(range.end)); + let b = if b.y == a.y { b } else { point(a.x, a.y) }; + Some(Bounds::from_corners( + bounds.origin + a, + bounds.origin + point(b.x, a.y + layout.line_height), + )) + } + + fn selection_bounds_for_range( + &mut self, + range_utf16: Range, + bounds: Bounds, + window: &mut Window, + cx: &mut Context, + ) -> Vec> { + self.bounds_for_range(range_utf16, bounds, window, cx) + .into_iter() + .collect() + } + + fn character_index_for_point( + &mut self, + point: gpui::Point, + _window: &mut Window, + _cx: &mut Context, + ) -> Option { + let local = self.last_bounds?.localize(&point)?; + let layout = self.last_layout.as_ref()?; + if layout.text != self.content { + return None; + } + Some(self.offset_to_utf16(layout.index_at(local))) + } +} + +struct TextElement { + input: Entity, +} + +struct PrepaintState { + /// The text's box, shifted left by a one-line field's scroll. + text: Bounds, + layout: Option, + emoji: Vec, + cursor: Option, + selections: Vec, + /// Each misspelled word's run on a row: its left and right, and the row's top. + spelling: Vec<(Pixels, Pixels, Pixels)>, +} + +impl TextInput { + /// What is drawn (placeholder, bullets or the text) and its runs, in the element's style. + fn display(&self, window: &Window) -> (SharedString, Vec, Pixels) { + let mut style = window.text_style(); + let content = self.content.clone(); + let (text, color) = if content.is_empty() { + (self.placeholder.clone(), self.look.placeholder) + } else if self.look.masked { + if let Some(size) = self.look.masked_size { + style.font_size = size.into(); + } + ( + BULLET.repeat(content.graphemes(true).count()).into(), + style.color, + ) + } else { + let subs = self.subs(); + if subs.is_empty() { + (content, style.color) + } else { + let mut text = String::with_capacity(content.len()); + let mut at = 0; + for sub in subs.iter() { + text.push_str(&content[at..sub.content.start]); + text.push_str(sub.label.as_deref().unwrap_or(EMOJI_SLOT)); + at = sub.content.end; + } + text.push_str(&content[at..]); + (text.into(), style.color) + } + }; + let run = TextRun { + len: text.len(), + font: style.font(), + color, + background_color: None, + underline: None, + strikethrough: None, + }; + let marked = self + .marked_range + .as_ref() + .filter(|_| !self.look.masked && !self.content.is_empty()) + .map(|m| self.to_display(m.start)..self.to_display(m.end)); + let runs = match marked.as_ref() { + Some(m) => [ + TextRun { + len: m.start, + ..run.clone() + }, + TextRun { + len: m.end - m.start, + underline: Some(UnderlineStyle { + color: Some(run.color), + thickness: px(1.0), + wavy: false, + }), + ..run.clone() + }, + TextRun { + len: text.len() - m.end, + ..run + }, + ] + .into_iter() + .filter(|r| r.len > 0) + .collect(), + None => vec![run], + }; + self.chips.borrow_mut().clear(); + let runs = match self.decorated.as_ref().filter(|_| !self.content.is_empty() && !self.look.masked) { + Some(names) => self.decorate(runs, names), + None => runs, + }; + let slots: Vec> = self.subs().iter().filter(|s| s.label.is_none()).map(|s| s.display.clone()).collect(); + let runs = slot_runs(runs, &slots); + (text, runs, style.font_size.to_pixels(window.rem_size())) + } + + /// Splits `runs` at each decorated span and styles what falls inside. + fn decorate(&self, runs: Vec, names: &[String]) -> Vec { + use crate::decorate::Deco; + let subs = self.subs(); + let labels: Vec<&Sub> = subs.iter().filter(|s| s.label.is_some()).collect(); + let tokens: Vec<(std::ops::Range, Deco)> = crate::decorate::tokenize(&self.content, names) + .into_iter() + .filter(|(r, _)| !labels.iter().any(|s| r.start < s.content.end && s.content.start < r.end)) + .collect(); + let (marks, paint) = match self.colors { + Some(owned) => { + let skip: Vec> = tokens + .iter() + .filter(|(_, d)| matches!(d, Deco::Code | Deco::CodeMark | Deco::Mention | Deco::Spoiler)) + .map(|(r, _)| r.clone()) + .chain(subs.iter().map(|s| s.content.clone())) + .collect(); + crate::textcolor::composer_paint(&self.content, owned, &skip) + } + None => Default::default(), + }; + let disp = |r: &std::ops::Range| self.to_display(r.start)..self.to_display(r.end); + let paint: Vec<(std::ops::Range, Hsla)> = paint.iter().map(|(r, c)| (disp(r), *c)).collect(); + let mut spans: Vec<(std::ops::Range, Deco)> = tokens + .iter() + .map(|(r, d)| (disp(r), *d)) + .chain(labels.iter().map(|s| (s.display.clone(), Deco::Mention))) + .chain(marks.iter().map(|r| (disp(r), Deco::Mark))) + .collect(); + if spans.is_empty() { + return runs; + } + spans.sort_by_key(|(r, _)| r.start); + *self.chips.borrow_mut() = spans + .iter() + .filter_map(|(r, d)| match d { + Deco::Mention => Some((r.clone(), Hsla::from(gpui::Rgba { r: 89. / 255., g: 252. / 255., b: 179. / 255., a: 0.13 }), 4., 2.)), + Deco::Code => Some((r.clone(), gpui::hsla(0., 0., 1., 0.08), 3., 2.)), + Deco::Spoiler => Some((r.clone(), gpui::hsla(0., 0., 1., 0.16), 3., 0.)), + _ => None, + }) + .collect(); + let mut out = Vec::with_capacity(runs.len() + spans.len() * 2); + let mut at = 0; + for run in runs { + let end = at + run.len; + let mut from = at; + for (r, d) in spans.iter().filter(|(r, _)| r.start < end && r.end > at) { + let (s, e) = (r.start.max(at), r.end.min(end)); + if s > from { + out.push(TextRun { len: s - from, ..run.clone() }); + } + let mut styled = TextRun { len: e - s, ..run.clone() }; + let base = run.color; + match d { + Deco::Mark => styled.color = base.opacity(0.4), + Deco::CodeMark => { + styled.color = base.opacity(0.4); + styled.font.family = crate::markdown::MONO.into(); + } + Deco::Bold | Deco::Header => styled.font.weight = gpui::FontWeight::BOLD, + Deco::Italic => { + styled.font.style = gpui::FontStyle::Italic; + styled.color = base.opacity(0.7); + } + Deco::BoldItalic => { + styled.font.weight = gpui::FontWeight::BOLD; + styled.font.style = gpui::FontStyle::Italic; + } + Deco::Strike => { + styled.strikethrough = Some(gpui::StrikethroughStyle { + thickness: px(1.), + color: Some(base), + }) + } + Deco::Spoiler => {} + Deco::Code => styled.font.family = crate::markdown::MONO.into(), + Deco::Mention => { + styled.color = gpui::rgb(crate::theme::PRIMARY).into(); + styled.font.weight = gpui::FontWeight::MEDIUM; + } + Deco::Subtext => styled.color = base.opacity(0.75), + } + out.push(styled); + from = e; + } + if end > from { + out.push(TextRun { len: end - from, ..run }); + } + at = end; + } + if paint.is_empty() { + return out; + } + let mut painted = Vec::with_capacity(out.len() + paint.len() * 2); + let mut at = 0; + for run in out { + let end = at + run.len; + let mut from = at; + for (r, color) in paint.iter().filter(|(r, _)| r.start < end && r.end > at) { + let (s, e) = (r.start.max(at), r.end.min(end)); + if s > from { + painted.push(TextRun { len: s - from, ..run.clone() }); + } + painted.push(TextRun { len: e - s, color: Hsla { a: run.color.a, ..*color }, ..run.clone() }); + from = e; + } + if end > from { + painted.push(TextRun { len: end - from, ..run }); + } + at = end; + } + painted + } +} + +impl Element for TextElement { + type RequestLayoutState = (); + type PrepaintState = PrepaintState; + + fn id(&self) -> Option { + None + } + + fn source_location(&self) -> Option<&'static core::panic::Location<'static>> { + None + } + + fn request_layout( + &mut self, + _id: Option<&GlobalElementId>, + _inspector_id: Option<&gpui::InspectorElementId>, + window: &mut Window, + cx: &mut App, + ) -> (LayoutId, Self::RequestLayoutState) { + let input = self.input.read(cx); + let line_height = window.line_height(); + let mut style = Style::default(); + style.size.width = relative(1.).into(); + if input.multiline.is_none() { + style.size.height = line_height.into(); + return (window.request_layout(style, [], cx), ()); + } + // Unstretched: a stretched child is clamped to the field's max height and never overflows it to scroll. + style.align_self = Some(gpui::AlignSelf::FlexStart); + let (text, runs, font_size) = input.display(window); + let id = window.request_measured_layout(style, move |known, available, window, _| { + let width = known.width.or(match available.width { + gpui::AvailableSpace::Definite(w) => Some(w), + _ => None, + }); + let layout = Layout::shape(text.clone(), &runs, font_size, width, width.unwrap_or_default(), line_height, window); + size(width.unwrap_or(px(0.)), layout.height()) + }); + (id, ()) + } + + fn prepaint( + &mut self, + _id: Option<&GlobalElementId>, + _inspector_id: Option<&gpui::InspectorElementId>, + bounds: Bounds, + _request_layout: &mut Self::RequestLayoutState, + window: &mut Window, + cx: &mut App, + ) -> Self::PrepaintState { + tab_order::place(&self.input, bounds, window); + let input = self.input.read(cx); + if !input.look.masked { + let r = input.selected_range.clone(); + let (anchor, focus) = if input.selection_reversed { (r.end, r.start) } else { (r.start, r.end) }; + window.report_a11y_editable_text(&input.content, anchor, focus, bounds); + } + let (text, runs, font_size) = input.display(window); + let line_height = window.line_height(); + let wrap = input.multiline.map(|_| bounds.size.width); + let mut layout = Layout::shape(text, &runs, font_size, wrap, bounds.size.width, line_height, window); + layout.align = (input.center || input.right).then_some(bounds.size.width); + layout.right = input.right; + let (start, end) = if input.content.is_empty() { + (0, 0) + } else { + ( + input.to_display(input.selected_range.start), + input.to_display(input.selected_range.end), + ) + }; + let caret = if input.content.is_empty() { + 0 + } else { + input.to_display(input.cursor_offset()) + }; + let field = bounds; + let bounds = if input.multiline.is_none() && layout.align.is_none() { + let w = bounds.size.width - px(2.); + let text_w = layout.first_width(); + let x = layout.position(caret).x; + let mut sx = input.hscroll.get(); + if x - sx > w { + sx = x - w; + } else if x < sx { + sx = x; + } + sx = sx.min((text_w - w).max(px(0.))).max(px(0.)); + input.hscroll.set(sx); + Bounds::new(field.origin - point(sx, px(0.)), size(field.size.width + sx, field.size.height)) + } else { + field + }; + let o = bounds.origin; + let (cursor, selections) = if start == end { + let p = layout.position(caret); + ( + Some(fill( + Bounds::new(o + p, size(px(2.), line_height)), + c(ACCENT), + )), + Vec::new(), + ) + } else if layout.has_bidi() { + let tint = ca(89, 252, 179, 0.25); + let rects = layout.spans(start..end, bounds.size.width).into_iter().map(|(x0, x1, y)| { + fill(Bounds::from_corners(o + point(x0, y), o + point(x1, y + line_height)), tint) + }); + (None, rects.collect()) + } else { + let (a, b) = (layout.position(start), layout.position(end)); + let tint = ca(89, 252, 179, 0.25); + let mut rects = Vec::new(); + if a.y == b.y { + rects.push(Bounds::from_corners( + o + a, + o + point(b.x, b.y + line_height), + )); + } else { + rects.push(Bounds::from_corners( + o + a, + o + point(bounds.size.width, a.y + line_height), + )); + if b.y > a.y + line_height { + rects.push(Bounds::from_corners( + o + point(px(0.), a.y + line_height), + o + point(bounds.size.width, b.y), + )); + } + rects.push(Bounds::from_corners( + o + point(px(0.), b.y), + o + point(b.x, b.y + line_height), + )); + } + (None, rects.into_iter().map(|r| fill(r, tint)).collect()) + }; + let spelling = match input.spell.as_ref().filter(|s| s.text == input.content && !input.look.masked) { + Some(sp) => sp + .words + .iter() + .flat_map(|r| { + let (start, end) = (input.to_display(r.start), input.to_display(r.end)); + if layout.has_bidi() { + return layout.spans(start..end, px(0.)).into_iter().map(|(x0, x1, y)| (o.x + x0, o.x + x1, o.y + y)).collect(); + } + let (a, b) = (layout.position(start), layout.position(end)); + if a.y == b.y { + vec![(o.x + a.x, o.x + b.x, o.y + a.y)] + } else { + vec![(o.x + a.x, o.x + bounds.size.width, o.y + a.y), (o.x, o.x + b.x, o.y + b.y)] + } + }) + .collect(), + None => Vec::new(), + }; + let side = font_size * 1.25; + let emoji = input + .subs() + .iter() + .filter_map(|sub| Some((sub, sub.src.clone()?))) + .map(|(sub, src)| { + let p = match layout.has_bidi() { + true => layout.spans(sub.display.clone(), px(0.)).first().map_or_else(|| layout.position(sub.display.start), |s| point(s.0, s.2)), + false => layout.position(sub.display.start), + }; + let mut art = crate::pic::img(src).size(side).into_any_element(); + let at = o + point(p.x, p.y + (line_height - side) / 2.); + art.prepaint_as_root( + at, + size(side, side).map(gpui::AvailableSpace::Definite), + window, + cx, + ); + art + }) + .collect(); + PrepaintState { + text: bounds, + layout: Some(layout), + emoji, + cursor, + selections, + spelling, + } + } + + fn paint( + &mut self, + _id: Option<&GlobalElementId>, + _inspector_id: Option<&gpui::InspectorElementId>, + bounds: Bounds, + _request_layout: &mut Self::RequestLayoutState, + prepaint: &mut Self::PrepaintState, + window: &mut Window, + cx: &mut App, + ) { + let focus_handle = self.input.read(cx).focus_handle.clone(); + window.handle_input( + &focus_handle, + ElementInputHandler::new(bounds, self.input.clone()), + cx, + ); + let field = bounds; + let bounds = prepaint.text; + let mask = gpui::ContentMask::new(Bounds::new(field.origin - point(px(0.), px(40.)), size(field.size.width, field.size.height + px(80.)))); + let (layout, caret) = window.with_content_mask(Some(mask), |window| { + for quad in prepaint.selections.drain(..) { + window.paint_quad(quad); + } + let layout = prepaint.layout.take().unwrap(); + // A chip spans the text's 18px content box, not the 21px line. + let inset = ((layout.line_height - px(18.)) / 2.).max(px(0.)); + for (range, fill, radius, pad) in self.input.read(cx).chips.borrow().iter() { + if layout.has_bidi() { + for (x0, x1, y) in layout.spans(range.clone(), px(0.)) { + let quad = Bounds::new( + bounds.origin + point(x0 - px(*pad), y + inset), + gpui::size(x1 - x0 + px(2. * pad), layout.line_height - inset * 2.), + ); + window.paint_quad(gpui::fill(quad, *fill).corner_radii(gpui::Corners::all(px(*radius)))); + } + continue; + } + let (mut a, b) = (layout.position(range.start), layout.position(range.end)); + // A chip opening right at a soft wrap reads as the end of the row above. + let second = layout.after(range.start); + if second <= range.end { + let p = layout.position(second); + if p.y > a.y { + a = point(px(0.), p.y); + } + } + let rows = if a.y == b.y { + vec![(a.x, b.x, a.y)] + } else { + vec![(a.x, bounds.size.width, a.y), (px(0.), b.x, b.y)] + }; + for (x0, x1, y) in rows.into_iter().filter(|(x0, x1, _)| x1 > x0) { + let quad = Bounds::new( + bounds.origin + point(x0 - px(*pad), y + inset), + gpui::size(x1 - x0 + px(2. * pad), layout.line_height - inset * 2.), + ); + window.paint_quad(gpui::fill(quad, *fill).corner_radii(gpui::Corners::all(px(*radius)))); + } + } + for (_, y, para) in &layout.lines { + let line = match para { + Para::Plain(line) => line, + Para::Bidi(b) => { + for (r, row) in b.rows.iter().enumerate() { + let at = point(layout.row_x(b, row), *y + layout.line_height * r as f32); + row.line.paint(bounds.origin + at, layout.line_height, gpui::TextAlign::Left, None, window, cx).ok(); + } + continue; + } + }; + let align = if layout.right { + gpui::TextAlign::Right + } else if layout.align.is_some() { + gpui::TextAlign::Center + } else { + gpui::TextAlign::Left + }; + line.paint( + bounds.origin + point(px(0.), *y), + layout.line_height, + align, + layout.align.map(|_| bounds), + window, + cx, + ) + .ok(); + } + for art in &mut prepaint.emoji { + art.paint(window, cx); + } + let dot = px(3.); + for (x0, x1, y) in prepaint.spelling.drain(..) { + let top = y + layout.line_height - px(4.5); + for x in spell_dots(x0, x1) { + window.paint_quad( + gpui::fill(Bounds::new(point(x, top), size(dot, dot)), ca(255, 69, 58, 1.)) + .corner_radii(gpui::Corners::all(dot / 2.)), + ); + } + } + let caret = prepaint.cursor.take(); + let focused = focus_handle.is_focused(window); + if focused && let Some(cursor) = caret.clone() { + window.paint_quad(cursor); + } + (layout, caret) + }); + let scrolled = self.input.update(cx, |input, _| { + input.last_layout = Some(layout); + input.last_bounds = Some(bounds); + // Keep the caret in view of a scrolled field. + if input.reveal && input.multiline.is_some() { + input.reveal = false; + if let Some(cursor) = caret { + let view = input.scroll.bounds(); + let mut offset = input.scroll.offset(); + let (top, bottom) = (cursor.bounds.top(), cursor.bounds.bottom()); + if top < view.top() { + offset.y += view.top() - top; + } else if bottom > view.bottom() { + offset.y -= bottom - view.bottom(); + } else { + return false; + } + input.scroll.set_offset(offset); + return true; + } + } + false + }); + // A notify mid-draw is dropped, so the new offset would wait for an unrelated repaint. + if scrolled { + window.request_animation_frame(); + } + } +} + +impl Render for TextInput { + fn render(&mut self, window: &mut Window, cx: &mut Context) -> impl IntoElement { + self.spell_follow(cx); + let menu = self.menu.map(|at| { + let (pick, close) = (cx.entity().downgrade(), cx.entity().downgrade()); + // Laid over the whole window, so a press anywhere outside the rows closes it. + gpui::anchored().position(point(px(0.), px(0.))).child( + div().relative().w(window.viewport_size().width).h(window.viewport_size().height).child(crate::kit::context_menu( + at, + &self.edit_menu(), + move |ix, window, cx| { + pick.update(cx, |this, cx| this.on_edit_menu(ix, window, cx)).ok(); + }, + |_, _, _, _| {}, + Default::default(), + None, + move |_, cx| { + close + .update(cx, |this, cx| { + this.menu = None; + if let Some(s) = this.spell.as_mut() { + s.menu = None; + } + cx.notify(); + }) + .ok(); + }, + )), + ) + }); + let role = if self.look.masked { + gpui::accesskit::Role::PasswordInput + } else if self.multiline.is_some() { + gpui::accesskit::Role::MultilineTextInput + } else { + gpui::accesskit::Role::TextInput + }; + div() + .id("text-input") + .role(role) + .aria_placeholder(self.placeholder.clone()) + .when(cfg!(target_os = "android") && !self.held, |d| { + // A tap elsewhere drops the keyboard, as a page blurs its field. + d.on_mouse_down_out(cx.listener(|this, _, window, cx| { + if this.focus_handle.is_focused(window) { + window.blur(cx); + } + })) + }) + .when(!self.look.masked, |d| d.aria_value(self.content.clone())) + .flex() + .key_context("TextInput") + .track_focus(&self.focus_handle(cx)) + .cursor(CursorStyle::IBeam) + .on_action(cx.listener(Self::backspace)) + .on_action(cx.listener(Self::delete)) + .on_action(cx.listener(Self::left)) + .on_action(cx.listener(Self::right)) + .on_action(cx.listener(Self::select_left)) + .on_action(cx.listener(Self::select_right)) + .on_action(cx.listener(Self::select_all)) + .on_action(cx.listener(Self::home)) + .on_action(cx.listener(Self::end)) + .on_action(cx.listener(Self::show_character_palette)) + .on_action(cx.listener(Self::paste)) + .on_action(cx.listener(Self::cut)) + .on_action(cx.listener(Self::copy)) + .on_action(cx.listener(Self::newline)) + .on_action(cx.listener(Self::undo)) + .on_action(cx.listener(Self::redo)) + .on_action(cx.listener(Self::word_left)) + .on_action(cx.listener(Self::word_right)) + .on_action(cx.listener(Self::select_word_left)) + .on_action(cx.listener(Self::select_word_right)) + .on_action(cx.listener(Self::delete_word_left)) + .on_action(cx.listener(Self::delete_word_right)) + .on_action(cx.listener(Self::select_home)) + .on_action(cx.listener(Self::select_end)) + .on_action(cx.listener(|this, _: &Bold, w, cx| this.mark("**", w, cx))) + .on_action(cx.listener(|this, _: &Italic, w, cx| this.mark("*", w, cx))) + .on_action(cx.listener(|this, _: &Code, w, cx| this.mark("`", w, cx))) + .on_action(cx.listener(|this, _: &Strike, w, cx| this.mark("~~", w, cx))) + .on_action(cx.listener(Self::send_now)) + .on_action(cx.listener(|this, _: &Up, w, cx| { + if this.nav { + return cx.emit(Nav::Up); + } + this.vertical(-1., false, w, cx) + })) + .on_action(cx.listener(|this, _: &Down, w, cx| { + if this.nav { + return cx.emit(Nav::Down); + } + this.vertical(1., false, w, cx) + })) + .on_action(cx.listener(|this, _: &Tab, w, cx| { + if this.nav || this.chip { + cx.emit(Nav::Pick); + } else if !tab_order::step(cx.entity_id(), false, w, cx) { + cx.propagate(); + } + })) + .on_action(cx.listener(|_, _: &TabBack, w, cx| { + if !tab_order::step(cx.entity_id(), true, w, cx) { + cx.propagate(); + } + })) + .on_action(cx.listener(|this, _: &SelectUp, w, cx| this.vertical(-1., true, w, cx))) + .on_action(cx.listener(|this, _: &SelectDown, w, cx| this.vertical(1., true, w, cx))) + .on_mouse_down(MouseButton::Left, cx.listener(Self::on_mouse_down)) + .on_mouse_down(MouseButton::Right, cx.listener(Self::on_right_down)) + .on_mouse_up(MouseButton::Left, cx.listener(Self::on_mouse_up)) + .on_mouse_up_out(MouseButton::Left, cx.listener(Self::on_mouse_up)) + .on_mouse_move(cx.listener(Self::on_mouse_move)) + .on_action(cx.listener(Self::send)) + .on_action(cx.listener(Self::cancel)) + .w_full() + .when_some(self.multiline, |d, max| { + d.max_h(max).overflow_y_scroll().track_scroll(&self.scroll) + }) + .font_family(self.look.family) + .font_weight(self.look.weight) + .line_height(self.look.line_height) + .text_size(self.look.size) + .text_color(self.look.color) + .child(TextElement { input: cx.entity() }) + .children(menu) + } +} + +impl Focusable for TextInput { + fn focus_handle(&self, _: &App) -> FocusHandle { + self.focus_handle.clone() + } +} + +pub struct SendText(pub String); +/// The text changed. +pub struct InputChanged; +impl EventEmitter for TextInput {} + +/// A key that would leave the field: Left at its start, Right at its end, Backspace or +/// Delete when empty. Only emitted with `edges`, for a row of fields walked as one. +#[derive(Clone, Copy, PartialEq, Eq)] +pub enum Edge { + Start, + End, + Empty, +} +impl EventEmitter for TextInput {} +/// Escape in the field. +pub struct CancelInput; + +/// A paste that carried no text but a picture or a file. +pub enum Pasted { + Image { bytes: Vec, ext: &'static str }, + Paths(Vec), +} + +impl EventEmitter for TextInput {} +impl EventEmitter