diff --git a/.babysteps/tauri-migration.plan.md b/.babysteps/tauri-migration.plan.md new file mode 100644 index 0000000..4867d88 --- /dev/null +++ b/.babysteps/tauri-migration.plan.md @@ -0,0 +1,96 @@ +# Main-to-Tauri feature-parity follow-up + +Feature parity, not a whole-branch merge. Two queues share this file: the active +2026-11-06..08 delta queue (D01-D09), then the remaining collection/artwork/platform +queue (M03-M06) from the earlier plan. + +## Where the branches stand + +- Baseline: `tauri-port` at `b0eec88` (`3e1432c` M02 plus the artwork-display fix). +- Source: `origin/main` at `0310657`; the delta is `96fd68c..0310657`, 32 commits. + The earlier plan compared against `96fd68c`, and `main` was fast-forwarded from + there to `0310657` after M01/M02 were planned. +- Completed already: M01 (`b1b29ac`) and M02 (`3e1432c`). +- Main originals for every read below are snapshotted in + `localTmp/main-ref-0310657/` (ignored scratch; regenerate with the command under + Reference snapshot if the directory is missing). + +Keep Tauri v2 as the product runtime. Every forecast below is under the 225,000-token +work budget. The active model prices all stages at $0, so the $0.70 per-slice cap is +not approached; a paid model would be governed by the same cap. Existing desktop and +Android target constraints, the Android support limitations, and `docs/donot.md` +remain authoritative. + +## Delta queue (active) + +Every row prices the standing set — `docs/STATE.md`, this plan, its task list, +`docs/donot.md` and `.operator/specs/desktop-runtime.md` — plus the task's own reads. +`reads` is the row's whole priced set and `allowance` is the non-reading estimate; a +slice's seed copies both verbatim and `babysteps-budget --seed` rejects any file the +row does not price. + +| slice | task | scope | reads | allowance | +|---|---|---|---|---:| +| P1 | D01 | Quiet interface palette, `interface.css`, grouped Settings, shortened copy, artwork type grid, transparent header. | docs/STATE.md, .babysteps/tauri-migration.plan.md, docs/donot.md, .operator/specs/desktop-runtime.md, .babysteps/main-delta.tasks.json, renderer/index.html, renderer/styles.css, renderer/appearance.js, localTmp/main-ref-0310657/renderer/index.html, localTmp/main-ref-0310657/renderer/styles.css, localTmp/main-ref-0310657/renderer/appearance.js, localTmp/main-ref-0310657/renderer/interface.css | 87827 | +| P2 | D02 | Launcher chrome: `LibraryChrome`, `DetailsResize`, shelf space when details hide, `/` search, console previews and key navigation. | docs/STATE.md, .babysteps/tauri-migration.plan.md, docs/donot.md, .operator/specs/desktop-runtime.md, .babysteps/main-delta.tasks.json, renderer/app.js, renderer/index.html, renderer/styles.css, localTmp/main-ref-0310657/renderer/app.js, localTmp/main-ref-0310657/renderer/index.html | 70827 | +| P3 | D03 | Flat graphite button-prompt SVG/PNG set, `build-prompts.js`, manifest and preview, prompt checks. | docs/STATE.md, .babysteps/tauri-migration.plan.md, docs/donot.md, .operator/specs/desktop-runtime.md, .babysteps/main-delta.tasks.json, renderer/prompts.js, scripts/build-prompts.js, scripts/check-prompts.cjs, scripts/check-prompts-preload.cjs, localTmp/main-ref-0310657/renderer/prompts.js, localTmp/main-ref-0310657/scripts/build-prompts.js, localTmp/main-ref-0310657/scripts/check-prompts.cjs | 27828 | +| P4 | D04 | Page turn and media carousel replacing spinner and colour cards, retired-layout migration, selected-disc geometry, bookshelf disc peek and sizing, carousel checks. | docs/STATE.md, .babysteps/tauri-migration.plan.md, docs/donot.md, .operator/specs/desktop-runtime.md, .babysteps/main-delta.tasks.json, renderer/app.js, renderer/appearance.js, renderer/library-ui.css, renderer/styles.css, scripts/check-carousel.cjs, scripts/check-library-ui.cjs, localTmp/main-ref-0310657/renderer/app.js, localTmp/main-ref-0310657/renderer/appearance.js, localTmp/main-ref-0310657/renderer/library-ui.css, localTmp/main-ref-0310657/renderer/styles.css, localTmp/main-ref-0310657/scripts/check-carousel.cjs, localTmp/main-ref-0310657/scripts/check-library-ui.cjs | 48827 | +| P5 | D05 | Back covers, cartridge lift, spine hinges, label z-offset, physical-media overrides, Super Famicom packaging, booklet proportions. | docs/STATE.md, .babysteps/tauri-migration.plan.md, docs/donot.md, .operator/specs/desktop-runtime.md, .babysteps/main-delta.tasks.json, renderer/app.js, renderer/art.js, renderer/packaging.js, renderer/cartridges.js, renderer/styles.css, localTmp/main-ref-0310657/renderer/app.js, localTmp/main-ref-0310657/renderer/art.js, localTmp/main-ref-0310657/renderer/packaging.js, localTmp/main-ref-0310657/renderer/cartridges.js, localTmp/main-ref-0310657/renderer/styles.css | 53828 | +| P6 | D06 | Library cache and cache-first start, 16-way parallel scan, one listing per folder, tie-only size stats, disc side-file check, title sort, `startLibrary`/`applyLibrary`. | docs/STATE.md, .babysteps/tauri-migration.plan.md, docs/donot.md, .operator/specs/desktop-runtime.md, .babysteps/main-delta.tasks.json, src-tauri/src/backend.rs, src-tauri/src/config.rs, src-tauri/src/lib.rs, renderer/app.js, renderer/tauri-bridge.js, scripts/check-library-ui.cjs, localTmp/main-ref-0310657/main.js, localTmp/main-ref-0310657/renderer/app.js, localTmp/main-ref-0310657/preload.js | 50827 | +| P7 | D07 | Polite web artwork source plus MarioWiki and Internet Archive front-cover fallbacks, disk cache, source UI and checks. | docs/STATE.md, .babysteps/tauri-migration.plan.md, docs/donot.md, .operator/specs/desktop-runtime.md, .babysteps/main-delta.tasks.json, src-tauri/src/artwork.rs, src-tauri/src/backend.rs, renderer/artwork-ui.js, scripts/check-artwork.cjs, scripts/check-artwork-ui.cjs, .operator/specs/artwork-service.md, localTmp/main-ref-0310657/web-source.js, localTmp/main-ref-0310657/mariowiki.js, localTmp/main-ref-0310657/internet-archive.js, localTmp/main-ref-0310657/artwork.js, localTmp/main-ref-0310657/scripts/check-artwork.cjs, localTmp/main-ref-0310657/scripts/check-artwork-ui.cjs | 102827 | +| P8 | D08 | Feedback dialog, report composition, diagnostics/copy/open commands and issue templates. | docs/STATE.md, .babysteps/tauri-migration.plan.md, docs/donot.md, .operator/specs/desktop-runtime.md, .babysteps/main-delta.tasks.json, renderer/index.html, renderer/styles.css, renderer/tauri-bridge.js, src-tauri/src/backend.rs, src-tauri/src/lib.rs, src-tauri/Cargo.toml, localTmp/main-ref-0310657/feedback.js, localTmp/main-ref-0310657/renderer/feedback-ui.js, localTmp/main-ref-0310657/renderer/index.html, localTmp/main-ref-0310657/renderer/styles.css, localTmp/main-ref-0310657/scripts/check-feedback.cjs, localTmp/main-ref-0310657/scripts/check-feedback-ui.cjs, localTmp/main-ref-0310657/.github/ISSUE_TEMPLATE/bug_report.md, localTmp/main-ref-0310657/.github/ISSUE_TEMPLATE/feedback.md | 67827 | +| P9 | D09 | Demo capture, README/CHANGELOG/screenshots, exclusion record, gates and the parity audit close-out. | docs/STATE.md, .babysteps/tauri-migration.plan.md, docs/donot.md, .operator/specs/desktop-runtime.md, .babysteps/main-delta.tasks.json, README.md, docs/SUPPORT.md, package.json, .github/workflows/release.yml, scripts/record-reddit-demo.cjs, scripts/reddit-demo-timeline.js, localTmp/main-ref-0310657/README.md, localTmp/main-ref-0310657/CHANGELOG.md, localTmp/main-ref-0310657/package.json, localTmp/main-ref-0310657/scripts/capture-readme.cjs, localTmp/main-ref-0310657/scripts/record-reddit-demo.cjs, localTmp/main-ref-0310657/scripts/reddit-demo-timeline.js, localTmp/main-ref-0310657/scripts/full-demo-timeline.js | 60975 | +| P10 | M03 | Collection administration, user-added systems and games, hide/group/rename, per-game emulator selection, details editor, hidden list, drag order and Recomp menus from `64a5ba6`. | docs/STATE.md, .babysteps/tauri-migration.plan.md, docs/donot.md, .operator/specs/desktop-runtime.md, .babysteps/main-to-tauri.tasks.json, renderer/app.js, renderer/tauri-bridge.js, src-tauri/src/backend.rs, src-tauri/src/config.rs, src-tauri/src/emulators.rs, scripts/check-library-ui.cjs | 104888 | +| P11a | M04a | Compatible LaunchBox/ScreenScraper provider behavior through the Rust artwork service only; manual workflows stay in M04b. | docs/STATE.md, .babysteps/tauri-migration.plan.md, docs/donot.md, .operator/specs/desktop-runtime.md, .babysteps/main-to-tauri.tasks.json, src-tauri/src/artwork.rs, src-tauri/src/backend.rs, scripts/check-artwork.cjs, .operator/specs/artwork-service.md | 70000 | +| P11b | M04b | Manual discovery/download/viewing workflows (artwork.js manual handling, Art manual drawing, artwork UI) against the provider contract established in M04a. | docs/STATE.md, .babysteps/tauri-migration.plan.md, docs/donot.md, .operator/specs/desktop-runtime.md, .babysteps/main-to-tauri.tasks.json, artwork.js, renderer/art.js, renderer/artwork-ui.js, scripts/check-artwork-ui.cjs | 55000 | +| P12a | M05a | Platform-aware launch behavior: Steam/SteamOS, Linux X11/gamescope, and launch logging only where missing. | docs/STATE.md, .babysteps/tauri-migration.plan.md, docs/donot.md, .operator/specs/desktop-runtime.md, .babysteps/main-to-tauri.tasks.json, renderer/app.js, src-tauri/src/backend.rs, src-tauri/src/config.rs | 70000 | +| P12b | M05b | Emulator metadata and custom/PC game configuration: updated emulator/system metadata and custom/PC game configuration only where missing. | docs/STATE.md, .babysteps/tauri-migration.plan.md, docs/donot.md, .operator/specs/desktop-runtime.md, .babysteps/main-to-tauri.tasks.json, emulators.json, src-tauri/src/emulators.rs, src-tauri/src/config.rs | 50000 | +| P13 | M06 | Remaining parity checks, Tauri release docs and target validation not already closed by D09. | docs/STATE.md, .babysteps/tauri-migration.plan.md, docs/donot.md, .operator/specs/desktop-runtime.md, .babysteps/main-to-tauri.tasks.json, scripts/check-library-ui.cjs, scripts/check-carousel.cjs, scripts/check-artwork.cjs, scripts/check-artwork-ui.cjs, .github/workflows/release.yml, README.md, docs/SUPPORT.md, src-tauri/Cargo.toml, src-tauri/tauri.conf.json | 95019 | + +Order is strictly D01, D02, D03, D04, D05, D06, D07, D08, D09, then M03, M04a, M04b, M05a, M05b, M06 (M03 after D09; M04a after M03; M04b after M04a; M05a after M03; M05b after M03; M06 after M01, M04b and M05b). + +## Exclusions + +- Leia SR is Windows-only: an Electron offscreen renderer and a native D3D11 + presenter. No macOS, Linux ARM64 or Android target can use it, so `native/leia-*`, + `renderer/leia-*`, `leia-output.js`, the `3D` button, `LeiaUI` and the snapshot + IPC are excluded. Revisit only if a Windows target is added. +- Main's Electron release path, `checks.yml`, Capacitor `android/` project and + `start.bat` are excluded. The Tauri `.github/workflows/release.yml` is authoritative. +- The stray 571 KB root file `1` added by `01b77fd` is not ported. +- Do not port all of `main`; port the listed behaviour and adapt it to the branch + renderer. + +## Renderer divergence to respect + +The branch renderer is not a smaller copy of main's: at `b0eec88`, `app.js` is 50 KB +against main's 124 KB, `index.html` 19 KB against 34 KB, `packaging.js` 8 KB against +17 KB, and `cartridges.js` 6 KB against 17 KB. The branch has no `minimal.css` or +`physical-models.css` at all; its rules are merged into `styles.css`. Main's delta +patches therefore have to be translated, not cherry-picked, and whole-file imports +of `minimal.css`/`physical-models.css` are out of scope. + +## Approved task list + +`.babysteps/main-delta.tasks.json` for D01-D09, then `.babysteps/main-to-tauri.tasks.json` +for M03-M06. Do not change scope, estimates or order without re-planning. + +## Reference snapshot + +```sh +mkdir -p localTmp/main-ref-0310657 +git archive 0310657 -- feedback.js main.js preload.js artwork.js web-source.js \ + mariowiki.js internet-archive.js CHANGELOG.md .github/ISSUE_TEMPLATE \ + scripts/build-prompts.js scripts/check-carousel.cjs scripts/check-library-ui.cjs \ + scripts/check-artwork.cjs scripts/check-artwork-ui.cjs scripts/check-feedback.cjs \ + scripts/check-feedback-ui.cjs scripts/check-prompts.cjs scripts/capture-readme.cjs \ + scripts/record-reddit-demo.cjs scripts/reddit-demo-timeline.js \ + scripts/full-demo-timeline.js renderer/app.js renderer/appearance.js \ + renderer/art.js renderer/packaging.js renderer/cartridges.js \ + renderer/library-ui.css renderer/library-ui.js renderer/styles.css \ + renderer/index.html renderer/prompts.js renderer/interface.css \ + renderer/minimal.css renderer/physical-models.css renderer/feedback-ui.js \ + renderer/xmb.css package.json README.md | + tar -x -C localTmp/main-ref-0310657 +``` + diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 0000000..0fc546a --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,21 @@ +--- +name: Report a problem +about: Something in PyroCade is broken or behaving unexpectedly +title: "[Bug] " +--- + +## Problem +What happened, and what did you expect? Include the error message if there is one. + +## Steps to reproduce +1. +2. +3. + +## App and device +- PyroCade version: +- Operating system and version: +- Emulator and version (if relevant): + +## Screenshots or other details (optional) +You can attach screenshots here. Reports are public: remove passwords, personal file paths and other private information. Please do not attach games, BIOS files or keys. diff --git a/.github/ISSUE_TEMPLATE/feedback.md b/.github/ISSUE_TEMPLATE/feedback.md new file mode 100644 index 0000000..6ae0b32 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feedback.md @@ -0,0 +1,14 @@ +--- +name: Feedback or suggestion +about: Share an idea, request a feature or tell us how PyroCade could work better +title: "[Feedback] " +--- + +## Feedback +What would you like to see changed or added? + +## How it would help +Describe what you are trying to do and how this would help you. + +## Examples or screenshots (optional) +Reports are public: leave out passwords, personal file paths and other private information. diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 8deb193..662a900 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1,9 +1,7 @@ -# Builds the Windows installer and the Linux packages, smoke-tests Linux, and attaches -# everything to a *draft* GitHub release. Publish the draft when it looks right; installed -# copies of PyroCade only see published releases. name: Release on: + pull_request: push: tags: ['v*'] workflow_dispatch: @@ -19,75 +17,326 @@ env: TAG: ${{ github.event.inputs.tag || github.ref_name }} jobs: - windows: - runs-on: windows-latest + validate: + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: 22 + cache: npm + - uses: dtolnay/rust-toolchain@stable + - run: sudo apt-get update && sudo apt-get install -y build-essential curl file libgtk-3-dev libssl-dev libwebkit2gtk-4.1-dev libxdo-dev patchelf rpm librsvg2-dev wget xvfb + - run: npm ci + - name: Check Rust formatting + run: cargo fmt --manifest-path src-tauri/Cargo.toml -- --check + - name: Test migrated Rust behavior + run: npm run tauri:test + - name: Check renderer and parity scripts + run: | + node --check scripts/check-library-ui.cjs + node --check scripts/check-carousel.cjs + node --check scripts/check-artwork.cjs + node --check scripts/check-artwork-ui.cjs + npm run artwork:check + - name: Check Rust targets + run: cargo check --manifest-path src-tauri/Cargo.toml + + macos-arm64: + if: ${{ github.event_name != 'pull_request' }} + needs: validate + runs-on: macos-14 + env: + TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }} + TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }} + TAURI_UPDATER_PUBLIC_KEY: ${{ vars.TAURI_UPDATER_PUBLIC_KEY }} steps: - uses: actions/checkout@v4 with: { ref: '${{ env.TAG }}' } - uses: actions/setup-node@v4 with: { node-version: 22, cache: npm } - run: npm ci - - run: npx electron-builder --win nsis --publish never + - uses: dtolnay/rust-toolchain@stable + with: + targets: aarch64-apple-darwin + - name: Verify native ARM64 runner + run: test "$(uname -m)" = arm64 + - name: Build macOS ARM64 release + run: | + if [ -n "$TAURI_SIGNING_PRIVATE_KEY" ] && [ -n "$TAURI_UPDATER_PUBLIC_KEY" ]; then + TAURI_CONFIG="$(python3 - <<'PY' + import json, os + print(json.dumps({ + "bundle": {"createUpdaterArtifacts": True}, + "plugins": {"updater": { + "pubkey": os.environ["TAURI_UPDATER_PUBLIC_KEY"], + "endpoints": [f"https://github.com/{os.environ['GITHUB_REPOSITORY']}/releases/latest/download/latest.json"], + }}, + })) + PY + )" + export TAURI_CONFIG + fi + npm run dist:macos:arm64 + - name: Install and smoke-test macOS ARM64 artifact + env: + APP_SMOKE_STARTUP_SECONDS: 10 + run: | + dmg=$(find src-tauri/target/aarch64-apple-darwin/release/bundle/dmg -name '*.dmg' -print -quit) + test -n "$dmg" + mountpoint="$RUNNER_TEMP/pyrocade-dmg" + installed_app="$RUNNER_TEMP/Applications/PyroCade.app" + mkdir -p "$mountpoint" "$(dirname "$installed_app")" + hdiutil attach "$dmg" -nobrowse -readonly -mountpoint "$mountpoint" + app=$(find "$mountpoint" -maxdepth 2 -name '*.app' -print -quit) + test -n "$app" + ditto "$app" "$installed_app" + hdiutil detach "$mountpoint" + executable=$(/usr/libexec/PlistBuddy -c 'Print :CFBundleExecutable' "$installed_app/Contents/Info.plist") + "$installed_app/Contents/MacOS/$executable" >"$RUNNER_TEMP/pyrocade-smoke.log" 2>&1 & + app_pid=$! + sleep "$APP_SMOKE_STARTUP_SECONDS" + if ! kill -0 "$app_pid" 2>/dev/null; then + cat "$RUNNER_TEMP/pyrocade-smoke.log" + exit 1 + fi + kill "$app_pid" + wait "$app_pid" || true + - name: Collect macOS release artifacts + run: | + mkdir -p dist + cp -f src-tauri/target/aarch64-apple-darwin/release/bundle/dmg/*.dmg dist/ + cp -f src-tauri/target/aarch64-apple-darwin/release/bundle/macos/*.app.tar.gz dist/ 2>/dev/null || : + cp -f src-tauri/target/aarch64-apple-darwin/release/bundle/macos/*.app.tar.gz.sig dist/ 2>/dev/null || : - uses: actions/upload-artifact@v4 with: - name: windows - path: dist/PyroCade-Setup-*.exe + name: pyrocade-macos-arm64 + path: dist/* if-no-files-found: error - linux: - runs-on: ubuntu-22.04 + linux-arm64: + if: ${{ github.event_name != 'pull_request' }} + needs: validate + runs-on: macos-14 + env: + TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }} + TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }} + TAURI_UPDATER_PUBLIC_KEY: ${{ vars.TAURI_UPDATER_PUBLIC_KEY }} steps: - uses: actions/checkout@v4 with: { ref: '${{ env.TAG }}' } - uses: actions/setup-node@v4 with: { node-version: 22, cache: npm } - # rpm builds the Fedora package, libarchive-tools the Arch one; xvfb runs the smoke test. - - run: sudo apt-get update && sudo apt-get install -y rpm libarchive-tools xvfb - run: npm ci - - run: npx electron-builder --linux AppImage deb rpm pacman --publish never - - name: Smoke test the AppImage + - name: Build and package Linux ARM64 in Apple Container env: - APPIMAGE_EXTRACT_AND_RUN: '1' - PYROCADE_SNAP: ${{ runner.temp }}/appimage.png - PYROCADE_JS: (async()=>JSON.stringify({version:await api.appVersion(),emulators:(await api.emuList()).filter(e=>e.managed).length,demo:!document.getElementById('demoBanner').classList.contains('hidden')}))() + GITHUB_REPOSITORY: ${{ github.repository }} run: | - chmod +x dist/PyroCade-*.AppImage - timeout 120 xvfb-run -a dist/PyroCade-*.AppImage --no-sandbox - cat "$PYROCADE_SNAP.txt"; echo - test -s "$PYROCADE_SNAP" - grep -q '"emulators":11' "$PYROCADE_SNAP.txt" - - name: Smoke test the .deb + set -eu + mkdir -p dist + container run --rm --memory 3G --cpus 4 \ + -v "$GITHUB_WORKSPACE:/work" -w /work \ + -e GITHUB_REPOSITORY \ + ubuntu:24.04 bash -lc ' + set -eu + apt-get update + DEBIAN_FRONTEND=noninteractive apt-get install -y build-essential curl file libgtk-3-dev libssl-dev libwebkit2gtk-4.1-dev libxdo-dev patchelf rpm librsvg2-dev wget xvfb pkg-config + curl -fsSL https://deb.nodesource.com/setup_22.x | bash - + DEBIAN_FRONTEND=noninteractive apt-get install -y nodejs + curl --proto "=https" --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --profile minimal + . "$HOME/.cargo/env" + rustup target add aarch64-unknown-linux-gnu + cargo install tauri-cli --locked + export CARGO_TARGET_DIR=/work/localTmp/linux-arm64-target + mkdir -p "$CARGO_TARGET_DIR" + cat > /tmp/build-appimage.mjs <<'JS' + import { spawnSync } from 'node:child_process'; + import fs from 'node:fs'; + import path from 'node:path'; + import os from 'node:os'; + const root = '/work'; + const env = { ...process.env, PATH: `${process.env.HOME}/.cargo/bin:${process.env.PATH}` }; + const run = (command, args, options = {}) => { + const result = spawnSync(command, args, { stdio: 'inherit', env, ...options }); + if (result.status !== 0) throw new Error(`${command} failed with ${result.status}`); + }; + const targetDir = '/work/localTmp/linux-arm64-target'; + const bundle = path.join(targetDir, 'aarch64-unknown-linux-gnu/release/bundle'); + const bundleAppImage = path.join(bundle, 'appimage'); + const base = path.join(os.tmpdir(), 'pyrocade-appimage'); + const target = path.join(base, 'appdir'); + fs.rmSync(base, { recursive: true, force: true }); + fs.mkdirSync(base, { recursive: true }); + run('cargo', ['tauri', 'build', '--target', 'aarch64-unknown-linux-gnu', '--bundles', 'deb,rpm'], { cwd: root, env: { ...env, CARGO_TARGET_DIR: targetDir } }); + const appimageConfig = { bundle: { targets: ['appimage'], createUpdaterArtifacts: Boolean(env.TAURI_SIGNING_PRIVATE_KEY && env.TAURI_UPDATER_PUBLIC_KEY) } }; + if (env.TAURI_UPDATER_PUBLIC_KEY) appimageConfig.plugins = { updater: { pubkey: env.TAURI_UPDATER_PUBLIC_KEY, endpoints: [`https://github.com/${env.GITHUB_REPOSITORY}/releases/latest/download/latest.json`] } }; + const appimageEnv = { ...env, TAURI_CONFIG: JSON.stringify(appimageConfig), CARGO_TARGET_DIR: targetDir }; + run('cargo', ['tauri', 'build', '--target', 'aarch64-unknown-linux-gnu', '--bundles', 'appimage'], { cwd: root, env: appimageEnv }); + const sourceAppDir = path.join(bundleAppImage, 'PyroCade.AppDir'); + if (!fs.existsSync(sourceAppDir)) throw new Error(`Tauri did not produce ${sourceAppDir}`); + const copyTree = (sourceDir, targetDir) => { + fs.mkdirSync(targetDir, { recursive: true }); + for (const entry of fs.readdirSync(sourceDir, { withFileTypes: true })) { + const sourceFile = path.join(sourceDir, entry.name); + const targetFile = path.join(targetDir, entry.name); + if (entry.isDirectory()) copyTree(sourceFile, targetFile); + else if (entry.isSymbolicLink()) fs.symlinkSync(fs.readlinkSync(sourceFile), targetFile); + else fs.copyFileSync(sourceFile, targetFile); + } + }; + copyTree(sourceAppDir, target); + fs.chmodSync(target, 0o755); + const executable = path.join(target, 'usr/bin/pyrocade'); + if (!fs.existsSync(executable)) throw new Error(`Missing AppImage executable: ${executable}`); + const appimagetool = path.join(base, 'appimagetool'); + run('curl', ['-fL', 'https://github.com/AppImage/appimagetool/releases/download/continuous/appimagetool-aarch64.AppImage', '-o', appimagetool]); + fs.chmodSync(appimagetool, 0o755); + run(appimagetool, ['--appimage-extract'], { cwd: base }); + const toolDir = path.join(base, 'squashfs-root'); + if (!fs.existsSync(path.join(toolDir, 'AppRun'))) throw new Error('Failed to extract appimagetool runtime'); + const pkgVersion = JSON.parse(fs.readFileSync(path.join(root, 'src-tauri/tauri.conf.json'), 'utf8')).version; + const out = path.join(root, 'dist', `PyroCade_${pkgVersion}_aarch64-extract.AppImage`); + const runtime = path.join(base, 'runtime-aarch64'); + run('curl', ['-fL', 'https://github.com/AppImage/AppImageKit/releases/download/continuous/runtime-aarch64', '-o', runtime]); + fs.chmodSync(runtime, 0o755); + run(path.join(toolDir, 'AppRun'), ['--runtime-file', runtime, target, out], { cwd: base, env: { ...env, ARCH: 'arm64' } }); + if (!fs.existsSync(out)) throw new Error(`Missing extracted-type AppImage: ${out}`); + for (const kind of ['deb', 'rpm']) { + const source = path.join(bundle, kind); + for (const file of fs.readdirSync(source)) { + const p = path.join(source, file); + if (fs.statSync(p).isFile()) fs.copyFileSync(p, path.join(root, 'dist', file)); + } + } + JS + node /tmp/build-appimage.mjs + ' + - uses: actions/upload-artifact@v4 + with: + name: pyrocade-linux-arm64 + path: dist/* + if-no-files-found: error + + android-arm64: + needs: validate + runs-on: ubuntu-24.04 + env: + NODE_VERSION: '22' + JAVA_VERSION: '17' + ANDROID_COMPILE_API_LEVEL: '36' + ANDROID_TARGET_API_LEVEL: '35' + ANDROID_BUILD_TOOLS_VERSION: '36.0.0' + ANDROID_NDK_VERSION: '28.2.13676358' + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || env.TAG }} + - uses: actions/setup-node@v4 + with: + node-version: ${{ env.NODE_VERSION }} + cache: npm + - uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: ${{ env.JAVA_VERSION }} + - uses: android-actions/setup-android@v3 + - name: Install pinned Android SDK components + run: | + sdkmanager --install "platforms;android-${ANDROID_COMPILE_API_LEVEL}" "platforms;android-${ANDROID_TARGET_API_LEVEL}" "build-tools;${ANDROID_BUILD_TOOLS_VERSION}" "ndk;${ANDROID_NDK_VERSION}" + set +e + yes | sdkmanager --licenses + license_status=${PIPESTATUS[1]} + set -e + test "$license_status" -eq 0 + - uses: dtolnay/rust-toolchain@stable + with: + targets: aarch64-linux-android + - run: npm ci + - name: Add APK output directory + run: mkdir -p dist + - name: Generate Android project + run: npm run tauri -- android init --ci --skip-targets-install + - name: Build Android ARM64 APK env: - PYROCADE_SNAP: ${{ runner.temp }}/deb.png + KEYSTORE_B64: ${{ secrets.PYROCADE_ANDROID_KEYSTORE }} + KEYSTORE_PASSWORD: ${{ secrets.PYROCADE_ANDROID_KEYSTORE_PASSWORD }} + KEY_ALIAS: ${{ secrets.PYROCADE_ANDROID_KEY_ALIAS }} + KEY_PASSWORD: ${{ secrets.PYROCADE_ANDROID_KEY_PASSWORD }} run: | - sudo apt-get install -y ./dist/pyrocade_*_amd64.deb - timeout 120 xvfb-run -a pyrocade --no-sandbox - test -s "$PYROCADE_SNAP" + keystore_dir="$RUNNER_TEMP/android-signing" + mkdir -p "$keystore_dir" + if [ -n "$KEYSTORE_B64" ]; then + echo "$KEYSTORE_B64" | base64 -d > "$keystore_dir/release.keystore" + chmod 600 "$keystore_dir/release.keystore" + export TAURI_ANDROID_KEYSTORE_PATH="$keystore_dir/release.keystore" + export TAURI_ANDROID_KEYSTORE_PASSWORD="$KEYSTORE_PASSWORD" + export TAURI_ANDROID_KEY_ALIAS="$KEY_ALIAS" + export TAURI_ANDROID_KEY_PASSWORD="$KEY_PASSWORD" + elif [ "$GITHUB_EVENT_NAME" != "pull_request" ]; then + echo "A stable private Android keystore is required for release builds." >&2 + exit 1 + fi + npm run dist:android:arm64 - uses: actions/upload-artifact@v4 with: - name: linux - path: | - dist/PyroCade-*.AppImage - dist/pyrocade_*.deb - dist/pyrocade-*.rpm - dist/pyrocade-*.pkg.tar.zst - ${{ runner.temp }}/*.png + name: ${{ github.event_name == 'pull_request' && 'pyrocade-android-arm64-unsigned-ci' || 'pyrocade-android-arm64' }} + path: dist/*.apk if-no-files-found: error release: - needs: [windows, linux] + needs: [validate, macos-arm64, linux-arm64, android-arm64] runs-on: ubuntu-latest steps: + - run: mkdir -p dist - uses: actions/download-artifact@v4 - with: { path: out } + with: { path: dist } + - name: Generate signed updater manifest + env: + GH_REPO: ${{ github.repository }} + GH_TAG: ${{ env.TAG }} + run: | + python3 - <<'PY' + from datetime import datetime, timezone + import json, os + from pathlib import Path + from urllib.parse import quote + + platforms = {} + for signature_path in Path("dist").rglob("*.sig"): + filename = signature_path.name[:-4] + if filename.endswith(".app.tar.gz"): + target = "darwin-aarch64" + elif filename.endswith("-extract.AppImage"): + target = "linux-aarch64" + else: + continue + artifact = signature_path.with_name(filename) + if not artifact.is_file(): + continue + platforms[target] = { + "signature": signature_path.read_text().strip(), + "url": f"https://github.com/{os.environ['GH_REPO']}/releases/download/{quote(os.environ['GH_TAG'])}/{quote(filename)}", + } + + if platforms: + manifest = { + "version": os.environ["GH_TAG"].lstrip("vV"), + "pub_date": datetime.now(timezone.utc).isoformat(), + "platforms": platforms, + } + Path("dist/latest.json").write_text(json.dumps(manifest, indent=2) + "\n") + print(f"Generated signed updater manifest for: {', '.join(sorted(platforms))}") + else: + print("No signed updater artifacts; releases will use manual update links.") + PY - name: Attach to draft release env: GH_TOKEN: ${{ github.token }} GH_REPO: ${{ github.repository }} run: | - files=$(find out -type f \( -name '*.exe' -o -name '*.AppImage' -o -name '*.deb' -o -name '*.rpm' -o -name '*.pkg.tar.zst' \)) + mapfile -d '' files < <(find dist -mindepth 2 -type f ! -name '*.idsig' -print0) if gh release view "$TAG" >/dev/null 2>&1; then - gh release upload "$TAG" $files --clobber + gh release upload "$TAG" "${files[@]}" --clobber else - gh release create "$TAG" $files --draft --title "PyroCade ${TAG#v}" --generate-notes + gh release create "$TAG" "${files[@]}" --draft --title "PyroCade ${TAG#v}" --generate-notes fi diff --git a/.gitignore b/.gitignore index 0944209..ba2efb9 100644 --- a/.gitignore +++ b/.gitignore @@ -15,5 +15,13 @@ Desktop.ini .vscode/ *.log -# Installer builds +# Installer builds and scratch references dist/ +localTmp/ +src-tauri/target/ +src-tauri/gen/schemas/ +src-tauri/gen/android/ +.opencode/ +.operator/ +.rnsk-memory/ +./.rnsk-memory diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..f99a83a --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,330 @@ +# PyroCade — `tauri-port` Fork (Windows build guide) + +> **Windows-only: if you are building on macOS, ignore this file.** +> This file lives at the repo root, *outside* `renderer/`. The Tauri build +> bundles `frontendDist` (`../renderer`), so `AGENTS.md` is never packaged into +> a macOS `.app`/`.dmg` (or any other bundle) and is not read by any build +> script. On a Mac, delete/skip this file and build with the standard +> `npm run dist:macos:arm64` flow instead. + +An agent (Claude Code / Anthropic harness, Cursor, Copilot, etc.) ramping on +this fork should treat **Windows as the primary target**. Upstream +(`Pyrodrifter/PyroCade`, branch `main`) is the original Electron app. This +fork (`kaicherry/PyroCade`, branch `tauri-port`) is the Tauri v2 port. + +``` +Branch: tauri-port Remote: https://github.com/kaicherry/PyroCade.git +Renderer: renderer/ (static HTML/CSS/JS, no bundler) +Host: src-tauri/ (Tauri 2 + Rust) +Emulator catalog: emulators.json +CI: .github/workflows/release.yml +``` + +Electron is **dev-only** — it is not part of the shipped app. It is used for +`scripts/check-*.cjs` harness runs (`prompts:export`, `prompts:check`, +`carousel:check`, `brand:*`, `demo:record`, `docs:screens`). The shipped runtime +is Tauri WebView2 (Windows) / WKWebView (macOS) / WebKitGTK (Linux). + +--- + +## 1. Prerequisites (Windows) + +All paths below assume PowerShell 7+ (or Windows Terminal) and a **native +Win32** checkout (not WSL for the Tauri build itself). + +| Tool | Version / notes | +|------|-----------------| +| Windows | 10 (1809+) or 11, x64. ARM64 Windows cross-build is not configured. | +| Git | For `git clone`; line endings must be `CRLF` (default on Windows) | +| Node.js | **22 LTS** (match `.github/workflows/release.yml`). Add Node to `PATH` before Tauri. | +| Rust | **stable** via rustup; MSVC target. `rustup toolchain install stable`, `rustup default stable`. | +| MSVC Build Tools | Required by Tauri/Rust: **Visual Studio Build Tools 2022** with _“Desktop development with C++”_ workload (MSVC v143, Windows 10/11 SDK). | +| WebView2 | Pre-installed on Win10 1809+/Win11. On older/enterprise images, install the Evergreen Runtime: | +| NSIS / WiX | Optional for Windows installers. If you add bundle targets, install NSIS (and WiX 3 for MSI) and ensure `makensis.exe` is on `PATH`. | + +Verify: + +```powershell +node -v # v22.x +npm -v +cargo --version +rustc --version +cl.exe # from “Developer PowerShell for VS 2022” — or install Build Tools +``` + +If `cl.exe` is not found, launch a **Developer PowerShell for VS 2022**, +or run `vswhere` / enable “VS Developer Shell” before `tauri build`. + +--- + +## 2. Clone and install + +```powershell +git clone https://github.com/kaicherry/PyroCade.git pyroCade +Set-Location pyroCade +git checkout tauri-port +npm ci +``` + +`npm ci` installs `npm` deps including `@tauri-apps/cli` (`^2.11.4`) and +dev-only `electron` (`^39.0.0`). `cargo` deps install on first build. + +If Electron fails with `Electron failed to install correctly, please delete +node_modules/electron`: + +```powershell +Remove-Item -Recurse -Force node_modules\electron +npm install electron --ignore-scripts=false +``` + +Electron is only needed for `npx electron scripts/*.cjs` checks. Tauri +`tauri dev` / `tauri build` do not need a working Electron install. + +--- + +## 3. Run in dev mode + +```powershell +npm start +# = tauri dev +``` + +Runs the Rust host + dev WebView and presents `renderer/index.html`. The +renderer is **static** — there is no `vite`/`webpack` step. Edit +`renderer/*.js|css` and the dev window reloads. + +- Rust changes: Vite-style hot reload does **not** apply — let `tauri dev` + rebuild the Rust binary. +- To test the release bundle: `npm run build` (see §4). + +Environment: + +| Var | Purpose | +|-----|---------| +| `TAURI_CONFIG` | Override bundle keys at build time (updater pubkey/endpoints in CI). | +| `CARGO_TARGET_DIR` | Custom target dir (CI Linux job uses `localTmp/`; on Windows you can keep the default `src-tauri\target\`). | + +--- + +## 4. Build a Windows release + +Windows x64 artifacts are produced two ways: + +### Native (on Windows) + +```powershell +# Dev/debug bundle (single-file .exe + default targets) +npx tauri build + +# Bundled release (same command, release profile) +npm run build + +# Output layout (default targets from src-tauri/tauri.conf.json) +# src-tauri\target\release\pyrocade.exe +# src-tauri\target\release\bundle\ +``` + +### Cross-compile from macOS (cargo-xwin) + +Tauri documents NSIS cross-compilation from macOS/Linux (MSI needs Windows/WiX). +Prerequisites on macOS: `brew install nsis llvm lld`, `rustup target add +x86_64-pc-windows-msvc`, `cargo install --locked cargo-xwin`. Use the +**rustup** toolchain (Homebrew `rustc` lacks the Windows target) and expose +LLVM's `llvm-rc`/`lld`: + +```bash +export PATH="/Users/kaicherry/.rustup/toolchains/stable-aarch64-apple-darwin/bin:$HOME/.cargo/bin:/opt/homebrew/opt/llvm@22/bin:$PATH" +npm run tauri build -- --runner cargo-xwin --target x86_64-pc-windows-msvc --bundles nsis +# → src-tauri/target/x86_64-pc-windows-msvc/release/bundle/nsis/PyroCade_*_x64-setup.exe +``` + +If `rust-lld` aborts with `Library not loaded: @rpath/libLLVM.dylib`, symlink +`~/.rustup/.../lib/libLLVM.dylib` into +`~/.rustup/.../lib/rustlib/aarch64-apple-darwin/lib/` (rustup layout puts it +one level up from where the linker looks). `windows.nsis.installerIcon` +must be `../renderer/assets/brand/pyrocade.ico` (NSIS needs ICO, not PNG). + +### Bundle targets + +`src-tauri/tauri.conf.json` lists: + +```json +"targets": ["app", "dmg", "appimage", "deb", "rpm", "nsis", "msi"] +``` + +`nsis`/`msi` are native Windows installers. `app`/`dmg`/`appimage`/`deb`/`rpm` +are the macOS/Linux set (see §5 table). Fixtures built from macOS supply +`PyroCade_*_x64-setup.exe` (NSIS) + portable `PyroCade_*_x64.exe`. + +For a **single-file exe / app folder only** (no installer), keep default +`targets` and use `src-tauri\target\release\pyrocade.exe` (or +`bundle\msi\`/`nsis\` when enabled). Copy the `.exe` for manual QA without +building installers. + +### Linux AppImage (extract-type, non-FUSE) + +Build in Apple Containers with **container-local** storage (spec: +`desktop-runtime.md`): one-shot `container run --memory 3G --cpus 4` for +ARM64, `-a x86_64` for x86_64 via Rosetta 2 (never Lima QEMU — ~50 min). +Inside the container: deps + Node 22 + Rust + `cargo tauri build`, then +`copyTree` the `PyroCade.AppDir` to `os.tmpdir()` and package with + +``` +AppRun --runtime-file +``` + +(`cargo tauri build --bundles appimage` alone already emits a standard +AppImage; the extract-type repack is the distributable on the release page.) + +### macOS signing / notarization + +macOS artifacts use Developer ID + notarization: + +```bash +APPLE_SIGNING_IDENTITY="Developer ID Application: …" \ + npm run tauri build -- --target aarch64-apple-darwin --bundles app,dmg +xcrun notarytool submit dist/PyroCade_*_aarch64.dmg --keychain-profile impressium --wait +xcrun stapler staple dist/PyroCade_*_aarch64.dmg +``` + +`impressium` is a stored `notarytool` Keychain profile (Apple ID + Team ID + +app-specific password already in Keychain). Verify with +`spctl -a -vv PyroCade.app` → `accepted source=Notarized Developer ID`. + +### Android signing + +Applies on Windows, macOS and CI alike. Tauri reads +`src-tauri/gen/android/keystore.properties` (private, gitignored): + +``` +keyAlias=pyrocade +storeFile=/Users//.keystores/pyrocade.jks +``` + +plus a `signingConfigs.release` block in the generated +`app/build.gradle.kts`. Both are produced by `scripts/configure-android.cjs` +when `TAURI_ANDROID_KEYSTORE_PATH` / `TAURI_ANDROID_KEYSTORE_PASSWORD` / +`TAURI_ANDROID_KEY_ALIAS` / `TAURI_ANDROID_KEY_PASSWORD` env are set; +generate the store once with `keytool -genkeypair -keystore ~/.keystores/pyrocade.jks +-alias pyrocade -keyalg RSA -keysize 2048 -validity 10000`, then + +```bash +npm run tauri:android:configure +RUSTC="$(rustup which rustc)" npm run dist:android:arm64 +``` + +Signed output is `app-arm64-release.apk` (rename to +`PyroCade_0.2.1_android-arm64.apk` for the release). Verify with +`$ANDROID_HOME/build-tools/36.0.0/apksigner verify --print-certs dist/*.apk`. + +### Emulator catalog on Windows + +`emulators.json` uses per-OS `platforms` keys (`windows` / `macos` / `linux`). +`src-tauri/src/emulators.rs::target_platform()` returns `windows` under +`cfg(target_os = "windows")`. On Windows, the downloader selects the +`windows/x86_64` (or current-arch) asset when present. Custom linking +(“Use existing program…”, “Choose program…”, `--with-args {rom}`) is the +same flow as the other OSes. + +### App data on Windows + +Per-user data (`config.json`, `data/emulators//`, `data/media/`) lives +under Tauri's app-data dir (notably `%APPDATA%\PyroCade` / Letta-style path +returned by `dirs`). Never commit `data/` — it is `.gitignored`. + +--- + +## 5. Checks + +Run from the repo root (PowerShell). All should be green before opening a PR. + +```powershell +# Rust (gates — fmt/test/check) +cargo fmt --manifest-path src-tauri/Cargo.toml -- --check +cargo test --manifest-path src-tauri/Cargo.toml +cargo check --manifest-path src-tauri/Cargo.toml + +# Renderer / parity checks +node scripts/check-artwork.cjs # npm run artwork:check +node scripts/check-feedback.cjs # part of npm run feedback:check +``` + +Electron checks (`npx electron scripts/check-*.cjs`, `npm run prompts:check`, +`npm run carousel:check`, etc.) run the static renderer headless — they +exercise Nintendo/Xbox/PlayStation prompts, carousel layout, brand/icon +export and demo timelines without a Tauri window. + +On Windows, prefer `node --check + + @@ -216,6 +368,10 @@

Download artwork

+ + + + diff --git a/renderer/interface.css b/renderer/interface.css new file mode 100644 index 0000000..b4ef147 --- /dev/null +++ b/renderer/interface.css @@ -0,0 +1,237 @@ +/* Shared chrome for the launcher. Game art and case materials keep their own colours. */ +:root { + color-scheme: dark; + --canvas: #1d1c1b; + --surface: #272523; + --raised: #302e2c; + --hover: #3b3936; + --field: #211f1e; + --line: #45423f; + --control-line: #5c5853; + --text: #f2eee8; + --muted: #bbb7b1; + --secondary: #a39e98; + --accent: #efaa68; + --accent2: #ffca97; + --ink: #24211f; + --selected: color-mix(in srgb, var(--accent) 21%, var(--surface)); + --stage-light: color-mix(in srgb, var(--accent) 14%, #363330); + --glass: var(--surface); + --bar-text: var(--muted); + --bar-dim: var(--secondary); + --bar-hover: var(--raised); + --bar-pill: var(--selected); + --gutter: clamp(24px, 3.2vw, 60px); + --radius: 7px; +} + +html, body { background: var(--canvas); font-family: "Segoe UI Variable Text", "Segoe UI", system-ui, sans-serif; } +body { scrollbar-color: var(--control-line) var(--field); } + +button, .actions button, .view:not(#view-library) button, #info .actions button { + border: 1px solid var(--line); + border-radius: var(--radius); + background: var(--raised); + color: var(--text); + box-shadow: none; + font-weight: 550; +} +button:hover, .actions button:hover, .view:not(#view-library) button:hover, #info .actions button:hover { + background: var(--hover); + border-color: var(--control-line); +} +button.primary, .actions button.primary, +.view:not(#view-library) button.primary, #info .actions button.primary { + background: var(--accent); + color: var(--ink); + border: 1px solid transparent; + box-shadow: none; + font-weight: 650; +} +button.primary:hover, .actions button.primary:hover, +.view:not(#view-library) button.primary:hover, #info .actions button.primary:hover { + background: var(--accent2); + border-color: transparent; + box-shadow: none; +} +input, select, textarea, .view:not(#view-library) :is(input:not([type=checkbox], [type=range], [type=color]), select) { + background: var(--field); + color: var(--text); + border-color: var(--control-line); + border-radius: var(--radius); +} +input::placeholder, textarea::placeholder { color: var(--secondary); } +select option, select optgroup { background: var(--field); color: var(--text); } +input:is([type=checkbox], [type=range]) { accent-color: var(--accent); } +:is(button, a, input, select, textarea, summary, [tabindex]):focus-visible { + outline: 2px solid var(--accent2); + outline-offset: 3px; +} +kbd, code { background: var(--field); border-color: var(--line); color: var(--muted); } +a { color: var(--accent2); } + +/* Keep the backdrop charcoal, with the active accent concentrated around the shelf. */ +#bg, html:not([data-theme=ember]) #bg { + background: radial-gradient(ellipse at 50% 43%, var(--stage-light), var(--canvas) 71%); +} +.bg-layer, html:not([data-theme=ember]) .bg-layer { filter: blur(68px) grayscale(.76); } +.bg-layer.on { opacity: .12; } +.bg-vignette { background: linear-gradient(180deg, transparent 25%, var(--canvas) 97%); } +html:has(#xmb[data-scene=ribbon]) #xmb { opacity: .26; } +html.ambient:has(#xmb[data-scene=ribbon]) #xmb { opacity: .45; } +#floor, html:not([data-theme=ember]) #floor { + background: radial-gradient(ellipse at 50% 50%, color-mix(in srgb, var(--accent) 22%, transparent), transparent 70%); + opacity: .65; +} +#caseView { background: radial-gradient(ellipse at 50% 43%, var(--stage-light), #171615 76%); } + +/* Library */ +header { background: transparent; } +header::after, #info::before, html:not([data-theme=ember]) #info::before { background: var(--line); } +header .toolbar { border-color: var(--line); } +.brand { letter-spacing: .17em; } +#tabs { gap: 2px; padding: 0; background: none; border: 0; border-radius: 0; backdrop-filter: none; } +#tabs button, .chips .system-tile { + position: relative; + border: 0; + border-radius: var(--radius); + background: none; + box-shadow: none; + backdrop-filter: none; + color: var(--bar-text); +} +#tabs button:hover, .chips .system-tile:hover { background: var(--bar-hover); color: var(--text); } +#tabs button.active, .chips .system-tile.active { background: var(--bar-pill); color: #fff; } +#tabs button.active::after, .chips .system-tile.active::after { + content: ''; + position: absolute; + left: 12px; + right: 12px; + bottom: 3px; + height: 2px; + border-radius: 2px; + background: var(--accent); +} +.system-browser, #btnAppearance { border-radius: var(--radius); } +.search, .system-picker-search { + background: var(--field); + border: 1px solid var(--control-line); + border-radius: var(--radius); +} +.search:focus-within, .system-picker-search:focus-within { border-color: var(--accent2); } +.search input, .system-picker-search input { background: transparent; } +.search input:focus-visible, .system-picker-search input:focus-visible { outline: none; } +#clearSearch { background: transparent; color: var(--muted); } +.shelf-arrow { + background: var(--surface); + border-color: var(--line); + border-radius: var(--radius); + box-shadow: none; + backdrop-filter: none; +} +.shelf-arrow:hover { background: var(--hover); } +.shelf-position { left: var(--gutter); right: var(--gutter); opacity: 1; color: var(--muted); } +.shelf-progress { background: var(--line); height: 2px; } +.shelf-progress i, .bar i, #artProgress::-webkit-progress-value { background: var(--accent); box-shadow: none; } +#info { background: none; padding-inline: var(--gutter); } +#info::before { left: var(--gutter); right: var(--gutter); } +#info h1, .case-title h2 { font-weight: 625; letter-spacing: -.025em; text-shadow: none; } +#gDesc, .prompt-hint { color: var(--muted); } +#libraryHints { left: var(--gutter); right: var(--gutter); border-color: var(--line); } +#info .actions button { white-space: nowrap; } +#info .shot { border-radius: var(--radius); box-shadow: none; } +#gShot.shot-empty { background: var(--field); border-color: var(--control-line); } + +/* Management screens */ +#view-emus, #view-artwork, #view-settings { + background: var(--canvas); + padding: 32px max(var(--gutter), calc((100vw - 1440px) / 2)) 48px; +} +.view:not(#view-library) .view-head { align-items: flex-start; margin-bottom: 26px; } +.view:not(#view-library) .view-head h1 { font-size: clamp(29px, 2.4vw, 36px); font-weight: 625; letter-spacing: -.035em; } +.view:not(#view-library) .view-head .sub { color: var(--muted); line-height: 1.55; } +.view:not(#view-library) :is(.panel, .emu) { + background: var(--surface); + border-color: var(--line); + border-radius: 10px; + backdrop-filter: none; +} +.view:not(#view-library) .panel h2 { font-size: 17px; font-weight: 625; letter-spacing: -.015em; } +.emu h3 { letter-spacing: -.015em; } +.emu-source, .help pre { background: var(--field); color: var(--muted); } +.emu .tag, .art-state { border-radius: 4px; background: var(--field); } +.emu .tag.ok, #artImportStatus, .art-state[data-status=complete] { color: #b9cfae; } +.emu .tag.up { color: #e0c496; } +.art-field, #artTypes legend, .art-state { color: var(--muted); } +.art-state[data-status=running] { color: var(--accent2); border-color: var(--control-line); } +.art-stats strong { font-weight: 600; } +.art-stats span, #artTypes small { font-size: 12px; } +#artTypes { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 12px 16px; } +#artTypes label { margin: 0; } +.art-retry + .art-retry { margin-top: 8px; } +.art-options > .actions { margin-top: 20px; } +.settings-groups { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 16px; } +.settings-groups > .panel { min-width: 0; } +.settings-groups h2 { margin: 0 0 15px; } +.settings-groups .row:not(.check) { min-height: 33px; } +.settings-groups .row > span { width: 9.5em; flex: 0 0 9.5em; } +.settings-groups .row :is(input, select) { min-width: 0; } +.settings-groups .row .update-version { width: auto; flex: none; } +.settings-groups .row.check { min-height: 28px; } +.settings-groups .prompt-note { margin: 5px 0 12px; } +.settings-groups .prompt-note:empty, #settingsScanStatus:empty { display: none; } +.settings-section-title { margin: 24px 0 12px; font-size: 17px; font-weight: 625; } +#sysTable { margin-top: 12px; } +#sysTable thead { background: var(--field); } +#sysTable th { font-size: 11px; letter-spacing: .035em; text-transform: none; } +#sysTable tbody tr:hover { background: #ffffff04; } + +/* Dialogs and overlays */ +:is(#systemPicker, #appearancePicker), +#toast { + background: var(--surface); + border: 1px solid var(--control-line); + border-radius: 11px; + color: var(--text); + box-shadow: 0 16px 52px #0006; + backdrop-filter: none; +} +:is(#systemPicker, #appearancePicker)::backdrop { + background: #151413b3; + backdrop-filter: blur(4px); +} +#appearancePicker .system-picker-heading { margin-bottom: 12px; } +.appearance-label { margin: 17px 0 8px; } +#appearancePicker .row.check { font-size: 12px; } +.system-picker-heading h2 { + font-weight: 625; + letter-spacing: -.025em; +} +.system-picker-heading > button { color: var(--muted); border-radius: var(--radius); } +.appearance-label, .appearance-note, .system-picker-footer, +.system-picker-card .n, .sound-controls output { + color: var(--muted); +} +.appearance-label { text-transform: none; letter-spacing: .03em; font-weight: 600; font-size: 12px; } +.layout-option, .theme-option, .system-picker-card, .sound-controls button { + background: var(--raised); + border-color: var(--line); + border-radius: var(--radius); +} +:is(.layout-option, .theme-option, .system-picker-card)[aria-pressed=true] { + background: var(--selected); + border-color: var(--accent); + color: var(--text); +} +.layout-mini { background: var(--field); } +.layout-mini i { background: var(--control-line); border-color: var(--secondary); } +.layout-mini i:nth-child(2) { background: var(--accent); } +.layout-option small, .theme-option, .search-icon, #systemPickerEmpty { color: var(--muted); } +.system-glyph { background: var(--field); border-color: var(--line); } +.update-banner { border-radius: var(--radius); } +#toast { max-width: min(560px, 90vw); } + +@media (max-width: 1250px) { + .settings-groups .row > span { width: 8em; flex-basis: 8em; } + .settings-groups .prompt-preview-link { margin-left: 0; } +} diff --git a/renderer/library-ui.css b/renderer/library-ui.css index c01aa68..5de2a40 100644 --- a/renderer/library-ui.css +++ b/renderer/library-ui.css @@ -65,23 +65,59 @@ dialog { color:var(--text); user-select:none; } #appearancePicker { width:470px; max-height:calc(100vh - 100px); margin:94px 30px 0 auto; padding:24px; }#appearancePicker::backdrop { background:#03071075; backdrop-filter:blur(3px); } .appearance-label { font-size:10px; text-transform:uppercase; letter-spacing:.14em; color:#9baac1; margin:23px 0 12px; }.layout-options { display:grid; grid-template-columns:repeat(2,1fr); gap:10px; } .layout-option { border-radius:12px; padding:10px; text-align:left; background:#141c27; border-color:#ffffff10; }.layout-option[aria-pressed=true] { border-color:var(--accent); background:color-mix(in srgb,var(--accent) 8%,#141c27); }.layout-option strong { font-size:11px; font-weight:600; display:block; margin-top:8px; }.layout-option small { display:block; color:#8494ad; font-size:9px; margin-top:3px; } -.layout-mini { height:51px; display:flex; justify-content:center; align-items:center; gap:4px; background:#080d1480; border-radius:6px; overflow:hidden; perspective:200px; }.layout-mini i { display:block; width:20px; height:32px; border-radius:2px; background:linear-gradient(150deg,color-mix(in srgb,var(--accent) 50%,#414d60),#1e2c40); border:1px solid #ffffff35; }.layout-mini i:nth-child(2) { height:40px; background:linear-gradient(150deg,var(--accent2),var(--accent)); }.layout-mini[data-kind=vertical] { flex-direction:column; gap:2px; }.layout-mini[data-kind=vertical] i { width:23px; height:12px; }.layout-mini[data-kind=vertical] i:nth-child(2) { width:33px; height:19px; }.layout-mini[data-kind=flipbook] { gap:0; }.layout-mini[data-kind=flipbook] i { transform:rotateY(50deg) rotate(-4deg); margin-right:-2px; }.layout-mini[data-kind=flipbook] i:nth-child(2) { width:29px; transform:rotateY(-15deg); }.layout-mini[data-kind=swatches] { flex-wrap:wrap; padding:9px 20px; gap:4px; }.layout-mini[data-kind=swatches] i { width:32px; height:14px; } +.layout-mini { height:51px; display:flex; justify-content:center; align-items:center; gap:4px; background:#080d1480; border-radius:6px; overflow:hidden; perspective:200px; }.layout-mini i { display:block; width:20px; height:32px; border-radius:2px; background:linear-gradient(150deg,color-mix(in srgb,var(--accent) 50%,#414d60),#1e2c40); border:1px solid #ffffff35; }.layout-mini i:nth-child(2) { height:40px; background:linear-gradient(150deg,var(--accent2),var(--accent)); }.layout-mini[data-kind=vertical] { flex-direction:column; gap:2px; }.layout-mini[data-kind=vertical] i { width:23px; height:12px; }.layout-mini[data-kind=vertical] i:nth-child(2) { width:33px; height:19px; }.layout-mini[data-kind=flipbook] { gap:0; }.layout-mini[data-kind=flipbook] i { transform:rotateY(50deg) rotate(-4deg); margin-right:-2px; }.layout-mini[data-kind=flipbook] i:nth-child(2) { width:29px; transform:rotateY(-15deg); } +.layout-mini[data-kind=page-turn] { gap: 0; } +.layout-mini[data-kind=page-turn] i:first-child { transform-origin: right; transform: rotateY(-30deg); } +.layout-mini[data-kind=page-turn] i:nth-child(2) { height: 33px; transform: rotateY(14deg); } +.layout-mini[data-kind=page-turn] i:last-child { width: 12px; margin-left: -7px; transform: rotateY(50deg); } +.layout-mini[data-kind=media] i { width: 22px; height: 22px; border-radius: 50%; transform: rotateY(40deg); background: radial-gradient(circle,#080d14 0 13%,transparent 14%),linear-gradient(150deg,color-mix(in srgb,var(--accent) 50%,#414d60),#1e2c40); } +.layout-mini[data-kind=media] i:first-child { transform: rotateY(-40deg); } +.layout-mini[data-kind=media] i:nth-child(2) { width: 32px; height: 32px; transform: none; background: radial-gradient(circle,#080d14 0 13%,transparent 14%),linear-gradient(150deg,var(--accent2),var(--accent)); } .theme-options { display:flex; gap:8px; }.theme-option { flex:1; padding:8px 3px; border-radius:10px; text-align:center; font-size:9px; color:#9cabc1; background:#121a25; border-color:#ffffff0b; }.theme-option i { display:block; width:23px; height:23px; border-radius:50%; margin:0 auto 7px; background:var(--theme-gradient); border:2px solid #ffffff20; }.theme-option[aria-pressed=true] { color:#f3f5fa; border-color:var(--accent); }.appearance-note { font-size:10px; color:#8798b1; line-height:1.6; margin:20px 0 0; } .sound-controls { display:flex; align-items:center; gap:12px; }.sound-controls button { border-radius:9px; font-size:11px; padding:8px 10px; white-space:nowrap; background:#1b2330; }.sound-controls input { min-width:0; width:100%; padding:0; accent-color:var(--accent); height:4px; }.sound-controls output { color:#99a8be; font-size:10px; min-width:27px; } -.swatch-card { display:none; } -html[data-layout=vertical] .item .sway,html[data-layout=flipbook] .item .sway { animation:none; transform:none; } -html[data-layout=flipbook] .item { transition:transform .78s cubic-bezier(.2,.7,.2,1); } -html[data-layout=swatches] .item { left:0 !important; top:0 !important; } -html[data-layout=swatches] .item .sway,html[data-layout=swatches] .item .shadow { display:none; } -html[data-layout=swatches] .swatch-card { display:flex; position:absolute; inset:0; gap:14px; align-items:center; padding:14px; border:1px solid #ffffff14; border-radius:14px; background:radial-gradient(ellipse at 0 0,var(--swatch-color,#50487b),#121923 130%); box-shadow:0 8px 25px #0002; overflow:hidden; transition:transform .2s,border-color .2s; } -html[data-layout=swatches] .item.sel .swatch-card { border-color:var(--accent2); box-shadow:0 0 0 2px color-mix(in srgb,var(--accent) 18%,transparent),0 15px 35px #0004; transform:translateY(-2px); } -.swatch-cover { position:relative; flex-shrink:0; width:53px; height:78px; border-radius:4px; box-shadow:3px 5px 12px #0005; --w:53px; } -.swatch-copy { min-width:0; }.swatch-copy strong { font-size:13px; line-height:1.3; font-weight:650; display:-webkit-box;-webkit-line-clamp:3;-webkit-box-orient:vertical;overflow:hidden; }.swatch-copy small { display:block; font-size:9px; color:#d3dbe6b3; margin-top:7px; } -html[data-layout=swatches] .shelf-spotlight { opacity:.4; } +html:is([data-layout=vertical],[data-layout=flipbook],[data-layout=page-turn]) .item.sel .sway { animation: none; transform: none; } +html:is([data-layout=flipbook],[data-layout=page-turn]) .item { transition: transform .78s cubic-bezier(.2,.7,.2,1); } +/* Page turn: cases turn round, so a disc or cartridge waiting behind one would show on its back as + it turns: it goes the moment its case is no longer selected rather than after sliding home. */ +html[data-layout=page-turn] .item:not(.sel) .physical-media { visibility: hidden; transition: none; } +html[data-layout=page-turn] .item:not(.sel) .shadow { display: none; } +/* Media carousel: every game shows its disc or cartridge, centred where its case would be, and + the cases (with their reflections and shadows) are left out. The doubled class outranks the + case layouts' reveal rules, which slide the media out from behind the selected case. The + selected disc turns. */ +html[data-layout=media] .item :is(.box,.ground-reflection,.shadow) { display: none; } +html[data-layout=media] .item .physical-media.physical-media { visibility: visible; transform: none; translate: none; transition: none; } +html[data-layout=media] .item.far .physical-media.physical-media { visibility: hidden; } +html[data-layout=media] .item.sel .disc-rotor { animation: disc-spin 14s linear infinite; } +/* The slow floating sway of a selected case made the selected cartridge's label drop out every few + seconds (drawn behind the plain face as the shell turned); here it is held at a fixed turn. */ +html[data-layout=media] .item.sel .sway { animation: none; transform: rotateY(14deg) rotateX(-3deg); } html:not([data-theme=ember]) #bg { background:radial-gradient(ellipse at 20% 0,color-mix(in srgb,var(--accent) 16%,#080b14),#070a11 75%); } html:not([data-theme=ember]) .bg-layer { filter:blur(40px) saturate(.85) brightness(.32); } html:not([data-theme=ember]) #floor { background:radial-gradient(ellipse,var(--accent) 0%,transparent 70%); opacity:.10; } html:not([data-theme=ember]) .shelf-spotlight { background:radial-gradient(ellipse,color-mix(in srgb,var(--accent) 10%,transparent),transparent 68%); } html:not([data-theme=ember]) #info::before { background:linear-gradient(90deg,color-mix(in srgb,var(--accent) 40%,transparent),#ffffff0c 45%,transparent); } +#renameGame,#gameDetailsEditor,#emuChoice { border:1px solid #ffffff23; border-radius:18px; padding:28px; background:linear-gradient(145deg,#283545c9,#111925e6); backdrop-filter:blur(34px) saturate(1.3); box-shadow:0 30px 100px #0009,inset 0 1px 0 #ffffff16; width:min(520px,calc(100vw - 80px)); } +#renameGame::backdrop,#gameDetailsEditor::backdrop,#emuChoice::backdrop { background:#030710b3; backdrop-filter:blur(12px); } +#renameGame label,#gameDetailsEditor label { display:flex; flex-direction:column; gap:6px; font-size:11px; color:#9baac1; margin-top:12px; } +#emu-choice-list,.emu-choice-list { display:flex; flex-direction:column; gap:8px; } +.emu-choice-option { display:flex; flex-direction:column; text-align:left; gap:2px; padding:10px 12px; border-radius:10px; background:#171e2980; border:1px solid #ffffff0b; } +.emu-choice-option[aria-pressed=true] { border-color:var(--accent); } +#gameMenu { position:fixed; z-index:200; display:flex; flex-direction:column; min-width:220px; padding:6px; gap:2px; border-radius:12px; background:#111925f0; border:1px solid #ffffff23; box-shadow:0 30px 100px #0009; } +#gameMenu[hidden] { display:none; } +.game-menu-item { display:flex; gap:8px; align-items:center; text-align:left; padding:8px 10px; border-radius:8px; background:transparent; border:0; } +.game-menu-item:hover,.game-menu-item:focus-visible { background:#ffffff12; } +.empty-box { display:flex; align-items:center; gap:12px; justify-content:center; } +.empty-hide { padding:8px 12px; border-radius:9px; } +.sys-tools { display:flex; align-items:center; gap:10px; flex-wrap:wrap; margin:10px 0; } +.add-form { display:flex; gap:10px; align-items:center; flex-wrap:wrap; margin:10px 0; } +.hidden-list,.added-list { display:flex; flex-direction:column; gap:6px; padding:0; margin:10px 0 0; list-style:none; } +.hidden-list li,.added-list li { display:flex; justify-content:space-between; gap:12px; align-items:center; padding:8px 10px; background:#ffffff06; border-radius:8px; } +.sys-remove { font-size:11px; padding:4px 8px; border-radius:7px; margin-left:8px; } +.sys-hidden { opacity:.55; } +.game-dragging { opacity:.7; } +.cover-drag-preview { position:absolute; width:104px; height:144px; background-size:cover; border-radius:8px; pointer-events:none; } +.drop-before { outline:2px solid var(--accent); } +.drop-after { outline:2px solid var(--accent2); } @media(max-width:1250px) { header { gap:15px; padding-left:28px; padding-right:28px; }.brand { font-size:17px; }#tabs button { padding:8px 10px; gap:6px; }#inputBadge { display:none; }.toolbar { grid-template-columns:111px minmax(0,1fr) 185px; padding-left:28px;padding-right:28px;gap:9px; }.chips .system-tile { min-width:86px; }.system-browser { padding:7px;gap:6px; }.system-browser-icon svg { width:16px; }#libraryHints { left:32px;right:32px; }.system-picker-footer { font-size:9px; } } -@media(max-height:740px) { .toolbar { padding-top:6px; }#stage { top:73px;min-height:125px; }#info h1 { font-size:30px; }#info { padding-bottom:0; }.system-picker-heading { margin-bottom:18px; }#appearancePicker { margin-top:80px;padding:20px; }.layout-mini { height:37px; }.appearance-label { margin-top:17px; }.appearance-note { margin-top:14px; }html[data-layout=swatches] .swatch-card { padding:8px;gap:10px; }.swatch-cover { height:61px;width:44px; }.swatch-copy strong { font-size:11px;-webkit-line-clamp:2; } } +@media(max-height:740px) { .toolbar { padding-top:6px; }#stage { top:73px;min-height:125px; }#info h1 { font-size:30px; }#info { padding-bottom:0; }.system-picker-heading { margin-bottom:18px; }#appearancePicker { margin-top:80px;padding:20px; }.layout-mini { height:37px; }.appearance-label { margin-top:17px; }.appearance-note { margin-top:14px; } } diff --git a/renderer/library-ui.js b/renderer/library-ui.js index 4ecd470..14da73c 100644 --- a/renderer/library-ui.js +++ b/renderer/library-ui.js @@ -2,6 +2,7 @@ const LibraryUI=(()=>{ const $=s=>document.querySelector(s); let context,entries=[],railFrame=null,pickerChosen=false; + let favoriteSet=new Set(),recentlyPlayed=[],sortKey='title',sortAsc=true; const shapes={ grid:'', pad:'', @@ -20,33 +21,86 @@ const LibraryUI=(()=>{ library:'', download:'', art:'', - settings:'' + settings:'', + favorite:'' }; - const glyph={all:'grid',psp:'wide',switch:'switch',switch2:'switch',nds:'dual','3ds':'dual',gb:'handheld',gbc:'handheld',gba:'wide',wii:'remote',wiiu:'wide',gc:'cube',n64:'n64',nes:'nes',dreamcast:'swirl',a2600:'joystick',arcade:'arcade'}; - const shortNames={ps1:'PS1',ps2:'PS2',ps3:'PS3',ps4:'PS4',switch:'Switch',switch2:'Switch 2',nds:'DS','3ds':'3DS',gb:'Game Boy',gbc:'GBC',gba:'GBA',n64:'N64',snes:'SNES',nes:'NES',gc:'GameCube',genesis:'Genesis',x360:'Xbox 360',a2600:'Atari'}; + const glyph={all:'grid',ps1:'psp',ps2:'ps2',ps3:'ps3',ps4:'ps4',switch:'switch',switch2:'switch2',nds:'nds','3ds':'3ds',gb:'gb',gbc:'gbc',gba:'gba',n64:'n64',snes:'snes',nes:'nes',gc:'gc',genesis:'genesis',xbox:'xbox',x360:'x360',a2600:'a2600',arcade:'arcade'}; + // Compact chip labels (dropped in a rewrite; render() dereferences this). + // Anything missing falls back to the full system name. + const shortNames={ps1:'PS1',ps2:'PS2',ps3:'PS3',ps4:'PS4',psp:'PSP',switch:'Switch',switch2:'Switch 2',nds:'DS','3ds':'3DS',gb:'Game Boy',gbc:'GBC',gba:'GBA',n64:'N64',snes:'SNES',nes:'NES',gc:'GameCube',wii:'Wii',wiiu:'Wii U',genesis:'Genesis',xbox:'Xbox',x360:'Xbox 360',a2600:'Atari',dreamcast:'Dreamcast'}; function icon(id){return ``} + function isAndroid(){return /android/i.test(navigator.userAgent||'')||(navigator.platform||'').toLowerCase().includes('android')} + function emulatorStateFor(system){ + const emus=context?.getState?.().emus||[]; + const emu=emus.find(e=>e.id===system.emulator); + if(!emu)return{label:'NO EMULATOR',linked:false}; + if(isAndroid())return emu.package||emu.linked?{label:`LINKED ${emu.package||''}`.trim(),linked:true,emu}:{label:'NOT LINKED',linked:false,emu}; + if(emu.installed)return{label:'INSTALLED',linked:true,emu}; + if(emu.exe)return{label:'LINKED',linked:true,emu}; + return{label:'NOT INSTALLED',linked:false,emu}; + } function element(tag,cls,text){const n=document.createElement(tag);n.className=cls;if(text!==undefined)n.textContent=text;return n} const smooth=()=>document.documentElement.dataset.motion==='reduced'?'instant':'smooth'; + async function toggleFavorite(entry){ + try{const result=await window.api?.toggleFavorite?.(entry.id);if(result&&context?.refresh){favoriteSet=new Set(context.getState().config?.favorites||[]);context.refresh()}}catch(e){console.error('toggleFavorite failed:',e)} + } function button(entry,cls){ const b=element('button',cls);b.type='button';b.dataset.id=entry.id;b.style.setProperty('--system-color',entry.color||'#ff954e'); b.setAttribute('aria-pressed',String(entry.id===context.getState().system)); - b.setAttribute('aria-label',`${entry.name}, ${entry.count.toLocaleString()} ${entry.count===1?'game':'games'}`); - b.title=`${entry.name} · ${entry.count.toLocaleString()} ${entry.count===1?'game':'games'}`; + const emu=entry.id==='all'?null:emulatorStateFor(entry); + const emuSuffix=isAndroid()&&emu?`, emulator ${emu.label.toLowerCase()}`:''; + const isFav=favoriteSet.has(entry.id); + b.setAttribute('aria-label',`${entry.name}, ${entry.count.toLocaleString()} ${entry.count===1?'game':'games'}${emuSuffix}${isFav?' · Favorite':''}`); + b.title=`${entry.name} · ${entry.count.toLocaleString()} ${entry.count===1?'game':'games'}${emuSuffix?` · ${emu.label}`:''}${isFav?' · ★ Favorite':''}`; + if(emu)b.dataset.emulator=emu.label.toLowerCase().replace(/\s+/g,'-'); const mark=element('span','system-glyph');mark.innerHTML=icon(entry.id);const copy=element('span','system-copy'); - const compact=cls==='system-tile';copy.append(element('span','system-name',compact?(shortNames[entry.id]||entry.name):entry.name),element('span','n',compact?entry.count.toLocaleString():entry.count?`${entry.count.toLocaleString()} ${entry.count===1?'game':'games'}`:'No games yet'));b.append(mark,copy);return b; + const compact=cls==='system-tile'; + copy.append(element('span','system-name',compact?(shortNames[entry.id]||entry.name):entry.name),element('span','n',compact?entry.count.toLocaleString():entry.count?`${entry.count.toLocaleString()} ${entry.count===1?'game':'games'}`:'No games yet')); + if(isAndroid()&&emu)copy.append(element('span','emu-state',emu.label)); + // Favorite toggle button (visible on desktop, hidden on Android). + if(!isAndroid()){ + const favBtn=element('button','fav-btn','F'); + favBtn.type='button';favBtn.dataset.fav='true'; + favBtn.innerHTML=``; + favBtn.setAttribute('aria-label',`${isFav?'Remove from':'Add to'} favorites`); + favBtn.onclick=(e)=>{e.stopPropagation();toggleFavorite(entry)}; + b.appendChild(favBtn); + } + b.append(mark,copy);return b; } function render(){ - const s=context.getState(),counts={};for(const g of s.games)counts[g.system]=(counts[g.system]||0)+1; - entries=[{id:'all',name:'All games',count:s.games.length,color:'#ffad65'},...s.config.systems.filter(sys=>counts[sys.id]||sys.romDir).map(sys=>({...sys,count:counts[sys.id]||0}))]; + const s=context.getState(),counts={};for(const g of s.games){if(g.hidden)continue;counts[g.system]=(counts[g.system]||0)+1;} + entries=[{id:'all',name:'All games',count:Object.values(counts).reduce((a,b)=>a+b,0),color:'#ffad65'},...s.config.systems.filter(sys=>!sys.hidden&&(counts[sys.id]||sys.romDir)).map(sys=>({...sys,count:counts[sys.id]||0}))]; + // Update library state from config. + favoriteSet=new Set(s.config?.favorites||[]); + recentlyPlayed=s.config?.recentlyPlayed||[]; + sortKey=s.config?.sortKey||'title'; + sortAsc=s.config?.sortAsc!==false; + document.body.dataset.platform=isAndroid()?'android':'desktop'; const nav=$('#systems');nav.replaceChildren();for(const e of entries){const b=button(e,'system-tile');b.onclick=()=>context.select(e.id);nav.append(b)} + // Update filter buttons. + updateFilterButtons(s.config); $('#systemTotal').textContent=`${entries.length-1} systems`; $('#systemPickerSummary').textContent=`${s.games.length.toLocaleString()} games · ${entries.length-1} systems`; if(pickerOpen())renderPicker();requestAnimationFrame(updateRail); } + function updateFilterButtons(config){ + const favOnly=config?.showFavoritesOnly||false; + const showRec=config?.showRecentlyPlayed||false; + const sortBtn=$('#sortButton'); + const favBtn=$('#filterFavorites'); + const recBtn=$('#filterRecentlyPlayed'); + if(favBtn){favBtn.classList.toggle('active',favOnly);favBtn.setAttribute('aria-pressed',String(favOnly));} + if(recBtn){recBtn.classList.toggle('active',showRec);recBtn.setAttribute('aria-pressed',String(showRec));} + if(sortBtn){ + const labels={title:'Title',system:'System',favorites:'Favorites',recent:'Recent',custom:'Custom'}; + sortBtn.textContent=labels[sortKey]||'Title'; + } + } function select(){ const s=context.getState(); - for(const b of $('#systems').querySelectorAll('button')){const active=b.dataset.id===s.system;b.classList.toggle('active',active);b.setAttribute('aria-pressed',String(active));b.tabIndex=active?0:-1} - const active=$('#systems button.active');active?.scrollIntoView({inline:'center',block:'nearest',behavior:smooth()}); + for(const b of $('#systems').querySelectorAll(':scope > button')){const active=b.dataset.id===s.system;b.classList.toggle('active',active);b.setAttribute('aria-pressed',String(active));b.tabIndex=active?0:-1} + const active=$('#systems > button.active');active?.scrollIntoView({inline:'center',block:'nearest',behavior:smooth()}); $('#clearSearch').classList.toggle('hidden',!$('#search').value);$('.search-shortcut').classList.toggle('hidden',!!$('#search').value); const name=entries.find(e=>e.id===s.system)?.name||'All games'; $('#searchSummary').textContent=s.query?`${s.list.length.toLocaleString()} matches in ${name}`:`${s.list.length.toLocaleString()} games · ${name}`; @@ -55,7 +109,7 @@ const LibraryUI=(()=>{ function updateRail(){ const rail=$('#systems');if(!rail)return;const max=rail.scrollWidth-rail.clientWidth; $('#systemsPrev').disabled=rail.scrollLeft<2;$('#systemsNext').disabled=max-rail.scrollLeft<2; - rail.parentElement.classList.toggle('can-scroll-left',rail.scrollLeft>2);rail.parentElement.classList.toggle('can-scroll-right',max-rail.scrollLeft>2); + rail.parentElement.classList.toggle('can-scroll-left',rail.scrollLeft>2);rail.parentElement.classList.toggle('can-scroll-right',max-rail.scrollLeft<2); } function pageRail(direction){$('#systems').scrollBy({left:direction*$('#systems').clientWidth*.72,behavior:smooth()})} function pickerOpen(){return !!$('#systemPicker')?.open} @@ -70,7 +124,7 @@ const LibraryUI=(()=>{ $('#systemSearch').value='';renderPicker();$('#systemPicker').showModal();$('#btnSystemPicker').setAttribute('aria-expanded','true');$('#systemSearch').focus(); } function movePicker(direction){ - const cards=[...$('#systemPickerGrid').querySelectorAll('button')];if(!cards.length)return; + const cards=[...$('#systemPickerGrid').querySelectorAll(':scope > button')];if(!cards.length)return; if(document.activeElement.id==='systemPickerAppearance'){cards[Math.max(0,cards.length-1)].focus();return;} const columns=getComputedStyle($('#systemPickerGrid')).gridTemplateColumns.split(' ').length; const i=cards.indexOf(document.activeElement),step=direction==='left'?-1:direction==='right'?1:direction==='up'?-columns:columns; @@ -104,12 +158,35 @@ const LibraryUI=(()=>{ $('#systems').addEventListener('wheel',e=>{if(e.ctrlKey||$('#systems').scrollWidth<=$('#systems').clientWidth)return;e.preventDefault();$('#systems').scrollLeft+=Math.abs(e.deltaX)>Math.abs(e.deltaY)?e.deltaX:e.deltaY},{passive:false}); $('#systems').addEventListener('keydown',e=>{ if(!['ArrowLeft','ArrowRight','ArrowUp','ArrowDown','Home','End'].includes(e.key))return; - e.preventDefault();e.stopPropagation();const buttons=[...$('#systems').querySelectorAll('button')],i=buttons.indexOf(document.activeElement); + e.preventDefault();e.stopPropagation();const buttons=[...$('#systems').querySelectorAll(':scope > button')],i=buttons.indexOf(document.activeElement); const n=e.key==='Home'?0:e.key==='End'?buttons.length-1:Math.max(0,Math.min(buttons.length-1,i+(['ArrowLeft','ArrowUp'].includes(e.key)?-1:1))); buttons[n]?.focus();if(buttons[n])context.select(buttons[n].dataset.id); }); $('#clearSearch').onclick=()=>{$('#search').value='';$('#search').dispatchEvent(new Event('input'));$('#search').focus()}; + // Library state filter buttons. + const favBtn=$('#filterFavorites'); + if(favBtn)favBtn.onclick=async()=>{ + const s=context.getState(); + const newVal=!s.config?.showFavoritesOnly; + try{await window.api?.updateLibraryPrefs?.({showFavoritesOnly:newVal});context?.refresh?.()}catch(e){console.error('updateLibraryPrefs failed:',e)} + }; + const recBtn=$('#filterRecentlyPlayed'); + if(recBtn)recBtn.onclick=async()=>{ + const s=context.getState(); + const newVal=!s.config?.showRecentlyPlayed; + try{await window.api?.updateLibraryPrefs?.({showRecentlyPlayed:newVal});context?.refresh?.()}catch(e){console.error('updateLibraryPrefs failed:',e)} + }; + const sortBtn=$('#sortButton'); + if(sortBtn){ + const modes=['title','system','favorites','recent','custom']; + let idx=modes.indexOf(sortKey); + sortBtn.onclick=async()=>{ + idx=(idx+1)%modes.length; + const newKey=modes[idx]; + try{await window.api?.updateLibraryPrefs?.({sortKey:newKey});context?.refresh?.()}catch(e){console.error('updateLibraryPrefs failed:',e)} + }; + } new ResizeObserver(updateRail).observe($('#systems')); } - return {init,render,select,pickerOpen,openPicker,controller}; + return {init,render,select,pickerOpen,openPicker,controller,isAndroid,emulatorStateFor}; })(); diff --git a/renderer/loom-scene.js b/renderer/loom-scene.js new file mode 100644 index 0000000..6e4f16e --- /dev/null +++ b/renderer/loom-scene.js @@ -0,0 +1,57 @@ +// "Loom": two bundles of fine light threads that slowly gather and part, with small shuttle lights +// travelling along single threads. Calm, theme-coloured, and stateless (a pure function of time). +const Loom=(()=>{ + const N=72,SHUTTLES=12; + const hash=n=>{n=Math.imul(n^(n>>>15),2246822507);n=Math.imul(n^(n>>>13),3266489909);return((n^(n>>>16))>>>0)/4294967296}; + const TEAL=[96,206,214]; + const mix=(a,b,k)=>[a[0]+(b[0]-a[0])*k,a[1]+(b[1]-a[1])*k,a[2]+(b[2]-a[2])*k]; + const rgba=(c,a)=>`rgba(${c[0]|0},${c[1]|0},${c[2]|0},${a})`; + // Vertical position (0..1) of thread i in a bundle at horizontal position u. + function strand(bundle,i,u,t){ + const f=i/(N-1),dir=bundle?-1:1; + const centre=(bundle?.6:.4)+.2*Math.sin(u*2.1+t*.06*dir+bundle*1.7)+.07*Math.sin(u*5.3-t*.035+bundle); + const spread=(.2+.14*Math.sin(u*3+t*.045*dir+bundle*2))*(1.15+.85*Math.sin(u*4.2+t*.05+bundle*3)); + return centre+(f-.5)*spread+.016*Math.sin(u*9+f*6+t*.09*dir); + } + function draw(ctx,w,h,t,accent,accent2){ + ctx.globalCompositeOperation='source-over'; + const bg=ctx.createLinearGradient(0,0,0,h);bg.addColorStop(0,'#04060d');bg.addColorStop(.55,'#08111f');bg.addColorStop(1,'#04070e'); + ctx.fillStyle=bg;ctx.fillRect(0,0,w,h); + const glow=ctx.createRadialGradient(w*.5,h*.5,0,w*.5,h*.5,w*.6);glow.addColorStop(0,rgba(mix(accent,TEAL,.5),.16));glow.addColorStop(1,'rgba(0,0,0,0)'); + ctx.fillStyle=glow;ctx.fillRect(0,0,w,h); + ctx.globalCompositeOperation='lighter';ctx.lineWidth=Math.max(1,h/620); + const step=Math.max(6,w/110); + for(let b=0;b<2;b++){ + const base=b?TEAL:accent; + for(let i=0;i1.05)continue; + const i=Math.floor(hash(lap*31+k*17)*N),col=mix(bundle?TEAL:accent2,[255,255,255],.35); + const edge=Math.min(1,(u+.05)*8,(1.05-u)*8),pos=d=>[(u-d)*w,strand(bundle,i,u-d,t)*h]; + for(let s=18;s>0;s--){ + const p=pos(s*.006),q=pos((s-1)*.006); + ctx.strokeStyle=rgba(col,.5*edge*(1-s/19)**2);ctx.lineWidth=(.5+(1-s/19)*1.8)*u0; + ctx.beginPath();ctx.moveTo(p[0],p[1]);ctx.lineTo(q[0],q[1]);ctx.stroke(); + } + const [x,y]=pos(0),r=20*u0,g=ctx.createRadialGradient(x,y,0,x,y,r); + g.addColorStop(0,rgba(col,.9*edge));g.addColorStop(.25,rgba(col,.25*edge));g.addColorStop(1,rgba(col,0)); + ctx.fillStyle=g;ctx.fillRect(x-r,y-r,r*2,r*2); + ctx.fillStyle=`rgba(255,255,255,${.9*edge})`;ctx.beginPath();ctx.arc(x,y,1.8*u0,0,6.3);ctx.fill(); + } + ctx.globalCompositeOperation='source-over'; + const v=ctx.createRadialGradient(w/2,h/2,Math.min(w,h)*.4,w/2,h/2,Math.max(w,h)*.75);v.addColorStop(0,'rgba(0,0,0,0)');v.addColorStop(1,'rgba(0,0,5,.5)'); + ctx.fillStyle=v;ctx.fillRect(0,0,w,h); + } + return {draw}; +})(); diff --git a/renderer/packaging.js b/renderer/packaging.js index 2bada6a..3c01049 100644 --- a/renderer/packaging.js +++ b/renderer/packaging.js @@ -28,9 +28,22 @@ const Packaging=(()=>{ a2600:p([230,310,42],'#bdb09d','cardboard','#a94123','#fff','ATARI 2600','#eb9d39'), arcade:p([318,225,52],'#b8ad98','cardboard','#28262c','#fff','ARCADE','#bc8b29') }; - function profile(sys){return profiles[sys.id]||p([230,323,24],'#292a31','plastic','#252631','#fff',sys.name,sys.color||'#444')} + // Super Famicom boxes came in both orientations: a tall narrow box and a wide flat one. + // The packaging key (sys.packaging) selects which one; the size feeds art() and caseSize(). + const regionalProfiles={ + 'superfamicom-tall':p([174,318,42],'#c8bca6','cardboard','#f0ece3','#1b1b20','SUPER FAMICOM','#d13839'), + 'superfamicom-wide':p([318,174,42],'#c8bca6','cardboard','#f0ece3','#1b1b20','SUPER FAMICOM','#d13839'), + }; + const famicomSpine={band:'#f0ece3',ink:'#1b1b20',body:'#f0ece3',text:'#1b1b20',mark:['SUPER','FAMICOM'],style:'nintendo',rule:'#d13839'}; + const model=sys=>regionalProfiles[sys.packaging]||profiles[sys.id]; + const design=sys=>{ + if(regionalProfiles[sys.packaging])return famicomSpine; + const v=profile(sys); + return {band:v.bg,ink:v.ink,body:v.bg,text:v.ink,mark:[v.brand],style:['ps1','ps2','ps3','ps4','psp'].includes(sys.id)?'ps':'plain',rule:v.accent,accent:v.accent}; + }; + function profile(sys){return model(sys)||p([230,323,24],'#292a31','plastic','#252631','#fff',sys.name,sys.color||'#444')} function decorate(box,a){ - const v=profile(a.sys);box.dataset.packaging=a.sys.id;box.dataset.material=v.material;box.dataset.media=a.sys.media; + const v=profile(a.sys);box.dataset.packaging=a.sys.packaging||a.sys.id;box.dataset.material=v.material;box.dataset.media=a.sys.media; box.style.setProperty('--case-shell',v.shell);box.style.setProperty('--case-rim',v.material==='cardboard'?'0px':v.material==='jewel'?'3px':'2px'); box.style.setProperty('--case-print',v.bg); box.style.setProperty('--case-ink',v.ink); @@ -60,6 +73,10 @@ const Packaging=(()=>{ const inner=lid.querySelector('.l-inner'); for(const corner of ['tl','tr','bl','br'])inner.append(node('case-booklet-tab case-booklet-tab-'+corner)); const right=box.querySelector(':scope > .f-right');right?.append(node('case-latch')); + // The cover's hinge follows the free edge of the spine as it folds out from the tray. + const caseSpine=node('case-spine'); + caseSpine.append(box.querySelector(':scope > .f-left'),node('face case-spine-inner')); + box.append(caseSpine); } } function brand(sys,D,height){ @@ -95,5 +112,5 @@ const Packaging=(()=>{ footer.style.fontSize=fitText(footer.textContent,footerHeight*.9,a.D*.24)+'px'; insert.append(brand(a.sys,a.D,header),titleArea,footer);face.append(insert);return face; } - return {profiles,profile,decorate,spine,finish}; + return {profiles,profile,size:sys=>model(sys)?.size,design,decorate,spine,finish}; })(); diff --git a/renderer/pixel-scenes.js b/renderer/pixel-scenes.js new file mode 100644 index 0000000..bbdefba --- /dev/null +++ b/renderer/pixel-scenes.js @@ -0,0 +1,131 @@ +// Procedural 16-bit style backgrounds (day and night), drawn with whole-pixel rectangles and fixed palettes. +const PixelScenes=(()=>{ + const H=180; + const hash=n=>{n=Math.imul(n^(n>>>15),2246822507);n=Math.imul(n^(n>>>13),3266489909);return((n^(n>>>16))>>>0)/4294967296}; + const palettes={ + day:{ + sky:['#3f9be0','#52aae8','#66b9ee','#7cc7f3','#93d3f6','#aadef9','#c2e9fb','#dcf4fd'], + sun:['#fff6b8','#ffe36e','#ffc93c'],cloud:['#ffffff','#e3f1fb','#c6def2'], + hills:[['#9ccfb8','#86bfa5'],['#6fb48f','#5aa17c'],['#3f8d62','#2f7a52']],tree:['#1f5e3f','#2c7a50'], + grass:['#2f7a3d','#3f9a4a','#58b45a'],bird:'#27406b' + }, + night:{ + sky:['#070b22','#0a1030','#0e1740','#131f4f','#1a2860','#223472','#2c4084','#394e94'], + sun:['#f7f4dc','#dcd8bd','#bfbba0'],cloud:['#2b3a78','#223066','#1b2756'], + hills:[['#27346e','#202b5c'],['#1c2552','#161e46'],['#111836','#0c1229']],tree:['#080d22','#0e1630'], + grass:['#0a1a22','#0f2a2a','#173c35'],bird:'#0000' + } + }; + let clouds=null,skyline=null,stars=null,flies=null,shooting=null; + function seed(w){ + clouds=Array.from({length:7},(_,i)=>({x:hash(i*7+1)*w*1.3,y:10+hash(i*7+2)*60,w:22+hash(i*7+3)*34,v:.5+hash(i*7+4)*1.3})); + stars=Array.from({length:90},(_,i)=>({x:Math.floor(hash(i*5+11)*w),y:Math.floor(hash(i*5+12)*H*.55),p:hash(i*5+13)*6.28,b:hash(i*5+14)>.85})); + flies=Array.from({length:16},(_,i)=>({x:hash(i*3+21)*w,y:H*.6+hash(i*3+22)*H*.33,p:hash(i*3+23)*6.28,s:.3+hash(i*3+24)})); + skyline=[];let x=0,k=0;while(x{c.fillStyle=col;c.fillRect(Math.round(x),Math.round(y),Math.round(w),Math.round(h))}; + function sky(c,w,p,horizon){ + const n=p.sky.length,band=horizon/n; + for(let y=0;yband-2){c.fillStyle=p.sky[b+1];for(let x=(y&1);xr)continue; + c.fillStyle=d>r-1.6?cols[2]:d>r-4?cols[1]:cols[0];c.fillRect(Math.round(cx+x),Math.round(cy+y),1,1); + } + } + function cloud(c,p,cl,w){ + const x=((cl.x%(w+80))+w+80)%(w+80)-60,y=cl.y,u=cl.w; + const rows=[[.18,.5],[.06,.88],[0,1],[.05,.9]]; + rows.forEach(([off,len],i)=>{rect(c,i===3?p.cloud[1]:p.cloud[0],x+u*off,y+i*4,u*len,4);}); + rect(c,p.cloud[2],x+u*.05,y+16,u*.9,2); + } + function ridge(x,l,t,amp){ + const u=x+t;return Math.round(Math.sin(u*.021+l*2.1)*amp+Math.sin(u*.047+l*5.3)*amp*.45+Math.sin(u*.0083+l)*amp*.8); + } + function hills(c,w,p,t,horizon,night){ + p.hills.forEach(([top,body],l)=>{ + const speed=[.9,2.2,4.6][l],base=horizon-10+l*16,amp=[16,13,10][l],off=night?0:t*speed; + for(let x=0;x>2)%4)+4)%4)*3,1,1)} + } + if(l===2){ + // pine trees on the nearest ridge, scrolling with it + const step=14,first=Math.floor(off/step)-1; + for(let k=first;k.55&&(k>.93?Math.floor(t/30+k*50)%2===0:true); + if(on)rect(c,k>.8?'#ffd36a':'#f5b94d',wx,wy,1,2); + } + } + } + function grass(c,w,p,t){ + const gy=H-12;rect(c,p.grass[0],0,gy,w,12);rect(c,p.grass[1],0,gy,w,2); + for(let x=0;x{for(let rx=0;rx4.7&&tw>.6)?'#ffffff':'#8d9fdc',s.x,s.y,1,1); + if(s.b){rect(ctx,'#6f82c7',s.x-1,s.y,1,1);rect(ctx,'#6f82c7',s.x+1,s.y,1,1);rect(ctx,'#6f82c7',s.x,s.y-1,1,1);rect(ctx,'#6f82c7',s.x,s.y+1,1,1)} + } + if(t>shooting.at){if(!shooting.life){shooting.x=hash(Math.floor(t))*w*.7+20;shooting.y=8+hash(Math.floor(t)+1)*40;shooting.life=1} + shooting.life+=.05;for(let i=0;i<8;i++)rect(ctx,i<2?'#ffffff':'#8fa4e6',shooting.x+shooting.life*60-i*2.5,shooting.y+shooting.life*30-i*1.2,2,1); + if(shooting.life>2.2){shooting.life=0;shooting.at=t+9+hash(Math.floor(t)+2)*14}} + const mx=w*.78,my=36+Math.sin(t*.05)*3;disc(ctx,mx,my,15,p.sun); + for(const [dx,dy,r] of [[-5,-4,3],[4,3,4],[-3,6,2]])disc(ctx,mx+dx,my+dy,r,['#c9c5aa','#c9c5aa','#b3af95']); + }else{ + const sx=w*.22,sy=34+Math.sin(t*.05)*2;disc(ctx,sx,sy,13,p.sun); + ctx.fillStyle='#ffe36e55';for(let a=0;a<8;a++){const an=a*.785+t*.1;rect(ctx,'#fff3a0',sx+Math.cos(an)*21,sy+Math.sin(an)*21,2,2)} + } + for(const cl of clouds)cloud(ctx,p,{...cl,x:cl.x+t*cl.v*(night?.1:1)},w); + if(!night)birds(ctx,w,t,p.bird); + hills(ctx,w,p,t,horizon,night); + if(night)city(ctx,w,p,t,horizon+4); + // hills drawn first for the city silhouette? keep the nearest ridge above the skyline + if(night){const [top,body]=p.hills[2],base=horizon-10+32,off=0;for(let x=0;x-.3; + if(on){rect(ctx,'#d9ff7a',x,y,1,1);rect(ctx,'#d9ff7a55',x-1,y,3,1)} + } + } + return {draw,height:H}; +})(); diff --git a/renderer/prompts.js b/renderer/prompts.js index 531b759..fee92b2 100644 --- a/renderer/prompts.js +++ b/renderer/prompts.js @@ -19,11 +19,12 @@ const Prompts = (() => { } function library(family,layout='carousel') { const keyboard = family === 'keyboard'; + const playFace = family === 'nintendo' ? 'east' : 'south'; const groups = keyboard ? [ ['keyboard',['left','right'],'Browse'],['keyboard',['up','down'],'System'],['keyboard',['enter'],'Play'], - ['keyboard',['space'],'Open case'],['keyboard',['m'],'Manual'],['keyboard',['pageup','pagedown'],'Jump 10'],['keyboard',['f11'],'Fullscreen'] + ['keyboard',['space'],'Open case'],['keyboard',['m'],'Manual'],['keyboard',['i'],'Details'],['keyboard',['o'],'UI mode'],['keyboard',['pageup','pagedown'],'Jump 10'],['keyboard',['f11'],'Fullscreen'] ] : [ - [family,['left-stick-horizontal'],'Browse'],[family,['lb','rb'],'System'],[family,['south'],'Play'], + [family,['left-stick-horizontal'],'Browse'],[family,['lb','rb'],'System'],[family,[playFace],'Play'], [family,['north'],'Open case'],[family,['west'],'Manual'],[family,['lt','rt'],'Jump 10'] ]; if(['vertical','swatches'].includes(layout)){ @@ -34,12 +35,14 @@ const Prompts = (() => { } function caseHints(family) { const keyboard = family === 'keyboard'; + const playFace = family === 'nintendo' ? 'east' : 'south'; + const backFace = family === 'nintendo' ? 'south' : 'east'; const groups = keyboard ? [ ['mouse',['drag-left'],'Rotate'],['mouse',['scroll'],'Zoom'],['keyboard',['enter'],'Play'], ['keyboard',['m'],'Manual'],['keyboard',['escape'],'Back'] ] : [ - [family,['left-stick-horizontal'],'Rotate'],[family,['lt','rt'],'Zoom'],[family,['south'],'Play'], - [family,['north'],'Open / close'],[family,['west'],'Manual'],[family,['east'],'Back'] + [family,['left-stick-horizontal'],'Rotate'],[family,['lt','rt'],'Zoom'],[family,[playFace],'Play'], + [family,['north'],'Open / close'],[family,['west'],'Manual'],[family,[backFace],'Back'] ]; return groups.map(g=>hint(...g)).join(''); } diff --git a/renderer/ps2-scene.js b/renderer/ps2-scene.js new file mode 100644 index 0000000..ef5523d --- /dev/null +++ b/renderer/ps2-scene.js @@ -0,0 +1,99 @@ +// A dark navy void of drifting towers and glass cubes with glowing orbs trailing comet streaks. +const Ps2Scene=(()=>{ + const NEAR=.2,FAR=2.3,TRAIL=80; + let seed=11;const R=()=>((seed=Math.imul(seed^(seed>>>15),2246822507)+0x9e3779b9>>>0)/4294967296); + let boxes=null,orbs=null,blobs=null,fog=null,W=0,H=0,sim=0; + const ORB_COLORS=[[255,90,220],[70,255,110],[255,50,60],[110,120,255],[80,220,255],[255,190,80]]; + const FACE={near:[142,166,214],top:[170,192,232],bottom:[56,70,110],left:[96,116,168],right:[74,92,140]}; + + function makeBox(far){ + const r=R(),tower=r<.45,glass=r>.8,side=R()<.5?-1:1; + const sx=tower?.16+R()*.2:.1+R()*.17,sy=tower?.16+R()*.2:sx,sz=tower?.5+R()*1.1:sx; + const lateral=tower?.5+R()*.9:.1+R()*1.2; + return {x:(tower||R()<.6?side:(R()<.5?-1:1))*lateral,y:(R()*2-1)*(tower?.95:.85),z:far?FAR*(.8+R()*.2):NEAR+sz/2+R()*(FAR-NEAR-.2),sx,sy,sz,glass,speed:0,shade:.9+R()*.18}; + } + function spawnOrb(o={}){ + const edge=R(),a=R()*6.283; + o.x=W*(.1+R()*.8);o.y=H*(.1+R()*.8);o.ang=a;o.curv=(R()<.5?-1:1)*(.18+R()*.4);o.speed=H*(.14+R()*.1); + o.max=7+R()*6;o.life=0;o.trail=[];o.color=ORB_COLORS[Math.floor(R()*ORB_COLORS.length)];o.wob=R()*6.28;return o; + } + function init(w,h){ + W=w;H=h;seed=11; + boxes=Array.from({length:30},()=>makeBox(false)); + orbs=Array.from({length:6},(_,i)=>{const o=spawnOrb();o.life=i*1.7;return o}); + blobs=Array.from({length:6},()=>({x:.2+R()*.6,y:.2+R()*.6,r:.35+R()*.25,p:R()*6.28,s:.03+R()*.03})); + fog=Array.from({length:9},()=>({x:R(),y:.25+R()*.7,r:.28+R()*.3,p:R()*6.28,s:.018+R()*.025,a:.06+R()*.06})); + sim=0;for(let i=0;i<240;i++)step(1/30); + } + function step(dt){ + for(const o of orbs){ + o.life+=dt;o.ang+=(o.curv+Math.sin(o.life*.7+o.wob)*.12)*dt; + o.x+=Math.cos(o.ang)*o.speed*dt;o.y+=Math.sin(o.ang)*o.speed*dt; + o.trail.push([o.x,o.y]);if(o.trail.length>TRAIL)o.trail.shift(); + if(o.life>o.max||o.x<-60||o.x>W+60||o.y<-60||o.y>H+60)spawnOrb(o); + } + sim+=dt; + } + function project(x,y,z,f,ox,oy){return [W/2+ox+x/z*f,H/2+oy+y/z*f]} + const rgba=(c,a,k=1)=>`rgba(${c[0]*k|0},${c[1]*k|0},${c[2]*k|0},${a})`; + function drawBox(ctx,b,f,ox,oy){ + const x0=b.x-b.sx/2,x1=b.x+b.sx/2,y0=b.y-b.sy/2,y1=b.y+b.sy/2,z0=b.z-b.sz/2,z1=b.z+b.sz/2; + const fade=Math.min(1,(FAR-b.z)/.45)*Math.min(1,(z0-NEAR)/.18); + if(fade<=0)return; + const P=(x,y,z)=>project(x,y,z,f,ox,oy); + const c={nnn:P(x0,y0,z0),pnn:P(x1,y0,z0),npn:P(x0,y1,z0),ppn:P(x1,y1,z0),nnp:P(x0,y0,z1),pnp:P(x1,y0,z1),npp:P(x0,y1,z1),ppp:P(x1,y1,z1)}; + const faces=[['near',[c.nnn,c.pnn,c.ppn,c.npn],-1,'z',z0],['top',[c.nnn,c.pnn,c.pnp,c.nnp],y0,'y',-1],['bottom',[c.npn,c.ppn,c.ppp,c.npp],y1,'y',1],['left',[c.nnn,c.nnp,c.npp,c.npn],x0,'x',-1],['right',[c.pnn,c.pnp,c.ppp,c.ppn],x1,'x',1]]; + const dist=Math.min(1,.8+.2*(1-b.z/FAR)); + for(const [name,pts,coord,axis,sign] of faces){ + // A face is visible when the camera (origin) is on its outward side. + const visible=axis==='z'?true:axis==='x'?(sign<0?x0>0:x1<0):(sign<0?y0>0:y1<0); + if(!visible)continue; + ctx.beginPath();pts.forEach(([px,py],i)=>i?ctx.lineTo(px,py):ctx.moveTo(px,py));ctx.closePath(); + if(b.glass){ctx.fillStyle=`rgba(170,205,255,${.07*fade})`;ctx.fill();ctx.strokeStyle=`rgba(205,225,255,${.4*fade})`;ctx.lineWidth=Math.max(1,H/700*1.4);ctx.stroke()} + else{ctx.fillStyle=rgba(FACE[name],fade*dist,b.shade);ctx.fill()} + } + if(b.glass){ + ctx.strokeStyle=`rgba(190,215,255,${.22*fade})`;ctx.lineWidth=1;ctx.beginPath(); + for(const [a,d] of [[c.nnn,c.nnp],[c.pnn,c.pnp],[c.npn,c.npp],[c.ppn,c.ppp]]){ctx.moveTo(a[0],a[1]);ctx.lineTo(d[0],d[1])}ctx.stroke(); + } + } + function drawOrb(ctx,o){ + const u=H/700,fadeIn=Math.min(1,o.life/1.2),fadeOut=Math.min(1,(o.max-o.life)/1.5),k=Math.max(0,Math.min(fadeIn,fadeOut)),n=o.trail.length; + if(n<2||k<=0)return; + ctx.lineCap='round'; + for(let i=1;i0)step(Math.min(dt,.1)); + ctx.globalCompositeOperation='source-over'; + ctx.fillStyle='#02050f';ctx.fillRect(0,0,w,h); + for(const b of blobs){ + const cx=w*(b.x+Math.sin(sim*b.s+b.p)*.08),cy=h*(b.y+Math.cos(sim*b.s*1.3+b.p)*.08),r=Math.max(w,h)*b.r; + const g=ctx.createRadialGradient(cx,cy,0,cx,cy,r);g.addColorStop(0,'rgba(20,64,180,.5)');g.addColorStop(.6,'rgba(8,28,90,.16)');g.addColorStop(1,'rgba(2,5,15,0)'); + ctx.fillStyle=g;ctx.fillRect(0,0,w,h); + } + const f=h*.62,ox=0,oy=0,sorted=[...boxes].sort((a,c)=>c.z-a.z); + const haze=amount=>{for(const g of fog){ + const cx=w*(g.x+Math.sin(sim*g.s+g.p)*.14),cy=h*(g.y+Math.cos(sim*g.s*1.2+g.p)*.07),r=Math.max(w,h)*g.r; + const grad=ctx.createRadialGradient(cx,cy,0,cx,cy,r);grad.addColorStop(0,`rgba(70,115,215,${g.a*amount})`);grad.addColorStop(.55,`rgba(30,60,150,${g.a*amount*.5})`);grad.addColorStop(1,'rgba(10,25,80,0)'); + ctx.fillStyle=grad;ctx.fillRect(0,0,w,h); + }}; + // Fog sits between the far and near blocks so depth reads through it. + for(const b of sorted)if(b.z>1.25)drawBox(ctx,b,f,ox,oy); + haze(1); + for(const b of sorted)if(b.z<=1.25)drawBox(ctx,b,f,ox,oy); + haze(.4); + // Dark fall-off toward the corners, like the original. + const v=ctx.createRadialGradient(w/2,h/2,Math.min(w,h)*.35,w/2,h/2,Math.max(w,h)*.75);v.addColorStop(0,'rgba(0,0,0,0)');v.addColorStop(1,'rgba(0,0,6,.55)');ctx.fillStyle=v;ctx.fillRect(0,0,w,h); + ctx.globalCompositeOperation='lighter';for(const o of orbs)drawOrb(ctx,o);ctx.globalCompositeOperation='source-over'; + } + return {draw}; +})(); diff --git a/renderer/styles.css b/renderer/styles.css index ad0505d..4454219 100644 --- a/renderer/styles.css +++ b/renderer/styles.css @@ -23,6 +23,25 @@ kbd { font: 600 11px "Segoe UI"; padding: 2px 6px; border-radius: 4px; backgroun code { background: rgba(255,255,255,.08); padding: 1px 5px; border-radius: 4px; } .hidden { display: none !important; } +/* Feedback stays in-app until the user chooses to open their browser. */ +#feedbackDialog { width:min(650px,calc(100vw - 48px)); max-height:calc(100vh - 48px); overflow:auto; border:1px solid var(--line); border-radius:18px; padding:24px; color:var(--text); background:#151b27; box-shadow:0 30px 100px #0009; user-select:text; } +#feedbackDialog::backdrop { background:#030710b3; backdrop-filter:blur(12px); } +.feedback-heading { display:flex; align-items:center; justify-content:space-between; gap:16px; } +.feedback-heading h2 { margin:0; font-size:22px; } +.feedback-heading button { padding:4px 12px; font-size:24px; } +#feedbackForm > label, #feedbackStepsGroup > label { display:block; font-size:13px; margin:14px 0 6px; } +#feedbackForm > input, #feedbackForm > select, #feedbackForm textarea { width:100%; } +#feedbackForm textarea { display:block; resize:vertical; min-height:70px; font:inherit; font-size:14px; color:var(--text); background:rgba(0,0,0,.35); border:1px solid var(--line); border-radius:8px; padding:9px 11px; } +#feedbackForm textarea:focus { outline:1px solid var(--accent); } +#feedbackForm .feedback-diagnostics-toggle { display:flex; align-items:center; gap:8px; } +#feedbackDevice { white-space:pre-wrap; overflow-wrap:anywhere; font-size:12px; line-height:1.5; padding:10px 12px; border-radius:8px; background:#0004; margin:8px 0; } +.feedback-note, #feedbackPrivacy { font-size:12px; line-height:1.6; } +#feedbackStatus { font-size:13px; line-height:1.5; overflow-wrap:anywhere; } +#feedbackStatus:empty { display:none; } +.feedback-actions { display:flex; justify-content:flex-end; gap:10px; margin-top:16px; } +.feedback-browse { padding:0; border:0; border-radius:0; background:transparent; color:var(--accent2); font-size:12px; } +.feedback-browse:hover { background:transparent; text-decoration:underline; } + /* ---------- ambient background ---------- */ #bg { position: fixed; inset: 0; z-index: 0; background: radial-gradient(ellipse at 50% 30%, var(--tint), #07080c 70%); transition: background 1s; } .bg-layer { position: absolute; inset: -60px; background-size: cover; background-position: center; filter: blur(40px) saturate(1.3) brightness(.45); @@ -30,6 +49,69 @@ code { background: rgba(255,255,255,.08); padding: 1px 5px; border-radius: 4px; .bg-layer.on { opacity: 1; } .bg-vignette { position: absolute; inset: 0; background: radial-gradient(ellipse at center, transparent 30%, rgba(0,0,0,.75) 100%), linear-gradient(to bottom, rgba(0,0,0,.4), transparent 20%, transparent 60%, rgba(0,0,0,.85)); } +/* The ambient canvas sits inside #bg; xmb.css owns its scene and screensaver styling. */ + +/* ---------- physical media models ---------- */ +.disc-mini .disc-metal { mask-image: radial-gradient(circle,transparent 0 10.5%,#000 11%); } +.disc-mini .disc-surface { inset: 2px; mask-image: radial-gradient(circle,transparent 0 22%,#000 22.5%); } +.disc-mini .disc-hub { background: radial-gradient(circle,transparent 0 10.5%,#e0e7f077 11% 13%,#aab5c788 13.5% 19%,#e2eaf070 19.5% 22%,transparent 22.5%); } +.cartridge-whole-photo { position: absolute; inset: 0; width: 100%; height: 100%; object-fit: contain; } + +/* Flat covers omit the model DOM as well as the perspective effects. */ +html[data-models='off'] :is(#stage,.model-stage) { perspective: none; } +html[data-models='off'] :is(.item,.item .sway,.flat-cover,.flat-case,#caseRig) { transform-style: flat; } +html[data-models='off'] .item .sway { transform: none !important; animation: none !important; display: block !important; } +html[data-models='off'] .item { filter: none !important; } +html[data-models='off'] .flat-cover { display: block !important; } +html[data-models='off'] .flat-cover .f-front { transform: none; } +.flat-case .face { width: var(--w); height: var(--h); transform: none; } +.flat-case .f-back,.flat-case.flat-back .f-front { display: none; } +.flat-case.flat-back .f-back { display: block; } +html[data-models='off'] :is(#caseView,#tabs,.search) { backdrop-filter: none; } +html[data-animations='off'] *,html[data-animations='off'] *::before,html[data-animations='off'] *::after { animation: none !important; transition: none !important; scroll-behavior: auto !important; } + +/* ---------- layout refinements ---------- */ +html[data-layout=bookshelf] .item { transition: transform .55s cubic-bezier(.2,.8,.2,1); } +html[data-layout=bookshelf] .item.sel .sway { animation: none; transform: none; } +html[data-layout=bookshelf] .item:not(.sel) .shadow { display: none; } +html[data-layout=bookshelf] .item:not(.sel):hover .f-left::after { box-shadow: inset 0 0 0 100px #ffffff1a; } +html[data-layout=bookshelf] .item.sel.media-revealed .disc-model { + /* Keep the disc in the gap beside the selected case, clear of adjacent spines. */ + transform: translate3d(calc((var(--w) - var(--mw)) / 2 + var(--bookshelf-disc-peek, 0px)), calc(var(--h) * -.02), -8px) rotateY(-15deg) rotateZ(14deg); +} +#rackPost { position: absolute; display: none; } + +/* ---- Used copies: scuffs, worn corners, faded labels ---- */ +html[data-wear='on'] .box .f-front, html[data-wear='on'] .box .f-back, html[data-wear='on'] .box .f-left, html[data-wear='on'] .box .l-front { filter: saturate(.8) sepia(.12) brightness(.97); } +html[data-wear='on'] .box .f-front::after, html[data-wear='on'] .box .l-front::after { + content: ''; position: absolute; inset: 0; pointer-events: none; + background: + repeating-linear-gradient(17deg, transparent 0 37px, #ffffff24 37px 38px, transparent 38px 91px), + repeating-linear-gradient(-62deg, transparent 0 53px, #ffffff1c 53px 54px, transparent 54px 140px), + radial-gradient(ellipse at 88% 9%, #ffffff1c, transparent 22%), + radial-gradient(ellipse at 12% 94%, #0000002a, transparent 26%), + linear-gradient(115deg, rgba(255,255,255,.2) 0%, rgba(255,255,255,.04) 28%, transparent 45%, rgba(255,255,255,.05) 80%); + box-shadow: inset 0 0 0 1px #ffffff22, inset 0 0 10px #ffffff1a; +} +html[data-wear='on'] .disc-surface, html[data-wear='on'] .cartridge-label { filter: saturate(.78) sepia(.16); } +html[data-wear='on'] .disc-surface::before { content: ''; position: absolute; inset: 0; border-radius: 50%; pointer-events: none; z-index: 1; + background: repeating-conic-gradient(from 10deg, transparent 0 7deg, #ffffff12 7deg 7.3deg, transparent 7.3deg 23deg); } +html[data-wear='on'] .cartridge-label::after { content: ''; position: absolute; inset: 0; pointer-events: none; + background: repeating-linear-gradient(-35deg, transparent 0 13px, #ffffff16 13px 14px, transparent 14px 40px), radial-gradient(ellipse at 90% 92%, #fff3 0, transparent 18%); } +html[data-wear='on'] .item:not(.sel) .box .f-front::after { background: #080b1555; box-shadow: none; } + +/* ---- Instruction booklet with real thickness (back cover, spine and page edges) ---- */ +.manual { --bt: max(4px, calc(var(--w) * .024)); } +.manual .page { transform: translateZ(calc(var(--bt) / 2)); } +.manual-back, .manual-edge { position: absolute; pointer-events: none; } +.manual-back { inset: 0; border-radius: 2px; background: #dcd8cf; transform: translateZ(calc(var(--bt) / -2)) rotateY(180deg); } +.manual-edge { background: repeating-linear-gradient(90deg, #f6f4ee 0 1px, #cdc8bc 1px 2px); } +.manual-edge-fore, .manual-edge-spine { top: 0; bottom: 0; width: var(--bt); } +.manual-edge-fore { right: 0; transform: translateX(calc(var(--bt) / 2)) rotateY(90deg); } +.manual-edge-spine { left: 0; transform: translateX(calc(var(--bt) / -2)) rotateY(-90deg); background: linear-gradient(90deg, #b9b4a8, #e8e5dd 50%, #b9b4a8); } +.manual-edge-top, .manual-edge-bottom { left: 0; right: 0; height: var(--bt); background: repeating-linear-gradient(0deg, #f6f4ee 0 1px, #cdc8bc 1px 2px); } +.manual-edge-top { top: 0; transform: translateY(calc(var(--bt) / -2)) rotateX(90deg); } +.manual-edge-bottom { bottom: 0; transform: translateY(calc(var(--bt) / 2)) rotateX(-90deg); } /* ---------- header ---------- */ header { position: relative; z-index: 5; display: flex; align-items: center; gap: 32px; padding: 18px 36px; } @@ -91,7 +173,72 @@ header { position: relative; z-index: 5; display: flex; align-items: center; gap .shelf-instruction { margin-left: auto; color: #a1a9bc; } #empty { position: absolute; inset: 0; display: grid; place-items: center; color: var(--muted); font-size: 18px; } -.item { position: absolute; transform-style: preserve-3d; transition: transform .65s cubic-bezier(.2,.75,.2,1); cursor: pointer; } + +.shelf-continuation { position:absolute;left:50%;top:51%;transform-style:preserve-3d;pointer-events:none; } +.shelf-transfer .item, .shelf-transfer .physical-media, .shelf-transfer .ground-reflection { transition:none !important; } +.item.console-arrival { transition:none !important; } +.console-preview { position:absolute;left:84%;right:-120px;top:51%;transform:translateY(-50%);display:flex;align-items:center;gap:20px;pointer-events:none;transition:opacity .3s ease; } +.console-preview.previous { left:-120px;right:84%;flex-direction:row-reverse;text-align:right; } +.console-preview-name { flex:1;min-width:0;font-family:inherit;font-size:clamp(14px,1.45vw,27px);font-weight:600;letter-spacing:.02em;line-height:1.2;color:var(--text);text-shadow:0 2px 16px #0008; } +.console-preview-covers { display:flex;align-items:center;flex:1;min-width:0;gap:6px; } +.console-preview.previous .console-preview-covers { flex-direction:row-reverse; } +.console-preview-cover { position:relative;flex:1;max-width:72px;min-width:0;aspect-ratio:.7;transform:perspective(500px) rotateY(-14deg);opacity:.85; } +.console-preview-cover:nth-child(2) { opacity:.45; } +.console-preview-cover:nth-child(3) { opacity:.2; } +.console-preview.previous .console-preview-cover { transform:perspective(500px) rotateY(14deg); } +.console-preview-face { position:absolute;inset:0;background-size:100% 100%;background-position:center;border-radius:2px;box-shadow:-2px 3px 9px #0008;border:1px solid #ffffff25;overflow:hidden; } +html[data-chrome-mode]:not([data-chrome-hidden='true']) #libraryHints { opacity:1;pointer-events:auto; } +html[data-chrome-hidden='true'] :is(header,#libraryHints,.shelf-position,.shelf-arrow,.banner) { opacity:0 !important;pointer-events:none !important; } +html[data-chrome-hidden='true'] #info { transition:opacity .35s ease; } +html[data-chrome-hidden='true']:not([data-details-pinned='true']) #info { opacity:0 !important;pointer-events:none !important; } +html[data-details-pinned='true'] #info { opacity:1; } +#view-library { overflow:clip; } +.shelf-tools { margin-left:auto;display:flex;align-items:center;gap:8px; } +html[data-info-bar='xlarge'] #info { gap:28px; } +html[data-info-bar='xlarge'] #info .info-text { max-width:min(70vw,1100px); } +html[data-info-bar='xlarge'] #info h1 { font-size:clamp(34px,3.4vw,58px);-webkit-line-clamp:2;line-height:1.1; } +html[data-info-bar='xlarge'] #info .meta { font-size:clamp(14px,1.2vw,19px); } +html[data-info-bar='xlarge'] #info #gDesc { font-size:clamp(14px,1.3vw,20px);line-height:1.45;-webkit-line-clamp:3; } +html[data-info-bar='xlarge'] #info .shot { width:clamp(200px,25vw,420px); } +html[data-info-bar='xlarge'] #info { display:grid;grid-template-columns:minmax(0,1fr) clamp(220px,23vw,420px) minmax(0,1fr);gap:24px;align-items:center; } +html[data-info-bar='xlarge'] #info .info-text { grid-column:1;max-width:none;min-width:0; } +html[data-info-bar='xlarge'] #info .shot { grid-column:2;grid-row:1;width:100%;box-sizing:border-box;align-self:center;background-size:contain;background-repeat:no-repeat; } +html[data-info-bar='xlarge'] #info .shot video { object-fit:contain; } +#detailsResizeHandle { position:absolute;left:0;right:0;top:-14px;width:100%;height:24px;display:flex;align-items:center;justify-content:center;cursor:ns-resize;touch-action:none;z-index:12;border-radius:10px;background:#121923c9;border:1px solid #ffffff25; } +#detailsResizeHandle span { display:block;width:36px;height:4px;border-radius:4px;background:#ffffff80; } +#detailsResizeHandle:is(:hover,:focus-visible) { border-color:var(--accent);outline:none; } +.details-dragging, .details-dragging * { cursor:ns-resize !important;user-select:none !important; } +html[data-details-resized='true'] #info { height:var(--details-height);box-sizing:border-box;display:grid;grid-template-columns:minmax(0,1fr) var(--details-shot-width) minmax(0,1fr);align-items:center;gap:24px;padding-top:22px; } +html[data-details-resized='true'] #info .info-text { grid-column:1;grid-row:1;max-width:none;min-width:0; } +html[data-details-resized='true'] #info .shot { grid-column:2;grid-row:1;width:100%;background-size:contain;background-repeat:no-repeat;box-sizing:border-box; } +html[data-details-resized='true'] #info h1 { font-size:var(--details-title-size); } +html[data-details-resized='true'] #info .meta { font-size:var(--details-meta-size); } +html[data-details-resized='true'] #info #gDesc { font-size:var(--details-desc-size); } +html[data-details-tiny='true'] #info :is(.eyebrow,.meta) { display:none !important; } +html[data-details-resized='true'] #info .actions { margin-top:8px;gap:6px; } +html[data-details-resized='true'] #info .actions button { font-size:12px;padding:.4em .7em; } +html[data-details-resized='true'] #info .actions .button-prompt { width:24px;height:24px; } +html[data-details-tiny='true'] #info .actions { display:none; } +#detailsResizeHandle { background:transparent;border:0;box-shadow:none;opacity:0;transition:opacity .18s ease; } +#detailsResizeHandle:hover, #detailsResizeHandle:focus-visible, .details-dragging #detailsResizeHandle { opacity:.65; } +#detailsResizeHandle span { height:3px;width:32px;background:#ffffffa0; } +#detailsResizeHandle:is(:hover,:focus-visible) { border:0; } +html[data-details-flow='true'] #info { display:grid;grid-template-columns:minmax(0,1fr) var(--details-shot-width);gap:24px;align-items:center; } +html[data-details-flow='true'] #info .info-text { grid-column:1;grid-row:1;max-width:none;min-width:0; } +html[data-details-flow='true'] #info .shot { grid-column:2;grid-row:1;width:100%;box-sizing:border-box;align-self:end;position:relative; } +html[data-details-resized='true'][data-details-flow='true'] #info { grid-template-rows:minmax(0,1fr); } +html[data-details-resized='true'] #info { max-height:var(--details-max-height); } +html[data-details-flow='true'] #info{column-gap:24px!important;} +html[data-details-flow='true'] #gShot.shot{width:100%!important;} +html[data-details-flow='true'] #info .info-text { align-self:end;min-height:var(--details-shot-height);display:flex;flex-direction:column; } +html[data-details-flow='true'] #info .info-text #gTitle { flex:none;font-size:min(var(--details-title-size, clamp(22px, 3.4vw, 58px)), var(--details-title-cap));margin:3px 0; } +html[data-details-flow='true'][data-details-shot-tight='true'] #info #gTitle { -webkit-line-clamp:1; } +html[data-details-flow='true'] #info .meta { flex:none;flex-wrap:nowrap;white-space:nowrap;overflow:hidden; } +html[data-details-flow='true'] #info #gDesc { flex:1 1 auto;min-height:0;margin:4px 0; } +html[data-details-flow='true'] #info .actions { flex:none;flex-wrap:wrap;margin-top:auto; } +html[data-details-flow='true'] #info .actions button { flex:none;white-space:nowrap; } + +.item { position: absolute; width: var(--w); height: var(--h); transform-style: preserve-3d; transition: transform .65s cubic-bezier(.2,.75,.2,1); cursor: pointer; } .item.far { visibility: hidden; pointer-events: none; } /* Filters or opacity on a 3D ancestor flatten its six faces. Shade the faces instead. */ .item:not(.sel) .f-front::after { background: #080b1555; } @@ -137,6 +284,7 @@ header { position: relative; z-index: 5; display: flex; align-items: center; gap .f-back::after { background: linear-gradient(245deg, rgba(255,255,255,.12), transparent 40%); } /* Packaging materials and printed spine inserts, shared by shelf and case viewer. */ .box[data-material] :is(.f-front,.f-back,.l-front) { padding: var(--case-rim); background-origin: content-box; background-clip: content-box; border-radius: var(--case-radius); background-color: var(--case-shell); } +.box:is([data-packaging='snes'],[data-packaging^='superfamicom-']) :is(.f-front,.f-back) { background-size: contain; background-position: center; background-repeat: no-repeat; } .box[data-material] :is(.f-front,.l-front) > .digital-sleeve { inset: var(--case-rim); } .box[data-material] :is(.f-front,.f-back,.l-front)::after { border: var(--case-rim) solid var(--case-shell); border-radius: var(--case-radius); box-shadow: inset 0 0 0 1px #ffffff24; } .box[data-material] :is(.f-right,.f-top,.f-bottom) { background: linear-gradient(90deg,#0004,transparent 25%,#ffffff28 48%,#0003 52%,transparent 75%),var(--case-shell); border: 1px solid #ffffff25; } @@ -204,10 +352,20 @@ header { position: relative; z-index: 5; display: flex; align-items: center; gap /* Shared physical media: carousel preview and full case viewer use the same model. */ .physical-media { position: absolute; width: var(--mw); height: var(--mh); left: calc((var(--w) - var(--mw)) / 2); top: calc((var(--h) - var(--mh)) / 2); transform-style: preserve-3d; } -.item .physical-media { visibility: hidden; transform: translate3d(0,0,0); transition: transform .85s cubic-bezier(.2,.8,.2,1), visibility 0s .85s; } +.item .physical-media { visibility: hidden; pointer-events: none; transform: translate3d(0,0,0); transition: transform .85s cubic-bezier(.2,.8,.2,1), visibility 0s .85s; } .item.sel.media-revealed .physical-media { visibility: visible; transition-delay: 0s; } -.item.sel.media-revealed .disc-model { transform: translate3d(calc(var(--w) * .65), calc(var(--h) * .04), -8px) rotateY(-15deg) rotateZ(14deg); } -.item.sel.media-revealed .cartridge-model { transform: translate3d(calc(var(--w) * .71), calc(var(--h) * -.28), -8px) rotateY(-17deg) rotateZ(9deg); } +.item.far .physical-media { visibility: hidden; transition: none; } +.item.sel.media-revealed .physical-media { --media-out: min(var(--media-slide), calc(var(--w) * .8 - var(--mw) / 2)); } +.item.sel.media-revealed .disc-model { --media-slide: calc(var(--w) * .65); transform: translate3d(var(--media-out, calc(var(--w) * .65)), calc(var(--h) * .04), -8px) rotateY(-15deg) rotateZ(14deg); } +.item.sel.media-revealed .disc-rotor { animation: disc-spin 120s linear infinite; } +.item .disc-surface::after { animation: none; } +@keyframes disc-spin { to { transform: rotate(360deg); } } +/* Cartridges rise above their own cover so the label is visible, with the lift capped for tall shells. */ +.item.sel.media-revealed .cartridge-model { + --media-slide: calc(var(--w) * .71); + --media-lift: calc((var(--mh) - var(--h)) / 2 - min(var(--mh) * .55, var(--h) * .36)); + transform: translate3d(var(--media-out), var(--media-lift), -8px) rotateY(-17deg) rotateZ(9deg); +} .disc-rotor { position: absolute; inset: 0; border-radius: 50%; transform-style: preserve-3d; } .disc-metal, .disc-surface, .disc-hub { position: absolute; inset: 0; border-radius: 50%; } .disc-metal { background: conic-gradient(#dce4ec,#767e95,#e8eff3,#b0c3d0,#737d94,#e0e6ed); box-shadow: 0 1px 0 #fff9, 2px 5px 2px #050610; mask-image: radial-gradient(circle,transparent 0 7%,#000 7.5%); } @@ -224,6 +382,7 @@ header { position: relative; z-index: 5; display: flex; align-items: center; gap .cartridge-molding { position: absolute; inset: 0; width: 100%; height: 100%; } .cartridge-front::after { content: ''; position: absolute; inset: 0; pointer-events: none; background: linear-gradient(120deg,#ffffff16,transparent 34%,#0001 80%); } .cartridge-label { position: absolute; background-size: cover; background-position: center; border-radius: 1.5px; box-shadow: 0 0 0 1px #0005, 0 1px 0 #ffffff30; overflow: hidden; } +.cartridge-label-well { position: absolute; border-radius: 3px; background: #0000003a; box-shadow: inset 0 2px 3px #0009,inset 0 -1px 1px #0004,0 1px 0 #ffffff42; } .case.open .physical-media { transition: transform 1s cubic-bezier(.2,.8,.2,1) .55s; transform: translate3d(calc(var(--w) * .85),-8px,150px) rotateY(-12deg) rotateZ(6deg); } .case .physical-media { transform: translateZ(0px); transition: transform .65s cubic-bezier(.2,.8,.2,1); } @@ -290,18 +449,47 @@ html[data-motion="reduced"] .spinner { animation: spin 1.5s linear infinite !imp background: radial-gradient(circle at 50% 50%, #2a2d35 0 12%, #0d0e12 12.5% 13.5%, #1a1c22 14%) , #16181d; } .jewel .tray { background: radial-gradient(circle at 50% 50%, rgba(255,255,255,.2) 0 12%, #111 12.5% 13.5%, rgba(20,22,30,.9) 14%); } .cartbox .tray, .ds .tray { background: linear-gradient(#202228, #15161b); } -.lid { position: absolute; left: 0; top: 0; width: var(--w); height: var(--h); transform-style: preserve-3d; transform-origin: 0 50%; - transform: translateZ(calc(var(--d) / 2)); transition: transform 1.1s cubic-bezier(.5,0,.2,1); } +.lid, .case-spine { position: absolute; left: 0; top: 0; height: var(--h); transform-style: preserve-3d; transform-origin: 0 50%; transition: transform 1.1s cubic-bezier(.5,0,.2,1); } +/* The cover's hinge follows the free edge of the spine as it folds out from the tray. */ +.case-spine { width: var(--d); transform: translateZ(calc(var(--d) / -2)) rotateY(-90deg); } +.case.open .case-spine { transform: translateZ(calc(var(--d) / -2)) rotateY(-180deg); } +.case-spine .face { left: 0; width: 100%; height: 100%; } +.case-spine .f-left { transform: translateZ(.5px); } +.case-spine-inner { transform: rotateY(180deg) translateZ(.5px); background: linear-gradient(90deg,#0005,#fff2 23%,#0001 77%,#0006),var(--case-shell); } +.lid { width: var(--w); transform: translateZ(calc(var(--d) / -2)) rotateY(-90deg) translateX(var(--d)) rotateY(90deg); } .lid .face { width: var(--w); height: var(--h); } .lid .l-front { transform: translateZ(.5px); } .lid .l-inner { transform: rotateY(180deg) translateZ(.5px); background: linear-gradient(135deg, #1c1e25, #101116); box-shadow: inset 0 0 0 6px #22252d; } -.case.open .lid { transform: translateZ(calc(var(--d) / 2)) rotateY(-150deg); } +.case.open .lid { transform: translateZ(calc(var(--d) / -2)) rotateY(-180deg) translateX(var(--d)) rotateY(30deg); } .case[data-material='cardboard'] .tray { background: var(--case-shell); } .case[data-material='cardboard'] .lid { height: var(--d); transform-origin: 50% 0; transform: translateZ(calc(var(--d) / -2)) rotateX(90deg); } .case[data-material='cardboard'] .lid .face { height: var(--d); background: var(--case-print); border: 1px solid var(--case-shell); } .case[data-material='cardboard'] .lid .l-inner { background: var(--case-shell); box-shadow: none; } .case[data-material='cardboard'].open .lid { transform: translateZ(calc(var(--d) / -2)) rotateX(155deg); } -.case[data-material='cardboard'].open .physical-media { transform: translate3d(0,calc(var(--h) * -.8),8px) rotateY(-8deg) rotateZ(-4deg); } +/* The cartridge waits inside its cardboard box, centred, and comes out through the open top. + It stays straight and moves in one continuous arc: the rise (translate) and the move forward + (transform) are separate animations with their own easing, so neither stops while the other + starts. It rises a little past its resting height, and the forward move begins as its bottom + clears the top, so the glide is at full speed while the rise peaks; it then settles just above + the box, in front of the flap, where the whole label shows. */ +.case[data-material='cardboard'] .physical-media { transform: translateZ(0); translate: 0 0; } +.case[data-material='cardboard'].open .physical-media { + --media-clear: min(calc(var(--h) * -.8), calc((var(--h) + var(--mh)) / -2 - 2px)); + --media-over: calc(var(--media-clear) - 30px); + --media-front: calc((var(--d) + var(--cd, 2px)) / 2 + 4px); + translate: 0 var(--media-clear); + transform: translateZ(var(--media-front)); + animation: cardboard-media-rise 1.4s .7s both, cardboard-media-forward .9s ease-in-out 1.12s both; +} +@keyframes cardboard-media-rise { + 0% { translate: 0 0; animation-timing-function: cubic-bezier(.25,.6,.35,1); } + 57% { translate: 0 var(--media-over); animation-timing-function: ease-in-out; } + 100% { translate: 0 var(--media-clear); } +} +@keyframes cardboard-media-forward { + from { transform: translateZ(0); } + to { transform: translateZ(var(--media-front)); } +} .box-flap-title { position: absolute; inset: 0; display: grid; place-items: center; font-size: calc(var(--d) * .21); font-weight: 650; padding: 2px 8%; color: var(--case-ink); text-align: center; overflow: hidden; } .manual { position: absolute; transform-style: preserve-3d; transition: transform 1s cubic-bezier(.3,.9,.3,1); } @@ -315,7 +503,8 @@ html[data-motion="reduced"] .spinner { animation: spin 1.5s linear infinite !imp .manual .tag { position: absolute; bottom: -34px; left: 0; right: 0; text-align: center; font-size: 13px; color: var(--muted); opacity: 0; transition: opacity .3s 1.4s; } .case.open .manual { transition-delay: .55s; transform: translate3d(calc(var(--w) * -1.08), 14px, 150px) rotateY(20deg) rotateZ(-3deg) scale(.92); } .case.open .manual .tag { opacity: 1; } -.case.open .manual:hover .page { transform: translateZ(20px) scale(1.02); } +.case.open .manual:hover .page { transform: translateZ(calc(var(--bt) / 2 + 20px)) scale(1.02); } +.case.side-view .manual .tag { opacity: 0 !important; transition: opacity .15s; } /* ---------- emulators ---------- */ .view-head { display: flex; align-items: flex-end; justify-content: space-between; gap: 24px; margin-bottom: 20px; } diff --git a/renderer/tauri-bridge.js b/renderer/tauri-bridge.js new file mode 100644 index 0000000..9e7b033 --- /dev/null +++ b/renderer/tauri-bridge.js @@ -0,0 +1,90 @@ +(() => { + if (!window.__TAURI__?.core?.invoke) return; + + const invoke = window.__TAURI__.core.invoke; + const listen = window.__TAURI__.event.listen; + const convertFileSrc = window.__TAURI__.core.convertFileSrc; + // SAF tree URIs are stored as-is; only file:// media becomes asset URLs. + const isContentUri = value => typeof value === 'string' && value.startsWith('content://'); + const convertPaths = value => { + if (isContentUri(value)) return value; if (typeof value === 'string' && value.startsWith('file://')) { + try { return convertFileSrc(decodeURIComponent(new URL(value).pathname)); } catch { return value; } + } + if (Array.isArray(value)) return value.map(convertPaths); + if (value && typeof value === 'object') return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, convertPaths(item)])); + return value; + }; + const call = (command, args) => invoke(command, args).then(convertPaths); + const subscribe = (event, fn) => { + let stop; + // Events bypass `call()`'s convertPaths, so Rust file:// URLs (with %20 + // segments from paths with spaces - e.g. "Application Support") would + // never load as images in the webview. Convert them here too. + listen(event, message => fn(convertPaths(message.payload))).then(unlisten => { stop = unlisten; }); + return () => stop?.(); + }; + + const toggleFullscreen = async () => { + const appWindow = window.__TAURI__.window.getCurrentWindow(); + await appWindow.setFullscreen(!(await appWindow.isFullscreen())); + }; + + window.addEventListener('keydown', event => { + if (event.key !== 'F11' || event.repeat) return; + event.preventDefault(); + toggleFullscreen().catch(error => console.error('Failed to toggle fullscreen:', error)); + }); + + window.api = { + ...window.api, + getConfig: () => call('get_config'), + setConfig: cfg => call('set_config', { cfg }), + scan: (withReport = false, options) => call('scan_library', { with_report: withReport, options: options ?? null }), + cachedLibrary: () => call('cached_library'), + toggleFavorite: id => call('toggle_favorite', { game_id: id }), + recordPlay: (id, playTime) => call('record_play', { id, play_time: playTime }), + updateLibraryPrefs: prefs => call('update_library_prefs', { prefs }), + getFavorites: () => call('get_favorites'), + getRecentlyPlayed: limit => call('get_recently_played', { limit }), + setHidden: opts => call('set_game_hidden', { game_id: opts.gameId, hidden: !!opts.hidden }), + setSystemGamesHidden: opts => call('set_system_games_hidden', { system: opts.system, hidden: !!opts.hidden }), + setMetadata: opts => call('set_game_metadata', { opts }), + setGameEmulator: opts => call('set_game_emulator', { opts }), + saveGameOrder: opts => call('save_game_order', { opts }), + addGame: opts => call('add_game', { opts }), + removeGame: id => call('remove_game', { id }), + gameList: () => call('list_extra_games'), + launch: id => call('launch_game', { id }), + fetchArt: (sys, base, options) => call('fetch_art', { sysId: sys, base, options }), + artStart: options => call('start_artwork_download', { options }), + artStatus: () => call('artwork_status'), + artCancel: () => call('cancel_artwork_download'), + artOpenFolder: () => call('open_artwork_folder'), + artImport: options => call('import_artwork', { options }), + artSources: () => call('artwork_sources'), + artSetScreenScraper: details => call('set_screenscraper', { details }), + artFindManuals: () => call('find_manuals'), + manualUrl: path => call('manual_url', { path }), + emuList: () => call('list_emulators'), + emuCheck: id => call('check_emulator_update', { id }), + emuInstall: id => call('install_emulator', { id }), + emuUninstall: id => call('uninstall_emulator', { id }), + emuOpenFolder: id => call('open_emulator_folder', { id }), + emuPickExe: id => call('pick_emulator_executable', { id }), + emuAddCustom: opts => call('add_custom_emulator', { opts }), + pickFolder: title => call('pick_folder', { title }), // Android SAF grant arrives as content URI + openManual: path => call('open_manual', { path }), + onProgress: fn => subscribe('emu:progress', fn), + onArtProgress: fn => subscribe('art:progress', fn), + onAppUpdateProgress: fn => subscribe('app:updateProgress', fn), + onToast: fn => subscribe('toast', fn), + appVersion: () => call('app_version'), + quitApp: () => call('quit_app'), + appCheckUpdate: () => call('check_app_update'), + appInstallUpdate: () => call('install_app_update'), + appOpenRelease: url => call('open_release', { url }), + feedbackInfo: () => call('feedback_info'), + feedbackCopy: text => call('feedback_copy', { text }), + feedbackOpen: url => call('feedback_open', { url }) + }; +})(); diff --git a/renderer/xmb.css b/renderer/xmb.css new file mode 100644 index 0000000..37d3329 --- /dev/null +++ b/renderer/xmb.css @@ -0,0 +1,78 @@ +/* Calmer library chrome, XMB-style ambient layer, idle screensaver, and more physical cases. */ + +/* ---------- ambient ribbon ---------- */ +#xmb { position: absolute; inset: 0; width: 100%; height: 100%; opacity: .8; pointer-events: none; transition: opacity 2s ease; mix-blend-mode: screen; } +#xmb[hidden] { display: none; } +#xmb[data-scene='pixel'] { mix-blend-mode: normal; image-rendering: pixelated; opacity: .85; } +html.ambient #xmb[data-scene='pixel'] { opacity: 1; } +html:has(#xmb[data-scene='pixel']) .bg-layer { opacity: 0 !important; } +html:has(#xmb[data-scene='pixel']) .bg-vignette { background: radial-gradient(ellipse at center, transparent 45%, rgba(0,0,0,.55) 100%), linear-gradient(to bottom, rgba(0,0,0,.25), transparent 18%, transparent 40%, rgba(0,0,0,.74)); } +html.ambient #xmb { opacity: 1; } +html[data-motion="reduced"] #xmb { opacity: .55; } + +/* ---------- decluttering ---------- */ +.shelf-heading, #inputBadge, .format-badge { display: none !important; } +.shelf-arrow { opacity: 0; transition: opacity .35s, background .2s, transform .15s, border-color .2s; } +#stage:hover .shelf-arrow, .shelf-arrow:focus-visible { opacity: 1; } +.shelf-position { opacity: .55; } +#gDesc { display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; max-height: none; } +#libraryHints { transition: opacity 1.2s ease; } +html.quiet #libraryHints { opacity: 0; pointer-events: none; } +.banner { font-size: 12px; padding: 4px 14px; background: rgba(255,255,255,.05); border-color: var(--line); color: var(--muted); } +header, .toolbar, #info .actions, #gDesc, .shot, .shelf-position, .banner, .brand, #tabs, #btnAppearance { transition: opacity .9s ease; } + +/* ---------- idle screensaver ---------- */ +html.ambient, html.ambient * { cursor: none !important; } +html.ambient header { background: none; backdrop-filter: none; pointer-events: none; } +html.ambient header::after { opacity: 0; } +html.ambient header > :not(.header-status), html.ambient .header-status > :not(#clock), +html.ambient .toolbar, html.ambient #libraryHints, html.ambient .shelf-arrow, html.ambient .shelf-position, +html.ambient .banner, html.ambient #info .actions, html.ambient #gDesc, html.ambient .shot, html.ambient #info::before { opacity: 0 !important; pointer-events: none; } +html.ambient #clock { position: fixed; top: 34px; right: 56px; font-size: 52px; font-weight: 200; letter-spacing: .02em; color: #fff; opacity: .85; + text-shadow: 0 2px 30px #0008; animation: clock-drift 900s ease-in-out infinite alternate; } +@keyframes clock-drift { to { transform: translate(-36px, 28px); } } +html.ambient #info { bottom: 56px; } +html.ambient #info h1 { text-shadow: 0 4px 34px #000a; } +html.ambient .item.sel .sway { animation-duration: 12s; } + +/* ---------- more physical cases ---------- */ +/* Moulded hinge groove running down the cover of plastic cases. */ +.box[data-material='plastic'] .case-surface-finish::before, +.box[data-material='clear'] .case-surface-finish::before, +.box[data-material='clamshell'] .case-surface-finish::before { content: ''; position: absolute; top: 1.5%; bottom: 1.5%; left: .6%; width: .6px; background: #00000050; box-shadow: .6px 0 0 #ffffff28; } +.box[data-material] .f-back .case-surface-finish::before { left: auto; right: .6%; box-shadow: -.6px 0 0 #ffffff28; } +.box[data-material='jewel'] .case-surface-finish::after { content: ''; position: absolute; inset: 0; background: linear-gradient(0deg,#0000 0 93%,#00000030 96%,#0000 98%),linear-gradient(#0000 0 4%,#ffffff35 5%,#0000 7%); } + + + +/* Demo hint fades away on its own. */ +#demoBanner:not(.hidden) { animation: banner-fade 1.2s ease 9s forwards; } +@keyframes banner-fade { to { opacity: 0; visibility: hidden; } } + +/* Keep the scene palettes distinct from the selected game's artwork glow. */ +html:has(#xmb[data-scene='xbox']) .bg-layer, +html:has(#xmb[data-scene='towers']) .bg-layer, +html:has(#xmb[data-scene='loom']) .bg-layer, +html:has(#xmb[data-scene='codex']) .bg-layer { opacity: .15 !important; } + +/* Towers & orbs is an opaque scene, so it replaces the blend and keeps game art out of the way. */ +#xmb:is([data-scene='towers'],[data-scene='loom']) { mix-blend-mode: normal; opacity: .92; } +html.ambient #xmb:is([data-scene='towers'],[data-scene='loom']) { opacity: 1; } + +/* Detail sizes return unused space to the game shelf. */ +html:is([data-info-bar='small'],[data-info-bar='compact']) #info { padding-top: 10px; gap: 22px; } +html:is([data-info-bar='small'],[data-info-bar='compact']) #info h1 { font-size: clamp(22px, 2.2vw, 30px); margin: 4px 0; -webkit-line-clamp: 1; } +html:is([data-info-bar='small'],[data-info-bar='compact']) #info .eyebrow { font-size: 10px; letter-spacing: .18em; } +html:is([data-info-bar='small'],[data-info-bar='compact']) #info .meta { font-size: 12px; gap: 10px; } +html:is([data-info-bar='small'],[data-info-bar='compact']) #info .meta span + span::before { margin-right: 10px; } +html:is([data-info-bar='small'],[data-info-bar='compact']) #info #gDesc { font-size: 12px; line-height: 1.4; margin: 5px 0 8px; -webkit-line-clamp: 1; } +html:is([data-info-bar='small'],[data-info-bar='compact']) #info .actions { gap: 8px; margin-top: 8px; } +html:is([data-info-bar='small'],[data-info-bar='compact']) #info .actions button { font-size: 12px; padding: .45em .8em; } +html:is([data-info-bar='small'],[data-info-bar='compact']) #info .actions .button-prompt { width: 24px; height: 24px; } +html[data-info-bar='small'] #info .shot { width: clamp(145px, 16vw, 210px); } +html[data-info-bar='compact'] #info :is(#gDesc,.shot,.meta,.eyebrow) { display: none !important; } +html[data-info-bar='compact'] #info { align-items: center; } +html[data-info-bar='compact'] #info .info-text { display: flex; align-items: center; gap: 18px; max-width: none; min-width: 0; } +html[data-info-bar='compact'] #info h1 { flex: 1; min-width: 0; font-size: clamp(18px, 1.8vw, 24px); } +html[data-info-bar='compact'] #info .actions { flex-shrink: 0; margin: 0; } +html[data-info-bar='hidden'] #info { display: none; } diff --git a/scripts/build-prompts.js b/scripts/build-prompts.js index 82b587f..9f04f18 100644 --- a/scripts/build-prompts.js +++ b/scripts/build-prompts.js @@ -3,18 +3,24 @@ const fs = require('node:fs'); const path = require('node:path'); const root = path.join(__dirname, '../renderer/assets/prompts'); const xml = s => String(s).replace(/[&<>"']/g, c => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c])); -const ink = '#f2f3f7', accent = '#ffb347'; -const text = (s, size = 24, color = ink, y = 34) => `${xml(s)}`; +const ink = '#f4f0eb', accent = '#b9d3f0', shell = '#2e2b29', edge = '#817a73'; +function text(label, size = 24, color = ink) { + // SVG middle aligns to the lowercase x-height. Raise the baseline for descenders + // and lower it for cap-height labels to centre the visible glyphs. + const offset = /[gjpqy]/.test(label) ? 0 : label === "Q" ? .06 : .095; + const y = 32 + size * offset; + return `${xml(label)}`; +} const line = (d, color = ink, width = 3) => ``; const circle = (cx, cy, r, fill, stroke = 'none', sw = 2) => ``; function cap(shape = 'round') { - const rect = shape === 'round' ? 'x="8" y="6" width="48" height="48" rx="24"' : shape === 'trigger' ? 'x="6" y="6" width="52" height="48" rx="13"' : 'x="4" y="10" width="56" height="40" rx="11"'; - return ``; + if (shape === 'round') return circle(32, 32, 23, shell, edge); + const rect = shape === 'trigger' ? 'x="6" y="9" width="52" height="46" rx="10"' : 'x="3" y="11" width="58" height="42" rx="8"'; + return ``; } -const defs = ''; const directionAngles = {up:0, 'up-right':45, right:90, 'down-right':135, down:180, 'down-left':225, left:270, 'up-left':315}; -const arrow = (direction, color = accent, small = false) => `${line(small ? 'M27 18 L32 13 L37 18 M32 14 V23' : 'M23 27 L32 18 L41 27 M32 19 V43',color,3)}`; -const cross = (color = '#212735') => ``; +const arrow = (direction, color = accent, small = false) => `${line(small ? 'M27 18 L32 13 L37 18 M32 14 V23' : 'M23 28 L32 19 L41 28 M32 19 V45',color,3)}`; +const cross = () => ``; function dpad(dir) { const base = cross(); if (directionAngles[dir] !== undefined) return base + arrow(dir); @@ -23,30 +29,42 @@ function dpad(dir) { return base + ['up','right','down','left'].map(d => arrow(d, ink, true)).join(''); } function stick(side, dir) { - const base = circle(32,32,24,'#10141e','#687184') + circle(32,32,17,'url(#shell)','#8892a5',1.5); - if (dir === 'press') return base + text(side === 'left' ? 'L3' : 'R3',19) + line('M27 5 L32 10 L37 5',accent); + const base = circle(32, 32, 23, shell, edge); + if (dir === 'press') return base + text(side === 'left' ? 'L3' : 'R3',20); if (dir === 'rotate') return base + text(side === 'left' ? 'L' : 'R',18) + line('M13 15 A25 25 0 1 1 8 40 M8 40 L6 29 M8 40 L18 37',accent,2.5); if (dir === 'horizontal') return base + arrow('left',accent,true) + arrow('right',accent,true) + text(side === 'left' ? 'L' : 'R',16); if (dir === 'vertical') return base + arrow('up',accent,true) + arrow('down',accent,true) + text(side === 'left' ? 'L' : 'R',16); return base + (dir ? arrow(dir) : text(side === 'left' ? 'L' : 'R',22)); } +const keyMarks = { + '+': 'M23 32 H41 M32 23 V41', + '−': 'M23 32 H41', + ',': 'M34 28 Q34 34 30 36', + '/': 'M26 44 L38 20', + '[': 'M36 20 H28 V44 H36', + ']': 'M28 20 H36 V44 H28', +}; +function keyMark(label, size) { + if (label === '.') return circle(32, 32, 2.5, ink); + return keyMarks[label] ? line(keyMarks[label], ink) : text(label, size); +} function symbol(name, color) { if (name === 'cross') return line('M23 23 L41 41 M41 23 L23 41',color,3.5); if (name === 'circle') return circle(32,32,12,'none',color,3); if (name === 'square') return ``; - return line('M32 18 L47 43 H17 Z',color,3); + return line('M32 19 L47 45 H17 Z',color,3); } const families = { xbox: {name:'Xbox', face:['A','B','X','Y'], colors:['#8fe09a','#ff8d93','#80bcff','#ffe082'], shoulders:['LB','RB','LT','RT'], menus:['View','Menu','Guide','Share']}, playstation: {name:'PlayStation', face:['cross','circle','square','triangle'], colors:['#91bfff','#ff929b','#f0a5de','#8fe0cc'], shoulders:['L1','R1','L2','R2'], menus:['Share','Options','PS','Touch']}, - nintendo: {name:'Nintendo', face:['B','A','Y','X'], colors:[ink,ink,ink,ink], shoulders:['L','R','ZL','ZR'], menus:['−','+','Home','Capture']}, + nintendo: {name:'Nintendo', face:['B','A','X','Y'], colors:[ink,ink,ink,ink], shoulders:['L','R','ZL','ZR'], menus:['−','+','Home','Capture']}, generic: {name:'Generic gamepad', face:['1','2','3','4'], colors:[ink,ink,ink,ink], shoulders:['L1','R1','L2','R2'], menus:['Select','Start','Home','Share']}, }; -const manifest = {version:1, canvas:64, style:'PyroCade graphite / amber', families:{}, assets:[]}; +const manifest = {version:1, canvas:64, style:'PyroCade flat graphite', families:{}, assets:[]}; function add(family, id, label, body) { const file = `${family}/${id}.svg`; fs.mkdirSync(path.join(root,family),{recursive:true}); - fs.writeFileSync(path.join(root,file), `${xml(label)}${defs}${body}\n`); + fs.writeFileSync(path.join(root,file), `${xml(label)}${body}\n`); manifest.assets.push({family,id,label,file}); } for (const [family, spec] of Object.entries(families)) { @@ -59,7 +77,7 @@ for (const [family, spec] of Object.entries(families)) { : label === 'View' ? line('M20 22 H36 V36 H20 Z M28 28 H44 V42 H28') : label === 'Home' ? line('M19 30 L32 19 L45 30 M23 28 V44 H41 V28 M29 44 V34 H35 V44') : label === 'Capture' ? circle(32,32,10,'none',ink,3) - : text(label,label.length > 5 ? 11 : label.length > 3 ? 13 : 22); + : keyMark(label, label.length > 5 ? 12 : label.length > 3 ? 15 : 22); add(family,id,label,cap()+drawing); }); for (const dir of ['all','horizontal','vertical',...Object.keys(directionAngles)]) add(family,`dpad-${dir}`,`D-pad ${dir}`,dpad(dir)); @@ -70,19 +88,23 @@ manifest.families.keyboard = 'Keyboard'; const keys = Object.fromEntries('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'.split('').map(x=>[x.toLowerCase(),x])); Object.assign(keys,{enter:'Enter',space:'Space',escape:'Esc',tab:'Tab',backspace:'Bksp',shift:'Shift',ctrl:'Ctrl',alt:'Alt',delete:'Del',insert:'Ins',home:'Home',end:'End',pageup:'PgUp',pagedown:'PgDn',plus:'+',minus:'−',comma:',',period:'.',slash:'/',bracketleft:'[',bracketright:']'}); for(let i=1;i<=12;i++) keys['f'+i] = 'F'+i; -for(const [id,label] of Object.entries(keys)) add('keyboard',id,label,cap('wide')+text(label,label.length>3?14:label.length>1?19:25)); +for(const [id,label] of Object.entries(keys)) add('keyboard',id,label,cap('wide')+keyMark(label,label.length>3?18:label.length>1?20:26)); for(const dir of ['up','right','down','left']) add('keyboard',dir,`Arrow ${dir}`,cap('wide')+arrow(dir,ink)); add('keyboard','arrows','Arrow keys',cap('wide')+['up','right','down','left'].map(d=>arrow(d,ink,true)).join('')); manifest.families.mouse = 'Mouse'; +const mouseGestures = { + scroll: 'M32 36 V50 M28 40 L32 36 L36 40 M28 46 L32 50 L36 46', + 'scroll-up': 'M28 40 L32 36 L36 40 M32 36 V50', + 'scroll-down': 'M28 46 L32 50 L36 46 M32 36 V50', + move: 'M23 43 H41 M32 36 V50 M26 40 L23 43 L26 46 M38 40 L41 43 L38 46 M29 39 L32 36 L35 39 M29 47 L32 50 L35 47', + 'drag-left': 'M23 43 H41 M27 39 L23 43 L27 47 M37 39 L41 43 L37 47', +}; for (const id of ['mouse','left','right','middle','scroll','scroll-up','scroll-down','move','drag-left']) { - let body = ''; - if (id === 'left' || id === 'drag-left') body += ''; - if (id === 'right') body += ''; - body += line('M16 31 H48 M32 8 V21','#687184',1.5) + ''; - if (id === 'scroll-up') body += arrow('up',accent,true); - if (id === 'scroll-down') body += arrow('down',accent,true); - if (id === 'scroll') body += line('M7 23 V42 M3 27 L7 23 L11 27 M3 38 L7 42 L11 38',accent,2); - if (id === 'move' || id === 'drag-left') body += line('M4 37 V25 M1 29 L4 25 L7 29 M1 33 L4 37 L7 33 M53 38 H63 M56 35 L53 38 L56 41 M60 35 L63 38 L60 41',accent,2); + let body = ``; + if (id === 'left' || id === 'drag-left') body += ''; + if (id === 'right') body += ''; + body += line('M16 31 H48 M32 8 V21',edge,2) + ''; + if (mouseGestures[id]) body += line(mouseGestures[id], accent, 2); add('mouse',id,`Mouse ${id === 'mouse' ? '' : id.replaceAll('-',' ')}`.trim(),body); } fs.writeFileSync(path.join(root,'manifest.json'),JSON.stringify(manifest,null,2)+'\n'); @@ -90,6 +112,22 @@ fs.writeFileSync(path.join(root,'manifest.js'),'// Generated by scripts/build-pr const cards = manifest.assets.map(a=>`
${xml(a.label)}
${xml(a.id)}
`); const groups = Object.entries(manifest.families).map(([id,name])=>`

${name}${manifest.assets.filter(a=>a.family===id).length} prompts

${cards.filter((_,i)=>manifest.assets[i].family===id).join('')}
`).join(''); fs.writeFileSync(path.join(root,'preview.html'),`PyroCade · Button prompts
PYROCADE / INPUT ASSETS

Every button. One language.

${manifest.assets.length} original prompts · Transparent SVG · Graphite keycaps, amber directions · PNG exports at 64 and 128 px
Face buttons follow physical positions. Nintendo: B south, A east, Y west, X north.

${groups}
`); +* { box-sizing: border-box; } +body { margin: 0; background: #1d1c1b; color: #f2eee8; font: 14px "Segoe UI", system-ui, sans-serif; } +header, main { max-width: 1280px; margin: auto; padding: 36px; } +header { border-bottom: 1px solid #45423f; } +h1 { margin: 0 0 10px; font-size: 36px; font-weight: 650; letter-spacing: -.03em; } +p { color: #bbb7b1; line-height: 1.55; } +nav { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 18px; } +a { color: inherit; text-decoration: none; padding: 7px 12px; border: 1px solid #5c5853; border-radius: 7px; } +a:hover, a:focus-visible { border-color: #afd6ff; } +section { margin-bottom: 32px; scroll-margin-top: 24px; } +h2 { font-size: 21px; font-weight: 650; } +h2 span { margin-left: 12px; font-size: 12px; color: #bbb7b1; font-weight: 400; } +.grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(110px, 1fr)); gap: 8px; } +figure { margin: 0; padding: 12px 5px 9px; background: #272523; border: 1px solid #45423f; border-radius: 7px; text-align: center; } +img { width: 64px; height: 64px; } +figcaption { font: 11px Consolas, monospace; color: #bbb7b1; margin-top: 4px; overflow-wrap: anywhere; } +@media (max-width: 600px) { header, main { padding: 22px; } } +

Button prompts

${manifest.assets.length} icons · SVG and transparent 64 px and 128 px PNGs

${groups}
`); console.log(`Built ${manifest.assets.length} SVG prompts and preview in ${root}`); diff --git a/scripts/capture-readme.cjs b/scripts/capture-readme.cjs new file mode 100644 index 0000000..c70950a --- /dev/null +++ b/scripts/capture-readme.cjs @@ -0,0 +1,47 @@ +// Recreates the README screenshots in docs/media from the demo shelf: npm run docs:screens +// Tauri port (D09): renderer-only capture via the readme-preload fixture; the deleted +// Electron app (main.js/preload.js) is not loaded. Electron is dev-only tooling. +// Launch animation has no branch launchFx (play() toasts on demo games); the +// launch screenshot is still taken, without the animation when present. +const {app, BrowserWindow} = require('electron'); +const fs = require('node:fs'); +const path = require('node:path'); +const os = require('node:os'); +const root = path.resolve(__dirname, '..'); +// PYROCADE_SCREENS_DIR writes somewhere else (e.g. to keep screenshots taken from a real library). +const out = process.env.PYROCADE_SCREENS_DIR || path.join(root, 'docs', 'media'); +app.setPath('sessionData', path.join(os.tmpdir(), 'PyroCade-readme-' + process.pid)); + +app.whenReady().then(async () => { + const win = new BrowserWindow({show:false, width:1600, height:900, webPreferences:{preload:path.join(__dirname, 'readme-preload.cjs'), + sandbox:false, contextIsolation:true, offscreen:true, backgroundThrottling:false}}); + win.setContentSize(1600, 900); + const js = code => win.webContents.executeJavaScript(`(async()=>{const pause=ms=>new Promise(r=>setTimeout(r,ms));${code}})()`); + async function snap(name) { + win.webContents.invalidate(); await new Promise(r => setTimeout(r, 250)); + const image = (await win.webContents.capturePage()).resize({width:1600}); + fs.writeFileSync(path.join(out, name), image.toJPEG(86)); console.log('saved', name); + } + try { + fs.mkdirSync(out, {recursive:true}); + await win.loadFile(path.join(root, 'renderer', 'index.html')); + await js(`for(let i=0;i<100&&!S.list.length;i++)await pause(50);document.querySelector('#demoBanner')?.classList.add('hidden');`); + const library = async (layout, theme, index, file, wait = 1800) => { + await js(`showView('library');setSystem('all');Appearance.apply({layout:'${layout}',theme:'${theme}'},false);select(${index});await pause(${wait});`); + await snap(file); + }; + await library('carousel', 'ember', 1, 'screen-carousel.jpg'); + // Bookshelf looks best full: repeat the demo games to fill the shelf. + await js(`window.__demo=S.games;S.games=[0,1,2,3].flatMap(k=>window.__demo.map(g=>({...g,id:g.id+'#'+k,media:{...g.media},info:{...g.info}})));setSystem('all');await pause(300);`); + await library('bookshelf', 'glacier', 20, 'screen-bookshelf.jpg'); + await js(`S.games=window.__demo;setSystem('all');await pause(300);`); + await library('page-turn', 'violet', 5, 'screen-page-turn.jpg'); + await js(`Appearance.apply({layout:'carousel',theme:'ember'},false);select(1);await pause(900);await openCase();await pause(2300);CV.ry=26;rig();await pause(300);`); + await snap('screen-case.jpg'); + await js(`closeCase();await pause(700);if(typeof launchFx==='function')launchFx(S.list.find(g=>sysOf(g.system).media==='cart'));await pause(2700);`); + await snap('screen-launch.jpg'); + await js(`document.querySelector('.launch-fx')?.remove();showView('emus');await pause(900);`); + await snap('screen-emulators.jpg'); + app.exit(0); + } catch (e) { console.error(e); app.exit(1); } +}); diff --git a/scripts/check-artwork-ui-preload.cjs b/scripts/check-artwork-ui-preload.cjs index a346e4c..9969d9d 100644 --- a/scripts/check-artwork-ui-preload.cjs +++ b/scripts/check-artwork-ui-preload.cjs @@ -15,17 +15,55 @@ const games=[game('ps1:spyro','Spyro the Dragon','ps1','Spyro the Dragon (USA)') const front=path.resolve(__dirname,'../data/media/ps1/covers/Spyro the Dragon (USA).png'); if(fs.existsSync(front))games[0].media.front=pathToFileURL(front).href; const png=Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aX1cAAAAASUVORK5CYII=','base64'); +const pdf=Buffer.from('%PDF-1.4\n1 0 obj<>endobj\n%%EOF'); let listener=()=>{}; -const service=createArtworkService({dataDir:root,getSystems:()=>systems,getGames:()=>games,normalize:s=>s.replace(/\([^)]*\)|\[[^\]]*\]/g,'').replace(/[^a-z0-9]/gi,'').toLowerCase(),onProgress:p=>listener(p),fetchImpl:async(url,{signal})=>{ +let ss={user:'',devId:'',password:'',devPassword:''}; +const ssConfigured=()=>!!(ss.user&&ss.devId&&ss.password&&ss.devPassword); +const service=createArtworkService({dataDir:root,getSystems:()=>systems,getGames:()=>games,normalize:s=>s.replace(/\([^)]*\)|\[[^\]]*\]/g,'').replace(/[^a-z0-9]/gi,'').toLowerCase(),onProgress:p=>listener(p),screenscraper:{configured:ssConfigured,systems:{ps1:57,gba:12,switch:225},find:async(game,kind)=>kind==='manual'?['https://example.test/manual.pdf']:[]},fetchImpl:async(url,{signal})=>{ await new Promise((resolve,reject)=>{const timer=setTimeout(resolve,140);signal.addEventListener('abort',()=>{clearTimeout(timer);reject(new DOMException('Cancelled','AbortError'))},{once:true})}); - if(url.endsWith('/'))return new Response(games.filter(g=>g.system!=='switch'&&!g.base.includes('Unknown')).map(g=>`image`).join('')); + if(String(url).includes('.pdf'))return new Response(pdf,{headers:{'content-type':'application/pdf'}}); + if(String(url).endsWith('/'))return new Response(games.filter(g=>g.system!=='switch'&&!g.base.includes('Unknown')).map(g=>`image`).join('')); return new Response(png,{headers:{'content-type':'image/png'}}); }}); +const artSources=()=>({launchbox:{built:Date.now()},screenscraper:{user:ss.user,devId:ss.devId,hasPassword:!!ss.password,hasDevPassword:!!ss.devPassword,ready:ssConfigured()}}); contextBridge.exposeInMainWorld('api',{ getConfig:async()=>({systems,emulators:{},customEmulators:[],hideWhilePlaying:true}),scan:async()=>games,emuList:async()=>[],onToast:()=>{},onProgress:()=>{},fetchArt:async()=>null, setConfig:async c=>c,openManual:async()=>{},launch:async()=>{},pickFolder:async()=>null, artStart:async opts=>service.start(opts),artStatus:async()=>service.status(),artCancel:async()=>service.cancel(),artOpenFolder:async()=>'',onArtProgress:fn=>{listener=fn}, - artImport:async({gameId,kind})=>({gameId,media:{[kind]:pathToFileURL(front).href+'?import-test'},replace:true}) + artSources:async()=>artSources(), + artSetScreenScraper:async(details)=>{ + if(details.clear)ss={user:'',devId:'',password:'',devPassword:''}; + else { + if(details.user!==undefined)ss.user=String(details.user||'').trim().slice(0,200); + if(details.devId!==undefined)ss.devId=String(details.devId||'').trim().slice(0,200); + if(details.password)ss.password=String(details.password).trim().slice(0,200); + if(details.devPassword)ss.devPassword=String(details.devPassword).trim().slice(0,200); + } + return artSources(); + }, + artFindManuals:async()=>{ + const folder=path.join(root,'manual-folder');fs.mkdirSync(folder,{recursive:true}); + const target=games.find(g=>!g.media.manual); + if(!target)return {found:0,matched:[]}; + const src=path.join(folder,target.base+'.pdf');fs.writeFileSync(src,pdf); + const dest=path.join(root,'media',target.system,'manuals',target.base+'.pdf');fs.mkdirSync(path.dirname(dest),{recursive:true});fs.writeFileSync(dest,pdf); + target.media.manual=dest; + return {found:1,matched:[{gameId:target.id,media:{manual:dest},replace:true}]}; + }, + manualUrl:async(p)=>{ + const known=typeof p==='string'&&/\.pdf$/i.test(p)&&games.some(g=>g.media.manual===p)&&fs.existsSync(p); + if(!known)throw new Error('Manual not found.'); + return pathToFileURL(p).href; + }, + artImport:async({gameId,kind})=>{ + if(kind==='manual'){ + const target=games.find(g=>g.id===gameId);if(!target)throw new Error('Select a game in your library first.'); + const dest=path.join(root,'media',target.system,'manuals',target.base+'.pdf');fs.mkdirSync(path.dirname(dest),{recursive:true});fs.writeFileSync(dest,pdf); + target.media.manual=dest; + return {gameId,media:{manual:dest},replace:true}; + } + return {gameId,media:{[kind]:pathToFileURL(front).href+'?import-test'},replace:true}; + } }); contextBridge.exposeInMainWorld('artworkTest',{ cleanup:async()=>{ diff --git a/scripts/check-artwork-ui.cjs b/scripts/check-artwork-ui.cjs index 6098740..3ae9efd 100644 --- a/scripts/check-artwork-ui.cjs +++ b/scripts/check-artwork-ui.cjs @@ -1,19 +1,26 @@ +// This fixture targets shared-renderer behavior only; Electron is not the Tauri host. +// Treating a passing result as Tauri validation tests the wrong WebView. const {app,BrowserWindow}=require('electron'); const path=require('node:path'); const fs=require('node:fs'); -const os=require('node:os'); -app.setPath('sessionData',path.join(os.tmpdir(),'PyroCade-artwork-check-'+process.pid)); +const root=path.resolve(__dirname,'..'); +const scratchDir=path.join(root,'localTmp'); +const sessionDataDir=path.join(scratchDir,'PyroCade-artwork-check-'+process.pid); +fs.mkdirSync(sessionDataDir,{recursive:true}); +app.setPath('sessionData',sessionDataDir); +const outputDir=path.join(scratchDir,'artwork-ui-check'); app.whenReady().then(async()=>{ const errors=[]; const win=new BrowserWindow({show:false,width:1600,height:900,webPreferences:{preload:path.join(__dirname,'check-artwork-ui-preload.cjs'),sandbox:false,contextIsolation:true,backgroundThrottling:false,offscreen:true}}); const watchdog=setTimeout(()=>{console.error('Artwork UI check timed out');app.exit(1)},30000); win.webContents.on('console-message',e=>{if(e.level==='error')errors.push(e.message)}); const run=code=>win.webContents.executeJavaScript(`(async()=>{const assert=(v,m)=>{if(!v)throw new Error(m)}; const pause=ms=>new Promise(r=>setTimeout(r,ms)); const until=async(fn)=>{for(let i=0;i<300;i++){if(fn())return;await pause(10)}throw new Error('Artwork UI timed out')}; ${code}})()`); - async function snap(name){win.webContents.invalidate();await new Promise(r=>setTimeout(r,300));const shot=await win.webContents.capturePage();if(shot.isEmpty())throw new Error('Empty capture');fs.writeFileSync(path.resolve(__dirname,'../output',name),shot.toPNG())} + async function snap(name){win.webContents.invalidate();await new Promise(r=>setTimeout(r,300));const shot=await win.webContents.capturePage();if(shot.isEmpty())throw new Error('Empty capture');fs.writeFileSync(path.join(outputDir,name),shot.toPNG())} try { await win.loadFile(path.resolve(__dirname,'../renderer/index.html')); await run(` await until(()=>S.games.length===4); + assert(typeof play==='function'&&play.toString().includes('launching'),'play() is missing its re-entrancy guard'); document.querySelector('#btnArtwork').click(); assert(document.querySelector('#view-artwork').classList.contains('active'),'Artwork action did not open the downloader'); assert(document.querySelector('#artScope').value==='game','Game action did not select one game'); @@ -42,7 +49,7 @@ app.whenReady().then(async()=>{ assert(document.querySelector('#artStart').disabled,'No-type download should be disabled'); document.querySelector('#artTypes input[value=front]').checked=true;document.querySelector('#artTypes').dispatchEvent(new Event('change')); `); - fs.mkdirSync(path.resolve(__dirname,'../output'),{recursive:true}); + fs.mkdirSync(outputDir,{recursive:true}); await snap('artwork-downloader-verified.png'); win.setContentSize(1100,650); await run(`await pause(100);const view=document.querySelector('#view-artwork');assert(view.scrollWidth<=view.clientWidth,'Artwork view overflows horizontally');const button=document.querySelector('#artStart');button.scrollIntoView();assert(button.getBoundingClientRect().bottom<=innerHeight,'Download action cannot be reached at minimum size');`); @@ -51,9 +58,15 @@ app.whenReady().then(async()=>{ S.config.systems.find(s=>s.id==='switch').artworkProvider='gametdb-switch'; select(3);ArtworkUI.open('game'); assert(document.querySelector('#artSourceLabel').textContent.includes('GameTDB'),'Switch source was not shown'); + assert(document.querySelector('#artSourceLabel').textContent.includes('LaunchBox'),'LaunchBox was not shown as a source'); + assert(document.querySelector('#artSourceLabel').textContent.includes('ScreenScraper'),'ScreenScraper was not shown as a source'); + assert(document.querySelector('#artSourceLabel').textContent.includes('Super Mario Wiki'),'Fallback sources were not shown'); + assert(document.querySelector('#artSourceLabel').textContent.includes('Internet Archive'),'Internet Archive fallback was not shown'); + assert((document.querySelector('#artSourceDetails').textContent||'').includes('never replacing an existing cover'),'Front-cover fallback policy was not shown'); assert(!document.querySelector('#artStart').disabled,'Switch download must be enabled'); assert(document.querySelector('#artTypes input[value=screenshot]').disabled,'Unsupported Switch screenshot option should be disabled'); assert(!document.querySelector('#artTypes input[value=disc]').disabled,'Switch cartridge labels should be enabled'); + assert(document.querySelector('#artTypes input[value=manual]').disabled,'Manual download must be disabled before ScreenScraper login'); const before=S.games[3].media.front; await document.querySelector('#artImport').onclick(); assert(S.games[3].media.front!==before&&S.games[3].media.front.includes('import-test'),'Image import did not replace the selected artwork'); @@ -61,8 +74,57 @@ app.whenReady().then(async()=>{ document.querySelector('#artTypes input[value=front]').checked=false;document.querySelector('#artTypes').dispatchEvent(new Event('change')); assert(document.querySelector('#artStart').disabled,'Switch with no chosen type should be disabled'); `); + await run(` + // ScreenScraper login enables manual downloads; passwords never reach getConfig. + assert(!document.querySelector('#ssUser').disabled,'ScreenScraper login fields must be editable'); + document.querySelector('#ssUser').value='tester'; + document.querySelector('#ssPassword').value='pass'; + document.querySelector('#ssDevId').value='dev'; + document.querySelector('#ssDevPassword').value='devpass'; + await document.querySelector('#ssSave').onclick(); + assert(document.querySelector('#ssStatus').textContent.includes('saved'),'ScreenScraper login was not saved'); + assert(document.querySelector('#artScreenScraperState').textContent.includes('Signed in'),'ScreenScraper ready state was not shown'); + assert(!document.querySelector('#artTypes input[value=manual]').disabled,'Manual download must be enabled after ScreenScraper login'); + const cfg=await api.getConfig(); + assert(!cfg.screenscraper,'ScreenScraper passwords must never cross getConfig to the renderer'); + // Manual download: filesystem-path payload, never a file URL (#1). + select(1);ArtworkUI.open('game'); + document.querySelector('#artTypes').querySelectorAll('input').forEach(i=>i.checked=false); + document.querySelector('#artTypes input[value=manual]').checked=true;document.querySelector('#artTypes').dispatchEvent(new Event('change')); + assert(!document.querySelector('#artStart').disabled,'Manual download must be enabled for a ScreenScraper system'); + await document.querySelector('#artStart').onclick(); + await until(()=>document.querySelector('#artJobState').textContent==='Complete'); + assert(S.games[1].media.manual&&S.games[1].media.manual.endsWith('.pdf'),'Manual PDF was not applied to the library'); + assert(!S.games[1].media.manual.startsWith('file:'),'Manual payload must stay a filesystem path, not a file URL'); + const manualUrl=await api.manualUrl(S.games[1].media.manual); + assert(manualUrl.startsWith('file:'),'Manual viewer URL must be a file URL for the iframe'); + // Manual import: choose a PDF for a game without one. + select(2);ArtworkUI.open('game'); + document.querySelector('#artImportKind').value='manual';document.querySelector('#artImportKind').dispatchEvent(new Event('change')); + assert(document.querySelector('#artImport').textContent.includes('PDF'),'Manual import button must name PDF'); + await document.querySelector('#artImport').onclick(); + assert(S.games[2].media.manual&&S.games[2].media.manual.endsWith('.pdf'),'Manual import did not store the PDF'); + assert(!S.games[2].media.manual.startsWith('file:'),'Imported manual must stay a filesystem path, not a file URL'); + assert(document.querySelector('#artImportStatus').textContent.includes('Manual added'),'Manual import feedback missing'); + // Find manuals in a folder matches the remaining game without a manual. + await document.querySelector('#artFindManuals').onclick(); + assert(document.querySelector('#artImportStatus').textContent.includes('matched'),'Find manuals matched count missing'); + assert(S.games[0].media.manual&&!S.games[0].media.manual.startsWith('file:'),'Found manual must be a filesystem path'); + // Manual viewer opens with the file URL and the external opener receives the filesystem path. + select(1);ArtworkUI.open('game'); + let opened=null;const originalOpen=api.openManual;api.openManual=async p=>{opened=p}; + await manual(S.games[1]); + assert(document.querySelector('#manualViewer').open,'Manual viewer did not open'); + assert(document.querySelector('#manualFrame').src.includes('.pdf'),'Manual viewer iframe did not load the PDF'); + document.querySelector('#manualExternal').click(); + await pause(50); + assert(opened===S.games[1].media.manual,'External opener must receive the filesystem path'); + assert(!String(opened).startsWith('file:'),'External opener path must not be a file URL'); + api.openManual=originalOpen; + closeManual(); + `); await run(`await artworkTest.cleanup();`); if(errors.length)throw new Error(errors.join('\n')); - clearTimeout(watchdog);console.log('Passed: one-game download, new artwork applied, custom-art preservation, whole-library scope, progress, cancellation, resume, unavailable matches, unsupported systems, no-type guard, and minimum-window layout.');app.exit(0); + clearTimeout(watchdog);console.log('Passed: one-game download, new artwork applied, custom-art preservation, whole-library scope, progress, cancellation, resume, unavailable matches, unsupported systems, no-type guard, ScreenScraper login, manual download/import/find/viewer with filesystem-path payloads, and minimum-window layout.');app.exit(0); } catch(e){console.error(e);await run('await artworkTest.cleanup();').catch(()=>{});app.exit(1)} }); diff --git a/scripts/check-artwork.cjs b/scripts/check-artwork.cjs index 4583c52..f09a017 100644 --- a/scripts/check-artwork.cjs +++ b/scripts/check-artwork.cjs @@ -73,7 +73,119 @@ async function until(test){for(let i=0;i<300;i++){if(test())return;await pause(1 assert(switchCalls.some(u=>u.includes('/label/EN/AABPA.png')),'Switch label must be available for the cartridge'); assert(!switchCalls.some(u=>u.includes('Named_Snaps')),'Switch must not query Libretro'); assert.equal(switchCalls.filter(u=>u.includes('switchtdb.txt')).length,1,'Switch types must share the metadata request'); - console.log('Passed: missing screenshots with cached covers, custom-art preservation, exact-region matching, independent title art, refreshed matches, invalid-image handling, path validation, shared requests, cancellation, resume, unsupported systems and progress updates.'); + // D07: Rust fallback contract (static check of the Tauri host; the unit tests in artwork.rs + // cover the matching logic without network). The legacy JS above has no fallback. + { + const rust=await fs.readFile(path.join(__dirname,'../src-tauri/src/artwork.rs'),'utf8'); + for(const needle of [ + 'mariowiki_covers','archive_covers','fetch_mariowiki_image','fetch_internet_archive_image', + 'slow down','410','429','503','WEB_CACHE_AGE_SECS','30 * 86400','Duration::from_secs(20)', + 'trusted_release','without_version','region_of','fits_front','infobox_images','is_front_cover', + 'item_name','systems_of','front_files','softwareboxart','?action=raw','Category','Nintendo DS game covers', + ]) assert(rust.includes(needle),`Rust fallback missing ${needle}`); + // Front covers only, after the existing providers: fallback gated on kind == "front". + assert(rust.includes('kind == "front"'),'Fallback must be gated on front covers only'); + // Polite 1/s: two per-site gates. + assert((rust.match(/PoliteSite::/g)||[]).length>=2,'Polite per-site gates missing'); + const ui=await fs.readFile(path.join(__dirname,'../renderer/artwork-ui.js'),'utf8'); + assert(ui.includes('Super Mario Wiki'),'Artwork UI must name Super Mario Wiki'); + assert(ui.includes('Internet Archive'),'Artwork UI must name Internet Archive'); + assert(ui.includes('never replacing an existing cover'),'Artwork UI must state front-cover fallback policy'); + } + // M04a: LaunchBox/ScreenScraper providers through the Rust artwork service (same static style as D07). + { + const rust=await fs.readFile(path.join(__dirname,'../src-tauri/src/artwork.rs'),'utf8'); + for(const needle of [ + 'launchbox_platform','launchbox_covers','fetch_launchbox_image','parse_launchbox_metadata', + 'launchbox_index_file','build_launchbox_index','load_launchbox_index','download_launchbox_zip', + 'LAUNCHBOX_METADATA','LAUNCHBOX_IMAGES','LAUNCHBOX_INDEX_VERSION','LAUNCHBOX_KEEP', + 'Metadata.xml','launchbox-index.json','Box - Front','launchbox_front_rank','launchbox_file_ok', + 'screenscraper_system','screenscraper_covers','screenscraper_configured','screenscraper_credentials', + 'fetch_screenscraper_image','screenscraper_medias','screenscraper_json','screenscraper_lookup_url', + 'SCREENSCRAPER_API','jeuInfos.php','romtaille','crc32_update','box-2D','screenscraper_media_url', + 'PoliteSite::ScreenScraper','PoliteSite::LaunchBox','allow_index_download', + ]) assert(rust.includes(needle),`Rust provider missing ${needle}`); + // Front covers only, after Libretro/GameTDB: same gate as the D07 providers. + assert(rust.includes('launchbox_covers(&system_id)'),'LaunchBox must join the front-cover fallback gate'); + assert(rust.includes('screenscraper_covers(&system_id, config)'),'ScreenScraper must join the front-cover fallback gate'); + // ScreenScraper never runs without all four credentials (user, devId, password, devPassword). + assert(rust.includes('credentials.dev_password.is_empty()'),'ScreenScraper must require credentials'); + const backend=await fs.readFile(path.join(__dirname,'../src-tauri/src/backend.rs'),'utf8'); + // ScreenScraper passwords must never cross the bridge to the renderer. + assert(backend.includes('object.remove("screenscraper")'),'Backend must strip ScreenScraper credentials from get_config'); + assert(backend.includes('cfg["screenscraper"] = section.clone()'),'Backend must preserve ScreenScraper credentials on set_config'); + } + // M04b: manual workflows against the M04a provider contract (static check of the Tauri host; + // the unit tests in artwork.rs cover the PDF validation without network). + { + const rust=await fs.readFile(path.join(__dirname,'../src-tauri/src/artwork.rs'),'utf8'); + for(const needle of [ + 'MANUAL_MAX_BYTES','valid_pdf','fetch_screenscraper_manual','screenscraper_manual_urls','request_pdf', + 'manuel','artwork_sources','set_screenscraper','find_manuals','manual_url', + 'hasPassword','hasDevPassword','manual_loose_key','manual_bare_key', + ]) assert(rust.includes(needle),`Rust manual workflow missing ${needle}`); + // Manual payloads stay filesystem paths: the manual branch must not build a file URL. + assert(rust.includes('manuals')&&rust.includes('{base}.pdf'),'Manual files must live in manuals/.pdf'); + const lib=await fs.readFile(path.join(__dirname,'../src-tauri/src/lib.rs'),'utf8'); + for(const needle of ['artwork::artwork_sources','artwork::set_screenscraper','artwork::find_manuals','artwork::manual_url']) + assert(lib.includes(needle),`Tauri command not registered: ${needle}`); + const bridge=await fs.readFile(path.join(__dirname,'../renderer/tauri-bridge.js'),'utf8'); + for(const needle of ['artSources','artSetScreenScraper','artFindManuals','manualUrl']) + assert(bridge.includes(needle),`Tauri bridge missing ${needle}`); + const ui=await fs.readFile(path.join(__dirname,'../renderer/artwork-ui.js'),'utf8'); + for(const needle of ['LaunchBox','ScreenScraper','artFindManuals','artSetScreenScraper','Choose PDF']) + assert(ui.includes(needle),`Artwork UI must expose ${needle}`); + const app=await fs.readFile(path.join(__dirname,'../renderer/app.js'),'utf8'); + assert(app.includes("api.manualUrl"),'Manual viewer must resolve a file URL via manualUrl'); + assert(app.includes("api.openManual"),'Manual viewer must keep the native opener for the filesystem path'); + const html=await fs.readFile(path.join(__dirname,'../renderer/index.html'),'utf8'); + for(const needle of ['value="manual"','Manual (PDF)','artFindManuals','manualViewer','ssUser','ssPassword']) + assert(html.includes(needle),`Artwork view missing ${needle}`); + // Legacy JS service: manual handling preserves the filesystem-path payload (#1). + const manualGame={id:'snes:Game',title:'Game',base:'Game',system:'snes',media:{}}; + const manualService=createArtworkService({dataDir:path.join(dir,'manual-legacy'),getSystems:()=>[{id:'snes',name:'SNES',libretro:'Nintendo - Super Nintendo'}],getGames:()=>[manualGame],normalize,screenscraper:{configured:()=>true,systems:{snes:4},find:async()=>['https://example.test/manual.pdf']},fetchImpl:async()=>new Response(Buffer.from('%PDF-1.4\n%%EOF'),{headers:{'content-type':'application/pdf'}})}); + const downloaded=await manualService.downloadGame(manualGame,['manual']); + assert.equal(downloaded.downloaded,1,'Legacy manual download must succeed'); + assert(downloaded.media.manual.endsWith('.pdf')&&!downloaded.media.manual.startsWith('file:'),'Legacy manual must stay a filesystem path'); + const badGame={id:'snes:Bad',title:'Bad',base:'Bad',system:'snes',media:{}}; + const badService=createArtworkService({dataDir:path.join(dir,'manual-bad'),getSystems:()=>[{id:'snes',name:'SNES',libretro:'Nintendo - Super Nintendo'}],getGames:()=>[badGame],normalize,screenscraper:{configured:()=>true,systems:{snes:4},find:async()=>['https://example.test/manual.pdf']},fetchImpl:async()=>new Response('not a pdf')}); + const rejected=await badService.downloadGame(badGame,['manual']); + assert.equal(rejected.missing,1,'Non-PDF manual bytes must be skipped as missing'); + } + // M05a: platform-aware launch behavior (static check of the Tauri host; unit tests in + // backend.rs cover the LD filter and Steam/gamescope detection without launching). + { + const rust=await fs.readFile(path.join(__dirname,'../src-tauri/src/backend.rs'),'utf8'); + for(const needle of [ + 'pyrocade.log','log_start','log_launch','steam_start_detected','is_gamescope', + 'steam_filtered_ld_library_path','steam-runtime','steamrt','ubuntu12_32','ubuntu12_64','pressure-vessel', + 'apply_steam_fix_to_command','cleared LD_PRELOAD','removed Steam libraries from LD_LIBRARY_PATH', + 'DISPLAY unset under gamescope','steamFix', + ]) assert(rust.includes(needle),`Rust launch logging missing ${needle}`); + // Launch children inherit the parent environment; the only per-child change is the + // Linux-only Steam LD sanitization, so nothing may clear the whole environment. + assert(!rust.includes('env_clear'),'Launch children must inherit the parent environment'); + const app=await fs.readFile(path.join(__dirname,'../renderer/app.js'),'utf8'); + assert(app.includes('let launching = false')&&app.includes('if (launching) return')&&app.includes('finally { launching = false; }'),'play() must guard re-entrant launches'); + } + // M05b: emulator metadata and PC config (static check; unit tests in config.rs/emulators.rs + // cover the .nup migration, direct-folder scan depth and the RPCS3 asset regex). + { + const catalog=JSON.parse(await fs.readFile(path.join(__dirname,'../emulators.json'),'utf8')); + const rpcs3=catalog.find(e=>e.id==='rpcs3'); + const asset=(rpcs3.platforms?.windows?.x86_64||{}).asset||''; + assert(asset.includes('_win64(_msvc)?'),'RPCS3 Windows asset must match the _msvc variant'); + const config=await fs.readFile(path.join(__dirname,'../src-tauri/src/config.rs'),'utf8'); + for(const needle of [ + '{"id":"pc"','"direct":true','ext-switch2-nup','merge_migrates_switch2_nup_once','"migrations"', + ]) assert(config.includes(needle),`Rust config missing ${needle}`); + // Direct systems scan only the top folder, because game folders hold helper binaries. + const backend=await fs.readFile(path.join(__dirname,'../src-tauri/src/backend.rs'),'utf8'); + assert(backend.includes('start_depth')&&backend.includes('direct_depth_skips_nested_helper_binaries'),'Direct-folder scan depth missing'); + const emulators=await fs.readFile(path.join(__dirname,'../src-tauri/src/emulators.rs'),'utf8'); + assert(emulators.includes('rpcs3_windows_asset_matches_the_msvc_variant'),'RPCS3 asset test missing'); + } + console.log('Passed: missing screenshots with cached covers, custom-art preservation, exact-region matching, independent title art, refreshed matches, invalid-image handling, path validation, shared requests, cancellation, resume, unsupported systems, M05 launch-logging/Steam LD parity and M05 emulator-metadata parity.'); } finally { // Only remove the unique test directory inside the OS temp directory. assert.equal(path.dirname(path.resolve(dir)),path.resolve(os.tmpdir())); diff --git a/scripts/check-carousel.cjs b/scripts/check-carousel.cjs index 4d834d7..214adb0 100644 --- a/scripts/check-carousel.cjs +++ b/scripts/check-carousel.cjs @@ -1,16 +1,20 @@ -// Exercise the real renderer in an isolated Electron window, with no user-data writes. +// This fixture targets shared-renderer behavior only; Electron is not the Tauri host. +// Treating a passing result as Tauri validation tests the wrong WebView. const {app,BrowserWindow} = require('electron'); const fs = require('node:fs'); const path = require('node:path'); -const os = require('node:os'); -app.setPath('sessionData',path.join(os.tmpdir(),'PyroCade-carousel-check-'+process.pid)); -const output=path.resolve(__dirname,'../output'); +const root=path.resolve(__dirname,'..'); +const scratchDir=path.join(root,'localTmp'); +const sessionDataDir=path.join(scratchDir,'PyroCade-carousel-check-'+process.pid); +fs.mkdirSync(sessionDataDir,{recursive:true}); +app.setPath('sessionData',sessionDataDir); +const output=path.join(scratchDir,'carousel-check'); app.whenReady().then(async()=>{ const errors=[]; const win=new BrowserWindow({show:false,width:1600,height:900,webPreferences:{preload:path.join(__dirname,'check-prompts-preload.cjs'),contextIsolation:true,sandbox:false,backgroundThrottling:false,offscreen:true}}); const watchdog=setTimeout(()=>{console.error('Carousel check timed out');app.exit(1)},45000); win.webContents.on('console-message',event=>{if(event.level==='error')errors.push(event.message)}); - const run=code=>win.webContents.executeJavaScript(`(async()=>{const assert=(v,m)=>{if(!v)throw new Error(m)}; const pause=ms=>new Promise(r=>setTimeout(r,ms)); const finish=()=>document.getAnimations().forEach(a=>{if(Number.isFinite(a.effect.getComputedTiming().endTime))a.finish()}); ${code}})()`); + const run=code=>win.webContents.executeJavaScript(`(async()=>{const assert=(v,m)=>{if(!v)throw new Error(m)}; const pause=ms=>new Promise(r=>setTimeout(r,ms)); const until=async(fn,msg)=>{const start=Date.now();for(;;){let value;try{value=await fn();}catch{}if(value)return value;if(Date.now()-start>8000)throw new Error(msg||'Timed out waiting for condition');await pause(30);}}; const finish=()=>document.getAnimations().forEach(a=>{if(Number.isFinite(a.effect.getComputedTiming().endTime))a.finish()}); ${code}})()`); async function snap(name){ await run('await Promise.all([...document.images].map(i=>i.decode().catch(()=>{})));'); win.webContents.invalidate(); @@ -25,6 +29,20 @@ app.whenReady().then(async()=>{ await run(` await pause(100); assert(S.games.length===12,'Fixture library failed'); + assert(typeof play==='function'&&play.toString().includes('launching'),'play() is missing its re-entrancy guard'); + assert(document.querySelector('#xmb'),'Ambient canvas is missing'); + assert(Ambient.backgrounds().includes('loom'),'Ambient scenes are unavailable'); + Appearance.apply({infoBar:'compact'},false); + assert(document.documentElement.dataset.infoBar==='compact','Info bar setting did not apply'); + Appearance.apply({infoBar:'small'},false); + assert(Appearance.layouts.bookshelf&&Appearance.layouts['page-turn']&&Appearance.layouts.media,'Bookshelf, Page turn and Media carousel layouts are unavailable'); + assert(!Appearance.layouts.spinner&&!Appearance.layouts.swatches,'Retired layouts remain in the picker'); + Appearance.apply({layout:'bookshelf'},false);layout(); + assert(document.querySelector('#layoutOptions [data-layout="bookshelf"]'),'Bookshelf option is missing'); + assert([...document.querySelectorAll('.item')].some(item=>item.style.transform.includes('rotateY(90deg)')),'Bookshelf cases are not displayed spine-out'); + Appearance.apply({layout:'page-turn'},false);layout(); + assert([...document.querySelectorAll('.item')].some(item=>item.style.transform.includes('rotateY(')),'Page turn cases are not arranged around a spine'); + Appearance.apply({layout:'carousel'},false);layout(); applyMotion('full'); select(0); await pause(1700);finish(); const selected=document.querySelector('.item.sel'); assert(selected.classList.contains('media-revealed'),'Disc did not reveal after selection'); @@ -51,6 +69,47 @@ app.whenReady().then(async()=>{ await run(`await openCase();await pause(1900);finish();`); await snap('carousel-case-viewer.png'); await run(`closeCase();`); + await run(` + for(const [retired,replacement] of [['spinner','page-turn'],['swatches','media'],['top-flip','media']]){ + assert(!document.querySelector('#layoutOptions [data-layout="'+retired+'"]'),'Retired layout remains in the picker'); + Appearance.apply({layout:retired},false); + assert(Appearance.mode()===replacement,'Saved layout did not migrate to '+replacement); + } + Appearance.apply({layout:'media'},false);layout(); + const mediaSel=document.querySelector('.item.sel'); + assert(getComputedStyle(mediaSel.querySelector('.box')).display==='none','Media carousel still shows the case'); + const media=mediaSel.querySelector('.physical-media'); + assert(media&&getComputedStyle(media).visibility==='visible','Media carousel does not show the disc or cartridge'); + for(const item of document.querySelectorAll('.item:not(.far)'))assert(getComputedStyle(item.querySelector('.physical-media')).visibility==='visible','A neighbouring disc or cartridge is hidden'); + const oldMediaSel=S.sel; + input('right');assert(S.sel===oldMediaSel+1,'Media carousel did not move right');input('left');assert(S.sel===oldMediaSel,'Media carousel did not move left'); + Appearance.apply({layout:'page-turn'},false);layout(); + const oldPageSel=S.sel,outgoing=items.get(oldPageSel); + input('right'); + assert(S.sel===oldPageSel+1,'Page turn did not advance to the next case'); + let pose; + for(let i=0;i<60;i++){ + pose=new DOMMatrix(getComputedStyle(outgoing).transform); + if(pose.m11<0)break; + await pause(16); + } + assert(pose.m11<0,'Page turn did not swing the outgoing case across the spine: '+outgoing.style.transform); + input('left');await pause(40); + Appearance.apply({layout:'carousel'},false);layout(); + `); + await run(` + Appearance.apply({layout:'bookshelf'},false); + await until(()=>document.querySelector('.item.sel.media-revealed .disc-rotor'),'Bookshelf disc did not reveal'); + const disc=document.querySelector('.item.sel .disc-model'); + const discStyle=getComputedStyle(disc); + const box=disc.closest('.item').querySelector('.box'); + const peek=new DOMMatrix(discStyle.transform).m41-(box.offsetWidth-disc.offsetWidth)/2; + assert(discStyle.visibility==='visible'&&peek>=47,'Bookshelf disc does not extend far enough past the case'); + assert(getComputedStyle(disc.firstChild).animationDuration==='120s','Bookshelf disc should take two minutes per turn'); + applyMotion('reduced'); + assert(getComputedStyle(document.querySelector('.item.sel .disc-rotor')).animationName==='none','Bookshelf disc spins in reduced motion'); + Appearance.apply({layout:'carousel'},false);layout();applyMotion('full'); + `); await run(` // Browse quickly: pending media from earlier selections must never pop out later. select(1); select(2); select(3); await pause(550); @@ -92,7 +151,7 @@ app.whenReady().then(async()=>{ await run('await pause(3300);'); await snap('carousel-minimum-window.png'); if(errors.length)throw new Error(errors.join('\n')); - console.log('Passed: disc/cartridge reveal, six box faces, depth, fast navigation, case lifecycle, dialog focus, reduced motion, empty search, minimum layout, persisted motion preference.'); + console.log('Passed: disc/cartridge reveal, Page turn and Media carousel, retired-layout migration, Bookshelf disc peek, six box faces, depth, fast navigation, case lifecycle, dialog focus, reduced motion, empty search, minimum layout, persisted motion preference.'); clearTimeout(watchdog);app.exit(0); }catch(e){console.error(e);app.exit(1)} }); diff --git a/scripts/check-feedback-ui.cjs b/scripts/check-feedback-ui.cjs new file mode 100644 index 0000000..56e09a4 --- /dev/null +++ b/scripts/check-feedback-ui.cjs @@ -0,0 +1,82 @@ +// Exercise the actual form without opening a browser, changing the user's +// clipboard, reading their library or submitting anything to GitHub. +const {app,BrowserWindow,ipcMain}=require('electron'); +const path=require('node:path'),fs=require('node:fs'),os=require('node:os'); +const root=path.resolve(__dirname,'..'); +app.setPath('sessionData',path.join(os.tmpdir(),'PyroCade-feedback-check-'+process.pid)); +const opened=[],copied=[]; +let failBrowser=false,failInfo=false; +const diagnostics='PyroCade: test\nOS: Test OS (x64)\nTauri: test\nInstallation: From source'; +ipcMain.handle('feedback:info',async()=>{if(failInfo)throw new Error('Device unavailable');return diagnostics;}); +ipcMain.handle('feedback:copy',async(_event,text)=>{if(typeof text!=='string'||!text)throw new Error('Nothing to copy yet.');copied.push(text);return null;}); +ipcMain.handle('feedback:open',async(_event,url)=>{if(failBrowser)throw new Error('Browser unavailable. You can copy the report instead.');if(typeof url!=='string'||!url.startsWith('https://github.com/Pyrodrifter/PyroCade/issues/'))throw new Error('Not a GitHub issue link');opened.push(url);return null;}); +app.whenReady().then(async()=>{ + const win=new BrowserWindow({show:false,width:1100,height:650,webPreferences:{preload:path.join(__dirname,'check-prompts-preload.cjs'),sandbox:false,contextIsolation:true,offscreen:true,backgroundThrottling:false}}); + const errors=[]; + win.webContents.on('console-message',event=>{if(event.level==='error')errors.push(event.message)}); + const watchdog=setTimeout(()=>{console.error('Feedback UI check timed out');app.exit(1)},45000); + const run=code=>win.webContents.executeJavaScript(`(async()=>{const assert=(v,m)=>{if(!v)throw new Error(m)};const pause=ms=>new Promise(r=>setTimeout(r,ms));${code}})()`); + try { + await win.loadFile(path.join(root,'renderer/index.html')); + await run(` + await pause(150);showView('settings');document.querySelector('#btnFeedback').click();await pause(50); + assert(FeedbackUI.isOpen(),'Feedback dialog did not open');assert(document.activeElement.id==='feedbackSummary','Summary did not receive focus'); + assert(document.querySelector('#feedbackDevice').textContent.includes('OS: Test OS'),'Device details missing'); + document.querySelector('#feedbackOpen').click();await pause(30); + assert(!document.querySelector('#feedbackSummary').validity.valid,'Empty summary accepted'); + document.querySelector('#feedbackSummary').value='Case does not open'; + document.querySelector('#feedbackDescription').value='Expected the case to open, but it stayed closed.'; + document.querySelector('#feedbackSteps').value='1. Choose a game\\n2. Open case'; + document.querySelector('#feedbackCopy').click();await pause(50); + assert(document.querySelector('#feedbackStatus').textContent.includes('Report copied'),'Copy status missing'); + document.querySelector('#feedbackOpen').click();await pause(50); + assert(document.querySelector('#feedbackStatus').textContent.includes('GitHub opened'),'Browser status missing'); + `); + if(opened.length!==1||copied.length!==1)throw new Error('Invalid form triggered a report action, or valid action failed'); + const report=new URL(opened[0]); + if(copied[0]!==report.searchParams.get('title')+'\n\n'+report.searchParams.get('body'))throw new Error('Copy and browser reports differ'); + await run(` + const kind=document.querySelector('#feedbackKind');kind.value='feedback';kind.dispatchEvent(new Event('change')); + assert(document.querySelector('#feedbackStepsGroup').hidden,'Bug steps still visible for feedback'); + document.querySelector('#feedbackDiagnostics').click();assert(document.querySelector('#feedbackDevice').hidden,'Device preview did not hide'); + document.querySelector('#feedbackCopy').click();await pause(30); + const before=S.sel;input('left');assert(S.sel===before,'Controller changed the shelf behind the modal'); + document.body.dispatchEvent(new KeyboardEvent('keydown',{key:'k',ctrlKey:true,bubbles:true}));assert(!LibraryUI.pickerOpen(),'Shortcut opened a dialog behind feedback'); + `); + if(copied[1].includes('Test OS')||copied[1].includes('Steps to reproduce'))throw new Error('Feedback included opted-out device details or hidden steps'); + failBrowser=true; + await run(` + document.querySelector('#feedbackOpen').click();await pause(40); + assert(document.querySelector('#feedbackStatus').textContent.includes('Browser unavailable'),'Browser failure not shown'); + assert(document.querySelector('#feedbackDescription').value.includes('stayed closed'),'Draft lost after failure'); + assert(!document.querySelector('#feedbackCopy').disabled,'Copy unavailable after failure'); + input('back');await pause(30);assert(!FeedbackUI.isOpen(),'Controller could not dismiss modal');assert(document.activeElement.id==='btnFeedback','Focus not restored'); + document.querySelector('#btnFeedback').click();await pause(20); + assert(document.querySelector('#feedbackSummary').value==='Case does not open','Draft lost on close'); + document.querySelector('#feedbackDiagnostics').click();await pause(40); + `); + fs.mkdirSync(path.join(root,'output'),{recursive:true}); + fs.writeFileSync(path.join(root,'output/feedback-minimum-window.png'),(await win.webContents.capturePage()).toPNG()); + await run(` + const modal=document.querySelector('#feedbackDialog');modal.scrollTop=modal.scrollHeight;await pause(30); + const button=document.querySelector('#feedbackOpen').getBoundingClientRect(),bounds=modal.getBoundingClientRect(); + assert(button.bottom<=bounds.bottom&&bounds.bottom<=innerHeight,'Feedback actions are clipped at minimum size'); + document.querySelector('#feedbackClose').click(); + `); + // Reload simulates a fresh app with a failed diagnostics request. + failInfo=true; + await new Promise(resolve=>{win.webContents.once('did-finish-load',resolve);win.reload();}); + await run(` + await pause(100);showView('settings');document.querySelector('#btnFeedback').click();await pause(40); + assert(document.querySelector('#feedbackDevice').textContent.includes('unavailable'),'Diagnostics error missing'); + assert(document.querySelector('#feedbackDiagnostics').disabled&&!document.querySelector('#feedbackDiagnostics').checked,'Unavailable diagnostics still included'); + document.querySelector('#feedbackSummary').value='Feedback without device details';document.querySelector('#feedbackDescription').value='Still works offline.'; + document.querySelector('#feedbackCopy').click();await pause(30); + assert(document.querySelector('#feedbackStatus').textContent.includes('Report copied'),'Diagnostics failure prevented copying'); + `); + // A copy with device details opted out must not query diagnostics again. + if(copied.length!==3)throw new Error('Report without diagnostics could not be copied'); + if(errors.length)throw new Error(errors.join('\n')); + clearTimeout(watchdog);console.log('Feedback UI passed: validation, both report types, copy/open, opt-out, failure recovery, draft retention, controller isolation, focus restoration and minimum window.');app.exit(0); + }catch(error){console.error(error);app.exit(1)} +}); diff --git a/scripts/check-feedback.cjs b/scripts/check-feedback.cjs new file mode 100644 index 0000000..32cc6e3 --- /dev/null +++ b/scripts/check-feedback.cjs @@ -0,0 +1,47 @@ +const assert = require('node:assert/strict'); +const { createReport, createFeedbackService } = require('../renderer/feedback'); + +const diagnostics = 'PyroCade: 0.6.0\nOS: Test OS (x64)\nTauri: test\nInstallation: From source'; +const bug = {kind:'bug',summary:' Cannot open a case ',description:'Expected a case. Saw an error instead.',steps:'1. Choose a game\n2. Open case',includeDiagnostics:true}; + +(async () => { + const opened = [], copied = []; + const service = createFeedbackService({diagnostics:()=>diagnostics,openExternal:async url=>opened.push(url),writeText:text=>copied.push(text)}); + assert.equal(service.info(), diagnostics); + const report = createReport(bug, diagnostics); + assert.equal(report.title, '[Bug] Cannot open a case'); + assert.ok(report.body.includes(bug.steps) && report.body.includes(diagnostics)); + await service.open(bug); + const url = new URL(opened[0]); + assert.equal(url.origin + url.pathname, 'https://github.com/Pyrodrifter/PyroCade/issues/new'); + assert.equal(url.searchParams.get('body'), report.body); + assert.equal(url.searchParams.get('template'), 'bug_report.md'); + service.copy(bug); + assert.equal(copied[0], `${report.title}\n\n${report.body}`); + + const idea = {...bug,kind:'feedback',summary:'日本語 & #? 🎮',description:'An idea with & a link: https://example.com',includeDiagnostics:false}; + await service.open(idea); + const ideaUrl = new URL(opened[1]); + assert.equal(ideaUrl.searchParams.get('title'), '[Feedback] ' + idea.summary); + assert.equal(ideaUrl.searchParams.get('template'), 'feedback.md'); + assert.ok(!ideaUrl.searchParams.get('body').includes('Steps to reproduce')); + assert.ok(!ideaUrl.searchParams.get('body').includes(diagnostics)); + assert.ok(ideaUrl.searchParams.get('body').includes(idea.description)); + for (const bad of [null, {...bug,kind:'other'}, {...bug,summary:' '}, {...bug,description:''}, {...bug,summary:33}, {...bug,description:'x'.repeat(4001)}, {...bug,steps:'x'.repeat(2001)}]) { + assert.throws(()=>service.copy(bad)); + await assert.rejects(()=>service.open(bad)); + } + assert.equal(opened.length, 2, 'Invalid reports opened the browser'); + assert.equal(copied.length, 1, 'Invalid reports overwrote the clipboard'); + + const long = {...bug,description:'日本語'.repeat(1000)}; + await assert.rejects(()=>service.open(long), /Copy report/); + service.copy(long); + assert.ok(copied.at(-1).includes(long.description), 'Long reports were truncated'); + const windows = createFeedbackService({diagnostics:()=>diagnostics,openExternal:async()=>{throw new Error('URL limit bypassed');},writeText:()=>{},maxUrlLength:2081}); + await assert.rejects(()=>windows.open({...bug,description:'x'.repeat(2100)}), /Copy report/); + const broken = createFeedbackService({diagnostics:()=>diagnostics,openExternal:async()=>{throw new Error('Browser unavailable');},writeText:()=>{throw new Error('Clipboard unavailable');}}); + await assert.rejects(()=>broken.open(bug), /Browser unavailable/); + assert.throws(()=>broken.copy(bug), /Clipboard unavailable/); + console.log('Feedback checks passed: validation, bug/feedback bodies, privacy toggle, URL encoding, fixed destination, copy parity, long reports and failures.'); +})().catch(error=>{console.error(error);process.exitCode=1;}); diff --git a/scripts/check-library-ui.cjs b/scripts/check-library-ui.cjs index a24f468..98f6863 100644 --- a/scripts/check-library-ui.cjs +++ b/scripts/check-library-ui.cjs @@ -1,76 +1,179 @@ -const {app,BrowserWindow}=require('electron'); -const fs=require('node:fs'),path=require('node:path'),os=require('node:os'); -const {pathToFileURL}=require('node:url'); -const root=path.resolve(__dirname,'..');app.setPath('sessionData',path.join(os.tmpdir(),'PyroCade-library-check-'+process.pid)); -const coverDir=path.join(root,'data/media/switch/covers'); -const fixtures=fs.readdirSync(coverDir).filter(n=>n.endsWith('.png')).slice(0,16).map((name,i)=>({id:'fixture:'+i,system:'switch',base:name.slice(0,-4),title:name.replace(/\[[^\]]*\]|\([^)]*\)|\.png$/g,'').replace(/\bv?\d+(?:\.\d+)+\b/gi,'').trim(),demo:true,media:{front:pathToFileURL(path.join(coverDir,name)).href},info:{}})); -app.whenReady().then(async()=>{ - const win=new BrowserWindow({show:false,width:1584,height:861,webPreferences:{preload:path.join(__dirname,'check-prompts-preload.cjs'),sandbox:false,contextIsolation:true,offscreen:true,backgroundThrottling:false}});win.setContentSize(1584,861); - const errors=[];win.webContents.on('console-message',e=>{if(e.level==='error')errors.push(e.message)}); - const watchdog=setTimeout(()=>{console.error('Library UI check timed out');app.exit(1)},60000); - const run=code=>win.webContents.executeJavaScript(`(async()=>{const assert=(v,m)=>{if(!v)throw new Error(m)};const pause=ms=>new Promise(r=>setTimeout(r,ms));${code}})()`); - const snap=async name=>{win.webContents.invalidate();await new Promise(r=>setTimeout(r,150));fs.writeFileSync(path.join(root,'output',name),(await win.webContents.capturePage()).toPNG())}; - try{ - await win.loadFile(path.join(root,'renderer/index.html')); - await run(` - await pause(120);applyMotion('reduced'); - S.config.systems=Object.entries(Packaging.profiles).map(([id,p])=>({id,name:p.brand,color:p.accent,romDir:'fixture/'+id,caseType:['switch','switch2'].includes(id)?'switch':'dvd',media:Cartridges.profiles[id]?'cart':'disc'})); - S.games=${JSON.stringify(fixtures)};S.demo=false;document.querySelector('#demoBanner').classList.add('hidden');renderChips();setSystem('switch');select(3); - for(const g of S.games)measure(g);await pause(200); - assert(document.querySelectorAll('#systems button').length===25,'Configured empty systems were lost'); - assert(document.querySelectorAll('#systems [aria-pressed=true]').length===1,'System selection is ambiguous'); - const rail=document.querySelector('#systems');rail.scrollLeft=0;rail.dispatchEvent(new WheelEvent('wheel',{deltaY:240,cancelable:true}));assert(rail.scrollLeft>0,'Mouse wheel does not scroll the system rail'); - const first=rail.querySelector('button');first.focus();first.dispatchEvent(new KeyboardEvent('keydown',{key:'ArrowRight',bubbles:true}));assert(S.system==='ps1'&&document.activeElement.dataset.id==='ps1','Rail keyboard navigation did not move focus and selection'); - document.body.dispatchEvent(new KeyboardEvent('keydown',{key:'k',ctrlKey:true,bubbles:true}));assert(LibraryUI.pickerOpen()&&document.activeElement.id==='systemSearch','Ctrl+K did not open the system browser'); - const search=document.querySelector('#systemSearch');search.value='switch 2';search.dispatchEvent(new Event('input'));assert(document.querySelectorAll('#systemPickerGrid button').length===1,'System filter failed'); - search.dispatchEvent(new KeyboardEvent('keydown',{key:'Enter',bubbles:true}));await pause(30);assert(S.system==='switch2'&&!LibraryUI.pickerOpen(),'System picker did not select an empty configured system');assert(document.activeElement.id==='btnSystemPicker','Picker did not restore focus'); - setSystem('switch');select(3);LibraryUI.openPicker();input('right');assert(document.activeElement.matches('#systemPickerGrid button'),'Controller cannot browse the picker');input('back');await pause(20); - LibraryUI.openPicker();input('manual');assert(Appearance.panelOpen()&&!LibraryUI.pickerOpen(),'Controller cannot open appearance from system browser'); - input('right');assert(document.activeElement.dataset.layout==='vertical','Controller cannot move among layouts');input('play');assert(Appearance.mode()==='vertical','Controller cannot select layout');input('left');input('play'); - assert(document.querySelector('.system-tile').offsetHeight<=38,'System rail is no longer compact'); - `); - await snap('ui-appearance-panel.png'); - await run(`document.querySelector('#appearancePicker').close();await pause(30);`); - const themes=['ember','glacier','violet','mint'];let index=0; - for(const layout of ['carousel','vertical','flipbook','swatches']){ - await run(` - setSystem('switch');select(3);Appearance.apply({layout:'${layout}',theme:'${themes[index++]}' });await Appearance.persist();await pause(100); - assert(document.documentElement.dataset.layout==='${layout}','Layout did not apply'); - assert(S.config.libraryLayout==='${layout}','Layout was not persisted');assert(document.querySelector('.item.sel'),'Selection was lost'); - if('${layout}'==='vertical'){const old=S.sel;input('down');assert(S.sel===old+1,'Vertical input does not move down');input('up')} - if('${layout}'==='swatches'){const old=S.sel,cols=Appearance.geometry(document.querySelector('#stage'),S.sel,S.list.length).columns;input('down');assert(S.sel===old+cols,'Grid input does not move by a row');input('up');assert(document.querySelectorAll('.item:not(.far) .swatch-card').length>1,'Colour cards did not render');} - const p=document.querySelector('.item.sel').getBoundingClientRect(),info=document.querySelector('#info').getBoundingClientRect();assert(p.bottom0.001&&peak<.3&&energy>0,'Sound engine produced silence or excessive output'); - AudioUI.configure({enabled:false,volume:0});assert(!AudioUI.play('scroll'),'Zero volume did not silence cues');await Appearance.persist();assert(!S.config.uiSound.enabled&&S.config.uiSound.volume===0,'Sound preference was not saved'); - return {peak:Number(peak.toFixed(4)),energy:Number(energy.toFixed(4))}; - `); - if(errors.length)throw new Error(errors.join('\n')); - clearTimeout(watchdog);console.log(JSON.stringify({passed:'System icons/counts, horizontal wheel and keyboard navigation, searchable picker, controller navigation, focus restoration, four layouts, five themes, automatic preference saving, search clear, case viewer, minimum window and rendered audio',sound}));app.exit(0); - }catch(e){console.error(e);app.exit(1)} +const fs = require('node:fs'); +const path = require('node:path'); +const { spawn } = require('node:child_process'); + +const root = path.resolve(__dirname, '..'); +// The WebDriver listener uses port 4444, because tauri-driver uses it by default. +// A second driver on that port conflicts instead of opening another session. +const webdriverPort = process.env.TAURI_WEBDRIVER_PORT || '4444'; +// The readiness timeout is 30,000 milliseconds, because a driver that never binds has established nothing. +// The client must stop retrying rather than leave a CI job hanging. +const readinessTimeoutMs = Number(process.env.TAURI_WEBDRIVER_TIMEOUT_MS || '30000'); +// The poll interval is 100 milliseconds, because readiness checks need room to yield. +// A zero-delay retry loop would waste a core while WebKit starts. +const readinessPollIntervalMs = Number(process.env.TAURI_WEBDRIVER_POLL_MS || '100'); +// The canvas sample extent is one pixel, because one painted pixel proves renderer output. +// An unpainted sample would confuse API availability with drawing. +const canvasSampleExtent = 1; +// The canvas origin is zero pixels, because drawing starts at its upper-left corner. +// A non-origin sample would miss the one-pixel test surface. +const canvasOrigin = 0; +// The smoke transform rotates by 90 degrees, because an identity transform proves no 3D path. +// A missing preserve-3d result means the platform renderer flattened the surface. +const smokeTransformCss = 'rotateY(90deg)'; +const appBinary = process.env.TAURI_APP_BINARY || path.join(root, 'src-tauri/target/aarch64-unknown-linux-gnu/release/pyrocade'); +const baseUrl = `http://127.0.0.1:${webdriverPort}`; +const driver = spawn(process.env.TAURI_DRIVER || 'tauri-driver', ['--port', webdriverPort], { + cwd: root, + stdio: ['ignore', 'ignore', 'pipe'], }); + +let driverOutput = ''; +let driverSpawnError; +let sessionId; +driver.stderr.on('data', (chunk) => { driverOutput += chunk.toString(); }); +driver.on('error', (error) => { driverSpawnError = error; }); + +async function request(method, route, body) { + const response = await fetch(`${baseUrl}${route}`, { + method, + headers: body ? { 'content-type': 'application/json' } : undefined, + body: body ? JSON.stringify(body) : undefined, + }); + const text = await response.text(); + const payload = text ? JSON.parse(text) : null; + if (!response.ok) throw new Error(`${method} ${route} failed (${response.status}): ${text}`); + const value = payload && Object.hasOwn(payload, 'value') ? payload.value : payload; + if (value && value.error) throw new Error(`${value.error}: ${value.message || text}`); + return value; +} + +async function waitForDriver() { + const deadline = Date.now() + readinessTimeoutMs; + while (Date.now() < deadline) { + if (driverSpawnError) throw driverSpawnError; + if (driver.exitCode !== null) throw new Error(`tauri-driver exited ${driver.exitCode}: ${driverOutput}`); + try { + const status = await request('GET', '/status'); + if (!status || status.ready !== false) return; + } catch {} + await new Promise((resolve) => setTimeout(resolve, readinessPollIntervalMs)); + } + throw new Error(`tauri-driver did not become ready: ${driverOutput}`); +} + +async function run() { + fs.accessSync(appBinary, fs.constants.X_OK); + await waitForDriver(); + const session = await request('POST', '/session', { + capabilities: { + alwaysMatch: { + 'tauri:options': { application: appBinary }, + }, + }, + }); + sessionId = session.sessionId; + if (!sessionId) throw new Error(`tauri-driver did not return a session id: ${JSON.stringify(session)}`); + + const script = ` + // The callback offset is one argument, because WebDriver appends it after the provided arguments. + // Any other offset invokes a test argument instead of completing the command. + const lastArgumentOffset = 1; + const completionArgumentPosition = arguments.length - lastArgumentOffset; + const complete = arguments[completionArgumentPosition]; + (async () => { + const assert = (condition, message) => { if (!condition) throw new Error(message); }; + const stage = document.querySelector('#stage'); + assert(stage, 'Tauri renderer did not create the library stage'); + + assert(typeof navigator.getGamepads === 'function', 'Gamepad API is unavailable'); + assert(navigator.getGamepads() !== null, 'Gamepad API could not be queried'); + window.dispatchEvent(new Event('gamepadconnected')); + document.dispatchEvent(new KeyboardEvent('keydown', {key:'ArrowRight', bubbles:true, cancelable:true})); + + const tile = document.createElement('div'); + tile.style.transformStyle = 'preserve-3d'; + tile.style.transform = ${JSON.stringify(smokeTransformCss)}; + stage.append(tile); + assert(getComputedStyle(tile).transformStyle === 'preserve-3d', 'WebView did not preserve 3D transforms'); + assert(getComputedStyle(stage).perspective !== 'none', 'Library stage has no perspective'); + const canvas = document.createElement('canvas'); + canvas.width = ${canvasSampleExtent}; + canvas.height = ${canvasSampleExtent}; + const context = canvas.getContext('2d'); + assert(context, 'Canvas 2D context is unavailable'); + context.fillStyle = 'red'; + context.fillRect(${canvasOrigin}, ${canvasOrigin}, ${canvasSampleExtent}, ${canvasSampleExtent}); + assert(context.getImageData(${canvasOrigin}, ${canvasOrigin}, ${canvasSampleExtent}, ${canvasSampleExtent}).data[${canvasOrigin}] > ${canvasOrigin}, 'Canvas did not render a pixel'); + + assert(typeof AudioUI !== 'undefined' && typeof AudioUI.play === 'function', 'Renderer audio service is unavailable'); + assert(Appearance.layouts['page-turn'] && Appearance.layouts.media, 'Page turn and Media carousel layouts are unavailable'); + assert(!Appearance.layouts.spinner && !Appearance.layouts.swatches, 'Retired layouts remain in the picker'); + Appearance.apply({layout:'spinner'}, false); + assert(Appearance.mode() === 'page-turn', 'Saved spinner layout did not migrate to page-turn'); + Appearance.apply({layout:'swatches'}, false); + assert(Appearance.mode() === 'media', 'Saved swatches layout did not migrate to media'); + Appearance.apply({layout:'carousel'}, false); + let audioContextCreated = false; + const NativeAudioContext = window.AudioContext; + window.AudioContext = class extends NativeAudioContext { + constructor() { super(); audioContextCreated = true; } + }; + AudioUI.configure({enabled:true}); + AudioUI.play('scroll'); + assert(audioContextCreated, 'Renderer audio service did not create an AudioContext'); + assert(AudioUI.settings().enabled, 'Renderer audio service did not enable sound'); + + assert(typeof api.cachedLibrary === 'function', 'Tauri bridge does not expose cachedLibrary'); + assert(typeof api.scan === 'function', 'Tauri bridge does not expose scan'); + assert(typeof startLibrary === 'function', 'Renderer does not expose startLibrary'); + assert(typeof applyLibrary === 'function', 'Renderer does not expose applyLibrary'); + // M03 collection administration behind the bridge. + for (const method of ['setHidden','setSystemGamesHidden','setMetadata','setGameEmulator','saveGameOrder','addGame','removeGame','gameList']) { + assert(typeof api[method] === 'function', 'Tauri bridge does not expose ' + method); + } + for (const id of ['renameGame','gameDetailsEditor','emuChoice','gameMenu','hiddenGames','addSystemForm','addGameForm','btnFavorite','btnHide','btnEmulator','btnEditDetails']) { + assert(document.getElementById(id), 'Renderer is missing #' + id + ' (M03 collection UI)'); + } + assert(typeof toggleGameFavorite === 'function', 'Renderer does not expose toggleGameFavorite'); + assert(typeof toggleHidden === 'function', 'Renderer does not expose toggleHidden'); + assert(typeof editGameDetails === 'function', 'Renderer does not expose editGameDetails'); + assert(typeof openEmuChoice === 'function', 'Renderer does not expose openEmuChoice'); + assert(typeof renderHiddenGames === 'function', 'Renderer does not expose renderHiddenGames'); + const cached = await api.cachedLibrary(); + assert(cached === null || Array.isArray(cached), 'cachedLibrary did not return a library or null'); + const unchanged = await api.scan(false, {onlyIfChanged: true}); + assert(unchanged === null || Array.isArray(unchanged), 'scan onlyIfChanged did not return null or a library'); + const extra = await api.gameList(); + assert(Array.isArray(extra), 'gameList did not return the user-added games array'); + // M05b system catalog through the bridge; M05a play() re-entrancy guard. + assert(typeof api.getConfig === 'function', 'Tauri bridge does not expose getConfig'); + const sysConfig = await api.getConfig(); + const pcSystem = (sysConfig.systems || []).find((s) => s.id === 'pc'); + assert(pcSystem && pcSystem.direct === true, 'PC Games direct system missing from config'); + const switch2System = (sysConfig.systems || []).find((s) => s.id === 'switch2'); + assert(switch2System && switch2System.extensions.includes('.nup'), 'Switch 2 .nup extension missing from config'); + assert(typeof play === 'function' && play.toString().includes('launching'), 'play() is missing its re-entrancy guard'); + return {gamepadApi:'available', transform:'preserve-3d', canvas:'painted', audio:'AudioContext created', libraryCache:'cachedLibrary and scan onlyIfChanged exposed', collection:'M03 bridge and dialogs exposed', m05:'pc direct, switch2 .nup, play guard'}; + })().then(complete).catch(error => complete({error:error.message || String(error), stack:error.stack})); + `; + const result = await request('POST', `/session/${sessionId}/execute/async`, { script, args: [] }); + if (result && result.error) throw new Error(result.error); + + const screenshot = await request('GET', `/session/${sessionId}/screenshot`); + const screenshotPath = path.join(root, 'localTmp', `tauri-webdriver-${Date.now()}.png`); + fs.writeFileSync(screenshotPath, Buffer.from(screenshot, 'base64')); + console.log(JSON.stringify({ passed: result, screenshot: screenshotPath })); +} + +run() + .catch((error) => { + console.error(error); + process.exitCode = 1; + }) + .finally(async () => { + if (sessionId) { + try { await request('DELETE', `/session/${sessionId}`); } catch {} + } + driver.kill(); + }); diff --git a/scripts/check-prompts-preload.cjs b/scripts/check-prompts-preload.cjs index 8a9d28f..c49b469 100644 --- a/scripts/check-prompts-preload.cjs +++ b/scripts/check-prompts-preload.cjs @@ -1,10 +1,15 @@ // Isolated fixture: no real ROM folders, downloads, launches, or saved settings. -const {contextBridge} = require('electron'); +const {contextBridge, ipcRenderer} = require('electron'); +const invoke = channel => (...args) => ipcRenderer.invoke(channel, ...args); const config = {systems:[ {id:'ps2',name:'PlayStation 2',caseType:'dvd',media:'disc',color:'#1d3f8f',romDir:'',extensions:['.iso'],emulator:''}, {id:'gba',name:'Game Boy Advance',caseType:'cartbox',media:'cart',color:'#4b3a9b',romDir:'',extensions:['.gba'],emulator:''} ],emulators:{},customEmulators:[],hideWhilePlaying:true,uiSound:{enabled:false,volume:.25}}; contextBridge.exposeInMainWorld('api',{ + feedbackInfo:()=>invoke('feedback:info')(), + feedbackCopy:text=>invoke('feedback:copy')(text), + feedbackOpen:url=>invoke('feedback:open')(url), + appVersion:async()=>'0.0.0-test',appCheckUpdate:async()=>null,appInstallUpdate:async()=>{},appOpenRelease:async()=>{},onAppUpdateProgress:()=>{},artSources:async()=>({launchbox:{built:0},screenscraper:{user:'',devId:'',hasPassword:false,hasDevPassword:false,ready:false}}),artSetScreenScraper:async()=>({launchbox:{built:0},screenscraper:{user:'',devId:'',ready:false}}), getConfig:async()=>config, scan:async()=>[],emuList:async()=>[],onToast:()=>{},onProgress:()=>{},fetchArt:async()=>null, setConfig:async c=>Object.assign(config,c),openManual:async()=>{},launch:async()=>{},pickFolder:async()=>null }); diff --git a/scripts/check-prompts.cjs b/scripts/check-prompts.cjs index 61745db..fc1b624 100644 --- a/scripts/check-prompts.cjs +++ b/scripts/check-prompts.cjs @@ -34,8 +34,8 @@ app.whenReady().then(async()=>{ const ps=controller('DualSense Wireless Controller',1);window.testPads=[xbox,ps];await press(ps,15); assert(document.querySelector('#btnPlay img').alt==='cross','Second active pad / PlayStation detection'); const ns=controller('Nintendo Switch Pro Controller',2);window.testPads=[ns];await press(ns,15); - assert(document.querySelector('#btnPlay img').alt==='B','Nintendo south label'); - assert(document.querySelector('#cvBack img').alt==='A','Nintendo east label'); + assert(document.querySelector('#btnPlay img').alt==='A','Nintendo Play is A (east)'); + assert(document.querySelector('#cvBack img').alt==='B','Nintendo Back is B (south)'); // Override preview, then persist through the ordinary Save flow (mock API). showView('settings'); const selector=document.querySelector('#sPrompts'); selector.value='playstation';selector.dispatchEvent(new Event('change')); @@ -47,7 +47,7 @@ app.whenReady().then(async()=>{ await openCase();await new Promise(r=>setTimeout(r,750)); await press(ns,3);assert(!CV.open,'North did not toggle case closed'); await press(ns,3);assert(CV.open,'North did not toggle case open'); - await press(ns,1);assert(!caseShown(),'East did not go back'); + await press(ns,0);assert(!caseShown(),'South (B) did not go back'); window.testPads=[];await frame(); assert(document.querySelector('#btnPlay img').alt==='Enter','Disconnect did not reset prompts'); window.testPads=[xbox];await press(xbox,15); diff --git a/scripts/configure-android.cjs b/scripts/configure-android.cjs new file mode 100644 index 0000000..e1bdcf3 --- /dev/null +++ b/scripts/configure-android.cjs @@ -0,0 +1,54 @@ +const fs = require('node:fs'); +const path = require('node:path'); + +// androidCompileApiLevel defaults to 36 and androidTargetApiLevel to 35. +// Gradle requires the compile platform installed; targetSdk opts the app into runtime changes. +const androidCompileApiLevel = Number(process.env.ANDROID_COMPILE_API_LEVEL || 36); +const androidTargetApiLevel = Number(process.env.ANDROID_TARGET_API_LEVEL || 35); +const buildFile = path.join(__dirname, '..', 'src-tauri', 'gen', 'android', 'app', 'build.gradle.kts'); +let source = fs.readFileSync(buildFile, 'utf8'); + +for (const [setting, apiLevel] of [['compileSdk', androidCompileApiLevel], ['targetSdk', androidTargetApiLevel]]) { + const property = new RegExp(`^(\\s*${setting}\\s*=\\s*)\\d+(\\s*)$`, 'm'); + if (!property.test(source)) throw new Error(`Could not find generated ${setting} setting in ${buildFile}`); + source = source.replace(property, `$1${apiLevel}$2`); +} + +// Signing (Tauri v2 reads keystore.properties + signingConfigs in build.gradle.kts). +// Local/CI export TAURI_ANDROID_KEYSTORE_PATH + KEYSTORE_PASSWORD + KEY_ALIAS + KEY_PASSWORD; +// the script writes the private properties file and idempotently patches Gradle. +const signingPath = process.env.TAURI_ANDROID_KEYSTORE_PATH || ''; +const signingAlias = process.env.TAURI_ANDROID_KEY_ALIAS || process.env.ANDROID_KEY_ALIAS || ''; +const signingStorePass = process.env.TAURI_ANDROID_KEYSTORE_PASSWORD || process.env.KEYSTORE_PASSWORD || process.env.TAURI_ANDROID_KEY_PASSWORD || process.env.ANDROID_KEY_PASSWORD || ''; +if (signingPath) { + if (!signingAlias) throw new Error('TAURI_ANDROID_KEY_ALIAS is required when TAURI_ANDROID_KEYSTORE_PATH is set'); + if (!signingStorePass) throw new Error('TAURI_ANDROID_KEYSTORE_PASSWORD (or TAURI_ANDROID_KEY_PASSWORD) is required when TAURI_ANDROID_KEYSTORE_PATH is set'); + const androidDir = path.join(__dirname, '..', 'src-tauri', 'gen', 'android'); + fs.writeFileSync(path.join(androidDir, 'keystore.properties'), `keyAlias=${signingAlias}\npassword=${signingStorePass}\nstoreFile=${signingPath}\n`); + if (!source.includes('java.io.FileInputStream')) { + source = source.replace('import java.util.Properties', 'import java.io.FileInputStream\nimport java.util.Properties'); + } + if (!source.includes('signingConfigs')) { + const signingBlock = ` signingConfigs { + create("release") { + val keystorePropertiesFile = rootProject.file("keystore.properties") + val keystoreProperties = Properties() + if (keystorePropertiesFile.exists()) { + keystoreProperties.load(FileInputStream(keystorePropertiesFile)) + } + keyAlias = keystoreProperties["keyAlias"] as String + keyPassword = keystoreProperties["password"] as String + storeFile = file(keystoreProperties["storeFile"] as String) + storePassword = keystoreProperties["password"] as String + } + } +`; + if (!/buildTypes\s*\{/.test(source)) throw new Error('Could not find buildTypes in generated build.gradle.kts'); + source = source.replace(/ buildTypes\s*\{/, `${signingBlock} buildTypes {`); + } + if (!source.includes('signingConfig = signingConfigs.getByName("release")')) { + source = source.replace(/getByName\("release"\)\s*\{/, 'getByName("release") {\n signingConfig = signingConfigs.getByName("release")'); + } +} + +fs.writeFileSync(buildFile, source); diff --git a/scripts/full-demo-timeline.js b/scripts/full-demo-timeline.js new file mode 100644 index 0000000..9a700ec --- /dev/null +++ b/scripts/full-demo-timeline.js @@ -0,0 +1,71 @@ +// Direct app footage and native interface sounds. No captions or end card. +(async()=>{ + const pause=ms=>new Promise(r=>setTimeout(r,ms)); + const connect=AudioNode.prototype.connect; + AudioNode.prototype.connect=function(destination,...rest){ + if(destination===this.context.destination){ + if(!window.demoAudioDestination){ + window.demoAudioDestination=this.context.createMediaStreamDestination(); + window.demoAudioChunks=[]; + window.demoAudioRecorder=new MediaRecorder(window.demoAudioDestination.stream,{mimeType:'audio/webm;codecs=opus',audioBitsPerSecond:128000}); + window.demoAudioRecorder.ondataavailable=e=>{if(e.data.size)window.demoAudioChunks.push(e.data)}; + const clock=this.context.createConstantSource();clock.offset.value=.000001;connect.call(clock,window.demoAudioDestination);clock.start(); + } + return connect.call(this,window.demoAudioDestination,...rest); + } + return connect.call(this,destination,...rest); + }; + AudioUI.configure({enabled:true,volume:.28});AudioUI.play('confirm');await pause(250); + const pick=(system,re)=>{closeCase();setSystem(system);select(Math.max(0,S.list.findIndex(g=>re.test(g.title))));}; + const view=(layout,theme='ember')=>{Appearance.apply({layout,theme},false);AudioUI.play('confirm')}; + const toggle=(id,on)=>{const b=document.querySelector('#'+id);b.checked=on;b.dispatchEvent(new Event('change'));AudioUI.play('confirm')}; + const search=async text=>{const input=document.querySelector('#search');input.focus();input.value='';for(const c of text){input.value+=c;input.dispatchEvent(new Event('input'));await pause(150)}await pause(250);input.blur()}; + window.demo20=async()=>{ + window.demoAudioRecorder.start(1000);const start=performance.now(); + const at=async(t,fn)=>{await pause(Math.max(0,start+t*1000-performance.now()));await fn()}; + await at(1.8,()=>select((S.sel+1)%S.list.length)); + await at(4,()=>select((S.sel+1)%S.list.length)); + await at(6.2,()=>openCase()); + await at(8.8,()=>tween({rx:-9,ry:26,tx:20,z:260},1400)); + await at(11.5,()=>setOpen(false)); + await at(13,()=>document.querySelector('#cvFlip').click()); + await at(15.5,()=>pick('snes',/Super Mario World/i)); + await at(17.3,()=>openCase()); + await at(20,()=>tween({rx:-12,ry:29,tx:0,z:220},1500)); + await at(23,()=>pick('gb',/Super Mario Land/i)); + await at(24.7,()=>openCase()); + await at(27.5,()=>tween({rx:-10,ry:27,tx:0,z:250},1300)); + await at(30,()=>{closeCase();setSystem('all');}); + await at(31,()=>search('Mario')); + await at(34,()=>select(Math.min(2,S.list.length-1))); + await at(36,()=>{const s=document.querySelector('#search');s.value='';s.dispatchEvent(new Event('input'));}); + await at(37,()=>document.querySelector('#btnAppearance').click()); + await at(38.5,()=>view('bookshelf','glacier')); + await at(39.8,()=>document.querySelector('#appearancePicker').close()); + await at(41,()=>select(Math.min(S.sel+2,S.list.length-1))); + await at(43,()=>view('page-turn','glacier')); + await at(45,()=>select(Math.min(S.sel+3,S.list.length-1))); + await at(47,()=>view('vertical','glacier')); + await at(48.5,()=>select(Math.min(S.sel+1,S.list.length-1))); + await at(50,()=>view('flipbook','glacier')); + await at(51.5,()=>select(Math.min(S.sel+1,S.list.length-1))); + await at(53,()=>view('media','glacier')); + await at(54.5,()=>select(Math.min(S.sel+2,S.list.length-1))); + await at(56,()=>{showView('settings');document.querySelector('#sDisableModels').scrollIntoView({block:'center',behavior:'smooth'});}); + await at(58,()=>toggle('sDisableAnimations',true)); + await at(59,()=>toggle('sDisableModels',true)); + await at(60.5,()=>{showView('library');view('carousel','ember');}); + await at(62,()=>select(Math.min(S.sel+1,S.list.length-1))); + await at(63,()=>select(Math.min(S.sel+1,S.list.length-1))); + await at(64.5,()=>{showView('settings');document.querySelector('#sDisableModels').scrollIntoView({block:'center'});}); + await at(65.3,()=>toggle('sDisableModels',false)); + await at(66,()=>toggle('sDisableAnimations',false)); + await at(67,()=>{showView('library');pick('switch2',/Donkey Kong/i);}); + await at(68.5,()=>openCase()); + await at(71,()=>tween({rx:-9,ry:24,tx:10,z:250},1400)); + await at(74.7,()=>{}); + const audio=await new Promise(resolve=>{window.demoAudioRecorder.onstop=async()=>{const data=new Uint8Array(await new Blob(window.demoAudioChunks,{type:'audio/webm'}).arrayBuffer());let binary='';for(let i=0;i ({...s, romDir: ''})); +const catalog = JSON.parse(fs.readFileSync(path.join(root, 'emulators.json'), 'utf8')); +const config = {systems, emulators:{}, customEmulators:[], hideWhilePlaying:true, launchAnimation:true, + mediaRoot:'', checkUpdates:true, promptFamily:'auto', motion:'auto', eShopStyle:'enhanced', + libraryTheme:'ember', libraryLayout:'carousel', uiSound:{enabled:false, volume:.25}, ambient:{idleMinutes:60, background:'ribbon'}, + extraGames:[], favorites:[], hiddenGames:[], gameDetails:{}, gameEmulators:{}, gameOrders:{}, recentlyPlayed:[], sortKey:'title', sortAsc:true, + showFavoritesOnly:false, showRecentlyPlayed:false, recentlyPlayedLimit:20}; +const installed = new Set(['duckstation', 'pcsx2', 'mgba']); +const emus = catalog.map(e => ({id:e.id, name:e.name, systems:e.systems, repo:e.source?.repo ?? e.repo, officialRepo:e.source?.repo ?? e.repo, managed:true, + prerelease:!!e.source?.prerelease, args:e.args, exe:installed.has(e.id) ? `C:\\PyroCade\\emulators\\${e.id}\\${e.id}.exe` : null, + installed:installed.has(e.id) ? {name:'Latest release', date:'2026-11-01'} : null, forked:false})); +const sources = {launchbox:{built:Date.now()}, screenscraper:{user:'', devId:'', hasPassword:false, hasDevPassword:false, ready:false}}; + +contextBridge.exposeInMainWorld('api', { + appVersion:async()=>require(path.join(root, 'package.json')).version, appCheckUpdate:async()=>({available:false}), appInstallUpdate:async()=>{}, + appOpenRelease:async()=>{}, onAppUpdateProgress:()=>{}, artSources:async()=>sources, artSetScreenScraper:async()=>sources, + artStatus:async()=>null, onArtProgress:()=>{}, onArtMedia:()=>{}, onLibraryInfo:()=>{}, onToast:()=>{}, onProgress:()=>{}, + getConfig:async()=>config, setConfig:async c=>Object.assign(config, c), scan:async()=>[], cachedLibrary:async()=>null, + toggleFavorite:async()=>[], recordPlay:async()=>true, updateLibraryPrefs:async()=>true, + getFavorites:async()=>[], getRecentlyPlayed:async()=>[], + setHidden:async()=>({hidden:false}), setSystemGamesHidden:async()=>[], setMetadata:async()=>({}), setGameEmulator:async()=>({}), saveGameOrder:async()=>[], + addGame:async()=>null, removeGame:async()=>true, gameList:async()=>[], + emuList:async()=>emus, emuCheck:async()=>({upToDate:true}), emuInstall:async()=>true, emuUninstall:async()=>true, + emuOpenFolder:async()=>true, emuPickExe:async()=>null, emuAddCustom:async()=>true, + fetchArt:async()=>null, artStart:async()=>false, artCancel:async()=>true, artOpenFolder:async()=>true, artImport:async()=>({}), + openManual:async()=>{}, launch:async()=>true, pickFolder:async()=>null, + feedbackInfo:async()=>'PyroCade: fixture\nOS: Fixture\nTauri: fixture\nInstallation: Fixture', feedbackCopy:async()=>true, feedbackOpen:async()=>true, +}); diff --git a/scripts/record-reddit-demo.cjs b/scripts/record-reddit-demo.cjs index 4ed7310..6cdbe09 100644 --- a/scripts/record-reddit-demo.cjs +++ b/scripts/record-reddit-demo.cjs @@ -1,15 +1,19 @@ -// Capture an isolated instance of the real app; never records the desktop. -process.env.PYROCADE_RECORD='1'; +// Capture an isolated instance of the renderer; never records the desktop. +// Tauri port (D09): the Electron app (main.js/preload.js) is not required. +// Loads renderer/index.html offscreen through readme-preload.cjs, then runs +// reddit-demo-timeline.js and records the same 35s demo with ffmpeg. const {app,BrowserWindow}=require('electron'); -const fs=require('node:fs'),path=require('node:path'),{spawn}=require('node:child_process'),{once}=require('node:events'); +const fs=require('node:fs'),path=require('node:path'),os=require('node:os'),{spawn}=require('node:child_process'),{once}=require('node:events'); const root=path.resolve(__dirname,'..'),out=path.join(root,'output/reddit-demo');fs.mkdirSync(out,{recursive:true}); +app.setPath('sessionData',path.join(os.tmpdir(),'PyroCade-reddit-' + process.pid)); app.commandLine.appendSwitch('force-device-scale-factor','1'); -require('../main.js'); const pause=ms=>new Promise(r=>setTimeout(r,ms)); app.whenReady().then(async()=>{ let encoder; try{ - const win=BrowserWindow.getAllWindows()[0],web=win.webContents;win.setContentSize(1920,1080);web.setZoomFactor(1.2);web.setFrameRate(30); + const win=new BrowserWindow({show:false,width:1920,height:1080,webPreferences:{preload:path.join(__dirname,'readme-preload.cjs'),sandbox:false,contextIsolation:true,offscreen:true,backgroundThrottling:false}}); + const web=win.webContents;win.setContentSize(1920,1080);web.setZoomFactor(1.2);web.setFrameRate(30); + await win.loadFile(path.join(root,'renderer/index.html')); const deadline=Date.now()+90000; while(Date.now()false))break;await pause(200)} web.setZoomFactor(1.25);await pause(200); @@ -32,7 +36,7 @@ app.whenReady().then(async()=>{ } encoder.stdin.end();const [exitCode]=await finished;fs.closeSync(log);if(exitCode!==0)throw new Error('Video encoder failed: '+exitCode); const result=await recording;fs.writeFileSync(path.join(out,'ui-audio.webm'),Buffer.from(result.audio,'base64')); - fs.writeFileSync(path.join(out,'capture-info.json'),JSON.stringify({frames,paintCount,elapsedMs:result.elapsed,resolution:[width,height],fps:30,scenes:['Carousel and cartridge reveal','Open and rotate a Switch 2 case','Vertical stack / Glacier','Flipbook / Violet','Colour cards / Mint','Themes and sound controls','Feedback end card']},null,2)); + fs.writeFileSync(path.join(out,'capture-info.json'),JSON.stringify({frames,paintCount,elapsedMs:result.elapsed,resolution:[width,height],fps:30,scenes:['Carousel and cartridge reveal','Open and rotate a Switch 2 case','Vertical stack / Glacier','Flipbook / Violet','Media carousel / Mint','Themes and sound controls','Feedback end card']},null,2)); console.log(`Captured ${frames} frames and UI audio. Encoding upload file…`); const final=path.join(root,'output/PyroCade-Reddit-Demo.mp4'); const mux=spawn('ffmpeg',['-hide_banner','-loglevel','warning','-y','-i',video,'-i',path.join(out,'ui-audio.webm'),'-map','0:v:0','-map','1:a:0','-c:v','copy','-c:a','aac','-b:a','128k','-af','aresample=async=1:first_pts=0,apad,volume=2.4,afade=t=in:st=0:d=0.15,afade=t=out:st=34.3:d=0.7','-t','35','-movflags','+faststart','-metadata','title=PyroCade — emulator frontend showcase',final],{windowsHide:true,stdio:'ignore'}); diff --git a/scripts/reddit-demo-timeline.js b/scripts/reddit-demo-timeline.js index 75ac561..300a58d 100644 --- a/scripts/reddit-demo-timeline.js +++ b/scripts/reddit-demo-timeline.js @@ -56,9 +56,9 @@ await at(14,()=>select(S.sel+1));await at(15.5,()=>select(S.sel+1)); await at(17,()=>{Appearance.apply({theme:'violet',layout:'flipbook'},false);label('Flipbook','Turn through your favourites.','A little shelf magic with every selection.')}); await at(18.3,()=>select(S.sel+1));await at(19.5,()=>select(S.sel+1));await at(20.7,()=>select(S.sel+1)); - await at(22,()=>{Appearance.apply({theme:'mint',layout:'swatches'},false);select(0);label('Colour cards','A palette from every cover.','A compact grid, coloured by the games themselves.')}); + await at(22,()=>{Appearance.apply({theme:'mint',layout:'media'},false);select(4);label('Media carousel','The games themselves.','Discs and cartridges, out of their cases.')}); await at(24,()=>select(5));await at(25.5,()=>select(6)); - await at(27,()=>{document.querySelector('#btnAppearance').click();label('Make it yours','Four views. Five moods.','Themes, layouts and playful UI sounds.','top-left')}); + await at(27,()=>{document.querySelector('#btnAppearance').click();label('Appearance','Six layouts and five themes.','Choose a layout, colours and sounds.','top-left')}); await at(28,()=>{Appearance.apply({theme:'rose'},false);AudioUI.play('confirm')}); await at(29.2,()=>{Appearance.apply({theme:'glacier'},false);AudioUI.play('confirm')}); await at(30.6,()=>{document.querySelector('#appearancePicker').close();Appearance.apply({theme:'ember',layout:'carousel'},false);S.sel=Math.max(0,S.list.findIndex(g=>g.title.includes('Super Mario Bros. Wonder')));layout();showInfo();caption.remove()}); diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock new file mode 100644 index 0000000..36c3356 --- /dev/null +++ b/src-tauri/Cargo.lock @@ -0,0 +1,6098 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "adler2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" + +[[package]] +name = "aho-corasick" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" +dependencies = [ + "memchr", +] + +[[package]] +name = "alloc-no-stdlib" +version = "3.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2fb6cfd47bf496ff64095c20eaba0c201404ee38714d4142fcfa1dc334fcc7a" + +[[package]] +name = "alloc-stdlib" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b5c1865780388bfa186411ab5f247819487fc4864c6e9c3106611fa347586e1" +dependencies = [ + "alloc-no-stdlib", +] + +[[package]] +name = "android_system_properties" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc" +dependencies = [ + "libc", +] + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + +[[package]] +name = "arbitrary" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bc62ac97cc33321f50863d514c3bc38a453947a8f9e781137e47c7401020aed" +dependencies = [ + "derive_arbitrary", +] + +[[package]] +name = "arboard" +version = "3.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aeb9553e62312c8756a5979254fc6d7da8bbeb5986a1e17037fab932f7037917" +dependencies = [ + "clipboard-win", + "image", + "log", + "objc2", + "objc2-app-kit", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-foundation", + "parking_lot", + "percent-encoding", + "windows-sys 0.61.2", + "wl-clipboard-rs", + "x11rb", +] + +[[package]] +name = "async-broadcast" +version = "0.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "435a87a52755b8f27fcf321ac4f04b2802e337c8c4872923137471ec39c37532" +dependencies = [ + "event-listener", + "event-listener-strategy", + "futures-core", + "pin-project-lite", +] + +[[package]] +name = "async-channel" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "924ed96dd52d1b75e9c1a3e6275715fd320f5f9439fb5a4a11fa51f4221158d2" +dependencies = [ + "concurrent-queue", + "event-listener-strategy", + "futures-core", + "pin-project-lite", +] + +[[package]] +name = "async-executor" +version = "1.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f426a31126c735126297bc5ea7a521263c9faff4f63ca415267ee625651c4f37" +dependencies = [ + "async-task", + "concurrent-queue", + "fastrand", + "futures-lite", + "pin-project-lite", + "slab", +] + +[[package]] +name = "async-io" +version = "2.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "456b8a8feb6f42d237746d4b3e9a178494627745c3c56c6ea55d92ba50d026fc" +dependencies = [ + "autocfg", + "cfg-if", + "concurrent-queue", + "futures-io", + "futures-lite", + "parking", + "polling", + "rustix", + "slab", + "windows-sys 0.61.2", +] + +[[package]] +name = "async-lock" +version = "3.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0876700b0d007ad25d5508865a4259c3af9af6d296bf663a0d586d0bc3369f6f" +dependencies = [ + "event-listener", + "event-listener-strategy", + "pin-project-lite", +] + +[[package]] +name = "async-process" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc50921ec0055cdd8a16de48773bfeec5c972598674347252c0399676be7da75" +dependencies = [ + "async-channel", + "async-io", + "async-lock", + "async-signal", + "async-task", + "blocking", + "cfg-if", + "event-listener", + "futures-lite", + "rustix", +] + +[[package]] +name = "async-recursion" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4f8abc12baad266b1c8cec146854c195b5864b4221d4b2ca7296a7ae82d9e451" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "async-signal" +version = "0.2.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52b5aaafa020cf5053a01f2a60e8ff5dccf550f0f77ec54a4e47285ac2bab485" +dependencies = [ + "async-io", + "async-lock", + "atomic-waker", + "cfg-if", + "futures-core", + "futures-io", + "rustix", + "signal-hook-registry", + "slab", + "windows-sys 0.61.2", +] + +[[package]] +name = "async-task" +version = "4.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b75356056920673b02621b35afd0f7dda9306d03c79a30f5c56c44cf256e3de" + +[[package]] +name = "async-trait" +version = "0.1.92" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "atk" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "241b621213072e993be4f6f3a9e4b45f65b7e6faad43001be957184b7bb1824b" +dependencies = [ + "atk-sys", + "glib", + "libc", +] + +[[package]] +name = "atk-sys" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c5e48b684b0ca77d2bbadeef17424c2ea3c897d44d566a1617e7e8f30614d086" +dependencies = [ + "glib-sys", + "gobject-sys", + "libc", + "system-deps", +] + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "base64" +version = "0.21.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d297deb1925b89f2ccc13d7635fa0714f12c87adce1c75356b39ca9b7178567" + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + +[[package]] +name = "bit-set" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08807e080ed7f9d5433fa9b275196cfc35414f66a0c79d864dc51a0d825231a3" +dependencies = [ + "bit-vec", +] + +[[package]] +name = "bit-vec" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e764a1d40d510daf35e07be9eb06e75770908c27d411ee6c92109c9840eaaf7" + +[[package]] +name = "bitflags" +version = "1.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" +dependencies = [ + "serde_core", +] + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "block2" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdeb9d870516001442e364c5220d3574d2da8dc765554b4a617230d33fa58ef5" +dependencies = [ + "objc2", +] + +[[package]] +name = "blocking" +version = "1.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a70e4329df6cb94385eed412ec92375c3cdd8a6e502493d1229b6414e4036dfa" +dependencies = [ + "async-channel", + "async-task", + "futures-io", + "futures-lite", + "piper", +] + +[[package]] +name = "brotli" +version = "9.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "627b7cfb0578f0eafce087a90fcd40add1231900b69e4d4de2d456260a4f5d81" +dependencies = [ + "alloc-no-stdlib", + "alloc-stdlib", + "brotli-decompressor", +] + +[[package]] +name = "brotli-decompressor" +version = "6.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34c6783f42c21c952ad7112b354f0ba2f10760e9decea5b1b60523d6e270faaf" +dependencies = [ + "alloc-no-stdlib", + "alloc-stdlib", +] + +[[package]] +name = "bs58" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf88ba1141d185c399bee5288d850d63b8369520c1eafc32a0430b5b6c287bf4" +dependencies = [ + "tinyvec", +] + +[[package]] +name = "bumpalo" +version = "3.20.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" + +[[package]] +name = "bytemuck" +version = "1.25.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797" + +[[package]] +name = "byteorder" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" + +[[package]] +name = "byteorder-lite" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495" + +[[package]] +name = "bytes" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" +dependencies = [ + "serde", +] + +[[package]] +name = "cairo-rs" +version = "0.18.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ca26ef0159422fb77631dc9d17b102f253b876fe1586b03b803e63a309b4ee2" +dependencies = [ + "bitflags 2.13.2", + "cairo-sys-rs", + "glib", + "libc", + "once_cell", + "thiserror 1.0.69", +] + +[[package]] +name = "cairo-sys-rs" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "685c9fa8e590b8b3d678873528d83411db17242a73fccaed827770ea0fedda51" +dependencies = [ + "glib-sys", + "libc", + "system-deps", +] + +[[package]] +name = "camino" +version = "1.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbbad30e4b4c14a39e3cc8aed085a12a327257c316619c93581e017bc52be591" +dependencies = [ + "serde_core", +] + +[[package]] +name = "cargo-platform" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e35af189006b9c0f00a064685c727031e3ed2d8020f7ba284d78cc2671bd36ea" +dependencies = [ + "serde", +] + +[[package]] +name = "cargo_metadata" +version = "0.19.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dd5eb614ed4c27c5d706420e4320fbe3216ab31fa1c33cd8246ac36dae4479ba" +dependencies = [ + "camino", + "cargo-platform", + "semver", + "serde", + "serde_json", + "thiserror 2.0.21", +] + +[[package]] +name = "cargo_toml" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82f4b26e751e711a5302649417f2da046dce6391b2ea30a4820f37462314f0b9" +dependencies = [ + "semver", + "serde", + "toml 1.2.0+spec-1.1.0", +] + +[[package]] +name = "cc" +version = "1.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "375989decec1a0fa424442bed520fa12ede43a48475ce8c7417d2c69b32b5f6b" +dependencies = [ + "find-msvc-tools", + "shlex", +] + +[[package]] +name = "cesu8" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6d43a04d8753f35258c91f8ec639f792891f748a1edbd759cf1dcea3382ad83c" + +[[package]] +name = "cfb" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a347dcabdae9c31b0825fd6a8bed285ec9c2acb89c47827126d52fa4f59cece3" +dependencies = [ + "fnv", + "uuid", + "web-time", +] + +[[package]] +name = "cfg-expr" +version = "0.15.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d067ad48b8650848b989a59a86c6c36a995d02d2bf778d45c3c5d57bc2718f02" +dependencies = [ + "smallvec", + "target-lexicon", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "cfg_aliases" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" + +[[package]] +name = "chacha20" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.1", + "rand_core", +] + +[[package]] +name = "chrono" +version = "0.4.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" +dependencies = [ + "iana-time-zone", + "js-sys", + "num-traits", + "serde", + "wasm-bindgen", + "windows-link", +] + +[[package]] +name = "clipboard-win" +version = "5.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "052af7878466feccda12ba7a6a67d019d712f296809559b47c12c8cc196d3a9a" +dependencies = [ + "error-code", +] + +[[package]] +name = "color_quant" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d7b894f5411737b7867f4827955924d7c254fc9f4d91a6aad6b097804b1018b" + +[[package]] +name = "combine" +version = "4.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4356eba6976435498d05a311ee9fc486da3bc81c200d3f0d7dd9703b41913f92" +dependencies = [ + "bytes", + "memchr", +] + +[[package]] +name = "concurrent-queue" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ca0197aee26d1ae37445ee532fefce43251d24cc7c166799f4d46817f1d3973" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "cookie" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a373e3602691c3cdea496d2f0ee5935151e6168fe87739483c463db1b2f2f87" +dependencies = [ + "time", + "version_check", +] + +[[package]] +name = "core-foundation" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91e195e091a93c46f7102ec7818a2aa394e1e1771c3ab4825963fa03e45afb8f" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "core-foundation" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + +[[package]] +name = "core-graphics" +version = "0.25.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "064badf302c3194842cf2c5d61f56cc88e54a759313879cdf03abdd27d0c3b97" +dependencies = [ + "bitflags 2.13.2", + "core-foundation 0.10.1", + "core-graphics-types", + "foreign-types", + "libc", +] + +[[package]] +name = "core-graphics-types" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d44a101f213f6c4cdc1853d4b78aef6db6bdfa3468798cc1d9912f4735013eb" +dependencies = [ + "bitflags 2.13.2", + "core-foundation 0.10.1", + "libc", +] + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "cpufeatures" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" +dependencies = [ + "libc", +] + +[[package]] +name = "crc32fast" +version = "1.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5f97d3416d5337d15c4b0d78c8c91df922ca143f57ec20e2d1c188333047ef04" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "crossbeam-channel" +version = "0.5.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "98b0cc327b5bc766e7fda9c9260cc0fa81b43a8e240440422dff70788e3f9ef1" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" + +[[package]] +name = "crunchy" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "cssparser" +version = "0.37.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c9cdaae01d5ed7882b04d795e7f752f46ff52d2fa3b50a20d28c464510bba98" +dependencies = [ + "cssparser-macros", + "dtoa-short", + "itoa", + "phf", + "smallvec", +] + +[[package]] +name = "cssparser-macros" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d045de693cb712d0b22c6a64be5b953f67b3ce00ab5ad3dd5d8b441886ab8e1a" +dependencies = [ + "quote", + "syn 3.0.9", +] + +[[package]] +name = "ctor" +version = "1.0.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "914a755b7c2d4af2bdcff7ce1739e2db9a1b81a9b07123d8015786ae03c0980d" + +[[package]] +name = "darling" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed17f5901b6630b993ca003def43f2f8ef4014fc13b047b57aad617ff32bc2ec" +dependencies = [ + "darling_core", + "darling_macro", +] + +[[package]] +name = "darling_core" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6837e2cf7485aaae18f86181d2f0e9a7ed297a025e220aeabf63fdebd3a2ddff" +dependencies = [ + "ident_case", + "proc-macro2", + "quote", + "strsim", + "syn 3.0.9", +] + +[[package]] +name = "darling_macro" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ac7135c3ef02b2f7833bbeb1be5ba7f966dcde8a87c6b87f65a778d71a02785" +dependencies = [ + "darling_core", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "dbus" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ab69f03cc8c4340c9c8e315114e1658e6775a9b16a04357973aa21cec22b32e" +dependencies = [ + "libc", + "libdbus-sys", + "windows-sys 0.61.2", +] + +[[package]] +name = "defmt" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4a0795ac740cb54d7b3775c9c17345f6aaecf884c01733b39d6017738e0e3e1" +dependencies = [ + "bitflags 1.3.2", + "defmt-macros", +] + +[[package]] +name = "defmt-macros" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "840bb056bd99c495c9188198a258ab787c79f306d864db3e6e8451442d6d8366" +dependencies = [ + "defmt-parser", + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "defmt-parser" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "71958f69fb2de856c5dd51ac9377e986ca1aa5919f931bf5395a807277f889a0" +dependencies = [ + "thiserror 2.0.21", +] + +[[package]] +name = "deranged" +version = "0.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e" +dependencies = [ + "serde_core", +] + +[[package]] +name = "derive_arbitrary" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b034bd7d5f032402a2479444dcc6f74e36a03f31854d41680fb240ef682a1ac" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "derive_more" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d751e9e49156b02b44f9c1815bcb94b984cdcc4396ecc32521c739452808b134" +dependencies = [ + "derive_more-impl", +] + +[[package]] +name = "derive_more-impl" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "799a97264921d8623a957f6c3b9011f3b5492f557bbb7a5a19b7fa6d06ba8dcb" +dependencies = [ + "proc-macro2", + "quote", + "rustc_version", + "syn 2.0.119", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", +] + +[[package]] +name = "dirs" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3e8aa94d75141228480295a7d0e7feb620b1a5ad9f12bc40be62411e38cce4e" +dependencies = [ + "dirs-sys", +] + +[[package]] +name = "dirs" +version = "7.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8d57d423b3c82e89b9a24ca3091fee61f456a26edbd28d26c65906f4bc1dcd8f" +dependencies = [ + "dirs-sys", +] + +[[package]] +name = "dirs-sys" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e01a3366d27ee9890022452ee61b2b63a67e6f13f58900b651ff5665f0bb1fab" +dependencies = [ + "libc", + "option-ext", + "redox_users", + "windows-sys 0.61.2", +] + +[[package]] +name = "dispatch2" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e0e367e4e7da84520dedcac1901e4da967309406d1e51017ae1abfb97adbd38" +dependencies = [ + "bitflags 2.13.2", + "block2", + "libc", + "objc2", +] + +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "dlopen2" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e2c5bd4158e66d1e215c49b837e11d62f3267b30c92f1d171c4d3105e3dc4d4" +dependencies = [ + "dlopen2_derive", + "libc", + "once_cell", + "winapi", +] + +[[package]] +name = "dlopen2_derive" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fbbb781877580993a8707ec48672673ec7b81eeba04cfd2310bd28c08e47c8f" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "dom_query" +version = "0.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fac5fca71e65e94cc718a6e2af65d6e0f9c6027751c2aa562fbb5087fda639bc" +dependencies = [ + "bit-set", + "cssparser", + "foldhash 0.2.0", + "html5ever", + "precomputed-hash", + "selectors", + "tendril", +] + +[[package]] +name = "downcast-rs" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75b325c5dbd37f80359721ad39aca5a29fb04c89279657cffdda8736d0c0b9d2" + +[[package]] +name = "dpi" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d8b14ccef22fc6f5a8f4d7d768562a182c04ce9a3b3157b91390b52ddfdf1a76" +dependencies = [ + "serde", +] + +[[package]] +name = "dtoa" +version = "1.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c3cf4824e2d5f025c7b531afcb2325364084a16806f6d47fbc1f5fbd9960590" + +[[package]] +name = "dtoa-short" +version = "0.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd1511a7b6a56299bd043a9c167a6d2bfb37bf84a6dfceaba651168adfb43c87" +dependencies = [ + "dtoa", +] + +[[package]] +name = "dunce" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" + +[[package]] +name = "dyn-clone" +version = "1.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555" + +[[package]] +name = "embed-resource" +version = "3.0.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6168487b5e7eb2673e6efe1200b1848016e436a6ca0b8031bf04bd9d493a249f" +dependencies = [ + "cc", + "memchr", + "rustc_version", + "toml 1.2.0+spec-1.1.0", + "vswhom", + "winreg", +] + +[[package]] +name = "embed_plist" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ef6b89e5b37196644d8796de5268852ff179b44e96276cf4290264843743bb7" + +[[package]] +name = "endi" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "66b7e2430c6dff6a955451e2cfc438f09cea1965a9d6f87f7e3b90decc014099" + +[[package]] +name = "enumflags2" +version = "0.7.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1027f7680c853e056ebcec683615fb6fbbc07dbaa13b4d5d9442b146ded4ecef" +dependencies = [ + "enumflags2_derive", + "serde", +] + +[[package]] +name = "enumflags2_derive" +version = "0.7.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67c78a4d8fdf9953a5c9d458f9efe940fd97a0cab0941c075a813ac594733827" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "erased-serde" +version = "0.4.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e59b668157f32d3459d4bd634861a06ffa2503a461ca5f0916b9f0252605e66" +dependencies = [ + "serde", + "serde_core", + "typeid", +] + +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "error-code" +version = "3.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b5343afd4a8365a643ac588dab4cf234a190c7f6c88c9f6dd6ffe00837661b7" + +[[package]] +name = "event-listener" +version = "5.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a23add41df1562121a9393cb065eab5146a1242410f23a644851e90cfd669d2" +dependencies = [ + "parking", + "pin-project-lite", +] + +[[package]] +name = "event-listener-strategy" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8be9f3dfaaffdae2972880079a491a1a8bb7cbed0b8dd7a347f668b4150a3b93" +dependencies = [ + "event-listener", + "pin-project-lite", +] + +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + +[[package]] +name = "fax" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "caf1079563223d5d59d83c85886a56e586cfd5c1a26292e971a0fa266531ac5a" + +[[package]] +name = "fdeflate" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c" +dependencies = [ + "simd-adler32", +] + +[[package]] +name = "field-offset" +version = "0.3.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38e2275cc4e4fc009b0669731a1e5ab7ebf11f469eaede2bab9309a5b4d6057f" +dependencies = [ + "memoffset", + "rustc_version", +] + +[[package]] +name = "filetime" +version = "0.2.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c287a33c7f0a620c38e641e7f60827713987b3c0f26e8ddc9462cc69cf75759" +dependencies = [ + "cfg-if", + "libc", +] + +[[package]] +name = "find-msvc-tools" +version = "0.1.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" + +[[package]] +name = "fixedbitset" +version = "0.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5905ec755cc8386d7928353e4d356d2be3e89e81e5ca01fe630a1ca4d08dc175" + +[[package]] +name = "flate2" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e634e2e0ebac1ee034020da1ca582e17ffe4e0f5e985823721e168928136dcb" +dependencies = [ + "crc32fast", + "miniz_oxide 0.9.1", + "zlib-rs", +] + +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + +[[package]] +name = "foldhash" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" + +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + +[[package]] +name = "foreign-types" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d737d9aa519fb7b749cbc3b962edcf310a8dd1f4b67c91c4f83975dbdd17d965" +dependencies = [ + "foreign-types-macros", + "foreign-types-shared", +] + +[[package]] +name = "foreign-types-macros" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea5190182e6915eb873ddbc16e23b711b6eb1f9c00a0d0a3a91b5f6228475225" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "foreign-types-shared" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa9a19cbb55df58761df49b23516a86d432839add4af60fc256da840f66ed35b" + +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "futures-channel" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" +dependencies = [ + "futures-core", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-executor" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "031b47cf1a3c6cc8bc2fc76cd437f521619387907d469316e7c0bc278f1f5432" +dependencies = [ + "futures-core", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-io" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" + +[[package]] +name = "futures-lite" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f78e10609fe0e0b3f4157ffab1876319b5b0db102a2c60dc4626306dc46b44ad" +dependencies = [ + "fastrand", + "futures-core", + "futures-io", + "parking", + "pin-project-lite", +] + +[[package]] +name = "futures-macro" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "futures-sink" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-core", + "futures-io", + "futures-macro", + "futures-sink", + "futures-task", + "memchr", + "pin-project-lite", + "slab", +] + +[[package]] +name = "gdk" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9f245958c627ac99d8e529166f9823fb3b838d1d41fd2b297af3075093c2691" +dependencies = [ + "cairo-rs", + "gdk-pixbuf", + "gdk-sys", + "gio", + "glib", + "libc", + "pango", +] + +[[package]] +name = "gdk-pixbuf" +version = "0.18.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "50e1f5f1b0bfb830d6ccc8066d18db35c487b1b2b1e8589b5dfe9f07e8defaec" +dependencies = [ + "gdk-pixbuf-sys", + "gio", + "glib", + "libc", + "once_cell", +] + +[[package]] +name = "gdk-pixbuf-sys" +version = "0.18.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9839ea644ed9c97a34d129ad56d38a25e6756f99f3a88e15cd39c20629caf7" +dependencies = [ + "gio-sys", + "glib-sys", + "gobject-sys", + "libc", + "system-deps", +] + +[[package]] +name = "gdk-sys" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c2d13f38594ac1e66619e188c6d5a1adb98d11b2fcf7894fc416ad76aa2f3f7" +dependencies = [ + "cairo-sys-rs", + "gdk-pixbuf-sys", + "gio-sys", + "glib-sys", + "gobject-sys", + "libc", + "pango-sys", + "pkg-config", + "system-deps", +] + +[[package]] +name = "gdkwayland-sys" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "140071d506d223f7572b9f09b5e155afbd77428cd5cc7af8f2694c41d98dfe69" +dependencies = [ + "gdk-sys", + "glib-sys", + "gobject-sys", + "libc", + "pkg-config", + "system-deps", +] + +[[package]] +name = "gdkx11" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3caa00e14351bebbc8183b3c36690327eb77c49abc2268dd4bd36b856db3fbfe" +dependencies = [ + "gdk", + "gdkx11-sys", + "gio", + "glib", + "libc", + "x11", +] + +[[package]] +name = "gdkx11-sys" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e2e7445fe01ac26f11601db260dd8608fe172514eb63b3b5e261ea6b0f4428d" +dependencies = [ + "gdk-sys", + "glib-sys", + "libc", + "system-deps", + "x11", +] + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "gethostname" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1bd49230192a3797a9a4d6abe9b3eed6f7fa4c8a8a4947977c6f80025f92cbd8" +dependencies = [ + "rustix", + "windows-link", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "wasi", + "wasm-bindgen", +] + +[[package]] +name = "getrandom" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" +dependencies = [ + "cfg-if", + "libc", + "r-efi 5.3.0", + "wasip2", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "r-efi 6.0.0", + "rand_core", + "wasm-bindgen", +] + +[[package]] +name = "gif" +version = "0.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee8cfcc411d9adbbaba82fb72661cc1bcca13e8bba98b364e62b2dba8f960159" +dependencies = [ + "color_quant", + "weezl", +] + +[[package]] +name = "gio" +version = "0.18.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4fc8f532f87b79cbc51a79748f16a6828fb784be93145a322fa14d06d354c73" +dependencies = [ + "futures-channel", + "futures-core", + "futures-io", + "futures-util", + "gio-sys", + "glib", + "libc", + "once_cell", + "pin-project-lite", + "smallvec", + "thiserror 1.0.69", +] + +[[package]] +name = "gio-sys" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "37566df850baf5e4cb0dfb78af2e4b9898d817ed9263d1090a2df958c64737d2" +dependencies = [ + "glib-sys", + "gobject-sys", + "libc", + "system-deps", + "winapi", +] + +[[package]] +name = "glib" +version = "0.18.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "233daaf6e83ae6a12a52055f568f9d7cf4671dabb78ff9560ab6da230ce00ee5" +dependencies = [ + "bitflags 2.13.2", + "futures-channel", + "futures-core", + "futures-executor", + "futures-task", + "futures-util", + "gio-sys", + "glib-macros", + "glib-sys", + "gobject-sys", + "libc", + "memchr", + "once_cell", + "smallvec", + "thiserror 1.0.69", +] + +[[package]] +name = "glib-macros" +version = "0.18.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bb0228f477c0900c880fd78c8759b95c7636dbd7842707f49e132378aa2acdc" +dependencies = [ + "heck 0.4.1", + "proc-macro-crate 2.0.2", + "proc-macro-error", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "glib-sys" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "063ce2eb6a8d0ea93d2bf8ba1957e78dbab6be1c2220dd3daca57d5a9d869898" +dependencies = [ + "libc", + "system-deps", +] + +[[package]] +name = "glob" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b" + +[[package]] +name = "gobject-sys" +version = "0.18.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0850127b514d1c4a4654ead6dedadb18198999985908e6ffe4436f53c785ce44" +dependencies = [ + "glib-sys", + "libc", + "system-deps", +] + +[[package]] +name = "gtk" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd56fb197bfc42bd5d2751f4f017d44ff59fbb58140c6b49f9b3b2bdab08506a" +dependencies = [ + "atk", + "cairo-rs", + "field-offset", + "futures-channel", + "gdk", + "gdk-pixbuf", + "gio", + "glib", + "gtk-sys", + "gtk3-macros", + "libc", + "pango", + "pkg-config", +] + +[[package]] +name = "gtk-sys" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f29a1c21c59553eb7dd40e918be54dccd60c52b049b75119d5d96ce6b624414" +dependencies = [ + "atk-sys", + "cairo-sys-rs", + "gdk-pixbuf-sys", + "gdk-sys", + "gio-sys", + "glib-sys", + "gobject-sys", + "libc", + "pango-sys", + "system-deps", +] + +[[package]] +name = "gtk3-macros" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52ff3c5b21f14f0736fed6dcfc0bfb4225ebf5725f3c0209edeec181e4d73e9d" +dependencies = [ + "proc-macro-crate 1.3.1", + "proc-macro-error", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "half" +version = "2.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b" +dependencies = [ + "cfg-if", + "crunchy", + "zerocopy", +] + +[[package]] +name = "hashbrown" +version = "0.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888" + +[[package]] +name = "hashbrown" +version = "0.15.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" +dependencies = [ + "foldhash 0.1.5", +] + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" + +[[package]] +name = "heck" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8" + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "hermit-abi" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e17592d60ebacc7d5e169f4663c5f84f9161cc90328abcfe8456f41e4dfcb284" + +[[package]] +name = "hex" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" + +[[package]] +name = "html5ever" +version = "0.39.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "46a1761807faccc9a19e86944bbf40610014066306f96edcdedc2fb714bcb7b8" +dependencies = [ + "log", + "markup5ever", +] + +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "http-body" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c" +dependencies = [ + "bytes", + "http", +] + +[[package]] +name = "http-body-util" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "pin-project-lite", +] + +[[package]] +name = "http-range" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2149c4b4b83390c71fab669730347d578ec6bdf759f2160c581ad8b8819733b4" + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "hyper" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c3e324da4c95177d6291d4c8730197c0d1822f8a9766814a4a44fa5ab797c9c" +dependencies = [ + "atomic-waker", + "bytes", + "futures-core", + "http", + "http-body", + "httparse", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", + "want", +] + +[[package]] +name = "hyper-rustls" +version = "0.27.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dfa8e654703247911e29c23fbeaa261834bd9bb74efba2f9acddc37bfb127f53" +dependencies = [ + "http", + "hyper", + "hyper-util", + "rustls", + "tokio", + "tokio-rustls", + "tower-service", + "webpki-roots", +] + +[[package]] +name = "hyper-util" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff" +dependencies = [ + "base64 0.23.1", + "bytes", + "futures-channel", + "futures-util", + "http", + "http-body", + "httparse", + "hyper", + "ipnet", + "libc", + "percent-encoding", + "pin-project-lite", + "socket2", + "system-configuration", + "tokio", + "tower-service", + "tracing", + "windows-registry", +] + +[[package]] +name = "iana-time-zone" +version = "0.1.65" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470" +dependencies = [ + "android_system_properties", + "core-foundation-sys", + "iana-time-zone-haiku", + "js-sys", + "log", + "wasm-bindgen", + "windows-core", +] + +[[package]] +name = "iana-time-zone-haiku" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" +dependencies = [ + "cc", +] + +[[package]] +name = "ico" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d75e94d66081e4d8dcd098bd8dc5254800fea14a26389b298410158d834de167" +dependencies = [ + "byteorder", + "png", +] + +[[package]] +name = "icu_collections" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe090a42a0d3140fed8c63263ed1fecc02422cb2f4bfe55cd8de2de1b8e105dd" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25d29b57c17c6528d0dc4c2141cfa2d08200465acb537a3909c8b9b8a4a984c0" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "404a3b8c486f205c87fe7f23ab6894d84a4ad76d6e4671ae1981ba7def87c599" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20f0088bfb7441f7a37fa0c9e20cb1e9cba1cac6b9ce8cd2a6dc44294f8e8cbc" + +[[package]] +name = "icu_properties" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ea83d991c56158f7cf898bf86436c1dfe7c07ee82fe88951f2695c9f37a379f" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b98f29af82d02b163fe50161388350e743bb3107cc8e8c2f7314cb505faddfcf" + +[[package]] +name = "icu_provider" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "413099315636c588ee8f011190b329b971a09a8fae9d157e01dcae8379468514" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "ident_case" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "image" +version = "0.25.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85ab80394333c02fe689eaf900ab500fbd0c2213da414687ebf995a65d5a6104" +dependencies = [ + "bytemuck", + "byteorder-lite", + "color_quant", + "gif", + "image-webp", + "moxcms", + "num-traits", + "png", + "tiff", + "zune-core", + "zune-jpeg", +] + +[[package]] +name = "image-webp" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "525e9ff3e1a4be2fbea1fdf0e98686a6d98b4d8f937e1bf7402245af1909e8c3" +dependencies = [ + "byteorder-lite", + "quick-error", +] + +[[package]] +name = "indexmap" +version = "1.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bd070e393353796e801d209ad339e89596eb4c8d430d18ede6a1cced8fafbd99" +dependencies = [ + "autocfg", + "hashbrown 0.12.3", + "serde", +] + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown 0.17.1", + "serde", + "serde_core", +] + +[[package]] +name = "infer" +version = "0.22.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f4200d433cbd5178df7797c9c2e75b348b728e39631cf14520d1e2fc424201f4" +dependencies = [ + "cfb", +] + +[[package]] +name = "ipnet" +version = "2.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0" + +[[package]] +name = "is-docker" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "928bae27f42bc99b60d9ac7334e3a21d10ad8f1835a4e12ec3ec0464765ed1b3" +dependencies = [ + "once_cell", +] + +[[package]] +name = "is-wsl" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "173609498df190136aa7dea1a91db051746d339e18476eed5ca40521f02d7aa5" +dependencies = [ + "is-docker", + "once_cell", +] + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "javascriptcore-rs" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca5671e9ffce8ffba57afc24070e906da7fc4b1ba66f2cabebf61bf2ea257fcc" +dependencies = [ + "bitflags 1.3.2", + "glib", + "javascriptcore-rs-sys", +] + +[[package]] +name = "javascriptcore-rs-sys" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af1be78d14ffa4b75b66df31840478fef72b51f8c2465d4ca7c194da9f7a5124" +dependencies = [ + "glib-sys", + "gobject-sys", + "libc", + "system-deps", +] + +[[package]] +name = "jiff" +version = "0.2.39" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ac703058abac89e5c39b0b879dce2b6b14a4ba36600c7e7e3d0c60a6883ef3c" +dependencies = [ + "defmt", + "jiff-core", + "jiff-static", + "jiff-tzdb-platform", + "log", + "portable-atomic", + "portable-atomic-util", + "serde_core", + "windows-link", +] + +[[package]] +name = "jiff-core" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aee43309eb53bafb8c36d35d6e444769c8f8e6206a9fbf7546f5db9d7d4a0e93" +dependencies = [ + "defmt", + "log", +] + +[[package]] +name = "jiff-static" +version = "0.2.39" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dc32470c67eb7d0e9ccb74303fa925313dc04cecb1aa048beaa6f391e36a93d" +dependencies = [ + "jiff-core", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "jiff-tzdb" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa8377070c6bae868759445e5a77f66d84f0b72f3a054bfb00e6d038b8282da7" + +[[package]] +name = "jiff-tzdb-platform" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "875a5a69ac2bab1a891711cf5eccbec1ce0341ea805560dcd90b7a2e925132e8" +dependencies = [ + "jiff-tzdb", +] + +[[package]] +name = "jni" +version = "0.21.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a87aa2bb7d2af34197c04845522473242e1aa17c12f4935d5856491a7fb8c97" +dependencies = [ + "cesu8", + "cfg-if", + "combine", + "jni-sys 0.3.1", + "log", + "thiserror 1.0.69", + "walkdir", + "windows-sys 0.45.0", +] + +[[package]] +name = "jni" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5efd9a482cf3a427f00d6b35f14332adc7902ce91efb778580e180ff90fa3498" +dependencies = [ + "cfg-if", + "combine", + "jni-macros", + "jni-sys 0.4.1", + "log", + "simd_cesu8", + "thiserror 2.0.21", + "walkdir", + "windows-link", +] + +[[package]] +name = "jni-macros" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a00109accc170f0bdb141fed3e393c565b6f5e072365c3bd58f5b062591560a3" +dependencies = [ + "proc-macro2", + "quote", + "rustc_version", + "simd_cesu8", + "syn 2.0.119", +] + +[[package]] +name = "jni-sys" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41a652e1f9b6e0275df1f15b32661cf0d4b78d4d87ddec5e0c3c20f097433258" +dependencies = [ + "jni-sys 0.4.1", +] + +[[package]] +name = "jni-sys" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6377a88cb3910bee9b0fa88d4f42e1d2da8e79915598f65fb0c7ee14c878af2" +dependencies = [ + "jni-sys-macros", +] + +[[package]] +name = "jni-sys-macros" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264" +dependencies = [ + "quote", + "syn 2.0.119", +] + +[[package]] +name = "js-sys" +version = "0.3.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + +[[package]] +name = "json-patch" +version = "4.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7421438de105a0827e44fadd05377727847d717c80ce29a229f85fd04c427b72" +dependencies = [ + "jsonptr", + "serde", + "serde_json", + "thiserror 2.0.21", +] + +[[package]] +name = "jsonptr" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5a3cc660ba5d72bce0b3bb295bf20847ccbb40fd423f3f05b61273672e561fe" +dependencies = [ + "serde", + "serde_json", +] + +[[package]] +name = "keyboard-types" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fbe853b403ae61a04233030ae8a79d94975281ed9770a1f9e246732b534b28d" +dependencies = [ + "bitflags 2.13.2", + "serde", +] + +[[package]] +name = "libappindicator" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03589b9607c868cc7ae54c0b2a22c8dc03dd41692d48f2d7df73615c6a95dc0a" +dependencies = [ + "glib", + "gtk", + "gtk-sys", + "libappindicator-sys", + "log", +] + +[[package]] +name = "libappindicator-sys" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e9ec52138abedcc58dc17a7c6c0c00a2bdb4f3427c7f63fa97fd0d859155caf" +dependencies = [ + "gtk-sys", + "libloading", + "once_cell", +] + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "libdbus-sys" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "328c4789d42200f1eeec05bd86c9c13c7f091d2ba9a6ea35acdf51f31bc0f043" +dependencies = [ + "pkg-config", +] + +[[package]] +name = "libloading" +version = "0.7.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b67380fd3b2fbe7527a606e18729d21c6f3951633d0500574c4dc22d2d638b9f" +dependencies = [ + "cfg-if", + "winapi", +] + +[[package]] +name = "libredox" +version = "0.1.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61ff90caf6077a803a240f62fdbe88645a890bbca49ef8174c3cb0404362171d" +dependencies = [ + "libc", +] + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "litemap" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" + +[[package]] +name = "lock_api" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" +dependencies = [ + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + +[[package]] +name = "lru-slab" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4050469837a6ff301cd14c1f8f24f88549e6d548f24f64e2148eb0f72cebc51f" + +[[package]] +name = "markup5ever" +version = "0.39.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7122d987ec5f704ee56f6e5b41a7d93722e9aae27ae07cafa4036c4d3f9757de" +dependencies = [ + "log", + "tendril", + "web_atoms", +] + +[[package]] +name = "md5" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "490cc448043f947bae3cbee9c203358d62dbee0db12107a74be5c30ccfd09771" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "memoffset" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a" +dependencies = [ + "autocfg", +] + +[[package]] +name = "mime" +version = "0.3.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" + +[[package]] +name = "minisign-verify" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "871285dc19d8d0ebe0eef3d0e99a205f2a71363b122632cbbfa4a6c370a960ce" + +[[package]] +name = "miniz_oxide" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316" +dependencies = [ + "adler2", + "simd-adler32", +] + +[[package]] +name = "miniz_oxide" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" +dependencies = [ + "adler2", + "simd-adler32", +] + +[[package]] +name = "mio" +version = "1.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1788edb87fdc09c7e26304471e2f5be8cdefb1b6930d6e3985fc02ff53bf86ee" +dependencies = [ + "libc", + "wasi", + "windows-sys 0.61.2", +] + +[[package]] +name = "moxcms" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb85c154ba489f01b25c0d36ae69a87e4a1c73a72631fc6c0eb6dde34a73e44b" +dependencies = [ + "num-traits", + "pxfm", +] + +[[package]] +name = "muda" +version = "0.20.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cca139e57da4383727f189e43e66e84fa372347027fc996f9f1a007ec0a37996" +dependencies = [ + "crossbeam-channel", + "dpi", + "gtk", + "keyboard-types", + "objc2", + "objc2-app-kit", + "objc2-core-foundation", + "objc2-foundation", + "once_cell", + "png", + "serde", + "thiserror 2.0.21", + "windows-sys 0.61.2", +] + +[[package]] +name = "ndk" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3f42e7bbe13d351b6bead8286a43aac9534b82bd3cc43e47037f012ebfd62d4" +dependencies = [ + "bitflags 2.13.2", + "jni-sys 0.3.1", + "log", + "ndk-sys", + "num_enum", + "raw-window-handle", + "thiserror 1.0.69", +] + +[[package]] +name = "ndk-context" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27b02d87554356db9e9a873add8782d4ea6e3e58ea071a9adb9a2e8ddb884a8b" + +[[package]] +name = "ndk-sys" +version = "0.6.0+11769913" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee6cda3051665f1fb8d9e08fc35c96d5a244fb1be711a03b71118828afc9a873" +dependencies = [ + "jni-sys 0.3.1", +] + +[[package]] +name = "new_debug_unreachable" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "650eef8c711430f1a879fdd01d4745a7deea475becfb90269c06775983bbf086" + +[[package]] +name = "nix" +version = "0.31.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf20d2fde8ff38632c426f1165ed7436270b44f199fc55284c38276f9db47c3d" +dependencies = [ + "bitflags 2.13.2", + "cfg-if", + "cfg_aliases", + "libc", +] + +[[package]] +name = "nom" +version = "8.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df9761775871bdef83bee530e60050f7e54b1105350d6884eb0fb4f46c2f9405" +dependencies = [ + "memchr", +] + +[[package]] +name = "num-conv" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "num_enum" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d0bca838442ec211fa11de3a8b0e0e8f3a4522575b5c4c06ed722e005036f26" +dependencies = [ + "num_enum_derive", + "rustversion", +] + +[[package]] +name = "num_enum_derive" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "680998035259dcfcafe653688bf2aa6d3e2dc05e98be6ab46afb089dc84f1df8" +dependencies = [ + "proc-macro-crate 3.5.0", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "objc2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08849bbd4767dfae9457696856ae1c84fe4e0281bbe4a7abff2d0e06fb7981f8" +dependencies = [ + "objc2-encode", + "objc2-exception-helper", +] + +[[package]] +name = "objc2-app-kit" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d49e936b501e5c5bf01fda3a9452ff86dc3ea98ad5f283e1455153142d97518c" +dependencies = [ + "bitflags 2.13.2", + "block2", + "objc2", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-foundation", + "objc2-quartz-core", +] + +[[package]] +name = "objc2-cloud-kit" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73ad74d880bb43877038da939b7427bba67e9dd42004a18b809ba7d87cee241c" +dependencies = [ + "bitflags 2.13.2", + "objc2", + "objc2-foundation", +] + +[[package]] +name = "objc2-core-data" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b402a653efbb5e82ce4df10683b6b28027616a2715e90009947d50b8dd298fa" +dependencies = [ + "objc2", + "objc2-foundation", +] + +[[package]] +name = "objc2-core-foundation" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536" +dependencies = [ + "bitflags 2.13.2", + "dispatch2", + "objc2", +] + +[[package]] +name = "objc2-core-graphics" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e022c9d066895efa1345f8e33e584b9f958da2fd4cd116792e15e07e4720a807" +dependencies = [ + "bitflags 2.13.2", + "dispatch2", + "objc2", + "objc2-core-foundation", + "objc2-io-surface", +] + +[[package]] +name = "objc2-core-image" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5d563b38d2b97209f8e861173de434bd0214cf020e3423a52624cd1d989f006" +dependencies = [ + "objc2", + "objc2-foundation", +] + +[[package]] +name = "objc2-core-location" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca347214e24bc973fc025fd0d36ebb179ff30536ed1f80252706db19ee452009" +dependencies = [ + "objc2", + "objc2-foundation", +] + +[[package]] +name = "objc2-core-text" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0cde0dfb48d25d2b4862161a4d5fcc0e3c24367869ad306b0c9ec0073bfed92d" +dependencies = [ + "bitflags 2.13.2", + "objc2", + "objc2-core-foundation", + "objc2-core-graphics", +] + +[[package]] +name = "objc2-encode" +version = "4.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef25abbcd74fb2609453eb695bd2f860d389e457f67dc17cafc8b8cbc89d0c33" + +[[package]] +name = "objc2-exception-helper" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c7a1c5fbb72d7735b076bb47b578523aedc40f3c439bea6dfd595c089d79d98a" +dependencies = [ + "cc", +] + +[[package]] +name = "objc2-foundation" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272" +dependencies = [ + "bitflags 2.13.2", + "block2", + "libc", + "objc2", + "objc2-core-foundation", +] + +[[package]] +name = "objc2-io-surface" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "180788110936d59bab6bd83b6060ffdfffb3b922ba1396b312ae795e1de9d81d" +dependencies = [ + "bitflags 2.13.2", + "objc2", + "objc2-core-foundation", +] + +[[package]] +name = "objc2-osa-kit" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f112d1746737b0da274ef79a23aac283376f335f4095a083a267a082f21db0c0" +dependencies = [ + "bitflags 2.13.2", + "objc2", + "objc2-app-kit", + "objc2-foundation", +] + +[[package]] +name = "objc2-quartz-core" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96c1358452b371bf9f104e21ec536d37a650eb10f7ee379fff67d2e08d537f1f" +dependencies = [ + "bitflags 2.13.2", + "objc2", + "objc2-core-foundation", + "objc2-foundation", +] + +[[package]] +name = "objc2-ui-kit" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d87d638e33c06f577498cbcc50491496a3ed4246998a7fbba7ccb98b1e7eab22" +dependencies = [ + "bitflags 2.13.2", + "block2", + "objc2", + "objc2-cloud-kit", + "objc2-core-data", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-core-image", + "objc2-core-location", + "objc2-core-text", + "objc2-foundation", + "objc2-quartz-core", + "objc2-user-notifications", +] + +[[package]] +name = "objc2-user-notifications" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9df9128cbbfef73cda168416ccf7f837b62737d748333bfe9ab71c245d76613e" +dependencies = [ + "objc2", + "objc2-foundation", +] + +[[package]] +name = "objc2-web-kit" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2e5aaab980c433cf470df9d7af96a7b46a9d892d521a2cbbb2f8a4c16751e7f" +dependencies = [ + "bitflags 2.13.2", + "block2", + "objc2", + "objc2-app-kit", + "objc2-core-foundation", + "objc2-foundation", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "open" +version = "5.4.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8d8c8b8e725ad26404d6896eb2f064294a0a7b4f1d9120210d85544684c4ca95" +dependencies = [ + "dunce", + "is-wsl", + "libc", +] + +[[package]] +name = "openssl-probe" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e036b411754132fd6b74e94b74e9a13c5cf606fa93d1885c35860d3060820b1" + +[[package]] +name = "option-ext" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d" + +[[package]] +name = "ordered-stream" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9aa2b01e1d916879f73a53d01d1d6cee68adbb31d6d9177a8cfce093cced1d50" +dependencies = [ + "futures-core", + "pin-project-lite", +] + +[[package]] +name = "os_pipe" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "osakit" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "732c71caeaa72c065bb69d7ea08717bd3f4863a4f451402fc9513e29dbd5261b" +dependencies = [ + "objc2", + "objc2-foundation", + "objc2-osa-kit", + "serde", + "serde_json", + "thiserror 2.0.21", +] + +[[package]] +name = "pango" +version = "0.18.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ca27ec1eb0457ab26f3036ea52229edbdb74dee1edd29063f5b9b010e7ebee4" +dependencies = [ + "gio", + "glib", + "libc", + "once_cell", + "pango-sys", +] + +[[package]] +name = "pango-sys" +version = "0.18.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "436737e391a843e5933d6d9aa102cb126d501e815b83601365a948a518555dc5" +dependencies = [ + "glib-sys", + "gobject-sys", + "libc", + "system-deps", +] + +[[package]] +name = "parking" +version = "2.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f38d5652c16fde515bb1ecef450ab0f6a219d619a7274976324d5e377f7dceba" + +[[package]] +name = "parking_lot" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall", + "smallvec", + "windows-link", +] + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "petgraph" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8701b58ea97060d5e5b155d383a69952a60943f0e6dfe30b04c287beb0b27455" +dependencies = [ + "fixedbitset", + "hashbrown 0.15.5", + "indexmap 2.14.2", +] + +[[package]] +name = "phf" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c1562dc717473dbaa4c1f85a36410e03c047b2e7df7f45ee938fbef64ae7fadf" +dependencies = [ + "phf_macros", + "phf_shared", + "serde", +] + +[[package]] +name = "phf_codegen" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "49aa7f9d80421bca176ca8dbfebe668cc7a2684708594ec9f3c0db0805d5d6e1" +dependencies = [ + "phf_generator", + "phf_shared", +] + +[[package]] +name = "phf_generator" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "135ace3a761e564ec88c03a77317a7c6b80bb7f7135ef2544dbe054243b89737" +dependencies = [ + "fastrand", + "phf_shared", +] + +[[package]] +name = "phf_macros" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "812f032b54b1e759ccd5f8b6677695d5268c588701effba24601f6932f8269ef" +dependencies = [ + "phf_generator", + "phf_shared", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "phf_shared" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e57fef6bc5981e38c2ce2d63bfa546861309f875b8a75f092d1d54ae2d64f266" +dependencies = [ + "siphasher", +] + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "piper" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c835479a4443ded371d6c535cbfd8d31ad92c5d23ae9770a61bc155e4992a3c1" +dependencies = [ + "atomic-waker", + "fastrand", + "futures-io", +] + +[[package]] +name = "pkg-config" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" + +[[package]] +name = "plist" +version = "1.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "327a4cb2ad49dc48adfdc9da89e22c64d488b508c67a044d71ba729e4521a285" +dependencies = [ + "base64 0.23.1", + "indexmap 2.14.2", + "quick-xml 0.42.0", + "serde", + "time", +] + +[[package]] +name = "png" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61" +dependencies = [ + "bitflags 2.13.2", + "crc32fast", + "fdeflate", + "flate2", + "miniz_oxide 0.8.9", +] + +[[package]] +name = "polling" +version = "3.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d0e4f59085d47d8241c88ead0f274e8a0cb551f3625263c05eb8dd897c34218" +dependencies = [ + "cfg-if", + "concurrent-queue", + "hermit-abi", + "pin-project-lite", + "rustix", + "windows-sys 0.61.2", +] + +[[package]] +name = "portable-atomic" +version = "1.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85" + +[[package]] +name = "portable-atomic-util" +version = "0.2.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10ab3eb7f3becc3a1cbc4f2c6f20267996cfc1a6467a873763411b136a122715" +dependencies = [ + "portable-atomic", +] + +[[package]] +name = "potential_utf" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" +dependencies = [ + "zerovec", +] + +[[package]] +name = "powerfmt" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958" + +[[package]] +name = "precomputed-hash" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "925383efa346730478fb4838dbe9137d2a47675ad789c546d150a6e1dd4ab31c" + +[[package]] +name = "proc-macro-crate" +version = "1.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f4c021e1093a56626774e81216a4ce732a735e5bad4868a03f3ed65ca0c3919" +dependencies = [ + "once_cell", + "toml_edit 0.19.15", +] + +[[package]] +name = "proc-macro-crate" +version = "2.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b00f26d3400549137f92511a46ac1cd8ce37cb5598a96d382381458b992a5d24" +dependencies = [ + "toml_datetime 0.6.3", + "toml_edit 0.20.2", +] + +[[package]] +name = "proc-macro-crate" +version = "3.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f" +dependencies = [ + "toml_edit 0.25.18+spec-1.1.0", +] + +[[package]] +name = "proc-macro-error" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da25490ff9892aab3fcf7c36f08cfb902dd3e71ca0f9f9517bea02a73a5ce38c" +dependencies = [ + "proc-macro-error-attr", + "proc-macro2", + "quote", + "syn 1.0.109", + "version_check", +] + +[[package]] +name = "proc-macro-error-attr" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1be40180e52ecc98ad80b184934baf3d0d29f979574e439af5a55274b35f869" +dependencies = [ + "proc-macro2", + "quote", + "version_check", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "pxfm" +version = "0.1.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea" + +[[package]] +name = "pyrocade" +version = "0.4.2" +dependencies = [ + "anyhow", + "chrono", + "dirs 6.0.0", + "futures-util", + "image", + "md5", + "quick-xml 0.37.5", + "regex", + "reqwest 0.12.28", + "serde", + "serde_json", + "tauri", + "tauri-build", + "tauri-plugin-clipboard-manager", + "tauri-plugin-dialog", + "tauri-plugin-opener", + "tauri-plugin-process", + "tauri-plugin-updater", + "tokio", + "url", + "uuid", + "walkdir", + "zip 2.6.1", +] + +[[package]] +name = "quick-error" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3" + +[[package]] +name = "quick-xml" +version = "0.37.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "331e97a1af0bf59823e6eadffe373d7b27f485be8748f71471c662c1f269b7fb" +dependencies = [ + "memchr", +] + +[[package]] +name = "quick-xml" +version = "0.41.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e660451e55124f798a69a5af3f49ccfbefbd41910eefd25caf2393e1f3473ec1" +dependencies = [ + "memchr", +] + +[[package]] +name = "quick-xml" +version = "0.42.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41b1177fdf999d2321d3fb46ff47159d9c1fb9ad66a4879f8c50a0b504615e9b" +dependencies = [ + "memchr", +] + +[[package]] +name = "quinn" +version = "0.11.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4051e23e9185c255a7e33ef59cdbca87a22d359052eecd22fc6b901fb37d9d11" +dependencies = [ + "bytes", + "cfg_aliases", + "pin-project-lite", + "quinn-proto", + "quinn-udp", + "rustc-hash", + "rustls", + "socket2", + "thiserror 2.0.21", + "tokio", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-proto" +version = "0.11.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e750cca55fe4f0439a15d0bb529da9651e79993e8e72c61a899a36d462befbe" +dependencies = [ + "bytes", + "getrandom 0.4.3", + "lru-slab", + "rand", + "rand_pcg", + "ring", + "rustc-hash", + "rustls", + "rustls-pki-types", + "slab", + "thiserror 2.0.21", + "tinyvec", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-udp" +version = "0.5.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af66907df18639dcf4db56ca65490cabc4b27a97dbadd96f2926cca73298f016" +dependencies = [ + "cfg_aliases", + "libc", + "once_cell", + "socket2", + "tracing", + "windows-sys 0.61.2", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rand" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af" +dependencies = [ + "chacha20", + "getrandom 0.4.3", + "rand_core", +] + +[[package]] +name = "rand_core" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" + +[[package]] +name = "rand_pcg" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "caa0f4137e1c0a72f4c651489402276c8e8e1cf081f3b0ba156d2cbeef09e86a" +dependencies = [ + "rand_core", +] + +[[package]] +name = "raw-window-handle" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20675572f6f24e9e76ef639bc5552774ed45f1c30e2951e1e99c59888861c539" + +[[package]] +name = "redox_syscall" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +dependencies = [ + "bitflags 2.13.2", +] + +[[package]] +name = "redox_users" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60dc65c0ff1a7ae1294b0c67b9f14baf70b644404010370171787bfac1038fc0" +dependencies = [ + "libredox", + "thiserror 2.0.21", +] + +[[package]] +name = "ref-cast" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e440fb4e4b4147295338efb76001ab9e4efc0e5839df2c47fc5ac2381d365c3" +dependencies = [ + "ref-cast-impl", +] + +[[package]] +name = "ref-cast-impl" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92ecd8964f8453721699a1ed72037b0db49ce2f5a5138486ee89bed6f67cdf3a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "regex" +version = "1.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" + +[[package]] +name = "reqwest" +version = "0.12.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147" +dependencies = [ + "base64 0.22.1", + "bytes", + "futures-core", + "futures-util", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-rustls", + "hyper-util", + "js-sys", + "log", + "percent-encoding", + "pin-project-lite", + "quinn", + "rustls", + "rustls-pki-types", + "serde", + "serde_json", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tokio-rustls", + "tokio-util", + "tower", + "tower-http", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "wasm-streams 0.4.2", + "web-sys", + "webpki-roots", +] + +[[package]] +name = "reqwest" +version = "0.13.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "16a1cfa75cc186dd73d5818e510e042e40927bccc9c236b061cea97e1eb08029" +dependencies = [ + "base64 0.23.1", + "bytes", + "futures-core", + "futures-util", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-rustls", + "hyper-util", + "js-sys", + "log", + "percent-encoding", + "pin-project-lite", + "rustls", + "rustls-pki-types", + "rustls-platform-verifier", + "serde", + "serde_json", + "sync_wrapper", + "tokio", + "tokio-rustls", + "tokio-util", + "tower", + "tower-http", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "wasm-streams 0.5.0", + "web-sys", +] + +[[package]] +name = "rfd" +version = "0.17.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20dafead71c16a34e1ff357ddefc8afc11e7d51d6d2b9fbd07eaa48e3e540220" +dependencies = [ + "block2", + "dispatch2", + "glib-sys", + "gobject-sys", + "gtk-sys", + "js-sys", + "libc", + "log", + "objc2", + "objc2-app-kit", + "objc2-core-foundation", + "objc2-foundation", + "percent-encoding", + "raw-window-handle", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", + "windows-sys 0.61.2", +] + +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + +[[package]] +name = "rustc-hash" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" + +[[package]] +name = "rustc_version" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" +dependencies = [ + "semver", +] + +[[package]] +name = "rustix" +version = "1.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" +dependencies = [ + "bitflags 2.13.2", + "errno", + "libc", + "linux-raw-sys", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustls" +version = "0.23.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" +dependencies = [ + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-native-certs" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a073f5dc7469f984c52ad2752b63b0807745133b6de880b7b64c1ac4c48aec4" +dependencies = [ + "openssl-probe", + "rustls-pki-types", + "schannel", + "security-framework", +] + +[[package]] +name = "rustls-pki-types" +version = "1.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96" +dependencies = [ + "web-time", + "zeroize", +] + +[[package]] +name = "rustls-platform-verifier" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1167586491e2b18b8bfbb293e8180ec17c201c4f076d7cb3070ca964e7598f98" +dependencies = [ + "core-foundation 0.10.1", + "core-foundation-sys", + "jni 0.22.4", + "log", + "once_cell", + "rustls", + "rustls-native-certs", + "rustls-platform-verifier-android", + "rustls-webpki", + "security-framework", + "security-framework-sys", + "webpki-root-certs", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustls-platform-verifier-android" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eec689c0bc40ff2458a5977b6619cb718087084a18e02a131c599b62d05e1a5f" + +[[package]] +name = "rustls-webpki" +version = "0.103.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4443b1b6d39d7c663139942cc4558262562d2c84123bb6282ef177009ca8b281" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + +[[package]] +name = "same-file" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "schannel" +version = "0.1.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9cb23c424d8ee841bb4d813677ca237e2a610067d594fec130f87d6093495ab5" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "schemars" +version = "0.8.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3fbf2ae1b8bc8e02df939598064d22402220cd5bbcca1c76f7d6a310974d5615" +dependencies = [ + "dyn-clone", + "indexmap 1.9.3", + "schemars_derive", + "serde", + "serde_json", + "url", + "uuid", +] + +[[package]] +name = "schemars" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cd191f9397d57d581cddd31014772520aa448f65ef991055d7f61582c65165f" +dependencies = [ + "dyn-clone", + "ref-cast", + "serde", + "serde_json", +] + +[[package]] +name = "schemars" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab508826f74a77ca9d5aba6ff19b522583ee3eaf28a19384ff3d0e5835fadf6e" +dependencies = [ + "dyn-clone", + "ref-cast", + "serde", + "serde_json", +] + +[[package]] +name = "schemars_derive" +version = "0.8.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32e265784ad618884abaea0600a9adf15393368d840e0222d101a072f3f7534d" +dependencies = [ + "proc-macro2", + "quote", + "serde_derive_internals", + "syn 2.0.119", +] + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "security-framework" +version = "3.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d" +dependencies = [ + "bitflags 2.13.2", + "core-foundation 0.10.1", + "core-foundation-sys", + "libc", + "security-framework-sys", +] + +[[package]] +name = "security-framework-sys" +version = "2.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "selectors" +version = "0.38.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8adfa1c298912827b8a28b223b3b874357397ae706e6190acd9bf28cee99114d" +dependencies = [ + "bitflags 2.13.2", + "cssparser", + "derive_more", + "log", + "new_debug_unreachable", + "phf", + "phf_codegen", + "precomputed-hash", + "rustc-hash", + "servo_arc", + "smallvec", +] + +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" +dependencies = [ + "serde", + "serde_core", +] + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde-untagged" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9faf48a4a2d2693be24c6289dbe26552776eb7737074e6722891fadbe6c5058" +dependencies = [ + "erased-serde", + "serde", + "serde_core", + "typeid", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "serde_derive_internals" +version = "0.29.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "18d26a20a969b9e3fdf2fc2d9f21eda6c40e2de84c9408bb5d3b05d499aae711" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_repr" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8d3b1629de253c70a0508c3899572da79ca359fdab27c7920ff00406df418906" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "serde_spanned" +version = "0.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf41e0cfaf7226dca15e8197172c295a782857fcb97fad1808a166870dee75a3" +dependencies = [ + "serde", +] + +[[package]] +name = "serde_spanned" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7523beb55eece201a2356bee0bbca0d1ab466c14c07703b2e0ee6d42cb0c2c" +dependencies = [ + "serde_core", +] + +[[package]] +name = "serde_urlencoded" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" +dependencies = [ + "form_urlencoded", + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "serde_with" +version = "3.24.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df9adc193c780ef8f159aee8b61e2d5801aaa555e6eb0947fe45530ec506296f" +dependencies = [ + "base64 0.23.1", + "bs58", + "chrono", + "hex", + "indexmap 1.9.3", + "indexmap 2.14.2", + "jiff", + "schemars 0.9.0", + "schemars 1.2.3", + "serde_core", + "serde_json", + "serde_with_macros", + "time", +] + +[[package]] +name = "serde_with_macros" +version = "3.24.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3e17bbc68e28663bbbb90df47e058aa7eda4fb445b89fe70457bb94fbccf6e49" +dependencies = [ + "darling", + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "serialize-to-javascript" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "04f3666a07a197cdb77cdf306c32be9b7f598d7060d50cfd4d5aa04bfd92f6c5" +dependencies = [ + "serde", + "serde_json", + "serialize-to-javascript-impl", +] + +[[package]] +name = "serialize-to-javascript-impl" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "772ee033c0916d670af7860b6e1ef7d658a4629a6d0b4c8c3e67f09b3765b75d" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "servo_arc" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "170fb83ab34de17dc69aa7c67482b22218ddb85da56546f9bd6b929e32a05930" +dependencies = [ + "stable_deref_trait", +] + +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "digest", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "signal-hook-registry" +version = "1.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +dependencies = [ + "errno", + "libc", +] + +[[package]] +name = "simd-adler32" +version = "0.3.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" + +[[package]] +name = "simd_cesu8" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11031e251abf8611c80f460e19dbdeb54a66db918e49c65a7065b46ac7aec520" +dependencies = [ + "rustc_version", + "simdutf8", +] + +[[package]] +name = "simdutf8" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" + +[[package]] +name = "siphasher" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33f4fe9184a62d842c9ef383018f3306d8ba224fd9d836f56d7288308847c256" + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.16.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0d5d4b1981b8bbbb7aed204cae5726d683d5d6ac7e74ec54122ea28f315e7c8" + +[[package]] +name = "socket2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "softbuffer" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aac18da81ebbf05109ab275b157c22a653bb3c12cf884450179942f81bcbf6c3" +dependencies = [ + "bytemuck", + "js-sys", + "ndk", + "objc2", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-foundation", + "objc2-quartz-core", + "raw-window-handle", + "redox_syscall", + "tracing", + "wasm-bindgen", + "web-sys", + "windows-sys 0.61.2", +] + +[[package]] +name = "soup3" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "471f924a40f31251afc77450e781cb26d55c0b650842efafc9c6cbd2f7cc4f9f" +dependencies = [ + "futures-channel", + "gio", + "glib", + "libc", + "soup3-sys", +] + +[[package]] +name = "soup3-sys" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ebe8950a680a12f24f15ebe1bf70db7af98ad242d9db43596ad3108aab86c27" +dependencies = [ + "gio-sys", + "glib-sys", + "gobject-sys", + "libc", + "system-deps", +] + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "static_vcruntime" +version = "3.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff7589a1859b09232522bb9edf076ca7fcf14ded96685d3fa629db73023ffbb7" + +[[package]] +name = "string_cache" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a18596f8c785a729f2819c0f6a7eae6ebeebdfffbfe4214ae6b087f690e31901" +dependencies = [ + "new_debug_unreachable", + "parking_lot", + "phf_shared", + "precomputed-hash", +] + +[[package]] +name = "string_cache_codegen" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "585635e46db231059f76c5849798146164652513eb9e8ab2685939dd90f29b69" +dependencies = [ + "phf_generator", + "phf_shared", + "proc-macro2", + "quote", +] + +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "swift-rs" +version = "1.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cefd87076fd385308ee4aff597256c902f1fbb4d031de1558efc12f8ffefadd9" +dependencies = [ + "base64 0.21.7", + "serde", + "serde_json", +] + +[[package]] +name = "syn" +version = "1.0.109" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237" +dependencies = [ + "proc-macro2", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "sync_wrapper" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" +dependencies = [ + "futures-core", +] + +[[package]] +name = "synstructure" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "system-configuration" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a13f3d0daba03132c0aa9767f98351b3488edc2c100cda2d2ec2b04f3d8d3c8b" +dependencies = [ + "bitflags 2.13.2", + "core-foundation 0.9.4", + "system-configuration-sys", +] + +[[package]] +name = "system-configuration-sys" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e1d1b10ced5ca923a1fcb8d03e96b8d3268065d724548c0211415ff6ac6bac4" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "system-deps" +version = "6.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a3e535eb8dded36d55ec13eddacd30dec501792ff23a0b1682c38601b8cf2349" +dependencies = [ + "cfg-expr", + "heck 0.5.0", + "pkg-config", + "toml 0.8.2", + "version-compare", +] + +[[package]] +name = "tao" +version = "0.37.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d5777b06fe6435126ae8d816eba269e050e1e10d302cf5461e9c49eccabc3548" +dependencies = [ + "bitflags 2.13.2", + "block2", + "core-foundation 0.10.1", + "core-graphics", + "crossbeam-channel", + "dbus", + "dispatch2", + "dlopen2", + "dpi", + "gdkwayland-sys", + "gdkx11-sys", + "gtk", + "jni 0.21.1", + "libc", + "log", + "ndk", + "ndk-context", + "ndk-sys", + "objc2", + "objc2-app-kit", + "objc2-foundation", + "objc2-ui-kit", + "parking_lot", + "percent-encoding", + "raw-window-handle", + "tao-macros", + "unicode-segmentation", + "url", + "windows", + "windows-core", + "windows-version", + "x11-dl", +] + +[[package]] +name = "tao-macros" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5f7eeb6d99155545da6150a1795945f16ac9c178deb2a5f2e74d776107bd5849" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "tar" +version = "0.4.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f6221d9a6003c78398e3b239969f352578258df48c8eb051caadae0015bc840" +dependencies = [ + "filetime", + "libc", + "xattr", +] + +[[package]] +name = "target-lexicon" +version = "0.12.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61c41af27dd6d1e27b1b16b489db798443478cef1f06a660c96db617ba5de3b1" + +[[package]] +name = "tauri" +version = "2.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5fb0244332cfb9cee7e2a568bf5da29a36ed8fdbd717f6f47a66b6b7b358c072" +dependencies = [ + "anyhow", + "bytes", + "cookie", + "dirs 7.0.0", + "dunce", + "embed_plist", + "getrandom 0.3.4", + "glob", + "gtk", + "heck 0.5.0", + "http", + "http-range", + "jni 0.21.1", + "libc", + "log", + "mime", + "muda", + "objc2", + "objc2-app-kit", + "objc2-foundation", + "objc2-ui-kit", + "objc2-web-kit", + "percent-encoding", + "plist", + "raw-window-handle", + "reqwest 0.13.5", + "serde", + "serde_json", + "serde_repr", + "serialize-to-javascript", + "swift-rs", + "tauri-build", + "tauri-macros", + "tauri-runtime", + "tauri-runtime-wry", + "tauri-utils", + "thiserror 2.0.21", + "tokio", + "tray-icon", + "url", + "webkit2gtk", + "webview2-com", + "window-vibrancy", + "windows", +] + +[[package]] +name = "tauri-build" +version = "2.7.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "adddb0e648752aaac5da9c3c3c6a68e1e87cab55e3b757b18a9441ef8c3ac614" +dependencies = [ + "anyhow", + "cargo_toml", + "dirs 7.0.0", + "glob", + "heck 0.5.0", + "json-patch", + "schemars 0.8.22", + "semver", + "serde", + "serde_json", + "static_vcruntime", + "strsim", + "tauri-utils", + "tauri-winres", + "walkdir", +] + +[[package]] +name = "tauri-codegen" +version = "2.7.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fb37631cf71dab5e8ab55e1bdd701e18a52653d90b78e71d0e5598b1e0a61316" +dependencies = [ + "base64 0.23.1", + "brotli", + "ico", + "json-patch", + "plist", + "png", + "proc-macro2", + "quote", + "semver", + "serde", + "serde_json", + "sha2", + "syn 2.0.119", + "tauri-utils", + "thiserror 2.0.21", + "time", + "url", + "uuid", + "walkdir", +] + +[[package]] +name = "tauri-macros" +version = "2.7.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0cc38db58854c10fb5f91a887ed8bf82d3239bb92b5d8db86eda09e96d9963d1" +dependencies = [ + "heck 0.5.0", + "proc-macro2", + "quote", + "syn 2.0.119", + "tauri-codegen", + "tauri-utils", +] + +[[package]] +name = "tauri-plugin" +version = "2.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67fb21a77e8f94e8beb3325e583102488659365af0a3948b7ea244c5b779c291" +dependencies = [ + "anyhow", + "glob", + "plist", + "schemars 0.8.22", + "serde", + "serde_json", + "tauri-utils", + "walkdir", +] + +[[package]] +name = "tauri-plugin-clipboard-manager" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9be5ed8d94c33afe8377e885119069f6508780659271d0a25cfc54d441f2bc81" +dependencies = [ + "arboard", + "log", + "serde", + "serde_json", + "tauri", + "tauri-plugin", + "thiserror 2.0.21", +] + +[[package]] +name = "tauri-plugin-dialog" +version = "2.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce0fb9c2b6d34a9720627ed930ebc8af26f61e648695aecaeb03d5c33c5896f5" +dependencies = [ + "log", + "raw-window-handle", + "rfd", + "serde", + "serde_json", + "tauri", + "tauri-plugin", + "tauri-plugin-fs", + "thiserror 2.0.21", + "url", +] + +[[package]] +name = "tauri-plugin-fs" +version = "2.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d58eb1d4984e535f47a642ffec09a2da6f5c18a12b5902d12126cb7626d628b" +dependencies = [ + "anyhow", + "dunce", + "glob", + "log", + "objc2-foundation", + "percent-encoding", + "schemars 0.8.22", + "serde", + "serde_json", + "serde_repr", + "tauri", + "tauri-plugin", + "tauri-utils", + "thiserror 2.0.21", + "toml 1.2.0+spec-1.1.0", + "url", +] + +[[package]] +name = "tauri-plugin-opener" +version = "2.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53810be1b4fed22bb6ac3f4cab5a2b80d9391d1af436bda145607532bc0bb219" +dependencies = [ + "dunce", + "glob", + "objc2-app-kit", + "objc2-foundation", + "open", + "schemars 0.8.22", + "serde", + "serde_json", + "tauri", + "tauri-plugin", + "thiserror 2.0.21", + "url", + "windows", + "zbus", +] + +[[package]] +name = "tauri-plugin-process" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "74ae3d8549ae564c0397377373e262f340908eb23a5b9fbe03f2a00007dc0038" +dependencies = [ + "tauri", + "tauri-plugin", +] + +[[package]] +name = "tauri-plugin-updater" +version = "2.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d957abbcb3f9f6c76d22a3a0f012f30880640d0bccb5634d2b12a9937e4c872b" +dependencies = [ + "base64 0.23.1", + "dirs 7.0.0", + "flate2", + "futures-util", + "http", + "infer", + "libc", + "log", + "minisign-verify", + "osakit", + "percent-encoding", + "reqwest 0.13.5", + "rustls", + "semver", + "serde", + "serde_json", + "tar", + "tauri", + "tauri-plugin", + "tempfile", + "thiserror 2.0.21", + "time", + "tokio", + "url", + "windows-sys 0.61.2", + "zip 9.3.0", +] + +[[package]] +name = "tauri-runtime" +version = "2.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7c55766d99cea69055904d1735b93c2049302b2e09effd462120deb5581d78e9" +dependencies = [ + "cookie", + "dpi", + "gtk", + "http", + "jni 0.21.1", + "objc2", + "objc2-ui-kit", + "objc2-web-kit", + "raw-window-handle", + "serde", + "serde_json", + "tauri-utils", + "thiserror 2.0.21", + "url", + "webkit2gtk", + "webview2-com", + "windows", +] + +[[package]] +name = "tauri-runtime-wry" +version = "2.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1aa9d8b7a120f879f44fdc1053f7b7dbf416bf0bbc6a72b714dec46b782b52f" +dependencies = [ + "gtk", + "http", + "jni 0.21.1", + "log", + "objc2", + "objc2-app-kit", + "percent-encoding", + "raw-window-handle", + "softbuffer", + "tao", + "tauri-runtime", + "tauri-utils", + "url", + "webkit2gtk", + "webview2-com", + "windows", + "wry", +] + +[[package]] +name = "tauri-utils" +version = "2.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "362ab21cd4cc713f2a02b1a9b5688198b1541cfb6907c4281e9190e0f0ef4aa3" +dependencies = [ + "anyhow", + "brotli", + "cargo_metadata", + "ctor", + "dom_query", + "dunce", + "glob", + "http", + "infer", + "json-patch", + "log", + "memchr", + "phf", + "plist", + "proc-macro2", + "quote", + "regex", + "schemars 0.8.22", + "semver", + "serde", + "serde-untagged", + "serde_json", + "serde_with", + "swift-rs", + "thiserror 2.0.21", + "toml 1.2.0+spec-1.1.0", + "url", + "urlpattern", + "uuid", + "walkdir", +] + +[[package]] +name = "tauri-winres" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c52bb6904475a6ca662f15ef787f18ade61d5740a1ee12c45d3b748efdb6f796" +dependencies = [ + "dunce", + "embed-resource", + "toml 1.2.0+spec-1.1.0", +] + +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom 0.4.3", + "once_cell", + "rustix", + "windows-sys 0.61.2", +] + +[[package]] +name = "tendril" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5fed54709c5b3a53d09bb1c113ea4f5ceafd1e772ddcb0030a82e1d56c087b08" +dependencies = [ + "new_debug_unreachable", +] + +[[package]] +name = "thiserror" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52" +dependencies = [ + "thiserror-impl 1.0.69", +] + +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl 2.0.21", +] + +[[package]] +name = "thiserror-impl" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "tiff" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63feaf3343d35b6ca4d50483f94843803b0f51634937cc2ec519fc32232bc52" +dependencies = [ + "fax", + "flate2", + "half", + "quick-error", + "weezl", + "zune-jpeg", +] + +[[package]] +name = "time" +version = "0.3.55" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134" +dependencies = [ + "deranged", + "num-conv", + "powerfmt", + "serde_core", + "time-core", + "time-macros", +] + +[[package]] +name = "time-core" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109" + +[[package]] +name = "time-macros" +version = "0.2.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e689342a48d2ea927c87ea50cabf8594854bf940e9310208848d680d668ed85" +dependencies = [ + "num-conv", + "time-core", +] + +[[package]] +name = "tinystr" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "abc840c238154d58f9e86b2792261edfde565a17696e1cda1a449de27979801a" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "tinyvec" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" + +[[package]] +name = "tokio" +version = "1.54.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3" +dependencies = [ + "bytes", + "libc", + "mio", + "pin-project-lite", + "signal-hook-registry", + "socket2", + "tokio-macros", + "windows-sys 0.61.2", +] + +[[package]] +name = "tokio-macros" +version = "2.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "tokio-rustls" +version = "0.26.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9cc2678c2cdd569ef8215e2afd7954ada2ae20b4fdd2c5fe6139a3b02d105db" +dependencies = [ + "rustls", + "tokio", +] + +[[package]] +name = "tokio-util" +version = "0.7.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e464cf451ba96ebfc6f9b6542f17ee8b8956e33f1e40d9690624e59d7a7f8a4b" +dependencies = [ + "bytes", + "futures-core", + "futures-sink", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "toml" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "185d8ab0dfbb35cf1399a6344d8484209c088f75f8f68230da55d48d95d43e3d" +dependencies = [ + "serde", + "serde_spanned 0.6.9", + "toml_datetime 0.6.3", + "toml_edit 0.20.2", +] + +[[package]] +name = "toml" +version = "1.2.0+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c5ffcdf8f50436dbbfd675c1fe1b8e0854f42b7defea8584bdebe1aee900e561" +dependencies = [ + "indexmap 2.14.2", + "serde_core", + "serde_spanned 1.1.2", + "toml_datetime 1.1.2+spec-1.1.0", + "toml_parser", + "toml_writer", + "winnow 1.0.5", +] + +[[package]] +name = "toml_datetime" +version = "0.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7cda73e2f1397b1262d6dfdcef8aafae14d1de7748d66822d3bfeeb6d03e5e4b" +dependencies = [ + "serde", +] + +[[package]] +name = "toml_datetime" +version = "1.1.2+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b86d767906c6c42421dcba507eb9d203e779497710a47782a224bb871653053" +dependencies = [ + "serde_core", +] + +[[package]] +name = "toml_edit" +version = "0.19.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b5bb770da30e5cbfde35a2d7b9b8a2c4b8ef89548a7a6aeab5c9a576e3e7421" +dependencies = [ + "indexmap 2.14.2", + "toml_datetime 0.6.3", + "winnow 0.5.40", +] + +[[package]] +name = "toml_edit" +version = "0.20.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "396e4d48bbb2b7554c944bde63101b5ae446cff6ec4a24227428f15eb72ef338" +dependencies = [ + "indexmap 2.14.2", + "serde", + "serde_spanned 0.6.9", + "toml_datetime 0.6.3", + "winnow 0.5.40", +] + +[[package]] +name = "toml_edit" +version = "0.25.18+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ec6e78bd70db9420d8d212fa9dc97f116448a1ceff5d00eabb991d407e21396" +dependencies = [ + "indexmap 2.14.2", + "toml_datetime 1.1.2+spec-1.1.0", + "toml_parser", + "winnow 1.0.5", +] + +[[package]] +name = "toml_parser" +version = "1.1.5+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c" +dependencies = [ + "winnow 1.0.5", +] + +[[package]] +name = "toml_writer" +version = "1.2.0+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "009dbb7700f11c55ef83aebbe4c0e9cf1f1ac0844bd8d6f00dc38f302026e13a" + +[[package]] +name = "tower" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" +dependencies = [ + "futures-core", + "futures-util", + "pin-project-lite", + "sync_wrapper", + "tokio", + "tower-layer", + "tower-service", +] + +[[package]] +name = "tower-http" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840" +dependencies = [ + "bitflags 2.13.2", + "bytes", + "futures-util", + "http", + "http-body", + "pin-project-lite", + "tower", + "tower-layer", + "tower-service", + "url", +] + +[[package]] +name = "tower-layer" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" + +[[package]] +name = "tower-service" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "pin-project-lite", + "tracing-attributes", + "tracing-core", +] + +[[package]] +name = "tracing-attributes" +version = "0.1.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", +] + +[[package]] +name = "tray-icon" +version = "0.25.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2b9c52859a94554803ccd4a24b98f74148ebc73b90676d783f3490b1bff9d72" +dependencies = [ + "crossbeam-channel", + "dirs 7.0.0", + "libappindicator", + "muda", + "objc2", + "objc2-app-kit", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-foundation", + "once_cell", + "png", + "serde", + "thiserror 2.0.21", + "windows-sys 0.61.2", +] + +[[package]] +name = "tree_magic_mini" +version = "3.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8765b90061cba6c22b5831f675da109ae5561588290f9fa2317adab2714d5a6" +dependencies = [ + "memchr", + "nom", + "petgraph", +] + +[[package]] +name = "try-lock" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" + +[[package]] +name = "typed-path" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ce898823d8cd0f028662d2f349694b1af0a5cc9be83f1d213a00d3147445e1e" + +[[package]] +name = "typeid" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc7d623258602320d5c55d1bc22793b57daff0ec7efc270ea7d55ce1d5f5471c" + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "uds_windows" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2f6fb2847f6742cd76af783a2a2c49e9375d0a111c7bef6f71cd9e738c72d6e" +dependencies = [ + "memoffset", + "tempfile", + "windows-sys 0.61.2", +] + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "unicode-segmentation" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8" + +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "url" +version = "2.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", + "serde_derive", +] + +[[package]] +name = "urlpattern" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df16f50ef4cc145211879a3867ba757076b25dfee812040dcb0658bd9ae7904b" +dependencies = [ + "icu_properties", + "regex", + "serde", + "url", +] + +[[package]] +name = "utf8_iter" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af3bd9d3e571c26fcce9d033b87ea5ab061b8d2ffe9b7a5675d810d68f03edf0" +dependencies = [ + "utf_types", +] + +[[package]] +name = "utf_types" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a3b425286980a367278453f3b6d28cdcb134b574e5a35824a6ff5eebad50bb6" + +[[package]] +name = "uuid" +version = "1.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a0e2d11620c50695fe12bbbfde96b3477fe606e7284c22d505c12ce51214514" +dependencies = [ + "getrandom 0.4.3", + "js-sys", + "serde_core", + "wasm-bindgen", +] + +[[package]] +name = "version-compare" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03c2856837ef78f57382f06b2b8563a2f512f7185d732608fd9176cb3b8edf0e" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "vswhom" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be979b7f07507105799e854203b470ff7c78a1639e330a58f183b5fea574608b" +dependencies = [ + "libc", + "vswhom-sys", +] + +[[package]] +name = "vswhom-sys" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fb067e4cbd1ff067d1df46c9194b5de0e98efd2810bbc95c5d5e5f25a3231150" +dependencies = [ + "cc", + "libc", +] + +[[package]] +name = "walkdir" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b" +dependencies = [ + "same-file", + "winapi-util", +] + +[[package]] +name = "want" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec4cdd0dd910afe868b7ef477227d8d538b46b3075031afee8a9f2acb0a2ed0b" +dependencies = [ + "try-lock", +] + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasip2" +version = "1.0.4+wasi-0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487" +dependencies = [ + "wit-bindgen", +] + +[[package]] +name = "wasm-bindgen" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0181c14ddd6c7b8b0b0132a5f1ea2f32be0d893cd3ea97b6e3b28886b8a3d1c" +dependencies = [ + "cfg-if", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.80" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e14e0327cb5368ad60ccb22d04a9827a693c95a926d8d125e9fa39e0baec501" +dependencies = [ + "js-sys", + "tokio", + "wasm-bindgen", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e931a02a39abdbf66966fc35902b5ed58344750a70885bed4ebb3d8eaf28ed9" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ca4b54280e455bd831e33a6b8e734baf432fe63fbc35c42ac14ce67a043a53a" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 3.0.9", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b1f9c3798725016c6ee5f2f57869ec0831e8bbc0ab0310a86e787e97f41389e" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "wasm-streams" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15053d8d85c7eccdbefef60f06769760a563c7f0a9d6902a13d35c7800b0ad65" +dependencies = [ + "futures-util", + "js-sys", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + +[[package]] +name = "wasm-streams" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d1ec4f6517c9e11ae630e200b2b65d193279042e28edd4a2cda233e46670bbb" +dependencies = [ + "futures-util", + "js-sys", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + +[[package]] +name = "wayland-backend" +version = "0.3.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38a91b4eaddff87b1cd1074985e3713da4af2c49742d1b356b2c01670a67a078" +dependencies = [ + "cc", + "downcast-rs", + "rustix", + "smallvec", + "wayland-sys", +] + +[[package]] +name = "wayland-client" +version = "0.31.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3c36a0f861ad76d0901f2800b46321410d9f73f2ea88aac0650d86c32688073" +dependencies = [ + "bitflags 2.13.2", + "rustix", + "wayland-backend", + "wayland-scanner", +] + +[[package]] +name = "wayland-protocols" +version = "0.32.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23d0c813de3daa2ed6520af85a3bd49b0e722a3078506899aa9686fea58dc4b6" +dependencies = [ + "bitflags 2.13.2", + "wayland-backend", + "wayland-client", + "wayland-scanner", +] + +[[package]] +name = "wayland-protocols-wlr" +version = "0.3.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eb04e52f7836d7c7976c78ca0250d61e33873c34156a2a1fc9474828ec268234" +dependencies = [ + "bitflags 2.13.2", + "wayland-backend", + "wayland-client", + "wayland-protocols", + "wayland-scanner", +] + +[[package]] +name = "wayland-scanner" +version = "0.31.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "338e30461b3a2b67d70eb30a6d89f8e0c93a833e07d2ae89085cd070c4a00ac0" +dependencies = [ + "proc-macro2", + "quick-xml 0.41.0", + "quote", +] + +[[package]] +name = "wayland-sys" +version = "0.31.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d8eab23fefc9e41f8e841df4a9c707e8a8c4ed26e944ef69297184de2785e3be" +dependencies = [ + "pkg-config", +] + +[[package]] +name = "web-sys" +version = "0.3.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7d179596ff5ec0f6de4db64d54011bde6289cc49603d3a6e4ce3f329207ab88" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "web-time" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "web_atoms" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba8b815c1b593dc0baf78dd0f4fc8fdb2de53198fb1163738093e9a311c33fb3" +dependencies = [ + "phf", + "phf_codegen", + "string_cache", + "string_cache_codegen", +] + +[[package]] +name = "webkit2gtk" +version = "2.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1027150013530fb2eaf806408df88461ae4815a45c541c8975e61d6f2fc4793" +dependencies = [ + "bitflags 1.3.2", + "cairo-rs", + "gdk", + "gdk-sys", + "gio", + "gio-sys", + "glib", + "glib-sys", + "gobject-sys", + "gtk", + "gtk-sys", + "javascriptcore-rs", + "libc", + "once_cell", + "soup3", + "webkit2gtk-sys", +] + +[[package]] +name = "webkit2gtk-sys" +version = "2.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "916a5f65c2ef0dfe12fff695960a2ec3d4565359fdbb2e9943c974e06c734ea5" +dependencies = [ + "bitflags 1.3.2", + "cairo-sys-rs", + "gdk-sys", + "gio-sys", + "glib-sys", + "gobject-sys", + "gtk-sys", + "javascriptcore-rs-sys", + "libc", + "pkg-config", + "soup3-sys", + "system-deps", +] + +[[package]] +name = "webpki-root-certs" +version = "1.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e49d0e65abc00c142e8f9428da991da9f1a250c39be97459901eb12b9b49f62a" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "webpki-roots" +version = "1.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f5f280bbb2b287bc8e7de7e3852945a0ff50d1bbcb5ed42b6c7a568c546df171" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "webview2-com" +version = "0.39.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f89fca7a704cee10dcb3654c1dbb8941d1783132f1917358af75bec37a7d7e6" +dependencies = [ + "webview2-com-macros", + "webview2-com-sys", + "windows", + "windows-core", +] + +[[package]] +name = "webview2-com-macros" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67a921c1b6914c367b2b823cd4cde6f96beec77d30a939c8199bb377cf9b9b54" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "webview2-com-sys" +version = "0.39.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b3a07132775117d6065853d9d1178157b8c90e228de47129d6bce2c7edebedfb" +dependencies = [ + "thiserror 2.0.21", + "windows", + "windows-core", +] + +[[package]] +name = "weezl" +version = "0.1.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a28ac98ddc8b9274cb41bb4d9d4d5c425b6020c50c46f25559911905610b4a88" + +[[package]] +name = "winapi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" +dependencies = [ + "winapi-i686-pc-windows-gnu", + "winapi-x86_64-pc-windows-gnu", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" + +[[package]] +name = "winapi-util" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" + +[[package]] +name = "window-vibrancy" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "111e51caca442cafd9bab396628ac4d814880eaea4e63dfd76a12e9f342b5580" +dependencies = [ + "objc2", + "objc2-app-kit", + "objc2-core-foundation", + "objc2-foundation", + "objc2-quartz-core", + "raw-window-handle", + "windows-sys 0.61.2", + "windows-version", +] + +[[package]] +name = "windows" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580" +dependencies = [ + "windows-collections", + "windows-core", + "windows-future", + "windows-numerics", +] + +[[package]] +name = "windows-collections" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610" +dependencies = [ + "windows-core", +] + +[[package]] +name = "windows-core" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" +dependencies = [ + "windows-implement", + "windows-interface", + "windows-link", + "windows-result", + "windows-strings", +] + +[[package]] +name = "windows-future" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb" +dependencies = [ + "windows-core", + "windows-link", + "windows-threading", +] + +[[package]] +name = "windows-implement" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-interface" +version = "0.59.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-numerics" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26" +dependencies = [ + "windows-core", + "windows-link", +] + +[[package]] +name = "windows-registry" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02752bf7fbdcce7f2a27a742f798510f3e5ad88dbe84871e5168e2120c3d5720" +dependencies = [ + "windows-link", + "windows-result", + "windows-strings", +] + +[[package]] +name = "windows-result" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-strings" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-sys" +version = "0.45.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75283be5efb2831d37ea142365f009c02ec203cd29a3ebecbc093d52315b66d0" +dependencies = [ + "windows-targets 0.42.2", +] + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets 0.52.6", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-targets" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e5180c00cd44c9b1c88adb3693291f1cd93605ded80c250a75d472756b4d071" +dependencies = [ + "windows_aarch64_gnullvm 0.42.2", + "windows_aarch64_msvc 0.42.2", + "windows_i686_gnu 0.42.2", + "windows_i686_msvc 0.42.2", + "windows_x86_64_gnu 0.42.2", + "windows_x86_64_gnullvm 0.42.2", + "windows_x86_64_msvc 0.42.2", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm 0.52.6", + "windows_aarch64_msvc 0.52.6", + "windows_i686_gnu 0.52.6", + "windows_i686_gnullvm", + "windows_i686_msvc 0.52.6", + "windows_x86_64_gnu 0.52.6", + "windows_x86_64_gnullvm 0.52.6", + "windows_x86_64_msvc 0.52.6", +] + +[[package]] +name = "windows-threading" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-version" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4060a1da109b9d0326b7262c8e12c84df67cc0dbc9e33cf49e01ccc2eb63631" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "597a5118570b68bc08d8d59125332c54f1ba9d9adeedeef5b99b02ba2b0698f8" + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e08e8864a60f06ef0d0ff4ba04124db8b0fb3be5776a5cd47641e942e58c4d43" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c61d927d8da41da96a81f029489353e68739737d3beca43145c8afec9a31a84f" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44d840b6ec649f480a41c8d80f9c65108b92d89345dd94027bfe06ac444d1060" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8de912b8b8feb55c064867cf047dda097f92d51efad5b491dfb98f6bbb70cb36" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26d41b46a36d453748aedef1486d5c7a85db22e56aff34643984ea85514e94a3" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9aec5da331524158c6d1a4ac0ab1541149c0b9505fde06423b02f5ef0106b9f0" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "winnow" +version = "0.5.40" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f593a95398737aeed53e489c785df13f3618e41dbcd6718c6addbf1395aa6876" +dependencies = [ + "memchr", +] + +[[package]] +name = "winnow" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c3b93199df0ab874cdf0c6a94f0a0dc3423fe41f1cafb62b8bd7b1deb277aef" +dependencies = [ + "memchr", +] + +[[package]] +name = "winreg" +version = "0.56.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d6f32a0ff4a9f6f01231eb2059cc85479330739333e0e58cadf03b6af2cca10" +dependencies = [ + "cfg-if", + "windows-sys 0.61.2", +] + +[[package]] +name = "wit-bindgen" +version = "0.57.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" + +[[package]] +name = "wl-clipboard-rs" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "959c7ac3b8afde864f7a7448ac16f29b2b83350b7eccbf77fb781c3999aa6848" +dependencies = [ + "libc", + "log", + "os_pipe", + "rustix", + "thiserror 2.0.21", + "tree_magic_mini", + "wayland-backend", + "wayland-client", + "wayland-protocols", + "wayland-protocols-wlr", +] + +[[package]] +name = "writeable" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" + +[[package]] +name = "wry" +version = "0.57.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "759c50ddad0ef9913bb5496cb9d509a50433a3b78cb0238d61105526589cf0e9" +dependencies = [ + "base64 0.23.1", + "block2", + "cookie", + "crossbeam-channel", + "dirs 7.0.0", + "dom_query", + "dpi", + "dunce", + "gdkx11", + "gtk", + "http", + "javascriptcore-rs", + "jni 0.21.1", + "libc", + "ndk", + "objc2", + "objc2-app-kit", + "objc2-core-foundation", + "objc2-foundation", + "objc2-ui-kit", + "objc2-web-kit", + "percent-encoding", + "raw-window-handle", + "sha2", + "soup3", + "tao-macros", + "thiserror 2.0.21", + "url", + "webkit2gtk", + "webkit2gtk-sys", + "webview2-com", + "windows", + "windows-core", + "windows-version", + "x11-dl", +] + +[[package]] +name = "x11" +version = "2.21.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "502da5464ccd04011667b11c435cb992822c2c0dbde1770c988480d312a0db2e" +dependencies = [ + "libc", + "pkg-config", +] + +[[package]] +name = "x11-dl" +version = "2.21.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38735924fedd5314a6e548792904ed8c6de6636285cb9fec04d5b1db85c1516f" +dependencies = [ + "libc", + "once_cell", + "pkg-config", +] + +[[package]] +name = "x11rb" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9993aa5be5a26815fe2c3eacfc1fde061fc1a1f094bf1ad2a18bf9c495dd7414" +dependencies = [ + "gethostname", + "rustix", + "x11rb-protocol", +] + +[[package]] +name = "x11rb-protocol" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea6fc2961e4ef194dcbfe56bb845534d0dc8098940c7e5c012a258bfec6701bd" + +[[package]] +name = "xattr" +version = "1.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "963d6fab92d5504b971dc8bd90ca743c2575e590bc8071ea5bc571598667ae08" +dependencies = [ + "libc", + "rustix", +] + +[[package]] +name = "yoke" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "417ef3fcf6c300b7dbd25c85531a746931c02ad536f3cf4786ed1e88223340b3" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", + "synstructure", +] + +[[package]] +name = "zbus" +version = "5.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5db4be7c075cb421e4b7ee645541604239bd243ba7c357511f4ff3a74b555907" +dependencies = [ + "async-broadcast", + "async-executor", + "async-io", + "async-lock", + "async-process", + "async-recursion", + "async-task", + "async-trait", + "blocking", + "enumflags2", + "event-listener", + "futures-core", + "futures-lite", + "hex", + "libc", + "ordered-stream", + "rustix", + "serde", + "serde_repr", + "tracing", + "uds_windows", + "uuid", + "windows-sys 0.61.2", + "winnow 1.0.5", + "zbus_macros", + "zbus_names", + "zvariant", +] + +[[package]] +name = "zbus_macros" +version = "5.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2990635d09ade6df1868f72f8cac69a876a90981e8bd3c40b1be413f8dc88f40" +dependencies = [ + "proc-macro-crate 3.5.0", + "proc-macro2", + "quote", + "syn 3.0.9", + "zbus_names", + "zvariant", + "zvariant_utils", +] + +[[package]] +name = "zbus_names" +version = "4.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "812a12be4ead7a59e18ea8f047d08add0066b73bc62fc1467066a2472ae088dd" +dependencies = [ + "serde", + "winnow 1.0.5", + "zvariant", +] + +[[package]] +name = "zcheapstr" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "939f186d9ecebe044315a5cb6d6f78568bbc21152adc954d5a0c2f58bdbc9920" +dependencies = [ + "serde", +] + +[[package]] +name = "zerocopy" +version = "0.8.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5fe1f8f1b06191a00962174c61aa5005e0bb391a6d80d07e24d115c01a92ed8" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "863ad3ac83293fb4d740aedbfdc9240dd8d1a50c1099acd76ce80ce7c7230c7f" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", + "synstructure", +] + +[[package]] +name = "zeroize" +version = "1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" + +[[package]] +name = "zerotrie" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f58a2799cfe9a1670c7ea8edbd52ef8edb93cb37a7f83bf31ba9e35d9dae6a40" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3743ddbf47738d929cd1ae2e199d40d0162979dfe31aef8ae646d2bf00bf97a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "zip" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1dcb24d0152526ae49b9b96c1dcf71850ca1e0b882e4e28ed898a93c41334744" +dependencies = [ + "arbitrary", + "crc32fast", + "crossbeam-utils", + "flate2", + "indexmap 2.14.2", + "memchr", + "zopfli", +] + +[[package]] +name = "zip" +version = "9.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eaeb7f16d2605b49aef586996ded29e65642fab7259a3077e537351df6d80426" +dependencies = [ + "crc32fast", + "getrandom 0.4.3", + "indexmap 2.14.2", + "libc", + "memchr", + "nix", + "typed-path", + "windows-sys 0.61.2", +] + +[[package]] +name = "zlib-rs" +version = "0.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112" + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" + +[[package]] +name = "zopfli" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aaf7fc5d30c28483d93805c4a5e12b05bbb52407fa67c5f8bd552374cd01fb11" +dependencies = [ + "bumpalo", + "crc32fast", + "log", + "simd-adler32", +] + +[[package]] +name = "zune-core" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d56377fd46368984a170bc5aac5567e52ca5da874caa60bea39fcbca78fb658b" + +[[package]] +name = "zune-jpeg" +version = "0.5.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27bc9d5b815bc103f142aa054f561d9187d191692ec7c2d1e2b4737f8dbd7296" +dependencies = [ + "zune-core", +] + +[[package]] +name = "zvariant" +version = "5.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "80bf6d6cd6a4b601acb64cfb8284cdc643fcfa75ef26ae3c46ec8aa4e8a1fbb7" +dependencies = [ + "endi", + "enumflags2", + "serde", + "winnow 1.0.5", + "zcheapstr", + "zvariant_derive", + "zvariant_utils", +] + +[[package]] +name = "zvariant_derive" +version = "5.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef2672456ba1cb54b5eaec136e63135b3c7495fb938e53b28a62e633496d486d" +dependencies = [ + "proc-macro-crate 3.5.0", + "proc-macro2", + "quote", + "syn 3.0.9", + "zvariant_utils", +] + +[[package]] +name = "zvariant_utils" +version = "4.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bad0294361a320b694a328460dc73add56c306150f5cb6bfafc44446120008a3" +dependencies = [ + "proc-macro2", + "quote", + "serde", + "syn 3.0.9", + "winnow 1.0.5", +] diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml new file mode 100644 index 0000000..74a7c16 --- /dev/null +++ b/src-tauri/Cargo.toml @@ -0,0 +1,37 @@ +[package] +name = "pyrocade" +version = "0.4.2" +description = "PyroCade emulator front end" +authors = ["Pyrodrifter"] +edition = "2024" + +[lib] +name = "pyrocade_lib" +crate-type = ["staticlib", "cdylib", "rlib"] + +[build-dependencies] +tauri-build = { version = "2", features = [] } + +[dependencies] +anyhow = "1" +chrono = { version = "0.4", features = ["serde"] } +dirs = "6" +futures-util = "0.3" +image = { version = "0.25", default-features = false, features = ["png", "jpeg", "webp", "gif"] } +md5 = "0.7" +quick-xml = "0.37" +regex = "1" +reqwest = { version = "0.12", default-features = false, features = ["json", "stream", "rustls-tls"] } +serde = { version = "1", features = ["derive"] } +serde_json = "1" +tauri = { version = "2", features = ["protocol-asset"] } +tauri-plugin-clipboard-manager = "2" +tauri-plugin-dialog = "2" +tauri-plugin-opener = "2" +tauri-plugin-process = "2" +tauri-plugin-updater = "2" +tokio = { version = "1", features = ["fs", "macros", "process", "rt-multi-thread", "sync", "time"] } +url = "2" +uuid = { version = "1", features = ["v4"] } +walkdir = "2" +zip = { version = "2", default-features = false, features = ["deflate"] } diff --git a/src-tauri/build.rs b/src-tauri/build.rs new file mode 100644 index 0000000..99a3747 --- /dev/null +++ b/src-tauri/build.rs @@ -0,0 +1,6 @@ +fn main() { + // The renderer is embedded at compile time, so a renderer-only edit needs a crate rebuild + // to reach the binary; without this cargo reuses the previous embed and ships stale UI. + println!("cargo:rerun-if-changed=../renderer"); + tauri_build::build() +} diff --git a/src-tauri/capabilities/default.json b/src-tauri/capabilities/default.json new file mode 100644 index 0000000..5c8d2da --- /dev/null +++ b/src-tauri/capabilities/default.json @@ -0,0 +1,7 @@ +{ + "$schema": "../gen/schemas/desktop-schema.json", + "identifier": "default", + "description": "PyroCade desktop window permissions", + "windows": ["main"], + "permissions": ["core:default"] +} diff --git a/src-tauri/src/artwork.rs b/src-tauri/src/artwork.rs new file mode 100644 index 0000000..5a79dc9 --- /dev/null +++ b/src-tauri/src/artwork.rs @@ -0,0 +1,3810 @@ +use crate::backend::{AppState, Game}; +use image::GenericImageView; +use serde_json::{Value, json}; +use std::collections::{HashMap, HashSet, VecDeque}; +use std::fs::{self, OpenOptions}; +use std::io::{BufReader, Cursor, Read, Write}; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Mutex, OnceLock, RwLock}; +use std::time::{Duration, Instant}; +use tauri::{AppHandle, Emitter, Manager, State}; +use tauri_plugin_dialog::DialogExt; +use tauri_plugin_opener::OpenerExt; +use url::Url; + +const LIBRETRO: &str = "https://thumbnails.libretro.com"; +const SWITCH_DATABASE: &str = "https://www.gametdb.com/switchtdb.txt?LANG=EN"; +const SWITCH_IMAGES: &str = "https://art.gametdb.com/switch"; +const MARIOWIKI: &str = "https://www.mariowiki.com"; +const MARIOWIKI_IMAGES: &str = "https://mario.wiki.gallery"; +const ARCHIVE_API: &str = "https://archive.org"; +const ARCHIVE_IIIF: &str = "https://iiif.archive.org/image/iiif/3"; +const ARCHIVE_COLLECTION: &str = "softwareboxart"; +const LAUNCHBOX_METADATA: &str = "https://gamesdb.launchbox-app.com/Metadata.zip"; +const LAUNCHBOX_IMAGES: &str = "https://images.launchbox-app.com"; +const SCREENSCRAPER_API: &str = "https://api.screenscraper.fr/api2"; +const SCREENSCRAPER_SOFTNAME: &str = "PyroCade"; +// LAUNCHBOX_INDEX_VERSION is the LaunchBox index schema version; a different on-disk version rebuilds from the database download. +const LAUNCHBOX_INDEX_VERSION: u64 = 2; +// LAUNCHBOX_KEEP bounds front files kept per game, so the cached index stays small. +const LAUNCHBOX_KEEP: usize = 6; +// SCREENSCRAPER_CRC_LIMIT bounds checksum hashing to cartridge-sized ROMs; larger disc images are matched by name and size. +const SCREENSCRAPER_CRC_LIMIT: u64 = 64 * 1024 * 1024; +// USER_AGENT stays PyroCade-Frontend: the branch host and the web sources share it. +const USER_AGENT: &str = "PyroCade-Frontend"; +const WEB_CACHE_AGE_SECS: u64 = 30 * 86400; +const ARCHIVE_INDEX_VERSION: u64 = 2; +const ARCHIVE_MAX_FILE_BYTES: u64 = 19 * 1024 * 1024; +// MAX_ARTWORK_PIXELS caps one image at 40 million pixels, because compressed bytes do not bound decoded memory. +const MAX_ARTWORK_PIXELS: u64 = 40_000_000; +// MAX_SWITCH_CODES bounds title collisions, because each match multiplies remote requests. +const MAX_SWITCH_CODES: usize = 4; +// MANUAL_MAX_BYTES caps one manual PDF; manuals are PDF files, not images. +const MANUAL_MAX_BYTES: usize = 150 * 1024 * 1024; +const TYPES: &[(&str, &str, Option<&str>)] = &[ + ("front", "covers", Some("Named_Boxarts")), + ("frontHQ", "cover-hq", None), + ("screenshot", "screenshots", Some("Named_Snaps")), + ("title", "titlescreens", Some("Named_Titles")), + ("back", "backcovers", Some("Named_Boxarts")), + ("spine", "spines", None), + ("disc", "discs", Some("Named_Titles")), + ("fanart", "fanart", None), + ("manual", "manuals", None), +]; + +#[derive(Default)] +pub struct ArtworkControl { + job: Option, + cancelled: Option>, +} + +#[tauri::command] +pub async fn fetch_art( + state: State<'_, AppState>, + sys_id: String, + base: String, + options: Option, +) -> Result { + let game = state + .games + .read() + .map_err(|e| e.to_string())? + .iter() + .find(|g| g.system == sys_id && g.base == base) + .cloned() + .ok_or_else(|| "Game is no longer in your library. Rescan and try again.".to_owned())?; + let config = state.config(); + let types = if options + .as_ref() + .and_then(|o| o.get("hq")) + .and_then(Value::as_bool) + .unwrap_or(false) + { + vec!["frontHQ".to_owned()] + } else { + vec!["front".to_owned(), "screenshot".to_owned()] + }; + let retry_missing = options + .as_ref() + .and_then(|o| o.get("retryMissing")) + .and_then(Value::as_bool) + .unwrap_or(false); + let refreshed_indexes = Arc::new(Mutex::new(HashSet::new())); + // Automatic lookups reuse a cached LaunchBox index; only the Artwork page may build it. + let result = download_game( + &state.app, + &game, + &types, + &config, + &state.data_dir, + None, + retry_missing, + &refreshed_indexes, + false, + ) + .await; + update_game_media(&state.games, &game.id, &result); + Ok(result.get("media").cloned().unwrap_or_else(|| json!({}))) +} + +#[tauri::command] +pub fn artwork_status(state: State<'_, AppState>) -> Option { + state.artwork.lock().ok()?.job.clone() +} + +#[tauri::command] +pub fn cancel_artwork_download(app: AppHandle, state: State<'_, AppState>) -> Option { + let mut control = state.artwork.lock().ok()?; + if control + .job + .as_ref() + .and_then(|j| j.get("status")) + .and_then(Value::as_str) + == Some("running") + { + if let Some(cancelled) = &control.cancelled { + cancelled.store(true, Ordering::Relaxed); + } + if let Some(job) = control.job.as_mut() { + job["status"] = Value::String("cancelling".to_owned()); + } + emit_job(&app, &mut control, None, true); + } + control.job.clone() +} + +#[tauri::command] +pub fn start_artwork_download( + app: AppHandle, + state: State<'_, AppState>, + options: Value, +) -> Result { + let mut control = state.artwork.lock().map_err(|e| e.to_string())?; + if control + .job + .as_ref() + .and_then(|j| j.get("status")) + .and_then(Value::as_str) + .is_some_and(|s| s == "running" || s == "cancelling") + { + return Err("An artwork download is already running".to_owned()); + } + let scope = options + .get("scope") + .and_then(Value::as_str) + .unwrap_or_default(); + if !["game", "system", "library"].contains(&scope) { + return Err("Choose a download scope".to_owned()); + } + let known: HashSet<&str> = TYPES.iter().map(|(kind, _, _)| *kind).collect(); + let types: Vec = options + .get("types") + .and_then(Value::as_array) + .into_iter() + .flatten() + .filter_map(Value::as_str) + .filter(|kind| known.contains(*kind)) + .map(str::to_owned) + .collect(); + if types.is_empty() { + return Err("Choose at least one artwork type".to_owned()); + } + let retry_missing = options + .get("retryMissing") + .and_then(Value::as_bool) + .unwrap_or(false); + let all_games = state.games.read().map_err(|e| e.to_string())?.clone(); + let games: Vec = all_games + .into_iter() + .filter(|game| match scope { + "game" => options.get("gameId").and_then(Value::as_str) == Some(&game.id), + "system" => options.get("systemId").and_then(Value::as_str) == Some(&game.system), + _ => true, + }) + .collect(); + if games.is_empty() { + return Err("No games found. Add a ROM folder and rescan your library first.".to_owned()); + } + let cancel = Arc::new(AtomicBool::new(false)); + control.cancelled = Some(cancel.clone()); + control.job = Some(json!({ + "id":uuid::Uuid::new_v4().to_string(),"seq":0,"status":"running","scope":scope,"types":types, + "total":games.len(),"completed":0,"downloaded":0,"existing":0,"missing":0,"unsupported":0,"errors":0, + "lastTitle":"Preparing download…","entries":[],"startedAt":chrono::Utc::now().timestamp_millis() + })); + emit_job(&app, &mut control, None, true); + let initial = control.job.clone().expect("job was initialized"); + let types = types.clone(); + drop(control); + + let queue = Arc::new(Mutex::new(VecDeque::from(games))); + let refreshed_indexes = Arc::new(Mutex::new(HashSet::new())); + let config = state.config(); + let data_dir = state.data_dir.clone(); + let game_store = state.games.clone(); + let job_store = state.artwork.clone(); + let app_for_task = app.clone(); + let worker_count = 2; + tauri::async_runtime::spawn(async move { + let mut workers = Vec::new(); + for _ in 0..worker_count { + let queue = queue.clone(); + let cancelled = cancel.clone(); + let config = config.clone(); + let data_dir = data_dir.clone(); + let game_store = game_store.clone(); + let job_store = job_store.clone(); + let app = app_for_task.clone(); + let types = types.clone(); + let refreshed_indexes = refreshed_indexes.clone(); + workers.push(tauri::async_runtime::spawn(async move { + loop { + if cancelled.load(Ordering::Relaxed) { + break; + } + let game = queue.lock().ok().and_then(|mut q| q.pop_front()); + let Some(game) = game else { + break; + }; + if let Ok(mut control) = job_store.lock() { + if let Some(job) = control.job.as_mut() { + job["lastTitle"] = Value::String(game.title.clone()); + } + emit_job(&app, &mut control, None, false); + } + let result = download_game( + &app, + &game, + &types, + &config, + &data_dir, + Some(&cancelled), + retry_missing, + &refreshed_indexes, + true, + ) + .await; + update_game_media(&game_store, &game.id, &result); + if let Ok(mut control) = job_store.lock() { + if let Some(job) = control.job.as_mut() { + increment(job, "completed", 1); + for key in ["downloaded", "existing", "missing"] { + increment(job, key, result[key].as_u64().unwrap_or_default()); + } + increment( + job, + "unsupported", + u64::from(result["unsupported"].as_bool().unwrap_or(false)), + ); + increment( + job, + "errors", + u64::from( + result["errors"].as_array().is_some_and(|e| !e.is_empty()), + ), + ); + let mut entries = + job["entries"].as_array().cloned().unwrap_or_default(); + entries.insert(0, result.clone()); + entries.truncate(8); + job["entries"] = Value::Array(entries); + } + let item = (result["downloaded"].as_u64().unwrap_or_default() > 0) + .then_some(result); + emit_job(&app, &mut control, item, false); + } + } + })); + } + for worker in workers { + let _ = worker.await; + } + if let Ok(mut control) = job_store.lock() { + if let Some(job) = control.job.as_mut() { + job["status"] = Value::String( + if cancel.load(Ordering::Relaxed) { + "cancelled" + } else { + "complete" + } + .to_owned(), + ); + job["finishedAt"] = json!(chrono::Utc::now().timestamp_millis()); + } + emit_job(&app_for_task, &mut control, None, true); + control.cancelled = None; + } + }); + Ok(initial) +} + +#[tauri::command] +pub fn open_artwork_folder(app: AppHandle, state: State<'_, AppState>) -> Result<(), String> { + let path = state.data_dir.join("media"); + fs::create_dir_all(&path).map_err(|e| e.to_string())?; + app.opener() + .open_path(path.to_string_lossy().into_owned(), None::<&str>) + .map_err(|e| e.to_string()) +} + +#[tauri::command] +pub async fn import_artwork( + app: AppHandle, + state: State<'_, AppState>, + options: Value, +) -> Result, String> { + let game_id = options + .get("gameId") + .and_then(Value::as_str) + .ok_or("Select a game in your library first.")?; + let kind = options + .get("kind") + .and_then(Value::as_str) + .ok_or("Choose an artwork type.")?; + if ![ + "front", + "back", + "spine", + "disc", + "screenshot", + "title", + "fanart", + "manual", + ] + .contains(&kind) + { + return Err("Choose an artwork type.".to_owned()); + } + let game = state + .games + .read() + .map_err(|e| e.to_string())? + .iter() + .find(|g| g.id == game_id) + .cloned() + .ok_or("Select a game in your library first.")?; + if kind == "manual" { + let Some(source) = app + .dialog() + .file() + .set_title(format!("Choose the manual for {}", game.title)) + .blocking_pick_file() + .and_then(|p| p.into_path().ok()) + else { + return Ok(None); + }; + let bytes = fs::read(&source).map_err(|e| e.to_string())?; + if !valid_pdf(&bytes) { + return Err(format!( + "{} is not a PDF file.", + source + .file_name() + .and_then(|n| n.to_str()) + .unwrap_or("The chosen file") + )); + } + let base = safe_base(&game.base)?; + let directory = state + .data_dir + .join("media") + .join(&game.system) + .join("manuals"); + fs::create_dir_all(&directory).map_err(|e| e.to_string())?; + let file = directory.join(format!("{base}.pdf")); + if fs::canonicalize(&file).ok() != fs::canonicalize(&source).ok() { + let temporary = file.with_extension("pdf.tmp"); + fs::write(&temporary, bytes).map_err(|e| e.to_string())?; + fs::rename(&temporary, &file).map_err(|e| e.to_string())?; + } + // Manual payloads stay filesystem paths for the native opener and viewer. + let _ = app.asset_protocol_scope().allow_file(&file); + let stored = file.to_string_lossy().into_owned(); + let result = json!({"gameId":game.id,"media":{"manual":stored},"replace":true}); + update_game_media(&state.games, &game.id, &result); + return Ok(Some(result)); + } + let Some(source) = app + .dialog() + .file() + .set_title("Choose artwork image") + .blocking_pick_file() + .and_then(|p| p.into_path().ok()) + else { + return Ok(None); + }; + let bytes = fs::read(source).map_err(|e| e.to_string())?; + let image = image::load_from_memory(&bytes) + .map_err(|_| "Choose a valid image smaller than 40 megapixels.".to_owned())?; + let dimensions = image.dimensions(); + if dimensions.0 == 0 + || dimensions.1 == 0 + || dimensions.0 > 16384 + || dimensions.1 > 16384 + || u64::from(dimensions.0) * u64::from(dimensions.1) > MAX_ARTWORK_PIXELS + { + return Err("Choose a valid image smaller than 40 megapixels.".to_owned()); + } + let mut png = Cursor::new(Vec::new()); + image + .write_to(&mut png, image::ImageFormat::Png) + .map_err(|e| e.to_string())?; + let directory = state + .data_dir + .join("media") + .join(&game.system) + .join(type_folder(kind)); + fs::create_dir_all(&directory).map_err(|e| e.to_string())?; + let file = directory.join(format!("{}.png", safe_base(&game.base)?)); + let temporary = file.with_extension("png.tmp"); + fs::write(&temporary, png.into_inner()).map_err(|e| e.to_string())?; + fs::rename(&temporary, &file).map_err(|e| e.to_string())?; + let _ = app.asset_protocol_scope().allow_file(&file); + let url = Url::from_file_path(&file) + .map_err(|_| "Could not create artwork URL".to_owned())? + .to_string(); + let result = json!({"gameId":game.id,"media":{kind:url},"replace":true}); + update_game_media(&state.games, &game.id, &result); + Ok(Some(result)) +} + +#[tauri::command] +pub fn artwork_sources(state: State<'_, AppState>) -> Value { + let config = state.config(); + let built = fs::metadata(web_cache_file(&state.data_dir, "launchbox-index.json")) + .ok() + .and_then(|m| m.modified().ok()) + .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok()) + .map(|d| d.as_millis() as i64) + .unwrap_or(0); + let section = config.get("screenscraper"); + let field = |key: &str| { + section + .and_then(|s| s.get(key)) + .and_then(Value::as_str) + .unwrap_or("") + .to_owned() + }; + let has_password = !field("password").is_empty(); + let has_dev_password = !field("devPassword").is_empty(); + json!({ + "launchbox": {"built": built}, + "screenscraper": { + "user": field("user"), + "devId": field("devId"), + "hasPassword": has_password, + "hasDevPassword": has_dev_password, + "ready": screenscraper_configured(&config) + } + }) +} + +#[tauri::command] +pub fn set_screenscraper(state: State<'_, AppState>, details: Value) -> Result { + if !details.is_object() { + return Err("Invalid ScreenScraper details".to_owned()); + } + let text = |key: &str| { + details + .get(key) + .and_then(Value::as_str) + .map(|s| s.trim().chars().take(200).collect::()) + }; + let mut current = state.config.write().map_err(|e| e.to_string())?; + let old = current + .get("screenscraper") + .cloned() + .unwrap_or_else(|| json!({})); + let old_field = |key: &str| { + old.get(key) + .and_then(Value::as_str) + .unwrap_or("") + .to_owned() + }; + let clear = details + .get("clear") + .and_then(Value::as_bool) + .unwrap_or(false); + let next_section = if clear { + json!({"user": "", "devId": "", "password": "", "devPassword": ""}) + } else { + let mut next = old.clone(); + if let Some(value) = text("user") { + next["user"] = json!(value); + } + if let Some(value) = text("devId") { + next["devId"] = json!(value); + } + // An empty password field keeps the saved password. + if let Some(value) = text("password") { + if !value.is_empty() { + next["password"] = json!(value); + } + } + if let Some(value) = text("devPassword") { + if !value.is_empty() { + next["devPassword"] = json!(value); + } + } + if next.get("user").is_none() { + next["user"] = json!(old_field("user")); + } + if next.get("devId").is_none() { + next["devId"] = json!(old_field("devId")); + } + if next.get("password").is_none() { + next["password"] = json!(old_field("password")); + } + if next.get("devPassword").is_none() { + next["devPassword"] = json!(old_field("devPassword")); + } + next + }; + current["screenscraper"] = next_section; + let next = crate::config::config_for_save(current.clone(), ¤t)?; + crate::config::save_config(&state.config_path, &next)?; + *current = next; + drop(current); + Ok(artwork_sources(state)) +} + +#[tauri::command] +pub fn manual_url( + app: AppHandle, + state: State<'_, AppState>, + path: String, +) -> Result { + let candidate = Path::new(&path); + let known = path.to_lowercase().ends_with(".pdf") + && candidate.is_file() + && state + .games + .read() + .map(|games| { + games + .iter() + .any(|g| g.media.get("manual").is_some_and(|m| m == &path)) + }) + .unwrap_or(false); + if !known { + return Err("Manual not found.".to_owned()); + } + let _ = app.asset_protocol_scope().allow_file(candidate); + Url::from_file_path(candidate) + .map(|url| url.to_string()) + .map_err(|_| "Manual not found.".to_owned()) +} + +#[cfg(not(target_os = "android"))] +#[tauri::command] +pub async fn find_manuals( + app: AppHandle, + state: State<'_, AppState>, +) -> Result, String> { + let Some(folder) = app + .dialog() + .file() + .blocking_pick_folder() + .and_then(|p| p.into_path().ok()) + else { + return Ok(None); + }; + let mut pdfs: Vec = Vec::new(); + let mut stack = vec![(folder.clone(), 0_u8)]; + while let Some((dir, depth)) = stack.pop() { + let Ok(entries) = fs::read_dir(&dir) else { + continue; + }; + for entry in entries.flatten() { + let p = entry.path(); + if p.is_dir() && depth < 6 { + stack.push((p, depth + 1)); + } else if p.is_file() + && p.extension() + .is_some_and(|e| e.to_string_lossy().eq_ignore_ascii_case("pdf")) + { + pdfs.push(p); + if pdfs.len() >= 20000 { + break; + } + } + } + if pdfs.len() >= 20000 { + break; + } + } + let mut by_key: HashMap> = HashMap::new(); + for p in &pdfs { + let stem = p.file_stem().and_then(|s| s.to_str()).unwrap_or(""); + for key in [manual_loose_key(stem), manual_bare_key(stem)] { + if !key.is_empty() { + by_key.entry(key).or_default().push(p.clone()); + } + } + } + let games = state.games.read().map_err(|e| e.to_string())?.clone(); + let mut matched = Vec::new(); + for game in &games { + if game.media.contains_key("manual") || game.media.get("manual").is_some() { + continue; + } + let names = [game.base.clone(), game.title.clone()]; + let mut seen = HashSet::new(); + let mut options: Vec = Vec::new(); + for name in &names { + for key in [manual_loose_key(name), manual_bare_key(name)] { + if key.is_empty() { + continue; + } + if let Some(paths) = by_key.get(&key) { + for path in paths { + if seen.insert(path.clone()) { + options.push(path.clone()); + } + } + } + } + } + if options.is_empty() { + continue; + } + let config = state.config(); + let system_words: Vec = config + .get("systems") + .and_then(Value::as_array) + .and_then(|systems| { + systems + .iter() + .find(|s| s.get("id").and_then(Value::as_str) == Some(&game.system)) + }) + .map(|s| { + ["name", "id", "libretro"] + .into_iter() + .filter_map(|k| s.get(k).and_then(Value::as_str).map(|v| v.to_lowercase())) + .collect() + }) + .unwrap_or_default(); + let best = options + .iter() + .find(|p| { + let lower = p.to_string_lossy().to_lowercase(); + system_words + .iter() + .any(|w| !w.is_empty() && lower.contains(w)) + }) + .cloned() + .unwrap_or_else(|| options[0].clone()); + let Ok(bytes) = fs::read(&best) else { continue }; + if !valid_pdf(&bytes) { + continue; + } + let Ok(base) = safe_base(&game.base) else { + continue; + }; + let dest = state + .data_dir + .join("media") + .join(&game.system) + .join("manuals") + .join(format!("{base}.pdf")); + if let Some(parent) = dest.parent() { + let _ = fs::create_dir_all(parent); + } + if fs::canonicalize(&dest).ok() == fs::canonicalize(&best).ok() { + let _ = app.asset_protocol_scope().allow_file(&dest); + let stored = dest.to_string_lossy().into_owned(); + let entry = json!({"gameId": game.id, "media": {"manual": stored}, "replace": true}); + update_game_media(&state.games, &game.id, &entry); + matched.push(entry); + continue; + } + let temporary = dest.with_extension("pdf.tmp"); + if fs::write(&temporary, bytes).is_err() { + continue; + } + if fs::rename(&temporary, &dest).is_err() { + let _ = fs::remove_file(&temporary); + continue; + } + let _ = app.asset_protocol_scope().allow_file(&dest); + let stored = dest.to_string_lossy().into_owned(); + let entry = json!({"gameId": game.id, "media": {"manual": stored}, "replace": true}); + update_game_media(&state.games, &game.id, &entry); + matched.push(entry); + } + Ok(Some(json!({"found": pdfs.len(), "matched": matched}))) +} + +#[cfg(target_os = "android")] +#[tauri::command] +pub fn find_manuals(_app: AppHandle, _state: State<'_, AppState>) -> Result, String> { + Err("Manual folder picking needs a document-tree grant; the dialog plugin does not support folder picking on Android." + .to_owned()) +} + +fn valid_pdf(bytes: &[u8]) -> bool { + bytes.len() >= 5 && &bytes[0..5] == b"%PDF-" +} + +fn manual_loose_key(name: &str) -> String { + let cleaned = clean_title_like(name); + let lower = cleaned.to_lowercase(); + let without = regex::Regex::new(r"&|\band\b|\bthe\b") + .unwrap() + .replace_all(&lower, ""); + without + .chars() + .filter(|c| c.is_ascii_alphanumeric()) + .collect() +} + +fn manual_bare_key(name: &str) -> String { + static BRAND: OnceLock = OnceLock::new(); + let brand = BRAND.get_or_init(|| { + regex::Regex::new(r"(?i)^\s*(disney\s*[-•]?\s*pixar|disney|pixar|dreamworks|nickelodeon|nicktoons)('s)?\b[\s:-]*").unwrap() + }); + let cleaned = clean_title_like(name); + if !brand.is_match(&cleaned) { + return String::new(); + } + let stripped = brand.replace(&cleaned, ""); + let key = manual_loose_key(&stripped); + if key.len() >= 6 { key } else { String::new() } +} + +async fn request_pdf( + url: Url, + cancelled: Option<&Arc>, +) -> Result>, String> { + if cancelled.is_some_and(|c| c.load(Ordering::Relaxed)) { + return Err("Cancelled".to_owned()); + } + polite_gap(PoliteSite::ScreenScraper).await; + let response = reqwest::Client::builder() + .user_agent(USER_AGENT) + .timeout(Duration::from_secs(60)) + .build() + .map_err(|e| e.to_string())? + .get(url) + .send() + .await + .map_err(|e| e.to_string())?; + match response.status().as_u16() { + 404 | 410 => return Ok(None), + 429 | 503 => { + return Err("ScreenScraper asked PyroCade to slow down; try again later".to_owned()); + } + status if !response.status().is_success() => { + return Err(format!("ScreenScraper returned HTTP {status}")); + } + _ => {} + } + if response + .content_length() + .is_some_and(|n| n > MANUAL_MAX_BYTES as u64) + { + return Err("Manual is too large".to_owned()); + } + let bytes = response.bytes().await.map_err(|e| e.to_string())?.to_vec(); + if bytes.len() > MANUAL_MAX_BYTES { + return Err("Manual is too large".to_owned()); + } + if !valid_pdf(&bytes) { + return Err("Manual source did not return a PDF".to_owned()); + } + Ok(Some(bytes)) +} + +async fn screenscraper_manual_urls( + game: &Game, + system: u32, + credentials: &ScreenScraperCredentials, + data_dir: &Path, + cancelled: Option<&Arc>, +) -> Result, String> { + let rom_size = fs::metadata(&game.rom_path).map(|meta| meta.len()).ok(); + let crc = rom_size.and_then(|size| screenscraper_crc(game, size)); + let url = screenscraper_lookup_url(game, system, credentials, rom_size, crc); + let Some(data) = screenscraper_json(url, cancelled).await? else { + return Ok(Vec::new()); + }; + let Some(medias) = data + .get("response") + .and_then(|r| r.get("jeu")) + .and_then(|j| j.get("medias")) + .and_then(Value::as_array) + else { + return Ok(Vec::new()); + }; + let file = web_cache_file(data_dir, "screenscraper.json"); + let key = format!("ss-manual/{system}/{}", game.id); + if let Some(cached) = web_cache_get(&file, &key) { + if let Some(urls) = cached.as_array() { + let found: Vec = urls + .iter() + .filter_map(Value::as_str) + .map(str::to_owned) + .collect(); + if !found.is_empty() { + return Ok(found); + } + } + } + let mut candidates: Vec<(u32, String)> = medias + .iter() + .filter(|media| media.get("type").and_then(Value::as_str) == Some("manuel")) + .filter_map(|media| { + let url = media.get("url").and_then(Value::as_str)?; + if !screenscraper_media_url(url) { + return None; + } + let region = media.get("region").and_then(Value::as_str).unwrap_or(""); + Some((screenscraper_region_rank(region), url.to_owned())) + }) + .collect(); + candidates.sort_by_key(|(rank, _)| *rank); + candidates.truncate(6); + let found: Vec = candidates.into_iter().map(|(_, url)| url).collect(); + web_cache_set(&file, &key, json!(found)); + Ok(found) +} + +async fn fetch_screenscraper_manual( + game: &Game, + sys_id: &str, + config: &Value, + data_dir: &Path, + cancelled: Option<&Arc>, +) -> Result>, String> { + let Some(system) = screenscraper_system(sys_id) else { + return Ok(None); + }; + let Some(credentials) = screenscraper_credentials(config) else { + return Ok(None); + }; + let urls = screenscraper_manual_urls(game, system, &credentials, data_dir, cancelled).await?; + for url in urls { + if cancelled.is_some_and(|c| c.load(Ordering::Relaxed)) { + return Err("Cancelled".to_owned()); + } + let parsed = Url::parse(&url).map_err(|e| e.to_string())?; + match request_pdf(parsed, cancelled).await { + Ok(Some(bytes)) => return Ok(Some(bytes)), + Ok(None) => {} + Err(error) => { + if error == "Cancelled" || cancelled.is_some_and(|c| c.load(Ordering::Relaxed)) { + return Err(error); + } + } + } + } + Ok(None) +} + +fn emit_job(app: &AppHandle, control: &mut ArtworkControl, item: Option, force: bool) { + let Some(job) = control.job.as_mut() else { + return; + }; + if !force && item.is_none() { + return; + } + let sequence = job["seq"].as_u64().unwrap_or_default() + 1; + job["seq"] = json!(sequence); + let mut event = job.clone(); + if let Some(item) = item { + event["item"] = item; + } + let _ = app.emit("art:progress", event); +} + +fn increment(value: &mut Value, key: &str, amount: u64) { + let next = value.get(key).and_then(Value::as_u64).unwrap_or_default() + amount; + value[key] = json!(next); +} + +fn update_game_media(store: &Arc>>, game_id: &str, result: &Value) { + let Some(media) = result.get("media").and_then(Value::as_object) else { + return; + }; + let replace = result + .get("replace") + .and_then(Value::as_bool) + .unwrap_or(false); + if let Ok(mut games) = store.write() { + if let Some(game) = games.iter_mut().find(|g| g.id == game_id) { + for (kind, url) in media { + if replace || !game.media.contains_key(kind) { + if let Some(url) = url.as_str() { + game.media.insert(kind.clone(), url.to_owned()); + } + } + } + } + } +} + +async fn download_game( + app: &AppHandle, + game: &Game, + types: &[String], + config: &Value, + data_dir: &Path, + cancelled: Option<&Arc>, + retry_missing: bool, + refreshed_indexes: &Arc>>, + allow_index_download: bool, +) -> Value { + let system = config + .get("systems") + .and_then(Value::as_array) + .into_iter() + .flatten() + .find(|s| s.get("id").and_then(Value::as_str) == Some(&game.system)); + let Some(system) = system else { + return empty_result(game, true); + }; + let switch = system.get("artworkProvider").and_then(Value::as_str) == Some("gametdb-switch"); + let system_id = system + .get("id") + .and_then(Value::as_str) + .unwrap_or("") + .to_owned(); + let fallback = mariowiki_covers(&system_id) + || archive_covers(&system_id) + || launchbox_covers(&system_id) + || screenscraper_covers(&system_id, config); + if !switch && system.get("libretro").and_then(Value::as_str).is_none() && !fallback { + return empty_result(game, true); + } + let base = match safe_base(&game.base) { + Ok(base) => base, + Err(error) => { + return json!({"gameId":game.id,"title":game.title,"media":{},"downloaded":0,"existing":0,"missing":0,"errors":[error],"unsupported":false}); + } + }; + let mut media = serde_json::Map::new(); + let mut downloaded = 0_u64; + let mut existing = 0_u64; + let mut missing = 0_u64; + let mut errors = Vec::new(); + for kind in types { + if cancelled.is_some_and(|c| c.load(Ordering::Relaxed)) { + break; + } + if game.media.contains_key(kind) { + existing += 1; + continue; + } + if kind == "manual" { + let manual_path = data_dir + .join("media") + .join(&game.system) + .join("manuals") + .join(format!("{base}.pdf")); + if manual_path.is_file() { + existing += 1; + let _ = app.asset_protocol_scope().allow_file(&manual_path); + media.insert( + kind.clone(), + Value::String(manual_path.to_string_lossy().into_owned()), + ); + continue; + } + match fetch_screenscraper_manual(game, &system_id, config, data_dir, cancelled).await { + Ok(Some(bytes)) => { + if cancelled.is_some_and(|c| c.load(Ordering::Relaxed)) { + break; + } + match write_new(&manual_path, &bytes) { + Ok(true) => { + downloaded += 1; + let _ = app.asset_protocol_scope().allow_file(&manual_path); + media.insert( + kind.clone(), + Value::String(manual_path.to_string_lossy().into_owned()), + ); + } + Ok(false) => { + existing += 1; + let _ = app.asset_protocol_scope().allow_file(&manual_path); + media.insert( + kind.clone(), + Value::String(manual_path.to_string_lossy().into_owned()), + ); + } + Err(error) => errors.push(error), + } + } + Ok(None) => missing += 1, + Err(_) if cancelled.is_some_and(|c| c.load(Ordering::Relaxed)) => break, + Err(error) => errors.push(error), + } + continue; + } + let Some((_, folder, remote)) = TYPES.iter().find(|(name, _, _)| name == kind) else { + continue; + }; + let path = data_dir + .join("media") + .join(&game.system) + .join(folder) + .join(format!("{base}.png")); + if path.is_file() { + existing += 1; + // Cached media enters the asset scope before its file:// reaches the renderer. + let _ = app.asset_protocol_scope().allow_file(&path); + if let Ok(url) = Url::from_file_path(&path) { + media.insert(kind.clone(), Value::String(url.to_string())); + } + continue; + } + let primary = if switch { + fetch_switch_image( + system, + game, + kind, + data_dir, + cancelled, + retry_missing, + refreshed_indexes, + ) + .await + } else if let Some(remote) = remote { + fetch_libretro_image( + system, + &base, + kind, + remote, + data_dir, + cancelled, + retry_missing, + refreshed_indexes, + ) + .await + } else { + Ok(None) + }; + // Front covers only, after the existing providers, never replacing an existing cover: + // the media/file checks above already returned `existing`, so a fallback here can only fill a gap. + let result = if kind == "front" + && !matches!(primary, Ok(Some(_))) + && !cancelled.is_some_and(|c| c.load(Ordering::Relaxed)) + { + let mut primary_error: Option = None; + let mut primary_cancelled = false; + if let Err(error) = primary { + if error == "Cancelled" || cancelled.is_some_and(|c| c.load(Ordering::Relaxed)) { + primary_cancelled = true; + } else { + primary_error = Some(error); + } + } + let mariowiki_refresh = + refresh_index(retry_missing, refreshed_indexes, "mariowiki".to_owned()); + let mut outcome: Option>, String>> = None; + if primary_cancelled { + outcome = Some(Err("Cancelled".to_owned())); + } + if outcome.is_none() && mariowiki_covers(&system_id) { + let wiki = + fetch_mariowiki_image(game, &system_id, data_dir, cancelled, mariowiki_refresh) + .await; + match wiki { + Ok(Some(bytes)) => outcome = Some(Ok(Some(bytes))), + Ok(None) => {} + Err(error) => { + if error == "Cancelled" + || cancelled.is_some_and(|c| c.load(Ordering::Relaxed)) + { + outcome = Some(Err(error)); + } else if primary_error.is_none() { + primary_error = Some(error); + } + } + } + } + if outcome.is_none() + && !cancelled.is_some_and(|c| c.load(Ordering::Relaxed)) + && archive_covers(&system_id) + { + let archive_refresh = refresh_index( + retry_missing, + refreshed_indexes, + "internet-archive".to_owned(), + ); + let archive = fetch_internet_archive_image( + game, + &system_id, + data_dir, + cancelled, + archive_refresh, + ) + .await; + match archive { + Ok(Some(bytes)) => outcome = Some(Ok(Some(bytes))), + Ok(None) => {} + Err(error) => { + if error == "Cancelled" + || cancelled.is_some_and(|c| c.load(Ordering::Relaxed)) + { + outcome = Some(Err(error)); + } else if primary_error.is_none() { + primary_error = Some(error); + } + } + } + } + if outcome.is_none() + && !cancelled.is_some_and(|c| c.load(Ordering::Relaxed)) + && launchbox_covers(&system_id) + { + let launchbox_refresh = + refresh_index(retry_missing, refreshed_indexes, "launchbox".to_owned()); + let launchbox = fetch_launchbox_image( + game, + &system_id, + data_dir, + cancelled, + launchbox_refresh, + allow_index_download, + ) + .await; + match launchbox { + Ok(Some(bytes)) => outcome = Some(Ok(Some(bytes))), + Ok(None) => {} + Err(error) => { + if error == "Cancelled" + || cancelled.is_some_and(|c| c.load(Ordering::Relaxed)) + { + outcome = Some(Err(error)); + } else if primary_error.is_none() { + primary_error = Some(error); + } + } + } + } + if outcome.is_none() + && !cancelled.is_some_and(|c| c.load(Ordering::Relaxed)) + && screenscraper_covers(&system_id, config) + { + let screenscraper_refresh = + refresh_index(retry_missing, refreshed_indexes, "screenscraper".to_owned()); + let screenscraper = fetch_screenscraper_image( + game, + &system_id, + config, + data_dir, + cancelled, + screenscraper_refresh, + ) + .await; + match screenscraper { + Ok(Some(bytes)) => outcome = Some(Ok(Some(bytes))), + Ok(None) => {} + Err(error) => { + if error == "Cancelled" + || cancelled.is_some_and(|c| c.load(Ordering::Relaxed)) + { + outcome = Some(Err(error)); + } else if primary_error.is_none() { + primary_error = Some(error); + } + } + } + } + match outcome { + Some(Ok(Some(bytes))) => Ok(Some(bytes)), + Some(Err(error)) => Err(error), + Some(Ok(None)) => match primary_error { + Some(error) => Err(error), + None => Ok(None), + }, + None => match primary_error { + Some(error) => Err(error), + None => Ok(None), + }, + } + } else { + primary + }; + match result { + Ok(Some(bytes)) => { + if cancelled.is_some_and(|c| c.load(Ordering::Relaxed)) { + break; + } + match write_new(&path, &bytes) { + Ok(true) => downloaded += 1, + Ok(false) => existing += 1, + Err(error) => { + errors.push(error); + continue; + } + } + // Fresh files enter the asset scope before their file:// is handed out. + let _ = app.asset_protocol_scope().allow_file(&path); + if let Ok(url) = Url::from_file_path(&path) { + media.insert(kind.clone(), Value::String(url.to_string())); + } + } + Ok(None) => missing += 1, + Err(_) if cancelled.is_some_and(|c| c.load(Ordering::Relaxed)) => break, + Err(error) => errors.push(error), + } + } + json!({"gameId":game.id,"title":game.title,"media":media,"downloaded":downloaded,"existing":existing,"missing":missing,"errors":errors,"unsupported":false}) +} + +fn empty_result(game: &Game, unsupported: bool) -> Value { + json!({"gameId":game.id,"title":game.title,"media":{},"downloaded":0,"existing":0,"missing":0,"errors":[],"unsupported":unsupported}) +} + +async fn fetch_libretro_image( + system: &Value, + base: &str, + kind: &str, + remote: &str, + data_dir: &Path, + cancelled: Option<&Arc>, + retry_missing: bool, + refreshed_indexes: &Arc>>, +) -> Result>, String> { + let category = system + .get("libretro") + .and_then(Value::as_str) + .ok_or("Artwork system is missing its Libretro name")?; + let dir = data_dir.join("media").join("_index"); + let file = dir.join(format!( + "{}-{}.json", + system.get("id").and_then(Value::as_str).unwrap_or("system"), + kind + )); + let system_id = system.get("id").and_then(Value::as_str).unwrap_or("system"); + let refresh = refresh_index( + retry_missing, + refreshed_indexes, + format!("{system_id}/{kind}"), + ); + let mut cached_files = vec![file.clone()]; + if kind == "front" { + cached_files.push(dir.join(format!("{system_id}.json"))); + } + let cached_names = if refresh { + None + } else { + cached_files.into_iter().find_map(|cached| { + let fresh = cached + .metadata() + .ok() + .and_then(|m| m.modified().ok()) + .and_then(|t| t.elapsed().ok()) + .is_some_and(|age| age.as_secs() < 30 * 86400); + if !fresh { + return None; + } + fs::read_to_string(cached) + .ok() + .and_then(|s| serde_json::from_str::>(&s).ok()) + }) + }; + let names = match cached_names { + Some(names) => names, + None => { + let mut url = Url::parse(&format!("{LIBRETRO}/")).map_err(|e| e.to_string())?; + url.path_segments_mut() + .map_err(|_| "Invalid artwork URL".to_owned())? + .push(category) + .push(remote); + let text = request_text(url, cancelled).await?.unwrap_or_default(); + let regex = regex::Regex::new(r#"href="([^"?]*?\.png)""#).unwrap(); + let names: Vec = regex + .captures_iter(&text) + .filter_map(|c| c.get(1).map(|m| m.as_str().to_owned())) + .filter(|name| Path::new(name).file_name().and_then(|n| n.to_str()) == Some(name)) + .collect(); + if !text.is_empty() && names.is_empty() { + return Err(format!("Could not read the {remote} artwork list")); + } + fs::create_dir_all(&dir).map_err(|e| e.to_string())?; + fs::write( + &file, + serde_json::to_vec(&names).map_err(|e| e.to_string())?, + ) + .map_err(|e| e.to_string())?; + names + } + }; + let mut names = names; + names.sort_by_key(|name| artwork_region_rank(name)); + let wanted = loose_key(base); + let name = names + .into_iter() + .find(|name| loose_key(name.trim_end_matches(".png")) == wanted); + let Some(name) = name else { + return Ok(None); + }; + let mut url = Url::parse(&format!("{LIBRETRO}/")).map_err(|e| e.to_string())?; + url.path_segments_mut() + .map_err(|_| "Invalid artwork URL".to_owned())? + .push(category) + .push(remote) + .push(&name); + request_image(url, cancelled).await +} + +async fn fetch_switch_image( + system: &Value, + game: &Game, + kind: &str, + data_dir: &Path, + cancelled: Option<&Arc>, + retry_missing: bool, + refreshed_indexes: &Arc>>, +) -> Result>, String> { + if !["front", "frontHQ", "disc", "back"].contains(&kind) { + return Ok(None); + } + let file = data_dir.join("media/_index/gametdb-switch.txt"); + let refresh = refresh_index( + retry_missing, + refreshed_indexes, + "gametdb-switch".to_owned(), + ); + let cached_text = if refresh { + None + } else if file + .metadata() + .ok() + .and_then(|m| m.modified().ok()) + .and_then(|t| t.elapsed().ok()) + .is_some_and(|age| age.as_secs() < 7 * 86400) + { + fs::read_to_string(&file).ok() + } else { + None + }; + let text = match cached_text { + Some(text) => text, + None => { + let text = request_text( + Url::parse(SWITCH_DATABASE).map_err(|e| e.to_string())?, + cancelled, + ) + .await? + .ok_or("Could not read the GameTDB Switch title list")?; + if !text.contains("TITLES =") { + return Err("Could not read the GameTDB Switch title list".to_owned()); + } + fs::create_dir_all(file.parent().unwrap()).map_err(|e| e.to_string())?; + fs::write(&file, &text).map_err(|e| e.to_string())?; + text + } + }; + let clean = |s: &str| { + regex::Regex::new(r"\bv?\d+(?:\.\d+)+\b|\s*\([^)]*\)|\s*\[[^]]*\]") + .unwrap() + .replace_all(s, "") + .to_string() + }; + let keys = [ + loose_key(&clean(&game.title)), + loose_key(&clean(&game.base)), + ]; + let line_re = regex::Regex::new(r"(?m)^([A-Z0-9]{5}) = (.+)$").unwrap(); + let mut codes = Vec::new(); + for capture in line_re.captures_iter(&text) { + let Some(title) = capture.get(2).map(|m| m.as_str()) else { + continue; + }; + let Some(code) = capture.get(1).map(|m| m.as_str()) else { + continue; + }; + if keys.contains(&loose_key(title)) && !codes.iter().any(|seen| seen == code) { + codes.push(code.to_owned()); + if codes.len() == MAX_SWITCH_CODES { + break; + } + } + } + let category = match kind { + "frontHQ" => "coverHQ", + "front" => "cover", + "back" => "backHQ", + _ => "label", + }; + let extension = if kind == "disc" { "png" } else { "jpg" }; + for code in codes { + for region in ["US", "EN", "JA"] { + if cancelled.is_some_and(|c| c.load(Ordering::Relaxed)) { + return Err("Cancelled".to_owned()); + } + let url = Url::parse(&format!( + "{SWITCH_IMAGES}/{category}/{region}/{code}.{extension}" + )) + .map_err(|e| e.to_string())?; + if let Some(bytes) = request_image(url, cancelled).await? { + return Ok(Some(bytes)); + } + } + } + let _ = system; + Ok(None) +} + +async fn request_text( + url: Url, + cancelled: Option<&Arc>, +) -> Result, String> { + let Some(bytes) = request_bytes(url, cancelled).await? else { + return Ok(None); + }; + String::from_utf8(bytes) + .map(Some) + .map_err(|e| e.to_string()) +} + +async fn request_image( + url: Url, + cancelled: Option<&Arc>, +) -> Result>, String> { + let Some(bytes) = request_bytes(url, cancelled).await? else { + return Ok(None); + }; + let image = image::load_from_memory(&bytes) + .map_err(|_| "Artwork server did not return a valid image".to_owned())?; + let (width, height) = image.dimensions(); + if width == 0 + || height == 0 + || width > 16384 + || height > 16384 + || u64::from(width) * u64::from(height) > MAX_ARTWORK_PIXELS + { + return Err("Invalid artwork dimensions".to_owned()); + } + let mut output = Cursor::new(Vec::new()); + image + .write_to(&mut output, image::ImageFormat::Png) + .map_err(|e| e.to_string())?; + Ok(Some(output.into_inner())) +} + +async fn request_bytes( + url: Url, + cancelled: Option<&Arc>, +) -> Result>, String> { + if cancelled.is_some_and(|c| c.load(Ordering::Relaxed)) { + return Err("Cancelled".to_owned()); + } + let response = reqwest::Client::builder() + .user_agent(USER_AGENT) + .timeout(std::time::Duration::from_secs(18)) + .build() + .map_err(|e| e.to_string())? + .get(url) + .send() + .await + .map_err(|e| e.to_string())?; + if response.status().as_u16() == 404 { + return Ok(None); + } + if !response.status().is_success() { + return Err(format!( + "Artwork server returned HTTP {}", + response.status() + )); + } + if response + .content_length() + .is_some_and(|n| n > 20 * 1024 * 1024) + { + return Err("Artwork image is too large".to_owned()); + } + let bytes = response.bytes().await.map_err(|e| e.to_string())?; + if bytes.len() > 20 * 1024 * 1024 { + return Err("Artwork image is too large".to_owned()); + } + Ok(Some(bytes.to_vec())) +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum PoliteSite { + MarioWiki, + Archive, + LaunchBox, + ScreenScraper, +} + +fn polite_last(site: PoliteSite) -> &'static Mutex> { + static MARIO_LAST: OnceLock>> = OnceLock::new(); + static ARCHIVE_LAST: OnceLock>> = OnceLock::new(); + static LAUNCHBOX_LAST: OnceLock>> = OnceLock::new(); + static SCREENSCRAPER_LAST: OnceLock>> = OnceLock::new(); + match site { + PoliteSite::MarioWiki => MARIO_LAST.get_or_init(|| Mutex::new(None)), + PoliteSite::Archive => ARCHIVE_LAST.get_or_init(|| Mutex::new(None)), + PoliteSite::LaunchBox => LAUNCHBOX_LAST.get_or_init(|| Mutex::new(None)), + PoliteSite::ScreenScraper => SCREENSCRAPER_LAST.get_or_init(|| Mutex::new(None)), + } +} + +async fn polite_gap(site: PoliteSite) { + loop { + let now = Instant::now(); + let wait = { + let mut guard = polite_last(site).lock().unwrap(); + match *guard { + Some(last) => { + let eligible = last + Duration::from_secs(1); + if now < eligible { + Some(eligible - now) + } else { + *guard = Some(now); + None + } + } + None => { + *guard = Some(now); + None + } + } + }; + if let Some(d) = wait { + tokio::time::sleep(d).await; + } else { + break; + } + } +} + +async fn polite_bytes( + url: Url, + site: PoliteSite, + site_name: &'static str, + cancelled: Option<&Arc>, +) -> Result>, String> { + if cancelled.is_some_and(|c| c.load(Ordering::Relaxed)) { + return Err("Cancelled".to_owned()); + } + polite_gap(site).await; + if cancelled.is_some_and(|c| c.load(Ordering::Relaxed)) { + return Err("Cancelled".to_owned()); + } + let response = reqwest::Client::builder() + .user_agent(USER_AGENT) + .timeout(Duration::from_secs(20)) + .build() + .map_err(|e| e.to_string())? + .get(url) + .send() + .await + .map_err(|e| e.to_string())?; + let status = response.status().as_u16(); + if status == 404 || status == 410 { + return Ok(None); + } + if status == 429 || status == 503 { + return Err(format!( + "{site_name} asked PyroCade to slow down (HTTP {status}); try again later" + )); + } + if !response.status().is_success() { + return Err(format!("{site_name} returned HTTP {}", response.status())); + } + let bytes = response.bytes().await.map_err(|e| e.to_string())?; + if bytes.len() > 25 * 1024 * 1024 { + return Err(format!("{site_name} sent an unreadable reply")); + } + Ok(Some(bytes.to_vec())) +} + +async fn polite_text( + url: Url, + site: PoliteSite, + site_name: &'static str, + cancelled: Option<&Arc>, +) -> Result, String> { + let Some(bytes) = polite_bytes(url, site, site_name, cancelled).await? else { + return Ok(None); + }; + String::from_utf8(bytes) + .map(Some) + .map_err(|e| e.to_string()) +} + +async fn polite_json( + url: Url, + site: PoliteSite, + site_name: &'static str, + cancelled: Option<&Arc>, +) -> Result, String> { + let Some(bytes) = polite_bytes(url, site, site_name, cancelled).await? else { + return Ok(None); + }; + serde_json::from_slice(&bytes) + .map(Some) + .map_err(|_| format!("{site_name} sent an unreadable reply")) +} + +fn web_cache_file(data_dir: &Path, name: &str) -> PathBuf { + data_dir.join("media").join("_index").join(name) +} + +fn web_cache_lock() -> &'static Mutex<()> { + static LOCK: OnceLock> = OnceLock::new(); + LOCK.get_or_init(|| Mutex::new(())) +} + +fn read_web_cache(file: &Path) -> serde_json::Map { + let Ok(text) = fs::read_to_string(file) else { + return serde_json::Map::new(); + }; + let Ok(parsed) = serde_json::from_str::(&text) else { + return serde_json::Map::new(); + }; + parsed.as_object().cloned().unwrap_or_default() +} + +fn web_cache_get(file: &Path, key: &str) -> Option { + let _guard = web_cache_lock().lock().unwrap(); + let cache = read_web_cache(file); + let entry = cache.get(key)?; + let at = entry.get("at").and_then(Value::as_i64)?; + let now = chrono::Utc::now().timestamp_millis(); + if now - at < 0 || (now - at) as u64 >= WEB_CACHE_AGE_SECS * 1000 { + return None; + } + entry.get("value").cloned() +} + +fn web_cache_set(file: &Path, key: &str, value: Value) { + let _guard = web_cache_lock().lock().unwrap(); + let mut cache = read_web_cache(file); + cache.insert( + key.to_owned(), + json!({"at": chrono::Utc::now().timestamp_millis(), "value": value}), + ); + if let Some(parent) = file.parent() { + let _ = fs::create_dir_all(parent); + } + let tmp = file.with_extension("json.tmp"); + if let Ok(text) = serde_json::to_string(&cache) { + if fs::write(&tmp, text).is_ok() { + let _ = fs::rename(&tmp, file); + } + } +} + +fn untrusted_re() -> &'static regex::Regex { + static RE: OnceLock = OnceLock::new(); + RE.get_or_init(|| regex::Regex::new(r"(?i)\([^)]*\b(?:demo|beta|proto|prototype|sample|kiosk|hack|modification|unl|unlicensed|pirate|aftermarket|homebrew)\b[^)]*\)|\[h\d*[^\]]*\]").unwrap()) +} + +fn trusted_release(base: &str) -> bool { + !untrusted_re().is_match(base) +} + +fn without_version(key: &str) -> String { + regex::Regex::new(r"(?i)version") + .unwrap() + .replace_all(key, "") + .into_owned() +} + +fn region_of(text: &str) -> &'static str { + let mut groups: Vec = Vec::new(); + groups.extend( + regex::Regex::new(r"\([^)]*\)") + .unwrap() + .find_iter(text) + .map(|m| m.as_str().to_owned()), + ); + groups.extend( + regex::Regex::new(r"\[[^\]]*\]") + .unwrap() + .find_iter(text) + .map(|m| m.as_str().to_owned()), + ); + let s = groups.join(" "); + if regex::Regex::new(r"(?i)\b(USA?|U|NTSC-U|Canada|North America)\b|-USA\b|\(UE?\)") + .unwrap() + .is_match(&s) + { + return "us"; + } + if regex::Regex::new(r"(?i)\b(Europe|EUR?|E|PAL|UK|UKV|NOE|FRA|ESP|Spain|Germany|France|Italy|Australia|World)\b").unwrap().is_match(&s) { + return "eu"; + } + if regex::Regex::new(r"(?i)\b(Japan|JPN?|J)\b") + .unwrap() + .is_match(&s) + { + return "jp"; + } + "" +} + +fn franchise_matches(text: &str) -> bool { + regex::Regex::new(r"(?i)\b(mario|luigi|yoshi|wario|waluigi|peach|bowser|toad|donkey kong|diddy kong|smash bros|game & watch|nes remix|wrecking crew|picross)").unwrap().is_match(text) +} + +fn clean_title_like(name: &str) -> String { + let value = regex::Regex::new(r"\s*[\(\[][^\)\]]*[\)\]]") + .unwrap() + .replace_all(name, "") + .replace('_', " "); + let value = regex::Regex::new(r"^\d{3,5}\s*-?\s+") + .unwrap() + .replace(&value, ""); + let value = regex::Regex::new(r"(?i)\s*\b(decrypted|encrypted)\b\s*$") + .unwrap() + .replace(&value, ""); + let cleaned = regex::Regex::new(r"\s+") + .unwrap() + .replace_all(&value, " ") + .trim() + .to_owned(); + if cleaned.is_empty() { + name.to_owned() + } else { + cleaned + } +} + +fn fallback_key(value: &str) -> String { + let cleaned = clean_title_like(value); + let lower = cleaned.to_lowercase(); + let without = regex::Regex::new(r"&|\band\b|\bthe\b") + .unwrap() + .replace_all(&lower, ""); + without + .chars() + .filter(|c| c.is_ascii_alphanumeric()) + .collect() +} + +fn artwork_title_keys(game: &Game) -> Vec { + let mut keys = Vec::new(); + for source in [&game.title, &game.base] { + if source.is_empty() { + continue; + } + let cleaned = regex::Regex::new(r"\bv?\d+(?:\.\d+)+\b|\s*\([^)]*\)|\s*\[[^\]]*\]") + .unwrap() + .replace_all(source, "") + .into_owned(); + keys.push(fallback_key(&cleaned)); + let split = regex::Regex::new(r"([a-z])([A-Z])") + .unwrap() + .replace_all(&cleaned, "$1 $2") + .into_owned(); + keys.push(fallback_key(&split)); + } + keys.retain(|k| !k.is_empty()); + keys.dedup(); + keys +} + +fn mariowiki_covers(sys_id: &str) -> bool { + matches!( + sys_id, + "nes" + | "snes" + | "n64" + | "gc" + | "wii" + | "wiiu" + | "switch" + | "switch2" + | "gb" + | "gbc" + | "gba" + | "nds" + | "3ds" + ) +} + +fn mariowiki_system_names(sys_id: &str) -> &'static [&'static str] { + match sys_id { + "nes" => &["Nintendo Entertainment System", "Family Computer"], + "snes" => &["Super Nintendo Entertainment System", "Super Famicom"], + "n64" => &["Nintendo 64"], + "gc" => &["Nintendo GameCube"], + "wii" => &["Wii"], + "wiiu" => &["Wii U"], + "switch" => &["Nintendo Switch"], + "switch2" => &["Nintendo Switch 2"], + "gb" => &["Game Boy"], + "gbc" => &["Game Boy Color"], + "gba" => &["Game Boy Advance"], + "nds" => &["Nintendo DS"], + "3ds" => &["Nintendo 3DS"], + _ => &[], + } +} + +fn wiki_page_names(title: &str) -> Vec { + let stripped = regex::Regex::new(r"\s*\([^)]*\)|\s*\[[^\]]*\]|\s*\{[^}]*\}") + .unwrap() + .replace_all(title, "") + .into_owned(); + let stripped = regex::Regex::new(r"\bv?\d+(?:\.\d+)+\b") + .unwrap() + .replace_all(&stripped, "") + .into_owned(); + let stripped = stripped.replace('_', " "); + let t = regex::Regex::new(r"\s+") + .unwrap() + .replace_all(&stripped, " ") + .trim() + .to_owned(); + if t.is_empty() { + return Vec::new(); + } + let mut out = Vec::new(); + for v in [ + t.clone(), + t.replacen(" - ", ": ", 1), + t.replace(" - ", ": "), + ] { + if !out.contains(&v) { + out.push(v); + } + } + out.truncate(3); + out +} + +fn encode_uri_component(value: &str) -> String { + let mut out = String::new(); + for b in value.bytes() { + let c = b as char; + if c.is_ascii_alphanumeric() + || matches!(c, '-' | '_' | '.' | '!' | '~' | '*' | '\'' | '(' | ')') + { + out.push(c); + } else { + out.push_str(&format!("%{b:02X}")); + } + } + out +} + +fn wiki_image_url(file: &str, host: &str) -> String { + let mut name = file.trim().replace(' ', "_"); + if let Some(first) = name.chars().next() { + name = first.to_uppercase().collect::() + &name[first.len_utf8()..]; + } + let hex = format!("{:x}", md5::compute(name.as_bytes())); + format!( + "{host}/images/{}/{}/{}", + &hex[0..1], + &hex[0..2], + encode_uri_component(&name) + ) +} + +fn wiki_page_url(name: &str) -> String { + let underscored = name.replace(' ', "_"); + let encoded = encode_uri_component(&underscored).replace("%2F", "/"); + format!("{MARIOWIKI}/{encoded}?action=raw") +} + +fn infobox_images(text: &str) -> Option> { + if !regex::Regex::new(r"(?i)\{\{\s*game infobox") + .unwrap() + .is_match(text) + { + return None; + } + let line = regex::Regex::new(r"(?im)^\|\s*image\s*=(.*)$") + .unwrap() + .captures(text) + .and_then(|c| c.get(1).map(|m| m.as_str().to_owned())) + .unwrap_or_default(); + let images: Vec = regex::Regex::new(r"(?i)\[\[\s*File\s*:\s*([^\|\]]+)") + .unwrap() + .captures_iter(&line) + .filter_map(|c| c.get(1).map(|m| m.as_str().trim().to_owned())) + .take(3) + .collect(); + Some(images) +} + +fn is_front_cover(file: &str, text: &str, sys_id: &str) -> bool { + let bare = file + .rsplit('.') + .nth(1) + .unwrap_or(file) + .replace(['_', '-'], " "); + if regex::Regex::new(r"(?i)\b(back|rear|spine|side|cart|cartridge|disc|label|manual|logo|screenshot|sticker|card|insert)\b") + .unwrap() + .is_match(&bare) + { + return false; + } + if regex::Regex::new(r"(?i)\bback (cover|box|of the box)\b") + .unwrap() + .is_match(text) + { + return false; + } + let categories: Vec = + regex::Regex::new(r"(?i)\[\[\s*Category\s*:\s*([^\]\|]+?)\s*game covers\s*[\]\|]") + .unwrap() + .captures_iter(text) + .filter_map(|c| c.get(1).map(|m| m.as_str().trim().to_lowercase())) + .collect(); + mariowiki_system_names(sys_id) + .iter() + .any(|name| categories.iter().any(|c| c == &name.to_lowercase())) +} + +async fn wiki_page( + name: &str, + cancelled: Option<&Arc>, +) -> Result, String> { + let url = Url::parse(&wiki_page_url(name)).map_err(|e| e.to_string())?; + let mut text = polite_text(url, PoliteSite::MarioWiki, "Super Mario Wiki", cancelled).await?; + if let Some(t) = text.clone() { + let target = regex::Regex::new(r"(?i)^\s*#REDIRECT\s*\[\[([^\]\|#]+)") + .unwrap() + .captures(&t) + .and_then(|c| c.get(1).map(|m| m.as_str().trim().to_owned())); + if let Some(target) = target { + let url = Url::parse(&wiki_page_url(&target)).map_err(|e| e.to_string())?; + text = polite_text(url, PoliteSite::MarioWiki, "Super Mario Wiki", cancelled).await?; + } + } + Ok(text) +} + +async fn fetch_mariowiki_image( + game: &Game, + sys_id: &str, + data_dir: &Path, + cancelled: Option<&Arc>, + refresh: bool, +) -> Result>, String> { + if !mariowiki_covers(sys_id) { + return Ok(None); + } + if !trusted_release(&game.base) { + return Ok(None); + } + let probe = if !game.title.is_empty() { + &game.title + } else { + &game.base + }; + if !franchise_matches(probe) && !franchise_matches(&game.base) { + return Ok(None); + } + let names = wiki_page_names(if !game.title.is_empty() { + &game.title + } else { + &game.base + }); + let key = format!( + "v1/{sys_id}/{}", + names.first().map(String::as_str).unwrap_or("") + ); + let file = web_cache_file(data_dir, "mariowiki.json"); + let mut urls: Option> = None; + if !refresh { + if let Some(cached) = web_cache_get(&file, &key) { + if let Some(arr) = cached.as_array() { + let list: Vec = arr + .iter() + .filter_map(Value::as_str) + .map(str::to_owned) + .collect(); + urls = Some(list); + } + } + } + if urls.is_none() { + let mut found: Vec = Vec::new(); + let mut done = false; + for name in &names { + if cancelled.is_some_and(|c| c.load(Ordering::Relaxed)) { + return Err("Cancelled".to_owned()); + } + let text = wiki_page(name, cancelled).await?; + let Some(text) = text else { continue }; + let Some(files) = infobox_images(&text) else { + continue; + }; + for candidate in files { + let file_page = format!("File:{candidate}"); + let file_text = wiki_page(&file_page, cancelled).await?; + if let Some(file_text) = file_text { + if is_front_cover(&candidate, &file_text, sys_id) { + found = vec![wiki_image_url(&candidate, MARIOWIKI_IMAGES)]; + break; + } + } + if cancelled.is_some_and(|c| c.load(Ordering::Relaxed)) { + return Err("Cancelled".to_owned()); + } + } + // The game's own page exists: no cover for this system means stop. + done = true; + break; + } + let _ = done; + web_cache_set(&file, &key, json!(found)); + urls = Some(found); + } + for url in urls.unwrap_or_default() { + if cancelled.is_some_and(|c| c.load(Ordering::Relaxed)) { + return Err("Cancelled".to_owned()); + } + let parsed = Url::parse(&url).map_err(|e| e.to_string())?; + match request_image(parsed, cancelled).await { + Ok(Some(bytes)) => return Ok(Some(bytes)), + Ok(None) => continue, + Err(error) => { + if error == "Cancelled" || cancelled.is_some_and(|c| c.load(Ordering::Relaxed)) { + return Err(error); + } + continue; + } + } + } + Ok(None) +} + +fn archive_covers(sys_id: &str) -> bool { + archive_system_names(sys_id).is_some() +} + +fn archive_system_names(sys_id: &str) -> Option<&'static [&'static str]> { + match sys_id { + "nds" => Some(&["nintendo ds", "nds"]), + "3ds" => Some(&["nintendo 3ds", "3ds"]), + "gba" => Some(&["game boy advance", "gameboy advance", "gba"]), + "gbc" => Some(&["game boy color", "gameboy color", "gbc"]), + "gb" => Some(&["game boy", "gameboy", "gb"]), + "snes" => Some(&[ + "snes", + "super nintendo", + "super nintendo entertainment system", + "super famicom", + "sfc", + ]), + "nes" => Some(&[ + "nes", + "nintendo entertainment system", + "famicom", + "nintendo famicom", + ]), + "n64" => Some(&["n64", "nintendo 64"]), + "gc" => Some(&["gamecube", "nintendo gamecube", "gcn"]), + "wii" => Some(&["wii", "nintendo wii"]), + "wiiu" => Some(&["wii u", "nintendo wii u"]), + "switch" => Some(&["nintendo switch", "switch"]), + "ps1" => Some(&[ + "ps1", + "psx", + "playstation", + "sony playstation", + "playstation 1", + ]), + "ps2" => Some(&["ps2", "playstation 2", "sony playstation 2"]), + "ps3" => Some(&["ps3", "playstation 3", "sony playstation 3"]), + "psp" => Some(&["psp", "playstation portable", "sony psp"]), + "dreamcast" => Some(&["dreamcast", "sega dreamcast"]), + "genesis" => Some(&["genesis", "mega drive", "sega genesis", "sega mega drive"]), + "xbox" => Some(&["xbox", "microsoft xbox"]), + "x360" => Some(&["xbox 360", "microsoft xbox 360"]), + "a2600" => Some(&["atari 2600", "atari vcs"]), + _ => None, + } +} + +fn archive_serial(sys_id: &str) -> Option<&'static str> { + match sys_id { + "nds" => Some(r"\b(?:NTR|TWL)-[A-Z0-9]{3,4}\b"), + "3ds" => Some(r"\bCTR-[A-Z0-9]{3,4}\b"), + "gba" => Some(r"\bAGB-[A-Z0-9]{3,4}\b"), + "gbc" => Some(r"\bCGB-[A-Z0-9]{3,4}\b"), + "gb" => Some(r"\bDMG-[A-Z0-9]{2,4}\b"), + "snes" => Some(r"\b(?:SNS|SHVC)-[A-Z0-9]{2,4}\b"), + "nes" => Some(r"\bNES-[A-Z0-9]{2,4}\b"), + "n64" => Some(r"\bNUS-[A-Z0-9]{3,4}\b"), + "gc" => Some(r"\bDOL-[A-Z0-9]{3,4}\b"), + "wii" => Some(r"\bRVL-[A-Z0-9]{3,4}\b"), + "wiiu" => Some(r"\bWUP-[A-Z0-9]{3,4}\b"), + "switch" => Some(r"\bHAC-[A-Z0-9]{4,5}\b"), + "psp" => Some(r"\bU[LC][UEJAK][SM][- ]?\d{5}\b"), + _ => None, + } +} + +fn archive_over(sys_id: &str) -> &'static [&'static str] { + match sys_id { + "3ds" => &["nds"], + "gba" => &["gb", "gbc"], + "gbc" => &["gb"], + "snes" => &["nes"], + "wiiu" => &["wii"], + "ps2" => &["ps1"], + "ps3" => &["ps1"], + "psp" => &["ps1"], + "x360" => &["xbox"], + _ => &[], + } +} + +const LAUNCHBOX_PLATFORMS: &[(&str, &str)] = &[ + ("ps1", "Sony Playstation"), + ("ps2", "Sony Playstation 2"), + ("ps3", "Sony Playstation 3"), + ("ps4", "Sony Playstation 4"), + ("psp", "Sony PSP"), + ("switch", "Nintendo Switch"), + ("switch2", "Nintendo Switch 2"), + ("wiiu", "Nintendo Wii U"), + ("wii", "Nintendo Wii"), + ("gc", "Nintendo GameCube"), + ("n64", "Nintendo 64"), + ("snes", "Super Nintendo Entertainment System"), + ("nes", "Nintendo Entertainment System"), + ("3ds", "Nintendo 3DS"), + ("nds", "Nintendo DS"), + ("gba", "Nintendo Game Boy Advance"), + ("gbc", "Nintendo Game Boy Color"), + ("gb", "Nintendo Game Boy"), + ("dreamcast", "Sega Dreamcast"), + ("genesis", "Sega Genesis"), + ("xbox", "Microsoft Xbox"), + ("x360", "Microsoft Xbox 360"), + ("a2600", "Atari 2600"), + ("arcade", "Arcade"), + ("pc", "Windows"), +]; + +const SCREENSCRAPER_SYSTEMS: &[(&str, u32)] = &[ + ("genesis", 1), + ("nes", 3), + ("snes", 4), + ("gb", 9), + ("gbc", 10), + ("gba", 12), + ("gc", 13), + ("n64", 14), + ("nds", 15), + ("wii", 16), + ("3ds", 17), + ("wiiu", 18), + ("dreamcast", 23), + ("a2600", 26), + ("xbox", 32), + ("x360", 33), + ("ps1", 57), + ("ps2", 58), + ("ps3", 59), + ("psp", 61), + ("arcade", 75), + ("switch", 225), +]; + +const SCREENSCRAPER_REGIONS: &[&str] = &["us", "wor", "ss", "eu", "uk", "fr", "de", "jp"]; + +fn launchbox_platform(sys_id: &str) -> Option<&'static str> { + LAUNCHBOX_PLATFORMS + .iter() + .find(|(id, _)| *id == sys_id) + .map(|(_, name)| *name) +} + +fn launchbox_covers(sys_id: &str) -> bool { + launchbox_platform(sys_id).is_some() +} + +fn screenscraper_system(sys_id: &str) -> Option { + SCREENSCRAPER_SYSTEMS + .iter() + .find(|(id, _)| *id == sys_id) + .map(|(_, system)| *system) +} + +struct ScreenScraperCredentials { + user: String, + dev_id: String, + password: String, + dev_password: String, +} + +fn screenscraper_credentials(config: &Value) -> Option { + let section = config.get("screenscraper")?; + let field = |key: &str| { + section + .get(key) + .and_then(Value::as_str) + .unwrap_or("") + .trim() + .to_owned() + }; + let credentials = ScreenScraperCredentials { + user: field("user"), + dev_id: field("devId"), + password: field("password"), + dev_password: field("devPassword"), + }; + if credentials.user.is_empty() + || credentials.dev_id.is_empty() + || credentials.password.is_empty() + || credentials.dev_password.is_empty() + { + None + } else { + Some(credentials) + } +} + +fn screenscraper_configured(config: &Value) -> bool { + screenscraper_credentials(config).is_some() +} + +fn screenscraper_covers(sys_id: &str, config: &Value) -> bool { + screenscraper_system(sys_id).is_some() && screenscraper_configured(config) +} + +fn screenscraper_region_rank(region: &str) -> u32 { + SCREENSCRAPER_REGIONS + .iter() + .position(|known| *known == region) + .unwrap_or(SCREENSCRAPER_REGIONS.len()) as u32 +} + +fn screenscraper_media_url(url: &str) -> bool { + let Ok(parsed) = Url::parse(url) else { + return false; + }; + parsed.scheme() == "https" + && parsed + .host_str() + .is_some_and(|host| host == "screenscraper.fr" || host.ends_with(".screenscraper.fr")) +} + +fn front_shapes(sys_id: &str) -> &'static [f64] { + match sys_id { + "nds" | "3ds" => &[0.89], + "gba" | "gbc" | "gb" => &[1.0], + "snes" | "n64" => &[1.38, 0.72], + "nes" => &[0.73, 1.4], + "gc" | "wii" | "wiiu" => &[0.72], + "switch" => &[0.62], + "ps1" | "dreamcast" => &[1.0], + "ps2" | "genesis" | "xbox" | "x360" => &[0.71], + "ps3" => &[0.86], + "psp" => &[0.58], + "a2600" => &[0.74], + _ => &[], + } +} + +fn fits_front(sys_id: &str, width: u32, height: u32) -> bool { + if width == 0 || height == 0 { + return false; + } + let ratio = width as f64 / height as f64; + front_shapes(sys_id) + .iter() + .any(|shape| (ratio / shape - 1.0).abs() <= 0.08) +} + +fn archive_tokens(value: &str) -> String { + value.to_lowercase().replace('_', " ").trim().to_owned() +} + +fn systems_of(title: &str, subjects: &[String]) -> Vec { + let mut words: HashSet = HashSet::new(); + for s in subjects { + words.insert(archive_tokens(s)); + } + for g in regex::Regex::new(r"\(([^)]+)\)") + .unwrap() + .captures_iter(title) + .filter_map(|c| c.get(1).map(|m| m.as_str().to_owned())) + { + words.insert(archive_tokens(&g)); + } + for part in regex::Regex::new(r"\s+[-–—]\s+").unwrap().split(title) { + words.insert(archive_tokens(part)); + } + let mut found: Vec = Vec::new(); + for sys in [ + "nds", + "3ds", + "gba", + "gbc", + "gb", + "snes", + "nes", + "n64", + "gc", + "wii", + "wiiu", + "switch", + "ps1", + "ps2", + "ps3", + "psp", + "dreamcast", + "genesis", + "xbox", + "x360", + "a2600", + ] { + let names = archive_system_names(sys).unwrap_or(&[]); + let serial_hit = + archive_serial(sys).is_some_and(|p| regex::Regex::new(p).unwrap().is_match(title)); + if names.iter().any(|n| words.contains(*n)) || serial_hit { + found.push(sys.to_owned()); + } + } + let serial: Vec = found + .iter() + .filter(|id| { + archive_serial(id).is_some_and(|p| regex::Regex::new(p).unwrap().is_match(title)) + }) + .cloned() + .collect(); + if serial.len() == 1 { + return serial; + } + let mut set: HashSet = found.into_iter().collect(); + for id in set.clone() { + for lower in archive_over(&id) { + set.remove(*lower); + } + } + set.into_iter().collect() +} + +fn item_name(title: &str) -> String { + let split = regex::Regex::new(r"\s+(?:[\[\(]|(?:PAL|NTSC(?:-[UJ])?)\b|[A-Z]{2,4}-[A-Z0-9]{2,5}(?:-[A-Z0-9]{1,3})*\b|\d{3,4} ?[dD][pP][iI]\b|\d{2}-[bB][iI][tT]\b)") + .unwrap() + .split(title) + .next() + .unwrap_or(title) + .to_owned(); + let parts: Vec<&str> = regex::Regex::new(r"\s+[-–—]\s+") + .unwrap() + .split(&split) + .collect(); + let all_names: Vec<&str> = [ + "nds", + "3ds", + "gba", + "gbc", + "gb", + "snes", + "nes", + "n64", + "gc", + "wii", + "wiiu", + "switch", + "ps1", + "ps2", + "ps3", + "psp", + "dreamcast", + "genesis", + "xbox", + "x360", + "a2600", + ] + .into_iter() + .flat_map(|id| archive_system_names(id).unwrap_or(&[]).iter().copied()) + .collect(); + let stop = parts.iter().position(|p| { + let toks = archive_tokens(p); + all_names.contains(&toks.as_str()) + || regex::Regex::new(r"(?i)^(box|cover|complete|scans?|full cover|europe|usa|japan)\b") + .unwrap() + .is_match(p) + }); + let mut name = if let Some(idx) = stop { + if idx > 0 { + parts[..idx].join(" - ") + } else { + split.clone() + } + } else { + split + }; + name = regex::Regex::new(r"(?i)^scans?\s+-\s+") + .unwrap() + .replace(&name, "") + .into_owned(); + name = regex::Regex::new( + r"(?i)\s+(?:box scans?|box art|boxart|box|hi ?res|scans?|covers?|full cover)\b.*$", + ) + .unwrap() + .replace(&name, "") + .trim() + .to_owned(); + let mut sorted = all_names.clone(); + sorted.sort_by_key(|n| std::cmp::Reverse(n.len())); + for n in sorted { + let suffix = format!(" {n}"); + if name.to_lowercase().ends_with(&suffix) { + name = name[..name.len() - suffix.len()].trim().to_owned(); + break; + } + } + name.trim().to_owned() +} + +#[derive(Clone, Debug)] +struct ArchiveItem { + id: String, + key: String, + system: String, + region: &'static str, +} + +fn index_item(doc: &Value) -> Option { + let id = doc + .get("identifier") + .and_then(Value::as_str) + .unwrap_or("") + .to_owned(); + let title = doc + .get("title") + .and_then(Value::as_str) + .unwrap_or("") + .to_owned(); + if !regex::Regex::new(r"^[\w.-]+$").unwrap().is_match(&id) + || title.is_empty() + || regex::Regex::new(r"(?i)\b(display|promo\w*|demo|demonstration|custom|fan ?made|fan ?art|mock-?up|reproduction|repro|not for resale|nfr|sample|kiosk|beta|prototype)\b").unwrap().is_match(&title) + || (regex::Regex::new(r"(?i)\b(manual|map|poster|inserts?|cart|cartridge|disc|label|card|registration card|guide ?book|strategy guide|catalog(?:ue)?|flyer|ad|advert\w*|offer|sweepstakes|coupon)\b").unwrap().is_match(&title) + && !regex::Regex::new(r"(?i)\b(box|boxes|cover|covers|complete)\b").unwrap().is_match(&title)) + { + return None; + } + let subjects: Vec = doc + .get("subject") + .map(|s| { + if let Some(arr) = s.as_array() { + arr.iter() + .filter_map(Value::as_str) + .map(str::to_owned) + .collect() + } else if let Some(single) = s.as_str() { + vec![single.to_owned()] + } else { + Vec::new() + } + }) + .unwrap_or_default(); + if subjects.iter().any(|s| regex::Regex::new(r"(?i)\b(display|promo\w*|demo|demonstration|custom|fan ?made|fan ?art|mock-?up|reproduction|repro|not for resale|nfr|sample|kiosk|beta|prototype)\b").unwrap().is_match(s)) { + return None; + } + if subjects.iter().any(|s| regex::Regex::new(r"(?i)\b(manual|map|poster|inserts?|cart|cartridge|disc|label|card|registration card|guide ?book|strategy guide|catalog(?:ue)?|flyer|ad|advert\w*|offer|sweepstakes|coupon)\b").unwrap().is_match(s)) + && !regex::Regex::new(r"(?i)\b(box|boxes|cover|covers|complete)\b").unwrap().is_match(&title) + && !subjects.iter().any(|s| regex::Regex::new(r"(?i)\b(box|boxes|cover|covers|complete)\b").unwrap().is_match(s)) + { + return None; + } + let systems = systems_of(&title, &subjects); + if systems.len() != 1 { + return None; + } + let key = fallback_key(&item_name(&title)); + if key.len() < 3 + || regex::Regex::new(r"^(?:\d+(?:games?)?in1|(?:\d+)?(?:game)?pack|doublepack|combo(?:pack)?|collection|compilation)$").unwrap().is_match(&key) + { + return None; + } + Some(ArchiveItem { + id, + key, + system: systems.into_iter().next().unwrap_or_default(), + region: region_of(&title), + }) +} + +fn front_files(files: &[Value]) -> Vec { + let mut out: Vec<(bool, String)> = files + .iter() + .filter_map(|f| { + let name = f.get("name").and_then(Value::as_str)?; + let format = f.get("format").and_then(Value::as_str).unwrap_or(""); + let size: u64 = f + .get("size") + .and_then(|s| { + if let Some(n) = s.as_u64() { + Some(n) + } else if let Some(s) = s.as_str() { + s.parse().ok() + } else { + None + } + }) + .unwrap_or(u64::MAX); + if !regex::Regex::new(r"(?i)^(JPEG|PNG)$").unwrap().is_match(format) || size > ARCHIVE_MAX_FILE_BYTES { + return None; + } + let base_raw = name.rsplit('/').next().unwrap_or(name); + let base_no_ext = base_raw.rsplit('.').last().unwrap_or(base_raw); + // Strip only the final extension (name may contain dots). + let base_no_ext = if let Some(dot) = base_raw.rfind('.') { + &base_raw[..dot] + } else { + base_no_ext + }; + let camel = regex::Regex::new(r"([a-z])([A-Z])") + .unwrap() + .replace_all(base_no_ext, "$1 $2") + .into_owned(); + let base = camel + .to_lowercase() + .replace(['_', '.', '-'], " "); + if !regex::Regex::new(r"\bfront\b").unwrap().is_match(&base) { + return None; + } + if regex::Regex::new(r"\b(back|rear|reverse|spine|side|cart|cartridge|disc|disk|cd|dvd|umd|media|label|manual|insert|inlay|inside|inner|survey|poster|card|sleeve|obi|tray|case|shell|sticker|thumb|thumbnail|preview|ad|advert|outer|slip ?cover)\b").unwrap().is_match(&base) { + return None; + } + Some((!regex::Regex::new(r"(?i)^jpe?g$").unwrap().is_match(format), name.to_owned())) + }) + .collect(); + out.sort_by(|a, b| a.0.cmp(&b.0)); + out.into_iter().map(|(_, n)| n).collect() +} + +fn archive_index_file(data_dir: &Path) -> PathBuf { + web_cache_file(data_dir, "archive-boxart.json") +} + +fn group_archive_items( + items: &[ArchiveItem], +) -> HashMap>> { + let mut by_system: HashMap>> = HashMap::new(); + for item in items { + let keys = [item.key.clone(), without_version(&item.key)]; + let map = by_system.entry(item.system.clone()).or_default(); + for k in keys { + if k.is_empty() { + continue; + } + map.entry(k).or_default().push(item.clone()); + } + } + by_system +} + +async fn build_archive_index( + data_dir: &Path, + cancelled: Option<&Arc>, +) -> Result, String> { + let mut docs: Vec = Vec::new(); + for page in 1..=5 { + if cancelled.is_some_and(|c| c.load(Ordering::Relaxed)) { + return Err("Cancelled".to_owned()); + } + let mut url = + Url::parse(&format!("{ARCHIVE_API}/advancedsearch.php")).map_err(|e| e.to_string())?; + { + let mut q = url.query_pairs_mut(); + q.append_pair("q", &format!("collection:{ARCHIVE_COLLECTION}")); + q.append_pair("rows", "10000"); + q.append_pair("page", &page.to_string()); + q.append_pair("output", "json"); + q.append_pair("fl[]", "identifier"); + q.append_pair("fl[]", "title"); + q.append_pair("fl[]", "subject"); + } + let data = polite_json(url, PoliteSite::Archive, "The Internet Archive", cancelled) + .await? + .ok_or("Could not read the Internet Archive box art list")?; + let response = data + .get("response") + .and_then(Value::as_object) + .ok_or("Could not read the Internet Archive box art list")?; + let found = response + .get("docs") + .and_then(Value::as_array) + .ok_or("Could not read the Internet Archive box art list")?; + docs.extend(found.iter().cloned()); + if found.is_empty() { + break; + } + if let Some(total) = response.get("numFound").and_then(Value::as_u64) { + if (docs.len() as u64) >= total { + break; + } + } + } + let items: Vec = docs.iter().filter_map(index_item).collect(); + if items.is_empty() { + return Err("The Internet Archive box art list was empty".to_owned()); + } + let file = archive_index_file(data_dir); + if let Some(parent) = file.parent() { + fs::create_dir_all(parent).map_err(|e| e.to_string())?; + } + let built = json!({ + "version": ARCHIVE_INDEX_VERSION, + "built": chrono::Utc::now().timestamp_millis(), + "items": items.iter().map(|i| json!({ + "id": i.id, "key": i.key, "system": i.system, "region": i.region + })).collect::>() + }); + let tmp = file.with_extension("json.tmp"); + fs::write(&tmp, serde_json::to_vec(&built).map_err(|e| e.to_string())?) + .map_err(|e| e.to_string())?; + fs::rename(&tmp, &file).map_err(|e| e.to_string())?; + Ok(items) +} + +async fn load_archive_index( + data_dir: &Path, + cancelled: Option<&Arc>, + refresh: bool, +) -> Result>>, String> { + let file = archive_index_file(data_dir); + let now_ms = chrono::Utc::now().timestamp_millis() as u64; + let age_ms: u64 = file + .metadata() + .ok() + .and_then(|m| m.modified().ok()) + .and_then(|t| t.elapsed().ok()) + .map(|d| d.as_millis() as u64) + .unwrap_or(u64::MAX); + let mut want_refresh = refresh; + if want_refresh && age_ms < 86400 * 1000 { + want_refresh = false; + } + if !want_refresh && age_ms < WEB_CACHE_AGE_SECS * 1000 { + if let Ok(text) = fs::read_to_string(&file) { + if let Ok(cached) = serde_json::from_str::(&text) { + if cached.get("version").and_then(Value::as_u64) == Some(ARCHIVE_INDEX_VERSION) { + if let Some(items) = cached.get("items").and_then(Value::as_array) { + let parsed: Vec = items + .iter() + .filter_map(|v| { + Some(ArchiveItem { + id: v.get("id").and_then(Value::as_str)?.to_owned(), + key: v.get("key").and_then(Value::as_str)?.to_owned(), + system: v.get("system").and_then(Value::as_str)?.to_owned(), + region: match v.get("region").and_then(Value::as_str) { + Some("us") => "us", + Some("eu") => "eu", + Some("jp") => "jp", + _ => "", + }, + }) + }) + .collect(); + if !parsed.is_empty() { + if now_ms >= (cached.get("built").and_then(Value::as_u64).unwrap_or(0)) + { + return Ok(group_archive_items(&parsed)); + } + } + } + } + } + } + } + let items = build_archive_index(data_dir, cancelled).await?; + Ok(group_archive_items(&items)) +} + +async fn archive_scan_size( + id: &str, + name: &str, + files_file: &Path, + cancelled: Option<&Arc>, +) -> Result, String> { + let key = format!("size:{id}/{name}"); + if let Some(cached) = web_cache_get(files_file, &key) { + if cached.is_null() { + return Ok(None); + } + if let Some(arr) = cached.as_array() { + if arr.len() == 2 { + let w = arr[0].as_u64().unwrap_or(0) as u32; + let h = arr[1].as_u64().unwrap_or(0) as u32; + if w > 0 && h > 0 { + return Ok(Some((w, h))); + } + } + } + return Ok(None); + } + let target = format!("{id}/{name}"); + let url = Url::parse(&format!( + "{ARCHIVE_IIIF}/{}/info.json", + encode_uri_component(&target) + )) + .map_err(|e| e.to_string())?; + let info = polite_json(url, PoliteSite::Archive, "The Internet Archive", cancelled).await?; + let size = info.as_ref().and_then(|v| { + let w = v.get("width").and_then(Value::as_u64)?; + let h = v.get("height").and_then(Value::as_u64)?; + if w > 0 && h > 0 { + Some((w as u32, h as u32)) + } else { + None + } + }); + web_cache_set( + files_file, + &key, + size.map(|(w, h)| json!([w, h])).unwrap_or(Value::Null), + ); + Ok(size) +} + +async fn archive_item_files( + id: &str, + files_file: &Path, + cancelled: Option<&Arc>, +) -> Result, String> { + if let Some(cached) = web_cache_get(files_file, id) { + if let Some(arr) = cached.as_array() { + return Ok(arr + .iter() + .filter_map(Value::as_str) + .map(str::to_owned) + .collect()); + } + } + let url = Url::parse(&format!( + "{ARCHIVE_API}/metadata/{}/files", + encode_uri_component(id) + )) + .map_err(|e| e.to_string())?; + let data = polite_json(url, PoliteSite::Archive, "The Internet Archive", cancelled).await?; + let names = data + .as_ref() + .and_then(|v| v.get("result")) + .and_then(Value::as_array) + .map(|arr| front_files(arr)) + .unwrap_or_default(); + web_cache_set(files_file, id, json!(names)); + Ok(names) +} + +async fn fetch_internet_archive_image( + game: &Game, + sys_id: &str, + data_dir: &Path, + cancelled: Option<&Arc>, + refresh: bool, +) -> Result>, String> { + if !archive_covers(sys_id) { + return Ok(None); + } + if !trusted_release(&game.base) { + return Ok(None); + } + let by_system = load_archive_index(data_dir, cancelled, refresh).await?; + let Some(by_key) = by_system.get(sys_id) else { + return Ok(None); + }; + let own = region_of(&game.base); + let rank = |r: &str| -> i32 { + if !r.is_empty() && r == own { + 0 + } else { + match r { + "us" => 1, + "eu" => 2, + "jp" => 3, + _ => 4, + } + } + }; + let mut seen: HashMap = HashMap::new(); + for key in artwork_title_keys(game) { + for expanded in [key.clone(), without_version(&key)] { + if let Some(list) = by_key.get(&expanded) { + for item in list { + seen.entry(item.id.clone()).or_insert_with(|| item.clone()); + } + } + } + } + let mut items: Vec = seen.into_values().collect(); + items.sort_by_key(|i| rank(i.region)); + items.truncate(3); + let files_file = web_cache_file(data_dir, "archive-items.json"); + let mut urls: Vec = Vec::new(); + for item in items { + if cancelled.is_some_and(|c| c.load(Ordering::Relaxed)) { + return Err("Cancelled".to_owned()); + } + for name in archive_item_files(&item.id, &files_file, cancelled) + .await? + .into_iter() + .take(2) + { + let Some(size) = archive_scan_size(&item.id, &name, &files_file, cancelled).await? + else { + continue; + }; + if !fits_front(sys_id, size.0, size.1) { + continue; + } + let target = format!("{}/{}", item.id, name); + urls.push(format!( + "{ARCHIVE_IIIF}/{}/full/!1600,1600/0/default.jpg", + encode_uri_component(&target) + )); + } + } + urls.truncate(4); + for url in urls { + if cancelled.is_some_and(|c| c.load(Ordering::Relaxed)) { + return Err("Cancelled".to_owned()); + } + let parsed = Url::parse(&url).map_err(|e| e.to_string())?; + match request_image(parsed, cancelled).await { + Ok(Some(bytes)) => return Ok(Some(bytes)), + Ok(None) => continue, + Err(error) => { + if error == "Cancelled" || cancelled.is_some_and(|c| c.load(Ordering::Relaxed)) { + return Err(error); + } + continue; + } + } + } + Ok(None) +} + +fn launchbox_front_rank(image_type: &str, region: &str) -> Option { + let type_rank = match image_type { + "Box - Front" => 0, + "Box - Front - Reconstructed" => 1, + _ => return None, + }; + let region_rank = if region.is_empty() { + 1 + } else if regex::Regex::new(r"North America|United States|World|Canada") + .unwrap() + .is_match(region) + { + 0 + } else if regex::Regex::new(r"Europe|United Kingdom|Australia|Oceania") + .unwrap() + .is_match(region) + { + 2 + } else { + 3 + }; + Some(type_rank * 10 + region_rank) +} + +fn launchbox_file_ok(name: &str) -> bool { + regex::Regex::new(r"(?i)^[\w.-]+\.(png|jpe?g)$") + .unwrap() + .is_match(name) +} + +fn parse_launchbox_metadata( + source: R, + cancelled: Option<&Arc>, +) -> Result< + ( + HashMap>>, + HashMap>>, + ), + String, +> { + let wanted: HashSet = LAUNCHBOX_PLATFORMS + .iter() + .map(|(_, platform)| (*platform).to_owned()) + .collect(); + let mut platform_of: HashMap = HashMap::new(); + let mut names: HashMap>> = HashMap::new(); + let mut ranked: HashMap>> = HashMap::new(); + let mut reader = quick_xml::Reader::from_reader(BufReader::new(source)); + reader.config_mut().trim_text(true); + let mut buffer = Vec::new(); + let mut record = false; + let mut fields: HashMap = HashMap::new(); + let mut field: Option = None; + let mut text = String::new(); + let mut events: u64 = 0; + loop { + buffer.clear(); + events += 1; + if events % 4096 == 0 && cancelled.is_some_and(|c| c.load(Ordering::Relaxed)) { + return Err("Cancelled".to_owned()); + } + match reader.read_event_into(&mut buffer) { + Ok(quick_xml::events::Event::Start(event)) => { + let tag = String::from_utf8_lossy(event.local_name().as_ref()).into_owned(); + match tag.as_str() { + "Game" | "GameAlternateName" | "GameImage" => { + record = true; + fields.clear(); + field = None; + } + _ => { + if record { + field = Some(tag); + text.clear(); + } + } + } + } + Ok(quick_xml::events::Event::Text(event)) => { + if field.is_some() { + let decoded = event.unescape().map(|s| s.into_owned()).unwrap_or_default(); + text.push_str(&decoded); + } + } + Ok(quick_xml::events::Event::End(event)) => { + let tag = String::from_utf8_lossy(event.local_name().as_ref()).into_owned(); + match tag.as_str() { + "Game" | "GameAlternateName" | "GameImage" => { + let id = fields.get("DatabaseID").cloned().unwrap_or_default(); + if !id.is_empty() { + match tag.as_str() { + "Game" => { + let platform = + fields.get("Platform").cloned().unwrap_or_default(); + if wanted.contains(&platform) { + platform_of.insert(id.clone(), platform.clone()); + let key = fallback_key( + fields.get("Name").map(String::as_str).unwrap_or(""), + ); + if !key.is_empty() { + let list = names + .entry(platform) + .or_default() + .entry(key) + .or_default(); + if !list.contains(&id) { + list.push(id); + } + } + } + } + "GameAlternateName" => { + if let Some(platform) = platform_of.get(&id).cloned() { + let key = fallback_key( + fields + .get("AlternateName") + .map(String::as_str) + .unwrap_or(""), + ); + if !key.is_empty() { + let list = names + .entry(platform) + .or_default() + .entry(key) + .or_default(); + if !list.contains(&id) { + list.push(id); + } + } + } + } + _ => { + if let Some(platform) = platform_of.get(&id).cloned() { + let rank = launchbox_front_rank( + fields.get("Type").map(String::as_str).unwrap_or(""), + fields.get("Region").map(String::as_str).unwrap_or(""), + ); + if let Some(rank) = rank { + let file = + fields.get("FileName").cloned().unwrap_or_default(); + if launchbox_file_ok(&file) { + ranked + .entry(platform) + .or_default() + .entry(id) + .or_default() + .push((rank, file)); + } + } + } + } + } + } + record = false; + field = None; + fields.clear(); + } + _ => { + if let Some(current) = field.take() { + fields.insert(current, text.trim().to_owned()); + text.clear(); + } + } + } + } + Ok(quick_xml::events::Event::Eof) => break, + Ok(_) => {} + Err(_) => return Err("Could not read the LaunchBox database".to_owned()), + } + } + if platform_of.is_empty() { + return Err("Could not read any games from the LaunchBox database".to_owned()); + } + let mut images: HashMap>> = HashMap::new(); + for (platform, by_id) in ranked { + let mapped = by_id + .into_iter() + .map(|(id, mut files)| { + files.sort_by_key(|(rank, _)| *rank); + files.truncate(LAUNCHBOX_KEEP); + ( + id, + files.into_iter().map(|(_, file)| file).collect::>(), + ) + }) + .collect::>(); + images.insert(platform, mapped); + } + Ok((names, images)) +} + +fn launchbox_index_file(data_dir: &Path) -> PathBuf { + data_dir.join("media/_index/launchbox-index.json") +} + +async fn download_launchbox_zip( + path: &Path, + cancelled: Option<&Arc>, +) -> Result<(), String> { + if cancelled.is_some_and(|c| c.load(Ordering::Relaxed)) { + return Err("Cancelled".to_owned()); + } + polite_gap(PoliteSite::LaunchBox).await; + let client = reqwest::Client::builder() + .user_agent(USER_AGENT) + .timeout(Duration::from_secs(600)) + .build() + .map_err(|e| e.to_string())?; + let mut response = client + .get(LAUNCHBOX_METADATA) + .send() + .await + .map_err(|e| e.to_string())?; + if !response.status().is_success() { + return Err(format!("LaunchBox returned HTTP {}", response.status())); + } + if let Some(parent) = path.parent() { + fs::create_dir_all(parent).map_err(|e| e.to_string())?; + } + let mut file = fs::File::create(path).map_err(|e| e.to_string())?; + while let Some(chunk) = response.chunk().await.map_err(|e| e.to_string())? { + if cancelled.is_some_and(|c| c.load(Ordering::Relaxed)) { + drop(file); + let _ = fs::remove_file(path); + return Err("Cancelled".to_owned()); + } + file.write_all(&chunk).map_err(|e| e.to_string())?; + } + Ok(()) +} + +async fn build_launchbox_index( + data_dir: &Path, + cancelled: Option<&Arc>, +) -> Result { + let dir = data_dir.join("media/_index"); + fs::create_dir_all(&dir).map_err(|e| e.to_string())?; + let zip_path = dir.join(format!("launchbox-metadata-{}.zip", uuid::Uuid::new_v4())); + download_launchbox_zip(&zip_path, cancelled).await?; + let (names, images) = { + let file = fs::File::open(&zip_path).map_err(|e| e.to_string())?; + let mut archive = zip::ZipArchive::new(file).map_err(|e| e.to_string())?; + let entry = archive + .by_name("Metadata.xml") + .map_err(|_| "The LaunchBox database is missing Metadata.xml".to_owned())?; + parse_launchbox_metadata(entry, cancelled)? + }; + let _ = fs::remove_file(&zip_path); + let built = json!({ + "version": LAUNCHBOX_INDEX_VERSION, + "built": chrono::Utc::now().timestamp_millis(), + "names": names, + "images": images + }); + let file = launchbox_index_file(data_dir); + let tmp = file.with_extension("json.tmp"); + fs::write(&tmp, serde_json::to_vec(&built).map_err(|e| e.to_string())?) + .map_err(|e| e.to_string())?; + fs::rename(&tmp, &file).map_err(|e| e.to_string())?; + Ok(built) +} + +async fn load_launchbox_index( + data_dir: &Path, + cancelled: Option<&Arc>, + refresh: bool, + allow_download: bool, +) -> Result, String> { + let file = launchbox_index_file(data_dir); + let age_ms: u64 = file + .metadata() + .ok() + .and_then(|m| m.modified().ok()) + .and_then(|t| t.elapsed().ok()) + .map(|d| d.as_millis() as u64) + .unwrap_or(u64::MAX); + let mut want_refresh = refresh; + if want_refresh && age_ms < 86400 * 1000 { + want_refresh = false; + } + if let Ok(text) = fs::read_to_string(&file) { + if let Ok(cached) = serde_json::from_str::(&text) { + if cached.get("version").and_then(Value::as_u64) == Some(LAUNCHBOX_INDEX_VERSION) { + if !want_refresh && age_ms < WEB_CACHE_AGE_SECS * 1000 { + return Ok(Some(cached)); + } + if !allow_download { + return Ok(Some(cached)); + } + } + } + } + if !allow_download { + return Ok(None); + } + Ok(Some(build_launchbox_index(data_dir, cancelled).await?)) +} + +async fn first_image( + urls: Vec, + cancelled: Option<&Arc>, +) -> Result>, String> { + let mut failure: Option = None; + for url in urls { + if cancelled.is_some_and(|c| c.load(Ordering::Relaxed)) { + return Err("Cancelled".to_owned()); + } + let parsed = Url::parse(&url).map_err(|e| e.to_string())?; + match request_image(parsed, cancelled).await { + Ok(Some(bytes)) => return Ok(Some(bytes)), + Ok(None) => {} + Err(error) => { + if error == "Cancelled" || cancelled.is_some_and(|c| c.load(Ordering::Relaxed)) { + return Err(error); + } + failure = Some(error); + } + } + } + match failure { + Some(error) => Err(error), + None => Ok(None), + } +} + +async fn fetch_launchbox_image( + game: &Game, + sys_id: &str, + data_dir: &Path, + cancelled: Option<&Arc>, + refresh: bool, + allow_download: bool, +) -> Result>, String> { + let Some(platform) = launchbox_platform(sys_id) else { + return Ok(None); + }; + if !trusted_release(&game.base) { + return Ok(None); + } + let Some(index) = load_launchbox_index(data_dir, cancelled, refresh, allow_download).await? + else { + return Ok(None); + }; + let Some(names) = index.get("names").and_then(|names| names.get(platform)) else { + return Ok(None); + }; + let Some(images) = index.get("images").and_then(|images| images.get(platform)) else { + return Ok(None); + }; + let mut keys = Vec::new(); + for key in artwork_title_keys(game) { + keys.push(key.clone()); + keys.push(without_version(&key)); + } + for key in keys { + let Some(ids) = names.get(&key).and_then(Value::as_array) else { + continue; + }; + for id in ids { + let Some(files) = id + .as_str() + .and_then(|id| images.get(id)) + .and_then(Value::as_array) + else { + continue; + }; + if files.is_empty() { + continue; + } + let urls: Vec = files + .iter() + .filter_map(Value::as_str) + .map(|file| format!("{LAUNCHBOX_IMAGES}/{file}")) + .collect(); + if !urls.is_empty() { + return first_image(urls, cancelled).await; + } + } + } + Ok(None) +} + +fn crc32_table() -> &'static [u32; 256] { + static TABLE: OnceLock<[u32; 256]> = OnceLock::new(); + TABLE.get_or_init(|| { + let mut table = [0u32; 256]; + for (index, slot) in table.iter_mut().enumerate() { + let mut crc = index as u32; + for _ in 0..8 { + crc = if crc & 1 != 0 { + 0xEDB88320 ^ (crc >> 1) + } else { + crc >> 1 + }; + } + *slot = crc; + } + table + }) +} + +fn crc32_update(crc: u32, data: &[u8]) -> u32 { + let mut crc = !crc; + for &byte in data { + crc = crc32_table()[(crc ^ u32::from(byte)) as usize & 0xff] ^ (crc >> 8); + } + !crc +} + +fn screenscraper_crc(game: &Game, size: u64) -> Option { + if size > SCREENSCRAPER_CRC_LIMIT { + return None; + } + let mut file = fs::File::open(&game.rom_path).ok()?; + let mut crc = 0u32; + let mut buffer = [0u8; 8192]; + loop { + match file.read(&mut buffer) { + Ok(0) => break, + Ok(read) => crc = crc32_update(crc, &buffer[..read]), + Err(_) => return None, + } + } + Some(crc) +} + +fn screenscraper_lookup_url( + game: &Game, + system: u32, + credentials: &ScreenScraperCredentials, + rom_size: Option, + crc: Option, +) -> Url { + let rom_path = Path::new(&game.rom_path); + let folder = game.rom_path.to_lowercase().ends_with("exefs/main"); + let mut url = Url::parse(&format!("{SCREENSCRAPER_API}/jeuInfos.php")) + .expect("ScreenScraper API URL is valid"); + { + let mut q = url.query_pairs_mut(); + q.append_pair("devid", &credentials.dev_id); + q.append_pair("devpassword", &credentials.dev_password); + q.append_pair("softname", SCREENSCRAPER_SOFTNAME); + q.append_pair("output", "json"); + q.append_pair("ssid", &credentials.user); + q.append_pair("sspassword", &credentials.password); + q.append_pair("systemeid", &system.to_string()); + if folder { + q.append_pair("romtype", "dossier"); + q.append_pair("romnom", &game.base); + } else { + q.append_pair("romtype", "rom"); + let romnom = rom_path + .file_name() + .and_then(|name| name.to_str()) + .unwrap_or(&game.base); + q.append_pair("romnom", romnom); + if let Some(size) = rom_size { + q.append_pair("romtaille", &size.to_string()); + if let Some(crc) = crc { + q.append_pair("crc", &format!("{crc:08X}")); + } + } + } + } + url +} + +async fn screenscraper_json( + url: Url, + cancelled: Option<&Arc>, +) -> Result, String> { + if cancelled.is_some_and(|c| c.load(Ordering::Relaxed)) { + return Err("Cancelled".to_owned()); + } + polite_gap(PoliteSite::ScreenScraper).await; + if cancelled.is_some_and(|c| c.load(Ordering::Relaxed)) { + return Err("Cancelled".to_owned()); + } + let response = reqwest::Client::builder() + .user_agent(USER_AGENT) + .timeout(Duration::from_secs(25)) + .build() + .map_err(|e| e.to_string())? + .get(url) + .send() + .await + .map_err(|e| e.to_string())?; + match response.status().as_u16() { + 404 => return Ok(None), + 400 => return Err("ScreenScraper could not read the request".to_owned()), + 401 => return Err("ScreenScraper is busy right now; try again later".to_owned()), + 403 => return Err("ScreenScraper rejected the developer ID or password".to_owned()), + 423 => return Err("ScreenScraper is down for maintenance".to_owned()), + 426 => return Err("ScreenScraper no longer accepts this version of PyroCade".to_owned()), + 429 => return Err("ScreenScraper says too many requests; slow down and retry".to_owned()), + 430 => return Err("Your ScreenScraper daily quota is used up".to_owned()), + 431 => return Err("ScreenScraper saw too many unknown ROMs today".to_owned()), + status if !response.status().is_success() => { + return Err(format!("ScreenScraper returned HTTP {status}")); + } + _ => {} + } + let data = response + .json::() + .await + .map_err(|_| "ScreenScraper sent an unreadable reply".to_owned())?; + Ok(Some(data)) +} + +async fn screenscraper_medias( + game: &Game, + system: u32, + credentials: &ScreenScraperCredentials, + cancelled: Option<&Arc>, +) -> Result, String> { + let rom_size = fs::metadata(&game.rom_path).map(|meta| meta.len()).ok(); + let crc = rom_size.and_then(|size| screenscraper_crc(game, size)); + let url = screenscraper_lookup_url(game, system, credentials, rom_size, crc); + let Some(data) = screenscraper_json(url, cancelled).await? else { + return Ok(Vec::new()); + }; + let Some(medias) = data + .get("response") + .and_then(|response| response.get("jeu")) + .and_then(|jeu| jeu.get("medias")) + .and_then(Value::as_array) + else { + return Ok(Vec::new()); + }; + let mut candidates: Vec<(u32, String)> = medias + .iter() + .filter(|media| media.get("type").and_then(Value::as_str) == Some("box-2D")) + .filter_map(|media| { + let url = media.get("url").and_then(Value::as_str)?; + if !screenscraper_media_url(url) { + return None; + } + let region = media.get("region").and_then(Value::as_str).unwrap_or(""); + Some((screenscraper_region_rank(region), url.to_owned())) + }) + .collect(); + candidates.sort_by_key(|(rank, _)| *rank); + candidates.truncate(6); + Ok(candidates.into_iter().map(|(_, url)| url).collect()) +} + +async fn fetch_screenscraper_image( + game: &Game, + sys_id: &str, + config: &Value, + data_dir: &Path, + cancelled: Option<&Arc>, + refresh: bool, +) -> Result>, String> { + let Some(system) = screenscraper_system(sys_id) else { + return Ok(None); + }; + let Some(credentials) = screenscraper_credentials(config) else { + return Ok(None); + }; + let file = web_cache_file(data_dir, "screenscraper.json"); + let key = format!("ss/{sys_id}/{}", game.id); + let mut urls: Option> = None; + if !refresh { + if let Some(cached) = web_cache_get(&file, &key) { + if let Some(cached) = cached.as_array() { + urls = Some( + cached + .iter() + .filter_map(Value::as_str) + .map(str::to_owned) + .collect(), + ); + } + } + } + if urls.is_none() { + let found = screenscraper_medias(game, system, &credentials, cancelled).await?; + web_cache_set(&file, &key, json!(found)); + urls = Some(found); + } + first_image(urls.unwrap_or_default(), cancelled).await +} + +fn write_new(path: &Path, bytes: &[u8]) -> Result { + fs::create_dir_all(path.parent().ok_or("Artwork directory is invalid")?) + .map_err(|e| e.to_string())?; + let mut file = match OpenOptions::new().write(true).create_new(true).open(path) { + Ok(file) => file, + Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => return Ok(false), + Err(e) => return Err(e.to_string()), + }; + file.write_all(bytes).map(|_| true).map_err(|e| { + let _ = fs::remove_file(path); + e.to_string() + }) +} + +fn refresh_index( + retry_missing: bool, + refreshed_indexes: &Mutex>, + key: String, +) -> bool { + retry_missing + && refreshed_indexes + .lock() + .map(|mut refreshed| refreshed.insert(key)) + .unwrap_or(false) +} + +fn artwork_region_rank(name: &str) -> (bool, bool) { + let us = name.contains("(USA"); + let preferred = us || name.contains("(Europe") || name.contains("(World"); + (!us, !preferred) +} + +fn safe_base(base: &str) -> Result<&str, String> { + if base.is_empty() + || base == "." + || base == ".." + || base + .chars() + .any(|c| c.is_control() || "<>:\"/\\|?*".contains(c)) + { + return Err("Invalid game filename".to_owned()); + } + Ok(base) +} + +fn type_folder(kind: &str) -> &'static str { + TYPES + .iter() + .find(|(name, _, _)| *name == kind) + .map(|(_, folder, _)| *folder) + .unwrap_or("covers") +} + +fn loose_key(value: &str) -> String { + value + .to_lowercase() + .chars() + .filter(|c| c.is_ascii_alphanumeric()) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn libretro_matches_prefer_us_then_europe_or_world() { + let mut names = vec![ + "Game (World).png", + "Game (Japan).png", + "Game (USA).png", + "Game (Europe).png", + ]; + names.sort_by_key(|name| artwork_region_rank(name)); + assert_eq!( + names, + [ + "Game (USA).png", + "Game (World).png", + "Game (Europe).png", + "Game (Japan).png", + ] + ); + } + + #[test] + fn retry_missing_refreshes_each_index_once_per_job() { + let refreshed = Mutex::new(HashSet::new()); + assert!(refresh_index(true, &refreshed, "snes/front".to_owned())); + assert!(!refresh_index(true, &refreshed, "snes/front".to_owned())); + assert!(!refresh_index( + false, + &refreshed, + "snes/screenshot".to_owned() + )); + } + + #[test] + fn imported_artwork_replaces_the_backend_game_media() { + let game = Game { + id: "game".to_owned(), + system: "snes".to_owned(), + rom_path: "game.sfc".to_owned(), + base: "game".to_owned(), + title: "Game".to_owned(), + info: json!({}), + media: std::collections::HashMap::from([( + "front".to_owned(), + "file:///old.png".to_owned(), + )]), + shell: None, + hidden: false, + scanned_title: None, + custom_title: false, + version: None, + media_type: None, + emulator: None, + added: None, + }; + let games = Arc::new(RwLock::new(vec![game])); + update_game_media( + &games, + "game", + &json!({"replace":true,"media":{"front":"file:///new.png"}}), + ); + assert_eq!( + games.read().unwrap()[0] + .media + .get("front") + .map(String::as_str), + Some("file:///new.png") + ); + } + + #[test] + fn fallback_skips_untrusted_releases_and_ignores_version() { + assert!(!trusted_release( + "Super Mario World Co-op (Super Mario World modification) (1.0)" + )); + assert!(!trusted_release("Tetris (Demo) (USA)")); + assert!(trusted_release("Mario Kart DS (USA)")); + assert_eq!(without_version("pokemonblackversion"), "pokemonblack"); + assert_eq!(region_of("Game (USA) [TWL-IRBO-USA]"), "us"); + assert_eq!(region_of("Game (Europe)"), "eu"); + assert_eq!(region_of("Game (Japan)"), "jp"); + // A bare title word is not a region tag. + assert_eq!(region_of("Game E"), ""); + } + + #[test] + fn mariowiki_pages_and_image_paths() { + assert_eq!( + wiki_page_names("Mario & Luigi - Partners in Time (Europe) (En,Fr)")[0], + "Mario & Luigi - Partners in Time" + ); + assert!( + wiki_page_names("Mario & Luigi - Partners in Time (Europe)") + .iter() + .any(|n| n == "Mario & Luigi: Partners in Time") + ); + assert!( + wiki_image_url("MKDS NA Box Art.png", MARIOWIKI_IMAGES) + .ends_with("/images/e/e1/MKDS_NA_Box_Art.png") + ); + let text = "{{game infobox\n|image=[[File:MKDS NA Box Art.png|270px]]\n|platforms=[[Nintendo DS]]\n}}"; + assert_eq!( + infobox_images(text), + Some(vec!["MKDS NA Box Art.png".to_owned()]) + ); + assert_eq!(infobox_images("{{disambig}}"), None); + let cover_page = "{{game-cover}}\n[[Category:Nintendo DS game covers]]"; + assert!(is_front_cover("MKDS NA Box Art.png", cover_page, "nds")); + assert!(!is_front_cover("MPDS Box Back.png", cover_page, "nds")); + let n64_cover = "[[Category:Nintendo 64 game covers]]"; + assert!(!is_front_cover("SM64 Box.png", n64_cover, "nds")); + assert!(is_front_cover("SM64 Box.png", n64_cover, "n64")); + let back_cover = "{{game-cover}}\n[[Category:Nintendo DS game covers]]\nback cover"; + assert!(!is_front_cover("Box.png", back_cover, "nds")); + } + + #[test] + fn internet_archive_titles_systems_and_front_files() { + assert_eq!( + item_name("Pokemon - Black Version [TWL-IRBO-USA] (Nintendo DS) - Box Scans (1200DPI)"), + "Pokemon - Black Version" + ); + assert_eq!( + item_name("Sword of Hope, The (Spain) DMG-SE-ESP 1200dpi 48bit"), + "Sword of Hope, The" + ); + assert_eq!( + item_name("Advance Wars Dual Strike Nintendo Ds box art full cover"), + "Advance Wars Dual Strike" + ); + let systems = systems_of( + "Invincible Iron Man, The [AGB-AIOE USA] Box Scan", + &[ + "Nintendo".to_owned(), + "GameBoy".to_owned(), + "GameBoy Advance".to_owned(), + "GBA".to_owned(), + ], + ); + assert_eq!(systems, vec!["gba".to_owned()]); + let ambiguous = systems_of("Some Game", &["Nintendo DS".to_owned(), "PSP".to_owned()]); + assert_eq!(ambiguous.len(), 2); + let files = front_files(&[ + json!({"name":"Mario and Wario - Box Front.jpg","format":"JPEG","size":"6086510"}), + json!({"name":"Mario and Wario - Cart Front.jpg","format":"JPEG","size":"1131975"}), + json!({"name":"Mario and Wario - Box Back.jpg","format":"JPEG","size":"5754998"}), + json!({"name":"Mario and Wario - Box Front_thumb.jpg","format":"JPEG Thumb","size":"20000"}), + json!({"name":"021_GAME_NDS_survey_front.jpg","format":"JPEG","size":"500000"}), + json!({"name":"scans/001 SLES-03633-Front.jpg","format":"JPEG","size":"6444678"}), + json!({"name":"FrontCover.png","format":"PNG","size":"900000"}), + ]); + assert_eq!( + files, + [ + "Mario and Wario - Box Front.jpg", + "scans/001 SLES-03633-Front.jpg", + "FrontCover.png" + ] + ); + assert!( + index_item(&json!({ + "identifier":"x", + "title":"Tomb Raider: Prophecy, The [5001656] Merchandise Offer", + "subject":["GameBoy Advance","Insert","Merchandise Offer"] + })) + .is_none() + ); + assert!(index_item(&json!({ + "identifier":"x", + "title":"Castlevania Portrait Of Ruin [NTR-ACBE-USA] (Nintendo DS) - Box, Manual, Cart Scans (1200DPI)", + "subject":["Nintendo DS"] + })) + .is_some()); + assert!(fits_front("ps1", 2953, 3015)); + assert!(fits_front("snes", 4140, 3000)); + assert!(fits_front("snes", 2160, 3000)); + assert!(!fits_front("snes", 3137, 6735)); + assert!(!fits_front("arcade", 1000, 1000)); + } + + #[test] + fn launchbox_and_screenscraper_cover_their_systems() { + assert_eq!(launchbox_platform("ps4"), Some("Sony Playstation 4")); + assert_eq!(launchbox_platform("arcade"), Some("Arcade")); + assert!(launchbox_covers("snes")); + assert!(!launchbox_covers("unknown")); + assert_eq!(screenscraper_system("snes"), Some(4)); + assert_eq!(screenscraper_system("ps1"), Some(57)); + assert_eq!(screenscraper_system("switch"), Some(225)); + assert_eq!(screenscraper_system("ps4"), None); + assert_eq!(screenscraper_region_rank("us"), 0); + assert!(screenscraper_region_rank("us") < screenscraper_region_rank("wor")); + assert!(screenscraper_region_rank("eu") < screenscraper_region_rank("jp")); + assert!(screenscraper_region_rank("xx") > screenscraper_region_rank("jp")); + } + + #[test] + fn launchbox_front_files_rank_type_then_region() { + assert_eq!( + launchbox_front_rank("Box - Front", "United States"), + Some(0) + ); + assert_eq!( + launchbox_front_rank("Box - Front - Reconstructed", "Europe"), + Some(12) + ); + assert_eq!(launchbox_front_rank("Box - Front", ""), Some(1)); + assert_eq!( + launchbox_front_rank("Screenshot - Gameplay", "United States"), + None + ); + assert!(launchbox_file_ok("Game-01.jpg")); + assert!(launchbox_file_ok("a.b_png.PNG")); + assert!(!launchbox_file_ok("dir/Game.jpg")); + assert!(!launchbox_file_ok("Game.bmp")); + } + + #[test] + fn launchbox_metadata_parses_games_names_and_front_files() { + let xml = "1Sony PlaystationTest Game2OtherSkipped1Test Game & More1Box - Fronttest-reconstructed.jpgEurope1Box - Fronttest-front.jpgUnited States1Screenshot - Gameplayignored.jpgUnited States"; + let (names, images) = + parse_launchbox_metadata(Cursor::new(xml), None).expect("metadata parses"); + let platform = "Sony Playstation"; + assert_eq!(names[platform]["testgame"], vec!["1".to_owned()]); + assert!(names[platform].contains_key("testgamemore")); + assert_eq!( + images[platform]["1"], + vec![ + "test-front.jpg".to_owned(), + "test-reconstructed.jpg".to_owned() + ] + ); + assert!(!names.contains_key("Other")); + } + + #[test] + fn crc32_matches_the_ieee_check_value() { + assert_eq!(crc32_update(0, b"123456789"), 0xCBF43926); + assert_eq!(crc32_update(0, b""), 0); + } + + #[test] + fn screenscraper_stays_inert_without_credentials() { + let config = json!({"screenscraper": {"user": "u", "devId": "d"}}); + assert!(!screenscraper_configured(&config)); + assert!(!screenscraper_covers("snes", &config)); + let configured = json!({"screenscraper": {"user": "u", "devId": "d", "password": "p", "devPassword": "q"}}); + assert!(screenscraper_configured(&configured)); + assert!(screenscraper_covers("snes", &configured)); + assert!(!screenscraper_covers("ps4", &configured)); + } + + #[test] + fn screenscraper_lookup_names_the_rom() { + let game = Game { + id: "snes:game".to_owned(), + system: "snes".to_owned(), + rom_path: "roms/Game (USA).sfc".to_owned(), + base: "Game (USA)".to_owned(), + title: "Game".to_owned(), + info: json!({}), + media: std::collections::HashMap::new(), + shell: None, + hidden: false, + scanned_title: None, + custom_title: false, + version: None, + media_type: None, + emulator: None, + added: None, + }; + let credentials = ScreenScraperCredentials { + user: "u".to_owned(), + dev_id: "d".to_owned(), + password: "p".to_owned(), + dev_password: "q".to_owned(), + }; + let url = screenscraper_lookup_url(&game, 4, &credentials, Some(12345), Some(0xCBF43926)); + let query = url.query().unwrap_or(""); + assert!(query.contains("systemeid=4")); + assert!(query.contains("romnom=Game+%28USA%29.sfc")); + assert!(query.contains("romtaille=12345")); + assert!(query.contains("crc=CBF43926")); + let dossier = Game { + rom_path: "roms/exefs/main".to_owned(), + ..game + }; + let url = screenscraper_lookup_url(&dossier, 4, &credentials, None, None); + let query = url.query().unwrap_or(""); + assert!(query.contains("romtype=dossier")); + assert!(query.contains("romnom=Game+%28USA%29")); + assert!(screenscraper_media_url( + "https://www.screenscraper.fr/box-2D.png" + )); + assert!(!screenscraper_media_url( + "http://www.screenscraper.fr/box-2D.png" + )); + assert!(!screenscraper_media_url("https://example.com/box-2D.png")); + } + + #[test] + fn valid_pdf_tracks_the_magic_and_nothing_else() { + assert!(valid_pdf(b"%PDF-1.4\n%%EOF")); + assert!(!valid_pdf(b"%PDF")); + assert!(!valid_pdf(b"not a pdf")); + assert!(!valid_pdf(b"")); + } + + #[test] + fn manual_keys_match_titles_without_punctuation_or_brands() { + assert_eq!(manual_loose_key("Pokemon - Ruby (U) [!]"), "pokemonruby"); + assert_eq!( + manual_loose_key("The Legend of Zelda & Friends"), + "legendofzeldafriends" + ); + assert_eq!(manual_bare_key("Disney Pixar Toy Story"), "toystory"); + assert_eq!(manual_bare_key("Toy Story"), ""); + } +} diff --git a/src-tauri/src/backend.rs b/src-tauri/src/backend.rs new file mode 100644 index 0000000..9f2bb48 --- /dev/null +++ b/src-tauri/src/backend.rs @@ -0,0 +1,3657 @@ +use crate::config::{config_for_save, load_config, save_config}; +use crate::storage::{is_content_uri, split_storage_refs}; +use serde::{Deserialize, Serialize}; +use serde_json::{Map, Value, json}; +use std::collections::{HashMap, HashSet}; +use std::fs; +use std::io::Write; +use std::path::{Path, PathBuf}; +#[cfg(not(target_os = "android"))] +use std::process::{Command, Stdio}; +use std::sync::{Arc, Mutex, RwLock}; +use tauri::{AppHandle, Emitter, Manager, State}; +#[cfg(not(target_os = "android"))] +use tauri_plugin_dialog::DialogExt; +use tauri_plugin_opener::OpenerExt; +use tauri_plugin_updater::UpdaterExt; +use url::Url; + +pub struct AppState { + pub(crate) app: AppHandle, + pub data_dir: PathBuf, + pub emu_dir: PathBuf, + pub config_path: PathBuf, + pub(crate) config: Arc>, + pub(crate) games: Arc>>, + pub(crate) artwork: Arc>, + warning: Mutex>, +} + +#[derive(Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Game { + pub id: String, + pub system: String, + pub rom_path: String, + pub base: String, + pub title: String, + pub info: Value, + pub media: HashMap, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub shell: Option, + #[serde(default)] + pub hidden: bool, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub scanned_title: Option, + #[serde(default)] + pub custom_title: bool, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub version: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub media_type: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub emulator: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub added: Option, +} + +#[derive(Clone)] +struct RomFile { + name: String, + path: PathBuf, + root: PathBuf, + root_index: usize, + size: Option, + is_dump: bool, + added: Option, + title_override: Option, +} + +struct MediaIndex { + game_dirs: HashMap, + kinds: HashMap>, + files: HashSet, +} + +#[derive(Clone)] +struct Listed { + name: String, + path: PathBuf, + is_dir: bool, + is_file: bool, +} + +#[derive(Default)] +struct ScanListings { + inner: Arc>>>>, +} + +impl ScanListings { + fn list(&self, dir: &Path) -> Arc> { + let key = dir.to_string_lossy().to_lowercase(); + if let Some(listed) = self + .inner + .lock() + .expect("listings lock poisoned") + .get(&key) + .cloned() + { + return listed; + } + let listed: Vec = fs::read_dir(dir) + .map(|entries| { + entries + .filter_map(Result::ok) + .map(|entry| Listed { + name: entry.file_name().to_string_lossy().to_string(), + path: entry.path(), + is_dir: entry.file_type().is_ok_and(|t| t.is_dir()), + is_file: entry.file_type().is_ok_and(|t| t.is_file()), + }) + .collect() + }) + .unwrap_or_default(); + let listed = Arc::new(listed); + self.inner + .lock() + .expect("listings lock poisoned") + .insert(key, listed.clone()); + listed + } +} + +const SCAN_CONCURRENCY: usize = 16; + +fn map_limit(items: &[T], limit: usize, f: &F) -> Vec +where + T: Sync, + R: Send, + F: Fn(&T) -> R + Sync, +{ + if items.is_empty() { + return Vec::new(); + } + let workers = limit.min(items.len()).max(1); + let chunk = items.len().div_ceil(workers); + std::thread::scope(|scope| { + let handles: Vec<_> = items + .chunks(chunk) + .map(|part| scope.spawn(move || part.iter().map(f).collect::>())) + .collect(); + handles + .into_iter() + .flat_map(|handle| handle.join().expect("scan worker panicked")) + .collect() + }) +} + +impl AppState { + pub fn new(app: &AppHandle) -> Result> { + let data_dir = data_directory(app)?; + let config_path = data_dir.join("config.json"); + let (config, warning) = load_config(&config_path); + fs::create_dir_all(&data_dir)?; + fs::create_dir_all(data_dir.join("emulators"))?; + log_start(&data_dir); + let _ = app.asset_protocol_scope().allow_directory(&data_dir, true); + Ok(Self { + app: app.clone(), + emu_dir: data_dir.join("emulators"), + data_dir, + config_path, + config: Arc::new(RwLock::new(config)), + games: Arc::new(RwLock::new(Vec::new())), + artwork: Arc::new(Mutex::new(crate::artwork::ArtworkControl::default())), + warning: Mutex::new(warning), + }) + } + + pub(crate) fn config(&self) -> Value { + self.config.read().expect("config lock poisoned").clone() + } +} + +fn data_directory(app: &AppHandle) -> Result> { + if cfg!(target_os = "android") { + return Ok(app.path().app_data_dir()?); + } + if let Some(portable) = std::env::var_os("PORTABLE_EXECUTABLE_DIR") { + return Ok(PathBuf::from(portable).join("data")); + } + if cfg!(debug_assertions) { + return Ok(std::env::current_dir()?.join("data")); + } + let base = if cfg!(target_os = "linux") { + dirs::config_dir() + } else { + dirs::data_dir() + } + .ok_or("could not determine the user data directory")?; + Ok(base.join("PyroCade").join("data")) +} + +#[tauri::command] +pub fn get_config(state: State<'_, AppState>) -> Value { + let mut config = state.config(); + // ScreenScraper passwords stay in the app data config; the renderer never sees them. + if let Some(object) = config.as_object_mut() { + object.remove("screenscraper"); + } + if let Some(warning) = state.warning.lock().expect("warning lock poisoned").take() { + let app = state.app.clone(); + std::thread::spawn(move || { + std::thread::sleep(std::time::Duration::from_millis(300)); + let _ = app.emit("toast", warning); + }); + } + config +} + +#[tauri::command] +pub fn set_config(state: State<'_, AppState>, cfg: Value) -> Result { + let mut current = state.config.write().map_err(|e| e.to_string())?; + let mut cfg = cfg; + // ScreenScraper credentials are owned by the backend; the renderer cannot overwrite them. + if let Some(section) = current.get("screenscraper") { + cfg["screenscraper"] = section.clone(); + } else if let Some(object) = cfg.as_object_mut() { + object.remove("screenscraper"); + } + let next = config_for_save(cfg, ¤t)?; + save_config(&state.config_path, &next)?; + *current = next.clone(); + Ok(next) +} + +#[tauri::command] +pub async fn scan_library( + app: AppHandle, + state: State<'_, AppState>, + with_report: Option, + options: Option, +) -> Result>, String> { + let config = state.config(); + let only_if_changed = options + .as_ref() + .and_then(|o| o.get("onlyIfChanged")) + .and_then(Value::as_bool) + .unwrap_or(false); + let with_report = with_report.unwrap_or(false); + let (cached_raw, known_sizes) = read_library_cache(&config, &state.data_dir); + let data_dir = state.data_dir.clone(); + let app_for_scan = app.clone(); + let config_for_scan = config.clone(); + let known_sizes_for_scan = known_sizes.clone(); + let outcome = tauri::async_runtime::spawn_blocking(move || { + scan( + &app_for_scan, + &config_for_scan, + &data_dir, + &known_sizes_for_scan, + with_report, + ) + }) + .await + .map_err(|e| e.to_string())??; + let raw_text = serde_json::to_string(&outcome.games).map_err(|e| e.to_string())?; + let changed = write_library_cache( + &config, + &state.data_dir, + &raw_text, + &outcome.sizes, + cached_raw.as_ref(), + ); + if only_if_changed && !with_report && !changed { + return Ok(None); + } + let mut games = outcome.games; + apply_library_state(&mut games, &config); + *state.games.write().map_err(|e| e.to_string())? = games.clone(); + Ok(Some(games)) +} + +#[tauri::command] +pub async fn cached_library(state: State<'_, AppState>) -> Result>, String> { + let config = state.config(); + let data_dir = state.data_dir.clone(); + let config_for_read = config.clone(); + let (cached_raw, _known_sizes) = tauri::async_runtime::spawn_blocking(move || { + read_library_cache(&config_for_read, &data_dir) + }) + .await + .map_err(|e| e.to_string())?; + let Some(cached) = cached_raw else { + return Ok(None); + }; + let mut games = cached; + apply_library_state(&mut games, &config); + *state.games.write().map_err(|e| e.to_string())? = games.clone(); + Ok(Some(games)) +} + +fn library_cache_key(config: &Value) -> Value { + let systems: Vec = config + .get("systems") + .and_then(Value::as_array) + .map(|systems| { + systems + .iter() + .map(|system| { + json!([ + system.get("id").and_then(Value::as_str).unwrap_or(""), + system.get("romDir").and_then(Value::as_str).unwrap_or(""), + system.get("extensions").cloned().unwrap_or(json!([])), + system + .get("direct") + .and_then(Value::as_bool) + .unwrap_or(false), + ]) + }) + .collect() + }) + .unwrap_or_default(); + json!({ + "version": app_version(), + "mediaRoot": config.get("mediaRoot").and_then(Value::as_str).unwrap_or(""), + "extraGames": config.get("extraGames").cloned().unwrap_or(json!([])), + "systems": systems, + }) +} + +fn read_library_cache( + config: &Value, + data_dir: &Path, +) -> (Option>, HashMap) { + let path = data_dir.join("library-cache.json"); + let Ok(text) = fs::read_to_string(&path) else { + return (None, HashMap::new()); + }; + let Ok(cached) = serde_json::from_str::(&text) else { + return (None, HashMap::new()); + }; + let sizes: HashMap = cached + .get("sizes") + .and_then(Value::as_object) + .map(|sizes| { + sizes + .iter() + .filter_map(|(path, size)| size.as_u64().map(|size| (path.clone(), size))) + .collect() + }) + .unwrap_or_default(); + if cached.get("key") != Some(&library_cache_key(config)) { + return (None, sizes); + } + let games: Option> = cached + .get("games") + .and_then(|games| serde_json::from_value(games.clone()).ok()) + .filter(|games: &Vec| !games.is_empty()); + (games, sizes) +} + +fn write_library_cache( + config: &Value, + data_dir: &Path, + raw_text: &str, + sizes: &HashMap, + cached_raw: Option<&Vec>, +) -> bool { + let previous_text = cached_raw + .map(|games| serde_json::to_string(games).unwrap_or_default()) + .unwrap_or_default(); + let changed = raw_text != previous_text; + let sizes_text = serde_json::to_string(sizes).unwrap_or_default(); + let previous_sizes_text = { + let (_games, previous_sizes) = read_library_cache(config, data_dir); + serde_json::to_string(&previous_sizes).unwrap_or_default() + }; + if !changed && sizes_text == previous_sizes_text { + return false; + } + let _ = fs::create_dir_all(data_dir); + let tmp = data_dir.join("library-cache.json.tmp"); + let payload = format!( + "{{\"key\":{},\"sizes\":{},\"games\":{}}}", + library_cache_key(config), + sizes_text, + raw_text + ); + if fs::write(&tmp, payload).is_ok() { + let _ = fs::rename(&tmp, data_dir.join("library-cache.json")); + } + changed +} + +/// Apply collection state: favorites, hidden, renames, per-game details/emulator, orders. +fn apply_library_state(games: &mut Vec, config: &Value) { + let favorites: Vec = config + .get("favorites") + .and_then(Value::as_array) + .map(|arr| { + arr.iter() + .filter_map(Value::as_str) + .map(str::to_owned) + .collect() + }) + .unwrap_or_default(); + + let hidden_games: std::collections::HashSet = config + .get("hiddenGames") + .and_then(Value::as_array) + .map(|arr| { + arr.iter() + .filter_map(Value::as_str) + .map(str::to_owned) + .collect() + }) + .unwrap_or_default(); + + let game_details = config + .get("gameDetails") + .and_then(Value::as_object) + .cloned() + .unwrap_or_default(); + let game_emulators = config + .get("gameEmulators") + .and_then(Value::as_object) + .cloned() + .unwrap_or_default(); + let game_orders = config + .get("gameOrders") + .and_then(Value::as_object) + .cloned() + .unwrap_or_default(); + + // Annotate each scanned game with its collection state before sorting/filtering. + for game in games.iter_mut() { + if game.scanned_title.is_none() { + game.scanned_title = Some(game.title.clone()); + } + let scanned = game + .scanned_title + .clone() + .unwrap_or_else(|| game.title.clone()); + game.hidden = hidden_games.contains(&game.id); + if let Some(details) = game_details.get(&game.id).and_then(Value::as_object) { + let custom_title = details + .get("title") + .and_then(Value::as_str) + .map(str::trim) + .filter(|s| !s.is_empty()) + .filter(|s| *s != scanned); + if let Some(title) = custom_title { + game.title = title.to_owned(); + game.custom_title = true; + } else { + game.title = scanned.clone(); + game.custom_title = false; + } + game.version = details + .get("version") + .and_then(Value::as_str) + .map(str::trim) + .filter(|s| !s.is_empty()) + .map(str::to_owned); + game.media_type = details + .get("mediaType") + .and_then(Value::as_str) + .map(str::trim) + .filter(|s| !s.is_empty()) + .map(str::to_owned); + } else { + game.title = scanned.clone(); + game.custom_title = false; + game.version = None; + game.media_type = None; + } + if let Some(emulator) = game_emulators.get(&game.id).and_then(Value::as_str) { + let emulator = emulator.trim(); + game.emulator = if emulator.is_empty() { + None + } else { + Some(emulator.to_owned()) + }; + } else { + game.emulator = None; + } + } + + let recently_played: Vec = config + .get("recentlyPlayed") + .and_then(Value::as_array) + .cloned() + .unwrap_or_default(); + + let limit: usize = config + .get("recentlyPlayedLimit") + .and_then(Value::as_u64) + .unwrap_or(20) as usize; + + let show_favorites_only = config + .get("showFavoritesOnly") + .and_then(Value::as_bool) + .unwrap_or(false); + + let show_recently_played = config + .get("showRecentlyPlayed") + .and_then(Value::as_bool) + .unwrap_or(false); + + let sort_key: &str = config + .get("sortKey") + .and_then(Value::as_str) + .unwrap_or("title"); + + let sort_asc = config + .get("sortAsc") + .and_then(Value::as_bool) + .unwrap_or(true); + + // Build a set of favorite IDs for fast lookup. + let fav_set: std::collections::HashSet<&str> = favorites.iter().map(|s| s.as_str()).collect(); + + // Filter to favorites only if requested. + if show_favorites_only { + games.retain(|g| fav_set.contains(g.id.as_str())); + } + + // Inject recently played games that are not already in the library. + if show_recently_played { + let existing_ids: std::collections::HashSet<&str> = + games.iter().map(|g| g.id.as_str()).collect(); + let mut injected: Vec = recently_played + .iter() + .filter(|rp| { + let gid = rp.get("id").and_then(Value::as_str); + gid.map(|id| !existing_ids.contains(id)).unwrap_or(false) + }) + .filter_map(|rp| { + let id = rp.get("id")?.as_str()?.to_owned(); + let title = rp.get("title")?.as_str()?.to_owned(); + Some(Game { + id, + system: String::new(), + rom_path: String::new(), + base: String::new(), + title, + info: Value::Object(serde_json::Map::new()), + media: HashMap::new(), + shell: None, + hidden: false, + scanned_title: None, + custom_title: false, + version: None, + media_type: None, + emulator: None, + added: None, + }) + }) + .collect(); + // Sort injected by timestamp descending (most recent first). + injected.sort_by(|a, b| { + let ta = recently_played + .iter() + .find(|rp| rp.get("id").and_then(Value::as_str) == Some(&a.id)) + .and_then(|rp| rp.get("timestamp").and_then(Value::as_u64)) + .unwrap_or(0); + let tb = recently_played + .iter() + .find(|rp| rp.get("id").and_then(Value::as_str) == Some(&b.id)) + .and_then(|rp| rp.get("timestamp").and_then(Value::as_u64)) + .unwrap_or(0); + tb.cmp(&ta) + }); + let injected: Vec = injected.into_iter().take(limit).collect(); + games.extend(injected); + } + + // Sort by the configured key. + games.sort_by(|a, b| { + let cmp = match sort_key { + "title" => a.title.to_lowercase().cmp(&b.title.to_lowercase()), + "system" => a.system.cmp(&b.system), + "favorites" => { + let fa = fav_set.contains(a.id.as_str()) as u8; + let fb = fav_set.contains(b.id.as_str()) as u8; + fb.cmp(&fa) // favorites first + } + "recent" => { + let ta = config + .get("recentlyPlayed") + .and_then(Value::as_array) + .and_then(|arr| { + arr.iter().find_map(|rp| { + rp.get("id").and_then(Value::as_str).and_then(|id| { + if id == a.id { + rp.get("timestamp").and_then(Value::as_u64) + } else { + None + } + }) + }) + }) + .unwrap_or(0); + let tb = config + .get("recentlyPlayed") + .and_then(Value::as_array) + .and_then(|arr| { + arr.iter().find_map(|rp| { + rp.get("id").and_then(Value::as_str).and_then(|id| { + if id == b.id { + rp.get("timestamp").and_then(Value::as_u64) + } else { + None + } + }) + }) + }) + .unwrap_or(0); + tb.cmp(&ta) // most recent first + } + "custom" => { + let rank = |game: &Game| { + game_orders + .get(&game.system) + .and_then(Value::as_array) + .and_then(|ids| ids.iter().position(|id| id.as_str() == Some(&game.id))) + .unwrap_or(usize::MAX) + }; + let a_rank = rank(a); + let b_rank = rank(b); + if a.system != b.system { + a.system.cmp(&b.system) + } else if a_rank != b_rank { + a_rank.cmp(&b_rank) + } else { + a.title.to_lowercase().cmp(&b.title.to_lowercase()) + } + } + _ => a.title.to_lowercase().cmp(&b.title.to_lowercase()), + }; + if sort_key == "custom" { + cmp + } else if sort_asc { + cmp + } else { + cmp.reverse() + } + }); +} + +#[tauri::command] +pub fn toggle_favorite(state: State<'_, AppState>, game_id: String) -> Result { + let mut config = state.config.write().map_err(|e| e.to_string())?; + let mut favorites: Vec = config + .get_mut("favorites") + .and_then(Value::as_array_mut) + .map(|arr| { + arr.iter() + .filter_map(Value::as_str) + .map(str::to_owned) + .collect() + }) + .unwrap_or_default(); + + let is_favorite = favorites.contains(&game_id); + if is_favorite { + favorites.retain(|id| id != &game_id); + } else { + favorites.push(game_id); + } + *config.get_mut("favorites").unwrap() = + Value::Array(favorites.into_iter().map(Value::String).collect()); + let config_clone = config.clone(); + drop(config); + save_config(&state.config_path, &config_clone)?; + Ok(json!({"isFavorite": !is_favorite})) +} + +#[tauri::command] +pub fn record_play( + state: State<'_, AppState>, + game_id: String, + play_time: f64, +) -> Result<(), String> { + let mut config = state.config.write().map_err(|e| e.to_string())?; + let mut recently_played: Vec = config + .get_mut("recentlyPlayed") + .and_then(Value::as_array_mut) + .map(|arr| arr.iter().cloned().collect()) + .unwrap_or_default(); + + // Remove existing entry for this game if present. + recently_played.retain(|rp| rp.get("id").and_then(Value::as_str) != Some(&game_id)); + + // Add new entry at the front. + let entry = json!({ + "id": game_id, + "timestamp": chrono::Utc::now().timestamp_millis(), + "playTime": play_time + }); + recently_played.insert(0, entry); + + let limit: usize = config + .get("recentlyPlayedLimit") + .and_then(Value::as_u64) + .unwrap_or(20) as usize; + recently_played.truncate(limit); + + *config.get_mut("recentlyPlayed").unwrap() = Value::Array( + recently_played + .into_iter() + .map(|v| Value::Object(v.as_object().unwrap().clone())) + .collect(), + ); + let config_clone = config.clone(); + drop(config); + save_config(&state.config_path, &config_clone)?; + Ok(()) +} + +#[tauri::command] +pub fn update_library_prefs(state: State<'_, AppState>, prefs: Value) -> Result { + let mut config = state.config.write().map_err(|e| e.to_string())?; + if let Some(sort_key) = prefs.get("sortKey").and_then(Value::as_str) { + config["sortKey"] = json!(sort_key); + } + if let Some(sort_asc) = prefs.get("sortAsc").and_then(Value::as_bool) { + config["sortAsc"] = json!(sort_asc); + } + if let Some(show_fav) = prefs.get("showFavoritesOnly").and_then(Value::as_bool) { + config["showFavoritesOnly"] = json!(show_fav); + } + if let Some(show_rec) = prefs.get("showRecentlyPlayed").and_then(Value::as_bool) { + config["showRecentlyPlayed"] = json!(show_rec); + } + if let Some(limit) = prefs.get("recentlyPlayedLimit").and_then(Value::as_u64) { + config["recentlyPlayedLimit"] = json!(limit); + } + let config_clone = config.clone(); + drop(config); + save_config(&state.config_path, &config_clone)?; + Ok(config_clone) +} + +#[tauri::command] +pub fn get_favorites(state: State<'_, AppState>) -> Vec { + state + .config() + .get("favorites") + .and_then(Value::as_array) + .map(|arr| { + arr.iter() + .filter_map(Value::as_str) + .map(str::to_owned) + .collect() + }) + .unwrap_or_default() +} + +#[tauri::command] +pub fn get_recently_played(state: State<'_, AppState>, _limit: usize) -> Vec { + state + .config() + .get("recentlyPlayed") + .and_then(Value::as_array) + .cloned() + .unwrap_or_default() +} + +// Hiding writes to the collection state; the ROM folder is never renamed, moved or deleted. +#[tauri::command] +pub fn set_game_hidden( + state: State<'_, AppState>, + game_id: String, + hidden: bool, +) -> Result { + { + let games = state.games.read().map_err(|e| e.to_string())?; + if !games.iter().any(|g| g.id == game_id) { + return Err("Select a game in your library first.".to_owned()); + } + } + let mut config = state.config.write().map_err(|e| e.to_string())?; + let mut hidden_games: Vec = config + .get_mut("hiddenGames") + .and_then(Value::as_array_mut) + .map(|arr| { + arr.iter() + .filter_map(Value::as_str) + .map(str::to_owned) + .collect() + }) + .unwrap_or_default(); + if hidden { + if !hidden_games.contains(&game_id) { + hidden_games.push(game_id.clone()); + } + } else { + hidden_games.retain(|id| id != &game_id); + } + *config.get_mut("hiddenGames").unwrap() = + Value::Array(hidden_games.into_iter().map(Value::String).collect()); + let config_clone = config.clone(); + drop(config); + save_config(&state.config_path, &config_clone)?; + let mut games = state.games.write().map_err(|e| e.to_string())?; + let game = games + .iter_mut() + .find(|g| g.id == game_id) + .ok_or_else(|| "Select a game in your library first.".to_owned())?; + game.hidden = hidden; + Ok(game.clone()) +} + +#[tauri::command] +pub fn set_system_games_hidden( + state: State<'_, AppState>, + system: String, + hidden: bool, +) -> Result, String> { + let config_snapshot = state.config(); + if !config_snapshot + .get("systems") + .and_then(Value::as_array) + .is_some_and(|systems| { + systems + .iter() + .any(|s| s.get("id").and_then(Value::as_str) == Some(system.as_str())) + }) + { + return Err("Unknown system.".to_owned()); + } + let system_games: Vec = { + let games = state.games.read().map_err(|e| e.to_string())?; + games + .iter() + .filter(|g| g.system == system) + .map(|g| g.id.clone()) + .collect() + }; + let mut config = state.config.write().map_err(|e| e.to_string())?; + let mut hidden_games: Vec = config + .get_mut("hiddenGames") + .and_then(Value::as_array_mut) + .map(|arr| { + arr.iter() + .filter_map(Value::as_str) + .map(str::to_owned) + .collect() + }) + .unwrap_or_default(); + for game_id in &system_games { + if hidden { + if !hidden_games.contains(game_id) { + hidden_games.push(game_id.clone()); + } + } else { + hidden_games.retain(|id| id != game_id); + } + } + *config.get_mut("hiddenGames").unwrap() = + Value::Array(hidden_games.into_iter().map(Value::String).collect()); + let config_clone = config.clone(); + drop(config); + save_config(&state.config_path, &config_clone)?; + let mut games = state.games.write().map_err(|e| e.to_string())?; + let mut updated = Vec::new(); + for game in games.iter_mut() { + if game.system == system { + game.hidden = hidden; + updated.push(game.clone()); + } + } + Ok(updated) +} + +// The details editor (M03) is the only writer of title/version/mediaType overrides. +#[tauri::command] +pub fn set_game_metadata(state: State<'_, AppState>, opts: Value) -> Result { + let game_id = opts + .get("gameId") + .and_then(Value::as_str) + .unwrap_or("") + .to_owned(); + if game_id.is_empty() { + return Err("Select a game in your library first.".to_owned()); + } + { + let games = state.games.read().map_err(|e| e.to_string())?; + if !games.iter().any(|g| g.id == game_id) { + return Err("Select a game in your library first.".to_owned()); + } + } + let has_title = opts.get("title").and_then(Value::as_str).is_some(); + let title_raw = opts + .get("title") + .and_then(Value::as_str) + .unwrap_or("") + .to_owned(); + let has_version = opts.get("version").and_then(Value::as_str).is_some(); + let version_raw = opts + .get("version") + .and_then(Value::as_str) + .unwrap_or("") + .to_owned(); + let has_media = opts.get("mediaType").and_then(Value::as_str).is_some(); + let media_raw = opts + .get("mediaType") + .and_then(Value::as_str) + .unwrap_or("") + .to_owned(); + if has_title { + let trimmed = title_raw.split_whitespace().collect::>().join(" "); + if !trimmed.is_empty() && trimmed.len() > 200 { + return Err("Enter a title of up to 200 characters.".to_owned()); + } + } + if has_version && version_raw.trim().len() > 80 { + return Err("Enter a version of up to 80 characters.".to_owned()); + } + if has_media + && !["", "disc", "switch", "switch2", "gba", "n64", "nds"].contains(&media_raw.trim()) + { + return Err("Choose a supported media type.".to_owned()); + } + + let mut config = state.config.write().map_err(|e| e.to_string())?; + let details_map = config + .get_mut("gameDetails") + .and_then(Value::as_object_mut) + .ok_or("Invalid game details")? + .entry(game_id.clone()) + .or_insert_with(|| json!({})); + let details_obj = details_map.as_object_mut().ok_or("Invalid game details")?; + let scanned_title = { + let games = state.games.read().map_err(|e| e.to_string())?; + games + .iter() + .find(|g| g.id == game_id) + .and_then(|g| g.scanned_title.clone()) + .unwrap_or_default() + }; + if has_title { + let trimmed = title_raw.split_whitespace().collect::>().join(" "); + if trimmed.is_empty() || trimmed == scanned_title { + details_obj.remove("title"); + } else { + details_obj.insert("title".to_owned(), Value::String(trimmed)); + } + } + if has_version { + let trimmed = version_raw.trim().to_owned(); + if trimmed.is_empty() { + details_obj.remove("version"); + } else { + details_obj.insert("version".to_owned(), Value::String(trimmed)); + } + } + if has_media { + let trimmed = media_raw.trim().to_owned(); + if trimmed.is_empty() { + details_obj.remove("mediaType"); + } else { + details_obj.insert("mediaType".to_owned(), Value::String(trimmed)); + } + } + if details_obj.is_empty() { + if let Some(map) = config.get_mut("gameDetails").and_then(Value::as_object_mut) { + map.remove(&game_id); + } + } + let config_clone = config.clone(); + drop(config); + save_config(&state.config_path, &config_clone)?; + let mut games = state.games.write().map_err(|e| e.to_string())?; + let game = games + .iter_mut() + .find(|g| g.id == game_id) + .ok_or_else(|| "Select a game in your library first.".to_owned())?; + let scanned = game + .scanned_title + .clone() + .unwrap_or_else(|| game.title.clone()); + let custom = config_clone + .get("gameDetails") + .and_then(|v| v.get(&game_id)) + .and_then(|v| v.get("title")) + .and_then(Value::as_str) + .map(str::trim) + .filter(|s| !s.is_empty() && *s != scanned); + if let Some(title) = custom { + game.title = title.to_owned(); + game.custom_title = true; + } else { + game.title = scanned.clone(); + game.custom_title = false; + } + game.version = config_clone + .get("gameDetails") + .and_then(|v| v.get(&game_id)) + .and_then(|v| v.get("version")) + .and_then(Value::as_str) + .map(str::trim) + .filter(|s| !s.is_empty()) + .map(str::to_owned); + game.media_type = config_clone + .get("gameDetails") + .and_then(|v| v.get(&game_id)) + .and_then(|v| v.get("mediaType")) + .and_then(Value::as_str) + .map(str::trim) + .filter(|s| !s.is_empty()) + .map(str::to_owned); + Ok(game.clone()) +} + +#[tauri::command] +pub fn set_game_emulator(state: State<'_, AppState>, opts: Value) -> Result { + let game_id = opts + .get("gameId") + .and_then(Value::as_str) + .unwrap_or("") + .to_owned(); + if game_id.is_empty() { + return Err("Select a game in your library first.".to_owned()); + } + let emulator_raw = opts + .get("emulator") + .and_then(Value::as_str) + .map(str::trim) + .unwrap_or("") + .to_owned(); + { + let games = state.games.read().map_err(|e| e.to_string())?; + if !games.iter().any(|g| g.id == game_id) { + return Err("Select a game in your library first.".to_owned()); + } + } + if !emulator_raw.is_empty() && emulator_raw != "__direct" { + let config_snapshot = state.config(); + if crate::emulators::find_definition(&emulator_raw, &config_snapshot).is_none() { + return Err("That emulator is no longer set up.".to_owned()); + } + } + let mut config = state.config.write().map_err(|e| e.to_string())?; + let map = config + .get_mut("gameEmulators") + .and_then(Value::as_object_mut) + .ok_or("Invalid emulator settings")?; + if emulator_raw.is_empty() { + map.remove(&game_id); + } else { + map.insert(game_id.clone(), Value::String(emulator_raw.clone())); + } + let config_clone = config.clone(); + drop(config); + save_config(&state.config_path, &config_clone)?; + let mut games = state.games.write().map_err(|e| e.to_string())?; + let game = games + .iter_mut() + .find(|g| g.id == game_id) + .ok_or_else(|| "Select a game in your library first.".to_owned())?; + game.emulator = if emulator_raw.is_empty() { + None + } else { + Some(emulator_raw) + }; + Ok(game.clone()) +} + +#[tauri::command] +pub fn save_game_order(state: State<'_, AppState>, opts: Value) -> Result, String> { + let system = opts + .get("system") + .and_then(Value::as_str) + .unwrap_or("") + .to_owned(); + if system.is_empty() { + return Err("Choose a console to reorder.".to_owned()); + } + let game_ids: Vec = opts + .get("gameIds") + .and_then(Value::as_array) + .map(|arr| { + arr.iter() + .filter_map(Value::as_str) + .map(str::to_owned) + .collect() + }) + .unwrap_or_default(); + let config_snapshot = state.config(); + if !config_snapshot + .get("systems") + .and_then(Value::as_array) + .is_some_and(|systems| { + systems + .iter() + .any(|s| s.get("id").and_then(Value::as_str) == Some(system.as_str())) + }) + { + return Err("Choose a console to reorder.".to_owned()); + } + let actual: Vec = { + let games = state.games.read().map_err(|e| e.to_string())?; + games + .iter() + .filter(|g| g.system == system) + .map(|g| g.id.clone()) + .collect() + }; + let valid: HashSet<&str> = actual.iter().map(String::as_str).collect(); + let mut seen = HashSet::new(); + for id in &game_ids { + if !valid.contains(id.as_str()) || !seen.insert(id.as_str()) { + return Err( + "The game order does not match this console. Rescan and try again.".to_owned(), + ); + } + } + let mut order = game_ids.clone(); + for id in &actual { + if !order.contains(id) { + order.push(id.clone()); + } + } + let mut config = state.config.write().map_err(|e| e.to_string())?; + let map = config + .get_mut("gameOrders") + .and_then(Value::as_object_mut) + .ok_or("Invalid game orders")?; + map.insert( + system.clone(), + Value::Array(order.iter().map(|id| Value::String(id.clone())).collect()), + ); + let config_clone = config.clone(); + drop(config); + save_config(&state.config_path, &config_clone)?; + Ok(order) +} + +#[tauri::command] +pub fn list_extra_games(state: State<'_, AppState>) -> Vec { + let config = state.config(); + config + .get("extraGames") + .and_then(Value::as_array) + .cloned() + .unwrap_or_default() + .into_iter() + .map(|entry| { + let path = entry.get("path").and_then(Value::as_str).unwrap_or(""); + let missing = + !path.is_empty() && !is_content_uri(path) && !std::path::Path::new(path).exists(); + json!({ + "id": entry.get("id").and_then(Value::as_str).unwrap_or(""), + "system": entry.get("system").and_then(Value::as_str).unwrap_or(""), + "path": path, + "title": entry.get("title").and_then(Value::as_str).unwrap_or(""), + "missing": missing, + }) + }) + .collect() +} + +#[tauri::command] +pub fn remove_game(state: State<'_, AppState>, id: String) -> Result { + let mut config = state.config.write().map_err(|e| e.to_string())?; + if let Some(extra) = config.get_mut("extraGames").and_then(Value::as_array_mut) { + extra.retain(|x| x.get("id").and_then(Value::as_str) != Some(&id)); + } + let config_clone = config.clone(); + drop(config); + save_config(&state.config_path, &config_clone)?; + Ok(true) +} + +/// Adds one game file to a system without a ROM folder. Opens the native +/// file picker, so it must be `async` like other dialog commands. +#[cfg(not(target_os = "android"))] +#[tauri::command] +pub async fn add_game( + app: AppHandle, + state: State<'_, AppState>, + opts: Value, +) -> Result, String> { + let system = opts + .get("system") + .and_then(Value::as_str) + .unwrap_or("") + .to_owned(); + if system.is_empty() { + return Err("Choose a system first.".to_owned()); + } + let config_snapshot = state.config(); + let sys = config_snapshot + .get("systems") + .and_then(Value::as_array) + .and_then(|systems| { + systems + .iter() + .find(|s| s.get("id").and_then(Value::as_str) == Some(system.as_str())) + .cloned() + }) + .ok_or_else(|| "Choose a system first.".to_owned())?; + let sys_name = sys + .get("name") + .and_then(Value::as_str) + .unwrap_or(&system) + .to_owned(); + let Some(path) = app + .dialog() + .file() + .set_title(format!("Add a game to {sys_name}")) + .blocking_pick_file() + .and_then(|p| p.into_path().ok()) + else { + return Ok(None); + }; + let path_string = path.to_string_lossy().to_owned(); + let mut config = state.config.write().map_err(|e| e.to_string())?; + let extra = config + .get_mut("extraGames") + .and_then(Value::as_array_mut) + .ok_or("Invalid settings")?; + if extra.iter().any(|x| { + x.get("system").and_then(Value::as_str) == Some(system.as_str()) + && x.get("path") + .and_then(Value::as_str) + .is_some_and(|p| Path::new(p) == path.as_path()) + }) { + return Err("That game is already in your library.".to_owned()); + } + let file_name = path + .file_name() + .and_then(|s| s.to_str()) + .unwrap_or("") + .to_owned(); + let guess = { + let stem_name = Path::new(&file_name) + .file_stem() + .and_then(|s| s.to_str()) + .unwrap_or(&file_name) + .to_owned(); + let ext = path + .extension() + .and_then(|s| s.to_str()) + .unwrap_or("") + .to_lowercase(); + if (ext == "exe" || ext == "app") + && path + .parent() + .and_then(|p| p.file_name()) + .and_then(|s| s.to_str()) + .is_some_and(|s| s.len() > 2) + { + path.parent() + .and_then(|p| p.file_name()) + .and_then(|s| s.to_str()) + .unwrap_or(&stem_name) + .to_owned() + } else { + display_title(&stem_name) + } + }; + let title_over = opts + .get("title") + .and_then(Value::as_str) + .map(str::trim) + .filter(|s| !s.is_empty()) + .map(|s| s.chars().take(120).collect::()); + let title = title_over.unwrap_or(guess); + let entry = json!({ + "id": uuid::Uuid::new_v4().to_string()[..8].to_owned(), + "system": system, + "path": path_string, + "title": title, + }); + extra.push(entry.clone()); + let config_clone = config.clone(); + drop(config); + save_config(&state.config_path, &config_clone)?; + Ok(Some(entry)) +} + +#[cfg(target_os = "android")] +#[tauri::command] +pub fn add_game( + _app: AppHandle, + _state: State<'_, AppState>, + _opts: Value, +) -> Result, String> { + Err( + "Adding a single file on Android needs a document grant; use a ROM folder instead." + .to_owned(), + ) +} + +fn wait_for_child( + child: std::process::Child, + window: Option, +) -> std::thread::JoinHandle<()> { + std::thread::spawn(move || { + let mut child = child; + let _ = child.wait(); + #[cfg(target_os = "android")] + let _ = window; + #[cfg(not(target_os = "android"))] + if let Some(window) = window { + let _ = window.unminimize(); + let _ = window.set_focus(); + } + }) +} + +// ---------- Launch logging and Steam/gamescope environment ---------- +// Main wrote data/logs/pyrocade.log so a start that fails on someone else's device +// can be looked at without asking them to run anything. Launch children inherit +// the parent environment; the only per-child change is the Steam LD sanitization +// below (and nothing at all on Android, where ROM URIs stay untouched). +fn log_path(data_dir: &Path) -> PathBuf { + data_dir.join("logs").join("pyrocade.log") +} + +fn append_launch_log(data_dir: &Path, entry: &str) { + let path = log_path(data_dir); + if let Some(dir) = path.parent() { + if fs::create_dir_all(dir).is_err() { + return; + } + } + if let Ok(meta) = fs::metadata(&path) { + if meta.len() > 512 * 1024 { + let _ = fs::rename(&path, path.with_extension("log.old")); + } + } + if let Ok(mut file) = fs::OpenOptions::new().create(true).append(true).open(&path) { + let stamp = chrono::Utc::now().to_rfc3339(); + let _ = writeln!(file, "{stamp} {entry}"); + } +} + +fn env_or_empty(name: &str) -> String { + std::env::var(name).unwrap_or_default() +} + +fn log_start(data_dir: &Path) { + let desktop = env_or_empty("XDG_CURRENT_DESKTOP"); + let session = env_or_empty("XDG_SESSION_TYPE"); + let display = env_or_empty("DISPLAY"); + let wayland = !env_or_empty("WAYLAND_DISPLAY").is_empty() + || !env_or_empty("GAMESCOPE_WAYLAND_DISPLAY").is_empty(); + let steam = steam_start_detected(cfg!(target_os = "linux"), &|name| std::env::var(name).ok()); + let app_image = !env_or_empty("APPIMAGE").is_empty(); + append_launch_log( + data_dir, + &format!( + "start {} platform={} arch={} desktop={} session={} wayland={} display={} steam={} appImage={}", + app_version(), + std::env::consts::OS, + std::env::consts::ARCH, + desktop, + session, + wayland, + display, + steam, + app_image + ), + ); +} + +fn steam_start_detected(is_linux: bool, get: &dyn Fn(&str) -> Option) -> bool { + if !is_linux { + return false; + } + for key in ["SteamGameId", "SteamAppId", "STEAM_COMPAT_APP_ID"] { + if get(key).is_some_and(|v| !v.trim().is_empty()) { + return true; + } + } + is_gamescope(get) +} + +fn is_gamescope(get: &dyn Fn(&str) -> Option) -> bool { + get("XDG_CURRENT_DESKTOP").as_deref() == Some("gamescope") + || get("GAMESCOPE_WAYLAND_DISPLAY").is_some_and(|v| !v.trim().is_empty()) +} + +fn steam_filtered_ld_library_path(value: &str) -> Option { + let kept: Vec<&str> = value + .split(':') + .filter(|entry| { + if entry.is_empty() { + return false; + } + let lower = entry.to_lowercase(); + !(lower.contains("steam-runtime") + || lower.contains("steamrt") + || lower.contains("ubuntu12_32") + || lower.contains("ubuntu12_64") + || lower.contains("pressure-vessel") + || lower.contains("/steam/")) + }) + .collect(); + if kept.is_empty() { + None + } else { + Some(kept.join(":")) + } +} + +fn log_launch(data_dir: &Path, kind: &str, game_id: &str, emulator_id: &str, fix_note: &str) { + if fix_note.is_empty() { + append_launch_log( + data_dir, + &format!("launch kind={kind} game={game_id} emulator={emulator_id}"), + ); + } else { + append_launch_log( + data_dir, + &format!( + "launch kind={kind} game={game_id} emulator={emulator_id} steamFix={fix_note}" + ), + ); + } +} + +#[cfg(not(target_os = "android"))] +fn apply_steam_fix_to_command(command: &mut Command) -> String { + if !cfg!(target_os = "linux") { + return String::new(); + } + let mut notes: Vec = Vec::new(); + if std::env::var_os("LD_PRELOAD").is_some() { + command.env_remove("LD_PRELOAD"); + notes.push("cleared LD_PRELOAD".to_owned()); + } + if let Ok(ld_library) = std::env::var("LD_LIBRARY_PATH") { + if let Some(kept) = steam_filtered_ld_library_path(&ld_library) { + if kept != ld_library { + command.env("LD_LIBRARY_PATH", &kept); + notes.push("removed Steam libraries from LD_LIBRARY_PATH".to_owned()); + } + } else if !ld_library.is_empty() { + command.env_remove("LD_LIBRARY_PATH"); + notes.push("removed Steam libraries from LD_LIBRARY_PATH".to_owned()); + } + } + if is_gamescope(&|name| std::env::var(name).ok()) && std::env::var_os("DISPLAY").is_none() { + notes.push("DISPLAY unset under gamescope; X11 emulators may fail".to_owned()); + } + notes.join(", ") +} + +#[cfg_attr(not(target_os = "android"), allow(dead_code))] +pub(crate) fn android_launch_target(package: &str, rom_uri: &str) -> Result { + // ROM URIs are passed through unchanged: a SAF content URI is not a + // filesystem path and is never converted into one here. + if package.trim().is_empty() { + return Err("No Android emulator package is linked.".to_owned()); + } + if rom_uri.trim().is_empty() { + return Err("This game has no ROM location yet.".to_owned()); + } + Ok(rom_uri.to_owned()) +} + +#[cfg(not(target_os = "android"))] +fn launch_direct( + app: &AppHandle, + state: &AppState, + config: &Value, + game: &Game, +) -> Result { + let file = Path::new(&game.rom_path); + if !file.exists() { + let name = file + .file_name() + .and_then(|s| s.to_str()) + .unwrap_or(&game.rom_path); + return Err(format!("{} is missing. Rescan in Settings.", name)); + } + #[cfg(unix)] + let is_app = file.extension().and_then(|s| s.to_str()) == Some("app"); + #[cfg(not(unix))] + let is_app = false; + #[cfg(unix)] + let is_program = is_app + || fs::metadata(file) + .map(|m| { + use std::os::unix::fs::PermissionsExt; + m.permissions().mode() & 0o111 != 0 + }) + .unwrap_or(false); + #[cfg(not(unix))] + let is_program = file.extension().and_then(|s| s.to_str()) == Some("exe"); + if !is_program { + app.opener() + .open_path(&game.rom_path, None::<&str>) + .map_err(|e| format!("Couldn't open: {e}"))?; + log_launch(&state.data_dir, "direct-opener", &game.id, "", ""); + return Ok(true); + } + let executable = file.to_path_buf(); + let app_bundle = cfg!(target_os = "macos") + .then(|| { + executable + .ancestors() + .find(|p| p.extension().and_then(|ext| ext.to_str()) == Some("app")) + }) + .flatten(); + let cwd = app_bundle + .and_then(Path::parent) + .or_else(|| executable.parent()) + .unwrap_or_else(|| Path::new(".")); + let mut command = if let Some(bundle) = app_bundle { + let mut command = Command::new("open"); + command.args(["--wait-apps", "-a"]).arg(bundle); + command + } else { + Command::new(&executable) + }; + let fix_note = apply_steam_fix_to_command(&mut command); + command + .current_dir(cwd) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()); + let child = command.spawn().map_err(|e| format!("Launch failed: {e}"))?; + let window = config + .get("hideWhilePlaying") + .and_then(Value::as_bool) + .unwrap_or(false) + .then(|| app.get_webview_window("main")) + .flatten(); + if let Some(window) = window.as_ref() { + let _ = window.minimize(); + } + wait_for_child(child, window); + log_launch(&state.data_dir, "direct", &game.id, "", &fix_note); + Ok(true) +} + +#[cfg(target_os = "android")] +fn launch_game_android(app: &AppHandle, package: &str, rom_uri: &str) -> Result { + let target = android_launch_target(package, rom_uri)?; + // On Android the opener plugin starts Intent.ACTION_VIEW with this URI, + // which hands the ROM to the linked emulator package. + let _ = package; + app.opener() + .open_url(target, None::<&str>) + .map_err(|e| format!("Launch failed: {e}"))?; + Ok(true) +} + +#[tauri::command] +pub fn launch_game(app: AppHandle, state: State<'_, AppState>, id: String) -> Result { + let game = state + .games + .read() + .map_err(|e| e.to_string())? + .iter() + .find(|g| g.id == id) + .cloned() + .ok_or_else(|| { + "This game is no longer in your library. Rescan in Settings and try again.".to_owned() + })?; + let config = state.config(); + let system = config + .get("systems") + .and_then(Value::as_array) + .into_iter() + .flatten() + .find(|s| s.get("id").and_then(Value::as_str) == Some(&game.system)) + .ok_or_else(|| "Unknown system".to_owned())?; + let own_emulator = config + .get("gameEmulators") + .and_then(|v| v.get(&game.id)) + .and_then(Value::as_str) + .map(str::trim) + .unwrap_or(""); + let system_direct = system + .get("direct") + .and_then(Value::as_bool) + .unwrap_or(false); + let is_direct = own_emulator == "__direct" || (own_emulator.is_empty() && system_direct); + if is_direct { + #[cfg(target_os = "android")] + { + return Err("Direct launch is not available on Android.".to_owned()); + } + #[cfg(not(target_os = "android"))] + { + return launch_direct(&app, &state, &config, &game); + } + } + let emulator_id = if !own_emulator.is_empty() { + own_emulator + } else { + system + .get("emulator") + .and_then(Value::as_str) + .filter(|s| !s.is_empty()) + .ok_or_else(|| { + format!( + "No emulator is set for {}. Choose one in Settings.", + system + .get("name") + .and_then(Value::as_str) + .unwrap_or(&game.system) + ) + })? + }; + let base = crate::emulators::find_definition(emulator_id, &config) + .ok_or_else(|| "Unknown emulator".to_owned())?; + let definition = crate::emulators::selected_definition(&base, &config, emulator_id); + #[cfg(target_os = "android")] + { + let package = crate::emulators::linked_package(&config, emulator_id).ok_or_else(|| { + format!( + "{} isn't linked yet. Link the installed app by package from the Emulators tab.", + definition + .get("name") + .and_then(Value::as_str) + .unwrap_or(emulator_id) + ) + })?; + return launch_game_android(&app, &package, &game.rom_path); + } + #[cfg(not(target_os = "android"))] + let executable = + crate::emulators::resolve_exe(&state.emu_dir, emulator_id, &definition, &config) + .ok_or_else(|| { + format!( + "{} isn't installed yet. Install it from the Emulators tab.", + definition + .get("name") + .and_then(Value::as_str) + .unwrap_or(emulator_id) + ) + })?; + #[cfg(not(target_os = "android"))] + let template = if emulator_id == system.get("emulator").and_then(Value::as_str).unwrap_or("") { + system + .get("args") + .and_then(Value::as_str) + .or_else(|| definition.get("args").and_then(Value::as_str)) + .unwrap_or("{rom}") + } else { + definition + .get("args") + .and_then(Value::as_str) + .unwrap_or("{rom}") + }; + #[cfg(not(target_os = "android"))] + let args: Vec = split_args(template) + .into_iter() + .map(|part| part.replace("{rom}", &game.rom_path)) + .collect(); + #[cfg(not(target_os = "android"))] + let app_bundle = cfg!(target_os = "macos") + .then(|| { + executable + .ancestors() + .find(|path| path.extension().and_then(|ext| ext.to_str()) == Some("app")) + }) + .flatten(); + #[cfg(not(target_os = "android"))] + let cwd = app_bundle + .and_then(Path::parent) + .or_else(|| executable.parent()) + .unwrap_or_else(|| Path::new(".")); + #[cfg(not(target_os = "android"))] + let mut command = if let Some(bundle) = app_bundle { + let mut command = Command::new("open"); + command + .args(["--wait-apps", "-a"]) + .arg(bundle) + .arg("--args") + .args(args); + command + } else { + let mut command = Command::new(&executable); + command.args(args); + command + }; + #[cfg(not(target_os = "android"))] + let fix_note = apply_steam_fix_to_command(&mut command); + #[cfg(not(target_os = "android"))] + command + .current_dir(cwd) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()); + #[cfg(not(target_os = "android"))] + let child = command.spawn().map_err(|e| format!("Launch failed: {e}"))?; + #[cfg(not(target_os = "android"))] + let window = config + .get("hideWhilePlaying") + .and_then(Value::as_bool) + .unwrap_or(false) + .then(|| app.get_webview_window("main")) + .flatten(); + #[cfg(not(target_os = "android"))] + if let Some(window) = window.as_ref() { + let _ = window.minimize(); + } + #[cfg(not(target_os = "android"))] + wait_for_child(child, window); + #[cfg(not(target_os = "android"))] + { + let data_dir = state.data_dir.clone(); + let game_id = game.id.clone(); + let emu_id = emulator_id.to_owned(); + log_launch(&data_dir, "emulator", &game_id, &emu_id, &fix_note); + } + Ok(true) +} + +struct ScanOutcome { + games: Vec, + sizes: HashMap, +} + +fn scan( + app: &AppHandle, + config: &Value, + data_dir: &Path, + known_sizes: &HashMap, + reread_sizes: bool, +) -> Result { + let listings = ScanListings::default(); + let mut games = Vec::new(); + let mut scan_sizes: HashMap = HashMap::new(); + let systems = config + .get("systems") + .and_then(Value::as_array) + .ok_or("Invalid settings")?; + for system in systems { + let Some(id) = system.get("id").and_then(Value::as_str) else { + continue; + }; + let extensions: HashSet = system + .get("extensions") + .and_then(Value::as_array) + .into_iter() + .flatten() + .filter_map(Value::as_str) + .map(str::to_lowercase) + .collect(); + if extensions.is_empty() { + continue; + } + let dirs: Vec = + split_storage_refs(system.get("romDir").and_then(Value::as_str).unwrap_or("")) + .into_iter() + .filter_map(|r| r.as_path().cloned()) + .filter(|p| p.is_dir()) + .collect(); + let extra_entries: Vec = config + .get("extraGames") + .and_then(Value::as_array) + .map(|arr| { + arr.iter() + .filter(|x| x.get("system").and_then(Value::as_str) == Some(id)) + .filter(|x| { + let path = x.get("path").and_then(Value::as_str).unwrap_or(""); + !path.is_empty() && (is_content_uri(path) || Path::new(path).exists()) + }) + .cloned() + .collect() + }) + .unwrap_or_default(); + if dirs.is_empty() && extra_entries.is_empty() { + continue; + } + let mut files = Vec::new(); + // Direct systems scan only the top folder, because game folders hold helper binaries. + let start_depth = if system + .get("direct") + .and_then(Value::as_bool) + .unwrap_or(false) + { + 4 + } else { + 0 + }; + for (root_index, root) in dirs.iter().enumerate() { + allow_tree(app, root); + walk_roms( + &listings, + root, + root, + root_index, + start_depth, + &extensions, + &mut files, + ); + } + for entry in &extra_entries { + let entry_id = entry + .get("id") + .and_then(Value::as_str) + .unwrap_or("") + .to_owned(); + let entry_path = entry + .get("path") + .and_then(Value::as_str) + .unwrap_or("") + .to_owned(); + let entry_title = entry + .get("title") + .and_then(Value::as_str) + .map(str::trim) + .filter(|s| !s.is_empty()) + .map(str::to_owned); + let file_name = Path::new(&entry_path) + .file_name() + .and_then(|s| s.to_str()) + .unwrap_or("") + .to_owned(); + if file_name.is_empty() { + continue; + } + let file_path = PathBuf::from(&entry_path); + let parent = file_path + .parent() + .map(|p| p.to_path_buf()) + .unwrap_or_else(|| PathBuf::from(".")); + files.push(RomFile { + name: file_name, + path: file_path, + root: parent, + root_index: 0, + size: None, + is_dump: false, + added: Some(entry_id), + title_override: entry_title, + }); + } + let playlists: HashSet = files + .iter() + .filter(|f| f.name.to_lowercase().ends_with(".m3u")) + .map(|f| loose_key(&stem(&f.name))) + .collect(); + files.retain(|f| { + let lower = f.name.to_lowercase(); + if lower.contains("(track ") && lower.contains(')') { + return false; + } + !(lower.contains("(disc ") + && playlists.contains(&loose_key( + &Path::new(&f.name) + .file_stem() + .and_then(|s| s.to_str()) + .unwrap_or(""), + ))) + }); + let best = select_best_roms(files, known_sizes, reread_sizes, &mut scan_sizes); + let roots = media_roots(config, system, &dirs, data_dir); + for root in &roots { + allow_tree(app, root); + } + let indexes: Vec = roots + .iter() + .map(|root| index_media_root(&listings, root)) + .collect(); + let lists: Vec> = + dirs.iter().map(|root| read_gamelist(root)).collect(); + let best_files: Vec = best.into_values().collect(); + let system_games = map_limit(&best_files, SCAN_CONCURRENCY, &|file| { + let base = Path::new(&file.name) + .file_stem() + .and_then(|s| s.to_str()) + .unwrap_or(&file.name) + .to_owned(); + let (media_paths, info, shell) = find_media(&indexes, &base, &listings); + let mut metadata = Map::new(); + for list in &lists { + if let Some(value) = list.get(&base.to_lowercase()).and_then(Value::as_object) { + metadata.extend(value.clone()); + break; + } + } + if let Some(info) = info.and_then(|v| v.as_object().cloned()) { + metadata.extend(info); + } + let media = media_paths + .into_iter() + .filter_map(|(kind, path)| media_value(&kind, &path).map(|value| (kind, value))) + .collect(); + let relative = file + .path + .strip_prefix(&file.root) + .unwrap_or(&file.path) + .to_string_lossy() + .replace('\\', "/"); + let suffix = if file.root_index == 0 { + relative + } else { + format!("{}:{}", file.root_index, relative) + }; + let game_id = if let Some(added) = file.added.clone() { + format!("{id}:added:{added}") + } else { + format!("{id}:{suffix}") + }; + let title = file.title_override.clone().unwrap_or_else(|| { + metadata + .get("title") + .and_then(Value::as_str) + .map(str::to_owned) + .unwrap_or_else(|| display_title(&base)) + }); + Game { + id: game_id, + system: id.to_owned(), + rom_path: file.path.to_string_lossy().to_string(), + base, + title, + info: Value::Object(metadata), + media, + shell, + hidden: false, + scanned_title: None, + custom_title: false, + version: None, + media_type: None, + emulator: None, + added: file.added.clone(), + } + }); + games.extend(system_games); + } + games.sort_by(|a, b| a.title.to_lowercase().cmp(&b.title.to_lowercase())); + Ok(ScanOutcome { + games, + sizes: scan_sizes, + }) +} + +fn media_roots(config: &Value, system: &Value, dirs: &[PathBuf], data_dir: &Path) -> Vec { + let id = system.get("id").and_then(Value::as_str).unwrap_or_default(); + let mut roots = Vec::new(); + if let Some(media_root) = config + .get("mediaRoot") + .and_then(Value::as_str) + .filter(|s| !s.is_empty() && !is_content_uri(s)) + { + roots.push(PathBuf::from(media_root).join(id)); + } + for dir in dirs { + roots.push(dir.join("media")); + roots.push(dir.clone()); + } + roots.push(data_dir.join("media").join(id)); + roots.retain(|p| p.is_dir()); + roots +} + +fn allow_tree(app: &AppHandle, path: &Path) { + let _ = app.asset_protocol_scope().allow_directory(path, true); +} + +fn walk_roms( + listings: &ScanListings, + root: &Path, + dir: &Path, + root_index: usize, + depth: usize, + extensions: &HashSet, + out: &mut Vec, +) { + let entries = listings.list(dir); + if extensions.contains(".nsp") + && entries + .iter() + .any(|e| e.is_dir && matches!(e.name.to_lowercase().as_str(), "base" | "exefs")) + { + for main in [dir.join("base/exefs/main"), dir.join("exefs/main")] { + if main.is_file() { + let label = dir.file_name().and_then(|s| s.to_str()).unwrap_or("Game"); + out.push(RomFile { + name: format!("{label}.dump"), + path: main, + root: root.to_path_buf(), + root_index, + size: Some(9_000_000_000), + is_dump: true, + added: None, + title_override: None, + }); + return; + } + } + } + for entry in entries.iter() { + let path = &entry.path; + let rom_ext = path + .extension() + .and_then(|e| e.to_str()) + .map(|e| format!(".{}", e.to_lowercase())) + .is_some_and(|e| extensions.contains(&e)); + if entry.is_dir { + if rom_ext { + out.push(RomFile { + name: entry.name.clone(), + size: Some(0), + is_dump: false, + path: path.clone(), + root: root.to_path_buf(), + root_index, + added: None, + title_override: None, + }); + } else if depth < 4 && !skip_dir(&entry.name) { + walk_roms(listings, root, path, root_index, depth + 1, extensions, out); + } + } else if entry.is_file && rom_ext { + out.push(RomFile { + name: entry.name.clone(), + size: None, + is_dump: false, + path: path.clone(), + root: root.to_path_buf(), + root_index, + added: None, + title_override: None, + }); + } + } +} + +fn skip_dir(name: &str) -> bool { + matches!( + name.to_lowercase().as_str(), + "source archives" + | "_extras" + | "extras" + | "texture packs" + | "save" + | "saves" + | "state" + | "states" + | "bios" + | "cheats" + | "patches" + | "media" + | "images" + | "manuals" + | "downloaded_media" + | "covers" + | "screenshots" + ) +} + +fn switch_title_id(name: &str) -> Option<(String, u32)> { + static TITLE_ID: std::sync::OnceLock = std::sync::OnceLock::new(); + let re = TITLE_ID.get_or_init(|| regex::Regex::new(r"\[(?i)([0-9a-f]{16})\]").unwrap()); + let caps = re.captures(name)?; + let id = u64::from_str_radix(caps.get(1)?.as_str(), 16).ok()?; + let base = format!("{:016x}", id & !0x1fff_u64); + Some((base, (id & 0x1fff_u64) as u32)) +} + +fn switch_group_key(name: &str) -> Option { + switch_title_id(name).map(|(base, _)| base) +} + +fn copy_score(file: &RomFile) -> i64 { + if file.added.is_some() { + return i64::MAX; + } + let name = file.name.to_lowercase(); + let mut score: i64 = 0; + if let Some((_, part)) = switch_title_id(&file.name) { + score += if part == 0 { 8 } else { -8 }; + } + if name.contains("(u)") + || name.contains("(usa") + || name.contains("(us)") + || name.contains("(e)") + || name.contains("(eu)") + || name.contains("(europe)") + || name.contains("(world") + || name.contains("(en)") + || name.contains("[usa") + || name.contains("(ue)") + { + score += 4; + } + if name.contains("(j)") || name.contains("(jp)") || name.contains("(japan)") { + score -= 2; + } + if name.contains("[!]") { + score += 2; + } + if ["update", "upd", "dlc", "(beta", "(proto", "(demo", "(hack"] + .iter() + .any(|s| name.contains(s)) + || has_dump_marker(&name) + { + score -= 6; + } + if !name.ends_with(".zip") { + score += 1; + } + score +} + +fn copy_size( + file: &mut RomFile, + known_sizes: &HashMap, + reread_sizes: bool, + scan_sizes: &mut HashMap, +) -> u64 { + if file.size.is_none() { + let key = file.path.to_string_lossy().to_string(); + file.size = Some(if !reread_sizes && known_sizes.contains_key(&key) { + known_sizes[&key] + } else { + fs::metadata(&file.path) + .map(|m| m.len()) + .unwrap_or_default() + }); + } + let size = file.size.unwrap_or_default(); + if !file.is_dump { + scan_sizes.insert(file.path.to_string_lossy().to_string(), size); + } + size.min(9_000_000_000) +} + +fn has_dump_marker(name: &str) -> bool { + static DUMP_MARKER: std::sync::OnceLock = std::sync::OnceLock::new(); + DUMP_MARKER + .get_or_init(|| regex::Regex::new(r"\[(?:b|h|t|o)\d*\]|\[v[1-9]\d*\]").unwrap()) + .is_match(name) +} + +fn select_best_roms( + files: Vec, + known_sizes: &HashMap, + reread_sizes: bool, + scan_sizes: &mut HashMap, +) -> HashMap { + let mut groups: HashMap> = HashMap::new(); + for file in files { + let base = Path::new(&file.name) + .file_stem() + .and_then(|s| s.to_str()) + .unwrap_or(&file.name) + .to_owned(); + // Switch updates/DLC group by title ID base instead of file name. + let key = if let Some(group) = switch_group_key(&file.name) { + format!("switch:{group}") + } else { + let normalized = loose_key(&base); + if normalized.is_empty() { + base.to_lowercase() + } else { + normalized + } + }; + groups.entry(key).or_default().push(file); + } + let mut best = HashMap::new(); + for (key, group) in groups { + let top_score = group.iter().map(copy_score).max().unwrap_or_default(); + let mut top: Vec = group + .into_iter() + .filter(|file| copy_score(file) == top_score) + .collect(); + let pick = if top.len() > 1 { + for file in &mut top { + copy_size(file, known_sizes, reread_sizes, scan_sizes); + } + let mut pick = top.remove(0); + for candidate in top { + let pick_size = copy_size(&mut pick.clone(), known_sizes, reread_sizes, scan_sizes); + let candidate_size = candidate.size.unwrap_or_default().min(9_000_000_000); + if pick_size < candidate_size { + pick = candidate; + } + } + pick + } else { + top.remove(0) + }; + best.insert(key, pick); + } + best +} + +fn index_media_root(listings: &ScanListings, root: &Path) -> MediaIndex { + let mut index = MediaIndex { + game_dirs: HashMap::new(), + kinds: HashMap::new(), + files: HashSet::new(), + }; + for entry in listings.list(root).iter().filter(|e| e.is_dir) { + let name = entry.name.to_lowercase(); + if let Some((kind, _)) = media_kind_folder(&name) { + let map = index.kinds.entry(kind.to_owned()).or_default(); + for file in listings.list(&entry.path).iter().filter(|f| f.is_file) { + index + .files + .insert(file.path.to_string_lossy().to_lowercase()); + if valid_media_extension(kind, &file.path) { + map.entry(stem(&file.name)) + .or_insert_with(|| file.path.clone()); + } + } + } else { + index.game_dirs.insert(name, entry.path.clone()); + } + } + index +} + +fn media_kind_folder(name: &str) -> Option<(&'static str, &'static [&'static str])> { + [ + ("front", &["covers", "box2dfront", "boxart"][..]), + ("frontHQ", &["cover-hq"][..]), + ("screenshot", &["screenshots", "snaps", "images"][..]), + ("title", &["titlescreens", "titles"][..]), + ("back", &["backcovers", "box2dback"][..]), + ("spine", &["spines", "box2dside"][..]), + ("disc", &["physicalmedia", "discs", "support"][..]), + ("fanart", &["fanart", "backgrounds"][..]), + ("logo", &["marquees", "wheel", "logos"][..]), + ("video", &["videos"][..]), + ("manual", &["manuals"][..]), + ] + .into_iter() + .find(|(_, folders)| folders.contains(&name)) +} + +fn valid_media_extension(kind: &str, path: &Path) -> bool { + let ext = path + .extension() + .and_then(|e| e.to_str()) + .unwrap_or_default() + .to_lowercase(); + if kind == "manual" { + return ext == "pdf"; + } + if kind == "video" { + return ["mp4", "webm"].contains(&ext.as_str()); + } + ["png", "jpg", "jpeg", "webp", "gif"].contains(&ext.as_str()) +} + +// Manual paths stay filesystem paths for the native opener; artwork uses file URLs. +fn media_value(kind: &str, path: &Path) -> Option { + if kind == "manual" { + Some(path.to_string_lossy().into_owned()) + } else { + Url::from_file_path(path).ok().map(|url| url.to_string()) + } +} + +fn find_media( + indexes: &[MediaIndex], + base: &str, + listings: &ScanListings, +) -> (HashMap, Option, Option) { + let key = base.to_lowercase(); + let mut media = HashMap::new(); + let mut info = None; + let mut seen: HashSet = HashSet::new(); + for index in indexes { + let dir = index + .game_dirs + .get(&key) + .or_else(|| index.game_dirs.get(&clean_title(base).to_lowercase())); + if let Some(dir) = dir { + let files = listings.list(dir); + for file in files.iter().filter(|f| f.is_file) { + seen.insert(file.path.to_string_lossy().to_lowercase()); + } + for (kind, names) in media_names() { + if media.contains_key(kind) { + continue; + } + let hit = names.iter().find_map(|name| { + files + .iter() + .filter(|f| { + f.is_file + && stem(&f.name) == *name + && valid_media_extension(kind, &f.path) + }) + .min_by_key(|f| { + if f.path + .extension() + .is_some_and(|e| e.eq_ignore_ascii_case("png")) + { + 0 + } else { + 1 + } + }) + }); + if let Some(hit) = hit { + media.insert(kind.to_owned(), hit.path.clone()); + } + } + if info.is_none() { + if let Some(file) = files + .iter() + .find(|f| f.is_file && f.name.eq_ignore_ascii_case("info.json")) + { + info = fs::read_to_string(&file.path) + .ok() + .and_then(|s| serde_json::from_str(&s).ok()); + } + } + } + for (kind, paths) in &index.kinds { + if !media.contains_key(kind) { + if let Some(path) = paths.get(&key) { + media.insert(kind.clone(), path.clone()); + } + } + } + } + let mut shell = None; + if let Some(disc) = media.get("disc") { + let shell_file = disc.with_extension("json"); + let shell_key = shell_file.to_string_lossy().to_lowercase(); + let listed = seen.contains(&shell_key) + || indexes.iter().any(|index| index.files.contains(&shell_key)); + if listed { + if let Ok(text) = fs::read_to_string(&shell_file) { + if let Ok(parsed) = serde_json::from_str::(&text) { + if let Some(value) = parsed.get("shell").and_then(Value::as_str) { + let valid = value.len() == 7 + && value.starts_with('#') + && value[1..].chars().all(|c| c.is_ascii_hexdigit()); + if valid { + shell = Some(value.to_owned()); + } + } + } + } + } + } + (media, info, shell) +} + +fn media_names() -> Vec<(&'static str, &'static [&'static str])> { + vec![ + ("front", &["front", "cover", "box-front", "boxfront", "box"]), + ("frontHQ", &["front-hq"]), + ("back", &["back", "box-back", "boxback"]), + ("spine", &["spine", "box-spine", "side"]), + ( + "disc", + &["disc", "cd", "cart", "cartridge", "media", "physicalmedia"], + ), + ("manual", &["manual"]), + ("screenshot", &["screenshot", "snap", "screen"]), + ("title", &["title", "titlescreen"]), + ("fanart", &["fanart", "background", "bg"]), + ("logo", &["logo", "marquee", "wheel"]), + ("video", &["video", "trailer"]), + ] +} + +fn read_gamelist(root: &Path) -> HashMap { + let Ok(xml) = fs::read_to_string(root.join("gamelist.xml")) else { + return HashMap::new(); + }; + parse_gamelist(&xml) +} + +fn parse_gamelist(xml: &str) -> HashMap { + let mut map = HashMap::new(); + let Ok(game_re) = regex::Regex::new(r"(?s)].*?") else { + return map; + }; + for game in game_re.find_iter(xml).map(|m| m.as_str()) { + let Some(path) = xml_tag(game, "path") else { + continue; + }; + let mut info = Map::new(); + for (tag, key) in [ + ("name", "title"), + ("desc", "description"), + ("developer", "developer"), + ("publisher", "publisher"), + ("genre", "genre"), + ("players", "players"), + ] { + if let Some(value) = xml_tag(game, tag) { + info.insert(key.to_owned(), Value::String(value)); + } + } + if let Some(released) = xml_tag(game, "releasedate") { + info.insert( + "year".to_owned(), + Value::String(released.chars().take(4).collect()), + ); + } + map.insert(stem(&path).to_lowercase(), Value::Object(info)); + } + map +} + +fn xml_tag(xml: &str, tag: &str) -> Option { + let expression = regex::Regex::new(&format!(r"(?s)<{tag}>(.*?)")).ok()?; + let text = expression.captures(xml)?.get(1)?.as_str().trim(); + Some(quick_xml::escape::unescape(text).ok()?.into_owned()) +} + +fn stem(name: &str) -> String { + Path::new(name) + .file_stem() + .and_then(|s| s.to_str()) + .unwrap_or(name) + .to_lowercase() +} + +fn loose_key(text: &str) -> String { + clean_title(text) + .to_lowercase() + .replace('&', " ") + .split_whitespace() + .filter(|word| *word != "and" && *word != "the") + .flat_map(str::chars) + .filter(char::is_ascii_alphanumeric) + .collect() +} + +fn clean_title(name: &str) -> String { + static BRACKETED: std::sync::OnceLock = std::sync::OnceLock::new(); + static RELEASE_NUMBER: std::sync::OnceLock = std::sync::OnceLock::new(); + static ENCRYPTION_SUFFIX: std::sync::OnceLock = std::sync::OnceLock::new(); + static WHITESPACE: std::sync::OnceLock = std::sync::OnceLock::new(); + let value = BRACKETED + .get_or_init(|| regex::Regex::new(r"\s*[\(\[][^)\]]*[\)\]]").unwrap()) + .replace_all(name, "") + .replace('_', " "); + let value = RELEASE_NUMBER + .get_or_init(|| regex::Regex::new(r"^\d{3,5}\s*-?\s+").unwrap()) + .replace(&value, ""); + let value = ENCRYPTION_SUFFIX + .get_or_init(|| regex::Regex::new(r"(?i)\s*\b(decrypted|encrypted)\b\s*$").unwrap()) + .replace(&value, ""); + let cleaned = WHITESPACE + .get_or_init(|| regex::Regex::new(r"\s+").unwrap()) + .replace_all(&value, " ") + .trim() + .to_owned(); + if cleaned.is_empty() { + name.to_owned() + } else { + cleaned + } +} + +fn display_title(name: &str) -> String { + let value = clean_title(name); + let (title, suffix) = value + .split_once(" - ") + .map_or((value.as_str(), None), |(title, suffix)| { + (title, Some(suffix)) + }); + for article in ["The", "A", "An"] { + if let Some(prefix) = title.strip_suffix(&format!(" {article}")) { + let prefix = prefix.trim_end_matches(',').trim_end(); + if !prefix.is_empty() { + return match suffix { + Some(suffix) => format!("{article} {prefix} - {suffix}"), + None => format!("{article} {prefix}"), + }; + } + } + } + value +} + +#[cfg(not(target_os = "android"))] +#[tauri::command] +/// Runs off the main thread so the Tauri dialog plugin's `blocking_*` APIs +/// can dispatch the native sheet to the main runloop and wait for it. +pub async fn pick_folder(app: AppHandle, title: String) -> Option { + app.dialog() + .file() + .set_title(title) + .blocking_pick_folder() + .and_then(|path| path.into_path().ok()) + .map(|path| path.to_string_lossy().to_string()) +} + +#[cfg(target_os = "android")] +#[tauri::command] +pub fn pick_folder(_app: AppHandle, _title: String) -> Result, String> { + // Dialog plugin does not support Android folder picking. A SAF grant + // must come from the native picker and persists as a content URI. + Err( + "Folder selection on Android needs a document-tree grant; the dialog plugin does not support folder picking there." + .to_owned(), + ) +} + +#[tauri::command] +pub fn open_manual(app: AppHandle, path: String) -> Result<(), String> { + app.opener() + .open_path(path, None::<&str>) + .map_err(|e| e.to_string()) +} + +#[tauri::command] +pub fn app_version() -> &'static str { + env!("CARGO_PKG_VERSION") +} + +#[tauri::command] +pub fn quit_app(app: tauri::AppHandle) { + app.exit(0); +} + +fn supports_self_update(os: &str, arch: &str, appimage: bool) -> bool { + matches!((os, arch), ("macos", "aarch64")) + || matches!((os, arch), ("linux", "aarch64") if appimage) +} + +fn self_update_supported() -> bool { + supports_self_update( + std::env::consts::OS, + std::env::consts::ARCH, + std::env::var_os("APPIMAGE").is_some(), + ) +} + +fn manual_update_hint() -> &'static str { + if cfg!(target_os = "linux") && std::env::var_os("APPIMAGE").is_none() { + "This Linux install is managed by your package manager. Install the matching ARM64 package from the release page." + } else { + "Download the matching platform and architecture release from the release page." + } +} + +#[tauri::command] +pub async fn check_app_update(app: AppHandle) -> Result { + const REPO: &str = "Pyrodrifter/PyroCade"; + let current = env!("CARGO_PKG_VERSION"); + let response = reqwest::Client::builder() + .user_agent("PyroCade-Frontend") + .build() + .map_err(|e| e.to_string())? + .get(format!( + "https://api.github.com/repos/{REPO}/releases/latest" + )) + .header("Accept", "application/vnd.github+json") + .send() + .await + .map_err(|e| e.to_string())?; + if response.status().as_u16() == 404 { + return Ok( + json!({"current":current,"available":false,"canInstall":false,"manualHint":"No published releases yet."}), + ); + } + if !response.status().is_success() { + return Err(format!( + "GitHub {}: {}{}", + response.status(), + response + .status() + .canonical_reason() + .unwrap_or("request failed"), + if response.status().as_u16() == 403 { + " (rate limited — try again later)" + } else { + "" + } + )); + } + let release: Value = response.json().await.map_err(|e| e.to_string())?; + let tag = release + .get("tag_name") + .and_then(Value::as_str) + .unwrap_or_default(); + let latest = tag.trim_start_matches(['v', 'V']); + let available = version_parts(latest) > version_parts(current); + let can_install = if self_update_supported() { + match app.updater() { + Ok(updater) => updater.check().await.is_ok_and(|update| update.is_some()), + Err(_) => false, + } + } else { + false + }; + Ok(json!({ + "current":current,"latest":latest,"available":available, + "name":release.get("name").and_then(Value::as_str).filter(|s| !s.is_empty()).unwrap_or(tag), + "notes":release.get("body").and_then(Value::as_str).unwrap_or(""), + "url":release.get("html_url"),"installer":Value::Null,"canInstall":can_install, + "manualHint":manual_update_hint() + })) +} + +#[tauri::command] +pub async fn install_app_update(app: AppHandle) -> Result { + if self_update_supported() { + if let Ok(updater) = app.updater() { + if let Ok(Some(update)) = updater.check().await { + let version = update.version.clone(); + let progress_version = version.clone(); + let progress_app = app.clone(); + let mut downloaded = 0usize; + update + .download_and_install( + move |chunk, total| { + downloaded += chunk; + let total = total.unwrap_or_default(); + let pct = if total > 0 { + downloaded as f64 / total as f64 + } else { + 0.0 + }; + let _ = progress_app.emit( + "app:updateProgress", + json!({ + "stage": format!("Downloading PyroCade {progress_version}…"), + "pct": pct, + "got": downloaded, + "total": total + }), + ); + }, + || {}, + ) + .await + .map_err(|e| e.to_string())?; + app.emit( + "app:updateProgress", + json!({"stage":"Update installed; restart PyroCade to finish.","pct":1,"done":true}), + ) + .map_err(|e| e.to_string())?; + return Ok(json!({"version":version,"mode":"updater"})); + } + } + } + + let update = check_app_update(app.clone()).await?; + if !update + .get("available") + .and_then(Value::as_bool) + .unwrap_or(false) + { + return Err("PyroCade is already up to date.".to_owned()); + } + let url = update + .get("url") + .and_then(Value::as_str) + .ok_or("Release page is unavailable")? + .to_owned(); + app.opener() + .open_url(url, None::<&str>) + .map_err(|e| e.to_string())?; + Ok(json!({"version":update.get("latest"),"mode":"manual"})) +} + +#[tauri::command] +pub fn open_release(app: AppHandle, url: String) -> Result<(), String> { + if !url.starts_with("https://github.com/") { + return Err("Not a GitHub link".to_owned()); + } + app.opener() + .open_url(url, None::<&str>) + .map_err(|e| e.to_string()) +} + +fn os_release() -> Option { + #[cfg(any(target_os = "macos", target_os = "linux"))] + { + std::process::Command::new("uname") + .arg("-r") + .output() + .ok() + .filter(|output| output.status.success()) + .map(|output| String::from_utf8_lossy(&output.stdout).trim().to_owned()) + .filter(|release| !release.is_empty()) + } + #[cfg(not(any(target_os = "macos", target_os = "linux")))] + { + None + } +} + +fn feedback_diagnostics() -> String { + let version = env!("CARGO_PKG_VERSION"); + let os = std::env::consts::OS; + let arch = std::env::consts::ARCH; + let os_detail = match os_release() { + Some(release) => format!("{os} {release} ({arch})"), + None => format!("{os} ({arch})"), + }; + let tauri_version = tauri::VERSION; + let installation = if cfg!(debug_assertions) { + "From source" + } else { + "Packaged app" + }; + format!( + "PyroCade: {version}\nOS: {os_detail}\nTauri: {tauri_version}\nInstallation: {installation}" + ) +} + +#[tauri::command] +pub fn feedback_info() -> String { + feedback_diagnostics() +} + +#[tauri::command] +pub fn feedback_copy(app: AppHandle, text: String) -> Result<(), String> { + if text.trim().is_empty() { + return Err("Nothing to copy yet.".to_owned()); + } + use tauri_plugin_clipboard_manager::ClipboardExt; + app.clipboard() + .write_text(text) + .map_err(|e| format!("Could not copy the report: {e}")) +} + +#[tauri::command] +pub fn feedback_open(app: AppHandle, url: String) -> Result<(), String> { + if !url.starts_with("https://github.com/Pyrodrifter/PyroCade/issues/") { + return Err("Not a GitHub issue link".to_owned()); + } + app.opener() + .open_url(url, None::<&str>) + .map_err(|e| e.to_string()) +} + +fn merge_object(target: &mut Value, source: &Value) { + let (Some(target), Some(source)) = (target.as_object_mut(), source.as_object()) else { + return; + }; + for (key, value) in source { + if key == "systems" { + continue; + } + if value.is_object() && target.get(key).is_some_and(Value::is_object) { + merge_object(target.get_mut(key).unwrap(), value); + } else { + target.insert(key.clone(), value.clone()); + } + } +} + +fn split_args(value: &str) -> Vec { + let mut result = Vec::new(); + let mut current = String::new(); + let mut quoted = false; + let mut any = false; + for ch in value.chars() { + if ch == '"' { + quoted = !quoted; + any = true; + } else if ch.is_whitespace() && !quoted { + if any { + result.push(std::mem::take(&mut current)); + any = false; + } + } else { + current.push(ch); + any = true; + } + } + if any { + result.push(current); + } + result +} + +fn version_parts(value: &str) -> (u64, u64, u64) { + let mut parts = value + .trim_start_matches(['v', 'V']) + .split(['.', '+', '-']) + .map(|s| s.parse::().unwrap_or_default()); + ( + parts.next().unwrap_or_default(), + parts.next().unwrap_or_default(), + parts.next().unwrap_or_default(), + ) +} + +#[cfg(test)] +mod library_tests { + use super::*; + + #[test] + fn self_updater_is_limited_to_supported_arm64_installs() { + assert!(supports_self_update("macos", "aarch64", false)); + assert!(supports_self_update("linux", "aarch64", true)); + assert!(!supports_self_update("linux", "aarch64", false)); + assert!(!supports_self_update("linux", "x86_64", true)); + } + + #[test] + fn feedback_diagnostics_lists_only_basic_device_details() { + let diagnostics = feedback_diagnostics(); + assert!(diagnostics.contains(&format!("PyroCade: {}", env!("CARGO_PKG_VERSION")))); + assert!(diagnostics.contains("OS: ")); + assert!(diagnostics.contains("Tauri: ")); + assert!(diagnostics.contains("Installation: ")); + assert!(!diagnostics.contains("Electron")); + assert!(!diagnostics.contains("data/")); + } + + #[test] + fn feedback_issue_url_must_target_this_repos_issue_pages() { + assert!( + "https://github.com/Pyrodrifter/PyroCade/issues/new?template=bug_report.md" + .starts_with("https://github.com/Pyrodrifter/PyroCade/issues/") + ); + assert!( + !"https://github.com/Pyrodrifter/PyroCade/releases" + .starts_with("https://github.com/Pyrodrifter/PyroCade/issues/") + ); + assert!( + !"https://example.com/issues/new" + .starts_with("https://github.com/Pyrodrifter/PyroCade/issues/") + ); + } + + fn rom_file(name: &str) -> RomFile { + RomFile { + name: name.to_owned(), + path: PathBuf::from(name), + root: PathBuf::from("roms"), + root_index: 0, + size: None, + is_dump: false, + added: None, + title_override: None, + } + } + + fn select(files: Vec) -> HashMap { + let mut sizes = HashMap::new(); + select_best_roms(files, &HashMap::new(), false, &mut sizes) + } + + #[test] + fn manual_media_keeps_a_filesystem_path() { + assert_eq!( + media_value("manual", Path::new("/library/manual.pdf")), + Some("/library/manual.pdf".to_owned()) + ); + assert_eq!( + media_value("front", Path::new("/library/front.png")), + Some("file:///library/front.png".to_owned()) + ); + } + + #[test] + fn game_serialization_preserves_the_renderer_payload_contract() { + let game = Game { + id: "snes:game".to_owned(), + system: "snes".to_owned(), + rom_path: "/roms/game.sfc".to_owned(), + base: "game".to_owned(), + title: "Game".to_owned(), + info: serde_json::json!({"year":"1998"}), + media: HashMap::from([ + ("front".to_owned(), "file:///media/front.png".to_owned()), + ("manual".to_owned(), "/media/manual.pdf".to_owned()), + ]), + shell: Some("#a1b2c3".to_owned()), + hidden: false, + scanned_title: Some("Game".to_owned()), + custom_title: false, + version: None, + media_type: None, + emulator: None, + added: None, + }; + + let payload = serde_json::to_value(game).unwrap(); + + assert_eq!(payload["id"], "snes:game"); + assert_eq!(payload["romPath"], "/roms/game.sfc"); + assert_eq!(payload["info"]["year"], "1998"); + assert_eq!(payload["media"]["front"], "file:///media/front.png"); + assert_eq!(payload["media"]["manual"], "/media/manual.pdf"); + assert_eq!(payload["shell"], "#a1b2c3"); + assert_eq!(payload["hidden"], false); + assert_eq!(payload["scannedTitle"], "Game"); + assert_eq!(payload["customTitle"], false); + } + + #[test] + fn local_media_aliases_and_video_files_are_indexable() { + assert_eq!( + media_kind_folder("images").map(|(kind, _)| kind), + Some("screenshot") + ); + assert_eq!( + media_kind_folder("wheel").map(|(kind, _)| kind), + Some("logo") + ); + assert!(valid_media_extension("video", Path::new("trailer.webm"))); + assert!(valid_media_extension("manual", Path::new("manual.pdf"))); + } + + #[test] + fn gamelist_metadata_decodes_entities_and_released_year() { + let games = parse_gamelist( + "./Mario & Luigi.romMario & LuigiSave & play19981021T000000", + ); + let info = games.get("mario & luigi").unwrap(); + assert_eq!(info["title"], "Mario & Luigi"); + assert_eq!(info["description"], "Save & play"); + assert_eq!(info["year"], "1998"); + } + + #[test] + fn rom_selection_uses_clean_titles_and_rejects_numbered_dumps() { + let selected = select(vec![ + rom_file("Game (USA) [v1].zip"), + rom_file("Game (USA) [!].chd"), + ]); + assert_eq!(selected.len(), 1); + assert_eq!(selected.values().next().unwrap().name, "Game (USA) [!].chd"); + assert_eq!(clean_title("0004 - Zelda (USA) [!] Encrypted"), "Zelda"); + assert_eq!( + display_title("Legend of Zelda, The - Ocarina (USA)"), + "The Legend of Zelda - Ocarina" + ); + } + + #[test] + fn switch_updates_and_dlc_group_with_their_base_game() { + let selected = select(vec![ + rom_file("Game [0100abcd12340000][v0].nsp"), + rom_file("Game [0100abcd12340800][v0].nsp"), + rom_file("Game [0100abcd12341000][v0].nsp"), + ]); + assert_eq!(selected.len(), 1); + assert_eq!( + selected.values().next().unwrap().name, + "Game [0100abcd12340000][v0].nsp" + ); + assert_eq!( + switch_group_key("Game [0100ABCD12340800][v0].nsp"), + Some("0100abcd12340000".to_owned()) + ); + assert_eq!(switch_group_key("Game.nsp"), None); + } + + #[test] + fn apply_library_state_carries_hidden_renames_and_emulator_overrides() { + let config = json!({ + "favorites": [], + "hiddenGames": ["snes:secret"], + "gameDetails": {"snes:zelda": {"title": "Custom Zelda", "version": "1.01", "mediaType": "disc"}}, + "gameEmulators": {"snes:zelda": "snes9x"}, + "gameOrders": {}, + "recentlyPlayed": [], + "showFavoritesOnly": false, + "showRecentlyPlayed": false, + "sortKey": "title", + "sortAsc": true + }); + let mut games = vec![ + Game { + id: "snes:zelda".to_owned(), + system: "snes".to_owned(), + rom_path: String::new(), + base: "zelda".to_owned(), + title: "Zelda".to_owned(), + info: Value::Null, + media: HashMap::new(), + shell: None, + hidden: false, + scanned_title: None, + custom_title: false, + version: None, + media_type: None, + emulator: None, + added: None, + }, + Game { + id: "snes:secret".to_owned(), + system: "snes".to_owned(), + rom_path: String::new(), + base: "secret".to_owned(), + title: "Secret".to_owned(), + info: Value::Null, + media: HashMap::new(), + shell: None, + hidden: false, + scanned_title: None, + custom_title: false, + version: None, + media_type: None, + emulator: None, + added: None, + }, + ]; + super::apply_library_state(&mut games, &config); + let zelda = games.iter().find(|g| g.id == "snes:zelda").unwrap(); + assert_eq!(zelda.title, "Custom Zelda"); + assert_eq!(zelda.scanned_title.as_deref(), Some("Zelda")); + assert!(zelda.custom_title); + assert_eq!(zelda.version.as_deref(), Some("1.01")); + assert_eq!(zelda.media_type.as_deref(), Some("disc")); + assert_eq!(zelda.emulator.as_deref(), Some("snes9x")); + assert!(!zelda.hidden); + let secret = games.iter().find(|g| g.id == "snes:secret").unwrap(); + assert!(secret.hidden); + assert_eq!(secret.title, "Secret"); + } + + #[test] + fn apply_library_state_honours_custom_order_per_system() { + let config = json!({ + "favorites": [], + "hiddenGames": [], + "gameDetails": {}, + "gameEmulators": {}, + "gameOrders": {"snes": ["snes:b", "snes:a"]}, + "recentlyPlayed": [], + "showFavoritesOnly": false, + "showRecentlyPlayed": false, + "sortKey": "custom", + "sortAsc": true + }); + let mut games = vec![ + Game { + id: "snes:a".to_owned(), + system: "snes".to_owned(), + rom_path: String::new(), + base: "a".to_owned(), + title: "Apple".to_owned(), + info: Value::Null, + media: HashMap::new(), + shell: None, + hidden: false, + scanned_title: None, + custom_title: false, + version: None, + media_type: None, + emulator: None, + added: None, + }, + Game { + id: "snes:b".to_owned(), + system: "snes".to_owned(), + rom_path: String::new(), + base: "b".to_owned(), + title: "Zebra".to_owned(), + info: Value::Null, + media: HashMap::new(), + shell: None, + hidden: false, + scanned_title: None, + custom_title: false, + version: None, + media_type: None, + emulator: None, + added: None, + }, + ]; + super::apply_library_state(&mut games, &config); + assert_eq!(games[0].id, "snes:b"); + assert_eq!(games[1].id, "snes:a"); + } + + #[test] + fn android_launch_passes_content_uri_through_unchanged() { + let uri = "content://com.android.externalstorage.documents/tree/abc/document/rom.zip"; + assert_eq!( + android_launch_target("com.retroarch.aarch64", uri).unwrap(), + uri + ); + assert!(android_launch_target("", uri).is_err()); + assert!(android_launch_target("com.retroarch.aarch64", "").is_err()); + } + + #[test] + fn steam_start_requires_linux_and_a_steam_marker() { + let plain = |_: &str| None; + assert!(!steam_start_detected(true, &plain)); + assert!(!steam_start_detected(false, &|_| Some("123".to_owned()))); + assert!(steam_start_detected(true, &|name| { + (name == "SteamGameId").then_some("123".to_owned()) + })); + assert!(steam_start_detected(true, &|name| { + (name == "XDG_CURRENT_DESKTOP").then_some("gamescope".to_owned()) + })); + assert!(steam_start_detected(true, &|name| { + (name == "GAMESCOPE_WAYLAND_DISPLAY").then_some("wayland-0".to_owned()) + })); + } + + #[test] + fn steam_library_filter_removes_only_steam_runtime_entries() { + let mixed = "/usr/lib:/home/u/.local/lib:/run/steam-runtime/libs:/opt/STEAM/libs:/home/u/pressure-vessel/libs"; + assert_eq!( + steam_filtered_ld_library_path(mixed).unwrap(), + "/usr/lib:/home/u/.local/lib" + ); + assert!(steam_filtered_ld_library_path("/run/steamrt/libs").is_none()); + assert!(steam_filtered_ld_library_path("").is_none()); + assert_eq!( + steam_filtered_ld_library_path("/usr/lib:/bin").unwrap(), + "/usr/lib:/bin" + ); + } + + // A directory-ROM is itself the game: bundles carry no inner file with + // the ROM extension, so walking them would list nothing at all. + #[test] + fn directory_roms_are_collected_like_files() { + let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("../localTmp") + .join(format!("pyrocade-walk-roms-test-{}", uuid::Uuid::new_v4())); + let bundle = root.join("Game One.app"); + fs::create_dir_all(bundle.join("Contents/MacOS")).unwrap(); + fs::write(bundle.join("Contents/MacOS/Game"), [0u8; 42]).unwrap(); + fs::create_dir_all(root.join("Game Two.app")).unwrap(); + fs::create_dir_all(root.join("nested")).unwrap(); + fs::write(root.join("nested/Game Three.nsp"), [0u8; 7]).unwrap(); + fs::create_dir_all(root.join("media")).unwrap(); + fs::write(root.join("media/Game Four.nsp"), [0u8; 7]).unwrap(); + let extensions: HashSet = [".app", ".nsp"].iter().map(|s| s.to_string()).collect(); + let mut out = Vec::new(); + walk_roms( + &ScanListings::default(), + &root, + &root, + 0, + 0, + &extensions, + &mut out, + ); + let names: Vec<_> = out.iter().map(|f| f.name.as_str()).collect(); + assert!(names.contains(&"Game One.app")); + assert!(names.contains(&"Game Two.app")); + assert!(names.contains(&"Game Three.nsp")); + assert!(!names.contains(&"Game Four.nsp")); + // Directory-ROMs report size 0: they are never walked (copy_score + // only uses size as a tie-break, and bundles hold tens of GB). + assert_eq!( + out.iter().find(|f| f.name == "Game One.app").unwrap().size, + Some(0) + ); + fs::remove_dir_all(&root).unwrap(); + } + + // Direct systems start at depth 4: the same walk contract as scan uses. + #[test] + fn direct_depth_skips_nested_helper_binaries() { + let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("../localTmp") + .join(format!("pyrocade-direct-test-{}", uuid::Uuid::new_v4())); + fs::create_dir_all(root.join("Game One")).unwrap(); + fs::write(root.join("Game One/play.exe"), [0u8; 7]).unwrap(); + fs::write(root.join("Top.exe"), [0u8; 7]).unwrap(); + let extensions: HashSet = [".exe"].iter().map(|s| s.to_string()).collect(); + let mut shallow = Vec::new(); + walk_roms( + &ScanListings::default(), + &root, + &root, + 0, + 4, + &extensions, + &mut shallow, + ); + let names: Vec<_> = shallow.iter().map(|f| f.name.as_str()).collect(); + assert!(names.contains(&"Top.exe")); + assert!(!names.contains(&"play.exe")); + let mut deep = Vec::new(); + walk_roms( + &ScanListings::default(), + &root, + &root, + 0, + 0, + &extensions, + &mut deep, + ); + assert!(deep.iter().any(|f| f.name == "play.exe")); + fs::remove_dir_all(&root).unwrap(); + } + + #[test] + fn child_monitor_waits_for_process_exit() { + // childDelaySeconds keeps the child alive long enough to distinguish waiting from dropping. + const CHILD_DELAY_SECONDS: u64 = 1; + let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("../localTmp") + .join(format!("pyrocade-child-test-{}", uuid::Uuid::new_v4())); + fs::create_dir_all(&root).unwrap(); + let marker = root.join("exited"); + let command = format!("sleep {CHILD_DELAY_SECONDS}; printf done > \"$1\""); + let child = Command::new("sh") + .args(["-c", &command, "sh"]) + .arg(&marker) + .spawn() + .unwrap(); + + super::wait_for_child(child, None).join().unwrap(); + + let result = fs::read_to_string(&marker); + let _ = fs::remove_dir_all(&root); + assert_eq!(result.unwrap(), "done"); + } + + #[test] + fn favorites_filter_keeps_only_favorited_games() { + let config = json!({ + "favorites": ["snes:zelda", "nes:mario"], + "showFavoritesOnly": true, + "recentlyPlayed": [], + "sortKey": "title", + "sortAsc": true + }); + let mut games = vec![ + Game { + id: "snes:zelda".to_owned(), + system: "snes".to_owned(), + rom_path: String::new(), + base: "zelda".to_owned(), + title: "Zelda".to_owned(), + info: Value::Null, + media: HashMap::new(), + shell: None, + hidden: false, + scanned_title: None, + custom_title: false, + version: None, + media_type: None, + emulator: None, + added: None, + }, + Game { + id: "nes:mario".to_owned(), + system: "nes".to_owned(), + rom_path: String::new(), + base: "mario".to_owned(), + title: "Mario".to_owned(), + info: Value::Null, + media: HashMap::new(), + shell: None, + hidden: false, + scanned_title: None, + custom_title: false, + version: None, + media_type: None, + emulator: None, + added: None, + }, + Game { + id: "ps1:finalfantasy".to_owned(), + system: "ps1".to_owned(), + rom_path: String::new(), + base: "finalfantasy".to_owned(), + title: "Final Fantasy".to_owned(), + info: Value::Null, + media: HashMap::new(), + shell: None, + hidden: false, + scanned_title: None, + custom_title: false, + version: None, + media_type: None, + emulator: None, + added: None, + }, + ]; + super::apply_library_state(&mut games, &config); + assert_eq!(games.len(), 2); + let ids: Vec<&str> = games.iter().map(|g| g.id.as_str()).collect(); + assert!(ids.contains(&"snes:zelda")); + assert!(ids.contains(&"nes:mario")); + assert!(!ids.contains(&"ps1:finalfantasy")); + } + + #[test] + fn sort_by_favorites_places_favorites_first() { + let config = json!({ + "favorites": ["snes:zelda"], + "showFavoritesOnly": false, + "recentlyPlayed": [], + "sortKey": "favorites", + "sortAsc": true + }); + let mut games = vec![ + Game { + id: "nes:mario".to_owned(), + system: "nes".to_owned(), + rom_path: String::new(), + base: "mario".to_owned(), + title: "Mario".to_owned(), + info: Value::Null, + media: HashMap::new(), + shell: None, + hidden: false, + scanned_title: None, + custom_title: false, + version: None, + media_type: None, + emulator: None, + added: None, + }, + Game { + id: "snes:zelda".to_owned(), + system: "snes".to_owned(), + rom_path: String::new(), + base: "zelda".to_owned(), + title: "Zelda".to_owned(), + info: Value::Null, + media: HashMap::new(), + shell: None, + hidden: false, + scanned_title: None, + custom_title: false, + version: None, + media_type: None, + emulator: None, + added: None, + }, + Game { + id: "ps1:ff".to_owned(), + system: "ps1".to_owned(), + rom_path: String::new(), + base: "ff".to_owned(), + title: "Final Fantasy".to_owned(), + info: Value::Null, + media: HashMap::new(), + shell: None, + hidden: false, + scanned_title: None, + custom_title: false, + version: None, + media_type: None, + emulator: None, + added: None, + }, + ]; + super::apply_library_state(&mut games, &config); + assert_eq!(games[0].id, "snes:zelda"); // favorites first + } + + #[test] + fn recently_played_injection_adds_missing_games() { + let config = json!({ + "favorites": [], + "showFavoritesOnly": false, + "showRecentlyPlayed": true, + "recentlyPlayed": [ + {"id": "ps1:crash", "title": "Crash Bandicoot", "timestamp": 1000000}, + {"id": "snes:zelda", "title": "Zelda", "timestamp": 900000} + ], + "recentlyPlayedLimit": 20, + "sortKey": "title", + "sortAsc": true + }); + let mut games = vec![Game { + id: "snes:zelda".to_owned(), + system: "snes".to_owned(), + rom_path: String::new(), + base: "zelda".to_owned(), + title: "Zelda".to_owned(), + info: Value::Null, + media: HashMap::new(), + shell: None, + hidden: false, + scanned_title: None, + custom_title: false, + version: None, + media_type: None, + emulator: None, + added: None, + }]; + super::apply_library_state(&mut games, &config); + // Crash Bandicoot should be injected (not in original library). + assert!(games.iter().any(|g| g.id == "ps1:crash")); + // Zelda should still be present. + assert!(games.iter().any(|g| g.id == "snes:zelda")); + } + + #[test] + fn sort_by_title_ascending_and_descending() { + let mut games = vec![ + Game { + id: "a".to_owned(), + system: String::new(), + rom_path: String::new(), + base: "a".to_owned(), + title: "Zebra".to_owned(), + info: Value::Null, + media: HashMap::new(), + shell: None, + hidden: false, + scanned_title: None, + custom_title: false, + version: None, + media_type: None, + emulator: None, + added: None, + }, + Game { + id: "b".to_owned(), + system: String::new(), + rom_path: String::new(), + base: "b".to_owned(), + title: "Apple".to_owned(), + info: Value::Null, + media: HashMap::new(), + shell: None, + hidden: false, + scanned_title: None, + custom_title: false, + version: None, + media_type: None, + emulator: None, + added: None, + }, + Game { + id: "c".to_owned(), + system: String::new(), + rom_path: String::new(), + base: "c".to_owned(), + title: "Mango".to_owned(), + info: Value::Null, + media: HashMap::new(), + shell: None, + hidden: false, + scanned_title: None, + custom_title: false, + version: None, + media_type: None, + emulator: None, + added: None, + }, + ]; + let config_asc = json!({"favorites":[],"showFavoritesOnly":false,"showRecentlyPlayed":false,"recentlyPlayed":[],"recentlyPlayedLimit":20,"sortKey":"title","sortAsc":true}); + let config_desc = json!({"favorites":[],"showFavoritesOnly":false,"showRecentlyPlayed":false,"recentlyPlayed":[],"recentlyPlayedLimit":20,"sortKey":"title","sortAsc":false}); + super::apply_library_state(&mut games, &config_asc); + assert_eq!(games[0].title, "Apple"); + assert_eq!(games[2].title, "Zebra"); + let mut games2 = vec![ + Game { + id: "a".to_owned(), + system: String::new(), + rom_path: String::new(), + base: "a".to_owned(), + title: "Zebra".to_owned(), + info: Value::Null, + media: HashMap::new(), + shell: None, + hidden: false, + scanned_title: None, + custom_title: false, + version: None, + media_type: None, + emulator: None, + added: None, + }, + Game { + id: "b".to_owned(), + system: String::new(), + rom_path: String::new(), + base: "b".to_owned(), + title: "Apple".to_owned(), + info: Value::Null, + media: HashMap::new(), + shell: None, + hidden: false, + scanned_title: None, + custom_title: false, + version: None, + media_type: None, + emulator: None, + added: None, + }, + Game { + id: "c".to_owned(), + system: String::new(), + rom_path: String::new(), + base: "c".to_owned(), + title: "Mango".to_owned(), + info: Value::Null, + media: HashMap::new(), + shell: None, + hidden: false, + scanned_title: None, + custom_title: false, + version: None, + media_type: None, + emulator: None, + added: None, + }, + ]; + super::apply_library_state(&mut games2, &config_desc); + assert_eq!(games2[0].title, "Zebra"); + assert_eq!(games2[2].title, "Apple"); + } + + #[test] + fn multidisc_handling_preserves_root_index() { + let files = vec![ + RomFile { + name: "Game (USA).chd".to_owned(), + path: PathBuf::from("Game (USA).chd"), + root: PathBuf::from("roms"), + root_index: 0, + size: None, + is_dump: false, + added: None, + title_override: None, + }, + RomFile { + name: "Game (USA) (Disc 2).chd".to_owned(), + path: PathBuf::from("Game (USA) (Disc 2).chd"), + root: PathBuf::from("roms"), + root_index: 1, + size: None, + is_dump: false, + added: None, + title_override: None, + }, + ]; + let best = select(files); + assert_eq!(best.len(), 1); + let best_file = best.values().next().unwrap(); + assert_eq!(best_file.root_index, 0); + // Disc 2 should reference root_index 1. + let files2 = vec![ + RomFile { + name: "Game (USA).chd".to_owned(), + path: PathBuf::from("Game (USA).chd"), + root: PathBuf::from("roms"), + root_index: 0, + size: None, + is_dump: false, + added: None, + title_override: None, + }, + RomFile { + name: "Game (USA) (Disc 2).chd".to_owned(), + path: PathBuf::from("Game (USA) (Disc 2).chd"), + root: PathBuf::from("roms"), + root_index: 1, + size: None, + is_dump: false, + added: None, + title_override: None, + }, + ]; + let best2 = select(files2); + assert_eq!(best2.len(), 1); + } + + #[test] + fn tied_copies_use_cached_sizes_without_statting() { + let mut sizes = HashMap::new(); + let known: HashMap = + HashMap::from([("a/Game.chd".to_owned(), 10), ("b/Game.chd".to_owned(), 99)]); + let mut small = rom_file("Game.chd"); + small.path = PathBuf::from("a/Game.chd"); + let mut big = rom_file("Game.chd"); + big.path = PathBuf::from("b/Game.chd"); + let best = select_best_roms(vec![small, big], &known, false, &mut sizes); + assert_eq!( + best.values().next().unwrap().path, + PathBuf::from("b/Game.chd") + ); + assert_eq!(sizes.get("a/Game.chd"), Some(&10)); + assert_eq!(sizes.get("b/Game.chd"), Some(&99)); + } + + #[test] + fn cache_key_tracks_version_media_extra_and_system_shape() { + let config = json!({ + "mediaRoot": "/media", + "extraGames": [{"id": "x"}], + "systems": [{"id": "snes", "romDir": "/roms", "extensions": [".sfc"], "direct": false}] + }); + let key = library_cache_key(&config); + assert_eq!(key["version"], app_version()); + assert_eq!(key["mediaRoot"], "/media"); + assert_eq!(key["extraGames"].as_array().unwrap().len(), 1); + assert_eq!(key["systems"][0][0], "snes"); + assert_eq!(key["systems"][0][3], false); + } + + #[test] + fn cache_roundtrip_returns_games_only_for_matching_key() { + let dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("../localTmp") + .join(format!("pyrocade-cache-test-{}", uuid::Uuid::new_v4())); + fs::create_dir_all(&dir).unwrap(); + let config = json!({"mediaRoot": "", "extraGames": [], "systems": []}); + let games = vec![Game { + id: "snes:game".to_owned(), + system: "snes".to_owned(), + rom_path: "/roms/game.sfc".to_owned(), + base: "game".to_owned(), + title: "Game".to_owned(), + info: Value::Null, + media: HashMap::new(), + shell: Some("#123abc".to_owned()), + hidden: false, + scanned_title: None, + custom_title: false, + version: None, + media_type: None, + emulator: None, + added: None, + }]; + let raw = serde_json::to_string(&games).unwrap(); + let sizes = HashMap::from([("/roms/game.sfc".to_owned(), 42)]); + assert!(write_library_cache(&config, &dir, &raw, &sizes, None)); + let (cached, known) = read_library_cache(&config, &dir); + assert_eq!(cached.unwrap().len(), 1); + assert_eq!(known.get("/roms/game.sfc"), Some(&42)); + assert!(!write_library_cache( + &config, + &dir, + &raw, + &sizes, + Some(&games) + )); + let other = json!({"mediaRoot": "/elsewhere", "extraGames": [], "systems": []}); + let (miss, kept) = read_library_cache(&other, &dir); + assert!(miss.is_none()); + assert_eq!(kept.get("/roms/game.sfc"), Some(&42)); + fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn disc_sidecar_shell_is_read_only_when_listed() { + let dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("../localTmp") + .join(format!("pyrocade-shell-test-{}", uuid::Uuid::new_v4())); + let game_dir = dir.join("Game"); + fs::create_dir_all(&game_dir).unwrap(); + fs::write(game_dir.join("disc.png"), [0u8; 4]).unwrap(); + fs::write(game_dir.join("disc.json"), r##"{"shell":"#00ff88"}"##).unwrap(); + let listings = ScanListings::default(); + let mut index = MediaIndex { + game_dirs: HashMap::new(), + kinds: HashMap::new(), + files: HashSet::new(), + }; + index.game_dirs.insert("game".to_owned(), game_dir); + let (_media, _info, shell) = find_media(&[index], "Game", &listings); + assert_eq!(shell.as_deref(), Some("#00ff88")); + fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn scan_sorts_titles_case_insensitively() { + let mut titles = vec!["zebra".to_owned(), "Apple".to_owned(), "mango".to_owned()]; + titles.sort_by(|a, b| a.to_lowercase().cmp(&b.to_lowercase())); + assert_eq!(titles, vec!["Apple", "mango", "zebra"]); + } +} diff --git a/src-tauri/src/config.rs b/src-tauri/src/config.rs new file mode 100644 index 0000000..4bc8e01 --- /dev/null +++ b/src-tauri/src/config.rs @@ -0,0 +1,501 @@ +use serde_json::{Value, json}; +use std::fs; +use std::path::Path; + +const SYSTEMS: &str = r###"[ + {"id":"ps1","name":"PlayStation","caseType":"jewel","media":"disc","color":"#9aa3ad","extensions":[".m3u",".cue",".chd",".pbp"],"emulator":"duckstation","libretro":"Sony - PlayStation"}, + {"id":"ps2","name":"PlayStation 2","caseType":"dvd","media":"disc","color":"#1d3f8f","extensions":[".iso",".chd",".cso",".gz"],"emulator":"pcsx2","libretro":"Sony - PlayStation 2"}, + {"id":"ps3","name":"PlayStation 3","caseType":"bluray","media":"disc","color":"#2b2b2b","extensions":[".iso"],"emulator":"rpcs3","libretro":"Sony - PlayStation 3"}, + {"id":"ps4","name":"PlayStation 4","caseType":"bluray","media":"disc","color":"#1a4fb5","extensions":[".pkg"],"emulator":"shadps4"}, + {"id":"psp","name":"PSP","caseType":"umd","media":"disc","color":"#111111","extensions":[".iso",".cso",".chd"],"emulator":"ppsspp","libretro":"Sony - PlayStation Portable"}, + {"id":"switch","name":"Nintendo Switch","caseType":"switch","media":"cart","color":"#e60012","extensions":[".nsp",".xci",".nsz"],"emulator":"","artworkProvider":"gametdb-switch"}, + {"id":"switch2","name":"Nintendo Switch 2","caseType":"switch","media":"cart","color":"#d0021b","extensions":[".nsp",".xci",".nsz",".xcz",".nup"],"emulator":"","artworkProvider":"gametdb-switch"}, + {"id":"wiiu","name":"Wii U","caseType":"dvd","media":"disc","color":"#1a9ad6","extensions":[".wua",".wud",".wux",".rpx"],"emulator":"cemu","libretro":"Nintendo - Wii U"}, + {"id":"wii","name":"Wii","caseType":"dvd","media":"disc","color":"#e9eef2","extensions":[".rvz",".wbfs",".iso"],"emulator":"","libretro":"Nintendo - Wii"}, + {"id":"gc","name":"GameCube","caseType":"gc","media":"disc","color":"#5a4a9c","extensions":[".rvz",".iso",".gcm",".ciso"],"emulator":"","libretro":"Nintendo - GameCube"}, + {"id":"n64","name":"Nintendo 64","caseType":"bigbox","media":"cart","color":"#2a7d3a","extensions":[".z64",".n64",".v64"],"emulator":"","libretro":"Nintendo - Nintendo 64"}, + {"id":"snes","name":"Super Nintendo","caseType":"bigbox","media":"cart","color":"#7b6fb5","extensions":[".sfc",".smc"],"emulator":"","libretro":"Nintendo - Super Nintendo Entertainment System"}, + {"id":"nes","name":"NES","caseType":"nesbox","media":"cart","color":"#c4262e","extensions":[".nes",".zip"],"emulator":"","libretro":"Nintendo - Nintendo Entertainment System"}, + {"id":"3ds","name":"Nintendo 3DS","caseType":"ds","media":"cart","color":"#d41e2a","extensions":[".3ds",".cci",".cxi",".cia"],"emulator":"azahar","libretro":"Nintendo - Nintendo 3DS"}, + {"id":"nds","name":"Nintendo DS","caseType":"ds","media":"cart","color":"#c9c9c9","extensions":[".nds",".zip"],"emulator":"melonds","libretro":"Nintendo - Nintendo DS"}, + {"id":"gba","name":"Game Boy Advance","caseType":"cartbox","media":"cart","color":"#4b3a9b","extensions":[".gba",".zip"],"emulator":"mgba","libretro":"Nintendo - Game Boy Advance"}, + {"id":"gbc","name":"Game Boy Color","caseType":"cartbox","media":"cart","color":"#7a3fb0","extensions":[".gbc",".zip"],"emulator":"mgba","libretro":"Nintendo - Game Boy Color"}, + {"id":"gb","name":"Game Boy","caseType":"cartbox","media":"cart","color":"#8b8f6a","extensions":[".gb",".zip"],"emulator":"mgba","libretro":"Nintendo - Game Boy"}, + {"id":"dreamcast","name":"Dreamcast","caseType":"jewel","media":"disc","color":"#e8e8e8","extensions":[".chd",".gdi",".cdi"],"emulator":"flycast","libretro":"Sega - Dreamcast"}, + {"id":"genesis","name":"Sega Genesis","caseType":"dvd","media":"cart","color":"#1b1b1b","extensions":[".md",".gen",".smd",".zip"],"emulator":"","libretro":"Sega - Mega Drive - Genesis"}, + {"id":"xbox","name":"Xbox","caseType":"dvd","media":"disc","color":"#1c8a2e","extensions":[".iso",".xiso"],"emulator":"xemu","libretro":"Microsoft - Xbox"}, + {"id":"x360","name":"Xbox 360","caseType":"dvd","media":"disc","color":"#7cbb00","extensions":[".iso",".xex",".zar"],"emulator":"","libretro":"Microsoft - Xbox 360"}, + {"id":"pc","name":"PC Games","caseType":"dvd","media":"disc","color":"#3b82f6","extensions":[".lnk",".url",".exe"],"emulator":"","direct":true}, + {"id":"a2600","name":"Atari 2600","caseType":"nesbox","media":"cart","color":"#a0522d","extensions":[".a26",".zip"],"emulator":"","libretro":"Atari - 2600"}, + {"id":"arcade","name":"Arcade","caseType":"bigbox","media":"cart","color":"#d4a017","extensions":[".zip"],"emulator":"","libretro":"MAME"} +]"###; + +pub fn default_config() -> Value { + json!({ + "mediaRoot": "", + "hideWhilePlaying": true, + "checkUpdates": true, + "promptFamily": "auto", + "motion": "auto", + "eShopStyle": "enhanced", + "libraryTheme": "ember", + "libraryLayout": "carousel", + "uiSound": {"enabled": true, "volume": 0.25}, + "systems": serde_json::from_str::(SYSTEMS).expect("default systems JSON is valid").as_array().unwrap().iter().map(|s| { + let mut system = s.clone(); + system["romDir"] = Value::String(String::new()); + system + }).collect::>(), + "emulators": {}, + "customEmulators": [], + "extraGames": [], + "favorites": [], + "hiddenGames": [], + "gameDetails": {}, + "gameEmulators": {}, + "gameOrders": {}, + "recentlyPlayed": [], + "sortKey": "title", + "sortAsc": true, + "showFavoritesOnly": false, + "showRecentlyPlayed": false, + "recentlyPlayedLimit": 20, + "migrations": [] + }) +} + +pub fn merge_config(saved: Value) -> Result { + let saved_systems = saved + .get("systems") + .and_then(Value::as_array) + .ok_or_else(|| "missing systems".to_owned())?; + let mut merged = default_config(); + let defaults = merged["systems"].as_array().cloned().unwrap_or_default(); + let mut systems = Vec::with_capacity(saved_systems.len().max(defaults.len())); + for existing in saved_systems { + let id = existing.get("id").and_then(Value::as_str); + let mut system = defaults + .iter() + .find(|d| d.get("id").and_then(Value::as_str) == id) + .cloned() + .unwrap_or_else(|| json!({})); + merge_object(&mut system, existing); + systems.push(system); + } + for default in defaults { + if !systems.iter().any(|s| s.get("id") == default.get("id")) { + systems.push(default); + } + } + let mut saved_other = saved.clone(); + if let Some(object) = saved_other.as_object_mut() { + object.remove("systems"); + } + merge_object(&mut merged, &saved_other); + merged["systems"] = Value::Array(systems); + if let Some(map) = merged.get_mut("emulators") { + if !map.is_object() { + *map = json!({}); + } + } + if !merged.get("customEmulators").is_some_and(Value::is_array) { + merged["customEmulators"] = json!([]); + } + // Preserve library state fields from saved config. + if !merged.get("favorites").is_some_and(Value::is_array) { + merged["favorites"] = saved.get("favorites").cloned().unwrap_or_else(|| json!([])); + } + if !merged.get("hiddenGames").is_some_and(Value::is_array) { + merged["hiddenGames"] = saved + .get("hiddenGames") + .cloned() + .unwrap_or_else(|| json!([])); + } + if !merged.get("gameDetails").is_some_and(Value::is_object) { + merged["gameDetails"] = saved + .get("gameDetails") + .cloned() + .unwrap_or_else(|| json!({})); + } + if !merged.get("gameEmulators").is_some_and(Value::is_object) { + merged["gameEmulators"] = saved + .get("gameEmulators") + .cloned() + .unwrap_or_else(|| json!({})); + } + if !merged.get("gameOrders").is_some_and(Value::is_object) { + merged["gameOrders"] = saved + .get("gameOrders") + .cloned() + .unwrap_or_else(|| json!({})); + } + if !merged.get("recentlyPlayed").is_some_and(Value::is_array) { + merged["recentlyPlayed"] = saved + .get("recentlyPlayed") + .cloned() + .unwrap_or_else(|| json!([])); + } + if merged.get("sortKey").is_none_or(|v| !v.is_string()) { + merged["sortKey"] = saved + .get("sortKey") + .cloned() + .unwrap_or_else(|| json!("title")); + } + if merged.get("sortAsc").is_none_or(|v| !v.is_boolean()) { + merged["sortAsc"] = saved.get("sortAsc").cloned().unwrap_or_else(|| json!(true)); + } + if merged + .get("showFavoritesOnly") + .is_none_or(|v| !v.is_boolean()) + { + merged["showFavoritesOnly"] = saved + .get("showFavoritesOnly") + .cloned() + .unwrap_or_else(|| json!(false)); + } + if merged + .get("showRecentlyPlayed") + .is_none_or(|v| !v.is_boolean()) + { + merged["showRecentlyPlayed"] = saved + .get("showRecentlyPlayed") + .cloned() + .unwrap_or_else(|| json!(false)); + } + if merged + .get("recentlyPlayedLimit") + .is_none_or(|v| !v.is_number()) + { + merged["recentlyPlayedLimit"] = saved + .get("recentlyPlayedLimit") + .cloned() + .unwrap_or_else(|| json!(20)); + } + if !merged.get("migrations").is_some_and(Value::is_array) { + merged["migrations"] = saved + .get("migrations") + .cloned() + .unwrap_or_else(|| json!([])); + } + // One-time file-type migration; a type the user removes afterwards stays removed. + let mut done: Vec = merged["migrations"] + .as_array() + .map(|a| { + a.iter() + .filter_map(Value::as_str) + .map(str::to_owned) + .collect() + }) + .unwrap_or_default(); + if !done.contains(&"ext-switch2-nup".to_owned()) { + if let Some(switch2) = merged["systems"].as_array_mut().and_then(|s| { + s.iter_mut() + .find(|s| s.get("id").and_then(Value::as_str) == Some("switch2")) + }) { + let extensions = switch2 + .as_object_mut() + .map(|o| o.entry("extensions").or_insert_with(|| json!([])).clone()) + .unwrap_or_else(|| json!([])); + let needs_nup = !extensions + .as_array() + .is_some_and(|e| e.iter().any(|v| v == ".nup")); + if needs_nup { + if let Some(object) = switch2.as_object_mut() { + if let Some(e) = object.get_mut("extensions").and_then(Value::as_array_mut) { + e.push(json!(".nup")); + } else { + object.insert("extensions".to_owned(), json!([".nup"])); + } + } + } + } + done.push("ext-switch2-nup".to_owned()); + merged["migrations"] = json!(done); + } + Ok(merged) +} + +pub fn config_for_save(incoming: Value, current: &Value) -> Result { + if !incoming.get("systems").is_some_and(Value::is_array) { + return Err("Invalid settings".to_owned()); + } + let mut next = incoming; + next["emulators"] = current + .get("emulators") + .cloned() + .unwrap_or_else(|| json!({})); + next["customEmulators"] = current + .get("customEmulators") + .cloned() + .unwrap_or_else(|| json!([])); + next["extraGames"] = current + .get("extraGames") + .cloned() + .unwrap_or_else(|| json!([])); + // Preserve library state fields from current config. + next["favorites"] = current + .get("favorites") + .cloned() + .unwrap_or_else(|| json!([])); + next["hiddenGames"] = current + .get("hiddenGames") + .cloned() + .unwrap_or_else(|| json!([])); + next["gameDetails"] = current + .get("gameDetails") + .cloned() + .unwrap_or_else(|| json!({})); + next["gameEmulators"] = current + .get("gameEmulators") + .cloned() + .unwrap_or_else(|| json!({})); + next["gameOrders"] = current + .get("gameOrders") + .cloned() + .unwrap_or_else(|| json!({})); + next["recentlyPlayed"] = current + .get("recentlyPlayed") + .cloned() + .unwrap_or_else(|| json!([])); + next["sortKey"] = current + .get("sortKey") + .cloned() + .unwrap_or_else(|| json!("title")); + next["sortAsc"] = current + .get("sortAsc") + .cloned() + .unwrap_or_else(|| json!(true)); + next["showFavoritesOnly"] = current + .get("showFavoritesOnly") + .cloned() + .unwrap_or_else(|| json!(false)); + next["showRecentlyPlayed"] = current + .get("showRecentlyPlayed") + .cloned() + .unwrap_or_else(|| json!(false)); + next["recentlyPlayedLimit"] = current + .get("recentlyPlayedLimit") + .cloned() + .unwrap_or_else(|| json!(20)); + next["migrations"] = current + .get("migrations") + .cloned() + .unwrap_or_else(|| json!([])); + Ok(next) +} + +fn merge_object(target: &mut Value, source: &Value) { + let (Some(target), Some(source)) = (target.as_object_mut(), source.as_object()) else { + return; + }; + for (key, value) in source { + if value.is_object() && target.get(key).is_some_and(Value::is_object) { + merge_object(target.get_mut(key).unwrap(), value); + } else { + target.insert(key.clone(), value.clone()); + } + } +} + +pub fn load_config(path: &Path) -> (Value, Option) { + let text = match fs::read_to_string(path) { + Ok(text) => text, + Err(_) => return (default_config(), None), + }; + let parsed = serde_json::from_str::(&text) + .map_err(|e| e.to_string()) + .and_then(merge_config); + match parsed { + Ok(config) => (config, None), + Err(error) => { + let backup = path.with_file_name(format!( + "config.json.broken-{}", + chrono::Utc::now().timestamp_millis() + )); + let _ = fs::copy(path, &backup); + let warning = format!( + "Your settings file was damaged, so defaults were loaded. The old file was kept as {} in the data folder.", + backup + .file_name() + .and_then(|n| n.to_str()) + .unwrap_or("config.json.broken") + ); + let _ = error; + (default_config(), Some(warning)) + } + } +} + +pub fn save_config(path: &Path, config: &Value) -> Result<(), String> { + fs::create_dir_all(path.parent().unwrap_or_else(|| Path::new("."))) + .map_err(|e| e.to_string())?; + let tmp = path.with_extension("json.tmp"); + let bytes = serde_json::to_vec_pretty(config).map_err(|e| e.to_string())?; + fs::write(&tmp, bytes).map_err(|e| e.to_string())?; + fs::rename(tmp, path).map_err(|e| e.to_string()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn defaults_include_the_current_system_catalog() { + let config = default_config(); + assert_eq!(config["systems"].as_array().unwrap().len(), 25); + assert_eq!(config["systems"][0]["romDir"], ""); + assert_eq!(config["uiSound"]["volume"], 0.25); + assert_eq!(config["extraGames"], json!([])); + assert_eq!(config["hiddenGames"], json!([])); + assert_eq!(config["gameDetails"], json!({})); + assert_eq!(config["gameEmulators"], json!({})); + assert_eq!(config["gameOrders"], json!({})); + let pc = config["systems"] + .as_array() + .unwrap() + .iter() + .find(|s| s["id"] == "pc") + .expect("pc system"); + assert_eq!(pc["direct"], true); + assert_eq!(pc["extensions"], json!([".lnk", ".url", ".exe"])); + let switch2 = config["systems"] + .as_array() + .unwrap() + .iter() + .find(|s| s["id"] == "switch2") + .expect("switch2 system"); + assert!( + switch2["extensions"] + .as_array() + .unwrap() + .contains(&json!(".nup")) + ); + assert_eq!(config["migrations"], json!([])); + } + + #[test] + fn merge_preserves_collection_state() { + let saved = json!({ + "systems": [], + "hiddenGames": ["ps1:zelda"], + "gameDetails": {"ps1:zelda": {"title": "Custom", "version": "1.01", "mediaType": "disc"}}, + "gameEmulators": {"ps1:zelda": "duckstation"}, + "gameOrders": {"ps1": ["ps1:zelda", "ps1:crc"]} + }); + let merged = merge_config(saved).unwrap(); + assert_eq!(merged["hiddenGames"], json!(["ps1:zelda"])); + assert_eq!(merged["gameDetails"]["ps1:zelda"]["title"], "Custom"); + assert_eq!(merged["gameEmulators"]["ps1:zelda"], "duckstation"); + assert_eq!(merged["gameOrders"]["ps1"], json!(["ps1:zelda", "ps1:crc"])); + } + + #[test] + fn merge_preserves_user_values_and_adds_new_default_systems() { + let saved = json!({ + "mediaRoot": "/media/art", + "systems": [{"id":"ps1","romDir":"/roms/ps1","name":"My PlayStation"}], + "emulators": {"duckstation":{"exe":"/opt/duckstation"}}, + "customEmulators": [{"id":"custom-one"}] + }); + let merged = merge_config(saved).unwrap(); + assert_eq!(merged["mediaRoot"], "/media/art"); + assert_eq!(merged["systems"][0]["romDir"], "/roms/ps1"); + assert_eq!(merged["systems"][0]["name"], "My PlayStation"); + assert_eq!(merged["systems"].as_array().unwrap().len(), 25); + assert_eq!(merged["customEmulators"][0]["id"], "custom-one"); + assert!( + merged["systems"] + .as_array() + .unwrap() + .iter() + .any(|s| s["id"] == "pc") + ); + } + + #[test] + fn merge_preserves_saf_document_tree_uris() { + let saved = json!({ + "systems": [{"id":"ps1","romDir":"content://com.android.externalstorage.documents/tree/abc"}] + }); + let merged = merge_config(saved).unwrap(); + assert_eq!( + merged["systems"][0]["romDir"], + "content://com.android.externalstorage.documents/tree/abc" + ); + } + + #[test] + fn merge_migrates_switch2_nup_once() { + let saved = json!({ + "systems": [ + {"id":"switch2","romDir":"/roms","extensions":[".nsp",".xci",".nsz",".xcz"]} + ] + }); + let merged = merge_config(saved).unwrap(); + let switch2 = merged["systems"] + .as_array() + .unwrap() + .iter() + .find(|s| s["id"] == "switch2") + .unwrap(); + assert!( + switch2["extensions"] + .as_array() + .unwrap() + .contains(&json!(".nup")) + ); + assert!( + merged["migrations"] + .as_array() + .unwrap() + .contains(&json!("ext-switch2-nup")) + ); + // A user-removed type stays removed once the migration has run. + let saved2 = json!({ + "systems": [ + {"id":"switch2","romDir":"/roms","extensions":[".nsp"]} + ], + "migrations": ["ext-switch2-nup"] + }); + let merged2 = merge_config(saved2).unwrap(); + let switch2b = merged2["systems"] + .as_array() + .unwrap() + .iter() + .find(|s| s["id"] == "switch2") + .unwrap(); + assert_eq!(switch2b["extensions"], json!([".nsp"])); + } + + #[test] + fn renderer_settings_cannot_overwrite_backend_owned_emulator_state() { + let current = json!({"emulators":{"one":{"exe":"/safe/path"}},"customEmulators":[{"id":"local"}],"migrations":["ext-switch2-nup"]}); + let next = config_for_save( + json!({"systems":[],"emulators":{},"customEmulators":[],"migrations":[]}), + ¤t, + ) + .unwrap(); + assert_eq!(next["emulators"]["one"]["exe"], "/safe/path"); + assert_eq!(next["customEmulators"][0]["id"], "local"); + assert_eq!(next["migrations"], json!(["ext-switch2-nup"])); + } + + #[test] + fn renderer_settings_cannot_overwrite_collection_state() { + let current = json!({ + "hiddenGames": ["ps1:zelda"], + "gameDetails": {"ps1:zelda": {"title": "Custom"}}, + "gameEmulators": {"ps1:zelda": "duckstation"}, + "gameOrders": {"ps1": ["ps1:zelda"]} + }); + let next = config_for_save( + json!({"systems":[], "hiddenGames": [], "gameDetails": {}, "gameEmulators": {}, "gameOrders": {}}), + ¤t, + ) + .unwrap(); + assert_eq!(next["hiddenGames"], json!(["ps1:zelda"])); + assert_eq!(next["gameDetails"]["ps1:zelda"]["title"], "Custom"); + assert_eq!(next["gameEmulators"]["ps1:zelda"], "duckstation"); + assert_eq!(next["gameOrders"]["ps1"], json!(["ps1:zelda"])); + } +} diff --git a/src-tauri/src/emulators.rs b/src-tauri/src/emulators.rs new file mode 100644 index 0000000..80baf52 --- /dev/null +++ b/src-tauri/src/emulators.rs @@ -0,0 +1,1245 @@ +use crate::backend::AppState; +use crate::config::save_config; +use futures_util::StreamExt; +use serde_json::{Value, json}; +use std::collections::HashSet; +use std::fs; +#[cfg(not(target_os = "macos"))] +use std::fs::File; +use std::path::{Path, PathBuf}; +use std::process::Command; +use tauri::{AppHandle, Emitter, State}; +use tauri_plugin_dialog::DialogExt; +use tauri_plugin_opener::OpenerExt; +use tokio::io::AsyncWriteExt; + +const CATALOG: &str = include_str!("../../emulators.json"); + +#[tauri::command] +pub fn list_emulators(state: State<'_, AppState>) -> Result, String> { + let config = state.config(); + let catalog: Vec = serde_json::from_str(CATALOG).map_err(|e| e.to_string())?; + let mut ids = HashSet::new(); + let mut result = Vec::new(); + for entry in catalog.iter().chain( + config + .get("customEmulators") + .and_then(Value::as_array) + .into_iter() + .flatten(), + ) { + if let Some(id) = entry.get("id").and_then(Value::as_str) { + if ids.insert(id.to_owned()) { + result.push(emu_status(&state, entry, &config)); + } + } + } + Ok(result) +} + +#[tauri::command] +pub async fn check_emulator_update( + state: State<'_, AppState>, + id: String, +) -> Result { + if is_android_target() { + return Err( + "Emulators on Android are installed from the Play Store; update them there.".to_owned(), + ); + } + let config = state.config(); + let latest = latest_release(&id, &config).await?; + let installed = read_manifest(&state.emu_dir, &id); + let update_available = + installed.as_ref().and_then(|m| m.get("assetId")) != latest.get("assetId"); + Ok(json!({"latest":latest,"updateAvailable":update_available})) +} + +#[tauri::command] +pub async fn install_emulator( + app: AppHandle, + state: State<'_, AppState>, + id: String, +) -> Result { + if is_android_target() { + return Err( + "Emulators on Android are installed from the Play Store; link the installed app by package instead." + .to_owned(), + ); + } + { + let mut guard = installing().lock().map_err(|e| e.to_string())?; + if !guard.insert(id.clone()) { + return Err("Already installing".to_owned()); + } + } + let result = install_inner(&app, &state, &id).await; + if let Ok(mut guard) = installing().lock() { + guard.remove(&id); + } + result +} + +static INSTALLING: std::sync::OnceLock>> = + std::sync::OnceLock::new(); + +fn installing() -> &'static std::sync::Mutex> { + INSTALLING.get_or_init(|| std::sync::Mutex::new(HashSet::new())) +} + +async fn install_inner(app: &AppHandle, state: &AppState, id: &str) -> Result { + let config = state.config(); + let definition = find_definition(id, &config).ok_or_else(|| "Unknown emulator".to_owned())?; + let definition = selected_definition(&definition, &config, id); + definition + .get("source") + .filter(|v| !v.is_null()) + .ok_or_else(|| { + "This emulator is not managed by the downloader on this platform and architecture." + .to_owned() + })?; + emit_progress( + app, + json!({"id":id,"stage":"Checking latest release…","pct":0}), + ); + let release = latest_release_from_definition(&definition, &config, id).await?; + let url = release + .get("url") + .and_then(Value::as_str) + .ok_or("Release asset has no URL")?; + let asset_name = release + .get("assetName") + .and_then(Value::as_str) + .ok_or("Release asset has no filename")?; + let temp = std::env::temp_dir().join(format!("pyrocade-{}", uuid::Uuid::new_v4())); + fs::create_dir_all(&temp).map_err(|e| e.to_string())?; + let archive = temp.join(asset_name); + let result = async { + let response = reqwest::Client::builder().user_agent("PyroCade-Frontend").build().map_err(|e| e.to_string())? + .get(url).send().await.map_err(|e| e.to_string())?; + if !response.status().is_success() { return Err(format!("Download failed: HTTP {}", response.status())); } + let total = response.content_length().or_else(|| release.get("size").and_then(Value::as_u64)).unwrap_or_default(); + let mut stream = response.bytes_stream(); + let mut file = tokio::fs::File::create(&archive).await.map_err(|e| e.to_string())?; + let mut got = 0_u64; + let mut last = std::time::Instant::now(); + while let Some(chunk) = stream.next().await { + let chunk = chunk.map_err(|e| e.to_string())?; + file.write_all(&chunk).await.map_err(|e| e.to_string())?; + got += chunk.len() as u64; + if last.elapsed() >= std::time::Duration::from_millis(120) { + emit_progress(app, json!({"id":id,"stage":format!("Downloading {asset_name}"),"pct":if total > 0 { got as f64 / total as f64 } else { 0.0 },"got":got,"total":total})); + last = std::time::Instant::now(); + } + } + file.flush().await.map_err(|e| e.to_string())?; + let stage = temp.join("unpacked"); + fs::create_dir_all(&stage).map_err(|e| e.to_string())?; + if is_archive(asset_name) { + emit_progress(app, json!({"id":id,"stage":"Extracting…","pct":1})); + extract_archive(&archive, &stage)?; + } else { + fs::rename(&archive, stage.join(asset_name)).map_err(|e| e.to_string())?; + } + let source_dir = one_wrapping_directory(&stage); + let bundle_regex = definition + .get("appBundle") + .and_then(Value::as_str) + .map(|pattern| regex::Regex::new(&format!("(?i){pattern}"))) + .transpose() + .map_err(|e| e.to_string())?; + let found_bundle = bundle_regex + .as_ref() + .and_then(|pattern| find_app_bundle(&source_dir, pattern)); + let found = if let Some(bundle) = found_bundle { + bundle + } else { + let exe_pattern = definition + .get("exe") + .and_then(Value::as_str) + .ok_or("Emulator program pattern is missing")?; + let exe_regex = regex::Regex::new(&format!("(?i){exe_pattern}")) + .map_err(|e| e.to_string())?; + find_program(&source_dir, &exe_regex).ok_or_else(|| { + format!("Downloaded, but couldn't find the program (/{exe_pattern}/) in it.") + })? + }; + let relative = found.strip_prefix(&source_dir).map_err(|e| e.to_string())?; + let destination = state.emu_dir.join(id); + copy_tree(&source_dir, &destination)?; + let executable = destination.join(relative); + if !executable.is_dir() { + set_executable(&executable)?; + } + let mut manifest = release.clone(); + manifest["exe"] = Value::String(relative.to_string_lossy().replace('\\', "/")); + manifest["platform"] = Value::String(target_platform().to_owned()); + manifest["architecture"] = Value::String(target_architecture().to_owned()); + manifest["installedAt"] = Value::String(chrono::Utc::now().to_rfc3339()); + if let Some(object) = manifest.as_object_mut() { object.remove("notes"); } + write_manifest(&state.emu_dir, id, &manifest)?; + emit_progress(app, json!({"id":id,"stage":"Done","pct":1,"done":true})); + Ok(emu_status(state, &find_definition(id, &config).ok_or("Unknown emulator")?, &config)) + }.await; + let _ = fs::remove_dir_all(&temp); + result +} + +#[tauri::command] +pub fn uninstall_emulator(state: State<'_, AppState>, id: String) -> Result { + let config = state.config(); + let definition = find_definition(&id, &config).ok_or_else(|| "Unknown emulator".to_owned())?; + let path = state.emu_dir.join(&id); + if path.exists() { + fs::remove_dir_all(&path).map_err(|e| e.to_string())?; + } + Ok(emu_status(&state, &definition, &config)) +} + +#[tauri::command] +pub fn open_emulator_folder( + app: AppHandle, + state: State<'_, AppState>, + id: String, +) -> Result<(), String> { + if is_android_target() { + return Err( + "Emulators on Android are installed apps, not folders; launch them by package instead." + .to_owned(), + ); + } + let config = state.config(); + let definition = find_definition(&id, &config).ok_or_else(|| "Unknown emulator".to_owned())?; + let exe = resolve_exe(&state.emu_dir, &id, &definition, &config); + let path = exe + .and_then(|p| p.parent().map(Path::to_path_buf)) + .unwrap_or_else(|| state.emu_dir.clone()); + fs::create_dir_all(&path).map_err(|e| e.to_string())?; + app.opener() + .open_path(path.to_string_lossy().into_owned(), None::<&str>) + .map_err(|e| e.to_string()) +} + +#[tauri::command] +/// `async` so the dialog's `blocking_*` call runs off the main thread: +/// sync Tauri commands execute on the main thread and would park it in the +/// plugin's rendezvous `recv()` forever. +pub async fn pick_emulator_executable( + app: AppHandle, + state: State<'_, AppState>, + id: String, +) -> Result, String> { + if is_android_target() { + return Err( + "Link an installed emulator by package name on Android instead of picking a program." + .to_owned(), + ); + } + let Some(path) = app + .dialog() + .file() + .set_title("Choose emulator program") + .blocking_pick_file() + .and_then(|p| p.into_path().ok()) + else { + return Ok(None); + }; + let mut config = state.config.write().map_err(|e| e.to_string())?; + let overrides = config["emulators"] + .as_object_mut() + .ok_or("Invalid emulator settings")?; + let current = overrides.entry(id.clone()).or_insert_with(|| json!({})); + current["exe"] = Value::String(path.to_string_lossy().to_string()); + let next = config.clone(); + save_config(&state.config_path, &next)?; + let definition = find_definition(&id, &next).ok_or_else(|| "Unknown emulator".to_owned())?; + Ok(Some(emu_status(&state, &definition, &next))) +} + +#[tauri::command] +pub async fn add_custom_emulator( + app: AppHandle, + state: State<'_, AppState>, + opts: Value, +) -> Result, String> { + let name = opts + .get("name") + .and_then(Value::as_str) + .unwrap_or("Custom emulator") + .trim(); + if name.is_empty() { + return Err("Enter an emulator name.".to_owned()); + } + let android_package = if is_android_target() { + let package = opts + .get("package") + .and_then(Value::as_str) + .unwrap_or("") + .trim() + .to_owned(); + if !valid_android_package(&package) { + return Err( + "Enter a valid Android package name such as com.retroarch.aarch64.".to_owned(), + ); + } + Some(package) + } else { + None + }; + let path = if android_package.is_none() { + let Some(path) = app + .dialog() + .file() + .set_title(format!("Choose {name} program")) + .blocking_pick_file() + .and_then(|p| p.into_path().ok()) + else { + return Ok(None); + }; + Some(path) + } else { + None + }; + let slug = name + .to_lowercase() + .chars() + .map(|c| if c.is_ascii_alphanumeric() { c } else { '-' }) + .collect::(); + let id = format!( + "custom-{}", + slug.split('-') + .filter(|s| !s.is_empty()) + .collect::>() + .join("-") + ); + let mut config = state.config.write().map_err(|e| e.to_string())?; + let custom = config["customEmulators"] + .as_array_mut() + .ok_or("Invalid emulator settings")?; + custom.retain(|entry| entry.get("id").and_then(Value::as_str) != Some(&id)); + custom.push(json!({ + "id": id, "name": name, + "systems": opts.get("systems").cloned().unwrap_or_else(|| json!([])), + "args": opts.get("args").and_then(Value::as_str).unwrap_or("{rom}"), + "exe": path.as_ref().map(|path| path.to_string_lossy().into_owned()).unwrap_or_default(), + "package": android_package.clone() + })); + let next = config.clone(); + save_config(&state.config_path, &next)?; + let definition = + find_definition(&id, &next).ok_or_else(|| "Could not save custom emulator".to_owned())?; + Ok(Some(emu_status(&state, &definition, &next))) +} + +pub(crate) fn find_definition(id: &str, config: &Value) -> Option { + let catalog: Vec = serde_json::from_str(CATALOG).ok()?; + catalog + .into_iter() + .find(|e| e.get("id").and_then(Value::as_str) == Some(id)) + .or_else(|| { + config + .get("customEmulators") + .and_then(Value::as_array)? + .iter() + .find(|e| e.get("id").and_then(Value::as_str) == Some(id)) + .cloned() + }) +} + +pub(crate) fn is_android_target() -> bool { + target_platform() == "android" +} + +fn valid_android_package(package: &str) -> bool { + // Android package names are reverse-DNS: at least two segments, + // each starting with a letter or underscore. + let package = package.trim(); + if package.is_empty() || package.len() > 255 { + return false; + } + let segments: Vec<_> = package.split('.').collect(); + if segments.len() < 2 { + return false; + } + segments.iter().all(|segment| { + !segment.is_empty() + && segment + .chars() + .next() + .is_some_and(|c| c.is_ascii_alphabetic() || c == '_') + && segment + .chars() + .all(|c| c.is_ascii_alphanumeric() || c == '_') + }) +} + +pub(crate) fn linked_package(config: &Value, id: &str) -> Option { + config + .get("emulators") + .and_then(|v| v.get(id)) + .and_then(|v| v.get("package")) + .and_then(Value::as_str) + .filter(|package| valid_android_package(package)) + .map(|package| package.trim().to_owned()) + .or_else(|| { + config + .get("customEmulators") + .and_then(Value::as_array) + .into_iter() + .flatten() + .find(|entry| entry.get("id").and_then(Value::as_str) == Some(id)) + .and_then(|entry| entry.get("package").and_then(Value::as_str)) + .filter(|package| valid_android_package(package)) + .map(|package| package.trim().to_owned()) + }) +} + +#[tauri::command] +pub fn link_android_emulator( + state: State<'_, AppState>, + id: String, + package: String, +) -> Result { + let config = state.config(); + find_definition(&id, &config).ok_or_else(|| "Unknown emulator".to_owned())?; + let package = package.trim().to_owned(); + if !valid_android_package(&package) { + return Err("Enter a valid Android package name such as com.retroarch.aarch64.".to_owned()); + } + let mut config = state.config.write().map_err(|e| e.to_string())?; + let entry = config["emulators"] + .as_object_mut() + .ok_or("Invalid emulator settings")? + .entry(id.clone()) + .or_insert_with(|| json!({})); + entry["package"] = Value::String(package); + let next = config.clone(); + save_config(&state.config_path, &next)?; + let definition = find_definition(&id, &next).ok_or_else(|| "Unknown emulator".to_owned())?; + Ok(emu_status(&state, &definition, &next)) +} + +#[tauri::command] +pub fn unlink_android_emulator(state: State<'_, AppState>, id: String) -> Result { + let config = state.config(); + find_definition(&id, &config).ok_or_else(|| "Unknown emulator".to_owned())?; + let mut config = state.config.write().map_err(|e| e.to_string())?; + if let Some(entry) = config + .get_mut("emulators") + .and_then(|v| v.as_object_mut()) + .and_then(|object| object.get_mut(&id)) + { + if let Some(object) = entry.as_object_mut() { + object.remove("package"); + } + } + let next = config.clone(); + save_config(&state.config_path, &next)?; + let definition = find_definition(&id, &next).ok_or_else(|| "Unknown emulator".to_owned())?; + Ok(emu_status(&state, &definition, &next)) +} + +pub(crate) fn selected_definition(base: &Value, config: &Value, id: &str) -> Value { + selected_definition_for_target(base, config, id, target_platform(), target_architecture()) +} + +fn selected_definition_for_target( + base: &Value, + config: &Value, + id: &str, + platform: &str, + architecture: &str, +) -> Value { + let custom = base.get("custom").and_then(Value::as_bool).unwrap_or(false) + || base + .get("id") + .and_then(Value::as_str) + .is_some_and(|s| s.starts_with("custom-")); + let specific = base + .get("platforms") + .and_then(|p| p.get(platform)) + .and_then(|p| p.get(architecture)); + let mut selected = base.clone(); + if !custom { + if let Some(data) = specific { + if let Some(object) = selected.as_object_mut() { + for key in [ + "asset", + "exe", + "appBundle", + "args", + "source", + "repo", + "systems", + "package", + ] { + if let Some(value) = data.get(key) { + object.insert(key.to_owned(), value.clone()); + } + } + if data.get("repo").is_some() { + let source = object.entry("source").or_insert_with(|| json!({})); + source["repo"] = data["repo"].clone(); + } + } + } else { + selected["source"] = Value::Null; + selected["asset"] = Value::Null; + selected["exe"] = Value::Null; + selected["appBundle"] = Value::Null; + } + } + if let Some(override_value) = config.get("emulators").and_then(|v| v.get(id)) { + if let Some(object) = selected.as_object_mut() { + for (key, value) in override_value.as_object().into_iter().flatten() { + if !["exe", "asset", "source", "appBundle"].contains(&key.as_str()) { + object.insert(key.clone(), value.clone()); + } + } + object.insert( + "exePath".to_owned(), + override_value.get("exe").cloned().unwrap_or(Value::Null), + ); + } + } + // Android has no managed desktop downloads: any catalog emulator can be + // linked manually by package, so it is always available but never managed. + let available = custom || specific.is_some() || platform == "android"; + let managed = !custom + && platform != "android" + && available + && selected + .pointer("/source/repo") + .and_then(Value::as_str) + .is_some() + && selected.get("asset").and_then(Value::as_str).is_some() + && (selected.get("exe").and_then(Value::as_str).is_some() + || selected.get("appBundle").and_then(Value::as_str).is_some()); + selected["custom"] = Value::Bool(custom); + selected["available"] = Value::Bool(available); + selected["managed"] = Value::Bool(managed); + selected["platform"] = Value::String(platform.to_owned()); + selected["architecture"] = Value::String(architecture.to_owned()); + selected +} + +fn target_platform() -> &'static str { + if cfg!(target_os = "windows") { + "windows" + } else if cfg!(target_os = "macos") { + "macos" + } else if cfg!(target_os = "linux") { + "linux" + } else if cfg!(target_os = "android") { + "android" + } else { + std::env::consts::OS + } +} + +fn target_architecture() -> &'static str { + if cfg!(target_arch = "aarch64") { + "arm64" + } else if cfg!(target_arch = "x86_64") { + "x86_64" + } else { + std::env::consts::ARCH + } +} + +fn manifest_matches_target(manifest: &Value, definition: &Value) -> bool { + let platform = definition + .get("platform") + .and_then(Value::as_str) + .unwrap_or_default(); + let architecture = definition + .get("architecture") + .and_then(Value::as_str) + .unwrap_or_default(); + match ( + manifest.get("platform").and_then(Value::as_str), + manifest.get("architecture").and_then(Value::as_str), + ) { + (Some(installed_platform), Some(installed_architecture)) => { + installed_platform == platform && installed_architecture == architecture + } + (None, None) => architecture == "x86_64" && matches!(platform, "windows" | "linux"), + _ => false, + } +} + +fn emu_status(state: &AppState, base: &Value, config: &Value) -> Value { + let id = base.get("id").and_then(Value::as_str).unwrap_or_default(); + let definition = selected_definition(base, config, id); + let manifest = read_manifest(&state.emu_dir, id); + let exe = resolve_exe(&state.emu_dir, id, &definition, config); + let package = linked_package(config, id); + let installed = manifest.as_ref().filter(|m| { + manifest_matches_target(m, &definition) + && m.get("exe") + .and_then(Value::as_str) + .is_some_and(|exe| is_program_path(&state.emu_dir.join(id).join(exe))) + }); + json!({ + "id": id, + "name": definition.get("name").cloned().unwrap_or(Value::String(id.to_owned())), + "systems": definition.get("systems").cloned().unwrap_or_else(|| json!([])), + "repo": definition.pointer("/source/repo"), + "custom": definition.get("custom").and_then(Value::as_bool).unwrap_or(false), + "available": definition.get("available").and_then(Value::as_bool).unwrap_or(false), + "platform": definition.get("platform"), + "architecture": definition.get("architecture"), + "prerelease": definition.pointer("/source/prerelease").and_then(Value::as_bool).unwrap_or(false) || config.pointer(&format!("/emulators/{id}/prerelease")).and_then(Value::as_bool).unwrap_or(false), + "args": definition.get("args"), + "exe": exe.map(|p| p.to_string_lossy().to_string()), + "installed": installed.map(|m| json!({"version":m.get("tag"),"name":m.get("releaseName"),"date":m.get("publishedAt")})), + "managed": definition.get("managed").and_then(Value::as_bool).unwrap_or(false), + "package": package.clone(), + "linked": package.is_some(), + "android": definition.get("platform").and_then(Value::as_str) == Some("android") + }) +} + +pub(crate) fn resolve_exe( + emu_dir: &Path, + id: &str, + definition: &Value, + config: &Value, +) -> Option { + let definition = selected_definition(definition, config, id); + if let Some(path) = definition + .get("exePath") + .and_then(Value::as_str) + .filter(|s| !s.is_empty()) + { + let path = PathBuf::from(path); + if path.is_absolute() && is_program_path(&path) { + return Some(path); + } + } + if let Some(exe) = read_manifest(emu_dir, id).and_then(|manifest| { + manifest_matches_target(&manifest, &definition) + .then(|| { + manifest + .get("exe") + .and_then(Value::as_str) + .map(str::to_owned) + }) + .flatten() + }) { + let path = emu_dir.join(id).join(exe); + if is_program_path(&path) { + return Some(path); + } + } + config + .get("customEmulators") + .and_then(Value::as_array) + .into_iter() + .flatten() + .find(|e| e.get("id").and_then(Value::as_str) == Some(id)) + .and_then(|e| e.get("exe").and_then(Value::as_str)) + .map(PathBuf::from) + .filter(|p| is_program_path(p)) +} + +fn is_program_path(path: &Path) -> bool { + path.is_file() + || (path.is_dir() && path.extension().and_then(|ext| ext.to_str()) == Some("app")) +} + +fn manifest_path(emu_dir: &Path, id: &str) -> PathBuf { + emu_dir.join(id).join("manifest.json") +} +fn read_manifest(emu_dir: &Path, id: &str) -> Option { + fs::read_to_string(manifest_path(emu_dir, id)) + .ok() + .and_then(|s| serde_json::from_str(&s).ok()) +} +fn write_manifest(emu_dir: &Path, id: &str, manifest: &Value) -> Result<(), String> { + let dir = emu_dir.join(id); + fs::create_dir_all(&dir).map_err(|e| e.to_string())?; + fs::write( + dir.join("manifest.json"), + serde_json::to_vec_pretty(manifest).map_err(|e| e.to_string())?, + ) + .map_err(|e| e.to_string()) +} + +async fn latest_release(id: &str, config: &Value) -> Result { + let definition = find_definition(id, config).ok_or_else(|| "Unknown emulator".to_owned())?; + latest_release_from_definition(&selected_definition(&definition, config, id), config, id).await +} + +async fn latest_release_from_definition( + definition: &Value, + config: &Value, + id: &str, +) -> Result { + let source = definition + .get("source") + .filter(|v| !v.is_null()) + .ok_or_else(|| { + "This emulator is not managed by the downloader on this platform and architecture." + .to_owned() + })?; + let repo = source + .get("repo") + .and_then(Value::as_str) + .ok_or("Emulator release repository is missing")?; + let pattern = definition + .get("asset") + .and_then(Value::as_str) + .ok_or("Emulator release asset pattern is missing")?; + let regex = regex::Regex::new(&format!("(?i){pattern}")).map_err(|e| e.to_string())?; + let prerelease = source + .get("prerelease") + .and_then(Value::as_bool) + .unwrap_or(false) + || config + .pointer(&format!("/emulators/{id}/prerelease")) + .and_then(Value::as_bool) + .unwrap_or(false); + let client = reqwest::Client::builder() + .user_agent("PyroCade-Frontend") + .build() + .map_err(|e| e.to_string())?; + let urls = if prerelease { + vec![format!( + "https://api.github.com/repos/{repo}/releases?per_page=15" + )] + } else { + vec![format!( + "https://api.github.com/repos/{repo}/releases/latest" + )] + }; + let mut releases = Vec::new(); + for url in urls { + let response = client + .get(url) + .header("Accept", "application/vnd.github+json") + .send() + .await + .map_err(|e| e.to_string())?; + if !response.status().is_success() { + return Err(format!( + "GitHub {}: {}", + response.status(), + response + .status() + .canonical_reason() + .unwrap_or("request failed") + )); + } + let value: Value = response.json().await.map_err(|e| e.to_string())?; + if prerelease { + releases.extend(value.as_array().cloned().unwrap_or_default()); + } else { + releases.push(value); + } + } + for release in releases { + if release + .get("draft") + .and_then(Value::as_bool) + .unwrap_or(false) + { + continue; + } + let Some(asset) = release + .get("assets") + .and_then(Value::as_array) + .into_iter() + .flatten() + .find(|asset| { + asset + .get("name") + .and_then(Value::as_str) + .is_some_and(|n| regex.is_match(n)) + }) + else { + continue; + }; + let tag = release + .get("tag_name") + .and_then(Value::as_str) + .unwrap_or_default(); + return Ok(json!({ + "tag": tag, + "releaseName": release.get("name").and_then(Value::as_str).filter(|s| !s.is_empty()).unwrap_or(tag), + "publishedAt": asset.get("updated_at").or_else(|| release.get("published_at")), + "assetId": asset.get("id"), "assetName": asset.get("name"), + "size": asset.get("size"), "url": asset.get("browser_download_url"), + "notes": release.get("body").and_then(Value::as_str).unwrap_or("") + })); + } + Err(format!( + "No {} download matching /{pattern}/ found in recent releases.", + match target_platform() { + "windows" => "Windows", + "macos" => "macOS", + "linux" => "Linux", + "android" => "Android", + _ => "platform", + } + )) +} + +fn emit_progress(app: &AppHandle, value: Value) { + let _ = app.emit("emu:progress", value); +} + +fn is_archive(name: &str) -> bool { + regex::Regex::new(r"(?i)\.(zip|7z|tar|tgz|tar\.(gz|xz|zst|bz2))$") + .unwrap() + .is_match(name) +} + +fn extract_archive(archive: &Path, destination: &Path) -> Result<(), String> { + let extension = archive + .file_name() + .and_then(|s| s.to_str()) + .unwrap_or_default() + .to_lowercase(); + if extension.ends_with(".zip") { + return extract_zip(archive, destination); + } + let candidates: Vec<(&str, Vec)> = if extension.ends_with(".7z") { + vec![ + ( + "7z", + vec![ + "x".into(), + "-y".into(), + format!("-o{}", destination.display()), + archive.display().to_string(), + ], + ), + ( + "7za", + vec![ + "x".into(), + "-y".into(), + format!("-o{}", destination.display()), + archive.display().to_string(), + ], + ), + ] + } else { + vec![ + ( + "bsdtar", + vec![ + "-xf".into(), + archive.display().to_string(), + "-C".into(), + destination.display().to_string(), + ], + ), + ( + "tar", + vec![ + "-xf".into(), + archive.display().to_string(), + "-C".into(), + destination.display().to_string(), + ], + ), + ] + }; + for (command, args) in candidates { + match Command::new(command).args(args).status() { + Ok(status) if status.success() => return Ok(()), + Ok(status) => { + return Err(format!( + "{command} could not extract the archive (exit {}).", + status.code().unwrap_or(-1) + )); + } + Err(error) if error.kind() == std::io::ErrorKind::NotFound => continue, + Err(error) => return Err(error.to_string()), + } + } + Err(format!( + "Can't unpack {}: install bsdtar or 7-Zip.", + archive + .file_name() + .and_then(|s| s.to_str()) + .unwrap_or("archive") + )) +} + +fn validate_zip(archive: &Path) -> Result<(), String> { + let file = fs::File::open(archive).map_err(|e| e.to_string())?; + let mut zip = zip::ZipArchive::new(file).map_err(|e| e.to_string())?; + for index in 0..zip.len() { + let entry = zip.by_index(index).map_err(|e| e.to_string())?; + if entry.enclosed_name().is_none() { + return Err(format!("Unsafe path in archive: {}", entry.name())); + } + if entry + .unix_mode() + .is_some_and(|mode| mode & 0o170000 == 0o120000) + { + return Err(format!( + "Symbolic links are not allowed in archives: {}", + entry.name() + )); + } + } + Ok(()) +} + +fn extract_zip(archive: &Path, destination: &Path) -> Result<(), String> { + validate_zip(archive)?; + #[cfg(target_os = "macos")] + { + let status = Command::new("/usr/bin/ditto") + .args(["-x", "-k"]) + .arg(archive) + .arg(destination) + .status() + .map_err(|e| e.to_string())?; + if !status.success() { + return Err(format!( + "ditto could not extract the archive (exit {}).", + status.code().unwrap_or(-1) + )); + } + return Ok(()); + } + #[cfg(not(target_os = "macos"))] + { + let file = File::open(archive).map_err(|e| e.to_string())?; + let mut zip = zip::ZipArchive::new(file).map_err(|e| e.to_string())?; + for index in 0..zip.len() { + let mut entry = zip.by_index(index).map_err(|e| e.to_string())?; + let relative = entry + .enclosed_name() + .ok_or_else(|| format!("Unsafe path in archive: {}", entry.name()))?; + let target = destination.join(relative); + if entry.is_dir() { + fs::create_dir_all(&target).map_err(|e| e.to_string())?; + continue; + } + if let Some(parent) = target.parent() { + fs::create_dir_all(parent).map_err(|e| e.to_string())?; + } + let mut output = File::create(target).map_err(|e| e.to_string())?; + std::io::copy(&mut entry, &mut output).map_err(|e| e.to_string())?; + } + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::{ + CATALOG, linked_package, manifest_matches_target, selected_definition_for_target, + valid_android_package, + }; + use serde_json::{Value, json}; + + #[test] + fn unsupported_arm64_target_does_not_inherit_x86_downloads() { + let base = json!({ + "id": "emu", + "source": {"repo":"windows-x64"}, + "asset": "windows-x64.zip", + "exe": "program.exe", + "platforms": { + "linux": {"x86_64": { + "source": {"repo":"linux-x64"}, + "asset": "linux-x86_64.AppImage", + "exe": "program.AppImage" + }} + } + }); + for platform in ["macos", "linux"] { + let selected = + selected_definition_for_target(&base, &json!({}), "emu", platform, "arm64"); + + assert_eq!(selected["available"], false); + assert_eq!(selected["managed"], false); + assert_eq!(selected["source"], Value::Null); + assert_eq!(selected["asset"], Value::Null); + assert_eq!(selected["exe"], Value::Null); + } + let selected = selected_definition_for_target(&base, &json!({}), "emu", "android", "arm64"); + assert_eq!(selected["available"], true); + assert_eq!(selected["managed"], false); + assert_eq!(selected["source"], Value::Null); + assert_eq!(selected["asset"], Value::Null); + assert_eq!(selected["exe"], Value::Null); + } + + #[test] + fn android_package_names_are_reverse_dns() { + assert!(valid_android_package("com.retroarch.aarch64")); + assert!(valid_android_package("org.ppsspp.ppsspp")); + assert!(valid_android_package("com.duckstation")); + assert!(!valid_android_package("")); + assert!(!valid_android_package("retroarch")); + assert!(!valid_android_package("com..app")); + assert!(!valid_android_package("1com.app")); + assert!(!valid_android_package("com.my app")); + } + + #[test] + fn android_manual_link_is_available_without_managed_download() { + let base = json!({ + "id": "emu", + "platforms": {"linux": {"x86_64": { + "source": {"repo":"linux-x64"}, + "asset": "linux-x86_64.AppImage", + "exe": "program.AppImage" + }}} + }); + let selected = selected_definition_for_target(&base, &json!({}), "emu", "android", "arm64"); + assert_eq!(selected["available"], true); + assert_eq!(selected["managed"], false); + assert_eq!(selected["platform"], "android"); + } + + #[test] + fn linked_package_reads_config_overrides_and_custom_entries() { + let config = json!({"emulators":{"duckstation":{"package":"com.duckstation"}}}); + assert_eq!( + linked_package(&config, "duckstation").as_deref(), + Some("com.duckstation") + ); + assert_eq!(linked_package(&config, "missing"), None); + let config = json!({"emulators":{"duckstation":{"package":"not a package"}}}); + assert_eq!(linked_package(&config, "duckstation"), None); + let config = json!({ + "emulators": {}, + "customEmulators": [{"id":"custom-one","package":"com.example.emu"}] + }); + assert_eq!( + linked_package(&config, "custom-one").as_deref(), + Some("com.example.emu") + ); + } + + #[test] + fn arm64_catalog_download_and_manual_link_remain_distinct() { + let base = json!({ + "id": "emu", + "platforms": {"linux": {"arm64": { + "source": {"repo":"linux-arm64"}, + "asset": "linux-aarch64.AppImage", + "exe": "program.AppImage" + }}} + }); + let config = json!({"emulators":{"emu":{"exe":"/custom/program"}}}); + let selected = selected_definition_for_target(&base, &config, "emu", "linux", "arm64"); + + assert_eq!(selected["available"], true); + assert_eq!(selected["managed"], true); + assert_eq!(selected["asset"], "linux-aarch64.AppImage"); + assert_eq!(selected["exe"], "program.AppImage"); + assert_eq!(selected["exePath"], "/custom/program"); + } + + #[test] + fn legacy_manifests_are_trusted_only_on_x86_64_desktop_targets() { + let legacy = json!({"exe":"program.AppImage"}); + assert!(manifest_matches_target( + &legacy, + &json!({"platform":"linux","architecture":"x86_64"}) + )); + assert!(!manifest_matches_target( + &legacy, + &json!({"platform":"linux","architecture":"arm64"}) + )); + } + + #[test] + fn catalog_has_managed_macos_and_linux_arm64_builds() { + let catalog: Vec = serde_json::from_str(CATALOG).unwrap(); + for id in [ + "duckstation", + "pcsx2", + "ppsspp", + "azahar", + "melonds", + "xemu", + "flycast", + "shadps4", + ] { + let base = catalog + .iter() + .find(|entry| entry.get("id").and_then(Value::as_str) == Some(id)) + .unwrap(); + let selected = selected_definition_for_target(base, &json!({}), id, "macos", "arm64"); + assert_eq!(selected["managed"], true, "macOS ARM64 {id}"); + assert!(selected["appBundle"].is_string(), "macOS app bundle {id}"); + } + for id in ["duckstation", "ppsspp", "melonds", "mgba", "xemu"] { + let base = catalog + .iter() + .find(|entry| entry.get("id").and_then(Value::as_str) == Some(id)) + .unwrap(); + let selected = selected_definition_for_target(base, &json!({}), id, "linux", "arm64"); + assert_eq!(selected["managed"], true, "Linux ARM64 {id}"); + } + } + + #[test] + fn catalog_patterns_compile_with_the_runtime_regex_engine() { + let catalog: Vec = serde_json::from_str(CATALOG).unwrap(); + for entry in catalog { + let platforms = entry["platforms"].as_object().unwrap(); + for architectures in platforms.values() { + for target in architectures.as_object().unwrap().values() { + for key in ["asset", "exe", "appBundle"] { + if let Some(pattern) = target.get(key).and_then(Value::as_str) { + regex::Regex::new(&format!("(?i){pattern}")).unwrap(); + } + } + } + } + } + } + + #[test] + fn rpcs3_windows_asset_matches_the_msvc_variant() { + let catalog: Vec = serde_json::from_str(CATALOG).unwrap(); + let rpcs3 = catalog + .iter() + .find(|entry| entry.get("id").and_then(Value::as_str) == Some("rpcs3")) + .unwrap(); + let pattern = rpcs3 + .pointer("/platforms/windows/x86_64/asset") + .and_then(Value::as_str) + .unwrap(); + let matcher = regex::Regex::new(&format!("(?i){pattern}")).unwrap(); + assert!(matcher.is_match("rpcs3-v0.0.35_win64.7z")); + assert!(matcher.is_match("rpcs3-v0.0.35_win64_msvc.7z")); + } + + #[test] + fn zip_archives_with_parent_paths_are_rejected() { + let root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("../localTmp") + .join(format!("pyrocade-archive-test-{}", uuid::Uuid::new_v4())); + std::fs::create_dir_all(&root).unwrap(); + let archive_path = root.join("escape.zip"); + let mut archive = zip::ZipWriter::new(std::fs::File::create(&archive_path).unwrap()); + archive + .start_file("../outside", zip::write::SimpleFileOptions::default()) + .unwrap(); + std::io::Write::write_all(&mut archive, b"outside").unwrap(); + archive.finish().unwrap(); + + let result = super::extract_archive(&archive_path, &root.join("unpacked")); + + let _ = std::fs::remove_dir_all(&root); + assert!(result.is_err(), "parent paths must not be extracted"); + } +} + +fn one_wrapping_directory(path: &Path) -> PathBuf { + let Ok(entries) = fs::read_dir(path) else { + return path.to_path_buf(); + }; + let entries: Vec<_> = entries.filter_map(Result::ok).collect(); + if entries.len() == 1 && entries[0].file_type().is_ok_and(|t| t.is_dir()) { + let wrapper = entries[0].path(); + if wrapper.extension().and_then(|ext| ext.to_str()) == Some("app") { + path.to_path_buf() + } else { + wrapper + } + } else { + path.to_path_buf() + } +} + +fn find_program(root: &Path, regex: ®ex::Regex) -> Option { + let mut stack = vec![root.to_path_buf()]; + while let Some(dir) = stack.pop() { + for entry in fs::read_dir(dir).ok()?.filter_map(Result::ok) { + let path = entry.path(); + if entry.file_type().ok()?.is_dir() { + stack.push(path); + } else if path + .file_name() + .and_then(|n| n.to_str()) + .is_some_and(|n| regex.is_match(n)) + { + return Some(path); + } + } + } + None +} + +fn find_app_bundle(root: &Path, regex: ®ex::Regex) -> Option { + let mut stack = vec![root.to_path_buf()]; + while let Some(dir) = stack.pop() { + for entry in fs::read_dir(dir).ok()?.filter_map(Result::ok) { + let path = entry.path(); + if entry.file_type().ok()?.is_dir() { + if path + .file_name() + .and_then(|n| n.to_str()) + .is_some_and(|n| regex.is_match(n)) + && path.join("Contents/MacOS").is_dir() + { + return Some(path); + } + stack.push(path); + } + } + } + None +} + +fn copy_tree(source: &Path, destination: &Path) -> Result<(), String> { + fs::create_dir_all(destination).map_err(|e| e.to_string())?; + for entry in walkdir::WalkDir::new(source).follow_links(false) { + let entry = entry.map_err(|e| e.to_string())?; + let relative = entry + .path() + .strip_prefix(source) + .map_err(|e| e.to_string())?; + if relative.as_os_str().is_empty() { + continue; + } + let target = destination.join(relative); + if entry.file_type().is_dir() { + fs::create_dir_all(&target).map_err(|e| e.to_string())?; + } else if entry.file_type().is_file() { + if let Some(parent) = target.parent() { + fs::create_dir_all(parent).map_err(|e| e.to_string())?; + } + fs::copy(entry.path(), target).map_err(|e| e.to_string())?; + } else if entry.file_type().is_symlink() { + if let Some(parent) = target.parent() { + fs::create_dir_all(parent).map_err(|e| e.to_string())?; + } + let link = fs::read_link(entry.path()).map_err(|e| e.to_string())?; + #[cfg(unix)] + std::os::unix::fs::symlink(link, target).map_err(|e| e.to_string())?; + #[cfg(windows)] + if entry.path().is_dir() { + std::os::windows::fs::symlink_dir(link, target).map_err(|e| e.to_string())?; + } else { + std::os::windows::fs::symlink_file(link, target).map_err(|e| e.to_string())?; + } + } + } + Ok(()) +} + +fn set_executable(path: &Path) -> Result<(), String> { + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let mut permissions = fs::metadata(path).map_err(|e| e.to_string())?.permissions(); + permissions.set_mode(0o755); + fs::set_permissions(path, permissions).map_err(|e| e.to_string())?; + } + Ok(()) +} diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs new file mode 100644 index 0000000..458988c --- /dev/null +++ b/src-tauri/src/lib.rs @@ -0,0 +1,72 @@ +use tauri::Manager; + +mod artwork; +mod backend; +mod config; +mod emulators; +mod storage; + +// Android stays in the app-private data dir; user ROMs are SAF tree URIs. +#[cfg_attr(mobile, tauri::mobile_entry_point)] +pub fn run() { + tauri::Builder::default() + .plugin(tauri_plugin_clipboard_manager::init()) + .plugin(tauri_plugin_dialog::init()) + .plugin(tauri_plugin_opener::init()) + .plugin(tauri_plugin_process::init()) + .setup(|app| { + app.manage(backend::AppState::new(app.handle())?); + Ok(()) + }) + .invoke_handler(tauri::generate_handler![ + backend::get_config, + backend::set_config, + backend::scan_library, + backend::cached_library, + backend::toggle_favorite, + backend::record_play, + backend::update_library_prefs, + backend::get_favorites, + backend::get_recently_played, + backend::set_game_hidden, + backend::set_system_games_hidden, + backend::set_game_metadata, + backend::set_game_emulator, + backend::save_game_order, + backend::list_extra_games, + backend::remove_game, + backend::add_game, + backend::launch_game, + emulators::list_emulators, + emulators::check_emulator_update, + emulators::install_emulator, + emulators::uninstall_emulator, + emulators::open_emulator_folder, + emulators::pick_emulator_executable, + emulators::add_custom_emulator, + emulators::link_android_emulator, + emulators::unlink_android_emulator, + artwork::fetch_art, + artwork::start_artwork_download, + artwork::artwork_status, + artwork::cancel_artwork_download, + artwork::open_artwork_folder, + artwork::import_artwork, + artwork::artwork_sources, + artwork::set_screenscraper, + artwork::find_manuals, + artwork::manual_url, + backend::pick_folder, + backend::open_manual, + backend::app_version, + backend::quit_app, + backend::check_app_update, + backend::install_app_update, + backend::open_release, + backend::feedback_info, + backend::feedback_copy, + backend::feedback_open + ]) + .run(tauri::generate_context!()) + .expect("failed to run PyroCade"); +} diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rs new file mode 100644 index 0000000..a71597f --- /dev/null +++ b/src-tauri/src/main.rs @@ -0,0 +1,5 @@ +#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")] + +fn main() { + pyrocade_lib::run(); +} diff --git a/src-tauri/src/storage.rs b/src-tauri/src/storage.rs new file mode 100644 index 0000000..3291f84 --- /dev/null +++ b/src-tauri/src/storage.rs @@ -0,0 +1,78 @@ +use std::path::PathBuf; + +// StorageRef distinguishes a filesystem path from an Android document-tree URI. +// A content URI is not a path: it cannot be read with std::fs. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum StorageRef { + FilePath(PathBuf), + ContentUri(String), +} + +pub fn is_content_uri(value: &str) -> bool { + value.trim_start().starts_with("content://") +} + +// Parse one trimmed entry from a persisted romDir list. Content URIs keep +// their exact spelling; the URI is persisted, never canonicalised as a path. +pub fn parse_storage_ref(value: &str) -> Option { + let trimmed = value.trim(); + if trimmed.is_empty() { + return None; + } + if is_content_uri(trimmed) { + Some(StorageRef::ContentUri(trimmed.to_owned())) + } else { + Some(StorageRef::FilePath(PathBuf::from(trimmed))) + } +} + +pub fn split_storage_refs(value: &str) -> Vec { + value.split('|').filter_map(parse_storage_ref).collect() +} + +impl StorageRef { + pub fn is_filesystem(&self) -> bool { + matches!(self, StorageRef::FilePath(_)) + } + + pub fn as_path(&self) -> Option<&PathBuf> { + match self { + StorageRef::FilePath(path) => Some(path), + StorageRef::ContentUri(_) => None, + } + } + + pub fn as_string(&self) -> String { + match self { + StorageRef::FilePath(path) => path.to_string_lossy().into_owned(), + StorageRef::ContentUri(uri) => uri.clone(), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn content_uri_is_not_a_filesystem_path() { + assert!(is_content_uri( + "content://com.android.externalstorage.documents/tree/abc" + )); + assert!(!is_content_uri("/storage/emulated/0/roms")); + assert!(!is_content_uri("")); + } + + #[test] + fn split_preserves_document_tree_uris() { + let refs = + split_storage_refs("/roms/a|content://com.android.externalstorage.documents/tree/abc"); + assert_eq!(refs.len(), 2); + assert!(refs[0].is_filesystem()); + assert_eq!(refs[1].as_path(), None); + assert_eq!( + refs[1].as_string(), + "content://com.android.externalstorage.documents/tree/abc" + ); + } +} diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json new file mode 100644 index 0000000..deb0361 --- /dev/null +++ b/src-tauri/tauri.conf.json @@ -0,0 +1,62 @@ +{ + "$schema": "https://schema.tauri.app/config/2", + "productName": "PyroCade", + "version": "0.4.2", + "identifier": "com.pyrodrifter.pyrocade", + "build": { + "frontendDist": "../renderer" + }, + "app": { + "withGlobalTauri": true, + "windows": [ + { + "label": "main", + "title": "PyroCade", + "width": 1600, + "height": 900, + "minWidth": 1100, + "minHeight": 650, + "resizable": true, + "fullscreen": false + } + ], + "security": { + "assetProtocol": { + "enable": true, + "scope": [] + }, + "csp": "default-src 'self' ipc: http://ipc.localhost; img-src 'self' asset: http://asset.localhost data: blob: https: file:; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline'; connect-src ipc: http://ipc.localhost https:; font-src 'self' data:; media-src 'self' asset: http://asset.localhost data: blob:" + } + }, + "bundle": { + "active": true, + "createUpdaterArtifacts": false, + "targets": ["app", "dmg", "appimage", "deb", "rpm", "nsis", "msi"], + "windows": { + "nsis": { + "installerIcon": "../renderer/assets/brand/pyrocade.ico" + } + }, + "android": { + "minSdkVersion": 24 + }, + "category": "Game", + "shortDescription": "3D carousel front end for emulators", + "longDescription": "A glass-styled emulator front end with a 3D library, animated physical media, six browsing layouts and a built-in emulator downloader and updater.", + "icon": [ + "../renderer/assets/brand/pyrocade-icon-512.png", + "../renderer/assets/brand/pyrocade.ico" + ], + "macOS": { + "minimumSystemVersion": "12.0" + }, + "linux": { + "deb": { + "depends": ["libwebkit2gtk-4.1-0", "libgtk-3-0"] + }, + "rpm": { + "depends": ["webkit2gtk4.1", "gtk3"] + } + } + } +}