diff --git a/.github/workflows/gpui.yaml b/.github/workflows/gpui.yaml new file mode 100644 index 000000000..f8eb215fa --- /dev/null +++ b/.github/workflows/gpui.yaml @@ -0,0 +1,272 @@ +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-core/**' + - 'crates/vector-calls/**' + - 'src-tauri/src/**' + - '.github/workflows/gpui.yaml' + pull_request: + paths: + - 'crates/vector-gpui/**' + - '.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 }} --bin vector-gpui + + # 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: + 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' + - 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 tor,i2p' + # The Tauri client's Linux release host: its glibc is the floor the AppImage runs on. + - platform: ubuntu-22.04 + target: x86_64-unknown-linux-gnu + out: release + features: '--no-default-features --features video-static,tor,i2p' + runs-on: ${{ matrix.platform }} + env: + CARGO_PROFILE_RELEASE_LTO: thin + CARGO_PROFILE_RELEASE_CODEGEN_UNITS: '16' + 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 + + - 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 + + # whisper builds its Vulkan backend on Linux, which needs glslc, as in the Tauri release. + - name: Vulkan SDK (Linux) + if: startsWith(matrix.platform, 'ubuntu') + 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 (macOS, Linux) + if: startsWith(matrix.platform, 'macos') || startsWith(matrix.platform, 'ubuntu') + 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: (startsWith(matrix.platform, 'macos') || startsWith(matrix.platform, 'ubuntu')) && 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 }} + + - name: Linux environment + if: startsWith(matrix.platform, 'ubuntu') + run: echo "FFMPEG_DIR=$GITHUB_WORKSPACE/src-tauri/native-deps/ffmpeg/${{ matrix.target }}" >> "$GITHUB_ENV" + + # An Intel host building for arm64: ggml's native CPU probe would read the host. + - name: macOS environment + if: startsWith(matrix.platform, 'macos') + run: | + echo "FFMPEG_DIR=$GITHUB_WORKSPACE/src-tauri/native-deps/ffmpeg/${{ matrix.target }}" >> "$GITHUB_ENV" + echo "SDKROOT=$(xcrun --sdk macosx --show-sdk-path)" >> "$GITHUB_ENV" + echo "GGML_NATIVE=OFF" >> "$GITHUB_ENV" + echo "MACOSX_DEPLOYMENT_TARGET=11.0" >> "$GITHUB_ENV" + + - 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: package-${{ matrix.target }} + + - name: Build + shell: bash + run: 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" + + - name: Bundle (Windows) + if: startsWith(matrix.platform, 'windows') + shell: pwsh + run: | + New-Item -ItemType Directory -Force -Path "$env:RUNNER_TEMP\pkg" | Out-Null + Copy-Item "$env:CARGO_TARGET_DIR\${{ matrix.out }}\vector-gpui.exe" "$env:RUNNER_TEMP\pkg\Vector GPUI.exe" + $version = (Select-String -Path Cargo.toml -Pattern '^version = "(.*)"' | Select-Object -First 1).Matches.Groups[1].Value + & "${env:ProgramFiles(x86)}\NSIS\makensis.exe" /V2 ` + "/DSOURCE=$env:RUNNER_TEMP\pkg\Vector GPUI.exe" "/DICON=$env:GITHUB_WORKSPACE\src-tauri\icons\icon.ico" ` + "/DVERSION=$version" "/DOUTFILE=$env:RUNNER_TEMP\pkg\Vector-GPUI_x64-setup.exe" scripts\installer.nsi + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + + - 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" + + - uses: actions/upload-artifact@v4 + with: + name: vector-gpui-${{ matrix.target }} + path: ${{ runner.temp }}/pkg + retention-days: 14 diff --git a/.github/workflows/publish.yaml b/.github/workflows/publish.yaml index 06412adea..e6974ccda 100644 --- a/.github/workflows/publish.yaml +++ b/.github/workflows/publish.yaml @@ -391,8 +391,56 @@ 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 GPUI client's updater bundles. Optional: a failure here leaves its `*-gpui` manifest + # entries out and never holds back the Tauri release. + 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 + + - 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: | + ls -l pkg + for f in pkg/Vector-GPUI_*; do npx --yes @tauri-apps/cli@2.12.2 signer sign "$f"; done + + - name: Upload to the release + run: gh release upload "$TAG" pkg/Vector-GPUI_* --clobber --repo "$GITHUB_REPOSITORY" + checksums: - needs: [release, publish-tauri, publish-android, publish-android-fdroid] + needs: [release, publish-tauri, publish-android, publish-android-fdroid, publish-gpui] + if: ${{ !cancelled() && needs.publish-tauri.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.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 c22e788d5..acf1a6e06 100644 --- a/crates/vector-core/Cargo.toml +++ b/crates/vector-core/Cargo.toml @@ -141,7 +141,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/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/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 88471c4c9..bf14213b6 100644 --- a/crates/vector-core/src/db/community.rs +++ b/crates/vector-core/src/db/community.rs @@ -1284,6 +1284,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> { @@ -1359,33 +1368,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 => {} } } } @@ -2949,13 +2954,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(); { @@ -2984,12 +2989,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(); @@ -3040,9 +3045,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 @@ -3056,8 +3059,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 }) @@ -6118,12 +6120,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) } @@ -6179,7 +6187,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() }) } @@ -6198,7 +6206,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 79f571a62..2bc2697b0 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!( @@ -1258,6 +1269,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()); @@ -1654,7 +1667,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 adb2925e0..7732c5ada 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; 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/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/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/.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..161c91c1a --- /dev/null +++ b/crates/vector-gpui/Cargo.lock @@ -0,0 +1,15540 @@ +# 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_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" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be17b688510d934ce13f48a2beba700e11583e281e0fda99c22bb256a14eda73" +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 = "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", + "jpeg-decoder", + "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", + "waker-fn", + "windows 0.62.2", + "zed-scap", +] + +[[package]] +name = "gpui_apple" +version = "0.1.0" +source = "git+https://github.com/zed-industries/zed?rev=f8cfc7ed9e57503def9479138894f3139f5400cc#f8cfc7ed9e57503def9479138894f3139f5400cc" +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" +source = "git+https://github.com/zed-industries/zed?rev=f8cfc7ed9e57503def9479138894f3139f5400cc#f8cfc7ed9e57503def9479138894f3139f5400cc" +dependencies = [ + "anyhow", + "console_error_panic_hook", + "gpui", + "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 = "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" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3f42e7bbe13d351b6bead8286a43aac9534b82bd3cc43e47037f012ebfd62d4" +dependencies = [ + "bitflags 2.13.2", + "jni-sys 0.3.1", + "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.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5dcb124b932705c146e3e7e61d1b4d2c63720434422ed191a550228d04149555" +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 = "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 = "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.11.0" +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", + "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.5.1" +dependencies = [ + "anyhow", + "arboard", + "base64 0.22.1", + "bip39", + "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_platform", + "gpui_wgpu", + "gtk", + "http", + "image", + "jpegxl-src", + "jxl-oxide", + "libc", + "libwebp-sys", + "log", + "memchr", + "minisign-verify", + "nokhwa", + "nostr-sdk", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "objc2-foundation 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", + "sysinfo 0.31.4", + "tar", + "tempfile", + "tobj", + "tokio", + "unicode-bidi", + "unicode-linebreak", + "unicode-properties", + "unicode-segmentation", + "url", + "vector-core", + "vector-gpui-media", + "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", + "libc", + "lofty", + "log", + "memchr", + "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", + "zip", +] + +[[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..c7c9f7b54 --- /dev/null +++ b/crates/vector-gpui/Cargo.toml @@ -0,0 +1,205 @@ +[package] +name = "vector-gpui" +version = "0.5.1" +edition = "2024" +license = "MIT" +description = "Vector on GPUI: the native-rendered client, at parity with the Tauri one." +publish = 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 = [] + +[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"] } +anyhow = "1" +unicode-segmentation = "1" +unicode-bidi = "0.3" +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" +nokhwa = { version = "0.10", features = ["input-native"] } +arboard = { version = "3.7", default-features = false } +dom_query = "0.28" + +# Screen sharing: X11 read directly; macOS and Windows through xcap. +[target.'cfg(not(target_os = "linux"))'.dependencies] +xcap = "0.9" + +# 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 } +objc2 = "0.6" +objc2-foundation = { version = "0.3", features = ["NSString", "NSArray", "NSURL", "NSEnumerator", "NSRange", "NSObjCRuntime"] } +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(target_os = "linux"))'.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] + +[profile.dev] +debug = "line-tables-only" + +[profile.dev.package."*"] +opt-level = 3 +debug = false + +[profile.release] +lto = "fat" +codegen-units = 1 +panic = "abort" +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" } +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" + +# 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_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. +gpui_wgpu = { path = "vendor/gpui_wgpu" } + +[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..8ef716436 --- /dev/null +++ b/crates/vector-gpui/README.md @@ -0,0 +1,55 @@ +# 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. + +## 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/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-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/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.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..316987656 --- /dev/null +++ b/crates/vector-gpui/build.rs @@ -0,0 +1,167 @@ +//! 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() { + // 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..dc218fcfb --- /dev/null +++ b/crates/vector-gpui/media/Cargo.toml @@ -0,0 +1,85 @@ +[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"] + +[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" + +# 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/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..5933f5cd6 --- /dev/null +++ b/crates/vector-gpui/media/src/calls/mod.rs @@ -0,0 +1,38 @@ +//! 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"] +pub mod share_native; +#[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..894ba5ab1 --- /dev/null +++ b/crates/vector-gpui/media/src/lib.rs @@ -0,0 +1,207 @@ +//! 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; + } +} + +#[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")] +#[path = "../../../../src-tauri/src/whisper.rs"] +#[allow(dead_code)] +pub mod whisper; +#[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); + } + + 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 { + 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..bbb2105b6 --- /dev/null +++ b/crates/vector-gpui/media/src/miniapps.rs @@ -0,0 +1,116 @@ +//! 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; +#[path = "../../../../src-tauri/src/miniapps/isolated.rs"] +#[allow(dead_code)] +mod isolated_core; +#[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) + } + + #[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..a13b76e98 --- /dev/null +++ b/crates/vector-gpui/reference/fixtures.json @@ -0,0 +1,4923 @@ +{ + "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": "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, + "grantable": "18446744073709551615", + "roles": [ + { + "role_id": "1111111111111111111111111111111111111111111111111111111111111111", + "name": "Mods", + "color": 5897395, + "position": 1 + }, + { + "role_id": "2222222222222222222222222222222222222222222222222222222222222222", + "name": "Helpers", + "color": 3718648, + "position": 2 + }, + { + "role_id": "3333333333333333333333333333333333333333333333333333333333333333", + "name": "Designers", + "color": 0, + "position": 3 + } + ], + "overwrites": [ + { + "kind": "everyone", + "id": null, + "npub": null, + "allow": "0", + "deny": "16384" + }, + { + "kind": "role", + "id": "1111111111111111111111111111111111111111111111111111111111111111", + "npub": null, + "allow": "16416", + "deny": "0" + }, + { + "kind": "member", + "id": "2bd806c97f0e00af1a1fc3328fa763a9269723c8db8fac4f93af71db186d6e90", + "npub": "npub190vqdjtlpcq27xslcveglfmr4ynfwg7gmw86cnun4acakxrdd6gqnp929a", + "allow": "65536", + "deny": "131072" + } + ], + "members": [ + { + "id": "2bd806c97f0e00af1a1fc3328fa763a9269723c8db8fac4f93af71db186d6e90", + "npub": "npub190vqdjtlpcq27xslcveglfmr4ynfwg7gmw86cnun4acakxrdd6gqnp929a" + }, + { + "id": "81b637d8fcd2c6da6359e6963113a1170de795e4b725b84d1e0b4cfd9ec58ce9", + "npub": "npub1sxmr0k8u6trd5c6eu6trzyapzux7090ykujmsng7pdx0m8k93n5sd02fwn" + }, + { + "id": "4c26d9074c27d89ede59270c0ac14b71e071b15239519f75474b2f3ba63481f5", + "npub": "npub1fsndjp6vylvfahjeyuxq4s2tw8s8rv2j89ge7a28fvhnhf35s86sg3uctf" + } + ] + }, + "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.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/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.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/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/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..468347fd9 --- /dev/null +++ b/crates/vector-gpui/scripts/bundle-appimage.sh @@ -0,0 +1,64 @@ +#!/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 +set -euo pipefail + +bins=$(realpath "$1") +out=$(realpath -m "$2") +here=$(cd "$(dirname "$0")/.." && pwd) +repo=$(cd "$here/../.." && pwd) + +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" < +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) +app="$out/Vector GPUI.app" + +rm -rf "$app" +mkdir -p "$app/Contents/MacOS" "$app/Contents/Resources" +cp "$bin" "$app/Contents/MacOS/vector-gpui" +cp "$tauri/icons/icon.icns" "$app/Contents/Resources/icon.icns" + +# Its own identifier, so it never takes the desktop client's notifications or vector:// links. +cat > "$app/Contents/Info.plist" < + + + + CFBundleIdentifierio.vectorapp + CFBundleNameVector GPUI + CFBundleDisplayNameVector GPUI + CFBundleExecutablevector-gpui + CFBundleIconFileicon + CFBundlePackageTypeAPPL + CFBundleShortVersionString$version + CFBundleVersion$version + CFBundleInfoDictionaryVersion6.0 + LSMinimumSystemVersion11.0 + NSHighResolutionCapable + 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/Vector-GPUI-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/Vector-GPUI_$arch.app.tar.gz" "Vector GPUI.app" +rm -rf "$app" diff --git a/crates/vector-gpui/scripts/installer.nsi b/crates/vector-gpui/scripts/installer.nsi new file mode 100644 index 000000000..29d833d27 --- /dev/null +++ b/crates/vector-gpui/scripts/installer.nsi @@ -0,0 +1,155 @@ +; 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" + + 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/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/applog.rs b/crates/vector-gpui/src/applog.rs new file mode 100644 index 000000000..46d4ae3b9 --- /dev/null +++ b/crates/vector-gpui/src/applog.rs @@ -0,0 +1,73 @@ +//! 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] {}: {}", + 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")); + } + let env = env_logger::Builder::from_default_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(); + append(&format!( + "[{} PANIC] {info}\n\nBacktrace:\n{backtrace}\n", + vector_core::logging::timestamp_utc() + )); + })); + previous(info); + })); +} 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/attachments.rs b/crates/vector-gpui/src/attachments.rs new file mode 100644 index 000000000..10355c760 --- /dev/null +++ b/crates/vector-gpui/src/attachments.rs @@ -0,0 +1,1157 @@ +//! 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 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}; + +const IMAGES: [&str; 11] = [ + "png", "jpeg", "jpg", "gif", "webp", "jxl", "svg", "bmp", "tiff", "tif", "ico", +]; +/// Pictures that wait behind their blur rather than a file box. +const BLURRED: [&str; 9] = ["png", "jpeg", "jpg", "gif", "webp", "jxl", "tiff", "tif", "ico"]; + +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 + }; + 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 > std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_millis() as u64) { + 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, + 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., + 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 { "Not sent" } else { "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, device(ctx, w, h)) + { + 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().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("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), + ) +} + +fn device(ctx: &Ctx, w: f32, h: f32) -> (u32, u32) { + ( + (w * ctx.scale).round() as u32, + (h * ctx.scale).round() as u32, + ) +} + +/// `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, device(ctx, w, h))?; + 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_note(&att.id, att.size)) + }; + Some( + div() + .relative() + .w(px(w)) + .h(px(h)) + .child(img(thumb).size_full().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.)).tooltip(crate::kit::tooltip("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("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 { + let compact = w < 205. || h < 76.; + let color = if failed.is_some() { + c(DANGER) + } else { + c(PRIMARY) + }; + let icon = 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(_) => "Download Failed".to_string(), + None if paused.is_some() => "Resume Download".to_string(), + None => format!("Download {}", att.extension.to_uppercase()) + .trim() + .to_string(), + }; + let sub = match failed { + Some(e) if !e.is_empty() => e.chars().take(64).collect(), + Some(_) => "Tap to Retry".to_string(), + None if paused.is_some() => paused.unwrap_or_default().trim_start_matches("Resume download · ").to_string() + " done", + None if att.size > 0 => media::format_bytes(att.size), + None => "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 + .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))) + .child(tile) + .child( + div() + .min_w_0() + .pr(px(4.)) + .flex() + .flex_col() + .child( + div() + .text_size(px(14.)) + .line_height(px(17.5)) + .text_color(white_a(0.92)) + .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)) + .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 = format!("Failed: {} · Tap to Retry", e.chars().take(48).collect::()); + file_box_on(ctx, &media, m, &att, FileState::Failed, Some(&label), tap(Act::XdcUrl(url))) + } + XdcUrl::Probing | XdcUrl::Absent => { + let label = format!("Tap to Load · {host}"); + 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() { "Mini App".into() } else { p.name.clone().into() }, + None if att.name.is_empty() => description.into(), + None => att.name.clone().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}") + })), + ), + ) + .child(bar(t.pct)) + } else { + let sub = match (label, state) { + (Some(l), _) => l.to_string(), + (None, FileState::Failed) => { + let reason: String = media + .failed + .get(&att.id) + .map(|r| r.chars().take(64).collect()) + .unwrap_or_default(); + if reason.is_empty() { + "Download Failed · Tap to Retry".into() + } else { + format!("Failed: {reason} · Tap to Retry") + } + } + _ => match (media.resume_note(&att.id, att.size), &size) { + (Some(r), _) => r, + (None, Some(s)) => format!("{kind} — {s}"), + (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() + .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 = live.peers.len(); + let label = if live.active { + "Playing" + } else if players > 0 { + "Click to Join" + } else { + "Click to 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)| { + div() + .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(format!("{players} online")), + ) + }) + .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)), + ) +} diff --git a/crates/vector-gpui/src/audio.rs b/crates/vector-gpui/src/audio.rs new file mode 100644 index 000000000..688b08456 --- /dev/null +++ b/crates/vector-gpui/src/audio.rs @@ -0,0 +1,1723 @@ +//! 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 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::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("Audio file not found".into()) + } + } + AudioInputSpec::Sealed(p, mime) => vector_core::vcache::open(p, mime) + .map(AudioInput::Held) + .ok_or_else(|| "Video file not found".into()), + AudioInputSpec::Held(h) => vector_core::media::open(h) + .map(AudioInput::Held) + .ok_or_else(|| "Audio file 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: "Downloading model...".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 + } + + pub fn dispose_all(&mut self) { + if let Ok(e) = engine() { + for id in self.sources.keys() { + let _ = e.stop(*id); + } + } + self.sources.clear(); + self.players.clear(); + self.active = None; + } +} + +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(|b| image::load_from_memory(b).ok()); + 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.filter(|t| !t.is_empty()), + artist: m.artist.filter(|t| !t.is_empty()), + album: m.album.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(); + (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() { + 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] = &[ + "Song", " ", " ", "(", ")", "-", " - ", "Remastered", "remaster", "REMASTER", "ed", "2011", "201", "Live", + "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:?}"); + } + } +} + +pub fn format_time(ms: u64) -> String { + let s = ms / 1000; + 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 (main, note) = split_title(t.album.as_deref().or(t.title.as_deref()).unwrap_or(&att.name)); + 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 { + format!("{n} songs \u{b7} {} min", (duration as f64 / 60000.).round()) + } else { + format!("{n} songs") + }; + 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: &'static str| { + 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", _) => "Shuffle", + (_, crate::album::Repeat::One) => "Repeat one", + (_, crate::album::Repeat::All) => "Repeat all", + _ => "Repeat", + }; + div() + .id(SharedString::from(format!("album-{key}-{id}"))) + .tooltip(crate::kit::tooltip(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()) + .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()).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", "Play")) + .child(pill("shuffle-play", AlbumAct::Play(true), false, "icons/shuffle.svg", "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 { "Show fewer".to_string() } else { format!("Show all {n} songs") }) + }); + 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}"))) + .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; + div() + .id(id) + .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>>, + 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))) + .tooltip(crate::kit::tooltip(if open { "Hide lyrics" } else { "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}"))) + .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}"), + None => track.to_string(), + }, + None => att.name.clone(), + }; + let now_title = chapters.map(|ch| split_title(&ch[track_idx.max(0) as usize].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, + 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() + .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))) + .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() + .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(|| att.name.clone()); + 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()) + .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()) + .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))) + .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..8bb3dc6b1 --- /dev/null +++ b/crates/vector-gpui/src/audit.rs @@ -0,0 +1,648 @@ +//! 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 serde_json::Value; + +use crate::kit::Choice; + +pub const FAMILIES: &[Choice] = &[ + Choice { + value: "all", + label: "All Actions", + }, + Choice { + value: "community", + label: "Community", + }, + Choice { + value: "roles", + label: "Roles", + }, + Choice { + value: "members", + label: "Members", + }, + Choice { + value: "channels", + label: "Channels", + }, + Choice { + value: "messages", + label: "Messages", + }, + Choice { + value: "voice", + label: "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 + } +} + +const PERMS: &[(u32, &str)] = &[ + (0, "Manage Roles"), + (1, "Manage Channels"), + (2, "Manage Community"), + (3, "Kick Members"), + (4, "Ban Members"), + (5, "Manage Messages"), + (6, "Create Invites"), + (8, "View Audit Log"), + (9, "Mention @everyone"), + (11, "Pin Messages"), + (13, "View Channels"), + (14, "Send Messages"), + (15, "Send in Threads"), + (16, "Attach Files"), + (17, "Add Reactions"), + (18, "Read Message History"), + (19, "Connect"), + (20, "Speak"), + (21, "Video"), + (22, "Priority Speaker"), + (23, "Mute Members"), + (24, "Deafen Members"), + (25, "Move Members"), + (26, "Timeout Members"), + (28, "Manage Nicknames"), + (29, "Change Nickname"), +]; + +pub fn permission_name(bit: u64) -> String { + PERMS + .iter() + .find(|(b, _)| u64::from(*b) == bit) + .map(|(_, n)| n.to_string()) + .unwrap_or_else(|| format!("Permission {bit}")) +} + +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(|| "a 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 => "a private channel".into(), + }, + "category" => name.unwrap_or("a category").into(), + _ => String::new(), + } +} + +fn plural(n: u64, one: &str, many: &str) -> String { + if n == 1 { + one.into() + } else { + format!("{n} {many}") + } +} + +/// `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 actor = match s(entry, "actor") { + Some(a) => member(Some(a)), + None => "Someone".into(), + }; + let t = entry.get("target"); + let name = |x: Option<&Value>| (target_name(x, member), true); + let plain = |x: &str| (x.to_string(), false); + 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 = || (member(sub("author").and_then(Value::as_str)), true); + let count = || { + new_of("count") + .and_then(Value::as_u64) + .filter(|n| *n > 0) + .unwrap_or(1) + }; + let action = s(entry, "action").unwrap_or(""); + let rest: Vec<(String, bool)> = match action { + "community_create" => vec![plain(" created the community")], + "community_update" => vec![plain(" updated the community")], + "roles_activate" => vec![plain(" switched the community to its new roles")], + "everyone_update" => vec![plain(" changed what "), name(t), plain(" can do")], + "role_create" => vec![plain(" created the role "), name(t)], + "role_update" => vec![plain(" updated the role "), name(t)], + "role_delete" => vec![plain(" deleted the role "), name(t)], + "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() { + vec![ + plain(" gave "), + name(t), + plain(" the role "), + name(added.first()), + ] + } else if removed.len() == 1 && added.is_empty() { + vec![ + plain(" took "), + name(removed.first()), + plain(" from "), + name(t), + ] + } else { + vec![plain(" changed the roles of "), name(t)] + } + } + "member_ban" => vec![plain(" banned "), name(t)], + "member_unban" => vec![plain(" unbanned "), name(t)], + "banlist_update" => vec![plain(" updated the ban list")], + "member_kick" => vec![plain(" kicked "), name(t)], + "member_timeout" => { + let until = new_of("until") + .and_then(Value::as_u64) + .map(|ms| format!(" until {}", when_full(ms))) + .unwrap_or_default(); + vec![plain(" timed out "), name(t), plain(&until)] + } + "member_timeout_remove" => vec![plain(" lifted the timeout on "), name(t)], + "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")); + let mut whose = if own { + vec![plain(" their nickname")] + } else { + vec![plain(" the nickname of "), name(t)] + }; + match nick { + Some(n) => { + let mut v = vec![plain(" set")]; + v.append(&mut whose); + v.extend([plain(" to "), (n.to_string(), true)]); + v + } + None => { + let mut v = vec![plain(" removed")]; + v.append(&mut whose); + v + } + } + } + "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); + vec![ + plain(&format!( + " created the {}{}channel ", + if private { "private " } else { "" }, + if voice { "voice " } else { "" } + )), + name(t), + ] + } + "channel_update" => vec![plain(" updated "), name(t)], + "channel_delete" => vec![plain(" deleted the channel "), name(t)], + "category_create" => vec![plain(" created the category "), name(t)], + "category_update" => vec![plain(" updated the category "), name(t)], + "category_delete" => vec![plain(" deleted the category "), name(t)], + "overwrite_create" => vec![ + plain(" set permissions for "), + name(sub("for")), + plain(" in "), + name(sub("in")), + ], + "overwrite_update" => vec![ + plain(" changed permissions for "), + name(sub("for")), + plain(" in "), + name(sub("in")), + ], + "overwrite_delete" => vec![ + plain(" cleared the permissions for "), + name(sub("for")), + plain(" in "), + name(sub("in")), + ], + "channel_sync" => vec![ + plain(" synced "), + name(t), + plain(" to "), + name(new_of("category")), + ], + "channel_unsync" => vec![plain(" unsynced "), name(t), plain(" from its category")], + "message_pin" => vec![ + plain(" pinned a message by "), + author(), + plain(" in "), + name(sub("channel")), + ], + "message_unpin" => vec![ + plain(" unpinned a message by "), + author(), + plain(" in "), + name(sub("channel")), + ], + "pins_update" => vec![plain(" changed the pins in "), name(t)], + "message_delete" => vec![ + plain(" deleted a message by "), + author(), + plain(" in "), + name(sub("channel")), + ], + "invite_create" => vec![plain(&format!( + " created {}", + plural(count(), "an invite link", "invite links") + ))], + "invite_delete" => vec![plain(&format!( + " revoked {}", + plural(count(), "an invite link", "invite links") + ))], + "keys_rotate" if field(entry, "severed").is_some() => { + vec![plain(" locked the community down and rotated its keys")] + } + "keys_rotate" => vec![plain(" rotated the community's keys")], + "voice_mute" => vec![ + plain(" muted "), + name(t), + plain(" in "), + name(new_of("channel")), + ], + "voice_unmute" => vec![ + plain(" unmuted "), + name(t), + plain(" in "), + name(new_of("channel")), + ], + "voice_deafen" => vec![ + plain(" deafened "), + name(t), + plain(" in "), + name(new_of("channel")), + ], + "voice_undeafen" => vec![ + plain(" undeafened "), + name(t), + plain(" in "), + name(new_of("channel")), + ], + "voice_move" => vec![plain(" moved "), name(t), plain(" to "), name(new_of("to"))], + "voice_disconnect" => vec![ + plain(" disconnected "), + name(t), + plain(" from "), + name(new_of("channel")), + ], + _ => vec![plain(" made a change")], + }; + let mut out = vec![(actor, true)]; + out.extend(rest); + out +} + +fn view_name(v: &Value) -> String { + match v.as_str() { + Some("chat") => "Text".into(), + Some("voice") => "Voice".into(), + Some("forum") => "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 => "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) => format!("Name: {} → {new}", shown(o)), + None => format!("Name: {new}"), + }); + } + } + "description" => out.push(if truthy(new) { + "Changed the description".into() + } else { + "Removed the description".into() + }), + "topic" => out.push(if truthy(new) { + format!("Topic: {}", new.map(shown).unwrap_or_default()) + } else { + "Removed the topic".into() + }), + f @ ("icon" | "banner") => { + let verb = match new.and_then(Value::as_str) { + Some("removed") => "Removed", + Some("added") => "Added", + _ => "Changed", + }; + out.push(format!("{verb} the {f}")); + } + f @ ("relays" | "voice_relays") => { + let kind = if f == "relays" { + "relay" + } else { + "voice relay" + }; + out.extend( + added + .iter() + .map(|r| format!("Added the {kind} {}", shown(r))), + ); + out.extend( + removed + .iter() + .map(|r| format!("Removed the {kind} {}", shown(r))), + ); + } + "color" => out.push(match old { + Some(o) => format!( + "Colour: {} → {}", + hex_color(o), + hex_color(new.unwrap_or(&Value::Null)) + ), + None => format!("Colour: {}", hex_color(new.unwrap_or(&Value::Null))), + }), + "permissions" => { + if !added.is_empty() { + out.push(format!( + "{}: {}", + if creating { "Permissions" } else { "Granted" }, + perms(&c["added"]) + )); + } + if !removed.is_empty() { + out.push(format!("Revoked: {}", perms(&c["removed"]))); + } + } + "allow" => { + if !added.is_empty() { + out.push(format!("Allowed: {}", perms(&c["added"]))); + } + if !removed.is_empty() { + out.push(format!("No longer allowed: {}", perms(&c["removed"]))); + } + } + "deny" => { + if !added.is_empty() { + out.push(format!("Denied: {}", perms(&c["added"]))); + } + if !removed.is_empty() { + out.push(format!("No longer denied: {}", perms(&c["removed"]))); + } + } + "position" => out.push("Moved it in the list".into()), + "display" => out.push(if truthy(new) { + "Shown on its own in the member list".into() + } else { + "No longer shown on its own in the member list".into() + }), + "mentionable" => out.push(if truthy(new) { + "Anyone can mention it".into() + } else { + "No longer mentionable by everyone".into() + }), + "view" if !creating => out.push(format!( + "Type: {} → {}", + old.map(view_name).unwrap_or_default(), + new.map(view_name).unwrap_or_default() + )), + "private" if !creating => out.push("Made it private".into()), + "category" if action == "channel_update" => out.push(if truthy(new) { + format!("Moved to {}", target_name(new, member)) + } else { + "Moved out of its category".into() + }), + "roles" => { + out.extend( + added + .iter() + .map(|r| format!("Added {}", target_name(Some(r), member))), + ); + out.extend( + removed + .iter() + .map(|r| format!("Removed {}", target_name(Some(r), member))), + ); + if let Some(held) = c.get("held").and_then(Value::as_array) { + out.push(if held.is_empty() { + "Holds no roles".into() + } else { + format!( + "Holds {}", + 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(format!("Nickname: {o} → {n}")), + (Some(o), None) => out.push(format!("Was {o}")), + _ => {} + }, + "banned" => { + if let Some(held) = c.get("held").and_then(Value::as_array) { + out.push(if held.is_empty() { + "Nobody is banned".into() + } else { + format!( + "Banned: {}", + 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("What came before this was compacted when the community's keys were rotated, so what it changed isn't known.".into()); + } + out +} + +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 "Just now".into(); + } + if diff < 3_600_000 { + return plural(diff / 60_000, "A minute ago", "minutes ago"); + } + 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 => format!("Today at {}", crate::data::clock(ms)), + 1 => format!("Yesterday at {}", crate::data::clock(ms)), + _ if chrono::Datelike::year(&d) == chrono::Datelike::year(&today) => { + d.format("%b %-d").to_string() + } + _ => d.format("%b %-d, %Y").to_string(), + } +} + +pub fn when_full(ms: u64) -> String { + crate::data::local(ms) + .format("%b %-d, %Y, %-I:%M %p") + .to_string() +} + +#[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"] + ); + 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..461c26c95 --- /dev/null +++ b/crates/vector-gpui/src/backend/account.rs @@ -0,0 +1,668 @@ +//! 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", + [], + |_| 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, + } +} + +/// 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", + [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| { + 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 +} + +fn touch_last_active() { + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_secs()) + .unwrap_or(0); + let _ = db::set_sql_setting("last_active".into(), now.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(|_| "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(|_| "Invalid Seed Phrase".to_string())? + }; + *FRESH_ACCOUNT_NPUB.lock().unwrap() = 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("Another account is already signed in.".into()); + } + *PENDING_NSEC.lock().unwrap() = Some(keys.secret_key().to_bech32().map_err(|e| e.to_string())?); + if let Some(stale) = MNEMONIC_SEED.lock().unwrap().as_mut() { + stale.zeroize(); + } + *MNEMONIC_SEED.lock().unwrap() = None; + store_identity(&keys); + drop(keys); + install_client(); + insert_own_profile(&npub).await; + *PENDING_ACCOUNT.lock().unwrap() = 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() = 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() = Some(phrase); + *PENDING_ACCOUNT.lock().unwrap() = Some(npub.clone()); + *FRESH_ACCOUNT_NPUB.lock().unwrap() = 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("Password must not be empty.".into()); + } + let nsec = Zeroizing::new( + PENDING_NSEC + .lock() + .unwrap() + .clone() + .ok_or("No pending key")?, + ); + let seed = MNEMONIC_SEED.lock().unwrap().clone().map(Zeroizing::new); + + // 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 kdf = password.as_ref().map(|_| vector_core::crypto::Kdf::fresh()); + let key = match (&password, &kdf) { + (Some(pwd), Some(kdf)) => Some(Zeroizing::new( + vector_core::crypto::derive_key(pwd.as_str(), kdf).await, + )), + _ => 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()); + + let pending = PENDING_ACCOUNT.lock().unwrap().take(); + if let Some(npub) = pending { + // 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}"); + } + } + let security = password.as_ref().map(|_| 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")?; + db::settings::commit_bunker_account_setup( + &stored_key, + password.is_some(), + security, + &seal(&url)?, + &remote_hex, + None, + kdf_row.as_deref(), + )?; + state::clear_pending_bunker_setup(); + } else { + db::settings::commit_account_setup( + &stored_key, + password.is_some(), + security, + stored_seed.as_deref(), + None, + 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(); + if let Some(s) = guard.as_mut() { + s.zeroize(); + } + *guard = None; + } + state::set_encryption_enabled(password.is_some()); + 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().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().clone() +} + +pub(super) fn set_pending(npub: String) { + *FRESH_ACCOUNT_NPUB.lock().unwrap() = None; + *PENDING_ACCOUNT.lock().unwrap() = Some(npub); +} + +/// Forget an account that was started but never committed. +pub fn abandon_pending() { + *PENDING_ACCOUNT.lock().unwrap() = None; + *FRESH_ACCOUNT_NPUB.lock().unwrap() = None; +} + +/// Unlock the stored account: its key opened under `password` when it is encrypted. +pub async fn unlock(password: Option>) -> Result { + *FRESH_ACCOUNT_NPUB.lock().unwrap() = 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); + if !matches!(kind, SignerKind::Local | SignerKind::Bunker) { + return Err( + "This account signs with an external signer, which this client cannot use yet.".into(), + ); + } + let stored = db::get_pkey()?.ok_or("No private key found")?; + let mut nsec = match &password { + Some(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())?; + 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 + } + None => stored, + }; + let keys = Keys::parse(&nsec).map_err(|_| "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 +} + +/// 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")?; + 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")? + .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 Some(client) = state::nostr_client() else { + return false; + }; + if !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; + 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}")); + } + 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}")); + } + 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(format!("Failed to remove account directory: {e}")); + } + _ => {} + } + // 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(format!("{} isn't connected yet. Try again, or pick another network.", k.label())); + } + 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..b51f07ae9 --- /dev/null +++ b/crates/vector-gpui/src/backend/actions.rs @@ -0,0 +1,324 @@ +//! 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})"))?; + 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}"))?; + 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()), + 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()), + }, + }; + 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 urls: Vec = msg + .attachments + .iter() + .flat_map(|a| a.all_urls().map(str::to_string)) + .collect(); + let urls = db::attachments::urls_unreferenced_elsewhere(&urls, &message_id).unwrap_or_default(); + if !urls.is_empty() { + if let Ok(signer) = vector_core::signer::active_signer() { + vector_core::blossom::delete_blobs_best_effort(signer, urls); + } + } + let _ = db::events::delete_event(&message_id).await; + emit_removed(&message_id, &chat_id); + // A Community message that went unconfirmed may have landed anyway: take it back. + db::spawn_bound(async move { + vector_core::community::v2::service::discard_unconfirmed(&chat_id, &message_id).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()); + } + 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})"))?; + if author != db::get_current_account()? { + return Err("Cannot revoke a reaction that isn't 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}"))?; + let recipient = + PublicKey::parse(&chat_id).map_err(|e| format!("Invalid DM counterpart: {e}"))?; + 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..5a025f3f6 --- /dev/null +++ b/crates/vector-gpui/src/backend/archive.rs @@ -0,0 +1,288 @@ +//! 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 { + 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) { + 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); + } +} + +fn walk( + current: &Path, + prefix: &str, + items: &mut Vec, + total: &mut u64, + depth: u32, +) -> Result<(), String> { + if depth > MAX_DEPTH { + return Err("Directory nesting too deep (>128 levels)".into()); + } + let read = std::fs::read_dir(current) + .map_err(|e| format!("Failed to read directory {}: {e}", current.display()))?; + for entry in read { + let entry = entry.map_err(|e| format!("Failed to read entry: {e}"))?; + 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()) + .unwrap_or("folder") + .to_string(), + _ => "Archive".into(), + } +} + +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("Directory is 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; + }; + // 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("Nothing to zip".into()); + } + Ok(("Archive".into(), 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)?; + let file_name = format!("{name}.zip"); + let path = work_slot() + .map_err(|e| format!("Failed to create zip file: {e}"))? + .join(&file_name); + let cancelled = || cancel.load(Ordering::Relaxed); + + let run = || -> Result<(u32, u32, Vec), String> { + let file = + std::fs::File::create(&path).map_err(|e| format!("Failed to create zip file: {e}"))?; + let mut zw = zip::ZipWriter::new(BufWriter::new(file)); + // 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| format!("Failed to add directory: {e}"))?; + if entries.len() < LISTED { + entries.push(Entry { + path: dir, + size: 0, + is_dir: true, + }); + } + continue; + } + if cancelled() { + return Err("Cancelled".into()); + } + // Re-checked at zip time: a file swapped for a link since the walk is skipped. + 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| format!("Failed to start file in zip: {e}"))?; + if item.size > 0 { + let data = std::fs::read(&item.source) + .map_err(|e| format!("Failed to read file {}: {e}", item.source.display()))?; + for chunk in data.chunks(CHUNK) { + if cancelled() { + return Err("Cancelled".into()); + } + zw.write_all(chunk) + .map_err(|e| format!("Failed to write to zip: {e}"))?; + 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| format!("Failed to finalize zip: {e}"))?; + Ok((files, dirs, entries)) + }; + match run() { + Ok((file_count, dir_count, entries)) => { + let size = 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..653a5ecee --- /dev/null +++ b/crates/vector-gpui/src/backend/attachments.rs @@ -0,0 +1,309 @@ +//! 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(); + 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().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().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); +} + +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"); + }; + let Some(idx) = message + .attachments + .iter() + .position(|a| a.id == attachment_id) + else { + return fail(&chat, &msg_id, &attachment_id, "Attachment not found"); + }; + 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": "Too large to hold without keeping it" }), + ); + return false; + } + let Some(active) = Active::claim(&attachment_id) else { + return fail( + &chat, + &msg_id, + &attachment_id, + "This file is 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) => 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 = tokio::task::spawn_blocking(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.to_string()), + } + } else { + bytes + }; + if in_memory && ram.insert(hash32, bytes, mime).is_err() && !keep { + return fail( + &chat, + &msg_id, + &attachment_id, + "Too much media is open to show this one", + ); + } + + { + 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..55f2e47f1 --- /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().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(), 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().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")?; + 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("No invite code found for this user")?; + 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/bunker.rs b/crates/vector-gpui/src/backend/bunker.rs new file mode 100644 index 000000000..05f0f9c17 --- /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) } +} + +/// 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(); + 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("Another account is 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("The signer went away before it was set up".into()); + } + let client_nsec = Zeroizing::new(client_keys.secret_key().to_bech32().map_err(|e| e.to_string())?); + *PENDING_NSEC.lock().unwrap() = 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("Must start with 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(format!("Bunker setup failed: {e}")) + } + } +} + +/// 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, format!("Signer didn't return your pubkey. If you're in Manual mode, check your signer app for an approval prompt. ({e})")); + 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("This account is not a remote-signer account.".into()); + } + let expected = vector_core::db::get_bunker_remote_pubkey() + .ok() + .flatten() + .ok_or("Bunker account missing cached remote pubkey")? + .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("No client keypair loaded — please return to the login screen and try again")?; + 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, format!("Signer didn't return your pubkey. Check the signer app for an approval prompt. ({e})")))); + } + }; + if remote.to_hex() != expected { + let _ = nc.shutdown().await; + return done(Err("Signer returned a different identity. Re-authorize is only for the original account — logout to switch accounts.".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(format!("Failed to persist bunker URL: {e}"))); + } + 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")?; + 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})"))?; + let expected = vector_core::db::get_bunker_remote_pubkey()?.ok_or("Bunker account missing cached remote pubkey")?; + 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("Remote signer returned a different identity than this account. Either re-authorize from Settings, or logout and re-add the account.".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..1fea549a5 --- /dev/null +++ b/crates/vector-gpui/src/backend/calls.rs @@ -0,0 +1,79 @@ +//! 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 +} + +/// 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 label names the network. +pub fn off_clearnet_label() -> Option { + use vector_core::transport::Kind; + match vector_core::transport::preference() { + Some(Kind::Clearnet) => None, + Some(k) => Some(k.label().to_string()), + None => Some("the network in use".into()), + } +} + +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("A call is 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..f91e5e207 --- /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")?; + 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")?; + 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")?; + 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..00c7a598d --- /dev/null +++ b/crates/vector-gpui/src/backend/community.rs @@ -0,0 +1,1573 @@ +//! 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, AtomicU64, 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}")); + } + 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(|| "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(), + }) +} + +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(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 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() + }; + let graph = is_held(&community_id).then(|| VectorCore.community_role_graph(&community_id).ok()).flatten(); + (members, admins, unlisted, graph) +} + +/// 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 { + return Ok(false); + }; + let community_id = + db::community::community_id_for_channel(&channel_id)?.ok_or("Unknown Community channel")?; + 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 + }) +} + +/// `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("Unknown Community channel")?; + 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("Unknown Community channel")?; + 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")?; + let community = load(&community_id)?; + let ch = ChannelId(id32(&channel_id)?); + let channel = community + .channel(&ch) + .ok_or("Channel not found in Community")?; + let (_, epoch) = community.channel_secret(channel); + let ms = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap_or_default() + .as_millis() as u64; + + 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(); + + 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::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(e) => { + let failed = STATE.lock().await.update_message(&message_id, |m| { + m.set_failed(true); + m.set_pending(false); + }); + if let Some((_, msg)) = failed { + Callback.on_failed(&channel_id, &message_id, &msg); + } + Err(e) + } + } + }) + .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; +const COOLDOWN_MS: u64 = 20_000; + +static IN_FLIGHT: AtomicBool = AtomicBool::new(false); +static RERUN: AtomicBool = AtomicBool::new(false); +static RECONNECT_ARMED: AtomicBool = AtomicBool::new(false); +static LAST_END_MS: AtomicU64 = AtomicU64::new(0); + +fn now_ms() -> u64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_millis() as u64) + .unwrap_or(0) +} + +/// 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()) +} + +/// A burst of reconnects becomes one sweep once it settles. +pub fn after_reconnect() { + if !realtime::subscription_ready() || RECONNECT_ARMED.swap(true, Ordering::SeqCst) { + return; + } + db::spawn_bound(async { + let cooling = (LAST_END_MS.load(Ordering::SeqCst) + COOLDOWN_MS).saturating_sub(now_ms()); + tokio::time::sleep(Duration::from_millis(cooling.max(1500))).await; + RECONNECT_ARMED.store(false, Ordering::SeqCst); + request(); + }); +} + +async fn run() { + RERUN.store(false, Ordering::SeqCst); + sweep().await; + LAST_END_MS.store(now_ms(), Ordering::SeqCst); + 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).unwrap_or(0)) + }); + targets.push(( + PaintTarget { + community_id: CommunityId(id.0), + channel_hex: hex, + since, + }, + at, + )); + } + } + super::emit("communities_changed", ()); + targets.sort_by_key(|t| std::cmp::Reverse(t.1)); + let channels: Vec = targets.iter().map(|(t, _)| t.channel_hex.clone()).collect(); + volley::paint_all(targets.into_iter().map(|(t, _)| t).collect()).await; + for id in &held { + realtime::enqueue_follow(id); + } + stream::iter(channels) + .map(|cid| async move { + if !db::session_stopped() { + let _ = sync_channel(cid, None).await; + } + }) + .buffer_unordered(WINDOW) + .collect::>() + .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", ()); +} + +/// 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("A channel needs a 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. +pub async fn mark_read(community_id: String) { + for ch in channel_ids(&community_id) { + super::messaging::mark_as_read(ch.clone(), None).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("No relays available to host the Community".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")?; + 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 +} + +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(&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: local.name.clone(), + 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: folded.name.clone(), + 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")? + .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 +} + +/// 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)); + tokio::join!( + vector_core::community::v2::service::debug_control_report(&c), + vector_core::community::v2::service::explain_epoch_state(&transport, &c), + ) + }) + .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}"))?; + 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}"))?; + let servers = vector_core::state::get_blossom_servers(); + if servers.is_empty() { + return Err("No Blossom servers configured.".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("The community's first channel can't be deleted".to_string()); + } + let name = community + .channel(&ch) + .map(|c| c.name.clone()) + .ok_or("Channel not found in Community")?; + 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..1e453814e --- /dev/null +++ b/crates/vector-gpui/src/backend/community_files.rs @@ -0,0 +1,514 @@ +//! 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())); + } + 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 +} + +/// 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 !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}"))?; + 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("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("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")?; + let my_npub = author.to_bech32().ok(); + let community_id = vector_core::db::community::community_id_for_channel(&channel)? + .ok_or("Unknown Community channel")?; + 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("Community not found")?; + let ch = vector_core::community::ChannelId(id32(&channel)?); + if community.channel(&ch).is_none() { + return Err("Channel not found in Community".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| format!("Signer unavailable: {e}"))?; + let servers = vector_core::state::get_blossom_servers(); + if servers.is_empty() { + mark_failed(&channel, &pending_id).await; + return Err("No Blossom servers configured.".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(format!("Upload failed: {e}")); + } + }; + 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::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(e) => { + mark_failed(&channel, &pending_id).await; + Err(e) + } + } + }) + .await +} + +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()); + } + 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..8bba02b10 --- /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() = Some((path, map)); +} + +pub fn get(key: &str) -> Option { + let guard = STORE.lock().unwrap(); + 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(); + 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..1eb7057ae --- /dev/null +++ b/crates/vector-gpui/src/backend/embedvideo.rs @@ -0,0 +1,357 @@ +//! 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"; + +/// 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().contains(url) { + return false; + } + STOP.lock().unwrap().insert(url.to_string()); + true +} + +fn stopped(url: &str) -> bool { + STOP.lock().unwrap().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" { + 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("Not a web video".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(|_| "Too much media is open to show this one".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("Not a web video".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("Not a web video".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().insert(url.clone()) { + return Err("This video is already downloading".into()); + } + STOP.lock().unwrap().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("This video is too large to play in chat".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 = "Failed to download".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().remove(&url); + STOP.lock().unwrap().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("Media server returned an error status".into())); + } + let total = resp.content_length().filter(|&n| n > 0); + if total.is_some_and(|t| t > limit) { + return Err(Fail::Refused("This video is too large to play in chat".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("This video is too large to play in chat".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("The download 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("Not a video".into()))?; + if let (Some(want), Some(got)) = (expected, hash) + && got != want + { + return Err(Fail::Refused("The video doesn't match the post's 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("Too much media is open to play this one".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..8b03aa4fe --- /dev/null +++ b/crates/vector-gpui/src/backend/events.rs @@ -0,0 +1,230 @@ +//! 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, + chat_id: &str, + npub: &str, + joined: bool, + event_id: &str, + created_at: u64, + invited_by: Option<&str>, + invited_label: Option<&str>, + ) { + let (chat_id, npub, event_id) = (chat_id.to_string(), npub.to_string(), event_id.to_string()); + let invited_by = invited_by.map(str::to_string); + let invited_label = invited_label.map(str::to_string); + db::spawn_bound(async move { + presence(&chat_id, &npub, joined, &event_id, created_at, invited_by.as_deref(), invited_label.as_deref()).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. +async fn presence( + channel_id: &str, + npub: &str, + joined: bool, + event_id: &str, + created_at: u64, + invited_by: Option<&str>, + invited_label: Option<&str>, +) { + 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() + }); + if nameless { + vector_core::profile::sync::queue_profile_sync(npub.to_string(), vector_core::profile::sync::SyncPriority::High, false); + } + vector_core::emit_event( + "system_event", + &json!({ + "conversation_id": channel_id, + "event_id": event_id, + "event_type": et.as_u8(), + "member_pubkey": npub, + "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..9dce92fb7 --- /dev/null +++ b/crates/vector-gpui/src/backend/gifs.rs @@ -0,0 +1,178 @@ +//! 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)) +} + +/// 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> { + let body = fetch(&format!("{SERVICE}/api/v1/{query}"), LISTING_MAX) + .await + .map_err(|e| format!("gif service: {e}"))? + .ok_or("gif service: no usable answer")?; + let json: serde_json::Value = + serde_json::from_slice(&body).map_err(|_| "gif service: answer is not JSON")?; + 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> { + 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..b19920848 --- /dev/null +++ b/crates/vector-gpui/src/backend/images.rs @@ -0,0 +1,331 @@ +//! 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())); + } + // 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("Image 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("Image too large".into()); + } + out.extend_from_slice(&chunk); + } + Ok(out) +} + +/// 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 { + 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 ") { + 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 image".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 directory")? + .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("Invalid emoji 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("community image failed integrity check".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 image")?; + let path = cache_dir(kind) + .ok_or("No cache directory")? + .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..e71d2def6 --- /dev/null +++ b/crates/vector-gpui/src/backend/inline.rs @@ -0,0 +1,174 @@ +//! 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())); + } + 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()); + } + 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()); + } + 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) +} + +/// 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; + } + 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); + } + if let Some(path) = kept(&url) { + return tokio::task::spawn_blocking(move || { + vector_core::vcache::read(&path).ok().map(|b| b.to_vec()) + }) + .await + .ok() + .flatten(); + } + 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..56f28474c --- /dev/null +++ b/crates/vector-gpui/src/backend/install.rs @@ -0,0 +1,228 @@ +//! 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, + /// Base64 of the minisign `.sig` file, as the manifest carries it. + pub signature: String, +} + +/// This build's entry in a manifest's `platforms`: kept apart from the Tauri client's. +pub fn platform_key() -> String { + let os = match std::env::consts::OS { + "macos" => "darwin", + other => other, + }; + format!("{os}-{}-gpui", std::env::consts::ARCH) +} + +pub fn asset(manifest: &serde_json::Value) -> Option { + let p = manifest.get("platforms")?.get(platform_key())?; + Some(Asset { + url: p.get("url")?.as_str()?.to_string(), + signature: p.get("signature")?.as_str()?.to_string(), + }) +} + +/// Whether the running copy can be replaced in place. +pub fn supported() -> bool { + target().is_some() +} + +/// What the update replaces: the `.app` bundle, the AppImage, or (Windows) the install folder. +fn target() -> Option { + if cfg!(target_os = "linux") { + return std::env::var_os("APPIMAGE").map(PathBuf::from).filter(|p| p.is_file()); + } + 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(Path::to_path_buf); + } + exe.parent().map(Path::to_path_buf) +} + +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("The update's signature is malformed") + }; + let key = minisign_verify::PublicKey::decode(&text(pubkey)?).map_err(|_| "The release key is malformed")?; + let sig = minisign_verify::Signature::decode(&text(signature)?).map_err(|_| "The update's signature is malformed")?; + key.verify(bytes, &sig, false).map_err(|_| "The update's signature does not match, so it was not installed".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| format!("Update download failed: {e}"))?; + if !resp.status().is_success() { + return Err(format!("Update download failed: HTTP {}", resp.status())); + } + let total = resp.content_length().unwrap_or(0); + let mut bytes = Vec::with_capacity(total as usize); + let mut shown = 0u64; + while let Some(chunk) = resp.chunk().await.map_err(|e| format!("Update download interrupted: {e}"))? { + bytes.extend_from_slice(&chunk); + let got = bytes.len() as u64; + if got - shown >= 256 * 1024 || got == total { + shown = got; + progress(got, total); + } + } + verify(&bytes, &asset.signature)?; + 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| format!("Update folder: {e}"))?; + let path = dir.join(name); + std::fs::write(&path, &bytes).map_err(|e| format!("Update file: {e}"))?; + 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<(), String> { + let target = target().ok_or("This copy of Vector can't update itself; install the new release by hand")?; + install_at(bundle, &target) +} + +#[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| format!("Couldn't stage the update: {e}"))?; + 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| format!("Couldn't replace the app: {e}"))?; + 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("The app has no folder")?; + let staging = parent.join(".vector-update"); + let _ = std::fs::remove_dir_all(&staging); + std::fs::create_dir_all(&staging).map_err(|e| format!("Couldn't stage the update: {e}"))?; + 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| format!("Couldn't unpack the update: {e}"))?; + 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("The update holds no app")?; + // 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| format!("Couldn't replace the app: {e}"))?; + if let Err(e) = std::fs::rename(&fresh, app) { + let _ = std::fs::rename(&old, app); + return Err(format!("Couldn't replace the app: {e}")); + } + 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| format!("Couldn't start the installer: {e}")) +} + +#[cfg(not(any(target_os = "linux", target_os = "macos", windows)))] +fn install_at(_: &Path, _: &Path) -> Result<(), String> { + Err("No in-app updates on this platform".into()) +} + +/// Start the installed copy once this process has gone, so it isn't handed back to us as a +/// second instance. Windows' installer starts it itself. +pub fn relaunch() -> Result<(), String> { + #[cfg(unix)] + { + let target = target().ok_or("Nothing to start")?; + 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())) + .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 the_platform_entry_is_this_builds_own() { + let key = platform_key(); + assert!(key.ends_with("-gpui")); + let m = serde_json::json!({"platforms": {key.clone(): {"url": "https://x/a.tar.gz", "signature": "c2ln"}}}); + assert_eq!(asset(&m).map(|a| a.url), Some("https://x/a.tar.gz".into())); + assert!(asset(&serde_json::json!({"platforms": {"linux-x86_64": {"url": "u", "signature": "s"}}})).is_none()); + } +} diff --git a/crates/vector-gpui/src/backend/market.rs b/crates/vector-gpui/src/backend/market.rs new file mode 100644 index 000000000..5ffb9744f --- /dev/null +++ b/crates/vector-gpui/src/backend/market.rs @@ -0,0 +1,252 @@ +//! 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(|| "The App Store isn't ready yet".to_string()) +} + +/// Tags are relay data: one spelling of each, so every page and count agrees. +fn tidy(mut apps: Vec) -> Vec { + for app in &mut apps { + 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 mut app = MARKETPLACE_STATE.try_read().ok()?.get_app(id).cloned()?; + app.categories = tidy(vec![app.clone()]).remove(0).categories; + Some(app) +} + +/// 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, a.name, 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)?; + Some((id.to_string(), info.label.clone(), info.description.clone(), 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}"))?; + 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("Listing not found")?; + let edited = vector_core::webxdc::edit_marketplace_listing(¤t, &listing.borrow(¤t.version)).await?; + if !session.is_live() { + return Err("Account changed during the edit".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..49abe7ae6 --- /dev/null +++ b/crates/vector-gpui/src/backend/mediaport.rs @@ -0,0 +1,378 @@ +//! 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 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("This file isn't on this device any more")?; + 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| format!("Couldn't save the file: {e}"))?; + 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("Couldn't save the file: it didn't read back as sent".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); + format!("Couldn't save the file: {e}") + }) +} + +/// 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("Turn on Keep Files on This Device first.".into()); + } + if super::attachments::any_running() || !stop().await { + return Err("Change this once your downloads finish.".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..0cf413f8e --- /dev/null +++ b/crates/vector-gpui/src/backend/messaging.rs @@ -0,0 +1,456 @@ +//! 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(); + uploads + .values() + .for_each(|flag| flag.store(true, std::sync::atomic::Ordering::Release)); + uploads.clear(); + FAIL_REASONS.lock().unwrap().clear(); +} + +pub fn cancel_upload(pending_id: &str) { + if let Some(flag) = UPLOAD_CANCEL.lock().unwrap().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().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()); + } + 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().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().remove(old_id); + CANCELLED.lock().unwrap().push(old_id.to_string()); + return; + } + let reason = FAIL_REASONS.lock().unwrap().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(); + 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 +} + +/// 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(|_| ()); + } + if !IMAGE_EXTS.contains(&extension.as_str()) { + match std::fs::metadata(&path) { + Ok(m) if m.len() > 0 => {} + Ok(_) => return Err("File is empty (0 bytes)".into()), + Err(e) => return Err(format!("Failed to read file metadata: {e}")), + } + let source = vector_core::sending::FileSource::Path(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 = + Arc::new(std::fs::read(&file).map_err(|e| format!("Couldn't read the file: {e}"))?); + 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(|_| ()) +} + +/// 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 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")?; + 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(), + 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..c00b02592 --- /dev/null +++ b/crates/vector-gpui/src/backend/mod.rs @@ -0,0 +1,237 @@ +//! 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 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 security; +pub mod selfsync; +pub mod sound; +pub mod storage; +pub mod transcribe; +pub mod sync; +pub mod transfer; +pub mod transport; +pub mod unfurl; +pub mod install; +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 { + dirs::data_dir() + .unwrap_or_else(std::env::temp_dir) + .join("io.vectorapp") +} + +/// 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); + + // 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()); + if let Some(dl) = dirs::download_dir() { + vector_core::db::set_download_dir(dl.join("vector")); + } + 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()); + 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(); + 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 { + 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); + }); + } + 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..871f0475f --- /dev/null +++ b/crates/vector-gpui/src/backend/network.rs @@ -0,0 +1,977 @@ +//! 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 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap_or_default() + .as_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}")) + } + 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()); + } + let json = + serde_json::to_string(value).map_err(|e| format!("Failed to serialize {key}: {e}"))?; + 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")?; + 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("Not a default relay".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()); + } + let mut relays = load_custom_relays()?; + if relays + .iter() + .any(|r| r.url.eq_ignore_ascii_case(&normalized)) + { + return Err("Relay already exists".to_string()); + } + if is_default_relay(&normalized) { + return Err("Cannot add default relay as custom relay".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("Relay not found")?; + 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()); + } + let mut relays = load_custom_relays()?; + let relay = relays + .iter_mut() + .find(|r| r.url.eq_ignore_ascii_case(&url)) + .ok_or("Relay not found")?; + 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)"); + } + 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})")), + Err(e) => { + vector_core::log_warn!("[Relay] add {url} failed: {e}"); + add_relay_log(url, "error", &format!("Failed to add: {e}")); + } + } + } + // 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; +} + +/// 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"); + } + 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)", + ); + } + + 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)), + ); + 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 { + if let Some(c) = state::nostr_client() { + vector_core::resubscribe_relay_after_reconnect(&c, &relay_url).await; + } + super::sync::after_reconnect(); + } + } + }); + } + + // 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"); + 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...", + ); + 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"); + 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("Cannot add a default server as custom".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("Server already 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("Server not found")? + .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/notify.rs b/crates/vector-gpui/src/backend/notify.rs new file mode 100644 index 000000000..6887c407e --- /dev/null +++ b/crates/vector-gpui/src/backend/notify.rs @@ -0,0 +1,274 @@ +//! 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, show_notification_generic, 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. + 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: || { + 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)); + }, + }); + #[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 show(data: NotificationData) { + if FOCUSED.load(Ordering::Relaxed) { + return; + } + ready(); + show_notification_generic(data); +} + +fn file_body(msg: &Message) -> String { + let ext = msg.attachments.first().map(|a| a.extension.as_str()).unwrap_or("file"); + format!("Sent a {}", crate::data::file_type(ext).1) +} + +/// 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, "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), + ); +} + +/// 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, "Someone", nickname); + let community_name = state + .get_chat(chat_id) + .and_then(|c| c.metadata.get_name().map(str::to_string)) + .unwrap_or_else(|| "Community".to_string()); + 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) { + native_notify::remove_chat(chat_id); +} + +pub fn deleted(message_id: &str) { + native_notify::remove_message(message_id); +} + +pub fn blocked(npub: &str) { + native_notify::remove_sender(npub); +} + +/// The account is leaving this machine's screen: its notifications leave with it. +pub fn account_gone(npub: &str) { + 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(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(); + 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..566d30343 --- /dev/null +++ b/crates/vector-gpui/src/backend/packs.rs @@ -0,0 +1,239 @@ +//! 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}"))?; + reader.limits(vector_core::crypto::bounded_image_limits()); + let img = reader + .decode() + .map_err(|_| "Image couldn't be read (unsupported or corrupt file)".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}"))?; + 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(format!( + "File is {} KB, max is {} KB.", + bytes.len() / 1024, + MAX_EMOJI_BYTES / 1024 + )); + } + if bytes.is_empty() { + return Err("File is empty.".into()); + } + vector_core::state::nostr_client().ok_or("Nostr client not initialised")?; + let signer = + vector_core::signer::active_signer().map_err(|e| format!("Failed to get signer: {e}"))?; + let servers = vector_core::blossom_servers::compute_enabled_servers(); + if servers.is_empty() { + return Err("No Blossom servers configured.".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("A pack needs at least one 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")?; + let signer = + vector_core::signer::active_signer().map_err(|e| format!("Failed to get signer: {e}"))?; + 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/pivx.rs b/crates/vector-gpui/src/backend/pivx.rs new file mode 100644 index 000000000..5c7dc3e4e --- /dev/null +++ b/crates/vector-gpui/src/backend/pivx.rs @@ -0,0 +1,114 @@ +//! 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(|| "The wallet isn't ready yet".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 = std::env::var("LC_ALL") + .or_else(|_| std::env::var("LC_MONETARY")) + .or_else(|_| std::env::var("LANG")) + .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..4d2c70c33 --- /dev/null +++ b/crates/vector-gpui/src/backend/prefs.rs @@ -0,0 +1,339 @@ +//! 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) { + 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}"))?) + } + }; + 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/rail.rs b/crates/vector-gpui/src/backend/rail.rs new file mode 100644 index 000000000..c8676bfec --- /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("Still syncing your communities, try again in a moment".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..86b9b2189 --- /dev/null +++ b/crates/vector-gpui/src/backend/security.rs @@ -0,0 +1,149 @@ +//! 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(|_| "A migration is already in progress".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("Wait for the encryption change to finish".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. +async fn prove(credential: Option>) -> Result, String> { + if !state::is_encryption_enabled_fast() { + return Err("Local Encryption is not enabled".into()); + } + 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("Encryption is 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("Account changed, nothing was modified".into()); + } + if state::is_encryption_enabled_fast() { + return Err("Encryption is 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 key = prove(credential).await?; + let _one = Migrating::enter()?; + if !session.is_live() { + return Err("Account changed, nothing was modified".into()); + } + sweep(|| at_rest::disable(&key, &progress)) +} + +/// 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 old_key = at_rest::prove_credential(&old).await?; + drop(old); + 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("Account changed, nothing was modified".into()); + } + sweep(|| at_rest::rekey(&old_key, &new_key, &kdf, &kind, None, &progress)) +} + +/// 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("This is an external signer account. Your identity key lives on your signer app, never on this device, so there's nothing to export here.".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("The account changed, so nothing was exported".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..aaced8929 --- /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")?; + let config = device + .default_output_config() + .map_err(|e| format!("Failed to get output config: {e}"))?; + 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}"))?; + 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")?; + let id = track.id; + let mut rate = track + .codec_params + .sample_rate + .ok_or("Unknown sample rate")?; + let mut decoder = symphonia::default::get_codecs() + .make(&track.codec_params, &DecoderOptions::default()) + .map_err(|e| format!("Failed to create decoder: {e}"))?; + 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 = std::fs::read(path).map_err(|e| format!("Failed to read cache file: {e}"))?; + if bytes.len() % 4 != 0 { + return Err("Invalid cache file size".into()); + } + 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")?; + 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")?; + 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()); + } + 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:?}")), + } + .map_err(|e| format!("Failed to open output: {e}"))?; + stream.play().map_err(|e| format!("Failed to play: {e}"))?; + 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}"))?; + 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}"))?; + 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")? + .to_string_lossy(); + std::fs::create_dir_all(sounds_dir) + .map_err(|e| format!("Failed to create sounds cache dir: {e}"))?; + let dest = sounds_dir.join(format!("{stem}_{rate}.raw")); + let bytes: Vec = samples.iter().flat_map(|s| s.to_le_bytes()).collect(); + std::fs::write(&dest, bytes).map_err(|e| format!("Failed to write cache file: {e}"))?; + Ok(dest) +} diff --git a/crates/vector-gpui/src/backend/storage.rs b/crates/vector-gpui/src/backend/storage.rs new file mode 100644 index 000000000..463257bf8 --- /dev/null +++ b/crates/vector-gpui/src/backend/storage.rs @@ -0,0 +1,322 @@ +//! 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(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("No file types to clear".into()); + } + if !super::mediaport::stop().await { + return Err(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()) +} + +const KEEP_MEDIA_BUSY: &str = "Turn this off once your downloads finish."; +const CLEAR_BUSY: &str = "Clear this once your files finish moving."; + +/// 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(KEEP_MEDIA_BUSY.into()); + } + set(false)?; + if super::attachments::any_running() { + let _ = set(true); + return Err(KEEP_MEDIA_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..5ec6b9842 --- /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" }) + } 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("Not a 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(); + 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().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().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(); + 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(); + !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(); + 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(); + let heads: Vec = st.heads.iter().map(|h| format!("{:?}@{}..{}{}", h.reader, h.at / CHUNK, h.last / CHUNK, if h.waiting { " waiting" } else { "" })).collect(); + let conns: Vec = st.conns.iter().map(|c| format!("#{}@{} read {:?} ago", c.id, c.chunk, c.used.elapsed())).collect(); + format!("heads {heads:?}, conns {conns:?}, gaps {:?}, failures {}, window {} chunks", self.gaps(&st), st.failures, self.window(&st) / CHUNK) + } + + /// A read is waiting on the network. + pub fn starving(&self) -> bool { + Self::playhead_waits(&self.state.lock().unwrap()) + } + + pub fn error(&self) -> Option { + self.state.lock().unwrap().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("The video doesn't match the post's 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(); + 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().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(); + 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, "The video host stopped answering".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(), 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().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().conns.retain(|c| c.id != id), + Ok(Err(_)) | Err(_) if parked => return s.state.lock().unwrap().conns.retain(|c| c.id != id), + Ok(Err(e)) => return failed(&weak, id, e), + Err(_) => return failed(&weak, id, "The 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(); + 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(); + 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(); + 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, "The video stopped loading")); + } + self.touch(&mut st, at, true); + self.moved.notify_one(); + let step = Duration::from_millis(250); + st = self.arrived.wait_timeout(st, step).unwrap().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("The video host stopped answering ranges".into()), + s => Err(format!("The video host answered {s}")), + } + } + + 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(format!("The video host answered {status}")) + }; + } + 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("The video host sent a 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().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().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().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().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().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().heads.iter().any(|h| h.waiting) && t0.elapsed() < Duration::from_secs(5) { + std::thread::sleep(Duration::from_millis(5)); + } + assert!(s.state.lock().unwrap().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().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().heads.iter().any(|h| h.waiting) && t0.elapsed() < Duration::from_secs(5) { + std::thread::sleep(Duration::from_millis(5)); + } + assert!(s.state.lock().unwrap().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(); + 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..c9ca2b986 --- /dev/null +++ b/crates/vector-gpui/src/backend/sync.rs @@ -0,0 +1,306 @@ +//! 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" })); + if dms(false).await.reached_none() { + watch_unreachable(); + } + 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", + &format!("Couldn't reach any of your {} relays, new messages may be missing", 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. +pub fn notifs() { + 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}"); + } + }); +} + +// ── Catch-up ──────────────────────────────────────────────────────────────── + +/// Quiet time after a sweep before a reconnect buys another. +const COOLDOWN_MS: u64 = 20_000; +static RECONNECT_ARMED: AtomicBool = AtomicBool::new(false); +static LAST_END_MS: AtomicU64 = AtomicU64::new(0); + +fn now_ms() -> u64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_millis() as u64) + .unwrap_or(0) +} + +/// A burst of relay reconnects becomes one catch-up once it settles. +pub fn after_reconnect() { + if !vector_core::community::v2::realtime::subscription_ready() + || RECONNECT_ARMED.swap(true, Ordering::SeqCst) + { + return; + } + db::spawn_bound(async { + let cooling = (LAST_END_MS.load(Ordering::SeqCst) + COOLDOWN_MS).saturating_sub(now_ms()); + tokio::time::sleep(Duration::from_millis(cooling.max(1500))).await; + RECONNECT_ARMED.store(false, Ordering::SeqCst); + super::community::request(); + dms(true).await; + LAST_END_MS.store(now_ms(), Ordering::SeqCst); + }); +} + +/// What a dropped live subscription or a stretch away missed. +pub fn catch_up(what: vector_core::live_subs::CatchUp) { + if !vector_core::community::v2::realtime::subscription_ready() { + return; + } + match what { + vector_core::live_subs::CatchUp::Relay(_) => after_reconnect(), + vector_core::live_subs::CatchUp::All { .. } => { + super::community::request(); + db::spawn_bound(async { + dms(true).await; + }); + } + } +} + +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 = dm_pass(Opts { + is_new, + only: None, + bootstrap: false, + }) + .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: 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); + }); +} diff --git a/crates/vector-gpui/src/backend/transcribe.rs b/crates/vector-gpui/src/backend/transcribe.rs new file mode 100644 index 000000000..7c645d66a --- /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()) +} + +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..d085eb5fc --- /dev/null +++ b/crates/vector-gpui/src/backend/transfer.rs @@ -0,0 +1,95 @@ +//! 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; + +const NOT_WAITING: &str = "The transfer is no longer waiting for approval"; + +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("This account's key lives in your signer app, so there's nothing to send from here. Sign in with your signer on the other device.".into()); + } + Some(vector_core::state::my_public_key().ok_or("Sign in first")?) + } 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(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(NOT_WAITING.into()); + } + let session = vector_core::db::current_session(); + let key = if vector_core::state::is_encryption_enabled_fast() { + let credential = credential + .filter(|c| !c.is_empty()) + .ok_or(vector_core::db::at_rest::CREDENTIAL_REQUIRED)?; + Some(vector_core::db::at_rest::prove_credential(&credential).await?) + } else { + None + }; + let (nsec, seed) = vector_core::db::at_rest::open_identity_secrets(key.as_deref())?; + if !session.is_live() { + return Err("The account changed, so nothing was sent".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 => { + "This device's stored key doesn't match the account, so nothing was sent".to_string() + } + _ => 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")?; + 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() = 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..d42cfb465 --- /dev/null +++ b/crates/vector-gpui/src/backend/transport.rs @@ -0,0 +1,1319 @@ +//! 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("The account changed. Try again.".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}"))?; + 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("The account changed. Try again.".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("The account changed. Try again.".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("The network preference isn't 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("The network can only be changed here before signing in.".into()); + } + if vector_core::signer::pairing_pending() { + return Err("Finish or cancel the signer connection first.".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("End the call to change networks.".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(|_| "Couldn't save the network choice. It applies until Vector restarts.".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}"))?; + 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("Use Tor or I2P to check this address.".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("Vector looks these up only for your 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("Use Tor or I2P to check this address.".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 ")); + 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}"))?; + std::fs::create_dir_all(&cache).map_err(|e| format!("create cache dir: {e}"))?; + // 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("Tor can only be switched here before signing in.".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()); + } + } + 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()); + } + 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() }; + } + 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}"), + None => "disabled".to_string(), + }, + Some(TorStatus::Disabled) => "disabled".to_string(), + Some(TorStatus::Bootstrapping(p)) => format!("bootstrapping {p}%"), + Some(TorStatus::Connected) => "connected".to_string(), + Some(TorStatus::Failed(e)) => format!("failed: {e}"), + } +} + +#[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 ")); + 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(|_| "Timed out building/reading circuit (20s)".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()) + } +} + +/// 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 { + 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}")), + }; + 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..092c16378 --- /dev/null +++ b/crates/vector-gpui/src/backend/unfurl.rs @@ -0,0 +1,283 @@ +//! 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", +]; + +fn extract_https_urls(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 +} + +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()), + } +} + +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}")); + } + 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())); + } + let data: Value = response.json().await.map_err(|e| e.to_string())?; + let author = data["author_name"].as_str().unwrap_or("Twitter"); + 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") + .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") + }) + }) + .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; + }; + for url in extract_https_urls(&vector_core::net::strip_md_link_claims(&message.content)) + .into_iter() + .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 +} diff --git a/crates/vector-gpui/src/backend/updates.rs b/crates/vector-gpui/src/backend/updates.rs new file mode 100644 index 000000000..e0e3e9577 --- /dev/null +++ b/crates/vector-gpui/src/backend/updates.rs @@ -0,0 +1,176 @@ +//! 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) => format!("v{a}.{b}.{c} Preview {n}"), + 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 { + 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(format!("Update server answered {}", resp.status())); + } + 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("Update manifest too large".into()); + } + body.extend_from_slice(&chunk); + } + let manifest: serde_json::Value = + serde_json::from_slice(&body).map_err(|e| format!("Invalid update manifest: {e}"))?; + 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 })) +} + +/// Where a release is installed from when this copy can't update itself. +pub fn release_page(version: Version) -> String { + let [a, b, c] = version.core; + match version.preview { + Some(n) => format!("https://github.com/VectorPrivacy/Vector/releases/tag/v{a}.{b}.{c}-{n}"), + None => format!("https://github.com/VectorPrivacy/Vector/releases/tag/v{a}.{b}.{c}"), + } +} + +#[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"); + } +} diff --git a/crates/vector-gpui/src/backend/upload.rs b/crates/vector-gpui/src/backend/upload.rs new file mode 100644 index 000000000..7db50261e --- /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(|_| "Image couldn't be loaded from disk")?; + picture_ext(&path).ok_or("File type is not allowed for avatars (only images are permitted)")?; + 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("Not connected")?; + let signer = + vector_core::signer::active_signer().map_err(|e| format!("Signer unavailable: {e}"))?; + 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("Failed to broadcast the update to the network.".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..7afc0dc4a --- /dev/null +++ b/crates/vector-gpui/src/backend/xdcurl.rs @@ -0,0 +1,159 @@ +//! 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`. +pub fn find(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 +} + +/// 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()).unwrap_or("Mini App").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("Not a Mini App URL".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"); + } +} diff --git a/crates/vector-gpui/src/badge.rs b/crates/vector-gpui/src/badge.rs new file mode 100644 index 000000000..c43ab31b4 --- /dev/null +++ b/crates/vector-gpui/src/badge.rs @@ -0,0 +1,79 @@ +//! 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::{PCWSTR, w}; + + 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 _ = list.SetOverlayIcon(hwnd, icon, w!("Unread messages")); + 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", + 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..1d6701243 --- /dev/null +++ b/crates/vector-gpui/src/badgecard.rs @@ -0,0 +1,366 @@ +//! 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::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: &'static str, + 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: &'static str, + /// 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(), + "Vector Beta Inviter", + None, + vec![( + vec![ + p("Acquired by inviting "), + ( + format!( + "{} {}", + b.invites, + if b.invites == 1 { "user" } else { "users" } + ), + Run::Bold, + ), + p(" to the Vector Beta!"), + ], + 0., + )], + None, + "", + ), + Badge::Fawkes => ( + "icons/fawkes_mask.svg".into(), + "V for Vector Badge", + None, + vec![ + ( + vec![p( + "Acquired by logging in on Guy Fawkes Day\u{a0}(November 5, 2025).", + )], + 21., + ), + ( + vec![( + "Remember, remember the 5th of November...".into(), + Run::Aside, + )], + 0., + ), + ], + None, + "Full Premium Access", + ), + Badge::BugHunter => ( + format!("icons/bughunter_{}.svg", b.bug.clamp(1, 3)), + "Bug Hunter", + Some(format!("Tier {}", b.bug)), + vec![( + vec![p( + "Bug Hunter badges are one of the most prestigious awards to true contributors of Vector who have identified and reported bugs or issues.", + )], + 0., + )], + Some(b.bug), + if b.bug >= 3 { + "Full Premium Access" + } else { + "Partial Premium Access" + }, + ), + Badge::V2026 => ( + "icons/vforvector2026.svg".into(), + "V for Vector Badge", + Some("2026 Edition".into()), + vec![ + ( + vec![p( + "Remember, Remember... the\u{a0}Fifth\u{a0}of\u{a0}November.", + )], + 10., + ), + ( + vec![p( + "\u{201c}People should not be afraid of their governments. Governments should be afraid of their people.\u{201d}", + )], + 0., + ), + ], + None, + "Partial Premium Access", + ), + }; + Self { + svg: svg.into(), + title, + subtitle, + desc, + tier, + access, + tilt: Point::default(), + opened: std::time::Instant::now(), + } + } +} + +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), + 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), + ) + .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/bin/vector-gpui-miniapp.rs b/crates/vector-gpui/src/bin/vector-gpui-miniapp.rs new file mode 100644 index 000000000..ae40a8c7d --- /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() = Some(std::io::stdout()); + *PENDING.lock().unwrap() = 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..dd1c63b51 --- /dev/null +++ b/crates/vector-gpui/src/call.rs @@ -0,0 +1,1485 @@ +//! `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 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::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) -> &'static str { + match self { + Quality::Excellent => "Excellent", + Quality::Good => "Good", + Quality::Fair => "Fair", + Quality::Poor => "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, +} + +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, + } + } +} + +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"); + 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 { + "Calling…" + } else { + "Incoming call" + } + .into(), + Some(Phase::Connecting) => "Connecting…".into(), + Some(Phase::Active) if self.peer_away => "Waiting for them to come back…".into(), + Some(Phase::Active) if self.stalled => "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>) -> &'static str { + match reason { + Some("rejected") => "Declined", + Some("busy") => "Busy", + Some("no_answer") => "No answer", + Some("missed") => "Missed call", + Some("connect_failed") => "Could not connect", + Some("disconnected") => "Connection lost", + Some("audio_failed") => "Microphone unavailable", + Some("send_failed") => "Could not reach the relays", + Some("answered_elsewhere") => "Answered on another device", + _ => "Call ended", + } +} + +pub fn clock(ms: u64) -> String { + let s = ms / 1000; + let m = s / 60; + let h = m / 60; + if h > 0 { + format!("{h}:{:02}:{:02}", m % 60, s % 60) + } else { + format!("{:02}:{:02}", m % 60, s % 60) + } +} + +fn lost_word(v: f32) -> String { + if v < 0.05 { + "nothing lost".into() + } else if v < 1. { + "under 1% lost".into() + } else { + format!("{v:.prec$}% lost", prec = if v < 10. { 1 } else { 0 }) + } +} + +#[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), + 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), +} + +/// 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) + .tooltip(crate::kit::tooltip(if call.mic_off { + "Microphone access is off" + } else if call.muted { + "Unmute microphone" + } else { + "Mute microphone" + })) + .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 hangup_btn(on: &OnAct) -> impl IntoElement { + let o = on.clone(); + round_btn("call-hangup", 34.) + .tooltip(crate::kit::tooltip("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.) + .tooltip(crate::kit::tooltip("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 { + "Incoming video call" + } else { + "Incoming call" + }, + )) + .child( + div() + .flex() + .gap(px(40.)) + .mt(px(18.)) + .child( + round_btn("call-decline", 60.) + .tooltip(crate::kit::tooltip("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: &'static str) -> 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: &'static str) -> impl IntoElement { + div() + .w(px(84.)) + .flex_shrink_0() + .text_size(px(12.5)) + .text_color(white_a(0.8)) + .child(text) +} + +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: &'static str, + 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 { + let pct = (call.volume / 2.).clamp(0., 1.); + let at = |b: Bounds, x: Pixels| { + let v = ((x - b.origin.x) / b.size.width.max(px(1.))).clamp(0., 1.) * 200.; + (v / 5.).round() * 5. / 100. + }; + let bounds = call.slider.clone(); + let dragging = call.sliding.clone(); + 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::Volume(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::Volume(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("Their volume")) + .child( + div() + .id("call-volume") + .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!("{}%", (call.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("Measuring the connection…") + .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(format!("{} ms", r.rtt as u32)), + ) + .child(format!( + "· {} · {}", + lost_word(r.lost), + if ago == 0 { + "now".to_string() + } else { + format!("{ago}s 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(format!("delay, up to {} ms", 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("lost audio"), + ) + .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 { + "none".to_string() + } else if lost < 1. { + "under 1%".into() + } else { + format!("{lost:.prec$}%", prec = if lost < 10. { 1 } else { 0 }) + }; + let path = match stats.map(|s| s.path.as_str()) { + Some("relay") => "via relay", + Some("direct") => "direct", + _ => "", + }; + 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. => "lowered, the network is dropping packets", + (_, Some(b)) if b >= 64 => "full quality", + _ => "", + }; + let row = |l: &'static str, v: AnyElement| { + let tip = match l { + "Lost audio" => Some("Moments the speaker had to fill in because the audio was late or missing"), + "Bitrate" => Some("How much data your voice uses. It rises on a clean connection and drops when packets are being lost"), + _ => None, + }; + div() + .flex() + .items_center() + .child( + div() + .id(l) + .when_some(tip, |d, t| d.tooltip(crate::kit::tooltip(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.muted && !call.mic_off, |d| { + d.child( + div() + .flex() + .items_center() + .child(label("Your voice")) + .child(meter(call.levels.0, live)), + ) + }) + .children(crate::callpics::panel_blocks(call, on)) + .child(section("Voice processing")) + .child( + div() + .flex() + .flex_col() + .gap(px(6.)) + .child(switch( + "call-agc", + "Automatic gain", + proc_.auto_gain, + Switch::AutoGain, + on, + )) + .child(switch( + "call-aec", + "Echo cancellation", + proc_.echo_cancel, + Switch::EchoCancel, + on, + )) + .child(switch( + "call-ns", + "Noise suppression", + proc_.noise_suppress, + Switch::NoiseSuppress, + on, + )), + ) + .child(section("Connection")) + .child( + div() + .flex() + .flex_col() + .gap(px(6.)) + .child(row( + "Quality", + match call.quality { + Some(q) => value("").child(dot(q)).child(q.label()).into_any_element(), + None => value("Measuring…").into_any_element(), + }, + )) + .child(row( + "Delay", + value( + stats + .map(|s| format!("{} ms", s.rtt_ms)) + .unwrap_or_else(|| "…".into()), + ) + .when(!path.is_empty(), |d| d.child(hint(path))) + .into_any_element(), + )) + .child(row("Lost audio", value(lost_text).into_any_element())) + .child(row( + "Bitrate", + value( + bitrate + .map(|b| format!("{b} kbit/s")) + .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(dot(q))) + .child(div().truncate().child(format!( + "{}{}", + call.status(), + if live && call.peer_muted { + " · muted" + } else { + "" + } + ))); + 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") + .tooltip(crate::kit::tooltip("Open the 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)).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..1d5e8c604 --- /dev/null +++ b/crates/vector-gpui/src/callpics.rs @@ -0,0 +1,496 @@ +//! 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 std::time::Instant; + +use gpui::{AnyElement, InteractiveElement, 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::theme::{ACCENT, c, ca, white_a}; + +const QUALITY: [&[(&str, u32)]; 2] = [ + &[("Low", 1), ("Medium", 3), ("High", 5), ("Best", 6)], + &[("Low", 1), ("Medium", 3), ("High", 5), ("Best", 7), ("Ultra", 8)], +]; +const FPS: [&[u32]; 2] = [&[15, 30], &[5, 10, 15, 30, 60]]; +const BLOCK_TITLE: [&str; 2] = ["Camera quality", "Screenshare quality"]; +const KIND: [&str; 2] = ["camera", "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) + .tooltip(crate::kit::tooltip(match (k, state) { + (0, true) => "Turn the camera off", + (0, false) => "Turn the camera on", + (_, true) => "Stop sharing the screen", + (_, false) => "Share the screen", + })) + .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(format!("Waiting for their {}…", KIND[k])))) + .child(small_btn("call-picture-max", "ui/call-max.svg").tooltip(crate::kit::tooltip("Fill the 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(format!("{name} is sharing a screen")), + ) + }) + } + None => d.child(idle(div()).child(crate::ui::avatar(store, &call.peer, 64.)).child("Their camera is off")), + }) + .children(inset.map(|k| { + let iw = (w * 0.26).min(150.); + let o = on.clone(); + div() + .id("call-picture-inset") + .tooltip(crate::kit::tooltip("Fill the window with their 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") + .tooltip(crate::kit::tooltip("Back to the call window (Esc)")) + .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") + .tooltip(crate::kit::tooltip("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)| format!("{w}×{h} · {fps} fps · {kbps} kbit/s")) + .unwrap_or_default(); + let (rung, fps) = call.prefs[k]; + let mut q: Vec<(String, Option)> = vec![("Adaptive".into(), None)]; + q.extend(QUALITY[k].iter().map(|(l, r)| (l.to_string(), Some(*r)))); + let q_label = q.iter().find(|(_, v)| *v == rung).map(|(l, _)| l.clone()).unwrap_or_else(|| "Adaptive".into()); + let mut f: Vec<(String, Option)> = vec![("Adaptive".into(), None)]; + f.extend(FPS[k].iter().map(|r| (format!("{r} fps"), Some(*r)))); + let f_label = f.iter().find(|(_, v)| *v == fps).map(|(l, _)| l.clone()).unwrap_or_else(|| "Adaptive".into()); + let row = |l: &'static str, 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("Quality", compact_select(("call-q", k), q_label, call.pref_open == Some((k, false)), q, (k, false), on))) + .child(row("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( + "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("Change…") + .into_any_element(), + )) + .child(row( + "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 { "Sharing" } else { "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("System permission required"), + ) + }, + )) + .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("Not offered by this window").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 { + ["Their camera", "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(format!("{w}×{h} · {} fps", seen.dec_fps[k]))) + .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..3e6497cf9 --- /dev/null +++ b/crates/vector-gpui/src/callvideo/camera.rs @@ -0,0 +1,136 @@ +//! 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. + +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::mpsc::Sender; +use std::time::Duration; + +use nokhwa::pixel_format::RgbFormat; +use nokhwa::utils::{CameraFormat, CameraIndex, FrameFormat, RequestedFormat, RequestedFormatType, Resolution}; +use vector_core::calls::wire::VideoKind; + +use super::yuv::I420; +use super::{In, clock_us}; + +pub struct Capture { + pub(super) stop: Arc, +} + +impl Drop for Capture { + fn drop(&mut self) { + self.stop.store(true, Ordering::Relaxed); + } +} + +/// macOS asks once for the camera; the other systems gate it in their own settings. +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("Camera access is blocked in your system privacy settings".into()), + Err(_) => Err("The camera never answered".into()), + } + } + #[cfg(not(target_os = "macos"))] + Ok(()) +} + +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. +pub fn open(kind: VideoKind, 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("Could not open the camera".into())); + return; + } + }; + if let Err(e) = cam.open_stream() { + log::warn!("camera stream: {e}"); + let _ = ready_tx.send(Err("Could not open the camera".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 }), + Ok(Err(e)) => Err(e), + Err(_) => { + stop.store(true, Ordering::Relaxed); + Err("The camera never answered".into()) + } + } +} diff --git a/crates/vector-gpui/src/callvideo/mod.rs b/crates/vector-gpui/src/callvideo/mod.rs new file mode 100644 index 000000000..021063af8 --- /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 as open_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..8f4a60930 --- /dev/null +++ b/crates/vector-gpui/src/callvideo/screen.rs @@ -0,0 +1,260 @@ +//! 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`. + +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("Screen sharing is not available on this system".into()); + } + let (conn, n) = x11rb::connect(None).map_err(|_| "Screen sharing is not available on this system".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, "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(|| format!("Screen {}", i + 1)); + (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 = "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("The screen is gone")?.2), + Target::Window(w) => { + let g = self.conn.get_geometry(w).map_err(err)?.reply().map_err(|_| "The window was 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("This screen's pixel format isn't supported".into()); + } + Ok(Grab { w, h, stride: img.data.len() / h, bgr: true, data: img.data }) + } + } +} + +#[cfg(not(target_os = "linux"))] +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 { "Entire screen".into() } else { m.friendly_name().or_else(|_| m.name()).unwrap_or_else(|_| format!("Screen {}", i + 1)) }; + 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 { format!("{title} — {app}") })); + } + } + 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("The screen is gone")?; + 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("The window was closed")?; + 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 }) +} diff --git a/crates/vector-gpui/src/callvideo/vp8.rs b/crates/vector-gpui/src/callvideo/vp8.rs new file mode 100644 index 000000000..9a318aefd --- /dev/null +++ b/crates/vector-gpui/src/callvideo/vp8.rs @@ -0,0 +1,140 @@ +//! 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")?; + 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())); + } + 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()) + } + + pub fn decode(&mut self, _: &[u8], _: usize) -> Result)>, String> { + Err("built without FFmpeg".into()) + } + } +} + +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)); + } +} diff --git a/crates/vector-gpui/src/callvideo/worker.rs b/crates/vector-gpui/src/callvideo/worker.rs new file mode 100644 index 000000000..03859618a --- /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(); + 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..d83947a39 --- /dev/null +++ b/crates/vector-gpui/src/callvideo/yuv.rs @@ -0,0 +1,238 @@ +//! 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) + } + + /// 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}"); + } + } +} diff --git a/crates/vector-gpui/src/chaneditor.rs b/crates/vector-gpui/src/chaneditor.rs new file mode 100644 index 000000000..cb016408b --- /dev/null +++ b/crates/vector-gpui/src/chaneditor.rs @@ -0,0 +1,1266 @@ +//! 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::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, NavOn, anchor}; +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: &'static str, + pub desc: &'static str, +} + +const fn perm(bit: u32, name: &'static str, desc: &'static str) -> Perm { + Perm { bit, name, desc } +} + +pub const CHANNEL: &[Perm] = &[ + perm(13, "View Channel", "See the channel and read it. A private channel's key follows this."), + perm(14, "Send Messages", "Post here. Without it for @everyone, only those you allow can post."), + perm(15, "Send in Threads", "Reply inside a thread."), + perm(16, "Attach Files", "Share images, videos and files."), + perm(17, "Add Reactions", "React to messages."), + perm(18, "Read Message History", "Read what was said before they could see the channel."), + perm(5, "Manage Messages", "Hide messages from members beneath them here."), +]; + +pub const VOICE: &[Perm] = &[ + perm(19, "Connect", "Join the channel's call."), + perm(20, "Speak", "Be heard in the call."), + perm(21, "Video", "Share a camera or a screen."), + perm(22, "Priority Speaker", "Lower others while speaking."), + perm(23, "Mute Members", "Mute others in the call."), + perm(24, "Deafen Members", "Stop others hearing the call."), + perm(25, "Move Members", "Move others between calls."), + perm(26, "Timeout Members", "Time out members beneath them here."), +]; + +const GROUPS: [(&str, &str, &str, &[Perm]); 2] = [ + ("perm-channel", "Channel", "view send threads attach files reactions history manage messages hide", CHANNEL), + ("perm-voice", "Voice", "connect speak video priority mute deafen move timeout", VOICE), +]; + +const VIEWS: [(&str, &str, &str); 2] = [ + ("chat", "Text", "Messages first."), + ("voice", "Voice", "Opens its call, with the chat beside it."), +]; + +#[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, +} + +pub struct Overwrite { + /// `everyone`, `role:` or `member:`. + pub key: String, + pub npub: Option, + pub allow: u64, + pub deny: u64, +} + +/// `get_channel_permissions`, parsed. +#[derive(Default)] +pub struct Perms { + pub activated: bool, + pub can_manage: bool, + pub synced: bool, + pub category: Option, + pub grantable: u64, + pub roles: Vec, + pub overwrites: Vec, + /// (hex, npub) of everyone a member overwrite can name. + pub members: Vec<(String, String)>, +} + +fn bits(v: &Value) -> u64 { + v.as_str() + .and_then(|s| s.parse().ok()) + .or_else(|| v.as_u64()) + .unwrap_or(0) +} + +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"]), + grantable: bits(&v["grantable"]), + 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"]).unwrap_or_default(), + color: r["color"].as_u64().unwrap_or(0) as u32, + position: r["position"].as_i64().unwrap_or(0), + }) + .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"]), + } + }) + .collect(), + members: v["members"] + .as_array() + .into_iter() + .flatten() + .filter_map(|m| Some((str_of(&m["id"])?, str_of(&m["npub"])?))) + .collect(), + } + } + + 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), + ClearSearch, + View(&'static str), + Private(bool), + Sync(bool), + Target(String), + Bit(u32, Tri), + Lock(bool), + ToggleAdd, + CloseAdd, + Pick(String), + Reset, + Save, + Delete, +} + +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, + pub member: bool, + 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 (allow, deny) = p.stored("everyone"); + LOCK_BITS.iter().all(|b| p.grantable & (1 << b) != 0 || (allow | deny) & (1 << b) != 0) + } + + /// A bit you lack can't be set, but one already set may be cleared. + pub fn can_touch(&self, bit: u32) -> bool { + let Some(p) = self.perms.as_ref() else { return false }; + let b = 1u64 << bit; + let (allow, deny) = p.stored(&self.target); + p.grantable & b == b || (allow | deny) & b == b + } + + /// 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: false, 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("Deleted role".into(), |r| r.name.clone()), + color: Some(role.map_or(0, |r| r.color)), + member: false, + 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: true, 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", "Name", "name rename title")]; + if !self.is_category { + overview.push(anchor("ch-topic", "Topic", "topic description about")); + overview.push(anchor("ch-view", "Opens As", "view text voice opens")); + if activated { + overview.push(anchor("ch-private", "Privacy", "private privacy public hidden key")); + } + } + let mut permissions: Vec = Vec::new(); + if self.syncable() { + permissions.push(anchor("ch-sync", "Category Sync", "sync category inherit")); + } + let own = self.perms_open() && !self.perms.as_ref().is_some_and(|p| p.synced); + if own { + permissions.push(anchor("ch-lock", "Lockdown", "lock lockdown locked spam read only announcements")); + } + permissions.push(anchor("ch-targets", "Roles & Members", "roles members everyone overwrite who")); + if own { + permissions.extend(GROUPS.iter().map(|(id, title, keys, _)| anchor(id, title, keys))); + } + vec![ + Category { id: "overview", label: "Overview", icon: "info", danger: false, anchors: overview }, + Category { id: "permissions", label: "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| !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, _)| !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() }; + (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("Name")) + .child(field_head(if m.is_category { "Category Name" } else { "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("Topic")) + .child(field_head("What this channel is for", 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("Opens As")).child(lede("How a member's client opens the channel. It changes nothing about who can do what.")).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("Privacy")).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("Private Channel"), + if m.saved.view == "voice" { + "Only members and roles you let in can join it." + } else { + "Only members and roles you let in can see it." + }, + )) + .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: &'static str| { + 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("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("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(format!("Search to find the other {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(format!("Nobody matches \"{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("Roles & Members")).child(hint("Loading..."))).into_any_element()]; + }; + if !p.open() { + return vec![block( + true, + div().child(heading("Roles & Members")).child(lede(if p.activated { + "Changing who can do what here needs Manage Roles." + } else { + "Channel permissions come with the new roles. Switch to them in Community Settings, under Roles." + })), + ) + .into_any_element()]; + } + let mut out = Vec::new(); + if m.syncable() { + let synced = p.synced; + out.push( + block( + true, + div().child(heading("Category 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(if synced { + "This channel follows its category's permissions. Edit them from the category, or stop syncing to set its own." + } else { + "This channel sets its own permissions." + }), + ) + .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, |d| d.opacity(0.45)) + .when(!m.busy, |d| d.cursor_pointer().hover(|d| d.underline()).on_click(click(on, move || Act::Sync(!synced)))) + .child(if synced { "Stop syncing" } else { "Sync with its category" }), + ), + ), + ) + .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("Lockdown")).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 { + "Locked. Only the roles and members you allow can post, react or join calls here." + } else { + "Only the roles and members you allow can post, react or join calls, and nothing anyone else sends reaches its readers." + })) + .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 { "Unlock".to_string() } else { format!("Lock {}", if m.is_category { "Category" } else { "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("Roles & Members")) + .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("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(if t.member { + div() + .size(px(18.)) + .flex_shrink_0() + .flex() + .items_center() + .justify_center() + .child(svg().path("icons/user-circle.svg").size(px(16.)).text_color(c(0x6f6f6f))) + .into_any_element() + } else { + 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("no rules yet")) + }).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 { + "Channels synced to this category follow these rules." + } else { + "Pick who to set rules for. Anything left alone follows what they hold across the community." + })) + .child(rows), + ) + .into_any_element(), + ); + for (_, title, _, perms) in GROUPS { + 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 { "A private channel opens only to the roles and members you allow." } 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(format!("for {l}")) + })), + ) + .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): (String, bool) = if m.busy { + ("Saving...".into(), false) + } else if warn { + ( + if m.warn_switch { + format!("Save or reset the rules for {} first", open.unwrap_or_else(|| "this target".into())) + } else { + "Save or reset your changes before closing".into() + }, + true, + ) + } else if let Some(e) = m.error.clone() { + (e, true) + } else { + ("You have unsaved changes".into(), 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", "Reset", live, click(on, || Act::Reset))) + .child(save_btn("ce-save", "Save Changes", 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("Deleted role".into(), |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]); + let active = m + .anchor + .filter(|a| section.anchors.iter().any(|x| x.id == *a)) + .unwrap_or(section.anchors[0].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 = if m.saved.name.is_empty() { + if m.is_category { "Category".to_string() } else { "Channel".to_string() } + } else { + m.saved.name.clone() + }; + 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 { "Delete Category" } else { "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")), + ), + ) + .child( + div() + .id(SharedString::from(format!("ce-scroll-{}", section.id))) + .flex_1() + .min_h_0() + .overflow_y_scroll() + .track_scroll(&m.scroll) + .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().map(|b| { + 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", + "grantable": "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.grantable, u64::MAX); + 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..b17399951 --- /dev/null +++ b/crates/vector-gpui/src/cmdform.rs @@ -0,0 +1,566 @@ +//! 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 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) { + if i + 1 == self.parts.len() { + 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() => 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); + div() + .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(); + div() + .id(SharedString::from(format!("cmd-pick-{i}"))) + .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}"))) + .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 { + div() + .size_full() + .flex() + .items_center() + .gap(px(8.)) + .child( + div() + .flex_shrink_0() + .whitespace_nowrap() + .text_size(px(13.5)) + .text_color(white_a(0.85)) + .flex() + .child("Using\u{a0}") + .child(div().font_weight(FontWeight::SEMIBOLD).text_color(c(PRIMARY)).child(format!("/{}", form.cmd.name))) + .child("\u{a0}with"), + ) + .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(bot.0)), + ) + .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..48c84cea6 --- /dev/null +++ b/crates/vector-gpui/src/commands.rs @@ -0,0 +1,938 @@ +//! 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 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::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 text = || arg("text", ArgType::String, true, format!("The message to {w}")); + let message = || arg("message", ArgType::String, false, "What to say before it".into()); + let mut out = Vec::new(); + if effects { + out.push(sys("rainbow", format!("Send your message in rainbow {w}s"), vec![text()], Builtin::Effect, &[])); + out.push(sys( + "gradient", + format!("Fade your message from one {w} to another"), + vec![ + arg("from", ArgType::Color, true, format!("The {w} it starts in: a name or #hex")), + arg("to", ArgType::Color, true, format!("The {w} it ends in: a name or #hex")), + text(), + ], + Builtin::Effect, + &[], + )); + out.push(sys( + w, + format!("Send your message in one {w}"), + vec![arg(w, ArgType::Color, true, format!("Its {w}: a name or #hex")), text()], + Builtin::Effect, + &[], + )); + } + out.push(sys( + "time", + "A time everyone sees in their own zone".into(), + vec![arg("when", ArgType::String, true, "Like “friday 8pm” or “in 2 hours”".into())], + Builtin::Time, + &[], + )); + out.push(sys("shrug", "Add ¯\\_(ツ)_/¯ to your message".into(), vec![message()], Builtin::Face("¯\\_(ツ)_/¯"), &[])); + out.push(sys( + "flip", + "Add (╯°□°)╯︵ ┻━┻ to your message".into(), + vec![message()], + Builtin::Face("(╯°□°)╯︵ ┻━┻"), + &["tableflip"], + )); + out.push(sys("unflip", "Add ┬─┬ノ( º _ ºノ) to your message".into(), vec![message()], Builtin::Face("┬─┬ノ( º _ ºノ)"), &[])); + out.push(sys("coinflip", "Flip a coin: heads or tails".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}")), + // Decided on the sender's device, as any dice roll in a chat is. + Builtin::Coinflip => { + let heads = rand::random::(); + Some(format!("🪙 Coin flip: **{}**", if heads { "Heads" } else { "Tails" })) + } + _ => 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: c.description.clone(), + 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: a.description.clone(), + 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) +} + +pub fn arg_error(a: &Arg, v: &str) -> Option { + if v.len() > 1024 { + return Some("is too long (max 1024 characters)".into()); + } + 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(|| "must be a whole number".into()) + } + ArgType::Number => (v.trim().is_empty() || !v.trim().parse::().is_ok_and(f64::is_finite)).then(|| "must be a number".into()), + ArgType::Bool => (!["true", "false", "yes", "no", "1", "0"].contains(&v.to_lowercase().as_str())).then(|| "must be true or false".into()), + ArgType::User => (!v.starts_with("npub1") || v.len() > 70).then(|| "must be a user (npub)".into()), + ArgType::Choice => (!a.choices.iter().any(|c| c == v)).then(|| format!("must be one of: {}", a.choices.join(", "))), + ArgType::Color => vector_core::text_color::hex(v).is_none().then(|| format!("must be a {} name or #hex", textcolor::color_word())), + 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(format!("Missing required argument \"{}\"", a.name)), + None => {} + Some((_, v)) => { + if let Some(e) = arg_error(a, v) { + return Some(format!("\"{}\" {e}", a.name)); + } + } + } + } + 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 { + format!("Loading {n} bot{}…", if n == 1 { "" } else { "s" }) + } else { + "Looking for 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(), "Recently Used".into(), 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)) + } 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} ") }; + format!("{base}{value} ") + } + + 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(format!("Unclosed quote in /{name}")); + }; + if let Some(e) = validate(&cmd, &parsed) { + return Route::Error(format!("/{name}: {e}")); + } + 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("Checking for 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 = r.show_bot.then(|| { + if r.cmd.is_system() { + avatar(&Face::Mark) + } else { + avatar(&bot_face(&r.cmd.bot).1.map_or(Face::Placeholder, Face::Path)) + } + }); + div() + .id(SharedString::from(format!("cmd-{}", r.cmd.key()))) + .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) + } 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))) + .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..7f0cf8521 --- /dev/null +++ b/crates/vector-gpui/src/commsettings.rs @@ -0,0 +1,2129 @@ +//! 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 std::collections::HashSet; +use std::rc::Rc; + +use gpui::prelude::*; +use gpui::{AnyElement, App, Entity, FontWeight, ScrollHandle, SharedString, Window, div, px, svg}; +use crate::pic::img; + +use crate::composer::TextInput; +use crate::data::Store; +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; + +pub struct Saved { + pub name: String, + pub description: String, + pub relays: Vec, + pub voice: Vec, +} + +#[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 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), + ClearSearch, + AddRelay, + RemoveRelay(usize), + EditRelay(usize), + CommitEdit, + CancelEdit, + AddVoice, + RemoveVoice(usize), + 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 + } + + 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", + "Overview", + "info", + vec![ + anchor( + "identity", + "Icon & Name", + "icon avatar logo picture image name title rename", + ), + anchor( + "banner", + "Banner", + "banner cover header art background picture image", + ), + anchor( + "description", + "Description", + "description about bio summary", + ), + ], + ), + section( + "relays", + "Relays", + "globe", + vec![ + anchor( + "relay-list", + "Hosting Relays", + "relays servers hosting network nostr", + ), + anchor( + "voice-relays", + "Voice Relays", + "voice relays iroh calls audio", + ), + ], + ), + ]; + if self.can("manage_roles") { + out.push(section( + "roles", + "Roles", + "shield-filled", + crate::roles::anchors(&self.roles), + )); + } + if self.can("ban") { + out.push(section( + "bans", + "Bans", + "x-user", + vec![anchor( + "ban-list", + "Banned Members", + "bans banned unban blocked removed", + )], + )); + } + if self.can("view_audit_log") { + out.push(section( + "audit", + "Audit Log", + "clock", + vec![anchor( + "audit-list", + "Audit Log", + "audit log history changes actions who when record", + )], + )); + } + 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("That isn't a relay address.".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("Use wss://, or ws:// for an .onion or .i2p address.".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("That relay is already 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("A voice relay is an https:// address.".into()); + } + if rest.split(['/', '?', '#']).next().unwrap_or("").is_empty() { + return Err("That isn't a relay address.".into()); + } + let normal = format!("{}/", text.trim_end_matches('/')); + if list.contains(&normal) { + return Err("That relay is already listed.".into()); + } + if list.len() >= VOICE_RELAYS_MAX { + return Err(format!("At most {VOICE_RELAYS_MAX} voice relays.")); + } + Ok(normal) +} + +pub(crate) fn heading(text: &'static str) -> impl IntoElement { + div() + .mb(px(20.)) + .text_size(px(24.)) + .line_height(px(28.)) + .font_weight(FontWeight::BOLD) + .text_color(c(0xffffff)) + .child(text) +} + +pub(crate) fn lede(text: &'static str) -> impl IntoElement { + div() + .mt(px(-8.)) + .mb(px(18.)) + .text_size(px(14.)) + .line_height(px(21.)) + .text_color(c(0x9a9a9a)) + .child(text) +} + +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()) +} + +pub(crate) fn block(first: bool, body: impl IntoElement) -> impl IntoElement { + div() + .pt(px(30.)) + .pb(px(34.)) + .when(!first, |d| d.border_t_1().border_color(c(0x262626))) + .child(body) +} + +pub(crate) fn field_head( + label: &'static str, + 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), + ) + .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("New") +} + +fn remove_btn( + id: &'static str, + label: &'static str, + 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 { + "Add a banner" + } else { + "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("Icon & Name")).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.tooltip(crate::kit::tooltip("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", "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("Community Name", Some((name_len, NAME_MAX, name_len == 0)))) + .child(input_box(&m.name, 42., editable)) + .child(hint("The icon shows on the rail and beside every invite. Square images crop best.").mt(px(10.))), + ), + ), + )) + .child(block( + false, + div().child(heading("Banner")).child( + div() + .flex() + .flex_col() + .items_start() + .gap(px(10.)) + .child( + div() + .id("cs-banner") + .when(editable, |d| d.tooltip(crate::kit::tooltip(if has_banner { "Change banner" } else { "Add a 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", "Remove Banner", click(on, || Act::RemoveBanner)))), + ), + )) + .child(block( + false, + div() + .child(heading("Description")) + .child(field_head("What this community is about", 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()), + ), + )) + .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") + .tooltip(crate::kit::tooltip("What AUTH means")) + .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("AUTH", 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, "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("No relays recorded for this community.").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("Using iroh's public relays, run by n0.")) + .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("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("Hosting Relays")) + .child(lede("Every message, channel and member list in this community lives on these relays, end-to-end encrypted.")) + .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.clone().map(|e| hint(e).mt(px(10.)).text_color(c(crate::timeline::DANGER)))) + .child(hint("A new relay is checked and given this community's whole history before anyone moves to it, and the old relays tell members where everyone went.").mt(px(10.))) + }), + )) + .child(block( + false, + div() + .child(heading("Voice Relays")) + .child(lede("Voice channels connect through these relays, end-to-end encrypted. Each relay sees where callers connect from.")) + .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.clone().map(|e| hint(e).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 { + 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 { + "No matches." + } else { + "Nobody is banned from this community." + }) + .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(format!( + "{} {} ({})", + if all { "Deselect" } else { "Select" }, + if querying { "matches" } else { "all" }, + 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("Banned Members")) + .child(lede("A banned member is silenced everywhere in this community and can't rejoin until they're unbanned.")) + .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(format!("{} of {BANS_MAX}", m.bans.len()))), + ) + .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("Reading this community's history…").into_any_element() + } else if let Some(e) = a.error.clone().filter(|_| a.entries.is_empty()) { + hint(e) + .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 { + "No matches." + } else { + "Nothing has happened here yet." + })); + } + 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() + .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)) + .when(open, |s| { + s.with_transformation(gpui::Transformation::rotate( + gpui::radians(std::f32::consts::PI), + )) + }), + ), + ) + }), + ); + 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", "Show more", true, click(on, || Act::AuditMore))))) + .when(a.compacted, |d| d.child(hint("Some history from before a key rotation this device didn't live through can't be read back."))) + .into_any_element() + }; + let filter = crate::kit::select( + "audit-filter", + 170., + crate::audit::FAMILIES, + a.action, + a.filter_open, + 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("Audit Log"), + ) + .child( + div() + .flex() + .gap(px(4.)) + .when(m.advanced, |d| { + d.child(text_btn( + "audit-report", + "Sync Report", + !m.report.as_ref().is_some_and(|r| r.loading), + click(on, || Act::SyncReport), + )) + }) + .child(text_btn( + "audit-refresh", + "Refresh", + !a.loading, + click(on, || Act::AuditRefresh), + )), + ), + ) + .child(lede( + "Every change to this community, signed by whoever made it.", + )) + .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: &'static str) -> 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): (String, Vec) = if unban { + let label = if n == m.bans.len() && n > 1 { + "Unban All".to_string() + } else { + format!("Unban {n}") + }; + ( + if m.unbanning { + format!("Unbanning {n}...") + } else { + format!("{n} {} selected", if n == 1 { "member" } else { "members" }) + }, + vec![ + text_btn( + "cs-clear-bans", + "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(|p| format!("Saving {p}%")) + .unwrap_or_else(|| "Saving...".into()) + .into() + } else if warn { + "Save or reset your changes before closing".into() + } else { + "You have unsaved changes".into() + }, + vec![ + text_btn("cs-reset", "Reset", !m.saving, click(on, || Act::Reset)), + save_btn( + "cs-save", + "Save Changes", + !m.saving && !name_empty, + click(on, || Act::Save), + ) + .into_any_element(), + ], + ) + }; + 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 warn { + c(crate::timeline::DANGER) + } else { + c(0xe6e6e6) + }) + .child(text), + ) + .child(div().flex().gap(px(6.)).children(actions)), + ) + .into_any_element(), + ) +} + +pub(crate) fn text_btn( + id: &'static str, + label: &'static str, + 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_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]); + let active = m + .anchor + .filter(|a| section.anchors.iter().any(|x| x.id == *a)) + .unwrap_or(section.anchors[0].id); + let name = store + .community(&m.community) + .map(|c| c.name.clone()) + .filter(|n| !n.is_empty()) + .unwrap_or_else(|| "Community".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, + ) + }; + 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), + }; + 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"), + ), + ), + ) + .child( + div() + .id(SharedString::from(format!("cs-scroll-{}", section.id))) + .flex_1() + .min_h_0() + .overflow_y_scroll() + .track_scroll(&m.scroll) + .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(body), + ), + ) + .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(card) + .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() +} + +const REPORT_KINDS: &[(u64, &str)] = &[ + (0, "community"), + (1, "role"), + (2, "channel"), + (3, "grant"), + (4, "banlist"), + (8, "invite links"), + (10, "dissolved"), + (11, "pins"), + (13, "role"), + (14, "permissions"), + (15, "category"), + (16, "tenure"), + (17, "channel sync"), + (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}")) +} + +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!( + " {}{} · held v{} · newest v{}", + shown(&e["entity"]), + if truthy(&e["mine"]) { " (yours)" } else { "" }, + v(&e["floor"]), + v(&e["newest"]), + ); + if truthy(&e["newest"]) { + out += &format!(" by {}", shown(&e["newest"]["author"])); + } + if truthy(&e["refused"]) { + out += &format!(" · refused: {}", shown(&e["refused"])); + } + if truthy(&e["carried"]) { + out += "· kept, refused"; + } + if truthy(&e["kept"]) { + out += "· kept"; + } + if truthy(&e["newest"]) && !truthy(&e["newest"]["admitted"]) { + out += "· not admitted"; + } + 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: &'static str) -> 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("Reading the control plane…")); + } else if let Some(err) = &r.error { + body = body.child(div().text_size(px(13.)).text_color(c(crate::timeline::DANGER)).child(err.clone())); + } 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)) + .child(report_chip(if settled { "Authority settled" } else { "Authority unsettled" }, !settled)) + .child(report_chip(if cut { "Read cut short" } else { "Read whole" }, cut)) + .child(report_chip( + format!("{} edits, {} pages", shown(&ctl["editions"]), shown(&ctl["pages_read"])), + false, + )) + .when(truthy(&ctl["would_update"]), |d| d.child(report_chip("Unsaved changes", true))); + } else if truthy(&ctl["error"]) { + chips = chips.child(report_chip(format!("Control: {}", shown(&ctl["error"])), true)); + } + if truthy(&ep["error"]) { + chips = chips.child(report_chip(format!("Epoch: {}", shown(&ep["error"])), true)); + } + body = body.child(chips); + let flagged = report_flagged(d); + if !flagged.is_empty() { + body = body.child(report_label("Worth a look")).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("Full report")).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("Sync Report")) + .child( + div() + .mt(px(4.)) + .text_size(px(13.)) + .line_height(px(24.)) + .text_color(white_a(0.55)) + .child("How this device reads the community. Versions and short IDs only, safe to share."), + ), + ) + .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", "Close", true, click(on, || Act::ReportClose))) + .child(save_btn("sr-copy", "Copy Report", !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..a0ffa01f1 --- /dev/null +++ b/crates/vector-gpui/src/community.rs @@ -0,0 +1,1565 @@ +//! Communities: the rail's rows, a Community's channel pane, its channel header and the +//! member panel beside the conversation. + +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::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 open channel's ⋯. + ChatMenu, + 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, + 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"]).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. + 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; + 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("Invite People"), + "icons/settings.svg" => Some("Edit Channel"), + "icons/chat-bubble.svg" => Some("Open Chat"), + _ => None, + }; + div() + .id(path) + .when_some(tip, |d, t| d.tooltip(crate::kit::tooltip(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 + ))) + .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| 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(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 => String::new(), + 1 => "1 Member".to_string(), + n => format!("{n} Members"), + }), + ), + ) + .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(banner_art(path, width)) + }); + 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| 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(cat.name.to_uppercase(), 0.99) + .font_weight(FontWeight::BOLD) + .text_size(px(11.)) + .line_height(px(24.)) + .text_color(c(LABEL)), + ) + .child( + div() + .size(px(18.)) + .flex() + .items_center() + .justify_center() + .child(icon("icons/chevron-down.svg", 11.7, white_a(0.38)).when( + closed, + |s| { + s.with_transformation(gpui::Transformation::rotate( + gpui::radians(-std::f32::consts::FRAC_PI_2), + )) + }, + )), + ), + ) + .when(owner, |d| { + let key = cat.category_id.clone(); + d.child( + div() + .id(SharedString::from(format!("cat-add-{}", cat.category_id))) + .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() + .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() + .flex_shrink_0() + .gap(px(8.)) + .child(icon(channel_glyph(ch), 19., white_a(0.45))) + .child( + div() + .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(topic) + })), + ) + .children(pins.map(crate::pins::button)) + .child( + div() + .id("chat-menu") + .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") + .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(|p| p.status.title.clone()) + .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() + .tooltip(crate::kit::tooltip("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() + .tooltip(crate::kit::tooltip("Bot")) + .child(svg().path("icons/bot.svg").size(px(14.)).flex_shrink_0().text_color(c(ACCENT))), + ) + }) + .children(crate::timeline::timeout_mark(store, Some(cid), npub)) + .children(unlisted.map(|why| { + let label = if why == "departed" { "Posting after leaving" } else { "Never announced joining" }; + let (tap, why) = (on.clone(), why.to_string()); + div() + .id("unlisted") + .flex() + .p(px(8.)) + .m(px(-8.)) + .cursor_pointer() + .tooltip(crate::kit::tooltip(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) + }) + })), + ) +} + +/// 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 query = view.search.read(cx).text().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); + 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(), "Admin".into())); + } + order.push(("sec-members".into(), "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(label.to_uppercase(), 0.99) + .font_weight(FontWeight::BOLD) + .text_size(px(11.)) + .line_height(px(24.)) + .text_color(c(LABEL)), + ) + .child( + div() + .flex_1() + .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() + .mt(px(8.)) + .size(px(16.)) + .flex() + .items_center() + .justify_center() + .child(icon("icons/chevron-down.svg", 10.4, white_a(0.32)).when( + closed, + |s| { + s.with_transformation(gpui::Transformation::rotate( + gpui::radians(-std::f32::consts::FRAC_PI_2), + )) + }, + )), + ), + ) + .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) => ("Loading members…", false), + (_, true) => ("No one has spoken yet. Members appear here once they post.", true), + _ => ("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("OWNER", 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: &'static str, ink: gpui::Hsla, on: Click| { + div() + .id(SharedString::from(id)) + .tooltip(crate::kit::tooltip(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("Community invite"), + ), + ) + .child( + div() + .ml_auto() + .flex() + .gap(px(8.)) + .child(button( + format!("invite-accept-{}", inv.community_id), + "icons/check.svg", + "Accept Invite", + c(ACCENT), + accept, + )) + .child(button( + format!("invite-decline-{}", inv.community_id), + "icons/x.svg", + "Decline Invite", + 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() + .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 { + ("Sent", inv.sent_at) + } else { + ("Received", inv.received_at) + }; + let row = |first: bool, label: &'static str, 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: &'static str, 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("Community invite"), + ), + ) + .child( + div() + .mt(px(15.)) + .rounded(px(12.)) + .border_1() + .border_color(c(0x262626)) + .flex() + .flex_col() + .child(row(true, "From", person(&inv.inviter).into_any_element())) + .children(owner.map(|o| row(false, "Owner", person(&o).into_any_element()))) + .child(row( + false, + sent.0, + div() + .child(crate::util::relative_time(sent.1, now)) + .into_any_element(), + )) + .child(row( + false, + "Expires", + div() + .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", "Decline", false, decline)) + .child(button("invite-accept", "Accept", 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(card), + ) + .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..d85414e25 --- /dev/null +++ b/crates/vector-gpui/src/composer.rs @@ -0,0 +1,2598 @@ +//! 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::*; + +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, + 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, and when: a run of it undoes as one step. + typed: Option, + /// 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"; + +/// 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, WrappedLine)>, + line_height: Pixels, + /// Centred within this width, each visual row on its own. + align: Option, + right: bool, +} + +impl Layout { + fn shape( + text: SharedString, + runs: &[TextRun], + font_size: Pixels, + wrap: Option, + 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, h) = (line.len(), line.size(line_height).height); + lines.push((start, y, line)); + start += len + 1; + y += h; + } + Self { + text, + lines, + line_height, + align: None, + right: false, + } + } + + /// 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. } + } + + fn height(&self) -> Pixels { + self.lines + .last() + .map(|(_, y, l)| *y + l.size(self.line_height).height) + .unwrap_or(self.line_height) + .max(self.line_height) + } + + fn line_at(&self, index: usize) -> Option<&(usize, Pixels, WrappedLine)> { + self.lines + .iter() + .rev() + .find(|(start, _, _)| *start <= index) + } + + /// The char boundary after `index`. + fn after(&self, index: usize) -> usize { + self.line_at(index).map_or(index, |(start, _, line)| { + let local = index - start; + index + line.text.get(local..).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, line)) = self.line_at(index) else { + return point(px(0.), px(0.)); + }; + let local = index.saturating_sub(*start).min(line.len()); + 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) + } + + fn index_at(&self, p: Point) -> usize { + let Some((start, y, line)) = self + .lines + .iter() + .rev() + .find(|(_, y, _)| *y <= p.y) + .or(self.lines.first()) + else { + return 0; + }; + let h = line.size(self.line_height).height; + let ly = (p.y - *y).clamp(px(0.), (h - px(1.)).max(px(0.))); + 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()) + } +} + +impl TextInput { + fn left(&mut self, _: &Left, 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 right(&mut self, _: &Right, 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) { + self.select_to(self.previous_boundary(self.cursor_offset()), window, cx); + } + + fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context) { + self.select_to(self.next_boundary(self.cursor_offset()), 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() { + 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() { + 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 = |c: char| if c.is_alphanumeric() || c == '_' { 0 } else if c.is_whitespace() { 1 } else { 2 }; + 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("No Guesses Found", "").disabled(true)); + } + items.extend(guesses.iter().map(|g| MenuItem::new(g.clone(), ""))); + items.push(MenuItem::divider()); + items.push(MenuItem::new("Ignore Spelling", "")); + items.push(MenuItem::new("Learn Spelling", "")); + items.push(MenuItem::divider()); + } + items.extend([ + MenuItem::new("Cut", "").disabled(!picked), + MenuItem::new("Copy", "").disabled(!picked), + MenuItem::new("Paste", ""), + MenuItem::divider(), + MenuItem::new("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.replace_text_in_range(None, &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.replace_text_in_range(None, &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; a run of typing keeps only its first. + fn remember(&mut self, typing: bool) { + let now = std::time::Instant::now(); + let joins = typing && self.typed.is_some_and(|t| now.duration_since(t).as_millis() < 1000); + if !joins { + self.undo.push((self.content.clone(), self.selected_range.clone())); + if self.undo.len() > 200 { + self.undo.remove(0); + } + } + self.typed = typing.then_some(now); + self.redo.clear(); + } + + fn forget(&mut self) { + self.undo.clear(); + self.redo.clear(); + self.typed = 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.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 = first.is_alphanumeric() || first == '_'; + for (i, c) in it { + if c.is_whitespace() || (c.is_alphanumeric() || 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 = first.is_alphanumeric() || first == '_'; + let mut end = self.content.len(); + for (i, c) in it { + if c.is_whitespace() || (c.is_alphanumeric() || c == '_') != word { + end = offset + i; + break; + } + } + self.out_of_sub(end, true) + } + + fn word_left(&mut self, _: &WordLeft, window: &mut Window, cx: &mut Context) { + self.move_to(self.word_start(self.cursor_offset()), window, cx); + } + + fn word_right(&mut self, _: &WordRight, window: &mut Window, cx: &mut Context) { + self.move_to(self.word_end(self.cursor_offset()), window, cx); + } + + fn select_word_left(&mut self, _: &SelectWordLeft, window: &mut Window, cx: &mut Context) { + self.select_to(self.word_start(self.cursor_offset()), window, cx); + } + + fn select_word_right(&mut self, _: &SelectWordRight, window: &mut Window, cx: &mut Context) { + self.select_to(self.word_end(self.cursor_offset()), window, cx); + } + + fn delete_word_left(&mut self, _: &DeleteWordLeft, window: &mut Window, cx: &mut Context) { + if self.selected_range.is_empty() { + 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.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(false); + 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 typing = range.is_empty() + && self.marked_range.is_none() + && new_text.graphemes(true).count() == 1 + && !new_text.chars().any(char::is_whitespace); + self.remember(typing); + + 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); + 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, 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); + 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, 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.lines.first().map(|(_, _, l)| l.width()).unwrap_or_default(); + 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 { + 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 (a, b) = (layout.position(input.to_display(r.start)), layout.position(input.to_display(r.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 = 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 { + bounds: 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() { + 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, line) in &layout.lines { + 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(), + move |_, cx| { + close + .update(cx, |this, cx| { + this.menu = None; + if let Some(s) = this.spell.as_mut() { + s.menu = None; + } + cx.notify(); + }) + .ok(); + }, + )), + ) + }); + div() + .id("text-input") + .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