├── .docker └── spacebar_server.Dockerfile ├── .env.example ├── .envrc ├── .github ├── ISSUE_TEMPLATE │ ├── bug_report.yml │ └── feature_request.yml ├── scope-round-200.png └── workflows │ ├── build.yml │ └── check.yml ├── .gitignore ├── .scripts ├── linux.sh ├── macOS.sh └── windows.bat ├── Cargo.lock ├── Cargo.toml ├── LICENSE ├── README.md ├── assets ├── .gitkeep ├── brand │ └── scope-round-200.png └── icons │ ├── a-large-small.svg │ ├── arrow-down.svg │ ├── arrow-left.svg │ ├── arrow-right.svg │ ├── arrow-up.svg │ ├── asterisk.svg │ ├── bell.svg │ ├── calendar.svg │ ├── check.svg │ ├── chevron-down.svg │ ├── chevron-left.svg │ ├── chevron-right.svg │ ├── chevron-up.svg │ ├── chevrons-up-down.svg │ ├── circle-check.svg │ ├── circle-x.svg │ ├── close.svg │ ├── copy.svg │ ├── dash.svg │ ├── delete.svg │ ├── ellipsis-vertical.svg │ ├── ellipsis.svg │ ├── eye-off.svg │ ├── eye.svg │ ├── github.svg │ ├── globe.svg │ ├── heart-off.svg │ ├── heart.svg │ ├── inbox.svg │ ├── info.svg │ ├── loader-circle.svg │ ├── loader.svg │ ├── maximize.svg │ ├── menu.svg │ ├── minimize.svg │ ├── minus.svg │ ├── moon.svg │ ├── palette.svg │ ├── panel-bottom-open.svg │ ├── panel-bottom.svg │ ├── panel-left-open.svg │ ├── panel-left.svg │ ├── panel-right-open.svg │ ├── panel-right.svg │ ├── plus.svg │ ├── search.svg │ ├── sort-ascending.svg │ ├── sort-descending.svg │ ├── star-off.svg │ ├── star.svg │ ├── sun.svg │ ├── thumbs-down.svg │ ├── thumbs-up.svg │ ├── triangle-alert.svg │ ├── window-close.svg │ ├── window-maximize.svg │ ├── window-minimize.svg │ └── window-restore.svg ├── rust-toolchain.toml ├── rustfmt.toml ├── shell.nix └── src ├── cache ├── Cargo.toml └── src │ ├── async_list │ ├── mod.rs │ ├── refcache.rs │ ├── refcacheslice.rs │ └── tests.rs │ └── lib.rs ├── chat ├── Cargo.toml └── src │ ├── async_list.rs │ ├── channel.rs │ ├── client.rs │ ├── lib.rs │ └── message.rs ├── discord ├── Cargo.toml └── src │ ├── channel │ └── mod.rs │ ├── client.rs │ ├── lib.rs │ ├── message │ ├── author.rs │ ├── content.rs │ └── mod.rs │ └── snowflake.rs ├── ui ├── Cargo.toml └── src │ ├── actions.rs │ ├── app.rs │ ├── app_state.rs │ ├── channel │ ├── message.rs │ ├── message_list.rs │ └── mod.rs │ ├── main.rs │ └── menu.rs └── util ├── Cargo.toml └── src └── lib.rs /.docker/spacebar_server.Dockerfile: -------------------------------------------------------------------------------- 1 | FROM node:22-slim AS builder 2 | WORKDIR /app 3 | 4 | RUN apt-get update && apt-get install -y git \ 5 | && rm -rf /var/lib/apt/lists/* 6 | 7 | RUN git clone https://github.com/spacebarchat/server.git . 8 | 9 | RUN npm ci --include prod --include dev --include optional --include peer 10 | RUN npm run setup 11 | RUN npm prune --production 12 | 13 | CMD ["npm", "run", "start"] -------------------------------------------------------------------------------- /.env.example: -------------------------------------------------------------------------------- 1 | DISCORD_TOKEN="your discord token" 2 | DEMO_CHANNEL_ID="your demo channel id" -------------------------------------------------------------------------------- /.envrc: -------------------------------------------------------------------------------- 1 | use nix 2 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.yml: -------------------------------------------------------------------------------- 1 | name: Bug report 2 | description: Create a report to help us improve 3 | title: "[Bug]: " 4 | labels: ["bug", "triage"] 5 | body: 6 | - type: markdown 7 | attributes: 8 | value: | 9 | Thanks for taking the time to fill out this bug report! 10 | - type: textarea 11 | id: bug-description 12 | attributes: 13 | label: Describe the bug 14 | description: A clear and concise description of what the bug is 15 | validations: 16 | required: true 17 | - type: textarea 18 | id: reproduction 19 | attributes: 20 | label: Steps to reproduce 21 | description: How can we reproduce this issue? 22 | placeholder: | 23 | 1. Go to '...' 24 | 2. Click on '....' 25 | 3. Scroll down to '....' 26 | 4. See error 27 | validations: 28 | required: true 29 | - type: textarea 30 | id: expected 31 | attributes: 32 | label: Expected behavior 33 | description: What did you expect to happen? 34 | validations: 35 | required: true 36 | - type: input 37 | id: os 38 | attributes: 39 | label: Operating System and Architecture 40 | description: What OS and architecture are you using? 41 | placeholder: "e.g. MacOS, Apple Silicon/aarch64" 42 | validations: 43 | required: true 44 | - type: input 45 | id: version 46 | attributes: 47 | label: Scope Version 48 | description: What version of Scope are you running? 49 | placeholder: "e.g. 0.1.0" 50 | validations: 51 | required: true 52 | - type: textarea 53 | id: screenshots 54 | attributes: 55 | label: Screenshots 56 | description: If applicable, add screenshots to help explain your problem 57 | validations: 58 | required: false 59 | - type: textarea 60 | id: additional 61 | attributes: 62 | label: Additional context 63 | description: Add any other context about the problem here 64 | validations: 65 | required: false 66 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.yml: -------------------------------------------------------------------------------- 1 | name: Feature request 2 | description: Suggest an idea for Scope 3 | title: "[Feature]: " 4 | labels: ["enhancement", "triage"] 5 | body: 6 | - type: markdown 7 | attributes: 8 | value: | 9 | Thanks for taking the time to suggest a feature! 10 | - type: textarea 11 | id: problem 12 | attributes: 13 | label: Is your feature request related to a problem? 14 | description: A clear and concise description of what the problem is 15 | placeholder: "I'm always frustrated when [...]" 16 | validations: 17 | required: true 18 | - type: textarea 19 | id: solution 20 | attributes: 21 | label: Describe the solution you'd like 22 | description: A clear and concise description of what you want to happen 23 | validations: 24 | required: true 25 | - type: textarea 26 | id: alternatives 27 | attributes: 28 | label: Describe alternatives you've considered 29 | description: A clear and concise description of any alternative solutions or features you've considered 30 | validations: 31 | required: false 32 | - type: textarea 33 | id: additional 34 | attributes: 35 | label: Additional context 36 | description: Add any other context or screenshots about the feature request here 37 | validations: 38 | required: false 39 | -------------------------------------------------------------------------------- /.github/scope-round-200.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/scopeclient/scope/a61a2d0c31685064fade18dc53da5cc52bb6211f/.github/scope-round-200.png -------------------------------------------------------------------------------- /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | name: "Nightly Builds" 2 | 3 | on: 4 | push: 5 | branches: [main] 6 | workflow_dispatch: 7 | inputs: 8 | ref: 9 | description: "Branch or tag to build" 10 | required: true 11 | default: "main" 12 | type: string 13 | 14 | env: 15 | CARGO_TERM_COLOR: always 16 | APP_BUNDLE_ID: "com.scopeclient.desktop" 17 | 18 | jobs: 19 | get-version: 20 | name: Get Version 21 | runs-on: ubuntu-latest 22 | outputs: 23 | version: ${{ steps.get_version.outputs.version }} 24 | steps: 25 | - uses: actions/checkout@v4 26 | - name: Get Version 27 | id: get_version 28 | run: echo "version=$(grep '^version = ' src/ui/Cargo.toml | cut -d '"' -f2)" >> $GITHUB_OUTPUT 29 | 30 | build-linux: 31 | needs: get-version 32 | name: Build Linux 33 | runs-on: ubuntu-latest 34 | steps: 35 | - uses: actions/checkout@v4 36 | with: 37 | ref: ${{ github.event.inputs.ref || github.ref }} 38 | 39 | - name: Install Rust 40 | uses: dtolnay/rust-toolchain@master 41 | with: 42 | toolchain: stable 43 | 44 | - name: Cache Rust dependencies 45 | uses: Swatinem/rust-cache@v2 46 | with: 47 | shared-key: "rust-cache-linux" 48 | cache-on-failure: true 49 | 50 | - name: Install Linux Dependencies 51 | run: | 52 | sudo apt-get update 53 | sudo apt-get install -y libxkbcommon-dev libxkbcommon-x11-dev libx11-dev libvulkan-dev vulkan-validationlayers \ 54 | libgtk-3-dev libgdk3.0-cil-dev libsoup-3.0-dev libjavascriptcoregtk-4.1-dev \ 55 | libwebkit2gtk-4.1-dev 56 | 57 | - name: Build Release 58 | run: cargo build --release 59 | 60 | - name: Create AppImage 61 | run: | 62 | sudo apt-get install -y libfuse2 63 | # Create .desktop file 64 | mkdir -p AppDir/usr/share/applications 65 | cat > AppDir/usr/share/applications/scope.desktop << EOF 66 | [Desktop Entry] 67 | Name=Scope 68 | Exec=scope 69 | Icon=scope 70 | Type=Application 71 | Categories=Development; 72 | EOF 73 | 74 | # Copy icon 75 | mkdir -p AppDir/usr/share/icons/hicolor/256x256/apps/ 76 | cp .github/scope-round-200.png AppDir/usr/share/icons/hicolor/256x256/apps/scope.png 77 | 78 | # Copy binary 79 | mkdir -p AppDir/usr/bin 80 | cp target/release/scope AppDir/usr/bin/ 81 | 82 | # Create AppImage 83 | wget -O linuxdeploy-x86_64.AppImage https://github.com/linuxdeploy/linuxdeploy/releases/download/continuous/linuxdeploy-x86_64.AppImage 84 | chmod +x linuxdeploy-x86_64.AppImage 85 | ./linuxdeploy-x86_64.AppImage --appdir AppDir --output appimage 86 | mv Scope*.AppImage Scope-${{ needs.get-version.outputs.version }}.AppImage 87 | 88 | - name: Upload Artifact 89 | uses: actions/upload-artifact@v4 90 | with: 91 | name: Scope-${{ needs.get-version.outputs.version }}.AppImage 92 | path: Scope-${{ needs.get-version.outputs.version }}.AppImage 93 | 94 | build-windows: 95 | needs: get-version 96 | name: Build Windows 97 | runs-on: windows-latest 98 | steps: 99 | - uses: actions/checkout@v4 100 | with: 101 | ref: ${{ github.event.inputs.ref || github.ref }} 102 | 103 | - name: Install Rust 104 | uses: dtolnay/rust-toolchain@master 105 | with: 106 | toolchain: stable 107 | 108 | - name: Cache Rust dependencies 109 | uses: Swatinem/rust-cache@v2 110 | with: 111 | shared-key: "rust-cache-windows" 112 | cache-on-failure: true 113 | 114 | - name: Build Release 115 | run: cargo build --release 116 | 117 | - name: Install WiX Toolset 118 | run: | 119 | curl -OL https://github.com/wixtoolset/wix3/releases/download/wix3112rtm/wix311-binaries.zip 120 | Expand-Archive wix311-binaries.zip -DestinationPath wix 121 | echo "${{ github.workspace }}\wix" | Out-File -FilePath $env:GITHUB_PATH -Encoding utf8 -Append 122 | 123 | - name: Create WiX files 124 | shell: pwsh 125 | run: | 126 | @" 127 | 128 | 129 | 131 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | 150 | 151 | 152 | 153 | 154 | 155 | 156 | 157 | 158 | 159 | 160 | 161 | "@ | Out-File -FilePath "scope.wxs" -Encoding UTF8 162 | 163 | - name: Build MSI 164 | run: | 165 | candle scope.wxs 166 | light -ext WixUIExtension scope.wixobj 167 | mv scope.msi Scope-${{ needs.get-version.outputs.version }}.msi 168 | 169 | - name: Upload Artifact 170 | uses: actions/upload-artifact@v4 171 | with: 172 | name: Scope-${{ needs.get-version.outputs.version }}.msi 173 | path: Scope-${{ needs.get-version.outputs.version }}.msi 174 | 175 | build-macos-intel: 176 | needs: get-version 177 | name: Build macOS (Intel) 178 | runs-on: macos-latest 179 | env: 180 | APPLE_ID: ${{ secrets.APPLE_ID }} 181 | APPLE_ID_PASSWORD: ${{ secrets.APPLE_ID_PASSWORD }} 182 | KEYCHAIN_PASSWORD: $(openssl rand -base64 32) 183 | steps: 184 | - uses: actions/checkout@v4 185 | with: 186 | ref: ${{ github.event.inputs.ref || github.ref }} 187 | 188 | - name: Install Rust 189 | uses: dtolnay/rust-toolchain@master 190 | with: 191 | toolchain: stable 192 | 193 | - name: Cache Rust dependencies 194 | uses: Swatinem/rust-cache@v2 195 | with: 196 | shared-key: "rust-cache-macos-intel" 197 | cache-on-failure: true 198 | 199 | - name: Add Target 200 | run: rustup target add x86_64-apple-darwin 201 | 202 | - name: Build Release 203 | shell: bash 204 | run: cargo build --release --target x86_64-apple-darwin 205 | 206 | - name: Create App Bundle 207 | run: | 208 | mkdir -p Scope.app/Contents/{MacOS,Resources} 209 | cp target/x86_64-apple-darwin/release/scope Scope.app/Contents/MacOS/ 210 | cp .github/scope-round-200.png Scope.app/Contents/Resources/scope.icns 211 | 212 | cat > Scope.app/Contents/Info.plist << EOF 213 | 214 | 215 | 216 | 217 | CFBundleName 218 | Scope 219 | CFBundleDisplayName 220 | Scope 221 | CFBundleIdentifier 222 | ${{ env.APP_BUNDLE_ID }} 223 | CFBundleVersion 224 | ${{ needs.get-version.outputs.version }} 225 | CFBundlePackageType 226 | APPL 227 | CFBundleSignature 228 | ???? 229 | CFBundleExecutable 230 | scope 231 | CFBundleIconFile 232 | scope.icns 233 | LSMinimumSystemVersion 234 | 10.13 235 | NSHighResolutionCapable 236 | 237 | 238 | 239 | EOF 240 | 241 | - name: Import Apple Developer Certificate 242 | env: 243 | APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }} 244 | APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }} 245 | KEYCHAIN_PASSWORD: ${{ secrets.KEYCHAIN_PASSWORD }} 246 | run: | 247 | echo $APPLE_CERTIFICATE | base64 --decode > certificate.p12 248 | security create-keychain -p "$KEYCHAIN_PASSWORD" build.keychain 249 | security default-keychain -s build.keychain 250 | security unlock-keychain -p "$KEYCHAIN_PASSWORD" build.keychain 251 | security import certificate.p12 -k build.keychain -P "$APPLE_CERTIFICATE_PASSWORD" -T /usr/bin/codesign 252 | security set-key-partition-list -S apple-tool:,apple:,codesign: -s -k "$KEYCHAIN_PASSWORD" build.keychain 253 | rm certificate.p12 254 | 255 | - name: Sign App Bundle 256 | run: | 257 | codesign --force --options runtime --sign "Apple Development" Scope.app 258 | codesign --verify --verbose Scope.app 259 | 260 | - name: Create DMG 261 | run: | 262 | hdiutil create -volname "Scope" -srcfolder Scope.app -ov -format UDZO Scope-${{ needs.get-version.outputs.version }}_intel.dmg 263 | 264 | - name: Upload Artifact 265 | uses: actions/upload-artifact@v4 266 | with: 267 | name: Scope-${{ needs.get-version.outputs.version }}_intel.dmg 268 | path: Scope-${{ needs.get-version.outputs.version }}_intel.dmg 269 | 270 | build-macos-silicon: 271 | needs: get-version 272 | name: Build macOS (Silicon) 273 | runs-on: macos-latest 274 | env: 275 | APPLE_ID: ${{ secrets.APPLE_ID }} 276 | APPLE_ID_PASSWORD: ${{ secrets.APPLE_ID_PASSWORD }} 277 | KEYCHAIN_PASSWORD: $(openssl rand -base64 32) 278 | steps: 279 | - uses: actions/checkout@v4 280 | with: 281 | ref: ${{ github.event.inputs.ref || github.ref }} 282 | 283 | - name: Install Rust 284 | uses: dtolnay/rust-toolchain@master 285 | with: 286 | toolchain: stable 287 | 288 | - name: Cache Rust dependencies 289 | uses: Swatinem/rust-cache@v2 290 | with: 291 | shared-key: "rust-cache-macos-silicon" 292 | cache-on-failure: true 293 | 294 | - name: Add Target 295 | run: rustup target add aarch64-apple-darwin 296 | 297 | - name: Build Release 298 | shell: bash 299 | run: cargo build --release --target aarch64-apple-darwin 300 | 301 | - name: Create App Bundle 302 | run: | 303 | mkdir -p Scope.app/Contents/{MacOS,Resources} 304 | cp target/aarch64-apple-darwin/release/scope Scope.app/Contents/MacOS/ 305 | cp .github/scope-round-200.png Scope.app/Contents/Resources/scope.icns 306 | 307 | cat > Scope.app/Contents/Info.plist << EOF 308 | 309 | 310 | 311 | 312 | CFBundleName 313 | Scope 314 | CFBundleDisplayName 315 | Scope 316 | CFBundleIdentifier 317 | ${{ env.APP_BUNDLE_ID }} 318 | CFBundleVersion 319 | ${{ needs.get-version.outputs.version }} 320 | CFBundlePackageType 321 | APPL 322 | CFBundleSignature 323 | ???? 324 | CFBundleExecutable 325 | scope 326 | CFBundleIconFile 327 | scope.icns 328 | LSMinimumSystemVersion 329 | 10.13 330 | NSHighResolutionCapable 331 | 332 | 333 | 334 | EOF 335 | 336 | - name: Import Apple Developer Certificate 337 | env: 338 | APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }} 339 | APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }} 340 | KEYCHAIN_PASSWORD: ${{ secrets.KEYCHAIN_PASSWORD }} 341 | run: | 342 | echo $APPLE_CERTIFICATE | base64 --decode > certificate.p12 343 | security create-keychain -p "$KEYCHAIN_PASSWORD" build.keychain 344 | security default-keychain -s build.keychain 345 | security unlock-keychain -p "$KEYCHAIN_PASSWORD" build.keychain 346 | security import certificate.p12 -k build.keychain -P "$APPLE_CERTIFICATE_PASSWORD" -T /usr/bin/codesign 347 | security set-key-partition-list -S apple-tool:,apple:,codesign: -s -k "$KEYCHAIN_PASSWORD" build.keychain 348 | rm certificate.p12 349 | 350 | - name: Sign App Bundle 351 | run: | 352 | codesign --force --options runtime --sign "Apple Development" Scope.app 353 | codesign --verify --verbose Scope.app 354 | 355 | - name: Create DMG 356 | run: | 357 | hdiutil create -volname "Scope" -srcfolder Scope.app -ov -format UDZO Scope-${{ needs.get-version.outputs.version }}_silicon.dmg 358 | 359 | - name: Upload Artifact 360 | uses: actions/upload-artifact@v4 361 | with: 362 | name: Scope-${{ needs.get-version.outputs.version }}_silicon.dmg 363 | path: Scope-${{ needs.get-version.outputs.version }}_silicon.dmg 364 | -------------------------------------------------------------------------------- /.github/workflows/check.yml: -------------------------------------------------------------------------------- 1 | name: "Check Rust Project" 2 | 3 | on: 4 | push: 5 | branches: ["**"] 6 | pull_request: 7 | branches: ["**"] 8 | 9 | env: 10 | CARGO_TERM_COLOR: always 11 | 12 | jobs: 13 | check-project: 14 | name: Check Rust Project 15 | runs-on: ubuntu-latest 16 | steps: 17 | - name: Checkout code 18 | uses: actions/checkout@v4 19 | 20 | - name: Install Rust 21 | uses: dtolnay/rust-toolchain@master 22 | with: 23 | toolchain: stable 24 | 25 | - name: Cache Rust dependencies 26 | uses: Swatinem/rust-cache@v2 27 | with: 28 | shared-key: "rust-cache" 29 | cache-on-failure: true 30 | 31 | - name: Install Linux Dependencies 32 | run: | 33 | sudo apt-get update 34 | sudo apt-get install -y libxkbcommon-dev libxkbcommon-x11-dev libx11-dev libvulkan-dev vulkan-validationlayers \ 35 | libgtk-3-dev libgdk3.0-cil-dev libsoup-3.0-dev libjavascriptcoregtk-4.1-dev \ 36 | libwebkit2gtk-4.1-dev 37 | 38 | - name: Run `cargo check` 39 | run: cargo check 40 | 41 | - name: Run `cargo clippy` 42 | run: cargo clippy --all-targets --all-features -- -D warnings 43 | 44 | - name: Run `cargo test` 45 | run: cargo test --all-features 46 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | .vscode 3 | .DS_Store 4 | .direnv 5 | .env 6 | .editorconfig -------------------------------------------------------------------------------- /.scripts/linux.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | if [ -f .env ]; then 4 | export $(cat .env | grep -v '^#' | xargs) 5 | fi 6 | 7 | set -e 8 | 9 | echo "Building Scope..." 10 | cargo build --release 11 | 12 | echo "Creating AppImage structure..." 13 | mkdir -p AppDir/usr/share/applications 14 | mkdir -p AppDir/usr/share/icons/hicolor/256x256/apps/ 15 | mkdir -p AppDir/usr/bin 16 | 17 | cat > AppDir/usr/share/applications/scope.desktop << EOF 18 | [Desktop Entry] 19 | Name=Scope 20 | Exec=scope 21 | Icon=scope 22 | Type=Application 23 | Categories=Development; 24 | EOF 25 | 26 | echo "Copying files..." 27 | cp target/release/scope AppDir/usr/bin/ 28 | cp .github/scope-round-200.png AppDir/usr/share/icons/hicolor/256x256/apps/scope.png 29 | 30 | echo "Installing AppImage dependencies..." 31 | sudo apt-get update 32 | sudo apt-get install -y libfuse2 33 | 34 | echo "Creating AppImage..." 35 | wget -O linuxdeploy-x86_64.AppImage https://github.com/linuxdeploy/linuxdeploy/releases/download/continuous/linuxdeploy-x86_64.AppImage 36 | chmod +x linuxdeploy-x86_64.AppImage 37 | ./linuxdeploy-x86_64.AppImage --appdir AppDir --output appimage 38 | 39 | VERSION=$(grep '^version = ' src/ui/Cargo.toml | cut -d '"' -f2) 40 | mv Scope*.AppImage ../Scope-${VERSION}.AppImage 41 | rm -rf AppDir linuxdeploy-x86_64.AppImage 42 | 43 | echo "Build complete! AppImage is ready: Scope-${VERSION}.AppImage" 44 | -------------------------------------------------------------------------------- /.scripts/macOS.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # APPLE_CERTIFICATE - Your Apple Developer certificate 4 | # APPLE_CERTIFICATE_PASSWORD - Password for your certificate 5 | # APPLE_ID - Your Apple ID email 6 | # APPLE_ID_PASSWORD - Your Apple ID password 7 | # KEYCHAIN_PASSWORD - Password for the keychain 8 | # APP_BUNDLE_ID - Your app bundle identifier (e.g., "com.scope.app") 9 | 10 | if [ -f .env ]; then 11 | export $(cat .env | grep -v '^#' | xargs) 12 | fi 13 | 14 | set -e 15 | 16 | required_vars=("APPLE_CERTIFICATE" "APPLE_CERTIFICATE_PASSWORD" "APPLE_ID" "APPLE_ID_PASSWORD" "KEYCHAIN_PASSWORD" "APP_BUNDLE_ID") 17 | for var in "${required_vars[@]}"; do 18 | if [ -z "${!var}" ]; then 19 | exit 1 20 | fi 21 | done 22 | 23 | echo "Building Scope..." 24 | cargo build --release 25 | 26 | echo "Creating app bundle..." 27 | mkdir -p Scope.app/Contents/{MacOS,Resources} 28 | cp target/release/scope Scope.app/Contents/MacOS/ 29 | cp .github/scope-round-200.png Scope.app/Contents/Resources/scope.icns 30 | 31 | cat > Scope.app/Contents/Info.plist << EOF 32 | 33 | 34 | 35 | 36 | CFBundleName 37 | Scope 38 | CFBundleDisplayName 39 | Scope 40 | CFBundleIdentifier 41 | ${APP_BUNDLE_ID} 42 | CFBundleVersion 43 | $(grep '^version = ' src/ui/Cargo.toml | cut -d '"' -f2) 44 | CFBundlePackageType 45 | APPL 46 | CFBundleSignature 47 | ???? 48 | CFBundleExecutable 49 | scope 50 | CFBundleIconFile 51 | scope.icns 52 | LSMinimumSystemVersion 53 | 10.13 54 | NSHighResolutionCapable 55 | 56 | 57 | 58 | EOF 59 | 60 | echo "Setting up certificate..." 61 | rm -f certificate.p12 62 | echo "$APPLE_CERTIFICATE" | base64 --decode > certificate.p12 2>/dev/null 63 | security import certificate.p12 -P "$APPLE_CERTIFICATE_PASSWORD" -A 2>/dev/null 64 | 65 | SIGNING_IDENTITY=$(security find-identity -v -p codesigning | grep "Apple Development" | head -1 | awk -F '"' '{print $2}') 66 | 67 | if [ -z "$SIGNING_IDENTITY" ]; then 68 | exit 1 69 | fi 70 | 71 | echo "Using signing identity: $SIGNING_IDENTITY" 72 | echo "Signing application..." 73 | codesign --force --options runtime --sign "$SIGNING_IDENTITY" Scope.app 2>/dev/null 74 | 75 | rm -f certificate.p12 76 | 77 | echo "Creating DMG..." 78 | hdiutil create -volname "Scope" -srcfolder Scope.app -ov -format UDZO Scope.dmg 79 | 80 | echo "Signing DMG..." 81 | codesign --force --sign "$APPLE_CERTIFICATE" Scope.dmg 2>/dev/null 82 | 83 | echo "Notarizing DMG..." 84 | xcrun notarytool submit Scope.dmg --apple-id "$APPLE_ID" --password "$APPLE_ID_PASSWORD" --team-id "$APPLE_CERTIFICATE" --wait 85 | 86 | echo "Stapling notarization..." 87 | xcrun stapler staple Scope.dmg 88 | 89 | echo "Build complete! Signed and notarized DMG is ready: Scope.dmg" 90 | -------------------------------------------------------------------------------- /.scripts/windows.bat: -------------------------------------------------------------------------------- 1 | @echo off 2 | setlocal enabledelayedexpansion 3 | 4 | if exist .env ( 5 | for /f "tokens=*" %%a in (.env) do set %%a 6 | ) 7 | 8 | echo Building Scope... 9 | cargo build --release 10 | 11 | echo Creating installer directory structure... 12 | mkdir installer\bin 13 | 14 | echo Copying files... 15 | copy target\release\scope.exe installer\bin\ 16 | copy .github\scope-round-200.png installer\scope.ico 17 | 18 | echo Creating WiX files... 19 | ( 20 | echo ^ 21 | echo ^ 22 | echo ^ 24 | echo ^ 27 | echo ^ 28 | echo ^ 29 | echo ^ 30 | echo ^ 31 | echo ^ 32 | echo ^ 33 | echo ^ 34 | echo ^ 35 | echo ^ 36 | echo ^ 37 | echo ^ 38 | echo ^ 39 | echo ^ 40 | echo ^ 41 | echo ^ 42 | echo ^ 43 | echo ^ 44 | echo ^ 45 | echo ^ 46 | echo ^ 47 | echo ^ 48 | echo ^ 49 | echo ^ 50 | echo ^ 51 | echo ^ 52 | echo ^ 53 | echo ^ 54 | ) > scope.wxs 55 | 56 | echo Building MSI... 57 | candle scope.wxs 58 | light -ext WixUIExtension scope.wixobj 59 | 60 | echo Cleaning up build files... 61 | rmdir /s /q installer 62 | del scope.wxs 63 | del scope.wixobj 64 | del scope.wixpdb 65 | 66 | echo Build complete! MSI installer is ready: scope.msi 67 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [workspace] 2 | resolver = "2" 3 | members = ["src/ui", "src/cache", "src/chat", "src/discord"] 4 | 5 | [workspace.dependencies] 6 | chrono = "0.4.38" 7 | gpui = { git = "https://github.com/scopeclient/zed.git", branch = "feature/export-platform-window", default-features = false, features = [ 8 | "http_client", 9 | "font-kit", 10 | ] } 11 | components = { package = "ui", git = "https://github.com/scopeclient/components", version = "0.1.0" } 12 | reqwest_client = { git = "https://github.com/scopeclient/zed.git", branch = "feature/export-platform-window", version = "0.1.0" } 13 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published 637 | by the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . 662 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |
2 | 3 | 4 |

Scope

5 | 6 | The Discord client for power users. 7 |
8 | scopeclient.com » 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 |
No Release Downloads Yet
17 | 18 | Nightly releases can be found here. 19 | 20 |
21 | 22 | ###### Scope is in its earliest stages of development. This README will be fleshed out as the project progresses. 23 | 24 | ## Building the Project 25 | 26 | ### Prerequisites 27 | 28 | - [Rust & Cargo](https://doc.rust-lang.org/cargo/getting-started/installation.html) 29 | 30 | ### Steps 31 | 32 | 1. Clone the repository 33 | 2. Run `cargo build --release` 34 | 3. The binary will be in `./target/release/scope` 35 | 36 | ## Development Setup 37 | 38 | ### Prerequisites 39 | 40 | - [Rust & Cargo](https://doc.rust-lang.org/cargo/getting-started/installation.html) 41 | 42 | ### Steps 43 | 44 | 1. Clone the repository 45 | 2. Run `cargo run` 46 | - It's recommended to use `cargo watch -- cargo run` from [cargo-watch](https://github.com/watchexec/cargo-watch), but it's optional 47 | 48 | ## Environment Variables 49 | 50 | The binary requires the following environment variables to be set in the current working directory or in a `.env` file: 51 | 52 | - `DISCORD_TOKEN` - Your Discord token 53 | - `DEMO_CHANNEL_ID` - The channel ID to listen for messages on 54 | -------------------------------------------------------------------------------- /assets/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/scopeclient/scope/a61a2d0c31685064fade18dc53da5cc52bb6211f/assets/.gitkeep -------------------------------------------------------------------------------- /assets/brand/scope-round-200.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/scopeclient/scope/a61a2d0c31685064fade18dc53da5cc52bb6211f/assets/brand/scope-round-200.png -------------------------------------------------------------------------------- /assets/icons/a-large-small.svg: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /assets/icons/arrow-down.svg: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /assets/icons/arrow-left.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /assets/icons/arrow-right.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /assets/icons/arrow-up.svg: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /assets/icons/asterisk.svg: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /assets/icons/bell.svg: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /assets/icons/calendar.svg: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /assets/icons/check.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | -------------------------------------------------------------------------------- /assets/icons/chevron-down.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | -------------------------------------------------------------------------------- /assets/icons/chevron-left.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | -------------------------------------------------------------------------------- /assets/icons/chevron-right.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | -------------------------------------------------------------------------------- /assets/icons/chevron-up.svg: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /assets/icons/chevrons-up-down.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /assets/icons/circle-check.svg: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /assets/icons/circle-x.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /assets/icons/close.svg: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /assets/icons/copy.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /assets/icons/dash.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /assets/icons/delete.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /assets/icons/ellipsis-vertical.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /assets/icons/ellipsis.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /assets/icons/eye-off.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /assets/icons/eye.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /assets/icons/github.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /assets/icons/globe.svg: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /assets/icons/heart-off.svg: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /assets/icons/heart.svg: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /assets/icons/inbox.svg: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /assets/icons/info.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /assets/icons/loader-circle.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | -------------------------------------------------------------------------------- /assets/icons/loader.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /assets/icons/maximize.svg: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /assets/icons/menu.svg: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /assets/icons/minimize.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /assets/icons/minus.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | -------------------------------------------------------------------------------- /assets/icons/moon.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /assets/icons/palette.svg: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /assets/icons/panel-bottom-open.svg: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /assets/icons/panel-bottom.svg: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /assets/icons/panel-left-open.svg: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /assets/icons/panel-left.svg: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /assets/icons/panel-right-open.svg: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /assets/icons/panel-right.svg: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /assets/icons/plus.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /assets/icons/search.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /assets/icons/sort-ascending.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /assets/icons/sort-descending.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /assets/icons/star-off.svg: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /assets/icons/star.svg: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /assets/icons/sun.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /assets/icons/thumbs-down.svg: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /assets/icons/thumbs-up.svg: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /assets/icons/triangle-alert.svg: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /assets/icons/window-close.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /assets/icons/window-maximize.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /assets/icons/window-minimize.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /assets/icons/window-restore.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /rust-toolchain.toml: -------------------------------------------------------------------------------- 1 | [toolchain] 2 | channel = "stable" 3 | -------------------------------------------------------------------------------- /rustfmt.toml: -------------------------------------------------------------------------------- 1 | tab_spaces = 2 2 | max_width = 150 3 | chain_width = 150 4 | imports_layout = "Horizontal" 5 | -------------------------------------------------------------------------------- /shell.nix: -------------------------------------------------------------------------------- 1 | { pkgs ? import {} }: 2 | 3 | pkgs.mkShell { 4 | nativeBuildInputs = [ pkgs.pkg-config ]; 5 | buildInputs = with pkgs; [ 6 | libxkbcommon 7 | xorg.libX11 8 | vulkan-loader 9 | vulkan-validation-layers 10 | vulkan-headers 11 | ]; 12 | 13 | shellHook = '' 14 | export VK_LAYER_PATH="${pkgs.vulkan-validation-layers}/share/vulkan/explicit_layer.d" 15 | export LD_LIBRARY_PATH="${pkgs.vulkan-loader}/lib:$LD_LIBRARY_PATH" 16 | ''; 17 | } 18 | -------------------------------------------------------------------------------- /src/cache/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "scope-backend-cache" 3 | version = "0.1.0" 4 | edition = "2021" 5 | license = "AGPL-3.0-or-later" 6 | 7 | [dependencies] 8 | gpui.workspace = true 9 | rand = "0.8.5" 10 | scope-chat = { version = "0.1.0", path = "../chat" } 11 | tokio = "1.41.1" 12 | -------------------------------------------------------------------------------- /src/cache/src/async_list/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod refcache; 2 | pub mod refcacheslice; 3 | pub mod tests; 4 | 5 | use std::collections::HashMap; 6 | 7 | use refcache::CacheReferences; 8 | use refcacheslice::Exists; 9 | use scope_chat::async_list::{AsyncListIndex, AsyncListItem, AsyncListResult}; 10 | 11 | pub struct AsyncListCache { 12 | cache_refs: CacheReferences, 13 | cache_map: HashMap, 14 | } 15 | 16 | impl Default for AsyncListCache { 17 | fn default() -> Self { 18 | Self::new() 19 | } 20 | } 21 | 22 | impl AsyncListCache { 23 | pub fn new() -> Self { 24 | Self { 25 | cache_refs: CacheReferences::new(), 26 | cache_map: HashMap::new(), 27 | } 28 | } 29 | 30 | pub fn append_bottom(&mut self, value: I) { 31 | let identifier = value.get_list_identifier(); 32 | 33 | self.cache_refs.append_bottom(identifier.clone()); 34 | self.cache_map.insert(identifier, value); 35 | } 36 | 37 | pub fn insert(&mut self, index: AsyncListIndex, value: I, is_top: bool, is_bottom: bool) { 38 | let identifier = value.get_list_identifier(); 39 | 40 | self.cache_map.insert(identifier.clone(), value); 41 | self.cache_refs.insert(index, identifier.clone(), is_top, is_bottom); 42 | } 43 | 44 | /// you mut **KNOW** that the item you are inserting is not: 45 | /// - directly next to (Before or After) **any** item in the list 46 | /// - the first or last item in the list 47 | pub fn insert_detached(&mut self, value: I) { 48 | let identifier = value.get_list_identifier(); 49 | 50 | self.cache_map.insert(identifier.clone(), value); 51 | self.cache_refs.insert_detached(identifier); 52 | } 53 | 54 | pub fn bounded_at_top_by(&self) -> Option { 55 | self.cache_refs.top_bound() 56 | } 57 | 58 | pub fn bounded_at_bottom_by(&self) -> Option { 59 | self.cache_refs.bottom_bound() 60 | } 61 | 62 | pub fn get(&self, index: AsyncListIndex) -> Exists> { 63 | let cache_result = self.cache_refs.get(index.clone()); 64 | 65 | if let Exists::Yes(cache_result) = cache_result { 66 | let content = self.cache_map.get(&cache_result).unwrap().clone(); 67 | let is_top = self.cache_refs.top_bound().map(|v| v == content.get_list_identifier()).unwrap_or(false); 68 | let is_bottom = self.cache_refs.bottom_bound().map(|v| v == content.get_list_identifier()).unwrap_or(false); 69 | 70 | return Exists::Yes(AsyncListResult { content, is_top, is_bottom }); 71 | }; 72 | 73 | if let Exists::No = cache_result { 74 | return Exists::No; 75 | } 76 | 77 | Exists::Unknown 78 | } 79 | 80 | pub fn find(&self, identifier: &I::Identifier) -> Option { 81 | self.cache_map.get(identifier).cloned() 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /src/cache/src/async_list/refcache.rs: -------------------------------------------------------------------------------- 1 | use std::{collections::HashMap, fmt::Debug}; 2 | 3 | use scope_chat::async_list::AsyncListIndex; 4 | 5 | use super::refcacheslice::{self, CacheReferencesSlice, Exists}; 6 | 7 | pub struct CacheReferences { 8 | // dense segments are unordered (spooky!) slices of content we do! know about. 9 | // the u64 in the hashmap represents a kind of "segment identifier" 10 | dense_segments: HashMap>, 11 | 12 | top_bounded_identifier: Option, 13 | bottom_bounded_identifier: Option, 14 | } 15 | 16 | impl Default for CacheReferences { 17 | fn default() -> Self { 18 | Self::new() 19 | } 20 | } 21 | 22 | impl CacheReferences { 23 | pub fn new() -> Self { 24 | Self { 25 | dense_segments: HashMap::new(), 26 | top_bounded_identifier: None, 27 | bottom_bounded_identifier: None, 28 | } 29 | } 30 | 31 | pub fn append_bottom(&mut self, identifier: I) { 32 | let mut id = None; 33 | 34 | for (segment_id, segment) in self.dense_segments.iter() { 35 | if let Exists::Yes(_) = segment.get(AsyncListIndex::RelativeToBottom(0)) { 36 | if id.is_some() { 37 | panic!("There should only be one bottom bound segment"); 38 | } 39 | 40 | id = Some(*segment_id) 41 | } 42 | } 43 | 44 | if let Some(id) = id { 45 | self.dense_segments.get_mut(&id).unwrap().append_bottom(identifier); 46 | } else { 47 | self.insert(AsyncListIndex::RelativeToBottom(0), identifier, false, true); 48 | } 49 | } 50 | 51 | pub fn top_bound(&self) -> Option { 52 | let index = self.top_bounded_identifier?; 53 | let top_bound = self.dense_segments.get(&index).unwrap(); 54 | 55 | assert!(top_bound.is_bounded_at_top); 56 | 57 | Some(top_bound.item_references.first().unwrap().clone()) 58 | } 59 | 60 | pub fn bottom_bound(&self) -> Option { 61 | let index = self.bottom_bounded_identifier?; 62 | let bottom_bound = self.dense_segments.get(&index).unwrap(); 63 | 64 | assert!(bottom_bound.is_bounded_at_bottom); 65 | 66 | Some(bottom_bound.item_references.last().unwrap().clone()) 67 | } 68 | 69 | pub fn get(&self, index: AsyncListIndex) -> Exists { 70 | for segment in self.dense_segments.values() { 71 | let result = segment.get(index.clone()); 72 | 73 | if let Exists::Yes(value) = result { 74 | return Exists::Yes(value); 75 | } else if let Exists::No = result { 76 | return Exists::No; 77 | } 78 | } 79 | 80 | Exists::Unknown 81 | } 82 | 83 | /// you mut **KNOW** that the item you are inserting is not: 84 | /// - directly next to (Before or After) **any** item in the list 85 | /// - the first or last item in the list 86 | pub fn insert_detached(&mut self, item: I) { 87 | self.dense_segments.insert( 88 | rand::random(), 89 | CacheReferencesSlice { 90 | is_bounded_at_top: false, 91 | is_bounded_at_bottom: false, 92 | 93 | item_references: vec![item], 94 | }, 95 | ); 96 | } 97 | 98 | pub fn insert(&mut self, index: AsyncListIndex, item: I, is_top: bool, is_bottom: bool) { 99 | // insert routine is really complex: 100 | // an insert can "join" together 2 segments 101 | // an insert can append to a segment 102 | // or an insert can construct a new segment 103 | 104 | let mut segments = vec![]; 105 | 106 | for (i, segment) in self.dense_segments.iter() { 107 | if let Some(position) = segment.can_insert(index.clone()) { 108 | segments.push((position, *i)); 109 | } 110 | } 111 | 112 | if segments.is_empty() { 113 | let id = rand::random(); 114 | 115 | self.dense_segments.insert( 116 | id, 117 | CacheReferencesSlice { 118 | is_bounded_at_top: is_top, 119 | is_bounded_at_bottom: is_bottom, 120 | 121 | item_references: vec![item], 122 | }, 123 | ); 124 | 125 | if is_bottom { 126 | self.bottom_bounded_identifier = Some(id); 127 | } 128 | 129 | if is_top { 130 | self.top_bounded_identifier = Some(id); 131 | } 132 | } else if segments.len() == 1 { 133 | self.dense_segments.get_mut(&segments[0].1).unwrap().insert(index.clone(), item, is_bottom, is_top); 134 | 135 | if is_top { 136 | self.top_bounded_identifier = Some(segments[0].1) 137 | } 138 | if is_bottom { 139 | self.bottom_bounded_identifier = Some(segments[0].1) 140 | } 141 | } else if segments.len() == 2 { 142 | assert!(!is_top); 143 | assert!(!is_bottom); 144 | 145 | let (li, ri) = match (segments[0], segments[1]) { 146 | ((refcacheslice::Position::After, lp), (refcacheslice::Position::Before, rp)) => (lp, rp), 147 | ((refcacheslice::Position::Before, rp), (refcacheslice::Position::After, lp)) => (lp, rp), 148 | 149 | _ => panic!("How are there two candidates that aren't (Before, After) or (After, Before)?"), 150 | }; 151 | 152 | let (left, right) = if li < ri { 153 | let right = self.dense_segments.remove(&ri).unwrap(); 154 | let left = self.dense_segments.remove(&li).unwrap(); 155 | 156 | (left, right) 157 | } else { 158 | let left = self.dense_segments.remove(&li).unwrap(); 159 | let right = self.dense_segments.remove(&ri).unwrap(); 160 | 161 | (left, right) 162 | }; 163 | 164 | let mut merged = left.item_references; 165 | 166 | merged.push(item); 167 | 168 | merged.extend(right.item_references); 169 | 170 | let id = rand::random(); 171 | 172 | self.dense_segments.insert( 173 | id, 174 | CacheReferencesSlice { 175 | is_bounded_at_top: left.is_bounded_at_top, 176 | is_bounded_at_bottom: right.is_bounded_at_bottom, 177 | 178 | item_references: merged, 179 | }, 180 | ); 181 | 182 | if left.is_bounded_at_top { 183 | self.top_bounded_identifier = Some(id); 184 | } 185 | 186 | if right.is_bounded_at_bottom { 187 | self.bottom_bounded_identifier = Some(id); 188 | } 189 | } else { 190 | panic!("Impossible state") 191 | } 192 | } 193 | } 194 | 195 | impl Debug for CacheReferences { 196 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 197 | f.debug_struct("CacheReferences") 198 | .field("top_bounded_segment", &self.top_bounded_identifier) 199 | .field("bottom_bounded_segment", &self.bottom_bounded_identifier) 200 | .field("dense_segments", &self.dense_segments) 201 | .finish() 202 | } 203 | } 204 | -------------------------------------------------------------------------------- /src/cache/src/async_list/refcacheslice.rs: -------------------------------------------------------------------------------- 1 | use std::fmt::Debug; 2 | 3 | use scope_chat::async_list::AsyncListIndex; 4 | 5 | pub struct CacheReferencesSlice { 6 | pub is_bounded_at_top: bool, 7 | pub is_bounded_at_bottom: bool, 8 | 9 | // the vec's 0th item is the top, and it's last item is the bottom 10 | // the vec MUST NOT be empty. 11 | pub(super) item_references: Vec, 12 | } 13 | 14 | pub enum Exists { 15 | Yes(T), 16 | No, 17 | Unknown, 18 | } 19 | 20 | impl CacheReferencesSlice { 21 | fn find_index_of(&self, item: I) -> Option { 22 | for (haystack, index) in self.item_references.iter().zip(0..) { 23 | if *haystack == item { 24 | return Some(index); 25 | } 26 | } 27 | 28 | None 29 | } 30 | 31 | fn get_index(&self, index: AsyncListIndex) -> Option { 32 | match index { 33 | AsyncListIndex::RelativeToBottom(count) if self.is_bounded_at_bottom => Some((self.item_references.len() as isize) - (1 + (count as isize))), 34 | 35 | AsyncListIndex::RelativeToTop(count) if self.is_bounded_at_top => Some(count as isize), 36 | 37 | AsyncListIndex::After(item) => Some((self.find_index_of(item)? as isize) + 1), 38 | 39 | AsyncListIndex::Before(item) => Some((self.find_index_of(item)? as isize) - 1), 40 | 41 | _ => None, 42 | } 43 | } 44 | 45 | pub fn append_bottom(&mut self, index: I) { 46 | assert!(self.is_bounded_at_bottom); 47 | 48 | self.item_references.push(index); 49 | } 50 | 51 | pub fn get(&self, index: AsyncListIndex) -> Exists { 52 | let index = self.get_index(index); 53 | 54 | if let Some(index) = index { 55 | if index < 0 { 56 | if self.is_bounded_at_top { 57 | return Exists::No; 58 | } else { 59 | return Exists::Unknown; 60 | } 61 | } 62 | 63 | if index as usize >= self.item_references.len() { 64 | if self.is_bounded_at_bottom { 65 | return Exists::No; 66 | } else { 67 | return Exists::Unknown; 68 | } 69 | } 70 | 71 | Exists::Yes(self.item_references.get(index as usize).cloned().unwrap()) 72 | } else { 73 | Exists::Unknown 74 | } 75 | } 76 | 77 | pub fn can_insert(&self, index: AsyncListIndex) -> Option { 78 | match index { 79 | AsyncListIndex::After(item) => self.find_index_of(item).map(|idx| { 80 | if idx == (self.item_references.len() - 1) { 81 | Position::After 82 | } else { 83 | Position::Inside 84 | } 85 | }), 86 | AsyncListIndex::Before(item) => self.find_index_of(item).map(|idx| if idx == 0 { Position::Before } else { Position::Inside }), 87 | 88 | _ => panic!("TODO: Figure out what well-defined behaviour for what should occur for inserting relative to top or bottom"), 89 | } 90 | } 91 | 92 | pub fn insert(&mut self, index: AsyncListIndex, value: I, is_bottom: bool, is_top: bool) { 93 | if is_bottom { 94 | self.is_bounded_at_bottom = true 95 | } 96 | if is_top { 97 | self.is_bounded_at_top = true 98 | } 99 | 100 | match index { 101 | AsyncListIndex::After(item) => { 102 | let i = self.find_index_of(item).unwrap(); 103 | 104 | self.item_references.insert(i + 1, value); 105 | } 106 | AsyncListIndex::Before(item) => { 107 | let i = self.find_index_of(item).unwrap(); 108 | 109 | self.item_references.insert(i, value); 110 | } 111 | 112 | _ => panic!("TODO: Figure out what well-defined behaviour for what should occur for inserting relative to top or bottom"), 113 | } 114 | } 115 | } 116 | 117 | impl Debug for CacheReferencesSlice { 118 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 119 | f.debug_struct("CacheReferences") 120 | .field("is_bounded_at_top", &self.is_bounded_at_top) 121 | .field("is_bounded_at_bottom", &self.is_bounded_at_bottom) 122 | .field("item_references", &self.item_references) 123 | .finish() 124 | } 125 | } 126 | 127 | #[derive(Clone, Copy)] 128 | pub enum Position { 129 | /// Closer to the top 130 | Before, 131 | /// Closer to the bottom 132 | After, 133 | Inside, 134 | } 135 | -------------------------------------------------------------------------------- /src/cache/src/async_list/tests.rs: -------------------------------------------------------------------------------- 1 | use std::fmt::Debug; 2 | 3 | #[allow(unused_imports)] 4 | use scope_chat::async_list::{AsyncListIndex, AsyncListItem, AsyncListResult}; 5 | 6 | #[allow(unused_imports)] 7 | use crate::async_list::{refcacheslice::Exists, AsyncListCache}; 8 | 9 | #[allow(dead_code)] 10 | #[derive(Clone, Copy, PartialEq, Eq, Debug)] 11 | struct ListItem(i64); 12 | 13 | impl AsyncListItem for ListItem { 14 | type Identifier = i64; 15 | 16 | fn get_list_identifier(&self) -> Self::Identifier { 17 | self.0 18 | } 19 | } 20 | 21 | #[allow(dead_code)] 22 | fn assert_query_exists(result: Exists>, item: I, is_top_in: bool, is_bottom_in: bool) { 23 | if let Exists::Yes(AsyncListResult { content, is_top, is_bottom }) = result { 24 | assert_eq!(content, item); 25 | assert_eq!(is_top, is_top_in); 26 | assert_eq!(is_bottom, is_bottom_in); 27 | } else { 28 | panic!("Expected eq yes") 29 | } 30 | } 31 | 32 | #[test] 33 | pub fn cache_can_append_bottom_in_unbounded_state() { 34 | let mut cache = AsyncListCache::::new(); 35 | 36 | cache.append_bottom(ListItem(0)); 37 | 38 | assert_eq!(cache.bounded_at_bottom_by(), Some(0)); 39 | assert_eq!(cache.find(&0), Some(ListItem(0))); 40 | assert_query_exists(cache.get(AsyncListIndex::RelativeToBottom(0)), ListItem(0), false, true); 41 | } 42 | 43 | #[test] 44 | pub fn cache_can_append_bottom_many_times_successfully() { 45 | let mut cache = AsyncListCache::::new(); 46 | 47 | cache.append_bottom(ListItem(0)); 48 | 49 | assert_eq!(cache.bounded_at_bottom_by(), Some(0)); 50 | assert_eq!(cache.find(&0), Some(ListItem(0))); 51 | assert_query_exists(cache.get(AsyncListIndex::RelativeToBottom(0)), ListItem(0), false, true); 52 | 53 | cache.append_bottom(ListItem(1)); 54 | 55 | assert_eq!(cache.bounded_at_bottom_by(), Some(1)); 56 | assert_eq!(cache.find(&1), Some(ListItem(1))); 57 | assert_eq!(cache.find(&0), Some(ListItem(0))); 58 | assert_query_exists(cache.get(AsyncListIndex::RelativeToBottom(0)), ListItem(1), false, true); 59 | assert_query_exists(cache.get(AsyncListIndex::RelativeToBottom(1)), ListItem(0), false, false); 60 | assert_query_exists(cache.get(AsyncListIndex::Before(1)), ListItem(0), false, false); 61 | assert_query_exists(cache.get(AsyncListIndex::After(0)), ListItem(1), false, true); 62 | 63 | cache.append_bottom(ListItem(2)); 64 | 65 | assert_eq!(cache.bounded_at_bottom_by(), Some(2)); 66 | assert_eq!(cache.find(&2), Some(ListItem(2))); 67 | assert_eq!(cache.find(&1), Some(ListItem(1))); 68 | assert_eq!(cache.find(&0), Some(ListItem(0))); 69 | assert_query_exists(cache.get(AsyncListIndex::RelativeToBottom(0)), ListItem(2), false, true); 70 | assert_query_exists(cache.get(AsyncListIndex::RelativeToBottom(1)), ListItem(1), false, false); 71 | assert_query_exists(cache.get(AsyncListIndex::RelativeToBottom(2)), ListItem(0), false, false); 72 | assert_query_exists(cache.get(AsyncListIndex::Before(1)), ListItem(0), false, false); 73 | assert_query_exists(cache.get(AsyncListIndex::Before(2)), ListItem(1), false, false); 74 | assert_query_exists(cache.get(AsyncListIndex::After(0)), ListItem(1), false, false); 75 | assert_query_exists(cache.get(AsyncListIndex::After(1)), ListItem(2), false, true); 76 | } 77 | 78 | #[test] 79 | pub fn cache_can_work_unlocated() { 80 | let mut cache = AsyncListCache::::new(); 81 | 82 | cache.insert_detached(ListItem(0)); 83 | assert_eq!(cache.find(&0), Some(ListItem(0))); 84 | 85 | cache.insert(AsyncListIndex::After(0), ListItem(2), false, false); 86 | 87 | assert_eq!(cache.find(&0), Some(ListItem(0))); 88 | assert_eq!(cache.find(&2), Some(ListItem(2))); 89 | assert_query_exists(cache.get(AsyncListIndex::After(0)), ListItem(2), false, false); 90 | assert_query_exists(cache.get(AsyncListIndex::Before(2)), ListItem(0), false, false); 91 | 92 | cache.insert(AsyncListIndex::Before(0), ListItem(-2), false, false); 93 | assert_eq!(cache.find(&-2), Some(ListItem(-2))); 94 | assert_eq!(cache.find(&0), Some(ListItem(0))); 95 | assert_eq!(cache.find(&2), Some(ListItem(2))); 96 | assert_query_exists(cache.get(AsyncListIndex::After(0)), ListItem(2), false, false); 97 | assert_query_exists(cache.get(AsyncListIndex::Before(2)), ListItem(0), false, false); 98 | assert_query_exists(cache.get(AsyncListIndex::Before(0)), ListItem(-2), false, false); 99 | assert_query_exists(cache.get(AsyncListIndex::After(-2)), ListItem(0), false, false); 100 | } 101 | 102 | #[test] 103 | pub fn cache_can_insert_between() { 104 | let mut cache = AsyncListCache::::new(); 105 | 106 | cache.insert_detached(ListItem(0)); 107 | assert_eq!(cache.find(&0), Some(ListItem(0))); 108 | 109 | cache.insert(AsyncListIndex::After(0), ListItem(2), false, false); 110 | 111 | assert_eq!(cache.find(&0), Some(ListItem(0))); 112 | assert_eq!(cache.find(&2), Some(ListItem(2))); 113 | assert_query_exists(cache.get(AsyncListIndex::After(0)), ListItem(2), false, false); 114 | assert_query_exists(cache.get(AsyncListIndex::Before(2)), ListItem(0), false, false); 115 | 116 | cache.insert(AsyncListIndex::Before(0), ListItem(-2), false, false); 117 | assert_eq!(cache.find(&-2), Some(ListItem(-2))); 118 | assert_eq!(cache.find(&0), Some(ListItem(0))); 119 | assert_eq!(cache.find(&2), Some(ListItem(2))); 120 | assert_query_exists(cache.get(AsyncListIndex::After(0)), ListItem(2), false, false); 121 | assert_query_exists(cache.get(AsyncListIndex::Before(2)), ListItem(0), false, false); 122 | assert_query_exists(cache.get(AsyncListIndex::Before(0)), ListItem(-2), false, false); 123 | assert_query_exists(cache.get(AsyncListIndex::After(-2)), ListItem(0), false, false); 124 | 125 | cache.insert(AsyncListIndex::After(-2), ListItem(-1), false, false); 126 | assert_eq!(cache.find(&-2), Some(ListItem(-2))); 127 | assert_eq!(cache.find(&-1), Some(ListItem(-1))); 128 | assert_eq!(cache.find(&0), Some(ListItem(0))); 129 | assert_eq!(cache.find(&2), Some(ListItem(2))); 130 | assert_query_exists(cache.get(AsyncListIndex::After(0)), ListItem(2), false, false); 131 | assert_query_exists(cache.get(AsyncListIndex::Before(2)), ListItem(0), false, false); 132 | assert_query_exists(cache.get(AsyncListIndex::Before(0)), ListItem(-1), false, false); 133 | assert_query_exists(cache.get(AsyncListIndex::Before(-1)), ListItem(-2), false, false); 134 | assert_query_exists(cache.get(AsyncListIndex::After(-2)), ListItem(-1), false, false); 135 | assert_query_exists(cache.get(AsyncListIndex::After(-1)), ListItem(0), false, false); 136 | 137 | cache.insert(AsyncListIndex::Before(2), ListItem(1), false, false); 138 | assert_eq!(cache.find(&-2), Some(ListItem(-2))); 139 | assert_eq!(cache.find(&-1), Some(ListItem(-1))); 140 | assert_eq!(cache.find(&0), Some(ListItem(0))); 141 | assert_eq!(cache.find(&1), Some(ListItem(1))); 142 | assert_eq!(cache.find(&2), Some(ListItem(2))); 143 | assert_query_exists(cache.get(AsyncListIndex::After(1)), ListItem(2), false, false); 144 | assert_query_exists(cache.get(AsyncListIndex::After(0)), ListItem(1), false, false); 145 | assert_query_exists(cache.get(AsyncListIndex::Before(2)), ListItem(1), false, false); 146 | assert_query_exists(cache.get(AsyncListIndex::Before(1)), ListItem(0), false, false); 147 | assert_query_exists(cache.get(AsyncListIndex::Before(0)), ListItem(-1), false, false); 148 | assert_query_exists(cache.get(AsyncListIndex::Before(-1)), ListItem(-2), false, false); 149 | assert_query_exists(cache.get(AsyncListIndex::After(-2)), ListItem(-1), false, false); 150 | assert_query_exists(cache.get(AsyncListIndex::After(-1)), ListItem(0), false, false); 151 | 152 | let mut cache = AsyncListCache::::new(); 153 | 154 | cache.insert_detached(ListItem(0)); 155 | assert_eq!(cache.find(&0), Some(ListItem(0))); 156 | 157 | cache.insert(AsyncListIndex::After(0), ListItem(2), false, false); 158 | 159 | assert_eq!(cache.find(&0), Some(ListItem(0))); 160 | assert_eq!(cache.find(&2), Some(ListItem(2))); 161 | assert_query_exists(cache.get(AsyncListIndex::After(0)), ListItem(2), false, false); 162 | assert_query_exists(cache.get(AsyncListIndex::Before(2)), ListItem(0), false, false); 163 | 164 | cache.insert(AsyncListIndex::Before(0), ListItem(-2), false, false); 165 | assert_eq!(cache.find(&-2), Some(ListItem(-2))); 166 | assert_eq!(cache.find(&0), Some(ListItem(0))); 167 | assert_eq!(cache.find(&2), Some(ListItem(2))); 168 | assert_query_exists(cache.get(AsyncListIndex::After(0)), ListItem(2), false, false); 169 | assert_query_exists(cache.get(AsyncListIndex::Before(2)), ListItem(0), false, false); 170 | assert_query_exists(cache.get(AsyncListIndex::Before(0)), ListItem(-2), false, false); 171 | assert_query_exists(cache.get(AsyncListIndex::After(-2)), ListItem(0), false, false); 172 | 173 | cache.insert(AsyncListIndex::Before(0), ListItem(-1), false, false); 174 | assert_eq!(cache.find(&-2), Some(ListItem(-2))); 175 | assert_eq!(cache.find(&-1), Some(ListItem(-1))); 176 | assert_eq!(cache.find(&0), Some(ListItem(0))); 177 | assert_eq!(cache.find(&2), Some(ListItem(2))); 178 | assert_query_exists(cache.get(AsyncListIndex::After(0)), ListItem(2), false, false); 179 | assert_query_exists(cache.get(AsyncListIndex::Before(2)), ListItem(0), false, false); 180 | assert_query_exists(cache.get(AsyncListIndex::Before(0)), ListItem(-1), false, false); 181 | assert_query_exists(cache.get(AsyncListIndex::Before(-1)), ListItem(-2), false, false); 182 | assert_query_exists(cache.get(AsyncListIndex::After(-2)), ListItem(-1), false, false); 183 | assert_query_exists(cache.get(AsyncListIndex::After(-1)), ListItem(0), false, false); 184 | 185 | cache.insert(AsyncListIndex::After(0), ListItem(1), false, false); 186 | assert_eq!(cache.find(&-2), Some(ListItem(-2))); 187 | assert_eq!(cache.find(&-1), Some(ListItem(-1))); 188 | assert_eq!(cache.find(&0), Some(ListItem(0))); 189 | assert_eq!(cache.find(&1), Some(ListItem(1))); 190 | assert_eq!(cache.find(&2), Some(ListItem(2))); 191 | assert_query_exists(cache.get(AsyncListIndex::After(1)), ListItem(2), false, false); 192 | assert_query_exists(cache.get(AsyncListIndex::After(0)), ListItem(1), false, false); 193 | assert_query_exists(cache.get(AsyncListIndex::Before(2)), ListItem(1), false, false); 194 | assert_query_exists(cache.get(AsyncListIndex::Before(1)), ListItem(0), false, false); 195 | assert_query_exists(cache.get(AsyncListIndex::Before(0)), ListItem(-1), false, false); 196 | assert_query_exists(cache.get(AsyncListIndex::Before(-1)), ListItem(-2), false, false); 197 | assert_query_exists(cache.get(AsyncListIndex::After(-2)), ListItem(-1), false, false); 198 | assert_query_exists(cache.get(AsyncListIndex::After(-1)), ListItem(0), false, false); 199 | } 200 | 201 | #[test] 202 | pub fn cache_can_merge() { 203 | let mut cache = AsyncListCache::::new(); 204 | 205 | cache.insert_detached(ListItem(0)); 206 | assert_eq!(cache.find(&0), Some(ListItem(0))); 207 | 208 | cache.insert(AsyncListIndex::After(0), ListItem(1), false, false); 209 | 210 | assert_eq!(cache.find(&0), Some(ListItem(0))); 211 | assert_eq!(cache.find(&1), Some(ListItem(1))); 212 | assert_query_exists(cache.get(AsyncListIndex::After(0)), ListItem(1), false, false); 213 | assert_query_exists(cache.get(AsyncListIndex::Before(1)), ListItem(0), false, false); 214 | 215 | cache.insert_detached(ListItem(4)); 216 | assert_eq!(cache.find(&4), Some(ListItem(4))); 217 | 218 | cache.insert(AsyncListIndex::Before(4), ListItem(3), false, false); 219 | 220 | assert_eq!(cache.find(&4), Some(ListItem(4))); 221 | assert_eq!(cache.find(&3), Some(ListItem(3))); 222 | assert_query_exists(cache.get(AsyncListIndex::After(3)), ListItem(4), false, false); 223 | assert_query_exists(cache.get(AsyncListIndex::Before(4)), ListItem(3), false, false); 224 | 225 | cache.insert(AsyncListIndex::Before(3), ListItem(2), false, false); 226 | cache.insert(AsyncListIndex::After(1), ListItem(2), false, false); 227 | 228 | assert_eq!(cache.find(&4), Some(ListItem(4))); 229 | assert_eq!(cache.find(&3), Some(ListItem(3))); 230 | assert_eq!(cache.find(&2), Some(ListItem(2))); 231 | assert_eq!(cache.find(&1), Some(ListItem(1))); 232 | assert_eq!(cache.find(&0), Some(ListItem(0))); 233 | assert_query_exists(cache.get(AsyncListIndex::After(3)), ListItem(4), false, false); 234 | assert_query_exists(cache.get(AsyncListIndex::Before(4)), ListItem(3), false, false); 235 | assert_query_exists(cache.get(AsyncListIndex::After(2)), ListItem(3), false, false); 236 | assert_query_exists(cache.get(AsyncListIndex::Before(3)), ListItem(2), false, false); 237 | assert_query_exists(cache.get(AsyncListIndex::After(1)), ListItem(2), false, false); 238 | assert_query_exists(cache.get(AsyncListIndex::Before(2)), ListItem(1), false, false); 239 | assert_query_exists(cache.get(AsyncListIndex::After(0)), ListItem(1), false, false); 240 | assert_query_exists(cache.get(AsyncListIndex::Before(1)), ListItem(0), false, false); 241 | } 242 | -------------------------------------------------------------------------------- /src/cache/src/lib.rs: -------------------------------------------------------------------------------- 1 | pub mod async_list; 2 | -------------------------------------------------------------------------------- /src/chat/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "scope-chat" 3 | version = "0.1.0" 4 | edition = "2021" 5 | license = "AGPL-3.0-or-later" 6 | 7 | [dependencies] 8 | tokio = "1.41.1" 9 | chrono.workspace = true 10 | gpui.workspace = true 11 | -------------------------------------------------------------------------------- /src/chat/src/async_list.rs: -------------------------------------------------------------------------------- 1 | use std::{fmt::Debug, future::Future, hash::Hash, sync::Arc}; 2 | 3 | pub trait AsyncList { 4 | type Content: AsyncListItem; 5 | 6 | fn bounded_at_top_by(&self) -> impl Future::Identifier>>; 7 | fn get( 8 | &self, 9 | index: AsyncListIndex<::Identifier>, 10 | ) -> impl Future>> + Send; 11 | fn find(&self, identifier: &::Identifier) -> impl Future>; 12 | fn bounded_at_bottom_by(&self) -> impl Future::Identifier>>; 13 | } 14 | 15 | impl AsyncList for Arc { 16 | type Content = L::Content; 17 | 18 | fn bounded_at_bottom_by(&self) -> impl Future::Identifier>> { 19 | (**self).bounded_at_bottom_by() 20 | } 21 | 22 | fn bounded_at_top_by(&self) -> impl Future::Identifier>> { 23 | (**self).bounded_at_top_by() 24 | } 25 | 26 | fn find(&self, identifier: &::Identifier) -> impl Future> { 27 | (**self).find(identifier) 28 | } 29 | 30 | fn get( 31 | &self, 32 | index: AsyncListIndex<::Identifier>, 33 | ) -> impl Future>> + Send { 34 | (**self).get(index) 35 | } 36 | } 37 | 38 | pub trait AsyncListItem: Clone { 39 | type Identifier: Eq + Hash + Clone + Send + Debug; 40 | 41 | fn get_list_identifier(&self) -> Self::Identifier; 42 | } 43 | 44 | #[derive(Clone)] 45 | pub enum AsyncListIndex { 46 | RelativeToTop(usize), 47 | /// Before is closer to the top 48 | Before(I), 49 | 50 | RelativeToBottom(usize), 51 | /// After is closer to the bottom 52 | After(I), 53 | } 54 | 55 | impl Copy for AsyncListIndex {} 56 | 57 | impl Debug for AsyncListIndex { 58 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 59 | match self { 60 | Self::After(i) => f.debug_tuple("AsyncListIndex::After").field(i).finish()?, 61 | Self::Before(i) => f.debug_tuple("AsyncListIndex::Before").field(i).finish()?, 62 | Self::RelativeToTop(i) => f.debug_tuple("AsyncListIndex::RelativeToTop").field(i).finish()?, 63 | Self::RelativeToBottom(i) => f.debug_tuple("AsyncListIndex::RelativeToBottom").field(i).finish()?, 64 | }; 65 | 66 | Ok(()) 67 | } 68 | } 69 | 70 | #[derive(Clone)] 71 | pub struct AsyncListResult { 72 | pub content: T, 73 | pub is_top: bool, 74 | pub is_bottom: bool, 75 | } 76 | 77 | impl Debug for AsyncListResult { 78 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 79 | f.debug_struct("AsyncListResult").field("content", &self.content).field("is_top", &self.is_top).field("is_bottom", &self.is_bottom).finish() 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /src/chat/src/channel.rs: -------------------------------------------------------------------------------- 1 | use std::{fmt::Debug, sync::Arc}; 2 | 3 | use tokio::sync::broadcast; 4 | 5 | use crate::{async_list::AsyncList, message::Message}; 6 | 7 | pub trait Channel: AsyncList + Send + Sync + Clone { 8 | type Message: Message; 9 | type Identifier: Sized + Copy + Clone + Debug + Eq + PartialEq; 10 | 11 | fn get_receiver(&self) -> broadcast::Receiver; 12 | 13 | fn send_message(&self, content: String, nonce: String) -> Self::Message; 14 | 15 | fn get_identifier(&self) -> Self::Identifier; 16 | } 17 | 18 | impl Channel for Arc { 19 | type Identifier = C::Identifier; 20 | type Message = C::Message; 21 | 22 | fn get_identifier(&self) -> Self::Identifier { 23 | (**self).get_identifier() 24 | } 25 | 26 | fn get_receiver(&self) -> broadcast::Receiver { 27 | (**self).get_receiver() 28 | } 29 | 30 | fn send_message(&self, content: String, nonce: String) -> Self::Message { 31 | (**self).send_message(content, nonce) 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/chat/src/client.rs: -------------------------------------------------------------------------------- 1 | use std::{fmt::Debug, future::Future}; 2 | 3 | use crate::channel::Channel; 4 | 5 | pub trait ClientConstructor { 6 | type ConstructorArguments; 7 | type ConstructorFailure; 8 | 9 | fn construct(args: Self::ConstructorArguments) -> impl Future>; 10 | } 11 | 12 | pub trait Client { 13 | type Identifier: Sized + Copy + Clone + Debug + Eq + PartialEq; 14 | type Channel: Channel; 15 | 16 | fn channel(identifier: Self::Identifier) -> impl Future>; 17 | } 18 | -------------------------------------------------------------------------------- /src/chat/src/lib.rs: -------------------------------------------------------------------------------- 1 | pub mod async_list; 2 | pub mod channel; 3 | pub mod client; 4 | pub mod message; 5 | -------------------------------------------------------------------------------- /src/chat/src/message.rs: -------------------------------------------------------------------------------- 1 | use std::fmt::Debug; 2 | 3 | use chrono::{DateTime, Utc}; 4 | use gpui::{IntoElement, Render, View, WindowContext}; 5 | 6 | use crate::async_list::AsyncListItem; 7 | 8 | pub trait Message: Clone + AsyncListItem + Send { 9 | type Identifier: Sized + Copy + Clone + Debug + Eq + PartialEq; 10 | type Author: MessageAuthor::Identifier>; 11 | type Content: Render; 12 | 13 | fn get_author(&self) -> Self::Author; 14 | fn get_content(&self, cx: &mut WindowContext) -> View; 15 | fn get_identifier(&self) -> Option<::Identifier>; 16 | fn get_nonce(&self) -> impl PartialEq; 17 | fn should_group(&self, previous: &Self) -> bool; 18 | fn get_timestamp(&self) -> Option>; 19 | } 20 | 21 | #[derive(Debug, Clone, Copy)] 22 | pub struct IconRenderConfig { 23 | size: usize, 24 | } 25 | 26 | impl Default for IconRenderConfig { 27 | fn default() -> Self { 28 | IconRenderConfig { size: 1024 } 29 | } 30 | } 31 | 32 | impl IconRenderConfig { 33 | pub fn small() -> Self { 34 | IconRenderConfig { size: 32 } 35 | } 36 | 37 | pub fn with_size(mut self, size: usize) -> IconRenderConfig { 38 | self.size = size; 39 | self 40 | } 41 | 42 | pub fn size(&self) -> usize { 43 | self.size 44 | } 45 | } 46 | 47 | pub trait MessageAuthor: PartialEq + Eq { 48 | type Identifier: Sized + Copy + Clone + Debug + Eq + PartialEq; 49 | type DisplayName: IntoElement + Clone; 50 | type Icon: IntoElement + Clone; 51 | 52 | fn get_display_name(&self) -> Self::DisplayName; 53 | fn get_icon(&self, config: IconRenderConfig) -> Self::Icon; 54 | fn get_identifier(&self) -> Self::Identifier; 55 | } 56 | -------------------------------------------------------------------------------- /src/discord/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "scope-backend-discord" 3 | version = "0.1.0" 4 | edition = "2021" 5 | license = "AGPL-3.0-or-later" 6 | 7 | [dependencies] 8 | gpui.workspace = true 9 | scope-chat = { version = "0.1.0", path = "../chat" } 10 | serenity = { git = "https://github.com/scopeclient/serenity", version = "0.12" } 11 | tokio = "1.41.1" 12 | chrono.workspace = true 13 | scope-backend-cache = { version = "0.1.0", path = "../cache" } 14 | url = "2.5.3" 15 | querystring = "1.1.0" 16 | catty = "0.1.5" 17 | atomic_refcell = "0.1.13" 18 | rand = "0.8.5" 19 | dashmap = "6.1.0" 20 | -------------------------------------------------------------------------------- /src/discord/src/channel/mod.rs: -------------------------------------------------------------------------------- 1 | use std::sync::{Arc, OnceLock}; 2 | 3 | use chrono::Utc; 4 | use scope_backend_cache::async_list::{refcacheslice::Exists, AsyncListCache}; 5 | use scope_chat::{ 6 | async_list::{AsyncList, AsyncListIndex, AsyncListItem, AsyncListResult}, 7 | channel::Channel, 8 | }; 9 | use serenity::all::{ChannelId, GetMessages, MessageId}; 10 | use tokio::sync::{broadcast, Mutex, Semaphore}; 11 | 12 | use crate::{ 13 | client::DiscordClient, 14 | message::{DiscordMessage, DiscordMessageData}, 15 | snowflake::Snowflake, 16 | }; 17 | 18 | pub struct DiscordChannel { 19 | channel: Arc, 20 | 21 | receiver: broadcast::Receiver, 22 | client: Arc, 23 | cache: Arc>>, 24 | blocker: Semaphore, 25 | } 26 | 27 | impl DiscordChannel { 28 | pub(crate) async fn new(client: Arc, channel_id: ChannelId) -> Self { 29 | let (sender, receiver) = broadcast::channel(10); 30 | 31 | client.add_channel_message_sender(channel_id, sender).await; 32 | 33 | let channel = Arc::new(channel_id.to_channel(client.discord()).await.unwrap()); 34 | 35 | DiscordChannel { 36 | channel, 37 | receiver, 38 | client, 39 | cache: Arc::new(Mutex::new(AsyncListCache::new())), 40 | blocker: Semaphore::new(1), 41 | } 42 | } 43 | } 44 | 45 | impl Channel for DiscordChannel { 46 | type Message = DiscordMessage; 47 | type Identifier = Snowflake; 48 | 49 | fn get_receiver(&self) -> broadcast::Receiver { 50 | self.receiver.resubscribe() 51 | } 52 | 53 | fn send_message(&self, content: String, nonce: String) -> DiscordMessage { 54 | let client = self.client.clone(); 55 | let channel_id = self.channel.id(); 56 | let sent_content = content.clone(); 57 | let sent_nonce = nonce.clone(); 58 | 59 | tokio::spawn(async move { 60 | client.send_message(channel_id, sent_content, sent_nonce).await; 61 | }); 62 | 63 | DiscordMessage { 64 | channel: self.channel.clone(), 65 | client: self.client.clone(), 66 | data: DiscordMessageData::Pending { 67 | nonce, 68 | content, 69 | sent_time: Utc::now(), 70 | list_item_id: Snowflake::random(), 71 | }, 72 | content: OnceLock::new(), 73 | } 74 | } 75 | 76 | fn get_identifier(&self) -> Self::Identifier { 77 | self.channel.id().into() 78 | } 79 | } 80 | 81 | const DISCORD_MESSAGE_BATCH_SIZE: u8 = 50; 82 | 83 | impl AsyncList for DiscordChannel { 84 | async fn bounded_at_bottom_by(&self) -> Option { 85 | let lock = self.cache.lock().await; 86 | let cache_value = lock.bounded_at_top_by(); 87 | 88 | if let Some(v) = cache_value { 89 | return Some(v); 90 | }; 91 | 92 | match &*self.channel { 93 | serenity::model::channel::Channel::Guild(guild_channel) => guild_channel.messages(self.client.discord(), GetMessages::new().limit(1)).await, 94 | serenity::model::channel::Channel::Private(private_channel) => { 95 | private_channel.messages(self.client.discord(), GetMessages::new().limit(1)).await 96 | } 97 | _ => unimplemented!(), 98 | } 99 | .unwrap() 100 | .first() 101 | .map(|v| Snowflake(v.id.get())) 102 | } 103 | 104 | async fn bounded_at_top_by(&self) -> Option { 105 | let lock = self.cache.lock().await; 106 | let cache_value = lock.bounded_at_bottom_by(); 107 | 108 | if let Some(v) = cache_value { 109 | return Some(v); 110 | }; 111 | 112 | panic!("Unsupported") 113 | } 114 | 115 | async fn find(&self, identifier: &Snowflake) -> Option { 116 | let lock = self.cache.lock().await; 117 | let cache_value = lock.find(identifier); 118 | 119 | drop(lock); 120 | 121 | if let Some(v) = cache_value { 122 | return Some(v); 123 | } 124 | 125 | let result = self.client.get_specific_message(self.channel.id(), MessageId::new(identifier.0)).await?; 126 | 127 | Some(DiscordMessage::load_serenity(self.client.clone(), Arc::new(result)).await) 128 | } 129 | 130 | async fn get(&self, index: AsyncListIndex) -> Option> { 131 | let permit = self.blocker.acquire().await; 132 | let mut lock = self.cache.lock().await; 133 | let cache_value = lock.get(index); 134 | 135 | if let Exists::Yes(v) = cache_value { 136 | return Some(v); 137 | } else if let Exists::No = cache_value { 138 | return None; 139 | } 140 | 141 | let mut result: Option = None; 142 | let mut is_top = false; 143 | let mut is_bottom = false; 144 | 145 | match index { 146 | AsyncListIndex::RelativeToTop(_) => todo!("Unsupported"), 147 | AsyncListIndex::RelativeToBottom(index) => { 148 | if index != 0 { 149 | unimplemented!() 150 | } 151 | 152 | let v = self.client.get_messages(self.channel.id(), GetMessages::new().limit(DISCORD_MESSAGE_BATCH_SIZE)).await; 153 | 154 | let is_end = v.len() == DISCORD_MESSAGE_BATCH_SIZE as usize; 155 | is_bottom = true; 156 | is_top = v.len() == 1; 157 | 158 | let mut iter = v.into_iter(); 159 | 160 | let v = iter.next(); 161 | 162 | if let Some(v) = v { 163 | let msg = DiscordMessage::load_serenity(self.client.clone(), Arc::new(v)).await; 164 | let mut id = msg.get_list_identifier(); 165 | lock.append_bottom(msg.clone()); 166 | result = Some(msg); 167 | 168 | for message in iter { 169 | let msg = DiscordMessage::load_serenity(self.client.clone(), Arc::new(message)).await; 170 | let nid = msg.get_list_identifier(); 171 | 172 | lock.insert(AsyncListIndex::Before(id), msg, false, is_end); 173 | 174 | id = nid; 175 | } 176 | }; 177 | } 178 | AsyncListIndex::After(message) => { 179 | // NEWEST first 180 | let v = self 181 | .client 182 | .get_messages( 183 | self.channel.id(), 184 | GetMessages::new().after(MessageId::new(message.0)).limit(DISCORD_MESSAGE_BATCH_SIZE), 185 | ) 186 | .await; 187 | let mut current_index: Snowflake = message; 188 | 189 | let is_end = v.len() == DISCORD_MESSAGE_BATCH_SIZE as usize; 190 | let len = v.len(); 191 | is_bottom = is_end && v.len() == 1; 192 | 193 | for (message, index) in v.into_iter().rev().zip(0..) { 194 | let id = Snowflake(message.id.get()); 195 | 196 | let value = DiscordMessage::load_serenity(self.client.clone(), Arc::new(message)).await; 197 | 198 | if index == 0 { 199 | result = Some(value.clone()); 200 | } 201 | 202 | lock.insert(AsyncListIndex::After(current_index), value, false, is_end && index == (len - 1)); 203 | 204 | current_index = id; 205 | } 206 | } 207 | AsyncListIndex::Before(message) => { 208 | let v = self 209 | .client 210 | .get_messages( 211 | self.channel.id(), 212 | GetMessages::new().before(MessageId::new(message.0)).limit(DISCORD_MESSAGE_BATCH_SIZE), 213 | ) 214 | .await; 215 | let mut current_index: Snowflake = message; 216 | 217 | println!("Discord gave us {:?} messages (out of {:?})", v.len(), DISCORD_MESSAGE_BATCH_SIZE); 218 | 219 | let is_end = v.len() == DISCORD_MESSAGE_BATCH_SIZE as usize; 220 | let len = v.len(); 221 | is_top = is_end && v.len() == 1; 222 | 223 | result = None; 224 | 225 | for (message, index) in v.into_iter().zip(0..) { 226 | let id = Snowflake(message.id.get()); 227 | 228 | let value = DiscordMessage::load_serenity(self.client.clone(), Arc::new(message)).await; 229 | 230 | if index == 0 { 231 | result = Some(value.clone()); 232 | } 233 | 234 | lock.insert(AsyncListIndex::Before(current_index), value, false, is_end && index == len); 235 | 236 | current_index = id; 237 | } 238 | } 239 | }; 240 | 241 | drop(permit); 242 | drop(lock); 243 | 244 | result.map(|v| AsyncListResult { 245 | content: v, 246 | is_top, 247 | is_bottom, 248 | }) 249 | } 250 | 251 | type Content = DiscordMessage; 252 | } 253 | 254 | impl Clone for DiscordChannel { 255 | fn clone(&self) -> Self { 256 | Self { 257 | channel: self.channel.clone(), 258 | receiver: self.receiver.resubscribe(), 259 | client: self.client.clone(), 260 | cache: self.cache.clone(), 261 | blocker: Semaphore::new(1), 262 | } 263 | } 264 | } 265 | -------------------------------------------------------------------------------- /src/discord/src/client.rs: -------------------------------------------------------------------------------- 1 | use std::{ 2 | collections::HashMap, 3 | sync::{Arc, OnceLock, Weak}, 4 | }; 5 | 6 | use atomic_refcell::AtomicRefCell; 7 | use dashmap::DashMap; 8 | use serenity::{ 9 | all::{ 10 | Cache, CacheHttp, ChannelId, Context, CreateMessage, EventHandler, GatewayIntents, GetMessages, GuildId, Http, Member, Message, MessageId, 11 | ModelError, Ready, User, 12 | }, 13 | async_trait, 14 | }; 15 | use tokio::sync::{broadcast, RwLock}; 16 | 17 | use crate::{channel::DiscordChannel, message::DiscordMessage, snowflake::Snowflake}; 18 | 19 | #[allow(dead_code)] 20 | pub struct SerenityClient { 21 | // enable this when we enable the serenity[voice] feature 22 | // voice_manager: Option> 23 | http: Arc, 24 | cache: Arc, 25 | } 26 | 27 | impl CacheHttp for SerenityClient { 28 | fn http(&self) -> &Http { 29 | &self.http 30 | } 31 | 32 | fn cache(&self) -> Option<&Arc> { 33 | Some(&self.cache) 34 | } 35 | } 36 | 37 | #[derive(Default)] 38 | pub struct DiscordClient { 39 | channel_message_event_handlers: RwLock>>>, 40 | client: OnceLock, 41 | user: OnceLock>, 42 | channels: RwLock>>, 43 | member: DashMap>, 44 | ready_notifier: AtomicRefCell>>, 45 | weak: Weak, 46 | } 47 | 48 | impl DiscordClient { 49 | pub async fn new(token: String) -> Arc { 50 | let (sender, receiver) = catty::oneshot::<()>(); 51 | 52 | let client = Arc::new_cyclic(|weak| DiscordClient { 53 | ready_notifier: AtomicRefCell::new(Some(sender)), 54 | weak: weak.clone(), 55 | 56 | ..Default::default() 57 | }); 58 | 59 | let mut discord = serenity::Client::builder(token, GatewayIntents::all()).event_handler_arc(client.clone()).await.expect("Error creating client"); 60 | 61 | let _ = client.client.set(SerenityClient { 62 | // voice_manager: discord.voice_manager.clone(), 63 | cache: discord.cache.clone(), 64 | http: discord.http.clone(), 65 | }); 66 | 67 | tokio::spawn(async move { 68 | if let Err(why) = discord.start().await { 69 | panic!("Client error: {why:?}"); 70 | } 71 | }); 72 | 73 | receiver.await.expect("The ready notifier was dropped"); 74 | 75 | client 76 | } 77 | 78 | pub fn discord(&self) -> &SerenityClient { 79 | self.client.get().unwrap() 80 | } 81 | 82 | pub fn own_user(&self) -> Arc { 83 | self.user.get().unwrap().clone() 84 | } 85 | 86 | pub fn own_member(&self, guild: GuildId) -> Option> { 87 | self.member.get(&guild).map(|v| v.clone()) 88 | } 89 | 90 | pub async fn add_channel_message_sender(&self, channel: ChannelId, sender: broadcast::Sender) { 91 | self.channel_message_event_handlers.write().await.entry(channel).or_default().push(sender); 92 | } 93 | 94 | pub async fn channel(self: Arc, channel_id: Snowflake) -> Arc { 95 | let channel_id = ChannelId::new(channel_id.0); 96 | 97 | let self_clone = self.clone(); 98 | let mut channels = self_clone.channels.write().await; 99 | let existing = channels.get(&channel_id); 100 | 101 | if let Some(existing) = existing { 102 | return existing.clone(); 103 | } 104 | 105 | let new = Arc::new(DiscordChannel::new(self, channel_id).await); 106 | 107 | channels.insert(channel_id, new.clone()); 108 | 109 | new 110 | } 111 | 112 | pub async fn send_message(&self, channel_id: ChannelId, content: String, nonce: String) { 113 | channel_id 114 | .send_message( 115 | self.discord().http.clone(), 116 | CreateMessage::new().content(content).enforce_nonce(true).nonce(serenity::all::Nonce::String(nonce)), 117 | ) 118 | .await 119 | .unwrap(); 120 | } 121 | 122 | pub async fn get_messages(&self, channel_id: ChannelId, builder: GetMessages) -> Vec { 123 | println!("Discord: get_messages: {:?}", builder); 124 | // FIXME: proper error handling 125 | channel_id.messages(self.discord().http.clone(), builder).await.unwrap() 126 | } 127 | 128 | pub async fn get_specific_message(&self, channel_id: ChannelId, message_id: MessageId) -> Option { 129 | println!("Discord: get_specific_messages"); 130 | // FIXME: proper error handling 131 | Some(channel_id.message(self.discord().http.clone(), message_id).await.unwrap()) 132 | } 133 | } 134 | 135 | #[async_trait] 136 | impl EventHandler for DiscordClient { 137 | async fn ready(&self, _: Context, ready: Ready) { 138 | self.user.get_or_init(|| Arc::new((*ready.user).clone())); 139 | 140 | if let Some(ready_notifier) = self.ready_notifier.borrow_mut().take() { 141 | ready_notifier.send(()).unwrap(); 142 | } 143 | } 144 | 145 | async fn message(&self, _: Context, msg: Message) { 146 | if let Some(vec) = self.channel_message_event_handlers.read().await.get(&msg.channel_id) { 147 | let msg = Arc::new(msg); 148 | let channel = Arc::new(msg.channel(self.discord()).await.unwrap()); 149 | let member = match msg.member(self.discord()).await { 150 | Ok(v) => Ok(Some(Arc::new(v))), 151 | Err(serenity::Error::Model(ModelError::ItemMissing)) => Ok(None), 152 | Err(e) => Err(e), 153 | } 154 | .unwrap(); 155 | 156 | for sender in vec { 157 | let _ = sender.send(DiscordMessage::from_serenity( 158 | self.weak.upgrade().unwrap(), 159 | msg.clone(), 160 | channel.clone(), 161 | member.clone(), 162 | )); 163 | } 164 | } 165 | } 166 | } 167 | -------------------------------------------------------------------------------- /src/discord/src/lib.rs: -------------------------------------------------------------------------------- 1 | pub mod channel; 2 | pub mod client; 3 | pub mod message; 4 | pub mod snowflake; 5 | -------------------------------------------------------------------------------- /src/discord/src/message/author.rs: -------------------------------------------------------------------------------- 1 | use std::sync::Arc; 2 | 3 | use gpui::{div, img, IntoElement, ParentElement, RenderOnce, SharedString, Styled, WindowContext}; 4 | use scope_chat::message::{IconRenderConfig, MessageAuthor}; 5 | use url::Url; 6 | 7 | use crate::{client::DiscordClient, snowflake::Snowflake}; 8 | 9 | #[derive(Clone)] 10 | pub enum DiscordMessageAuthorData { 11 | User(Arc), 12 | NonMemberAuthor(Arc), 13 | Member(Arc), 14 | } 15 | 16 | #[derive(Clone)] 17 | pub struct DiscordMessageAuthor { 18 | pub data: DiscordMessageAuthorData, 19 | 20 | pub client: Arc, 21 | } 22 | 23 | impl PartialEq for DiscordMessageAuthor { 24 | fn eq(&self, other: &Self) -> bool { 25 | match (&self.data, &other.data) { 26 | (DiscordMessageAuthorData::Member(ref left), DiscordMessageAuthorData::Member(ref right)) => { 27 | left.guild_id == right.guild_id && left.user.id == right.user.id 28 | } 29 | (DiscordMessageAuthorData::User(ref left), DiscordMessageAuthorData::User(ref right)) => left.id == right.id, 30 | _ => false, 31 | } 32 | } 33 | } 34 | impl Eq for DiscordMessageAuthor {} 35 | 36 | impl MessageAuthor for DiscordMessageAuthor { 37 | type Identifier = Snowflake; 38 | type DisplayName = DisplayName; 39 | type Icon = DisplayIcon; 40 | 41 | fn get_display_name(&self) -> Self::DisplayName { 42 | match &self.data { 43 | DiscordMessageAuthorData::Member(member) => DisplayName(member.display_name().to_owned().into()), 44 | DiscordMessageAuthorData::User(user) => DisplayName(user.display_name().to_owned().into()), 45 | DiscordMessageAuthorData::NonMemberAuthor(message) => DisplayName(message.author.display_name().to_owned().into()), 46 | } 47 | } 48 | 49 | fn get_icon(&self, config: IconRenderConfig) -> Self::Icon { 50 | match &self.data { 51 | DiscordMessageAuthorData::Member(member) => DisplayIcon( 52 | member.avatar_url().or(member.user.avatar_url()).unwrap_or(member.user.default_avatar_url()), 53 | config, 54 | ), 55 | DiscordMessageAuthorData::User(user) => DisplayIcon(user.avatar_url().unwrap_or(user.default_avatar_url()), config), 56 | DiscordMessageAuthorData::NonMemberAuthor(message) => { 57 | DisplayIcon(message.author.avatar_url().unwrap_or(message.author.default_avatar_url()), config) 58 | } 59 | } 60 | } 61 | 62 | fn get_identifier(&self) -> Self::Identifier { 63 | match &self.data { 64 | DiscordMessageAuthorData::Member(member) => member.user.id.into(), 65 | DiscordMessageAuthorData::User(user) => user.id.into(), 66 | DiscordMessageAuthorData::NonMemberAuthor(message) => message.author.id.into(), 67 | } 68 | } 69 | } 70 | 71 | #[derive(Clone, IntoElement, Debug)] 72 | pub struct DisplayName(pub SharedString); 73 | 74 | impl RenderOnce for DisplayName { 75 | fn render(self, _: &mut WindowContext) -> impl IntoElement { 76 | div().text_sm().child(self.0) 77 | } 78 | } 79 | 80 | #[derive(Clone, IntoElement, Debug)] 81 | pub struct DisplayIcon(pub String, pub IconRenderConfig); 82 | 83 | impl RenderOnce for DisplayIcon { 84 | fn render(self, _: &mut WindowContext) -> impl IntoElement { 85 | let mut url = Url::parse(&self.0).unwrap(); 86 | let mut query_params = querystring::querify(url.query().unwrap_or("")); 87 | 88 | let mut key_found = false; 89 | let size = self.1.size().to_string(); 90 | 91 | for (key, value) in query_params.iter_mut() { 92 | if key == &"size" { 93 | *value = &size; 94 | key_found = true; 95 | } 96 | } 97 | 98 | if !key_found { 99 | query_params.push(("size", &size)); 100 | } 101 | 102 | url.set_query(Some(&querystring::stringify(query_params))); 103 | 104 | img(url.to_string()).w_full().h_full().rounded_full() 105 | } 106 | } 107 | -------------------------------------------------------------------------------- /src/discord/src/message/content.rs: -------------------------------------------------------------------------------- 1 | use gpui::{div, IntoElement, ParentElement, Render, Styled, ViewContext}; 2 | use serenity::all::Message; 3 | 4 | #[derive(Clone, Debug)] 5 | pub struct DiscordMessageContent { 6 | pub content: String, 7 | pub is_pending: bool, 8 | } 9 | 10 | impl DiscordMessageContent { 11 | pub fn pending(content: String) -> DiscordMessageContent { 12 | DiscordMessageContent { content, is_pending: true } 13 | } 14 | 15 | pub fn received(message: &Message) -> DiscordMessageContent { 16 | DiscordMessageContent { 17 | content: message.content.clone(), 18 | is_pending: false, 19 | } 20 | } 21 | } 22 | 23 | impl Render for DiscordMessageContent { 24 | fn render(&mut self, _: &mut ViewContext) -> impl IntoElement { 25 | div().opacity(if self.is_pending { 0.25 } else { 1.0 }).child(self.content.clone()) 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/discord/src/message/mod.rs: -------------------------------------------------------------------------------- 1 | use std::sync::{Arc, OnceLock}; 2 | 3 | use author::DiscordMessageAuthor; 4 | use chrono::{DateTime, Utc}; 5 | use content::DiscordMessageContent; 6 | use gpui::{View, VisualContext, WindowContext}; 7 | use scope_chat::{async_list::AsyncListItem, message::Message}; 8 | use serenity::all::{ModelError, Nonce}; 9 | 10 | use crate::{client::DiscordClient, snowflake::Snowflake}; 11 | 12 | pub mod author; 13 | pub mod content; 14 | 15 | #[derive(Clone)] 16 | pub enum DiscordMessageData { 17 | Pending { 18 | nonce: String, 19 | content: String, 20 | sent_time: DateTime, 21 | list_item_id: Snowflake, 22 | }, 23 | Received(Arc, Option>), 24 | } 25 | 26 | #[derive(Clone)] 27 | pub struct DiscordMessage { 28 | pub client: Arc, 29 | pub channel: Arc, 30 | pub data: DiscordMessageData, 31 | pub content: OnceLock>, 32 | } 33 | 34 | impl DiscordMessage { 35 | pub async fn load_serenity(client: Arc, msg: Arc) -> Self { 36 | let channel = Arc::new(msg.channel(client.discord()).await.unwrap()); 37 | let member = match msg.member(client.discord()).await { 38 | Ok(v) => Ok(Some(Arc::new(v))), 39 | Err(serenity::Error::Model(ModelError::ItemMissing)) => Ok(None), 40 | Err(e) => Err(e), 41 | } 42 | .unwrap(); 43 | 44 | Self { 45 | client, 46 | channel, 47 | data: DiscordMessageData::Received(msg, member), 48 | 49 | content: OnceLock::new(), 50 | } 51 | } 52 | 53 | pub fn from_serenity( 54 | client: Arc, 55 | msg: Arc, 56 | channel: Arc, 57 | member: Option>, 58 | ) -> Self { 59 | Self { 60 | client, 61 | channel, 62 | data: DiscordMessageData::Received(msg, member), 63 | 64 | content: OnceLock::new(), 65 | } 66 | } 67 | } 68 | 69 | enum NonceState<'r> { 70 | Fixed(&'r String), 71 | Discord(&'r Option), 72 | } 73 | 74 | impl<'r> PartialEq for NonceState<'r> { 75 | fn eq(&self, other: &Self) -> bool { 76 | match (self, other) { 77 | // comparing anything with `None` means they are not equal 78 | (NonceState::Discord(None), _) => false, 79 | (_, NonceState::Discord(None)) => false, 80 | 81 | // two Fixed strings are equal if their contents are 82 | (NonceState::Fixed(left), NonceState::Fixed(right)) => left == right, 83 | 84 | // Fixed strings are only equal to Discord String Nonces 85 | (NonceState::Fixed(left), NonceState::Discord(Some(Nonce::String(right)))) => *left == right, 86 | (NonceState::Discord(Some(Nonce::String(right))), NonceState::Fixed(left)) => *left == right, 87 | 88 | // Discord Nonces are only equal if their types are. 89 | (NonceState::Discord(Some(Nonce::Number(left))), NonceState::Discord(Some(Nonce::Number(right)))) => left == right, 90 | (NonceState::Discord(Some(Nonce::String(left))), NonceState::Discord(Some(Nonce::String(right)))) => left == right, 91 | 92 | _ => false, 93 | } 94 | } 95 | } 96 | 97 | impl Message for DiscordMessage { 98 | type Identifier = Snowflake; 99 | type Author = DiscordMessageAuthor; 100 | type Content = DiscordMessageContent; 101 | 102 | fn get_author(&self) -> DiscordMessageAuthor { 103 | match &self.data { 104 | DiscordMessageData::Pending { .. } => DiscordMessageAuthor { 105 | client: self.client.clone(), 106 | data: match &*self.channel { 107 | serenity::model::channel::Channel::Private(_) => author::DiscordMessageAuthorData::User(self.client.own_user().clone()), 108 | serenity::model::channel::Channel::Guild(guild_channel) => match self.client.own_member(guild_channel.guild_id) { 109 | Some(member) => author::DiscordMessageAuthorData::Member(member), 110 | None => author::DiscordMessageAuthorData::User(self.client.own_user().clone()), 111 | }, 112 | _ => unimplemented!(), 113 | }, 114 | }, 115 | 116 | DiscordMessageData::Received(message, member) => DiscordMessageAuthor { 117 | client: self.client.clone(), 118 | data: match member { 119 | None => author::DiscordMessageAuthorData::NonMemberAuthor(message.clone()), 120 | Some(member) => author::DiscordMessageAuthorData::Member(member.clone()), 121 | }, 122 | }, 123 | } 124 | } 125 | 126 | // TODO: want reviewer discussion. I'm really stretching the abilities of gpui here and im not sure if this is the right way to do this. 127 | fn get_content(&self, cx: &mut WindowContext) -> View { 128 | self 129 | .content 130 | .get_or_init(|| { 131 | let content = match &self.data { 132 | DiscordMessageData::Pending { content, .. } => DiscordMessageContent::pending(content.clone()), 133 | DiscordMessageData::Received(message, _) => DiscordMessageContent::received(message), 134 | }; 135 | 136 | cx.new_view(|_cx| content) 137 | }) 138 | .clone() 139 | } 140 | 141 | fn get_identifier(&self) -> Option { 142 | match &self.data { 143 | DiscordMessageData::Received(message, _) => Some(message.id.into()), 144 | DiscordMessageData::Pending { .. } => None, 145 | } 146 | } 147 | 148 | fn get_nonce(&self) -> impl PartialEq { 149 | match &self.data { 150 | DiscordMessageData::Pending { nonce, .. } => NonceState::Fixed(nonce), 151 | DiscordMessageData::Received(message, _) => NonceState::Discord(&message.nonce), 152 | } 153 | } 154 | 155 | fn should_group(&self, previous: &Self) -> bool { 156 | const MAX_DISCORD_MESSAGE_GAP_SECS_FOR_GROUP: i64 = 5 * 60; 157 | 158 | let left = self.get_timestamp().unwrap(); 159 | let right = previous.get_timestamp().unwrap(); 160 | 161 | left.signed_duration_since(right).num_seconds() <= MAX_DISCORD_MESSAGE_GAP_SECS_FOR_GROUP 162 | } 163 | 164 | fn get_timestamp(&self) -> Option> { 165 | match &self.data { 166 | DiscordMessageData::Pending { sent_time, .. } => Some(*sent_time), 167 | DiscordMessageData::Received(message, _) => DateTime::from_timestamp_millis(message.timestamp.timestamp_millis()), 168 | } 169 | } 170 | } 171 | 172 | impl AsyncListItem for DiscordMessage { 173 | type Identifier = Snowflake; 174 | 175 | fn get_list_identifier(&self) -> Self::Identifier { 176 | match &self.data { 177 | DiscordMessageData::Pending { list_item_id, .. } => *list_item_id, 178 | DiscordMessageData::Received(message, _) => message.id.into(), 179 | } 180 | } 181 | } 182 | -------------------------------------------------------------------------------- /src/discord/src/snowflake.rs: -------------------------------------------------------------------------------- 1 | use serenity::all::{ChannelId, GuildId, MessageId, UserId}; 2 | 3 | #[derive(Clone, Hash, PartialEq, Eq, Copy, Debug)] 4 | pub struct Snowflake(pub u64); 5 | 6 | impl Snowflake { 7 | pub fn random() -> Snowflake { 8 | Snowflake(rand::random()) 9 | } 10 | } 11 | 12 | #[allow(clippy::to_string_trait_impl)] 13 | impl ToString for Snowflake { 14 | fn to_string(&self) -> String { 15 | self.0.to_string() 16 | } 17 | } 18 | 19 | impl From for Snowflake { 20 | fn from(value: UserId) -> Self { 21 | Snowflake(value.get()) 22 | } 23 | } 24 | 25 | impl From for Snowflake { 26 | fn from(value: GuildId) -> Self { 27 | Snowflake(value.get()) 28 | } 29 | } 30 | 31 | impl From for Snowflake { 32 | fn from(value: ChannelId) -> Self { 33 | Snowflake(value.get()) 34 | } 35 | } 36 | 37 | impl From for Snowflake { 38 | fn from(value: MessageId) -> Self { 39 | Snowflake(value.get()) 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/ui/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "scope" 3 | version = "0.1.0" 4 | edition = "2021" 5 | authors = [ 6 | "Rose Kodsi-Hall ", 7 | # Add yourself here if you contribute! 8 | ] 9 | description = "discord client for power users" 10 | readme = "README.md" 11 | homepage = "https://www.scopeclient.com/" 12 | repository = "https://github.com/scopeclient/scope" 13 | keywords = ["discord", "scope", "reticle"] 14 | license = "AGPL-3.0-or-later" 15 | 16 | [dependencies] 17 | gpui.workspace = true 18 | reqwest_client.workspace = true 19 | scope-chat = { version = "0.1.0", path = "../chat" } 20 | scope-util = { version = "0.1.0", path = "../util" } 21 | scope-backend-discord = { version = "0.1.0", path = "../discord" } 22 | scope-backend-cache = { version = "0.1.0", path = "../cache" } 23 | dotenv = "0.15.0" 24 | env_logger = "0.11.5" 25 | tokio = { version = "1.41.1", features = ["full"] } 26 | components.workspace = true 27 | log = "0.4.22" 28 | random-string = "1.1.0" 29 | rust-embed = "8.5.0" 30 | chrono.workspace = true 31 | catty = "0.1.5" 32 | 33 | [features] 34 | default = ["gpui/x11"] 35 | wayland = ["gpui/wayland"] 36 | -------------------------------------------------------------------------------- /src/ui/src/actions.rs: -------------------------------------------------------------------------------- 1 | use gpui::actions; 2 | 3 | actions!(scope, [Quit, Hide]); 4 | -------------------------------------------------------------------------------- /src/ui/src/app.rs: -------------------------------------------------------------------------------- 1 | use components::theme::ActiveTheme; 2 | use gpui::{div, img, rgb, Context, Model, ParentElement, Render, Styled, View, ViewContext, VisualContext}; 3 | use scope_backend_discord::{channel::DiscordChannel, client::DiscordClient, snowflake::Snowflake}; 4 | 5 | use crate::channel::ChannelView; 6 | 7 | pub struct App { 8 | channel: Model>>>, 9 | } 10 | 11 | impl App { 12 | pub fn new(ctx: &mut ViewContext<'_, Self>) -> App { 13 | let token = dotenv::var("DISCORD_TOKEN").expect("Must provide DISCORD_TOKEN in .env"); 14 | let demo_channel_id = dotenv::var("DEMO_CHANNEL_ID").expect("Must provide DEMO_CHANNEL_ID in .env"); 15 | 16 | let mut context = ctx.to_async(); 17 | 18 | let channel = ctx.new_model(|_| None); 19 | 20 | let async_channel = channel.clone(); 21 | 22 | ctx 23 | .foreground_executor() 24 | .spawn(async move { 25 | let client = DiscordClient::new(token).await; 26 | let channel = client.channel(Snowflake(demo_channel_id.parse().unwrap())).await; 27 | let view = context.new_view(|cx| ChannelView::::create(cx, channel)).unwrap(); 28 | 29 | async_channel 30 | .update(&mut context, |a, b| { 31 | *a = Some(view); 32 | b.notify() 33 | }) 34 | .unwrap(); 35 | }) 36 | .detach(); 37 | 38 | App { channel } 39 | } 40 | } 41 | 42 | impl Render for App { 43 | fn render(&mut self, cx: &mut gpui::ViewContext) -> impl gpui::IntoElement { 44 | let mut content = div().w_full().h_full(); 45 | 46 | if let Some(channel) = self.channel.read(cx).as_ref() { 47 | content = content.child(channel.clone()); 48 | } 49 | 50 | let title_bar = components::TitleBar::new() 51 | .child(div().flex().flex_row().text_color(rgb(0xFFFFFF)).gap_2().child(img("brand/scope-round-200.png").w_6().h_6()).child("Scope")); 52 | 53 | div().bg(cx.theme().background).w_full().h_full().flex().flex_col().child(title_bar).child(content) 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/ui/src/app_state.rs: -------------------------------------------------------------------------------- 1 | use std::sync::Weak; 2 | 3 | use gpui::{AppContext, Global}; 4 | 5 | pub struct AppState {} 6 | 7 | struct GlobalAppState(); 8 | 9 | impl Global for GlobalAppState {} 10 | 11 | impl AppState { 12 | pub fn set_global(_app_state: Weak, cx: &mut AppContext) { 13 | cx.set_global(GlobalAppState()); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/ui/src/channel/message.rs: -------------------------------------------------------------------------------- 1 | use chrono::Local; 2 | use gpui::{div, prelude::FluentBuilder, rgb, IntoElement, ParentElement, Styled, WindowContext}; 3 | use scope_chat::message::{IconRenderConfig, Message, MessageAuthor}; 4 | 5 | #[derive(Clone)] 6 | pub struct MessageGroup { 7 | contents: Vec, 8 | } 9 | 10 | impl MessageGroup { 11 | pub fn new(message: M) -> MessageGroup { 12 | MessageGroup { contents: vec![message] } 13 | } 14 | 15 | pub fn get_author(&self) -> M::Author { 16 | self.contents.first().unwrap().get_author() 17 | } 18 | 19 | pub fn add(&mut self, message: M) { 20 | // FIXME: This is scuffed, should be using PartialEq trait. 21 | if self.get_author().get_identifier() != message.get_author().get_identifier() { 22 | panic!("Authors must match in a message group") 23 | } 24 | 25 | self.contents.push(message); 26 | } 27 | 28 | pub fn size(&self) -> usize { 29 | self.contents.len() 30 | } 31 | 32 | pub fn remove(&mut self, index: usize) { 33 | if self.size() == 1 { 34 | panic!("Cannot remove such that it would leave the group empty."); 35 | } 36 | 37 | self.contents.remove(index); 38 | } 39 | 40 | pub fn last(&self) -> &M { 41 | self.contents.last().unwrap() 42 | } 43 | } 44 | 45 | pub fn message_group(group: MessageGroup, cx: &mut WindowContext) -> impl IntoElement { 46 | div() 47 | .flex() 48 | .flex_row() 49 | .text_color(rgb(0xFFFFFF)) 50 | .gap_4() 51 | .pb_6() 52 | .child(div().child(group.get_author().get_icon(IconRenderConfig::small())).flex_shrink_0().rounded_full().w_12().h_12()) 53 | .child( 54 | div() 55 | .flex() 56 | .min_w_0() 57 | .flex_shrink() 58 | .flex_col() 59 | // enabling this, and thus enabling ellipsis causes a consistent panic!? 60 | // .child(div().text_ellipsis().min_w_0().child(message.get_author().get_display_name())) 61 | .child( 62 | div().min_w_0().flex().gap_2().child(group.get_author().get_display_name()).when_some(group.last().get_timestamp(), |d, ts| { 63 | d.child(div().min_w_0().text_color(rgb(0xAFBAC7)).text_sm().child(ts.with_timezone(&Local).format("%I:%M %p").to_string())) 64 | }), 65 | ) 66 | .children(group.contents.iter().map(|v| v.get_content(cx).clone())), 67 | ) 68 | } 69 | -------------------------------------------------------------------------------- /src/ui/src/channel/message_list.rs: -------------------------------------------------------------------------------- 1 | use std::sync::Arc; 2 | 3 | use gpui::{div, list, rgb, Context, IntoElement, ListAlignment, ListState, Model, ParentElement, Pixels, Render, Styled, ViewContext}; 4 | use scope_chat::{ 5 | async_list::{AsyncListIndex, AsyncListItem}, 6 | channel::Channel, 7 | message::{Message, MessageAuthor}, 8 | }; 9 | use tokio::sync::RwLock; 10 | 11 | use super::message::{message_group, MessageGroup}; 12 | 13 | #[derive(Clone, Copy)] 14 | struct ListStateDirtyState { 15 | pub new_items: usize, 16 | pub shift: usize, 17 | } 18 | 19 | #[derive(Clone, Copy)] 20 | struct BoundFlags { 21 | pub before: bool, 22 | pub after: bool, 23 | } 24 | 25 | #[derive(Debug)] 26 | pub enum Element { 27 | Unresolved, 28 | Resolved(T), 29 | } 30 | 31 | pub struct MessageListComponent 32 | where 33 | C::Content: 'static, 34 | { 35 | list: Arc>, 36 | cache: Model>>>, 37 | overdraw: Pixels, 38 | 39 | // top, bottom 40 | bounds_flags: Model, 41 | 42 | list_state: Model>, 43 | list_state_dirty: Model>, 44 | } 45 | 46 | pub enum StartAt { 47 | Bottom, 48 | Top, 49 | } 50 | 51 | impl MessageListComponent 52 | where 53 | T: 'static, 54 | { 55 | pub fn create(cx: &mut ViewContext, list: T, overdraw: Pixels) -> Self { 56 | let cache = cx.new_model(|_| Default::default()); 57 | let list_state = cx.new_model(|_| None); 58 | let list_state_dirty = cx.new_model(|_| None); 59 | 60 | let lsc = list_state.clone(); 61 | 62 | cx.observe(&cache, move |c, _, cx| { 63 | let ls = c.list_state(cx); 64 | 65 | lsc.update(cx, |v, _| *v = Some(ls)); 66 | 67 | cx.notify(); 68 | }) 69 | .detach(); 70 | 71 | let lsc = list_state.clone(); 72 | 73 | cx.observe(&list_state_dirty, move |c, _, cx| { 74 | let ls = c.list_state(cx); 75 | 76 | lsc.update(cx, |v, _| *v = Some(ls)); 77 | 78 | cx.notify(); 79 | }) 80 | .detach(); 81 | 82 | MessageListComponent { 83 | list: Arc::new(RwLock::new(list)), 84 | cache, 85 | overdraw, 86 | bounds_flags: cx.new_model(|_| BoundFlags { before: false, after: false }), 87 | list_state, 88 | list_state_dirty, 89 | } 90 | } 91 | 92 | pub fn append_message(&mut self, cx: &mut ViewContext, message: T::Message) { 93 | self.cache.update(cx, |borrow, cx| { 94 | for item in borrow.iter_mut() { 95 | if let Element::Resolved(Some(haystack)) = item { 96 | if haystack.get_nonce() == message.get_nonce() { 97 | *item = Element::Resolved(Some(message)); 98 | 99 | cx.notify(); 100 | return; 101 | } 102 | } 103 | } 104 | 105 | if let Some(Element::Resolved(None)) = borrow.last() { 106 | borrow.pop(); 107 | } 108 | 109 | borrow.push(Element::Resolved(Some(message))); 110 | borrow.push(Element::Resolved(None)); 111 | 112 | cx.update_model(&self.list_state_dirty, |v, _| *v = Some(ListStateDirtyState { new_items: 1, shift: 0 })); 113 | 114 | cx.notify(); 115 | }); 116 | } 117 | 118 | fn list_state(&self, cx: &mut gpui::ViewContext) -> ListState { 119 | let bounds_model = self.bounds_flags.clone(); 120 | 121 | let list_state_dirty = *self.list_state_dirty.read(cx); 122 | 123 | let mut added_elements_bottom = 0; 124 | let mut shift = 0; 125 | 126 | let mut remaining_shift = list_state_dirty.map(|v| v.shift).unwrap_or(0); 127 | let mut remaining_gap_new_items = self.cache.read(cx).len() - list_state_dirty.map(|v| v.new_items).unwrap_or(0); 128 | 129 | let mut groups = vec![]; 130 | 131 | for (item, index) in self.cache.read(cx).iter().zip(0..) { 132 | let mut items_added: usize = 0; 133 | 134 | match item { 135 | Element::Unresolved => groups.push(Element::Unresolved), 136 | Element::Resolved(None) => groups.push(Element::Resolved(None)), 137 | Element::Resolved(Some(m)) => match groups.last_mut() { 138 | None | Some(Element::Unresolved) | Some(Element::Resolved(None)) => { 139 | items_added += 1; 140 | groups.push(Element::Resolved(Some(MessageGroup::new(m.clone())))); 141 | } 142 | Some(Element::Resolved(Some(old_group))) => { 143 | if m.get_author().get_identifier() == old_group.last().get_author().get_identifier() && m.should_group(old_group.last()) { 144 | old_group.add(m.clone()); 145 | } else { 146 | items_added += 1; 147 | groups.push(Element::Resolved(Some(MessageGroup::new(m.clone())))); 148 | } 149 | } 150 | }, 151 | } 152 | 153 | if index == 0 { 154 | continue; 155 | } 156 | 157 | if remaining_shift > 0 { 158 | remaining_shift -= 1; 159 | shift += items_added; 160 | } 161 | 162 | if remaining_gap_new_items == 0 { 163 | added_elements_bottom = items_added; 164 | } else { 165 | remaining_gap_new_items -= 1; 166 | } 167 | } 168 | 169 | let len = groups.len(); 170 | 171 | let new_list_state = ListState::new( 172 | if len == 0 { 1 } else { len + 2 }, 173 | ListAlignment::Bottom, 174 | self.overdraw, 175 | move |idx, cx| { 176 | if len == 0 { 177 | cx.update_model(&bounds_model, |v, _| v.after = true); 178 | 179 | return div().into_any_element(); 180 | } 181 | 182 | if idx == 0 { 183 | cx.update_model(&bounds_model, |v, _| v.before = true); 184 | 185 | div() 186 | } else if idx == len + 1 { 187 | cx.update_model(&bounds_model, |v, _| v.after = true); 188 | 189 | div() 190 | } else { 191 | match &groups[idx - 1] { 192 | Element::Unresolved => div().text_color(rgb(0xFFFFFF)).child("Loading..."), 193 | Element::Resolved(None) => div(), // we've hit the ends 194 | Element::Resolved(Some(group)) => div().child(message_group(group.clone(), cx)), 195 | } 196 | } 197 | .into_any_element() 198 | }, 199 | ); 200 | 201 | let old_list_state = self.list_state.read(cx); 202 | 203 | if let Some(old_list_state) = old_list_state { 204 | let mut new_scroll_top = old_list_state.logical_scroll_top(); 205 | 206 | if old_list_state.logical_scroll_top().item_ix == old_list_state.item_count() { 207 | new_scroll_top.item_ix += added_elements_bottom; 208 | 209 | if added_elements_bottom > 0 { 210 | new_scroll_top.offset_in_item = Pixels(0.); 211 | } 212 | } 213 | 214 | new_scroll_top.item_ix += shift; 215 | 216 | new_list_state.scroll_to(new_scroll_top); 217 | }; 218 | 219 | self.list_state.update(cx, |v, _| *v = Some(new_list_state.clone())); 220 | 221 | new_list_state 222 | } 223 | 224 | fn update(&mut self, cx: &mut gpui::ViewContext) { 225 | let mut dirty = None; 226 | 227 | let mut flags = *self.bounds_flags.read(cx); 228 | 229 | // update bottom 230 | if flags.after { 231 | let cache_model = self.cache.clone(); 232 | let list_handle = self.list.clone(); 233 | 234 | self.cache.update(cx, |borrow, cx| { 235 | let last = borrow.last(); 236 | 237 | let index = if let Some(last) = last { 238 | AsyncListIndex::After(if let Element::Resolved(Some(v)) = last { 239 | v.get_list_identifier() 240 | } else { 241 | flags.after = false; 242 | return; 243 | }) 244 | } else { 245 | AsyncListIndex::RelativeToBottom(0) 246 | }; 247 | 248 | borrow.push(Element::Unresolved); 249 | 250 | let insert_index = borrow.len() - 1; 251 | let mut async_ctx = cx.to_async(); 252 | 253 | cx.foreground_executor() 254 | .spawn(async move { 255 | let (sender, receiver) = catty::oneshot(); 256 | 257 | tokio::spawn(async move { 258 | match sender.send(list_handle.read().await.get(index).await) { 259 | Ok(_) => {} 260 | Err(_e) => log::error!("Failed to send."), 261 | } 262 | }); 263 | 264 | let v = receiver.await.unwrap(); 265 | 266 | cache_model 267 | .update(&mut async_ctx, |borrow, cx| { 268 | borrow[insert_index] = Element::Resolved(v.map(|v| v.content)); 269 | 270 | cx.notify(); 271 | }) 272 | .unwrap(); 273 | }) 274 | .detach(); 275 | 276 | dirty = Some(ListStateDirtyState { new_items: 1, shift: 0 }); 277 | }); 278 | } 279 | 280 | // update top 281 | if flags.before { 282 | let cache_model = self.cache.clone(); 283 | let list_handle = self.list.clone(); 284 | 285 | self.cache.update(cx, |borrow, cx| { 286 | let first = borrow.first(); 287 | 288 | let index = if let Some(first) = first { 289 | AsyncListIndex::Before(if let Element::Resolved(Some(v)) = first { 290 | v.get_list_identifier() 291 | } else { 292 | flags.before = false; 293 | return; 294 | }) 295 | } else { 296 | flags.before = false; 297 | return; 298 | }; 299 | 300 | borrow.insert(0, Element::Unresolved); 301 | 302 | let insert_index = 0; 303 | let mut async_ctx = cx.to_async(); 304 | 305 | cx.foreground_executor() 306 | .spawn(async move { 307 | let (sender, receiver) = catty::oneshot(); 308 | 309 | tokio::spawn(async move { 310 | match sender.send(list_handle.read().await.get(index).await) { 311 | Ok(_) => {} 312 | Err(_e) => log::error!("Failed to send."), 313 | } 314 | }); 315 | 316 | let v = receiver.await.unwrap(); 317 | 318 | cache_model 319 | .update(&mut async_ctx, |borrow, cx| { 320 | borrow[insert_index] = Element::Resolved(v.map(|v| v.content)); 321 | cx.notify(); 322 | }) 323 | .unwrap(); 324 | }) 325 | .detach(); 326 | 327 | dirty = { 328 | let mut v = dirty.unwrap_or(ListStateDirtyState { new_items: 0, shift: 0 }); 329 | 330 | v.shift += 1; 331 | 332 | Some(v) 333 | }; 334 | }); 335 | } 336 | 337 | self.list_state_dirty.update(cx, |v, _| { 338 | *v = dirty; 339 | }); 340 | 341 | if dirty.is_some() { 342 | cx.notify(); 343 | } 344 | 345 | self.bounds_flags.update(cx, |v, _| { 346 | if flags.after { 347 | v.after = false; 348 | } 349 | 350 | if flags.before { 351 | v.before = false; 352 | } 353 | }) 354 | } 355 | } 356 | 357 | impl Render for MessageListComponent { 358 | fn render(&mut self, cx: &mut gpui::ViewContext) -> impl gpui::IntoElement { 359 | self.update(cx); 360 | 361 | let ls = if let Some(v) = self.list_state.read(cx).clone() { 362 | v 363 | } else { 364 | let list_state = self.list_state(cx); 365 | 366 | let lsc = list_state.clone(); 367 | 368 | self.list_state.update(cx, move |v, _| *v = Some(lsc)); 369 | 370 | list_state 371 | }; 372 | 373 | div().w_full().h_full().child(list(ls).w_full().h_full()) 374 | } 375 | } 376 | -------------------------------------------------------------------------------- /src/ui/src/channel/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod message; 2 | pub mod message_list; 3 | 4 | use std::sync::Arc; 5 | 6 | use components::input::{InputEvent, TextInput}; 7 | use gpui::{div, ParentElement, Pixels, Render, Styled, View, VisualContext}; 8 | use message_list::MessageListComponent; 9 | use scope_chat::channel::Channel; 10 | 11 | pub struct ChannelView { 12 | list_view: View>>, 13 | message_input: View, 14 | } 15 | 16 | impl ChannelView { 17 | pub fn create(ctx: &mut gpui::ViewContext<'_, ChannelView>, channel: Arc) -> Self { 18 | let channel_listener = channel.get_receiver(); 19 | 20 | let c2 = channel.clone(); 21 | 22 | let list_view = ctx.new_view(|cx| MessageListComponent::create(cx, channel, Pixels(30.))); 23 | 24 | let async_model = list_view.clone(); 25 | let mut async_ctx = ctx.to_async(); 26 | 27 | ctx 28 | .foreground_executor() 29 | .spawn(async move { 30 | loop { 31 | let (sender, receiver) = catty::oneshot(); 32 | 33 | let mut l = channel_listener.resubscribe(); 34 | 35 | tokio::spawn(async move { 36 | match sender.send(l.recv().await) { 37 | Ok(_) => {} 38 | Err(_e) => log::error!("Failed to send message data!"), 39 | }; 40 | }); 41 | 42 | let message = receiver.await.unwrap().unwrap(); 43 | async_model 44 | .update(&mut async_ctx, |data, ctx| { 45 | data.append_message(ctx, message); 46 | ctx.notify(); 47 | }) 48 | .unwrap(); 49 | } 50 | }) 51 | .detach(); 52 | 53 | let message_input = ctx.new_view(|cx| { 54 | let mut input = components::input::TextInput::new(cx); 55 | 56 | input.set_size(components::Size::Large, cx); 57 | 58 | input 59 | }); 60 | 61 | let async_model = list_view.clone(); 62 | 63 | ctx 64 | .subscribe(&message_input, move |_, text_input, input_event, ctx| { 65 | if let InputEvent::PressEnter = input_event { 66 | let content = text_input.read(ctx).text().to_string(); 67 | if content.is_empty() { 68 | return; 69 | } 70 | 71 | text_input.update(ctx, |text_input, cx| { 72 | text_input.set_text("", cx); 73 | }); 74 | 75 | let nonce = random_string::generate(20, random_string::charsets::ALPHANUMERIC); 76 | let pending = c2.send_message(content, nonce); 77 | 78 | let mut async_ctx = ctx.to_async(); 79 | 80 | let async_model = async_model.clone(); 81 | 82 | ctx 83 | .foreground_executor() 84 | .spawn(async move { 85 | async_model 86 | .update(&mut async_ctx, |data, ctx| { 87 | data.append_message(ctx, pending); 88 | ctx.notify(); 89 | }) 90 | .unwrap(); 91 | }) 92 | .detach(); 93 | 94 | ctx.notify(); 95 | } 96 | }) 97 | .detach(); 98 | 99 | ChannelView:: { list_view, message_input } 100 | } 101 | } 102 | 103 | impl Render for ChannelView { 104 | fn render(&mut self, _: &mut gpui::ViewContext) -> impl gpui::IntoElement { 105 | div() 106 | .flex() 107 | .flex_col() 108 | .w_full() 109 | .h_full() 110 | .p_6() 111 | .child(div().w_full().h_full().flex().flex_col().child(self.list_view.clone())) 112 | .child(self.message_input.clone()) 113 | } 114 | } 115 | -------------------------------------------------------------------------------- /src/ui/src/main.rs: -------------------------------------------------------------------------------- 1 | pub mod actions; 2 | pub mod app; 3 | pub mod app_state; 4 | pub mod channel; 5 | pub mod menu; 6 | 7 | use std::sync::Arc; 8 | 9 | use app_state::AppState; 10 | use components::theme::{hsl, Theme, ThemeColor, ThemeMode}; 11 | use gpui::*; 12 | use http_client::anyhow; 13 | use menu::app_menus; 14 | 15 | #[derive(rust_embed::RustEmbed)] 16 | #[folder = "../../assets"] 17 | struct Assets; 18 | 19 | impl AssetSource for Assets { 20 | fn load(&self, path: &str) -> Result>> { 21 | Self::get(path).map(|f| Some(f.data)).ok_or_else(|| anyhow!("could not find asset at path \"{}\"", path)) 22 | } 23 | 24 | fn list(&self, path: &str) -> Result> { 25 | Ok(Self::iter().filter_map(|p| if p.starts_with(path) { Some(p.into()) } else { None }).collect()) 26 | } 27 | } 28 | 29 | fn init(_: Arc, cx: &mut AppContext) -> Result<()> { 30 | components::init(cx); 31 | 32 | if cfg!(target_os = "macos") { 33 | cx.bind_keys(vec![KeyBinding::new("cmd-q", actions::Quit, None)]); 34 | cx.bind_keys(vec![KeyBinding::new("cmd-h", actions::Hide, None)]); 35 | } else { 36 | cx.bind_keys(vec![KeyBinding::new("ctrl-h", actions::Hide, None)]); 37 | } 38 | 39 | cx.set_menus(app_menus()); 40 | 41 | cx.on_action(|_: &actions::Quit, cx| cx.quit()); 42 | cx.on_action(|_: &actions::Hide, cx| cx.hide()); 43 | 44 | Ok(()) 45 | } 46 | 47 | #[tokio::main] 48 | async fn main() { 49 | env_logger::init(); 50 | 51 | let app_state = Arc::new(AppState {}); 52 | 53 | App::new().with_assets(Assets).with_http_client(Arc::new(reqwest_client::ReqwestClient::new())).run(move |cx: &mut AppContext| { 54 | AppState::set_global(Arc::downgrade(&app_state), cx); 55 | 56 | if let Err(e) = init(app_state.clone(), cx) { 57 | log::error!("{}", e); 58 | return; 59 | } 60 | 61 | let mut theme = Theme::from(ThemeColor::dark()); 62 | theme.mode = ThemeMode::Dark; 63 | theme.accent = hsl(335.0, 97.0, 61.0); 64 | theme.title_bar = hsl(335.0, 97.0, 61.0); 65 | theme.background = hsl(225.0, 12.0, 10.0); 66 | 67 | cx.set_global(theme); 68 | cx.refresh(); 69 | 70 | let opts = WindowOptions { 71 | window_decorations: Some(WindowDecorations::Client), 72 | window_min_size: Some(size(Pixels(800.0), Pixels(600.0))), 73 | titlebar: Some(TitlebarOptions { 74 | appears_transparent: true, 75 | title: Some(SharedString::new_static("scope")), 76 | ..Default::default() 77 | }), 78 | ..Default::default() 79 | }; 80 | 81 | cx.open_window(opts, |cx| cx.new_view(crate::app::App::new)).unwrap(); 82 | }); 83 | } 84 | -------------------------------------------------------------------------------- /src/ui/src/menu.rs: -------------------------------------------------------------------------------- 1 | use gpui::{Menu, MenuItem}; 2 | 3 | use crate::actions; 4 | 5 | pub fn app_menus() -> Vec { 6 | vec![ 7 | Menu { 8 | name: "Scope".into(), 9 | items: vec![MenuItem::action("Quit", actions::Quit)], 10 | }, 11 | Menu { 12 | name: "Window".into(), 13 | items: vec![MenuItem::action("Hide", actions::Hide)], 14 | }, 15 | ] 16 | } 17 | -------------------------------------------------------------------------------- /src/util/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "scope-util" 3 | version = "0.1.0" 4 | edition = "2021" 5 | license = "AGPL-3.0-or-later" 6 | 7 | [dependencies] 8 | -------------------------------------------------------------------------------- /src/util/src/lib.rs: -------------------------------------------------------------------------------- 1 | pub trait ResultExt {} 2 | 3 | impl ResultExt for Result where E: std::fmt::Debug {} 4 | --------------------------------------------------------------------------------