diff --git a/.github/nightly-signing-policy.json b/.github/nightly-signing-policy.json index 26d6866fa..0eb1d65f8 100644 --- a/.github/nightly-signing-policy.json +++ b/.github/nightly-signing-policy.json @@ -4,10 +4,10 @@ "repository_id": 1408294296, "producer_workflow_id": 429734568, "producer_workflow_path": ".github/workflows/nightly.yml", - "producer_tooling_revision": "be00e5ccd18b68e950c8a08532f2230e7c3d0cba", - "producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba", + "producer_tooling_revision": "main", + "producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@main", "signer_workflow_path": ".github/workflows/nightly-sign.yml", - "signer_tooling_revision": "be00e5ccd18b68e950c8a08532f2230e7c3d0cba", + "signer_tooling_revision": "main", "release_branch": "nightly-signer", "manual_actors": [ "bflatastic", @@ -88,7 +88,9 @@ } }, "max_artifact_bytes": 2147483648, - "automatic_signer_actors": [], + "automatic_signer_actors": [ + "github-actions[bot]" + ], "platforms": { "windows-x86_64": { "unsigned_artifact_name": "nightly-unsigned-windows-x86_64", @@ -100,7 +102,15 @@ "unsigned_artifact_name": "nightly-unsigned-linux-x86_64", "trust": { "fingerprint": "2B76741B414AAD6CD33E631213A005C0B9D7C3ED" - } + }, + "package_formats": [ + "appimage", + "arch", + "deb", + "flatpak", + "oci", + "rpm" + ] }, "macos-aarch64": { "unsigned_artifact_name": "nightly-unsigned-macos-aarch64", diff --git a/.github/workflows/actions.lock b/.github/workflows/actions.lock index 5f9a6d7f1..6bcf04a45 100644 --- a/.github/workflows/actions.lock +++ b/.github/workflows/actions.lock @@ -11,6 +11,7 @@ workflows: '.github/workflows/lockfile.yml': - 'actions/checkout@v7.0.1' - 'step-security/harden-runner@v2.22.4' + '.github/workflows/nightly-dispatch.yml': [] '.github/workflows/nightly-macos.yml': - 'actions/checkout@v7.0.1' - 'step-security/harden-runner@v2.22.4' diff --git a/.github/workflows/nightly-dispatch.yml b/.github/workflows/nightly-dispatch.yml new file mode 100644 index 000000000..cd8166a73 --- /dev/null +++ b/.github/workflows/nightly-dispatch.yml @@ -0,0 +1,72 @@ +name: Dispatch release-ref nightly + +# Transport only, never authorization. No checkout, payload parsing or release environment. +on: + workflow_run: + workflows: [DeckCraft unsigned nightly] + types: [completed] + branches: [main] + +permissions: {} + +jobs: + dispatch: + # Actual context guards only; no checkout, release environment or platform secrets. + if: >- + github.repository == 'storytold/deckcraft' && + github.event_name == 'workflow_run' + runs-on: ubuntu-latest + timeout-minutes: 5 + permissions: + actions: write + steps: + - name: Dispatch only the exact completed producer run and attempt + shell: python + env: + GH_TOKEN: ${{ github.token }} + run: | + import json + import os + import urllib.request + + def require(value, message): + if not value: + raise RuntimeError(message) + + # These filters reduce noise; the protected signer-branch validator repeats admission + # against authenticated API metadata and required attestation/quality evidence. + require(os.environ.get('GITHUB_REPOSITORY') == 'storytold/deckcraft', 'wrong repository') + require(os.environ.get('GITHUB_EVENT_NAME') == 'workflow_run', 'wrong event') + with open(os.environ['GITHUB_EVENT_PATH'], encoding='utf-8') as stream: + event = json.load(stream) + require(event.get('action') == 'completed', 'producer is not complete') + require(event.get('repository', {}).get('full_name') == 'storytold/deckcraft', 'wrong event repository') + producer = event.get('workflow_run', {}) + require(producer.get('head_repository', {}).get('full_name') == 'storytold/deckcraft', 'foreign producer') + require(producer.get('path') == '.github/workflows/nightly.yml', 'wrong producer path') + require(producer.get('head_branch') == 'main', 'wrong producer branch') + require(producer.get('status') == 'completed' and producer.get('conclusion') == 'success', 'producer did not succeed') + # First scheduled attempt only; reviewed manual/re-run authority belongs to release policy. + require(producer.get('event') == 'schedule', 'not an automatic scheduled producer') + run_id, attempt = producer.get('id'), producer.get('run_attempt') + require(type(run_id) is int and run_id > 0, 'invalid producer run id') + require(type(attempt) is int and attempt == 1, 'invalid automatic producer attempt') + body = json.dumps({'ref': 'refs/heads/nightly-signer', 'inputs': { + 'producer_run_id': str(run_id), 'producer_run_attempt': str(attempt) + }}).encode('utf-8') + request = urllib.request.Request( + 'https://api.github.com/repos/storytold/deckcraft/actions/workflows/nightly-sign.yml/dispatches', + data=body, method='POST', headers={ + 'Authorization': 'Bearer ' + os.environ['GH_TOKEN'], + 'Accept': 'application/vnd.github+json', + 'Content-Type': 'application/json', + 'X-GitHub-Api-Version': '2022-11-28', + 'User-Agent': 'deckcraft-nightly-dispatch' + }) + class NoRedirect(urllib.request.HTTPRedirectHandler): + def redirect_request(self, req, fp, code, msg, headers, newurl): + raise RuntimeError('dispatch redirects are forbidden') + # One bounded request, no retry: duplicate transport is not publication authority. + with urllib.request.build_opener(NoRedirect()).open(request, timeout=20) as response: + require(response.status == 204, 'dispatch was not accepted') + print('Dispatched producer run/attempt to the release-ref validator; not a signing result.') diff --git a/.github/workflows/nightly-sign.yml b/.github/workflows/nightly-sign.yml index 39176f6a9..52de7e1a4 100644 --- a/.github/workflows/nightly-sign.yml +++ b/.github/workflows/nightly-sign.yml @@ -34,12 +34,26 @@ jobs: checks: read attestations: write id-token: write - uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba + uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@main with: - tooling-revision: be00e5ccd18b68e950c8a08532f2230e7c3d0cba + tooling-revision: main app-name: deckcraft producer_run_id: ${{ inputs.producer_run_id }} producer_run_attempt: ${{ inputs.producer_run_attempt }} + secrets: + APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }} + APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }} + KEYCHAIN_PASSWORD: ${{ secrets.KEYCHAIN_PASSWORD }} + APPLE_ID: ${{ secrets.APPLE_ID }} + APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }} + APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }} + AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }} + AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }} + AZURE_CLIENT_SECRET: ${{ secrets.AZURE_CLIENT_SECRET }} + AZURE_SIGNING_ENDPOINT: ${{ secrets.AZURE_SIGNING_ENDPOINT }} + AZURE_SIGNING_ACCOUNT: ${{ secrets.AZURE_SIGNING_ACCOUNT }} + AZURE_CERT_PROFILE: ${{ secrets.AZURE_CERT_PROFILE }} + LINUX_SIGNING_KEY: ${{ secrets.LINUX_SIGNING_KEY }} # No secrets: inherit or raw platform values in this caller. Only the isolated native # callee job may bind the release environment and export its keys; that environment must # admit nightly-signer alongside release before the first dispatch. diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml index 12f47f3b4..68d193e7a 100644 --- a/.github/workflows/nightly.yml +++ b/.github/workflows/nightly.yml @@ -1,8 +1,10 @@ name: DeckCraft unsigned nightly -# Enabled for supervised manual runs by the reviewed manual actor only; no schedule yet. -# A later explicit opt-in may add a cadence (and turn on nightly-dispatch.yml with it). +# Runs on the reviewed nightly schedule (01:00 UTC) and for supervised manual runs +# by the reviewed manual actors. Completed scheduled runs are forwarded by nightly-dispatch.yml. on: + schedule: + - cron: '0 1 * * *' workflow_dispatch: permissions: @@ -22,9 +24,9 @@ jobs: actions: read attestations: write id-token: write - uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba + uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@main with: - tooling-revision: be00e5ccd18b68e950c8a08532f2230e7c3d0cba + tooling-revision: main app-name: deckcraft manual-actors: '["bflatastic","dylanmtaylor","echelon","FredApps","skylartaylor"]' craft-fonts-ref: 37827adc41fd165f9a9234ac40f94dbad353aa69 @@ -32,3 +34,4 @@ jobs: # craft-common-actions main commit that merged the exact-analysis admission (#371, after #370, # #369 and #364). platforms: '["windows-x86_64","linux-x86_64","macos-aarch64"]' + linux-package-formats: '["deb","rpm","appimage","flatpak","oci","arch"]' diff --git a/.github/workflows/sonarcloud.yml b/.github/workflows/sonarcloud.yml index 285fd642f..d0d3ce111 100644 --- a/.github/workflows/sonarcloud.yml +++ b/.github/workflows/sonarcloud.yml @@ -10,7 +10,7 @@ permissions: contents: read concurrency: - group: sonarcloud-${{ github.ref }} + group: ${{ github.ref == 'refs/heads/main' && format('sonarcloud-main-{0}', github.sha) || format('sonarcloud-{0}', github.ref) }} # A push to main is the run that publishes coverage; superseded runs there would never finish. cancel-in-progress: ${{ github.ref != 'refs/heads/main' }} diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 638e22eae..2043bd36c 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -20,6 +20,7 @@ artwork. The ribbon and menu icons stay original drawings. | `docs/brand/artcraft-mark-black.svg`, `docs/brand/artcraft-mark-black.png` | ArtCraft Team | ArtCraft brand kit | ArtCraft trademark, `docs/brand/LICENSE-brand.txt` | Mark for light backgrounds | | `docs/brand/LICENSE-brand.txt` | ArtCraft Team | ArtCraft brand kit | — (licence text) | Terms for the ArtCraft marks | | `assets/app-icon/deckcraft-1024.png`, `assets/app-icon/hicolor/*/apps/ai.storyteller.deckcraft.png` | DeckCraft contributors | rendered by DeckCraft from `assets/app-icon/icon-source.deckcraft` (shapes only) | MIT OR Apache-2.0 | Placeholder app icon (presentation board) until the mascot icon is drawn | +| `assets/app-icon/deckcraft-mark.svg` | DeckCraft contributors | Original drawing of the app icon’s card and play triangle | MIT OR Apache-2.0 | About and the Backstage mark | | `packaging/macos/dmg/background.svg` | @XusBadia | DeckCraft macOS DMG window background, original work for this repository (2026-10-08), derived from the DeckCraft app icon `assets/app-icon/deckcraft-1024.png` (referenced via ``, not copied); text is outlined Inter / JetBrains Mono glyph paths | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | Finder window of the macOS DMG; `packaging/macos/dmg/generate.py` renders it to `background.tiff` | | `packaging/macos/dmg/background.tiff` | @XusBadia | Rendered from `packaging/macos/dmg/background.svg` by `packaging/macos/dmg/generate.py` | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | 1x + 2x HiDPI TIFF for the macOS DMG window; includes the app icon (see its row) and LittleCMS's built-in sRGB profile ("No copyright, use freely") | | `assets/app-icon/deckcraft.icns`, `assets/app-icon/deckcraft.ico` | DeckCraft contributors | generated from the PNGs above by `packaging/icons.sh` (sips/iconutil, `cargo xtask ico`) | MIT OR Apache-2.0 | macOS and Windows app icons | diff --git a/Cargo.lock b/Cargo.lock index ae86b2171..48897cd8d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -156,6 +156,21 @@ dependencies = [ "equator", ] +[[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 = "allocator-api2" version = "0.2.21" @@ -184,6 +199,12 @@ dependencies = [ "pkg-config", ] +[[package]] +name = "ambient-authority" +version = "0.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e9d4ee0d472d1cd2e28c97dfa124b3d8d992e10eb0a035f33f5d12e3a177ba3b" + [[package]] name = "android-activity" version = "0.6.1" @@ -534,6 +555,30 @@ dependencies = [ "v_frame", ] +[[package]] +name = "aws-lc-rs" +version = "1.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "048006790404103c488e6c5616b3e7e702a71292aadda08e8f7698a9e0d2eb53" +dependencies = [ + "aws-lc-sys", + "untrusted 0.7.1", + "zeroize", +] + +[[package]] +name = "aws-lc-sys" +version = "0.47.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8bfbe32ac36b3c428696ce315464181bc4029d689fd58e3f2a4e58c252242f52" +dependencies = [ + "cc", + "cmake", + "dunce", + "fs_extra", + "pkg-config", +] + [[package]] name = "base64" version = "0.22.1" @@ -546,6 +591,12 @@ version = "0.23.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" +[[package]] +name = "base64ct" +version = "1.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" + [[package]] name = "bindgen" version = "0.72.1" @@ -601,12 +652,6 @@ dependencies = [ "no_std_io2", ] -[[package]] -name = "block" -version = "0.1.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d8c1fef690941d3e7788d328517591fecc684c084084702d6ff1641e993699a" - [[package]] name = "block-buffer" version = "0.10.4" @@ -647,6 +692,27 @@ dependencies = [ "piper", ] +[[package]] +name = "brotli" +version = "9.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9071f285ed78f04f37d675abaaef5de7689e2f30a216c8dc6795465d81910a13" +dependencies = [ + "alloc-no-stdlib", + "alloc-stdlib", + "brotli-decompressor", +] + +[[package]] +name = "brotli-decompressor" +version = "6.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "50986a054f56ca3e15382f3c09abee2bf494c00311b238daae118a06bc1c15f1" +dependencies = [ + "alloc-no-stdlib", + "alloc-stdlib", +] + [[package]] name = "built" version = "0.8.1" @@ -751,6 +817,24 @@ dependencies = [ "wayland-client", ] +[[package]] +name = "cap-primitives" +version = "4.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b5f74729fd2f44701d1a8eb47e906cdb3ccd9ec0f02baad85a744b791940b18" +dependencies = [ + "ambient-authority", + "fs-set-times", + "io-extras", + "io-lifetimes 3.0.1", + "ipnet", + "maybe-owned", + "rustix 1.1.6", + "rustix-linux-procfs", + "windows-sys 0.61.2", + "winx", +] + [[package]] name = "cast" version = "0.3.0" @@ -835,6 +919,7 @@ dependencies = [ "iana-time-zone", "js-sys", "num-traits", + "serde", "wasm-bindgen", "windows-link", ] @@ -859,6 +944,39 @@ dependencies = [ "error-code", ] +[[package]] +name = "cmake" +version = "0.1.58" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0f78a02292a74a88ac736019ab962ece0bc380e3f977bf72e376c5d78ff0678" +dependencies = [ + "cc", +] + +[[package]] +name = "cmpv2" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "961b955a666e25ee5a1091d219128d6e6401e3dab84efb1a2bf6b4035d797b39" +dependencies = [ + "crmf", + "der", + "spki", + "x509-cert", +] + +[[package]] +name = "cms" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b77c319abfd5219629c45c34c89ba945ed3c5e49fcde9d16b6c3885f118a730" +dependencies = [ + "const-oid", + "der", + "spki", + "x509-cert", +] + [[package]] name = "cobs" version = "0.3.0" @@ -923,6 +1041,12 @@ dependencies = [ "crossbeam-utils", ] +[[package]] +name = "const-oid" +version = "0.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8" + [[package]] name = "cookie-factory" version = "0.3.3" @@ -979,19 +1103,6 @@ dependencies = [ "libc", ] -[[package]] -name = "core-graphics2" -version = "0.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5b65858d95344d2711161cd92196732f67d6c5fea238cf12f994584828731a5c" -dependencies = [ - "bitflags 2.13.2", - "block", - "cfg-if", - "core-foundation 0.10.1", - "libc", -] - [[package]] name = "core_detect" version = "1.0.0" @@ -1065,20 +1176,74 @@ dependencies = [ "libc", ] +[[package]] +name = "craft" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=82ae5969349f2f70175011e01983eea32e4ae905#82ae5969349f2f70175011e01983eea32e4ae905" +dependencies = [ + "craft-automation", + "craft-behavior", + "craft-browse", + "craft-color-ui", + "craft-dialogs", + "craft-draw", + "craft-drawingml", + "craft-font-catalog", + "craft-font-manager", + "craft-gpu", + "craft-host", + "craft-i18n", + "craft-imaging", + "craft-keymap", + "craft-layers", + "craft-menu", + "craft-pages", + "craft-platform", + "craft-print", + "craft-quit", + "craft-review", + "craft-settings", + "craft-table", + "craft-text", + "craft-theme", + "craft-theme-editor", + "craft-theme-store", + "craft-timeline", + "craft-ui", + "craft-update", + "craft-web-api", + "craft-web-host", + "craft-window", + "egui", + "toml", +] + +[[package]] +name = "craft-ai-agents" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-ai-integrations?rev=d94a3593adcff504eaaad9e5aee4c84fd2f07a72#d94a3593adcff504eaaad9e5aee4c84fd2f07a72" +dependencies = [ + "dirs", + "serde", + "serde_json", +] + [[package]] name = "craft-appkit" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" +source = "git+https://github.com/storytold/craft-libs?rev=82ae5969349f2f70175011e01983eea32e4ae905#82ae5969349f2f70175011e01983eea32e4ae905" dependencies = [ "block2 0.6.2", + "objc2 0.6.5", "objc2-app-kit 0.3.2", + "objc2-core-graphics", "objc2-foundation 0.3.2", ] [[package]] name = "craft-atomic" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" +source = "git+https://github.com/storytold/craft-libs?rev=82ae5969349f2f70175011e01983eea32e4ae905#82ae5969349f2f70175011e01983eea32e4ae905" dependencies = [ "rustix 1.1.6", ] @@ -1086,16 +1251,41 @@ dependencies = [ [[package]] name = "craft-audio" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" +source = "git+https://github.com/storytold/craft-libs?rev=82ae5969349f2f70175011e01983eea32e4ae905#82ae5969349f2f70175011e01983eea32e4ae905" dependencies = [ "craft-media", "thiserror 2.0.21", ] +[[package]] +name = "craft-automation" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=82ae5969349f2f70175011e01983eea32e4ae905#82ae5969349f2f70175011e01983eea32e4ae905" +dependencies = [ + "base64 0.23.1", + "craft-behavior", + "craft-control", + "craft-host", + "craft-keymap", + "craft-platform", + "craft-theme", + "craft-ui", + "egui", + "getrandom 0.3.4", + "hmac", + "log", + "png 0.17.16", + "serde", + "serde_json", + "sha2", + "thiserror 2.0.21", + "web-time", +] + [[package]] name = "craft-behavior" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" +source = "git+https://github.com/storytold/craft-libs?rev=82ae5969349f2f70175011e01983eea32e4ae905#82ae5969349f2f70175011e01983eea32e4ae905" dependencies = [ "accesskit", "bitflags 2.13.2", @@ -1110,28 +1300,102 @@ dependencies = [ "smallvec", ] +[[package]] +name = "craft-browse" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=82ae5969349f2f70175011e01983eea32e4ae905#82ae5969349f2f70175011e01983eea32e4ae905" +dependencies = [ + "craft-behavior", + "craft-docpath", + "craft-host", + "craft-i18n", + "craft-platform", + "craft-settings", + "craft-theme", + "craft-ui", + "egui", + "kurbo", + "serde", +] + [[package]] name = "craft-cfb" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" +source = "git+https://github.com/storytold/craft-libs?rev=82ae5969349f2f70175011e01983eea32e4ae905#82ae5969349f2f70175011e01983eea32e4ae905" [[package]] name = "craft-cloud-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" +source = "git+https://github.com/storytold/craft-libs?rev=82ae5969349f2f70175011e01983eea32e4ae905#82ae5969349f2f70175011e01983eea32e4ae905" dependencies = [ "egui", ] +[[package]] +name = "craft-cms" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=82ae5969349f2f70175011e01983eea32e4ae905#82ae5969349f2f70175011e01983eea32e4ae905" +dependencies = [ + "md-5", + "rayon", +] + [[package]] name = "craft-codepage" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" +source = "git+https://github.com/storytold/craft-libs?rev=82ae5969349f2f70175011e01983eea32e4ae905#82ae5969349f2f70175011e01983eea32e4ae905" + +[[package]] +name = "craft-color-ui" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=82ae5969349f2f70175011e01983eea32e4ae905#82ae5969349f2f70175011e01983eea32e4ae905" +dependencies = [ + "craft-behavior", + "craft-cms", + "craft-drawingml", + "craft-host", + "craft-i18n", + "craft-keymap", + "craft-platform", + "craft-settings", + "craft-theme", + "craft-ui", + "craft-window", + "egui", + "serde", + "serde_json", +] + +[[package]] +name = "craft-control" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=82ae5969349f2f70175011e01983eea32e4ae905#82ae5969349f2f70175011e01983eea32e4ae905" +dependencies = [ + "craft-ai-agents", + "craft-atomic", + "craft-control-protocol", + "craft-flags", + "craft-platform", + "dirs", + "log", + "serde", + "serde_json", +] + +[[package]] +name = "craft-control-protocol" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=82ae5969349f2f70175011e01983eea32e4ae905#82ae5969349f2f70175011e01983eea32e4ae905" +dependencies = [ + "getrandom 0.3.4", + "serde_json", + "subtle", +] [[package]] name = "craft-deckcraft-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" +source = "git+https://github.com/storytold/craft-libs?rev=82ae5969349f2f70175011e01983eea32e4ae905#82ae5969349f2f70175011e01983eea32e4ae905" dependencies = [ "craft-zip", "serde", @@ -1140,18 +1404,63 @@ dependencies = [ "zip 9.1.0", ] +[[package]] +name = "craft-dialogs" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=82ae5969349f2f70175011e01983eea32e4ae905#82ae5969349f2f70175011e01983eea32e4ae905" +dependencies = [ + "block2 0.6.2", + "craft-appkit", + "craft-atomic", + "craft-behavior", + "craft-browse", + "craft-host", + "craft-i18n", + "craft-platform", + "craft-ui", + "egui", + "futures-lite", + "log", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "objc2-foundation 0.3.2", + "raw-window-handle", + "rfd", + "serde_json", + "zbus", +] + [[package]] name = "craft-docpath" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" +source = "git+https://github.com/storytold/craft-libs?rev=82ae5969349f2f70175011e01983eea32e4ae905#82ae5969349f2f70175011e01983eea32e4ae905" dependencies = [ "serde", ] +[[package]] +name = "craft-draw" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=82ae5969349f2f70175011e01983eea32e4ae905#82ae5969349f2f70175011e01983eea32e4ae905" +dependencies = [ + "craft-behavior", + "craft-color-ui", + "craft-host", + "craft-i18n", + "craft-keymap", + "craft-settings", + "craft-theme", + "craft-ui", + "egui", + "kurbo", + "serde", + "serde_json", +] + [[package]] name = "craft-drawingml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" +source = "git+https://github.com/storytold/craft-libs?rev=82ae5969349f2f70175011e01983eea32e4ae905#82ae5969349f2f70175011e01983eea32e4ae905" dependencies = [ "chrono", "craft-xml", @@ -1160,11 +1469,22 @@ dependencies = [ "serde", ] +[[package]] +name = "craft-flags" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=82ae5969349f2f70175011e01983eea32e4ae905#82ae5969349f2f70175011e01983eea32e4ae905" +dependencies = [ + "craft-atomic", + "dirs", + "toml_edit", +] + [[package]] name = "craft-font-catalog" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" +source = "git+https://github.com/storytold/craft-libs?rev=82ae5969349f2f70175011e01983eea32e4ae905#82ae5969349f2f70175011e01983eea32e4ae905" dependencies = [ + "fontique", "harfrust 0.13.3", "kurbo", "skrifa 0.47.0", @@ -1174,15 +1494,79 @@ dependencies = [ "windows-registry", ] +[[package]] +name = "craft-font-manager" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=82ae5969349f2f70175011e01983eea32e4ae905#82ae5969349f2f70175011e01983eea32e4ae905" +dependencies = [ + "craft-behavior", + "craft-font-catalog", + "craft-font-store", + "craft-fonts-build", + "craft-host", + "craft-i18n", + "craft-theme", + "craft-ui", + "egui", + "epaint_default_fonts", + "log", + "serde", + "skrifa 0.47.0", +] + +[[package]] +name = "craft-font-os-windows" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=82ae5969349f2f70175011e01983eea32e4ae905#82ae5969349f2f70175011e01983eea32e4ae905" +dependencies = [ + "windows-registry", + "windows-sys 0.61.2", +] + +[[package]] +name = "craft-font-store" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=82ae5969349f2f70175011e01983eea32e4ae905#82ae5969349f2f70175011e01983eea32e4ae905" +dependencies = [ + "cap-primitives", + "craft-atomic", + "craft-font-catalog", + "craft-font-os-windows", + "flate2", + "log", + "ruzstd", + "serde", + "serde_json", + "sha2", + "skrifa 0.47.0", + "tar", + "thiserror 2.0.21", + "toml", + "ureq", + "wuff", +] + [[package]] name = "craft-fonts-build" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" +source = "git+https://github.com/storytold/craft-libs?rev=82ae5969349f2f70175011e01983eea32e4ae905#82ae5969349f2f70175011e01983eea32e4ae905" + +[[package]] +name = "craft-gpu" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=82ae5969349f2f70175011e01983eea32e4ae905#82ae5969349f2f70175011e01983eea32e4ae905" +dependencies = [ + "egui-wgpu", + "log", + "pollster 1.0.1", + "serde", + "thiserror 2.0.21", +] [[package]] name = "craft-host" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" +source = "git+https://github.com/storytold/craft-libs?rev=82ae5969349f2f70175011e01983eea32e4ae905#82ae5969349f2f70175011e01983eea32e4ae905" dependencies = [ "bitflags 2.13.2", "craft-i18n", @@ -1195,8 +1579,10 @@ dependencies = [ [[package]] name = "craft-i18n" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" +source = "git+https://github.com/storytold/craft-libs?rev=82ae5969349f2f70175011e01983eea32e4ae905#82ae5969349f2f70175011e01983eea32e4ae905" dependencies = [ + "brotli", + "brotli-decompressor", "chrono", "fixed_decimal", "icu_calendar", @@ -1220,10 +1606,28 @@ dependencies = [ "writeable", ] +[[package]] +name = "craft-imaging" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=82ae5969349f2f70175011e01983eea32e4ae905#82ae5969349f2f70175011e01983eea32e4ae905" +dependencies = [ + "craft-behavior", + "craft-color-ui", + "craft-host", + "craft-i18n", + "craft-keymap", + "craft-theme", + "craft-ui", + "egui", + "kurbo", + "serde", + "serde_json", +] + [[package]] name = "craft-keymap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" +source = "git+https://github.com/storytold/craft-libs?rev=82ae5969349f2f70175011e01983eea32e4ae905#82ae5969349f2f70175011e01983eea32e4ae905" dependencies = [ "craft-host", "craft-i18n", @@ -1235,10 +1639,24 @@ dependencies = [ "serde_json", ] +[[package]] +name = "craft-layers" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=82ae5969349f2f70175011e01983eea32e4ae905#82ae5969349f2f70175011e01983eea32e4ae905" +dependencies = [ + "craft-behavior", + "craft-i18n", + "craft-keymap", + "craft-theme", + "craft-ui", + "egui", + "serde", +] + [[package]] name = "craft-mcp-server" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" +source = "git+https://github.com/storytold/craft-libs?rev=82ae5969349f2f70175011e01983eea32e4ae905#82ae5969349f2f70175011e01983eea32e4ae905" dependencies = [ "serde_json", ] @@ -1246,15 +1664,33 @@ dependencies = [ [[package]] name = "craft-media" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" +source = "git+https://github.com/storytold/craft-libs?rev=82ae5969349f2f70175011e01983eea32e4ae905#82ae5969349f2f70175011e01983eea32e4ae905" dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-menu" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=82ae5969349f2f70175011e01983eea32e4ae905#82ae5969349f2f70175011e01983eea32e4ae905" +dependencies = [ + "craft-behavior", + "craft-host", + "craft-i18n", + "craft-keymap", + "craft-quit", + "craft-theme", + "craft-ui", + "craft-window", + "egui", + "serde", + "serde_json", +] + [[package]] name = "craft-metafile" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" +source = "git+https://github.com/storytold/craft-libs?rev=82ae5969349f2f70175011e01983eea32e4ae905#82ae5969349f2f70175011e01983eea32e4ae905" dependencies = [ "encoding_rs", "image", @@ -1265,17 +1701,26 @@ dependencies = [ [[package]] name = "craft-mime" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" +source = "git+https://github.com/storytold/craft-libs?rev=82ae5969349f2f70175011e01983eea32e4ae905#82ae5969349f2f70175011e01983eea32e4ae905" dependencies = [ "chrono", "craft-codepage", "encoding_rs", ] +[[package]] +name = "craft-nightly" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=82ae5969349f2f70175011e01983eea32e4ae905#82ae5969349f2f70175011e01983eea32e4ae905" +dependencies = [ + "uds_windows", + "winsafe", +] + [[package]] name = "craft-opc" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" +source = "git+https://github.com/storytold/craft-libs?rev=82ae5969349f2f70175011e01983eea32e4ae905#82ae5969349f2f70175011e01983eea32e4ae905" dependencies = [ "craft-xml", "craft-zip", @@ -1283,10 +1728,26 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-pages" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=82ae5969349f2f70175011e01983eea32e4ae905#82ae5969349f2f70175011e01983eea32e4ae905" +dependencies = [ + "craft-behavior", + "craft-keymap", + "craft-text", + "craft-theme", + "craft-ui", + "egui", + "kurbo", + "serde", + "serde_json", +] + [[package]] name = "craft-pdf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" +source = "git+https://github.com/storytold/craft-libs?rev=82ae5969349f2f70175011e01983eea32e4ae905#82ae5969349f2f70175011e01983eea32e4ae905" dependencies = [ "krilla", "serde", @@ -1296,21 +1757,27 @@ dependencies = [ [[package]] name = "craft-platform" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" +source = "git+https://github.com/storytold/craft-libs?rev=82ae5969349f2f70175011e01983eea32e4ae905#82ae5969349f2f70175011e01983eea32e4ae905" dependencies = [ + "arboard", "async-channel", "async-io", "async-process", - "core-graphics2", + "clipboard-win", + "craft-appkit", "craft-atomic", "craft-docpath", "craft-host", "craft-i18n", "craft-theme", + "fmv-macos-events", "futures-lite", "js-sys", "log", "objc2-app-kit 0.3.2", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-foundation 0.3.2", "rfd", "serde", "serde_json", @@ -1319,6 +1786,7 @@ dependencies = [ "web-sys", "web-time", "windows 0.62.2", + "wl-clipboard-rs", "x11rb", "xcap", "zbus", @@ -1327,7 +1795,7 @@ dependencies = [ [[package]] name = "craft-pptx" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" +source = "git+https://github.com/storytold/craft-libs?rev=82ae5969349f2f70175011e01983eea32e4ae905#82ae5969349f2f70175011e01983eea32e4ae905" dependencies = [ "craft-drawingml", "craft-opc", @@ -1339,22 +1807,66 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-print" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=82ae5969349f2f70175011e01983eea32e4ae905#82ae5969349f2f70175011e01983eea32e4ae905" +dependencies = [ + "craft-behavior", + "craft-host", + "craft-theme", + "craft-ui", + "craft-winprint-gdi", + "egui", + "js-sys", + "log", + "miniz_oxide 0.9.1", + "roxmltree", + "serde", + "serde_json", + "tempfile", + "wasm-bindgen", + "web-sys", + "winprint", + "winsafe", +] + [[package]] name = "craft-quit" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" +source = "git+https://github.com/storytold/craft-libs?rev=82ae5969349f2f70175011e01983eea32e4ae905#82ae5969349f2f70175011e01983eea32e4ae905" dependencies = [ "dispatch2", + "egui", "objc2 0.6.5", "objc2-app-kit 0.3.2", "wasm-bindgen", "web-sys", ] +[[package]] +name = "craft-review" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=82ae5969349f2f70175011e01983eea32e4ae905#82ae5969349f2f70175011e01983eea32e4ae905" +dependencies = [ + "base64 0.23.1", + "craft-behavior", + "craft-host", + "craft-i18n", + "craft-keymap", + "craft-pages", + "craft-theme", + "craft-ui", + "egui", + "image", + "kurbo", + "serde", +] + [[package]] name = "craft-rtf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" +source = "git+https://github.com/storytold/craft-libs?rev=82ae5969349f2f70175011e01983eea32e4ae905#82ae5969349f2f70175011e01983eea32e4ae905" dependencies = [ "craft-codepage", "encoding_rs", @@ -1363,7 +1875,7 @@ dependencies = [ [[package]] name = "craft-settings" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" +source = "git+https://github.com/storytold/craft-libs?rev=82ae5969349f2f70175011e01983eea32e4ae905#82ae5969349f2f70175011e01983eea32e4ae905" dependencies = [ "craft-atomic", "craft-host", @@ -1380,7 +1892,7 @@ dependencies = [ [[package]] name = "craft-svg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" +source = "git+https://github.com/storytold/craft-libs?rev=82ae5969349f2f70175011e01983eea32e4ae905#82ae5969349f2f70175011e01983eea32e4ae905" dependencies = [ "craft-xml", "flate2", @@ -1394,10 +1906,46 @@ dependencies = [ "vectorcraft-pathops", ] +[[package]] +name = "craft-table" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=82ae5969349f2f70175011e01983eea32e4ae905#82ae5969349f2f70175011e01983eea32e4ae905" +dependencies = [ + "craft-behavior", + "craft-keymap", + "craft-theme", + "craft-ui", + "egui", +] + +[[package]] +name = "craft-text" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=82ae5969349f2f70175011e01983eea32e4ae905#82ae5969349f2f70175011e01983eea32e4ae905" +dependencies = [ + "craft-behavior", + "craft-host", + "craft-keymap", + "craft-theme", + "craft-ui", + "egui", + "hypher", + "miniz_oxide 0.8.9", + "regex", + "regex-syntax", + "serde", + "serde_json", + "unicode-bidi", + "unicode-bidi-mirroring", + "unicode-general-category", + "unicode-linebreak", + "unicode-segmentation", +] + [[package]] name = "craft-theme" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" +source = "git+https://github.com/storytold/craft-libs?rev=82ae5969349f2f70175011e01983eea32e4ae905#82ae5969349f2f70175011e01983eea32e4ae905" dependencies = [ "bitflags 2.13.2", "craft-tracked", @@ -1409,15 +1957,65 @@ dependencies = [ "smallvec", ] +[[package]] +name = "craft-theme-editor" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=82ae5969349f2f70175011e01983eea32e4ae905#82ae5969349f2f70175011e01983eea32e4ae905" +dependencies = [ + "craft-behavior", + "craft-theme", + "craft-ui", + "egui", +] + +[[package]] +name = "craft-theme-store" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=82ae5969349f2f70175011e01983eea32e4ae905#82ae5969349f2f70175011e01983eea32e4ae905" +dependencies = [ + "craft-atomic", + "craft-behavior", + "craft-theme", + "craft-ui", + "dirs", + "egui", + "serde", + "serde_json", +] + +[[package]] +name = "craft-time" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=82ae5969349f2f70175011e01983eea32e4ae905#82ae5969349f2f70175011e01983eea32e4ae905" +dependencies = [ + "serde", + "thiserror 2.0.21", +] + +[[package]] +name = "craft-timeline" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=82ae5969349f2f70175011e01983eea32e4ae905#82ae5969349f2f70175011e01983eea32e4ae905" +dependencies = [ + "craft-behavior", + "craft-keymap", + "craft-theme", + "craft-time", + "craft-ui", + "egui", + "serde", + "web-time", +] + [[package]] name = "craft-tracked" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" +source = "git+https://github.com/storytold/craft-libs?rev=82ae5969349f2f70175011e01983eea32e4ae905#82ae5969349f2f70175011e01983eea32e4ae905" [[package]] name = "craft-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" +source = "git+https://github.com/storytold/craft-libs?rev=82ae5969349f2f70175011e01983eea32e4ae905#82ae5969349f2f70175011e01983eea32e4ae905" dependencies = [ "craft-cloud-ui", "craft-ui-canvas", @@ -1431,9 +2029,10 @@ dependencies = [ [[package]] name = "craft-ui-canvas" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" +source = "git+https://github.com/storytold/craft-libs?rev=82ae5969349f2f70175011e01983eea32e4ae905#82ae5969349f2f70175011e01983eea32e4ae905" dependencies = [ "craft-behavior", + "craft-font-catalog", "craft-i18n", "craft-keymap", "craft-theme", @@ -1447,7 +2046,7 @@ dependencies = [ [[package]] name = "craft-ui-contract" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" +source = "git+https://github.com/storytold/craft-libs?rev=82ae5969349f2f70175011e01983eea32e4ae905#82ae5969349f2f70175011e01983eea32e4ae905" dependencies = [ "accesskit", "craft-behavior", @@ -1485,7 +2084,7 @@ dependencies = [ [[package]] name = "craft-ui-macros" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" +source = "git+https://github.com/storytold/craft-libs?rev=82ae5969349f2f70175011e01983eea32e4ae905#82ae5969349f2f70175011e01983eea32e4ae905" dependencies = [ "proc-macro-crate", "proc-macro2", @@ -1496,7 +2095,7 @@ dependencies = [ [[package]] name = "craft-ui-panels" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" +source = "git+https://github.com/storytold/craft-libs?rev=82ae5969349f2f70175011e01983eea32e4ae905#82ae5969349f2f70175011e01983eea32e4ae905" dependencies = [ "craft-behavior", "craft-host", @@ -1514,7 +2113,7 @@ dependencies = [ [[package]] name = "craft-ui-patterns" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" +source = "git+https://github.com/storytold/craft-libs?rev=82ae5969349f2f70175011e01983eea32e4ae905#82ae5969349f2f70175011e01983eea32e4ae905" dependencies = [ "craft-behavior", "craft-host", @@ -1535,7 +2134,7 @@ dependencies = [ [[package]] name = "craft-ui-shell" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" +source = "git+https://github.com/storytold/craft-libs?rev=82ae5969349f2f70175011e01983eea32e4ae905#82ae5969349f2f70175011e01983eea32e4ae905" dependencies = [ "craft-behavior", "craft-host", @@ -1546,6 +2145,7 @@ dependencies = [ "craft-ui-macros", "craft-ui-panels", "craft-window", + "eframe", "egui", "raw-window-handle", "serde", @@ -1555,7 +2155,7 @@ dependencies = [ [[package]] name = "craft-ui-widgets" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" +source = "git+https://github.com/storytold/craft-libs?rev=82ae5969349f2f70175011e01983eea32e4ae905#82ae5969349f2f70175011e01983eea32e4ae905" dependencies = [ "craft-behavior", "craft-host", @@ -1574,13 +2174,15 @@ dependencies = [ [[package]] name = "craft-update" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" +source = "git+https://github.com/storytold/craft-libs?rev=82ae5969349f2f70175011e01983eea32e4ae905#82ae5969349f2f70175011e01983eea32e4ae905" dependencies = [ + "base64 0.22.1", "chrono", "craft-host", "craft-theme", "craft-ui", "dunce", + "ed25519-dalek", "egui", "flate2", "image", @@ -1593,6 +2195,7 @@ dependencies = [ "sha2", "tar", "tempfile", + "toml", "ureq", "verifysign", "winreg", @@ -1603,7 +2206,7 @@ dependencies = [ [[package]] name = "craft-video" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" +source = "git+https://github.com/storytold/craft-libs?rev=82ae5969349f2f70175011e01983eea32e4ae905#82ae5969349f2f70175011e01983eea32e4ae905" dependencies = [ "craft-media", "rav1e", @@ -1614,7 +2217,7 @@ dependencies = [ [[package]] name = "craft-web-api" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" +source = "git+https://github.com/storytold/craft-libs?rev=82ae5969349f2f70175011e01983eea32e4ae905#82ae5969349f2f70175011e01983eea32e4ae905" dependencies = [ "js-sys", "serde_json", @@ -1625,7 +2228,7 @@ dependencies = [ [[package]] name = "craft-web-host" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" +source = "git+https://github.com/storytold/craft-libs?rev=82ae5969349f2f70175011e01983eea32e4ae905#82ae5969349f2f70175011e01983eea32e4ae905" dependencies = [ "craft-host", "craft-platform", @@ -1637,7 +2240,7 @@ dependencies = [ [[package]] name = "craft-win32" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" +source = "git+https://github.com/storytold/craft-libs?rev=82ae5969349f2f70175011e01983eea32e4ae905#82ae5969349f2f70175011e01983eea32e4ae905" dependencies = [ "winsafe", ] @@ -1645,7 +2248,7 @@ dependencies = [ [[package]] name = "craft-window" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" +source = "git+https://github.com/storytold/craft-libs?rev=82ae5969349f2f70175011e01983eea32e4ae905#82ae5969349f2f70175011e01983eea32e4ae905" dependencies = [ "craft-appkit", "craft-atomic", @@ -1666,10 +2269,18 @@ dependencies = [ "x11rb", ] +[[package]] +name = "craft-winprint-gdi" +version = "0.1.0" +source = "git+https://github.com/storytold/winprint.rs?rev=64e7afd4d1483512385012c340ecaaaf0f3beb7f#64e7afd4d1483512385012c340ecaaaf0f3beb7f" +dependencies = [ + "windows-sys 0.61.2", +] + [[package]] name = "craft-xml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" +source = "git+https://github.com/storytold/craft-libs?rev=82ae5969349f2f70175011e01983eea32e4ae905#82ae5969349f2f70175011e01983eea32e4ae905" dependencies = [ "quick-xml 0.41.0", "serde", @@ -1679,7 +2290,7 @@ dependencies = [ [[package]] name = "craft-zip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" +source = "git+https://github.com/storytold/craft-libs?rev=82ae5969349f2f70175011e01983eea32e4ae905#82ae5969349f2f70175011e01983eea32e4ae905" dependencies = [ "flate2", "thiserror 2.0.21", @@ -1695,6 +2306,18 @@ dependencies = [ "cfg-if", ] +[[package]] +name = "crmf" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "36fe21b96d5b87f5de4b5b7202ec41c00110ac817ce6728fe75fb2fe5962ed92" +dependencies = [ + "cms", + "der", + "spki", + "x509-cert", +] + [[package]] name = "crossbeam-channel" version = "0.5.17" @@ -1751,6 +2374,33 @@ version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f27ae1dd37df86211c42e150270f82743308803d90a6f6e6651cd730d5e1732f" +[[package]] +name = "curve25519-dalek" +version = "4.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97fb8b7c4503de7d6ae7b42ab72a5a59857b4c937ec27a3d4539dba95b5ab2be" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "curve25519-dalek-derive", + "digest", + "fiat-crypto", + "rustc_version", + "subtle", + "zeroize", +] + +[[package]] +name = "curve25519-dalek-derive" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f46882e17999c6cc590af592290432be3bce0428cb0d5f8b6715e4dc7b383eb3" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "dasp_sample" version = "0.11.0" @@ -1765,18 +2415,18 @@ checksum = "be1e0bca6c3637f992fc1cc7cbc52a78c1ef6db076dbf1059c4323d6a2048376" [[package]] name = "deckcraft" -version = "0.19.0" +version = "0.20.0" dependencies = [ - "arboard", "chrono", "cpal", + "craft", + "craft-nightly", "craft-update", "deckcraft-engine", "deckcraft-media", "deckcraft-ui-egui", "eframe", "egui", - "fmv-macos-events", "image", "log", "rfd", @@ -1789,7 +2439,7 @@ dependencies = [ [[package]] name = "deckcraft-anim" -version = "0.19.0" +version = "0.20.0" dependencies = [ "deckcraft-geom", "deckcraft-model", @@ -1798,8 +2448,9 @@ dependencies = [ [[package]] name = "deckcraft-cli" -version = "0.19.0" +version = "0.20.0" dependencies = [ + "craft", "deckcraft-engine", "deckcraft-mcp", "serde_json", @@ -1808,14 +2459,14 @@ dependencies = [ [[package]] name = "deckcraft-color" -version = "0.19.0" +version = "0.20.0" dependencies = [ "craft-drawingml", ] [[package]] name = "deckcraft-engine" -version = "0.19.0" +version = "0.20.0" dependencies = [ "chrono", "craft-mime", @@ -1843,8 +2494,9 @@ dependencies = [ [[package]] name = "deckcraft-fonts" -version = "0.19.0" +version = "0.20.0" dependencies = [ + "craft", "epaint_default_fonts", "harfrust 0.13.3", "kurbo", @@ -1855,7 +2507,7 @@ dependencies = [ [[package]] name = "deckcraft-format" -version = "0.19.0" +version = "0.20.0" dependencies = [ "craft-deckcraft-format", "craft-rtf", @@ -1866,7 +2518,7 @@ dependencies = [ [[package]] name = "deckcraft-geom" -version = "0.19.0" +version = "0.20.0" dependencies = [ "craft-drawingml", "kurbo", @@ -1875,8 +2527,9 @@ dependencies = [ [[package]] name = "deckcraft-mcp" -version = "0.19.0" +version = "0.20.0" dependencies = [ + "craft", "craft-mcp-server", "deckcraft-engine", "deckcraft-render", @@ -1886,7 +2539,7 @@ dependencies = [ [[package]] name = "deckcraft-media" -version = "0.19.0" +version = "0.20.0" dependencies = [ "craft-audio", "craft-media", @@ -1899,7 +2552,7 @@ dependencies = [ [[package]] name = "deckcraft-model" -version = "0.19.0" +version = "0.20.0" dependencies = [ "craft-drawingml", "deckcraft-color", @@ -1912,7 +2565,7 @@ dependencies = [ [[package]] name = "deckcraft-pdf" -version = "0.19.0" +version = "0.20.0" dependencies = [ "craft-pdf", "deckcraft-fonts", @@ -1930,7 +2583,7 @@ dependencies = [ [[package]] name = "deckcraft-ppt" -version = "0.19.0" +version = "0.20.0" dependencies = [ "deckcraft-color", "deckcraft-engine", @@ -1945,7 +2598,7 @@ dependencies = [ [[package]] name = "deckcraft-pptx" -version = "0.19.0" +version = "0.20.0" dependencies = [ "craft-cfb", "craft-drawingml", @@ -1965,7 +2618,7 @@ dependencies = [ [[package]] name = "deckcraft-render" -version = "0.19.0" +version = "0.20.0" dependencies = [ "craft-metafile", "deckcraft-anim", @@ -1984,9 +2637,10 @@ dependencies = [ [[package]] name = "deckcraft-text" -version = "0.19.0" +version = "0.20.0" dependencies = [ "chrono", + "craft", "deckcraft-color", "deckcraft-fonts", "deckcraft-geom", @@ -1998,14 +2652,11 @@ dependencies = [ [[package]] name = "deckcraft-ui-egui" -version = "0.19.0" +version = "0.20.0" dependencies = [ - "craft-host", - "craft-keymap", - "craft-theme", - "craft-ui", + "chrono", + "craft", "craft-update", - "craft-window", "deckcraft-anim", "deckcraft-color", "deckcraft-engine", @@ -2015,36 +2666,59 @@ dependencies = [ "deckcraft-model", "deckcraft-render", "deckcraft-text", + "eframe", "egui", - "egui_extras", "egui_kittest", "log", "serde", "serde_json", "skrifa 0.47.0", "toml", + "ttf-parser", "web-time", ] [[package]] name = "deckcraft-web" -version = "0.19.0" +version = "0.20.0" dependencies = [ - "craft-web-api", - "craft-web-host", + "craft", "deckcraft-engine", "deckcraft-ui-egui", "eframe", "egui", "js-sys", "log", - "rfd", "serde_json", "wasm-bindgen", "wasm-bindgen-futures", "web-sys", ] +[[package]] +name = "der" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb" +dependencies = [ + "const-oid", + "der_derive", + "flagset", + "pem-rfc7468", + "zeroize", +] + +[[package]] +name = "der_derive" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8034092389675178f570469e6c3b0465d3d30b4505c294a6550db47f3c17ad18" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "deranged" version = "0.5.9" @@ -2083,6 +2757,7 @@ checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" dependencies = [ "block-buffer", "crypto-common", + "subtle", ] [[package]] @@ -2229,16 +2904,40 @@ checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" [[package]] name = "ecolor" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" +source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321" dependencies = [ "bytemuck", "emath", ] +[[package]] +name = "ed25519" +version = "2.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "115531babc129696a58c64a4fef0a8bf9e9698629fb97e9e40767d235cfbcd53" +dependencies = [ + "pkcs8", + "signature", +] + +[[package]] +name = "ed25519-dalek" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "70e796c081cee67dc755e1a36a0a172b897fab85fc3f6bc48307991f64e4eca9" +dependencies = [ + "curve25519-dalek", + "ed25519", + "serde", + "sha2", + "subtle", + "zeroize", +] + [[package]] name = "eframe" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" +source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321" dependencies = [ "ahash", "bytemuck", @@ -2273,7 +2972,7 @@ dependencies = [ [[package]] name = "egui" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" +source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321" dependencies = [ "accesskit", "ahash", @@ -2292,7 +2991,7 @@ dependencies = [ [[package]] name = "egui-wgpu" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" +source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321" dependencies = [ "ahash", "bytemuck", @@ -2311,7 +3010,7 @@ dependencies = [ [[package]] name = "egui-winit" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" +source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321" dependencies = [ "accesskit_winit", "arboard", @@ -2334,23 +3033,10 @@ dependencies = [ "winit", ] -[[package]] -name = "egui_extras" -version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" -dependencies = [ - "ahash", - "egui", - "enum-map", - "itertools 0.15.0", - "log", - "profiling", -] - [[package]] name = "egui_glow" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" +source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321" dependencies = [ "bytemuck", "egui", @@ -2363,7 +3049,7 @@ dependencies = [ [[package]] name = "egui_kittest" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" +source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321" dependencies = [ "dify", "eframe", @@ -2389,7 +3075,7 @@ checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" [[package]] name = "emath" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" +source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321" dependencies = [ "bytemuck", ] @@ -2426,26 +3112,6 @@ version = "1.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "66b7e2430c6dff6a955451e2cfc438f09cea1965a9d6f87f7e3b90decc014099" -[[package]] -name = "enum-map" -version = "3.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d4532960034c15ba2f55e9eee631040ecc473c32e6c4b200828c759840f13a06" -dependencies = [ - "enum-map-derive", -] - -[[package]] -name = "enum-map-derive" -version = "1.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7127272f64b3e098f7d81f350d672081b879bff896d219c42370dc858b1af9ff" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.6", -] - [[package]] name = "enumflags2" version = "0.7.12" @@ -2470,7 +3136,7 @@ dependencies = [ [[package]] name = "epaint" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" +source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321" dependencies = [ "ahash", "bytemuck", @@ -2496,7 +3162,11 @@ dependencies = [ [[package]] name = "epaint_default_fonts" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" +source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321" +dependencies = [ + "brotli", + "brotli-decompressor", +] [[package]] name = "equator" @@ -2602,6 +3272,12 @@ version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b97b65636e5b9ef369943878ac74335ba1c55c1cb6adbf1e2c293c624248d693" +[[package]] +name = "fiat-crypto" +version = "0.2.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d" + [[package]] name = "filetime" version = "0.2.29" @@ -2635,6 +3311,12 @@ version = "0.5.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1d674e81391d1e1ab681a28d99df07927c6d4aa5b027d7da16ba32d1d21ecd99" +[[package]] +name = "flagset" +version = "0.4.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7ac824320a75a52197e8f2d787f6a38b6718bb6897a35142d749af3c0e8f4fe" + [[package]] name = "flate2" version = "1.1.10" @@ -2655,6 +3337,28 @@ dependencies = [ "num-traits", ] +[[package]] +name = "fmt-derive" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1cb4a4b45c26455885f8b462db12978e51f60cc914337bccb9a36faf93410169" +dependencies = [ + "fmt-derive-proc", +] + +[[package]] +name = "fmt-derive-proc" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7704da0760734344ce8753f15b21e97c6be85dc5a8f2c3a963fbd042b3380d23" +dependencies = [ + "proc-macro-crate", + "proc-macro-error", + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "fmv-macos-events" version = "0.1.0" @@ -2666,6 +3370,12 @@ dependencies = [ "objc2-foundation 0.3.2", ] +[[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" @@ -2696,6 +3406,28 @@ dependencies = [ "bytemuck", ] +[[package]] +name = "fontique" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6688bc1294fe7117d788937b6c53480169b29c566954af490830d4c09da9516a" +dependencies = [ + "hashbrown 0.17.1", + "linebender_resource_handle", + "memmap2", + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-core-text", + "objc2-foundation 0.3.2", + "parlance", + "read-fonts 0.41.0", + "roxmltree", + "smallvec", + "windows 0.62.2", + "windows-core 0.62.2", + "yeslogic-fontconfig-sys", +] + [[package]] name = "foreign-types" version = "0.5.0" @@ -2732,6 +3464,33 @@ dependencies = [ "percent-encoding", ] +[[package]] +name = "fs-set-times" +version = "0.20.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94e7099f6313ecacbe1256e8ff9d617b75d1bcb16a6fddef94866d225a01a14a" +dependencies = [ + "io-lifetimes 2.0.4", + "rustix 1.1.6", + "windows-sys 0.59.0", +] + +[[package]] +name = "fs_extra" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" + +[[package]] +name = "futures-channel" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" +dependencies = [ + "futures-core", + "futures-sink", +] + [[package]] name = "futures-core" version = "0.3.34" @@ -2768,6 +3527,12 @@ dependencies = [ "syn 3.0.6", ] +[[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" @@ -2781,8 +3546,11 @@ 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", ] @@ -2847,8 +3615,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" dependencies = [ "cfg-if", + "js-sys", "libc", "wasi", + "wasm-bindgen", ] [[package]] @@ -2918,7 +3688,7 @@ dependencies = [ "hashbrown 0.17.1", "log", "peniko", - "png", + "png 0.18.1", "skrifa 0.44.0", "smallvec", "vello_common", @@ -3031,6 +3801,25 @@ dependencies = [ "euclid", ] +[[package]] +name = "h2" +version = "0.4.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b634322c4924093fe6a6e05ecbe5717cd3c6014934455f4ae8e5cf14ba3264a8" +dependencies = [ + "atomic-waker", + "bytes", + "fnv", + "futures-core", + "futures-sink", + "http", + "indexmap", + "slab", + "tokio", + "tokio-util", + "tracing", +] + [[package]] name = "half" version = "2.7.1" @@ -3149,6 +3938,15 @@ version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" +[[package]] +name = "hmac" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" +dependencies = [ + "digest", +] + [[package]] name = "http" version = "1.5.0" @@ -3159,12 +3957,103 @@ dependencies = [ "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 = "httparse" version = "1.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" +[[package]] +name = "hyper" +version = "1.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "229c6ff5584df4c6becbfe00567128bac768c8cd32ebc8a8366bd81ed072e8f3" +dependencies = [ + "atomic-waker", + "bytes", + "futures-channel", + "futures-core", + "h2", + "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", +] + +[[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 = "hypher" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "45f2b4f6b5da34d400d4c112eadcc14512cc5d04307a8eee182586d9bebd7ce6" + [[package]] name = "i_float" version = "5.0.0" @@ -3518,7 +4407,7 @@ dependencies = [ "image-webp", "moxcms", "num-traits", - "png", + "png 0.18.1", "tiff", "zune-core", "zune-jpeg", @@ -3576,6 +4465,34 @@ dependencies = [ "rustversion", ] +[[package]] +name = "io-extras" +version = "0.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20fd6de4ccfcc187e38bc21cfa543cb5a302cb86a8b114eb7f0bf0dc9f8ac00f" +dependencies = [ + "io-lifetimes 3.0.1", + "windows-sys 0.59.0", +] + +[[package]] +name = "io-lifetimes" +version = "2.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06432fb54d3be7964ecd3649233cddf80db2832f47fec34c01f65b3d9d774983" + +[[package]] +name = "io-lifetimes" +version = "3.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f0fb0570afe1fed943c5c3d4102d5358592d8625fda6a0007fdbe65a92fba96" + +[[package]] +name = "ipnet" +version = "2.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "007d6e6b91097094791302ccc6cd0588e0700ddac5c6829035bcd71eff4dc433" + [[package]] name = "is-docker" version = "0.2.0" @@ -3763,7 +4680,7 @@ dependencies = [ [[package]] name = "krilla" version = "0.8.2" -source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" +source = "git+https://github.com/storytold/craft-libs?rev=82ae5969349f2f70175011e01983eea32e4ae905#82ae5969349f2f70175011e01983eea32e4ae905" dependencies = [ "base64 0.22.1", "bumpalo", @@ -3774,7 +4691,7 @@ dependencies = [ "imagesize 0.14.0", "indexmap", "pdf-writer", - "png", + "png 0.18.1", "rayon", "rustc-hash 2.1.3", "rustybuzz", @@ -3966,6 +4883,12 @@ version = "0.4.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" +[[package]] +name = "lru-slab" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4050469837a6ff301cd14c1f8f24f88549e6d548f24f64e2148eb0f72cebc51f" + [[package]] name = "mach2" version = "0.4.3" @@ -3975,6 +4898,12 @@ dependencies = [ "libc", ] +[[package]] +name = "maybe-owned" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4facc753ae494aeb6e3c22f839b158aebd4f9270f55cd3c79906c45476c47ab4" + [[package]] name = "maybe-rayon" version = "0.1.1" @@ -3985,6 +4914,16 @@ dependencies = [ "rayon", ] +[[package]] +name = "md-5" +version = "0.10.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf" +dependencies = [ + "cfg-if", + "digest", +] + [[package]] name = "memchr" version = "2.8.3" @@ -4009,6 +4948,12 @@ dependencies = [ "autocfg", ] +[[package]] +name = "mime" +version = "0.3.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d5848f5a9e8117cf94f2f90faac24a87ff81600ff8628c1e3deaab572e76bfa1" + [[package]] name = "minicov" version = "0.3.8" @@ -4045,6 +4990,17 @@ dependencies = [ "simd-adler32", ] +[[package]] +name = "mio" +version = "1.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20521a903f02b0a573cd6840e9d0a5a0cc043d361fe924092cd70f8556cc9c4a" +dependencies = [ + "libc", + "wasi", + "windows-sys 0.61.2", +] + [[package]] name = "moxcms" version = "0.8.1" @@ -4068,7 +5024,7 @@ dependencies = [ "objc2-app-kit 0.3.2", "objc2-core-foundation", "objc2-foundation 0.3.2", - "png", + "png 0.18.1", "thiserror 2.0.21", "windows-sys 0.61.2", ] @@ -4863,7 +5819,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967" dependencies = [ "libc", - "windows-sys 0.45.0", + "windows-sys 0.61.2", ] [[package]] @@ -4895,6 +5851,12 @@ dependencies = [ "windows-link", ] +[[package]] +name = "parlance" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73072a9470554c8e794778acece2312661218aaabb635600957d952cf01c716e" + [[package]] name = "paste" version = "1.0.15" @@ -4919,6 +5881,25 @@ dependencies = [ "ryu", ] +[[package]] +name = "pem" +version = "3.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d30c53c26bc5b31a98cd02d20f25a7c8567146caf63ed593a9d87b2775291be" +dependencies = [ + "base64 0.22.1", + "serde_core", +] + +[[package]] +name = "pem-rfc7468" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88b39c9bfcfc231068454382784bb460aae594343fb030d46e9f50a645418412" +dependencies = [ + "base64ct", +] + [[package]] name = "peniko" version = "0.6.1" @@ -5060,6 +6041,16 @@ dependencies = [ "system-deps", ] +[[package]] +name = "pkcs8" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7" +dependencies = [ + "der", + "spki", +] + [[package]] name = "pkg-config" version = "0.3.34" @@ -5085,6 +6076,19 @@ dependencies = [ "time", ] +[[package]] +name = "png" +version = "0.17.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82151a2fc869e011c153adc57cf2789ccb8d9906ce52c0b39a6b5697749d7526" +dependencies = [ + "bitflags 1.3.2", + "crc32fast", + "fdeflate", + "flate2", + "miniz_oxide 0.8.9", +] + [[package]] name = "png" version = "0.18.1" @@ -5201,6 +6205,30 @@ dependencies = [ "toml_edit", ] +[[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" @@ -5259,6 +6287,63 @@ 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 2.1.3", + "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 = [ + "aws-lc-rs", + "bytes", + "getrandom 0.4.3", + "lru-slab", + "rand 0.10.4", + "rand_pcg", + "ring", + "rustc-hash 2.1.3", + "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" @@ -5311,6 +6396,15 @@ dependencies = [ "rand_core 0.9.5", ] +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" +dependencies = [ + "getrandom 0.2.17", +] + [[package]] name = "rand_core" version = "0.9.5" @@ -5326,6 +6420,15 @@ version = "0.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" +[[package]] +name = "rand_pcg" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eb95882a1e14462c69aea9984bb261293ccfe6022ef8de0eda18bd5afb0052df" +dependencies = [ + "rand_core 0.10.1", +] + [[package]] name = "range-alloc" version = "0.1.5" @@ -5519,6 +6622,49 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "19b30a45b0cd0bcca8037f3d0dc3421eaf95327a17cad11964fb8179b4fc4832" +[[package]] +name = "reqwest" +version = "0.13.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "16a1cfa75cc186dd73d5818e510e042e40927bccc9c236b061cea97e1eb08029" +dependencies = [ + "base64 0.23.1", + "bytes", + "encoding_rs", + "futures-channel", + "futures-core", + "futures-util", + "h2", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-rustls", + "hyper-util", + "js-sys", + "log", + "mime", + "percent-encoding", + "pin-project-lite", + "quinn", + "rustls", + "rustls-pki-types", + "rustls-platform-verifier", + "serde", + "serde_json", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tokio-rustls", + "tower", + "tower-http", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + [[package]] name = "resvg" version = "0.48.1" @@ -5580,7 +6726,7 @@ dependencies = [ "cfg-if", "getrandom 0.2.17", "libc", - "untrusted", + "untrusted 0.9.0", "windows-sys 0.52.0", ] @@ -5640,12 +6786,23 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "rustix-linux-procfs" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2fc84bf7e9aa16c4f2c758f27412dc9841341e16aa682d9c7ac308fe3ee12056" +dependencies = [ + "once_cell", + "rustix 1.1.6", +] + [[package]] name = "rustls" version = "0.23.46" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" dependencies = [ + "aws-lc-rs", "log", "once_cell", "ring", @@ -5673,6 +6830,7 @@ version = "1.15.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96" dependencies = [ + "web-time", "zeroize", ] @@ -5709,9 +6867,10 @@ version = "0.103.16" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4443b1b6d39d7c663139942cc4558262562d2c84123bb6282ef177009ca8b281" dependencies = [ + "aws-lc-rs", "ring", "rustls-pki-types", - "untrusted", + "untrusted 0.9.0", ] [[package]] @@ -5738,12 +6897,24 @@ dependencies = [ "unicode-script", ] +[[package]] +name = "ruzstd" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69e4ce4a039f42bf25920b95667e4d789e98749ab11bbb8d2c2936f788421bb5" + [[package]] name = "ryu" version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" +[[package]] +name = "ryu-js" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1f232fd0249f55adbe7f15bee58bbbd3d40708000b84e6482066d2ba599e08a9" + [[package]] name = "same-file" version = "1.0.6" @@ -5862,6 +7033,17 @@ dependencies = [ "zmij", ] +[[package]] +name = "serde_json_canonicalizer" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe52319a927259afbfa5180c5157cd8167edfd3e8c254f9558c7fef44c5649f2" +dependencies = [ + "ryu-js", + "serde", + "serde_json", +] + [[package]] name = "serde_repr" version = "0.1.21" @@ -5875,13 +7057,36 @@ dependencies = [ [[package]] name = "serde_spanned" -version = "1.1.1" +version = "1.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6662b5879511e06e8999a8a235d848113e942c9124f211511b16466ee2995f26" +checksum = "9c187e0a369471c550af028cba56d4f4fa2a489ad28151ae95a4d340a2a8b782" dependencies = [ "serde_core", ] +[[package]] +name = "serde_urlencoded" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" +dependencies = [ + "form_urlencoded", + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "sha1" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "digest", +] + [[package]] name = "sha2" version = "0.10.9" @@ -5915,6 +7120,175 @@ dependencies = [ "libc", ] +[[package]] +name = "signature" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de" +dependencies = [ + "rand_core 0.6.4", +] + +[[package]] +name = "sigstore-bundle" +version = "0.6.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e7dc53c8a941858d01479622dbb7650aaa2ee0ca1fb58fb6cdddbfc3064abbb" +dependencies = [ + "base64 0.22.1", + "hex", + "serde", + "serde_json", + "sigstore-crypto", + "sigstore-merkle", + "sigstore-rekor", + "sigstore-tsa", + "sigstore-types", + "thiserror 2.0.21", +] + +[[package]] +name = "sigstore-crypto" +version = "0.6.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da90c3d9af638898a5fdc347479b18f950bb0dde11ecf2244f94cd28135da53b" +dependencies = [ + "aws-lc-rs", + "base64 0.22.1", + "const-oid", + "der", + "digest", + "pem", + "rand_core 0.10.1", + "sha2", + "signature", + "sigstore-types", + "spki", + "thiserror 2.0.21", + "tracing", + "x509-cert", +] + +[[package]] +name = "sigstore-merkle" +version = "0.6.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7c0d53558825c77716855c13794306fff766854c1bf92948e77d7890da3f2455" +dependencies = [ + "base64 0.22.1", + "hex", + "sigstore-crypto", + "sigstore-types", + "thiserror 2.0.21", +] + +[[package]] +name = "sigstore-rekor" +version = "0.6.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "641fdaaa40d0cd6e249cf1671c2240beff1a3ece578062cf43e750779e8db2b3" +dependencies = [ + "base64 0.22.1", + "hex", + "reqwest", + "serde", + "serde_json", + "sigstore-crypto", + "sigstore-merkle", + "sigstore-types", + "thiserror 2.0.21", + "url", +] + +[[package]] +name = "sigstore-trust-root" +version = "0.6.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6b0d2550f05c096400066e858db13d91f9de3b750a7541fb1291c1dc80ca290" +dependencies = [ + "base64 0.22.1", + "chrono", + "hex", + "rustls-pki-types", + "serde", + "serde_json", + "sigstore-crypto", + "sigstore-types", + "thiserror 2.0.21", + "x509-cert", +] + +[[package]] +name = "sigstore-tsa" +version = "0.6.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bc86c8abc1ece6832236e7e34e9baebb5d4d40490c0332b814a0d8624ca7255" +dependencies = [ + "aws-lc-rs", + "base64 0.22.1", + "chrono", + "cmpv2", + "cms", + "const-oid", + "der", + "hex", + "rand 0.10.4", + "reqwest", + "rustls-pki-types", + "rustls-webpki", + "sigstore-crypto", + "sigstore-types", + "thiserror 2.0.21", + "tracing", + "x509-cert", + "x509-tsp", +] + +[[package]] +name = "sigstore-types" +version = "0.6.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8d870c9bcfdf83396ac2bd2d6a23c5d09ec02cc9fda50fa1cbb3dd71a9bee53" +dependencies = [ + "base64 0.22.1", + "chrono", + "hex", + "pem", + "serde", + "serde_json", + "thiserror 2.0.21", +] + +[[package]] +name = "sigstore-verify" +version = "0.6.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d30aff69036e4579b416956e9ba68cec45b793116f78f10842d04c7f8b924bab" +dependencies = [ + "base64 0.22.1", + "chrono", + "cms", + "const-oid", + "hex", + "pem", + "rustls-pki-types", + "rustls-webpki", + "serde", + "serde_json", + "serde_json_canonicalizer", + "sigstore-bundle", + "sigstore-crypto", + "sigstore-merkle", + "sigstore-rekor", + "sigstore-trust-root", + "sigstore-tsa", + "sigstore-types", + "thiserror 2.0.21", + "tls_codec", + "tracing", + "x509-cert", +] + [[package]] name = "simd-adler32" version = "0.3.10" @@ -6087,6 +7461,16 @@ dependencies = [ "serde", ] +[[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 = "spirv" version = "0.4.0+sdk-1.4.341.0" @@ -6096,6 +7480,16 @@ dependencies = [ "bitflags 2.13.2", ] +[[package]] +name = "spki" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d" +dependencies = [ + "base64ct", + "der", +] + [[package]] name = "stable_deref_trait" version = "1.2.1" @@ -6117,6 +7511,27 @@ dependencies = [ "float-cmp", ] +[[package]] +name = "strum" +version = "0.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9628de9b8791db39ceda2b119bbe13134770b56c138ec1d3af810d045c04f9bd" +dependencies = [ + "strum_macros", +] + +[[package]] +name = "strum_macros" +version = "0.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab85eea0270ee17587ed4156089e10b9e6880ee688791d45a905f5b1ca36f664" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "subsetter" version = "0.2.6" @@ -6340,6 +7755,16 @@ dependencies = [ "symphonia-metadata", ] +[[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" @@ -6362,6 +7787,15 @@ dependencies = [ "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" @@ -6385,6 +7819,27 @@ dependencies = [ "web-sys", ] +[[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 = "7.0.8" @@ -6406,6 +7861,7 @@ checksum = "3f6221d9a6003c78398e3b239969f352578258df48c8eb051caadae0015bc840" dependencies = [ "filetime", "libc", + "xattr", ] [[package]] @@ -6540,7 +7996,7 @@ dependencies = [ "bytemuck", "cfg-if", "log", - "png", + "png 0.18.1", "tiny-skia-path", ] @@ -6566,20 +8022,76 @@ dependencies = [ "zerovec", ] +[[package]] +name = "tinyvec" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" + +[[package]] +name = "tls_codec" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0de2e01245e2bb89d6f05801c564fa27624dbd7b1846859876c7dad82e90bf6b" +dependencies = [ + "tls_codec_derive", + "zeroize", +] + +[[package]] +name = "tls_codec_derive" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2d2e76690929402faae40aebdda620a2c0e25dd6d3b9afe48867dfd95991f4bd" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "tokio" version = "1.53.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e95f91fcc7a621e8b030f6aa23c71fe9838ae2fb4d8118b75602a328f5144044" dependencies = [ + "bytes", + "libc", + "mio", "pin-project-lite", + "socket2", + "windows-sys 0.61.2", +] + +[[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", + "libc", + "pin-project-lite", + "tokio", ] [[package]] name = "toml" -version = "1.1.6+spec-1.1.0" +version = "1.1.8+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "920602543f0911ab71da12c50d59701da54c196d1a2bf5cb4b75667f137a406a" +checksum = "20489e00e4d8741d6be680764cc12e270655e375a20d1011e844a9c3379e678d" dependencies = [ "indexmap", "serde_core", @@ -6592,9 +8104,9 @@ dependencies = [ [[package]] name = "toml_datetime" -version = "1.1.1+spec-1.1.0" +version = "1.1.3+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3165f65f62e28e0115a00b2ebdd37eb6f3b641855f9d636d3cd4103767159ad7" +checksum = "173f25c883cd2176a2d8212155638c0a60d484a9d84546d270866f40f56b6e49" dependencies = [ "serde_core", ] @@ -6616,18 +8128,63 @@ dependencies = [ [[package]] name = "toml_parser" -version = "1.1.3+spec-1.1.0" +version = "1.1.7+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d38ac1cf9b95face32296c0a3ede1fdc270627c9d9c02a7274dd6d960dc4d56" +checksum = "0bb28d6e049a9766c3bd91a8326e6179f5b132dec87906bb97018ef7a2f3431a" dependencies = [ "winnow", ] [[package]] name = "toml_writer" -version = "1.1.2+spec-1.1.0" +version = "1.2.0+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7d56353a2a665ad0f41a421187180aab746c8c325620617ad883a99a1cbe66d2" +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" @@ -6672,6 +8229,12 @@ dependencies = [ "petgraph", ] +[[package]] +name = "try-lock" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" + [[package]] name = "ttf-parser" version = "0.25.1" @@ -6779,6 +8342,12 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254" +[[package]] +name = "untrusted" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a156c684c91ea7d62626509bce3cb4e1d9ed5c4d978f7b4352658f96a4c26b4a" + [[package]] name = "untrusted" version = "0.9.0" @@ -6800,6 +8369,7 @@ dependencies = [ "rustls-platform-verifier", "ureq-proto", "utf8-zero", + "webpki-roots", ] [[package]] @@ -6917,7 +8487,7 @@ dependencies = [ "guillotiere", "log", "peniko", - "png", + "png 0.18.1", "smallvec", "thiserror 2.0.21", ] @@ -6933,7 +8503,7 @@ dependencies = [ "glifo", "hashbrown 0.17.1", "ordered-channel", - "png", + "png 0.18.1", "rayon", "thread_local", "vello_common", @@ -6971,6 +8541,15 @@ dependencies = [ "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" @@ -7276,6 +8855,15 @@ dependencies = [ "rustls-pki-types", ] +[[package]] +name = "webpki-roots" +version = "1.0.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7265c9301c16a8711c992c2d8da90ee77ef54b1ed51482d6dfeb00dc756b1297" +dependencies = [ + "rustls-pki-types", +] + [[package]] name = "weezl" version = "0.1.12" @@ -7790,7 +9378,7 @@ checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" [[package]] name = "winit" version = "0.30.13" -source = "git+https://github.com/storytold/winit.git?rev=a517b3846ee8457d84ee4975110bfda6797c44dc#a517b3846ee8457d84ee4975110bfda6797c44dc" +source = "git+https://github.com/storytold/winit.git?rev=0dfcec0eb62fda5904137a63a6dd0c3d83295f45#0dfcec0eb62fda5904137a63a6dd0c3d83295f45" dependencies = [ "ahash", "android-activity", @@ -7846,6 +9434,28 @@ dependencies = [ "memchr", ] +[[package]] +name = "winprint" +version = "0.2.1" +source = "git+https://github.com/storytold/winprint.rs?rev=8ae097ef941b432b0e7671b1ec3a506800e65e57#8ae097ef941b432b0e7671b1ec3a506800e65e57" +dependencies = [ + "flate2", + "fmt-derive", + "reqwest", + "scopeguard", + "sigstore-trust-root", + "sigstore-types", + "sigstore-verify", + "strum", + "tar", + "thiserror 2.0.21", + "windows 0.62.2", + "windows-core 0.62.2", + "windows-implement", + "windows-numerics", + "xml", +] + [[package]] name = "winreg" version = "0.55.0" @@ -7872,6 +9482,16 @@ version = "0.0.29" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9ef0ffc427f045c0cc9ebffd6f4f91153dcd2a1547b5c3c29ee3f541e16e95c6" +[[package]] +name = "winx" +version = "0.36.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f3fd376f71958b862e7afb20cfe5a22830e1963462f3a17f49d82a6c1d1f42d" +dependencies = [ + "bitflags 2.13.2", + "windows-sys 0.59.0", +] + [[package]] name = "wit-bindgen" version = "0.57.1" @@ -7924,6 +9544,16 @@ dependencies = [ "either", ] +[[package]] +name = "wuff" +version = "0.2.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6a992b57b3d1ee972b2e3fd9225e44793104d49818836dd812d5459187712dd" +dependencies = [ + "brotli-decompressor", + "bytes", +] + [[package]] name = "x11-dl" version = "2.21.0" @@ -7956,6 +9586,41 @@ version = "0.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ea6fc2961e4ef194dcbfe56bb845534d0dc8098940c7e5c012a258bfec6701bd" +[[package]] +name = "x509-cert" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1301e935010a701ae5f8655edc0ad17c44bad3ac5ce8c39185f75453b720ae94" +dependencies = [ + "const-oid", + "der", + "sha1", + "signature", + "spki", + "tls_codec", +] + +[[package]] +name = "x509-tsp" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f5ceece934a21607055b7ac5c25adb56a2ff559804b10705dc674d1d838c15e1" +dependencies = [ + "cmpv2", + "cms", + "der", +] + +[[package]] +name = "xattr" +version = "1.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "963d6fab92d5504b971dc8bd90ca743c2575e590bc8071ea5bc571598667ae08" +dependencies = [ + "libc", + "rustix 1.1.6", +] + [[package]] name = "xcap" version = "0.9.8" @@ -8023,6 +9688,12 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b9cc00251562a284751c9973bace760d86c0276c471b4be569fe6b068ee97a56" +[[package]] +name = "xml" +version = "1.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f45bb2c13fec6a6cb4c0f76a7e94839e110a14ec803ec2940777a94c347bc52" + [[package]] name = "xml-rs" version = "0.8.29" @@ -8037,7 +9708,7 @@ checksum = "9440ea3e5aeabb0ac63af70daf835274065238cdd0cec83418f417eae38bacee" [[package]] name = "xtask" -version = "0.19.0" +version = "0.20.0" dependencies = [ "serde_json", ] @@ -8048,6 +9719,17 @@ version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7a5a4b21e1a62b67a2970e6831bc091d7b87e119e7f9791aef9702e3bef04448" +[[package]] +name = "yeslogic-fontconfig-sys" +version = "6.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2232035104db97d8ded0e24a20d6ba61a0f904e5830d437f411d9a499336224" +dependencies = [ + "dlib", + "once_cell", + "pkg-config", +] + [[package]] name = "yoke" version = "0.8.3" @@ -8223,6 +9905,20 @@ name = "zeroize" version = "1.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" +dependencies = [ + "zeroize_derive", +] + +[[package]] +name = "zeroize_derive" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c50655cbb0fe3fc43170059e702f1ce5e19b84cec58dc87b037a09935c2f328" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] [[package]] name = "zerotrie" @@ -8374,14 +10070,19 @@ dependencies = [ [[patch.unused]] name = "egui_demo_lib" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" +source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321" + +[[patch.unused]] +name = "egui_extras" +version = "0.37.0" +source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321" [[patch.unused]] name = "egui_inspection" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" +source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321" [[patch.unused]] name = "egui_system_font_provider" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" +source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321" diff --git a/Cargo.toml b/Cargo.toml index 8e804ae36..91937a81a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,7 +4,7 @@ members = ["crates/*", "apps/*", "xtask"] default-members = ["crates/*", "apps/deckcraft", "apps/deckcraft-cli"] [workspace.package] -version = "0.19.0" +version = "0.20.0" edition = "2024" license = "MIT OR Apache-2.0" rust-version = "1.95" @@ -12,17 +12,21 @@ repository = "https://github.com/storytold/deckcraft" [workspace.dependencies] # OPC part-name primitives and package reader/writer. -craft-opc = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" } +craft-opc = { git = "https://github.com/storytold/craft-libs", rev = "82ae5969349f2f70175011e01983eea32e4ae905", version = "0.1.0" } # Compound File Binary directory reads (password-protected deck detection). -craft-cfb = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" } +craft-cfb = { git = "https://github.com/storytold/craft-libs", rev = "82ae5969349f2f70175011e01983eea32e4ae905", version = "0.1.0" } # Bounded XML reader and writer primitives. -craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" } +craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "82ae5969349f2f70175011e01983eea32e4ae905", version = "0.1.0" } # DrawingML colours, themes, charts, tables and text (craft-libs#778, #792). -craft-drawingml = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" } +craft-drawingml = { git = "https://github.com/storytold/craft-libs", rev = "82ae5969349f2f70175011e01983eea32e4ae905", version = "0.1.0" } # PresentationML PPTX/POTX/PPSX reader and writer (craft-libs#778). -craft-pptx = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" } +craft-pptx = { git = "https://github.com/storytold/craft-libs", rev = "82ae5969349f2f70175011e01983eea32e4ae905", version = "0.1.0" } +# The craft facade: UI framework, platform, settings, window and the suite crates DeckCraft's UI uses. +craft = { git = "https://github.com/storytold/craft-libs", rev = "82ae5969349f2f70175011e01983eea32e4ae905", version = "0.1.0" } # Shared MCP stdio framing and protocol constants (craft-libs#778). -craft-mcp-server = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" } +craft-mcp-server = { git = "https://github.com/storytold/craft-libs", rev = "82ae5969349f2f70175011e01983eea32e4ae905", version = "0.1.0" } +# Nightly profile isolation, launch protocol, and security fence. +craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "82ae5969349f2f70175011e01983eea32e4ae905", version = "=0.1.0" } # internal deckcraft-geom = { path = "crates/geom" } deckcraft-color = { path = "crates/color" } @@ -62,27 +66,21 @@ vello_cpu = "0.2" vello_common = { version = "0.2", default-features = false } image = { version = "0.25", default-features = false, features = ["png", "jpeg", "webp", "gif", "tiff", "bmp"] } # Base64 for command payloads (engine); base64_compat keeps the legacy lenient decoder. Same rev as craft-deckcraft-format. -craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "=0.1.0" } +craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "82ae5969349f2f70175011e01983eea32e4ae905", version = "=0.1.0" } # craft-media, craft-audio and craft-video share types and stay on one rev. # The .deckcraft package layer (identity, manifest, member names, bounded reads); crates/format maps the presentation onto it. -craft-deckcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "=0.1.0" } -craft-rtf = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "=0.1.0" } -craft-media = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "=0.1.0", default-features = false } -craft-audio = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "=0.1.0", default-features = false, features = ["opus-decode"] } +craft-deckcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "82ae5969349f2f70175011e01983eea32e4ae905", version = "=0.1.0" } +craft-rtf = { git = "https://github.com/storytold/craft-libs", rev = "82ae5969349f2f70175011e01983eea32e4ae905", version = "=0.1.0" } +craft-media = { git = "https://github.com/storytold/craft-libs", rev = "82ae5969349f2f70175011e01983eea32e4ae905", version = "=0.1.0", default-features = false } +craft-audio = { git = "https://github.com/storytold/craft-libs", rev = "82ae5969349f2f70175011e01983eea32e4ae905", version = "=0.1.0", default-features = false, features = ["opus-decode"] } # H.264, HEVC, VP9 and AV1 decoders. -craft-video = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "=0.1.0", default-features = false, features = ["h264-decode", "hevc-decode", "vp9-decode", "av1-decode", "threads"] } +craft-video = { git = "https://github.com/storytold/craft-libs", rev = "82ae5969349f2f70175011e01983eea32e4ae905", version = "=0.1.0", default-features = false, features = ["h264-decode", "hevc-decode", "vp9-decode", "av1-decode", "threads"] } # WMF, EMF and EMF+ reader. -craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "=0.1.0" } -craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "=0.1.0", default-features = false, features = ["write", "write-simple-text"] } +craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "82ae5969349f2f70175011e01983eea32e4ae905", version = "=0.1.0" } +craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "82ae5969349f2f70175011e01983eea32e4ae905", version = "=0.1.0", default-features = false, features = ["write", "write-simple-text"] } # craft-update: app-specific pretend versions apply to startup and manual checks. -craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", features = ["ui"] } -craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "=0.1.0" } -# The framework runtime's host: the app's identity, its window services, its key overrides and the theme mode -# the framework's components draw in. -craft-host = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "=0.1.0" } -craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "=0.1.0" } -craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "=0.1.0" } -craft-window = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "=0.1.0" } +craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "82ae5969349f2f70175011e01983eea32e4ae905", features = ["ui"] } +craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "82ae5969349f2f70175011e01983eea32e4ae905", version = "=0.1.0" } i_overlay = "9" quick-xml = "0.41" zip = { version = "3", default-features = false, features = ["deflate"] } @@ -90,12 +88,10 @@ miniz_oxide = { version = "0.9", default-features = false, features = ["with-all # ui egui = { version = "0.37", default-features = false } -egui_extras = { version = "0.37", default-features = false } eframe = { version = "0.37", default-features = false } egui_kittest = "0.37" web-time = "1.1" rfd = "0.17" -arboard = { version = "3.6", default-features = false } [workspace.lints.rust] unsafe_code = "forbid" @@ -129,19 +125,28 @@ codegen-units = 16 debug = 0 [patch.crates-io] -krilla = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "=0.8.2" } -ecolor = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } -emath = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } -epaint = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } -epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } -egui = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } -egui-winit = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } -egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } -egui_glow = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } -egui_extras = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } -egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } -egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } -eframe = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } -egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } -egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } -winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" } +# BEGIN port-kit framework overrides +krilla = { git = "https://github.com/storytold/craft-libs", rev = "82ae5969349f2f70175011e01983eea32e4ae905", version = "=0.8.2" } +ecolor = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" } +emath = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" } +epaint = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" } +epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" } +egui = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" } +egui-winit = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" } +egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" } +egui_glow = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" } +egui_extras = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" } +egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" } +egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" } +eframe = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" } +egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" } +egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" } +winit = { git = "https://github.com/storytold/winit.git", rev = "0dfcec0eb62fda5904137a63a6dd0c3d83295f45" } +# END port-kit framework overrides + +[workspace.metadata.cl] +selection = ["deckcraft", "deckcraft-anim", "deckcraft-cli", "deckcraft-color", "deckcraft-engine", "deckcraft-format", "deckcraft-geom", "deckcraft-mcp", "deckcraft-model", "deckcraft-pdf", "deckcraft-ppt", "deckcraft-pptx", "deckcraft-render", "deckcraft-text", "deckcraft-ui-egui", "deckcraft-web"] +tracked = ["egui", "eframe", "craft-ui", "craft-pptx", "craft-drawingml"] +unset_env = ["DECKCRAFT_BUILD_CHANNEL", "DECKCRAFT_VERSION", "DECKCRAFT_REQUIRE_WINRES", "CRAFT_FONTS_REQUIRED"] + +# BEGIN port-kit framework patch diff --git a/README.md b/README.md index a05dcc7fe..ea82d3c4c 100644 --- a/README.md +++ b/README.md @@ -160,7 +160,7 @@ same verbs: deckcraft-cli commands format. # list commands deckcraft-cli run --sample --cmd 'slide.new={"layout":"titleOnly","title":"Hello"}' --save hello.deckcraft deckcraft-cli mcp # MCP server over stdio (headless) -deckcraft-cli mcp --connect 7990 # drive the running app (deckcraft --control 7990) +deckcraft-cli mcp --connect 7990 --control-token-file PATH # drive the running app with its token file deckcraft-cli mcp --automation-read-root DIR --automation-write-root DIR # confine the headless agent to folders ``` diff --git a/apps/deckcraft-cli/Cargo.toml b/apps/deckcraft-cli/Cargo.toml index 6d2f572eb..6212b53a9 100644 --- a/apps/deckcraft-cli/Cargo.toml +++ b/apps/deckcraft-cli/Cargo.toml @@ -14,6 +14,7 @@ name = "deckcraft-cli" path = "src/main.rs" [dependencies] +craft = { workspace = true, features = ["automation", "font-catalog"] } deckcraft-engine = { workspace = true } deckcraft-mcp = { workspace = true } serde_json = { workspace = true } diff --git a/apps/deckcraft-cli/src/help.rs b/apps/deckcraft-cli/src/help.rs index 0cf057b3c..418e389d1 100644 --- a/apps/deckcraft-cli/src/help.rs +++ b/apps/deckcraft-cli/src/help.rs @@ -125,23 +125,34 @@ calls it. }, Subcommand { name: "app", - usage: "app [--port PORT] COMMAND [PARAMS] | --method METHOD [PARAMS]", + usage: "app [--port PORT] [--control-token TOKEN | --control-token-file PATH] (COMMAND [PARAMS] | --method METHOD [PARAMS])", summary: "run a command in the DeckCraft app started with --control", details: "Sends one request to the DeckCraft app started with `deckcraft --control PORT` (port 7979 by default) and prints its answer as JSON. COMMAND [PARAMS] runs a command, as run --cmd does; --method METHOD [PARAMS] calls a control-channel method such as ui.screenshot. PARAMS is a JSON object. - deckcraft-cli app shape.insert '{\"preset\":\"star5\",\"rect\":[100,100,200,200]}' - deckcraft-cli app --method ui.screenshot '{\"path\":\"/tmp/shot.png\"}'", +Authenticate with the app's per-launch token: --control-token-file PATH reads its token file; +--control-token TOKEN supplies the token directly. DECKCRAFT_CONTROL_TOKEN and +DECKCRAFT_CONTROL_TOKEN_FILE supply fallbacks when their corresponding flags are absent. +Start the app with --control-token-file PATH to have it create or read that file. + + deckcraft-cli app --control-token-file PATH shape.insert '{\"preset\":\"star5\",\"rect\":[100,100,200,200]}' + deckcraft-cli app --control-token-file PATH --method ui.screenshot '{\"path\":\"/tmp/shot.png\"}'", }, Subcommand { name: "mcp", - usage: "mcp [--connect PORT] [--sample] [--automation-read-root DIR]... [--automation-write-root DIR]...", + usage: "mcp [--connect PORT [--control-token TOKEN | --control-token-file PATH]] [--sample] [--automation-read-root DIR]... [--automation-write-root DIR]...", summary: "serve the commands to an agent over MCP on stdio", details: "Runs a Model Context Protocol server on stdin and stdout. It works on its own presentation without a window, or with --connect PORT (or host:port) on the DeckCraft app started with --control PORT. --sample opens the sample presentation. +Connected mode requires the app's per-launch token: --control-token-file PATH reads its token file, +or --control-token TOKEN supplies it directly. DECKCRAFT_CONTROL_TOKEN and +DECKCRAFT_CONTROL_TOKEN_FILE supply fallbacks when their corresponding flags are absent. +Start the app with --control-token-file PATH to have it create or read that file. +Headless mode does not resolve these credentials. + --automation-read-root DIR and --automation-write-root DIR confine every file the agent's commands read (open, pictures, audio, video) and write (save, export, PDF) to those folders, links followed. Repeat either flag to grant access to more folders; a root left out grants none of its access. They run the in-process diff --git a/apps/deckcraft-cli/src/main.rs b/apps/deckcraft-cli/src/main.rs index 961a3ec37..2dc7e5a38 100644 --- a/apps/deckcraft-cli/src/main.rs +++ b/apps/deckcraft-cli/src/main.rs @@ -9,6 +9,8 @@ mod help; use std::process::ExitCode; use std::sync::atomic::{AtomicBool, Ordering}; +#[cfg(not(target_arch = "wasm32"))] +use craft::automation::args::{ControlOptions, EnvNames, FlagNames}; use deckcraft_engine::Session; use serde_json::{Value, json}; @@ -57,6 +59,10 @@ fn main() -> ExitCode { outln!("{page}"); return ExitCode::SUCCESS; } + craft::font_catalog::app::configure(craft::font_catalog::app::AppFonts { + dirs: craft::font_catalog::office_font_dirs(&craft::font_catalog::FontEnv::from_process()), + ..Default::default() + }); match args.first().map(String::as_str) { Some("help" | "--help" | "-h") => match rest.first() { None => { @@ -666,16 +672,35 @@ fn remark(args: &str) -> &str { after.strip_prefix('(').and_then(|n| n.strip_suffix(')')).unwrap_or(after) } +#[cfg(not(target_arch = "wasm32"))] +fn control_token(flags: ControlOptions) -> Result { + let names = EnvNames::for_app("DECKCRAFT"); + let options = ControlOptions::resolve_tokens(flags, &names).map_err(|error| error.to_string())?; + craft::automation::security::client_token(options.token.as_deref(), options.token_file.as_deref(), &FlagNames::default(), &names) + .map_err(|error| error.to_string()) +} + +#[cfg(target_arch = "wasm32")] +fn app(_args: &[String]) -> Result<(), String> { + Err("app: connecting to a desktop app requires a native build of deckcraft-cli".into()) +} + +#[cfg(not(target_arch = "wasm32"))] fn app(args: &[String]) -> Result<(), String> { use deckcraft_mcp::{Backend, Remote, control_addr}; let mut port = deckcraft_mcp::DEFAULT_PORT.to_string(); let mut method: Option = None; let mut rest = vec![]; - let mut it = args.iter(); + let mut tokens = ControlOptions::default(); + let mut it = args.iter().cloned(); while let Some(a) = it.next() { + // PLAN: assumed ControlOptions::take_flag(&mut self, arg: &str, rest: &mut dyn Iterator) -> Result (platform-w1) + if tokens.take_flag(&a, &mut it).map_err(|error| error.to_string())? { + continue; + } match a.as_str() { - "--port" => port = it.next().cloned().ok_or("--port needs a value")?, - "--method" => method = Some(it.next().cloned().ok_or("--method needs a name")?), + "--port" => port = it.next().ok_or("--port needs a value")?, + "--method" => method = Some(it.next().ok_or("--method needs a name")?), "--help" | "-h" => { outln!("{}", help_page("app")); return Ok(()); @@ -683,8 +708,14 @@ fn app(args: &[String]) -> Result<(), String> { other => rest.push(other.to_string()), } } - let mut r = Remote::connect(&control_addr(&port)) - .map_err(|e| format!("no DeckCraft app on port {port} ({e}); start it with `deckcraft --control {port}`"))?; + let token = control_token(tokens)?; + let mut r = Remote::connect(&control_addr(&port), &token).map_err(|e| { + if e.kind() == std::io::ErrorKind::PermissionDenied { + format!("DeckCraft app on port {port} refused the control token: {e}") + } else { + format!("no DeckCraft app on port {port} ({e}); start it with `deckcraft --control {port}` and pass its token with --control-token-file PATH or --control-token TOKEN") + } + })?; let parse = |s: Option<&String>| -> Result { s.map(|j| serde_json::from_str(j).map_err(|e| format!("bad JSON: {e}"))).transpose().map(|v| v.unwrap_or(json!({}))) }; @@ -701,15 +732,24 @@ fn app(args: &[String]) -> Result<(), String> { fn mcp(args: &[String]) -> Result<(), String> { use deckcraft_engine::file_access::{self, AutomationRoots}; - use deckcraft_mcp::{Backend, Headless, Remote, Server, control_addr}; + use deckcraft_mcp::{Backend, Headless, Server}; + #[cfg(not(target_arch = "wasm32"))] + use deckcraft_mcp::{Remote, control_addr}; let mut connect: Option = None; let mut sample = false; + #[cfg(not(target_arch = "wasm32"))] + let mut tokens = ControlOptions::default(); let mut roots_args = automation_args::AutomationArgs::new(None, None); let mut it = args.iter().cloned(); while let Some(a) = it.next() { if roots_args.consume(&a, &mut it)? { continue; } + #[cfg(not(target_arch = "wasm32"))] + // PLAN: assumed ControlOptions::take_flag(&mut self, arg: &str, rest: &mut dyn Iterator) -> Result (platform-w1) + if tokens.take_flag(&a, &mut it).map_err(|error| error.to_string())? { + continue; + } match a.as_str() { "--connect" => connect = Some(it.next().ok_or("--connect needs a port or host:port")?), "--sample" => sample = true, @@ -727,7 +767,15 @@ so drop --connect (or use --connect without the roots)" .into()); } let backend: Box = match connect { - Some(c) => Box::new(Remote::connect(&control_addr(&c)).map_err(|e| format!("can't reach the app at {c}: {e}"))?), + Some(c) => { + #[cfg(target_arch = "wasm32")] + return Err(format!("can't connect to the app at {c}: connected MCP requires a native build of deckcraft-cli")); + #[cfg(not(target_arch = "wasm32"))] + { + let token = control_token(tokens)?; + Box::new(Remote::connect(&control_addr(&c), &token).map_err(|e| format!("can't reach the app at {c}: {e}"))?) + } + } None => { let mut h = Headless::new(); // `--sample` is the operator's own choice, made before the roots come into force. diff --git a/apps/deckcraft-web/Cargo.toml b/apps/deckcraft-web/Cargo.toml index e8b6b39fb..9692c7c2e 100644 --- a/apps/deckcraft-web/Cargo.toml +++ b/apps/deckcraft-web/Cargo.toml @@ -14,21 +14,18 @@ name = "deckcraft-web" path = "src/main.rs" [dependencies] +craft = { workspace = true, features = ["ui", "automation", "window", "settings", "font-catalog"] } deckcraft-engine = { workspace = true } deckcraft-ui-egui = { workspace = true } -# The page command API (storytold/craft-libs#413): window.deckcraft over the control channel. -craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" } -# The host messages (storytold/craft-libs): one contract and one bridge for the web builds. -craft-web-host = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" } egui = { workspace = true } log = { workspace = true } serde_json = { workspace = true } [target.'cfg(target_arch = "wasm32")'.dependencies] +craft = { workspace = true, features = ["web-api", "web-host", "platform-browser"] } # `wgpu` pulls egui-wgpu's defaults: WebGPU plus the WebGL2 fallback. eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit"] } -rfd = { workspace = true } wasm-bindgen = "0.2" wasm-bindgen-futures = "0.4" js-sys = "0.3" -web-sys = { version = "0.3", features = ["Window", "Document", "Element", "HtmlElement", "HtmlCanvasElement", "HtmlAnchorElement", "Blob", "BlobPropertyBag", "Url", "Location", "CssStyleDeclaration", "MessageEvent", "Event", "EventTarget", "UrlSearchParams"] } +web-sys = { version = "0.3", features = ["Window", "Document", "Element", "HtmlCanvasElement", "Location", "UrlSearchParams"] } diff --git a/apps/deckcraft-web/src/api.rs b/apps/deckcraft-web/src/api.rs index 5a74db92d..00c284ec7 100644 --- a/apps/deckcraft-web/src/api.rs +++ b/apps/deckcraft-web/src/api.rs @@ -1,17 +1,15 @@ -//! `window.deckcraft`: the page command API (`craft-web-api`, storytold/craft-libs#413) over the +//! `window.deckcraft`: the page command API (`craft::web_api`) over the //! app's own control channel, the one the desktop control server drives (`docs/control-protocol.md`). //! //! The crate owns the JavaScript side (`request`, `execute`, `commands`, `docInspect`, `uiInspect`, -//! `screenshot`, as promises with a timeout). This module is DeckCraft's part: a [`Request`] that -//! queues a [`ControlRequest`] for the app, which answers it on its next frame, and waits for the +//! `screenshot`, as promises with a timeout). This module is DeckCraft's part: a page request that +//! queues a [`ControlRequest`](craft::automation::control::ControlRequest) for the app, which answers it on its next frame, and waits for the //! reply. A call the page gave up on is released ([`Pending`]), so the app skips it if it has not started it, instead of //! applying a command the page was told had failed. -use std::sync::Arc; -use std::sync::atomic::AtomicU8; use std::sync::mpsc::{Receiver, TryRecvError}; -use deckcraft_ui_egui::ControlRequest; +use craft::automation::control::Dispatch; use serde_json::{Value, json}; /// How often a waiting call looks for the app's reply, in milliseconds (about a frame). @@ -22,7 +20,7 @@ const POLL_MS: i32 = 16; /// timeout fired, or the call was abandoned) releases the request: the app skips it if it has not started it (one it has taken still finishes). struct Pending { reply: Receiver, - state: Arc, + dispatch: Dispatch, answered: bool, } @@ -46,7 +44,7 @@ impl Pending { impl Drop for Pending { fn drop(&mut self) { if !self.answered { - ControlRequest::abandon(&self.state); + self.dispatch.give_up(); } } } @@ -57,11 +55,11 @@ pub use web::install; #[cfg(target_arch = "wasm32")] mod web { use std::rc::Rc; - use std::sync::mpsc::channel; + use std::sync::mpsc::{Receiver, channel}; - use craft_web_api::methods::Methods; - use craft_web_api::page::{PageApi, Request}; - use deckcraft_ui_egui::{ControlRequest, SlideApp}; + use craft::automation::control::ControlRequest; + use craft::web_api::methods::Methods; + use craft::web_api::page::{PageApi, Request}; use serde_json::json; use wasm_bindgen_futures::JsFuture; @@ -70,14 +68,13 @@ mod web { /// The app id in `window.`. const APP: &str = "deckcraft"; - /// Give the app its control queue and put `window.deckcraft` on the page. An existing + /// Return the app's control queue and put `window.deckcraft` on the page. An existing /// `window.deckcraft` keeps the functions it already has. - pub fn install(app: &mut SlideApp, ctx: egui::Context) { + pub fn install(ctx: egui::Context) -> Receiver { let (queue, requests) = channel::(); - app.control_rx = Some(requests); let request: Request = Rc::new(move |method, params| { let (control, reply) = ControlRequest::new(method, params); - let mut pending = Pending { reply, state: control.state.clone(), answered: false }; + let mut pending = Pending { reply, dispatch: control.dispatch.clone(), answered: false }; if queue.send(control).is_err() { pending.answered = true; return Box::pin(async { json!({"ok": false, "error": "the app is not running"}) }); @@ -95,6 +92,7 @@ mod web { if let Err(e) = Rc::new(PageApi::new(APP, Methods::default(), request)).install() { log::warn!("couldn't install window.{APP}: {e:?}"); } + requests } async fn sleep(ms: i32) { @@ -109,43 +107,16 @@ mod web { #[cfg(test)] mod tests { - use std::sync::atomic::Ordering; + use craft::automation::control::ControlRequest; use super::*; - /// `ControlRequest`'s `state` values (`deckcraft_ui_egui::control`): the app has started it, or its - /// sender gave up. - const TAKEN: u8 = 1; - const ABANDONED: u8 = 2; - - fn pending() -> (Pending, ControlRequest) { - let (control, reply) = ControlRequest::new("document.inspect", json!({})); - (Pending { reply, state: control.state.clone(), answered: false }, control) - } - #[test] fn a_call_the_page_gave_up_on_is_released_so_the_app_skips_it() { - let (waiting, control) = pending(); + let (control, reply) = ControlRequest::new("document.inspect", json!({})); + let mut waiting = Pending { reply, dispatch: control.dispatch.clone(), answered: false }; + assert!(waiting.poll().is_none()); drop(waiting); - assert_eq!(control.state.load(Ordering::SeqCst), ABANDONED); - assert!(!control.take(), "the app must not run a request the page was told had failed"); - } - - #[test] - fn an_answered_call_is_not_released() { - let (mut waiting, control) = pending(); - assert!(control.take()); - control.reply.send(json!({"ok": true, "result": 1})).unwrap_or_default(); - assert_eq!(waiting.poll(), Some(json!({"ok": true, "result": 1}))); - drop(waiting); - assert_eq!(control.state.load(Ordering::SeqCst), TAKEN); - } - - #[test] - fn a_request_the_app_never_runs_waits_until_it_is_dropped() { - let (mut waiting, control) = pending(); - assert_eq!(waiting.poll(), None); - drop(control); - assert_eq!(waiting.poll().and_then(|r| r["ok"].as_bool()), Some(false), "the app went away"); + assert!(!control.dispatch.start(), "the app must not run a request the page was told had failed"); } } diff --git a/apps/deckcraft-web/src/host.rs b/apps/deckcraft-web/src/host.rs index d264b13c8..a844af147 100644 --- a/apps/deckcraft-web/src/host.rs +++ b/apps/deckcraft-web/src/host.rs @@ -1,5 +1,5 @@ //! The host bridge, for pages that embed DeckCraft and keep its files (a Nextcloud app, a personal -//! file server). The messages and the two transports are `craft-web-host`'s +//! file server). The messages and the two transports are `craft::web_host`'s //! (storytold/craft-libs), the same contract as the other Craft apps' bridges, with the //! `deckcraft:` prefix. This module is DeckCraft's part of it. //! @@ -15,7 +15,7 @@ //! as its file, so Save goes back to it; an outline (.txt, .md, .rtf), a file without a name and //! a damaged file open untitled. //! - `deckcraft:save` (to the host): `{ name, saveAs, bytes }` (with the bytes as a transferred `ArrayBuffer` over `postMessage`) for -//! every file DeckCraft would otherwise download. The host stores it and reports failures +//! every file delivered through `Files::save` or `Files::write`. The host stores it and reports failures //! itself. `saveAs` says whether the file becomes the presentation's file: //! - Save: `false`. It writes the opened file under its own name and format (a .pptx stays a //! .pptx), as the desktop app does. A name the parent never sent (an untitled presentation, an @@ -36,16 +36,12 @@ use std::cell::RefCell; use std::rc::Rc; -use craft_web_host::web::{FileData, Host, Message}; -use deckcraft_ui_egui::{Services, SlideApp}; +use craft::web_host::web::{FileData, Host, Message}; +use deckcraft_ui_egui::SlideApp; /// The app id in the host messages (`deckcraft:ready`). const APP: &str = "deckcraft"; -/// The name `craft-web-host` gives an open request that carries none (it cleans a host's name and -/// falls back to this): no name is no file, so the presentation opens untitled. -const NAMELESS: &str = "document"; - /// The largest file a host may send. File › Open on the desktop refuses anything over 2 GiB. /// On wasm32 a `Vec` cannot hold 2 GiB (`isize::MAX` is one byte less), so a file of exactly /// 2 GiB is refused too, before its bytes are copied. @@ -54,6 +50,7 @@ const MAX_OPEN_BYTES: f64 = 2_147_483_648.0; /// The longest user name taken from `?author=` (the preferences' own limit). const MAX_AUTHOR_CHARS: usize = 256; +/// The embedding page's connection and files waiting for the app to open them. #[derive(Clone)] pub struct Bridge { host: Rc, @@ -66,27 +63,7 @@ impl Bridge { /// `data-host="page"` on the canvas, an unframed `?host=parent` page (it stays the normal app /// with downloads), or a parent on another origin. pub fn detect(canvas: &web_sys::HtmlCanvasElement) -> Option { - let host = Host::connect(APP, canvas)?; - // An opaque origin (a file:// page in some browsers) can't be a postMessage target. - if host.mode() == craft_web_host::Mode::Parent && web_sys::window()?.location().origin().ok()? == "null" { - return None; - } - Some(Self { host: Rc::new(host), opened: Rc::default() }) - } - - /// Hand saved and exported files to the host instead of downloading them, and hear the files - /// it sends. - pub fn connect(&self, services: &mut Services, ctx: egui::Context) { - self.listen(ctx); - let bridge = self.clone(); - services.host_save = Some(Box::new(move |name: &str, bytes: &[u8], save_as: bool| bridge.post_save(name, bytes, save_as))); - // Exports and Print are copies. - let bridge = self.clone(); - services.download = Some(Box::new(move |name: &str, bytes: &[u8]| { - if let Err(e) = bridge.post_save(name, bytes, false) { - log::error!("couldn't hand {name} to the page: {e}"); - } - })); + Host::connect(APP, canvas).map(|host| Self { host: Rc::new(host), opened: Rc::default() }) } /// `?author=`: the host's name for the user signs new comments. @@ -97,6 +74,7 @@ impl Bridge { } } + /// Tell the embedding page it can send files after the runner has started. pub fn post_ready(&self) { let _ = self.host.post_ready(env!("CARGO_PKG_VERSION"), false); } @@ -106,7 +84,7 @@ impl Bridge { let _ = self.host.post_failed(error, None); } - /// Before each frame: open the files the host sent. + /// Opens the files the page sent since the last call. pub fn open_files(&self, app: &mut SlideApp) { let opened = std::mem::take(&mut *self.opened.borrow_mut()); for (name, bytes) in opened { @@ -120,28 +98,22 @@ impl Bridge { self.host.post_dirty(app.session.documents().iter().any(|d| d.is_dirty())); } - fn post_save(&self, path: &str, bytes: &[u8], save_as: bool) -> Result<(), String> { - let name = std::path::Path::new(path).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| path.to_string()); - self.host.post_save(&name, bytes, None, save_as) - } - /// Hear `deckcraft:open` and queue the file for the next frame. - fn listen(&self, ctx: egui::Context) { + pub fn listen(&self, ctx: egui::Context) { let opened = self.opened.clone(); let host = self.host.clone(); self.host.listen(move |message| { let Message::Open { name, data } = message else { return }; if data.size() >= MAX_OPEN_BYTES { - log::warn!("host file {name} is 2 GiB or larger; not opened"); - let _ = host.post_failed(&format!("{name} is 2 GiB or larger, which DeckCraft's web build cannot open"), None); + let label = name.as_deref().unwrap_or("a file"); + log::warn!("host file {label} is 2 GiB or larger; not opened"); + let _ = host.post_failed(&format!("{label} is 2 GiB or larger, which DeckCraft's web build cannot open"), None); return; } let FileData::Bytes(array) = data else { - log::warn!("host file {name} came as a File; DeckCraft reads bytes only; not opened"); + log::warn!("host file {} came as a File; DeckCraft reads bytes only; not opened", name.as_deref().unwrap_or("a file")); return; }; - // No name is no file: the presentation opens untitled, never under an invented name. - let name = (name != NAMELESS).then_some(name); opened.borrow_mut().push((name, array.to_vec())); ctx.request_repaint(); }); diff --git a/apps/deckcraft-web/src/main.rs b/apps/deckcraft-web/src/main.rs index 6964162df..5d09c5a3c 100644 --- a/apps/deckcraft-web/src/main.rs +++ b/apps/deckcraft-web/src/main.rs @@ -6,11 +6,8 @@ //! //! Differences from the desktop app: //! - no TCP control channel (browsers can't listen on sockets); -//! - File → Open and Insert → Pictures/Audio/Video use the browser file picker; bytes arrive -//! asynchronously through `Services::inbox`, applied to the document, slide and operation -//! that started the pick (a dismissed picker or a closed document drops the file); -//! - Save and Export trigger a browser download (or go to the framing page with `?host=parent`); -//! - dropped files are read asynchronously by `web::WebShell` and delivered through the inbox; +//! - pickers, saves and drops use the framework's browser services, which read files asynchronously; +//! - Save and Export reach the framing page through `Files` when hosted, or use browser saves; //! - preferences are not persisted. //! //! URL query flags: `?webgl` forces the WebGL2 backend instead of WebGPU; `?blank` starts with an diff --git a/apps/deckcraft-web/src/presenter.rs b/apps/deckcraft-web/src/presenter.rs index 40cafe849..bb5756e1c 100644 --- a/apps/deckcraft-web/src/presenter.rs +++ b/apps/deckcraft-web/src/presenter.rs @@ -1,306 +1,191 @@ -//! Same-origin popup transport. Each window starts its own eframe/WASM runner. -use deckcraft_ui_egui::presenter::{Command, DeltaCache, Host, Snapshot, View}; -use std::{ - cell::RefCell, - collections::VecDeque, - rc::{Rc, Weak}, -}; -use wasm_bindgen::{JsCast, closure::Closure}; +//! Browser presenter peer; the audience owns playback and this page emits requests. -const MAX_MESSAGE: usize = 16 * 1024 * 1024; -const MAX_COMMANDS: usize = 64; -const PREFIX: &str = "#deckcraft-presenter="; -fn error(e: wasm_bindgen::JsValue) -> String { - format!("{e:?}") -} -fn origin() -> Result { - web_sys::window().ok_or("No browser window")?.location().origin().map_err(error) -} -pub fn token() -> Option { - let hash = web_sys::window()?.location().hash().ok()?; - let token = hash.strip_prefix(PREFIX)?; - (!token.is_empty() && token.len() < 128).then(|| token.to_owned()) -} -fn same_source(event: &web_sys::MessageEvent, window: &web_sys::Window, expected_origin: &str) -> bool { - event.origin() == expected_origin && event.source().is_some_and(|source| js_sys::Object::is(source.as_ref(), window.as_ref())) -} -fn send(window: &web_sys::Window, origin: &str, value: serde_json::Value) -> Result<(), String> { - let text = serde_json::to_string(&value).map_err(|e| e.to_string())?; - if text.len() > MAX_MESSAGE { - return Err("Presenter message is too large".into()); - } - window.post_message(&wasm_bindgen::JsValue::from_str(&text), origin).map_err(error) -} -struct State { - popup: Option, - token: String, - commands: VecDeque, - ready: bool, - refresh_images: bool, -} -pub struct BrowserHost { - state: Rc>, - origin: String, - listener: Closure, - button: Option<(web_sys::HtmlElement, Closure)>, - images: DeltaCache, -} -impl BrowserHost { - pub fn new(ctx: egui::Context) -> Result { - let window = web_sys::window().ok_or("No browser window")?; - let origin = origin()?; - let state = Rc::new(RefCell::new(State { popup: None, token: String::new(), commands: VecDeque::new(), ready: false, refresh_images: true })); - let weak = Rc::downgrade(&state); - let expected = origin.clone(); - let listener = Closure::new(move |event: web_sys::MessageEvent| { - let Some(state) = weak.upgrade() else { return }; - let Ok(mut state) = state.try_borrow_mut() else { return }; - let Some(popup) = state.popup.as_ref() else { return }; - if !same_source(&event, popup, &expected) { - return; - } - let Some(text) = event.data().as_string().filter(|s| s.len() <= 8192) else { return }; - let Ok(value) = serde_json::from_str::(&text) else { return }; - if value.get("token").and_then(|v| v.as_str()) != Some(state.token.as_str()) { - return; - } - match value.get("kind").and_then(|v| v.as_str()) { - Some("ready") => { - state.ready = true; - state.refresh_images = true; - } - Some("command") if state.commands.len() < MAX_COMMANDS => { - if let Some(command) = value.get("command").and_then(|v| serde_json::from_value(v.clone()).ok()) { - state.commands.push_back(command); - } - } - _ => {} - } - ctx.request_repaint(); - }); - window.add_event_listener_with_callback("message", listener.as_ref().unchecked_ref()).map_err(error)?; - Ok(Self { state, origin, listener, button: None, images: DeltaCache::default() }) - } - fn remove_button(&mut self) { - if let Some((button, callback)) = self.button.take() { - let _ = button.remove_event_listener_with_callback("click", callback.as_ref().unchecked_ref()); - button.remove(); - } - } - fn recovery_button(&mut self) { - if self.button.is_some() { - return; - } - let Some(document) = web_sys::window().and_then(|w| w.document()) else { return }; - let Some(body) = document.body() else { return }; - let Ok(element) = document.create_element("button") else { return }; - let Ok(button) = element.dyn_into::() else { return }; - button.set_text_content(Some("Open presenter window")); - let _ = button.set_attribute("style", "position:fixed;top:12px;right:12px;z-index:9999;padding:12px;color:white;background:#333;border:1px solid #aaa;border-radius:4px;cursor:pointer"); - let weak: Weak> = Rc::downgrade(&self.state); - let button_copy = button.clone(); - let callback = Closure::new(move |_event: web_sys::Event| { - if let Some(state) = weak.upgrade() { - match open_popup(&state) { - Ok(()) => { - button_copy.set_text_content(Some("Opening presenter window…")); - } - Err(_) => { - button_copy.set_text_content(Some("Popup blocked. Allow popups, then click to retry.")); - } - } - } - }); - if button.add_event_listener_with_callback("click", callback.as_ref().unchecked_ref()).is_ok() && body.append_child(&button).is_ok() { - self.button = Some((button, callback)); - } else { - let _ = button.remove_event_listener_with_callback("click", callback.as_ref().unchecked_ref()); - button.remove(); - } - } -} -fn open_popup(state: &Rc>) -> Result<(), String> { - let window = web_sys::window().ok_or("No browser window")?; - let mut state = state.try_borrow_mut().map_err(|_| "Presenter is busy")?; - if let Some(popup) = &state.popup - && !popup.closed().unwrap_or(true) - { - let _ = popup.focus(); - return Ok(()); - } - let token = format!("{}-{}", js_sys::Date::now(), js_sys::Math::random()); - let url = web_sys::Url::new(&window.location().href().map_err(error)?).map_err(error)?; - url.set_hash(&format!("{PREFIX}{token}")); - let popup = window - .open_with_url_and_target_and_features(&url.href(), "_blank", "popup,width=1100,height=700") - .map_err(error)? - .ok_or("Presenter popup was blocked. Use Open presenter window to retry.")?; - if popup.closed().unwrap_or(true) { - return Err("Browser isolation prevented connecting the presenter window".into()); - } - state.popup = Some(popup); - state.token = token; - state.commands.clear(); - state.ready = false; - Ok(()) -} -impl Host for BrowserHost { - fn open(&mut self) -> Result<(), String> { - self.close(); - let result = open_popup(&self.state); - if result.is_err() { - self.recovery_button(); - } - result - } - fn is_open(&self) -> bool { - self.state.borrow().popup.as_ref().is_some_and(|w| !w.closed().unwrap_or(true)) - } - fn commands(&mut self) -> Vec { - self.state.borrow_mut().commands.drain(..).collect() - } - fn update(&mut self, snapshot: Snapshot) { - if !self.is_open() { - self.recovery_button(); - return; - } - self.remove_button(); - let mut state = self.state.borrow_mut(); - if !state.ready { - return; - } - if let Some(popup) = state.popup.clone() { - let token = state.token.clone(); - let sent = self.images.send(snapshot, &token, state.refresh_images, |delta, current_changed, next_changed| { - send( - &popup, - &self.origin, - serde_json::json!({"kind":"snapshot", "token":token, "snapshot":delta, - "currentChanged":current_changed, "nextChanged":next_changed}), - ) - }); - if sent.is_ok() { - state.refresh_images = false; - } - } - } - fn close(&mut self) { - self.remove_button(); - let mut state = self.state.borrow_mut(); - if let Some(window) = state.popup.take() { - let _ = window.close(); - } - state.commands.clear(); - state.ready = false; - state.token.clear(); - } -} -impl Drop for BrowserHost { - fn drop(&mut self) { - self.close(); - if let Some(window) = web_sys::window() { - let _ = window.remove_event_listener_with_callback("message", self.listener.as_ref().unchecked_ref()); - } - } +use craft::i18n::Word; +use craft::ui::contract::{Politeness, Props as _, Show as _}; +use craft::ui::fonts::{I18nScripts, UiFonts}; +use craft::ui::notices::{Notice, NoticeLayout}; +use craft::ui::primitives::{CachedTexture, Revision, TextureStore, TextureStoreOptions}; +use craft::ui::runtime::env::WindowKey; +use craft::ui::runtime::frame::FrameInput; +use craft::ui::shell::{AppShell, embed}; +use craft::web_host::link::{LinkLimits, LinkState, WindowLink}; +use craft::web_host::popup::{PopupOpener, PopupPeer}; +use deckcraft_ui_egui::presenter::{Command, Preview, Snapshot, SnapshotDelta, merge}; +// PLAN: assumed pub const SHOW_SCOPE: craft::ui::runtime::commands::CommandScope in presenter_view (show-w7) +use deckcraft_ui_egui::presenter_view::{NextPic, PresenterModel, PreviewPic, SHOW_SCOPE, presenter_body}; +use deckcraft_ui_egui::show::{Blank, GridSource}; + +const MAX_SNAPSHOT: usize = 16 * 1024 * 1024; +const MAX_COMMAND: usize = 8192; + +fn limits(max_in: usize, max_out: usize) -> LinkLimits { + let mut limits = LinkLimits::default(); + limits.max_in = max_in; + limits.max_out = max_out; + limits.max_queued = 64; + limits } -pub struct Popup { - token: String, - origin: String, - opener: web_sys::Window, - snapshot: Rc>>, - last_received: Rc>, - listener: Closure, - view: View, +/// Creates the audience's presenter link; opening it remains a user action. +pub fn opener(ctx: &egui::Context) -> Option> { + let ctx = ctx.clone(); + PopupOpener::new("deckcraft", "popup,width=1100,height=700", limits(MAX_COMMAND, MAX_SNAPSHOT), move || ctx.request_repaint()) + .ok() + .map(|link| Box::new(link) as Box) } -impl Popup { - pub fn new(token: String, ctx: egui::Context) -> Result { - let window = web_sys::window().ok_or("No browser window")?; - // `opener` is a WindowProxy from another realm; instanceof Window can fail across - // realms. The browser API supplies a WindowProxy or null, and messages still verify - // exact source identity and origin before any data is accepted. - let opener = window.opener().map_err(error)?; - if opener.is_null() || opener.is_undefined() { - return Err("The audience window is unavailable".into()); - } - let opener: web_sys::Window = opener.unchecked_into(); - let origin = origin()?; - let snapshot: Rc>> = Rc::new(RefCell::new(None)); - let last_received = Rc::new(RefCell::new(js_sys::Date::now())); - let received = last_received.clone(); - let target = snapshot.clone(); - let expected_origin = origin.clone(); - let expected_opener = opener.clone(); - let expected_token = token.clone(); - let listener = Closure::new(move |event: web_sys::MessageEvent| { - if !same_source(&event, &expected_opener, &expected_origin) { - return; - } - let Some(text) = event.data().as_string().filter(|s| s.len() <= MAX_MESSAGE) else { return }; - let Ok(value) = serde_json::from_str::(&text) else { return }; - if value.get("token").and_then(|v| v.as_str()) != Some(expected_token.as_str()) - || value.get("kind").and_then(|v| v.as_str()) != Some("snapshot") - { - return; - } - if let Some(mut data) = value.get("snapshot").and_then(|v| serde_json::from_value::(v.clone()).ok()) { - if let Some(previous) = target.borrow().as_ref() { - if value.get("currentChanged").and_then(|v| v.as_bool()) == Some(false) { - data.current = previous.current.clone(); - } - if value.get("nextChanged").and_then(|v| v.as_bool()) == Some(false) { - data.next = previous.next.clone(); - } - if data.slides.is_none() { - data.slides = previous.slides.clone(); - } - } - *target.borrow_mut() = Some(data); - *received.borrow_mut() = js_sys::Date::now(); - ctx.request_repaint(); - } - }); - window.add_event_listener_with_callback("message", listener.as_ref().unchecked_ref()).map_err(error)?; - if let Some(document) = window.document() { + +// Separate variants keep slide zero distinct from either large preview. +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +enum Picture { + Current, + Next, + Slide(usize), +} + +/// A presenter page with its own show command scope and no playback state. +pub struct PopupApp { + peer: PopupPeer, + snapshot: Option, + /// The number of the last delta received. + seq: Option, + textures: TextureStore, + current_revision: u64, + next_revision: u64, + slides_revision: u64, +} + +impl PopupApp { + /// Installs the page runtime and connects to its same-origin audience window. + pub fn new(ctx: &egui::Context, install: craft::ui::runtime::InstallSpec) -> Result { + embed::install(ctx, install, &UiFonts::new(&I18nScripts)).map_err(|error| error.to_string())?; + let wake = ctx.clone(); + let peer = PopupPeer::connect("deckcraft", limits(MAX_SNAPSHOT, MAX_COMMAND), move || wake.request_repaint()) + .ok_or_else(|| "The audience window is unavailable".to_owned())?; + if let Some(document) = web_sys::window().and_then(|window| window.document()) { document.set_title("Presenter View — DeckCraft"); } - let popup = Self { token, origin, opener, snapshot, last_received, listener, view: View::default() }; - send(&popup.opener, &popup.origin, serde_json::json!({"kind":"ready","token":popup.token}))?; - Ok(popup) + Ok(Self { + peer, + snapshot: None, + seq: None, + textures: TextureStore::in_context(ctx, "deckcraft.popup", TextureStoreOptions::frames()), + current_revision: 0, + next_revision: 0, + slides_revision: 0, + }) } -} -impl eframe::App for Popup { - fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) { - let snapshot = self.snapshot.borrow(); - let notes = snapshot.as_ref().map_or("", |snapshot| snapshot.notes.as_str()); - if !self.view.prepare(ui.ctx(), notes) { - return; - } - ui.ctx().request_repaint_after(std::time::Duration::from_millis(500)); - if self.opener.closed().unwrap_or(true) { - ui.heading("The audience window has closed."); - return; - } - if js_sys::Date::now() - *self.last_received.borrow() > 10_000.0 { - ui.heading("The audience window is not responding."); - ui.label("Return to the audience window to resume the connection."); - return; - } - egui::CentralPanel::default().show(ui, |ui| { - if let Some(snapshot) = snapshot.as_ref() { - for command in self.view.ui(ui, snapshot) { - let _ = send(&self.opener, &self.origin, serde_json::json!({"kind":"command","token":self.token,"command":command})); - } - } else { - ui.label("Waiting for the audience window…"); + + fn receive(&mut self, ctx: &egui::Context) { + // take drains only this pass's arrivals; a second pass sees no replay of earlier deltas. + for payload in self.peer.take() { + let Some(delta) = SnapshotDelta::from_payload(&payload) else { continue }; + if self.seq.is_some_and(|seq| delta.seq != seq.wrapping_add(1)) { + // A full inbox dropped a delta, which may have carried an image: ask for every image again. + let _ = self.peer.post(&Command::Resync.to_payload()); } - }); + self.seq = Some(delta.seq); + if delta.current_changed { + self.current_revision = self.current_revision.wrapping_add(1); + self.textures.forget(ctx, &Picture::Current); + } + if delta.next_changed { + self.next_revision = self.next_revision.wrapping_add(1); + self.textures.forget(ctx, &Picture::Next); + } + if delta.snapshot.slides.is_some() { + self.slides_revision = self.slides_revision.wrapping_add(1); + self.textures.retain(ctx, |key| !matches!(key, Picture::Slide(_))); + } + self.snapshot = Some(merge(self.snapshot.as_ref(), delta)); + } } -} -impl Drop for Popup { - fn drop(&mut self) { - if let Some(window) = web_sys::window() { - let _ = window.remove_event_listener_with_callback("message", self.listener.as_ref().unchecked_ref()); + + fn picture(&self, ctx: &egui::Context, key: Picture, revision: u64, preview: Option<&Preview>) -> Option { + let preview = preview?; + let revision = Revision::new(revision); + self.textures.state(ctx, &key, revision).shown().or_else(|| Some(self.textures.put(ctx, key, revision, preview.image()?))) + } + + fn page(&mut self, ui: &mut egui::Ui, cx: &mut craft::ui::contract::BodyCx<'_>) { + let notice = if self.peer.state() == LinkState::Closed { + Some(("The audience window has closed.", "")) + } else if js_sys::Date::now() - self.peer.last_heard() > 10_000.0 { + Some(("The audience window is not responding.", "Return to the audience window to resume the connection.")) + } else if self.snapshot.is_none() { + Some(("Waiting for the audience window…", "")) + } else { + None + }; + if let Some((title, detail)) = notice { + Notice::new(craft::theme::variant::Tone::Info, Word::plain(detail)) + .id_salt("audience-link-state") + .title(Word::plain(title)) + .layout(NoticeLayout::Centred) + .announce(Politeness::Polite) + .show(ui); + return; + } + let Some(snapshot) = &self.snapshot else { return }; + let current = self.picture(ui.ctx(), Picture::Current, self.current_revision, snapshot.current.as_ref()); + let next = self.picture(ui.ctx(), Picture::Next, self.next_revision, snapshot.next.as_ref()); + // Slide(0), Slide(1), Slide(2) remain tiles 1, 2, 3; a malformed image must not shift later picks. + let slides: Vec<_> = snapshot + .slides + .as_deref() + .unwrap_or_default() + .iter() + .enumerate() + .map(|(index, preview)| self.picture(ui.ctx(), Picture::Slide(index), self.slides_revision, Some(preview))) + .collect::>() + .unwrap_or_default(); + let model = PresenterModel { + aspect: snapshot.aspect, + slide: snapshot.slide, + total: snapshot.total, + ended: snapshot.ended, + elapsed: snapshot.elapsed, + paused: snapshot.paused, + notes: &snapshot.notes, + notes_px: snapshot.notes_px, + blank: match snapshot.blank.as_deref() { + Some("black") => Some(Blank::Black), + Some("white") => Some(Blank::White), + _ => None, + }, + grid: snapshot.grid, + zoom_armed: snapshot.zoom_armed, + zoomed: snapshot.zoomed, + zoom_frame: None, + current: current.as_ref().map_or(PreviewPic::Pending, PreviewPic::Shown), + next: if let Some(next) = &next { + NextPic::Shown(next) + } else if snapshot.slide.saturating_add(1) >= snapshot.total { + NextPic::End + } else { + NextPic::Pending + }, + slides: GridSource::Pictures(&slides), + }; + let mut out = Vec::new(); + presenter_body(ui, cx, &model, &mut out); + for command in out { + let _ = self.peer.post(&command.to_payload()); } } } + +impl eframe::App for PopupApp { + fn raw_input_hook(&mut self, ctx: &egui::Context, _input: &mut egui::RawInput) { + embed::before_input(ctx, |_| FrameInput::new(deckcraft_ui_egui::theme::root_env())); + } + + fn logic(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) { + embed::logic(ctx, || embed::CloseDecision::Close); + } + + fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) { + self.receive(ui.ctx()); + ui.ctx().request_repaint_after(std::time::Duration::from_millis(500)); + AppShell::new(WindowKey::main()).page(true, SHOW_SCOPE, |_| None, |ui, cx, app: &mut Self| app.page(ui, cx)).show(ui, self); + } +} diff --git a/apps/deckcraft-web/src/web.rs b/apps/deckcraft-web/src/web.rs index 86e5e651b..3b4430b5a 100644 --- a/apps/deckcraft-web/src/web.rs +++ b/apps/deckcraft-web/src/web.rs @@ -1,13 +1,21 @@ -//! The browser shell: web `Services`, drag-and-drop, and the eframe web runner. +//! The browser shell: platform services, the embedding page, and the eframe web runner. -use deckcraft_engine::Session; -use deckcraft_ui_egui::{Inbox, InboxEvent, InboxFile, Services, SlideApp}; +use std::sync::Arc; + +use craft::automation::control::ControlChannel; +use craft::host::target::ShellInfo; +use craft::host::{AppInfo, Host, Wake}; +use craft::platform::browser_files::BrowserFiles; +use craft::platform::open::{DroppedFile, FileIntake, IntakeSender}; +use craft::settings::Location; +use craft::ui::runtime::InstallSpec; +use craft::ui::runtime::env::SystemReader; +use craft::web_host::link::role_token; +use craft::window::policy::Frame; +use craft::window::system::SystemWindows; +use deckcraft_ui_egui::{Platform, SlideApp}; use wasm_bindgen::JsCast as _; -const PRESENTATION_EXTS: &[&str] = &["deckcraft", "pptx", "potx", "ppsx", "ppt", "pot", "pps", "txt", "md"]; -const PICTURE_EXTS: &[&str] = &["png", "jpg", "jpeg", "gif", "webp", "bmp", "tif", "tiff"]; -const AUDIO_EXTS: &[&str] = &["wav", "mp3", "m4a", "aac", "flac", "ogg", "opus", "aif", "aiff"]; -const VIDEO_EXTS: &[&str] = &["mp4", "m4v", "mov", "webm"]; const CANVAS_ID: &str = "deckcraft_canvas"; const LOADING_ID: &str = "deckcraft_loading"; @@ -15,6 +23,7 @@ const LOADING_ID: &str = "deckcraft_loading"; /// build the sample or blank deck, and replace the loading element when launch finishes. pub fn start() { eframe::WebLogger::init(log::LevelFilter::Info).ok(); + craft::font_catalog::app::start(craft::font_catalog::app::AppFonts { store_poll: None, ..Default::default() }); wasm_bindgen_futures::spawn_local(async { let Some(document) = web_sys::window().and_then(|w| w.document()) else { log::error!("no document"); @@ -28,7 +37,8 @@ pub fn start() { // opens presentations in it and stores what it saves (`host`); `data-host="page"` on the // canvas opts a page in that runs DeckCraft in its own document. The presenter popup is // never the framed page. - let hosted = crate::presenter::token().is_none(); + let hash = web_sys::window().and_then(|window| window.location().hash().ok()).unwrap_or_default(); + let hosted = role_token(&hash).is_none(); let bridge = if hosted { crate::host::Bridge::detect(&canvas) } else { None }; if hosted && bridge.is_none() && query_param("host").as_deref() == Some("parent") { log::warn!("?host=parent needs a framing page on the same origin; saves download instead"); @@ -48,20 +58,38 @@ pub fn start() { if let Some(rs) = &cc.wgpu_render_state { log::info!("deckcraft-web {}: wgpu backend {:?}", env!("CARGO_PKG_VERSION"), rs.adapter.get_info().backend); } - deckcraft_ui_egui::install_ime_pass_hooks(&cc.egui_ctx); - // The presenter popup draws DeckCraft's presenter view only, with no framework component, so - // it runs without the framework runtime. - if let Some(token) = crate::presenter::token() { - let presenter = crate::presenter::Popup::new(token, cc.egui_ctx.clone()).map_err(std::io::Error::other)?; + let shell_info = ShellInfo::default(); + let repaint = cc.egui_ctx.clone(); + let install = InstallSpec::new(shell_info, Arc::new(SystemWindows)) + .system(SystemReader::start(move || repaint.request_repaint())) + .app_id(deckcraft_ui_egui::os_window::app_id()); + if role_token(&hash).is_some() { + let presenter = crate::presenter::PopupApp::new(&cc.egui_ctx, install).map_err(std::io::Error::other)?; return Ok(Box::new(presenter) as Box); } - deckcraft_ui_egui::framework::install_headless(&cc.egui_ctx); - let inbox: Inbox = Inbox::default(); - let mut services = services(inbox.clone(), cc.egui_ctx.clone()); + let wake = cc.egui_ctx.clone(); + let files = BrowserFiles::new(move || wake.request_repaint()); + let files = if app_bridge.is_some() { files.page_saves(craft::web_host::files::page_save) } else { files }; + let host = Host::builder(AppInfo { id: "deckcraft", name: "DeckCraft", version: env!("CARGO_PKG_VERSION") }) + .files(Arc::new(files)) + .build(); + let wake = cc.egui_ctx.clone(); + let (intake, drops) = FileIntake::new(Wake::new(move || wake.request_repaint())); + let platform = Platform { + install, + host, + settings: Location::Memory, + intake: Some(intake), + audio_out: None, + control: Some(ControlChannel::new(crate::api::install(cc.egui_ctx.clone()))), + frame: Frame::Native, + at_exit: None, + }; if let Some(bridge) = &app_bridge { - bridge.connect(&mut services, cc.egui_ctx.clone()); + bridge.listen(cc.egui_ctx.clone()); } - let mut app = SlideApp::new(Session::new(), services); + let mut app = SlideApp::new(&cc.egui_ctx, platform).map_err(|error| std::io::Error::other(error.to_string()))?; + app.services.presenter = crate::presenter::opener(&cc.egui_ctx); // In host mode the parent sends the presentation to edit; no sample meanwhile. if app_bridge.is_some() { if let Err(e) = app.start_for_host() { @@ -82,8 +110,7 @@ pub fn start() { { crate::host::Bridge::set_author(&mut app, &author); } - crate::api::install(&mut app, cc.egui_ctx.clone()); - Ok(Box::new(WebShell { app, inbox, bridge: app_bridge })) + Ok(Box::new(WebShell { app, bridge: app_bridge, drops })) }), ) .await; @@ -97,7 +124,20 @@ pub fn start() { if let Some(el) = document.get_element_by_id(LOADING_ID) { match result { Ok(()) => el.remove(), - Err(e) => el.set_inner_html(&format!("

DeckCraft failed to start: {e:?}

A browser with WebGPU or WebGL2 is required.

")), + Err(e) => { + el.set_text_content(None); + for text in [format!("DeckCraft failed to start: {e:?}"), "A browser with WebGPU or WebGL2 is required.".to_owned()] { + match document.create_element("p") { + Ok(paragraph) => { + paragraph.set_text_content(Some(&text)); + if let Err(error) = el.append_child(¶graph) { + log::error!("couldn't display startup failure: {error:?}"); + } + } + Err(error) => log::error!("couldn't display startup failure: {error:?}"), + } + } + } } } }); @@ -117,13 +157,13 @@ fn query_has(key: &str) -> bool { web_sys::UrlSearchParams::new_with_str(&query()).is_ok_and(|q| q.has(key)) } -/// Wraps the app to read dropped files asynchronously (browsers can't read them synchronously) -/// and feed them through the inbox. +/// Opens the embedding page's files before app logic and reports dirtiness afterwards. struct WebShell { app: SlideApp, - inbox: Inbox, /// The parent page that keeps the files (`?host=parent`). bridge: Option, + /// Feeds the files dropped on the canvas into the app's intake once the browser has read them. + drops: IntakeSender, } impl eframe::App for WebShell { @@ -134,7 +174,6 @@ impl eframe::App for WebShell { bridge.open_files(&mut self.app); } self.app.logic(ctx); - self.app.close_path(ctx); if let Some(bridge) = &self.bridge { bridge.report_dirty(&self.app); } @@ -145,123 +184,33 @@ impl eframe::App for WebShell { } } - /// Consume browser drops with fresh input, capture the identity before the asynchronous read, - /// and deliver the id, name, and bytes through the inbox. + /// Delegate only this pass's input to the app's framework hooks. Browsers read dropped files + /// only asynchronously: this pass's drops are taken here and reach the app's intake, in drop + /// order, once read. A file that cannot be read arrives without bytes, which the app reports. fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) { - // Browsers cannot read dropped files synchronously. Consume this pass's drops here, with - // fresh input, and capture the document/slide before the asynchronous read finishes. - for f in std::mem::take(&mut raw.dropped_files) { - let id = self.app.begin_external_file("drop"); - let inbox = self.inbox.clone(); - let ctx = ctx.clone(); + let dropped = std::mem::take(&mut raw.dropped_files); + if !dropped.is_empty() { + let drops = self.drops.clone(); wasm_bindgen_futures::spawn_local(async move { - let name = f.path().file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| "dropped".into()); - match f.bytes_async().await { - Ok(bytes) => { - push_inbox(&inbox, InboxEvent::File(InboxFile { id, name, bytes })); - ctx.request_repaint(); - } - Err(e) => { - log::error!("couldn't read dropped file {name}: {e}"); - push_inbox(&inbox, InboxEvent::Cancelled { id }); - ctx.request_repaint(); - } + let mut files = Vec::with_capacity(dropped.len()); + for file in dropped { + let name = file.path().file_name().map(|name| name.to_string_lossy().into_owned()).unwrap_or_default(); + let bytes = match file.bytes_async().await { + Ok(bytes) => Some(bytes.into()), + Err(error) => { + log::error!("couldn't read dropped file {name}: {error}"); + None + } + }; + files.push(DroppedFile { path: None, name, bytes }); } + drops.dropped(files); }); } self.app.raw_input_hook(ctx, raw); - self.app.before_input(ctx); } fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) { self.app.ui(ui); } } - -/// Web services: no file paths, so `pick_open`/`pick_save`/`read` stay `None` and the UI falls -/// back to `open_async` (browser picker → inbox) and `download`. -fn services(inbox: Inbox, ctx: egui::Context) -> Services { - let open_inbox = inbox.clone(); - let presenter = match crate::presenter::BrowserHost::new(ctx.clone()) { - Ok(host) => Some(Box::new(host) as Box), - Err(error) => { - log::error!("Presenter window: {error}"); - None - } - }; - Services { - presenter, - open_async: Some(Box::new(move |purpose: &str, request: u64| { - let inbox = open_inbox.clone(); - let ctx = ctx.clone(); - let dialog = match purpose { - "picture" => rfd::AsyncFileDialog::new().add_filter("Pictures", PICTURE_EXTS), - "audio" => rfd::AsyncFileDialog::new().add_filter("Audio", AUDIO_EXTS), - "video" => rfd::AsyncFileDialog::new().add_filter("Video", VIDEO_EXTS), - _ => rfd::AsyncFileDialog::new().add_filter("Presentations", PRESENTATION_EXTS), - }; - wasm_bindgen_futures::spawn_local(async move { - let Some(file) = dialog.pick_file().await else { - push_inbox(&inbox, InboxEvent::Cancelled { id: request }); - ctx.request_repaint(); - return; - }; - let bytes = file.read().await; - push_inbox(&inbox, InboxEvent::File(InboxFile { id: request, name: file.file_name(), bytes })); - ctx.request_repaint(); - }); - })), - write: Some(Box::new(|name: &str, bytes: &[u8]| download(name, bytes))), - download: Some(Box::new(|name: &str, bytes: &[u8]| { - if let Err(e) = download(name, bytes) { - log::error!("download of {name} failed: {e}"); - } - })), - inbox: Some(inbox), - ..Default::default() - } -} - -fn push_inbox(inbox: &Inbox, event: InboxEvent) { - inbox.lock().unwrap_or_else(|e| e.into_inner()).push(event); -} - -/// Trigger a browser download of `bytes` named after the last component of `path`. -fn download(path: &str, bytes: &[u8]) -> Result<(), String> { - let js = |e: wasm_bindgen::JsValue| format!("{e:?}"); - let name = std::path::Path::new(path).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| "deckcraft".into()); - let window = web_sys::window().ok_or("no window")?; - let document = window.document().ok_or("no document")?; - let parts = js_sys::Array::of1(&js_sys::Uint8Array::from(bytes)); - let opts = web_sys::BlobPropertyBag::new(); - opts.set_type(mime_for(&name)); - let blob = web_sys::Blob::new_with_u8_array_sequence_and_options(&parts, &opts).map_err(js)?; - let url = web_sys::Url::create_object_url_with_blob(&blob).map_err(js)?; - let a: web_sys::HtmlAnchorElement = document.create_element("a").map_err(js)?.dyn_into().map_err(|_| "not an anchor")?; - a.set_href(&url); - a.set_download(&name); - a.style().set_property("display", "none").map_err(js)?; - let body = document.body().ok_or("no body")?; - body.append_child(&a).map_err(js)?; - a.click(); - a.remove(); - // Revoke after the click has been dispatched; the download keeps its own reference. - let revoke = wasm_bindgen::closure::Closure::once_into_js(move || { - web_sys::Url::revoke_object_url(&url).ok(); - }); - window.set_timeout_with_callback_and_timeout_and_arguments_0(revoke.unchecked_ref(), 10_000).map_err(js)?; - Ok(()) -} - -fn mime_for(name: &str) -> &'static str { - match name.rsplit('.').next().map(str::to_ascii_lowercase).as_deref() { - Some("png") => "image/png", - Some("jpg" | "jpeg") => "image/jpeg", - Some("pdf") => "application/pdf", - Some("gif") => "image/gif", - Some("txt") => "text/plain", - Some("pptx") => "application/vnd.openxmlformats-officedocument.presentationml.presentation", - Some("deckcraft") => "application/zip", - _ => "application/octet-stream", - } -} diff --git a/apps/deckcraft/Cargo.toml b/apps/deckcraft/Cargo.toml index f4afdaf33..784bff2bc 100644 --- a/apps/deckcraft/Cargo.toml +++ b/apps/deckcraft/Cargo.toml @@ -11,9 +11,11 @@ default-run = "deckcraft" workspace = true [dependencies] +craft-nightly = { workspace = true } deckcraft-engine = { workspace = true } deckcraft-ui-egui = { workspace = true } deckcraft-media = { workspace = true } +craft = { workspace = true, features = ["ui-app", "window", "gpu-startup", "quit", "dialogs", "platform", "platform-clipboard-system", "automation", "settings", "font-catalog"] } # `clipboard` is the OS clipboard (Ctrl+C/X/V with other apps). Without it egui simulates one inside # the app; the egui 0.37 migration (#1350) dropped it from this list. eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit", "clipboard", "links", "wayland", "x11"] } @@ -30,7 +32,6 @@ winresource = "0.1" [target.'cfg(not(target_arch = "wasm32"))'.dependencies] craft-update = { workspace = true } rfd = { workspace = true } -arboard = { workspace = true, features = ["image-data"] } image = { workspace = true } cpal = "0.16" @@ -39,11 +40,7 @@ cpal = "0.16" winsafe = { version = "0.0.29", features = ["user", "shell"] } [target.'cfg(target_os = "macos")'.dependencies] -# Finder double-click, Open With, Dock drops and `open -a DeckCraft deck.pptx` arrive as a -# kAEOpenDocuments Apple event, which winit 0.30 doesn't handle. This audited crate (also used by -# GridCraft, PdfCraft and PhotoCraft) registers the handler (Objective-C interop needs unsafe, which -# our workspace forbids) behind a safe API. Pinned exactly: review the diff before bumping. -fmv-macos-events = "=0.1.0" +craft = { workspace = true, features = ["platform-apple-events"] } [target.'cfg(all(unix, not(target_os = "macos")))'.dependencies] winit = { version = "0.30", default-features = false, features = ["x11"] } diff --git a/apps/deckcraft/src/app_dirs.rs b/apps/deckcraft/src/app_dirs.rs index caa250c0e..a97e8ed48 100644 --- a/apps/deckcraft/src/app_dirs.rs +++ b/apps/deckcraft/src/app_dirs.rs @@ -8,29 +8,19 @@ //! `%APPDATA%\DeckCraft`, Linux `$XDG_CONFIG_HOME/deckcraft` or `~/.config/deckcraft`. //! //! DeckCraft has no portable mode and no `DECKCRAFT_CONFIG_DIR` override, so the stable resolution -//! is exactly the one `main.rs` used before the Nightly channel; the fence module -//! ([`crate::profile_root`]) still refuses a `DeckCraftData` folder or a `portable.txt` beside a -//! DeckCraft executable, which a hand-made portable copy could carry. +//! is exactly the one `main.rs` used before the Nightly channel; the `craft-nightly` fence +//! ([`crate::profile_root`]) still refuses a `portable.txt` marker beside a nightly executable. use std::ffi::OsString; -use std::path::{Path, PathBuf}; +use std::path::PathBuf; use std::sync::OnceLock; -/// The portable data folder name a hand-made portable copy could use. No DeckCraft package -/// writes it, but the fence refuses a profile inside one (see [`crate::profile_root`]). -pub const PORTABLE_DATA_DIR: &str = "DeckCraftData"; - /// The marker file of a portable copy, beside its executable. pub const PORTABLE_MARKERS: [&str; 1] = ["portable.txt"]; -/// The portable marker in `dir`, when it is a regular file. -pub fn portable_marker(dir: &Path) -> Option { - PORTABLE_MARKERS.iter().map(|name| dir.join(name)).find(|path| path.is_file()) -} - #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Mode { - /// The profile root chosen by the Launcher (`--launch-profile nightly-v1`). + /// The isolated Nightly profile root (from `--launch-profile nightly-v1` or direct self-isolation). Override, /// The platform convention (stable). Platform, @@ -95,26 +85,6 @@ pub fn user_dictionary() -> Option { user_dictionary_for(current()) } -/// The app's exclusive write probe: a new file created in `dir` and removed again. It never falls -/// back to another directory, so the Nightly validator can refuse a root it cannot write. -pub fn ensure_writable(dir: &Path) -> std::io::Result<()> { - // A probe left behind by an interrupted launch must not make a writable profile look - // unwritable, so each attempt uses a fresh name and a collision tries the next one. - // `create_new` still guarantees a create rather than a truncation. - for attempt in 0..8u32 { - let probe = dir.join(format!(".deckcraft-write-probe-{}-{attempt}", std::process::id())); - match std::fs::OpenOptions::new().write(true).create_new(true).open(&probe) { - Ok(file) => { - drop(file); - return std::fs::remove_file(probe); - } - Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue, - Err(error) => return Err(error), - } - } - Err(std::io::Error::new(std::io::ErrorKind::AlreadyExists, "no free write-probe name in the profile")) -} - #[cfg(test)] mod tests { use super::*; @@ -158,32 +128,4 @@ mod tests { assert!(std::ptr::eq(resolved, current())); assert_eq!(resolved.dir, config_dir()); } - - #[test] - fn permanent_probe_does_not_replace_an_existing_entry() { - let dir = std::env::temp_dir().join(format!("deckcraft-writable-{}-{}", std::process::id(), line!())); - std::fs::create_dir_all(&dir).unwrap(); - let probe = |attempt: u32| dir.join(format!(".deckcraft-write-probe-{}-{attempt}", std::process::id())); - // An entry already at the probe's name must never be truncated: the probe takes the next - // free name, and it removes only the file it created. - std::fs::write(probe(0), b"someone else's file").unwrap(); - ensure_writable(&dir).unwrap(); - assert_eq!(std::fs::read(probe(0)).unwrap(), b"someone else's file"); - assert!(!probe(1).exists()); - // Every name taken is an error, not a truncation of any of them. - for attempt in 0..8 { - std::fs::write(probe(attempt), b"someone else's file").unwrap(); - } - assert!(ensure_writable(&dir).is_err(), "no free probe name is reported, not truncated"); - for attempt in 0..8 { - assert_eq!(std::fs::read(probe(attempt)).unwrap(), b"someone else's file", "{attempt}"); - } - for attempt in 0..8 { - std::fs::remove_file(probe(attempt)).unwrap(); - } - // A folder whose stale probes were cleared is writable, and the probe leaves nothing behind. - ensure_writable(&dir).unwrap(); - assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 0); - std::fs::remove_dir_all(&dir).unwrap(); - } } diff --git a/apps/deckcraft/src/apple_events.rs b/apps/deckcraft/src/apple_events.rs deleted file mode 100644 index 172aff44e..000000000 --- a/apps/deckcraft/src/apple_events.rs +++ /dev/null @@ -1,53 +0,0 @@ -//! macOS open-documents and quit Apple events. -//! -//! Finder double-clicks, Open With, drops on the Dock icon and `open -a DeckCraft deck.pptx` don't -//! pass paths on the command line: LaunchServices sends the running (or just-launched) app a -//! `kAEOpenDocuments` ('odoc') Apple event. winit 0.30 doesn't handle it and owns the -//! `NSApplicationDelegate`. Handling it ourselves needs Objective-C class declarations, i.e. -//! `unsafe`, which this workspace forbids. The audited `fmv-macos-events` crate (also used by -//! GridCraft, PdfCraft and PhotoCraft) wraps exactly that, an `NSAppleEventManager` handler -//! registered before Finder's launch event that leaves winit's delegate alone, behind a safe -//! main-thread API. - -use deckcraft_ui_egui::SlideApp; -use fmv_macos_events::{Event, Inbox, Registration}; - -/// Keeps the Apple-event handlers registered; hold it until the event loop returns. -pub struct AppleEvents { - _registration: Registration, - inbox: Inbox, -} - -impl AppleEvents { - /// Register the handlers. Call on the main thread before the event loop starts, so the event - /// that launched the app (a Finder double-click) is caught too. - pub fn install() -> Self { - let (registration, inbox) = Registration::install(); - Self { _registration: registration, inbox } - } - - /// The queue the app drains every frame ([`poll`]); events arriving later wake `ctx`. - pub fn connect(&self, ctx: &egui::Context) -> Inbox { - let ctx = ctx.clone(); - self.inbox.set_wake(move || ctx.request_repaint()); - self.inbox.clone() - } -} - -/// Open the documents and act on the quit requests that arrived since the last frame. -pub fn poll(inbox: &Inbox, app: &mut SlideApp, ctx: &egui::Context) { - for e in inbox.drain() { - match e { - Event::Open(paths) => { - for p in paths.iter().filter_map(|p| p.to_str()) { - if let Err(e) = app.open_path(p) { - let safe_p = p.replace(['\r', '\n'], " "); - log::error!("{safe_p}: {e}"); - app.set_status(format!("Couldn't open {safe_p}: {e}")); - } - } - } - Event::Quit => ctx.send_viewport_cmd(egui::ViewportCommand::Close), - } - } -} diff --git a/apps/deckcraft/src/audio.rs b/apps/deckcraft/src/audio.rs index afa74a6ac..eb4b5bac0 100644 --- a/apps/deckcraft/src/audio.rs +++ b/apps/deckcraft/src/audio.rs @@ -120,18 +120,4 @@ mod tests { keep_stream_error(&slot, &"a later error"); assert_eq!(take_stream_error(&slot).as_deref(), Some("a later error")); } - - #[test] - fn a_poisoned_slot_still_reports() { - let slot = ErrorSlot::default(); - keep_stream_error(&slot, &"lost"); - let s = slot.clone(); - let _ = std::thread::spawn(move || { - let _g = s.lock(); - panic!("poison the slot"); - }) - .join(); - assert!(slot.is_poisoned()); - assert_eq!(take_stream_error(&slot).as_deref(), Some("lost")); - } } diff --git a/apps/deckcraft/src/build_flavor.rs b/apps/deckcraft/src/build_flavor.rs index fb05b758c..04b16966d 100644 --- a/apps/deckcraft/src/build_flavor.rs +++ b/apps/deckcraft/src/build_flavor.rs @@ -1,31 +1,13 @@ //! Build-time channel is distinct from a launch selector. A runtime environment cannot promote a stable build. -use crate::launch_profile::Profile; -use std::ffi::OsString; -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum BuildFlavor { - Stable, - NightlyV1, -} +pub use craft_nightly::BuildFlavor; pub const COMPILED: BuildFlavor = if cfg!(deckcraft_nightly_v1) { BuildFlavor::NightlyV1 } else { BuildFlavor::Stable }; -pub fn require_profile(flavor: BuildFlavor, profile: &Profile) -> Result<(), String> { - match (flavor, profile.is_nightly()) { - (BuildFlavor::NightlyV1, false) => Err("Open DeckCraft Nightly from ArtCraft Launcher".into()), - (BuildFlavor::Stable, true) => Err("This is a stable DeckCraft build; nightly-v1 requires the nightly build".into()), - _ => Ok(()), - } -} - pub fn needs_native_error(flavor: BuildFlavor, desktop_session: bool) -> bool { desktop_session && flavor == BuildFlavor::NightlyV1 } -pub fn version_query(args: &[OsString]) -> bool { - matches!(args, [arg] if arg == "--version" || arg == "-V") -} - pub fn version(flavor: BuildFlavor, stable: &str) -> String { match flavor { BuildFlavor::Stable => stable.to_owned(), @@ -35,7 +17,10 @@ pub fn version(flavor: BuildFlavor, stable: &str) -> String { #[cfg(test)] mod tests { + use std::ffi::OsString; + use super::*; + #[test] fn only_a_nightly_desktop_refusal_requests_a_native_dialog() { assert!(needs_native_error(BuildFlavor::NightlyV1, true)); @@ -45,28 +30,51 @@ mod tests { } #[test] - fn nightly_build_without_a_profile_is_refused_before_startup() { - let started = std::cell::Cell::new(false); - let result = require_profile(BuildFlavor::NightlyV1, &Profile::Stable).map(|()| started.set(true)); - assert!(result.unwrap_err().contains("ArtCraft Launcher")); - assert!(!started.get()); + fn nightly_direct_launch_self_isolates_into_canonical_profile_root() { + let spec = crate::profile_root::spec(); + let expected_root = craft_nightly::canonical_profile_root(crate::profile_root::APP_ID).unwrap(); + let launch = craft_nightly::parse_startup( + BuildFlavor::NightlyV1, + &spec, + [OsString::from("--sample"), OsString::from("deck.pptx")], + &crate::launch_profile::startup_options(), + ) + .unwrap(); + assert_eq!(launch.profile, craft_nightly::Profile::NightlyV1(expected_root)); + assert_eq!(launch.passthrough_args, [OsString::from("--sample"), OsString::from("deck.pptx")]); } #[test] - fn stable_and_nightly_flavors_accept_only_their_own_profile() { - let nightly = Profile::NightlyV1(std::path::PathBuf::from("already validated root")); - assert!(require_profile(BuildFlavor::Stable, &Profile::Stable).is_ok()); - assert!(require_profile(BuildFlavor::Stable, &nightly).is_err()); - assert!(require_profile(BuildFlavor::NightlyV1, &nightly).is_ok()); + fn stable_flavor_rejects_nightly_launch_flags() { + let spec = crate::profile_root::spec(); + let root = if cfg!(windows) { r"C:\NightlyData\profiles\deckcraft" } else { "/nightly-data/profiles/deckcraft" }; + let result = craft_nightly::parse_startup( + BuildFlavor::Stable, + &spec, + [ + OsString::from(craft_nightly::LAUNCH_PROFILE_FLAG), + OsString::from(craft_nightly::NIGHTLY_V1_CONTRACT), + OsString::from(craft_nightly::PROFILE_ROOT_FLAG), + OsString::from(root), + ], + &crate::launch_profile::startup_options(), + ); + assert!(matches!(result, Err(craft_nightly::ProfileError::NightlyFlagsInStableBuild))); } #[test] fn nightly_version_query_is_unambiguous_and_never_reinterprets_file_arguments() { + let spec = crate::profile_root::spec(); + let opts = crate::launch_profile::startup_options(); assert_eq!(version(BuildFlavor::Stable, "0.19.0"), "0.19.0"); assert_eq!(version(BuildFlavor::NightlyV1, "0.19.0"), "0.19.0 (nightly-v1)"); - assert!(version_query(&["--version".into()])); - assert!(version_query(&["-V".into()])); - assert!(!version_query(&["--".into(), "--version".into()])); - assert!(!version_query(&[])); + assert!(craft_nightly::parse_startup(BuildFlavor::NightlyV1, &spec, [OsString::from("--version")], &opts).unwrap().is_version_query()); + assert!(craft_nightly::parse_startup(BuildFlavor::NightlyV1, &spec, [OsString::from("-V")], &opts).unwrap().is_version_query()); + assert!( + !craft_nightly::parse_startup(BuildFlavor::NightlyV1, &spec, [OsString::from("--"), OsString::from("--version")], &opts) + .unwrap() + .is_version_query() + ); + assert!(!craft_nightly::parse_startup(BuildFlavor::NightlyV1, &spec, Vec::::new(), &opts).unwrap().is_version_query()); } } diff --git a/apps/deckcraft/src/control_server.rs b/apps/deckcraft/src/control_server.rs deleted file mode 100644 index 033ae4a4f..000000000 --- a/apps/deckcraft/src/control_server.rs +++ /dev/null @@ -1,310 +0,0 @@ -//! Loopback JSON-lines control server: one request per line, one reply per line. -//! This is the transport the MCP server (`deckcraft-cli mcp --connect`) wraps. -//! -//! The server only reads requests: a line that is not a JSON object with a string `method` (an -//! HTTP request line, a stray `nc`, binary data) gets one error reply and the connection is -//! closed, so nothing sent after it runs. Every resource a client can hold is bounded -//! ([`Limits`]): simultaneous connections, request line length, queued requests, and how long a -//! socket may sit idle or blocked on a write. - -use std::io::{BufRead, BufReader, ErrorKind, Read, Write}; -use std::net::{Shutdown, TcpListener, TcpStream}; -use std::sync::Arc; -use std::sync::atomic::{AtomicUsize, Ordering}; -use std::sync::mpsc::{Receiver, SyncSender, TrySendError, sync_channel}; -use std::time::{Duration, Instant}; - -use deckcraft_ui_egui::ControlRequest; -use serde_json::{Value, json}; - -/// Resource bounds for the control server. -#[derive(Clone, Copy, Debug)] -pub struct Limits { - /// Connections served at once; more are told `busy` and closed. - pub max_clients: usize, - /// Longest request line in bytes (newline excluded); a longer one closes the connection. - pub max_line: usize, - /// Requests waiting for the UI at once; more are answered `busy`. - pub queue: usize, - /// How long a connection may go without sending a byte before it is closed. - pub idle_timeout: Duration, - /// How long a reply write may block before the connection is closed. - pub write_timeout: Duration, - /// How long a request waits for the UI's answer. - pub reply_timeout: Duration, -} - -impl Default for Limits { - fn default() -> Self { - Self { - max_clients: 16, - // Picture and media inserts carry base64 payloads: room for files of about 190 MB. - max_line: 256 * 1024 * 1024, - queue: 64, - idle_timeout: Duration::from_secs(600), - write_timeout: Duration::from_secs(30), - reply_timeout: Duration::from_secs(60), - } - } -} - -pub fn start(port: u16, ctx: egui::Context) -> Receiver { - match TcpListener::bind(("127.0.0.1", port)) { - Ok(l) => { - log::info!("control server listening on 127.0.0.1:{port}"); - serve_listener(l, Limits::default(), ctx) - } - Err(e) => { - log::error!("control server failed to bind 127.0.0.1:{port}: {e}"); - sync_channel::(0).1 - } - } -} - -/// How long the accepting thread waits after a failed accept. Accepting can keep failing, for -/// example while the process has no file descriptors left, and retrying at once would keep a -/// core busy until it recovers. -const ACCEPT_RETRY: Duration = Duration::from_millis(100); - -/// The longest a connection refused as busy is drained before it is closed. -const REFUSED_GRACE: Duration = Duration::from_millis(250); - -/// Refused connections drained at once, each on a thread of its own. Past this many, a refused -/// connection gets the busy reply and is closed without a drain. -const MAX_REFUSING: usize = 16; - -/// The connections `incoming` accepts, calling `wait` after each failed accept. -fn accepted(incoming: impl Iterator>, mut wait: impl FnMut()) -> impl Iterator { - incoming.filter_map(move |stream| stream.map_err(|_| wait()).ok()) -} - -/// Accept connections on `listener` under `limits`; requests arrive on the returned receiver. -fn serve_listener(listener: TcpListener, limits: Limits, ctx: egui::Context) -> Receiver { - let (tx, rx) = sync_channel::(limits.queue.max(1)); - let active = Arc::new(AtomicUsize::new(0)); - let refusing = Arc::new(AtomicUsize::new(0)); - std::thread::spawn(move || { - for mut stream in accepted(listener.incoming(), || std::thread::sleep(ACCEPT_RETRY)) { - let _ = stream.set_write_timeout(Some(limits.write_timeout)); - if active.fetch_add(1, Ordering::SeqCst) >= limits.max_clients { - active.fetch_sub(1, Ordering::SeqCst); - let _ = writeln!(stream, "{}", json!({"ok": false, "error": "busy: too many control connections"})); - refuse(stream, &refusing, limits.write_timeout.min(REFUSED_GRACE)); - continue; - } - let slot = Slot(Arc::clone(&active)); - let tx = tx.clone(); - let ctx = ctx.clone(); - let spawned = std::thread::Builder::new().name("control-client".into()).spawn(move || { - let _slot = slot; - serve(stream, &tx, &ctx, limits); - }); - if spawned.is_err() { - log::warn!("control server could not start a client thread"); - } - } - }); - rx -} - -/// Close a connection that was told it is refused. A peer that wrote a line before it read the -/// reply would see only a reset, so the connection is drained for up to `grace` first, on a -/// thread of its own: the accepting thread goes straight back to accepting. Past -/// [`MAX_REFUSING`] drains at once, the connection is closed without one. -fn refuse(stream: TcpStream, refusing: &Arc, grace: Duration) { - if refusing.fetch_add(1, Ordering::SeqCst) >= MAX_REFUSING { - refusing.fetch_sub(1, Ordering::SeqCst); - return; - } - let slot = Slot(Arc::clone(refusing)); - let spawned = std::thread::Builder::new().name("control-refused".into()).spawn(move || { - let _slot = slot; - if let Ok(read) = stream.try_clone() { - close_politely(&stream, &mut BufReader::new(read), grace); - } - }); - if spawned.is_err() { - log::warn!("control server could not start a thread to close a refused connection"); - } -} - -/// Holds one connection slot; gives it back when the client thread ends, however it ends. -struct Slot(Arc); - -impl Drop for Slot { - fn drop(&mut self) { - self.0.fetch_sub(1, Ordering::SeqCst); - } -} - -enum Line { - Text(Vec), - TooLong, - Closed, -} - -/// Read one `\n`-terminated line of at most `max` bytes without buffering more than `max + 1`. -fn read_line(r: &mut impl BufRead, max: usize) -> Line { - let mut buf = Vec::new(); - let limit = u64::try_from(max).unwrap_or(u64::MAX).saturating_add(1); - match r.by_ref().take(limit).read_until(b'\n', &mut buf) { - Ok(0) | Err(_) => Line::Closed, - Ok(_) => { - if buf.last() == Some(&b'\n') { - buf.pop(); - Line::Text(buf) - } else if buf.len() > max { - Line::TooLong - } else { - // EOF inside a line: serve what arrived, the next read reports Closed. - Line::Text(buf) - } - } - } -} - -/// One request line, parsed. -enum Parsed { - Request { - id: Value, - method: String, - params: Value, - }, - Blank, - /// Not a request: reply with this error and close the connection. - Reject(String), -} - -fn parse(bytes: &[u8]) -> Parsed { - let Ok(text) = std::str::from_utf8(bytes) else { - return Parsed::Reject("not a control request (invalid UTF-8); closing the connection".into()); - }; - let text = text.trim(); - if text.is_empty() { - return Parsed::Blank; - } - if is_http_request_line(text) { - return Parsed::Reject("HTTP is not served here: this port takes JSON lines; closing the connection".into()); - } - let msg = match serde_json::from_str::(text) { - Ok(v) => v, - Err(e) => return Parsed::Reject(format!("bad JSON ({e}); expected one JSON request object per line; closing the connection")), - }; - let Some(obj) = msg.as_object() else { - return Parsed::Reject("not a control request (expected a JSON object); closing the connection".into()); - }; - let Some(method) = obj.get("method").and_then(Value::as_str) else { - return Parsed::Reject("not a control request (missing string `method`); closing the connection".into()); - }; - Parsed::Request { - id: obj.get("id").cloned().unwrap_or(Value::Null), - method: method.to_string(), - params: obj.get("params").cloned().unwrap_or(json!({})), - } -} - -/// An HTTP/1 request line (`POST / HTTP/1.1`) or the HTTP/2 preface (`PRI * HTTP/2.0`). -fn is_http_request_line(text: &str) -> bool { - const METHODS: [&str; 10] = ["GET", "HEAD", "POST", "PUT", "DELETE", "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"]; - text.split_once(' ').is_some_and(|(method, _)| METHODS.contains(&method)) - || text.rsplit_once(' ').is_some_and(|(_, version)| version.starts_with("HTTP/")) -} - -/// Close after the last reply so the peer can still read it. A peer that had sent another line -/// before the reply arrived -- two lines in one write, which any script does -- leaves input -/// unread in the socket, and closing a socket with unread input resets the connection: the reply -/// already queued for the peer is discarded and it sees only the reset. Sending the FIN first and -/// then draining, briefly and boundedly, makes the close orderly and the reason survive. -fn close_politely(out: &TcpStream, reader: &mut BufReader, grace: Duration) { - if out.shutdown(Shutdown::Write).is_err() { - return; - } - // Enough for a pipelined line or two; a peer that keeps talking is dropped at the deadline. - // The timeout is what is left of the grace before each read, not the whole of it: a peer that - // sends a byte just before each one expires would otherwise hold this thread, and its slot, - // for close to twice as long as the deadline says. The timeout is set on the handle that - // reads: on Windows, a read timeout set on one handle of a `try_clone` pair can fail to apply - // to reads through the other. - const MAX_DRAIN: usize = 64 << 10; - let until = Instant::now() + grace; - let mut sink = [0u8; 4 << 10]; - let mut drained = 0; - while drained < MAX_DRAIN { - let left = until.saturating_duration_since(Instant::now()); - if left.is_zero() || reader.get_ref().set_read_timeout(Some(left)).is_err() { - break; - } - match reader.read(&mut sink) { - Ok(0) | Err(_) => break, - Ok(n) => drained += n, - } - } -} - -fn serve(stream: TcpStream, tx: &SyncSender, ctx: &egui::Context, limits: Limits) { - if stream.set_read_timeout(Some(limits.idle_timeout)).is_err() || stream.set_write_timeout(Some(limits.write_timeout)).is_err() { - return; - } - let Ok(read) = stream.try_clone() else { return }; - let mut out = stream; - let mut reader = BufReader::new(read); - loop { - let line = match read_line(&mut reader, limits.max_line) { - Line::Text(t) => t, - Line::TooLong => { - let _ = writeln!(out, "{}", json!({"ok": false, "error": format!("request line longer than {} bytes", limits.max_line)})); - close_politely(&out, &mut reader, limits.write_timeout); - break; - } - Line::Closed => break, - }; - let reply = match parse(&line) { - Parsed::Blank => continue, - Parsed::Reject(e) => { - // The connection closes either way, but the peer is told why first: see - // `close_politely`, without which a peer that had pipelined another line had this - // reply reset away and saw nothing. - let _ = writeln!(out, "{}", json!({"ok": false, "error": e})); - close_politely(&out, &mut reader, limits.write_timeout); - break; - } - Parsed::Request { id, method, params } => { - let (req, rrx) = ControlRequest::new(method, params); - let state = Arc::clone(&req.state); - let mut r = match tx.try_send(req) { - Ok(()) => { - ctx.request_repaint(); - match rrx.recv_timeout(limits.reply_timeout) { - Ok(v) => v, - Err(_) => { - // Give up on the request. While it was still queued this makes - // sure it never runs late (#719); if the app had already taken - // it, its outcome is unknown rather than a definite failure. - if ControlRequest::abandon(&state) { - json!({"ok": false, "error": "timeout"}) - } else { - json!({"ok": false, "error": "timeout: the app had already started the request, so it may still run; its outcome is unknown"}) - } - } - } - } - Err(TrySendError::Full(_)) => json!({"ok": false, "error": "busy: too many queued requests"}), - Err(TrySendError::Disconnected(_)) => break, - }; - if let Some(o) = r.as_object_mut() { - o.insert("id".into(), id); - } - r - } - }; - if let Err(e) = writeln!(out, "{reply}") { - if matches!(e.kind(), ErrorKind::WouldBlock | ErrorKind::TimedOut) { - log::debug!("control client stopped reading replies; closing"); - } - break; - } - } -} - -#[cfg(test)] -mod tests; diff --git a/apps/deckcraft/src/control_server/tests.rs b/apps/deckcraft/src/control_server/tests.rs deleted file mode 100644 index b83146557..000000000 --- a/apps/deckcraft/src/control_server/tests.rs +++ /dev/null @@ -1,299 +0,0 @@ -use super::*; - -/// A failed accept is followed by a wait before the next one, so a listener that keeps -/// failing does not spin, and the connections around the failures still come through. -#[test] -fn a_failed_accept_waits_before_the_next() { - let failed = || Err(std::io::Error::other("no file descriptors left")); - let incoming = vec![failed(), Ok(1), failed(), failed(), Ok(2)]; - let mut waits = 0; - let connections: Vec = super::accepted(incoming.into_iter(), || waits += 1).collect(); - assert_eq!(connections, [1, 2]); - assert_eq!(waits, 3, "one wait per failed accept"); -} -use std::net::SocketAddr; -use std::time::Instant; - -fn small() -> Limits { - Limits { - max_clients: 2, - max_line: 64, - queue: 1, - idle_timeout: Duration::from_millis(300), - write_timeout: Duration::from_millis(300), - reply_timeout: Duration::from_millis(300), - } -} - -fn server(limits: Limits) -> (SocketAddr, Receiver) { - let l = TcpListener::bind("127.0.0.1:0").unwrap(); - let addr = l.local_addr().unwrap(); - (addr, serve_listener(l, limits, egui::Context::default())) -} - -fn client(addr: SocketAddr) -> (BufReader, TcpStream) { - let s = TcpStream::connect(addr).unwrap(); - s.set_read_timeout(Some(Duration::from_secs(5))).unwrap(); - (BufReader::new(s.try_clone().unwrap()), s) -} - -fn reply(r: &mut BufReader) -> Option { - let mut s = String::new(); - match r.read_line(&mut s) { - Ok(0) | Err(_) => None, - Ok(_) => serde_json::from_str(&s).ok(), - } -} - -/// Answer every request with its method name until the server goes away. -fn ui(rx: Receiver) { - std::thread::spawn(move || { - for req in rx { - let _ = req.reply.send(json!({"ok": true, "result": req.method})); - } - }); -} - -#[test] -fn request_round_trip() { - let (addr, rx) = server(small()); - ui(rx); - let (mut r, mut w) = client(addr); - writeln!(w, r#"{{"id":7,"method":"ui.inspect"}}"#).unwrap(); - let v = reply(&mut r).unwrap(); - assert_eq!(v["id"], 7); - assert_eq!(v["result"], "ui.inspect"); -} - -/// Every reply line until the server closes the connection. -fn replies_until_closed(r: &mut BufReader) -> Vec { - std::iter::from_fn(|| reply(r)).collect() -} - -/// A browser can POST to the port: its request line closes the connection before the JSON -/// line in its body is read, so nothing is dispatched. -#[test] -fn an_http_request_closes_the_connection_before_its_body_is_dispatched() { - let (addr, rx) = server(Limits { max_line: 512, ..small() }); - let (mut r, mut w) = client(addr); - w.write_all( - b"POST / HTTP/1.1\r\nHost: 127.0.0.1\r\nContent-Type: text/plain\r\n\r\n\ - {\"id\":1,\"method\":\"engine.execute\",\"params\":{\"command\":\"slide.new\"}}\n", - ) - .unwrap(); - let replies = replies_until_closed(&mut r); - assert_eq!(replies.len(), 1, "{replies:?}"); - assert!(replies[0]["error"].as_str().unwrap().contains("closing the connection"), "{replies:?}"); - assert!(rx.try_recv().is_err(), "the body was dispatched"); -} - -#[test] -fn a_line_that_is_not_a_request_closes_the_connection() { - let (addr, rx) = server(small()); - ui(rx); - for junk in [&b"hello\n"[..], b"[1,2]\n", b"{\"id\":1}\n", b"{\"method\":5}\n", b"\xff\xfe\n", b"GET /x HTTP/1.1\n"] { - let (mut r, mut w) = client(addr); - w.write_all(junk).unwrap(); - w.write_all(b"{\"id\":2,\"method\":\"m\"}\n").unwrap(); - let replies = replies_until_closed(&mut r); - assert_eq!(replies.len(), 1, "{replies:?}"); - assert_eq!(replies[0]["ok"], false); - } - assert!(is_http_request_line("OPTIONS * HTTP/1.1")); - assert!(is_http_request_line("PRI * HTTP/2.0")); - assert!(!is_http_request_line("{\"method\":\"GET /\"}")); -} - -/// A peer that pipelines -- two lines in one write, as a script does -- still reads why its -/// line was rejected. Closing with its second line unread resets the connection and discards -/// the reply already on its way, so the peer saw nothing at all; repeated here because it -/// depended on the timing of the two. -#[test] -fn a_pipelined_peer_still_reads_why_its_line_was_rejected() { - // A slot comes back only when the thread serving a peer ends, which can be after the next - // peer connects, so every peer has a slot of its own. - const PEERS: usize = 12; - let (addr, rx) = server(Limits { max_clients: PEERS, ..small() }); - for _ in 0..PEERS { - let (mut r, mut w) = client(addr); - w.write_all(b"hello\n").unwrap(); - // A second line, written after the first as a script writes it: it races the close. - let _ = w.write_all(b"{\"id\":2,\"method\":\"m\"}\n"); - let replies = replies_until_closed(&mut r); - assert_eq!(replies.len(), 1, "{replies:?}"); - assert_eq!(replies[0]["ok"], false); - assert!(replies[0]["error"].as_str().unwrap_or_default().contains("closing the connection"), "{replies:?}"); - } - // The line after the rejected one is never dispatched, pipelined or not. - assert!(rx.try_recv().is_err(), "a line after the rejection was dispatched"); -} - -/// A peer refused because every connection is taken still reads why when it had already -/// written a line: closing with that line unread resets the connection and discards the -/// reply. Repeated because it depends on the timing of the two. -#[test] -fn a_pipelined_peer_refused_as_busy_still_reads_why() { - let (addr, rx) = server(Limits { max_clients: 1, idle_timeout: Duration::from_secs(30), ..small() }); - ui(rx); - // Take the only slot, and make sure it is being served. - let (mut hr, mut hw) = client(addr); - writeln!(hw, r#"{{"id":1,"method":"m"}}"#).unwrap(); - assert!(reply(&mut hr).is_some()); - for _ in 0..50 { - let (mut r, mut w) = client(addr); - let _ = w.write_all(b"{\"id\":2,\"method\":\"m\"}\n"); - let replies = replies_until_closed(&mut r); - assert_eq!(replies.len(), 1, "{replies:?}"); - assert!(replies[0]["error"].as_str().unwrap_or_default().starts_with("busy"), "{replies:?}"); - } -} - -/// Peers refused as busy that stay connected without sending anything do not hold up the -/// connections after them: each one's drain runs to its deadline on a thread of its own, and -/// past `MAX_REFUSING` drains at once a refused connection is closed without one. -#[test] -fn silent_refused_peers_do_not_delay_the_next_refusal() { - let (addr, rx) = server(Limits { max_clients: 1, idle_timeout: Duration::from_secs(30), ..small() }); - ui(rx); - let (mut hr, mut hw) = client(addr); - writeln!(hw, r#"{{"id":1,"method":"m"}}"#).unwrap(); - assert!(reply(&mut hr).is_some()); - // Twenty drains of 250 ms each, one after another, would take five seconds. - let silent: Vec<_> = (0..MAX_REFUSING + 4).map(|_| client(addr)).collect(); - let start = Instant::now(); - let (mut r, _w) = client(addr); - let refused = reply(&mut r).unwrap(); - assert!(refused["error"].as_str().unwrap_or_default().starts_with("busy"), "{refused}"); - assert!(start.elapsed() < Duration::from_secs(1), "refused after {:?}", start.elapsed()); - drop(silent); -} - -/// A peer that keeps its connection open after its line was rejected gives its slot back at -/// the drain deadline (the write timeout), not at the idle timeout. -#[test] -fn a_rejected_peer_that_stays_connected_frees_its_slot_at_the_deadline() { - let (addr, rx) = server(Limits { max_clients: 1, idle_timeout: Duration::from_secs(30), ..small() }); - ui(rx); - let (mut r, mut w) = client(addr); - w.write_all(b"hello\n").unwrap(); - assert_eq!(reply(&mut r).unwrap()["ok"], false); - // `w` stays open, sending nothing. - let deadline = Instant::now() + Duration::from_secs(4); - loop { - let (mut dr, mut dw) = client(addr); - writeln!(dw, r#"{{"id":2,"method":"m"}}"#).unwrap(); - if reply(&mut dr).is_some_and(|v| v["ok"] == true) { - break; - } - assert!(Instant::now() < deadline, "slot never freed"); - std::thread::sleep(Duration::from_millis(50)); - } - drop(w); -} - -#[test] -fn oversized_line_closes_connection() { - let (addr, rx) = server(small()); - ui(rx); - let (mut r, mut w) = client(addr); - w.write_all(&[b'x'; 200]).unwrap(); - let v = reply(&mut r).unwrap(); - assert!(v["error"].as_str().unwrap().contains("longer than 64")); - assert!(reply(&mut r).is_none()); -} - -#[test] -fn idle_connection_is_closed() { - let (addr, rx) = server(small()); - ui(rx); - let (mut r, mut w) = client(addr); - w.write_all(b"{\"id\":1,").unwrap(); // unterminated, then silence - let t = Instant::now(); - assert!(reply(&mut r).is_none()); - assert!(t.elapsed() < Duration::from_secs(4)); -} - -#[test] -fn connection_limit_refuses_then_frees_slot() { - // `a` sends nothing. Under a 300 ms idle timeout, a slow run could close it before the - // third peer connected, and that peer then took its slot instead of reading `busy`. - let (addr, rx) = server(Limits { idle_timeout: Duration::from_secs(30), ..small() }); - ui(rx); - let a = client(addr); - let (mut br, mut bw) = client(addr); - // Make sure both are being served before the third arrives. - writeln!(bw, r#"{{"id":1,"method":"m"}}"#).unwrap(); - assert!(reply(&mut br).is_some()); - let (mut cr, _cw) = client(addr); - let v = reply(&mut cr).unwrap(); - assert!(v["error"].as_str().unwrap().starts_with("busy")); - drop(a); - // The freed slot is reusable once the server notices the disconnect. - let deadline = Instant::now() + Duration::from_secs(4); - loop { - let (mut dr, mut dw) = client(addr); - writeln!(dw, r#"{{"id":2,"method":"m"}}"#).unwrap(); - if reply(&mut dr).is_some_and(|v| v["ok"] == true) { - break; - } - assert!(Instant::now() < deadline, "slot never freed"); - std::thread::sleep(Duration::from_millis(50)); - } -} - -#[test] -fn blocked_ui_times_out_and_full_queue_is_busy() { - let (addr, rx) = server(small()); - // No UI: the request that reaches the one-slot queue first fills it and times out; the - // other finds it full. Each connection has its own thread, so either request can be first. - let (mut ar, mut aw) = client(addr); - let (mut br, mut bw) = client(addr); - writeln!(aw, r#"{{"id":1,"method":"m"}}"#).unwrap(); - writeln!(bw, r#"{{"id":2,"method":"m"}}"#).unwrap(); - let a = reply(&mut ar).unwrap(); - let b = reply(&mut br).unwrap(); - assert_eq!((&a["id"], &b["id"]), (&json!(1), &json!(2))); - let mut errors = [a["error"].as_str().unwrap_or_default(), b["error"].as_str().unwrap_or_default()]; - errors.sort_unstable(); - assert_eq!(errors, ["busy: too many queued requests", "timeout"], "{a} {b}"); - drop(rx); -} - -/// A request that timed out while it was still queued must not run when the window resumes (#719). -#[test] -fn timed_out_request_does_not_run_when_the_window_resumes() { - let (addr, rx) = server(Limits { max_line: 512, ..small() }); - let (mut r, mut w) = client(addr); - writeln!(w, r#"{{"id":1,"method":"engine.execute","params":{{"command":"slide.new"}}}}"#).unwrap(); - let t = reply(&mut r).unwrap(); - assert_eq!(t["error"], "timeout"); - // The window resumes and drains the queue, exactly as `SlideApp::drain_control` does. - let mut app = deckcraft_ui_egui::SlideApp::new(deckcraft_engine::Session::with_new(), deckcraft_ui_egui::Services::default()); - let ctx = egui::Context::default(); - let before = app.session.active().unwrap().doc.slides.len(); - let req = rx.try_recv().expect("the timed-out request is still queued"); - if req.take() { - let _ = deckcraft_ui_egui::control::handle(&mut app, &ctx, &req); - } - assert_eq!(app.session.active().unwrap().doc.slides.len(), before, "a request that timed out must not run when the window resumes"); - drop(rx); -} - -/// A request the app had already started when the reply timed out reports an unknown outcome, -/// not a definite failure (#719). -#[test] -fn a_request_already_started_when_the_reply_times_out_reports_an_unknown_outcome() { - let (addr, rx) = server(small()); - let ui = std::thread::spawn(move || { - let req = rx.recv().expect("the request is queued"); - assert!(req.take(), "the app claims the request"); - // Still running it when the sender's wait expires. - std::thread::sleep(Duration::from_millis(450)); - let _ = req.reply.send(json!({"ok": true, "result": "ran"})); - }); - let (mut r, mut w) = client(addr); - writeln!(w, r#"{{"id":1,"method":"m"}}"#).unwrap(); - let v = reply(&mut r).unwrap(); - assert!(v["error"].as_str().unwrap().contains("outcome is unknown"), "{v}"); - ui.join().unwrap(); -} diff --git a/apps/deckcraft/src/graphics.rs b/apps/deckcraft/src/graphics.rs deleted file mode 100644 index fc054c06d..000000000 --- a/apps/deckcraft/src/graphics.rs +++ /dev/null @@ -1,93 +0,0 @@ -//! Windows graphics instance configuration, applied before wgpu can initialize any driver. - -use eframe::{ - NativeOptions, - egui_wgpu::WgpuSetup, - wgpu::{Backends, Dx12Compiler}, -}; - -/// Default to DirectX 12 with FXC before creating the wgpu instance. Explicit -/// `WGPU_BACKEND` and `WGPU_DX12_COMPILER` choices, read by the caller, take precedence. -pub fn configure(options: &mut NativeOptions, backend_override: Option, compiler_override: Option) { - if let WgpuSetup::CreateNew(create) = &mut options.wgpu_options.wgpu_setup { - // eframe's default includes GL. Creating that backend can crash inside AMD's - // atio6axx.dll before adapter selection or any Rust error handling runs, so the - // window never appears. Choosing an adapter afterwards is too late: only leaving GL - // out of the instance avoids it. This matches the verified WGPU_BACKEND=dx12 - // workaround without mutating process environment variables. - create.instance_descriptor.backends = backend_override.unwrap_or(Backends::DX12); - // Auto loads whichever dxcompiler.dll the DLL search path finds; DeckCraft ships - // none, and without a matching dxil.dll the unsigned-DXIL warning fails wgpu's - // indirect-validation pipeline and loses the device before the first frame - // (issue #153). FXC uses the compiler that is part of Windows. - create.instance_descriptor.backend_options.dx12.shader_compiler = compiler_override.unwrap_or(Dx12Compiler::Fxc); - log::info!( - "Windows graphics: backends={:?}, DX12 compiler={:?}", - create.instance_descriptor.backends, - create.instance_descriptor.backend_options.dx12.shader_compiler - ); - } -} - -#[cfg(test)] -mod tests { - use super::*; - - fn configured_backends(backend_override: Option) -> Backends { - let mut options = NativeOptions::default(); - configure(&mut options, backend_override, None); - let WgpuSetup::CreateNew(create) = options.wgpu_options.wgpu_setup else { - panic!("default native options must create a wgpu instance"); - }; - create.instance_descriptor.backends - } - - #[test] - fn windows_default_initializes_only_dx12() { - // eframe's own default (PRIMARY | GL) would initialize OpenGL as well. - let WgpuSetup::CreateNew(eframe_default) = NativeOptions::default().wgpu_options.wgpu_setup else { - panic!("default native options must create a wgpu instance"); - }; - assert!(eframe_default.instance_descriptor.backends.contains(Backends::GL)); - assert_eq!(configured_backends(None), Backends::DX12); - } - - #[test] - fn windows_default_uses_fxc_instead_of_searching_for_dxc() { - let mut options = NativeOptions::default(); - if let WgpuSetup::CreateNew(create) = &mut options.wgpu_options.wgpu_setup { - // Auto can find an unrelated DXC without its matching DXIL runtime (issue #153). - create.instance_descriptor.backend_options.dx12.shader_compiler = Dx12Compiler::Auto; - } - configure(&mut options, None, None); - let WgpuSetup::CreateNew(create) = options.wgpu_options.wgpu_setup else { - panic!("default native options must create a wgpu instance"); - }; - assert!(matches!(create.instance_descriptor.backend_options.dx12.shader_compiler, Dx12Compiler::Fxc)); - } - - #[test] - fn explicit_compiler_override_is_preserved() { - for compiler in [Dx12Compiler::Fxc, Dx12Compiler::Auto, Dx12Compiler::DynamicDxc { dxc_path: "custom/dxcompiler.dll".into() }] { - let mut options = NativeOptions::default(); - configure(&mut options, None, Some(compiler.clone())); - let WgpuSetup::CreateNew(create) = options.wgpu_options.wgpu_setup else { - panic!("default native options must create a wgpu instance"); - }; - match (compiler, create.instance_descriptor.backend_options.dx12.shader_compiler) { - (Dx12Compiler::Fxc, Dx12Compiler::Fxc) | (Dx12Compiler::Auto, Dx12Compiler::Auto) => {} - (Dx12Compiler::DynamicDxc { dxc_path: expected }, Dx12Compiler::DynamicDxc { dxc_path: actual }) => { - assert_eq!(actual, expected); - } - (expected, actual) => panic!("compiler override changed from {expected:?} to {actual:?}"), - } - } - } - - #[test] - fn explicit_backend_override_is_preserved() { - for backends in [Backends::VULKAN, Backends::GL, Backends::DX12, Backends::VULKAN | Backends::DX12, Backends::empty()] { - assert_eq!(configured_backends(Some(backends)), backends); - } - } -} diff --git a/apps/deckcraft/src/launch_profile.rs b/apps/deckcraft/src/launch_profile.rs index fd95c757a..ce42b27e8 100644 --- a/apps/deckcraft/src/launch_profile.rs +++ b/apps/deckcraft/src/launch_profile.rs @@ -1,221 +1,105 @@ -//! Launcher-owned nightly-v1 bootstrap. Selected before logging, updates, fonts or saved state. -//! Stable launches retain their original arguments and directory policy. No environment mutation. +//! Nightly-v1 bootstrap powered by `craft-nightly`. Selected before logging, updates, fonts or +//! saved state. Stable launches retain their original arguments and directory policy; direct +//! nightly launches self-isolate into [`craft_nightly::canonical_profile_root`]. use std::ffi::OsString; -use std::path::{Component, Path, PathBuf}; -use std::sync::OnceLock; -pub const VERSION: &str = "nightly-v1"; - -#[derive(Clone, Debug, PartialEq, Eq)] -pub enum Profile { - Stable, - NightlyV1(PathBuf), -} - -impl Profile { - pub fn is_nightly(&self) -> bool { - matches!(self, Self::NightlyV1(_)) - } - - pub fn root(&self) -> Option<&Path> { - match self { - Self::Stable => None, - Self::NightlyV1(root) => Some(root), - } - } -} - -#[derive(Debug, PartialEq, Eq)] -pub struct Launch { - pub profile: Profile, - pub args: Vec, -} - -static PROFILE: OnceLock = OnceLock::new(); +use craft_nightly::{BuildFlavor, Launch, Profile, ProfileError, StartupOptions}; pub fn current() -> &'static Profile { - PROFILE.get().unwrap_or(&Profile::Stable) + craft_nightly::current().unwrap_or(&Profile::Stable) } -pub fn install(profile: Profile) -> Result<(), String> { - PROFILE.set(profile).map_err(|_| "the launch profile was already selected".into()) +pub fn startup_options() -> StartupOptions { + StartupOptions::new() } -/// Recognize only the agreed literal selector/root pair before `--`. Everything after it is -/// a file, even when it looks like a profile flag. No filesystem or startup hook runs here. -pub fn parse(args: Vec) -> Result { - let mut selector = None; - let mut root = None; - let mut other = Vec::new(); - let mut files = Vec::new(); - let mut iter = args.iter(); - let mut delimiter = false; - while let Some(arg) = iter.next() { - if arg == "--" { - delimiter = true; - files.extend(iter.cloned()); - break; - } - if arg == "--launch-profile" || arg == "--profile-root" { - let slot = if arg == "--launch-profile" { &mut selector } else { &mut root }; - if slot.is_some() { - return Err("the profile selector and root must each occur exactly once".into()); - } - let value = iter.next().filter(|v| !v.is_empty()).ok_or("the profile selector/root needs a value")?; - if value.to_string_lossy().starts_with("--") { - return Err("the profile selector/root needs a value".into()); - } - *slot = Some(value.clone()); - } else if arg.to_string_lossy().starts_with("--launch-profile=") || arg.to_string_lossy().starts_with("--profile-root=") { - return Err("the nightly protocol requires separate literal selector/root argument tokens".into()); - } else { - other.push(arg.clone()); - } - } - match (selector, root) { - (None, None) => Ok(Launch { profile: Profile::Stable, args }), - (Some(version), Some(root)) if version == VERSION => { - if !delimiter || !other.is_empty() { - return Err("nightly-v1 accepts only its selector/root followed by -- and file names".into()); - } - let root = PathBuf::from(root); - if !root.is_absolute() || root.components().any(|c| matches!(c, Component::ParentDir)) { - return Err("the nightly profile root must be absolute and contain no parent traversal".into()); - } - Ok(Launch { profile: Profile::NightlyV1(root), args: std::iter::once(OsString::from("--")).chain(files).collect() }) - } - (Some(_), Some(_)) => Err("unsupported launch profile (expected nightly-v1)".into()), - _ => Err("--launch-profile and --profile-root must be supplied together".into()), - } -} - -/// The Launcher's version check: the selector/root pair followed by exactly `--version` (or `-V`), -/// answered like a plain version query. Only [`parse`]'s lexical checks apply; the root is never -/// validated or touched, and `-- --version` stays a file name. -pub fn version_query(args: &[OsString]) -> bool { - let Some((last, pair)) = args.split_last() else { return false }; - if last != "--version" && last != "-V" { - return false; - } - let lexical = pair.iter().cloned().chain(std::iter::once(OsString::from("--"))).collect(); - matches!(parse(lexical), Ok(Launch { profile: Profile::NightlyV1(_), args }) if args.len() == 1) -} - -/// Validation finishes before the caller's first startup effect. Stable never calls the nightly -/// root validator, so its old config resolution stays unchanged. -pub fn prepare(mut launch: Launch, validate: impl FnOnce(&Path) -> Result) -> Result { - if let Profile::NightlyV1(root) = &launch.profile { - launch.profile = Profile::NightlyV1(validate(root)?); - } - Ok(launch) -} - -/// Resolve the selected private root before the caller's first startup effect. -pub fn validate_root(root: &Path, env: impl Fn(&str) -> Option, exe: Option<&Path>) -> Result { - crate::profile_root::validate(root, env, exe, crate::app_dirs::ensure_writable) +/// Parses startup arguments for `flavor`, validates and prepares the isolated profile root when +/// running as [`BuildFlavor::NightlyV1`], and installs the resolved profile process-wide. +pub fn prepare(flavor: BuildFlavor, args: impl IntoIterator) -> Result { + let spec = crate::profile_root::spec(); + craft_nightly::prepare_launch(flavor, &spec, args, &startup_options()) } #[cfg(test)] mod tests { + use std::path::PathBuf; + + use craft_nightly::{LAUNCH_PROFILE_FLAG, NIGHTLY_V1_CONTRACT, PROFILE_ROOT_FLAG, canonical_profile_root, parse_startup}; + use super::*; - use std::cell::Cell; + fn args(values: &[&str]) -> Vec { values.iter().map(OsString::from).collect() } + fn absolute() -> &'static str { if cfg!(windows) { r"C:\NightlyData\profiles\deckcraft" } else { "/nightly-data/profiles/deckcraft" } } - fn nightly() -> Vec { - args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--"]) - } - - /// The process installs one profile; later answers are read-only and a second install fails. - #[test] - fn the_process_installs_its_profile_once() { - assert_eq!(current(), &Profile::Stable, "an unselected process is a stable launch"); - assert!(install(Profile::Stable).is_ok()); - assert_eq!(current(), &Profile::Stable); - assert!(install(Profile::Stable).is_err()); - } #[test] - fn stable_arguments_and_directory_policy_are_unchanged() { + fn stable_arguments_and_profile_are_unchanged() { + let spec = crate::profile_root::spec(); for argv in [args(&[]), args(&["--sample", "a.pptx"]), args(&["--", "--launch-profile", "file.pptx"])] { - let launch = prepare(parse(argv.clone()).unwrap(), |_| panic!("stable must never validate a nightly root")).unwrap(); - assert_eq!(launch, Launch { profile: Profile::Stable, args: argv }); + let launch = parse_startup(BuildFlavor::Stable, &spec, argv.clone(), &startup_options()).unwrap(); + assert_eq!(launch.profile, Profile::Stable); + assert_eq!(launch.passthrough_args, argv); } } #[test] - fn exact_version_and_root_are_parsed_without_reinterpreting_file_names() { - let mut argv = nightly(); - argv.extend(args(&["--profile-root", "talk with spaces.pptx"])); - let launch = parse(argv).unwrap(); + fn explicit_launcher_arguments_are_parsed_without_reinterpreting_file_names() { + let spec = crate::profile_root::spec(); + let argv = args(&[LAUNCH_PROFILE_FLAG, NIGHTLY_V1_CONTRACT, PROFILE_ROOT_FLAG, absolute(), "--", "--profile-root", "talk with spaces.pptx"]); + let launch = parse_startup(BuildFlavor::NightlyV1, &spec, argv, &startup_options()).unwrap(); assert_eq!(launch.profile, Profile::NightlyV1(PathBuf::from(absolute()))); - assert_eq!(launch.args, args(&["--", "--profile-root", "talk with spaces.pptx"])); + assert_eq!(launch.passthrough_args, args(&["--profile-root", "talk with spaces.pptx"])); } #[test] - fn missing_duplicate_unknown_and_conflicting_profile_arguments_are_refused() { - for argv in [ - args(&["--launch-profile", VERSION]), - args(&["--profile-root", absolute()]), - args(&["--launch-profile", "future-v2", "--profile-root", absolute(), "--"]), - args(&["--launch-profile", VERSION, "--launch-profile", VERSION, "--profile-root", absolute(), "--"]), - args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--profile-root", absolute(), "--"]), - args(&["--launch-profile", VERSION, "--profile-root", "relative", "--"]), - args(&["--launch-profile", VERSION, "--profile-root", "", "--"]), - args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--control", "4242", "--"]), - args(&["--launch-profile", VERSION, "--profile-root", absolute()]), - args(&["--launch-profile=nightly-v1", "--profile-root", absolute(), "--"]), - ] { - assert!(parse(argv).is_err()); - } + fn direct_nightly_launch_self_isolates_and_preserves_user_args() { + let spec = crate::profile_root::spec(); + let expected_root = canonical_profile_root(crate::profile_root::APP_ID).unwrap(); + let launch = parse_startup(BuildFlavor::NightlyV1, &spec, args(&["--show", "deck.ppsx"]), &startup_options()).unwrap(); + assert_eq!(launch.profile, Profile::NightlyV1(expected_root)); + assert_eq!(launch.passthrough_args, args(&["--show", "deck.ppsx"])); } #[test] - fn the_launcher_version_check_is_a_version_query_only_in_its_exact_form() { - let pair = &["--launch-profile", VERSION, "--profile-root", absolute()]; - let reversed = &["--profile-root", absolute(), "--launch-profile", VERSION]; - for flag in ["--version", "-V"] { - for form in [pair, reversed] { - let mut argv = args(form); - argv.push(flag.into()); - assert!(version_query(&argv), "{argv:?}"); - } - } + fn launcher_and_plain_version_queries_are_recognized() { + let spec = crate::profile_root::spec(); for argv in [ args(&["--version"]), - args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--", "--version"]), - args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version", "--"]), - args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--control", "1", "--version"]), - args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version", "--version"]), - args(&["--version", "--launch-profile", VERSION, "--profile-root", absolute()]), - args(&["--launch-profile", "future-v2", "--profile-root", absolute(), "--version"]), - args(&["--launch-profile", VERSION, "--profile-root", "relative", "--version"]), - args(&["--launch-profile", VERSION, "--version"]), - args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--help"]), + args(&["-V"]), + args(&[LAUNCH_PROFILE_FLAG, NIGHTLY_V1_CONTRACT, PROFILE_ROOT_FLAG, absolute(), "--version"]), + args(&[PROFILE_ROOT_FLAG, absolute(), LAUNCH_PROFILE_FLAG, NIGHTLY_V1_CONTRACT, "-V"]), + args(&[LAUNCH_PROFILE_FLAG, NIGHTLY_V1_CONTRACT, PROFILE_ROOT_FLAG, absolute(), "--", "--version"]), ] { - assert!(!version_query(&argv), "{argv:?}"); + let launch = parse_startup(BuildFlavor::NightlyV1, &spec, argv.clone(), &startup_options()).unwrap(); + assert!(launch.is_version_query(), "{argv:?}"); + } + for argv in [ + args(&[LAUNCH_PROFILE_FLAG, NIGHTLY_V1_CONTRACT, PROFILE_ROOT_FLAG, absolute(), "--version", "--version"]), + args(&[LAUNCH_PROFILE_FLAG, NIGHTLY_V1_CONTRACT, PROFILE_ROOT_FLAG, absolute(), "--help"]), + ] { + let launch = parse_startup(BuildFlavor::NightlyV1, &spec, argv.clone(), &startup_options()).unwrap(); + assert!(!launch.is_version_query(), "{argv:?}"); } - // Outside the query the strict protocol still refuses the version flag. - assert!(parse(args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version"])).is_err()); } #[test] - fn failed_root_validation_never_reaches_startup_or_falls_back_to_stable() { - let reached = Cell::new(false); - let result = prepare(parse(nightly()).unwrap(), |_| Err("read-only or unsafe profile".into())).map(|_| reached.set(true)); - assert!(result.is_err()); - assert!(!reached.get()); - } - - #[test] - fn successful_root_validation_keeps_the_persistent_root_not_the_binary_tag() { - let checked = PathBuf::from(absolute()).join("checked"); - let launch = prepare(parse(nightly()).unwrap(), |_| Ok(checked.clone())).unwrap(); - assert_eq!(launch.profile.root(), Some(checked.as_path())); - assert!(launch.profile.is_nightly()); + fn missing_duplicate_unknown_and_misplaced_profile_arguments_are_refused() { + let spec = crate::profile_root::spec(); + for argv in [ + args(&[LAUNCH_PROFILE_FLAG, NIGHTLY_V1_CONTRACT]), + args(&[PROFILE_ROOT_FLAG, absolute()]), + args(&[LAUNCH_PROFILE_FLAG, "future-v2", PROFILE_ROOT_FLAG, absolute(), "--"]), + args(&[LAUNCH_PROFILE_FLAG, NIGHTLY_V1_CONTRACT, LAUNCH_PROFILE_FLAG, NIGHTLY_V1_CONTRACT, PROFILE_ROOT_FLAG, absolute(), "--"]), + args(&[LAUNCH_PROFILE_FLAG, NIGHTLY_V1_CONTRACT, PROFILE_ROOT_FLAG, absolute(), PROFILE_ROOT_FLAG, absolute(), "--"]), + args(&[LAUNCH_PROFILE_FLAG, NIGHTLY_V1_CONTRACT, PROFILE_ROOT_FLAG, "", "--"]), + args(&["--sample", LAUNCH_PROFILE_FLAG, NIGHTLY_V1_CONTRACT, PROFILE_ROOT_FLAG, absolute()]), + ] { + assert!(parse_startup(BuildFlavor::NightlyV1, &spec, argv.clone(), &startup_options()).is_err(), "{argv:?}"); + } } } diff --git a/apps/deckcraft/src/logging.rs b/apps/deckcraft/src/logging.rs deleted file mode 100644 index fed5d503e..000000000 --- a/apps/deckcraft/src/logging.rs +++ /dev/null @@ -1,601 +0,0 @@ -//! The desktop app's logger: `log::` records go to standard error and to a log file. -//! -//! Without a logger every `log::warn!`/`log::error!` in the workspace (the crash guard's panic -//! report, a failed crash-recovery save, PowerPoint parts that were skipped on import, audio output -//! problems) vanished. A launch from a desktop menu has no terminal, so the file is what a bug report -//! can attach: `/logs/deckcraft.log`, beside `ui.json` and `prefs.json`. Each start -//! moves the previous log to `deckcraft.1.log` (and that one to `.2`), so the log of a run that -//! crashed survives the next launch. -//! -//! Levels: `info` for DeckCraft's own crates, `warn` for everything else (wgpu and naga are -//! chatty). `RUST_LOG` replaces that with env_logger-style directives: `debug`, -//! `warn,deckcraft_pptx=trace`, `wgpu_core=info`. A directive ending in `*` matches every target -//! that starts with it (`deckcraft*=debug`). -//! -//! Records logged before the settings directory is known are kept (up to [`MAX_PENDING`]) and -//! written once the file is attached. Writing never panics: a file that can't be created or written -//! leaves standard error as the only sink. -//! -//! Realtime audio: the cpal callbacks (`audio.rs`) do not log; a stream error is kept and logged -//! from the UI thread when the stream stops. A record takes the sink lock only for one `write_all` -//! of an already formatted line (standard error is written outside the lock). - -use std::fs::File; -use std::io::Write; -use std::path::{Path, PathBuf}; -use std::sync::{Mutex, OnceLock, PoisonError}; -use std::time::SystemTime; - -use log::LevelFilter; - -/// The current log file's name inside the log directory. -pub const LOG_FILE: &str = "deckcraft.log"; -/// The log directory inside the settings directory. -pub const LOG_DIR: &str = "logs"; -/// How many previous logs are kept (`deckcraft.1.log` … `deckcraft..log`). -pub const KEEP: usize = 2; -/// The log file stops growing past this size (a runaway warning can't fill the disk). -pub const MAX_FILE_BYTES: u64 = 16 * 1024 * 1024; -/// Records kept in memory until the log file is attached. -pub const MAX_PENDING: usize = 512; -/// The built-in filter when `RUST_LOG` is unset or empty. -pub const DEFAULT_FILTER: &str = "warn,deckcraft*=info"; - -/// Per-target level filter parsed from env_logger-style directives. -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct Filter { - default: LevelFilter, - directives: Vec<(String, LevelFilter)>, -} - -impl Filter { - /// Parse `spec`; unknown levels and empty parts are skipped. Without a bare level, targets no - /// directive names log errors only. - pub fn parse(spec: &str) -> Filter { - let mut f = Filter { default: LevelFilter::Error, directives: Vec::new() }; - for part in spec.split(',').map(str::trim).filter(|p| !p.is_empty()) { - match part.split_once('=') { - Some((name, level)) => { - let name = name.trim(); - if let (false, Some(level)) = (name.is_empty(), parse_level(level)) { - f.directives.push((name.to_owned(), level)); - } - } - None => match parse_level(part) { - Some(level) => f.default = level, - // A bare target name: everything from it (env_logger does the same). - None => f.directives.push((part.to_owned(), LevelFilter::Trace)), - }, - } - } - f - } - - /// The level that applies to `target` (the most specific matching directive wins). - pub fn level_for(&self, target: &str) -> LevelFilter { - self.directives.iter().filter(|(name, _)| matches(name, target)).max_by_key(|(name, _)| name.len()).map_or(self.default, |(_, level)| *level) - } - - /// The most verbose level any target can reach (for `log::set_max_level`). - pub fn max(&self) -> LevelFilter { - self.directives.iter().map(|(_, level)| *level).fold(self.default, Ord::max) - } -} - -fn parse_level(s: &str) -> Option { - s.trim().parse().ok() -} - -/// `name` matches `target` itself and its submodules (`a` matches `a` and `a::b`, not `ab`); -/// `name*` matches every target starting with `name`. -fn matches(name: &str, target: &str) -> bool { - match name.strip_suffix('*') { - Some(prefix) => target.starts_with(prefix), - None => target.strip_prefix(name).is_some_and(|rest| rest.is_empty() || rest.starts_with("::")), - } -} - -/// `2026-10-08T07:59:17.728Z` (UTC, milliseconds). A clock before 1970 reads as the epoch; a clock -/// set absurdly far ahead keeps its real year (years far outside chrono's own range are preserved) -/// instead of panicking. -pub fn timestamp(t: SystemTime) -> String { - let since = t.duration_since(std::time::UNIX_EPOCH).unwrap_or_default(); - let (y, dt) = utc_parts(since.as_secs(), since.subsec_nanos()); - // `{:04}` rather than `%Y`, which writes a `+` before years past 9999. - format!("{y:04}-{}", dt.format("%m-%dT%H:%M:%S%.3fZ")) -} - -/// Unix seconds (+ nanos) → (proleptic Gregorian year, the same wall-clock instant moved into -/// chrono's range by whole 400-year cycles). The Gregorian calendar repeats every 400 years -/// (146_097 days), so month, day and time of day come from chrono and only the year is carried, -/// which keeps every input exact instead of collapsing out-of-range years to the epoch. `secs` is -/// `u64` (the clock is clamped at the epoch before 1970), so `days` always fits an `i64`. -fn utc_parts(secs: u64, nanos: u32) -> (i64, chrono::NaiveDateTime) { - use chrono::Datelike; - let (days, sod) = ((secs / 86_400) as i64, (secs % 86_400) as i64); - let (cycles, rest) = (days.div_euclid(146_097), days.rem_euclid(146_097)); - // `rest + 719_163` (1970-01-01 is CE day 719_163) is always a valid CE day, and `sod` < 86_400. - let date = i32::try_from(rest + 719_163).ok().and_then(chrono::NaiveDate::from_num_days_from_ce_opt); - let time = u32::try_from(sod).ok().and_then(|s| chrono::NaiveTime::from_num_seconds_from_midnight_opt(s, nanos.min(999_999_999))); - match (date, time) { - (Some(d), Some(t)) => { - let y = i128::from(d.year()) + i128::from(cycles) * 400; - (i64::try_from(y).unwrap_or(i64::MAX), d.and_time(t)) - } - _ => (1970, chrono::NaiveDateTime::default()), // unreachable - } -} - -fn numbered(dir: &Path, n: usize) -> PathBuf { - if n == 0 { dir.join(LOG_FILE) } else { dir.join(format!("deckcraft.{n}.log")) } -} - -/// Shift the previous logs up one (`.log` → `.1.log` → … → `..log`, the oldest dropped) -/// and create a fresh, empty log file in `dir` (created if missing). -pub fn rotate(dir: &Path) -> std::io::Result<(PathBuf, File)> { - std::fs::create_dir_all(dir)?; - for n in (1..=KEEP).rev() { - match std::fs::rename(numbered(dir, n - 1), numbered(dir, n)) { - Err(e) if e.kind() != std::io::ErrorKind::NotFound => return Err(e), - _ => {} - } - } - let path = numbered(dir, 0); - let file = File::create(&path)?; - Ok((path, file)) -} - -/// One formatted log line: ` [] : \n`. -pub fn format_line(ts: &str, level: log::Level, thread: &str, target: &str, message: &str) -> String { - let message = message.strip_suffix('\n').unwrap_or(message); - // Messages can embed document-controlled text (a part name, a relationship id): control - // characters other than tab are escaped and each continuation line is marked, so such text - // cannot start a line that looks like a record of its own. - let mut text = String::with_capacity(message.len()); - for c in message.chars() { - match c { - '\n' => text.push_str("\n | "), - '\t' => text.push(c), - c if c.is_control() => text.extend(c.escape_default()), - c => text.push(c), - } - } - format!("{ts} {level:<5} [{thread}] {target}: {text}\n") -} - -/// Where formatted lines go besides standard error: kept in memory until a file is attached, -/// then appended to it until it reaches its size cap. -pub struct Sink { - file: Option, - pending: Vec, - dropped: usize, - written: u64, - max_bytes: u64, - capped: bool, -} - -impl Sink { - pub fn new(max_bytes: u64) -> Sink { - Sink { file: None, pending: Vec::new(), dropped: 0, written: 0, max_bytes, capped: false } - } - - /// Append `line` to the file, or keep it until [`Sink::attach`]. - pub fn write(&mut self, line: &str) { - if self.file.is_none() { - if self.capped { - return; - } - if self.pending.len() < MAX_PENDING { - self.pending.push(line.to_owned()); - } else { - self.dropped = self.dropped.saturating_add(1); - } - return; - } - self.append(line); - } - - /// Start writing to `file`, first the lines kept so far. - pub fn attach(&mut self, file: File) { - self.file = Some(file); - for line in std::mem::take(&mut self.pending) { - self.append(&line); - } - if self.dropped > 0 { - let note = format!("{} earlier log lines were dropped before the log file was opened\n", self.dropped); - self.dropped = 0; - self.append(¬e); - } - } - - /// No file will come: drop the kept lines and keep none from now on. - pub fn close(&mut self) { - self.file = None; - self.pending = Vec::new(); - self.capped = true; - } - - fn append(&mut self, line: &str) { - if self.capped { - return; - } - let Some(file) = self.file.as_mut() else { return }; - let len = u64::try_from(line.len()).unwrap_or(u64::MAX); - let text = if self.written.saturating_add(len) > self.max_bytes { - self.capped = true; - format!("log file reached {} bytes; later records go to standard error only\n", self.max_bytes) - } else { - self.written = self.written.saturating_add(len); - line.to_owned() - }; - // A full disk or a vanished file must not take the app down: drop the file sink (and - // stop buffering, since no file will come). - if file.write_all(text.as_bytes()).is_err() { - self.file = None; - self.capped = true; - } - } -} - -/// The installed logger: a [`Filter`], standard error and a [`Sink`]. -pub struct AppLogger { - filter: Filter, - stderr: bool, - sink: Mutex, -} - -impl AppLogger { - pub fn new(filter: Filter, stderr: bool) -> AppLogger { - AppLogger { filter, stderr, sink: Mutex::new(Sink::new(MAX_FILE_BYTES)) } - } - - /// Rotate the logs in `dir` and send records to the fresh file; returns its path. - /// An unusable directory leaves standard error as the only sink ([`AppLogger::stderr_only`]). - pub fn attach_dir(&self, dir: &Path) -> Result { - match rotate(dir) { - Ok((path, file)) => { - self.sink.lock().unwrap_or_else(PoisonError::into_inner).attach(file); - Ok(path) - } - Err(e) => { - self.stderr_only(); - Err(format!("{}: {e}", dir.display())) - } - } - } - - /// No log file this run (no settings directory, or it can't be used): stop keeping records for one. - pub fn stderr_only(&self) { - self.sink.lock().unwrap_or_else(PoisonError::into_inner).close(); - } -} - -impl log::Log for AppLogger { - fn enabled(&self, metadata: &log::Metadata<'_>) -> bool { - metadata.level() <= self.filter.level_for(metadata.target()) - } - - fn log(&self, record: &log::Record<'_>) { - if !self.enabled(record.metadata()) { - return; - } - // Format before taking the lock, so the lock covers one write only. - let thread = std::thread::current(); - let line = - format_line(×tamp(SystemTime::now()), record.level(), thread.name().unwrap_or("?"), record.target(), &record.args().to_string()); - if self.stderr { - let _ = std::io::stderr().write_all(line.as_bytes()); - } - self.sink.lock().unwrap_or_else(PoisonError::into_inner).write(&line); - } - - fn flush(&self) {} -} - -/// Install the logger (filter from `RUST_LOG`, else [`DEFAULT_FILTER`]); `None` when another -/// logger was installed first. Call [`AppLogger::attach_dir`] once the settings directory is known. -pub fn install() -> Option<&'static AppLogger> { - static LOGGER: OnceLock = OnceLock::new(); - let spec = std::env::var("RUST_LOG").ok().filter(|s| !s.trim().is_empty()); - let filter = Filter::parse(spec.as_deref().unwrap_or(DEFAULT_FILTER)); - let max = filter.max(); - let logger = LOGGER.get_or_init(|| AppLogger::new(filter, true)); - log::set_logger(logger).ok()?; - log::set_max_level(max); - Some(logger) -} - -#[cfg(test)] -mod tests { - use super::*; - use log::Log; - use std::sync::atomic::{AtomicUsize, Ordering}; - use std::time::{Duration, UNIX_EPOCH}; - - fn temp_dir(tag: &str) -> PathBuf { - static N: AtomicUsize = AtomicUsize::new(0); - let d = std::env::temp_dir().join(format!("deckcraft-logging-{tag}-{}-{}", std::process::id(), N.fetch_add(1, Ordering::Relaxed))); - let _ = std::fs::remove_dir_all(&d); - d - } - - fn read(path: &Path) -> String { - std::fs::read_to_string(path).expect("read log") - } - - fn record(logger: &AppLogger, level: log::Level, target: &'static str, msg: &'static str) { - logger.log(&log::Record::builder().level(level).target(target).args(format_args!("{msg}")).build()); - } - - #[test] - fn the_default_filter_shows_deckcraft_info_and_other_crates_warnings() { - let f = Filter::parse(DEFAULT_FILTER); - assert_eq!(f.level_for("deckcraft"), LevelFilter::Info); - assert_eq!(f.level_for("deckcraft::audio"), LevelFilter::Info); - assert_eq!(f.level_for("deckcraft_engine::guard"), LevelFilter::Info); - assert_eq!(f.level_for("deckcraft_pptx::read"), LevelFilter::Info); - assert_eq!(f.level_for("wgpu_core::device"), LevelFilter::Warn); - assert_eq!(f.level_for("naga"), LevelFilter::Warn); - assert_eq!(f.max(), LevelFilter::Info); - } - - #[test] - fn directives_follow_env_logger_and_the_most_specific_one_wins() { - let f = Filter::parse("info,wgpu_core=error,deckcraft_pptx=trace,deckcraft_pptx::opc=off"); - assert_eq!(f.level_for("eframe"), LevelFilter::Info); - assert_eq!(f.level_for("wgpu_core::instance"), LevelFilter::Error); - assert_eq!(f.level_for("deckcraft_pptx::read"), LevelFilter::Trace); - assert_eq!(f.level_for("deckcraft_pptx::opc"), LevelFilter::Off); - assert_eq!(f.max(), LevelFilter::Trace); - // A module name is matched at `::` boundaries, not as a bare prefix. - assert_eq!(f.level_for("wgpu_core_extra"), LevelFilter::Info); - // A trailing `*` is a prefix. - assert_eq!(Filter::parse("warn,deckcraft_ui*=debug").level_for("deckcraft_ui_egui::canvas"), LevelFilter::Debug); - assert_eq!(Filter::parse("warn,deckcraft_ui*=debug").level_for("deckcraft_engine"), LevelFilter::Warn); - // A bare target name sets that target to the most verbose level, as env_logger does. - assert_eq!(Filter::parse("naga").level_for("naga::front"), LevelFilter::Trace); - assert_eq!(Filter::parse("naga").level_for("eframe"), LevelFilter::Error); - // Levels are case-insensitive; the last bare level wins. - assert_eq!(Filter::parse("debug,WARN").level_for("x"), LevelFilter::Warn); - } - - #[test] - fn hostile_specs_never_panic_and_fall_back_sensibly() { - let long = "a".repeat(100_000); - let specs = [ - "", - ",,,", - "=", - "==", - "=debug", - "deckcraft=", - "nonsense=loud", - "🦀=info", - "*", - "*=debug", - "a=b=c", - "warn,,deckcraft=DEBUG", - " \t ", - "\u{0}", - "é*=trace", - &long, - ]; - for spec in specs { - let f = Filter::parse(spec); - for target in ["deckcraft", "", "🦀", "é", "a::b"] { - let _ = f.level_for(target); - } - let _ = f.max(); - } - assert_eq!(Filter::parse("warn,,deckcraft=DEBUG").level_for("deckcraft"), LevelFilter::Debug); - assert_eq!(Filter::parse("nonsense=loud").level_for("nonsense"), LevelFilter::Error); - assert_eq!(Filter::parse("=debug").max(), LevelFilter::Error, "a directive without a name is skipped"); - assert_eq!(Filter::parse("*=debug").level_for("anything"), LevelFilter::Debug, "a lone `*` matches every target"); - assert_eq!(Filter::parse("é*=trace").level_for("éa"), LevelFilter::Trace); - } - - #[test] - fn timestamps_are_utc_with_milliseconds() { - assert_eq!(timestamp(UNIX_EPOCH), "1970-01-01T00:00:00.000Z"); - assert_eq!(timestamp(UNIX_EPOCH + Duration::from_millis(1_791_446_357_728)), "2026-10-08T07:59:17.728Z"); - // Leap day, and the day after it. - assert_eq!(timestamp(UNIX_EPOCH + Duration::from_secs(1_709_164_800)), "2024-02-29T00:00:00.000Z"); - assert_eq!(timestamp(UNIX_EPOCH + Duration::from_secs(1_709_251_199)), "2024-02-29T23:59:59.000Z"); - assert_eq!(timestamp(UNIX_EPOCH + Duration::from_secs(1_709_251_200)), "2024-03-01T00:00:00.000Z"); - // 2000 is a leap year (divisible by 400), 2100 is not. - assert_eq!(timestamp(UNIX_EPOCH + Duration::from_secs(951_782_400)), "2000-02-29T00:00:00.000Z"); - assert_eq!(timestamp(UNIX_EPOCH + Duration::from_secs(4_107_542_400)), "2100-03-01T00:00:00.000Z"); - // Before the epoch (a clock set wrong) clamps instead of panicking. - assert_eq!(timestamp(UNIX_EPOCH - Duration::from_secs(5)), "1970-01-01T00:00:00.000Z"); - // A clock set absurdly far ahead (past chrono's own range) keeps its real year rather than - // collapsing to the epoch. Windows' SystemTime can't hold such an instant, so it is built - // with a checked add and only asserted where it exists. - if let Some(far) = UNIX_EPOCH.checked_add(Duration::from_secs(u64::MAX / 2)) { - assert_eq!(timestamp(far), "292277026596-12-04T15:30:07.000Z"); - } - if let Some(far) = UNIX_EPOCH.checked_add(Duration::from_secs(10_000_000_000_000)) { - assert_eq!(timestamp(far), "318857-05-20T17:46:40.000Z"); - } - // Years past 9999 keep the plain zero-padded year (no `+`). - assert_eq!(timestamp(UNIX_EPOCH + Duration::from_secs(253_402_300_800)), "10000-01-01T00:00:00.000Z"); - } - - #[test] - fn rotation_keeps_the_previous_logs_and_starts_an_empty_file() { - let dir = temp_dir("rotate"); - for run in 1..=4 { - let (path, _file) = rotate(&dir).expect("rotate"); - assert_eq!(path, dir.join(LOG_FILE)); - assert_eq!(read(&path), ""); - std::fs::write(&path, format!("run {run}")).expect("write"); - } - assert_eq!(read(&dir.join(LOG_FILE)), "run 4"); - assert_eq!(read(&dir.join("deckcraft.1.log")), "run 3"); - assert_eq!(read(&dir.join("deckcraft.2.log")), "run 2"); - assert!(!dir.join("deckcraft.3.log").exists(), "only {KEEP} old logs are kept"); - let _ = std::fs::remove_dir_all(&dir); - } - - #[test] - fn rotation_into_an_unusable_directory_is_an_error_not_a_panic() { - let dir = temp_dir("blocked"); - std::fs::create_dir_all(dir.parent().expect("parent")).expect("tmp"); - std::fs::write(&dir, "a file where the directory should be").expect("block"); - assert!(rotate(&dir).is_err()); - assert!(rotate(&dir.join("below")).is_err()); - let _ = std::fs::remove_file(&dir); - } - - #[test] - fn a_line_carries_time_level_thread_target_and_message() { - assert_eq!( - format_line( - "2026-10-08T07:59:17.728Z", - log::Level::Warn, - "main", - "deckcraft_pptx::opc", - "pptx: skipping oversized part ppt/media/image1.png" - ), - "2026-10-08T07:59:17.728Z WARN [main] deckcraft_pptx::opc: pptx: skipping oversized part ppt/media/image1.png\n" - ); - // A multi-line message keeps its lines, each continuation marked; the record still ends in - // exactly one newline. - assert!(format_line("t", log::Level::Error, "w", "x", "a\nb\n").ends_with("x: a\n | b\n")); - // Injected line breaks and escape sequences cannot forge a record. - let line = format_line("t", log::Level::Warn, "w", "x", "part a\r\n2026 ERROR [m] y: forged\x1b[2J"); - assert_eq!(line.matches('\n').count(), 2); - assert!(!line.contains('\r') && !line.contains('\x1b')); - } - - #[test] - fn lines_logged_before_the_file_exists_are_written_when_it_is_attached() { - let dir = temp_dir("pending"); - let (path, file) = rotate(&dir).expect("rotate"); - let mut sink = Sink::new(MAX_FILE_BYTES); - sink.write("early 1\n"); - sink.write("early 2\n"); - sink.attach(file); - sink.write("late\n"); - assert_eq!(read(&path), "early 1\nearly 2\nlate\n"); - let _ = std::fs::remove_dir_all(&dir); - } - - #[test] - fn the_pending_buffer_is_bounded_and_says_how_much_it_dropped() { - let dir = temp_dir("bounded"); - let (path, file) = rotate(&dir).expect("rotate"); - let mut sink = Sink::new(MAX_FILE_BYTES); - for i in 0..MAX_PENDING + 5 { - sink.write(&format!("line {i}\n")); - } - sink.attach(file); - let text = read(&path); - assert_eq!(text.lines().filter(|l| l.starts_with("line ")).count(), MAX_PENDING); - assert_eq!(text.matches("5 earlier log lines were dropped").count(), 1, "{text}"); - assert!(text.contains("line 0\n") && !text.contains(&format!("line {MAX_PENDING}\n"))); - let _ = std::fs::remove_dir_all(&dir); - } - - #[test] - fn exactly_max_pending_lines_drop_nothing() { - let dir = temp_dir("exact"); - let (path, file) = rotate(&dir).expect("rotate"); - let mut sink = Sink::new(MAX_FILE_BYTES); - for i in 0..MAX_PENDING { - sink.write(&format!("line {i}\n")); - } - sink.attach(file); - let text = read(&path); - assert_eq!(text.lines().count(), MAX_PENDING); - assert!(!text.contains("dropped"), "{text}"); - let _ = std::fs::remove_dir_all(&dir); - } - - #[test] - fn the_file_stops_at_its_size_cap_with_one_note() { - let dir = temp_dir("cap"); - let (path, file) = rotate(&dir).expect("rotate"); - let mut sink = Sink::new(100); - sink.attach(file); - for i in 0..50 { - sink.write(&format!("line {i:02} with some padding\n")); - } - let text = read(&path); - assert_eq!(text.lines().filter(|l| l.starts_with("line ")).count(), 3, "{text}"); - assert_eq!(text.matches("log file reached 100 bytes").count(), 1, "{text}"); - let _ = std::fs::remove_dir_all(&dir); - } - - #[test] - fn the_logger_filters_records_and_writes_them_to_the_attached_file() { - let dir = temp_dir("logger"); - let logger = AppLogger::new(Filter::parse(DEFAULT_FILTER), false); - record(&logger, log::Level::Info, "deckcraft", "DeckCraft starting"); - record(&logger, log::Level::Info, "wgpu_core::device", "too chatty"); - let path = logger.attach_dir(&dir).expect("attach"); - assert_eq!(path, dir.join(LOG_FILE)); - record(&logger, log::Level::Warn, "wgpu_hal::vulkan", "a real warning"); - record(&logger, log::Level::Debug, "deckcraft", "below info"); - let text = read(&path); - let lines: Vec<&str> = text.lines().collect(); - assert_eq!(lines.len(), 2, "{text}"); - assert!(lines.first().is_some_and(|l| l.contains(" INFO [") && l.ends_with("deckcraft: DeckCraft starting")), "{text}"); - assert!(lines.get(1).is_some_and(|l| l.ends_with("wgpu_hal::vulkan: a real warning")), "{text}"); - assert!(logger.enabled(&log::Metadata::builder().level(log::Level::Info).target("deckcraft_engine::recovery").build())); - assert!(!logger.enabled(&log::Metadata::builder().level(log::Level::Info).target("naga").build())); - // A second launch rotates: the first log becomes `.1`. - let second = AppLogger::new(Filter::parse(DEFAULT_FILTER), false); - assert_eq!(second.attach_dir(&dir).expect("attach again"), dir.join(LOG_FILE)); - assert_eq!(read(&dir.join("deckcraft.1.log")), text); - let _ = std::fs::remove_dir_all(&dir); - } - - #[test] - fn records_from_many_threads_are_whole_lines() { - let dir = temp_dir("threads"); - let logger = AppLogger::new(Filter::parse("info"), false); - let path = logger.attach_dir(&dir).expect("attach"); - std::thread::scope(|s| { - for _ in 0..4 { - s.spawn(|| { - for _ in 0..100 { - record(&logger, log::Level::Info, "deckcraft", "from a worker"); - } - }); - } - }); - let text = read(&path); - assert_eq!(text.lines().count(), 400); - assert!(text.lines().all(|l| l.ends_with("deckcraft: from a worker")), "{text}"); - let _ = std::fs::remove_dir_all(&dir); - } - - #[test] - fn attaching_to_an_unusable_directory_reports_an_error_and_keeps_logging() { - let dir = temp_dir("unusable"); - std::fs::write(&dir, "not a directory").expect("block"); - let logger = AppLogger::new(Filter::parse("info"), false); - let e = logger.attach_dir(&dir).expect_err("a file is not a log directory"); - assert!(e.contains(&dir.display().to_string()), "{e}"); - record(&logger, log::Level::Error, "x", "still fine"); - let sink = logger.sink.lock().expect("sink"); - assert!(sink.file.is_none() && sink.pending.is_empty(), "nothing is kept for a file that will not come"); - drop(sink); - let _ = std::fs::remove_file(&dir); - } - - #[test] - fn a_poisoned_lock_does_not_stop_logging() { - let dir = temp_dir("poison"); - let logger = AppLogger::new(Filter::parse("info"), false); - let path = logger.attach_dir(&dir).expect("attach"); - let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { - let _guard = logger.sink.lock(); - panic!("poison the sink"); - })); - assert!(logger.sink.is_poisoned()); - record(&logger, log::Level::Info, "deckcraft", "after the panic"); - assert!(read(&path).contains("after the panic")); - let _ = std::fs::remove_dir_all(&dir); - } -} diff --git a/apps/deckcraft/src/main.rs b/apps/deckcraft/src/main.rs index 7641870b6..23c2fee51 100644 --- a/apps/deckcraft/src/main.rs +++ b/apps/deckcraft/src/main.rs @@ -1,170 +1,119 @@ //! DeckCraft desktop app. //! -//! Usage: `deckcraft [--control ] [--sample] [--show] [files…]` +//! Usage: `deckcraft [--control ] [--control-token | --control-token-file ] [--sample] [--show] [files…]` //! A PowerPoint Show (`.ppsx`) given last starts its slide show, as a double-click does in PowerPoint. //! `deckcraft --help` prints the flags and exits. `deckcraft --version` prints the version and exits. //! -//! `--control ` (or `DECKCRAFT_CONTROL_PORT`) starts a localhost JSON-lines control server: +//! `--control ` (or `DECKCRAFT_CONTROL_PORT`) starts an authenticated localhost JSON-lines server. +//! Supply `--control-token` or `--control-token-file`, or use the per-launch token printed to stderr. +//! After authentication, a request and reply look like: //! `{"id":1,"method":"ui.inspect","params":{}}` → `{"id":1,"ok":true,"result":…}`. //! See `deckcraft_ui_egui::control` for the methods. //! //! `log` records go to standard error and `/logs/deckcraft.log` (`RUST_LOG` sets the -//! levels); see [`logging`]. +//! levels); see [`craft::platform::logs`]. #![cfg_attr(all(target_os = "windows", not(debug_assertions)), windows_subsystem = "windows")] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] #![forbid(unsafe_code)] mod app_dirs; -#[cfg(target_os = "macos")] -mod apple_events; mod audio; #[cfg(test)] mod build_channel; mod build_flavor; -mod control_server; #[cfg(all(unix, not(target_os = "macos")))] mod display; -#[cfg(any(target_os = "windows", test))] -mod graphics; mod launch_profile; -mod logging; mod nightly_session; -#[cfg(not(target_arch = "wasm32"))] -mod pasteboard; mod process_identity; mod profile_root; -use deckcraft_engine::Session; -use deckcraft_ui_egui::{Services, SlideApp}; +use std::sync::{Arc, OnceLock}; -struct App( - SlideApp, - /// Files opened from Finder and quit requests (see `apple_events`). - #[cfg(target_os = "macos")] - fmv_macos_events::Inbox, -); +use craft::automation::args::{ControlOptions, EnvNames, FlagNames, OptionsError, Source, USAGE_EXIT_CODE, control_port}; +use craft::automation::control::ControlChannel; +use craft::automation::server::{Listening, ServerLimits, listen_with}; +use craft::behavior::placement::Defaults; +use craft::dialogs::service::{FilePanels, FileService}; +use craft::host::target::{Backend, ShellInfo}; +use craft::host::{AppInfo, Host, Wake}; +use craft::platform::clipboard::{Clipboard, ClipboardImage, SystemClipboard}; +use craft::platform::logs::{self, LogNames}; +use craft::platform::open::FileIntake; +use craft::settings::Location; +use craft::ui::runtime::InstallSpec; +use craft::ui::runtime::env::SystemReader; +use craft::ui::runtime::windows::WindowHost; +use craft::ui::shell::app::{AppSpec, native_options}; +use craft::ui::shell::embed; +use craft::window::Prefix; +use craft::window::policy::{Frame, TitleBarPref, decide_for}; +use deckcraft_ui_egui::{Platform, SlideApp}; + +const NAMES: LogNames = LogNames::new("deckcraft"); +const PREFIX: Prefix = Prefix::new("DECKCRAFT"); +const ICON_128: &[u8] = include_bytes!("../../../assets/app-icon/hicolor/128x128/apps/ai.storyteller.deckcraft.png"); + +struct App { + app: SlideApp, + panels: FilePanels, + _control: Option, +} impl eframe::App for App { fn logic(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) { - #[cfg(target_os = "macos")] - apple_events::poll(&self.1, &mut self.0, ctx); - self.0.logic(ctx); - self.0.close_path(ctx); + self.app.logic(ctx); } /// Forward native raw input to the wrapped application once per frame, then hand the framework /// runtime this frame's root values. fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) { - self.0.raw_input_hook(ctx, raw); - self.0.before_input(ctx); + // egui-winit's WindowEvent::Focused arm emits WindowFocused. Only this pass's events + // trigger a refresh; a second pass with no input cannot repeat the activation. + if raw.events.iter().any(|event| matches!(event, egui::Event::WindowFocused(true))) { + craft::font_catalog::app::on_activated(); + } + self.app.raw_input_hook(ctx, raw); } fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) { - deckcraft_ui_egui::framework::before_ui(ui.ctx(), &*frame); - self.0.ui(ui); + #[cfg(not(target_arch = "wasm32"))] + embed::before_ui(ui.ctx(), frame); + self.app.ui(ui); + self.panels.pump(Some(frame)); } fn on_exit(&mut self) { - // The one exit path macOS has: run the hook exactly once (the Nightly session record). - if let Some(hook) = self.0.services.at_exit.take() { - hook(); - } - save_prefs(&self.0); - // The window is closing for good: a ready update's helper starts now and installs it once - // the process has exited. - self.0.start_pending_update(); - // macOS (#279): end the process here, before eframe tears the window down. AccessKit's - // macOS adapter subclasses the window's content view and restores its class on teardown; - // AppKit's Touch Bar support observes that view (KVO), so in the next display cycle - // `-[_NSTouchBarFinderObservation invalidate]` throws "not registered" and the quit ends - // in a crash report. eframe calls `on_exit` on every way of quitting (⌘Q, the close - // button, `app.quit`), once the unsaved-changes prompt has let the window close, and - // nothing after it is needed: the preferences are saved and the log file is unbuffered. - // `on_exit` only runs once the app exists, never on a failed start. Same as GridCraft #117. - #[cfg(target_os = "macos")] - self.0.cleanup_print_previews(); - #[cfg(target_os = "macos")] - std::process::exit(0); + self.app.leave(); } } -fn load_prefs(app: &mut SlideApp) { - if std::env::var_os("DECKCRAFT_NO_PREFS").is_some() { - return; - } - let Some(dir) = app_dirs::config_dir() else { return }; - let (ui, prefs) = deckcraft_ui_egui::settings::load(&dir); - if let Some(ui) = ui { - app.ui = ui; - } - if let Some(prefs) = prefs { - app.session.prefs = prefs; - } +fn desktop_platform(install: InstallSpec, settings: Location, wake: Wake, at_exit: Option>) -> (Platform, FilePanels) { + let (service, panels) = FileService::new(wake); + let host = Host::builder(AppInfo { + id: "deckcraft", + name: deckcraft_ui_egui::os_window::name_for(deckcraft_ui_egui::os_window::identity()), + version: env!("CARGO_PKG_VERSION"), + }) + .icon_png(ICON_128) + .files(Arc::new(service)) + .build(); + let frame = install.frame.as_ref().map_or(Frame::Native, |decision| decision.frame.clone()); + (Platform { install, host, settings, intake: None, audio_out: None, control: None, frame, at_exit }, panels) } -fn save_prefs(app: &SlideApp) { - if std::env::var_os("DECKCRAFT_NO_PREFS").is_some() { - return; - } - if let Some(dir) = app_dirs::config_dir() { - deckcraft_ui_egui::settings::save(&dir, &app.ui, &app.session.prefs); - } -} - -/// The desktop services. `native_wayland`: the window is a Wayland client (not Xwayland). -fn services(native_wayland: bool) -> Services { - // On native Wayland, egui-winit owns the clipboard through winit's data device, which carries - // text and PNG but no HTML. `pasteboard` (arboard, built for X11 only) would put a copy on the - // Xwayland selection instead and skip egui's Wayland claim, so Ctrl+V would read something - // else. There, text goes through egui and pictures arrive as `PasteImage` events. - let pasteboard = !native_wayland; - Services { - pick_open: Some(Box::new(|purpose: &str| { - let d = rfd::FileDialog::new(); - let d = match purpose { - "picture" => d.add_filter("Pictures", &["png", "jpg", "jpeg", "gif", "webp", "bmp", "tif", "tiff"]), - "audio" => d.add_filter( - "Audio", - &["wav", "mp3", "m4a", "m4b", "aac", "flac", "ogg", "oga", "opus", "aif", "aiff", "aifc", "caf", "wma", "weba", "mka"], - ), - "video" => d.add_filter("Video", &["mp4", "m4v", "mov", "webm", "mkv", "wmv"]), - "theme" => d.add_filter("Themes and presentations", &["thmx", "pptx", "potx", "ppsx"]).add_filter("Office Theme", &["thmx"]), - _ => d - .add_filter("Presentations", &["deckcraft", "pptx", "potx", "ppsx", "ppt", "pot", "pps"]) - .add_filter("DeckCraft", &["deckcraft"]) - .add_filter("PowerPoint", &["pptx", "potx", "ppsx"]) - .add_filter("PowerPoint 97-2003", &["ppt", "pot", "pps"]) - .add_filter("Outline", &["txt", "md"]), - }; - d.pick_file().map(|p| p.to_string_lossy().to_string()) - })), - pick_save: Some(Box::new(|name: &str| rfd::FileDialog::new().set_file_name(name).save_file().map(|p| p.to_string_lossy().to_string()))), - read: Some(Box::new(|p: &str| std::fs::read(p).map_err(|e| e.to_string()))), - write: Some(Box::new(|p: &str, b: &[u8]| std::fs::write(p, b).map_err(|e| e.to_string()))), - clipboard_image: pasteboard.then(|| Box::new(pasteboard::image_png) as Box Option>>), - clipboard_html: pasteboard.then(|| Box::new(pasteboard::html) as Box Option>), - clipboard_set_html: pasteboard.then(|| Box::new(pasteboard::set_html) as Box bool>), - // Media is mixed and clocked by the output device; `DECKCRAFT_NO_AUDIO` plays silently. - audio_out: std::env::var_os("DECKCRAFT_NO_AUDIO") - .is_none() - .then(|| Box::new(audio::CpalOut::default()) as Box), - ..Default::default() - } -} - -/// Displays winit lists for `window`, counting an output Wayland lists twice once. `None` when it -/// lists none: Presenter View then stays as it was. -#[cfg(all(unix, not(target_os = "macos")))] -fn display_count(window: &winit::window::Window) -> Option { - let n = window.available_monitors().collect::>().len(); - (n > 0).then_some(n) +fn decode_png(bytes: &[u8]) -> Option { + let rgba = image::load_from_memory_with_format(bytes, image::ImageFormat::Png).ok()?.into_rgba8(); + Some(ClipboardImage { width: rgba.width(), height: rgba.height(), rgba: rgba.into_raw() }) } const USAGE: &str = "\ -Usage: deckcraft [--control PORT] [--sample] [--show] [FILE...] +Usage: deckcraft [--control PORT] [--control-token TOKEN | --control-token-file PATH] [--sample] [--show] [FILE...] - --control PORT JSON control server on 127.0.0.1:PORT - --sample open the sample presentation - --show start the slide show - --help, -h print this help and exit - --version, -V print the version and exit + --control PORT JSON control server on 127.0.0.1:PORT + --control-token TOKEN authenticate with a 64-character hexadecimal token + --control-token-file PATH read the control token from a file + --sample open the sample presentation + --show start the slide show + --help, -h print this help and exit + --version, -V print the version and exit A PowerPoint Show (.ppsx) given last starts its slide show. "; @@ -172,11 +121,12 @@ A PowerPoint Show (.ppsx) given last starts its slide show. enum Startup { Help, Version, - Run { control_port: Option, files: Vec, sample: bool, show: bool }, + Run { control: ControlOptions, files: Vec, sample: bool, show: bool }, } /// `--help` and `--version` leave before the window and the log file. -fn startup(mut control_port: Option, args: impl IntoIterator) -> Startup { +fn startup(nightly: bool, args: impl IntoIterator) -> Result { + let mut flags = ControlOptions::default(); let mut files = Vec::new(); let mut sample = false; let mut show = false; @@ -188,17 +138,42 @@ fn startup(mut control_port: Option, args: impl IntoIterator files.extend(args.by_ref()); break; } - "--control" => control_port = args.next().and_then(|p| p.parse().ok()), + "--control" | "--control-token" | "--control-token-file" => { + let value = args.next().ok_or_else(|| format!("a value is required for '{a}'"))?; + match a.as_str() { + "--control" => { + let port = + control_port(&value).map_err(|_| OptionsError::NotAPort { value, shown: "--control ".into() }.to_string())?; + flags.port = Some(port); + flags.sources.port = Some(Source::Flag); + } + "--control-token" => { + flags.token = Some(value); + flags.sources.token = Some(Source::Flag); + } + _ => { + flags.token_file = Some(value.into()); + flags.sources.token_file = Some(Source::Flag); + } + } + } "--sample" => sample = true, "--show" => show = true, - "--version" | "-V" => return Startup::Version, - "--help" | "-h" => return Startup::Help, + "--version" | "-V" => return Ok(Startup::Version), + "--help" | "-h" => return Ok(Startup::Help), // The process serial number older macOS adds when Finder launches the app. a if a.starts_with("-psn_") => {} _ => files.push(a), } } - Startup::Run { control_port, files, sample, show } + let names = EnvNames::for_app("DECKCRAFT"); + let control = if nightly { + ControlOptions::merged(flags, ControlOptions::default()) + } else { + ControlOptions::resolve(flags, &names).map_err(|e| e.to_string())? + }; + control.check(&FlagNames::default(), &names).map_err(|e| e.to_string())?; + Ok(Startup::Run { control, files, sample, show }) } fn app_icon() -> Option { @@ -212,42 +187,44 @@ fn app_icon() -> Option { /// Select the immutable launch profile before any startup service or side effect. fn prepare_launch() -> Option> { - // The trusted Launcher protocol is decided before logger/crash/update/font/prefs access. + // The trusted Launcher protocol (or direct nightly self-isolation) is decided before + // logger/crash/update/font/prefs access. let argv: Vec<_> = std::env::args_os().skip(1).collect(); - // Plain `--version`, or the Launcher's `--launch-profile nightly-v1 --profile-root - // --version`: answered before root validation, process identity, IPC or any window. - if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && (build_flavor::version_query(&argv) || launch_profile::version_query(&argv)) + // Preserve standalone version probes in environments without a resolvable profile directory. + if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 + && argv.len() == 1 + && argv.first().is_some_and(|arg| arg == "--version" || arg == "-V") { use std::io::Write as _; let _ = writeln!(std::io::stdout(), "DeckCraft {}", build_flavor::version(build_flavor::COMPILED, deckcraft_ui_egui::flavor::version())); return None; } - let early = launch_profile::parse(argv) - .and_then(|launch| { - build_flavor::require_profile(build_flavor::COMPILED, &launch.profile)?; - initialize_nightly_process_identity().map_err(|error| error.to_string())?; - Ok(launch) - }) - .and_then(|launch| { - launch_profile::prepare(launch, |root| { - launch_profile::validate_root(root, |key| std::env::var_os(key), std::env::current_exe().ok().as_deref()) - }) - }) - .unwrap_or_else(|error| { - report_launch_profile_error(&error); - std::process::exit(2) - }); + let early = launch_profile::prepare(build_flavor::COMPILED, argv).unwrap_or_else(|error| { + report_launch_profile_error(&error.to_string()); + std::process::exit(2) + }); + // Plain `--version`, or the Launcher's `--launch-profile nightly-v1 --profile-root + // [--] --version`: answered before process identity, IPC or any window. + if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && early.is_version_query() { + use std::io::Write as _; + let _ = writeln!(std::io::stdout(), "DeckCraft {}", build_flavor::version(build_flavor::COMPILED, deckcraft_ui_egui::flavor::version())); + return None; + } + if let Err(error) = initialize_nightly_process_identity() { + report_launch_profile_error(&error.to_string()); + std::process::exit(2); + } let identity = if early.profile.is_nightly() { deckcraft_ui_egui::os_window::LaunchIdentity::NightlyV1 } else { deckcraft_ui_egui::os_window::LaunchIdentity::Stable }; - if let Err(error) = launch_profile::install(early.profile).and_then(|()| deckcraft_ui_egui::os_window::select_identity(identity)) { + if let Err(error) = deckcraft_ui_egui::os_window::select_identity(identity) { report_launch_profile_error(&error); std::process::exit(2); } - Some(early.args) + Some(early.passthrough_args) } fn initialize_nightly_process_identity() -> Result<(), process_identity::IdentityError> { @@ -287,6 +264,9 @@ fn report_launch_profile_error(error: &str) { /// Install logging, parse startup arguments and environment, launch the native app, and /// propagate an eframe startup failure. +/// The log folder's name in the profile (and the config folder), which the profile check expects. +pub(crate) const LOG_DIR: &str = "logs"; + fn main() -> eframe::Result { let Some(arguments) = prepare_launch() else { return Ok(()) }; let nightly = launch_profile::current().is_nightly(); @@ -305,9 +285,9 @@ fn main() -> eframe::Result { let notice_shown = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); let exit_session = session.clone(); let exit_notice = notice_shown.clone(); - // First, so every start-up record (and the engine's panic hook, installed with the first - // Session) is captured; see `logging`. - let logger = logging::install(); + // The engine's first Session chains its panic hook to the platform crash hook. + let logger = logs::install(NAMES); + logs::crash::install("DeckCraft", env!("CARGO_PKG_VERSION"), None); // Nightly is managed by ArtCraft Launcher: no stable self-update helper runs in it. if !nightly && let Some(done) = craft_update::self_update::finish(&deckcraft_ui_egui::UPDATE_APP, &std::env::args_os().skip(1).collect::>()) @@ -318,10 +298,11 @@ fn main() -> eframe::Result { } return Ok(()); } - let (control_port, files, sample, show) = match startup( - if nightly { None } else { std::env::var("DECKCRAFT_CONTROL_PORT").ok().and_then(|p| p.parse().ok()) }, - arguments.into_iter().map(|a| a.to_string_lossy().into_owned()), - ) { + let launch = startup(nightly, arguments.into_iter().map(|a| a.to_string_lossy().into_owned())).unwrap_or_else(|error| { + eprintln!("error: {error}\nFor more information, try '--help'."); + std::process::exit(USAGE_EXIT_CODE); + }); + let (control, files, sample, show) = match launch { Startup::Help => { print!("{USAGE}"); return Ok(()); @@ -330,14 +311,15 @@ fn main() -> eframe::Result { println!("deckcraft {}", env!("CARGO_PKG_VERSION")); return Ok(()); } - Startup::Run { control_port, files, sample, show } => (control_port, files, sample, show), + Startup::Run { control, files, sample, show } => (control, files, sample, show), }; log::info!("DeckCraft {} ({} {})", deckcraft_ui_egui::flavor::version(), std::env::consts::OS, std::env::consts::ARCH); // The log file lives under the settings directory; opened after the arguments, so `--help` and // `--version` leave no file behind. Records logged until now are written to it first. + let log_dir = app_dirs::config_dir().map(|dir| dir.join(LOG_DIR)); if let Some(logger) = logger { - match app_dirs::config_dir().map(|d| logger.attach_dir(&d.join(logging::LOG_DIR))) { + match log_dir.as_deref().map(|dir| logger.attach_dir(dir)) { Some(Ok(path)) => log::info!("log file {}", path.display()), Some(Err(e)) => log::warn!("no log file: {e}"), None => { @@ -346,74 +328,111 @@ fn main() -> eframe::Result { } } } - let mut options = eframe::NativeOptions { - viewport: egui::ViewportBuilder::default() - .with_title(deckcraft_ui_egui::os_window::name_for(deckcraft_ui_egui::os_window::identity())) - .with_inner_size([1440.0, 900.0]) - .with_min_inner_size([900.0, 560.0]) - .with_drag_and_drop(true) - .with_fullsize_content_view(true) - .with_titlebar_shown(false) - .with_title_shown(false), - ..Default::default() - }; - options.viewport = options.viewport.with_app_id(deckcraft_ui_egui::os_window::app_id()); - if let Some(icon) = app_icon() { - options.viewport = options.viewport.with_icon(icon); - } + logs::crash::install("DeckCraft", env!("CARGO_PKG_VERSION"), log_dir); #[cfg(all(unix, not(target_os = "macos")))] - let x11 = match display::choose_from_env() { - display::Choice::X11 => true, - display::Choice::Default => false, + let backend = match display::choose_from_env() { + display::Choice::X11 => Backend::X11, + display::Choice::Default => Backend::from_env(), display::Choice::None => { // winit's own error says little to someone who started DeckCraft from a console. log::error!("no display: DISPLAY and WAYLAND_DISPLAY are not set"); eprintln!("DeckCraft needs a graphical session: neither DISPLAY nor WAYLAND_DISPLAY is set."); - false + Backend::from_env() } }; - // `Default` lets winit choose, and winit takes Wayland whenever `WAYLAND_DISPLAY` is set. #[cfg(not(all(unix, not(target_os = "macos"))))] - let x11 = false; + let backend = Backend::from_env(); + let decision = decide_for(PREFIX, backend, if cfg!(target_os = "macos") { TitleBarPref::Integrated } else { TitleBarPref::System }); + let spec = AppSpec::new( + deckcraft_ui_egui::os_window::app_id(), + deckcraft_ui_egui::os_window::name_for(deckcraft_ui_egui::os_window::identity()), + Defaults::new([1440.0, 900.0], [900.0, 560.0]), + ) + .shell_info(ShellInfo::default().backend(backend)) + .frame(decision.clone()); + let mut options = native_options(&spec); + options.viewport = options.viewport.with_drag_and_drop(true); + if let Some(icon) = app_icon() { + options.viewport = options.viewport.with_icon(icon); + } #[cfg(all(unix, not(target_os = "macos")))] - let native_wayland = !x11 && std::env::var_os("WAYLAND_DISPLAY").is_some_and(|w| !w.is_empty()); - #[cfg(not(all(unix, not(target_os = "macos"))))] - let native_wayland = false; - #[cfg(all(unix, not(target_os = "macos")))] - if x11 { + if backend == Backend::X11 { options.event_loop_builder = Some(Box::new(|b| { use winit::platform::x11::EventLoopBuilderExtX11; b.with_x11(); })); } - // Before eframe creates the wgpu instance: default Windows to DirectX 12 with FXC (see graphics.rs). - #[cfg(target_os = "windows")] - graphics::configure(&mut options, eframe::wgpu::Backends::from_env(), eframe::wgpu::Dx12Compiler::from_env()); - // Registered before the event loop starts, so it catches the Finder event that launched us as - // well as later ones. Lives until the event loop returns; the app creator only borrows it. + // eframe supplies the display handle when the event loop exists. + let mut setup = eframe::egui_wgpu::WgpuSetupCreateNew::without_display_handle(); + craft::gpu::configure(&mut setup); + options.wgpu_options.wgpu_setup = eframe::egui_wgpu::WgpuSetup::CreateNew(setup); + let context = Arc::new(OnceLock::::new()); + let wake_context = context.clone(); + let wake = Wake::new(move || { + if let Some(ctx) = wake_context.get() { + ctx.request_repaint(); + } + }); + let font_wake = wake.clone(); + craft::font_catalog::app::start(craft::font_catalog::app::AppFonts { + dirs: craft::font_catalog::office_font_dirs(&craft::font_catalog::FontEnv::from_process()), + on_change: Some(Arc::new(move |_| font_wake.wake())), + ..Default::default() + }); + // Installation precedes the event loop so Finder's launch event reaches the same intake. + let (intake, _sender) = FileIntake::new(wake.clone()); #[cfg(target_os = "macos")] - let apple_events = apple_events::AppleEvents::install(); - #[cfg(target_os = "macos")] - let apple_events = &apple_events; + let _apple = craft::platform::open::apple_events::install(_sender.clone()); let creator_notice = notice_shown.clone(); - let mut services = services(native_wayland); - // The Nightly session record is finished exactly once, on the clean exit path macOS has. - services.at_exit = Some(Box::new(move || { + let at_exit: Option> = Some(Box::new(move || { nightly_session::finish_once(&exit_session, exit_notice.load(std::sync::atomic::Ordering::Relaxed)); })); let result = eframe::run_native( deckcraft_ui_egui::os_window::name_for(deckcraft_ui_egui::os_window::identity()), options, Box::new(move |cc| { - deckcraft_ui_egui::framework::install(&cc.egui_ctx, x11)?; - deckcraft_ui_egui::install_ime_pass_hooks(&cc.egui_ctx); - let mut app = SlideApp::new(Session::new(), services); - // Presenter View asks winit how many displays there are when a show starts. - #[cfg(all(unix, not(target_os = "macos")))] - if let Some(window) = cc.winit_window().cloned() { - app.services.displays = Some(Box::new(move || display_count(&window))); + let ctx = &cc.egui_ctx; + let _ = context.set(ctx.clone()); + #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd", target_os = "netbsd", target_os = "dragonfly"))] + let window_system = embed::listed_monitors(cc); + #[cfg(not(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd", target_os = "netbsd", target_os = "dragonfly")))] + // PLAN: plan error: SystemWindows is craft::window::system::SystemWindows, supplied by AppSpec, not craft::ui::runtime::SystemWindows. + let window_system = spec.window_system; + let appearance_wake = wake.clone(); + let install = InstallSpec::new(spec.shell_info, window_system) + .placement(spec.placement) + .system(SystemReader::start(move || appearance_wake.wake())) + .app_id(spec.app_id) + .frame(decision) + .clipboard(Clipboard::new(SystemClipboard::new().decoder(decode_png))); + let settings = if std::env::var_os("DECKCRAFT_NO_PREFS").is_some() { + Location::Memory + } else { + app_dirs::config_dir().map_or(Location::Memory, Location::Dir) + }; + let (mut platform, panels) = desktop_platform(install, settings, wake, at_exit); + platform.intake = Some(intake); + // The output device clocks media; disabling audio leaves playback silent. + platform.audio_out = + std::env::var_os("DECKCRAFT_NO_AUDIO").is_none().then(|| Box::new(audio::CpalOut::default()) as Box); + let mut listening = None; + if let Some(port) = control.port { + let token = control.server_token().unwrap_or_else(|error| { + eprintln!("error: {error}\nFor more information, try '--help'."); + std::process::exit(USAGE_EXIT_CODE); + }); + eprintln!("deckcraft: {}", control.token_notice(&token)); + let limits = ServerLimits::default().max_request(256 << 20).max_response(256 << 20); + match listen_with(port, token, WindowHost::of(ctx), limits) { + Ok((rx, server)) => { + log::info!("control server listening on {}", server.addr); + platform.control = Some(ControlChannel::new(rx)); + listening = Some(server); + } + Err(error) => log::error!("control server: {error}"), + } } - load_prefs(&mut app); + let mut app = SlideApp::new(ctx, platform)?; if !nightly { // Nightly is managed by ArtCraft Launcher: no self-update prompt or stable feed. app.enable_update_checks(); @@ -436,11 +455,6 @@ fn main() -> eframe::Result { app.set_status("DeckCraft Nightly closed unexpectedly last time."); creator_notice.store(true, std::sync::atomic::Ordering::Relaxed); } - app.integrated_titlebar = cfg!(target_os = "macos"); - if let Some(port) = control_port { - let rx = control_server::start(port, cc.egui_ctx.clone()); - app = app.with_control(rx); - } if sample && let Err(e) = deckcraft_engine::sample::open_sample(&mut app.session) { log::error!("sample: {e}"); } @@ -451,11 +465,7 @@ fn main() -> eframe::Result { if show { app.start_show(0, false); } - Ok(Box::new(App( - app, - #[cfg(target_os = "macos")] - apple_events.connect(&cc.egui_ctx), - ))) + Ok(Box::new(App { app, panels, _control: listening })) }), ); // The exit hook normally finished it already; this covers a start that never created a window. @@ -467,33 +477,6 @@ fn main() -> eframe::Result { mod tests { use super::*; - /// #279: on macOS the process ends inside `on_exit`, before eframe would tear the window down. - /// The check runs in a child (this test binary again), since on macOS it ends the process. - #[test] - fn on_exit_ends_the_process_on_macos() { - if std::env::var_os("DECKCRAFT_TEST_ON_EXIT").is_some() { - let mut app = App( - SlideApp::new(Session::new(), Services::default()), - #[cfg(target_os = "macos")] - fmv_macos_events::Inbox::default(), - ); - println!("calling on_exit"); - eframe::App::on_exit(&mut app); - println!("on_exit returned"); - return; - } - let out = std::process::Command::new(std::env::current_exe().unwrap()) - .args(["--exact", "tests::on_exit_ends_the_process_on_macos", "--nocapture"]) - .env("DECKCRAFT_TEST_ON_EXIT", "1") - .env("DECKCRAFT_NO_PREFS", "1") - .output() - .unwrap(); - let stdout = String::from_utf8_lossy(&out.stdout); - assert!(out.status.success(), "{stdout}"); - assert!(stdout.contains("calling on_exit"), "the child didn't run the test: {stdout}"); - assert_eq!(stdout.contains("on_exit returned"), !cfg!(target_os = "macos"), "{stdout}"); - } - /// The egui 0.37 migration (#1350) left `clipboard` out of eframe's features. egui then /// simulated a clipboard inside the app: nothing pasted from other apps, and Ctrl+C/Ctrl+V /// lost text that went out as HTML. Keep the OS clipboard on. @@ -504,37 +487,11 @@ mod tests { assert!(eframe.contains("\"clipboard\""), "eframe must enable the OS clipboard: {eframe}"); } - /// On native Wayland, the X11-only pasteboard would bypass egui's Wayland clipboard; elsewhere - /// it carries HTML and pictures beside egui's text. - #[test] - fn the_pasteboard_stays_off_native_wayland() { - let s = services(true); - assert!(s.clipboard_html.is_none() && s.clipboard_set_html.is_none() && s.clipboard_image.is_none()); - let s = services(false); - assert!(s.clipboard_html.is_some() && s.clipboard_set_html.is_some() && s.clipboard_image.is_some()); - } - - #[test] - fn help_exits_instead_of_opening_a_file() { - assert!(matches!(startup(None, ["--help".to_string()]), Startup::Help)); - assert!(matches!(startup(None, ["-h".to_string()]), Startup::Help)); - assert!(matches!(startup(None, ["talk.pptx".to_string(), "--help".to_string()]), Startup::Help)); - assert!(matches!(startup(None, ["--version".to_string()]), Startup::Version)); - let launch = startup(Some(9), ["--sample".to_string(), "--control".to_string(), "4242".to_string(), "talk.pptx".to_string()]); - assert!(matches!(launch, Startup::Run { .. })); - if let Startup::Run { control_port, files, sample, show } = launch { - assert_eq!(control_port, Some(4242)); - assert_eq!(files, ["talk.pptx".to_string()]); - assert!(sample); - assert!(!show); - } - } - /// The delimiter is the Nightly Launcher's file list, never a file name of its own. #[test] fn the_delimiter_ends_the_flags_and_leaves_only_files() { - let launch = startup(None, ["--", "--control", "deck.pptx"].map(str::to_string)); - assert!(matches!(launch, Startup::Run { control_port: None, .. })); + let launch = startup(true, ["--", "--control", "deck.pptx"].map(str::to_string)).unwrap(); + assert!(matches!(&launch, Startup::Run { control, .. } if control.port.is_none())); if let Startup::Run { files, .. } = launch { assert_eq!(files, ["--control".to_string(), "deck.pptx".to_string()]); } @@ -547,39 +504,26 @@ mod tests { assert_eq!(deckcraft_ui_egui::os_window::name_for(deckcraft_ui_egui::os_window::LaunchIdentity::NightlyV1), "DeckCraft Nightly"); } - /// The exit hook (the Nightly session record) runs once, on the one exit path macOS has. - /// The check runs in a child with `DECKCRAFT_NO_PREFS=1`: `on_exit` saves the preferences - /// otherwise, and this test never loads the ones already on the machine. Not on macOS - /// itself: there `on_exit` ends the process, which is the behaviour the test above checks. - #[cfg(not(target_os = "macos"))] + /// Repeated exit paths must not finish a successor's Nightly record or start an update twice. #[test] fn leaving_runs_the_exit_hook_once() { - if std::env::var_os("DECKCRAFT_TEST_EXIT_HOOK").is_some() { - let runs = std::rc::Rc::new(std::cell::Cell::new(0)); - let counted = runs.clone(); - let services = Services { at_exit: Some(Box::new(move || counted.set(counted.get() + 1))), ..Default::default() }; - let mut app = App(SlideApp::new(Session::new(), services)); - eframe::App::on_exit(&mut app); - assert_eq!(runs.get(), 1); - eframe::App::on_exit(&mut app); - assert_eq!(runs.get(), 1, "a second exit must not run the hook again"); - println!("exit hook ran once"); - return; - } - let out = std::process::Command::new(std::env::current_exe().unwrap()) - .args(["--exact", "tests::leaving_runs_the_exit_hook_once", "--nocapture"]) - .env("DECKCRAFT_TEST_EXIT_HOOK", "1") - .env("DECKCRAFT_NO_PREFS", "1") - .output() - .unwrap(); - let stdout = String::from_utf8_lossy(&out.stdout); - assert!(out.status.success(), "{stdout}"); - assert!(stdout.contains("exit hook ran once"), "the child didn't run the test: {stdout}"); + let ctx = egui::Context::default(); + let runs = std::rc::Rc::new(std::cell::Cell::new(0)); + let counted = runs.clone(); + let install = InstallSpec::new(ShellInfo::default(), Arc::new(craft::window::system::SystemWindows)); + let (platform, panels) = desktop_platform(install, Location::Memory, Wake::none(), Some(Box::new(move || counted.set(counted.get() + 1)))); + let mut app = App { app: SlideApp::new(&ctx, platform).unwrap(), panels, _control: None }; + assert_eq!(runs.get(), 0); + app.app.leave(); + assert_eq!(runs.get(), 1); + app.app.leave(); + eframe::App::on_exit(&mut app); + assert_eq!(runs.get(), 1, "repeating the exit path must not repeat its hook"); } #[test] fn finder_process_serial_number_is_not_a_file() { - let launch = startup(None, ["-psn_0_1234567".to_string(), "talk.pptx".to_string()]); + let launch = startup(true, ["-psn_0_1234567".to_string(), "talk.pptx".to_string()]).unwrap(); assert!(matches!(launch, Startup::Run { .. })); if let Startup::Run { files, .. } = launch { assert_eq!(files, ["talk.pptx".to_string()]); diff --git a/apps/deckcraft/src/pasteboard.rs b/apps/deckcraft/src/pasteboard.rs deleted file mode 100644 index 98626295d..000000000 --- a/apps/deckcraft/src/pasteboard.rs +++ /dev/null @@ -1,77 +0,0 @@ -//! System pasteboard: HTML rich text, and a picture (TIFF on macOS, via arboard). -//! -//! Pages keeps bold, italic and underline when the pasteboard carries HTML plus the same plain -//! words. A shape with no text is copied as an image by the UI; this module only reads a picture -//! back (Keynote's TIFF) as PNG bytes. - -/// HTML currently on the pasteboard, when there is some. -pub fn html() -> Option { - let mut cb = arboard::Clipboard::new().ok()?; - let html = cb.get().html().ok()?; - let html = html.trim(); - if html.is_empty() { None } else { Some(html.to_string()) } -} - -/// Write `html` and the plain alternative `text`. `false` when the pasteboard refuses it. -pub fn set_html(html: &str, text: &str) -> bool { - let Ok(mut cb) = arboard::Clipboard::new() else { return false }; - cb.set_html(html, Some(text)).is_ok() -} - -/// The pasteboard picture as PNG bytes (TIFF on macOS is decoded by arboard). -pub fn image_png() -> Option> { - let mut cb = arboard::Clipboard::new().ok()?; - let img = cb.get_image().ok()?; - let width = u32::try_from(img.width).ok()?; - let height = u32::try_from(img.height).ok()?; - let rgba = image::RgbaImage::from_raw(width, height, img.bytes.into_owned())?; - let mut out = Vec::new(); - rgba.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).ok()?; - Some(out) -} - -#[cfg(test)] -mod tests { - use std::borrow::Cow; - - /// Puts HTML and a 1×1 picture on the macOS pasteboard and reads them back. - /// Restores whatever plain text was there. Other platforms return immediately. - #[test] - fn html_and_a_picture_round_trip_on_macos() { - if !cfg!(target_os = "macos") { - return; - } - let previous = arboard::Clipboard::new().ok().and_then(|mut cb| cb.get_text().ok()); - let _restore = Restore(previous); - assert!(super::set_html("DeckCraft", "DeckCraft"), "set html"); - let html = super::html().unwrap_or_default(); - assert!(html.contains("") || html.contains(""), "{html}"); - let text = arboard::Clipboard::new().ok().and_then(|mut cb| cb.get_text().ok()).unwrap_or_default(); - assert_eq!(text, "DeckCraft"); - let mut cb = arboard::Clipboard::new().expect("pasteboard"); - let img = arboard::ImageData { width: 1, height: 1, bytes: Cow::Owned(vec![255, 0, 0, 255]) }; - cb.set_image(img).expect("set image"); - drop(cb); - let png = super::image_png().expect("png"); - let decoded = image::load_from_memory(&png).expect("decode").to_rgba8(); - let p = decoded.get_pixel(0, 0); - assert!(p[0] > 200 && p[1] < 40 && p[3] > 200, "{p:?}"); - } - - /// Puts the previous plain text back, including when the test fails halfway. - struct Restore(Option); - - impl Drop for Restore { - fn drop(&mut self) { - let Ok(mut cb) = arboard::Clipboard::new() else { return }; - match self.0.take() { - Some(t) => { - let _ = cb.set_text(t); - } - None => { - let _ = cb.clear(); - } - } - } - } -} diff --git a/apps/deckcraft/src/process_identity.rs b/apps/deckcraft/src/process_identity.rs index 9d2e1c179..aad4be3bf 100644 --- a/apps/deckcraft/src/process_identity.rs +++ b/apps/deckcraft/src/process_identity.rs @@ -39,32 +39,3 @@ pub fn initialize(nightly: bool, app_id: &str) -> Result<(), IdentityError> { fn configure(explicit_nightly: bool, app_id: &str, set: impl FnOnce(&str) -> Result<(), String>) -> Result<(), String> { if explicit_nightly { set(app_id) } else { Ok(()) } } - -#[cfg(test)] -mod tests { - use super::*; - #[test] - fn stable_does_not_call_the_explicit_identity_api() { - configure(false, "nightly-id", |_| panic!("stable identity must remain implicit")).unwrap(); - } - - #[test] - fn nightly_applies_the_supplied_identity_once() { - let calls = std::cell::Cell::new(0); - configure(true, "nightly-id", |id| { - assert_eq!(id, "nightly-id"); - calls.set(calls.get() + 1); - Ok(()) - }) - .unwrap(); - assert_eq!(calls.get(), 1); - } - - #[test] - fn native_identity_failure_is_returned_instead_of_starting_a_window() { - let started = std::cell::Cell::new(false); - let result = configure(true, "nightly-id", |_| Err("native identity refused".into())).map(|()| started.set(true)); - assert_eq!(result.unwrap_err(), "native identity refused"); - assert!(!started.get()); - } -} diff --git a/apps/deckcraft/src/profile_root.rs b/apps/deckcraft/src/profile_root.rs index a7e9b3bfc..10a816b60 100644 --- a/apps/deckcraft/src/profile_root.rs +++ b/apps/deckcraft/src/profile_root.rs @@ -1,622 +1,238 @@ -//! App-owned nightly profile fences; no stable fallback, migration or process environment changes. +//! DeckCraft's nightly profile specification and extra forbidden-root fence for `craft-nightly`. use std::ffi::OsString; +use std::path::PathBuf; -use crate::app_dirs::{PORTABLE_DATA_DIR, portable_marker}; -use std::path::{Component, Path, PathBuf}; +use craft_nightly::AppProfileSpec; -/// The DeckCraft Nightly Flatpak app id (`packaging/linux/flatpak-bundle.sh`), the one Flatpak -/// instance a Nightly profile may inherit. -pub const NIGHTLY_FLATPAK_ID: &str = "ai.storyteller.deckcraft.nightly"; +/// Canonical application identifier for DeckCraft nightly profile isolation. +pub const APP_ID: &str = "deckcraft"; -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum Platform { - Windows, - Linux, - Mac, +const STABLE_DIR_NAMES: &[&str] = &["DeckCraft", "deckcraft"]; +const FOLDER_ONLY_ENTRIES: &[&str] = &["Recovery", "Dictionaries", crate::LOG_DIR]; + +/// Builds DeckCraft's [`AppProfileSpec`] for `craft-nightly`, preserving DeckCraft's exact +/// stable directory names, portable markers, folder-only entries, and OS-specific extra +/// forbidden roots. +pub fn spec() -> AppProfileSpec { + spec_with(|k| std::env::var_os(k)) } -impl Platform { - fn current() -> Result { - match std::env::consts::OS { - "windows" => Ok(Self::Windows), - "linux" => Ok(Self::Linux), - "macos" => Ok(Self::Mac), - _ => Err("nightly-v1 is not defined for this operating system".into()), - } - } - - fn ignores_case(self) -> bool { - self != Self::Linux +fn spec_with(env: impl Fn(&str) -> Option) -> AppProfileSpec { + AppProfileSpec { + app_id: APP_ID, + display_name: "DeckCraft", + stable_dir_names: STABLE_DIR_NAMES, + stable_package_id: "ai.storyteller.deckcraft", + nightly_package_id: "ai.storyteller.deckcraft.nightly", + profile_root_env: None, + forbidden_env_vars: &[], + portable_markers: &crate::app_dirs::PORTABLE_MARKERS, + folder_only_entries: FOLDER_ONLY_ENTRIES, + extra_forbidden_roots: extra_forbidden_roots(env), } } -fn absolute(path: PathBuf, label: &str) -> Result { - if !path.is_absolute() || path.components().any(|c| matches!(c, Component::ParentDir)) { - return Err(format!("{label} must be absolute and contain no parent traversal")); +#[cfg(any(unix, target_os = "windows"))] +fn non_empty_abs(env: &impl Fn(&str) -> Option, key: &str) -> Option { + let value = env(key)?; + if value.is_empty() { + return None; } - Ok(path) + let path = PathBuf::from(value); + path.is_absolute().then_some(path) } -fn required_base(env: &impl Fn(&str) -> Option, key: &str) -> Result { - let value = env(key).filter(|v| !v.is_empty()).ok_or_else(|| format!("cannot establish the stable {key} boundary"))?; - absolute(PathBuf::from(value), key) -} - -fn xdg_base(env: &impl Fn(&str) -> Option, key: &str, fallback: &str) -> Result { - match env(key).filter(|v| !v.is_empty()) { - Some(value) => absolute(PathBuf::from(value), key), - None => Ok(required_base(env, "HOME")?.join(fallback)), - } -} - -/// Resolve existing ancestors before creating anything. A dangling link or inaccessible ancestor -/// is not a missing directory that may be replaced or followed later. -fn canonical_future(path: &Path) -> Result { - let mut parent = path; - let mut missing = Vec::new(); - loop { - match std::fs::symlink_metadata(parent) { - Ok(_) => break, - Err(error) if error.kind() == std::io::ErrorKind::NotFound => { - missing.push(parent.file_name().ok_or("the profile root has no existing ancestor")?.to_os_string()); - parent = parent.parent().ok_or("the profile root has no existing ancestor")?; - } - Err(error) => return Err(format!("cannot inspect the profile boundary: {error}")), - } - } - let mut resolved = std::fs::canonicalize(parent).map_err(|e| format!("cannot resolve the profile boundary: {e}"))?; - for part in missing.into_iter().rev() { - resolved.push(part); - } - Ok(resolved) -} - -fn overlaps(a: &Path, b: &Path, platform: Platform) -> bool { - let parts = |p: &Path| { - p.components() - .map(|c| { - let value = c.as_os_str().to_string_lossy().into_owned(); - if platform.ignores_case() { value.to_lowercase() } else { value } - }) - .collect::>() - }; - let (a, b) = (parts(a), parts(b)); - a.starts_with(&b) || b.starts_with(&a) -} - -fn installation_boundary(platform: Platform, exe: &Path) -> Result { - let parent = exe.parent().ok_or("cannot establish the installation boundary")?; - if platform == Platform::Mac { - // A profile in Resources is still inside the versioned install, not beside MacOS. - if let Some(bundle) = exe.ancestors().find(|p| p.extension().is_some_and(|ext| ext.eq_ignore_ascii_case("app"))) { - return Ok(bundle.to_path_buf()); - } - } - Ok(parent.to_path_buf()) -} - -fn forbidden_roots(platform: Platform, env: &impl Fn(&str) -> Option, exe: &Path) -> Result, String> { - let mut roots = match platform { - Platform::Windows => { - let mut roots = ["APPDATA", "LOCALAPPDATA"] - .into_iter() - .map(|key| required_base(env, key).map(|p| p.join("DeckCraft"))) - .collect::, _>>()?; - // The MSI's default per-user and per-machine folders (install-policy.wxi). A custom - // install folder is not known here; the executable's own folder is fenced below. - roots.push(required_base(env, "LOCALAPPDATA")?.join("Programs").join("ArtCraft").join("DeckCraft")); - for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] { - if let Some(base) = env(key).filter(|v| !v.is_empty()) { - roots.push(absolute(PathBuf::from(base), key)?.join("ArtCraft").join("DeckCraft")); - } - } - roots - } - Platform::Linux => { - let mut roots = - [("XDG_CONFIG_HOME", ".config"), ("XDG_DATA_HOME", ".local/share"), ("XDG_CACHE_HOME", ".cache"), ("XDG_STATE_HOME", ".local/state")] - .into_iter() - .map(|(key, fallback)| xdg_base(env, key, fallback).map(|p| p.join("deckcraft"))) - .collect::, _>>()?; - roots.extend(["/usr/bin/deckcraft", "/usr/local/bin/deckcraft", "/opt/deckcraft"].map(PathBuf::from)); - // The stable Flatpak keeps its data in its own per-app folder. - roots.push(required_base(env, "HOME")?.join(".var/app/ai.storyteller.deckcraft")); - roots - } - Platform::Mac => { - let home = required_base(env, "HOME")?; - let library = home.join("Library"); - vec![ - library.join("Application Support/DeckCraft"), - library.join("Caches/DeckCraft"), - library.join("Caches/ai.storyteller.deckcraft"), - library.join("Preferences/DeckCraft"), - library.join("Preferences/ai.storyteller.deckcraft.plist"), - library.join("Saved Application State/ai.storyteller.deckcraft.savedState"), - home.join("Applications/DeckCraft.app"), - PathBuf::from("/Applications/DeckCraft.app"), - ] - } - }; - roots.push(installation_boundary(platform, exe)?); - roots.into_iter().map(|p| canonical_future(&p)).collect() -} - -fn private_subdirectory(root: &Path, name: impl AsRef, label: &str) -> Result { - let chosen = canonical_future(&absolute(root.to_path_buf(), "the nightly profile root")?)?; - let child = canonical_future(&chosen.join(name))?; - if child == chosen || !child.starts_with(&chosen) { - return Err(format!("the nightly {label} must stay inside its selected profile")); - } - Ok(child) -} - -/// Every existing entry directly in the profile (Dictionaries, logs, settings and so on) must -/// resolve inside it, so a link there cannot point Nightly's writes at another app's data. -fn entries_stay_inside(root: &Path) -> Result<(), String> { - let entries = match std::fs::read_dir(root) { - Ok(entries) => entries, - Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()), - Err(error) => return Err(format!("cannot inspect the nightly profile: {error}")), - }; - for entry in entries { - let entry = entry.map_err(|e| format!("cannot inspect the nightly profile: {e}"))?; - private_subdirectory(root, entry.file_name(), "profile entry")?; - } - // The one nested file Nightly writes itself: a link at Dictionaries/user.dic would append - // "add to dictionary" words to the stable app's file instead of this profile's. - private_subdirectory(root, std::path::Path::new("Dictionaries").join("user.dic"), "user dictionary")?; - Ok(()) -} - -/// Recognise a portable data namespace in both the supplied and resolved path. DeckCraft ships no -/// portable package, so this only refuses a hand-made copy; it is not an inventory of arbitrary -/// custom Stable overrides or a Launcher ownership proof. -fn is_portable_layout(path: &Path, platform: Platform) -> bool { - // Above the chosen folder itself, a marker only counts beside a DeckCraft executable, so an - // unrelated portable.txt higher up (in a user folder or at a drive root) does not refuse it. - path.ancestors().enumerate().any(|(depth, ancestor)| { - portable_marker(ancestor).is_some() && (depth == 0 || ["deckcraft.exe", "deckcraft"].iter().any(|exe| ancestor.join(exe).is_file())) - }) || path.components().any(|component| match component { - Component::Normal(name) if platform.ignores_case() => name.to_string_lossy().eq_ignore_ascii_case(PORTABLE_DATA_DIR), - Component::Normal(name) => name == PORTABLE_DATA_DIR, - _ => false, - }) -} - -/// The writable hook is the app's existing exclusive probe. Keeping it injected lets filesystem -/// boundary tests exercise the real policy without starting the app or changing global state. -pub fn validate( - root: &Path, - env: impl Fn(&str) -> Option, - exe: Option<&Path>, - writable: impl FnOnce(&Path) -> std::io::Result<()>, -) -> Result { - validate_for(Platform::current()?, root, env, exe, writable) -} - -fn validate_for( - platform: Platform, - root: &Path, - env: impl Fn(&str) -> Option, - exe: Option<&Path>, - writable: impl FnOnce(&Path) -> std::io::Result<()>, -) -> Result { - absolute(root.to_path_buf(), "the nightly profile root")?; - if let Some(id) = env("FLATPAK_ID").filter(|v| !v.is_empty()) { - // The native tar and app-bundle rows are not Flatpak packages: inheriting a Flatpak - // runtime could point another profile at the stable app's data. DeckCraft Nightly's own - // Flatpak (packaging/linux/flatpak-bundle.sh) is the one allowed instance, matched by its - // exact id; the stable id and any other app are refused. - if platform == Platform::Windows || id != NIGHTLY_FLATPAK_ID { - return Err("nightly-v1 accepts only the DeckCraft Nightly Flatpak instance; launch through the native Launcher".into()); - } - } - let chosen = canonical_future(root)?; - if is_portable_layout(root, platform) || is_portable_layout(&chosen, platform) { - return Err("the nightly root must not use a portable DeckCraft copy or its DeckCraftData settings folder".into()); - } - let exe = absolute(exe.ok_or("cannot establish the installation boundary")?.to_path_buf(), "the executable")?; - let forbidden = forbidden_roots(platform, &env, &exe)?; - if forbidden.iter().any(|stable| overlaps(&chosen, stable, platform)) { - return Err("the nightly root must not overlap stable data or an installation".into()); - } - entries_stay_inside(&chosen)?; - // Recovery can read, adopt, overwrite and sweep entries. Never let its alias leave this - // private profile, including toward a Stable portable directory not in our known roots. - private_subdirectory(&chosen, "Recovery", "recovery folder")?; - private_subdirectory(&chosen, "Dictionaries", "dictionary folder")?; - let mut create = std::fs::DirBuilder::new(); - create.recursive(true); - #[cfg(unix)] +fn extra_forbidden_roots(env: impl Fn(&str) -> Option) -> Vec { + #[cfg(target_os = "windows")] { - use std::os::unix::fs::DirBuilderExt as _; - create.mode(0o700); + let mut roots = Vec::new(); + // The MSI's default per-user and per-machine folders (install-policy.wxi). + if let Some(local) = non_empty_abs(&env, "LOCALAPPDATA") { + roots.push(local.join("Programs").join("ArtCraft").join("DeckCraft")); + } + for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] { + if let Some(base) = non_empty_abs(&env, key) { + roots.push(base.join("ArtCraft").join("DeckCraft")); + } + } + roots } - create.create(&chosen).map_err(|e| format!("cannot create the nightly profile: {e}"))?; - let confirmed = std::fs::canonicalize(&chosen).map_err(|e| format!("cannot resolve the created nightly profile: {e}"))?; - if confirmed != chosen || forbidden.iter().any(|stable| overlaps(&confirmed, stable, platform)) { - return Err("the nightly profile changed while it was being validated".into()); + #[cfg(target_os = "macos")] + { + let mut roots = vec![PathBuf::from("/Applications/DeckCraft.app")]; + if let Some(home) = non_empty_abs(&env, "HOME") { + let library = home.join("Library"); + roots.push(library.join("Preferences/ai.storyteller.deckcraft.plist")); + roots.push(library.join("Saved Application State/ai.storyteller.deckcraft.savedState")); + roots.push(home.join("Applications/DeckCraft.app")); + } + roots + } + #[cfg(all(unix, not(target_os = "macos")))] + { + let mut roots = vec![PathBuf::from("/usr/bin/deckcraft"), PathBuf::from("/usr/local/bin/deckcraft"), PathBuf::from("/opt/deckcraft")]; + // The stable Flatpak keeps its data in its own per-app folder. + if let Some(home) = non_empty_abs(&env, "HOME") { + roots.push(home.join(".var/app/ai.storyteller.deckcraft")); + } + roots + } + #[cfg(not(any(unix, target_os = "windows")))] + { + let _ = env; + Vec::new() } - private_subdirectory(&confirmed, "Recovery", "recovery folder")?; - private_subdirectory(&confirmed, "Dictionaries", "dictionary folder")?; - entries_stay_inside(&confirmed)?; - writable(&confirmed).map_err(|e| format!("the nightly profile is not writable: {e}"))?; - Ok(confirmed) } #[cfg(test)] mod tests { - use super::*; use std::collections::BTreeMap; + use std::path::Path; use std::sync::atomic::{AtomicU64, Ordering}; - struct Fixture { - root: PathBuf, - env: BTreeMap, - exe: PathBuf, - } + use craft_nightly::{ProfileError, validate_and_prepare_root}; - impl Fixture { - fn new() -> Self { + use super::*; + + struct TempDir(PathBuf); + + impl TempDir { + fn new(label: &str) -> Self { static NEXT: AtomicU64 = AtomicU64::new(0); let root = loop { - let candidate = - std::env::temp_dir().join(format!("deckcraft-profile-policy-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed))); + let candidate = std::env::temp_dir().join(format!( + "deckcraft-profile-spec-{label}-{}-{}", + std::process::id(), + NEXT.fetch_add(1, Ordering::Relaxed) + )); match std::fs::create_dir(&candidate) { Ok(()) => break std::fs::canonicalize(candidate).unwrap(), Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue, - Err(error) => panic!("cannot create owned fixture: {error}"), + Err(error) => panic!("cannot create temp dir: {error}"), } }; - let home = root.join("home"); - let exe = root.join("install/deckcraft"); - std::fs::create_dir_all(&home).unwrap(); - std::fs::create_dir_all(exe.parent().unwrap()).unwrap(); - std::fs::write(&exe, b"fixture executable, never run").unwrap(); - let env = [("HOME", home), ("APPDATA", root.join("roaming")), ("LOCALAPPDATA", root.join("local"))] - .into_iter() - .map(|(key, value)| (key.into(), value.into_os_string())) - .collect(); - Self { root, env, exe } + Self(root) } - fn get(&self, key: &str) -> Option { - self.env.get(key).cloned() - } - - fn check(&self, platform: Platform, root: &Path) -> Result { - validate_for( - platform, - root, - |key| self.get(key), - Some(&self.exe), - |dir| { - let probe = dir.join("exclusive-test-probe"); - let file = std::fs::OpenOptions::new().write(true).create_new(true).open(&probe)?; - drop(file); - std::fs::remove_file(probe) - }, - ) - } - - fn home(&self) -> PathBuf { - PathBuf::from(self.get("HOME").unwrap()) + fn path(&self) -> &Path { + &self.0 } } - impl Drop for Fixture { + impl Drop for TempDir { fn drop(&mut self) { - // Only the directory successfully created by this fixture is owned for removal. - std::fs::remove_dir_all(&self.root).unwrap(); + let _ = std::fs::remove_dir_all(&self.0); } } #[test] - fn portable_settings_from_another_install_are_refused_before_any_probe() { - let fixture = Fixture::new(); - let stable_install = fixture.root.join("stable portable install"); - let stable_data = stable_install.join(PORTABLE_DATA_DIR); - std::fs::create_dir_all(&stable_data).unwrap(); - std::fs::write(stable_install.join("portable.txt"), b"owned portable fixture").unwrap(); - std::fs::write(stable_data.join("settings.json"), b"stable settings must not change").unwrap(); - for platform in [Platform::Windows, Platform::Linux, Platform::Mac] { - for candidate in [&stable_data, &stable_data.join("nested nightly")] { - let probed = std::cell::Cell::new(false); - let result = validate_for( - platform, - candidate, - |key| fixture.get(key), - Some(&fixture.exe), - |_| { - probed.set(true); - Ok(()) - }, - ); - assert!(result.is_err(), "a different portable install is not a private Nightly profile"); - assert!(!probed.get(), "reject portable data before a writable probe"); - assert!(!stable_data.join("nested nightly").exists()); - assert_eq!(std::fs::read(stable_data.join("settings.json")).unwrap(), b"stable settings must not change"); - } + fn spec_preserves_deckcraft_isolation_constants() { + let s = spec(); + assert_eq!(s.app_id, "deckcraft"); + assert_eq!(s.display_name, "DeckCraft"); + assert_eq!(s.stable_dir_names, &["DeckCraft", "deckcraft"]); + assert_eq!(s.stable_package_id, "ai.storyteller.deckcraft"); + assert_eq!(s.nightly_package_id, "ai.storyteller.deckcraft.nightly"); + assert_eq!(s.profile_root_env, None); + assert!(s.forbidden_env_vars.is_empty()); + assert_eq!(s.portable_markers, &["portable.txt"]); + assert_eq!(s.folder_only_entries, &["Recovery", "Dictionaries", "logs"]); + } + + #[test] + fn extra_forbidden_roots_cover_platform_install_and_stable_paths() { + let mut env = BTreeMap::::new(); + if cfg!(target_os = "windows") { + env.insert("LOCALAPPDATA".into(), r"C:\Users\me\AppData\Local".into()); + env.insert("ProgramFiles".into(), r"C:\Program Files".into()); + } else { + env.insert("HOME".into(), "/home/me".into()); } - let private = fixture.root.join("DeckCraftData-backup-name/nightly"); - assert!(fixture.check(Platform::Linux, &private).is_ok(), "a merely similar name is not a portable settings component"); + let roots = extra_forbidden_roots(|key| env.get(key).cloned()); + #[cfg(target_os = "windows")] + { + assert!(roots.contains(&PathBuf::from(r"C:\Users\me\AppData\Local\Programs\ArtCraft\DeckCraft"))); + assert!(roots.contains(&PathBuf::from(r"C:\Program Files\ArtCraft\DeckCraft"))); + } + #[cfg(target_os = "macos")] + { + assert!(roots.contains(&PathBuf::from("/Applications/DeckCraft.app"))); + assert!(roots.contains(&PathBuf::from("/home/me/Applications/DeckCraft.app"))); + assert!(roots.contains(&PathBuf::from("/home/me/Library/Preferences/ai.storyteller.deckcraft.plist"))); + assert!(roots.contains(&PathBuf::from("/home/me/Library/Saved Application State/ai.storyteller.deckcraft.savedState"))); + } + #[cfg(all(unix, not(target_os = "macos")))] + { + assert!(roots.contains(&PathBuf::from("/usr/bin/deckcraft"))); + assert!(roots.contains(&PathBuf::from("/usr/local/bin/deckcraft"))); + assert!(roots.contains(&PathBuf::from("/opt/deckcraft"))); + assert!(roots.contains(&PathBuf::from("/home/me/.var/app/ai.storyteller.deckcraft"))); + } + } + + #[test] + fn valid_profile_root_reopens_and_enforces_folder_only_entries() { + let tmp = TempDir::new("reopen"); + let profile = tmp.path().join("nightly-profile"); + let s = spec(); + + let prepared = validate_and_prepare_root(&profile, &s).unwrap(); + assert_eq!(prepared, profile); + + for file_name in ["ui.json", "prefs.json", "nightly-session.lock", "nightly-session.json"] { + std::fs::write(prepared.join(file_name), b"saved profile data").unwrap(); + } + for dir_name in FOLDER_ONLY_ENTRIES { + std::fs::create_dir(prepared.join(dir_name)).unwrap(); + } + assert_eq!(validate_and_prepare_root(&profile, &s).unwrap(), prepared); + for name in ["ui.json", "prefs.json", "nightly-session.lock", "nightly-session.json"] { + assert_eq!(std::fs::read(prepared.join(name)).unwrap(), b"saved profile data", "{name} changed when reopening"); + } + + for dir_name in FOLDER_ONLY_ENTRIES { + let entry = prepared.join(dir_name); + std::fs::remove_dir(&entry).unwrap(); + std::fs::write(&entry, b"not a directory").unwrap(); + assert!(matches!(validate_and_prepare_root(&profile, &s), Err(ProfileError::ExpectedDirectoryEntry(_)))); + std::fs::remove_file(&entry).unwrap(); + std::fs::create_dir(&entry).unwrap(); + } + } + + #[test] + fn a_non_directory_profile_stops_startup_without_installing_a_profile() { + let temp = TempDir::new("invalid-root"); + let root = temp.path().join("ordinary-file"); + std::fs::write(&root, b"existing file").unwrap(); + let argv = craft_nightly::launch_arguments(&root, &[]); + assert!(craft_nightly::current().is_none()); + let result = crate::launch_profile::prepare(craft_nightly::BuildFlavor::NightlyV1, argv); + assert!(matches!(result, Err(ProfileError::NotADirectory(_)))); + assert!(craft_nightly::current().is_none()); + assert_eq!(std::fs::read(root).unwrap(), b"existing file"); + } + + #[test] + fn relative_and_traversal_profile_roots_are_refused() { + let tmp = TempDir::new("lexical"); + let s = spec(); + assert!(matches!(validate_and_prepare_root(Path::new("relative/nightly"), &s), Err(ProfileError::RelativeProfileRoot(_)))); + assert!(matches!(validate_and_prepare_root(&tmp.path().join("nightly/../escape"), &s), Err(ProfileError::ParentTraversalInProfileRoot(_)))); } #[cfg(unix)] #[test] - fn recovery_aliases_cannot_redirect_to_stable_missing_or_profile_root_data() { - let fixture = Fixture::new(); - let stable = fixture.home().join(".local/share/deckcraft/recovery"); - std::fs::create_dir_all(&stable).unwrap(); - std::fs::write(stable.join("stable-autosave"), b"stable recovery bytes").unwrap(); - for (index, target) in [stable.clone(), fixture.root.join("missing recovery target")].into_iter().enumerate() { - let private = fixture.root.join(format!("nightly-{index}")); - std::fs::create_dir(&private).unwrap(); - std::os::unix::fs::symlink(&target, private.join("Recovery")).unwrap(); - let probed = std::cell::Cell::new(false); - let result = validate_for( - Platform::Linux, - &private, - |key| fixture.get(key), - Some(&fixture.exe), - |_| { - probed.set(true); - Ok(()) - }, - ); - assert!(result.is_err(), "Recovery must not escape the private profile or follow a dangling alias"); - assert!(!probed.get()); - } - let private = fixture.root.join("nightly-self"); - std::fs::create_dir(&private).unwrap(); - std::os::unix::fs::symlink(&private, private.join("Recovery")).unwrap(); - assert!(fixture.check(Platform::Linux, &private).is_err(), "Recovery cannot treat all profile settings as recovery entries"); - assert_eq!(std::fs::read(stable.join("stable-autosave")).unwrap(), b"stable recovery bytes"); - } + fn symlink_inside_profile_root_is_refused() { + let tmp = TempDir::new("symlink"); + let outside = tmp.path().join("outside"); + let profile = tmp.path().join("nightly-profile"); + std::fs::create_dir_all(&outside).unwrap(); + std::fs::create_dir_all(&profile).unwrap(); + std::os::unix::fs::symlink(&outside, profile.join("Recovery")).unwrap(); - #[cfg(unix)] - #[test] - fn recovery_alias_to_a_private_subfolder_keeps_the_profile_usable() { - let fixture = Fixture::new(); - let private = fixture.root.join("nightly-private"); - let recovery = private.join("private-recovery"); - std::fs::create_dir_all(&recovery).unwrap(); - std::os::unix::fs::symlink(&recovery, private.join("Recovery")).unwrap(); - assert!(fixture.check(Platform::Linux, &private).is_ok()); - assert_eq!(std::fs::canonicalize(private.join("Recovery")).unwrap(), recovery); - } - - /// The public entry point reads the host platform and refuses a relative root before probing. - #[cfg(target_os = "linux")] - #[test] - fn the_public_validator_uses_the_host_platform_and_creates_only_the_profile() { - let fixture = Fixture::new(); - let root = fixture.home().join("nightly/profiles/deckcraft"); - let created = validate(&root, |key| fixture.get(key), Some(&fixture.exe), crate::app_dirs::ensure_writable) - .expect("a private profile under HOME is valid on Linux"); - assert_eq!(created, root); - assert!(created.is_dir()); - let probed = std::cell::Cell::new(false); - let refused = validate( - Path::new("relative/profile"), - |key| fixture.get(key), - Some(&fixture.exe), - |_| { - probed.set(true); - Ok(()) - }, - ); - assert!(refused.is_err()); - assert!(!probed.get(), "a relative root is refused before the write probe"); - } - - #[test] - fn overlap_check_handles_ancestor_descendant_and_prefix_lookalikes() { - let fixture = Fixture::new(); - let root = fixture.home().join("nightly/profiles/deckcraft"); - for platform in [Platform::Windows, Platform::Linux, Platform::Mac] { - assert!(overlaps(&root, &root.join("Recovery"), platform)); - assert!(overlaps(&root.join("Recovery"), &root, platform)); - assert!(!overlaps(&root, &root.with_file_name("deckcraft-other"), platform)); - } - } - - #[test] - fn linux_fences_app_xdg_subtrees_but_allows_launcher_sibling() { - let mut fixture = Fixture::new(); - for key in ["XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", "XDG_STATE_HOME"] { - fixture.env.insert(key.into(), fixture.root.join(key).into_os_string()); - } - for key in ["XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", "XDG_STATE_HOME"] { - let stable = PathBuf::from(fixture.get(key).unwrap()).join("deckcraft"); - std::fs::create_dir_all(&stable).unwrap(); - std::fs::write(stable.join("stable-sentinel"), b"stable bytes").unwrap(); - for candidate in [stable.clone(), stable.join("nightly"), stable.parent().unwrap().to_path_buf()] { - assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("overlap")); - } - assert_eq!(std::fs::read(stable.join("stable-sentinel")).unwrap(), b"stable bytes"); - } - let data = PathBuf::from(fixture.get("XDG_DATA_HOME").unwrap()); - let nightly = data.join("ArtCraftLauncher/nightly/profiles/deckcraft"); - assert_eq!(fixture.check(Platform::Linux, &nightly).unwrap(), nightly); - assert_eq!(std::fs::read_dir(nightly).unwrap().count(), 0); - } - - #[test] - fn mac_fences_only_app_library_subtrees_and_the_entire_bundle() { - let mut fixture = Fixture::new(); - fixture.exe = fixture.root.join("install/DeckCraft Nightly.app/Contents/MacOS/DeckCraft"); - std::fs::create_dir_all(fixture.exe.parent().unwrap()).unwrap(); - std::fs::write(&fixture.exe, b"fixture executable, never run").unwrap(); - let library = fixture.home().join("Library"); - for suffix in [ - "Application Support/DeckCraft", - "Caches/DeckCraft", - "Caches/ai.storyteller.deckcraft", - "Preferences/DeckCraft", - "Saved Application State/ai.storyteller.deckcraft.savedState", - ] { - let stable = library.join(suffix); - assert!(fixture.check(Platform::Mac, &stable.join("nightly")).unwrap_err().contains("overlap")); - assert!(!stable.exists()); - } - let inside_resources = fixture.exe.parent().unwrap().parent().unwrap().join("Resources/profile"); - assert!(fixture.check(Platform::Mac, &inside_resources).unwrap_err().contains("overlap")); - assert!(!inside_resources.exists()); - let valid = library.join("Application Support/ArtCraftLauncher/nightly/profiles/deckcraft"); - assert_eq!(fixture.check(Platform::Mac, &valid).unwrap(), valid); - } - - #[test] - fn windows_roaming_local_and_install_fences_remain_active() { - let fixture = Fixture::new(); - for key in ["APPDATA", "LOCALAPPDATA"] { - let stable = PathBuf::from(fixture.get(key).unwrap()).join("DeckCraft"); - assert!(fixture.check(Platform::Windows, &stable.join("nightly")).unwrap_err().contains("overlap")); - assert!(!stable.exists()); - } - assert!(fixture.check(Platform::Windows, &fixture.exe.parent().unwrap().join("profile")).is_err()); - assert!(fixture.check(Platform::Windows, &fixture.root.join("Launcher/profiles/deckcraft")).is_ok()); - } - - #[test] - fn windows_default_msi_install_folders_are_fenced() { - let mut fixture = Fixture::new(); - let local = PathBuf::from(fixture.get("LOCALAPPDATA").unwrap()); - let per_user = local.join("Programs").join("ArtCraft").join("DeckCraft"); - assert!(fixture.check(Platform::Windows, &per_user.join("nightly")).unwrap_err().contains("overlap")); - for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] { - let base = fixture.root.join(format!("machine {key}")); - fixture.env.insert(key.into(), base.clone().into_os_string()); - let machine = base.join("ArtCraft").join("DeckCraft"); - assert!(fixture.check(Platform::Windows, &machine.join("nightly")).unwrap_err().contains("overlap")); - assert!(!machine.exists()); - } - let sibling = local.join("Programs").join("ArtCraft").join("ArtCraftLauncher").join("nightly").join("deckcraft"); - assert!(fixture.check(Platform::Windows, &sibling).is_ok(), "the Launcher's own Programs sibling is not DeckCraft's install"); - } - - #[test] - fn folders_under_a_stable_portable_copy_are_refused_before_any_probe() { - let fixture = Fixture::new(); - let portable = fixture.root.join("D/DC"); - std::fs::create_dir_all(&portable).unwrap(); - std::fs::write(portable.join("portable.txt"), b"stable portable copy").unwrap(); - std::fs::write(portable.join("deckcraft.exe"), b"stable portable executable, never run").unwrap(); - for platform in [Platform::Windows, Platform::Linux, Platform::Mac] { - for candidate in [portable.join("nightly"), portable.join("deeper/nightly")] { - let probed = std::cell::Cell::new(false); - let result = validate_for( - platform, - &candidate, - |key| fixture.get(key), - Some(&fixture.exe), - |_| { - probed.set(true); - Ok(()) - }, - ); - assert!(result.unwrap_err().contains("portable")); - assert!(!probed.get()); - assert!(!candidate.exists()); - } - } - // A portable.txt that no DeckCraft executable sits beside is someone else's file. - let unrelated = fixture.root.join("user folder"); - std::fs::create_dir_all(&unrelated).unwrap(); - std::fs::write(unrelated.join("portable.txt"), b"another app's marker").unwrap(); - assert!(fixture.check(Platform::Windows, &unrelated.join("Launcher/nightly/deckcraft")).is_ok()); - } - - #[test] - fn linux_fences_the_stable_flatpak_data_folder() { - let fixture = Fixture::new(); - let flatpak = fixture.home().join(".var/app/ai.storyteller.deckcraft"); - for candidate in [flatpak.clone(), flatpak.join("data/nightly")] { - assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("overlap")); - } - assert!(!flatpak.exists()); - assert!(fixture.check(Platform::Linux, &fixture.home().join(".var/app/ai.storyteller.launcher/nightly")).is_ok()); - } - - #[cfg(unix)] - #[test] - fn any_profile_entry_alias_must_stay_inside_the_profile() { - let fixture = Fixture::new(); - let stable = fixture.home().join(".config/deckcraft/logs"); - std::fs::create_dir_all(&stable).unwrap(); - std::fs::write(stable.join("stable-log"), b"stable log bytes").unwrap(); - for name in ["Dictionaries", "logs", "ui.json"] { - let private = fixture.root.join(format!("nightly-{name}")); - std::fs::create_dir(&private).unwrap(); - std::os::unix::fs::symlink(&stable, private.join(name)).unwrap(); - let probed = std::cell::Cell::new(false); - let result = validate_for( - Platform::Linux, - &private, - |key| fixture.get(key), - Some(&fixture.exe), - |_| { - probed.set(true); - Ok(()) - }, - ); - assert!(result.is_err(), "{name} must not lead outside the profile"); - assert!(!probed.get()); - } - let private = fixture.root.join("nightly-inside"); - std::fs::create_dir_all(private.join("real-dictionaries")).unwrap(); - std::fs::write(private.join("ui.json"), b"{}").unwrap(); - std::os::unix::fs::symlink(private.join("real-dictionaries"), private.join("Dictionaries")).unwrap(); - assert!(fixture.check(Platform::Linux, &private).is_ok(), "regular files and links that stay inside are fine"); - assert_eq!(std::fs::read(stable.join("stable-log")).unwrap(), b"stable log bytes"); - } - - #[test] - fn ambiguous_environment_and_non_native_sandbox_are_refused_before_creation() { - let mut fixture = Fixture::new(); - let candidate = fixture.home().join("nightly/profiles/deckcraft"); - fixture.env.insert("XDG_CACHE_HOME".into(), "relative/cache".into()); - assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("absolute")); - fixture.env.remove("XDG_CACHE_HOME"); - // The stable Flatpak instance, or any other app's, is not a Nightly launch. - fixture.env.insert("FLATPAK_ID".into(), "ai.storyteller.deckcraft".into()); - assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("Flatpak")); - fixture.env.insert("FLATPAK_ID".into(), "org.example.other".into()); - assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("Flatpak")); - // DeckCraft Nightly's own Flatpak is the one allowed instance. - fixture.env.insert("FLATPAK_ID".into(), NIGHTLY_FLATPAK_ID.into()); - assert!(fixture.check(Platform::Linux, &candidate).is_ok()); - fixture.env.remove("FLATPAK_ID"); - fixture.env.remove("HOME"); - assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("HOME")); - } - - #[test] - fn non_directory_and_failed_write_probe_never_fall_back_to_stable() { - let fixture = Fixture::new(); - let file = fixture.home().join("not-a-directory"); - std::fs::write(&file, b"regular file").unwrap(); - assert!(fixture.check(Platform::Linux, &file.join("nightly")).is_err()); - let candidate = fixture.home().join("nightly/profiles/deckcraft"); - let result = validate_for( - Platform::Linux, - &candidate, - |key| fixture.get(key), - Some(&fixture.exe), - |_| Err(std::io::Error::new(std::io::ErrorKind::PermissionDenied, "read-only")), - ); - assert!(result.unwrap_err().contains("not writable")); - assert!(!candidate.join("Recovery").exists(), "a failed probe leaves no stable fallback behind"); - } - - #[test] - fn relative_roots_and_parent_traversal_are_refused() { - let fixture = Fixture::new(); - for candidate in [PathBuf::from("relative/nightly"), fixture.home().join("nightly/../escape")] { - assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("absolute")); - } + let s = spec(); + assert!(matches!(validate_and_prepare_root(&profile, &s), Err(ProfileError::SymlinkEntry(_)))); } } diff --git a/assets/app-icon/deckcraft-mark.svg b/assets/app-icon/deckcraft-mark.svg new file mode 100644 index 000000000..75a567d20 --- /dev/null +++ b/assets/app-icon/deckcraft-mark.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 4bf90c3a6..b5f8b96ee 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -297,6 +297,16 @@ pub fn parse_params(doc: &str) -> std::result::Result>, String> { /// growing would duplicate ids (#407). pub(crate) const NO_ID_SPACE: &str = "the presentation has used every object id and can hold no more"; +/// A style command whose keys are all optional is refused when it is given none of them, rather +/// than answering `changed` for a call that sets nothing. +pub(crate) fn require_any(p: &Value, cmd: &str, keys: &[&str]) -> Result<()> { + if keys.iter().any(|k| p.get(*k).is_some_and(|v| !v.is_null())) { + return Ok(()); + } + let (last, rest) = keys.split_last().map_or(("", &[][..]), |(l, r)| (*l, r)); + Err(bad(cmd, format!("`{cmd}` was given nothing to set: pass {} or {last}", rest.join(", ")))) +} + pub(crate) fn bad(cmd: &str, msg: impl Into) -> EngineError { EngineError::BadParams { cmd: cmd.into(), msg: msg.into() } } @@ -377,12 +387,17 @@ pub(crate) fn ok() -> Result { /// Parse a colour param: `"#RRGGBB"`, `"accent1"`…, or `{"scheme":"accent2","lumMod":75000}`. /// A preset or system colour keeps its base: `{"preset":"red"}`, -/// `{"system":"windowText","last":"#000000"}`. +/// `{"system":"windowText","last":"#000000"}`. `"mods"` lists transforms in order: +/// `{"preset":"red","mods":[{"op":"inv"},{"op":"inv"}]}`. A list longer than [`MAX_COLOR_MODS`] +/// makes the color invalid. pub(crate) fn color_param(p: &Value, key: &str) -> Option { let v = p.get(key)?; color_value(v) } +/// Most transforms a color param's `"mods"` list may hold. +pub(crate) const MAX_COLOR_MODS: usize = 256; + pub(crate) fn color_value(v: &Value) -> Option { use deckcraft_model::ColorRef; match v { @@ -413,8 +428,22 @@ pub(crate) fn color_value(v: &Value) -> Option { ColorRef::rgb(deckcraft_color::Rgba::from_hex(o.get("rgb").and_then(Value::as_str)?)?) }; for (k, val) in o { - if let Some(t) = deckcraft_color::ColorTransform::from_xml(k, val.as_i64().and_then(|x| i32::try_from(x).ok())) { - c.mods.push(t); + let n = val.as_i64().and_then(|x| i32::try_from(x).ok()); + if let Some(t) = deckcraft_color::ColorTransform::from_xml(k, n) { + // A value-bearing transform without a usable integer is skipped, not zeroed. + if n.is_some() || t.value().is_none() { + c.mods.push(t); + } + } + } + // `mods` lists transforms in order, repeats included: `[{"op":"inv"},{"op":"lumMod","val":50000}]`. + if let Some(list) = o.get("mods") { + let list = list.as_array()?; + if list.len() > MAX_COLOR_MODS { + return None; + } + for m in list { + c.mods.push(::deserialize(m).ok()?); } } Some(c) @@ -547,6 +576,10 @@ pub(crate) fn current_names(doc: &deckcraft_model::Presentation, sel: &crate::Se /// A name ending in `?` is optional. Text after `→` is the result, not an input. pub fn needs_arguments(params: &str) -> bool { let input = params.split('→').next().unwrap_or(params); + // Every key optional, but the command refuses a call that gives none of them. + if input.contains("(at least one key)") { + return true; + } let Some(start) = input.find('{') else { return false }; let inside = input.get(start + 1..).unwrap_or(""); let inside = inside.split('}').next().unwrap_or(inside); @@ -743,6 +776,16 @@ mod tests { } } + #[test] + fn a_non_integer_colour_transform_is_skipped_not_zeroed() { + for bad in [serde_json::json!("75000"), serde_json::json!(75000.0), serde_json::json!(0.75), serde_json::json!(3_000_000_000i64)] { + let c = color_value(&serde_json::json!({"scheme": "accent1", "lumMod": bad})).unwrap(); + assert!(c.mods.is_empty(), "{bad}: {:?}", c.mods); + } + let c = color_value(&serde_json::json!({"scheme": "accent1", "lumMod": 75000})).unwrap(); + assert_eq!(c.mods, vec![deckcraft_color::ColorTransform::LumMod(75000)]); + } + #[test] fn the_palette_skips_a_command_that_needs_a_value() { assert!(needs_arguments("{path}")); @@ -752,6 +795,7 @@ mod tests { assert!(needs_arguments("{axis: horizontal|vertical, ids?}")); assert!(needs_arguments("{percent}")); assert!(!needs_arguments("{}")); + assert!(needs_arguments("{left?: pt, top?: pt} (at least one key)")); assert!(!needs_arguments("{on?: bool}")); assert!(!needs_arguments("{theme?: name, size?: [w,h] pt, blank?: bool}")); assert!(!needs_arguments("{uid?: one entry, else all}")); @@ -783,5 +827,40 @@ mod tests { assert!(color_value(&json!({"preset": name})).is_some(), "{name}"); } assert!(color_value(&json!({"system": "3dDkShadow", "last": "#000000"})).is_some()); + let listed = color_value(&json!({"preset": "red", "mods": [{"op": "inv"}, {"op": "lumOff", "val": 20_000}, {"op": "inv"}]})); + let mods = vec![ColorTransform::Inv, ColorTransform::LumOff(20_000), ColorTransform::Inv]; + assert_eq!(listed, Some(ColorRef { base: ColorBase::Preset { name: "red".into() }, mods })); + assert_eq!(color_value(&json!({"preset": "red", "mods": [{"op": "notATransform"}]})), None); + } + + #[test] + fn color_mods_lists_follow_keyed_transforms() { + use deckcraft_color::{ColorTransform, SchemeSlot}; + use deckcraft_model::{ColorBase, ColorRef}; + use serde_json::json; + let red = ColorRef { base: ColorBase::Preset { name: "red".into() }, mods: vec![] }; + assert_eq!(color_value(&json!({"preset": "red", "mods": []})), Some(red.clone()), "an empty list adds no transforms"); + let two = color_value(&json!({"preset": "red", "mods": [{"op": "lumMod", "val": 75_000}, {"op": "lumOff", "val": 10_000}]})); + assert_eq!(two, Some(red.with(ColorTransform::LumMod(75_000)).with(ColorTransform::LumOff(10_000)))); + // The keyed `lumMod` comes first, then the list in order. + let both = + color_value(&json!({"scheme": "accent2", "lumMod": 75_000, "mods": [{"op": "lumOff", "val": 10_000}, {"op": "lumMod", "val": 50_000}]})); + let want = ColorRef::scheme(SchemeSlot::Accent2) + .with(ColorTransform::LumMod(75_000)) + .with(ColorTransform::LumOff(10_000)) + .with(ColorTransform::LumMod(50_000)); + assert_eq!(both, Some(want)); + // An unknown op anywhere in the list, or a `mods` value that is not a list, makes the color invalid. + assert_eq!(color_value(&json!({"scheme": "accent2", "lumMod": 75_000, "mods": [{"op": "lumOff", "val": 10_000}, {"op": "sparkle"}]})), None); + assert_eq!(color_value(&json!({"preset": "red", "mods": {"op": "inv"}})), None); + } + + #[test] + fn color_mods_lists_longer_than_the_cap_are_invalid() { + use deckcraft_color::ColorTransform; + use serde_json::json; + let at_cap = color_value(&json!({"preset": "red", "mods": vec![json!({"op": "inv"}); MAX_COLOR_MODS]})); + assert_eq!(at_cap.map(|c| c.mods), Some(vec![ColorTransform::Inv; MAX_COLOR_MODS])); + assert_eq!(color_value(&json!({"preset": "red", "mods": vec![json!({"op": "inv"}); MAX_COLOR_MODS + 1]})), None); } } diff --git a/crates/engine/src/cmd/animation.rs b/crates/engine/src/cmd/animation.rs index 5e3265df6..563d80dd6 100644 --- a/crates/engine/src/cmd/animation.rs +++ b/crates/engine/src/cmd/animation.rs @@ -56,8 +56,8 @@ pub fn specs() -> Vec { "Animation Painter", ["Animations", "Advanced Animation"], Some("Alt+Shift+C"), - "{sticky?: bool, id?}", - has_selection, + "{sticky?: bool, on?: bool, id?}", + painter_enabled, painter_pick ), cmd!("animation.painterApply", "Apply Animation", [], Some("Alt+Shift+V"), "{ids?}", has_selection, painter_apply), @@ -470,7 +470,15 @@ fn get(s: &mut Session, p: &Value) -> Result { Ok(serde_json::to_value(&sl.animations).unwrap_or_default()) } +fn painter_enabled(s: &Session) -> std::result::Result<(), String> { + if s.anim_painter.is_some() { Ok(()) } else { has_selection(s) } +} + fn painter_pick(s: &mut Session, p: &Value) -> Result { + if p.get("on").and_then(Value::as_bool) == Some(false) { + s.anim_painter = None; + return Ok(json!({"armed": false})); + } let st = s.doc()?; let id = id_param(p, "id", "animation.painter")? .or_else(|| st.selection.shapes.first().copied()) @@ -544,6 +552,30 @@ mod tests { use super::*; + #[test] + fn an_armed_animation_painter_can_disarm_without_a_source_but_cannot_rearm() -> crate::Result<()> { + let mut s = Session::with_new(); + let source = s.execute("shape.insert", &json!({"preset": "rect"}))?["id"].clone(); + s.execute("animation.add", &json!({"effect": "fade"}))?; + s.execute("animation.painter", &json!({"sticky": true}))?; + s.select(|_, sel| { + sel.shapes.clear(); + sel.text = None; + })?; + assert!(s.execute("animation.painter", &json!({})).is_err()); + assert!(s.anim_painter.is_some()); + s.execute("animation.painter", &json!({"on": false, "id": "invalid"}))?; + assert!(s.anim_painter.is_none(), "disarming precedes even explicit source validation"); + assert!(s.execute("animation.painter", &json!({})).is_err()); + s.execute("animation.painter", &json!({"id": source}))?; + assert!(s.anim_painter.is_some(), "an explicit animated source needs no selection"); + s.execute("animation.painter", &json!({"on": false}))?; + s.execute("animation.clear", &json!({}))?; + assert!(s.execute("animation.painter", &json!({"id": source})).is_err()); + assert!(s.anim_painter.is_none()); + Ok(()) + } + #[test] fn clear_rejects_invalid_index() { let mut s = Session::with_new(); diff --git a/crates/engine/src/cmd/arrange.rs b/crates/engine/src/cmd/arrange.rs index 854758e55..d1940012d 100644 --- a/crates/engine/src/cmd/arrange.rs +++ b/crates/engine/src/cmd/arrange.rs @@ -23,6 +23,7 @@ pub fn specs() -> Vec { ), cmd!("guide.move", "Move Guide", [], None, "{index, pos: pt}", has_doc, guide_move), cmd!("guide.delete", "Delete Guide", [], None, "{index}", has_doc, guide_delete), + cmd!("guide.set", "Set Guides", [], None, "{guides: [{vertical: bool, pos: pt}]} replaces all guides in one undo step", has_doc, guide_set), cmd!(query "guide.list", "Guides", [], None, "{} → [{vertical, pos}]", has_doc, guide_list), cmd!("arrange.bringToFront", "Bring to Front", ["Arrange"], Some("Cmd+Shift+]"), "{ids?}", has_selection, |s, p| order(s, p, 2)), cmd!("arrange.bringForward", "Bring Forward", ["Arrange"], Some("Cmd+]"), "{ids?}", has_selection, |s, p| order(s, p, 1)), @@ -578,6 +579,25 @@ fn guide_delete(s: &mut Session, p: &Value) -> Result { }) } +fn guide_set(s: &mut Session, p: &Value) -> Result { + let items = p.get("guides").and_then(Value::as_array).ok_or_else(|| bad("guide.set", "`guides` must be an array"))?; + if items.len() > MAX_GUIDES { + return Err(bad("guide.set", "too many guides")); + } + let mut guides: Vec = + serde_json::from_value(Value::Array(items.clone())).map_err(|_| bad("guide.set", "each guide needs `vertical` and a finite `pos`"))?; + for guide in &mut guides { + if !guide.pos.is_finite() { + return Err(bad("guide.set", "`pos` must be finite")); + } + guide.pos = guide.pos.clamp(0.0, guide_limit(s, guide.vertical)?); + } + s.edit(|doc, _| { + doc.guides = guides; + ok() + }) +} + fn guide_list(s: &mut Session, _p: &Value) -> Result { Ok(serde_json::to_value(&s.doc()?.doc.guides).unwrap_or_default()) } diff --git a/crates/engine/src/cmd/design.rs b/crates/engine/src/cmd/design.rs index 0a1202f74..82e8ce8b7 100644 --- a/crates/engine/src/cmd/design.rs +++ b/crates/engine/src/cmd/design.rs @@ -28,7 +28,8 @@ use master_view::{ }; pub use master_view::{handout_placeholder, notes_placeholder}; use slide_background::{background, hide_bg_graphics}; -pub use slide_setup::{civil, date_field_text, today}; +// PLAN: assumed slide_setup::SLIDE_SIZE_RANGE: RangeInclusive (dialogs-w8) +pub use slide_setup::{SLIDE_SIZE_RANGE, civil, date_field_text, today}; use slide_setup::{header_footer, scale_shapes, slide_size}; pub fn specs() -> Vec { @@ -85,13 +86,13 @@ pub fn specs() -> Vec { has_doc, header_footer ), - cmd!(noundo "view.slideMaster", "Slide Master", ["View", "Master Views"], None, "{master?: index, layout?: index}", has_doc, master_view), + cmd!(noundo "view.slideMaster", "Slide Master", ["View", "Master Views"], None, "{master?: index, layout?: index, toggle?: bool}", has_doc, master_view), cmd!( "view.handoutMaster", "Handout Master", ["View", "Master Views"], None, - "{} (creates the handout master with header, date, footer and page number if the deck has none)", + "{toggle?: bool} (creates the handout master with header, date, footer and page number if the deck has none)", has_doc, handout_view ), @@ -109,7 +110,7 @@ pub fn specs() -> Vec { "Notes Master", ["View", "Master Views"], None, - "{} (creates the notes master with header, date, slide image, notes body, footer and page number if the deck has none)", + "{toggle?: bool} (creates the notes master with header, date, slide image, notes body, footer and page number if the deck has none)", has_doc, notes_view ), @@ -308,3 +309,25 @@ mod tests; #[cfg(test)] mod browse_theme_tests; + +#[cfg(test)] +mod master_view_tests; + +/// A master view whose shown state is shared by commands and the ribbon. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum MasterView { + /// Any master view. + Slide, + /// The handout master view. + Handout, + /// The notes master view. + Notes, +} +/// Reports whether the requested master view is shown, or false without a document. +pub fn master_view_shown(s: &Session, which: MasterView) -> bool { + s.active().is_some_and(|st| match which { + MasterView::Slide => st.selection.target != Target::Slides, + MasterView::Handout => st.selection.target == Target::Handout, + MasterView::Notes => st.selection.target == Target::NotesMaster, + }) +} diff --git a/crates/engine/src/cmd/design/master_view.rs b/crates/engine/src/cmd/design/master_view.rs index c03bfa574..613d40a68 100644 --- a/crates/engine/src/cmd/design/master_view.rs +++ b/crates/engine/src/cmd/design/master_view.rs @@ -1,9 +1,12 @@ use super::{ - Arc, Fill, NO_ID_SPACE, PhType, Result, Run, RunKind, Session, Shape, ShapeId, Size, Target, TextBody, Value, bad, bool_param, json, - master_index, ok, opt_usize_param, rect_param, str_param, + Arc, Fill, MasterView, NO_ID_SPACE, PhType, Result, Run, RunKind, Session, Shape, ShapeId, Size, Target, TextBody, Value, bad, bool_param, json, + master_index, master_view_shown, ok, opt_usize_param, rect_param, str_param, }; pub(super) fn master_view(s: &mut Session, p: &Value) -> Result { + if p.get("toggle").and_then(Value::as_bool) == Some(true) && master_view_shown(s, MasterView::Slide) { + return close_master(s, p); + } let st = s.doc()?; let mi = opt_usize_param(p, "master", "view.slideMaster")?.unwrap_or_else(|| master_index(&st.doc, &st.selection)); // A master thumbnail sends `{master}` and means the master itself. `{master, layout}` selects @@ -58,7 +61,10 @@ pub fn handout_placeholder(kind: PhType, size: Size, id: ShapeId) -> Shape { const HANDOUT_KINDS: [(&str, PhType); 4] = [("header", PhType::Header), ("date", PhType::Date), ("footer", PhType::Footer), ("pageNumber", PhType::SlideNum)]; -pub(super) fn handout_view(s: &mut Session, _p: &Value) -> Result { +pub(super) fn handout_view(s: &mut Session, p: &Value) -> Result { + if p.get("toggle").and_then(Value::as_bool) == Some(true) && master_view_shown(s, MasterView::Handout) { + return close_master(s, p); + } let created = s.doc()?.doc.handout_master.is_none(); if created { s.edit(|doc, _| { @@ -166,7 +172,10 @@ pub fn notes_placeholder(kind: PhType, size: Size, id: ShapeId) -> Shape { } } -pub(super) fn notes_view(s: &mut Session, _p: &Value) -> Result { +pub(super) fn notes_view(s: &mut Session, p: &Value) -> Result { + if p.get("toggle").and_then(Value::as_bool) == Some(true) && master_view_shown(s, MasterView::Notes) { + return close_master(s, p); + } let created = s.doc()?.doc.notes_master.as_ref().is_none_or(|m| m.shapes.is_empty()); if created { s.edit(|doc, _| { diff --git a/crates/engine/src/cmd/design/master_view_tests.rs b/crates/engine/src/cmd/design/master_view_tests.rs new file mode 100644 index 000000000..890bb6072 --- /dev/null +++ b/crates/engine/src/cmd/design/master_view_tests.rs @@ -0,0 +1,41 @@ +use serde_json::json; + +use crate::{Session, Target}; + +#[test] +fn a_master_view_command_with_toggle_closes_the_master_it_shows() -> crate::Result<()> { + let commands = ["view.slideMaster", "view.handoutMaster", "view.notesMaster"]; + for initial in [None, Some(commands[0]), Some(commands[1]), Some(commands[2])] { + for command in commands { + let mut s = Session::with_new(); + let slides = s.doc()?.selection.target; + if let Some(initial) = initial { + s.execute(initial, &json!({}))?; + } + let before = s.doc()?.selection.target; + let closes = match command { + "view.slideMaster" => before != slides, + "view.handoutMaster" => before == Target::Handout, + _ => before == Target::NotesMaster, + }; + s.execute(command, &json!({"toggle": true}))?; + let after = s.doc()?.selection.target; + if closes { + assert_eq!(after, slides, "{command} closes from {before:?}"); + } else { + assert_ne!(after, slides, "{command} opens from {before:?}"); + match command { + "view.handoutMaster" => assert_eq!(after, Target::Handout), + "view.notesMaster" => assert_eq!(after, Target::NotesMaster), + _ => assert!(matches!(after, Target::Master { .. } | Target::Layout { .. })), + } + } + s.execute(command, &json!({}))?; + let opened = s.doc()?.selection.target; + assert_ne!(opened, slides); + s.execute(command, &json!({}))?; + assert_eq!(s.doc()?.selection.target, opened, "{command} without toggle keeps its view open"); + } + } + Ok(()) +} diff --git a/crates/engine/src/cmd/design/slide_setup.rs b/crates/engine/src/cmd/design/slide_setup.rs index 32534255a..ca52d073e 100644 --- a/crates/engine/src/cmd/design/slide_setup.rs +++ b/crates/engine/src/cmd/design/slide_setup.rs @@ -21,6 +21,9 @@ pub(super) fn scale_shapes(shapes: &mut [Shape], sx: f64, sy: f64, k: f64, ox: f } } +/// The supported slide dimensions in points. +pub const SLIDE_SIZE_RANGE: std::ops::RangeInclusive = 72.0..=4032.0; + pub(super) fn slide_size(s: &mut Session, p: &Value) -> Result { let size = if let Some(pre) = str_param(p, "preset") { let k = pre.to_ascii_lowercase(); @@ -29,8 +32,8 @@ pub(super) fn slide_size(s: &mut Session, p: &Value) -> Result { Size::new(*w, *h) } else { Size::new( - f64_param(p, "w").ok_or_else(|| bad("design.slideSize", "missing `w`"))?.clamp(72.0, 4032.0), - f64_param(p, "h").ok_or_else(|| bad("design.slideSize", "missing `h`"))?.clamp(72.0, 4032.0), + f64_param(p, "w").ok_or_else(|| bad("design.slideSize", "missing `w`"))?.clamp(*SLIDE_SIZE_RANGE.start(), *SLIDE_SIZE_RANGE.end()), + f64_param(p, "h").ok_or_else(|| bad("design.slideSize", "missing `h`"))?.clamp(*SLIDE_SIZE_RANGE.start(), *SLIDE_SIZE_RANGE.end()), ) }; let size = match str_param(p, "orientation") { diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 9b615bfd1..9b1086df1 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -335,8 +335,9 @@ fn paste(s: &mut Session, p: &Value) -> Result { } return paste_plain(s, t); } - let editing = s.doc()?.selection.text.is_some(); - if editing { + let (editing, notes) = s.doc()?.selection.text.as_ref().map_or((false, false), |t| (true, t.notes)); + // Copied shapes are pasted as shapes even while a text box is being edited (the caret leaves it), but never into the notes. + if editing && (notes || s.clipboard.text.is_some() || s.clipboard.shapes.is_empty()) { if let Some(body) = s.clipboard.text.clone() { return super::text::paste_body(s, &body); } diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index cdf1acf1b..b1600f848 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -181,7 +181,7 @@ fn open_other(name: &str, bytes: &[u8]) -> Result<(Presentation, Vec, Ve let lower = name.to_ascii_lowercase(); let rtf = deckcraft_format::rtf::sniff_rtf(bytes); if rtf || lower.ends_with(".txt") || lower.ends_with(".md") { - let text = String::from_utf8_lossy(bytes); + let text = if rtf { String::from_utf8_lossy(bytes).into_owned() } else { decode_outline_bytes(bytes) }; let mut p = defaults::blank_presentation(defaults::WIDE, Default::default(), false); if rtf { deckcraft_format::rtf::rtf_to_slides(&mut p, &text); @@ -234,10 +234,37 @@ fn probe_clips(p: &mut Presentation) { } } -/// An outline file's text: RTF is read into the tab-indented outline, anything else as UTF-8. +/// Decode outline text bytes by BOM: `EF BB BF` strips the UTF-8 BOM, `FF FE` decodes UTF-16LE, +/// `FE FF` decodes UTF-16BE, and anything else keeps lossy UTF-8 decoding. +fn decode_outline_bytes(bytes: &[u8]) -> String { + if let Some(rest) = bytes.strip_prefix(&[0xEF, 0xBB, 0xBF]) { + String::from_utf8_lossy(rest).into_owned() + } else if let Some(rest) = bytes.strip_prefix(&[0xFF, 0xFE]) { + decode_utf16(rest, u16::from_le_bytes) + } else if let Some(rest) = bytes.strip_prefix(&[0xFE, 0xFF]) { + decode_utf16(rest, u16::from_be_bytes) + } else { + String::from_utf8_lossy(bytes).into_owned() + } +} + +fn decode_utf16(bytes: &[u8], decode: fn([u8; 2]) -> u16) -> String { + let (chunks, tail) = bytes.as_chunks::<2>(); + let mut out: String = char::decode_utf16(chunks.iter().copied().map(decode)).map(|r| r.unwrap_or(char::REPLACEMENT_CHARACTER)).collect(); + if !tail.is_empty() { + out.push(char::REPLACEMENT_CHARACTER); + } + out +} + +/// An outline file's text: RTF is read into the tab-indented outline; plain text and Markdown +/// honour UTF-8, UTF-16LE and UTF-16BE BOMs and otherwise decode as UTF-8. pub fn outline_text(bytes: &[u8]) -> String { - let text = String::from_utf8_lossy(bytes); - if deckcraft_format::rtf::sniff_rtf(bytes) { deckcraft_format::rtf::rtf_to_outline(&text) } else { text.into_owned() } + if deckcraft_format::rtf::sniff_rtf(bytes) { + deckcraft_format::rtf::rtf_to_outline(&String::from_utf8_lossy(bytes)) + } else { + decode_outline_bytes(bytes) + } } pub fn add_opened(s: &mut Session, name: &str, path: Option, p: Presentation) -> usize { @@ -372,7 +399,8 @@ pub fn save_bytes(doc: &Presentation, format: &str) -> Result> { "pdf" => deckcraft_pdf::export(doc, &Default::default()).map_err(|e| EngineError::Other(e.to_string())), "gif" => gif_bytes(doc, &Value::Null), "png" | "jpeg" | "jpg" => Err(EngineError::Other("saving a presentation as a single image isn't supported; use file.export".into())), - _ => deckcraft_format::save(doc).map_err(|e| EngineError::Other(e.to_string())), + "deckcraft" => deckcraft_format::save(doc).map_err(|e| EngineError::Other(e.to_string())), + _ => Err(EngineError::Other(format!("unknown save format `{format}`"))), } } @@ -466,6 +494,27 @@ pub fn writable_format_for_path(path: &str) -> Option<&'static str> { WRITABLE_EXTENSIONS.contains(&ext.as_str()).then(|| format_for_path(path)) } +/// The format a save path names, or an error listing the file types DeckCraft writes. +fn writable_format(path: &str) -> Result<&'static str> { + writable_format_for_path(path).ok_or_else(|| { + EngineError::Other(format!( + "{path}: DeckCraft cannot save this file type; save as .pptx, .potx, .ppsx, .deckcraft, .pdf, .png, .jpg/.jpeg, .gif, .txt, .md or .rtf" + )) + }) +} + +/// Whether an explicit save format names the same writer as the path. `txt`/`outline` are the +/// same writer only for a `.txt` path, and `jpg`/`jpeg` are aliases; every other mismatch would +/// write bytes that lie about the file type. +fn same_save_format(path: &str, path_format: &str, format: &str) -> bool { + if format == path_format { + return true; + } + let lower = path.to_ascii_lowercase(); + (lower.ends_with(".txt") && matches!((path_format, format), ("outline", "txt") | ("txt", "outline"))) + || matches!((path_format, format), ("jpeg", "jpg") | ("jpg", "jpeg")) +} + /// Animated GIF bytes for `doc` with the options in `p` (see [`crate::gif_export::GifOptions::from_params`]). pub fn gif_bytes(doc: &Presentation, p: &Value) -> Result> { Ok(crate::gif_export::encode(doc, &crate::gif_export::GifOptions::from_params(p)?)?.bytes) @@ -500,17 +549,9 @@ pub fn format_for_path(path: &str) -> &'static str { /// becomes its file. `file.save` calls it after writing; the web host bridge calls it once the /// page has the bytes. pub fn mark_saved(s: &mut Session, path: Option) -> Result<()> { - let st = s.doc_mut()?; - st.saved_doc = st.doc.clone(); - if path.is_some() { - st.path = path; - } - st.revision += 1; - let uid = st.uid; - if let Some(dir) = &s.recovery_dir { - crate::recovery::discard(dir, uid); - } - Ok(()) + let st = s.doc()?; + let (uid, snapshot) = (st.uid, st.doc.clone()); + mark_saved_snapshot(s, uid, snapshot, path) } fn write_file(path: &str, bytes: &[u8]) -> Result<()> { @@ -523,7 +564,13 @@ fn save(s: &mut Session, p: &Value) -> Result { s.ui_requests.push(crate::UiRequest::PickFile { purpose: "saveAs".into() }); return Ok(json!({"needsPath": true})); }; - let format = str_param(p, "format").unwrap_or(format_for_path(&path)); + let path_format = writable_format(&path)?; + let format = str_param(p, "format").unwrap_or(path_format); + if !same_save_format(&path, path_format, format) { + return Err(EngineError::Other(format!( + "{path}: format `{format}` does not match the file type; save as {path_format} or choose a matching extension" + ))); + } let bytes = save_bytes(&s.doc()?.doc, format)?; write_file(&path, &bytes)?; mark_saved(s, Some(path.clone()))?; @@ -610,7 +657,10 @@ fn color_at(s: &mut Session, p: &Value) -> Result { fn export(s: &mut Session, p: &Value) -> Result { let path = str_param(p, "path").ok_or_else(|| bad("file.export", "missing `path`"))?.to_string(); - let format = str_param(p, "format").unwrap_or(format_for_path(&path)).to_string(); + let format = match str_param(p, "format") { + Some(f) => f.to_string(), + None => writable_format(&path)?.to_string(), + }; let st = s.doc()?; let scale = finite_scale(f64_or(p, "scale", 2.0)); let transparent = bool_or(p, "transparentBackground", false); @@ -856,3 +906,31 @@ mod tests { let _ = std::fs::remove_dir_all(&dir); } } + +/// Reads through the common validated transport callbacks and parses the presentation. +/// Maps transport failures to the engine error type. +pub fn read_presentation_file_with(path: &str, metadata: M, read: R) -> crate::Result +where + M: FnOnce(&str) -> std::result::Result<(bool, u64), String>, + R: FnOnce(&str) -> std::result::Result, String>, +{ + let bytes = crate::io::read_file_with(path, metadata, read).map_err(EngineError::Other)?; + loaded_file(path, &bytes) +} + +/// Records the serialized snapshot as the saved state of its originating document. +/// Leaves later edits dirty and never switches or redirects a closed document. +pub fn mark_saved_snapshot(s: &mut Session, uid: u64, snapshot: std::sync::Arc, path: Option) -> Result<()> { + let st = s.docs.iter_mut().find(|d| d.uid == uid).ok_or_else(|| EngineError::Other("the presentation is closed".into()))?; + st.saved_doc = snapshot; + if path.is_some() { + st.path = path; + } + st.revision += 1; + if !st.is_dirty() + && let Some(dir) = &s.recovery_dir + { + crate::recovery::discard(dir, uid); + } + Ok(()) +} diff --git a/crates/engine/src/cmd/format.rs b/crates/engine/src/cmd/format.rs index f4c280d7d..24554ca49 100644 --- a/crates/engine/src/cmd/format.rs +++ b/crates/engine/src/cmd/format.rs @@ -11,7 +11,7 @@ use std::sync::Arc; use super::text::{format_body, format_para, format_run, format_run_levels}; use super::{ CommandSpec, always, bad, base64_decode, bool_or, bool_param, cmd, color_param, edit_shapes, f64_or, f64_param, has_doc, has_text, - has_text_or_shapes, ids_param, ok, str_param, + has_text_or_shapes, ids_param, ok, require_any, str_param, }; use crate::{Result, Session}; use deckcraft_model::ShapeId; @@ -29,7 +29,10 @@ use font::{ }; pub use painter::Painted; pub(crate) use painter::apply_painted; -use painter::{font_add, font_rescan, painter_apply, painter_pick, state}; +use painter::{font_add, font_rescan, painter_apply, painter_enabled, painter_pick, state}; +// PLAN: assumed paragraph::PARAGRAPH_PT_RANGE: RangeInclusive (dialogs-w8) +// PLAN: assumed paragraph::COLUMN_COUNT_RANGE: RangeInclusive (dialogs-w8) +pub use paragraph::{COLUMN_COUNT_RANGE, PARAGRAPH_PT_RANGE}; use paragraph::{ align, align_to, anchor, autofit, bullets, columns, direction, level, line_spacing, margins, numbering, paragraph, paragraph_dialog, rtl, wrap, }; @@ -207,7 +210,7 @@ pub fn specs() -> Vec { "Paragraph…", ["Format"], None, - "{align?, indentLeft?: pt, indentFirst?: pt (negative = hanging), spaceBefore?: pt, spaceAfter?: pt, lineSpacing?: lines}", + "{align?, indentLeft?: pt, indentFirst?: pt (negative = hanging), spaceBefore?: pt, spaceAfter?: pt, lineSpacing?: lines, lineSpacingPt?: pt} (at least one key)", has_text_or_shapes, paragraph ), @@ -256,11 +259,11 @@ pub fn specs() -> Vec { "Text Box Margins", ["Format Shape", "Text Box"], None, - "{left?: pt, top?: pt, right?: pt, bottom?: pt}", + "{left?: pt, top?: pt, right?: pt, bottom?: pt} (at least one key)", has_text_or_shapes, margins ), - cmd!(noundo "format.painter", "Format Painter", ["Home", "Clipboard"], Some("Cmd+Shift+C"), "{sticky?: bool}", has_text_or_shapes, painter_pick), + cmd!(noundo "format.painter", "Format Painter", ["Home", "Clipboard"], Some("Cmd+Shift+C"), "{sticky?: bool, on?: bool}", painter_enabled, painter_pick), cmd!("format.painterApply", "Paste Formatting", [], Some("Cmd+Shift+V"), "{ids?}", has_text_or_shapes, painter_apply), cmd!(query "format.state", "Formatting State", [], None, "{} → the effective formatting at the selection (font, size, bold, …)", has_doc, state), ] @@ -328,6 +331,24 @@ mod tests { use super::*; use crate::{Session, UiRequest}; + #[test] + fn an_armed_format_painter_can_disarm_without_a_source_but_cannot_rearm() -> crate::Result<()> { + let mut s = Session::with_new(); + s.execute("shape.insert", &json!({"preset": "rect"}))?; + s.execute("format.painter", &json!({"sticky": true}))?; + s.select(|_, sel| { + sel.shapes.clear(); + sel.text = None; + })?; + assert!(s.execute("format.painter", &json!({})).is_err()); + assert!(s.painter.is_some(), "a refused pick keeps the armed painter available to disarm"); + s.execute("format.painter", &json!({"on": false}))?; + assert!(s.painter.is_none()); + assert!(s.execute("format.painter", &json!({})).is_err()); + assert!(s.painter.is_none()); + Ok(()) + } + fn shape() -> Session { let mut s = Session::with_new(); s.execute("shape.insert", &json!({"preset": "rect", "rect": [40.0, 40.0, 240.0, 80.0], "text": "Hello"})).unwrap(); @@ -405,6 +426,87 @@ mod tests { assert!(r.size.is_none() && r.fill.is_none()); } + #[test] + fn font_dialog_ok_keeps_the_text_color() { + use deckcraft_color::Rgba; + let preset = ColorRef { base: ColorBase::Preset { name: "red".into() }, mods: vec![] }.with(ColorTransform::LumMod(50_000)); + let system = ColorRef { base: ColorBase::System { name: "windowText".into(), last: Rgba::rgb(0x12, 0x34, 0x56) }, mods: vec![] } + .with(ColorTransform::Alpha(60_000)); + // A transform without a value, and a color that is not opaque. + let inverted = ColorRef { base: ColorBase::Preset { name: "red".into() }, mods: vec![] }.with(ColorTransform::Inv); + let translucent = ColorRef { base: ColorBase::System { name: "windowText".into(), last: Rgba::rgba(0x12, 0x34, 0x56, 0x80) }, mods: vec![] }; + let rgb = ColorRef::rgb(Rgba::rgba(0x12, 0x34, 0x56, 0x80)); + // A repeated transform, and two transforms in an order that is not alphabetical. + let twice = inverted.clone().with(ColorTransform::Inv); + let ordered = ColorRef::scheme(SchemeSlot::Accent2).with(ColorTransform::LumOff(20_000)).with(ColorTransform::LumMod(50_000)); + for color in [preset, system, inverted, translucent, rgb, twice, ordered] { + let mut s = shape(); + let fill = Fill::Solid { color: color.clone() }; + format_run(&mut s, &|r| r.fill = Some(fill.clone())).unwrap(); + s.ui_requests.clear(); + s.execute("format.fontDialog", &json!({})).unwrap(); + let Some(UiRequest::Dialog { params, .. }) = s.ui_requests.last().cloned() else { panic!("dialog request") }; + s.execute("format.fontDialog", &json!({"color": params["color"]})).unwrap(); + assert_eq!(props(&s).fill, Some(Fill::Solid { color }), "{}", params["color"]); + } + } + + #[test] + fn font_dialog_ok_without_color_keeps_colors_a_command_cannot_give() { + use deckcraft_color::Rgba; + let last = Rgba::rgb(0x12, 0x34, 0x56); + let preset = ColorRef { base: ColorBase::Preset { name: "notAColor".into() }, mods: vec![] }.with(ColorTransform::LumMod(50_000)); + let system = ColorRef { base: ColorBase::System { name: "notAColor".into(), last }, mods: vec![] }; + // More transforms than a command's `mods` list may carry, as an opened file can hold. + let many = ColorRef { base: ColorBase::Preset { name: "red".into() }, mods: vec![ColorTransform::Inv; crate::cmd::MAX_COLOR_MODS + 1] }; + for color in [preset, system, many] { + let mut s = shape(); + let fill = Fill::Solid { color: color.clone() }; + format_run(&mut s, &|r| r.fill = Some(fill.clone())).unwrap(); + s.ui_requests.clear(); + s.execute("format.fontDialog", &json!({})).unwrap(); + let Some(UiRequest::Dialog { mut params, .. }) = s.ui_requests.last().cloned() else { panic!("dialog request") }; + // OK with the Color field untouched and another field edited, as the dialog sends it. + params.as_object_mut().unwrap().remove("color"); + params["size"] = json!(20.0); + params["bold"] = json!(true); + s.execute("format.fontDialog", ¶ms).unwrap(); + let r = props(&s); + assert_eq!((r.size, r.bold), (Some(20.0), Some(true))); + assert_eq!(r.fill, Some(Fill::Solid { color })); + } + } + + #[test] + fn font_dialog_color_mods_round_trip_and_unknown_ops_are_errors() { + let two = ColorRef { base: ColorBase::Preset { name: "red".into() }, mods: vec![] } + .with(ColorTransform::LumMod(75_000)) + .with(ColorTransform::LumOff(10_000)); + let mut s = shape(); + let fill = Fill::Solid { color: two.clone() }; + format_run(&mut s, &|r| r.fill = Some(fill.clone())).unwrap(); + s.ui_requests.clear(); + s.execute("format.fontDialog", &json!({})).unwrap(); + let Some(UiRequest::Dialog { params, .. }) = s.ui_requests.last().cloned() else { panic!("dialog request") }; + assert_eq!(params["color"], json!({"preset": "red", "mods": [{"op": "lumMod", "val": 75_000}, {"op": "lumOff", "val": 10_000}]})); + s.execute("format.fontDialog", &json!({"color": params["color"]})).unwrap(); + assert_eq!(props(&s).fill, Some(Fill::Solid { color: two.clone() })); + // An unknown op is an error, and the run keeps its color. + let n = s.doc().unwrap().history.undo.len(); + let err = s.execute("format.fontDialog", &json!({"color": {"preset": "red", "mods": [{"op": "sparkle"}]}})).unwrap_err(); + assert!(err.to_string().contains("color"), "{err}"); + assert_eq!(s.doc().unwrap().history.undo.len(), n); + assert_eq!(props(&s).fill, Some(Fill::Solid { color: two })); + // An empty list gives the color with no transforms. + s.execute("format.fontDialog", &json!({"color": {"preset": "red", "mods": []}})).unwrap(); + assert_eq!(props(&s).fill, Some(Fill::Solid { color: ColorRef { base: ColorBase::Preset { name: "red".into() }, mods: vec![] } })); + // A scheme color with a keyed `lumMod` and a list keeps both, the keyed one first. + s.execute("format.fontDialog", &json!({"color": {"scheme": "accent2", "lumMod": 75_000, "mods": [{"op": "lumOff", "val": 10_000}]}})) + .unwrap(); + let scheme = ColorRef::scheme(SchemeSlot::Accent2).with(ColorTransform::LumMod(75_000)).with(ColorTransform::LumOff(10_000)); + assert_eq!(props(&s).fill, Some(Fill::Solid { color: scheme })); + } + #[test] fn font_dialog_with_no_fields_asks_the_ui_to_open() { let mut s = shape(); diff --git a/crates/engine/src/cmd/format/font.rs b/crates/engine/src/cmd/format/font.rs index 8bc8a5af4..13dcd5cd0 100644 --- a/crates/engine/src/cmd/format/font.rs +++ b/crates/engine/src/cmd/format/font.rs @@ -443,23 +443,39 @@ fn font_edits(p: &Value) -> Result { fn color_command_value(c: &deckcraft_model::ColorRef) -> Value { use deckcraft_model::ColorBase; let mut o = serde_json::Map::new(); - for m in &c.mods { - if let Some(v) = m.value() { - o.insert(m.xml_name().to_string(), json!(v)); - } + // An ordered list, so the order of the transforms and repeated ones such as `[inv, inv]` are kept. + if !c.mods.is_empty() { + o.insert("mods".into(), json!(c.mods)); } - match &c.base { - ColorBase::Rgb { rgb } if o.is_empty() => json!(format!("#{}", rgb.hex())), + // `#RRGGBB`, or `#RRGGBBAA` for a color that is not opaque. + let hex = |c: &deckcraft_color::Rgba| if c.a == 255 { format!("#{}", c.hex()) } else { format!("#{}{:02X}", c.hex(), c.a) }; + // A preset or system name that `color_value` does not know (kept from an opened file) is given as + // the color it is drawn with, so a caller that sends this `color` back gets a valid color. The + // Font dialog sends no `color` when its Color field is untouched, so the run keeps the stored name. + let base = match &c.base { + ColorBase::Preset { name } if !deckcraft_color::is_preset_name(name) => ColorBase::Rgb { rgb: deckcraft_color::Rgba::BLACK }, + ColorBase::System { name, last } if !deckcraft_color::is_system_name(name) => ColorBase::Rgb { rgb: *last }, + b => b.clone(), + }; + match &base { + ColorBase::Rgb { rgb } if o.is_empty() => json!(hex(rgb)), ColorBase::Rgb { rgb } => { - o.insert("rgb".into(), json!(format!("#{}", rgb.hex()))); + o.insert("rgb".into(), json!(hex(rgb))); Value::Object(o) } ColorBase::Scheme { slot } => { o.insert("scheme".into(), json!(slot.xml_name())); Value::Object(o) } - ColorBase::Preset { name } => json!(name), - ColorBase::System { last, .. } => json!(format!("#{}", last.hex())), + ColorBase::Preset { name } => { + o.insert("preset".into(), json!(name)); + Value::Object(o) + } + ColorBase::System { name, last } => { + o.insert("system".into(), json!(name)); + o.insert("last".into(), json!(hex(last))); + Value::Object(o) + } } } diff --git a/crates/engine/src/cmd/format/painter.rs b/crates/engine/src/cmd/format/painter.rs index 1d324811e..0fc6a33a3 100644 --- a/crates/engine/src/cmd/format/painter.rs +++ b/crates/engine/src/cmd/format/painter.rs @@ -1,6 +1,6 @@ use super::{ Bullet, Effects, Fill, Line, ParaProps, Result, RunProps, Session, Shape, Strike, Value, bad, base64_decode, bool_or, current_para, current_run, - ed, edit_shapes, format_run, ids_param, json, ok, resolve, str_param, + ed, edit_shapes, format_run, has_text_or_shapes, ids_param, json, ok, resolve, str_param, }; /// Formatting picked up by the Format Painter. @@ -14,7 +14,17 @@ pub struct Painted { pub style: Option, } +/// Keeps disarming available when the source selection has gone away. +pub(super) fn painter_enabled(s: &Session) -> std::result::Result<(), String> { + if s.painter.is_some() { Ok(()) } else { has_text_or_shapes(s) } +} + pub(super) fn painter_pick(s: &mut Session, p: &Value) -> Result { + if p.get("on").and_then(Value::as_bool) == Some(false) { + s.painter = None; + return Ok(json!({"armed": false})); + } + has_text_or_shapes(s).map_err(|why| bad("format.painter", why))?; let st = s.doc()?; let mut painted = Painted::default(); if let Some(t) = &st.selection.text { @@ -124,7 +134,7 @@ pub(super) fn state(s: &mut Session, _p: &Value) -> Result { })) } -/// Add a font from its bytes for this session (it then shows in the font menu and draws). +/// Registers font bytes through the catalogue adapter shared by rendering and the picker. pub(super) fn font_add(_s: &mut Session, p: &Value) -> Result { let data = str_param(p, "data").and_then(base64_decode).ok_or_else(|| bad("font.add", "missing or invalid base64 `data`"))?; if data.len() > 64 << 20 { @@ -137,12 +147,9 @@ pub(super) fn font_add(_s: &mut Session, p: &Value) -> Result { Ok(json!({"faces": faces})) } -/// Catalog the installed fonts again, so fonts installed while DeckCraft runs appear. +/// Refreshes installed fonts through the catalogue adapter shared by rendering and the picker. pub(super) fn font_rescan(_s: &mut Session, _p: &Value) -> Result { let db = deckcraft_fonts::FontDb::global(); - #[cfg(not(target_arch = "wasm32"))] let faces = db.load_system_fonts(); - #[cfg(target_arch = "wasm32")] - let faces = 0usize; Ok(json!({"faces": faces, "families": db.families().len()})) } diff --git a/crates/engine/src/cmd/format/paragraph.rs b/crates/engine/src/cmd/format/paragraph.rs index 64bb16487..1b2f1584f 100644 --- a/crates/engine/src/cmd/format/paragraph.rs +++ b/crates/engine/src/cmd/format/paragraph.rs @@ -1,6 +1,6 @@ use super::{ Align, Anchor, AutoFit, Bullet, Result, Session, Spacing, TextDir, Value, bad, bool_or, color_param, current_para, f64_or, f64_param, - format_body, format_para, json, ok, on_param, resolve, str_param, + format_body, format_para, json, ok, on_param, require_any, resolve, str_param, }; pub(super) fn align_to(s: &mut Session, a: Align) -> Result { @@ -114,12 +114,31 @@ pub(super) fn level(s: &mut Session, d: i32) -> Result { } pub(super) fn line_spacing(s: &mut Session, p: &Value) -> Result { - let sp = - if let Some(pt) = f64_param(p, "pt") { Spacing::Pts(pt.clamp(0.0, 1584.0)) } else { Spacing::Pct(f64_or(p, "lines", 1.0).clamp(0.0, 9.99)) }; + let sp = if let Some(pt) = f64_param(p, "pt") { Spacing::Pts(clamp_pt(pt)) } else { Spacing::Pct(f64_or(p, "lines", 1.0).clamp(0.0, 9.99)) }; format_para(s, &move |para| para.props.line_spacing = Some(sp)) } pub(super) fn paragraph(s: &mut Session, p: &Value) -> Result { + // The Paragraph dialog's other fields are format.paragraphDialog's; say so instead of + // calling the call empty. + if let Some(k) = + ["special", "specialBy", "indentRight", "spaceBeforeKind", "spaceAfterKind"].into_iter().find(|k| p.get(*k).is_some_and(|v| !v.is_null())) + { + // The dialog applies a kind or `specialBy` only with the value it qualifies. + let with = match k { + "spaceBeforeKind" => " together with `spaceBefore`", + "spaceAfterKind" => " together with `spaceAfter`", + "specialBy" => " together with `special`", + _ => "", + }; + return Err(bad( + "format.paragraph", + format!( + "`{k}` is a field of format.paragraphDialog (the whole Paragraph dialog); pass it there{with}. format.paragraph does not read it" + ), + )); + } + require_any(p, "format.paragraph", &["align", "indentLeft", "indentFirst", "spaceBefore", "spaceAfter", "lineSpacing", "lineSpacingPt"])?; let a = str_param(p, "align").map(|a| parse_align("format.paragraph", a)).transpose()?; let ml = f64_param(p, "indentLeft"); let ind = f64_param(p, "indentFirst"); @@ -169,8 +188,14 @@ pub(super) fn finite_key(p: &Value, cmd: &str, key: &str) -> Result> } } +/// The supported paragraph spacing in points. +pub const PARAGRAPH_PT_RANGE: std::ops::RangeInclusive = 0.0..=1584.0; + +/// The supported first-line and hanging indent in points: the paragraph spacing range on both sides of zero. +pub const PARAGRAPH_INDENT_RANGE: std::ops::RangeInclusive = -*PARAGRAPH_PT_RANGE.end()..=*PARAGRAPH_PT_RANGE.end(); + pub(super) fn clamp_pt(v: f64) -> f64 { - v.clamp(0.0, 1584.0) + v.clamp(*PARAGRAPH_PT_RANGE.start(), *PARAGRAPH_PT_RANGE.end()) } fn parse_align(cmd: &str, s: &str) -> Result { @@ -260,7 +285,7 @@ pub(super) fn paragraph_dialog(s: &mut Session, p: &Value) -> Result { let indent_right = finite_key(p, CMD, "indentRight")?.map(clamp_pt); let special_by = finite_key(p, CMD, "specialBy")?.map(|v| clamp_pt(v.max(0.0))); let indent = match p.get("special") { - None => finite_key(p, CMD, "indentFirst")?.map(|v| v.clamp(-1584.0, 1584.0)), + None => finite_key(p, CMD, "indentFirst")?.map(|v| v.clamp(*PARAGRAPH_INDENT_RANGE.start(), *PARAGRAPH_INDENT_RANGE.end())), Some(Value::String(kind)) => { let by = special_by.unwrap_or(0.0); Some(match kind.as_str() { @@ -358,9 +383,12 @@ fn current_columns(s: &Session) -> (u32, f64) { Some(c) => resolve::body(&c, sh), None => sh.text.as_ref().map(|b| b.body.clone()).unwrap_or_default(), }; - (body.columns.unwrap_or(1).clamp(1, 16), body.col_spacing.unwrap_or(0.0).max(0.0)) + (body.columns.unwrap_or(1).clamp(*COLUMN_COUNT_RANGE.start(), *COLUMN_COUNT_RANGE.end()), body.col_spacing.unwrap_or(0.0).max(0.0)) } +/// The supported text column counts. +pub const COLUMN_COUNT_RANGE: std::ops::RangeInclusive = 1..=16; + pub(super) fn columns(s: &mut Session, p: &Value) -> Result { const CMD: &str = "format.columns"; let count = match p.get("count") { @@ -368,8 +396,10 @@ pub(super) fn columns(s: &mut Session, p: &Value) -> Result { Some(v) => { let n = v .as_f64() - .filter(|n| n.fract() == 0.0 && (1.0..=16.0).contains(n)) - .ok_or_else(|| bad(CMD, "`count` must be a whole number from 1 to 16"))?; + .filter(|n| n.fract() == 0.0 && (f64::from(*COLUMN_COUNT_RANGE.start())..=f64::from(*COLUMN_COUNT_RANGE.end())).contains(n)) + .ok_or_else(|| { + bad(CMD, format!("`count` must be a whole number from {} to {}", COLUMN_COUNT_RANGE.start(), COLUMN_COUNT_RANGE.end())) + })?; Some(n as u32) } }; @@ -404,6 +434,7 @@ pub(super) fn wrap(s: &mut Session, p: &Value) -> Result { } pub(super) fn margins(s: &mut Session, p: &Value) -> Result { + require_any(p, "format.margins", &["left", "top", "right", "bottom"])?; let (l, t, r, b) = (f64_param(p, "left"), f64_param(p, "top"), f64_param(p, "right"), f64_param(p, "bottom")); format_body(s, &move |bp| { if l.is_some() { diff --git a/crates/engine/src/cmd/guides_tests.rs b/crates/engine/src/cmd/guides_tests.rs index 80bf3e680..e1a855d40 100644 --- a/crates/engine/src/cmd/guides_tests.rs +++ b/crates/engine/src/cmd/guides_tests.rs @@ -1,5 +1,4 @@ -//! Drawing guides: commands, dragging a guide with the pointer, snapping shapes to guides, and -//! the PPTX round trip. +//! Drawing guides: commands, shape snapping while visible and the PPTX round trip. use serde_json::json; @@ -32,17 +31,8 @@ fn drag_a_guide_drop_it_off_the_slide_and_snap_shapes_to_it() { let mut s = Session::with_new(); s.execute("slide.new", &json!({"layout": "blank"})).unwrap(); s.execute("guide.add", &json!({"vertical": true, "pos": 300})).unwrap(); - // Hidden guides can't be grabbed: the press starts a marquee instead. - ev(&mut s, PointerKind::Down, 300.0, 50.0); - ev(&mut s, PointerKind::Up, 300.0, 50.0); - assert_eq!(s.doc().unwrap().doc.guides[0].pos, 300.0); + s.execute("guide.move", &json!({"index": 0, "pos": 350})).unwrap(); s.tool.guides_visible = true; - ev(&mut s, PointerKind::Down, 301.0, 50.0); - ev(&mut s, PointerKind::Drag, 350.4, 60.0); - assert_eq!(s.tool.guide_drag, Some((0, 350.0)), "whole points while dragging"); - ev(&mut s, PointerKind::Up, 350.4, 60.0); - assert_eq!(s.doc().unwrap().doc.guides[0].pos, 350.0); - assert_eq!(s.tool.guide_drag, None); // A shape dragged near the guide snaps its left edge onto it. let id = s.execute("shape.insert", &json!({"preset": "rect", "rect": [100, 200, 80, 60]})).unwrap()["id"].as_u64().unwrap(); @@ -52,15 +42,43 @@ fn drag_a_guide_drop_it_off_the_slide_and_snap_shapes_to_it() { ev(&mut s, PointerKind::Drag, 388.0, 231.0); ev(&mut s, PointerKind::Up, 388.0, 231.0); let x = s.doc().unwrap().shapes().iter().find(|sh| sh.id.0 as u64 == id).and_then(|sh| sh.xfrm).unwrap(); - assert!((x.x - 350.0).abs() < 0.01, "{x:?}"); + let guide = s.doc().unwrap().doc.guides[0].pos; + assert!((x.x - guide).abs() < 0.01, "{x:?}"); - // Dropped off the slide: gone, and undo brings it back. - ev(&mut s, PointerKind::Down, 350.0, 10.0); - ev(&mut s, PointerKind::Drag, -40.0, 10.0); - ev(&mut s, PointerKind::Up, -40.0, 10.0); + s.execute("shape.setBounds", &json!({"id": id, "x": 100, "y": 200, "w": 80, "h": 60})).unwrap(); + s.tool.guides_visible = false; + ev(&mut s, PointerKind::Down, 140.0, 230.0); + ev(&mut s, PointerKind::Drag, 200.0, 230.0); + ev(&mut s, PointerKind::Drag, 388.0, 231.0); + ev(&mut s, PointerKind::Up, 388.0, 231.0); + let hidden = s.doc().unwrap().shapes().iter().find(|sh| sh.id.0 as u64 == id).and_then(|sh| sh.xfrm).unwrap(); + assert!((hidden.x - guide).abs() > 1.0, "a hidden guide does not snap the shape: {hidden:?}"); +} + +#[test] +fn replacing_guides_validates_atomically_and_undoes_the_whole_vector() { + let mut s = Session::with_new(); + for (vertical, pos) in [(true, 100.0), (false, 150.0), (true, 200.0)] { + s.execute("guide.add", &json!({"vertical": vertical, "pos": pos})).unwrap(); + } + let before = s.doc().unwrap().doc.guides.clone(); + let replacement = vec![ + deckcraft_model::DrawGuide { pos: before[2].pos + 25.0, ..before[2] }, + deckcraft_model::DrawGuide { pos: before[0].pos + 15.0, ..before[0] }, + ]; + s.execute("guide.set", &json!({"guides": replacement})).unwrap(); + assert_eq!(s.doc().unwrap().doc.guides, replacement, "one commit preserves the final order, moves and deletion"); + assert!(s.execute("guide.set", &json!({"guides": [before[0], {"vertical": false, "pos": null}]})).is_err()); + assert!(s.execute("guide.set", &json!({"guides": vec![before[0]; super::MAX_GUIDES + 1]})).is_err()); + assert_eq!(s.doc().unwrap().doc.guides, replacement, "a refused vector changes no guide"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc.guides, before, "one undo restores every moved and deleted guide"); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc.guides, replacement); + s.execute("guide.set", &json!({"guides": []})).unwrap(); assert!(s.doc().unwrap().doc.guides.is_empty()); s.execute("edit.undo", &json!({})).unwrap(); - assert_eq!(s.doc().unwrap().doc.guides.len(), 1); + assert_eq!(s.doc().unwrap().doc.guides, replacement); } #[test] diff --git a/crates/engine/src/cmd/insert.rs b/crates/engine/src/cmd/insert.rs index 1fd6e258e..b8968d4bb 100644 --- a/crates/engine/src/cmd/insert.rs +++ b/crates/engine/src/cmd/insert.rs @@ -20,6 +20,10 @@ mod links; mod picture; mod text_fields; +pub use album::{ + ALBUM_MAX_BYTES, ALBUM_MAX_ITEMS, ALBUM_MAX_TEXT, ALBUM_MAX_TOTAL, album_check_item_count, album_check_picture_bytes, album_check_text, + album_check_total_bytes, +}; use album::{photo_album, photo_album_edit}; pub use chart::chart_type; use chart::{chart, chart_data, chart_options, chart_type_cmd}; @@ -275,6 +279,7 @@ fn insert_icon(s: &mut Session, p: &Value) -> Result { if rect.w < 1.0 || rect.h < 1.0 { return Err(bad("insert.icon", "rect needs a positive width and height")); } + let (tag, value) = crate::icons::INSERTED_ICON_TAG; let shape = Shape { name: icon.label.to_string(), xfrm: Some(rect), @@ -296,6 +301,7 @@ fn insert_icon(s: &mut Session, p: &Value) -> Result { ..Default::default() }), style: Some(ShapeStyle::line(SchemeSlot::Tx1)), + tags: vec![(tag.into(), value.into())], ..Default::default() }; let id = add_shape(s, "insert.icon", shape, true)?; diff --git a/crates/engine/src/cmd/insert/album.rs b/crates/engine/src/cmd/insert/album.rs index 0d5195e23..1b71524b2 100644 --- a/crates/engine/src/cmd/insert/album.rs +++ b/crates/engine/src/cmd/insert/album.rs @@ -1,13 +1,57 @@ use super::picture::{content_type, media_bytes}; use super::{NO_ID_SPACE, Result, Session, ShapeKind, Value, bad, base64_encode, json}; -const ALBUM_MAX_ITEMS: usize = 48; +/// Maximum number of picture and text items a photo album can carry. +pub const ALBUM_MAX_ITEMS: usize = 48; -const ALBUM_MAX_BYTES: usize = 32 * 1024 * 1024; +/// Maximum decoded bytes in one album picture. +pub const ALBUM_MAX_BYTES: usize = 32 * 1024 * 1024; -const ALBUM_MAX_TOTAL: usize = 64 * 1024 * 1024; +/// Maximum decoded picture bytes in an album. +pub const ALBUM_MAX_TOTAL: usize = 64 * 1024 * 1024; -const ALBUM_MAX_TEXT: usize = 400; +/// Maximum Unicode characters in an album text box. +pub const ALBUM_MAX_TEXT: usize = 400; + +/// Checks the capacity of an album draft, which may still be empty. +pub fn album_check_item_count(count: usize) -> std::result::Result<(), String> { + if count > ALBUM_MAX_ITEMS { + return Err(format!("A photo album holds at most {ALBUM_MAX_ITEMS} pictures or text boxes")); + } + Ok(()) +} + +/// Returns the trimmed text of a valid album text box. +pub fn album_check_text(text: &str) -> std::result::Result<&str, String> { + let text = text.trim(); + if text.is_empty() { + return Err("A text box needs some text".into()); + } + if text.chars().count() > ALBUM_MAX_TEXT { + return Err(format!("Text is longer than {ALBUM_MAX_TEXT} characters")); + } + Ok(text) +} + +/// Checks a picture's decoded byte count without decoding its media format. +pub fn album_check_picture_bytes(name: &str, bytes: usize) -> std::result::Result<(), String> { + if bytes == 0 { + return Err("That file is empty".into()); + } + if bytes > ALBUM_MAX_BYTES { + return Err(format!("{name} is larger than 32 MB")); + } + Ok(()) +} + +/// Adds a picture's bytes to an album draft, refusing aggregate overflow. +pub fn album_check_total_bytes(total: usize, added: usize) -> std::result::Result { + let next = total.saturating_add(added); + if next > ALBUM_MAX_TOTAL { + return Err("The album is larger than 64 MB".into()); + } + Ok(next) +} #[derive(Clone, Copy)] struct AlbumLayout { @@ -258,9 +302,7 @@ fn album_items(p: &Value) -> Result> { if arr.is_empty() { return Err(bad("insert.photoAlbum", "add at least one picture or text box")); } - if arr.len() > ALBUM_MAX_ITEMS { - return Err(bad("insert.photoAlbum", "a photo album holds at most 48 pictures or text boxes")); - } + album_check_item_count(arr.len()).map_err(|message| bad("insert.photoAlbum", message))?; let mut items = Vec::with_capacity(arr.len()); let mut total = 0usize; for item in arr { @@ -272,25 +314,14 @@ fn album_items(p: &Value) -> Result> { let Some(text) = obj.get("text").and_then(Value::as_str) else { return Err(bad("insert.photoAlbum", "each album item needs `path`, `data` or `text`")); }; - let text = text.trim(); - if text.is_empty() { - return Err(bad("insert.photoAlbum", "a text box needs some text")); - } - if text.chars().count() > ALBUM_MAX_TEXT { - return Err(bad("insert.photoAlbum", "text is longer than 400 characters")); - } + let text = album_check_text(text).map_err(|message| bad("insert.photoAlbum", message))?; items.push(AlbumItem::Text(text.to_string())); continue; } let (name, bytes) = media_bytes(item, "insert.photoAlbum")?; - if bytes.len() > ALBUM_MAX_BYTES { - return Err(bad("insert.photoAlbum", format!("{name} is larger than 32 MB"))); - } - let next = total.saturating_add(bytes.len()); - if next > ALBUM_MAX_TOTAL { - return Err(bad("insert.photoAlbum", "the album is larger than 64 MB")); - } - total = next; + + album_check_picture_bytes(&name, bytes.len()).map_err(|message| bad("insert.photoAlbum", message))?; + total = album_check_total_bytes(total, bytes.len()).map_err(|message| bad("insert.photoAlbum", message))?; let ct = content_type(&name, &bytes); if !ct.starts_with("image/") { return Err(bad("insert.photoAlbum", format!("{name} is not a picture"))); @@ -777,6 +808,15 @@ mod seed_tests { use super::*; + #[test] + fn empty_svg_album_input_cannot_edit_the_document() { + let mut s = Session::with_new(); + let before = s.active().unwrap().doc.clone(); + assert!(s.execute("insert.photoAlbum", &json!({"pictures": [{"name": "empty.svg", "data": ""}]})).is_err()); + assert!(Arc::ptr_eq(&s.active().unwrap().doc, &before)); + assert!(s.active().unwrap().history.undo.is_empty()); + } + #[test] fn reopening_an_album_seeds_at_most_the_items_an_album_takes() { // One picture named by 500 shapes: the dialog gets 48 items, not 500 encoded copies. diff --git a/crates/engine/src/cmd/insert/picture.rs b/crates/engine/src/cmd/insert/picture.rs index 85dafa7aa..bd6e447ee 100644 --- a/crates/engine/src/cmd/insert/picture.rs +++ b/crates/engine/src/cmd/insert/picture.rs @@ -73,6 +73,19 @@ pub fn content_type(name: &str, bytes: &[u8]) -> &'static str { } } +/// The audio MIME for a container whose bytes are audio-only, so the PPTX writer stores it as +/// sound rather than a movie. Video-bearing containers keep their `video/*` type. +fn audio_content_type(ct: &'static str) -> &'static str { + match ct { + "video/x-ms-wmv" => "audio/x-ms-wma", + "video/mp4" => "audio/mp4", + "video/webm" => "audio/webm", + "video/ogg" => "audio/ogg", + "video/quicktime" => "audio/mp4", + _ => ct, + } +} + /// Natural size of an image in points (96 dpi), fitted inside the slide. fn fitted(s: &Session, bytes: &[u8]) -> (f64, f64) { let (w, h) = image::ImageReader::new(std::io::Cursor::new(bytes)) @@ -175,6 +188,10 @@ fn media(s: &mut Session, p: &Value, video: bool) -> Result { Err(_) if !video && !ct.starts_with("audio/") => return Err(bad(cmd, format!("{name} is not a supported audio file ({ct})"))), _ => {} } + // The extension decides the container's MIME even when the probe finds only an audio stream + // (#2390): keep it `audio/*` so the writer stores sound, not a movie. The validation above + // still uses the original `ct`, because an unreadable file has no audio stream. + let ct = if !video && has_audio && !has_video { audio_content_type(ct) } else { ct }; let (duration_ms, width, height, playable) = match &info { Ok(i) => { let (w, h) = i.video.as_ref().map(|v| (v.width, v.height)).unwrap_or((0, 0)); @@ -244,3 +261,23 @@ pub(super) fn audio(s: &mut Session, p: &Value) -> Result { pub(super) fn video(s: &mut Session, p: &Value) -> Result { media(s, p, true) } + +#[cfg(test)] +mod tests { + use super::audio_content_type; + + #[test] + fn audio_content_type_maps_every_audio_only_container() { + for (video, audio) in [ + ("video/x-ms-wmv", "audio/x-ms-wma"), + ("video/mp4", "audio/mp4"), + ("video/webm", "audio/webm"), + ("video/ogg", "audio/ogg"), + ("video/quicktime", "audio/mp4"), + ] { + assert_eq!(audio_content_type(video), audio, "{video}"); + } + assert_eq!(audio_content_type("audio/mpeg"), "audio/mpeg"); + assert_eq!(audio_content_type("application/octet-stream"), "application/octet-stream"); + } +} diff --git a/crates/engine/src/cmd/media.rs b/crates/engine/src/cmd/media.rs index 041793212..a0ab8fda6 100644 --- a/crates/engine/src/cmd/media.rs +++ b/crates/engine/src/cmd/media.rs @@ -182,7 +182,7 @@ mod tests { use deckcraft_model::ShapeId; use serde_json::json; - use crate::cmd::base64_encode; + use crate::cmd::{base64_decode, base64_encode}; use crate::{MediaStatus, Session, UiRequest}; fn wav() -> Vec { @@ -291,6 +291,72 @@ mod tests { assert!(r["warning"].as_str().is_some_and(|w| w.contains("can't be played")), "{r}"); } + #[test] + fn audio_only_asf_saves_as_sound() { + let mut s = Session::with_new(); + let bytes = include_bytes!("../../../media/tests/fixtures/tone.wma"); + let r = s.execute("insert.audio", &json!({"name": "tone.asf", "data": base64_encode(bytes)})).expect("insert"); + assert_eq!(r["contentType"], "audio/x-ms-wma", "{r}"); + + let saved = s.execute("file.saveBytes", &json!({"format": "pptx"})).expect("save"); + let zip = base64_decode(saved["data"].as_str().unwrap()).unwrap(); + let mut z = zip::ZipArchive::new(std::io::Cursor::new(zip)).unwrap(); + let names: Vec = (0..z.len()).map(|i| z.by_index(i).unwrap().name().to_string()).collect(); + assert!(names.iter().any(|n| n == "ppt/media/media1.wma"), "{names:?}"); + assert!(!names.iter().any(|n| n.ends_with(".wmv")), "{names:?}"); + + s.execute("file.openBytes", &json!({"name": "deck.pptx", "data": saved["data"]})).expect("open"); + let info = s.execute("media.info", &json!({})).expect("info"); + assert_eq!(info["video"], false, "{info}"); + assert!(info["durationMs"].as_u64().is_some_and(|ms| ms > 0), "{info}"); + assert_eq!(info["contentType"], "audio/x-ms-wma", "{info}"); + } + + #[test] + fn a_video_container_inserted_as_video_stays_a_movie() { + let mut s = Session::with_new(); + let clip = include_bytes!("../../../media/tests/fixtures/clip-h264.mp4"); + let r = s.execute("insert.video", &json!({"name": "clip.mp4", "data": base64_encode(clip)})).expect("insert"); + assert_eq!(r["contentType"], "video/mp4", "{r}"); + + let saved = s.execute("file.saveBytes", &json!({"format": "pptx"})).expect("save"); + s.execute("file.openBytes", &json!({"name": "deck.pptx", "data": saved["data"]})).expect("open"); + let info = s.execute("media.info", &json!({})).expect("info"); + assert_eq!(info["video"], true, "{info}"); + assert_eq!(info["contentType"], "video/mp4", "{info}"); + } + + #[test] + fn insert_video_still_rejects_an_audio_only_file() { + let mut s = Session::with_new(); + let bytes = include_bytes!("../../../media/tests/fixtures/tone.wma"); + let err = s.execute("insert.video", &json!({"name": "tone.asf", "data": base64_encode(bytes)})).unwrap_err(); + assert!(err.to_string().contains("has no video"), "{err}"); + } + + #[test] + fn unreadable_audio_is_still_refused() { + let mut s = Session::with_new(); + let err = s.execute("insert.audio", &json!({"name": "tone.wma", "data": base64_encode(b"not media")})).unwrap_err(); + assert!(err.to_string().contains("is not a supported audio file"), "{err}"); + } + + #[test] + fn audio_only_ogv_saves_as_sound() { + let mut s = Session::with_new(); + let _ = s.execute("slide.new", &json!({"layout": "blank"})); + let bytes = include_bytes!("../../../media/tests/fixtures/tone.ogg"); + let r = s.execute("insert.audio", &json!({"name": "tone.ogv", "data": base64_encode(bytes)})).expect("insert"); + assert_eq!(r["contentType"], "audio/ogg", "{r}"); + + let saved = s.execute("file.saveBytes", &json!({"format": "pptx"})).expect("save"); + let zip = base64_decode(saved["data"].as_str().unwrap()).unwrap(); + let mut z = zip::ZipArchive::new(std::io::Cursor::new(zip)).unwrap(); + let names: Vec = (0..z.len()).map(|i| z.by_index(i).unwrap().name().to_string()).collect(); + assert!(names.iter().any(|n| n == "ppt/media/media1.ogg"), "{names:?}"); + assert!(!names.iter().any(|n| n.ends_with(".ogv")), "{names:?}"); + } + #[test] fn a_vp8_webm_is_playable_and_warns_that_only_the_audio_plays() { let mut s = Session::with_new(); diff --git a/crates/engine/src/cmd/points.rs b/crates/engine/src/cmd/points.rs index 28eb0dd3b..7546e8c1b 100644 --- a/crates/engine/src/cmd/points.rs +++ b/crates/engine/src/cmd/points.rs @@ -1009,9 +1009,10 @@ pub fn segment_start_of(sh: &Shape, path: usize, index: usize) -> Option vs.iter().position(|v| Some(*v) == j.checked_sub(1)) } -/// Adding, deleting, opening or closing renumbers the points of `path`: a point type remembered -/// for one of them would follow the wrong point. +/// Renumbering invalidates menu picks and any point type remembered for `path`. fn forget_kinds(s: &mut Session, path: usize) { + s.tool.edit_segment = None; + s.tool.edit_vertex = None; if s.tool.vertex_kind.as_ref().is_some_and(|k| k.1 == path) { s.tool.vertex_kind = None; } diff --git a/crates/engine/src/cmd/reuse.rs b/crates/engine/src/cmd/reuse.rs index c85d5dc0f..22190d4a7 100644 --- a/crates/engine/src/cmd/reuse.rs +++ b/crates/engine/src/cmd/reuse.rs @@ -501,15 +501,19 @@ pub(crate) fn import_master( Ok(m) } +/// The content type of a tags part (`p:custDataLst`/`p:tags`), which belongs to exactly one owner. +const TAGS_CONTENT_TYPE: &str = "application/vnd.openxmlformats-officedocument.presentationml.tags+xml"; + /// Copy the source media `used` into `doc` under fresh ids, once each (identical bytes already in -/// `doc` are shared; a linked item keeps its link). +/// `doc` are shared; a linked item keeps its link). A tags part is never shared: identical tag lists +/// on a master and its layouts must stay one part per owner, or PowerPoint repairs the file. fn copy_media(cmd: &str, doc: &mut Presentation, src: &Presentation, used: &[MediaId], map: &mut HashMap) -> Result<()> { for &id in used { if map.contains_key(&id) { continue; } let Some(m) = src.media(id) else { continue }; - let new = if m.link.is_some() { + let new = if m.link.is_some() || m.content_type.eq_ignore_ascii_case(TAGS_CONTENT_TYPE) { let mut item = m.clone(); item.id = MediaId(doc.alloc_id().ok_or_else(|| bad(cmd, NO_ID_SPACE))?); let new = item.id; @@ -792,6 +796,94 @@ mod tests { assert_eq!(got, want, "every reference resolves to its own copied bytes"); } + /// A tags part belongs to one owner. Identical tag lists on a master and its layouts (a + /// think-cell or OLE object on each) come over as one item per owner, never one shared item, + /// so the saved file has a part for each and PowerPoint opens it without a repair. + #[test] + fn reused_master_keeps_a_tags_part_per_owner() { + const TAGS: &str = "application/vnd.openxmlformats-officedocument.presentationml.tags+xml"; + const TAGS_REL: &str = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/tags"; + let tags = br#""#.to_vec(); + let mut src = defaults::new_presentation(None); + let ids: Vec = (0..3) + .map(|_| { + let id = MediaId(src.alloc_id().expect("id")); + src.media.push(deckcraft_model::MediaItem { + id, + name: "tag1.xml".into(), + content_type: TAGS.into(), + data: Arc::new(tags.clone()), + link: None, + }); + id + }) + .collect(); + let object = |id: MediaId| { + Shape { + id: ShapeId(9100), + kind: ShapeKind::Opaque { + xml: r#""#.into(), + preview: None, + label: "think-cell".into(), + parts: vec![("rId2".into(), TAGS_REL.into(), id)], + }, + ..Default::default() + } + }; + let master = src.masters.first_mut().map(Arc::make_mut).expect("master"); + assert!(master.layouts.len() >= 2, "the default master has layouts to share the tags"); + master.shapes = vec![object(ids[0])]; + for (layout, id) in master.layouts.iter_mut().zip(&ids[1..]) { + layout.shapes = vec![object(*id)]; + } + let bytes = deckcraft_format::save(&src).expect("save"); + + let mut s = Session::with_new(); + let own = s.edit(|doc, _| Ok(doc.add_media("tag1.xml", TAGS, tags.clone()).expect("media"))).expect("own tags"); + s.execute( + "slide.reuse", + &json!({"data": super::super::base64_encode(&bytes), "name": "src.deckcraft", "slides": [0], "keepFormatting": true}), + ) + .expect("reuse"); + let doc = &s.doc().expect("doc").doc; + let imported = doc.masters.last().expect("imported master"); + let parts = |shapes: &[Shape]| -> Vec { + shapes + .iter() + .filter_map(|sh| match &sh.kind { + ShapeKind::Opaque { parts, .. } => Some(parts.iter().map(|(_, _, m)| *m)), + _ => None, + }) + .flatten() + .collect() + }; + let mut got = parts(&imported.shapes); + for layout in imported.layouts.iter().take(2) { + got.extend(parts(&layout.shapes)); + } + assert_eq!(got.len(), 3, "the master and two layouts each hold their object"); + for m in &got { + let item = doc.media(*m).expect("copied tags item"); + assert_eq!((item.content_type.as_str(), item.data.as_slice()), (TAGS, tags.as_slice()), "each copy keeps the tag list"); + assert_ne!(*m, own, "a copied tags part is not shared with the destination's own"); + } + let mut distinct = got.clone(); + distinct.sort_by_key(|m| m.0); + distinct.dedup(); + assert_eq!(distinct.len(), got.len(), "each owner has its own tags item: {got:?}"); + + let pptx = deckcraft_pptx::export(doc).expect("export"); + let mut z = zip::ZipArchive::new(std::io::Cursor::new(&pptx)).expect("zip"); + let mut written = 0; + for i in 0..z.len() { + let mut f = z.by_index(i).expect("entry"); + let mut body = Vec::new(); + std::io::Read::read_to_end(&mut f, &mut body).expect("read"); + written += usize::from(body == tags); + } + assert!(written >= 3, "the saved file has a tags part per owner, found {written}"); + } + fn link_to(slide: SlideId) -> Hyperlink { Hyperlink { action: Action::Slide { slide }, diff --git a/crates/engine/src/cmd/review.rs b/crates/engine/src/cmd/review.rs index 351ca29dc..67e99d273 100644 --- a/crates/engine/src/cmd/review.rs +++ b/crates/engine/src/cmd/review.rs @@ -246,6 +246,26 @@ fn neighbour(s: &mut Session, p: &Value, forward: bool) -> Result { Ok(json!({"slide": slide, "index": index, "text": text})) } +/// Whether alternative text is a picture's file name and nothing else: one word ending in a +/// picture file's extension (`IMG_2041.png`, `C:\\photos\\a.JPG`), or the name of the file the +/// picture came from, which may have spaces (`Screenshot 2024 at 10.00.png`). +fn is_file_name(alt: &str, file: Option<&str>) -> bool { + const PICTURE_EXTENSIONS: [&str; 15] = + ["png", "jpg", "jpeg", "jpe", "gif", "bmp", "tif", "tiff", "webp", "svg", "emf", "wmf", "heic", "avif", "ico"]; + let alt = alt.trim(); + let one_word = !alt.is_empty() && !alt.contains(char::is_whitespace); + (one_word && alt.rsplit_once('.').is_some_and(|(stem, ext)| !stem.is_empty() && PICTURE_EXTENSIONS.iter().any(|e| ext.eq_ignore_ascii_case(e)))) + || file.is_some_and(|f| !alt.is_empty() && f.trim().eq_ignore_ascii_case(alt)) +} + +/// The name of the file a picture shape's picture came from, if it has one. +fn picture_file<'a>(doc: &'a deckcraft_model::Presentation, sh: &deckcraft_model::Shape) -> Option<&'a str> { + match &sh.kind { + deckcraft_model::ShapeKind::Picture { fill } => doc.media(fill.media).map(|m| m.name.as_str()), + _ => None, + } +} + fn accessibility(s: &mut Session, _p: &Value) -> Result { let st = s.doc()?; let mut out = vec![]; @@ -261,8 +281,12 @@ fn accessibility(s: &mut Session, _p: &Value) -> Result { | deckcraft_model::ShapeKind::Media(_) | deckcraft_model::ShapeKind::Group { .. } ); - if needs_alt && sh.descr.trim().is_empty() && !sh.decorative { + if sh.descr.trim().is_empty() && !sh.decorative && (needs_alt || crate::icons::is_inserted_icon(sh)) { out.push(json!({"slide": i, "shape": sh.id, "name": sh.name, "issue": "Missing alternative text"})); + } else if needs_alt && !sh.decorative && is_file_name(&sh.descr, picture_file(&st.doc, sh)) { + // Insert Picture names a picture after its file, which is all a screen reader + // would then say (#2224). + out.push(json!({"slide": i, "shape": sh.id, "name": sh.name, "issue": "Alternative text is a file name"})); } }); // Low-contrast text against the slide background. @@ -1041,4 +1065,45 @@ mod accessibility_contrast_tests { assert!(!contrasts.iter().any(|issue| issue["shape"] == 6), "black control warned: {issues}"); assert!(!contrasts.iter().any(|issue| issue["shape"] == 8), "white break or spaces warned: {issues}"); } + + /// #2224: Insert Picture's alt text is the file name, which says nothing; it is reported until + /// it is described or marked decorative. A description that mentions a file is fine. + #[test] + fn alt_text_that_is_a_file_name_is_reported() { + let png: Vec = vec![ + 137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13, 73, 72, 68, 82, 0, 0, 0, 8, 0, 0, 0, 8, 8, 2, 0, 0, 0, 75, 109, 41, 220, 0, 0, 0, 17, 73, + 68, 65, 84, 120, 156, 99, 184, 163, 161, 129, 21, 49, 12, 45, 9, 0, 123, 123, 75, 1, 251, 162, 81, 240, 0, 0, 0, 0, 73, 69, 78, 68, 174, + 66, 96, 130, + ]; + let mut s = Session::with_new(); + let id = s.execute("insert.picture", &json!({"data": crate::cmd::base64_encode(&png), "name": "IMG_2041.png"})).unwrap()["id"].clone(); + let named = |s: &mut Session| { + let issues = s.execute("review.accessibility", &json!({})).unwrap(); + issues.as_array().unwrap().iter().filter(|i| i["shape"] == id && i["issue"] == "Alternative text is a file name").count() + }; + assert_eq!(named(&mut s), 1); + for (text, decorative, expected) in [ + ("photo.JPEG", false, 1), + ("C:\\Users\\me\\Pictures\\holiday.png", false, 1), + ("A red square", false, 0), + ("A red square, from IMG_2041.png", false, 0), + ("IMG_2041.png", true, 0), + ] { + s.execute("shape.altText", &json!({"text": text, "decorative": decorative, "ids": [id]})).unwrap(); + assert_eq!(named(&mut s), expected, "{text:?} decorative {decorative}"); + } + // A file name with spaces is reported when it is the picture's own file's. + let mut s = Session::with_new(); + let id = + s.execute("insert.picture", &json!({"data": crate::cmd::base64_encode(&png), "name": "Screenshot 2024 at 10.00.png"})).unwrap()["id"] + .clone(); + let issues = s.execute("review.accessibility", &json!({})).unwrap(); + assert!(issues.as_array().unwrap().iter().any(|i| i["shape"] == id && i["issue"] == "Alternative text is a file name"), "{issues}"); + assert!(!is_file_name("Version 2.0", None), "a version number is not a picture's extension"); + assert!(!is_file_name(".png", None)); + assert!(!is_file_name("A red square, from IMG_2041.png", None)); + // The picture's own file name counts, spaces and all. + assert!(is_file_name("Screenshot 2024 at 10.00.png", Some("Screenshot 2024 at 10.00.png"))); + assert!(!is_file_name("Screenshot 2024 at 10.00.png", None)); + } } diff --git a/crates/engine/src/cmd/shape.rs b/crates/engine/src/cmd/shape.rs index b7b3d3f05..54c25c67f 100644 --- a/crates/engine/src/cmd/shape.rs +++ b/crates/engine/src/cmd/shape.rs @@ -10,7 +10,7 @@ use serde_json::{Value, json}; use super::{ CommandSpec, NO_ID_SPACE, bad, bool_or, bool_param, cmd, color_param, color_value, edit_geometry, edit_shapes, f64_param, has_selection, - has_slide, id_param, ok, opt_usize_param, str_param, targets, usize_param, with_param, xfrm_of, + has_slide, id_param, ok, opt_usize_param, require_any, str_param, targets, usize_param, with_param, xfrm_of, }; use crate::{Result, Session}; @@ -34,7 +34,7 @@ pub fn specs() -> Vec { "Connect Shapes", [], None, - "{from: shape id, to: shape id, fromSite?, toSite?: site index (default: the closest pair), id?: existing line to glue (else a new connector), preset?: straightConnector1|bentConnector3|curvedConnector3} → {id}", + "{from: shape id, to: shape id, fromSite?, toSite?: site index (default: with neither given, the sites facing each other along the dominant direction between the shapes, a tie to the lower index; with one given, the closest site of the other shape; a box has 0 top, 1 left, 2 bottom, 3 right; shape.sites lists them), id?: existing line to glue (else a new connector), preset?: straightConnector1|bentConnector3|curvedConnector3} → {id}", has_slide, connect ), @@ -112,7 +112,7 @@ pub fn specs() -> Vec { "Shape Outline", ["Shape Format", "Shape Styles"], None, - "{color?, none?, width?: pt, dash?: solid|dot|dash|lgDash|dashDot|sysDot|sysDash, cap?: flat|round|square, join?: round|bevel|miter, compound?: single|double|thickThin|thinThick|triple, head?: none|triangle|stealth|diamond|oval|arrow, tail?, headSize?: sm|med|lg, tailSize?, reset?, ids?}; a group also formats its members", + "{color?, none?, width?: pt, dash?: solid|dot|dash|lgDash|dashDot|sysDot|sysDash, cap?: flat|round|square, join?: round|bevel|miter, compound?: single|double|thickThin|thinThick|triple, head?: none|triangle|stealth|diamond|oval|arrow, tail?, headSize?: sm|med|lg, tailSize?, reset?, ids?} (at least one key); a group also formats its members", has_selection, line ), @@ -121,7 +121,7 @@ pub fn specs() -> Vec { "Shape Effects", ["Shape Format", "Shape Styles"], None, - "{shadow?: none|outer|inner|perspective|{color, blur, dist, dir}, glow?: none|{color, radius}, softEdges?: pt, reflection?: none|tight|half|full, bevel?: none|circle|…, threeD?: {camera?: preset, rotX?, rotY?, rotZ?: deg, z?: pt, bevelTop?, bevelBottom?: none|circle|…, bevelTopW?, bevelTopH?, bevelBottomW?, bevelBottomH?, depth?, contour?: pt, material?, lighting?, reset?: true}, shadowProps?: {color?, transparency?: 0..1, size?: 0.01..2 (1 = 100%), blur?: pt, dist?: pt, dir?: deg}, glowProps?: {color?, transparency?, radius?: pt}, reflectionProps?: {transparency?, size?: 0..1, dist?: pt, blur?: pt}, reset?, ids?} (the *Props keys adjust the current effect, adding a default one when there is none)", + "{shadow?: none|outer|inner|perspective|{color, blur, dist, dir}, glow?: none|{color, radius}, softEdges?: pt, reflection?: none|tight|half|full, bevel?: none|circle|…, threeD?: {camera?: preset, rotX?, rotY?, rotZ?: deg, z?: pt, bevelTop?, bevelBottom?: none|circle|…, bevelTopW?, bevelTopH?, bevelBottomW?, bevelBottomH?, depth?, contour?: pt, material?, lighting?, reset?: true}, shadowProps?: {color?, transparency?: 0..1, size?: 0.01..2 (1 = 100%), blur?: pt, dist?: pt, dir?: deg}, glowProps?: {color?, transparency?, radius?: pt}, reflectionProps?: {transparency?, size?: 0..1, dist?: pt, blur?: pt}, reset?, ids?} (at least one key) (the *Props keys adjust the current effect, adding a default one when there is none)", has_selection, effects ), @@ -135,7 +135,15 @@ pub fn specs() -> Vec { quick_style ), cmd!("shape.rename", "Rename", ["Selection Pane"], None, "{name, id?}", has_selection, rename), - cmd!("shape.altText", "Alt Text", ["Shape Format", "Accessibility"], None, "{text, decorative?: bool, ids?}", has_selection, alt_text), + cmd!( + "shape.altText", + "Alt Text", + ["Shape Format", "Accessibility"], + None, + "{text?: string, decorative?: bool, ids?}", + has_selection, + alt_text + ), cmd!("shape.visible", "Show/Hide", ["Selection Pane"], None, "{visible?: bool, ids?}", has_selection, visible), cmd!( "shape.lock", @@ -161,7 +169,7 @@ pub fn specs() -> Vec { "Corrections", ["Picture Format", "Adjust"], None, - "{brightness?: -1..1, contrast?: -1..1, saturation?: 0..4, grayscale?: bool, transparency?: 0..1, reset?: bool, ids?}", + "{brightness?: -1..1, contrast?: -1..1, saturation?: 0..4, grayscale?: bool, transparency?: 0..1, reset?: bool, ids?} (at least one key)", has_selection, picture_adjust ), @@ -350,10 +358,12 @@ fn rename(s: &mut Session, p: &Value) -> Result { } fn alt_text(s: &mut Session, p: &Value) -> Result { - let text = str_param(p, "text").unwrap_or("").to_string(); + let text = str_param(p, "text"); let deco = bool_param(p, "decorative"); edit_shapes(s, p, "shape.altText", |sh| { - sh.descr = text.clone(); + if let Some(text) = text { + sh.descr = text.to_owned(); + } if let Some(d) = deco { sh.decorative = d; } diff --git a/crates/engine/src/cmd/shape/appearance.rs b/crates/engine/src/cmd/shape/appearance.rs index c9a318abc..c736beb78 100644 --- a/crates/engine/src/cmd/shape/appearance.rs +++ b/crates/engine/src/cmd/shape/appearance.rs @@ -1,7 +1,7 @@ use super::{ ColorRef, ColorTransform, Dash, Effects, Fill, Geom, Glow, Gradient, GradientShape, GradientStop, Line, LineEnd, PictureFill, PictureMode, Reflection, Result, Rgba, SchemeSlot, Session, Shadow, ShapeStyle, Value, apply_fill, bad, bool_or, color_param, color_value, edit_geometry, - edit_shapes, f64_param, inherited_fills, json, opt_usize_param, requested_fill, str_param, targets, + edit_shapes, f64_param, inherited_fills, json, opt_usize_param, requested_fill, require_any, str_param, targets, }; pub(super) fn adjust(s: &mut Session, p: &Value) -> Result { @@ -237,6 +237,7 @@ fn line_end(v: &str) -> Option { } pub(super) fn line(s: &mut Session, p: &Value) -> Result { + require_any(p, "shape.line", &["color", "none", "width", "dash", "cap", "join", "compound", "head", "tail", "headSize", "tailSize", "reset"])?; let reset = bool_or(p, "reset", false); let none = bool_or(p, "none", false); let color = color_param(p, "color"); @@ -356,6 +357,15 @@ fn shadow_preset(v: &Value) -> Option> { } pub(super) fn effects(s: &mut Session, p: &Value) -> Result { + // `glow: null` and `softEdges: null` clear those effects (No Glow, No Soft Edges), so a null + // counts as something to set for them. + if !["glow", "softEdges"].iter().any(|k| p.get(*k).is_some()) { + require_any( + p, + "shape.effects", + &["shadow", "glow", "softEdges", "reflection", "bevel", "threeD", "shadowProps", "glowProps", "reflectionProps", "reset"], + )?; + } let reset = bool_or(p, "reset", false); let shadow = p.get("shadow").and_then(shadow_preset); let glow: Option> = p.get("glow").map(|g| match g { diff --git a/crates/engine/src/cmd/shape/freeform.rs b/crates/engine/src/cmd/shape/freeform.rs index f6886c75f..75daff898 100644 --- a/crates/engine/src/cmd/shape/freeform.rs +++ b/crates/engine/src/cmd/shape/freeform.rs @@ -1,4 +1,4 @@ -use super::{ColorRef, Fill, Geom, Line, NO_ID_SPACE, Result, Session, Value, bad, bool_or, id_param, json, str_param, usize_param}; +use super::{ColorRef, Fill, Geom, Line, NO_ID_SPACE, Result, Session, Value, bad, bool_or, id_param, json, str_param, usize_param, xfrm_of}; pub(super) fn sites(s: &mut Session, p: &Value) -> Result { let id = id_param(p, "id", "shape.sites")?.ok_or_else(|| bad("shape.sites", "missing `id`"))?; @@ -24,20 +24,50 @@ pub(super) fn connect(s: &mut Session, p: &Value) -> Result { return Err(bad("shape.connect", "both shapes need connection sites (lines and groups have none)")); } let pick = |v: &[deckcraft_geom::Point], key: &str| usize_param(p, key).filter(|i| *i < v.len()); + // A site left unsaid is the one facing the other shape along the dominant direction between + // the two (a box mostly below is left from the bottom), which is where a person glues an + // arrow; "the closest pair" chose a side site for a diagonal neighbour and crossed boxes. + // The direction runs between the shapes' box centres: the mean of the sites is off-centre + // for a shape whose sites are not symmetric (a triangle's lie mostly along its base). + // In slide space, as the sites are: a shape inside a group is placed where the group draws it. + let centre = |id| { + crate::connect::locate(&st.doc, &st.selection, st.shapes(), id) + .map(|(sh, to_abs)| to_abs * xfrm_of(&st.doc, &st.selection, sh).center()) + .unwrap_or_default() + }; + let (ca, cb) = (centre(from), centre(to)); + // A tie goes to the lowest site index: an exact diagonal leaves a box from its bottom (site 2, + // before the right side, 3) and enters the other at its top (0, before the left side, 1), and + // shapes with one centre, where every direction is as good, both take site 0. + let facing = |v: &[deckcraft_geom::Point], c: deckcraft_geom::Point, dx: f64, dy: f64| { + let len = dx.hypot(dy).max(1e-9); + let cos: Vec = v + .iter() + .map(|q| { + let (sx, sy) = (q.x - c.x, q.y - c.y); + (sx * dx + sy * dy) / (sx.hypot(sy).max(1e-9) * len) + }) + .collect(); + let best = cos.iter().copied().fold(f64::NEG_INFINITY, f64::max); + cos.iter().position(|x| *x >= best - 1e-9).unwrap_or(0) + }; + // With one site given, the other end is the site of the other shape closest to it, as before; + // the facing rule is for the case where neither is given. + let closest = |v: &[deckcraft_geom::Point], to: deckcraft_geom::Point| { + let mut best = (f64::MAX, 0); + for (i, q) in v.iter().enumerate() { + let d = (*q - to).hypot(); + if d < best.0 { + best = (d, i); + } + } + best.1 + }; let (ia, ib) = match (pick(&a, "fromSite"), pick(&b, "toSite")) { (Some(i), Some(j)) => (i, j), - (fi, fj) => { - let mut best = (f64::MAX, 0, 0); - for (i, pa) in a.iter().enumerate().filter(|(i, _)| fi.is_none_or(|f| f == *i)) { - for (j, pb) in b.iter().enumerate().filter(|(j, _)| fj.is_none_or(|f| f == *j)) { - let d = (*pa - *pb).hypot(); - if d < best.0 { - best = (d, i, j); - } - } - } - (best.1, best.2) - } + (Some(i), None) => (i, closest(&b, a[i])), + (None, Some(j)) => (closest(&a, b[j]), j), + (None, None) => (facing(&a, ca, cb.x - ca.x, cb.y - ca.y), facing(&b, cb, ca.x - cb.x, ca.y - cb.y)), }; let (p0, p1) = (a[ia], b[ib]); let id = match id_param(p, "id", "shape.connect")? { diff --git a/crates/engine/src/cmd/shape/picture.rs b/crates/engine/src/cmd/shape/picture.rs index 09cf22ae0..5db75277f 100644 --- a/crates/engine/src/cmd/shape/picture.rs +++ b/crates/engine/src/cmd/shape/picture.rs @@ -1,4 +1,4 @@ -use super::{NO_ID_SPACE, Result, Session, Value, bad, bool_or, bool_param, edit_geometry, edit_shapes, f64_param, json}; +use super::{NO_ID_SPACE, Result, Session, Value, bad, bool_or, bool_param, edit_geometry, edit_shapes, f64_param, json, require_any}; pub(super) fn crop(s: &mut Session, p: &Value) -> Result { let c = [f64_param(p, "left"), f64_param(p, "top"), f64_param(p, "right"), f64_param(p, "bottom")]; @@ -15,6 +15,7 @@ pub(super) fn crop(s: &mut Session, p: &Value) -> Result { } pub(super) fn picture_adjust(s: &mut Session, p: &Value) -> Result { + require_any(p, "picture.adjust", &["brightness", "contrast", "saturation", "grayscale", "transparency", "reset"])?; edit_shapes(s, p, "picture.adjust", |sh| { if let deckcraft_model::ShapeKind::Picture { fill } = &mut sh.kind { let a = &mut fill.adjust; diff --git a/crates/engine/src/cmd/slide.rs b/crates/engine/src/cmd/slide.rs index 03114d2ff..5ee872703 100644 --- a/crates/engine/src/cmd/slide.rs +++ b/crates/engine/src/cmd/slide.rs @@ -38,7 +38,7 @@ pub fn specs() -> Vec { cmd!(noundo "slide.first", "First Slide", [], Some("Home"), "{}", has_slide, first), cmd!(noundo "slide.last", "Last Slide", [], Some("End"), "{}", has_slide, last), cmd!(noundo "slide.selectRange", "Select Slide Range", [], None, "{to: index, from?: index (default the current slide), add?: bool (keep the slides already selected)}", has_slide, select_range), - cmd!(noundo "slide.selectSlides", "Select Slides", [], None, "{ids?: [slide id], indices?: [index], add?: bool}", has_slide, select_slides), + cmd!(noundo "slide.selectSlides", "Select Slides", [], None, "{ids?: [slide id], indices?: [index], add?: bool, anchor?: slide id (the range anchor of a grid selection)}", has_slide, select_slides), cmd!("slide.hide", "Hide Slide", ["Slide Show", "Set Up"], None, "{index?, hidden?: bool}", has_slide, hide), cmd!("slide.layout", "Layout", ["Home", "Slides"], None, "{layout: name or kind, index?}", has_slide, set_layout), cmd!("slide.reset", "Reset", ["Home", "Slides"], None, "{index?}", has_slide, reset), @@ -47,7 +47,7 @@ pub fn specs() -> Vec { "Notes", ["View"], None, - "{text | body: formatted notes (as in slide.inspect's notesBody), index?} (text as typed: untouched notes keep their formatting)", + "{text | body: formatted notes (as in slide.inspect's notesBody), index?, coalesce?: bool (default false)} (text keeps untouched formatting; coalesce joins consecutive editor changes on one slide)", has_slide, notes ), @@ -337,7 +337,7 @@ fn slide_ids_param(v: &Value, doc: &Presentation, cmd: &str) -> Result Result { fn select_slides(s: &mut Session, p: &Value) -> Result { let add = bool_or(p, "add", false); + let anchor = p.get("anchor").and_then(Value::as_u64).and_then(|x| u32::try_from(x).ok()).map(SlideId); let ids: Vec = { let st = s.doc()?; let mut v: Vec = p @@ -429,7 +430,8 @@ fn select_slides(s: &mut Session, p: &Value) -> Result { } sel.shapes.clear(); sel.text = None; - sel.range_anchor = None; + let current = doc.slides.get(sel.slide).map(|x| x.id); + sel.range_anchor = anchor.filter(|a| doc.slide_index(*a).is_some()).zip(current); })?; Ok(json!({"selected": s.doc()?.selection.slides})) } @@ -600,6 +602,7 @@ fn reset(s: &mut Session, p: &Value) -> Result { fn notes(s: &mut Session, p: &Value) -> Result { let i = index_of(s, p)?; + let coalesce = bool_or(p, "coalesce", false); // Formatted notes as a whole (the notes editors), or text: then only what was retyped // changes, so bold, levels and bullets around it survive. let body = match p.get("body") { @@ -607,14 +610,26 @@ fn notes(s: &mut Session, p: &Value) -> Result { None => None, }; let text = str_param(p, "text").unwrap_or("").to_string(); + let st = s.doc_mut()?; + let slide = st.doc.slides.get(i).ok_or_else(|| bad("slide.notes", "no such slide"))?; + let id = slide.id; + let mut replacement = body.unwrap_or_else(|| { + let mut notes = slide.notes.clone(); + deckcraft_model::edit::replace_text(&mut notes, &text); + notes + }); + if !coalesce || st.notes_run != Some(id) { + st.notes_before = None; + } + st.notes_run = coalesce.then_some(id); + if coalesce && slide.notes == replacement { + return ok(); + } s.edit(|doc, _| { if let Some(sl) = doc.slides.get_mut(i) { let sl = Arc::make_mut(sl); let notes = &mut sl.notes; - match body { - Some(b) => *notes = b, - None => deckcraft_model::edit::replace_text(notes, &text), - } + std::mem::swap(notes, &mut replacement); if !notes.is_empty() { sl.has_notes_slide = true; } @@ -682,6 +697,11 @@ fn section_remove(s: &mut Session, p: &Value) -> Result { let sec = doc.sections.remove(i); if with_slides { doc.slides.retain(|x| !sec.slides.contains(&x.id)); + // As in slide.delete: the deleted slides leave every custom show and the selection. + for show in &mut doc.custom_shows { + show.slides.retain(|x| !sec.slides.contains(x)); + } + sel.slides.retain(|x| !sec.slides.contains(x)); sel.slide = sel.slide.min(doc.slides.len().saturating_sub(1)); } else if let Some(prev) = i.checked_sub(1).and_then(|k| doc.sections.get_mut(k)) { prev.slides.extend(sec.slides); @@ -754,6 +774,63 @@ mod tests { use crate::Session; + #[test] + fn consecutive_notes_edits_are_one_undo_step() { + let (mut s, _) = deck(2); + let read = |s: &Session, i: usize| s.doc().expect("doc").doc.slides[i].notes.text(); + let write = |s: &mut Session, i, text| { + s.execute("slide.notes", &json!({"index": i, "text": text, "coalesce": true})).expect("edit notes"); + }; + let initial = read(&s, 0); + for text in ["one", "one two", "one two three"] { + write(&mut s, 0, text); + } + let first_run = read(&s, 0); + s.execute("edit.undo", &json!({})).expect("undo run"); + assert_eq!(read(&s, 0), initial); + s.execute("edit.redo", &json!({})).expect("redo run"); + assert_eq!(read(&s, 0), first_run); + + write(&mut s, 0, "after redo"); + let before_command = read(&s, 0); + s.execute("slide.rename", &json!({"index": 0, "name": "named"})).expect("intervening edit"); + write(&mut s, 0, "after command"); + s.execute("edit.undo", &json!({})).expect("undo later notes"); + assert_eq!(read(&s, 0), before_command); + s.execute("edit.undo", &json!({})).expect("undo rename"); + assert_eq!(read(&s, 0), before_command); + s.execute("edit.undo", &json!({})).expect("undo post-redo run"); + assert_eq!(read(&s, 0), first_run); + + write(&mut s, 0, "slide zero"); + let zero = read(&s, 0); + let other = read(&s, 1); + write(&mut s, 1, "slide one"); + write(&mut s, 1, "slide one continued"); + s.execute("edit.undo", &json!({})).expect("undo other slide's run"); + assert_eq!(read(&s, 1), other); + assert_eq!(read(&s, 0), zero); + write(&mut s, 0, "after undo"); + s.execute("edit.undo", &json!({})).expect("undo starts a separate run"); + assert_eq!(read(&s, 0), zero); + assert!(s.doc().expect("doc").history.redo.len() < 2, "typing clears the prior redo branch"); + + write(&mut s, 0, "before navigating"); + let before_navigation = read(&s, 0); + s.execute("slide.go", &json!({"index": 0})).expect("select first"); + s.execute("slide.go", &json!({"index": 1})).expect("leave slide"); + s.execute("slide.go", &json!({"index": 0})).expect("return to slide"); + write(&mut s, 0, "after navigating"); + s.execute("edit.undo", &json!({})).expect("undo post-navigation edit"); + assert_eq!(read(&s, 0), before_navigation); + + s.execute("slide.notes", &json!({"index": 0, "text": "automation first"})).expect("default separate edit"); + let automation_first = read(&s, 0); + s.execute("slide.notes", &json!({"index": 0, "text": "automation second"})).expect("default separate edit"); + s.execute("edit.undo", &json!({})).expect("undo one automation edit"); + assert_eq!(read(&s, 0), automation_first); + } + #[test] fn invalid_index_params_are_rejected_not_defaulted_to_selection() { let mut s = Session::with_new(); @@ -928,6 +1005,29 @@ mod tests { assert_eq!(r["remaining"], 2, "{r}"); } + #[test] + fn removing_a_section_with_its_slides_prunes_them_from_custom_shows() { + let (mut s, ids) = deck(4); + s.execute("section.add", &json!({"name": "A", "at": 0})).expect("A"); + s.execute("section.add", &json!({"name": "B", "at": 2})).expect("B"); + let show = vec![deckcraft_model::SlideId(ids[0]), deckcraft_model::SlideId(ids[2]), deckcraft_model::SlideId(ids[3])]; + s.edit(|doc, _| { + doc.custom_shows = vec![deckcraft_model::CustomShow { name: "Short".into(), slides: show.clone() }]; + Ok(()) + }) + .expect("set custom show"); + s.execute("slide.selectSlides", &json!({"ids": [ids[1], ids[3]]})).expect("select"); + + s.execute("section.remove", &json!({"index": 1, "slides": true})).expect("remove B and its slides"); + assert_eq!(order(&s), [ids[0], ids[1]]); + let st = s.doc().expect("doc"); + assert_eq!(st.doc.custom_shows[0].slides, [deckcraft_model::SlideId(ids[0])], "the deleted slides leave the custom show"); + assert!(st.selection.slides.iter().all(|x| st.doc.slide_index(*x).is_some()), "the selection names only slides of the deck"); + + s.execute("edit.undo", &json!({})).expect("undo"); + assert_eq!(s.doc().expect("doc").doc.custom_shows[0].slides, show); + } + #[test] fn duplicate_keeps_section_order_in_step_with_slides() { let mut s = Session::with_new(); diff --git a/crates/engine/src/cmd/smartart.rs b/crates/engine/src/cmd/smartart.rs index 703251c5a..6083a9e73 100644 --- a/crates/engine/src/cmd/smartart.rs +++ b/crates/engine/src/cmd/smartart.rs @@ -14,7 +14,9 @@ use deckcraft_model::{ }; use serde_json::{Value, json}; -use super::{CommandSpec, NO_ID_SPACE, bad, bool_or, cmd, current_shapes, has_selection, shape_of, str_param, targets, xfrm_of}; +use super::{ + CommandSpec, NO_ID_SPACE, NOTHING_SELECTED, bad, bool_or, cmd, current_shapes, has_doc, has_selection, shape_of, str_param, targets, xfrm_of, +}; use crate::{EngineError, Result, Session}; mod diagrams; @@ -173,6 +175,20 @@ pub fn is_kind(k: &str) -> bool { LAYOUTS.iter().any(|(id, _)| *id == k) } +// Session::execute_unguarded defers explicit ids to the handlers only for selection errors. +fn selected_diagram(s: &Session) -> std::result::Result { + has_doc(s)?; + s.active().and_then(selected).map(|(_, diagram)| diagram).ok_or_else(|| NOTHING_SELECTED.into()) +} + +fn has_diagram(s: &Session) -> std::result::Result<(), String> { + selected_diagram(s).map(|_| ()) +} + +fn has_diagram_node(s: &Session) -> std::result::Result<(), String> { + selected_diagram(s).and_then(|diagram| if diagram.nodes.is_empty() { Err(NOTHING_SELECTED.into()) } else { Ok(()) }) +} + pub fn specs() -> Vec { vec![ cmd!( @@ -181,7 +197,7 @@ pub fn specs() -> Vec { ["Diagram Design", "Create Graphic"], None, "{id?} → {id, kind, nodes: [{text, level}]} (id: the Diagram group or one of its shapes; default the selection)", - has_selection, + has_diagram, nodes ), cmd!( @@ -190,7 +206,7 @@ pub fn specs() -> Vec { ["Diagram Design", "Create Graphic"], None, "{id?, nodes?: [{text, level}], lines?: [string] (leading tabs set the level), index?, text?, title?} (index + text edits one node; title: its Name and Title box)", - has_selection, + has_diagram, set_nodes ), cmd!( @@ -199,7 +215,7 @@ pub fn specs() -> Vec { ["Diagram Design", "Create Graphic"], None, "{id?, index?, position?: after|before|below|above|assistant, text?} → {index} (default: after the last node)", - has_selection, + has_diagram, add_node ), cmd!( @@ -208,18 +224,18 @@ pub fn specs() -> Vec { ["Diagram Design", "Create Graphic"], None, "{id?, index} (its sub-points move up one level)", - has_selection, + has_diagram, remove_node ), - cmd!("smartArt.promote", "Promote", ["Diagram Design", "Create Graphic"], None, "{id?, index}", has_selection, promote), - cmd!("smartArt.demote", "Demote", ["Diagram Design", "Create Graphic"], None, "{id?, index}", has_selection, demote), + cmd!("smartArt.promote", "Promote", ["Diagram Design", "Create Graphic"], None, "{id?, index}", has_diagram_node, promote), + cmd!("smartArt.demote", "Demote", ["Diagram Design", "Create Graphic"], None, "{id?, index}", has_diagram_node, demote), cmd!( "smartArt.layout", "Change Layout", ["Diagram Design", "Layouts"], None, "{id?, kind: list|blockList|hBulletList|process|chevron|verticalProcess|stepUp|cycle|blockCycle|radial|hierarchy|pyramid|invertedPyramid|matrix|titledMatrix|pictureList|pictureCaption|pictureProcess|pictureHList|timeline|venn|target|textCycle|continuousCycle|horizontalHierarchy|gridMatrix|gear|funnel|segmentedCycle|multidirectionalCycle|orgChart|halfCircleOrgChart|cycleMatrix|segmentedPyramid|pie|nameTitleOrgChart|verticalBoxList|trapezoidList|tableList|accentProcess|continuousBlockProcess|bendingProcess|linearVenn|stackedVenn|nestedTarget}", - has_selection, + has_diagram, change_layout ), cmd!( @@ -237,7 +253,7 @@ pub fn specs() -> Vec { ["Diagram Design", "Reset"], None, "{id?} → {id} (the graphic becomes a text box of its outline, bulleted by level)", - has_selection, + has_diagram, to_text ), cmd!( @@ -246,7 +262,7 @@ pub fn specs() -> Vec { ["Diagram Design", "Reset"], None, "{id?} (the graphic becomes a plain group of its shapes; the outline is dropped)", - has_selection, + has_diagram, to_shapes ), cmd!( @@ -255,7 +271,7 @@ pub fn specs() -> Vec { ["Diagram Design", "Create Graphic"], None, "{id?, index, data?: base64 | path?: string | reset?: bool} (the node's picture placeholder in picture layouts)", - has_selection, + has_diagram, set_picture ), cmd!( @@ -264,7 +280,7 @@ pub fn specs() -> Vec { ["Diagram Design", "Diagram Styles"], None, "{id?, style: flat|subtle|intense|outline|polished|inset|cartoon|powder|brick}", - has_selection, + has_diagram, change_style ), cmd!( @@ -273,7 +289,7 @@ pub fn specs() -> Vec { ["Diagram Design", "Diagram Styles"], None, "{id?, colors: colorful|range23|range34|range45|range56|accent1|…|accent6|accent1Grad|…|accent6Grad}", - has_selection, + has_diagram, change_colors ), ] @@ -294,6 +310,74 @@ mod tests { .collect() } + #[test] + fn command_eligibility_follows_the_selected_diagram_and_its_nodes() -> Result<()> { + let edits = [ + "smartArt.nodes", + "smartArt.setNodes", + "smartArt.addNode", + "smartArt.removeNode", + "smartArt.layout", + "smartArt.toText", + "smartArt.toShapes", + "smartArt.picture", + "smartArt.style", + "smartArt.colors", + ]; + let node_edits = ["smartArt.promote", "smartArt.demote"]; + let enabled = |s: &Session, id: &str| crate::find_command(id).is_some_and(|spec| spec.info(s).enabled); + let mut s = Session::with_new(); + s.execute("slide.new", &json!({"layout": "blank"}))?; + assert!(edits.iter().chain(&node_edits).all(|id| !enabled(&s, id))); + assert!(enabled(&s, "insert.smartArt")); + + s.execute("insert.textBox", &json!({"text": "Plan\nBuild"}))?; + assert!(edits.iter().chain(&node_edits).all(|id| !enabled(&s, id))); + assert!(enabled(&s, "smartArt.fromText")); + let graphic = s.execute("smartArt.fromText", &json!({"kind": "process"}))?["id"].clone(); + assert!(edits.iter().chain(&node_edits).all(|id| enabled(&s, id))); + + let child = s + .doc()? + .selected_shapes() + .into_iter() + .find_map(|shape| match &shape.kind { + ShapeKind::Group { children, .. } => children.first().map(|child| child.id.0), + _ => None, + }) + .ok_or_else(|| EngineError::Other("diagram has no child".into()))?; + s.execute("selection.select", &json!({"id": child}))?; + assert!(edits.iter().chain(&node_edits).all(|id| enabled(&s, id))); + assert_eq!(s.execute("smartArt.nodes", &json!({}))?["id"], graphic); + + s.execute("smartArt.setNodes", &json!({"nodes": []}))?; + assert!(edits.iter().all(|id| enabled(&s, id))); + assert!(node_edits.iter().all(|id| !enabled(&s, id))); + assert!(s.execute("smartArt.promote", &json!({"index": 0})).is_err()); + assert!(s.execute("smartArt.demote", &json!({"index": 0})).is_err()); + s.execute("selection.select", &json!({"id": graphic, "toggle": true}))?; + assert!(edits.iter().chain(&node_edits).all(|id| !enabled(&s, id))); + assert_eq!(s.execute("smartArt.nodes", &json!({"id": graphic}))?["id"], graphic); + assert!(s.execute("smartArt.promote", &json!({"id": graphic, "index": 0})).is_err()); + assert!(s.execute("smartArt.demote", &json!({"id": graphic, "index": 0})).is_err()); + s.execute("smartArt.addNode", &json!({"id": graphic, "index": null, "text": "Ship"}))?; + assert!(node_edits.iter().all(|id| enabled(&s, id))); + + let text = s.execute("insert.textBox", &json!({"text": "Notes"}))?["id"].clone(); + assert!(edits.iter().chain(&node_edits).all(|id| !enabled(&s, id))); + assert!(s.execute("smartArt.style", &json!({"id": text, "style": "outline"})).is_err()); + s.execute("smartArt.style", &json!({"id": graphic, "style": "outline"}))?; + assert!(selected(s.doc()?).is_some_and(|(_, diagram)| diagram.style == "outline")); + assert!(s.execute("smartArt.promote", &json!({"id": graphic, "index": 100})).is_err()); + s.execute("selection.select", &json!({"id": graphic, "toggle": true}))?; + assert!(edits.iter().chain(&node_edits).all(|id| !enabled(&s, id))); + s.execute("smartArt.nodes", &json!({"id": graphic}))?; + assert!(enabled(&s, "insert.smartArt")); + s.execute("insert.smartArt", &json!({"kind": "cycle", "items": ["A", "B"]}))?; + assert!(edits.iter().chain(&node_edits).all(|id| enabled(&s, id))); + Ok(()) + } + #[test] fn outline_edits() { let mut n = mk(&[0, 1, 1, 0]); diff --git a/crates/engine/src/cmd/table.rs b/crates/engine/src/cmd/table.rs index 0034645f8..3b2df7502 100644 --- a/crates/engine/src/cmd/table.rs +++ b/crates/engine/src/cmd/table.rs @@ -1,7 +1,7 @@ //! Table Design and Table Layout tabs. use deckcraft_geom::{Affine, Point, Rect}; -use deckcraft_model::{Shape, ShapeKind, Table}; +use deckcraft_model::{Cell, Shape, ShapeKind, Table}; use serde_json::{Value, json}; use super::{ @@ -24,18 +24,24 @@ pub fn specs() -> Vec { "rowBelow", "table.insertRowBelow" )), - cmd!("table.insertColumnLeft", "Insert Left", ["Table Layout", "Rows & Columns"], None, "{col?, id?}", has_selection, |s, p| rows_cols( - s, - p, - "colLeft", - "table.insertColumnLeft" - )), - cmd!("table.insertColumnRight", "Insert Right", ["Table Layout", "Rows & Columns"], None, "{col?, id?}", has_selection, |s, p| rows_cols( - s, - p, - "colRight", - "table.insertColumnRight" - )), + cmd!( + "table.insertColumnLeft", + "Insert Left", + ["Table Layout", "Rows & Columns"], + None, + "{col?, keepWidth?: bool (default false, as in PowerPoint: the table grows by the new column and the other widths stay; true: the other columns shrink in proportion so the table keeps its width), id?} the new column takes the width and cell formatting (fill, margins, anchor, text properties) of the column it is inserted beside", + has_selection, + |s, p| rows_cols(s, p, "colLeft", "table.insertColumnLeft") + ), + cmd!( + "table.insertColumnRight", + "Insert Right", + ["Table Layout", "Rows & Columns"], + None, + "{col?, keepWidth?: bool (default false, as in PowerPoint: the table grows by the new column and the other widths stay; true: the other columns shrink in proportion so the table keeps its width), id?} the new column takes the width and cell formatting (fill, margins, anchor, text properties) of the column it is inserted beside", + has_selection, + |s, p| rows_cols(s, p, "colRight", "table.insertColumnRight") + ), cmd!("table.deleteRow", "Delete Rows", ["Table Layout", "Rows & Columns"], None, "{row?, id?}", has_selection, |s, p| rows_cols( s, p, @@ -322,6 +328,15 @@ fn with_table(s: &mut Session, p: &Value, cmd: &str, f: impl Fn(&mut Table) -> R fn rows_cols(s: &mut Session, p: &Value, op: &str, name: &'static str) -> Result { let (r, c) = at(s, p, name)?; + // Absent: the table grows, as in PowerPoint; present, it must be a bool, so a mistyped value is refused + // rather than silently taken as the default. + let keep_width = match (op, p.get("keepWidth")) { + (_, None) | (_, Some(Value::Null)) => false, + (_, Some(Value::Bool(b))) => *b, + ("colLeft", Some(_)) => return Err(bad("table.insertColumnLeft", "`keepWidth` must be true or false")), + ("colRight", Some(_)) => return Err(bad("table.insertColumnRight", "`keepWidth` must be true or false")), + _ => false, + }; let op = op.to_string(); with_table(s, p, name, move |t| { match op.as_str() { @@ -329,8 +344,8 @@ fn rows_cols(s: &mut Session, p: &Value, op: &str, name: &'static str) -> Result let ok = match op.as_str() { "rowAbove" => t.insert_row(r), "rowBelow" => t.insert_row(r.saturating_add(1)), - "colLeft" => t.insert_col(c), - _ => t.insert_col(c.saturating_add(1)), + "colLeft" => insert_col_like(t, c, c, keep_width), + _ => insert_col_like(t, c.saturating_add(1), c, keep_width), }; if !ok { return Err(bad(name, format!("the table is at its {}-cell limit", deckcraft_model::table::MAX_CELLS))); @@ -351,6 +366,90 @@ fn rows_cols(s: &mut Session, p: &Value, op: &str, name: &'static str) -> Result }) } +/// Insert a column before `at` that looks like column `neighbour` (the one it is inserted beside): +/// its width, and in every row the neighbour cell's explicit formatting with no text. With +/// `keep_width` the columns then shrink in proportion so the table keeps its total width; +/// otherwise (PowerPoint's behaviour) the table grows by the new column and the widths stay. +/// Returns false, leaving the table as it was, when the column would take it past the cell limit. +fn insert_col_like(t: &mut Table, at: usize, neighbour: usize, keep_width: bool) -> bool { + let total = t.width(); + let neighbour = neighbour.min(t.cols.len().saturating_sub(1)); + let w = t.cols.get(neighbour).copied(); + // A neighbour covered by a merge (horizontally or vertically) is formatted as its anchor, which is what shows. + let covered = |r: usize, c: usize| t.rows.get(r).and_then(|row| row.cells.get(c)).is_some_and(|x| x.h_merge || x.v_merge); + let templates: Vec> = (0..t.rows.len()) + .map(|r0| { + let (mut r, mut n) = (r0, neighbour); + while covered(r, n) { + let cell = &t.rows[r].cells[n]; + if cell.h_merge && n > 0 { + n -= 1; + } else if cell.v_merge && r > 0 { + r -= 1; + } else { + break; + } + } + // Only the formatting is kept: the anchor's text is not copied once per covered row. + t.rows[r].cells.get(n).map(|src| { + let mut tpl = Cell::new(""); + copy_cell_format(&mut tpl, src); + tpl + }) + }) + .collect(); + if !t.insert_col(at) { + return false; + } + let at = at.min(t.cols.len().saturating_sub(1)); + if let (Some(w), Some(slot)) = (w, t.cols.get_mut(at)) { + *slot = w; + } + for (row, tpl) in t.rows.iter_mut().zip(templates) { + if let (Some(cell), Some(tpl)) = (row.cells.get_mut(at), tpl) { + copy_cell_format(cell, &tpl); + } + } + let grown = t.width(); + if keep_width && total > 1e-9 && grown > 1e-9 { + let k = total / grown; + for cw in &mut t.cols { + *cw *= k; + } + } + true +} + +/// `dst` takes `src`'s formatting (fill, borders, margins, anchor, text direction and the text +/// properties of its first paragraph, kept on the end mark of an empty paragraph) and keeps its +/// own spans and merge cover. Hyperlinks are not copied. +fn copy_cell_format(dst: &mut Cell, src: &Cell) { + dst.fill.clone_from(&src.fill); + dst.borders.clone_from(&src.borders); + dst.diag_down.clone_from(&src.diag_down); + dst.diag_up.clone_from(&src.diag_up); + dst.margins = src.margins; + dst.anchor = src.anchor; + dst.vertical = src.vertical; + dst.anchor_ctr = src.anchor_ctr; + dst.horz_overflow = src.horz_overflow; + let para = src.text.paragraphs.first().map(|p0| { + let mut end_props = p0.runs.first().map_or_else(|| p0.end_props.clone(), |r| r.props.clone()); + end_props.link = None; + end_props.hover = None; + let mut def_props = p0.def_props.clone(); + def_props.link = None; + def_props.hover = None; + deckcraft_model::text::Paragraph { level: p0.level, props: p0.props.clone(), runs: vec![], def_props, end_props } + }); + let mut list_style = src.text.list_style.clone(); + for l in list_style.levels.iter_mut().flatten() { + l.run.link = None; + l.run.hover = None; + } + dst.text = deckcraft_model::text::TextBody { body: src.text.body.clone(), list_style, paragraphs: vec![para.unwrap_or_default()] }; +} + fn merge(s: &mut Session, p: &Value) -> Result { let sel = s.doc()?.selection.cells; let from = cell_param(p, "from", "table.merge")?.or(sel.map(|c| c.1)).ok_or_else(|| bad("table.merge", "missing `from`"))?; @@ -626,11 +725,18 @@ fn distribute(s: &mut Session, p: &Value, rows: bool) -> Result { }) } +/// A row or column the table doesn't have is an error, like a malformed index (#2260): checked +/// inside the edit, so a refused resize changes nothing and adds no undo step. +fn index_in_table(cmd: &str, key: &str, i: usize, n: usize, what: &str) -> Result<()> { + if i < n { Ok(()) } else { Err(bad(cmd, format!("`{key}` {i} is out of range: the table has {n} {what}"))) } +} + fn column_width(s: &mut Session, p: &Value) -> Result { let (_, c) = at(s, p, "table.columnWidth")?; let w = f64_param(p, "width").ok_or_else(|| bad("table.columnWidth", "missing `width`"))?.clamp(4.0, 4000.0); let keep_total = bool_or(p, "keepTotal", false); with_table(s, p, "table.columnWidth", move |t| { + index_in_table("table.columnWidth", "col", c, t.n_cols(), "columns")?; // Keeping the table's width, the column to the right gives or takes the difference (dragging // an inner border). The last column has none: the table gets wider or narrower. let pair = t.cols.get(c).zip(t.cols.get(c.saturating_add(1))).map(|(a, b)| a.max(0.0) + b.max(0.0)).filter(|x| x.is_finite()); @@ -659,6 +765,7 @@ fn row_height(s: &mut Session, p: &Value) -> Result { let (r, _) = at(s, p, "table.rowHeight")?; let h = f64_param(p, "height").ok_or_else(|| bad("table.rowHeight", "missing `height`"))?.clamp(4.0, 4000.0); with_table(s, p, "table.rowHeight", move |t| { + index_in_table("table.rowHeight", "row", r, t.n_rows(), "rows")?; if let Some(x) = t.rows.get_mut(r) { x.height = h; } diff --git a/crates/engine/src/cmd/text.rs b/crates/engine/src/cmd/text.rs index bc79dccfc..52a8593cb 100644 --- a/crates/engine/src/cmd/text.rs +++ b/crates/engine/src/cmd/text.rs @@ -26,15 +26,14 @@ use autocorrect::autocorrect_options; pub use autocorrect::{AUTOCORRECT, AutoList, correct_word}; pub(crate) use caret::{apply_leading_tabs, delete_dir}; use caret::{delete, delete_surrounding, get, insert, move_caret, select, select_all, select_para, select_word, set}; -use editing::{edit, exit}; pub(crate) use editing::{insert_field, insert_text, paste_body}; pub use formatting::format_range; use formatting::{fonts_used, replace_font}; pub(crate) use formatting::{format_body, format_para, format_run, format_run_levels, link_text}; -pub use ime::{IME_SURROUNDING_MAX_BYTES, ImeSurrounding, cell_range_underlines, composition_underlines, ime_surrounding, range_underlines}; +pub use ime::{cell_range_underlines, range_underlines}; use ime::{commit, compose}; pub(crate) use layout::ctx_for; -pub use layout::{caret_color, caret_line, fit_text_box, layout_for, text_frame, text_pos_at}; +pub use layout::{caret_line, fit_text_box, layout_for, text_frame, text_pos_at}; /// Catalogue text-editing, selection, autocorrect, font, IME, and surrounding-deletion commands /// with their parameter docs and enabled predicates. @@ -95,8 +94,8 @@ pub fn specs() -> Vec { // An input method asks for text around the caret to be removed (macOS press-and-hold, // dictation, Wayland text-input). Internal: the keyboard and control protocol keep the // existing text.delete spelling. `bytes` says the counts are UTF-8 bytes (winit's - // `Ime::DeleteSurrounding`), otherwise characters, both in the logical text - // `ime_surrounding` publishes: a paragraph mark or soft line break is one `\n` byte, so a + // `Ime::DeleteSurrounding`), otherwise characters, both in the logical coordinates + // the editor publishes: a paragraph mark or soft line break is one `\n` byte, so a // range may cross paragraphs. The selection and pre-edit are kept; byte ranges round // inward to whole scalars. A deletion while composing stays in the composition's single // undo step. @@ -134,6 +133,128 @@ pub fn specs() -> Vec { ] } +/// Applies one replacement inside the session's guarded, rollback-capable transaction. +/// The handler records per-insert history; live preedits retain their original undo snapshot. +pub(crate) fn replace_text_range( + s: &mut Session, + range: std::ops::Range, + text: &str, + kind: crate::TextReplaceKind, +) -> Result { + use crate::TextReplaceKind; + + let st = s.doc()?; + let selection = st.selection.text.clone().ok_or_else(|| bad("text.replaceRange", NO_TEXT_POINT))?; + if !selection.notes && st.shape(selection.shape).is_none_or(|shape| shape.locked) { + return Err(bad("text.replaceRange", "the text being edited is unavailable or locked")); + } + let body = body_of(st, &selection).ok_or_else(|| bad("text.replaceRange", "the text being edited is gone"))?; + let invalid = || bad("text.replaceRange", "the range is not in the text"); + if range.start > range.end { + return Err(invalid()); + } + let from = flat_pos(body, range.start).ok_or_else(invalid)?; + let to = flat_pos(body, range.end).ok_or_else(invalid)?; + let old_text = (kind == TextReplaceKind::Typed).then(|| body.text()); + let composing = st.composition.is_some(); + if range.is_empty() && text.is_empty() && !composing { + return Ok(crate::TextReplaceResult { range, selection }); + } + s.begin_text_edit_session()?; + if !matches!(kind, TextReplaceKind::Composing | TextReplaceKind::Committed | TextReplaceKind::Deleted) { + s.settle_composition(); + } + let st = s.doc()?; + let (before, before_selection) = (st.doc.clone(), st.selection.clone()); + let vertex_kind = s.tool.vertex_kind.clone(); + match kind { + TextReplaceKind::Composing | TextReplaceKind::Committed => ime::replace_marked(s, from, to, text, kind == TextReplaceKind::Committed)?, + TextReplaceKind::Deleted if composing => ime::delete_range(s, range.clone(), text)?, + TextReplaceKind::Typed | TextReplaceKind::Pasted | TextReplaceKind::Deleted => { + if let Some(t) = s.doc_mut()?.selection.text.as_mut() { + // Setting the replacement endpoints is part of this edit, not a selection command + // that could settle composition or seal the session's cancellation boundary. + t.anchor = from; + t.caret = to; + t.line_end = None; + } + if kind == TextReplaceKind::Typed { + insert_text(s, text, None)?; + } else if from != to || !text.is_empty() { + editing::replace_selection(s, text, None)?; + } + let st = s.doc_mut()?; + if !Arc::ptr_eq(&before, &st.doc) { + let command = match kind { + TextReplaceKind::Pasted => "edit.paste", + TextReplaceKind::Deleted => "text.delete", + _ => "text.insert", + }; + let label = super::find_command(command).ok_or_else(|| bad("text.replaceRange", "the edit command is not registered"))?.label; + push_undo(st, HistoryEntry { label: label.into(), doc: before, selection: before_selection, vertex_kind }); + } + } + } + let st = s.doc()?; + let selection = st.selection.text.clone().ok_or_else(|| bad("text.replaceRange", NO_TEXT_POINT))?; + let body = body_of(st, &selection).ok_or_else(|| bad("text.replaceRange", "the text being edited is gone"))?; + let caret = flat_offset(body, selection.caret).ok_or_else(invalid)?; + let inserted = if kind == TextReplaceKind::Composing && !text.is_empty() { + let c = st.composition.as_ref().ok_or_else(|| bad("text.replaceRange", "the composition was refused"))?; + let start = flat_offset(body, c.start).ok_or_else(invalid)?; + start..start + c.len + } else if kind == TextReplaceKind::Deleted { + range.start..range.start + } else if text.is_empty() { + caret..caret + } else if let Some(old_text) = old_text { + // AutoCorrect can replace text preceding the requested insertion, such as (c) plus Space. + let after = body.text(); + let unchanged = old_text.chars().zip(after.chars()).take_while(|(a, b)| a == b).count(); + range.start.min(unchanged).min(caret)..caret + } else { + range.start.min(caret)..caret + }; + Ok(crate::TextReplaceResult { range: inserted, selection }) +} + +/// Character offsets count each paragraph separator once, including empty paragraphs. +fn flat_pos(body: &TextBody, mut offset: usize) -> Option { + if body.paragraphs.is_empty() { + return (offset == 0).then_some((0, 0)); + } + for (pi, para) in body.paragraphs.iter().enumerate() { + let len = para.char_len(); + if offset <= len { + return Some((pi, offset)); + } + offset = offset.checked_sub(len.checked_add(1)?)?; + } + None +} + +fn flat_offset(body: &TextBody, pos: Pos) -> Option { + if body.paragraphs.is_empty() { + return (pos == (0, 0)).then_some(0); + } + let para = body.paragraphs.get(pos.0)?; + if pos.1 > para.char_len() { + return None; + } + body.paragraphs.iter().take(pos.0).try_fold(pos.1, |offset, para| offset.checked_add(para.char_len())?.checked_add(1)) +} + +fn edit(s: &mut Session, p: &Value) -> Result { + let result = editing::edit(s, p)?; + s.begin_text_edit_session()?; + Ok(result) +} + +fn exit(s: &mut Session, p: &Value) -> Result { + s.finish_text_edit_session(false)?; + editing::exit(s, p) +} + /// The text body a text selection edits. pub fn body_of<'a>(st: &'a DocState, t: &TextSel) -> Option<&'a TextBody> { if t.notes { diff --git a/crates/engine/src/cmd/text/caret.rs b/crates/engine/src/cmd/text/caret.rs index db7cfd48e..df36eed4c 100644 --- a/crates/engine/src/cmd/text/caret.rs +++ b/crates/engine/src/cmd/text/caret.rs @@ -99,8 +99,8 @@ pub(super) fn delete_surrounding(s: &mut Session, p: &Value) -> Result { let t = st.selection.text.clone().ok_or_else(|| bad("text.deleteSurrounding", "not editing text"))?; let body = body_of(st, &t).ok_or_else(|| bad("text.deleteSurrounding", "the text being edited is gone"))?; let comp = composition_range(body, st.composition.as_ref()); - // The ranges are in the same logical coordinates `ime_surrounding` publishes: one byte for a - // paragraph separator and for a soft line break. A range may therefore cross paragraphs. + // The ranges use the logical coordinates the editor publishes: one byte for a paragraph + // separator and for a soft line break. A range may therefore cross paragraphs. let ordered = { let a = model_pos(body, t.anchor).ok_or_else(|| bad("text.deleteSurrounding", "the selection is not in the text"))?; let b = model_pos(body, t.caret).ok_or_else(|| bad("text.deleteSurrounding", "the selection is not in the text"))?; diff --git a/crates/engine/src/cmd/text/editing.rs b/crates/engine/src/cmd/text/editing.rs index 7e2c37cb4..377dc39ab 100644 --- a/crates/engine/src/cmd/text/editing.rs +++ b/crates/engine/src/cmd/text/editing.rs @@ -73,7 +73,6 @@ fn typed(s: &Session, body: &TextBody, at: Pos, text: &str) -> String { } pub(crate) fn insert_text(s: &mut Session, text: &str, props: Option) -> Result { - let inherited = inherited_aligns_for_edit(s); let text = { let st = s.doc()?; match &st.selection.text { @@ -84,11 +83,21 @@ pub(crate) fn insert_text(s: &mut Session, text: &str, props: Option) None => text.to_string(), } }; - let pos = edit_text(s, |body, t| { + let pos = replace_selection(s, &text, props)?; + autocorrect(s, text.chars().count() == 1)?; + // AutoCorrect can move the caret: a replaced word, or a list lead it removed. + let pos = s.doc()?.selection.text.as_ref().map_or(pos, |t| t.caret); + Ok(json!({"caret": [pos.0, pos.1]})) +} + +/// Shares insertion styling and paragraph direction rules across typing, pasting and deletion. +pub(super) fn replace_selection(s: &mut Session, text: &str, props: Option) -> Result { + let inherited = inherited_aligns_for_edit(s); + edit_text(s, |body, t| { let (a, b) = t.ordered(); let at = ed::delete(body, a, b); let props = props.clone().or_else(|| if a != b { Some(ed::props_at(body, at)) } else { unlinked_at_link_end(body, at) }); - let c = ed::insert(body, at, &text, props); + let c = ed::insert(body, at, text, props); t.anchor = c; t.caret = c; let last = body.paragraphs.len().saturating_sub(1); @@ -98,11 +107,7 @@ pub(crate) fn insert_text(s: &mut Session, text: &str, props: Option) } } c - })?; - autocorrect(s, text.chars().count() == 1)?; - // AutoCorrect can move the caret: a replaced word, or a list lead it removed. - let pos = s.doc()?.selection.text.as_ref().map_or(pos, |t| t.caret); - Ok(json!({"caret": [pos.0, pos.1]})) + }) } /// Per outline level (0..=8), whether shape `id` on the current slide already resolves an diff --git a/crates/engine/src/cmd/text/ime.rs b/crates/engine/src/cmd/text/ime.rs index 274995467..16622b490 100644 --- a/crates/engine/src/cmd/text/ime.rs +++ b/crates/engine/src/cmd/text/ime.rs @@ -1,24 +1,7 @@ -use super::caret::cell_on_slide; use super::editing::unlinked_at_link_end; use super::layout::{ctx_for, layout_for}; use super::{DocState, Paragraph, Result, Session, TextBody, TextSel, Value, bad, body_of, ed, edit_text, json, str_param, xfrm_of}; -/// Maximum number of UTF-8 bytes in an outgoing IME surrounding-text query. -/// -/// This matches `egui::output::MAX_IME_SURROUNDING_TEXT_BYTES`; keeping the bound here lets the -/// engine answer without copying a whole body or document. -pub const IME_SURROUNDING_MAX_BYTES: usize = 4000; - -/// Bounded committed text around an IME selection, in logical (not visual) order and with UTF-8 -/// byte offsets. The current input-method composition (pre-edit) is removed from both the text -/// and the offsets. -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct ImeSurrounding { - pub text: String, - pub cursor: usize, - pub anchor: usize, -} - /// How a soft line break reads in the IME view: a newline, like a paragraph break. /// /// The model stores it as `\u{b}` ([`RunKind::Break`]); publishing that control character would @@ -166,77 +149,6 @@ pub(super) fn walk_backward( } } -/// The committed logical text between two model positions (excluding `end`). `None` when it is -/// longer than `cap` bytes: every caller only needs a bounded answer. -fn logical_between(body: &TextBody, comp: Option<(usize, usize, usize)>, start: (usize, usize), end: (usize, usize), cap: usize) -> Option { - let (a, b) = if start <= end { (start, end) } else { (end, start) }; - let mut out = String::new(); - for pi in a.0..=b.0 { - let Some(para) = body.paragraphs.get(pi) else { return Some(out) }; - let from = if pi == a.0 { a.1 } else { 0 }; - let to = if pi == b.0 { b.1 } else { usize::MAX }; - for (i, ch) in committed_chars(para, comp_in(comp, pi)) { - if i < from || i >= to { - continue; - } - out.push(ch); - if out.len() > cap { - return None; - } - } - if pi < b.0 { - out.push('\n'); - if out.len() > cap { - return None; - } - } - } - Some(out) -} - -/// Committed surrounding text for the text being edited. -/// -/// Returns `None` when the body or selection is invalid, or when the selection alone is wider -/// than [`IME_SURROUNDING_MAX_BYTES`]. An empty body is `Some` with empty text, which is distinct -/// from an unavailable context. `cursor > anchor` is preserved for a reversed selection. -/// -/// Only a bounded window is measured and copied: the query walks at most the budget out from the -/// selection on each side and does not copy the rest of the body. Finding the selection's -/// character offsets inside one paragraph still scans that paragraph's prefix, so the time is not -/// bounded independently of the paragraph length. -pub fn ime_surrounding(st: &DocState, t: &TextSel) -> Option { - let body = body_of(st, t)?; - let comp = composition_range(body, st.composition.as_ref()); - let caret = model_pos(body, t.caret)?; - let anchor = model_pos(body, t.anchor)?; - let (start, end) = if caret <= anchor { (caret, anchor) } else { (anchor, caret) }; - let selected = logical_between(body, comp, start, end, IME_SURROUNDING_MAX_BYTES)?; - let selection_len = selected.len(); - let budget = IME_SURROUNDING_MAX_BYTES.saturating_sub(selection_len); - let (_, _, before_available) = walk_backward(body, comp, start, budget, true); - let (_, _, after_available) = walk_forward(body, comp, end, budget, true); - let mut before = (budget / 2).min(before_available); - let mut after = (budget - before).min(after_available); - before = (budget - after).min(before_available); - after = (budget - before).min(after_available); - let (window_start, _, _) = walk_backward(body, comp, start, before, true); - let (window_end, _, _) = walk_forward(body, comp, end, after, true); - let before_text = logical_between(body, comp, window_start, start, budget)?; - let after_text = logical_between(body, comp, end, window_end, budget)?; - let before_len = before_text.len(); - let mut text = before_text; - text.push_str(&selected); - text.push_str(&after_text); - // The budget arithmetic above already bounds this; refuse rather than publish more. - if text.len() > IME_SURROUNDING_MAX_BYTES { - return None; - } - // The caret and anchor are the selection's own endpoints, so their offsets inside the - // window are the window's start plus either end of the selected text. - let (cursor, anchor) = if caret >= anchor { (before_len + selection_len, before_len) } else { (before_len, before_len + selection_len) }; - Some(ImeSurrounding { text, cursor, anchor }) -} - /// Text an input method sends: no paragraph or line breaks (Enter is a key of its own). fn ime_text(s: &str) -> String { s.chars().filter(|c| !c.is_control()).collect() @@ -273,6 +185,7 @@ pub(super) fn compose(s: &mut Session, p: &Value) -> Result { match current { None if text.is_empty() => Ok(json!({"composing": false})), None => { + s.begin_text_edit_session()?; let st = s.doc()?; let (before, before_selection) = (st.doc.clone(), st.selection.clone()); let (start, props) = edit_text(s, |body, t| { @@ -376,43 +289,52 @@ pub fn cell_range_underlines( out } -/// Underlines under an input method's composition (#101), in slide coordinates: `(from, to, -/// thick)` per line, thick under the part being converted. Empty without a composition, or for -/// notes (an egui text field draws its own composition). -pub fn composition_underlines(st: &DocState) -> Vec<(deckcraft_geom::Point, deckcraft_geom::Point, bool)> { - let (Some(c), Some(t)) = (&st.composition, &st.selection.text) else { return vec![] }; - if t.notes { - return vec![]; +/// Replaces the marked text without a selection command that would settle it first. +pub(super) fn replace_marked(s: &mut Session, from: super::Pos, to: super::Pos, text: &str, committed: bool) -> Result<()> { + let st = s.doc()?; + let original_selection = st.selection.clone(); + let had_composition = st.composition.is_some(); + if let Some(c) = &st.composition { + if from != c.start || to != (c.start.0, c.start.1.saturating_add(c.len)) { + return Err(bad("text.replaceRange", "the range does not match the composition")); + } + } else if let Some(t) = s.doc_mut()?.selection.text.as_mut() { + t.anchor = from; + t.caret = to; + t.line_end = None; } - if let Some((row, col)) = t.cell { - let Some(placed) = cell_on_slide(st, t.shape, row, col) else { return vec![] }; - return underline_segments(&placed.layout, placed.to_slide, c); + let params = json!({"text": text}); + if committed && had_composition { + commit(s, ¶ms)?; + } else { + compose(s, ¶ms)?; + if !had_composition && let Some(c) = s.doc_mut()?.composition.as_mut() { + c.before_selection = original_selection; + } + if committed { + s.end_composition(); + } } - let Some(sh) = st.shape(t.shape) else { return vec![] }; - let Some(l) = layout_for(st, t) else { return vec![] }; - let x = xfrm_of(&st.doc, &st.selection, sh); - let tr = deckcraft_render::shape_geometry(sh, x.w, x.h).text_rect; - let m = deckcraft_render::text_transform(x.affine(), tr, l.rotation); - underline_segments(&l, m, c) + Ok(()) } -fn underline_segments( - layout: &deckcraft_text::TextLayout, - to_slide: deckcraft_geom::Affine, - c: &crate::Composition, -) -> Vec<(deckcraft_geom::Point, deckcraft_geom::Point, bool)> { - let pos = |ch: usize| deckcraft_text::Pos { para: c.start.0, ch: c.start.1 + ch }; - let mut out = vec![]; - let mut add = |a: usize, b: usize, thick: bool| { - for (x0, x1, y) in layout.composition_underlines(pos(a), pos(b)) { - out.push((to_slide * deckcraft_geom::Point::new(x0, y), to_slide * deckcraft_geom::Point::new(x1, y), thick)); - } +/// Removes an already normalized character range beside the live composition. +pub(super) fn delete_range(s: &mut Session, range: std::ops::Range, text: &str) -> Result<()> { + let st = s.doc()?; + let t = st.selection.text.as_ref().ok_or_else(|| bad("text.replaceRange", "not editing text"))?; + let body = body_of(st, t).ok_or_else(|| bad("text.replaceRange", "the text being edited is gone"))?; + let c = st.composition.as_ref().ok_or_else(|| bad("text.replaceRange", "not composing"))?; + let start = super::flat_offset(body, c.start).ok_or_else(|| bad("text.replaceRange", "the composition is not in the text"))?; + let end = start.saturating_add(c.len); + let (before, after) = if text.is_empty() && range.end == start { + (range.len(), 0) + } else if text.is_empty() && range.start == end { + (0, range.len()) + } else { + return Err(bad("text.replaceRange", "the deletion must be beside the composition")); }; - add(0, c.len, false); - if let Some((a, b)) = c.active { - add(a, b.min(c.len), true); - } - out + super::caret::delete_surrounding(s, &json!({"before": before, "after": after}))?; + Ok(()) } #[cfg(test)] @@ -484,65 +406,14 @@ mod ime_surrounding_tests { assert_eq!(text(&s, id), "aéb", "four bytes contain the whole emoji"); } - /// The committed query is logical text with UTF-8 byte offsets; it keeps a reversed - /// selection, removes the model-stored pre-edit, and treats an empty body as available. - #[test] - fn surrounding_text_is_committed_logical_and_bounded() { - use super::{IME_SURROUNDING_MAX_BYTES, ime_surrounding}; - - let mut s = Session::with_new(); - let id = edit(&mut s); - let st = s.doc().unwrap(); - let t = st.selection.text.clone().unwrap(); - let q = ime_surrounding(st, &t).unwrap(); - assert_eq!((q.text.as_str(), q.cursor, q.anchor), ("aé😀b", 8, 8)); - - s.execute("text.select", &json!({"anchor": [0, 3], "caret": [0, 1]})).unwrap(); - let st = s.doc().unwrap(); - let t = st.selection.text.clone().unwrap(); - let q = ime_surrounding(st, &t).unwrap(); - assert_eq!((q.cursor, q.anchor), (1, 7), "reversed selection keeps caret before anchor"); - assert_eq!(q.text, "aé😀b"); - - s.execute("text.set", &json!({"id": id, "text": "ab"})).unwrap(); - s.execute("text.move", &json!({"to": "end"})).unwrap(); - s.compose_text("日本", None).unwrap(); - let st = s.doc().unwrap(); - let t = st.selection.text.clone().unwrap(); - let q = ime_surrounding(st, &t).unwrap(); - assert_eq!((q.text.as_str(), q.cursor, q.anchor), ("ab", 2, 2), "pre-edit is not committed text"); - - s.execute("text.set", &json!({"id": id, "text": ""})).unwrap(); - let st = s.doc().unwrap(); - let t = st.selection.text.clone().unwrap(); - let q = ime_surrounding(st, &t).unwrap(); - assert_eq!((q.text.as_str(), q.cursor, q.anchor), ("", 0, 0), "empty body is available"); - - let long = "a".repeat(IME_SURROUNDING_MAX_BYTES + 1500); - s.execute("text.set", &json!({"id": id, "text": long})).unwrap(); - s.execute("text.move", &json!({"to": "end"})).unwrap(); - let st = s.doc().unwrap(); - let t = st.selection.text.clone().unwrap(); - let q = ime_surrounding(st, &t).unwrap(); - assert!(q.text.len() <= IME_SURROUNDING_MAX_BYTES, "{}", q.text.len()); - assert_eq!(q.cursor, q.text.len(), "caret stays at the end of the bounded window"); - } - - /// Paragraph marks are part of the logical text the platform sees (`\n`), so a deletion may - /// remove one and merge the paragraphs, exactly as the published offsets say. + /// A paragraph mark occupies one logical byte; deleting it merges its paragraphs. #[test] fn paragraph_marks_are_deletable_logical_text() { - use super::ime_surrounding; - let mut s = Session::with_new(); let id = edit(&mut s); s.execute("text.set", &json!({"id": id, "text": "ab\ncd"})).unwrap(); // The caret at the start of the second paragraph: after "ab" and its paragraph mark. s.execute("text.select", &json!({"anchor": [1, 0], "caret": [1, 0]})).unwrap(); - let st = s.doc().unwrap(); - let q = ime_surrounding(st, &st.selection.text.clone().unwrap()).unwrap(); - assert_eq!((q.text.as_str(), q.cursor, q.anchor), ("ab\ncd", 3, 3)); - // One byte before the caret is that paragraph mark. s.delete_surrounding(1, 0, true).unwrap(); assert_eq!(text(&s, id), "abcd", "the mark goes and the paragraphs merge"); @@ -563,12 +434,9 @@ mod ime_surrounding_tests { assert_eq!(text(&s, id), "abcd"); } - /// A soft line break (Shift+Enter) is published as a newline, like a paragraph break: the - /// platform must never see the model's `\u{b}`, which its own text filter would reject. + /// A soft line break occupies one logical byte even inside a single paragraph. #[test] fn soft_line_breaks_read_as_newlines() { - use super::ime_surrounding; - let mut s = Session::with_new(); let id = edit(&mut s); s.execute("text.autocorrect", &json!({"on": false})).unwrap(); // isolate logical line-break coordinates @@ -577,10 +445,6 @@ mod ime_surrounding_tests { s.execute("text.select", &json!({"anchor": [0, 1], "caret": [0, 1]})).unwrap(); s.execute("text.insert", &json!({"text": "\u{b}"})).unwrap(); assert_eq!(text(&s, id), "a\u{b}b", "a line break inside one paragraph"); - let st = s.doc().unwrap(); - let q = ime_surrounding(st, &st.selection.text.clone().unwrap()).unwrap(); - assert_eq!((q.text.as_str(), q.cursor, q.anchor), ("a\nb", 2, 2)); - // The break is one logical byte, so removing it removes one character. s.delete_surrounding(1, 0, true).unwrap(); assert_eq!(text(&s, id), "ab"); diff --git a/crates/engine/src/cmd/text/layout.rs b/crates/engine/src/cmd/text/layout.rs index 866eb7363..ba8de6e81 100644 --- a/crates/engine/src/cmd/text/layout.rs +++ b/crates/engine/src/cmd/text/layout.rs @@ -1,7 +1,7 @@ use super::caret::cell_on_slide; use super::{ - Affine, Arc, AutoFit, Ctx, DocState, Paragraph, Point, Pos, Presentation, Rect, Result, Selection, Session, Shape, ShapeId, Target, TextBody, - TextSel, Value, ed, resolve, xfrm_of, + Affine, Arc, AutoFit, Ctx, DocState, Point, Pos, Presentation, Rect, Result, Selection, Session, Shape, ShapeId, Target, TextBody, TextSel, + Value, resolve, xfrm_of, }; /// Refit a shape after its text changed: remember the shrink-on-overflow scale the layout @@ -179,22 +179,6 @@ pub fn caret_line(st: &DocState, t: &TextSel) -> Option<(deckcraft_geom::Point, Some((m * deckcraft_geom::Point::new(cx, top), m * deckcraft_geom::Point::new(cx, bot))) } -/// The colour of text typed at the caret. The canvas draws the caret in it, so the caret shows -/// wherever the text does: light on a dark slide, dark on a light one. `None` when that text -/// has no fill to take a colour from. -pub fn caret_color(st: &DocState, t: &TextSel) -> Option { - if t.notes || t.cell.is_some() { - return None; - } - let sh = st.shape(t.shape)?; - let body = sh.text.as_ref()?; - let ctx = ctx_for(&st.doc, &st.selection)?; - let blank = Paragraph::default(); - let para = body.paragraphs.get(t.caret.0).unwrap_or(&blank); - let props = resolve::run(&ctx, sh, para, &ed::props_at(body, t.caret)); - Some(resolve::text_color(&ctx, &props)).filter(|c| c.a > 0) -} - pub(super) fn pos_param(p: &Value, key: &str) -> Option { let a = p.get(key)?.as_array()?; Some((a.first()?.as_u64()? as usize, a.get(1)?.as_u64()? as usize)) diff --git a/crates/engine/src/compare.rs b/crates/engine/src/compare.rs index cb89d08f5..eae683156 100644 --- a/crates/engine/src/compare.rs +++ b/crates/engine/src/compare.rs @@ -514,14 +514,24 @@ pub fn accept(doc: &mut Presentation, rev: &Presentation, change: &Change) -> cr let Some(b) = change.revised.and_then(|r| rev.slides.get(r)).cloned() else { return Ok(None) }; let sl = adopt(doc, rev, &b, None)?; let at = change.slide.min(doc.slides.len()); + let id = sl.id; doc.slides.insert(at, Arc::new(sl)); + // The new slide joins the section of the slide before it, as slide.new does. + crate::cmd::slide::reassign_sections(doc, &[id], at); Ok(Some(at)) } ChangeKind::Deleted => { if change.slide >= doc.slides.len() || doc.slides.len() <= 1 { return Ok(None); } - doc.slides.remove(change.slide); + let gone = doc.slides.remove(change.slide).id; + // As in slide.delete: the slide leaves its section and every custom show. + for sec in &mut doc.sections { + sec.slides.retain(|x| *x != gone); + } + for show in &mut doc.custom_shows { + show.slides.retain(|x| *x != gone); + } Ok(Some(change.slide.min(doc.slides.len().saturating_sub(1)))) } } @@ -811,6 +821,33 @@ mod tests { assert!(s.execute("review.accept", &json!({"all": true})).is_err()); } + #[test] + fn accepted_slides_keep_sections_and_custom_shows_in_step() { + let (mut s, rev, _) = decks(); + let ids = |s: &Session| -> Vec { s.doc().unwrap().doc.slides.iter().map(|x| x.id).collect() }; + let before = ids(&s); + assert!(!s.doc().unwrap().doc.sections.is_empty(), "the sample deck has sections"); + let show: Vec<_> = before.iter().take(3).copied().collect(); + s.edit(|doc, _| { + doc.custom_shows = vec![deckcraft_model::CustomShow { name: "Short".into(), slides: show.clone() }]; + Ok(()) + }) + .unwrap(); + s.execute("review.compare", &json!({"name": "rev.deckcraft", "data": rev})).unwrap(); + s.execute("review.accept", &json!({"all": true})).unwrap(); + + let st = s.doc().unwrap(); + let after = ids(&s); + let gone = before[1]; + assert!(!after.contains(&gone), "the revision deleted slide 2"); + let in_sections: Vec<_> = st.doc.sections.iter().flat_map(|x| x.slides.iter().copied()).collect(); + assert_eq!(in_sections, after, "every slide is in one section, in deck order, and no section keeps the deleted slide"); + let new = st.doc.slides.iter().find(|x| super::slide_title(x) == "Brand new").unwrap().id; + assert!(st.doc.section_of(new).is_some(), "the inserted slide joins a section"); + assert!(!st.doc.custom_shows[0].slides.contains(&gone), "the deleted slide leaves the custom show"); + assert_eq!(st.doc.custom_shows[0].slides.len(), show.len() - 1); + } + #[test] fn reject_keeps_the_open_deck_and_accept_all_skips_rejected_revisions() { let (mut s, rev, n) = decks(); diff --git a/crates/engine/src/connect.rs b/crates/engine/src/connect.rs index 5991ba619..65779f92f 100644 --- a/crates/engine/src/connect.rs +++ b/crates/engine/src/connect.rs @@ -100,10 +100,14 @@ pub fn endpoints(x: &Xfrm) -> (Point, Point) { /// Move the ends of connectors glued to shapes on the edited slide to the current site positions. /// Connections to shapes that no longer exist are dropped. pub fn reroute(doc: &mut Presentation, sel: &Selection) { - let Some(list) = crate::shapes_mut(doc, sel) else { return }; - if !list.iter().any(|s| matches!(s.kind, ShapeKind::Connector { start: Some(_), .. } | ShapeKind::Connector { end: Some(_), .. })) { + // Read first: taking the list mutably would unshare the edited slide even when no connector is glued. + if !crate::shapes_of(doc, sel) + .iter() + .any(|s| matches!(s.kind, ShapeKind::Connector { start: Some(_), .. } | ShapeKind::Connector { end: Some(_), .. })) + { return; } + let Some(list) = crate::shapes_mut(doc, sel) else { return }; let snapshot: Vec = list.clone(); let view = doc.clone(); let site = |id: ShapeId, idx: u32| -> Option { diff --git a/crates/engine/src/file_access.rs b/crates/engine/src/file_access.rs index 72baaea27..b493f7161 100644 --- a/crates/engine/src/file_access.rs +++ b/crates/engine/src/file_access.rs @@ -286,6 +286,66 @@ mod tests { p.to_string_lossy().into_owned() } + #[test] + fn host_backed_reads_preserve_roots_regular_files_and_size_validation() { + use std::cell::Cell; + + let (base, roots) = folders("host-read"); + let inside = s(base.join("in/host.deckcraft")); + let outside = s(base.join("outside/host.deckcraft")); + let bytes = b"bytes supplied by the host".to_vec(); + confine(Some(&roots), || { + let accepted = crate::io::read_file_with(&inside, |_| Ok((true, bytes.len() as u64)), |_| Ok(bytes.clone())).unwrap(); + assert_eq!(accepted, bytes); + + let metadata_called = Cell::new(false); + let read_called = Cell::new(false); + let denied = crate::io::read_file_with( + &outside, + |_| { + metadata_called.set(true); + Ok((true, bytes.len() as u64)) + }, + |_| { + read_called.set(true); + Ok(bytes.clone()) + }, + ); + assert!(denied.unwrap_err().contains(&outside)); + assert!(!metadata_called.get(), "authority is checked before asking the host for metadata"); + assert!(!read_called.get(), "authority is checked before asking the host for bytes"); + + for metadata in [(false, bytes.len() as u64), (true, (2_u64 << 30) + 1)] { + let read_called = Cell::new(false); + let rejected = crate::io::read_file_with( + &inside, + |_| Ok(metadata), + |_| { + read_called.set(true); + Ok(bytes.clone()) + }, + ); + assert!(rejected.unwrap_err().contains(&inside)); + assert!(!read_called.get(), "file kind and size are checked before reading"); + } + + let metadata_error = crate::io::read_file_with(&inside, |_| Err("metadata unavailable".into()), |_| Ok(bytes.clone())); + assert!(metadata_error.unwrap_err().contains(&inside)); + let read_error = crate::io::read_file_with(&inside, |_| Ok((true, bytes.len() as u64)), |_| Err("read unavailable".into())); + assert!(read_error.unwrap_err().contains(&inside)); + + let captured = current(); + let worker_path = outside.clone(); + let rejected = std::thread::spawn(move || { + confine(captured.as_ref(), || crate::io::read_file_with(&worker_path, |_| Ok((true, 0)), |_| Ok(Vec::new()))) + }) + .join() + .unwrap(); + assert!(rejected.unwrap_err().contains(&outside), "a queued read retains the submitting thread's authority"); + }); + let _ = std::fs::remove_dir_all(base); + } + #[test] fn paths_inside_the_roots_pass_and_others_dont() { let (base, roots) = folders("inside"); diff --git a/crates/engine/src/icons.rs b/crates/engine/src/icons.rs index bdd462894..ea66dbf5d 100644 --- a/crates/engine/src/icons.rs +++ b/crates/engine/src/icons.rs @@ -12,6 +12,14 @@ use deckcraft_geom::{BezPath, PathEl}; /// Design size of every icon, in path units. Lucide's viewBox is `0 0 24 24`. pub const VIEW: f64 = 24.0; +/// Shape tag that preserves gallery icon identity in native and PPTX files. +pub(crate) const INSERTED_ICON_TAG: (&str, &str) = ("DECKCRAFT_INSERTED_ICON", "1"); + +pub(crate) fn is_inserted_icon(shape: &deckcraft_model::Shape) -> bool { + let (name, value) = INSERTED_ICON_TAG; + shape.tags.iter().any(|(key, tag_value)| key == name && tag_value == value) +} + /// One icon from the Insert gallery. pub struct Icon { pub name: &'static str, @@ -210,6 +218,43 @@ mod tests { assert!((width - 8.0).abs() < 0.05, "{width}"); } + #[test] + fn missing_icon_alt_text_is_reported_after_round_trips() { + let mut s = Session::with_new(); + let insert_icon = |s: &mut Session| s.execute("insert.icon", &json!({"name": "star"})).unwrap()["id"].as_u64().unwrap(); + let missing = insert_icon(&mut s); + let described = insert_icon(&mut s); + let decorative = insert_icon(&mut s); + let freeform = s.execute("shape.freeform", &json!({"points": [[0, 0], [20, 10], [5, 25]], "closed": true})).unwrap()["id"].as_u64().unwrap(); + s.execute("shape.rename", &json!({"ids": [freeform], "name": "Star"})).unwrap(); + s.execute("shape.rename", &json!({"ids": [missing], "name": "Repainted symbol"})).unwrap(); + s.execute("shape.altText", &json!({"ids": [described], "text": "Five-point outline"})).unwrap(); + s.execute("shape.altText", &json!({"ids": [decorative], "decorative": true})).unwrap(); + + let assert_alert = |s: &mut Session| { + let issues = s.execute("review.accessibility", &json!({})).unwrap(); + let shapes: Vec<_> = issues + .as_array() + .unwrap() + .iter() + .filter(|issue| issue["issue"] == "Missing alternative text") + .map(|issue| issue["shape"].as_u64().unwrap()) + .collect(); + assert_eq!(shapes, [missing], "{issues}"); + }; + assert_alert(&mut s); + + let doc = &s.doc().unwrap().doc; + let native = deckcraft_format::load(&deckcraft_format::save(doc).unwrap()).unwrap(); + let pptx = deckcraft_pptx::import(&deckcraft_pptx::export(doc).unwrap()).unwrap(); + let second_pptx = deckcraft_pptx::import(&deckcraft_pptx::export(&pptx).unwrap()).unwrap(); + for doc in [native, pptx, second_pptx] { + let mut reopened = Session::new(); + reopened.add_document(crate::DocState::new(doc, None, "Reopened deck".into())); + assert_alert(&mut reopened); + } + } + fn ink_in(img: &deckcraft_render::Image, x: f64, y: f64, w: f64, h: f64, scale: f64) -> usize { let x0 = (x * scale).floor().max(0.0) as u32; let y0 = (y * scale).floor().max(0.0) as u32; diff --git a/crates/engine/src/io.rs b/crates/engine/src/io.rs index 9a98f62a0..7d1977666 100644 --- a/crates/engine/src/io.rs +++ b/crates/engine/src/io.rs @@ -7,16 +7,11 @@ /// The bytes of the file at `path`, inside the automation read root when there is one. #[cfg(not(target_arch = "wasm32"))] pub fn read_file(path: &str) -> Result, String> { - crate::file_access::check_read(path)?; - let meta = std::fs::metadata(path).map_err(|e| format!("{path}: {e}"))?; - if !meta.is_file() { - return Err(format!("{path}: not a regular file")); - } - const MAX_FILE_SIZE: u64 = 2 << 30; // 2 GiB - if meta.len() > MAX_FILE_SIZE { - return Err(format!("{path}: file size {} exceeds 2 GiB limit", meta.len())); - } - std::fs::read(path).map_err(|e| format!("{path}: {e}")) + read_file_with( + path, + |path| std::fs::metadata(path).map(|metadata| (metadata.is_file(), metadata.len())).map_err(|error| error.to_string()), + |path| std::fs::read(path).map_err(|error| error.to_string()), + ) } #[cfg(target_arch = "wasm32")] @@ -87,6 +82,29 @@ pub fn file_len(_path: &str) -> Option { None } +/// Checks read access and regular-file metadata before reading through the callbacks. +/// Rejects metadata or returned bytes over 2 GiB, retaining the path in errors. +pub fn read_file_with(path: &str, metadata: M, read: R) -> Result, String> +where + M: FnOnce(&str) -> Result<(bool, u64), String>, + R: FnOnce(&str) -> Result, String>, +{ + crate::file_access::check_read(path)?; + let (regular, len) = metadata(path).map_err(|error| format!("{path}: {error}"))?; + if !regular { + return Err(format!("{path}: not a regular file")); + } + check_read_size(path, len)?; + let bytes = read(path).map_err(|error| format!("{path}: {error}"))?; + check_read_size(path, bytes.len() as u64)?; + Ok(bytes) +} + +fn check_read_size(path: &str, len: u64) -> Result<(), String> { + const MAX_FILE_SIZE: u64 = 2 << 30; + if len > MAX_FILE_SIZE { Err(format!("{path}: file size {len} exceeds 2 GiB limit")) } else { Ok(()) } +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/engine/src/keys.rs b/crates/engine/src/keys.rs index c28430043..1e707b2ee 100644 --- a/crates/engine/src/keys.rs +++ b/crates/engine/src/keys.rs @@ -74,18 +74,11 @@ impl Session { let r = match k { "enter" | "return" => Some(self.execute("text.insert", &json!({"text": if mods.shift { "\u{b}" } else { "\n" }}))), "escape" | "esc" => Some(self.execute("text.exit", &json!({}))), - "tab" => { - // Tab at the start of a paragraph changes the list level; elsewhere it types a tab. - let at_start = self.active().and_then(|d| d.selection.text.as_ref()).is_some_and(|t| t.ordered().0.1 == 0 || t.is_range()); - let in_cell = self.active().and_then(|d| d.selection.text.as_ref()).is_some_and(|t| t.cell.is_some()); - if in_cell { - Some(self.next_cell(mods.shift)) - } else if at_start { - Some(self.execute(if mods.shift { "format.outdent" } else { "format.indent" }, &json!({}))) - } else { - Some(self.execute("text.insert", &json!({"text": "\t"}))) - } - } + "tab" => match self.text_tab(mods.shift) { + Ok(true) => Some(Ok(Value::Null)), + Ok(false) => Some(self.execute("text.insert", &json!({"text": "\t"}))), + Err(error) => Some(Err(error)), + }, _ => None, }; if let Some(r) = r { @@ -322,6 +315,21 @@ impl Session { }) } + /// Tab (`back`: Shift+Tab) in edited text where it is not a tab character: in a table cell it goes to the next or + /// previous cell, at the start of a paragraph or over a range it changes the list level. `false` elsewhere, where + /// Tab types a tab. + pub fn text_tab(&mut self, back: bool) -> Result { + let Some(t) = self.active().and_then(|d| d.selection.text.clone()) else { return Ok(false) }; + if t.cell.is_some() { + self.next_cell(back)?; + } else if t.ordered().0.1 == 0 || t.is_range() { + self.execute(if back { "format.outdent" } else { "format.indent" }, &json!({}))?; + } else { + return Ok(false); + } + Ok(true) + } + fn next_cell(&mut self, back: bool) -> Result { let st = self.doc()?; let Some(t) = st.selection.text.clone() else { return Ok(Value::Null) }; diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 26b88ebfa..f6ecfb330 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -237,6 +237,9 @@ pub struct DocState { /// The list AutoFormat just started from a typed `* ` or `1. `, so Backspace right after /// can put the typed text back. pub auto_list: Option, + /// The slide whose editor's consecutive notes changes share one undo step. + pub notes_run: Option, + notes_before: Option>, } static NEXT_UID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); @@ -266,6 +269,8 @@ impl DocState { compare: None, last_duplicate: None, auto_list: None, + notes_run: None, + notes_before: None, } } pub fn is_dirty(&self) -> bool { @@ -283,14 +288,7 @@ impl DocState { } /// Shapes of the edited tree (current slide, or the master/layout in Slide Master view). pub fn shapes(&self) -> &[Shape] { - match self.selection.target { - Target::Slides => self.current_slide().map(|s| s.shapes.as_slice()).unwrap_or(&[]), - Target::Master { master } => self.doc.masters.get(master).map(|m| m.shapes.as_slice()).unwrap_or(&[]), - Target::Handout | Target::NotesMaster => page_master(&self.doc, self.selection.target).map(|m| m.shapes.as_slice()).unwrap_or(&[]), - Target::Layout { master, layout } => { - self.doc.masters.get(master).and_then(|m| m.layouts.get(layout)).map(|l| l.shapes.as_slice()).unwrap_or(&[]) - } - } + shapes_of(&self.doc, &self.selection) } pub fn shape(&self, id: ShapeId) -> Option<&Shape> { deckcraft_model::find_shape(self.shapes(), id) @@ -316,6 +314,16 @@ pub fn master_page(doc: &Presentation, t: Target) -> Option { Some(p) } +/// The edited shape tree of a presentation, read without unsharing its slide or master. +pub fn shapes_of<'a>(doc: &'a Presentation, sel: &Selection) -> &'a [Shape] { + match sel.target { + Target::Slides => doc.slides.get(sel.slide).map(|s| s.shapes.as_slice()).unwrap_or(&[]), + Target::Master { master } => doc.masters.get(master).map(|m| m.shapes.as_slice()).unwrap_or(&[]), + Target::Handout | Target::NotesMaster => page_master(doc, sel.target).map(|m| m.shapes.as_slice()).unwrap_or(&[]), + Target::Layout { master, layout } => doc.masters.get(master).and_then(|m| m.layouts.get(layout)).map(|l| l.shapes.as_slice()).unwrap_or(&[]), + } +} + /// Mutable access to the edited shape tree of a presentation. pub fn shapes_mut<'a>(doc: &'a mut Presentation, sel: &Selection) -> Option<&'a mut Vec> { match sel.target { @@ -329,7 +337,7 @@ pub fn shapes_mut<'a>(doc: &'a mut Presentation, sel: &Selection) -> Option<&'a } /// Engine preferences (the UI keeps its own). -#[derive(Clone, Debug, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(default, rename_all = "camelCase")] pub struct Prefs { pub snap_to_grid: bool, @@ -482,6 +490,16 @@ pub struct Clipboard { pub pastes: u32, } +type TextEditTarget = (u64, usize, Target, ShapeId, Option<(usize, usize)>, bool); + +#[derive(Clone)] +struct TextEditSession { + target: TextEditTarget, + before: Arc, + latest: Arc, + journal_start: usize, +} + pub struct Session { docs: Vec, active: Option, @@ -517,6 +535,8 @@ pub struct Session { next_loaded: u64, /// Compositions the application settled itself (see [`Session::composition_settles`]). composition_settles: u64, + active_generation: u64, + text_edit_session: Option, } impl Default for Session { @@ -551,6 +571,8 @@ impl Session { loaded: vec![], next_loaded: 0, composition_settles: 0, + active_generation: 0, + text_edit_session: None, } } /// Hand over a presentation read on another thread ([`cmd::file::read_presentation_file`]); @@ -624,6 +646,12 @@ impl Session { fn forget_vertex_kind_unless(&mut self, was: Option) { if self.active().map(|d| d.uid) != was { self.tool.vertex_kind = None; + self.active_generation = self.active_generation.wrapping_add(1); + self.text_edit_session = None; + for st in &mut self.docs { + st.notes_run = None; + st.notes_before = None; + } } } pub fn next_untitled(&mut self) -> String { @@ -641,6 +669,32 @@ impl Session { /// failed outer command, and committing the resulting undo entry or journal record. fn execute_unguarded(&mut self, id: &str, params: &Value) -> Result { let spec = find_command(id).ok_or_else(|| EngineError::UnknownCommand(id.into()))?; + if self.depth == 0 { + let text_input = matches!( + id, + "text.edit" + | "text.exit" + | "text.insert" + | "text.delete" + | "text.compose" + | "text.commit" + | "text.deleteSurrounding" + | "text.move" + | "text.select" + | "text.selectAll" + | "text.selectWord" + | "text.selectParagraph" + ); + if !self.text_boundary_matches() || (!text_input && (spec.undoable || spec.journal)) { + self.text_edit_session = None; + } + if ((spec.undoable && id != "slide.notes") || matches!(id, "edit.undo" | "edit.redo")) + && let Some(st) = self.active_mut() + { + st.notes_run = None; + st.notes_before = None; + } + } // Any other edit (or a click, a key, undo) settles an input method's composition first. if self.depth == 0 && (spec.journal || spec.undoable) && !matches!(id, "text.compose" | "text.commit") { self.settle_composition(); @@ -689,14 +743,32 @@ impl Session { && spec.undoable && outer { - push_undo(st, HistoryEntry { label: spec.label.to_string(), doc: old, selection: sel, vertex_kind }); + let joins_notes = id == "slide.notes" + && st.notes_run.is_some() + && st.notes_before.as_ref().is_some_and(|first| st.history.undo.last().is_some_and(|e| Arc::ptr_eq(first, &e.doc))); + if joins_notes { + st.history.redo.clear(); + if let Some(first) = &st.notes_before { + st.history.costs.insert(Arc::as_ptr(first) as usize, undo_cost(first, &st.doc)); + } + } else { + let notes_before = (id == "slide.notes" && st.notes_run.is_some()).then(|| old.clone()); + push_undo(st, HistoryEntry { label: spec.label.to_string(), doc: old, selection: sel, vertex_kind }); + st.notes_before = notes_before; + } } if spec.journal && outer { self.journal.push((id.to_string(), params.clone())); if self.journal.len() > 10_000 { self.journal.drain(..1000); + if let Some(boundary) = &mut self.text_edit_session { + boundary.journal_start = boundary.journal_start.saturating_sub(1000); + } } } + if outer { + self.advance_text_boundary(); + } Ok(if outer { self.with_editing(id, r) } else { r }) } @@ -784,13 +856,21 @@ impl Session { } let owner = |sel: &Selection| sel.text.as_ref().map(|t| (sel.slide, sel.target, t.shape, t.cell, t.notes)); let before = owner(&st.selection); + let slide_before = st.selection.slide; f(&doc, &mut st.selection); clamp_selection(st); + if st.selection.slide != slide_before { + st.notes_run = None; + st.notes_before = None; + } st.revision += 1; // A composition belongs to the text body it began in: leaving that body settles it. if st.composition.is_some() && owner(&st.selection) != before { self.settle_composition(); } + if self.text_target() != self.text_edit_session.as_ref().map(|b| b.target) { + self.text_edit_session = None; + } Ok(()) } } @@ -915,3 +995,145 @@ mod soak_tests; mod tests; #[cfg(test)] mod tests_keys; + +/// The kind of atomic replacement in the current edited text body. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum TextReplaceKind { + /// Typed input, including typed AutoCorrect. + Typed, + /// Live composition input. + Composing, + /// Committed composition input. + Committed, + /// Pasted text. + Pasted, + /// Deleted surrounding text, preserving live composition. + Deleted, +} + +/// The actual flattened inserted range and authoritative selection after replacement. +#[derive(Clone, Debug, PartialEq)] +pub struct TextReplaceResult { + /// The resulting inserted or marked character range. + pub range: std::ops::Range, + /// The complete authoritative text selection. + pub selection: TextSel, +} + +impl Session { + /// Atomically replaces character offsets in the current flattened edited body. + /// Restores text, selection, composition and history on error. + pub fn replace_text_range(&mut self, range: std::ops::Range, text: &str, kind: TextReplaceKind) -> Result { + let before = self.doc()?.clone(); + let boundary = self.text_edit_session.clone(); + let journal = self.journal.clone(); + let settles = self.composition_settles; + let depth = self.depth; + let mut output = None; + let result = self.guarded("text.replaceRange", |s| { + s.begin_text_edit_session()?; + // PLAN: assumed cmd::text::replace_text_range(&mut Session, Range, &str, TextReplaceKind) -> Result (shell-w9) + output = Some(cmd::text::replace_text_range(s, range, text, kind)?); + s.advance_text_boundary(); + Ok(Value::Null) + }); + if let Err(error) = result { + if let Some(st) = self.active_mut() + && st.uid == before.uid + { + *st = before; + } + self.depth = depth; + self.text_edit_session = boundary; + self.journal = journal; + self.composition_settles = settles; + return Err(error); + } + output.ok_or_else(|| EngineError::Internal("text.replaceRange".into(), "missing replacement result".into())) + } +} + +impl Session { + /// Opens an idempotent text edit boundary for the current document and target. + /// Includes any original composition snapshot without adding an undo entry. + pub fn begin_text_edit_session(&mut self) -> Result<()> { + let target = self.text_target().ok_or_else(|| cmd::bad("text", cmd::NO_TEXT_POINT))?; + if self.text_boundary_matches() { + return Ok(()); + } + let mut before = self.doc()?.clone(); + let latest = before.doc.clone(); + if let Some(composition) = before.composition.take() { + before.doc = composition.before; + before.selection = composition.before_selection; + } + self.text_edit_session = Some(TextEditSession { target, before: Arc::new(before), latest, journal_start: self.journal.len() }); + Ok(()) + } +} + +impl Session { + /// Finishes the current text edit boundary, optionally restoring only its edits. + /// Never crosses a sealed document or target boundary. + pub fn finish_text_edit_session(&mut self, cancel: bool) -> Result<()> { + let matches = self.text_boundary_matches(); + let Some(boundary) = self.text_edit_session.take() else { return Ok(()) }; + if !matches { + return Ok(()); + } + if !cancel { + self.settle_composition(); + return Ok(()); + } + if self.active().is_some_and(|st| st.composition.is_some()) { + self.composition_settles = self.composition_settles.wrapping_add(1); + } + let st = self.doc_mut()?; + if !Arc::ptr_eq(&st.doc, &boundary.before.doc) { + st.doc = boundary.before.doc.clone(); + st.selection = boundary.before.selection.clone(); + st.history = boundary.before.history.clone(); + st.composition = boundary.before.composition.clone(); + st.auto_list = boundary.before.auto_list.clone(); + st.notes_run = None; + st.notes_before = None; + st.revision = st.revision.wrapping_add(1); + self.journal.truncate(boundary.journal_start); + } + Ok(()) + } +} + +impl Session { + /// Returns the generation of actual active-document transitions. + /// Same-active and invalid requests leave the generation unchanged. + pub fn active_generation(&self) -> u64 { + self.active_generation + } + + fn text_target(&self) -> Option { + let st = self.active()?; + let t = st.selection.text.as_ref()?; + Some((st.uid, st.selection.slide, st.selection.target, if t.notes { ShapeId::default() } else { t.shape }, t.cell, t.notes)) + } + + fn text_boundary_matches(&self) -> bool { + self.text_edit_session + .as_ref() + .is_some_and(|b| self.text_target() == Some(b.target) && self.active().is_some_and(|st| Arc::ptr_eq(&st.doc, &b.latest))) + } + + fn advance_text_boundary(&mut self) { + let target = self.text_target(); + let latest = self.active().map(|st| st.doc.clone()); + if let Some(boundary) = &mut self.text_edit_session { + if Some(boundary.target) == target { + if let Some(latest) = latest { + boundary.latest = latest; + } + } else { + self.text_edit_session = None; + } + } + } +} diff --git a/crates/engine/src/spell.rs b/crates/engine/src/spell.rs index 44879a893..548e53549 100644 --- a/crates/engine/src/spell.rs +++ b/crates/engine/src/spell.rs @@ -22,6 +22,14 @@ enum FlagMode { Num, } +/// Where a part sits in a compound. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Pos { + First, + Middle, + Last, +} + #[derive(Clone, Debug)] enum Cond { Any, @@ -108,6 +116,8 @@ pub struct Dictionary { compound_begin: Option, compound_middle: Option, compound_end: Option, + /// `COMPOUNDPERMITFLAG`: an affix carrying it may sit inside a compound, not only at its ends. + compound_permit: Option, compound_min: usize, compound_max: usize, } @@ -167,6 +177,7 @@ impl Dictionary { ["COMPOUNDBEGIN", f, ..] => d.compound_begin = one_flag(Some(f), mode), ["COMPOUNDMIDDLE", f, ..] => d.compound_middle = one_flag(Some(f), mode), ["COMPOUNDEND", f, ..] | ["COMPOUNDLAST", f, ..] => d.compound_end = one_flag(Some(f), mode), + ["COMPOUNDPERMITFLAG", f, ..] => d.compound_permit = one_flag(Some(f), mode), ["COMPOUNDMIN", n, ..] => d.compound_min = n.parse::().unwrap_or(3).max(1), ["COMPOUNDWORDMAX", n, ..] => d.compound_max = n.parse().unwrap_or(0), ["REP", n] => { @@ -250,11 +261,26 @@ impl Dictionary { self.words.get(word).is_some_and(|hs| hs.iter().any(|f| self.has(f, self.forbidden))) } + /// An affix that may only be used inside a compound (`ONLYINCOMPOUND` among its continuation + /// flags): frami's zero suffixes that turn `Vor` into a compound's first part don't make `Vor` + /// a word of its own (#2145). + fn only_in_compound_affix(&self, a: &Affix) -> bool { + self.only_in_compound.is_some_and(|o| a.cont.contains(&o)) + } + + /// An affix that needs a further affix (`NEEDAFFIX` among its continuation flags): it can't be + /// the last affix of a word or of a compound part. + fn needs_another_affix(&self, a: &Affix) -> bool { + self.need_affix.is_some_and(|n| a.cont.contains(&n)) + } + /// Strip suffixes from `w` (one, or two through continuation flags); `extra` flags must also be - /// on the root, `cross` means the suffix must allow a prefix. - fn suffixed(&self, w: &[char], extra: &[Flag], cross: bool) -> bool { + /// on the root, `cross` means the suffix must allow a prefix. `completed`: a prefix that needs + /// nothing more is already on the word, so a suffix that needs another affix has it + /// (`work/US` with `SFX S 0 s/N` makes `unworks`, not `works`). + fn suffixed(&self, w: &[char], extra: &[Flag], cross: bool, completed: bool) -> bool { for s in &self.sfx { - if cross && !s.cross { + if (cross && !s.cross) || self.only_in_compound_affix(s) || (self.needs_another_affix(s) && !completed) { continue; } let Some(stem) = strip_end(w, &s.add, &s.strip) else { continue }; @@ -269,7 +295,7 @@ impl Dictionary { } // A second suffix whose continuation allows this one (`walk/A` + `ing/B`…). for s2 in &self.sfx { - if !s.cont.is_empty() || !s2.cont.contains(&s.flag) { + if !s.cont.is_empty() || !s2.cont.contains(&s.flag) || self.only_in_compound_affix(s2) { continue; } let Some(stem2) = strip_end(&stem, &s2.add, &s2.strip) else { continue }; @@ -285,24 +311,47 @@ impl Dictionary { false } - /// A root (or, for the last part, a suffixed root) carrying `flag`, as a compound part. - fn compound_part(&self, part: &[char], flag: Flag, last: bool) -> bool { + /// A root carrying `flag`, or a root with one affix, as a compound part at `pos`. + fn compound_part(&self, part: &[char], flag: Flag, pos: Pos) -> bool { let word: String = part.iter().collect(); let ok = self.words.get(&word).is_some_and(|hs| hs.iter().any(|f| !self.has(f, self.forbidden) && f.contains(&flag))); - ok || (last && self.suffixed_compound_end(part, flag)) + ok || self.affixed_compound_part(part, flag, pos) } - /// The last part of a compound with a suffix: the root must carry the compound `flag`. - fn suffixed_compound_end(&self, w: &[char], flag: Flag) -> bool { - self.sfx.iter().any(|s| { - strip_end(w, &s.add, &s.strip).is_some_and(|stem| { - s.cond_ok(&stem, false) - && self - .words - .get(&stem.iter().collect::()) - .is_some_and(|hs| hs.iter().any(|f| !self.has(f, self.forbidden) && f.contains(&flag) && f.contains(&s.flag))) - }) - }) + /// A compound part made of a root and one affix, as Hunspell reads them: a suffix ends the last + /// part and a prefix starts the first; anywhere else the affix needs `COMPOUNDPERMITFLAG`. + /// An affix that carries `NEEDAFFIX` needs a second one and doesn't count. A suffix found + /// through the plain compound flag whose continuation flags carry `COMPOUNDEND` may only be on + /// the last part. The compound `flag` + /// may be on the root or among the affix's continuation flags. German frami gives many first + /// parts their flag that way: `Vor/hij` with `SFX j 0 0/xoc` begins `Vorschlag` (#2145). + fn affixed_compound_part(&self, w: &[char], flag: Flag, pos: Pos) -> bool { + let permit = |a: &Affix| self.compound_permit.is_some_and(|p| a.cont.contains(&p)); + // An affix that itself needs another (`NEEDAFFIX` among its continuation flags) doesn't + // finish a part on its own. + let fits = |a: &Affix, stem: &[char], suffix: bool| { + !self.needs_another_affix(a) + // Only the last part may take a suffix found through the plain compound flag whose + // continuation flags carry the compound end flag; the begin, middle and prefix + // lookups don't check it, as in Hunspell. + && (pos == Pos::Last || !suffix || Some(flag) != self.compound || !self.compound_end.is_some_and(|e| a.cont.contains(&e))) + && self.words.get(&stem.iter().collect::()).is_some_and(|hs| { + hs.iter().any(|f| !self.has(f, self.forbidden) && f.contains(&a.flag) && (f.contains(&flag) || a.cont.contains(&flag))) + }) + }; + let suffixed = self + .sfx + .iter() + // At the end of a compound, Hunspell refuses a suffix that adds letters and may only be + // used inside compounds; a zero-length one is accepted. + .filter(|s| if pos == Pos::Last { s.add.is_empty() || !self.only_in_compound_affix(s) } else { permit(s) }) + .any(|s| strip_end(w, &s.add, &s.strip).is_some_and(|stem| s.cond_ok(&stem, false) && fits(s, &stem, true))); + suffixed + || self + .pfx + .iter() + .filter(|p| pos == Pos::First || permit(p)) + .any(|p| strip_start(w, &p.add, &p.strip).is_some_and(|stem| p.cond_ok(&stem, true) && fits(p, &stem, false))) } /// `w` made of dictionary parts allowed in compounds (`COMPOUNDFLAG`, or the begin, middle and @@ -323,11 +372,12 @@ impl Dictionary { let role = if index == 0 { self.compound_begin } else { self.compound_middle }; for i in min..=w.len() - min { let (head, rest) = w.split_at(i); - let head_ok = [self.compound, role].into_iter().flatten().any(|f| self.compound_part(head, f, false)); + let pos = if index == 0 { Pos::First } else { Pos::Middle }; + let head_ok = [self.compound, role].into_iter().flatten().any(|f| self.compound_part(head, f, pos)); if !head_ok { continue; } - if [self.compound, self.compound_end].into_iter().flatten().any(|f| self.compound_part(rest, f, true)) { + if [self.compound, self.compound_end].into_iter().flatten().any(|f| self.compound_part(rest, f, Pos::Last)) { return true; } if self.compounded(rest, index + 1, failed) { @@ -346,18 +396,21 @@ impl Dictionary { return true; } let w: Vec = word.chars().collect(); - if self.suffixed(&w, &[], false) { + if self.suffixed(&w, &[], false, false) { return true; } for p in &self.pfx { + if self.only_in_compound_affix(p) { + continue; + } let Some(stem) = strip_start(&w, &p.add, &p.strip) else { continue }; if !p.cond_ok(&stem, true) { continue; } - if self.root(&stem.iter().collect::(), &[p.flag], true) { + if !self.needs_another_affix(p) && self.root(&stem.iter().collect::(), &[p.flag], true) { return true; } - if p.cross && self.suffixed(&stem, &[p.flag], true) { + if p.cross && self.suffixed(&stem, &[p.flag], true, !self.needs_another_affix(p)) { return true; } } @@ -1032,6 +1085,106 @@ SFX D Y 1\nSFX D 0 ed/S .\n"; } } + #[test] + fn affixes_give_compound_parts_their_flags() { + // #2145, the way German frami builds compounds: the first and middle parts get their flags + // from zero affixes' continuation classes, not from the root, and those roots need an affix. + let aff = "COMPOUNDBEGIN B\nCOMPOUNDMIDDLE M\nCOMPOUNDEND E\nCOMPOUNDPERMITFLAG P\nONLYINCOMPOUND O\nNEEDAFFIX N\n\ + COMPOUNDMIN 2\nSFX j Y 1\nSFX j 0 0/BOP .\nSFX m Y 1\nSFX m 0 0/MOP .\nPFX q Y 1\nPFX q 0 0/BO .\n\ + SFX s Y 1\nSFX s 0 e .\nSFX u Y 1\nSFX u 0 s .\nPFX v Y 1\nPFX v 0 un .\nSFX t Y 1\nSFX t 0 0/BNP .\n"; + let dic = "8\nvor/Nj\nschlag/OEs\nwerk/Njm\nzeug/OEs\nding/Nq\nhaus/Ev\ntag/Bs\ntor/t\n"; + let d = Dictionary::parse(aff.as_bytes(), dic.as_bytes()); + // First part through SFX j, middle part through SFX m (it carries the permit flag), last + // part from its root, with or without a suffix there. + for w in ["vorschlag", "vorschlage", "werkzeug", "werkzeuge", "vorwerkzeug", "werkhaus", "dinghaus"] { + assert!(d.check(w), "{w}"); + } + for w in [ + // A NEEDAFFIX or ONLYINCOMPOUND root alone, or a part with no compound flag at all. + "vor", + "werk", + "schlag", + "hausvor", + "schlagzeug", + // A suffix on the first part without the permit flag (s), and a prefix on a later part + // without it (v). + "vorschlageschlag", + "werkunhaus", + // tag carries B but its suffix s has no permit flag; SFX t gives B but carries NEEDAFFIX. + "tageschlag", + "torhaus", + // Not words. + "vorschlagx", + "xvorschlag", + ] { + assert!(!d.check(w), "{w}"); + } + } + + #[test] + fn affixes_that_need_another_or_only_live_in_compounds_follow_hunspell() { + // Each row as Hunspell 1.7.6 reads the same dictionary: `sun/X` and `cat/S`, `SFX S` adding + // the compound flag X and NEEDAFFIX (N) or ONLYINCOMPOUND (O). + let dict = |sfx: &str| { + let aff = format!("COMPOUNDFLAG X\nCOMPOUNDMIN 3\nNEEDAFFIX N\nONLYINCOMPOUND O\nSFX S Y 1\nSFX S {sfx} .\n"); + Dictionary::parse(aff.as_bytes(), b"2\nsun/X\ncat/S\n".as_slice()) + }; + let rows: [(&str, &[&str], &[&str]); 4] = [ + // An affix that needs another finishes neither a word nor a compound part. + ("0 s/XN", &["sun", "cat"], &["cats", "suncats", "catssun"]), + ("0 0/XN", &["sun", "cat"], &["suncat"]), + // At the end of a compound a compound-only suffix may be empty, not add letters. + ("0 s/XO", &["sun", "cat"], &["cats", "suncats"]), + ("0 0/XO", &["sun", "cat", "suncat"], &["catsun", "suncatsun"]), + ]; + for (sfx, good, bad) in rows { + let d = dict(sfx); + for w in good { + assert!(d.check(w), "{sfx}: {w}"); + } + for w in bad { + assert!(!d.check(w), "{sfx}: {w}"); + } + } + } + + #[test] + fn a_prefix_completes_a_suffix_that_needs_another_affix() { + // As Hunspell 1.7.6 reads it: `work/US`, a suffix needing another affix (N). The prefix + // completes it (`unworks`); alone it doesn't (`works`); when both need another, neither + // completes the other. + for (pfx, good, bad) in + [("0 un", &["work", "unwork", "unworks"][..], &["works"][..]), ("0 un/N", &["work"][..], &["works", "unwork", "unworks"][..])] + { + let aff = format!("NEEDAFFIX N\nPFX U Y 1\nPFX U {pfx} .\nSFX S Y 1\nSFX S 0 s/N .\n"); + let d = Dictionary::parse(aff.as_bytes(), b"1\nwork/US\n".as_slice()); + for w in good { + assert!(d.check(w), "{pfx}: {w}"); + } + for w in bad { + assert!(!d.check(w), "{pfx}: {w}"); + } + } + } + + #[test] + fn an_affix_carrying_the_compound_end_flag_only_ends_a_compound() { + let aff = "COMPOUNDFLAG X\nCOMPOUNDEND E\nCOMPOUNDPERMITFLAG P\nCOMPOUNDMIN 3\nSFX S Y 1\nSFX S 0 s/XEP .\n"; + let d = Dictionary::parse(aff.as_bytes(), b"2\nsun/X\ncat/S\n".as_slice()); + assert!(d.check("suncats")); + assert!(d.check("cats")); + assert!(!d.check("catssun")); + // Through the begin flag, the end flag on the suffix doesn't matter: Hunspell 1.7.6 + // accepts `catssun` here (and `cats`), and rejects `catsun`, `suncats` and `suncat`. + let aff = "COMPOUNDBEGIN B\nCOMPOUNDEND E\nCOMPOUNDPERMITFLAG P\nCOMPOUNDMIN 3\nSFX S Y 1\nSFX S 0 s/BEP .\n"; + let d = Dictionary::parse(aff.as_bytes(), b"2\nsun/E\ncat/S\n".as_slice()); + assert!(d.check("catssun")); + assert!(d.check("cats")); + for w in ["catsun", "suncats", "suncat"] { + assert!(!d.check(w), "{w}"); + } + } + #[test] fn overlapping_compound_roots_with_a_failing_ending_stay_cheap() { // Roots a..aaaaaaaa overlap, so many splits of "aaa…ab" reach the same (tail, part) state; unmemoized that is millions of searches. diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 52006b7a7..efe5445a5 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -668,6 +668,32 @@ fn sample_placeholders_paste_with_their_look() { assert!(checked >= 3, "the sample has text placeholders ({checked})"); } +#[test] +fn copied_shapes_paste_as_shapes_while_a_text_box_is_being_edited() { + let mut s = session(); + s.execute("shape.insert", &json!({"preset": "ellipse", "rect": [10, 10, 50, 50]})).unwrap(); + s.execute("edit.copy", &json!({})).unwrap(); + let r = s.execute("insert.textBox", &json!({"text": "Hello"})).unwrap(); + let id = r["id"].as_u64().unwrap(); + s.execute("text.edit", &json!({"id": id})).unwrap(); + let before = s.doc().unwrap().current_slide().unwrap().shapes.len(); + s.execute("edit.paste", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().current_slide().unwrap().shapes.len(), before + 1); + assert!(s.doc().unwrap().selection.text.is_none()); +} + +#[test] +fn copied_shapes_are_not_pasted_while_the_notes_are_being_edited() { + let mut s = session(); + s.execute("shape.insert", &json!({"preset": "ellipse", "rect": [10, 10, 50, 50]})).unwrap(); + s.execute("edit.copy", &json!({})).unwrap(); + s.execute("text.edit", &json!({"notes": true})).unwrap(); + let before = s.doc().unwrap().current_slide().unwrap().shapes.len(); + s.execute("edit.paste", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().current_slide().unwrap().shapes.len(), before); + assert!(s.doc().unwrap().selection.text.as_ref().is_some_and(|t| t.notes)); +} + #[test] fn pasted_shapes_get_the_next_automatic_name() { let mut s = session(); @@ -1292,6 +1318,53 @@ fn pointer_draw_move_resize() { assert_eq!(v["box"]["w"], 150.0); } +/// A cancelled press (Escape over it, a lost capture) abandons its drag: a line being drawn is not inserted and leaves +/// no preview, and a resize is put back, neither adding an undo step. +#[test] +fn a_cancelled_drag_inserts_nothing_and_puts_a_resize_back() { + let mut s = session(); + let ev = |kind, x, y| PointerEvent { kind, x, y, mods: Mods::default(), tol: 3.0, pressure: None }; + let shapes = |s: &Session| s.doc().unwrap().shapes().len(); + let (before, undo) = (shapes(&s), s.doc().unwrap().history.undo.len()); + s.set_tool(ToolKind::Shape { preset: "line".into() }); + s.pointer(ev(PointerKind::Down, 100.0, 100.0)).unwrap(); + s.pointer(ev(PointerKind::Drag, 300.0, 200.0)).unwrap(); + assert!(s.tool.preview.is_some(), "the line shows its preview while drawn"); + s.cancel_drag(); + assert!(s.tool.preview.is_none() && !s.tool.dragging(), "the cancelled line leaves no preview"); + assert_eq!(shapes(&s), before, "the cancelled line is not inserted"); + assert_eq!(s.doc().unwrap().history.undo.len(), undo, "and adds no undo step"); + + let id = s.execute("shape.insert", &json!({"preset": "rect", "rect": [100.0, 100.0, 100.0, 80.0]})).unwrap()["id"].as_u64().unwrap(); + s.set_tool(ToolKind::Select); + s.execute("edit.select", &json!({"ids": [id]})).unwrap(); + let undo = s.doc().unwrap().history.undo.len(); + s.pointer(ev(PointerKind::Down, 200.0, 180.0)).unwrap(); + s.pointer(ev(PointerKind::Drag, 250.0, 200.0)).unwrap(); + let width = |s: &mut Session| s.execute("shape.inspect", &json!({"id": id})).unwrap()["box"]["w"].as_f64().unwrap(); + let resized = width(&mut s); + s.cancel_drag(); + assert!(width(&mut s) < resized, "the cancelled resize is put back"); + assert_eq!(s.doc().unwrap().history.undo.len(), undo, "and adds no undo step"); +} + +/// A cancelled move takes its smart guides with it: none is left on the slide for the next tool's gesture. +#[test] +fn a_cancelled_move_leaves_no_smart_guide() { + let mut s = session(); + let ev = |kind, x, y| PointerEvent { kind, x, y, mods: Mods::default(), tol: 3.0, pressure: None }; + s.execute("shape.insert", &json!({"preset": "rect", "rect": [100.0, 100.0, 100.0, 80.0]})).unwrap(); + let id = s.execute("shape.insert", &json!({"preset": "rect", "rect": [400.0, 300.0, 100.0, 80.0]})).unwrap()["id"].as_u64().unwrap(); + s.set_tool(ToolKind::Select); + s.execute("edit.select", &json!({"ids": [id]})).unwrap(); + s.pointer(ev(PointerKind::Down, 450.0, 340.0)).unwrap(); + // Level with the first rectangle's top. + s.pointer(ev(PointerKind::Drag, 450.0, 142.0)).unwrap(); + assert!(!s.tool.guides.is_empty(), "the moved shape shows a smart guide"); + s.cancel_drag(); + assert!(s.tool.guides.is_empty(), "the cancelled move leaves no guide"); +} + #[test] fn click_into_placeholder_starts_editing() { let mut s = session(); @@ -2505,65 +2578,6 @@ fn ime_on_a_selected_shape_replaces_its_text() { assert_eq!(s.commit_text("x").unwrap()["handled"], false); } -/// #101: the composition is underlined in place, under the composed characters, with a thicker -/// line under the part being converted. -#[test] -fn ime_composition_underlines_follow_the_text() { - let mut s = session(); - let title = s.doc().unwrap().current_slide().unwrap().shapes[0].id.0; - s.execute("text.edit", &json!({"id": title})).unwrap(); - assert!(cmd::text::composition_underlines(s.doc().unwrap()).is_empty()); - s.compose_text("にほんご", Some((2, 4))).unwrap(); - let u = cmd::text::composition_underlines(s.doc().unwrap()); - let thin: Vec<_> = u.iter().filter(|x| !x.2).collect(); - let thick: Vec<_> = u.iter().filter(|x| x.2).collect(); - assert_eq!((thin.len(), thick.len()), (1, 1), "{u:?}"); - let sh = s.doc().unwrap().current_slide().unwrap().shapes[0].clone(); - let x = cmd::xfrm_of(&s.doc().unwrap().doc, &s.doc().unwrap().selection, &sh); - for (a, b, _) in &u { - assert!(b.x > a.x && (a.y - b.y).abs() < 1e-9, "a horizontal line: {a:?} {b:?}"); - assert!(a.x >= x.x - 1.0 && b.x <= x.x + x.w + 1.0 && a.y > x.y && a.y < x.y + x.h, "inside the title box"); - } - assert!(thick[0].0.x > thin[0].0.x && (thick[0].1.x - thin[0].1.x).abs() < 1e-6, "the converted part is the end"); - s.commit_text("日本語").unwrap(); - assert!(cmd::text::composition_underlines(s.doc().unwrap()).is_empty()); -} - -/// #101: a composition in a table cell is underlined inside that cell, the same way slide text is. -#[test] -fn ime_composition_in_a_table_cell_is_underlined() { - let mut s = session(); - let id = s.execute("insert.table", &json!({"rows": 2, "cols": 2, "rect": [80.0, 90.0, 400.0, 120.0]})).unwrap()["id"].as_u64().unwrap(); - s.execute("text.edit", &json!({"id": id, "cell": [0, 0]})).unwrap(); - assert!(cmd::text::composition_underlines(s.doc().unwrap()).is_empty()); - let ts = s.doc().unwrap().selection.text.clone().unwrap(); - assert!(cmd::text::caret_line(s.doc().unwrap(), &ts).is_some(), "the caret is in the cell"); - s.compose_text("にほんご", Some((2, 4))).unwrap(); - let u = cmd::text::composition_underlines(s.doc().unwrap()); - let thin: Vec<_> = u.iter().filter(|x| !x.2).collect(); - let thick: Vec<_> = u.iter().filter(|x| x.2).collect(); - assert_eq!((thin.len(), thick.len()), (1, 1), "{u:?}"); - let sh = s.doc().unwrap().shape(deckcraft_model::ShapeId(id as u32)).unwrap().clone(); - let x = cmd::xfrm_of(&s.doc().unwrap().doc, &s.doc().unwrap().selection, &sh); - let deckcraft_model::ShapeKind::Table(tb) = &sh.kind else { panic!("not a table") }; - let col = tb.cols[0]; - let row = cmd::table_drawn_heights(&s.doc().unwrap().doc, &s.doc().unwrap().selection, tb)[0]; - for (a, b, _) in &u { - assert!(b.x > a.x && (a.y - b.y).abs() < 1e-6, "a horizontal line: {a:?} {b:?}"); - assert!(a.x >= x.x - 1.0 && b.x <= x.x + col + 1.0, "inside the first column"); - assert!(a.y > x.y && a.y < x.y + row + 1.0, "inside the first row"); - } - assert!(thick[0].0.x > thin[0].0.x && (thick[0].1.x - thin[0].1.x).abs() < 1e-6, "the converted part is the end"); - let ts = s.doc().unwrap().selection.text.clone().unwrap(); - let (top, bot) = cmd::text::caret_line(s.doc().unwrap(), &ts).unwrap(); - assert!(top.x >= x.x && top.x <= x.x + col && top.y >= x.y && bot.y <= x.y + row + 1.0, "caret in the cell"); - s.commit_text("日本語").unwrap(); - assert!(cmd::text::composition_underlines(s.doc().unwrap()).is_empty()); - let sh = s.doc().unwrap().shape(deckcraft_model::ShapeId(id as u32)).unwrap().clone(); - let deckcraft_model::ShapeKind::Table(tb) = &sh.kind else { panic!("not a table") }; - assert_eq!(tb.cell(0, 0).map(|c| c.text.text()), Some("日本語".into())); -} - /// File › Info (#76): the active presentation's name, location, counts and properties. #[test] fn file_info_reports_the_presentation() { @@ -2765,6 +2779,64 @@ fn plain_outlines_are_unchanged() { assert_eq!(p.slides.first().map(|s| s.title()).as_deref(), Some("# Intro")); } +#[test] +fn txt_outline_decodes_utf16_boms() { + let source = "Intro — café\r\n\tPoint one\r\n\t\tSub point 🚀\r\nSecond\r\n\tMore\r\n"; + let want = vec![ + ("Intro — café".to_string(), vec![(0, "Point one".to_string()), (1, "Sub point 🚀".to_string())]), + ("Second".to_string(), vec![(0, "More".to_string())]), + ]; + + let mut utf16_le = vec![0xFF, 0xFE]; + utf16_le.extend(source.encode_utf16().flat_map(u16::to_le_bytes)); + + let mut utf16_be = vec![0xFE, 0xFF]; + utf16_be.extend(source.encode_utf16().flat_map(u16::to_be_bytes)); + + for (label, bytes) in [("utf-16le bom", utf16_le.as_slice()), ("utf-16be bom", utf16_be.as_slice())] { + let p = crate::cmd::file::open_presentation("outline.txt", bytes).unwrap(); + assert_eq!(outline_of(&p), want, "open_presentation ({label})"); + assert_eq!(crate::cmd::file::outline_text(bytes), source, "outline_text ({label})"); + } + + // Truncated trailing byte and unpaired surrogate in UTF-16LE replace rather than panic. + let truncated_le = [0xFF, 0xFE, b'O', 0x00, b'k', 0x00, 0x00, 0xD8, 0x42]; + let p = crate::cmd::file::open_presentation("truncated.txt", &truncated_le).unwrap(); + assert_eq!(p.slides.len(), 1); + assert_eq!(p.slides[0].title(), "Ok\u{FFFD}\u{FFFD}"); + assert_eq!(crate::cmd::file::outline_text(&truncated_le), "Ok\u{FFFD}\u{FFFD}"); + + // BOM-only UTF-16 files open as one blank slide. + for bom in [&[0xFF, 0xFE][..], &[0xFE, 0xFF][..]] { + let p = crate::cmd::file::open_presentation("empty.txt", bom).unwrap(); + assert_eq!(p.slides.len(), 1); + assert_eq!(p.slides[0].title(), ""); + } +} + +#[test] +fn txt_outline_strips_utf8_bom_and_keeps_plain_utf8() { + let source = "Intro — café\r\n\tPoint one\r\n\t\tSub point 🚀\r\nSecond\r\n\tMore\r\n"; + let want = vec![ + ("Intro — café".to_string(), vec![(0, "Point one".to_string()), (1, "Sub point 🚀".to_string())]), + ("Second".to_string(), vec![(0, "More".to_string())]), + ]; + + let mut utf8_bom = vec![0xEF, 0xBB, 0xBF]; + utf8_bom.extend_from_slice(source.as_bytes()); + + for (label, bytes) in [("utf-8 bom", utf8_bom.as_slice()), ("utf-8 no bom", source.as_bytes())] { + let p = crate::cmd::file::open_presentation("outline.txt", bytes).unwrap(); + assert_eq!(outline_of(&p), want, "open_presentation ({label})"); + assert!(!p.slides[0].title().starts_with('\u{feff}'), "leading BOM kept ({label})"); + assert_eq!(crate::cmd::file::outline_text(bytes), source, "outline_text ({label})"); + } + + let p = crate::cmd::file::open_presentation("empty.txt", &[0xEF, 0xBB, 0xBF]).unwrap(); + assert_eq!(p.slides.len(), 1); + assert_eq!(p.slides[0].title(), ""); +} + #[test] fn rtf_without_heading_paragraphs_opens_as_one_blank_slide() { let p = crate::cmd::file::open_presentation("empty.rtf", br"{\rtf1\ansi}").unwrap(); @@ -3213,6 +3285,11 @@ fn shape_effects_props_adjust_shadow_glow_and_reflection() { let g = fx(&s).glow.unwrap(); assert_eq!(g.radius, 12.0); assert!((g.color.alpha() - 0.5).abs() < 1e-6); + s.execute("shape.effects", &json!({"glowProps": {"radius": 18}})).unwrap(); + let grown = fx(&s).glow.unwrap(); + assert_eq!(grown.radius, 18.0); + assert_eq!(grown.color, g.color); + assert!((grown.color.alpha() - 0.5).abs() < 1e-6); s.execute("shape.effects", &json!({"glowProps": {"radius": 0}})).unwrap(); assert!(fx(&s).glow.is_none()); // Reflection: transparency, size, distance, blur; hostile values are clamped or ignored. @@ -5572,37 +5649,6 @@ fn language_all_marks_every_text_in_the_deck_with_nothing_selected() { assert!(s.execute("format.languageAll", &json!({"lang": "en US!"})).is_err()); } -#[test] -fn the_caret_takes_the_colour_of_the_text() { - let caret = |theme: &str| { - let mut s = session(); - s.execute("design.theme", &json!({"name": theme})).unwrap(); - let title = s.doc().unwrap().current_slide().unwrap().shapes[0].id.0; - s.execute("text.edit", &json!({"id": title})).unwrap(); - let st = s.doc().unwrap(); - let empty = cmd::text::caret_color(st, &st.selection.text.clone().unwrap()).unwrap(); - s.execute("text.insert", &json!({"text": "Typed"})).unwrap(); - let st = s.doc().unwrap(); - assert_eq!(cmd::text::caret_color(st, &st.selection.text.clone().unwrap()), Some(empty)); - empty - }; - // Dark text on the light theme, light text on the dark one: never black on a dark slide. - let (light, dark) = (caret("DeckCraft"), caret("Nocturne")); - assert!(light.r < 0x60 && light.g < 0x60 && light.b < 0x60, "{light:?}"); - assert!(dark.r > 0xC0 && dark.g > 0xC0 && dark.b > 0xC0, "{dark:?}"); - // Text set to red gets a red caret. - let mut s = session(); - let title = s.doc().unwrap().current_slide().unwrap().shapes[0].id.0; - s.execute("text.edit", &json!({"id": title})).unwrap(); - s.execute("text.insert", &json!({"text": "Red"})).unwrap(); - s.execute("text.selectAll", &json!({})).unwrap(); - s.execute("format.color", &json!({"color": "#FF0000"})).unwrap(); - s.execute("text.move", &json!({"to": "end"})).unwrap(); - let st = s.doc().unwrap(); - let red = cmd::text::caret_color(st, &st.selection.text.clone().unwrap()).unwrap(); - assert_eq!((red.r, red.g, red.b), (0xFF, 0, 0)); -} - /// Smooth Corners (#286): a rounded rectangle becomes a squircle outline that survives PPTX. #[test] fn smooth_corners_makes_a_squircle_outline() { @@ -6061,15 +6107,47 @@ fn table_cell_commands_reject_an_invalid_cell_and_name_the_registered_command() assert!(e.contains("table.insertColumnLeft"), "error should name the registered command: {e}"); } +/// #2260 (the follow-up #1189's review named): a resize of a row or column the table doesn't +/// have is an error, and leaves the presentation and the undo and redo history as they were. #[test] -fn table_column_width_of_a_huge_column_is_ignored() { +fn table_resize_rejects_a_row_or_column_past_the_table() { let mut s = session(); let id = table_at(&mut s, &[100.0, 100.0], json!([["a", "b"], ["c", "d"]])); - for keep_total in [true, false] { - let r = s.execute("table.columnWidth", &json!({"id": id.0, "col": u64::MAX, "width": 50.0, "keepTotal": keep_total})); - assert!(r.is_ok(), "columnWidth must ignore a huge col (keepTotal {keep_total}), got {r:?}"); - assert_eq!(table_of(&s, id).cols, vec![100.0, 100.0], "no column changes"); + // A row height undone, so there is a redo step for the rejected resizes to keep. + s.execute("table.rowHeight", &json!({"id": id.0, "row": 0, "height": 30.0})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + for (cmd, params) in [ + ("table.rowHeight", json!({"id": id.0, "row": 2, "height": 50.0})), + ("table.rowHeight", json!({"id": id.0, "row": 99, "height": 50.0})), + ("table.columnWidth", json!({"id": id.0, "col": 2, "width": 50.0})), + ("table.columnWidth", json!({"id": id.0, "col": 99, "width": 50.0})), + ("table.columnWidth", json!({"id": id.0, "col": 99, "width": 50.0, "keepTotal": true})), + ("table.columnWidth", json!({"id": id.0, "col": u64::MAX, "width": 50.0, "keepTotal": true})), + ] { + let doc = s.doc().unwrap().doc.clone(); + let (undo, redo) = (s.doc().unwrap().history.undo.len(), s.doc().unwrap().history.redo.len()); + let e = s.execute(cmd, ¶ms).expect_err(&format!("{cmd} {params} should be rejected")); + assert!(e.to_string().contains(cmd), "the error should name {cmd}: {e}"); + assert!(std::sync::Arc::ptr_eq(&s.doc().unwrap().doc, &doc), "{cmd} {params} must leave the presentation unchanged"); + assert_eq!(s.doc().unwrap().history.undo.len(), undo, "{cmd} {params} must not add an undo step"); + assert_eq!(s.doc().unwrap().history.redo.len(), redo, "{cmd} {params} must keep the redo step"); } + // The history behaves as if they never ran: redo still brings back the row height. + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(table_of(&s, id).rows.first().map(|r| r.height), Some(30.0), "the redo step is still the row height"); +} + +#[test] +fn table_resize_in_range_still_works() { + let mut s = session(); + let id = table_at(&mut s, &[100.0, 100.0], json!([["a", "b"], ["c", "d"]])); + let undo = s.doc().unwrap().history.undo.len(); + s.execute("table.rowHeight", &json!({"id": id.0, "row": 1, "height": 50.0})).unwrap(); + s.execute("table.columnWidth", &json!({"id": id.0, "col": 1, "width": 150.0})).unwrap(); + let t = table_of(&s, id); + assert_eq!(t.rows.get(1).map(|r| r.height), Some(50.0)); + assert_eq!(t.cols, vec![100.0, 150.0]); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 2, "one undo step each"); } /// Slides imported from an outline join the section of the slide they follow, like `slide.new`. @@ -7227,6 +7305,125 @@ fn invalid_slide_index_never_falls_back_to_the_selection_in_export_commands() { let _ = std::fs::remove_dir_all(&dir); } +/// G6: with no sites given, shape.connect joins the sites that face each other along the +/// dominant direction between the two shapes (a box mostly below leaves from the bottom), not +/// "the closest pair", which for a diagonal neighbour picked a side site and crossed boxes. +#[test] +fn connector_default_sites_follow_the_dominant_direction() { + let mut s = session(); + let a = s.execute("shape.insert", &json!({"preset": "rect", "rect": [0, 0, 100, 50]})).unwrap()["id"].as_u64().unwrap(); + let diag = s.execute("shape.insert", &json!({"preset": "rect", "rect": [150, 200, 100, 50]})).unwrap()["id"].as_u64().unwrap(); + let r = s.execute("shape.connect", &json!({"from": a, "to": diag})).unwrap(); + assert_eq!((r["fromSite"].as_u64(), r["toSite"].as_u64()), (Some(2), Some(0)), "mostly below: bottom → top, not right → left: {r}"); + let r = s.execute("shape.connect", &json!({"from": diag, "to": a})).unwrap(); + assert_eq!((r["fromSite"].as_u64(), r["toSite"].as_u64()), (Some(0), Some(2)), "and back: top → bottom: {r}"); + // The direction runs between the shapes' centres, not between the means of their sites: a + // triangle's sites lie mostly along its base, which pulled the direction sideways and chose + // the box's left site for a box that is mostly below. + let tri = s.execute("shape.insert", &json!({"preset": "triangle", "rect": [400, 0, 100, 100]})).unwrap()["id"].as_u64().unwrap(); + let below = s.execute("shape.insert", &json!({"preset": "rect", "rect": [520, 155, 100, 50]})).unwrap()["id"].as_u64().unwrap(); + let r = s.execute("shape.connect", &json!({"from": tri, "to": below})).unwrap(); + assert_eq!(r["toSite"].as_u64(), Some(0), "centre to centre is mostly down: the box's top, not its left: {r}"); + // An exact diagonal ties the bottom with the right side (and the top with the left): the lower + // site index wins, so bottom → top, and top → bottom back. + let p = s.execute("shape.insert", &json!({"preset": "rect", "rect": [0, 300, 100, 50]})).unwrap()["id"].as_u64().unwrap(); + let q = s.execute("shape.insert", &json!({"preset": "rect", "rect": [200, 500, 100, 50]})).unwrap()["id"].as_u64().unwrap(); + let sites = |s: &mut Session, from: u64, to: u64| { + let r = s.execute("shape.connect", &json!({"from": from, "to": to})).unwrap(); + (r["fromSite"].as_u64(), r["toSite"].as_u64()) + }; + assert_eq!(sites(&mut s, p, q), (Some(2), Some(0))); + assert_eq!(sites(&mut s, q, p), (Some(0), Some(2))); + // Shapes with one centre tie every site: site 0 on both. + let big = s.execute("shape.insert", &json!({"preset": "rect", "rect": [600, 300, 200, 100]})).unwrap()["id"].as_u64().unwrap(); + let small = s.execute("shape.insert", &json!({"preset": "rect", "rect": [650, 325, 100, 50]})).unwrap()["id"].as_u64().unwrap(); + assert_eq!(sites(&mut s, big, small), (Some(0), Some(0))); + // One site given: the other end is the other shape's site closest to it, as before the facing + // rule (which is for when neither is given). From a's right side (100, 25) the diagonal box's + // top (200, 200) is nearest; to its left side (150, 225), a's bottom (50, 50). + let r = s.execute("shape.connect", &json!({"from": a, "to": diag, "fromSite": 3})).unwrap(); + assert_eq!((r["fromSite"].as_u64(), r["toSite"].as_u64()), (Some(3), Some(0)), "fromSite only: {r}"); + let r = s.execute("shape.connect", &json!({"from": a, "to": diag, "toSite": 1})).unwrap(); + assert_eq!((r["fromSite"].as_u64(), r["toSite"].as_u64()), (Some(2), Some(1)), "toSite only: {r}"); + let r = s.execute("shape.connect", &json!({"from": a, "to": diag, "fromSite": 2, "toSite": 3})).unwrap(); + assert_eq!((r["fromSite"].as_u64(), r["toSite"].as_u64()), (Some(2), Some(3)), "both given: {r}"); +} + +#[test] +fn style_commands_given_nothing_to_set_are_refused() { + let mut s = session(); + s.execute("insert.textBox", &json!({"text": "Hi", "rect": [50.0, 50.0, 200.0, 100.0]})).unwrap(); + for cmd in ["shape.line", "shape.effects", "picture.adjust", "format.paragraph", "format.margins"] { + let rev = s.doc().unwrap().revision; + let e = s.execute(cmd, &json!({})).unwrap_err().to_string(); + assert!(e.contains("given nothing to set") && e.contains(cmd), "{cmd}: {e}"); + assert_eq!(s.doc().unwrap().revision, rev, "{cmd} changed the deck"); + } + let e = s.execute("shape.line", &json!({})).unwrap_err().to_string(); + assert!(e.contains("pass color, none, width, dash"), "{e}"); + // A key, even one that changes nothing visible, is something to set. + s.execute("shape.line", &json!({"width": 2})).unwrap(); + s.execute("format.margins", &json!({"left": 5})).unwrap(); + // A null glow or soft edge clears it (No Glow, No Soft Edges): that is something to set. + let fx = |s: &Session| s.doc().unwrap().selected_shapes()[0].effects.clone().unwrap_or_default(); + s.execute("shape.effects", &json!({"glow": 8, "softEdges": 5})).unwrap(); + assert!(fx(&s).glow.is_some() && fx(&s).soft_edge.is_some()); + s.execute("shape.effects", &json!({"glow": null})).unwrap(); + assert!(fx(&s).glow.is_none() && fx(&s).soft_edge.is_some()); + s.execute("shape.effects", &json!({"softEdges": null})).unwrap(); + assert!(fx(&s).soft_edge.is_none()); + // The Paragraph dialog's own fields are format.paragraphDialog's, and the refusal says so. + for (k, v) in [("special", json!("hanging")), ("spaceBeforeKind", json!("pct")), ("indentRight", json!(10))] { + let e = s.execute("format.paragraph", &json!({ k: v })).unwrap_err().to_string(); + assert!(e.contains("format.paragraphDialog") && e.contains(k), "{k}: {e}"); + } + let e = s.execute("format.paragraph", &json!({"spaceBeforeKind": "pct"})).unwrap_err().to_string(); + assert!(e.contains("together with `spaceBefore`"), "{e}"); + // The palette lists only commands that run without arguments; these need one key. + for cmd in ["shape.line", "shape.effects", "picture.adjust", "format.paragraph", "format.margins"] { + let spec = crate::command_specs().iter().find(|c| c.id == cmd).unwrap(); + assert!(crate::cmd::needs_arguments(spec.params), "{cmd}: {}", spec.params); + } + s.execute("format.paragraphDialog", &json!({"special": "hanging", "specialBy": 18})).unwrap(); +} + +/// A call whose keys are all null sets nothing and is refused like an empty one, changing +/// nothing; one valid key is enough, nulls beside it ignored. +#[test] +fn style_commands_refuse_only_nulls_and_take_one_key() { + let mut png = vec![]; + image::DynamicImage::ImageRgba8(image::RgbaImage::from_pixel(4, 2, image::Rgba([200, 30, 30, 255]))) + .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png) + .unwrap(); + let mut s = session(); + let pic = + s.execute("insert.picture", &json!({"data": cmd::base64_encode(&png), "name": "a.png", "rect": [100, 100, 40, 20]})).unwrap()["id"].clone(); + let text = s.execute("insert.textBox", &json!({"text": "Hi", "rect": [50, 300, 200, 100]})).unwrap()["id"].clone(); + let nulls = |keys: &[&str]| serde_json::Value::Object(keys.iter().map(|k| ((*k).to_string(), serde_json::Value::Null)).collect()); + for (cmd, id, keys, one) in [ + ( + "picture.adjust", + &pic, + &["brightness", "contrast", "saturation", "grayscale", "transparency", "reset"][..], + json!({"brightness": 0.3, "contrast": null}), + ), + ( + "format.paragraph", + &text, + &["align", "indentLeft", "indentFirst", "spaceBefore", "spaceAfter", "lineSpacing", "lineSpacingPt"][..], + json!({"align": "center", "spaceBefore": null}), + ), + ] { + s.execute("edit.select", &json!({"ids": [id]})).unwrap(); + let rev = s.doc().unwrap().revision; + let e = s.execute(cmd, &nulls(keys)).unwrap_err().to_string(); + assert!(e.contains("given nothing to set") && e.contains(cmd), "{cmd}: {e}"); + assert_eq!(s.doc().unwrap().revision, rev, "{cmd}: only nulls changed the deck"); + s.execute(cmd, &one).unwrap_or_else(|e| panic!("{cmd} {one}: {e}")); + assert_ne!(s.doc().unwrap().revision, rev, "{cmd}: one key set something"); + } +} + #[test] fn highlight_with_an_invalid_colour_is_rejected_and_keeps_the_highlight() { let mut s = session(); @@ -7322,6 +7519,160 @@ fn master_body_placeholder_format_keeps_per_level_formatting() { assert_eq!(shown(&s), vec![Some(28.0), Some(24.0)]); } +/// A `keepWidth` that is not a bool is refused, naming it, and the table is left alone, not read +/// as the default (the table growing by the new column). +#[test] +fn table_insert_column_refuses_a_keep_width_that_is_not_a_bool() { + let mut s = session(); + let id = table_at(&mut s, &[280.0, 280.0, 280.0], json!([["a", "b", "c"]])); + for (cmd, bad) in [("table.insertColumnRight", json!("false")), ("table.insertColumnLeft", json!(0))] { + let err = s.execute(cmd, &json!({"id": id.0, "col": 1, "keepWidth": bad})).unwrap_err().to_string(); + assert!(err.contains("keepWidth") && err.contains(cmd), "{err}"); + let t = table_of(&s, id); + assert_eq!(t.n_cols(), 3, "{cmd} changed the table: {:?}", t.cols); + assert!((t.width() - 840.0).abs() < 1e-6, "width {}", t.width()); + } +} + +#[test] +fn table_insert_column_with_keep_width_keeps_the_table_width_and_copies_the_neighbour_format() { + let mut s = session(); + let id = table_at(&mut s, &[280.0, 280.0, 280.0], json!([["a", "b", "c"], ["d", "e", "f"]])); + s.execute("table.cellFill", &json!({"id": id.0, "color": "#FF0000", "cells": [[0, 2], [1, 2]]})).unwrap(); + s.execute("table.cellMargins", &json!({"id": id.0, "left": 20, "right": 20, "top": 5, "bottom": 5, "cells": [[0, 2]]})).unwrap(); + s.execute("table.cellAlign", &json!({"id": id.0, "anchor": "bottom", "cells": [[0, 2]]})).unwrap(); + s.execute("edit.select", &json!({"ids": [id.0]})).unwrap(); + s.execute("table.selectCells", &json!({"from": [0, 2], "to": [1, 2]})).unwrap(); + s.execute("format.bold", &json!({"on": true})).unwrap(); + // Right of the last column: four columns in the same 840 pt, the new one as wide as its + // neighbour, the others shrunk to make room. + s.execute("table.insertColumnRight", &json!({"id": id.0, "col": 2, "keepWidth": true})).unwrap(); + let t = table_of(&s, id); + assert_eq!(t.n_cols(), 4); + assert!((t.width() - 840.0).abs() < 1e-6, "width {}", t.width()); + assert!(t.cols.iter().all(|w| (w - 210.0).abs() < 1e-6), "{:?}", t.cols); + let x = s.doc().unwrap().shape(id).unwrap().xfrm.unwrap(); + assert!((x.w - 840.0).abs() < 1e-6, "frame {}", x.w); + // The new cells take the neighbour's explicit formatting. + let new = t.cell(0, 3).unwrap(); + assert_eq!(new.fill, Some(deckcraft_model::Fill::solid(deckcraft_model::ColorRef::rgb(deckcraft_color::Rgba::rgb(255, 0, 0))))); + assert_eq!(new.margins, Some([20.0, 20.0, 5.0, 5.0])); + assert_eq!(new.anchor, Some(deckcraft_model::text::Anchor::Bottom)); + assert_eq!(new.text.text(), "", "the new cell is empty"); + let bold = new.text.paragraphs.first().map(|p| p.end_props.bold.or(p.def_props.bold)); + assert_eq!(bold, Some(Some(true)), "the neighbour's bold carries over: {:?}", new.text); + assert_eq!(t.cell(1, 3).unwrap().fill, t.cell(1, 2).unwrap().fill); + // Left of the first column: the neighbour is the old first column. + s.execute("table.insertColumnLeft", &json!({"id": id.0, "col": 0, "keepWidth": true})).unwrap(); + let t = table_of(&s, id); + assert_eq!(t.n_cols(), 5); + assert!((t.width() - 840.0).abs() < 1e-6, "width {}", t.width()); + assert_eq!(t.cell(0, 1).unwrap().text.text(), "a"); + assert_eq!(t.cell(0, 0).unwrap().fill, None); + // keepWidth: false grows the table by the neighbour's width, as before. + s.execute("table.insertColumnRight", &json!({"id": id.0, "col": 4, "keepWidth": false})).unwrap(); + let t = table_of(&s, id); + assert_eq!(t.n_cols(), 6); + assert!((t.width() - 840.0 - 168.0).abs() < 1e-6, "width {}", t.width()); + // The insertion is journaled as called, and each one is a single undo step back to the table + // as it was: the columns, their widths and the frame. + let (jid, jp) = s.journal.last().cloned().unwrap(); + assert_eq!(jid, "table.insertColumnRight"); + assert_eq!(jp["keepWidth"], json!(false), "{jp}"); + s.execute("edit.undo", &json!({})).unwrap(); + let t = table_of(&s, id); + assert_eq!(t.n_cols(), 5); + assert!((t.width() - 840.0).abs() < 1e-6, "width {}", t.width()); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + let t = table_of(&s, id); + assert_eq!(t.n_cols(), 3); + assert!(t.cols.iter().all(|w| (w - 280.0).abs() < 1e-6), "{:?}", t.cols); + assert_eq!(t.cell(0, 2).unwrap().text.text(), "c"); + let x = s.doc().unwrap().shape(id).unwrap().xfrm.unwrap(); + assert!((x.w - 840.0).abs() < 1e-6, "frame {}", x.w); +} + +#[test] +fn table_insert_column_beside_a_merge_copies_the_anchor_format() { + let mut s = session(); + let id = table_at(&mut s, &[280.0, 280.0, 280.0], json!([["a", "b", "c"], ["d", "e", "f"]])); + s.execute("table.cellFill", &json!({"id": id.0, "color": "#FF0000", "cells": [[0, 0]]})).unwrap(); + s.execute("table.merge", &json!({"id": id.0, "from": [0, 0], "to": [0, 1]})).unwrap(); + // Right of the merge: the neighbour column holds the covered cell, but the anchor shows. + s.execute("table.insertColumnRight", &json!({"id": id.0, "col": 1})).unwrap(); + let t = table_of(&s, id); + assert!(t.cell(0, 1).unwrap().h_merge, "the merge stays put"); + assert_eq!(t.cell(0, 2).unwrap().fill, t.cell(0, 0).unwrap().fill); + assert!(t.cell(0, 2).unwrap().fill.is_some()); +} + +#[test] +fn table_insert_column_beside_a_two_row_merge_copies_the_anchor_format() { + let mut s = session(); + let id = table_at(&mut s, &[280.0, 280.0, 280.0], json!([["a", "b", "c"], ["d", "e", "f"]])); + s.execute("table.cellFill", &json!({"id": id.0, "color": "#FF0000", "cells": [[0, 0]]})).unwrap(); + s.execute("table.merge", &json!({"id": id.0, "from": [0, 0], "to": [1, 1]})).unwrap(); + s.execute("table.insertColumnRight", &json!({"id": id.0, "col": 1})).unwrap(); + let t = table_of(&s, id); + assert!(t.cell(1, 1).unwrap().h_merge && t.cell(1, 1).unwrap().v_merge, "the merge stays put"); + assert!(t.cell(0, 2).unwrap().fill.is_some()); + assert_eq!(t.cell(1, 2).unwrap().fill, t.cell(0, 0).unwrap().fill); +} + +/// A table near the slide's right edge, with no room for another column: by default an inserted +/// column widens it past the edge, as PowerPoint's Insert Right does (the frame keeps its left and +/// grows), and `keepWidth: true` keeps it on the slide. +#[test] +fn table_insert_column_near_the_slide_edge_grows_past_it_unless_it_keeps_its_width() { + let mut s = session(); + let id = table_at(&mut s, &[280.0, 280.0, 280.0], json!([["a", "b", "c"]])); + let slide_w = s.doc().unwrap().doc.slide_size.width; + let frame = |s: &Session| s.doc().unwrap().shape(id).unwrap().xfrm.unwrap(); + let before = frame(&s); + assert!(before.x + before.w <= slide_w && before.x + before.w + 280.0 > slide_w, "another column won't fit: {before:?}"); + s.execute("table.insertColumnRight", &json!({"id": id.0, "col": 2})).unwrap(); + assert_eq!(table_of(&s, id).n_cols(), 4); + let grown = frame(&s); + assert!((grown.x - before.x).abs() < 1e-6 && (grown.w - 1120.0).abs() < 1e-6, "{grown:?}"); + assert!(grown.x + grown.w > slide_w, "past the edge"); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("table.insertColumnRight", &json!({"id": id.0, "col": 2, "keepWidth": true})).unwrap(); + let kept = frame(&s); + assert_eq!(table_of(&s, id).n_cols(), 4); + assert!((kept.x - before.x).abs() < 1e-6 && (kept.w - before.w).abs() < 1e-6, "{kept:?}"); + assert!(kept.x + kept.w <= slide_w, "still on the slide"); +} + +/// PowerPoint inserts a column as wide as its neighbour and widens the table by that amount; the +/// other widths stay. Deleting a column narrows the table by its width, the others untouched. +#[test] +fn table_insert_and_delete_column_leave_other_widths_alone() { + let mut s = session(); + let id = table_at(&mut s, &[160.0, 234.0, 235.0, 235.0], json!([["a", "b", "c", "d"]])); + for (cmd, col, at, wide) in [("table.insertColumnRight", 0, 1, 160.0), ("table.insertColumnLeft", 3, 3, 235.0)] { + let before = table_of(&s, id).cols.clone(); + let w0 = table_of(&s, id).width(); + s.execute(cmd, &json!({"id": id.0, "col": col})).unwrap(); + let t = table_of(&s, id); + let mut want = before.clone(); + want.insert(at, wide); + assert_eq!(t.cols, want, "{cmd}"); + assert!((t.width() - w0 - wide).abs() < 1e-6, "{cmd} width {}", t.width()); + let x = s.doc().unwrap().shape(id).unwrap().xfrm.unwrap(); + assert!((x.w - t.width()).abs() < 1e-6, "{cmd} frame {}", x.w); + } + let before = table_of(&s, id).cols.clone(); + s.execute("table.deleteColumn", &json!({"id": id.0, "col": 1})).unwrap(); + let t = table_of(&s, id); + let mut want = before.clone(); + let gone = want.remove(1); + assert_eq!(t.cols, want); + assert!((t.width() - (before.iter().sum::() - gone)).abs() < 1e-6); + let x = s.doc().unwrap().shape(id).unwrap().xfrm.unwrap(); + assert!((x.w - t.width()).abs() < 1e-6, "frame {}", x.w); +} + #[test] fn table_edits_past_the_cell_cap_are_refused_not_trimmed() { use deckcraft_model::table::{MAX_CELLS, Row}; @@ -7452,6 +7803,153 @@ fn save_to_image_path_is_an_error_not_zip_bytes() { let _ = std::fs::remove_dir_all(&dir); } +#[test] +fn unsupported_save_paths_are_refused_and_write_nothing() { + let dir = std::env::temp_dir().join(format!("deckcraft-save-ext-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + for name in ["a.pptm", "a.ppt", "a.pot", "a.potm", "a.pps", "a.ppsm", "a.odp", "a.xml", "a.svg", "a.bmp", "a"] { + let mut s = Session::new(); + sample::open_sample(&mut s).unwrap(); + let path = dir.join(name).to_string_lossy().to_string(); + let before = s.doc().unwrap().path.clone(); + let err = s.execute("file.saveAs", &json!({"path": path})).unwrap_err(); + assert!(err.to_string().contains("cannot save"), "{name}: {err}"); + assert!(!std::path::Path::new(&path).exists(), "{name} must not be written"); + assert_eq!(s.doc().unwrap().path, before, "{name}: the document keeps its path"); + } + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn unsupported_paths_are_refused_even_with_an_explicit_format() { + let dir = std::env::temp_dir().join(format!("deckcraft-save-ext-fmt-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let mut s = Session::new(); + sample::open_sample(&mut s).unwrap(); + let path = dir.join("a.pptm").to_string_lossy().to_string(); + let err = s.execute("file.saveAs", &json!({"path": path, "format": "pptx"})).unwrap_err(); + assert!(err.to_string().contains("cannot save"), "{err}"); + assert!(!std::path::Path::new(&path).exists(), "the path guard wins over the explicit format"); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn unsupported_extensionless_save_is_refused_even_with_an_explicit_format() { + let dir = std::env::temp_dir().join(format!("deckcraft-save-extless-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let mut s = Session::new(); + sample::open_sample(&mut s).unwrap(); + let path = dir.join("no-extension").to_string_lossy().to_string(); + let err = s.execute("file.saveAs", &json!({"path": path, "format": "pptx"})).unwrap_err(); + assert!(err.to_string().contains("cannot save"), "{err}"); + assert!(!std::path::Path::new(&path).exists(), "the path guard wins over the explicit format"); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn save_bytes_rejects_an_unknown_format() { + let mut s = Session::new(); + sample::open_sample(&mut s).unwrap(); + let err = s.execute("file.saveBytes", &json!({"format": "odp"})).unwrap_err(); + assert!(err.to_string().contains("unknown save format"), "{err}"); + assert!(s.execute("file.saveBytes", &json!({"format": "deckcraft"})).is_ok()); +} + +#[test] +fn unsupported_export_paths_are_refused() { + let dir = std::env::temp_dir().join(format!("deckcraft-export-ext-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let mut s = Session::new(); + sample::open_sample(&mut s).unwrap(); + let path = dir.join("a.pptm").to_string_lossy().to_string(); + assert!(s.execute("file.export", &json!({"path": path})).is_err()); + assert!(!std::path::Path::new(&path).exists()); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn extensionless_export_with_an_explicit_format_still_writes() { + let dir = std::env::temp_dir().join(format!("deckcraft-export-fmt-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let mut s = Session::new(); + sample::open_sample(&mut s).unwrap(); + let path = dir.join("out").to_string_lossy().to_string(); + s.execute("file.export", &json!({"path": path, "format": "png", "slide": 0})).unwrap(); + assert!(std::path::Path::new(&path).exists()); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn supported_paths_still_save() { + let dir = std::env::temp_dir().join(format!("deckcraft-save-ok-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + for (name, magic) in [("a.pptx", b"PK".as_slice()), ("a.deckcraft", b"PK".as_slice()), ("a.txt", b"")] { + let mut s = Session::new(); + sample::open_sample(&mut s).unwrap(); + let path = dir.join(name).to_string_lossy().to_string(); + s.execute("file.saveAs", &json!({"path": path})).unwrap(); + let bytes = std::fs::read(&path).unwrap(); + assert!(!bytes.is_empty(), "{name}"); + if !magic.is_empty() { + assert!(bytes.starts_with(magic), "{name}: not a ZIP"); + } + } + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn explicit_save_format_must_match_the_path() { + let dir = std::env::temp_dir().join(format!("deckcraft-save-mismatch-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let mut s = Session::new(); + sample::open_sample(&mut s).unwrap(); + let path = dir.join("a.pptx").to_string_lossy().to_string(); + std::fs::write(&path, b"sentinel").unwrap(); + let before = s.doc().unwrap().path.clone(); + let err = s.execute("file.saveAs", &json!({"path": path, "format": "deckcraft"})).unwrap_err(); + assert!(err.to_string().contains("does not match"), "{err}"); + assert_eq!(std::fs::read(&path).unwrap(), b"sentinel", "the existing file is untouched"); + assert_eq!(s.doc().unwrap().path, before, "the document keeps its path"); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn existing_unsupported_destination_is_untouched() { + let dir = std::env::temp_dir().join(format!("deckcraft-save-existing-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let mut s = Session::new(); + sample::open_sample(&mut s).unwrap(); + let path = dir.join("a.pptm").to_string_lossy().to_string(); + std::fs::write(&path, b"sentinel").unwrap(); + let before = s.doc().unwrap().path.clone(); + let err = s.execute("file.saveAs", &json!({"path": path})).unwrap_err(); + assert!(err.to_string().contains("cannot save"), "{err}"); + assert_eq!(std::fs::read(&path).unwrap(), b"sentinel", "the existing file is untouched"); + assert_eq!(s.doc().unwrap().path, before, "the document keeps its path"); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn explicit_txt_format_is_allowed_for_a_txt_path() { + let dir = std::env::temp_dir().join(format!("deckcraft-save-txt-alias-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let mut s = Session::new(); + sample::open_sample(&mut s).unwrap(); + let path = dir.join("outline.txt").to_string_lossy().to_string(); + s.execute("file.saveAs", &json!({"path": path, "format": "txt"})).unwrap(); + assert!(!std::fs::read(&path).unwrap().is_empty()); + let _ = std::fs::remove_dir_all(&dir); +} + /// `shape.connect` glues to a shape inside a group, as PowerPoint does: the connector's /// end is set to the grouped shape and follows it when the group moves. The glue was dropped at /// once (the end stayed `None`) because rerouting only looked at the slide's top-level shapes, @@ -7624,3 +8122,101 @@ fn shape_adjust_and_quick_style_reject_invalid_index() { assert_eq!(s.doc().unwrap().shape(id).unwrap().style, before.style); s.execute("shape.adjust", &json!({"value": 0.4})).unwrap(); } + +#[test] +fn active_document_transitions_invalidate_captures_without_edits() { + let mut s = Session::new(); + let empty = s.active_generation(); + s.execute("file.new", &json!({})).unwrap(); + let a = s.active_index().unwrap(); + let a_uid = s.doc().unwrap().uid; + let a_revision = s.doc().unwrap().revision; + let first = s.active_generation(); + assert_ne!(first, empty); + s.execute("file.new", &json!({})).unwrap(); + let b = s.active_index().unwrap(); + let b_uid = s.doc().unwrap().uid; + let second = s.active_generation(); + assert_ne!(second, first); + for index in [a, b, a] { + let before = s.active_generation(); + s.set_active(index); + assert_ne!(s.active_generation(), before); + } + assert_eq!(s.doc().unwrap().uid, a_uid); + assert_eq!(s.doc().unwrap().revision, a_revision); + let same = s.active_generation(); + s.set_active(a); + s.set_active(usize::MAX); + s.close_document(usize::MAX); + assert_eq!(s.active_generation(), same); + s.close_document(a); + assert_ne!(s.active_generation(), same); + assert_eq!(s.doc().unwrap().uid, b_uid); + let remaining = s.active_generation(); + s.close_document(s.active_index().unwrap()); + assert!(s.active().is_none()); + assert_ne!(s.active_generation(), remaining); + let closed = s.active_generation(); + s.execute("file.new", &json!({})).unwrap(); + assert_ne!(s.active_generation(), closed); + assert_ne!(s.doc().unwrap().uid, a_uid); + assert_ne!(s.doc().unwrap().uid, b_uid); +} + +#[test] +fn partial_alt_text_updates_preserve_mixed_descriptions_and_decorative_values() { + let (mut s, a, b) = two_shapes(); + for (id, text, decorative) in [(a, "A diagram", false), (b, "A caption", true)] { + s.execute("shape.altText", &json!({"ids": [id.0], "text": text, "decorative": decorative})).unwrap(); + } + let descriptions = |s: &Session| [a, b].map(|id| s.doc().unwrap().shape(id).unwrap().descr.clone()); + let flags = |s: &Session| [a, b].map(|id| s.doc().unwrap().shape(id).unwrap().decorative); + let original = descriptions(&s); + assert_ne!(original[0], original[1]); + s.execute("shape.altText", &json!({"ids": [a.0, b.0], "decorative": true})).unwrap(); + assert_eq!(descriptions(&s), original); + assert!(flags(&s).into_iter().all(|decorative| decorative)); + s.execute("shape.altText", &json!({"ids": [a.0], "decorative": false})).unwrap(); + assert_eq!(descriptions(&s), original); + let mixed = flags(&s); + assert_ne!(mixed[0], mixed[1]); + s.execute("shape.altText", &json!({"ids": [a.0, b.0], "text": ""})).unwrap(); + assert!(descriptions(&s).iter().all(String::is_empty)); + assert_eq!(flags(&s), mixed); +} + +#[test] +fn editor_replacements_report_autocorrection_and_cancel_only_the_open_session() { + let mut s = session(); + let title = s.doc().unwrap().current_slide().unwrap().shapes[0].id.0; + let original = "(c)"; + s.execute("text.set", &json!({"id": title, "text": original})).unwrap(); + s.execute("text.edit", &json!({"id": title})).unwrap(); + let undo = s.doc().unwrap().history.undo.len(); + let at = original.chars().count(); + let corrected = cmd::text::correct_word(&s.prefs, original, true, true).unwrap(); + let expected = format!("{corrected} "); + let written = s.replace_text_range(at..at, " ", crate::TextReplaceKind::Typed).unwrap(); + assert_eq!(title_text(&s), expected); + assert_eq!(written.range, 0..expected.chars().count()); + assert_eq!(written.selection.caret, (0, expected.chars().count())); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1); + let before = s.doc().unwrap().clone(); + assert!(s.replace_text_range(0..usize::MAX, "x", crate::TextReplaceKind::Typed).is_err()); + let after = s.doc().unwrap(); + assert!(std::sync::Arc::ptr_eq(&before.doc, &after.doc)); + assert_eq!(after.selection, before.selection); + assert_eq!(after.history.undo.len(), before.history.undo.len()); + s.finish_text_edit_session(true).unwrap(); + assert_eq!(title_text(&s), original); + assert_eq!(s.doc().unwrap().history.undo.len(), undo); + let restored = s.doc().unwrap().doc.clone(); + s.finish_text_edit_session(true).unwrap(); + assert!(std::sync::Arc::ptr_eq(&restored, &s.doc().unwrap().doc)); + s.execute("text.exit", &json!({})).unwrap(); + s.execute("text.edit", &json!({"id": title})).unwrap(); + s.finish_text_edit_session(true).unwrap(); + assert!(std::sync::Arc::ptr_eq(&restored, &s.doc().unwrap().doc)); + assert_eq!(s.doc().unwrap().history.undo.len(), undo); +} diff --git a/crates/engine/src/tools.rs b/crates/engine/src/tools.rs index 2b7f78da9..fb889fd36 100644 --- a/crates/engine/src/tools.rs +++ b/crates/engine/src/tools.rs @@ -196,10 +196,6 @@ enum Drag { start: Point, add: bool, }, - /// Dragging drawing guide `index`. - Guide { - index: usize, - }, Create { start: Point, }, @@ -289,12 +285,8 @@ pub struct ToolState { pub edit_segment_t: Option, /// The point type last chosen for a vertex (shape, path, index, type): handle drags follow it. pub vertex_kind: Option<(ShapeId, usize, usize, String)>, - /// Drawing guides are shown (View › Guides): they can be dragged and shapes snap to them. + /// Drawing guides are shown (View › Guides): shapes snap to them. pub guides_visible: bool, - /// The guide being dragged and where it is now (slide points); `None` once dropped. - pub guide_drag: Option<(usize, f64)>, - /// The drawing guide under the pointer, for the cursor. - pub guide_hover: Option, /// Pressure from the pointer event being handled, if the device reported one. pressure: Option, } diff --git a/crates/engine/src/tools/drag.rs b/crates/engine/src/tools/drag.rs index 7e8b93a74..9ccc7466a 100644 --- a/crates/engine/src/tools/drag.rs +++ b/crates/engine/src/tools/drag.rs @@ -24,13 +24,6 @@ impl Session { } let Some(drag) = self.tool.drag.clone() else { return Ok(Value::Null) }; match drag { - Drag::Guide { index } => { - let vertical = self.active().and_then(|d| d.doc.guides.get(index)).is_some_and(|g| g.vertical); - let pos = if vertical { p.x } else { p.y }; - // Guides move in whole points unless snapping is off, as in PowerPoint. - let pos = if self.prefs.snap_to_grid && !mods.alt { pos.round() } else { pos }; - self.tool.guide_drag = Some((index, pos)); - } Drag::Move { ids, start, origs, moved, duplicate, enter_text } => { return self.drag_move(MoveDrag { ids, start, origs, moved, duplicate, enter_text }, p, mods, tol); } diff --git a/crates/engine/src/tools/geometry.rs b/crates/engine/src/tools/geometry.rs index 0da6aa60c..d2fb6d50f 100644 --- a/crates/engine/src/tools/geometry.rs +++ b/crates/engine/src/tools/geometry.rs @@ -115,22 +115,6 @@ impl Session { }) } - /// The drawing guide within `tol` of `p` (only while guides are shown). - pub fn guide_at(&self, p: Point, tol: f64) -> Option { - if !self.tool.guides_visible { - return None; - } - let st = self.active()?; - st.doc - .guides - .iter() - .enumerate() - .map(|(i, g)| (i, if g.vertical { (p.x - g.pos).abs() } else { (p.y - g.pos).abs() })) - .filter(|(_, d)| *d <= tol.max(2.0)) - .min_by(|a, b| a.1.total_cmp(&b.1)) - .map(|(i, _)| i) - } - /// Smart guides: snap `r` edges/centres to the slide and other shapes. Returns the offset to /// apply and the guides to draw. pub(super) fn snap_rect(&self, r: Rect, exclude: &[ShapeId], tol: f64, enabled: bool) -> (Vec2, Vec) { diff --git a/crates/engine/src/tools/pointer.rs b/crates/engine/src/tools/pointer.rs index bf195b9f8..da3745f08 100644 --- a/crates/engine/src/tools/pointer.rs +++ b/crates/engine/src/tools/pointer.rs @@ -14,6 +14,10 @@ impl Session { /// What's under `p` on the current slide. pub fn hit_test(&self, p: Point, tol: f64) -> Option { + self.hit_test_with_transform(p, tol, true) + } + + fn hit_test_with_transform(&self, p: Point, tol: f64, transform: bool) -> Option { let st = self.active()?; // In Edit Points, the edited shape's vertices come first. if let Some(id) = self.tool.editing_points(st) @@ -61,13 +65,15 @@ impl Session { return Some(Hit::Warp { id: *id, index: hd.index }); } } - let (pts, rot) = box_handles(&x); - if (rot - p).hypot() <= tol * 1.8 && st.selection.text.is_none() { - return Some(Hit::Rotate { id: *id }); - } - for (i, q) in pts.iter().enumerate() { - if (*q - p).hypot() <= tol * 1.6 { - return Some(Hit::Resize { id: *id, handle: i as u8 }); + if transform { + let (pts, rot) = box_handles(&x); + if (rot - p).hypot() <= tol * 1.8 && st.selection.text.is_none() { + return Some(Hit::Rotate { id: *id }); + } + for (i, q) in pts.iter().enumerate() { + if (*q - p).hypot() <= tol * 1.6 { + return Some(Hit::Resize { id: *id, handle: i as u8 }); + } } } } @@ -96,6 +102,10 @@ impl Session { /// Feed a pointer event to the active tool. Returns what happened (for agents). pub fn pointer(&mut self, ev: PointerEvent) -> Result { + self.pointer_route(ev, None) + } + + fn pointer_route(&mut self, ev: PointerEvent, transform_hit: Option>) -> Result { let tol = if ev.tol > 0.0 { ev.tol } else { 4.0 }; let p = Point::new(ev.x, ev.y); self.tool.pressure = ev.pressure.filter(|v| v.is_finite()).map(|v| v.clamp(0.0, 1.0)); @@ -106,7 +116,8 @@ impl Session { if !matches!(ev.kind, PointerKind::Move) { self.settle_composition(); } - match ev.kind { + let before_target = self.text_selection().map(|(shape, cell, notes, _, _)| (shape, cell, notes)); + let result = match ev.kind { PointerKind::Move => { if let Some(Drag::Freeform { points, mode, .. }) = &self.tool.drag { let closing = points.len() > 2 && points.first().is_some_and(|s| (*s - p).hypot() <= tol * 2.0); @@ -117,9 +128,7 @@ impl Session { self.tool.path_closing = closing; return Ok(Value::Null); } - self.tool.hover = self.hit_test(p, tol); - self.tool.guide_hover = - if self.tool.hover.is_none() && matches!(self.tool.kind, ToolKind::Select) { self.guide_at(p, tol) } else { None }; + self.tool.hover = self.pointer_hit(p, tol, transform_hit); let line_tool = matches!(&self.tool.kind, ToolKind::Shape { preset } if deckcraft_geom::preset::is_line_like(preset)); if line_tool { self.update_sites(p, tol, None); @@ -129,7 +138,7 @@ impl Session { } Ok(Value::Null) } - PointerKind::Down => self.down(p, ev.mods, tol), + PointerKind::Down => self.down(p, ev.mods, tol, transform_hit), PointerKind::Drag => self.drag(p, ev.mods, tol), PointerKind::Up => self.up(p, ev.mods), PointerKind::DoubleClick => { @@ -147,6 +156,18 @@ impl Session { Ok(Value::Null) } } + }; + let after_target = self.text_selection().map(|(shape, cell, notes, _, _)| (shape, cell, notes)); + if result.is_ok() && after_target.is_some() && after_target != before_target { + self.begin_text_edit_session()?; + } + result + } + + fn pointer_hit(&self, p: Point, tol: f64, transform_hit: Option>) -> Option { + match transform_hit { + Some(hit) => hit.or_else(|| self.hit_test_with_transform(p, tol, false)), + None => self.hit_test(p, tol), } } @@ -189,15 +210,29 @@ impl Session { } } - /// Cancels a point or handle drag in Edit Points when Esc is pressed: ends the drag, puts back the - /// document and selection saved at the press, and adds no undo step. Returns whether a drag was cancelled. + /// Cancels a point or handle drag in Edit Points when Esc is pressed (`cancel_drag`). Returns whether a drag was + /// cancelled. pub(crate) fn cancel_point_drag(&mut self) -> bool { if !matches!(self.tool.drag, Some(Drag::Vertex { .. } | Drag::Handle { .. })) { return false; } - self.tool.drag = None; + self.cancel_drag(); + true + } + + /// Abandons the pointer drag in progress, as a cancelled press does: ends the drag without committing it, clears + /// its previews, puts back the document and selection saved at the press, and adds no undo step. + pub fn cancel_drag(&mut self) { + if self.tool.drag.take().is_none() { + return; + } + self.tool.preview = None; + self.tool.marquee = None; + self.tool.guides.clear(); + self.tool.path_preview.clear(); + self.tool.path_closing = false; + self.tool.ink_preview.clear(); if let Some(st) = self.active_mut() - && st.interaction.as_ref().is_some_and(|i| i.label == "Edit Points") && let Some(i) = st.interaction.take() { // A modifier held during the drag may have set a point type; the drag is undone, so is that. @@ -209,7 +244,6 @@ impl Session { } self.tool.vertex_kind = kind; } - true } /// End the interaction only when it is the one `label` started. A twist must not commit a drag. @@ -221,7 +255,7 @@ impl Session { } /// Handle a pointer press and start the applicable tool interaction. - fn down(&mut self, p: Point, mods: Mods, tol: f64) -> Result { + fn down(&mut self, p: Point, mods: Mods, tol: f64, transform_hit: Option>) -> Result { if let Some(Drag::Freeform { mode, mut points, .. }) = self.tool.drag.clone() { // Next click of a freeform: close on the start point, else add a vertex. if points.len() > 2 && points.first().is_some_and(|s| (*s - p).hypot() <= tol * 2.0) { @@ -266,12 +300,13 @@ impl Session { } // Clicking inside the text being edited moves the caret / starts a text selection. let before = self.text_selection(); - if let Some((shape, pos)) = self.place_caret(p, tol, mods.shift)? { + let canonical_transform = matches!(transform_hit, Some(Some(Hit::Resize { .. } | Hit::Rotate { .. }))); + if !canonical_transform && let Some((shape, pos)) = self.place_caret(p, tol, mods.shift)? { let press = self.doc()?.selection.text.clone(); self.tool.drag = Some(Drag::TextSelect { shape, before, press }); return Ok(json!({"caret": [pos.0, pos.1]})); } - let hit = self.hit_test(p, tol); + let hit = self.pointer_hit(p, tol, transform_hit); // Edit Points: drag a vertex, Ctrl-click one to delete it or the outline to add one; // a click anywhere else leaves Edit Points. if let Some(eid) = self.doc().ok().and_then(|st| self.tool.editing_points(st)) { @@ -420,14 +455,6 @@ impl Session { let _ = self.execute("animation.painterApply", &json!({"ids": [id]})); } } - None if self.guide_at(p, tol).is_some() => { - // Away from every shape a press on a guide picks the guide up. - if let Some(index) = self.guide_at(p, tol) { - let pos = st.doc.guides.get(index).map(|g| g.pos).unwrap_or(0.0); - self.tool.drag = Some(Drag::Guide { index }); - self.tool.guide_drag = Some((index, pos)); - } - } None => { let add = mods.shift || mods.cmd; self.select(|_, sel| { @@ -452,18 +479,6 @@ impl Session { self.tool.glue = None; let mut out = Value::Null; match drag { - Some(Drag::Guide { index }) => { - // Dropped off the slide: the guide is deleted. - let (_, pos) = self.tool.guide_drag.take().unwrap_or((index, 0.0)); - let size = self.doc()?.doc.slide_size; - let vertical = self.doc()?.doc.guides.get(index).is_some_and(|g| g.vertical); - let limit = if vertical { size.width } else { size.height }; - out = if pos < 0.0 || pos > limit { - self.execute("guide.delete", &json!({"index": index}))? - } else { - self.execute("guide.move", &json!({"index": index, "pos": pos}))? - }; - } Some(Drag::Move { moved: false, enter_text: Some((id, at)), .. }) // Plain click on text: caret at the click (in a table, in the clicked cell). if self.edit_text_at(id, at)? => { @@ -601,3 +616,11 @@ impl Session { self.active().and_then(|d| d.shape(id)).is_some_and(|s| matches!(s.kind, ShapeKind::Picture { .. } | ShapeKind::Media(_))) } } + +impl Session { + /// Uses the canvas's canonical resize/rotate hit for hover and press, preserving its chosen drag on drag/up. + /// `None` suppresses transform re-hits while retaining ordinary shape, text and edit-point hits. + pub fn pointer_with_hit(&mut self, ev: PointerEvent, transform_hit: Option) -> Result { + self.pointer_route(ev, Some(transform_hit)) + } +} diff --git a/crates/fonts/Cargo.toml b/crates/fonts/Cargo.toml index dd873f650..b8e19be63 100644 --- a/crates/fonts/Cargo.toml +++ b/crates/fonts/Cargo.toml @@ -9,6 +9,7 @@ description = "DeckCraft fonts: font database (craft-fonts + system), substitute workspace = true [dependencies] +craft = { workspace = true, features = ["font-catalog"] } kurbo = { workspace = true } skrifa = { workspace = true } harfrust = { workspace = true } diff --git a/crates/fonts/src/fontdb.rs b/crates/fonts/src/fontdb.rs index e542c8d18..e019785b7 100644 --- a/crates/fonts/src/fontdb.rs +++ b/crates/fonts/src/fontdb.rs @@ -1,10 +1,10 @@ -//! Font database: bundled OFL fonts, user fonts, the installed system fonts (cataloged the first -//! time a lookup needs them, native only), outline cache. +//! Document font shaping and outlines over the shared font catalogue. use std::collections::HashMap; use std::sync::atomic::{AtomicU32, Ordering}; use std::sync::{Arc, Mutex, RwLock}; +use craft::font_catalog::{Catalog, FontEnv, Limits, Os, Source}; use kurbo::BezPath; use skrifa::instance::{Location, LocationRef, Size}; use skrifa::outline::{DrawSettings, OutlinePen}; @@ -170,7 +170,7 @@ pub const MISSING_FONT_FAMILY: &str = "Calibri"; #[derive(Clone)] enum FontBytes { Static(&'static [u8]), - Owned(Arc>), + Owned(Arc<[u8]>), } /// One loaded font face. @@ -279,7 +279,7 @@ impl FontFace { pub fn data(&self) -> &[u8] { match &self.bytes { FontBytes::Static(b) => b, - FontBytes::Owned(v) => v.as_slice(), + FontBytes::Owned(v) => v, } } pub fn skrifa(&self) -> Option> { @@ -357,47 +357,37 @@ impl FontFace { } } -#[cfg(not(target_arch = "wasm32"))] -#[derive(Clone, Debug)] -struct CatalogEntry { - family: String, - style: String, - path: std::path::PathBuf, -} - /// Process-wide font database. pub struct FontDb { faces: RwLock>>, outlines: Mutex, - #[cfg(not(target_arch = "wasm32"))] - catalog: RwLock>, - /// The folders the system font scan reads (the platform's font folders for [`FontDb::global`]). - #[cfg_attr(target_arch = "wasm32", allow(dead_code))] - font_dirs: Vec, - /// Set once the font folders have been scanned. Lookups by family name wait for the first - /// scan, so what they find doesn't depend on what ran before them. - #[cfg(not(target_arch = "wasm32"))] - cataloged: std::sync::OnceLock<()>, + catalog: Arc, + scope: CatalogScope, /// Families (lower case) whose cataloged files have all been loaded: a family's files load /// together, so a lookup never settles for the one face another name loaded ("Segoe UI /// Semibold" loads a face of the family "Segoe UI"). - #[cfg(not(target_arch = "wasm32"))] - loaded_families: Mutex>, + loaded_families: Mutex<(u64, std::collections::HashSet)>, /// System fallback state: enabled, and characters no system font covers. #[cfg(not(target_arch = "wasm32"))] sys: Mutex, - /// Held while installed fonts are loaded, so threads that need the same family wait for one - /// load instead of racing it: what a lookup finds doesn't depend on which thread got there - /// first. + /// Serializes broad coverage searches so parallel misses do not repeat file loads. #[cfg(not(target_arch = "wasm32"))] loading: Mutex<()>, } +enum CatalogScope { + Process, + Isolated, +} + #[cfg(not(target_arch = "wasm32"))] #[derive(Default)] struct SysFallback { enabled: bool, misses: std::collections::HashSet, + plain_misses: std::collections::HashSet, + color_misses: std::collections::HashSet, + generation: u64, } /// Does face `index` of `data` carry colour glyph tables? @@ -509,213 +499,6 @@ fn instance_legacy_names(family: &str, style: &str) -> Option<(String, String)> Some((format!("{family} {weight}"), if style_italic(style) { "Italic" } else { "Regular" }.into())) } -/// The tables skrifa reads glyph outlines from: `glyf` (TrueType), `CFF `, `CFF2` and `VARC`. For a -/// face with none of them (bitmaps only, or outlines in Apple's `hvgl` table), [`FontDb::outline`] -/// returns an empty path for every glyph. -#[cfg(not(target_arch = "wasm32"))] -const OUTLINE_TABLES: [&[u8; 4]; 4] = [b"glyf", b"CFF ", b"CFF2", b"VARC"]; - -/// (family, style) of every face in the font file at `path`, reading only its table directories -/// and `name` tables: a scan opens hundreds of font files, many of them megabytes long. A -/// variable font is cataloged under its default style; its named instances appear once it loads. -/// Faces with none of the [`OUTLINE_TABLES`] are left out. -#[cfg(not(target_arch = "wasm32"))] -fn file_face_names(path: &std::path::Path) -> Vec<(String, String)> { - use std::io::{Read, Seek, SeekFrom}; - /// Caps on what a (possibly damaged) file can make the scan read. - const MAX_FACES: u32 = 256; - const MAX_NAME_TABLE: u32 = 1 << 20; - let Ok(mut file) = std::fs::File::open(path) else { return vec![] }; - let mut read_at = |offset: u64, len: usize| -> Option> { - let mut buf = vec![0; len]; - file.seek(SeekFrom::Start(offset)).ok()?; - file.read_exact(&mut buf).ok()?; - Some(buf) - }; - let be32 = |b: &[u8], at: usize| b.get(at..at + 4).and_then(|s| s.try_into().ok()).map(u32::from_be_bytes); - let Some(head) = read_at(0, 12) else { return vec![] }; - // A collection lists where each face's table directory starts. - let starts: Vec = if head.starts_with(b"ttcf") { - let n = be32(&head, 8).unwrap_or(0).min(MAX_FACES) as usize; - read_at(12, n * 4).map(|b| b.as_chunks::<4>().0.iter().map(|c| u32::from_be_bytes(*c)).collect()).unwrap_or_default() - } else { - vec![0] - }; - starts - .into_iter() - .filter_map(|start| { - let dir = read_at(start.into(), 12)?; - let tables = u16::from_be_bytes(dir.get(4..6)?.try_into().ok()?) as usize; - let records = read_at(u64::from(start) + 12, tables * 16)?; - if !records.as_chunks::<16>().0.iter().any(|r| OUTLINE_TABLES.iter().any(|t| r.starts_with(*t))) { - return None; - } - let rec = records.as_chunks::<16>().0.iter().find(|r| r.starts_with(b"name"))?; - let (offset, len) = (be32(rec, 8)?, be32(rec, 12)?); - if len > MAX_NAME_TABLE { - return None; - } - let table = read_at(offset.into(), len as usize)?; - // A one-table font holding just the `name` table, to read it as the font itself would. - let mut font = Vec::with_capacity(28 + table.len()); - font.extend_from_slice(&0x0001_0000_u32.to_be_bytes()); - font.extend_from_slice(&[0, 1, 0, 16, 0, 0, 0, 0]); - font.extend_from_slice(b"name"); - for v in [0, 28, len] { - font.extend_from_slice(&u32::to_be_bytes(v)); - } - font.extend_from_slice(&table); - let f = skrifa::FontRef::new(&font).ok()?; - let (family, style) = face_names(&f)?; - // Cataloged under its Windows family too, so "Segoe UI Semibold" finds the file. - let legacy = legacy_names(&f, &family); - Some(std::iter::once((family, style)).chain(legacy)) - }) - .flatten() - .collect() -} - -/// Folder depth below a font folder that the system scan descends. -#[cfg(not(target_arch = "wasm32"))] -const MAX_SCAN_DEPTH: usize = 12; -/// Directory entries the system scan looks at in all. -#[cfg(not(target_arch = "wasm32"))] -const MAX_SCAN_ENTRIES: usize = 200_000; -/// The largest font file read (the biggest CJK collections are a few hundred MB). -#[cfg(not(target_arch = "wasm32"))] -pub const MAX_FONT_FILE: u64 = 512 << 20; - -/// A regular file of a size a font can have. -#[cfg(not(target_arch = "wasm32"))] -fn font_file_ok(meta: &std::fs::Metadata) -> bool { - meta.is_file() && meta.len() > 12 && meta.len() <= MAX_FONT_FILE -} - -/// The platform's font folders (the system's and the user's), scanned by [`FontDb::global`]. -/// Empty on wasm. -pub fn system_font_dirs() -> Vec { - let mut dirs: Vec = Vec::new(); - if cfg!(target_arch = "wasm32") { - return dirs; - } - let home = std::env::var_os("HOME").map(std::path::PathBuf::from); - if cfg!(target_os = "macos") { - dirs.extend(["/System/Library/Fonts", "/Library/Fonts"].map(Into::into)); - if let Some(h) = &home { - dirs.push(h.join("Library/Fonts")); - // Fonts Microsoft Office downloads on demand (Aptos…), used where Office put them. - dirs.push(h.join("Library/Group Containers/UBF8T346G9.Office/FontCache/4/CloudFonts")); - } - // Fonts Office installs inside its apps. - for app in ["Microsoft PowerPoint", "Microsoft Word", "Microsoft Excel"] { - dirs.push(std::path::PathBuf::from(format!("/Applications/{app}.app/Contents/Resources/DFonts"))); - } - // Fonts macOS ships as assets (PingFang, Yu Mincho, …): com_apple_MobileAsset_Font. - for parent in ["/System/Library/AssetsV2", "/System/Library/AssetsV2/PreinstalledAssetsV2/InstallWithOs"] { - let Ok(entries) = std::fs::read_dir(parent) else { continue }; - for e in entries.flatten() { - if e.file_name().to_string_lossy().starts_with("com_apple_MobileAsset_Font") { - dirs.push(e.path()); - } - } - } - } else if cfg!(windows) { - let root = std::env::var_os("WINDIR").map(std::path::PathBuf::from).unwrap_or_else(|| "C:\\Windows".into()); - dirs.push(root.join("Fonts")); - if let Some(l) = std::env::var_os("LOCALAPPDATA") { - let l = std::path::PathBuf::from(l); - dirs.push(l.join("Microsoft\\Windows\\Fonts")); - // Fonts Microsoft Office downloads on demand (Aptos…), used where Office put them; - // DeckCraft never ships or needs them. - dirs.push(l.join("Microsoft\\FontCache\\4\\CloudFonts")); - } - } else { - dirs.extend(["/usr/share/fonts", "/usr/local/share/fonts"].map(Into::into)); - if let Some(h) = &home { - dirs.push(h.join(".fonts")); - dirs.push(h.join(".local/share/fonts")); - } - let env = |k: &str| std::env::var_os(k).map(|v| v.to_string_lossy().into_owned()); - dirs.extend(xdg_font_dirs(env("XDG_DATA_HOME").as_deref(), env("XDG_DATA_DIRS").as_deref(), home.as_deref())); - // Inside Flatpak the host's fonts are mounted here. - dirs.extend(["/run/host/fonts", "/run/host/local-fonts", "/run/host/user-fonts"].map(Into::into)); - // Folders fontconfig is configured with (NixOS, Guix, custom setups). - for conf in fontconfig_files() { - if let Ok(text) = std::fs::read_to_string(&conf) { - dirs.extend(fontconfig_dirs(&text, env("XDG_DATA_HOME").as_deref(), home.as_deref())); - } - } - } - let mut seen = std::collections::HashSet::new(); - dirs.retain(|d| seen.insert(d.clone())); - dirs -} - -/// `/fonts` for `XDG_DATA_HOME` (default `~/.local/share`) and each `XDG_DATA_DIRS` -/// entry (default `/usr/local/share:/usr/share`). -fn xdg_font_dirs(data_home: Option<&str>, data_dirs: Option<&str>, home: Option<&std::path::Path>) -> Vec { - let mut v = vec![]; - match data_home.filter(|d| !d.is_empty()) { - Some(d) => v.push(std::path::Path::new(d).join("fonts")), - None => { - if let Some(h) = home { - v.push(h.join(".local/share/fonts")); - } - } - } - let dirs = data_dirs.filter(|d| !d.is_empty()).unwrap_or("/usr/local/share:/usr/share"); - v.extend(dirs.split(':').filter(|d| d.starts_with('/')).take(64).map(|d| std::path::Path::new(d).join("fonts"))); - v -} - -/// The fontconfig configuration files: `/etc/fonts/fonts.conf` and `/etc/fonts/conf.d/*.conf`. -fn fontconfig_files() -> Vec { - let mut v = vec![std::path::PathBuf::from("/etc/fonts/fonts.conf"), std::path::PathBuf::from("/etc/fonts/local.conf")]; - if let Ok(entries) = std::fs::read_dir("/etc/fonts/conf.d") { - let mut files: Vec<_> = entries.flatten().map(|e| e.path()).filter(|p| p.extension().is_some_and(|x| x == "conf")).collect(); - files.sort(); - files.truncate(512); - v.extend(files); - } - v -} - -/// The `` folders of a fontconfig file (`prefix="xdg"` is under `XDG_DATA_HOME`, a leading -/// `~` under home; relative and `cachedir` entries are skipped). -fn fontconfig_dirs(text: &str, data_home: Option<&str>, home: Option<&std::path::Path>) -> Vec { - let mut v = vec![]; - let mut rest = text; - while let Some(start) = rest.find("` or ``, not ``. - if !(after.starts_with('>') || after.starts_with(' ')) { - rest = after; - continue; - } - let Some(gt) = after.find('>') else { break }; - let attrs = &after[..gt]; - let body = &after[gt + 1..]; - let Some(end) = body.find("") else { break }; - let path = body[..end].trim(); - rest = &body[end..]; - if attrs.trim_end().ends_with('/') || path.is_empty() || v.len() >= 64 { - continue; - } - let p = if attrs.contains("prefix=\"xdg\"") { - let base = data_home.filter(|d| !d.is_empty()).map(std::path::PathBuf::from).or_else(|| home.map(|h| h.join(".local/share"))); - base.map(|b| b.join(path)) - } else if let Some(r) = path.strip_prefix("~/") { - home.map(|h| h.join(r)) - } else if path.starts_with('/') { - Some(std::path::PathBuf::from(path)) - } else { - None - }; - v.extend(p); - } - v -} - /// One face found in a font file: index, family, style and (variable fonts) the named instance's /// axis settings. type Found = (u32, String, String, Vec<([u8; 4], f32)>); @@ -832,7 +615,7 @@ fn line_split(f: &skrifa::FontRef, ascent: f64, descent: f64, upem: f64) -> f64 fn make_face(bytes: FontBytes, index: u32, family: String, style: String, coords: Vec<([u8; 4], f32)>) -> Option { let data: &[u8] = match &bytes { FontBytes::Static(b) => b, - FontBytes::Owned(v) => v.as_slice(), + FontBytes::Owned(v) => v, }; let f = skrifa::FontRef::from_index(data, index).ok()?; let settings: Vec<(skrifa::Tag, f32)> = coords.iter().map(|(t, v)| (skrifa::Tag::new(t), *v)).collect(); @@ -936,12 +719,20 @@ fn style_italic(style: &str) -> bool { } impl FontDb { - /// A database holding the bundled fonts, then the craft-fonts Japanese faces (Mincho first, - /// so they are the fallback for Japanese text after the requested and bundled fonts; empty - /// without `CRAFT_FONTS_DIR`), whose system font scan reads `font_dirs`. + /// An isolated database of bundled fonts and fonts discovered only in `font_dirs`. + /// Neither platform services nor the process catalogue contribute fixture fonts. pub fn with_font_dirs(font_dirs: Vec) -> Self { + let catalog = Arc::new(Catalog::new(FontEnv { os: Os::None, ..FontEnv::default() }).with_font_service(false)); + catalog.set_app_dirs(font_dirs.clone()); + catalog.set_confined_dirs(font_dirs); + Self::with_catalog(catalog, CatalogScope::Isolated) + } + + fn with_catalog(catalog: Arc, scope: CatalogScope) -> Self { let mut faces = Vec::new(); for data in bundled() { + // Registration also makes the bundled faces available to the browser's picker. + let _ = catalog.add_bytes(data.to_vec(), Source::Bundled, &Limits::default()); for (i, family, style, coords) in enumerate_faces(data) { if let Some(f) = make_face(FontBytes::Static(data), i, family, style, coords) { faces.push(Arc::new(f)); @@ -951,13 +742,9 @@ impl FontDb { Self { faces: RwLock::new(faces), outlines: Mutex::new(OutlineCache::default()), - #[cfg(not(target_arch = "wasm32"))] - catalog: RwLock::new(Vec::new()), - font_dirs, - #[cfg(not(target_arch = "wasm32"))] - cataloged: std::sync::OnceLock::new(), - #[cfg(not(target_arch = "wasm32"))] - loaded_families: Mutex::new(std::collections::HashSet::new()), + catalog, + scope, + loaded_families: Mutex::new((0, std::collections::HashSet::new())), #[cfg(not(target_arch = "wasm32"))] sys: Mutex::new(SysFallback { enabled: true, ..Default::default() }), #[cfg(not(target_arch = "wasm32"))] @@ -987,30 +774,20 @@ impl FontDb { false } - /// Process-wide database: the bundled fonts, then the installed system fonts, cataloged the - /// first time a lookup by family name needs them (or ahead of time by - /// [`FontDb::scan_in_background`]). + /// The document adapter over the same process catalogue used by the font picker. pub fn global() -> &'static FontDb { static DB: std::sync::OnceLock = std::sync::OnceLock::new(); - DB.get_or_init(|| FontDb::with_font_dirs(system_font_dirs())) + DB.get_or_init(|| FontDb::with_catalog(Catalog::global().clone(), CatalogScope::Process)) } pub(crate) fn read_faces(&self) -> std::sync::RwLockReadGuard<'_, Vec>> { self.faces.read().unwrap_or_else(std::sync::PoisonError::into_inner) } - /// The system font catalog, scanned first if it hasn't been yet. - #[cfg(not(target_arch = "wasm32"))] - fn read_catalog(&self) -> std::sync::RwLockReadGuard<'_, Vec> { - self.ensure_catalog(); - self.catalog.read().unwrap_or_else(std::sync::PoisonError::into_inner) - } - /// Family names available (loaded plus cataloged system fonts), sorted and deduplicated. pub fn families(&self) -> Vec { let mut v: Vec = self.read_faces().iter().map(|f| f.family.clone()).collect(); - #[cfg(not(target_arch = "wasm32"))] - v.extend(self.read_catalog().iter().map(|c| c.family.clone())); + v.extend(self.catalog.families().iter().cloned()); v.sort_by_key(|a| a.to_lowercase()); v.dedup_by(|a, b| a.eq_ignore_ascii_case(b)); v @@ -1024,10 +801,9 @@ impl FontDb { .filter(|f| f.family.eq_ignore_ascii_case(family) && !f.style.contains('{')) .map(|f| (f.italic, f.weight, f.style.clone())) .collect(); - #[cfg(not(target_arch = "wasm32"))] - for c in self.read_catalog().iter() { - if c.family.eq_ignore_ascii_case(family) && !v.iter().any(|(_, _, s)| s.eq_ignore_ascii_case(&c.style)) { - v.push((style_italic(&c.style), style_weight(&c.style), c.style.clone())); + for c in self.catalog.styles(family) { + if !v.iter().any(|(_, _, s)| s.eq_ignore_ascii_case(&c.style)) { + v.push((c.italic, c.weight, c.style)); } } v.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.total_cmp(&b.1)).then(a.2.cmp(&b.2))); @@ -1038,7 +814,11 @@ impl FontDb { /// Add a user font (TTF/OTF/TTC bytes). Returns the number of faces added (0 if unparseable or /// every face was already present). pub fn add_font(&self, bytes: Vec) -> usize { - self.add_fonts(vec![bytes]) + let added = self.add_fonts(vec![bytes.clone()]); + if added > 0 { + let _ = self.catalog.add_bytes(bytes, Source::User, &Limits::default()); + } + added } /// Add font files together: lookups see all of their faces or none, never part of a family. @@ -1049,7 +829,7 @@ impl FontDb { }; let mut new = Vec::new(); for bytes in files { - let data = Arc::new(bytes); + let data: Arc<[u8]> = bytes.into(); for (i, family, style, coords) in enumerate_faces(&data) { if present(&self.read_faces(), &family, &style) { continue; @@ -1071,110 +851,79 @@ impl FontDb { added } - /// Catalog the installed fonts unless that has been done: the first caller scans the font - /// folders, any other waits for that scan to finish. - #[cfg(not(target_arch = "wasm32"))] - fn ensure_catalog(&self) { - self.cataloged.get_or_init(|| { - self.scan_font_dirs(); - }); - } - - /// Catalog the installed fonts on a background thread, so the first lookup by family name - /// (opening a file, the font menus) doesn't wait for the scan. A no-op once they are - /// cataloged, and on wasm. + /// Starts the catalogue's shared background discovery. pub fn scan_in_background(&'static self) { - #[cfg(not(target_arch = "wasm32"))] - if self.cataloged.get().is_none() { - // A failed spawn leaves the scan to the first lookup that needs it. - let _ = std::thread::Builder::new().name("font-scan".into()).spawn(move || self.ensure_catalog()); - } + self.catalog.scan_in_background(); } - /// Scan the font folders again (fonts installed or removed since), cataloging the faces - /// found (native only). Font data is loaded when a cataloged family is first resolved. + /// Refresh the shared discovery lifecycle, or only this database's isolated catalogue. + /// Font data is loaded when a catalogued family is first resolved. /// Returns the number of faces cataloged. - #[cfg(not(target_arch = "wasm32"))] pub fn load_system_fonts(&self) -> usize { - // Families load again from the new catalog when next looked up. - self.loaded_families.lock().unwrap_or_else(std::sync::PoisonError::into_inner).clear(); - // The first scan, or a rescan once it is done (never both at once). - let mut first = None; - self.cataloged.get_or_init(|| first = Some(self.scan_font_dirs())); - first.unwrap_or_else(|| self.scan_font_dirs()) + let count = match self.scope { + CatalogScope::Process => { + craft::font_catalog::app::rescan_now(); + self.catalog.faces().len() + } + CatalogScope::Isolated => self.catalog.rescan(), + }; + self.invalidate_catalog(); + count } - #[cfg(not(target_arch = "wasm32"))] - fn scan_font_dirs(&self) -> usize { - let mut found = Vec::new(); - let mut stack: Vec<(std::path::PathBuf, usize)> = self.font_dirs.iter().map(|d| (d.clone(), 0)).collect(); - // Each folder once, however links lead back to it. - let mut visited = std::collections::HashSet::new(); - let mut entries = 0usize; - while let Some((d, depth)) = stack.pop() { - if !visited.insert(std::fs::canonicalize(&d).unwrap_or_else(|_| d.clone())) { - continue; - } - let Ok(rd) = std::fs::read_dir(&d) else { continue }; - for e in rd.flatten() { - // A link to `/` or a vast tree mustn't turn start-up into a disk crawl. - entries += 1; - if entries > MAX_SCAN_ENTRIES { - log::warn!("font scan stopped after {MAX_SCAN_ENTRIES} entries"); - stack.clear(); - break; - } - let p = e.path(); - // Follows links: what matters is what the entry leads to. - let Ok(meta) = std::fs::metadata(&p) else { continue }; - if meta.is_dir() { - if depth < MAX_SCAN_DEPTH { - stack.push((p, depth + 1)); - } - continue; - } - let ext = p.extension().and_then(std::ffi::OsStr::to_str).map(str::to_ascii_lowercase); - if !matches!(ext.as_deref(), Some("ttf" | "otf" | "ttc" | "otc")) { - continue; - } - // Only regular files: opening a FIFO named like a font blocks until something - // writes to it (start-up hung), and a device never ends. - if !font_file_ok(&meta) { - continue; - } - for (family, style) in file_face_names(&p) { - found.push(CatalogEntry { family, style, path: p.clone() }); - } - } - } - let n = found.len(); - log::debug!("cataloged {n} system font faces"); - *self.catalog.write().unwrap_or_else(std::sync::PoisonError::into_inner) = found; - n + /// Invalidates derived family lookups and coverage misses after catalogue changes. + pub fn invalidate_catalog(&self) { + *self.loaded_families.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = + (self.catalog.generation(), std::collections::HashSet::new()); + #[cfg(not(target_arch = "wasm32"))] + self.refresh_misses(true); } /// Load the files of the installed `family` (faces already loaded are kept). Returns whether /// it is loaded. - #[cfg(not(target_arch = "wasm32"))] fn load_cataloged(&self, family: &str) -> bool { - let loading = self.loading.lock().unwrap_or_else(std::sync::PoisonError::into_inner); - self.load_family(family, &loading) + let loaded = self.catalog.load_family(family); + for face in loaded.iter() { + self.add_catalog_face(&face.info, &face.data); + } + if loaded.is_empty() { + // A Windows family name: only the files of its faces, not their whole family. + for info in self.legacy_faces(family) { + if let Ok(data) = self.catalog.load(&info) { + self.add_catalog_face(&info, &data); + } + } + } + self.is_loaded(family) } - /// [`FontDb::load_cataloged`] for a caller already holding `loading`. - #[cfg(not(target_arch = "wasm32"))] - fn load_family(&self, family: &str, _loading: &std::sync::MutexGuard<'_, ()>) -> bool { - // Not skipped when some face of the family is loaded: a lookup by a Windows family name - // loads only that style's file, and the family's other files must still load later. - let paths: Vec = { - let cat = self.read_catalog(); - let mut p: Vec<_> = cat.iter().filter(|c| c.family.eq_ignore_ascii_case(family)).map(|c| c.path.clone()).collect(); - p.sort(); - p.dedup(); - p + fn add_catalog_face(&self, info: &craft::font_catalog::FaceInfo, data: &craft::font_catalog::FontData) { + let present = + |faces: &[Arc]| faces.iter().any(|f| f.family.eq_ignore_ascii_case(&info.family) && f.style.eq_ignore_ascii_case(&info.style)); + if present(&self.read_faces()) { + return; + } + let Some(face) = + make_face(FontBytes::Owned(data.bytes.clone()), data.index, info.family.clone(), info.style.clone(), info.variations.clone()) + else { + return; }; - self.add_fonts(paths.iter().filter(|p| std::fs::metadata(p).is_ok_and(|m| font_file_ok(&m))).filter_map(|p| std::fs::read(p).ok()).collect()); - self.is_loaded(family) + let mut faces = self.faces.write().unwrap_or_else(std::sync::PoisonError::into_inner); + if !present(&faces) { + faces.push(Arc::new(face)); + } + } + + #[cfg(not(target_arch = "wasm32"))] + fn refresh_misses(&self, force: bool) { + let generation = self.catalog.generation(); + let mut sys = self.sys.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + if force || sys.generation != generation { + sys.generation = generation; + sys.misses.clear(); + sys.plain_misses.clear(); + sys.color_misses.clear(); + } } /// Resolve a family + style to a face, falling back to the closest style of the family, then to @@ -1223,16 +972,24 @@ impl FontDb { // Every installed file of the family first, so the best style is among the candidates. The // lock is held while the files load, so another thread looking up the family waits for // them rather than finding none and falling back to another family. - #[cfg(not(target_arch = "wasm32"))] { let mut loaded = self.loaded_families.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + // Snapshot discovery before recording its generation, including the first lazy scan. + let _ = self.catalog.families(); + let generation = self.catalog.generation(); + if loaded.0 != generation { + *loaded = (generation, std::collections::HashSet::new()); + } let key = family.to_lowercase(); - if !loaded.contains(&key) { + if !loaded.1.contains(&key) { self.load_cataloged(family); - loaded.insert(key); + loaded.1.insert(key); } } - self.find(family, style) + self.find(family, style).or_else(|| { + let (info, _) = self.catalog.resolve(family, base_style(style))?; + self.find(&info.family, if style.contains('{') { style } else { &info.style }) + }) } /// Is `family` available (loaded, or installed on the system)? @@ -1240,11 +997,14 @@ impl FontDb { if self.is_loaded(family) { return true; } - #[cfg(not(target_arch = "wasm32"))] - if self.read_catalog().iter().any(|c| c.family.eq_ignore_ascii_case(family)) { - return true; - } - false + self.catalog.family(family).is_some() || !self.legacy_faces(family).is_empty() + } + + /// The cataloged faces whose Windows family is `family` ("Segoe UI Semibold"): the catalogue + /// lists them under their typographic family only. + fn legacy_faces(&self, family: &str) -> Vec { + let key = norm(family); + self.catalog.faces().iter().filter(|f| f.legacy_family.as_deref().is_some_and(|lf| norm(lf) == key)).cloned().collect() } pub(crate) fn is_loaded(&self, family: &str) -> bool { @@ -1394,6 +1154,8 @@ impl FontDb { if c.is_control() || c.is_whitespace() { return false; } + let cataloged = self.catalog.families(); + self.refresh_misses(false); let seen = self.read_faces().len(); { let sys = self.sys.lock().unwrap_or_else(std::sync::PoisonError::into_inner); @@ -1402,8 +1164,7 @@ impl FontDb { } } let covered = |db: &FontDb| db.read_faces().iter().any(|f| f.covers(c) && accept(f)); - let cataloged: Vec = self.read_catalog().iter().map(|e| e.family.clone()).collect(); - let loading = self.loading.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let _loading = self.loading.lock().unwrap_or_else(std::sync::PoisonError::into_inner); // Another thread may have loaded a face for `c` (faces are only ever added), or found // there is none, while this one waited. if self.read_faces().len() != seen && covered(self) { @@ -1414,26 +1175,14 @@ impl FontDb { } for fam in SYSTEM_FALLBACKS { if !self.is_loaded(fam) && cataloged.iter().any(|f| f.eq_ignore_ascii_case(fam)) { - self.load_family(fam, &loading); + self.load_cataloged(fam); if covered(self) { return true; } } } - let mut paths: Vec = - self.catalog.read().unwrap_or_else(std::sync::PoisonError::into_inner).iter().map(|e| e.path.clone()).collect(); - paths.sort(); - paths.dedup(); - for p in paths { - if std::fs::metadata(&p).map(|m| m.len() > 40 << 20).unwrap_or(true) { - continue; - } - let Ok(data) = std::fs::read(&p) else { continue }; - let hit = - enumerate_faces(&data).iter().any(|(i, _, _, _)| skrifa::FontRef::from_index(&data, *i).is_ok_and(|f| f.charmap().map(c).is_some())); - if hit && self.add_font(data) > 0 && covered(self) { - return true; - } + if self.load_covering(c, 40 << 20, accept) { + return true; } if remember_miss { self.sys.lock().unwrap_or_else(std::sync::PoisonError::into_inner).misses.insert(c); @@ -1484,8 +1233,7 @@ impl FontDb { }; #[cfg(not(target_arch = "wasm32"))] { - let cataloged: Vec = - if self.system_fallback_enabled() { self.read_catalog().iter().map(|e| e.family.clone()).collect() } else { Vec::new() }; + let cataloged = if self.system_fallback_enabled() { self.catalog.families().to_vec() } else { Vec::new() }; for fam in SYSTEM_FALLBACKS.iter().filter(|f| f.contains("Symbol")) { if !self.is_loaded(fam) && cataloged.iter().any(|f| f.eq_ignore_ascii_case(fam)) { self.load_cataloged(fam); @@ -1506,67 +1254,67 @@ impl FontDb { /// Load an installed font without colour tables covering `c`. True if one was loaded. #[cfg(not(target_arch = "wasm32"))] fn system_plain_fallback(&self, c: char) -> bool { - static MISSES: Mutex>> = Mutex::new(None); if c.is_control() || c.is_whitespace() { return false; } - if !self.sys.lock().unwrap_or_else(std::sync::PoisonError::into_inner).enabled { - return false; - } - if MISSES.lock().unwrap_or_else(std::sync::PoisonError::into_inner).get_or_insert_with(Default::default).contains(&c) { - return false; - } - let mut paths: Vec = self.read_catalog().iter().map(|e| e.path.clone()).collect(); - paths.sort(); - paths.dedup(); - for p in paths { - if std::fs::metadata(&p).map(|m| m.len() > 40 << 20).unwrap_or(true) { - continue; - } - let Ok(data) = std::fs::read(&p) else { continue }; - let hit = enumerate_faces(&data).iter().any(|(i, _, _, _)| { - !has_color_tables(&data, *i) && skrifa::FontRef::from_index(&data, *i).is_ok_and(|f| f.charmap().map(c).is_some()) - }); - if hit && self.add_font(data) > 0 { - return true; + let _ = self.catalog.families(); + self.refresh_misses(false); + { + let sys = self.sys.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + if !sys.enabled || sys.plain_misses.contains(&c) { + return false; } } - MISSES.lock().unwrap_or_else(std::sync::PoisonError::into_inner).get_or_insert_with(Default::default).insert(c); + if self.load_covering(c, 40 << 20, &|f| !f.is_color()) { + return true; + } + self.sys.lock().unwrap_or_else(std::sync::PoisonError::into_inner).plain_misses.insert(c); false } /// Load an installed colour font covering `c`. True if one was loaded. #[cfg(not(target_arch = "wasm32"))] fn system_color_fallback(&self, c: char) -> bool { - static MISSES: Mutex>> = Mutex::new(None); if c.is_control() || c.is_whitespace() { return false; } + let _ = self.catalog.families(); + self.refresh_misses(false); { let sys = self.sys.lock().unwrap_or_else(std::sync::PoisonError::into_inner); - if !sys.enabled { + if !sys.enabled || sys.color_misses.contains(&c) { return false; } } - if MISSES.lock().unwrap_or_else(std::sync::PoisonError::into_inner).get_or_insert_with(Default::default).contains(&c) { - return false; + if self.load_covering(c, 64 << 20, &FontFace::is_color) { + return true; } - let mut paths: Vec = self.read_catalog().iter().map(|e| e.path.clone()).collect(); - paths.sort(); - paths.dedup(); - for p in paths { - if std::fs::metadata(&p).map(|m| m.len() > 64 << 20).unwrap_or(true) { + self.sys.lock().unwrap_or_else(std::sync::PoisonError::into_inner).color_misses.insert(c); + false + } + + #[cfg(not(target_arch = "wasm32"))] + fn load_covering(&self, c: char, max_bytes: u64, accept: &impl Fn(&FontFace) -> bool) -> bool { + let faces = self.catalog.faces(); + let mut candidates: Vec<_> = faces.iter().collect(); + candidates.sort_by(|a, b| a.path.cmp(&b.path).then(a.index.cmp(&b.index))); + // Keep one file alive between adjacent faces so the catalogue's weak byte cache shares + // a collection or variable font's data instead of reading it once per named instance. + let mut previous_bytes = None; + for info in candidates { + if info.file_bytes.is_some_and(|size| size > max_bytes) { continue; } - let Ok(data) = std::fs::read(&p) else { continue }; - let hit = enumerate_faces(&data).iter().any(|(i, _, _, _)| { - has_color_tables(&data, *i) && skrifa::FontRef::from_index(&data, *i).is_ok_and(|f| f.charmap().map(c).is_some()) - }); - if hit && self.add_font(data) > 0 { + let Ok(data) = self.catalog.load(info) else { continue }; + let _ = previous_bytes.replace(data.bytes.clone()); + if !skrifa::FontRef::from_index(&data.bytes, data.index).is_ok_and(|font| font.charmap().map(c).is_some()) { + continue; + } + self.add_catalog_face(info, &data); + if self.read_faces().iter().any(|face| face.covers(c) && accept(face)) { return true; } } - MISSES.lock().unwrap_or_else(std::sync::PoisonError::into_inner).get_or_insert_with(Default::default).insert(c); false } @@ -1645,10 +1393,64 @@ impl OutlinePen for FlipPen { #[cfg(test)] mod font_dir_tests { - use std::path::{Path, PathBuf}; - use super::*; + #[cfg(unix)] + fn assert_fixture_discovered_after_rescan(env: FontEnv, directory: &std::path::Path) { + let catalog = Arc::new(Catalog::new(env.clone()).with_font_service(false)); + catalog.set_confined_dirs(vec![env.root]); + let db = FontDb::with_catalog(catalog.clone(), CatalogScope::Isolated); + assert!(!db.has_family("DeckCraft Legacy")); + let missing = db.face("DeckCraft Legacy", "Regular"); + std::fs::create_dir_all(directory).unwrap(); + let file = directory.join("regular.ttf"); + std::fs::write(&file, include_bytes!("../tests/fixtures/legacy-regular.ttf")).unwrap(); + db.load_system_fonts(); + let (info, _) = catalog.resolve("DeckCraft Legacy", "Regular").unwrap(); + assert!(db.families().contains(&info.family)); + let face = db.face(&info.family, &info.style); + assert_ne!(face.family, missing.family); + assert_eq!(face.family, info.family); + assert_eq!(face.style, info.style); + assert!(face.covers('A')); + assert!(!db.outline(&face, face.glyph_for('A')).elements().is_empty()); + let loaded = db.read_faces().len(); + db.load_system_fonts(); + assert_eq!(db.face(&info.family, &info.style).id(), face.id()); + assert_eq!(db.read_faces().len(), loaded); + std::fs::remove_file(file).unwrap(); + } + + #[test] + fn user_font_registration_is_shared_with_the_adapter_catalogue_and_is_idempotent() { + let catalog = Arc::new(Catalog::new(FontEnv { os: Os::None, ..FontEnv::default() }).with_font_service(false)); + let db = FontDb::with_catalog(catalog.clone(), CatalogScope::Isolated); + let bytes = include_bytes!("../tests/fixtures/legacy-semibold.ttf"); + assert!(catalog.family("DeckCraft Legacy Semibold").is_none()); + assert!(db.add_font(bytes.to_vec()) > 0); + let (info, _) = catalog.resolve("DeckCraft Legacy Semibold", "Regular").unwrap(); + let face = db.face("DeckCraft Legacy Semibold", "Regular"); + assert_eq!(face.family, info.family); + assert_eq!(face.style, info.style); + let before = catalog.faces().len(); + assert_eq!(db.add_font(bytes.to_vec()), 0); + assert_eq!(catalog.faces().len(), before); + assert_eq!(db.face(&info.family, &info.style).id(), face.id()); + } + + #[test] + fn catalogue_added_bytes_resolve_without_a_directory_scan() { + let catalog = Arc::new(Catalog::new(FontEnv { os: Os::None, ..FontEnv::default() }).with_font_service(false)); + let db = FontDb::with_catalog(catalog.clone(), CatalogScope::Isolated); + let family = "DeckCraft Legacy"; + let missing = db.face(family, "Regular"); + let infos = catalog.add_bytes(include_bytes!("../tests/fixtures/legacy-regular.ttf").to_vec(), Source::User, &Limits::default()).unwrap(); + let resolved = db.face(family, "Regular"); + assert_ne!(resolved.family, missing.family); + assert!(infos.iter().any(|info| info.family == resolved.family && info.style == resolved.style)); + assert!(resolved.covers('A')); + } + #[test] fn duplicate_collection_offsets_do_not_consume_face_cap() { let mut entries = vec![(0, 7); MAX_COLLECTION_FACES as usize]; @@ -1716,18 +1518,33 @@ mod font_dir_tests { assert_eq!(cache.elements, before); } + // The catalogue keeps only host-absolute XDG entries, and `/nix/…` is absolute only on a Unix host. #[test] + #[cfg(unix)] fn xdg_data_dirs_contribute_their_fonts_folders() { - let home = Path::new("/home/ann"); - assert_eq!( - xdg_font_dirs(None, None, Some(home)), - [home.join(".local/share/fonts"), "/usr/local/share/fonts".into(), "/usr/share/fonts".into()] - ); - let v = xdg_font_dirs(Some("/data/ann"), Some("/nix/profile/share:relative:/var/lib/flatpak/exports/share"), Some(home)); - assert_eq!(v, [PathBuf::from("/data/ann/fonts"), "/nix/profile/share/fonts".into(), "/var/lib/flatpak/exports/share/fonts".into()]); + let root = std::env::temp_dir().join(format!("deckcraft-fonts-xdg-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&root); + std::fs::create_dir_all(&root).unwrap(); + let home = root.join("home/ann"); + let env = FontEnv { os: Os::Unix, root: root.clone(), home: Some(home.clone()), ..FontEnv::default() }; + for directory in [home.join(".local/share/fonts"), root.join("usr/local/share/fonts"), root.join("usr/share/fonts")] { + assert_fixture_discovered_after_rescan(env.clone(), &directory); + } + let data_home = root.join("data/ann"); + let env = FontEnv { + xdg_data_home: Some(data_home.clone()), + xdg_data_dirs: Some(std::env::join_paths(["/nix/profile/share", "relative", "/var/lib/flatpak/exports/share"]).unwrap()), + ..env + }; + for directory in [data_home.join("fonts"), root.join("nix/profile/share/fonts"), root.join("var/lib/flatpak/exports/share/fonts")] { + assert_fixture_discovered_after_rescan(env.clone(), &directory); + } + let _ = std::fs::remove_dir_all(root); } + // A `` of `/…` is absolute only on a Unix host; elsewhere it joins the configuration's folder. #[test] + #[cfg(unix)] fn fontconfig_dir_entries_are_read() { let conf = r#" @@ -1739,23 +1556,54 @@ mod font_dir_tests { ignored /nix/store/abc-fonts/share/fonts "#; - let home = Path::new("/home/ann"); - let v = fontconfig_dirs(conf, None, Some(home)); - assert_eq!( - v, - [PathBuf::from("/usr/share/fonts"), home.join(".local/share/fonts"), home.join(".fonts"), "/nix/store/abc-fonts/share/fonts".into()] - ); - assert!(fontconfig_dirs("/never closed", None, Some(home)).is_empty()); + let root = std::env::temp_dir().join(format!("deckcraft-fontconfig-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&root); + std::fs::create_dir_all(&root).unwrap(); + let home = root.join("home/ann"); + let file = root.join("fonts.conf"); + std::fs::write(&file, conf).unwrap(); + let env = FontEnv { os: Os::Unix, root: root.clone(), home: Some(home.clone()), fontconfig_file: Some(file.clone()), ..FontEnv::default() }; + for directory in [ + root.join("usr/share/fonts"), + home.join(".local/share/fonts"), + home.join(".fonts"), + root.join("relative/fonts"), + root.join("nix/store/abc-fonts/share/fonts"), + ] { + assert_fixture_discovered_after_rescan(env.clone(), &directory); + } + std::fs::write(&file, "/never closed").unwrap(); + let relative = root.join("relative/fonts"); + std::fs::write(relative.join("regular.ttf"), include_bytes!("../tests/fixtures/legacy-regular.ttf")).unwrap(); + let catalog = Arc::new(Catalog::new(env).with_font_service(false)); + catalog.set_confined_dirs(vec![root.clone()]); + let db = FontDb::with_catalog(catalog.clone(), CatalogScope::Isolated); + assert!(!db.has_family("DeckCraft Legacy")); + let missing = db.face("DeckCraft Legacy", "Regular"); + std::fs::write(&file, conf).unwrap(); + db.load_system_fonts(); + let (info, _) = catalog.resolve("DeckCraft Legacy", "Regular").unwrap(); + let face = db.face(&info.family, &info.style); + assert_ne!(face.family, missing.family); + assert_eq!(face.family, info.family); + assert_eq!(face.style, info.style); + assert!(face.covers('A')); + assert!(!db.outline(&face, face.glyph_for('A')).elements().is_empty()); + let _ = std::fs::remove_dir_all(root); } #[test] #[cfg(target_os = "linux")] fn linux_dirs_include_flatpak_host_fonts_without_duplicates() { - let d = system_font_dirs(); - assert!(d.contains(&PathBuf::from("/run/host/user-fonts"))); - let mut u = d.clone(); - u.sort(); - u.dedup(); - assert_eq!(u.len(), d.len()); + let root = std::env::temp_dir().join(format!("deckcraft-fonts-flatpak-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&root); + std::fs::create_dir_all(&root).unwrap(); + let file = root.join("fonts.conf"); + std::fs::write(&file, "/run/host/user-fonts/run/host/user-fonts").unwrap(); + let env = FontEnv { os: Os::Unix, root: root.clone(), flatpak: true, fontconfig_file: Some(file), ..FontEnv::default() }; + for directory in ["run/host/fonts", "run/host/local-fonts", "run/host/user-fonts"] { + assert_fixture_discovered_after_rescan(env.clone(), &root.join(directory)); + } + let _ = std::fs::remove_dir_all(root); } } diff --git a/crates/fonts/src/lib.rs b/crates/fonts/src/lib.rs index 0bb0edb50..7aea1153a 100644 --- a/crates/fonts/src/lib.rs +++ b/crates/fonts/src/lib.rs @@ -16,7 +16,6 @@ mod shape; pub use fallback::{bundled_families, covers_cluster, is_emoji_cluster, ligature_carets}; pub use fontdb::{ FALLBACK_FAMILY, FaceRef, FontDb, FontFace, LAST_RESORT_FAMILY, MISSING_FONT_FAMILY, base_style, bundled, is_monospace_family, substitutes, - system_font_dirs, }; pub use harfrust::Feature; use harfrust::Tag; diff --git a/crates/fonts/src/tests.rs b/crates/fonts/src/tests.rs index e7a3f064d..9566855cd 100644 --- a/crates/fonts/src/tests.rs +++ b/crates/fonts/src/tests.rs @@ -111,6 +111,31 @@ fn concurrent_lookups_all_find_an_installed_family() { let _ = std::fs::remove_dir_all(&dir); } +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn catalog_rescan_discovers_new_families_and_retries_missing_styles() { + let dir = std::env::temp_dir().join(format!("deckcraft-fonts-rescan-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let db = FontDb::with_font_dirs(vec![dir.clone()]); + let isolated = FontDb::with_font_dirs(Vec::new()); + assert!(!db.has_family("DeckCraft Legacy")); + let missing = db.face("DeckCraft Legacy", "Semibold"); + std::fs::write(dir.join("regular.ttf"), include_bytes!("../tests/fixtures/legacy-regular.ttf")).unwrap(); + db.load_system_fonts(); + assert!(db.families().iter().any(|family| family == "DeckCraft Legacy")); + let regular = db.face("DeckCraft Legacy", "Semibold"); + assert_ne!(regular.family, missing.family); + assert!(!isolated.has_family(®ular.family)); + std::fs::write(dir.join("semibold.ttf"), include_bytes!("../tests/fixtures/legacy-semibold.ttf")).unwrap(); + db.load_system_fonts(); + let semibold = db.face("DeckCraft Legacy", "Semibold"); + assert_eq!(semibold.family, regular.family); + assert!(semibold.weight > regular.weight); + assert_ne!(semibold.id(), regular.id()); + let _ = std::fs::remove_dir_all(dir); +} + #[test] fn windows_family_names_find_their_faces() { // Documents name fonts by their Windows family ("Segoe UI Semibold"); the font's @@ -410,7 +435,8 @@ fn the_font_scan_skips_fifos_folders_and_link_loops() { let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(dir.join("sub")).unwrap(); std::fs::copy(std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/legacy-semibold.ttf"), dir.join("sub/real.ttf")).unwrap(); - let fifo = std::process::Command::new("mkfifo").arg(dir.join("trap.ttf")).status().is_ok_and(|s| s.success()); + // Hosts without mkfifo still exercise the other hostile directory entries. + let _ = std::process::Command::new("mkfifo").arg(dir.join("trap.ttf")).status(); std::fs::create_dir(dir.join("folder.ttf")).unwrap(); std::fs::write(dir.join("empty.otf"), b"").unwrap(); std::os::unix::fs::symlink(&dir, dir.join("sub/loop")).unwrap(); @@ -418,11 +444,16 @@ fn the_font_scan_skips_fifos_folders_and_link_loops() { let scan_dir = dir.clone(); std::thread::spawn(move || { let db = FontDb::with_font_dirs(vec![scan_dir]); - let _ = tx.send(db.load_system_fonts()); + db.load_system_fonts(); + // Bundled faces also belong to the catalogue, so its size cannot prove discovery. + let found = db.has_family("DeckCraft Legacy Semibold"); + let face = db.face("DeckCraft Legacy Semibold", "Regular"); + let drawable = face.covers('A') && !db.outline(&face, face.glyph_for('A')).elements().is_empty(); + let _ = tx.send((found, drawable)); }); - let n = rx.recv_timeout(std::time::Duration::from_secs(30)).expect("the font scan hung"); - assert!(n >= 1, "the real font was found"); - assert!(fifo || n >= 1); + let (found, drawable) = rx.recv_timeout(std::time::Duration::from_secs(30)).expect("the font scan hung"); + assert!(found, "the real font was found"); + assert!(drawable, "the discovered face supplies a drawable glyph"); let _ = std::fs::remove_dir_all(&dir); } diff --git a/crates/format/src/rtf.rs b/crates/format/src/rtf.rs index d93aedee0..184d6e40d 100644 --- a/crates/format/src/rtf.rs +++ b/crates/format/src/rtf.rs @@ -113,6 +113,9 @@ struct Outline { /// non-ASCII `Token::Symbol`. skip_cont: usize, line: String, + /// The document's code page (`\ansicpg`), which `\'hh` bytes are in: Windows-1252 until it + /// names another single-byte one (#2394). + code_page: u16, /// Paragraphs so far: outline level and text (empty only for an empty level-0 title). out: Vec<(usize, String)>, } @@ -199,6 +202,7 @@ fn paragraphs(rtf: &str) -> Vec<(usize, String)> { pending_skip: 0, skip_cont: 0, line: String::new(), + code_page: 1252, out: vec![], }; p.run(rtf); @@ -273,6 +277,12 @@ impl Outline { self.style_level = arg.filter(|a| (1..=9).contains(a) && self.headings[*a as usize]).map(|a| a as u32 - 1); } "li" => self.indent = i64::from(arg.unwrap_or(0)), + // A code page read a byte at a time; any other (East Asian multibyte, unknown) keeps Windows-1252. + "ansicpg" => { + if let Some(cp) = arg.and_then(|a| u16::try_from(a).ok()).filter(|cp| craft_rtf::codepage::is_byte_code_page(*cp)) { + self.code_page = cp; + } + } "tab" | "line" => self.line.push(' '), "uc" => self.st.uc = arg.unwrap_or(1).clamp(0, 8) as usize, "u" => self.unicode(i64::from(arg.unwrap_or(0))), @@ -294,14 +304,14 @@ impl Outline { self.pending_skip = self.st.uc; } - /// `\'hh`: one cp1252 byte. + /// `\'hh`: one byte in the document's code page. fn hex_escape(&mut self, h: u8) { if self.pending_skip > 0 { self.pending_skip -= 1; return; } if !self.st.skip && h != 0 { - self.line.push(craft_rtf::codepage::cp1252(h)); + self.line.push(craft_rtf::codepage::code_page_byte(self.code_page, h)); } } @@ -621,6 +631,28 @@ mod tests { assert_eq!(crate::slides_to_outline(&reopened), expected); } + /// A writer on a non-Western Windows locale names its code page with `\ansicpg` and writes + /// non-ASCII letters as `\'hh` bytes of that page (#2394); `\ansicpg1252` and no `\ansicpg` + /// both stay Windows-1252. + #[test] + fn hex_escapes_decode_in_the_code_page_ansicpg_names() { + let outline = |cpg: &str, title: &str, body: &str| { + let rtf = format!( + r"{{\rtf1\ansi{cpg}{{\stylesheet{{\s1 heading 1;}}{{\s2 heading 2;}}}}\pard\s1 {title}\par\pard\s2 {body}\par\pard\s1 Plain\par}}" + ); + let mut p = deckcraft_model::defaults::blank_presentation(deckcraft_model::defaults::WIDE, Default::default(), false); + assert_eq!(rtf_to_slides(&mut p, &rtf), 2, "{rtf}"); + crate::slides_to_outline(&p) + }; + assert_eq!( + outline(r"\ansicpg1250", r"\'8elu\'9dou\'e8k\'fd k\'f9\'f2", r"\'dap\'ecl \'ef\'e1belsk\'e9 \'f3dy"), + "Žluťoučký kůň\n\tÚpěl ďábelské ódy\nPlain\n" + ); + assert_eq!(outline(r"\ansicpg1251", r"\'cf\'f0\'e8\'e2\'e5\'f2", r"\'ec\'e8\'f0"), "Привет\n\tмир\nPlain\n"); + assert_eq!(outline(r"\ansicpg1252", r"Caf\'e9", r"\'93a\'94"), "Café\n\t“a”\nPlain\n"); + assert_eq!(outline("", r"Caf\'e9", r"\'93a\'94"), "Café\n\t“a”\nPlain\n"); + } + #[test] fn export_writes_heading_styles() { let mut p = deckcraft_model::defaults::blank_presentation(deckcraft_model::defaults::WIDE, Default::default(), false); diff --git a/crates/mcp/Cargo.toml b/crates/mcp/Cargo.toml index 3b9e1254f..ac7bf3aa9 100644 --- a/crates/mcp/Cargo.toml +++ b/crates/mcp/Cargo.toml @@ -9,6 +9,7 @@ description = "DeckCraft MCP server: JSON-RPC 2.0 over stdio, driving a running workspace = true [dependencies] +craft = { workspace = true, features = ["automation"] } craft-mcp-server = { workspace = true } deckcraft-engine = { workspace = true } deckcraft-render = { workspace = true } diff --git a/crates/mcp/src/backend.rs b/crates/mcp/src/backend.rs index fb809c09c..363107f0e 100644 --- a/crates/mcp/src/backend.rs +++ b/crates/mcp/src/backend.rs @@ -1,14 +1,11 @@ //! Where MCP tool calls end up: a control-channel method call. -use std::io::{BufRead, BufReader, Read, Write}; -use std::net::{TcpStream, ToSocketAddrs}; -use std::time::Duration; +#[cfg(not(target_arch = "wasm32"))] +use std::net::ToSocketAddrs; -use serde_json::{Value, json}; - -// Includes the newline, matching the control server's request budget. In particular a peer -// must not be able to grow a reply indefinitely by withholding its newline. -const MAX_REPLY_BYTES: u64 = 16 * 1024 * 1024; +#[cfg(not(target_arch = "wasm32"))] +use craft::automation::client::{ConnectError, ControlClient}; +use serde_json::Value; /// Something that answers control-channel methods (`engine.execute`, `document.inspect`, /// `ui.pointer`, `ui.render`, …). See `deckcraft_ui_egui::control` for the full list. @@ -21,122 +18,64 @@ pub trait Backend { fn describe(&self) -> String; } -/// A running DeckCraft app, reached through its loopback control port. +#[cfg(not(target_arch = "wasm32"))] +/// A running DeckCraft app, reached through its authenticated loopback control port. pub struct Remote { addr: String, - conn: Option<(BufReader, TcpStream)>, - next_id: u64, + token: String, + client: Option, } +#[cfg(not(target_arch = "wasm32"))] impl Remote { - /// Connect to `addr` (`127.0.0.1:7979`), failing fast when nothing is listening. - pub fn connect(addr: &str) -> std::io::Result { - let mut r = Self { addr: addr.to_string(), conn: None, next_id: 1 }; - r.reconnect()?; - Ok(r) + /// Authenticate with `token` at `addr` (`127.0.0.1:7979`), failing fast when nothing is listening. + pub fn connect(addr: &str, token: &str) -> std::io::Result { + let client = Self::connect_client(addr, token)?; + Ok(Self { addr: addr.to_string(), token: token.to_string(), client: Some(client) }) } + /// The control-channel address used for connections. pub fn addr(&self) -> &str { &self.addr } - fn reconnect(&mut self) -> std::io::Result<()> { - self.conn = None; - let mut last = std::io::Error::new(std::io::ErrorKind::NotFound, format!("cannot resolve {}", self.addr)); - for sa in self.addr.to_socket_addrs()? { - match TcpStream::connect_timeout(&sa, Duration::from_millis(800)) { - Ok(s) => { - s.set_nodelay(true).ok(); - // The app answers within 60 s (its own timeout); leave headroom. - s.set_read_timeout(Some(Duration::from_secs(90))).ok(); - let read = s.try_clone()?; - self.conn = Some((BufReader::new(read), s)); - return Ok(()); + fn connect_client(addr: &str, token: &str) -> std::io::Result { + let mut last = std::io::Error::new(std::io::ErrorKind::NotFound, format!("cannot resolve {addr}")); + for address in addr.to_socket_addrs()? { + match ControlClient::connect(address, token) { + Ok(client) => return Ok(client), + Err(error @ ConnectError::Refused(_)) => { + return Err(std::io::Error::new(std::io::ErrorKind::PermissionDenied, error.to_string())); } - Err(e) => last = e, + Err(error) => last = std::io::Error::other(error.to_string()), } } Err(last) } - - /// Write one request line. A failure here means the app never got a complete line, so retrying is safe. - /// A connection the app has already closed (it restarted since the last call) is replaced before writing. - fn send(&mut self, line: &str) -> std::io::Result<()> { - if self.conn.as_ref().is_none_or(|(reader, writer)| !reader.buffer().is_empty() || is_closed(writer)) { - self.reconnect()?; - } - let Some((_, writer)) = self.conn.as_mut() else { - return Err(std::io::Error::new(std::io::ErrorKind::NotConnected, "not connected")); - }; - writer.write_all(format!("{line}\n").as_bytes())?; - writer.flush() - } - - /// Read the reply to a request that was already sent. - fn receive(&mut self, id: u64) -> std::io::Result> { - let Some((reader, _)) = self.conn.as_mut() else { - return Err(std::io::Error::new(std::io::ErrorKind::NotConnected, "not connected")); - }; - let mut reply = Vec::new(); - reader.take(MAX_REPLY_BYTES + 1).read_until(b'\n', &mut reply)?; - if reply.len() as u64 > MAX_REPLY_BYTES { - return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "control reply exceeds 16 MiB")); - } - if reply.last() != Some(&b'\n') { - return Err(std::io::Error::new(std::io::ErrorKind::UnexpectedEof, "control reply has no terminating newline")); - } - let invalid = |message| std::io::Error::new(std::io::ErrorKind::InvalidData, message); - let v: Value = serde_json::from_slice(&reply).map_err(|e| invalid(format!("bad reply from app: {e}")))?; - if v.get("id").and_then(Value::as_u64) != Some(id) { - return Err(invalid("control reply has an unexpected request id".to_string())); - } - match v.get("ok").and_then(Value::as_bool) { - Some(true) if v.get("error").is_none() => { - v.get("result").cloned().map(Ok).ok_or_else(|| invalid("successful control reply has no result".to_string())) - } - Some(false) if v.get("result").is_none() => v - .get("error") - .and_then(Value::as_str) - .map(|error| Err(error.to_string())) - .ok_or_else(|| invalid("failed control reply has no error string".to_string())), - _ => Err(invalid("control reply has an invalid envelope".to_string())), - } - } -} - -/// True when the peer has closed or reset `stream`, or sent bytes nobody asked for. Between calls nothing -/// should be waiting, so only "would block" means the connection is still good. -fn is_closed(stream: &TcpStream) -> bool { - if stream.set_nonblocking(true).is_err() { - return true; - } - let mut byte = [0u8; 1]; - let open = matches!(stream.peek(&mut byte), Err(e) if e.kind() == std::io::ErrorKind::WouldBlock); - stream.set_nonblocking(false).is_err() || !open } +#[cfg(not(target_arch = "wasm32"))] impl Backend for Remote { fn call(&mut self, method: &str, params: Value) -> Result { - let id = self.next_id; - self.next_id += 1; - let line = json!({"id": id, "method": method, "params": params}).to_string(); - // One retry with a fresh connection (the app may have restarted), but only while the request - // was not sent. Once it is out, a lost reply leaves the outcome unknown and a resend could - // run an insert/delete/undo twice, so report that instead. - if self.send(&line).is_err() { - self.conn = None; - self.send(&line).map_err(|e| { - self.conn = None; - format!("DeckCraft app at {} is not reachable: {e}", self.addr) - })?; + // Replacing an unusable connection before sending cannot replay a mutation. + if self.client.as_ref().is_none_or(|client| !client.is_usable()) { + self.client = None; + self.client = Some( + Self::connect_client(&self.addr, &self.token).map_err(|error| format!("DeckCraft app at {} is not reachable: {error}", self.addr))?, + ); + } + let client = self.client.as_mut().ok_or_else(|| format!("DeckCraft app at {} is not connected", self.addr))?; + match client.call(method, params) { + Err(error) if client.is_broken() => { + // Once sent, a lost reply leaves the outcome unknown; replay could apply the edit twice. + self.client = None; + Err(format!( + "lost the reply from the DeckCraft app at {} ({error}); the command may or may not have run, check the document before retrying", + self.addr + )) + } + result => result, } - self.receive(id).map_err(|e| { - self.conn = None; - format!( - "lost the reply from the DeckCraft app at {} ({e}); the command may or may not have run, check the document before retrying", - self.addr - ) - })? } fn has_ui(&self) -> bool { @@ -149,172 +88,72 @@ impl Backend for Remote { } #[cfg(test)] +#[cfg(not(target_arch = "wasm32"))] mod tests { use super::*; - use std::net::TcpListener; - use std::sync::Arc; - use std::sync::atomic::{AtomicUsize, Ordering}; + use serde_json::json; + use std::io::{BufRead, BufReader, Write}; + use std::net::{TcpListener, TcpStream}; + use std::time::Duration; - fn reply_once(reply: Vec) -> (Remote, std::thread::JoinHandle<()>) { - let listener = TcpListener::bind("127.0.0.1:0").expect("bind"); - let addr = listener.local_addr().expect("addr").to_string(); - let peer = std::thread::spawn(move || { - let (mut stream, _) = listener.accept().expect("accept"); - stream.set_read_timeout(Some(Duration::from_secs(5))).expect("timeout"); - stream.set_write_timeout(Some(Duration::from_secs(5))).expect("write timeout"); + const TOKEN: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"; + + fn authenticate(stream: TcpStream) -> BufReader { + stream.set_read_timeout(Some(Duration::from_secs(5))).expect("read timeout"); + stream.set_write_timeout(Some(Duration::from_secs(5))).expect("write timeout"); + let mut reader = BufReader::new(stream); + let mut line = String::new(); + reader.read_line(&mut line).expect("auth request"); + reader.get_mut().write_all(b"{\"id\":1,\"ok\":true,\"result\":{\"authenticated\":true}}\n").expect("auth reply"); + reader + } + + fn request(reader: &mut BufReader) -> Value { + let mut line = String::new(); + reader.read_line(&mut line).expect("request"); + serde_json::from_str(&line).expect("request JSON") + } + + fn answer(reader: &mut BufReader, request: &Value) { + writeln!(reader.get_mut(), "{}", json!({"id": request["id"], "ok": true, "result": null})).expect("reply"); + } + + fn answer_until_closed(mut reader: BufReader) -> Vec { + let mut calls = Vec::new(); + loop { let mut line = String::new(); - BufReader::new(&stream).read_line(&mut line).expect("request"); - assert_eq!(serde_json::from_str::(&line).expect("JSON")["id"], 1); - // An oversized reply may be rejected before the peer finishes writing it. - let _ = stream.write_all(&reply); - }); - (Remote::connect(&addr).expect("connect"), peer) - } - - #[test] - fn wrong_reply_id_is_not_command_success() { - let (mut remote, peer) = reply_once(b"{\"id\":999,\"ok\":true,\"result\":\"unrelated\"}\n".to_vec()); - let result = remote.call("engine.execute", json!({"command":"slide.new"})); - peer.join().expect("peer"); - let error = result.expect_err("an unrelated reply cannot confirm a mutation"); - assert!(error.contains("may or may not have run"), "{error}"); - assert!(remote.conn.is_none(), "discard the invalid connection without replaying"); - } - - #[test] - fn matching_success_and_error_replies_keep_their_meaning() { - for (reply, expected) in [ - ("{\"id\":1,\"ok\":true,\"result\":null}\r\n", Ok(Value::Null)), - ("{\"id\":1,\"ok\":true,\"result\":{\"slides\":2}}\n", Ok(json!({"slides":2}))), - ("{\"id\":1,\"ok\":false,\"error\":\"disabled\"}\n", Err("disabled".into())), - ] { - let (mut remote, peer) = reply_once(reply.as_bytes().to_vec()); - assert_eq!(remote.call("engine.execute", json!({})), expected); - assert!(remote.conn.is_some(), "valid responses do not invalidate the connection"); - peer.join().expect("peer"); - } - } - - #[test] - fn malformed_reply_envelopes_leave_the_outcome_unknown() { - for reply in [ - "not JSON\n", - "[]\n", - "{\"ok\":true,\"result\":null}\n", - "{\"id\":\"1\",\"ok\":true,\"result\":null}\n", - "{\"id\":1,\"ok\":1,\"result\":null}\n", - "{\"id\":1,\"ok\":true}\n", - "{\"id\":1,\"ok\":false}\n", - "{\"id\":1,\"ok\":false,\"error\":42}\n", - "{\"id\":1,\"ok\":true,\"result\":null,\"error\":\"failed\"}\n", - "{\"id\":1,\"ok\":false,\"result\":null,\"error\":\"failed\"}\n", - ] { - let (mut remote, peer) = reply_once(reply.as_bytes().to_vec()); - let result = remote.call("engine.execute", json!({})); - peer.join().expect("peer"); - let error = result.expect_err(reply); - assert!(error.contains("may or may not have run"), "{reply}: {error}"); - assert!(remote.conn.is_none(), "{reply}: discard the invalid connection"); - } - } - - #[test] - fn eof_without_a_newline_is_not_a_complete_reply() { - let (mut remote, peer) = reply_once(b"{\"id\":1,\"ok\":true,\"result\":null}".to_vec()); - let result = remote.call("engine.execute", json!({})); - peer.join().expect("peer"); - assert!(result.is_err(), "a truncated frame cannot confirm a mutation"); - assert!(remote.conn.is_none()); - } - - #[test] - fn oversized_reply_is_rejected() { - let reply = format!("{{\"id\":1,\"ok\":true,\"result\":\"{}\"}}\n", "x".repeat(16 * 1024 * 1024)); - let (mut remote, peer) = reply_once(reply.into_bytes()); - let result = remote.call("engine.execute", json!({})); - let invalidated = remote.conn.is_none(); - // Close the socket before joining: the bounded reader need not drain the peer's reply. - remote.conn = None; - peer.join().expect("peer"); - assert!(result.is_err(), "a reply is limited to 16 MiB"); - let error = result.expect_err("checked above"); - assert!(error.contains("may or may not have run"), "{error}"); - assert!(invalidated, "discard the oversized reply's connection"); - } - - #[test] - fn reply_at_the_size_limit_is_accepted() { - let prefix = "{\"id\":1,\"ok\":true,\"result\":\""; - let suffix = "\"}\n"; - let payload_len = 16 * 1024 * 1024 - prefix.len() - suffix.len(); - let reply = format!("{prefix}{}{suffix}", "x".repeat(payload_len)); - let (mut remote, peer) = reply_once(reply.into_bytes()); - let result = remote.call("document.inspect", json!({})).expect("reply at the limit"); - assert_eq!(result.as_str().map(str::len), Some(payload_len)); - peer.join().expect("peer"); - } - - #[test] - fn buffered_unsolicited_reply_is_discarded_before_sending() { - let listener = TcpListener::bind("127.0.0.1:0").expect("bind"); - let addr = listener.local_addr().expect("addr").to_string(); - let peer = std::thread::spawn(move || { - let (mut first, _) = listener.accept().expect("first connection"); - first.set_read_timeout(Some(Duration::from_secs(5))).expect("timeout"); - let mut line = String::new(); - BufReader::new(&first).read_line(&mut line).expect("initial request"); - // Even a stale frame whose ID happens to match must not answer a new request. - first - .write_all(b"{\"id\":1,\"ok\":true,\"result\":\"first\"}\n{\"id\":2,\"ok\":true,\"result\":\"stale\"}\n") - .expect("two replies together"); - line.clear(); - let sent_on_stale = BufReader::new(&first).read_line(&mut line).expect("first request") != 0; - if !sent_on_stale { - let (mut fresh, _) = listener.accept().expect("fresh connection"); - fresh.set_read_timeout(Some(Duration::from_secs(5))).expect("timeout"); - BufReader::new(&fresh).read_line(&mut line).expect("fresh request"); - fresh.write_all(b"{\"id\":2,\"ok\":false,\"error\":\"rejected\"}\n").expect("actual reply"); + if reader.read_line(&mut line).expect("request or EOF") == 0 { + return calls; } - sent_on_stale - }); - let mut remote = Remote::connect(&addr).expect("connect"); - assert_eq!(remote.call("document.inspect", json!({})), Ok(json!("first"))); - // Force the stale frame into BufReader, where a socket-only peek cannot see it. - assert!(!remote.conn.as_mut().expect("connection").0.fill_buf().expect("buffer").is_empty()); - let result = remote.call("engine.execute", json!({"command":"slide.new"})); - let sent_on_stale = peer.join().expect("peer"); - assert_eq!(result, Err("rejected".into()), "only the fresh peer's response counts"); - assert!(!sent_on_stale, "replace a connection with buffered unsolicited bytes before sending"); + let call = serde_json::from_str(&line).expect("request JSON"); + answer(&mut reader, &call); + calls.push(call); + } } #[test] fn lost_reply_is_not_resent() { let listener = TcpListener::bind("127.0.0.1:0").expect("bind"); let addr = listener.local_addr().expect("addr").to_string(); - let executed = Arc::new(AtomicUsize::new(0)); - let count = Arc::clone(&executed); - std::thread::spawn(move || { - for stream in listener.incoming().flatten() { - let mut reader = BufReader::new(&stream); - let mut line = String::new(); - if reader.read_line(&mut line).unwrap_or(0) == 0 { - continue; - } - let n = count.fetch_add(1, Ordering::SeqCst) + 1; - if n > 1 { - let mut w = &stream; - let _ = w.write_all(b"{\"id\":2,\"ok\":true,\"result\":null}\n"); - } - // The first request is executed, then the connection drops without a reply. - } + let peer = std::thread::spawn(move || { + let mut first = authenticate(listener.accept().expect("first connection").0); + let mutation = request(&mut first); + drop(first); + let fresh = authenticate(listener.accept().expect("fresh connection").0); + let mut calls = vec![mutation]; + calls.extend(answer_until_closed(fresh)); + calls }); - let mut remote = Remote::connect(&addr).expect("connect"); - let err = remote.call("engine.execute", json!({})).expect_err("lost reply must be an error"); - assert!(err.contains("may or may not have run"), "{err}"); - assert_eq!(executed.load(Ordering::SeqCst), 1, "the command must not be replayed"); - // The next call opens a fresh connection and works. - assert!(remote.call("document.inspect", json!({})).is_ok()); - assert_eq!(executed.load(Ordering::SeqCst), 2); + let mut remote = Remote::connect(&addr, TOKEN).expect("connect"); + let mutation = "engine.execute"; + let inspection = "document.inspect"; + let error = remote.call(mutation, json!({"command": "slide.new"})).expect_err("lost reply must be an error"); + assert!(error.contains("may or may not have run"), "{error}"); + assert!(remote.call(inspection, json!({})).is_ok()); + drop(remote); + let calls = peer.join().expect("peer"); + let methods: Vec<_> = calls.iter().map(|call| call["method"].clone()).collect(); + assert_eq!(methods, vec![json!(mutation), json!(inspection)], "a lost mutation must not be replayed"); } #[test] @@ -322,32 +161,23 @@ mod tests { let listener = TcpListener::bind("127.0.0.1:0").expect("bind"); let addr = listener.local_addr().expect("addr").to_string(); let (closed_tx, closed_rx) = std::sync::mpsc::channel(); - let executed = Arc::new(AtomicUsize::new(0)); - let count = Arc::clone(&executed); - std::thread::spawn(move || { - let mut first = true; - for stream in listener.incoming().flatten() { - if first { - // The app restarts: the first connection closes before any request arrives. - first = false; - drop(stream); - let _ = closed_tx.send(()); - continue; - } - let mut reader = BufReader::new(&stream); - let mut line = String::new(); - if reader.read_line(&mut line).unwrap_or(0) == 0 { - continue; - } - count.fetch_add(1, Ordering::SeqCst); - let mut w = &stream; - let _ = w.write_all(b"{\"id\":1,\"ok\":true,\"result\":null}\n"); - } + let peer = std::thread::spawn(move || { + let first = authenticate(listener.accept().expect("first connection").0); + first.get_ref().shutdown(std::net::Shutdown::Both).expect("close first connection"); + drop(first); + closed_tx.send(()).expect("closed notification"); + let fresh = authenticate(listener.accept().expect("fresh connection").0); + answer_until_closed(fresh) }); - let mut remote = Remote::connect(&addr).expect("connect"); + let mut remote = Remote::connect(&addr, TOKEN).expect("connect"); closed_rx.recv().expect("server closed the first connection"); - std::thread::sleep(Duration::from_millis(200)); - assert!(remote.call("engine.execute", json!({})).is_ok(), "a request that never left must be sent on a fresh connection"); - assert_eq!(executed.load(Ordering::SeqCst), 1); + let method = "engine.execute"; + let params = json!({"command": "slide.new"}); + assert!(remote.call(method, params.clone()).is_ok(), "a request that never left must be sent on a fresh connection"); + drop(remote); + let calls = peer.join().expect("peer"); + assert_eq!(calls.len(), 1, "only the unsent call is sent after reconnecting"); + assert_eq!(calls[0]["method"], method); + assert_eq!(calls[0]["params"], params); } } diff --git a/crates/mcp/src/headless.rs b/crates/mcp/src/headless.rs index bd1faf09e..73751da3e 100644 --- a/crates/mcp/src/headless.rs +++ b/crates/mcp/src/headless.rs @@ -21,8 +21,8 @@ impl Default for Headless { } /// Hint appended to errors for methods that need a window. -pub(crate) const NEEDS_APP: &str = "it needs the desktop app: start `deckcraft --control 7979` and run the MCP server \ -with `deckcraft-cli mcp --connect 7979`"; +pub(crate) const NEEDS_APP: &str = "it needs the desktop app: start `deckcraft --control 7979 --control-token-file PATH` and run the MCP server \ +with `deckcraft-cli mcp --connect 7979 --control-token-file PATH`"; fn s<'a>(p: &'a Value, k: &str) -> Option<&'a str> { p.get(k).and_then(Value::as_str) @@ -154,11 +154,11 @@ impl Headless { "engine.commands" => Ok(serde_json::to_value(self.session.commands()).unwrap_or_default()), "document.inspect" => self.exec("document.inspect", &json!({})), "ui.pointer" => self.pointer(p), - "ui.key" => { + "engine.key" => { let key = s(p, "key").ok_or("missing `key`")?; self.session.key(key, mods_from(p)).map_err(|e| e.to_string()) } - "ui.text" => { + "engine.text" => { let t = s(p, "text").ok_or("missing `text`")?; self.session.type_text(t).map_err(|e| e.to_string()) } diff --git a/crates/mcp/src/lib.rs b/crates/mcp/src/lib.rs index b51ff31c7..1fc184cda 100644 --- a/crates/mcp/src/lib.rs +++ b/crates/mcp/src/lib.rs @@ -4,9 +4,9 @@ //! JSON-RPC 2.0, hand-written (no async runtime). The server exposes DeckCraft as a set of MCP //! tools and resources and forwards everything to a [`Backend`]: //! -//! - [`Remote`] talks to a running desktop app through its loopback JSON-lines control channel -//! (`deckcraft --control 7979`): one `{"id","method","params"}` line in, one -//! `{"id","ok","result"|"error"}` line out (see `docs/control-protocol.md`). +//! - `Remote` authenticates with a running desktop app's per-launch token through the framework's +//! JSON-lines control client. Start the app with `deckcraft --control 7979 --control-token-file PATH` +//! and pass that file to the client with `--control-token-file PATH` (see `docs/control-protocol.md`). //! - [`Headless`] hosts an in-process [`deckcraft_engine::Session`] and implements the //! engine-level control-channel methods itself (rendering pages with `deckcraft-render`), so //! agents can build layouts and look at them without a window. @@ -20,7 +20,9 @@ mod headless; mod server; mod tools; -pub use backend::{Backend, Remote}; +pub use backend::Backend; +#[cfg(not(target_arch = "wasm32"))] +pub use backend::Remote; pub use headless::Headless; pub use server::{PROTOCOL_VERSION, Server}; pub use tools::{ToolResult, call_tool, tool_definitions}; diff --git a/crates/mcp/src/tests.rs b/crates/mcp/src/tests.rs index 3ebf10bb9..6d41ae734 100644 --- a/crates/mcp/src/tests.rs +++ b/crates/mcp/src/tests.rs @@ -247,7 +247,11 @@ fn export_tool_lists_pdf_and_its_options() { assert!(formats.iter().any(|x| x == f), "format {f}: {export}"); } assert_eq!(props["layout"]["enum"], json!(["slides", "notes", "handouts"])); - assert_eq!(props["perPage"]["enum"], json!([1, 2, 3, 4, 6, 9])); + // Gemini function declarations accept only string enums (#2211): perPage stays a plain integer + // and the allowed values are spelled out in the description (the engine validates the set). + assert_eq!(props["perPage"]["type"], "integer"); + assert!(props["perPage"].get("enum").is_none(), "{export}"); + assert!(props["perPage"]["description"].as_str().unwrap().contains("1, 2, 3, 4, 6 or 9"), "{export}"); for p in ["dpi", "slides", "includeHidden", "textLayer", "frame", "paper", "orientation"] { assert!(props.get(p).is_some(), "{p}: {export}"); } diff --git a/crates/mcp/src/tools.rs b/crates/mcp/src/tools.rs index d09b2a439..55fdd311f 100644 --- a/crates/mcp/src/tools.rs +++ b/crates/mcp/src/tools.rs @@ -124,7 +124,7 @@ pub fn tool_definitions() -> Vec { "all": boolean("All slides (images)"), "scale": num("Pixels per point for images (default 2)"), "layout": {"type": "string", "enum": ["slides", "notes", "handouts"], "description": "PDF page layout (default slides)"}, - "perPage": {"type": "integer", "enum": [1, 2, 3, 4, 6, 9], "description": "PDF handouts: slides per page (default 6)"}, + "perPage": {"type": "integer", "description": "PDF handouts: slides per page (1, 2, 3, 4, 6 or 9; default 6)"}, "dpi": num("PDF: raster resolution of slide artwork, 36-600 (default 200)"), "slides": {"type": "array", "items": {"type": "integer", "minimum": 0}, "description": "PDF and GIF: slide indices to export, in order (default all)"}, "includeHidden": boolean("PDF and GIF: include hidden slides (default false)"), @@ -476,15 +476,15 @@ pub fn call_tool(b: &mut dyn Backend, name: &str, a: &Value) -> ToolResult { "key" => { let mut p = a.get("mods").cloned().filter(Value::is_object).unwrap_or(json!({})); p["key"] = a.get("key").cloned().unwrap_or_default(); - wrap(b.call("ui.key", p)) + wrap(b.call("engine.key", p)) } - "type_text" => wrap(b.call("ui.text", a)), + "type_text" => wrap(b.call("engine.text", a)), "screenshot" => { if !b.has_ui() { return ToolResult::error(format!("screenshot: {NEEDS_APP}. Use render_slide to see a slide headlessly.")); } - match b.call("ui.screenshot", json!({"base64": true})) { - Ok(v) => match v.get("png").and_then(Value::as_str) { + match b.call("ui.screenshot", json!({})) { + Ok(v) => match v.get("base64").and_then(Value::as_str) { Some(png) => ToolResult::image(png.to_string(), &json!({"width": v.get("width"), "height": v.get("height")})), None => ToolResult::json(&v), }, diff --git a/crates/media/src/audio.rs b/crates/media/src/audio.rs index 9f4ab3275..43d8dac48 100644 --- a/crates/media/src/audio.rs +++ b/crates/media/src/audio.rs @@ -7,9 +7,9 @@ use std::io::Cursor; use symphonia::core::audio::SampleBuffer; -use symphonia::core::codecs::{CODEC_TYPE_NULL, DecoderOptions}; +use symphonia::core::codecs::{CODEC_TYPE_NULL, Decoder, DecoderOptions}; use symphonia::core::errors::Error as SymError; -use symphonia::core::formats::FormatOptions; +use symphonia::core::formats::{FormatOptions, Track}; use symphonia::core::io::{MediaSourceStream, MediaSourceStreamOptions}; use symphonia::core::meta::MetadataOptions; use symphonia::core::probe::Hint; @@ -172,6 +172,21 @@ fn contained(f: impl FnOnce() -> Result) -> Result { const MAX_DEMUX_ERRORS: u32 = 64; fn decode_symphonia(bytes: &Bytes, ext: &str) -> Result { + decode_symphonia_capped(bytes, ext, MAX_PCM_SAMPLES) +} + +/// The track playback decodes, with its decoder: the first one a decoder can be made for (a +/// video's audio track follows its video track). The duration probe measures the same track. +fn playable_track(tracks: &[Track]) -> Option<(u32, Box)> { + let codecs = symphonia::default::get_codecs(); + tracks + .iter() + .filter(|t| t.codec_params.codec != CODEC_TYPE_NULL) + .find_map(|t| codecs.make(&t.codec_params, &DecoderOptions::default()).ok().map(|d| (t.id, d))) +} + +/// [`decode_symphonia`] stopping once `max_samples` samples have been decoded. +fn decode_symphonia_capped(bytes: &Bytes, ext: &str, max_samples: usize) -> Result { let mss = MediaSourceStream::new(Box::new(Cursor::new(Shared(bytes.clone()))), MediaSourceStreamOptions::default()); let mut hint = Hint::new(); match ext { @@ -189,14 +204,7 @@ fn decode_symphonia(bytes: &Bytes, ext: &str) -> Result { other => sym_err(other), })?; let mut format = probed.format; - let codecs = symphonia::default::get_codecs(); - // The first track we can decode (a video's audio track follows its video track). - let (track_id, mut decoder) = format - .tracks() - .iter() - .filter(|t| t.codec_params.codec != CODEC_TYPE_NULL) - .find_map(|t| codecs.make(&t.codec_params, &DecoderOptions::default()).ok().map(|d| (t.id, d))) - .ok_or(MediaError::Missing("audio track we can decode"))?; + let (track_id, mut decoder) = playable_track(format.tracks()).ok_or(MediaError::Missing("audio track we can decode"))?; let mut out: Vec = Vec::new(); let mut rate = 0; let mut channels = 0u16; @@ -245,7 +253,15 @@ fn decode_symphonia(bytes: &Bytes, ext: &str) -> Result { } if let Some(b) = buf.as_mut() { b.copy_interleaved_ref(decoded); - out.extend_from_slice(b.samples()); + // stop at the cap with whole frames, keeping what fits, like the Opus paths + let room = max_samples.saturating_sub(out.len()); + let s = b.samples(); + if s.len() > room { + let fit = room - room % (ch.max(1) as usize); + out.extend_from_slice(s.get(..fit).unwrap_or_default()); + break; + } + out.extend_from_slice(s); } } Err(SymError::DecodeError(e)) => log::debug!("audio decode: {e}"), @@ -280,6 +296,48 @@ pub(crate) fn probe_symphonia(bytes: &Bytes, ext: &str) -> Option<(String, u32, Some((name, p.sample_rate.unwrap_or(0), p.channels.map(|c| c.count() as u16).unwrap_or(0), p.n_frames)) } +/// Length in milliseconds of the track playback decodes, summed from its packet durations: the +/// file is demuxed but not decoded. `None` when the demuxer reports no durations. +pub(crate) fn demux_duration_ms(bytes: &Bytes, ext: &str) -> Option { + std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + let mss = MediaSourceStream::new(Box::new(Cursor::new(Shared(bytes.clone()))), MediaSourceStreamOptions::default()); + let mut hint = Hint::new(); + if ext != "unknown" { + hint.with_extension(ext); + } + let opts = FormatOptions { enable_gapless: true, ..Default::default() }; + let mut format = symphonia::default::get_probe().format(&hint, mss, &opts, &MetadataOptions::default()).ok()?.format; + let (id, _) = playable_track(format.tracks())?; + let tb = format.tracks().iter().find(|t| t.id == id)?.codec_params.time_base?; + let mut ticks = 0u64; + let mut errors = 0u32; + loop { + match format.next_packet() { + Ok(p) => { + errors = 0; + if p.track_id() == id { + ticks = ticks.saturating_add(p.dur); + } + } + Err(SymError::DecodeError(_)) => { + errors += 1; + if errors > MAX_DEMUX_ERRORS { + break; + } + } + Err(_) => break, + } + } + if ticks == 0 { + return None; + } + let t = tb.calc_time(ticks); + Some(t.seconds.saturating_mul(1000).saturating_add((t.frac * 1000.0).round() as u64)) + })) + .ok() + .flatten() +} + /// Interleaved PCM resampled (linear) to `rate`. pub fn resample(pcm: &Pcm, rate: u32) -> Pcm { if pcm.rate == rate || pcm.rate == 0 || rate == 0 { @@ -316,6 +374,43 @@ mod tests { assert!((r.at(101, 0) - 0.505).abs() < 1e-3); } + /// A long decode stops at the sample cap and keeps what it has, like the Opus paths, so audio + /// past the cap still plays (up to the cap) instead of failing. + #[test] + fn decode_stops_at_the_sample_cap() { + let b: Bytes = std::sync::Arc::new(std::fs::read(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/fixtures/tone.aac")).unwrap_or_default()); + let full = decode_symphonia_capped(&b, "aac", usize::MAX).unwrap(); + let capped = decode_symphonia_capped(&b, "aac", 1001).unwrap(); + assert!(full.samples.len() > 1001, "the fixture is longer than the cap"); + assert!(!capped.samples.is_empty() && capped.samples.len() <= 1001, "{}", capped.samples.len()); + assert_eq!(capped.samples.len() % capped.channels as usize, 0, "whole frames only"); + assert_eq!(capped.samples[..], full.samples[..capped.samples.len()], "the start is kept as decoded"); + } + + /// The duration is measured on the track playback decodes: the first one a decoder can be made + /// for, not the first one with any codec. + #[test] + fn duration_and_playback_pick_the_same_track() { + use symphonia::core::audio::Channels; + use symphonia::core::codecs::{CODEC_TYPE_AAC, CODEC_TYPE_OPUS, CodecParameters}; + let stereo = Channels::FRONT_LEFT | Channels::FRONT_RIGHT; + let mut opus = CodecParameters::new(); + opus.for_codec(CODEC_TYPE_OPUS).with_sample_rate(48_000).with_channels(stereo); + let mut aac = CodecParameters::new(); + aac.for_codec(CODEC_TYPE_AAC).with_sample_rate(44_100).with_channels(stereo); + let tracks = [Track::new(1, opus), Track::new(2, aac)]; + // the first track has a codec but no decoder in this build (Symphonia has no Opus decoder) + assert_ne!(tracks[0].codec_params.codec, CODEC_TYPE_NULL); + assert_eq!(playable_track(&tracks).map(|(id, _)| id), Some(2)); + } + + #[test] + fn demux_duration_matches_decoded_length() { + let b: Bytes = std::sync::Arc::new(std::fs::read(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/fixtures/tone.aac")).unwrap_or_default()); + let ms = demux_duration_ms(&b, "aac").unwrap_or(0) as i64; + assert!((ms - 500).abs() <= 60, "{ms} ms"); + } + #[test] fn wma_is_reported_unsupported() { let mut b = crate::ASF_HEADER.to_vec(); diff --git a/crates/media/src/probe.rs b/crates/media/src/probe.rs index 5a7da2aee..03b7b4f64 100644 --- a/crates/media/src/probe.rs +++ b/crates/media/src/probe.rs @@ -1,5 +1,5 @@ //! Media probing: container, duration, audio and video stream parameters — without decoding -//! (except for audio files whose container doesn't state a length). +//! (audio files whose container doesn't state a length are demuxed, not decoded). use crate::video::{codec_name, mkv_codec_name}; use crate::{ASF_HEADER, Bytes, Container, MediaError, Result}; @@ -50,9 +50,10 @@ fn ms(secs: f64) -> u64 { pub fn probe(bytes: &Bytes) -> Result { let mut info = probe_headers(bytes)?; if info.duration_ms == 0 && info.audio.as_ref().is_some_and(|a| a.decodable) && info.video.is_none() { - // No length in the header (raw MP3 / ADTS without an index): decode to measure. - if let Ok(pcm) = crate::audio::decode(bytes) { - info.duration_ms = ms(pcm.duration()); + // No length in the header (raw MP3 / ADTS without an index): add up the packet + // lengths. This only demuxes, so a long file neither allocates its PCM nor stalls the caller. + if let Some(d) = crate::audio::demux_duration_ms(bytes, Container::sniff(bytes).name()) { + info.duration_ms = d; } } Ok(info) diff --git a/crates/ppt/src/convert.rs b/crates/ppt/src/convert.rs index 3f162b36b..58e319fc1 100644 --- a/crates/ppt/src/convert.rs +++ b/crates/ppt/src/convert.rs @@ -990,13 +990,15 @@ fn xfrm(a: &draw::Anchor, m: Map, rot: f64, flip_h: bool, flip_v: bool) -> Xfrm let finite = |v: f64| if v.is_finite() { v } else { 0.0 }; let (l, t, r, b) = (finite(a.left * m.sx + m.ox), finite(a.top * m.sy + m.oy), finite(a.right * m.sx + m.ox), finite(a.bottom * m.sy + m.oy)); let (mut x, mut y, mut w, mut h) = (l.min(r), t.min(b), (r - l).abs(), (b - t).abs()); - let rot = if rot.is_finite() { rot.rem_euclid(360.0) } else { 0.0 }; - if (45.0..135.0).contains(&rot) || (225.0..315.0).contains(&rot) { + let stored_rot = if rot.is_finite() { rot.rem_euclid(360.0) } else { 0.0 }; + if (45.0..135.0).contains(&stored_rot) || (225.0..315.0).contains(&stored_rot) { let (cx, cy) = (x + w / 2.0, y + h / 2.0); std::mem::swap(&mut w, &mut h); x = cx - w / 2.0; y = cy - h / 2.0; } + // A shape flipped in exactly one direction stores its angle mirrored; undo it. + let rot = if flip_h ^ flip_v { (360.0 - stored_rot).rem_euclid(360.0) } else { stored_rot }; Xfrm { x, y, w, h, rot, flip_h, flip_v } } @@ -1072,4 +1074,35 @@ mod tests { assert_eq!(linear_angle(a), dm, "{a}"); } } + + /// [MS-ODRAW] stores the angle of a shape flipped in exactly one direction as 360° - θ. + /// The importer must undo that before writing `a:xfrm rot` (#2407). + #[test] + fn a_single_flip_mirrors_the_stored_legacy_rotation_back() { + let a = draw::Anchor { left: 0.0, top: 0.0, right: 100.0, bottom: 50.0 }; + let m = Map { sx: 1.0, sy: 1.0, ox: 0.0, oy: 0.0 }; + + // A 30° visual shape is stored as 330° with one flip. + let h = xfrm(&a, m, 330.0, true, false); + assert_eq!((h.rot, h.flip_h, h.flip_v), (30.0, true, false)); + let v = xfrm(&a, m, 330.0, false, true); + assert_eq!((v.rot, v.flip_h, v.flip_v), (30.0, false, true)); + assert_eq!(xfrm(&a, m, 30.0, true, false).rot, 330.0); + + // Both flips and no flip keep the stored angle. + assert_eq!(xfrm(&a, m, 330.0, true, true).rot, 330.0); + assert_eq!(xfrm(&a, m, 330.0, false, false).rot, 330.0); + + // A 90° visual shape is stored as 270°; the box swap still follows the stored angle. + let q = xfrm(&a, m, 270.0, true, false); + assert_eq!((q.rot, q.w, q.h), (90.0, 50.0, 100.0)); + + // The wrap is applied before the mirror. + assert_eq!(xfrm(&a, m, 360.0, true, false).rot, 0.0); + assert_eq!(xfrm(&a, m, -30.0, true, false).rot, 30.0); + + // A group's child map still applies before the flip correction. + let g = xfrm(&a, Map { sx: 2.0, sy: 3.0, ox: 10.0, oy: 20.0 }, 330.0, true, false); + assert_eq!((g.rot, g.x, g.y, g.w, g.h), (30.0, 10.0, 20.0, 200.0, 150.0)); + } } diff --git a/crates/pptx/src/convert.rs b/crates/pptx/src/convert.rs index cd9c197de..730b5d012 100644 --- a/crates/pptx/src/convert.rs +++ b/crates/pptx/src/convert.rs @@ -1280,7 +1280,11 @@ fn chart_kept_from(k: cd_chart::ChartKept) -> dm_chart::ChartKept { } fn chart_to(c: &dm_chart::Chart) -> cd_chart::Chart { + // PLAN: plan error: the sheet assigns these Chart fields here, but their P3(unowned) marker forbids replacing their initializer. let mut out = cd_chart::Chart { + // P3(unowned): earlier framework Chart fields (no contract id) + category_format: Default::default(), + date_1904: Default::default(), kind: chart_type_to(c.kind), title: c.title.clone(), categories: c.categories.clone(), @@ -1298,9 +1302,6 @@ fn chart_to(c: &dm_chart::Chart) -> cd_chart::Chart { gridlines: c.gridlines, minor_gridlines: c.minor_gridlines, axis_titles: c.axis_titles.clone(), - // DeckCraft's chart model keeps the raw category labels and the 1900 date system. - category_format: None, - date_1904: false, style: c.style, palette: c.palette.clone(), plot_fill: c.plot_fill.as_ref().map(fill_to), @@ -1340,6 +1341,8 @@ fn chart_to(c: &dm_chart::Chart) -> cd_chart::Chart { && let Some(raw) = &c.raw && let Some(parsed) = cd_chart::read::read_chart_xml(raw.as_bytes()).or_else(|| cd_chart::chartex::read_chartex_xml(raw.as_bytes())) { + out.category_format = parsed.category_format; + out.date_1904 = parsed.date_1904; out.data_table = parsed.data_table; out.first_slice_angle = parsed.first_slice_angle; out.pivot_source = parsed.pivot_source; @@ -2164,6 +2167,8 @@ pub(crate) fn pres_to_craft(p: &deckcraft_model::Presentation) -> craft_pptx::Pr media: p.media.iter().map(media_item_to).collect(), first_slide_number: p.first_slide_number, next_id: p.next_id, + // The model keeps no subset choice: a save writes whole embedded faces, as before craft-pptx read the flag. + save_subset_fonts: false, embedded_fonts: p .embedded_fonts .iter() diff --git a/crates/pptx/src/lib.rs b/crates/pptx/src/lib.rs index 941b76e66..26fbd12ff 100644 --- a/crates/pptx/src/lib.rs +++ b/crates/pptx/src/lib.rs @@ -59,10 +59,6 @@ impl craft_pptx::Defaults for DeckDefaults { Default::default() } - fn default_text_style(&self) -> craft_drawingml::text::ListStyle { - convert::list_style_to_craft(&defaults::default_text_style()) - } - fn application(&self) -> &str { "DeckCraft" } @@ -332,10 +328,164 @@ fn has_media_shapes(shapes: &[Shape]) -> bool { }) } +fn has_unpreviewed_ole_shapes(shapes: &[Shape]) -> bool { + shapes.iter().any(|s| match &s.kind { + ShapeKind::Opaque { preview: None, .. } => true, + ShapeKind::Group { children, .. } => has_unpreviewed_ole_shapes(children), + _ => false, + }) +} + +/// The VML part with Office conditional-comment markers (``) removed, so shapes wrapped in them are parsed. +fn strip_vml_conditionals(bytes: &[u8]) -> std::borrow::Cow<'_, [u8]> { + let mut out = Vec::with_capacity(bytes.len()); + let mut at = 0; + let mut changed = false; + while at < bytes.len() { + let rest = &bytes[at..]; + let marker = rest.iter().position(|b| *b == b'<').map(|i| at + i); + let Some(start) = marker else { + out.extend_from_slice(rest); + break; + }; + out.extend_from_slice(&bytes[at..start]); + let rest = &bytes[start..]; + let conditional = rest.starts_with(b"") { + next += 3; + } + at = next; + changed = true; + continue; + } + out.push(b'<'); + at = start + 1; + } + if changed { std::borrow::Cow::Owned(out) } else { std::borrow::Cow::Borrowed(bytes) } +} + +fn collect_vml_shapes<'a>(e: &'a craft_xml::El, out: &mut Vec<&'a craft_xml::El>, depth: usize) { + if depth > 64 || out.len() >= 10_000 { + return; + } + if e.is(craft_xml::Local("shape")) { + out.push(e); + } + for c in e.elements() { + collect_vml_shapes(c, out, depth + 1); + } +} + +fn vml_index(pkg: &mut craft_opc::LazyPackage, vml: &str) -> std::collections::HashMap { + let mut out = std::collections::HashMap::new(); + let Ok(Some(raw)) = pkg.read_limited(vml, craft_pptx::MAX_XML_PART as u64) else { + return out; + }; + let cleaned = strip_vml_conditionals(&raw); + let Ok(root) = craft_drawingml::xmlx::parse(&cleaned) else { + return out; + }; + let rels = pkg.rels(vml).unwrap_or_default(); + let mut shapes = Vec::new(); + collect_vml_shapes(&root, &mut shapes, 0); + for s in shapes { + let Some(img) = s.find(craft_xml::Local("imagedata")) else { continue }; + let Some(rid) = img.attr_local("relid").or_else(|| img.attr_local("id")) else { continue }; + let Some(target) = rels.target(rid) else { continue }; + let keys = [s.attr_local("spid"), s.attr_local("id")]; + for key in keys.into_iter().flatten().filter(|k| !k.is_empty()) { + out.entry(key.to_string()).or_insert_with(|| target.to_string()); + } + } + out +} + +fn collect_ole_spids(e: &craft_xml::El, out: &mut Vec<(u32, String)>, depth: usize) { + if depth > 64 || out.len() >= 10_000 { + return; + } + if e.is(craft_xml::Local("graphicFrame")) + && let Some(id) = e + .path(&[craft_xml::Local("nvGraphicFramePr"), craft_xml::Local("cNvPr")]) + .and_then(|c| c.attr_local("id")) + .and_then(craft_xml::value::to_u32_lossy) + && let Some(ole) = e.find(craft_xml::Local("oleObj")) + && let Some(spid) = ole.attr_local("spid").filter(|s| !s.is_empty()) + { + out.push((id, spid.to_string())); + } + for c in e.elements() { + collect_ole_spids(c, out, depth + 1); + } +} + +fn media_content_type(path: &str) -> &'static str { + match path.rsplit_once('.').map(|(_, ext)| ext).unwrap_or("") { + e if e.eq_ignore_ascii_case("png") => "image/png", + e if e.eq_ignore_ascii_case("jpg") || e.eq_ignore_ascii_case("jpeg") => "image/jpeg", + e if e.eq_ignore_ascii_case("gif") => "image/gif", + e if e.eq_ignore_ascii_case("svg") => "image/svg+xml", + e if e.eq_ignore_ascii_case("emf") => "image/x-emf", + e if e.eq_ignore_ascii_case("wmf") => "image/x-wmf", + _ => "application/octet-stream", + } +} + +fn apply_ole_vml_previews(pkg: &mut craft_opc::LazyPackage, slide_path: &str, se: &craft_xml::El, pres: &mut Presentation, slide_idx: usize) { + let mut ole_spids = Vec::new(); + collect_ole_spids(se, &mut ole_spids, 0); + if ole_spids.is_empty() { + return; + } + let slide_rels = pkg.rels(slide_path).unwrap_or_default(); + let vml_targets: Vec = slide_rels.all("vmlDrawing").filter(|r| !r.external).map(|r| r.target.clone()).collect(); + if vml_targets.is_empty() { + return; + } + let mut indices = Vec::new(); + for vml in &vml_targets { + indices.push(vml_index(pkg, vml)); + } + for (shape_id, spid) in ole_spids { + let needs_preview = pres + .slides + .get(slide_idx) + .and_then(|sl| deckcraft_model::find_shape(&sl.shapes, deckcraft_model::ShapeId(shape_id))) + .is_some_and(|sh| matches!(&sh.kind, ShapeKind::Opaque { preview: None, .. })); + if !needs_preview { + continue; + } + let Some(img_target) = indices.iter().find_map(|idx| idx.get(&spid)).cloned() else { + continue; + }; + let Ok(Some(img_bytes)) = pkg.read_limited(&img_target, 64 << 20) else { + continue; + }; + let name = img_target.rsplit_once('/').map_or(img_target.as_str(), |(_, n)| n).to_string(); + let ct = media_content_type(&name); + let Some(media_id) = pres.add_media(&name, ct, img_bytes) else { + continue; + }; + if let Some(slide_arc) = pres.slides.get_mut(slide_idx) + && let Some(sh) = deckcraft_model::find_shape_mut(&mut std::sync::Arc::make_mut(slide_arc).shapes, deckcraft_model::ShapeId(shape_id)) + && let ShapeKind::Opaque { preview, .. } = &mut sh.kind + { + *preview = Some(media_id); + } + } +} + fn post_import_timing(bytes: &[u8], pres: &mut Presentation) { let need_builds = has_unfolded_paragraph_builds(pres); let need_media = pres.slides.iter().any(|s| has_media_shapes(&s.shapes)); - if !need_builds && !need_media { + let need_ole = pres.slides.iter().any(|s| has_unpreviewed_ole_shapes(&s.shapes)); + if !need_builds && !need_media && !need_ole { return; } let Ok(mut pkg) = craft_opc::LazyPackage::open(bytes, &craft_pptx::LIMITS) else { @@ -354,10 +504,13 @@ fn post_import_timing(bytes: &[u8], pres: &mut Presentation) { return; }; for (i, s) in list.children(craft_xml::Local("sldId")).take(MAX_SLIDE_ENTRIES).enumerate() { - let Some(slide_arc) = pres.slides.get_mut(i) else { break }; - let Some(target) = s.attr_local("r:id").and_then(|rid| pres_rels.target(rid)) else { continue }; - let Ok(Some(sb)) = pkg.read_limited(target, craft_pptx::MAX_XML_PART as u64) else { continue }; + let Some(target) = s.attr_local("r:id").and_then(|rid| pres_rels.target(rid)).map(str::to_string) else { continue }; + let Ok(Some(sb)) = pkg.read_limited(&target, craft_pptx::MAX_XML_PART as u64) else { continue }; let Ok(se) = craft_drawingml::xmlx::parse(&sb) else { continue }; + if need_ole && pres.slides.get(i).is_some_and(|sl| has_unpreviewed_ole_shapes(&sl.shapes)) { + apply_ole_vml_previews(&mut pkg, &target, &se, pres, i); + } + let Some(slide_arc) = pres.slides.get_mut(i) else { break }; let Some(timing) = se.child(craft_xml::Local("timing")) else { continue }; if need_media && has_media_shapes(&slide_arc.shapes) { apply_media_timing(timing, &mut std::sync::Arc::make_mut(slide_arc).shapes); diff --git a/crates/pptx/tests/it/default_text_style.rs b/crates/pptx/tests/it/default_text_style.rs new file mode 100644 index 000000000..add9a43d9 --- /dev/null +++ b/crates/pptx/tests/it/default_text_style.rs @@ -0,0 +1,75 @@ +//! Presentation text defaults across PPTX import, export and reopen. + +use std::io::{Cursor, Read, Write}; + +use craft_xml::Local; +use deckcraft_model::{Presentation, defaults}; + +const PRESENTATION: &str = "ppt/presentation.xml"; + +fn imported_with_style(style_xml: &str) -> Presentation { + let base = deckcraft_pptx::export(&defaults::new_presentation(None)).expect("author fixture"); + let mut original = zip::ZipArchive::new(Cursor::new(base)).expect("open fixture package"); + let mut fixture = zip::ZipWriter::new(Cursor::new(Vec::new())); + for i in 0..original.len() { + let mut part = original.by_index(i).expect("package part"); + fixture.start_file(part.name(), zip::write::SimpleFileOptions::default()).expect("write package part"); + if part.name() == PRESENTATION { + let mut xml = String::new(); + part.read_to_string(&mut xml).expect("author fixture presentation XML"); + let start = xml.find("").expect("new decks have a populated style"); + let end_tag = ""; + let end = xml.find(end_tag).expect("end of presentation text style") + end_tag.len(); + xml.replace_range(start..end, style_xml); + fixture.write_all(xml.as_bytes()).expect("write fixture presentation XML"); + } else { + std::io::copy(&mut part, &mut fixture).expect("copy fixture part"); + } + } + let bytes = fixture.finish().expect("finish fixture package").into_inner(); + deckcraft_pptx::import(&bytes).expect("import authored fixture") +} + +fn assert_empty_after_two_saves(mut presentation: Presentation) { + assert!(presentation.default_text_style.is_empty(), "the imported style begins empty"); + for save in 1..=2 { + let bytes = deckcraft_pptx::export(&presentation).expect("save PPTX"); + let mut package = zip::ZipArchive::new(Cursor::new(&bytes)).expect("open saved package"); + let mut xml = Vec::new(); + package.by_name(PRESENTATION).expect("presentation part").read_to_end(&mut xml).expect("read presentation XML"); + let document = craft_drawingml::xmlx::parse(&xml).expect("parse saved presentation XML"); + assert!( + document.child(Local("defaultTextStyle")).is_none_or(|style| style.elements().next().is_none()), + "save {save} must not add inherited text formatting to an empty presentation style" + ); + presentation = deckcraft_pptx::import(&bytes).expect("reopen PPTX"); + assert!(presentation.default_text_style.is_empty(), "reopen {save} must retain the empty style"); + } +} + +#[test] +fn an_absent_presentation_text_style_stays_empty_after_two_saves() { + assert_empty_after_two_saves(imported_with_style("")); +} + +#[test] +fn an_empty_presentation_text_style_stays_empty_after_two_saves() { + assert_empty_after_two_saves(imported_with_style("")); +} + +#[test] +fn authored_presentation_text_styles_survive_two_saves() { + let imported = imported_with_style(r#""#); + assert_eq!(imported.default_text_style.level(0).expect("explicit level").run.kern, Some(88.0)); + let new_deck = defaults::new_presentation(None); + assert!(!new_deck.default_text_style.is_empty()); + + for mut presentation in [imported, new_deck] { + let expected = presentation.default_text_style.clone(); + for _ in 0..2 { + let bytes = deckcraft_pptx::export(&presentation).expect("save authored style"); + presentation = deckcraft_pptx::import(&bytes).expect("reopen authored style"); + assert_eq!(presentation.default_text_style, expected); + } + } +} diff --git a/crates/pptx/tests/it/main.rs b/crates/pptx/tests/it/main.rs index 6c136a37d..4d279a775 100644 --- a/crates/pptx/tests/it/main.rs +++ b/crates/pptx/tests/it/main.rs @@ -9,6 +9,7 @@ mod corpus_kinds; mod corpus_media; mod corpus_style; mod corpus_themes; +mod default_text_style; mod export_scale; mod fills; mod kept_parts; diff --git a/crates/pptx/tests/it/ole_vml.rs b/crates/pptx/tests/it/ole_vml.rs index ccdc803a2..ddaae24dd 100644 --- a/crates/pptx/tests/it/ole_vml.rs +++ b/crates/pptx/tests/it/ole_vml.rs @@ -32,6 +32,11 @@ fn deck() -> Vec { /// [`deck`] with `frames` in place of [`FRAME`]. fn deck_with(frames: &str) -> Vec { + deck_with_vml(frames, VML) +} + +/// [`deck`] with `frames` in place of [`FRAME`] and `vml` as the drawing. +fn deck_with_vml(frames: &str, vml: &str) -> Vec { let bytes = deckcraft_pptx::export(&defaults::new_presentation(None)).expect("export"); let mut z = zip::ZipArchive::new(Cursor::new(bytes)).expect("zip"); let mut out = zip::ZipWriter::new(Cursor::new(Vec::new())); @@ -55,7 +60,7 @@ fn deck_with(frames: &str) -> Vec { out.write_all(&d).expect("write"); } for (name, data) in [ - ("ppt/drawings/vmlDrawing1.vml", VML.as_bytes().to_vec()), + ("ppt/drawings/vmlDrawing1.vml", vml.as_bytes().to_vec()), ("ppt/drawings/_rels/vmlDrawing1.vml.rels", VML_RELS.as_bytes().to_vec()), ("ppt/media/other.png", png(10)), ("ppt/media/preview.png", png(200)), @@ -77,6 +82,18 @@ fn an_ole_object_without_a_picture_shows_its_vml_preview() { assert_eq!(media.name, "preview.png"); } +#[test] +fn a_vml_preview_inside_a_conditional_comment_is_found_by_its_o_spid() { + let head = &VML[..VML.find('>').expect("xml start") + 1]; + let vml = format!( + r#"{head}"# + ); + let p = deckcraft_pptx::import(&deck_with_vml(FRAME, &vml)).expect("import"); + let s = p.slides[0].shapes.iter().find(|s| s.name == "Object 3").expect("frame"); + let ShapeKind::Opaque { preview: Some(m), .. } = &s.kind else { panic!("{:?}", s.kind) }; + assert_eq!(p.media.iter().find(|x| x.id == *m).map(|x| x.name.as_str()), Some("preview.png")); +} + #[test] fn activex_controls_show_their_pictures() { let p = deckcraft_pptx::import(&deck()).expect("import"); diff --git a/crates/render/src/extent.rs b/crates/render/src/extent.rs index d5d9a2723..26c908f01 100644 --- a/crates/render/src/extent.rs +++ b/crates/render/src/extent.rs @@ -167,15 +167,20 @@ impl Region { } } +/// How far from a whole pixel an edge may be and still count as on it. +const EDGE_SLACK: f64 = 1e-3; + /// `r` (slide space) in pixels at `scale` pixels per point, rounded outwards; `None` when not finite. +/// An edge within [`EDGE_SLACK`] of a whole pixel counts as on it, so the float noise of a zoom that is +/// no exact binary fraction does not widen a slide-sized extent by a pixel. fn to_px(r: Rect, scale: f64) -> Option<(i64, i64, i64, i64)> { let lim = i32::MAX as f64 / 2.0; let px = |v: f64| if v.is_finite() { Some(v.clamp(-lim, lim)) } else { None }; Some(( - px((r.x0 * scale).floor())? as i64, - px((r.y0 * scale).floor())? as i64, - px((r.x1 * scale).ceil())? as i64, - px((r.y1 * scale).ceil())? as i64, + px((r.x0 * scale + EDGE_SLACK).floor())? as i64, + px((r.y0 * scale + EDGE_SLACK).floor())? as i64, + px((r.x1 * scale - EDGE_SLACK).ceil())? as i64, + px((r.y1 * scale - EDGE_SLACK).ceil())? as i64, )) } diff --git a/crates/render/src/paint.rs b/crates/render/src/paint.rs index 74d111236..e494f1f75 100644 --- a/crates/render/src/paint.rs +++ b/crates/render/src/paint.rs @@ -3,7 +3,7 @@ use deckcraft_color::Rgba; use deckcraft_geom::preset::FillMode; use deckcraft_model::resolve::Ctx; -use deckcraft_model::style::{ColorRef, Fill, GradientShape, PictureFill, PictureMode}; +use deckcraft_model::style::{ColorRef, Fill, GradientFlip, GradientShape, PictureFill, PictureMode}; use deckcraft_model::{PhType, Presentation}; use kurbo::{Affine, BezPath, Point, Rect, Shape as _}; use vello_cpu::{RenderContext, peniko}; @@ -51,16 +51,18 @@ pub fn fill_path( // its edges); a radial one ends on the circle around it, from a focus placed in the // shape's own box (PowerPoint's "from corner" presets centre the tile on the corner). let tile = tile_box(bounds, g.tile); - let stops: Vec<(f64, Rgba)> = g.stops.iter().map(|s| (s.pos, shade(rctx.color(&s.color, ph), mode))).collect(); - ctx.set_paint(gradient(&g.shape, stops, bounds, alpha)); - let mut stops: Vec<(f64, Rgba)> = g.stops.iter().map(|s| (s.pos.clamp(0.0, 1.0), shade(rctx.color(&s.color, ph), mode))).collect(); stops.sort_by(|a, b| a.0.total_cmp(&b.0)); // Rectangle and outline paths: rasterised (see `pathgrad`). if let GradientShape::Path { path: kind, focus } = &g.shape && matches!(kind.as_str(), "rect" | "shape") { - crate::pathgrad::fill(ctx, kind, *focus, &crate::ramp::expand(&stops), bounds, path, m, alpha); + let ramp = crate::ramp::expand(&stops); + if g.tile.iter().all(|v| *v == 0.0) { + crate::pathgrad::fill(ctx, kind, *focus, &ramp, bounds, path, m, alpha); + } else { + crate::pathgrad::fill_tiled_flipped(ctx, kind, *focus, &ramp, bounds, tile, g.flip.unwrap_or(GradientFlip::None), path, m, alpha); + } return; } // PowerPoint's ramp between stops (linear light, S-shaped), see `ramp`. diff --git a/crates/render/src/pathgrad.rs b/crates/render/src/pathgrad.rs index aef17fa81..f6800402f 100644 --- a/crates/render/src/pathgrad.rs +++ b/crates/render/src/pathgrad.rs @@ -12,6 +12,7 @@ use std::sync::Arc; use deckcraft_color::Rgba; +use deckcraft_model::style::GradientFlip; use kurbo::{Affine, BezPath, PathEl, Point, Rect}; use vello_cpu::{Pixmap, RenderContext, peniko}; @@ -62,6 +63,12 @@ pub(crate) fn fit_raster(edges: usize, pw: u32, ph: u32) -> (u32, u32) { /// focus rect `focus` (fractions inset from left, top, right, bottom), `outline` being the /// shape's flattened polygon(s) for `shape`. pub fn position(kind: &str, bounds: Rect, focus: [f64; 4], outline: &[Vec], p: Point) -> f64 { + position_in_tile(kind, bounds, bounds, focus, outline, p) +} + +/// [`position`] with the `rect` ramp ending on the edges of `tile` instead of `bounds`; the focus +/// rect is still measured in `bounds`. +fn position_in_tile(kind: &str, bounds: Rect, tile: Rect, focus: [f64; 4], outline: &[Vec], p: Point) -> f64 { let f = Rect::new( bounds.x0 + bounds.width() * focus[0].clamp(0.0, 1.0), bounds.y0 + bounds.height() * focus[1].clamp(0.0, 1.0), @@ -107,7 +114,7 @@ pub fn position(kind: &str, bounds: Rect, focus: [f64; 4], outline: &[Vec 0.0 } }; - axis(p.x, f.x0, f.x1, bounds.x0, bounds.x1).max(axis(p.y, f.y0, f.y1, bounds.y0, bounds.y1)).clamp(0.0, 1.0) + axis(p.x, f.x0, f.x1, tile.x0, tile.x1).max(axis(p.y, f.y0, f.y1, tile.y0, tile.y1)).clamp(0.0, 1.0) } } } @@ -287,15 +294,74 @@ pub fn ramp(stops: &[(f64, Rgba)]) -> Vec { /// `ramp::expand`) over `bounds`, faded by `alpha`; `m` maps the path to the output. #[allow(clippy::too_many_arguments)] pub fn fill(ctx: &mut RenderContext, kind: &str, focus: [f64; 4], stops: &[(f64, Rgba)], bounds: Rect, path: &BezPath, m: Affine, alpha: f64) { + fill_tiled(ctx, kind, focus, stops, bounds, bounds, path, m, alpha); +} + +/// [`fill`] with the gradient laid out in `tile` (the `a:tileRect` box in path units) and +/// repeated across the shape where `tile` does not cover it; a `tile` equal to `bounds` draws +/// as [`fill`] does. +#[allow(clippy::too_many_arguments)] +pub fn fill_tiled( + ctx: &mut RenderContext, + kind: &str, + focus: [f64; 4], + stops: &[(f64, Rgba)], + bounds: Rect, + tile: Rect, + path: &BezPath, + m: Affine, + alpha: f64, +) { + fill_tiled_flipped(ctx, kind, focus, stops, bounds, tile, GradientFlip::None, path, m, alpha); +} + +/// The part of `tile` a tiled gradient raster covers, with whether it repeats across and down. On +/// an axis where `tile` spans all of `cover` (the shape's box and path), the raster covers only +/// `cover` and nothing repeats on that axis; on any other axis it covers the whole tile, which +/// repeats. +pub(crate) fn tiled_sample(cover: Rect, tile: Rect) -> (Rect, bool, bool) { + let spans_x = tile.x0 <= cover.x0 && tile.x1 >= cover.x1; + let spans_y = tile.y0 <= cover.y0 && tile.y1 >= cover.y1; + let (x0, x1) = if spans_x { (cover.x0, cover.x1) } else { (tile.x0, tile.x1) }; + let (y0, y1) = if spans_y { (cover.y0, cover.y1) } else { (tile.y0, tile.y1) }; + (Rect::new(x0, y0, x1, y1), !spans_x, !spans_y) +} + +/// Fill `path` with repeated path-gradient tiles, reflecting alternate tiles along `flip` axes. +#[allow(clippy::too_many_arguments)] +pub(crate) fn fill_tiled_flipped( + ctx: &mut RenderContext, + kind: &str, + focus: [f64; 4], + stops: &[(f64, Rgba)], + bounds: Rect, + tile: Rect, + flip: GradientFlip, + path: &BezPath, + m: Affine, + alpha: f64, +) { if bounds.width() <= 0.0 || bounds.height() <= 0.0 || !bounds.is_finite() || stops.is_empty() { return; } + let tile = if tile.is_finite() && tile.width() > 0.0 && tile.height() > 0.0 { tile } else { bounds }; + let untiled = tile == bounds; + let cover = kurbo::Shape::bounding_box(path); + let cover = if cover.is_finite() { cover.union(bounds) } else { bounds }; + let (sample, repeat_x, repeat_y) = if untiled { (bounds, false, false) } else { tiled_sample(cover, tile) }; let k = crate::scale_of(m); let k = if k.is_finite() && k > 0.0 { k } else { 1.0 }; - let longest = bounds.width().max(bounds.height()) * k; - let s = (MAX_SIDE / longest).min(1.0) * k; - let (pw, ph) = (((bounds.width() * s).ceil() as u32).clamp(1, 4096), ((bounds.height() * s).ceil() as u32).clamp(1, 4096)); - let (outline, pw, ph) = if kind == "shape" { + let s = if untiled { (MAX_SIDE / (sample.width().max(sample.height()) * k)).min(1.0) * k } else { k }; + let (sx, sy) = if untiled { + (s, s) + } else { + let [a, b, c, d, _, _] = m.as_coeffs(); + let valid_scale = |v: f64| if v.is_finite() && v > 0.0 { v } else { 1.0 }; + (valid_scale(a.hypot(b)), valid_scale(c.hypot(d))) + }; + let limit = if untiled { 4096.0 } else { MAX_SIDE }; + let (pw, ph) = ((sample.width() * sx).ceil().clamp(1.0, limit) as u32, (sample.height() * sy).ceil().clamp(1.0, limit) as u32); + let (mut outline, pw, ph) = if kind == "shape" { let max_edges = edge_budget(pw, ph); let pixel = (bounds.width() / f64::from(pw)).min(bounds.height() / f64::from(ph)); let o = simplify(polygons(path), pixel, max_edges); @@ -309,13 +375,21 @@ pub fn fill(ctx: &mut RenderContext, kind: &str, focus: [f64; 4], stops: &[(f64, if kind == "shape" && outline.is_empty() { return; } + if !untiled { + for poly in &mut outline { + for p in poly { + p.x = tile.x0 + (p.x - bounds.x0) * tile.width() / bounds.width(); + p.y = tile.y0 + (p.y - bounds.y0) * tile.height() / bounds.height(); + } + } + } let lut = ramp(stops); let a = alpha.clamp(0.0, 1.0); let mut data = Vec::with_capacity((pw * ph) as usize); for j in 0..ph { for i in 0..pw { - let p = Point::new(bounds.x0 + (i as f64 + 0.5) / pw as f64 * bounds.width(), bounds.y0 + (j as f64 + 0.5) / ph as f64 * bounds.height()); - let t = position(kind, bounds, focus, &outline, p); + let p = Point::new(sample.x0 + (i as f64 + 0.5) / pw as f64 * sample.width(), sample.y0 + (j as f64 + 0.5) / ph as f64 * sample.height()); + let t = if untiled { position(kind, bounds, focus, &outline, p) } else { position_in_tile(kind, bounds, tile, focus, &outline, p) }; let c = lut.get((t * 255.0).round().clamp(0.0, 255.0) as usize).copied().unwrap_or(Rgba::BLACK); let ca = (c.a as f64 * a).round().clamp(0.0, 255.0); let mul = |v: u8| (v as f64 * ca / 255.0).round().clamp(0.0, 255.0) as u8; @@ -324,12 +398,24 @@ pub fn fill(ctx: &mut RenderContext, kind: &str, focus: [f64; 4], stops: &[(f64, } let pm = Arc::new(Pixmap::from_parts(data, pw as u16, ph as u16)); ctx.set_transform(m); - ctx.set_paint(vello_cpu::Image { - image: vello_cpu::ImageSource::Pixmap(pm), - sampler: peniko::ImageSampler { quality: peniko::ImageQuality::Medium, ..Default::default() }, - }); + let extend = |repeats: bool, reflected: bool| match (repeats, reflected) { + (false, _) => peniko::Extend::Pad, + (true, true) => peniko::Extend::Reflect, + (true, false) => peniko::Extend::Repeat, + }; + let sampler = if untiled { + peniko::ImageSampler { quality: peniko::ImageQuality::Medium, ..Default::default() } + } else { + peniko::ImageSampler { + x_extend: extend(repeat_x, matches!(flip, GradientFlip::X | GradientFlip::Xy)), + y_extend: extend(repeat_y, matches!(flip, GradientFlip::Y | GradientFlip::Xy)), + quality: peniko::ImageQuality::Medium, + ..Default::default() + } + }; + ctx.set_paint(vello_cpu::Image { image: vello_cpu::ImageSource::Pixmap(pm), sampler }); ctx.set_paint_transform( - Affine::translate(bounds.origin().to_vec2()) * Affine::scale_non_uniform(bounds.width() / pw as f64, bounds.height() / ph as f64), + Affine::translate(sample.origin().to_vec2()) * Affine::scale_non_uniform(sample.width() / pw as f64, sample.height() / ph as f64), ); ctx.fill_path(path); ctx.reset_paint_transform(); @@ -455,6 +541,48 @@ mod tests { assert!(px.chunks(4).all(|p| p[3] == 0), "nothing was painted"); } + #[test] + fn a_tile_reaching_past_the_shape_samples_only_the_shape() { + let b = Rect::new(0.0, 0.0, 400.0, 200.0); + // A corner preset's tile reaches a box up and left: nothing repeats, the shape is sampled. + assert_eq!(tiled_sample(b, Rect::new(-400.0, -200.0, 400.0, 200.0)), (b, false, false)); + // A tile inside the shape repeats on both axes. + let inner = Rect::new(100.0, 50.0, 200.0, 150.0); + assert_eq!(tiled_sample(b, inner), (inner, true, true)); + // A tile as tall as the shape and narrower repeats across only. + assert_eq!(tiled_sample(b, Rect::new(100.0, -10.0, 200.0, 210.0)), (Rect::new(100.0, 0.0, 200.0, 200.0), true, false)); + } + + #[test] + fn an_off_centre_tile_keeps_the_focus_in_the_shape_box() { + // The tile is the right half of the shape. A centred focus rect sits at the shape's centre, + // on the tile's left edge, and the ramp ends on the tile's right edge. + let b = Rect::new(0.0, 0.0, 400.0, 200.0); + let tile = Rect::new(200.0, 0.0, 400.0, 200.0); + let at = |x: f64| position_in_tile("rect", b, tile, CENTRE, &[], Point::new(x, 100.0)); + assert_eq!(at(200.0), 0.0, "the focus is at the shape's centre"); + assert!((at(300.0) - 0.5).abs() < 1e-9, "half way to the tile's right edge: {}", at(300.0)); + assert_eq!(at(400.0), 1.0, "the ramp ends on the tile's right edge"); + } + + #[test] + fn a_tile_reaching_past_the_shape_keeps_its_detail() { + // The tile is four boxes wide; the hard stop half way sits 200 pt in. The raster covers the + // shape only, so the edge stays within about a point. + let b = Rect::new(0.0, 0.0, 400.0, 200.0); + let tile = Rect::new(-1200.0, -200.0, 400.0, 200.0); + let (w, k) = (800u16, 2.0); + let stops = [(0.0, Rgba::WHITE), (0.5, Rgba::WHITE), (0.5, Rgba::BLACK), (1.0, Rgba::BLACK)]; + let mut ctx = RenderContext::new(w, 400); + fill_tiled(&mut ctx, "rect", [0.0, 0.0, 1.0, 1.0], &stops, b, tile, &b.to_path(0.1), Affine::scale(k), 1.0); + ctx.flush(); + let mut px = vec![0u8; usize::from(w) * 400 * 4]; + ctx.render(vello_cpu::PixmapMut::new(w, 400, &mut px).unwrap(), &mut vello_cpu::Resources::new()); + let red = |x: usize, y: usize| px[(y * usize::from(w) + x) * 4]; + assert!(red(397, 20) > 240, "before the edge {}", red(397, 20)); + assert!(red(403, 20) < 15, "after the edge {}", red(403, 20)); + } + #[test] fn the_ramp_runs_through_the_stops() { let stops = [(0.0, Rgba::rgb(0, 0, 0)), (0.5, Rgba::rgb(128, 128, 128)), (1.0, Rgba::rgb(255, 255, 255))]; diff --git a/crates/render/src/tests.rs b/crates/render/src/tests.rs index d94b646b0..881867693 100644 --- a/crates/render/src/tests.rs +++ b/crates/render/src/tests.rs @@ -3256,20 +3256,33 @@ fn line_chart_value_labels_are_drawn_above_their_points() { let sh = Shape { id: ShapeId(633), xfrm: Some(Xfrm::new(0.0, 0.0, 400.0, 300.0)), kind: ShapeKind::Chart(Box::new(c)), ..Default::default() }; render_slide(&deck_with(vec![sh]), 0, &RenderOpts { scale: 1.0, ..Default::default() }) }; - let red = |img: &Image| { - (0..400u32) - .flat_map(|x| (0..300u32).map(move |y| (x, y))) - .filter(|(x, y)| { - let p = img.pixel(*x, *y); - p[0] > 200 && p[1] < 60 && p[2] < 60 - }) - .count() + let is_red = |p: [u8; 4]| p[0] > 200 && p[1] < 60 && p[2] < 60; + let red = |img: &Image| (0..400u32).flat_map(|x| (0..300u32).map(move |y| (x, y))).filter(|(x, y)| is_red(img.pixel(*x, *y))).count(); + // The labels' own ink, counted as separate runs of columns, so the check holds in any interface face: every + // point gets a label of its own, whatever its glyphs weigh. + let label_runs = |off: &Image, on: &Image| { + let added: Vec = (0..400u32).map(|x| (0..300u32).any(|y| is_red(on.pixel(x, y)) && !is_red(off.pixel(x, y)))).collect(); + let mut runs = 0; + let mut gap = usize::MAX; + for inked in added { + if inked { + if gap >= 3 { + runs += 1; + } + gap = 0; + } else { + gap = gap.saturating_add(1); + } + } + runs }; for kind in [ChartType::Line, ChartType::LineMarkers] { - let (off, on) = (red(&draw(kind, false, false)), red(&draw(kind, true, false))); - assert!(on > off + 100, "{kind:?}: labels add red ink ({off} → {on})"); - let own = red(&draw(kind, true, true)); - assert!(own > off + 30, "{kind:?}: a series' own showVal shows its labels ({off} → {own})"); + let points = Chart::sample(kind).categories.len(); + let (off, on) = (draw(kind, false, false), draw(kind, true, false)); + assert!(red(&on) > red(&off), "{kind:?}: labels add red ink"); + assert!(label_runs(&off, &on) >= points, "{kind:?}: every point has its label ({} runs, {points} points)", label_runs(&off, &on)); + let own = draw(kind, true, true); + assert!(label_runs(&off, &own) >= points, "{kind:?}: a series' own showVal labels each of its points"); } // Area series keep none, and scatter and bubble series (drawn by the same code) are unchanged. for kind in [ChartType::Area, ChartType::Scatter, ChartType::Bubble] { diff --git a/crates/render/src/tests_wild.rs b/crates/render/src/tests_wild.rs index 2da29cb37..3df3096c6 100644 --- a/crates/render/src/tests_wild.rs +++ b/crates/render/src/tests_wild.rs @@ -6,7 +6,7 @@ use super::{ render_slide, trim_ends, }; use deckcraft_color::Rgba; -use deckcraft_model::style::ColorRef; +use deckcraft_model::style::{ColorRef, GradientFlip}; use deckcraft_model::{CustomPath, Geom, Presentation, Shape, ShapeId, Xfrm}; use kurbo::Shape as _; @@ -397,6 +397,92 @@ fn a_linear_gradient_spans_its_tile_rect() { assert!(img.pixel(305, 150)[0] < 15 && img.pixel(495, 150)[0] < 15, "{:?}", img.pixel(305, 150)); } +#[test] +fn a_rectangular_gradient_spans_its_tile_rect() { + let mut sh = radial([0.5; 4]); + if let Some(Fill::Gradient(g)) = &mut sh.fill { + g.shape = deckcraft_model::style::GradientShape::Path { path: "rect".into(), focus: [0.5; 4] }; + g.tile = [0.25, 0.0, 0.25, 0.0]; + } + let img = render(vec![sh]); + assert!(img.pixel(300, 200)[0] > 240, "center {:?}", img.pixel(300, 200)); + assert!(img.pixel(395, 200)[0] < 80, "tile edge {:?}", img.pixel(395, 200)); + assert!(img.pixel(450, 200)[0] > 80, "next tile {:?}", img.pixel(450, 200)); +} + +#[test] +fn a_shape_gradient_spans_its_tile_rect() { + let mut sh = radial([0.5; 4]); + sh.geom = Geom::Preset { name: "ellipse".into(), adj: vec![] }; + if let Some(Fill::Gradient(g)) = &mut sh.fill { + g.shape = deckcraft_model::style::GradientShape::Path { path: "shape".into(), focus: [0.5; 4] }; + g.tile = [0.25, 0.0, 0.25, 0.0]; + } + let img = render(vec![sh]); + assert!(img.pixel(300, 200)[0] > 240, "center {:?}", img.pixel(300, 200)); + assert!(img.pixel(395, 200)[0] < 80, "tile edge {:?}", img.pixel(395, 200)); + assert!(img.pixel(450, 200)[0] > 80, "next tile {:?}", img.pixel(450, 200)); +} + +#[test] +fn a_rectangular_gradient_reflects_alternate_tiles() { + let mut sh = radial([0.5; 4]); + if let Some(Fill::Gradient(g)) = &mut sh.fill { + g.shape = deckcraft_model::style::GradientShape::Path { path: "rect".into(), focus: [0.25, 0.5, 0.75, 0.5] }; + g.tile = [0.25, 0.0, 0.25, 0.0]; + } + let repeated = render(vec![sh.clone()]).pixel(450, 200)[0]; + if let Some(Fill::Gradient(g)) = &mut sh.fill { + g.flip = Some(GradientFlip::X); + } + let reflected = render(vec![sh]).pixel(450, 200)[0]; + assert!(repeated > reflected + 60, "repeat {repeated}, reflected {reflected}"); +} + +#[test] +fn small_rectangular_gradient_tiles_remain_distinct_in_a_large_shape() { + let mut sh = radial([0.5; 4]); + sh.xfrm = Some(Xfrm::new(100.0, 100.0, 4000.0, 200.0)); + if let Some(Fill::Gradient(g)) = &mut sh.fill { + g.shape = deckcraft_model::style::GradientShape::Path { path: "rect".into(), focus: [0.5; 4] }; + g.tile = [0.4995, 0.0, 0.4995, 0.0]; + } + let img = render(vec![sh]); + let edge = img.pixel(150, 200)[0]; + let center = img.pixel(152, 200)[0]; + assert!(i32::from(center) > i32::from(edge) + 100, "edge {edge}, center {center}"); +} + +#[test] +fn narrow_rectangular_gradient_tiles_keep_their_horizontal_ramp() { + let mut sh = radial([0.5; 4]); + sh.xfrm = Some(Xfrm::new(100.0, 100.0, 400.0, 4000.0)); + if let Some(Fill::Gradient(g)) = &mut sh.fill { + g.shape = deckcraft_model::style::GradientShape::Path { path: "rect".into(), focus: [0.5, 0.025, 0.5, 0.975] }; + g.tile = [0.495, 0.0, 0.495, 0.0]; + } + let img = render(vec![sh]); + let edge = img.pixel(150, 200)[0]; + let center = img.pixel(152, 200)[0]; + assert!(i32::from(center) > i32::from(edge) + 100, "edge {edge}, center {center}"); +} + +#[test] +fn a_scaled_group_keeps_detail_across_a_narrow_gradient_tile() { + let img = in_a_scaled_group(8.0, 0.125, Presentation::default(), |w, h| { + let mut sh = radial([0.5, 0.025, 0.5, 0.975]); + sh.xfrm = Some(Xfrm::new(0.0, 0.0, w, h)); + if let Some(Fill::Gradient(g)) = &mut sh.fill { + g.shape = deckcraft_model::style::GradientShape::Path { path: "rect".into(), focus: [0.5, 0.025, 0.5, 0.975] }; + g.tile = [0.491_666_666_666_666_64, 0.0, 0.491_666_666_666_666_64, 0.0]; + } + sh + }); + let edge = img.pixel(110, 130)[0]; + let center = img.pixel(112, 130)[0]; + assert!(i32::from(center) > i32::from(edge) + 60, "edge {edge}, center {center}"); +} + #[test] fn a_3d_pictures_border_stays_centred_on_its_edge() { let mut p = picture_deck(Some(Line::solid(ColorRef::rgb(RED), 8.0))); diff --git a/crates/text/Cargo.toml b/crates/text/Cargo.toml index c7dfa024d..9a6561c23 100644 --- a/crates/text/Cargo.toml +++ b/crates/text/Cargo.toml @@ -9,6 +9,7 @@ description = "DeckCraft text layout: runs to shaped glyph lines with bullets, i workspace = true [dependencies] +craft = { workspace = true, features = ["text"] } deckcraft-model = { workspace = true } deckcraft-geom = { workspace = true } deckcraft-color = { workspace = true } diff --git a/crates/text/src/autonum.rs b/crates/text/src/autonum.rs deleted file mode 100644 index c705f5490..000000000 --- a/crates/text/src/autonum.rs +++ /dev/null @@ -1,160 +0,0 @@ -fn roman(mut n: u32, upper: bool) -> String { - let table = [ - (1000, "m"), - (900, "cm"), - (500, "d"), - (400, "cd"), - (100, "c"), - (90, "xc"), - (50, "l"), - (40, "xl"), - (10, "x"), - (9, "ix"), - (5, "v"), - (4, "iv"), - (1, "i"), - ]; - let mut s = String::new(); - if n == 0 || n > 3999 { - return n.to_string(); - } - for (v, r) in table { - while n >= v { - s.push_str(r); - n -= v; - } - } - if upper { s.to_uppercase() } else { s } -} - -fn alpha_num(n: u32, upper: bool) -> String { - if n == 0 { - return String::new(); - } - let n = n - 1; - let c = (b'a' + (n % 26) as u8) as char; - let reps = (n / 26 + 1).min(50); - let s: String = std::iter::repeat_n(c, reps as usize).collect(); - if upper { s.to_uppercase() } else { s } -} - -/// Letters of a numbering alphabet: 1 → the first, past the end the letter doubles ("aa"), as -/// the Latin alphabetic schemes do. -fn letters(list: &[char], n: u32) -> String { - let len = list.len().max(1) as u32; - let Some(i) = n.checked_sub(1) else { return String::new() }; - let c = list.get((i % len) as usize).copied().unwrap_or('?'); - std::iter::repeat_n(c, (i / len + 1).min(50) as usize).collect() -} - -/// `n` written with the digits `zero..zero+9` (Thai, Devanagari, full-width digits). -fn digits_in(n: u32, zero: char) -> String { - n.to_string().chars().map(|d| d.to_digit(10).and_then(|v| char::from_u32(zero as u32 + v)).unwrap_or(d)).collect() -} - -const CJK_DIGITS: [char; 10] = ['〇', '一', '二', '三', '四', '五', '六', '七', '八', '九']; - -/// Chinese numerals: 10 → 十, 11 → 十一, 25 → 二十五, 105 → 一百零五. -pub(crate) fn chinese_num(n: u32) -> String { - if n == 0 || n > 99_999 { - return n.to_string(); - } - let units = ['\0', '十', '百', '千', '万']; - let ds: Vec = n.to_string().chars().filter_map(|c| c.to_digit(10)).collect(); - let mut out = String::new(); - let mut zero = false; - for (i, d) in ds.iter().enumerate() { - let place = ds.len() - 1 - i; - if *d == 0 { - zero = true; - continue; - } - if zero { - out.push('零'); - zero = false; - } - // "十" alone for 10–19, not "一十". - if !(*d == 1 && place == 1 && i == 0) { - out.push(CJK_DIGITS.get(*d as usize).copied().unwrap_or('?')); - } - if let Some(u) = units.get(place).filter(|u| **u != '\0') { - out.push(*u); - } - } - out -} - -/// Text of an auto-number bullet: `arabicPeriod` 3 → "3.". The East Asian, Thai, Hindi, Arabic -/// and Hebrew schemes are written as PowerPoint draws them: `ea1ChsPeriod` 10 → "十.", -/// `ea1JpnKorPeriod` 10 → "一〇." (digit by digit), `arabicDbPeriod` 13 → "13.", -/// `thaiAlphaParenR` 4 → "ง)", `hindiAlpha1Period` 1 → "क.", `arabic2Minus` 10 → "ي-" -/// (abjad order), `circleNumWdWhitePlain` 13 → "③" (those circles go to ten). -pub fn autonum(scheme: &str, n: u32) -> String { - const THAI: [char; 41] = [ - 'ก', 'ข', 'ค', 'ง', 'จ', 'ฉ', 'ช', 'ซ', 'ฌ', 'ญ', 'ฎ', 'ฏ', 'ฐ', 'ฑ', 'ฒ', 'ณ', 'ด', 'ต', 'ถ', 'ท', 'ธ', 'น', 'บ', 'ป', 'ผ', 'ฝ', 'พ', 'ฟ', - 'ภ', 'ม', 'ย', 'ร', 'ล', 'ว', 'ศ', 'ษ', 'ส', 'ห', 'ฬ', 'อ', 'ฮ', - ]; - const HINDI_VOWELS: [char; 11] = ['अ', 'आ', 'इ', 'ई', 'उ', 'ऊ', 'ऋ', 'ए', 'ऐ', 'ओ', 'औ']; - const HINDI_CONSONANTS: [char; 33] = [ - 'क', 'ख', 'ग', 'घ', 'ङ', 'च', 'छ', 'ज', 'झ', 'ञ', 'ट', 'ठ', 'ड', 'ढ', 'ण', 'त', 'थ', 'द', 'ध', 'न', 'प', 'फ', 'ब', 'भ', 'म', 'य', 'र', 'ल', - 'व', 'श', 'ष', 'स', 'ह', - ]; - const ARABIC_ALPHABET: [char; 28] = - ['ا', 'ب', 'ت', 'ث', 'ج', 'ح', 'خ', 'د', 'ذ', 'ر', 'ز', 'س', 'ش', 'ص', 'ض', 'ط', 'ظ', 'ع', 'غ', 'ف', 'ق', 'ك', 'ل', 'م', 'ن', 'ه', 'و', 'ي']; - const ARABIC_ABJAD: [char; 28] = - ['ا', 'ب', 'ج', 'د', 'ه', 'و', 'ز', 'ح', 'ط', 'ي', 'ك', 'ل', 'م', 'ن', 'س', 'ع', 'ف', 'ص', 'ق', 'ر', 'ش', 'ت', 'ث', 'خ', 'ذ', 'ض', 'ظ', 'غ']; - const HEBREW: [char; 22] = ['א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י', 'כ', 'ל', 'מ', 'נ', 'ס', 'ע', 'פ', 'צ', 'ק', 'ר', 'ש', 'ת']; - let circled = |first: u32, count: u32| char::from_u32(first + n.saturating_sub(1) % count).map(String::from).unwrap_or_else(|| n.to_string()); - let core = if scheme.starts_with("romanUc") { - roman(n, true) - } else if scheme.starts_with("romanLc") { - roman(n, false) - } else if scheme.starts_with("alphaUc") { - alpha_num(n, true) - } else if scheme.starts_with("alphaLc") { - alpha_num(n, false) - } else if scheme.starts_with("circleNumWdWhite") { - return circled(0x2460, 10); - } else if scheme.starts_with("circleNumWdBlack") { - return circled(0x2776, 10); - } else if scheme.starts_with("circleNum") { - return char::from_u32(0x2460 + n.saturating_sub(1).min(19)).map(String::from).unwrap_or_else(|| n.to_string()); - } else if scheme.starts_with("ea1Chs") || scheme.starts_with("ea1Cht") { - chinese_num(n) - } else if scheme.starts_with("ea1Jpn") { - n.to_string().chars().map(|d| d.to_digit(10).and_then(|v| CJK_DIGITS.get(v as usize).copied()).unwrap_or(d)).collect() - } else if scheme.starts_with("arabicDb") { - digits_in(n, '0') - } else if scheme.starts_with("thaiAlpha") { - letters(&THAI, n) - } else if scheme.starts_with("thaiNum") { - digits_in(n, '๐') - } else if scheme.starts_with("hindiAlpha1") { - letters(&HINDI_CONSONANTS, n) - } else if scheme.starts_with("hindiAlpha") { - letters(&HINDI_VOWELS, n) - } else if scheme.starts_with("hindiNum") { - digits_in(n, '०') - } else if scheme.starts_with("arabic1") { - letters(&ARABIC_ALPHABET, n) - } else if scheme.starts_with("arabic2") { - letters(&ARABIC_ABJAD, n) - } else if scheme.starts_with("hebrew2") { - letters(&HEBREW, n) - } else { - n.to_string() - }; - // East Asian schemes end with a full-width full stop. - let wide = scheme.starts_with("ea1") || scheme.starts_with("arabicDb"); - if scheme.ends_with("ParenBoth") { - format!("({core})") - } else if scheme.ends_with("ParenR") { - format!("{core})") - } else if scheme.ends_with("Period") { - format!("{core}{}", if wide { '.' } else { '.' }) - } else if scheme.ends_with("Minus") { - format!("{core}-") - } else { - core - } -} diff --git a/crates/text/src/lib.rs b/crates/text/src/lib.rs index 9e03a2b4d..e476bf592 100644 --- a/crates/text/src/lib.rs +++ b/crates/text/src/lib.rs @@ -34,7 +34,6 @@ use deckcraft_model::text::{Align, Anchor, AutoFit, BodyProps, Bullet, Caps, Par use deckcraft_model::{Fill, Shape}; use unicode_segmentation::UnicodeSegmentation; -mod autonum; mod breaking; mod layout; mod run; @@ -42,11 +41,9 @@ mod shape; mod style; mod symbol; -pub use autonum::autonum; -#[cfg(test)] -use autonum::chinese_num; #[cfg(test)] use breaking::{LINE_PITCH, break_opportunities, measure_str}; +pub use craft::text::lists::autonum; #[cfg(test)] pub(crate) use layout::LAYOUT_PASSES; pub use layout::layout; diff --git a/crates/text/src/shape.rs b/crates/text/src/shape.rs index d5558001d..1e1454024 100644 --- a/crates/text/src/shape.rs +++ b/crates/text/src/shape.rs @@ -1,7 +1,7 @@ -use super::autonum::autonum; +use super::autonum; use super::run::{RunEffects, TextShadow}; use super::style::{Cell, Opts, ParaShaped, Style, face_chain, make_style}; -use super::symbol::{covers_symbol, is_symbol_font, map_symbol_bullet, symbol_font_char, symbol_map_char}; +use super::symbol::{covers_symbol, is_symbol_font, map_symbol_bullet, symbol_fallback_char, symbol_font_char, symbol_map_char}; use super::{ Arc, Bullet, Caps, Ctx, Fill, FontDb, FontFace, FontSlot, HashMap, ParaProps, RunKind, RunProps, ScriptTag, Shape, ShapeParams, TextBody, UnicodeSegmentation, bidi, resolve, script, @@ -201,6 +201,15 @@ fn shape_cells( .filter(|f| db.has_family(f)) .map(|f| db.face(f, st.style_name)) .filter(|f| covers_symbol(f, cluster.first().copied().unwrap_or(' '))); + // Without that font, the code draws as the Unicode look-alike (not a missing-glyph box). + let mapped: Vec; + let cluster = match cluster.first().and_then(|c| symbol_fallback_char(*c, st.sym.as_deref())).filter(|_| sym_face.is_none()) { + Some(m) => { + mapped = std::iter::once(m).chain(cluster.iter().skip(1).copied()).collect(); + mapped.as_slice() + } + None => cluster, + }; let face = match (sym_face, prev.as_ref()) { (Some(f), _) => f, (None, Some(p)) @@ -246,12 +255,13 @@ fn shape_cells( } } } - // Items: maximal ranges of one level, face, script and shaping style (case mapping, language). + // Items: maximal ranges of one level, face, script and shaping style (case mapping, language, a:sym symbol font). let upper = |i: usize| styles.get(char_style.get(i).copied().unwrap_or(0)).is_some_and(|st| st.caps != Caps::None); let lang = |i: usize| styles.get(char_style.get(i).copied().unwrap_or(0)).and_then(|st| st.lang.as_deref()); let kern = |i: usize| styles.get(char_style.get(i).copied().unwrap_or(0)).is_some_and(|st| st.kern); let up = |i: usize| cells.get(i).is_some_and(|c| c.upright); - let key = |i: usize| (levels.get(i).copied(), char_face.get(i).copied(), scripts.get(i).map(|s| s.0), upper(i), lang(i), kern(i), up(i)); + let sym = |i: usize| styles.get(char_style.get(i).copied().unwrap_or(0)).and_then(|st| st.sym.as_deref()); + let key = |i: usize| (levels.get(i).copied(), char_face.get(i).copied(), scripts.get(i).map(|s| s.0), upper(i), lang(i), kern(i), up(i), sym(i)); let mut items: Vec<(usize, usize)> = Vec::new(); let mut a = 0; while a < n { @@ -391,7 +401,8 @@ fn shape_item( let sym = styles.get(first.style).and_then(|st| st.sym.as_deref()); let glyphs = deckcraft_fonts::shape_range(face, text, b0..b1, ¶ms, |ch| { let ch = if upper { caps_char(ch) } else { ch }; - symbol_map_char(face, ch, sym).unwrap_or(ch) + let own_font = sym.is_some_and(|s| face.family.eq_ignore_ascii_case(s)); + symbol_map_char(face, ch, sym).or_else(|| symbol_fallback_char(ch, sym).filter(|_| !own_font)).unwrap_or(ch) }); let upem = face.upem.max(1.0); let scale_of = |cell: &Cell| { diff --git a/crates/text/src/symbol.rs b/crates/text/src/symbol.rs index 6b6a8819b..02e5e4591 100644 --- a/crates/text/src/symbol.rs +++ b/crates/text/src/symbol.rs @@ -3,7 +3,7 @@ use super::{FontFace, UnicodeSegmentation}; /// Is `family` a symbol font (characters at U+F000 + code)? pub(crate) fn is_symbol_font(family: &str) -> bool { let f = family.to_ascii_lowercase(); - f.starts_with("wingdings") || f == "symbol" || f.starts_with("webdings") || f.starts_with("marlett") + f.starts_with("wingdings") || f == "symbol" || f.starts_with("webdings") || f.starts_with("marlett") || f.starts_with("monotype sorts") } /// Does `face` draw the symbol-font character `c` (a U+F0xx private-use code)? Either directly at @@ -30,6 +30,29 @@ pub(crate) fn symbol_map_char(face: &FontFace, ch: char, sym: Option<&str>) -> O symbol_font_draw(face, code) } +/// The Unicode look-alike that draws `ch`, a U+F0xx private-use code of the `a:sym` symbol font +/// `sym`, when that font is not installed (or does not draw the code): the characters bullets use +/// for these fonts. `None` when `ch` is not such a code, `sym` is not a symbol font, or a Symbol-font code +/// has no standard Unicode character (its fragment glyphs); Wingdings and Webdings codes without a look-alike draw as a bullet. +pub(crate) fn symbol_fallback_char(ch: char, sym: Option<&str>) -> Option { + let code = ch as u32; + if !(0xF000..=0xF0FF).contains(&code) { + return None; + } + let sym = sym?; + if !is_symbol_font(sym) { + return None; + } + let low = code & 0xFF; + if low == 0x20 { + return Some(' '); + } + if sym.eq_ignore_ascii_case("symbol") { + return symbol_unicode(low).or_else(|| (0x21..=0x7E).contains(&low).then_some(low)).and_then(char::from_u32); + } + map_symbol_bullet(&ch.to_string(), Some(sym)).chars().next() +} + /// The real-Unicode character the Symbol font's code `code` (0x00–0xFF) maps to, in the Adobe /// Symbol encoding (Unicode, Inc.'s `MAPPINGS/VENDORS/ADOBE/symbol.txt`; Apple's Mac OS Symbol /// shares this layout, with a few alternative Unicode choices — see `symbol_unicode_alts`): the @@ -277,7 +300,11 @@ pub fn map_symbol_bullet(c: &str, font: Option<&str>) -> String { } // Only the legacy symbol fonts: "Noto Sans Symbols" and the like are Unicode fonts whose // characters (❑ ❖) are drawn as they are. Private-use codes are mapped only when no font is named. - if f.contains("wingdings") || f == "symbol" || (font.is_none() && ('\u{f000}'..='\u{f0ff}').contains(&first)) { + if f.contains("wingdings") + || (f.starts_with("monotype sorts") && ((first as u32) < 0x100 || ('\u{f000}'..='\u{f0ff}').contains(&first))) + || f == "symbol" + || (font.is_none() && ('\u{f000}'..='\u{f0ff}').contains(&first)) + { let code = (first as u32) & 0xff; // Wingdings 2 and 3 put different shapes at the same codes. if f.starts_with("wingdings 2") { @@ -304,8 +331,11 @@ pub fn map_symbol_bullet(c: &str, font: Option<&str>) -> String { return m.to_string(); } let m = match code { + 0x6d if f.starts_with("monotype sorts") => '○', + 0xf0 if f.contains("wingdings") => '⇨', 0xa7 => '▪', 0xd8 => '➢', + 0xe8 => '➔', 0xfc => '✓', 0x76 => '❖', 0x71 => '❑', diff --git a/crates/text/src/tests.rs b/crates/text/src/tests.rs index cd5d82baf..7ef3e913d 100644 --- a/crates/text/src/tests.rs +++ b/crates/text/src/tests.rs @@ -1,8 +1,8 @@ use super::{ Affinity, Align, Anchor, Arc, AutoFit, BodyProps, Bullet, Caps, Cell, Ctx, Dash, Deco, DecoLine, FontDb, FontFace, GlyphRun, LINE_PITCH, - MoveMode, NoFields, Opts, ParaProps, Point, Pos, Rect, Rgba, SUB_SUPER, Shape, Spacing, Strike, TextBody, TextLayout, autonum, - break_opportunities, caps_char, chinese_num, covers_symbol, is_symbol_font, is_upright, layout, layout_scaled, map_symbol_bullet, measure_str, - resolve, shaping_features, symbol_char, symbol_font_char, symbol_font_draw, symbol_unicode, symbol_unicode_alts, + MoveMode, NoFields, Opts, ParaProps, Point, Pos, Rect, Rgba, SUB_SUPER, Shape, Spacing, Strike, TextBody, TextLayout, break_opportunities, + caps_char, covers_symbol, is_symbol_font, is_upright, layout, layout_scaled, map_symbol_bullet, measure_str, resolve, shaping_features, + symbol_char, symbol_font_char, symbol_font_draw, symbol_unicode, symbol_unicode_alts, }; use deckcraft_model::Fill; use deckcraft_model::defaults; @@ -413,16 +413,6 @@ fn empty_and_hostile_bodies_never_panic() { let _ = l.selection_rects(Pos { para: 5, ch: 0 }, Pos { para: 0, ch: 3 }); } -#[test] -fn autonum_formats() { - assert_eq!(autonum("arabicPeriod", 3), "3."); - assert_eq!(autonum("romanUcPeriod", 4), "IV."); - assert_eq!(autonum("alphaLcParenR", 2), "b)"); - assert_eq!(autonum("arabicParenBoth", 1), "(1)"); - assert_eq!(autonum("alphaUcPeriod", 27), "AA."); - assert_eq!(autonum("alphaUcPeriod", u32::MAX).len(), 51); // 50 letters + '.' -} - #[test] fn numbered_list_counts() { let (p, mut sh) = setup("a\nb\nc", 400.0, 300.0); @@ -1645,41 +1635,6 @@ fn small_kana_and_closing_brackets_follow_powerpoint_kinsoku() { assert_eq!(lines[0], "あいうえ", "{lines:?}"); } -#[test] -fn autonumber_schemes_follow_powerpoint() { - // As PowerPoint's export draws them (start values as in the probe deck). - for (scheme, n, want) in [ - ("ea1ChsPlain", 4, "四"), - ("ea1ChsPeriod", 10, "十."), - ("ea1ChtPeriod", 21, "二十一."), - ("ea1JpnKorPeriod", 10, "一〇."), - ("ea1JpnChsDbPeriod", 13, "一三."), - ("arabicDbPlain", 10, "10"), - ("arabicDbPeriod", 13, "13."), - ("circleNumDbPlain", 13, "⑬"), - ("circleNumWdWhitePlain", 13, "③"), - ("circleNumWdBlackPlain", 2, "❷"), - ("thaiAlphaPeriod", 1, "ก."), - ("thaiAlphaParenR", 4, "ง)"), - ("thaiAlphaParenBoth", 7, "(ช)"), - ("thaiNumPeriod", 10, "๑๐."), - ("hindiAlphaPeriod", 4, "ई."), - ("hindiAlpha1Period", 1, "क."), - ("hindiNumParenR", 13, "१३)"), - ("hebrew2Minus", 1, "א-"), - ("arabic1Minus", 13, "ش-"), - ("arabic2Minus", 10, "ي-"), - ("arabicPlain", 10, "10"), - ] { - assert_eq!(autonum(scheme, n), want, "{scheme} {n}"); - } - assert_eq!(chinese_num(105), "一百零五"); - assert_eq!(chinese_num(20), "二十"); - // Past the end of an alphabet the letter doubles, like "aa". - assert_eq!(autonum("hebrew2Minus", 23), "אא-"); - assert_eq!(autonum("thaiAlphaPeriod", 0), "."); -} - #[test] fn east_asian_vertical_text_marks_cjk_upright() { let (p, mut sh) = setup("日本、ABC 12", 300.0, 600.0); diff --git a/crates/text/tests/autocraft_regression_1916.rs b/crates/text/tests/autocraft_regression_1916.rs new file mode 100644 index 000000000..9ea567925 --- /dev/null +++ b/crates/text/tests/autocraft_regression_1916.rs @@ -0,0 +1,55 @@ +use deckcraft_fonts::FontDb; +use deckcraft_geom::Rect; +use deckcraft_model::defaults; +use deckcraft_model::resolve::Ctx; +use deckcraft_model::text::{Bullet, TextBody}; +use deckcraft_model::{LayoutType, Presentation, Xfrm}; +use deckcraft_text::{GlyphRun, NoFields, Opts, layout}; + +fn lay_sym(text: &str, sym: &str) -> Vec { + let mut p = Presentation::default(); + let lay = defaults::layout_of_kind(&p, LayoutType::TitleAndContent).expect("layout"); + let mut s = defaults::new_slide(&mut p, lay).expect("slide"); + let mut body = s.shapes.remove(1); + body.xfrm = Some(Xfrm::new(0.0, 0.0, 600.0, 300.0)); + body.text = Some(TextBody::from_text(text)); + let para = &mut body.text.as_mut().expect("text").paragraphs[0]; + para.props.bullet = Some(Bullet::None); + para.runs[0].props.font = Some("Arial".into()); + para.runs[0].props.font_sym = Some(sym.into()); + s.shapes = vec![body.clone()]; + p.slides = vec![std::sync::Arc::new(s)]; + let ctx = Ctx::for_slide(&p, &p.slides[0]).expect("ctx"); + let rect = Rect::new(0.0, 0.0, 600.0, 300.0); + layout(&ctx, &body, body.text.as_ref().expect("text"), &Opts { rect, fields: &NoFields, prompt_color: None, no_shrink: false }).runs +} + +#[test] +fn wingdings_arrow_without_the_sym_font_draws_the_unicode_arrow() { + let db = FontDb::global(); + if db.has_family("Wingdings") { + eprintln!("skipped: Wingdings is installed"); + return; + } + let arrow = '\u{2794}'; + let has_arrow = ["DejaVu Sans", "Noto Sans Symbols", "Noto Sans Symbols2", "Apple Symbols", "Segoe UI Symbol"] + .iter() + .any(|f| db.has_family(f) && db.face(f, "Regular").covers(arrow)); + if !has_arrow { + eprintln!("skipped: no installed font draws U+2794"); + return; + } + // U+F0E8 is Wingdings' right arrow (the issue's "F0 E8" box). + let runs = lay_sym("\u{F0E8} x", "Wingdings"); + let (run, i) = runs.iter().find_map(|r| r.cells.iter().position(|c| c.0 == 0).map(|i| (r, i))).expect("the symbol is drawn"); + let gid = run.glyphs.get(i).map(|g| g.0).expect("a glyph"); + assert_ne!(gid, 0, "the private-use code drew a missing-glyph box"); + assert_eq!(gid, run.face.glyph_for(arrow), "the code draws the arrow, not another character"); + // The Symbol font's bullet code (U+F0B7) draws its bullet, U+2022. + let runs = lay_sym("\u{F0B7} x", "Symbol"); + if let Some((run, i)) = runs.iter().find_map(|r| r.cells.iter().position(|c| c.0 == 0).map(|i| (r, i))) + && !db.has_family("Symbol") + { + assert_eq!(run.glyphs.get(i).map(|g| g.0), Some(run.face.glyph_for('\u{2022}'))); + } +} diff --git a/crates/text/tests/autocraft_regression_1935.rs b/crates/text/tests/autocraft_regression_1935.rs new file mode 100644 index 000000000..77f48211c --- /dev/null +++ b/crates/text/tests/autocraft_regression_1935.rs @@ -0,0 +1,12 @@ +use deckcraft_text::map_symbol_bullet; + +#[test] +fn monotype_sorts_m_bullet_is_open_circle() { + assert_eq!(map_symbol_bullet("m", Some("Monotype Sorts")), "\u{25CB}"); +} + +#[test] +fn wingdings_eth_bullet_is_right_arrow() { + assert_eq!(map_symbol_bullet("\u{f0}", Some("Wingdings")), "\u{21E8}"); + assert_eq!(map_symbol_bullet("\u{f0f0}", Some("Wingdings")), "\u{21E8}"); +} diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index dfcd6c5c1..b7469831b 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -9,6 +9,8 @@ description = "DeckCraft egui frontend (PowerPoint-style UI); swappable — noth workspace = true [dependencies] +craft = { workspace = true, features = ["ui", "platform", "settings", "window", "color-ui", "menu", "font-manager", "font-catalog", "review", "text", "web-host", "quit", "automation", "drawingml", "pages", "text-find", "timeline", "draw", "table", "color-ui-drawingml"] } +chrono = { workspace = true } deckcraft-geom = { workspace = true } deckcraft-color = { workspace = true } deckcraft-model = { workspace = true } @@ -19,25 +21,23 @@ deckcraft-anim = { workspace = true } deckcraft-engine = { workspace = true } deckcraft-media = { workspace = true } egui = { workspace = true, features = ["default_fonts", "monochrome_emoji_fonts"] } -egui_extras = { workspace = true } -craft-ui = { workspace = true } -craft-host = { workspace = true } -craft-keymap = { workspace = true } -craft-theme = { workspace = true } -craft-window = { workspace = true } +ttf-parser = "0.25" serde = { workspace = true } serde_json = { workspace = true } log = { workspace = true } web-time = { workspace = true } [target.'cfg(not(target_arch = "wasm32"))'.dependencies] +craft = { workspace = true, features = ["update"] } craft-update = { workspace = true } [dev-dependencies] +craft = { workspace = true, features = ["screen-testing"] } +eframe = { workspace = true } skrifa = { workspace = true } # kittest's own dev-dependencies do not propagate; tests need both font features explicitly. egui = { workspace = true, features = ["default_fonts", "monochrome_emoji_fonts"] } -egui_kittest = { workspace = true, features = ["wgpu", "snapshot"] } +egui_kittest = { workspace = true, features = ["wgpu", "snapshot", "eframe"] } [build-dependencies] serde_json = { workspace = true } diff --git a/crates/ui-egui/examples/icon_gallery.rs b/crates/ui-egui/examples/icon_gallery.rs deleted file mode 100644 index 6b1a38a58..000000000 --- a/crates/ui-egui/examples/icon_gallery.rs +++ /dev/null @@ -1,65 +0,0 @@ -//! Renders every DeckCraft icon into a labelled PNG grid, on a light and a dark background. -//! -//! ```sh -//! cargo run -p deckcraft-ui-egui --example icon_gallery -- /tmp/gallery.png -//! ``` -//! -//! Each cell shows the icon at 32 pt, at 16 pt, and disabled at 16 pt, with its name underneath. -//! An optional second argument filters icons by name substring. - -use deckcraft_ui_egui::icons::{self, Icon}; -use egui::{Align2, Color32, FontId, Rect, pos2, vec2}; - -const COLS: usize = 12; -const CELL_W: f32 = 110.0; -const CELL_H: f32 = 64.0; -const PAD: f32 = 12.0; - -struct Theme { - bg: Color32, - ink: Color32, - label: Color32, -} - -fn main() -> Result<(), Box> { - let mut args = std::env::args().skip(1); - let out = args.next().unwrap_or_else(|| "icon_gallery.png".to_owned()); - let filter = args.next(); - let list: Vec = Icon::ALL.iter().copied().filter(|i| filter.as_deref().is_none_or(|f| i.name().contains(f))).collect(); - - let rows = list.len().div_ceil(COLS); - let panel_h = rows as f32 * CELL_H + PAD * 2.0; - let width = COLS as f32 * CELL_W + PAD * 2.0; - let themes = [ - Theme { bg: Color32::from_rgb(0xff, 0xff, 0xff), ink: Color32::from_rgb(0x3a, 0x3a, 0x3a), label: Color32::from_rgb(0x70, 0x70, 0x70) }, - Theme { bg: Color32::from_rgb(0x2b, 0x2b, 0x2b), ink: Color32::from_rgb(0xe8, 0xe8, 0xe8), label: Color32::from_rgb(0xa8, 0xa8, 0xa8) }, - ]; - - let mut harness = - egui_kittest::Harness::builder().with_size(vec2(width, panel_h * themes.len() as f32)).with_pixels_per_point(2.0).wgpu().build_ui(|ui| { - let painter = ui.painter(); - for (ti, theme) in themes.iter().enumerate() { - let top = ti as f32 * panel_h; - painter.rect_filled(Rect::from_min_size(pos2(0.0, top), vec2(width, panel_h)), 0.0, theme.bg); - for (n, &icon) in list.iter().enumerate() { - let x = PAD + (n % COLS) as f32 * CELL_W; - let y = top + PAD + (n / COLS) as f32 * CELL_H; - let big = Rect::from_min_size(pos2(x + 14.0, y + 4.0), vec2(32.0, 32.0)); - icons::paint(painter, big, icon, theme.ink, false); - let small = Rect::from_min_size(pos2(x + 56.0, y + 12.0), vec2(16.0, 16.0)); - icons::paint(painter, small, icon, theme.ink, false); - let dis = Rect::from_min_size(pos2(x + 80.0, y + 12.0), vec2(16.0, 16.0)); - icons::paint(painter, dis, icon, theme.ink, true); - painter.text(pos2(x + CELL_W * 0.5, y + 46.0), Align2::CENTER_CENTER, icon.name(), FontId::proportional(9.5), theme.label); - } - } - }); - harness.run(); - let image = harness.render()?; - if let Some(dir) = std::path::Path::new(&out).parent() { - std::fs::create_dir_all(dir)?; - } - image.save(&out)?; - println!("wrote {} icons to {out}", list.len()); - Ok(()) -} diff --git a/crates/ui-egui/src/animpane_tests.rs b/crates/ui-egui/src/animpane_tests.rs index 1ec5cb9a5..0c2855577 100644 --- a/crates/ui-egui/src/animpane_tests.rs +++ b/crates/ui-egui/src/animpane_tests.rs @@ -19,19 +19,14 @@ fn harness() -> Harness<'static, SlideApp> { s.execute("edit.select", &json!({"ids": [id]})).unwrap(); s.execute("animation.add", &json!({"effect": effect, "start": start, "duration": dur})).unwrap(); } - let mut app = SlideApp::new(s, Services::default()); - app.ui.pane = Some("animation".into()); - let mut h = Harness::builder() - .with_context_setup(crate::framework::install_headless) - .with_size(egui::vec2(1400.0, 900.0)) - .with_step_dt(1.0 / 60.0) - .build_ui_state( - |ui, app: &mut SlideApp| { - app.logic(ui.ctx()); - app.ui(ui); - }, - app, - ); + let mut h = crate::test_harness::harness_with( + s, + Services::default(), + Harness::builder().with_size(egui::vec2(1400.0, 900.0)).with_step_dt(1.0 / 60.0), + |_| {}, + ); + // The command opens Pane::Task("animation") through the editor's pane host. + h.state_mut().run("view.pane", json!({"pane": "animation"})).unwrap(); h.run_steps(3); h } @@ -57,31 +52,68 @@ fn drag(h: &mut Harness<'_, SlideApp>, from: Pos2, to: Pos2) { #[test] fn after_previous_bar_starts_where_the_first_ends() { let h = harness(); - let a = h.get_by_label("Timing bar 1").rect(); - let b = h.get_by_label("Timing bar 2").rect(); + let a = h.get_by_role_and_label(egui::accesskit::Role::Slider, "Timing bar 1").rect(); + let b = h.get_by_role_and_label(egui::accesskit::Role::Slider, "Timing bar 2").rect(); assert!((b.left() - a.right()).abs() < 1.5, "{a:?} {b:?}"); assert!((b.width() - 2.0 * a.width()).abs() < 1.5, "2 s bar twice the 1 s bar"); } +#[test] +fn a_long_name_keeps_the_timeline_column() { + let mut h = harness(); + let before = h.get_by_role_and_label(egui::accesskit::Role::Slider, "Timing bar 1").rect(); + let id = h.state().session.active().unwrap().current_slide().unwrap().animations[0].shape.0; + h.state_mut().run("shape.rename", json!({"id": id, "name": "Aurora borealis over the northern lakes at midnight in winter"})).unwrap(); + h.run_steps(3); + let after = h.query_by_role_and_label(egui::accesskit::Role::Slider, "Timing bar 1").map(|node| node.rect()); + assert!(after.is_some_and(|after| after.width() >= before.width() - 0.5), "{before:?} {after:?}"); +} + #[test] fn dragging_a_bar_sets_the_delay_and_undoes() { let mut h = harness(); - let a = h.get_by_label("Timing bar 1").rect(); - // One second is the width of bar 1. - drag(&mut h, a.center(), a.center() + egui::vec2(a.width() / 2.0, 0.0)); - assert_eq!(timing(&h, 0), (500, 1000)); + let before = timing(&h, 0); + let a = h.get_by_role_and_label(egui::accesskit::Role::Slider, "Timing bar 1").rect(); + // A click without a drag is not a timing edit. + drag(&mut h, a.center(), a.center()); + assert_eq!(timing(&h, 0), before); + // Separate the click from the next press so it is not a double click. + h.run_steps(60); + let fraction = 0.5; + drag(&mut h, a.center(), a.center() + egui::vec2(a.width() * fraction, 0.0)); + let changed = timing(&h, 0); + assert_eq!(changed.0 - before.0, (before.1 as f32 * fraction) as u32); + assert_eq!(changed.1, before.1); h.state_mut().session.execute("edit.undo", &json!({})).unwrap(); - assert_eq!(timing(&h, 0), (0, 1000)); + assert_eq!(timing(&h, 0), before); } #[test] fn dragging_the_edge_sets_the_duration() { let mut h = harness(); - let b = h.get_by_label("Timing bar 2").rect(); - let one_sec = b.width() / 2.0; - let edge = h.get_by_label("Duration handle 2").rect().center(); - drag(&mut h, edge, edge - egui::vec2(one_sec, 0.0)); - assert_eq!(timing(&h, 1), (0, 1000)); + let before = timing(&h, 1); + let b = h.get_by_role_and_label(egui::accesskit::Role::Slider, "Timing bar 2").rect(); + let edge = h.get_by_role_and_label(egui::accesskit::Role::Slider, "Timing bar 2 end").rect().center(); + drag(&mut h, edge, edge - egui::vec2(b.width() / 2.0, 0.0)); + assert_eq!(timing(&h, 1), (before.0, before.1 / 2)); + + h.state_mut().session.execute("animation.timing", &json!({"index": 1, "duration": before.1, "repeat": 2})).unwrap(); + h.run_steps(2); + let repeated = timing(&h, 1); + let b = h.get_by_role_and_label(egui::accesskit::Role::Slider, "Timing bar 2").rect(); + let edge = h.get_by_role_and_label(egui::accesskit::Role::Slider, "Timing bar 2 end").rect().center(); + // Half the displayed four-second span is one second per iteration. + drag(&mut h, edge, edge - egui::vec2(b.width() / 2.0, 0.0)); + assert_eq!(timing(&h, 1), (repeated.0, repeated.1 / 2)); + + let shortened = timing(&h, 1); + let b = h.get_by_role_and_label(egui::accesskit::Role::Slider, "Timing bar 2").rect(); + let edge = h.get_by_role_and_label(egui::accesskit::Role::Slider, "Timing bar 2 end").rect().center(); + let least = crate::animtimeline::MIN_DURATION_MS; + let span_ms = shortened.1 * 2; + let target = egui::pos2(b.left() + b.width() * least as f32 / span_ms as f32, edge.y); + drag(&mut h, edge, target); + assert_eq!(timing(&h, 1), (before.0, least)); } /// Seconds on the play-all clock where the canvas preview is, right after the pane's play button. @@ -121,7 +153,7 @@ fn play_from_follows_the_effect_clicked_in_the_pane() { h.state_mut().session.execute("animation.add", &json!({"effect": "pulse", "start": "afterPrevious", "duration": 1000})).unwrap(); h.run_steps(2); // The row of the pulse, left of its bar. - let bar = h.get_by_label("Timing bar 3").rect(); + let bar = h.get_by_role_and_label(egui::accesskit::Role::Slider, "Timing bar 3").rect(); let row = egui::pos2(bar.left() - 20.0, bar.center().y); h.hover_at(row); h.run_steps(1); @@ -135,7 +167,7 @@ fn play_from_follows_the_effect_clicked_in_the_pane() { /// Clicks the pane row of effect `n` (1-based), left of its timing bar, with `button`. fn click_row(h: &mut Harness<'_, SlideApp>, n: usize, button: egui::PointerButton) { - let bar = h.get_by_label(&format!("Timing bar {n}")).rect(); + let bar = h.get_by_role_and_label(egui::accesskit::Role::Slider, &format!("Timing bar {n}")).rect(); let pos = egui::pos2(bar.left() - 20.0, bar.center().y); h.event(egui::Event::PointerMoved(pos)); h.run_steps(1); @@ -192,13 +224,3 @@ fn preview_rejects_a_from_that_is_not_an_effect_index() { } assert_eq!(h.state_mut().run("animation.preview", json!({"from": 1})).unwrap()["from"], 1.0); } - -#[test] -#[ignore = "writes a screenshot for review"] -fn screenshot() { - let _gpu = crate::gpu_lock::gpu_lock(); - let mut h = harness(); - h.run_steps(2); - let img = h.render().unwrap(); - img.save("/tmp/animpane.png").unwrap(); -} diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 845f591f1..ccd226cc2 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -1,57 +1,183 @@ -use super::clock::{monotonic_secs, now_ms}; -use super::ime_hooks::ime_in_ui_pass_key; -use super::services::{InboxEvent, Services}; -use super::state::{FilePlace, FilePurpose, ImeDescriptorKey, ImeDestination, ImeTerminalStamp, LocatedPlace, RECENT_MAX, UiState, ViewMode}; +pub(crate) mod catalog; +pub(crate) mod scheme; + +use super::services::Services; +use super::state::{FilePlace, FilePurpose, LocatedPlace, RECENT_MAX, ViewMode}; #[cfg(not(target_arch = "wasm32"))] use super::updates_ui; use super::{ - AnimPreview, ControlRequest, FileTarget, HashMap, ImeCancelled, ImeComposition, ImeResetPhase, ImeTerminalPending, InputTarget, Mods, - PendingFile, Perf, Receiver, Session, SlideApp, Target, UI_COMMANDS, UiRequest, Value, backstage, canvas, capture, dialogs, doc_window, - eyedropper, json, media, menus, notes, panes, preview, qat, ribbon, selpane, show, sorter, status, textures, theme, thumbs, toast, uifonts, + AnimPreview, FileTarget, HashMap, InputTarget, Perf, Platform, Session, SlideApp, Target, UiRequest, Value, backstage, dialogs, doc_window, json, + media, menus, preview, qat, ribbon, show, sorter, status, toast, }; +use craft::ui::contract::{Bind, CommandSet as _, Tracked}; +use craft::ui::runtime::commands::{CommandGate, CommandInput}; +use craft::ui::runtime::env::{Scale, WindowKey}; +use craft::ui::runtime::frame::FrameInput; +use craft::ui::runtime::windows::WindowHost; +use craft::ui::shell::{AppShell, PageKind, Slot, SlotSize, embed}; mod clipboard; mod commands; mod control; -mod document_focus; pub(crate) mod files; mod frame; -mod ime; mod input; mod keys; mod playback; -#[cfg(test)] -pub(crate) use clipboard::{OBJECTS_MARKER, system_clipboard_text}; -pub(crate) use document_focus::DocumentFocus; +pub(crate) use commands::GRID_SPACING_RANGE; +pub(crate) use files::FileOperation; #[cfg(test)] pub(crate) use files::web_image_files; +pub(crate) use keys::QAT_CLAIMS; pub use keys::key_name; +pub(crate) use playback::second_display; /// How long a transient status message stays visible. const STATUS_LINGER_MS: f64 = 6000.0; -impl SlideApp { - /// Remove temporary PDFs created for printing. - pub fn cleanup_print_previews(&mut self) { - self.print_previews.cleanup(); - } +/// A startup failure while installing the runtime or building the command catalogue. +#[derive(Debug)] +#[non_exhaustive] +pub enum AppError { + /// The runtime could not be installed. + Install(craft::ui::runtime::InstallError), + /// The initial command catalogue could not be built. + Catalog(String), +} - /// Build application UI state, taking ownership of audio output and initialising media, dialogs, - /// synthetic input, and timing fields. - pub fn new(session: Session, mut services: Services) -> Self { - let audio_out = services.audio_out.take(); - SlideApp { - last_fill: serde_json::json!("accent1"), - last_outline: serde_json::json!("tx1"), - table_pen: serde_json::json!({"width": 1.0}), +impl From for AppError { + fn from(error: craft::ui::runtime::InstallError) -> Self { + Self::Install(error) + } +} + +impl std::fmt::Display for AppError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Install(error) => write!(f, "{error}"), + Self::Catalog(error) => f.write_str(error), + } + } +} + +impl std::error::Error for AppError {} + +/// The app's font stack: the embedded craft-fonts faces, egui's monochrome emoji face as the fallback for every +/// family (the comment reactions and other emoji text) and Hack for symbols such as ◀. Every window that draws the +/// app's text installs this one. +pub(crate) fn ui_fonts() -> craft::ui::fonts::UiFonts<'static> { + let faces: Vec<_> = deckcraft_fonts::CRAFT_FONTS + .iter() + .map(|face| craft::ui::fonts::EmbeddedFace { + family: face.family, + style: face.style, + scripts: face.scripts, + index: 0, + bytes: face.bytes, + role: None, + }) + .collect(); + // craft-fonts has no emoji face. + let mut emoji = craft::ui::fonts::Emoji::default(); + emoji.monochrome = craft::ui::fonts::noto_emoji(); + craft::ui::fonts::UiFonts::new(&craft::ui::fonts::I18nScripts) + .craft_faces(&faces) + .emoji(emoji) + .egui_face("Hack", &[craft::ui::fonts::FontRef::proportional()]) +} + +impl SlideApp { + /// Installs one window's runtime, fonts, host services and persisted preferences. + pub fn new(ctx: &egui::Context, platform: Platform) -> Result { + crate::icons::register(); + let Platform { mut install, host, settings: location, intake, audio_out, control, frame, at_exit } = platform; + install.jobs = Some(host.jobs_shared().clone()); + let fonts = ui_fonts().ui_language(host.language_code()); + embed::install(ctx, install, &fonts)?; + host.clone().install(ctx); + + let mut options = craft::settings::OpenOptions::::new(location); + #[cfg(not(target_arch = "wasm32"))] + { + use craft::settings::Settings as _; + let portable = craft::settings::Portable { + markers: crate::settings::DeckSettings::PORTABLE_MARKERS, + dir: crate::settings::DeckSettings::PORTABLE_DIR, + }; + let resolved = craft::settings::paths::resolve_named( + crate::settings::DeckSettings::APP_ID, + crate::settings::DeckSettings::FOLDER_NAME, + &portable, + &options.location, + &options.probe, + ); + if let Some(dir) = resolved.dir { + options.location = craft::settings::Location::Dir(dir.clone()); + options.legacy = crate::settings::legacy(&dir); + } else { + options.location = craft::settings::Location::Memory; + } + } + #[cfg(target_arch = "wasm32")] + if options.location != craft::settings::Location::Memory { + options.legacy = crate::settings::legacy(std::path::Path::new("")); + } + let (store, report) = craft::settings::SettingsStore::open_with(options); + // PLAN: assumed DeckSettings { ui: UiState, prefs: Prefs } (shell-w12) + let saved = store.get().clone().sanitized(); + let mut session = Session::default(); + session.prefs = saved.prefs; + let catalog = catalog::build(&session, 1).map_err(AppError::Catalog)?; + let wake_ctx = ctx.clone(); + let wake = craft::host::Wake::new(move || wake_ctx.request_repaint()); + let intake = intake.or_else(|| Some(craft::platform::open::FileIntake::new(wake.clone()).0)); + let notices = craft::ui::notices::NoticeCenter::new().wake(wake.clone()); + let squiggles = crate::squiggles::Squiggles::new(host.jobs_shared().clone(), wake.clone()); + #[cfg(not(target_arch = "wasm32"))] + // PLAN: assumed OpeningJobs::new(Arc, Wake) -> OpeningJobs (shell-w3) + let opening_jobs = crate::opening::OpeningJobs::new(host.jobs_shared().clone(), wake); + let mut app = Self { + host, + control, + autosave: None, + notices, + palette_open: false, + palette_recents: Vec::new(), + palette_state: Default::default(), + guide_selection: Default::default(), + catalog, + injected_target: None, + twist_frame: None, + clock: Default::default(), + root: crate::theme::root_env(), + #[cfg(not(target_arch = "wasm32"))] + opening_jobs, + dialogs: Default::default(), + format_pane: Default::default(), + anim_pane: Default::default(), + fill_editor: Default::default(), + comments_pane: Default::default(), + pane_menu: None, + smartart_focus: None, + slide_reveal: None, + insert_zoom: Default::default(), + smooth_corners: Default::default(), + host_answers: Vec::new(), + icon_sheet: None, + canvas_view: craft::behavior::CanvasView::new(egui::Rect::NOTHING, craft::behavior::kurbo::Point::ZERO, 1.0), + picture: Default::default(), + ruler_tab_kind: Default::default(), + canvas_menu: None, + caret_blink: None, + selection_ime: Default::default(), + last_fill: json!("accent1"), + last_outline: json!("tx1"), + table_pen: json!({"width": 1.0}), session, - services, - ui: UiState::default(), - textures: textures::Textures::default(), - control_rx: None, - squiggles: Default::default(), - dialog: None, + services: Services::default(), + ui: saved.ui, + squiggles, thesaurus_query: String::new(), show: None, anim_preview: None, @@ -59,132 +185,113 @@ impl SlideApp { media: media::MediaHost::new(audio_out), status: None, opening: None, - toast: None, fonts_noted: Default::default(), - perf: Perf { frame_ms: 0.0, render_ms: 0.0, fps: 0.0 }, - synthetic: vec![], - synthetic_pending: false, - synthetic_next: vec![], - synthetic_next_target: None, - synthetic_injected: vec![], - synthetic_injected_at: None, - synthetic_generation: 0, - synthetic_target: None, - synthetic_focus: None, - document_focus: DocumentFocus::default(), - synthetic_injected_time: None, - ribbon_scroll: HashMap::new(), + perf: Perf { frame_ms: 0.0, render_ms: 0.0 }, show_instance: 0, - #[cfg(not(target_arch = "wasm32"))] - opening_generation: 0, - canvas_rect: None, eyedropper: None, - canvas_scale: 1.0, - slide_rect: None, - canvas_region: None, - palette: None, - integrated_titlebar: false, + integrated_titlebar: !matches!(frame, craft::window::policy::Frame::Native), backstage: None, - pending_urls: vec![], - print_previews: files::PrintPreviews::default(), + pending_urls: Vec::new(), #[cfg(not(target_arch = "wasm32"))] - updates_rt: updates_ui::Runtime::default(), - framework_dialogs: craft_ui::dialog::DialogHost::new(), - framework_host: crate::framework::host(), - pending_copy: None, - capture: capture::Capture::default(), - styled: false, - restyle: true, - fonts_ready: false, - last_time: 0.0, - last_recovery: 0.0, - quit_confirmed: false, - notes_buf: (0, usize::MAX, notes::Draft::default()), - ui_fonts: uifonts::UiFonts::default(), - thumb_drag: None, - selpane: selpane::State::default(), + print_previews: Default::default(), + #[cfg(not(target_arch = "wasm32"))] + updates_rt: Default::default(), + selpane: Default::default(), align_to: None, doc_window: None, - sorter: sorter::State::default(), - slides_focused: false, - v_seen: false, + sorter: Default::default(), recent_checked: HashMap::new(), - twisting: false, - next_file_id: 1, pending_files: Vec::new(), host_start: None, - ime_tracker: egui::ime_context::ImeContextTracker::new(), - ime_pending: None, - ime_frame_viewport: None, - ime_viewport: None, - ime_composition: None, - ime_terminal_pending: None, - ime_cancelled: None, - ime_generation: 0, - ime_settles_seen: 0, - ime_interrupt_pending: false, - ime_reset: HashMap::new(), + store, + intake, + at_exit, + left: false, + }; + for error in report.section_errors { + app.notify(format!("{}: {}", error.section, error.message)); + } + Ok(app) + } + + /// Removes temporary PDFs created for printing. + #[cfg(not(target_arch = "wasm32"))] + pub fn cleanup_print_previews(&mut self) { + self.print_previews.cleanup(); + } + + /// Holds the close request until dirty presentations have passed the closing guard. + pub fn close_decision(&mut self) -> embed::CloseDecision { + let dirty: Vec<_> = self.session.documents().iter().filter(|doc| doc.is_dirty()).map(|doc| doc.uid).collect(); + if !dirty.is_empty() && !self.quit_allowed() { + if self.dialogs.closing.is_none() { + self.show = None; + self.start_closing(craft::quit::CloseScope::Quit, dirty); + } + embed::CloseDecision::Hold + } else { + embed::CloseDecision::Close } } - pub fn with_control(mut self, rx: Receiver) -> Self { - self.control_rx = Some(rx); - self + /// Completes the platform exit record, settings, update and preview cleanup once. + pub fn leave(&mut self) { + if std::mem::replace(&mut self.left, true) { + return; + } + if let Some(at_exit) = self.at_exit.take() { + at_exit(); + } + self.sync_settings(); + if let Err(error) = self.store.flush() { + log::error!("Could not save settings: {error}"); + } + #[cfg(not(target_arch = "wasm32"))] + { + self.start_pending_update(); + self.cleanup_print_previews(); + } } + /// Displays a transient message in the status bar. pub fn set_status(&mut self, msg: impl Into) { - self.status = Some((msg.into(), now_ms())); + self.status = Some((msg.into(), self.clock.now() * 1000.0)); } - /// Turn on the automatic check for a newer release at start-up (desktop shell only; tests and - /// the web build never touch the network on their own). + /// Enables the desktop's automatic release check. #[cfg(not(target_arch = "wasm32"))] pub fn enable_update_checks(&mut self) { updates_ui::enable(self); } - /// Start the helper of an update that is ready, so that it installs once the process has - /// exited. The desktop shell calls it in `on_exit`, which ends the process on macOS before the - /// app is dropped. Later calls do nothing, and a Nightly launch never starts a stable update. + /// Starts the prepared update helper after settings have been saved. #[cfg(not(target_arch = "wasm32"))] pub fn start_pending_update(&mut self) { updates_ui::start_pending_update(self); } - /// A message that must be seen wherever the user is: a toast, which also shows over the start - /// screen and the File tab, where there is no status bar. + /// Posts a notice through the next shell pass, including over the File and show pages. pub fn notify(&mut self, msg: impl Into) { - self.toast = Some(toast::Toast { text: msg.into(), at: now_ms() }); + self.notices.enqueue(craft::ui::notices::PostedNotice::new(msg)); } - /// The transient status message while it is fresh; clears it once stale. Both the status bar - /// and the start screen draw it — the start screen has no status bar, and errors raised there - /// (a missing recent file, a failed sample) used to vanish (issue #172). - pub fn fresh_status(&mut self) -> Option { - let (msg, at) = self.status.clone()?; - if now_ms() - at < STATUS_LINGER_MS { - Some(msg) - } else { - self.status = None; - None - } + /// Returns a status message only while its six-second linger is active. + pub(crate) fn fresh_status(&self) -> Option<&str> { + let (msg, at) = self.status.as_ref()?; + (self.clock.now() * 1000.0 - at < STATUS_LINGER_MS).then_some(msg.as_str()) } - /// Return the current document count plus the active document uid, so callers can detect a - /// replacement document rather than only an index change. + /// The document count and active uid distinguish document replacement from index changes. pub(crate) fn docs_key(&self) -> (usize, Option) { - // The document uid, not just its index: closing one presentation and opening another - // must not look like the same document to the Backstage view or a queued input batch. (self.session.documents().len(), self.session.active().map(|d| d.uid)) } - /// The File tab's view is open over a presentation (not just the start screen with nothing - /// open). + /// Whether the File view is open over a presentation. pub fn backstage_open(&self) -> bool { self.backstage.is_some() && self.session.active().is_some() } - /// Opens the File tab's view on `page` (keeping its state when it is already open). + /// Opens the File view on `page`, retaining its state across page navigation. pub fn open_backstage(&mut self, page: backstage::Page) { let key = self.docs_key(); match &mut self.backstage { @@ -193,15 +300,13 @@ impl SlideApp { } } - /// Back to the presentation (no effect on the start screen, where nothing is open). + /// Returns to the presentation; the start page stays when nothing is open. pub fn close_backstage(&mut self) { if self.session.active().is_some() { self.backstage = None; } } - /// Keeps the File tab's view in step with the open presentations: it closes when one is - /// opened, created or closed (the result shows), and it is the start screen when none is open. fn sync_backstage(&mut self) { let key = self.docs_key(); let has_doc = self.session.active().is_some(); @@ -213,168 +318,281 @@ impl SlideApp { } } - /// Background work, run on every logic call (visible, hidden or `run_logic`). - /// - /// Only consumed queues and monotonic deadlines live here: control requests, asynchronous - /// opening/inbox results, screenshot completions/deadlines, AutoRecover pacing and media - /// clocks. UI events are handled in [`Self::ui`], where a forced hidden paint also arrives. + /// Supplies commands and root values once before the frame's first input pass. + /// Additional layout passes read that input and apply only their own events. + pub fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) { + self.withdraw_if_retargeted(ctx); + if !Self::root_viewport_admitted(ctx) { + return; + } + if WindowHost::of(ctx).injected_idle() { + self.drain_control(ctx); + } + #[cfg(not(target_arch = "wasm32"))] + if let Some(intake) = &self.intake { + let dropped = std::mem::take(&mut raw.dropped_files) + .into_iter() + .map(|file| craft::platform::open::DroppedFile { + path: Some(file.path().to_owned()), + name: file.path().file_name().map(|name| name.to_string_lossy().into_owned()).unwrap_or_default(), + bytes: None, + }) + .collect(); + intake.sender().dropped(dropped); + } + #[cfg(target_arch = "wasm32")] + let _ = raw; + embed::before_input(ctx, |output| { + for fired in &output.fired { + self.fire(ctx, fired); + } + let states = Tracked::new(catalog::command_states(self)); + let commands = CommandInput::new() + .catalog(self.catalog.clone()) + .states(&states) + .gate(CommandGate::new(self.session.active().is_some(), |has_doc, command| { + *has_doc + || *command == craft::ui::runtime::commands::CommandRef::from(craft::menu::ribbon::BackstageCommands::Back) + || catalog::START_SCREEN.contains(&command.id.as_str()) + })) + .paste_reads_clipboard(true); + // PLAN: plan error: InterfaceScale::apply is absent; runtime::frame::set_input applies this root Scale. + let mut root = self.root.clone().scale(Scale::new(self.ui.ui_scale)); + root.mode = match self.ui.brightness { + crate::Brightness::Light => craft::theme::ModeChoice::Light, + crate::Brightness::Dark => craft::theme::ModeChoice::Dark, + }; + root.values.set(craft::ui::primitives::FlagMark::Wave); + root.values.set(super::state::editor_zoom_scheme(ctx.pixels_per_point())); + let mut input = FrameInput::new(root).commands(commands); + input.host = craft::host::Host::try_of_ctx(ctx); + input + }); + } + + /// Pumps background work even while the window is hidden, then runs its one close path. pub fn logic(&mut self, ctx: &egui::Context) { if !Self::root_viewport_admitted(ctx) { - log::debug!("ignoring SlideApp::logic for render-only viewport {:?}", ctx.viewport_id()); return; } self.tick_hidden_show(ctx, web_time::Instant::now()); - // `raw_input_hook` runs before `App::logic`. In a full pass egui has already built - // `PointerState` and `keys_down` from every injected event, so retracting the events after - // this pass would not stop the derived click or key from reaching the UI. Defer instead: - // a control request, background-open result or inbox file that changes the document, - // target or modal owner waits until the admitted batch has been consumed by the old - // target's UI pass. A logic-only callback carries the RawInput into the next full pass - // (no live `InputState` here), so that pass still drains normally and the next - // `raw_input_hook` retracts a batch that went stale. - if !self.synthetic_batch_is_live(ctx) { - self.drain_control(ctx); + if WindowHost::of(ctx).injected_idle() { + self.drain_intake(ctx); self.poll_opening(); #[cfg(not(target_arch = "wasm32"))] updates_ui::tick(self, ctx); - // Inbox results are host file bytes and do not need fonts or a painted frame. A - // window that starts hidden must still apply a file picked before its first UI pass. - self.drain_inbox(); - } - self.drain_screenshots(); - // `raw_input_hook` ran before this logic pass. This is normally a no-op now that - // target-changing work is deferred for a live batch; it still covers a target change - // made by other logic, and keeps a logic-only batch pending for the next hook. - self.retract_synthetic_after_logic(ctx); - // Queued/settling screenshots force the bounded hidden paints they need; issued ones - // rely on the screenshot command and the completion callback, with only a deadline wake. - self.capture.request_paint_if_needed(ctx, web_time::Instant::now()); - if !self.synthetic.is_empty() || !self.synthetic_next.is_empty() || self.synthetic_pending { - ctx.request_repaint(); + self.take_file_answers(); } self.autosave_if_due(ctx); self.tick_media_clock(ctx); - self.note_settled_composition(ctx); - // In a full run_ui pass the UI callback after this logic half still owns the pass's final - // IME descriptor. Only a standalone run_logic callback proves that no custom editor was - // painted for this tick. Do not infer this from cumulative frame counters or stale - // geometry. - if !self.ime_in_ui_pass(ctx) { - self.finalize_ime_logic(ctx); - } + // Exit work must finish before the platform quits inside this callback. + embed::logic(ctx, || { + let decision = self.close_decision(); + if decision == embed::CloseDecision::Close { + self.leave(); + } + decision + }); } - /// Lay out the whole window. - /// - /// Every return route, including fonts/layout discards, show mode, modal/Backstage and the - /// no-document paths, reaches the same outer reset observation and finalizer below. No early - /// route may publish or inspect IME output on its own. + /// Lays out the title, ribbon, status and document, or the one active full-window page. pub fn ui(&mut self, ui: &mut egui::Ui) { let ctx = ui.ctx().clone(); if !Self::root_viewport_admitted(&ctx) { - log::debug!("ignoring SlideApp::ui for render-only viewport {:?}", ctx.viewport_id()); return; } - self.ui_inner(ui); - // The last writer (all panels, dialogs, the custom producer and deferred child windows) - // has run. Observe the actual custom descriptor for this pass, then reconcile the reset - // lifetime against the actual committed output. This also runs for discarded passes. - self.ime_frame_viewport = Some(ctx.viewport_id()); - let custom = self.observe_ime(&ctx); - self.finalize_ime_reset(&ctx, custom); - } - - /// Run the admitted root UI pass, including setup gating, panels, canvas, dialogs, overlays, and - /// show mode. - fn ui_inner(&mut self, ui: &mut egui::Ui) { - let ctx = ui.ctx().clone(); - self.ime_frame_viewport = Some(ctx.viewport_id()); - self.ime_pending = None; - let document_before = self.document_focus.drawn.take(); - if !self.ui_setup(&ctx) { - // This pass is discarded for the new fonts. The input events were already consumed - // by egui, so keep them queued for the next frame instead of silently losing them. - self.requeue_injected_synthetic(); - return; - } - let t0 = now_ms(); - let t = theme::Tokens::get(&ctx); - self.note_ui_text(&ctx); + let started = craft::platform::clock::monotonic_ms(); self.media.sync_video_textures(&ctx); - canvas::trackpad_twist(self, &ctx); - eyedropper::tick(self, &ctx); - self.opening_ui(&ctx); - if self.show.is_some() { - self.anim_preview = None; - show::ui(self, ui); - doc_window::show(self, &ctx); - self.perf.frame_ms = now_ms() - t0; - self.ui_end(&ctx); - return; - } self.sync_backstage(); self.keyboard(&ctx); self.sync_backstage(); - ribbon::title_bar(self, ui); - if self.backstage.is_none() && self.session.active().is_some() { - ribbon::show(self, ui); - status::status_bar(self, ui); - } - let now = ui.input(|i| i.time); - if self.tick_anim_preview(now) { + // The preview clock reads the frame's time once, in the pass that receives the frame's input; a rerun pass of + // the same frame shows the same moment. + if self.show.is_some() { + self.anim_preview = None; + } else if ctx.current_pass_index() == 0 && self.tick_anim_preview(ctx.input(|i| i.time)) { ctx.request_repaint(); } - egui::CentralPanel::default().frame(egui::Frame::NONE.fill(t.chrome)).show(ui, |ui| { - if self.backstage.is_some() { - // File tab: the Backstage view replaces everything below the title bar. - backstage::show(self, ui); - return; - } - if self.session.active().is_none() { - return; - } - match self.ui.view { - ViewMode::Sorter => sorter::show(self, ui), - ViewMode::NotesPage => sorter::notes_page(self, ui), - ViewMode::Outline | ViewMode::Normal | ViewMode::Reading => { - if self.ui.pane.is_some() { - panes::show(self, ui); - } - if self.ui.view == ViewMode::Outline { - sorter::outline_pane(self, ui); + let show_page = self.show.is_some(); + let page_kind = match (self.show.as_ref(), self.session.active()) { + (Some(show), Some(doc)) => show.page_kind(&doc.doc, self.services.presenter.is_some()), + _ => PageKind::BelowTitle, + }; + let page_scope = if show_page { show::SHOW_SCOPE } else { craft::menu::ribbon::BackstageCommands::SCOPE }; + let editor = !show_page && self.backstage.is_none() && self.session.active().is_some(); + AppShell::new(WindowKey::main()) + .title_bar(|_| None, |ui, cx, app| ribbon::title_bar(app, ui, cx)) + .top(Slot::new("ribbon").label("Ribbon").visible(editor).size(SlotSize::Content), |_| None, |ui, _, app| ribbon::show(app, ui)) + .status(editor, |_| None, |ui, _, app| status::status_bar(app, ui)) + .page( + show_page || self.backstage.is_some(), + page_scope, + |_| None, + |ui, cx, app| { + if app.show.is_some() { + show::ui(app, ui, cx); } else { - thumbs::show(self, ui); + backstage::page(app, ui, cx); + } + app.shell_body_end(ui); + }, + ) + .page_kind(page_kind) + .body(|ui, _, app| { + if app.session.active().is_some() { + match app.ui.view { + ViewMode::Sorter => sorter::show(app, ui), + ViewMode::NotesPage => sorter::notes_page(app, ui), + _ => crate::panels::show_editor(app, ui), } - egui::CentralPanel::default().frame(egui::Frame::NONE.fill(t.canvas)).show(ui, |ui| { - if self.ui.notes { - status::notes_pane(self, ui); - } - canvas::show(self, ui); - }); } - } - }); - self.finish_document(&ctx, document_before); + app.shell_body_end(ui); + }) + .show(ui, self); + self.perf.frame_ms = craft::platform::clock::monotonic_ms() - started; + self.issue_captures(ui); + } + + fn shell_body_end(&mut self, ui: &mut egui::Ui) { + let ctx = ui.ctx().clone(); + self.opening_ui(ui); + // PLAN: assumed doc_window::show(&mut SlideApp, &mut Ui) (shell-w3) + doc_window::show(self, ui); toast::note_missing_fonts(self); - toast::show(self, &ctx); - dialogs::show(self, &ctx); - #[cfg(not(target_arch = "wasm32"))] - updates_ui::show(self, &ctx); - self.framework_dialogs.run(ui); - menus::palette(self, &ctx); + if self.palette_open { + let entries = menus::palette_entries(&self.session); + let env = craft::ui::runtime::env::Env::of(ui); + let view = env.view(); + let index = craft::ui::menu::search::SearchIndex::new( + &view, + &entries, + &craft::ui::menu::search::Synonyms::of(&view.words::()), + ); + let out = craft::ui::patterns::panels::CommandPalette::new("Command Palette", &entries, &index, Bind::bound(&mut self.palette_open)) + .state(Bind::bound(&mut self.palette_state)) + .recents(Bind::bound(&mut self.palette_recents)) + .show(ui); + if let Some(command) = out.refused { + self.palette_open = false; + self.set_status(craft::ui::runtime::commands::resolve(&ctx, command).hint.as_deref().unwrap_or("Command unavailable")); + } + } + if let Some(filter) = self.icon_sheet.clone() + && !crate::icon_sheet::window(ui, &filter) + { + self.icon_sheet = None; + } + self.drain_requests(); + dialogs::pump(self, &ctx); + self.sync_settings(); + let now = web_time::Instant::now(); + let saved = self.store.tick(now); + if let Some(deadline) = saved.next_deadline { + ctx.request_repaint_after(deadline.saturating_duration_since(now)); + } + if let craft::settings::SaveStatus::Failed(error) = saved.status { + self.set_status(format!("Could not save settings: {error}")); + } + self.notices.clone().show(ui); for url in std::mem::take(&mut self.pending_urls) { ctx.open_url(egui::OpenUrl::new_tab(url)); } - if let Some(t) = self.pending_copy.take() { - ctx.copy_text(t); - } - self.drain_requests(); - doc_window::show(self, &ctx); - self.perf.frame_ms = now_ms() - t0; - self.ui_end(&ctx); } + fn sync_settings(&mut self) { + self.store.update(|saved| { + saved.ui.clone_from(&self.ui); + saved.prefs.clone_from(&self.session.prefs); + }); + } + + /// OS arrivals wait for injected input to finish so a late file cannot retarget its events. Taking the queue + /// empties it once; additional layout passes neither poll this queue nor replay its arrivals. + fn drain_intake(&mut self, ctx: &egui::Context) { + use craft::platform::open::Intake; + let arrivals = self.intake.as_ref().map(|intake| intake.take()).unwrap_or_default(); + for arrival in arrivals { + match arrival { + Intake::Open(paths) => { + let mut names = Vec::new(); + for path in paths { + if let Some(path) = path.to_str() { + names.push(path.to_owned()); + } else { + self.set_status("The file path is not valid Unicode; rename the file and open it again."); + } + } + self.open_from_system(&names); + } + Intake::Dropped { files, .. } => { + for file in files { + let bytes = match (file.bytes, file.path) { + (Some(bytes), _) => Ok(bytes.to_vec()), + (None, Some(path)) => match path.to_str() { + Some(path) => deckcraft_engine::io::read_file_with( + path, + |path| self.host.files().read_metadata(std::path::Path::new(path)).map_err(|error| error.to_string()), + |path| self.host.files().read(std::path::Path::new(path)).map_err(|error| error.to_string()), + ), + None => Err("The dropped file path is not valid Unicode".into()), + }, + (None, None) => Err("The dropped file has no readable content".into()), + }; + match bytes { + Ok(bytes) => self.open_or_insert_bytes(&file.name, bytes), + Err(error) => self.set_status(error), + } + } + } + Intake::Bytes { name, bytes, .. } => self.open_or_insert_bytes(&name, bytes.to_vec()), + Intake::Quit => { + WindowHost::of(ctx).act(egui::ViewportId::ROOT, craft::ui::runtime::windows::WindowAction::Close); + } + Intake::OpenFor { action, .. } => self.set_status(format!("Unsupported system file action: {action}")), + } + } + } + + /// The canvas region in screen points, absent before its first layout. + pub fn canvas_rect(&self) -> Option { + let rect = self.canvas_view.rect; + (rect.is_finite() && rect.is_positive()).then_some(rect) + } + + /// The slide's screen bounds derived from the active document and canvas transform. + pub fn slide_rect(&self) -> Option { + self.canvas_rect()?; + let doc = &self.session.active()?.doc; + let size = doc.slide_size; + let corners = self.canvas_view.quad(craft::behavior::kurbo::Rect::new(0.0, 0.0, size.width, size.height)); + Some(egui::Rect::from_points(&corners)) + } + + /// Screen points per slide point, from the canvas's authoritative view. + pub fn canvas_scale(&self) -> f32 { + self.canvas_view.zoom as f32 + } + + fn root_viewport_admitted(ctx: &egui::Context) -> bool { + ctx.viewport_id() == egui::ViewportId::ROOT + } + + /// Reveals a file without blocking layout; a failure uses the window's notice policy and wake. + #[cfg(not(target_arch = "wasm32"))] + pub(crate) fn reveal_file(&mut self, path: std::path::PathBuf) { + let notices = self.notices.clone(); + self.host.jobs_shared().spawn( + "reveal file", + Box::new(move || { + if let Err(error) = craft::platform::open::reveal(&path) { + notices.enqueue(craft::ui::notices::PostedNotice::new(error)); + } + }), + ); + } + + /// Opens a URL after the shell's controls have finished the pass. pub fn open_url(&mut self, url: &str) { - self.pending_urls.push(url.to_string()); + self.pending_urls.push(url.to_owned()); } } diff --git a/crates/ui-egui/src/app/catalog.rs b/crates/ui-egui/src/app/catalog.rs new file mode 100644 index 000000000..f1936d41e --- /dev/null +++ b/crates/ui-egui/src/app/catalog.rs @@ -0,0 +1,267 @@ +use std::collections::BTreeMap; + +use crate::{Session, SlideApp}; +use craft::keymap::{Binding, CommandDef, CommandRef, Scope}; +use craft::ui::runtime::commands::{AppCatalog, CommandState, CommandStates}; +use serde_json::Value; + +/// A UI command and its parameter documentation. +pub struct UiCommand { + /// Command id. + pub id: &'static str, + /// Visible command label. + pub label: &'static str, + /// Parameter documentation. + pub params: &'static str, +} + +/// The UI commands shared by the app. +pub static UI_COMMANDS: &[UiCommand] = &[ + UiCommand { id: "view.normal", label: "Normal", params: "{}" }, + UiCommand { id: "view.outline", label: "Outline View", params: "{}" }, + UiCommand { id: "view.sorter", label: "Slide Sorter", params: "{}" }, + UiCommand { id: "view.notesPage", label: "Notes Page", params: "{}" }, + UiCommand { id: "view.reading", label: "Reading View", params: "{}" }, + UiCommand { id: "view.notes", label: "Notes", params: "{on?: bool}" }, + UiCommand { id: "view.ruler", label: "Ruler", params: "{on?: bool}" }, + UiCommand { id: "view.gridlines", label: "Gridlines", params: "{on?: bool}" }, + UiCommand { id: "view.guides", label: "Guides", params: "{on?: bool}" }, + UiCommand { + id: "view.gridOptions", + label: "Grid Options…", + params: "{spacing?: pt, snap?: bool, smartGuides?: bool, gridlines?: bool, guides?: bool}", + }, + UiCommand { id: "view.zoomIn", label: "Zoom In", params: "{}" }, + UiCommand { id: "view.zoomOut", label: "Zoom Out", params: "{}" }, + UiCommand { id: "view.zoom", label: "Set Zoom", params: "{percent}" }, + UiCommand { id: "view.zoomDialog", label: "Zoom…", params: "{}" }, + UiCommand { id: "view.fit", label: "Fit to Window", params: "{}" }, + UiCommand { id: "view.pane", label: "Task Pane", params: "{pane: format|animation|selection|comments|designer|background|smartart|null}" }, + UiCommand { id: "review.thesaurusPane", label: "Thesaurus", params: "{word?}: open the Thesaurus pane on the selected word" }, + UiCommand { id: "view.tab", label: "Ribbon Tab", params: "{tab}" }, + UiCommand { id: "view.collapseRibbon", label: "Collapse the Ribbon", params: "{}" }, + UiCommand { id: "view.dark", label: "Dark Mode", params: "{on?: bool}" }, + UiCommand { id: "view.grayscale", label: "Grayscale", params: "{on?: bool}" }, + UiCommand { id: "view.newWindow", label: "New Window", params: "{on?: bool, slide?: index, delta?: int}" }, + UiCommand { id: "show.start", label: "Slide Show", params: "{from?: index, custom?: name, rehearse?: bool}" }, + UiCommand { + id: "show.presenter", + label: "Presenter View", + params: "{on?: bool} → {on, window} (presenter view appears in a separate window beside the show; the browser draws it inside the page only when no presenter popup link is installed)", + }, + UiCommand { id: "show.keepCursor", label: "Keep Mouse Cursor Visible", params: "{on?: bool}" }, + UiCommand { id: "show.end", label: "End Show", params: "{}" }, + UiCommand { id: "animation.preview", label: "Preview Animations", params: "{on?: bool, from?: effect index}" }, + UiCommand { id: "app.home", label: "Home", params: "{on?}" }, + UiCommand { id: "app.backstage", label: "File", params: "{page?: home|new|open|info|saveAs|print|export|about, on?: bool, keyboard?: bool}" }, + UiCommand { id: "app.closePresentation", label: "Close", params: "{}" }, + UiCommand { + id: "app.print", + label: "Print", + params: "{layout?, perPage?, slides?, includeHidden?, frame?, paper?: letter|a4|legal|a3, orientation?: portrait|landscape}", + }, + UiCommand { id: "app.about", label: "About DeckCraft", params: "{}" }, + UiCommand { id: "app.checkUpdates", label: "Check for Updates…", params: "{}" }, + UiCommand { id: "app.palette", label: "Command Palette", params: "{}" }, + UiCommand { id: "app.preferences", label: "Preferences…", params: "{}" }, + UiCommand { id: "app.openDialog", label: "Open…", params: "{purpose?}" }, + UiCommand { id: "app.forgetRecent", label: "Remove from Recent", params: "{path} → {recent: [paths]}" }, + UiCommand { id: "app.insertPictureDialog", label: "Picture from File…", params: "{}" }, + UiCommand { id: "app.smartArtPictureDialog", label: "Insert Picture in Diagram…", params: "{id?, index}" }, + UiCommand { id: "app.changePictureDialog", label: "Change Picture…", params: "{}" }, + UiCommand { id: "app.insertAudioDialog", label: "Audio from File…", params: "{}" }, + UiCommand { id: "app.reuseSlidesDialog", label: "Reuse Slides…", params: "{keepFormatting?: bool, path?: string}" }, + UiCommand { id: "app.insertVideoDialog", label: "Video from File…", params: "{}" }, + UiCommand { id: "app.saveAsDialog", label: "Save As…", params: "{}" }, + UiCommand { id: "app.exportDialog", label: "Export…", params: "{}" }, + UiCommand { id: "app.browseThemeDialog", label: "Browse for Themes…", params: "{}" }, + UiCommand { id: "app.compareDialog", label: "Compare…", params: "{}" }, + UiCommand { id: "app.dialog", label: "Open Dialog", params: "{id}" }, + UiCommand { id: "app.pasteSpecial", label: "Paste Special…", params: "{}" }, + UiCommand { + id: "app.qat", + label: "Quick Access Toolbar", + params: "{add: command id, params?, label?, icon?} | {remove: id, params?} | {reset: true} → [buttons]", + }, + UiCommand { id: "app.find", label: "Find…", params: "{}" }, + UiCommand { id: "app.replace", label: "Replace…", params: "{}" }, + UiCommand { id: "app.links", label: "Community Links", params: "{}" }, + UiCommand { id: "tool.set", label: "Tool", params: "{kind: select|shape|textBox|ink, preset?, mode?, color?, width?, toggle?: bool}" }, + UiCommand { id: "view.handoutPerPage", label: "Slides per Handout Page", params: "{n: 1|2|3|4|6|9}" }, +]; + +/// A default app chord bound to a command and its parameters. +pub(crate) struct DefaultChord { + /// Chords that run this reference. + pub keys: &'static [&'static str], + /// Command id. + pub id: &'static str, + /// JSON parameters, or empty for a bare command. + pub params: &'static str, + /// Visible command label. + pub label: &'static str, +} + +/// The app default chord bindings. +pub(crate) static DEFAULT_CHORDS: &[DefaultChord] = &[ + DefaultChord { keys: &["F5", "Cmd+Shift+Enter"], id: "show.start", params: "", label: "Slide Show" }, + DefaultChord { keys: &["Shift+F5", "Cmd+Enter"], id: "show.fromCurrent", params: "", label: "Play from Current Slide" }, + DefaultChord { keys: &["Cmd+S"], id: "file.save", params: "", label: "Save" }, + DefaultChord { keys: &["Cmd+Shift+S"], id: "app.saveAsDialog", params: "", label: "Save As…" }, + DefaultChord { keys: &["Alt+F"], id: "app.backstage", params: r#"{"page":"home","keyboard":true}"#, label: "File" }, + DefaultChord { keys: &["Cmd+P"], id: "app.backstage", params: r#"{"page":"print"}"#, label: "Print" }, + DefaultChord { keys: &["Cmd+W"], id: "app.closePresentation", params: "", label: "Close" }, + DefaultChord { keys: &["Cmd+O"], id: "app.openDialog", params: "", label: "Open…" }, + DefaultChord { keys: &["Cmd+Alt+V"], id: "app.pasteSpecial", params: "", label: "Paste Special…" }, + DefaultChord { keys: &["Cmd+Shift+P"], id: "app.palette", params: "", label: "Command Palette" }, + DefaultChord { keys: &["Cmd+,"], id: "app.preferences", params: "", label: "Preferences…" }, + DefaultChord { keys: &["Cmd+=", "Cmd+Plus"], id: "view.zoomIn", params: "", label: "Zoom In" }, + DefaultChord { keys: &["Cmd+-"], id: "view.zoomOut", params: "", label: "Zoom Out" }, + DefaultChord { keys: &["Cmd+0"], id: "view.fit", params: "", label: "Fit to Window" }, + DefaultChord { keys: &["Cmd+F1"], id: "view.collapseRibbon", params: "", label: "Collapse the Ribbon" }, + DefaultChord { keys: &["Shift+F9"], id: "view.gridlines", params: "", label: "Gridlines" }, + DefaultChord { keys: &["Alt+F9"], id: "view.guides", params: "", label: "Guides" }, + DefaultChord { keys: &["Cmd+K"], id: "app.dialog", params: r#"{"id":"hyperlink"}"#, label: "Hyperlink…" }, + DefaultChord { keys: &["Cmd+F"], id: "app.find", params: "", label: "Find…" }, + DefaultChord { keys: &["Cmd+H"], id: "app.replace", params: "", label: "Replace…" }, + DefaultChord { keys: &["Shift+F7"], id: "review.thesaurusPane", params: "", label: "Thesaurus" }, +]; + +/// Chords that mean something else while slide text is edited, in the canvas editor's scope: Ctrl+] and Ctrl+[ grow +/// and shrink the font there, as Ctrl+Shift+> and < do, where they arrange the shape elsewhere. +const TEXT_EDITING_CHORDS: &[(&str, &str)] = &[("format.grow", "textEditor: Cmd+]"), ("format.shrink", "textEditor: Cmd+[")]; + +// The framework owns these ids; the engine keeps its command vocabulary. +const EDIT_IDS: &[(&str, &str)] = &[ + ("edit.cut", "edit.cut"), + ("edit.copy", "edit.copy"), + ("edit.paste", "edit.paste"), + ("edit.select_all", "edit.selectAll"), + ("edit.undo", "edit.undo"), + ("edit.redo", "edit.redo"), + ("edit.delete", "edit.delete"), +]; + +fn framework_id_of(id: &str) -> &str { + EDIT_IDS.iter().find(|(_, engine)| *engine == id).map_or(id, |(framework, _)| *framework) +} + +fn merge(defs: &mut BTreeMap, def: CommandDef) { + use std::collections::btree_map::Entry; + match defs.entry(def.command.key()) { + Entry::Vacant(entry) => { + entry.insert(def); + } + Entry::Occupied(mut entry) => { + let held = entry.get_mut(); + for binding in def.defaults { + if !held.defaults.contains(&binding) { + held.defaults.push(binding); + } + } + if held.paths.is_empty() { + held.paths = def.paths; + } + } + } +} + +/// Builds the app command catalogue and its defaults. +pub(crate) fn build(session: &Session, generation: u64) -> Result { + let mut defs = BTreeMap::new(); + for row in UI_COMMANDS { + merge(&mut defs, CommandDef::new(CommandRef::new(row.id), row.label, Scope::app())); + } + let mut taken = Vec::new(); + for row in DEFAULT_CHORDS { + let params = + if row.params.is_empty() { Value::Null } else { serde_json::from_str(row.params).map_err(|e| format!("{} parameters: {e}", row.id))? }; + let mut def = CommandDef::new(CommandRef::with_params(row.id, params), row.label, Scope::app()); + for key in row.keys { + let binding = Binding::parse(key).map_err(|e| format!("{} binding: {e}", row.id))?; + taken.push(binding.clone()); + def = def.with_default(binding); + } + merge(&mut defs, def); + } + let mut replacements = Vec::new(); + for row in session.commands() { + let id = framework_id_of(row.id); + let mut def = CommandDef::new(CommandRef::new(row.id), row.label, Scope::app()).with_path(row.menu.iter().map(|s| s.to_string()).collect()); + if let Some(key) = row.shortcut { + let binding = Binding::parse(key).map_err(|e| format!("{} binding: {e}", row.id))?; + if !taken.contains(&binding) { + def.defaults.push(binding); + } + } + for (_, key) in TEXT_EDITING_CHORDS.iter().filter(|(id, _)| *id == row.id) { + def.defaults.push(Binding::parse(key).map_err(|e| format!("{} binding: {e}", row.id))?); + } + if EDIT_IDS.iter().any(|(framework, _)| *framework == id) { + replacements.push((id.to_string(), def.defaults.clone())); + if id != row.id { + def.defaults.clear(); + } + } + merge(&mut defs, def); + } + let mut catalog = AppCatalog::new(defs.into_values().collect(), generation).map_err(|e| e.to_string())?; + for (id, bindings) in replacements { + catalog = catalog.replace_defaults(id, bindings); + } + // The document editor opens the app's Font dialog; there is no Character pane. + Ok(catalog.replace_defaults("textEditor.character_panel", Vec::new())) +} + +/// Whether an id belongs to an app UI command. +pub fn is_ui_command(id: &str) -> bool { + UI_COMMANDS.iter().any(|row| row.id == id) +} + +/// The engine id corresponding to a framework edit command. +pub(crate) fn edit_command_of(id: &str) -> &str { + EDIT_IDS.iter().find(|(framework, _)| *framework == id).map_or(id, |(_, engine)| *engine) +} + +/// Publishes enabled states and the ribbon command states. +pub(crate) fn command_states(app: &mut SlideApp) -> CommandStates { + let mut states = CommandStates::new(); + let has_document = app.session.active().is_some(); + for row in app.session.commands() { + let state = CommandState::new().enabled(row.enabled); + states.set(CommandRef::new(row.id), state.clone()); + if framework_id_of(row.id) != row.id { + states.set(CommandRef::new(framework_id_of(row.id)), state); + } + } + for row in UI_COMMANDS { + // The ribbon publisher owns these rows, including their enabled state. + if matches!(row.id, "app.find" | "show.start") { + continue; + } + states.set(CommandRef::new(row.id), CommandState::new().enabled(has_document || START_SCREEN.contains(&row.id))); + } + for def in app.catalog.defs() { + if def.command.key_text().as_ref() == def.command.id.as_str() { + continue; + } + let enabled = if def.command.id == "app.backstage" { + has_document + || def + .command + .params + .get("page") + .and_then(Value::as_str) + .and_then(crate::backstage::Page::parse) + .is_some_and(|page| !page.needs_doc()) + } else { + has_document || START_SCREEN.contains(&def.command.id.as_str()) + }; + states.set(def.command.clone(), CommandState::new().enabled(enabled)); + } + crate::ribbon::states::publish(app, &mut states); + states +} + +/// Commands admitted while no document is open. +pub(crate) const START_SCREEN: &[&str] = &["app.openDialog", "app.palette", "app.preferences", "app.backstage", "file.new"]; diff --git a/crates/ui-egui/src/app/clipboard.rs b/crates/ui-egui/src/app/clipboard.rs index f6003dd04..0c84b8188 100644 --- a/crates/ui-egui/src/app/clipboard.rs +++ b/crates/ui-egui/src/app/clipboard.rs @@ -1,15 +1,7 @@ +use super::keys::{color_image_png, paste_image_pixels}; use super::{SlideApp, Value, json}; - -/// Text put on the system clipboard when the copied objects (a rectangle, a picture, slides…) -/// carry no text. egui-winit drops Ctrl+V when the system clipboard is empty, so without it the -/// shortcut never reached the session and only the context menu could paste objects (#182). An -/// invisible word joiner, so a paste into another app adds nothing visible. -pub(crate) const OBJECTS_MARKER: &str = "\u{2060}"; - -/// What a copy/cut leaves on the system clipboard for the session's plain-text rendering `t`. -pub(crate) fn system_clipboard_text(t: &str) -> String { - if t.is_empty() { OBJECTS_MARKER.to_string() } else { t.to_string() } -} +use craft::platform::clipboard::HTML; +use craft::ui::runtime::commands::{ClipContent, ClipItem, ClipboardHandle}; /// Whether pasted `text` (and the clipboard's `html`) only name a picture that is on the clipboard /// too, as a browser's Copy Image leaves them: the picture's address, perhaps followed by its alt @@ -58,21 +50,83 @@ fn visible_text(html: &str) -> String { } impl SlideApp { - /// Offer the copy or cut on the system clipboard. - /// - /// Slides go out as plain text. Text goes out as HTML plus the same plain words, so a paste - /// back into DeckCraft still uses the internal clipboard. A textless shape leaves the - /// invisible [`OBJECTS_MARKER`] rather than a picture: with only an image on the clipboard - /// egui-winit drops Ctrl+V, and the shortcut could no longer paste the shape here (#182). - pub(super) fn publish_clipboard(&mut self, ctx: &egui::Context, cut: bool) { - let cmd = if cut { "edit.cut" } else { "edit.copy" }; - let Ok(v) = self.session.execute(cmd, &json!({})) else { return }; - let text = v.get("text").and_then(Value::as_str).unwrap_or("").to_string(); - let html = v.get("html").and_then(Value::as_str).unwrap_or("").to_string(); - if self.session.clipboard.slides.is_empty() && !html.is_empty() && self.services.clipboard_set_html.as_mut().is_some_and(|f| f(&html, &text)) - { - return; + /// Copies or cuts the selection and offers the engine's reply to the installed clipboard. + pub(crate) fn publish_clipboard(&mut self, ctx: &egui::Context, cut: bool) { + let command = if cut { "edit.cut" } else { "edit.copy" }; + if let Ok(reply) = self.run(command, json!({})) { + self.offer_clipboard(ctx, &reply); } - ctx.copy_text(system_clipboard_text(&text)); + } + + /// Offers an already executed copy reply without executing the command again. + pub(crate) fn offer_clipboard(&mut self, ctx: &egui::Context, reply: &Value) { + let text = reply.get("text").and_then(Value::as_str).unwrap_or(""); + let html = reply.get("html").and_then(Value::as_str).filter(|html| !html.is_empty()); + let items = if self.session.clipboard.slides.is_empty() + && let Some(html) = html + { + vec![ClipItem::Html(html.into()), ClipItem::Text(text.into())] + } else if !text.is_empty() { + vec![ClipItem::Text(text.into())] + } else { + return; + }; + if let Err(error) = ClipboardHandle::of(ctx).offer(&items) { + self.set_status(error.to_string()); + } + } + + /// Pastes this event's content, or reads the installed clipboard for a bare paste chord. + pub(crate) fn paste(&mut self, ctx: &egui::Context, pasted: Option) { + let result = (|| -> Result<(), String> { + let clipboard = ClipboardHandle::of(ctx); + let pasted = pasted.unwrap_or_default(); + if let Some(image) = pasted.image { + return self.paste_picture(&image); + } + let event_text = pasted.text.filter(|text| !text.is_empty()); + let read_image = || -> Result, String> { + let Some(image) = clipboard.read_image().map_err(|e| e.to_string())? else { return Ok(None) }; + let size = [image.width as usize, image.height as usize]; + paste_image_pixels(size)?; + Ok(Some(egui::ColorImage::from_rgba_unmultiplied(size, &image.rgba))) + }; + if event_text.is_none() + && let Some(image) = read_image()? + { + return self.paste_picture(&image); + } + let html = clipboard + .read(&[HTML]) + .map_err(|e| e.to_string())? + .map(|flavor| String::from_utf8(flavor.data).map_err(|e| format!("invalid clipboard HTML: {e}"))) + .transpose()? + .filter(|html| !html.is_empty()); + if event_text.as_deref().is_some_and(|text| names_a_picture(text, html.as_deref())) + && let Some(image) = read_image()? + { + return self.paste_picture(&image); + } + let text = match event_text { + Some(text) => Some(text.to_string()), + None => clipboard.read_text().map_err(|e| e.to_string())?.filter(|text| !text.is_empty()), + }; + let mut params = json!({}); + if let Some(text) = text { + params["text"] = json!(text); + } + if let Some(html) = html { + params["html"] = json!(html); + } + self.run("edit.paste", params).map(|_| ()) + })(); + if let Err(error) = result { + self.set_status(error); + } + } + + pub(super) fn paste_picture(&mut self, image: &egui::ColorImage) -> Result<(), String> { + let png = color_image_png(image)?; + self.run("insert.picture", json!({"name": "Pasted image.png", "data": deckcraft_engine::cmd::base64_encode(&png)})).map(|_| ()) } } diff --git a/crates/ui-egui/src/app/commands.rs b/crates/ui-egui/src/app/commands.rs index e5c43af1a..39bfb65c4 100644 --- a/crates/ui-egui/src/app/commands.rs +++ b/crates/ui-egui/src/app/commands.rs @@ -1,6 +1,13 @@ +use super::catalog::{START_SCREEN, edit_command_of, is_ui_command}; +use super::files::SaveOutcome; #[cfg(not(target_arch = "wasm32"))] use super::updates_ui; -use super::{SlideApp, UI_COMMANDS, Value, ViewMode, backstage, dialogs, doc_window, json, media, qat, theme}; +use super::{SlideApp, Value, ViewMode, backstage, doc_window, json, media, qat}; +use craft::ui::patterns::panels::CommandPalette; +use craft::ui::runtime::commands::{FirePhase, FireSource, Fired}; + +/// Grid spacing in points accepted by the command and its form. +pub(crate) const GRID_SPACING_RANGE: std::ops::RangeInclusive = 1.0..=288.0; fn grid_options_touched(p: &Value) -> bool { ["spacing", "snap", "smartGuides", "gridlines", "guides"].iter().any(|k| p.get(*k).is_some()) @@ -18,28 +25,53 @@ impl SlideApp { /// Run a command by id (UI commands here, everything else in the engine). Errors show in the /// status bar and are returned. pub fn run(&mut self, id: &str, params: Value) -> Result { - let r = if UI_COMMANDS.iter().any(|c| c.0 == id) { + // The current slide by place and by id: a delete or an undo can put another slide at the same place. + let current = |d: &deckcraft_engine::DocState| (d.uid, d.selection.slide, d.current_slide().map(|slide| slide.id)); + let before = self.session.active().map(current); + let r = if is_ui_command(id) { self.run_ui(id, ¶ms) - } else if id == "file.save" && self.services.host_save.is_some() && params.get("path").is_none() { - // A page that keeps the files (`?host=parent`): Save by id (the command palette) goes - // to the page like Ctrl+S. The engine would write to the presentation's path, which a - // browser can't. - self.save_to_host(None).map(|name| json!({"path": name})) + } else if id == "file.save" && self.host.files().saves_to_page() && params.get("path").is_none() { + match self.session.active() { + Some(d) => { + let uid = d.uid; + let name = d + .path + .as_deref() + .and_then(|path| std::path::Path::new(path).file_name()) + .map(|name| name.to_string_lossy().into_owned()) + .unwrap_or_else(|| format!("{}.deckcraft", d.title())); + match self.save_document(uid) { + SaveOutcome::Saved | SaveOutcome::Downloaded => Ok(json!({"path": name})), + SaveOutcome::Pending => Ok(json!({"path": name, "pending": true})), + SaveOutcome::Cancelled => Err("The save was cancelled".into()), + SaveOutcome::Failed(reason) => Err(reason), + } + } + None => Err("no presentation is open".into()), + } } else { self.session.execute(id, ¶ms).map_err(|e| e.to_string()) }; match &r { - // Copy and Cut from the ribbon, menus, the slide's context menu or the control channel - // put the text on the system clipboard, as Ctrl+C and Ctrl+X do (#431). - Ok(v) if matches!(id, "edit.copy" | "edit.cut") => { - if let Some(t) = v.get("text").and_then(Value::as_str) { - self.pending_copy = Some(t.to_string()); + Ok(v) if matches!(id, "comment.next" | "comment.prev") => { + if let (Some(slide), Some(index)) = ( + v.get("slide").and_then(Value::as_u64).and_then(|n| usize::try_from(n).ok()), + v.get("index").and_then(Value::as_u64).and_then(|n| usize::try_from(n).ok()), + ) { + // PLAN: assumed crate::panels::comments::focus_comment(app: &mut SlideApp, slide: usize, index: usize) -> () (panels-w13) + crate::panels::comments::focus_comment(self, slide, index); + let _ = self.run_ui("view.pane", &json!({"pane": "comments"})); } } Ok(_) => {} Err(e) => self.set_status(e.clone()), } self.drain_requests(); + if let Some(d) = self.session.active() + && before != Some(current(d)) + { + self.slide_reveal = d.current_slide().map(|slide| slide.id); + } r } @@ -49,6 +81,20 @@ impl SlideApp { fn run_ui(&mut self, id: &str, p: &Value) -> Result { match id { + "tool.set" => { + let requested: deckcraft_engine::ToolKind = serde_json::from_value(p.clone()).map_err(|e| format!("invalid tool: {e}"))?; + let kind = if p.get("toggle").and_then(Value::as_bool).unwrap_or(false) && self.session.tool.kind == requested { + deckcraft_engine::ToolKind::Select + } else { + requested + }; + self.session.set_tool(kind); + } + "view.handoutPerPage" => { + let n = p.get("n").and_then(Value::as_u64).filter(|n| matches!(*n, 1 | 2 | 3 | 4 | 6 | 9)).ok_or("`n` must be 1, 2, 3, 4, 6 or 9")?; + self.ui.handout_per_page = n as u8; + return Ok(json!({"n": n})); + } "view.normal" => self.ui.view = ViewMode::Normal, "view.outline" => self.ui.view = ViewMode::Outline, "view.sorter" => self.ui.view = ViewMode::Sorter, @@ -70,7 +116,7 @@ impl SlideApp { None => None, Some(raw) => { let n = raw.as_f64().filter(|v| v.is_finite()).ok_or("`spacing` must be a finite number of points")?; - if !(1.0..=288.0).contains(&n) { + if !GRID_SPACING_RANGE.contains(&n) { return Err("`spacing` must be from 1 to 288 points".into()); } Some(n) @@ -101,7 +147,7 @@ impl SlideApp { } } } else { - self.dialog = Some(dialogs::Dialog::new("gridOptions")); + self.open_dialog("gridOptions", p.clone()); } return Ok(json!({ "spacing": self.session.prefs.grid_spacing, @@ -112,7 +158,7 @@ impl SlideApp { })); } "view.zoomIn" | "view.zoomOut" => { - let cur = self.ui.zoom.unwrap_or(self.canvas_scale); + let cur = self.ui.zoom.unwrap_or_else(|| self.canvas_scale()); let steps = [0.1, 0.25, 0.33, 0.5, 0.66, 0.75, 1.0, 1.25, 1.5, 2.0, 3.0, 4.0]; let next = if id == "view.zoomIn" { steps.iter().copied().find(|s| *s > cur + 0.01).unwrap_or(4.0) @@ -125,7 +171,7 @@ impl SlideApp { let pct = p.get("percent").and_then(Value::as_f64).ok_or("missing `percent`")?; self.ui.zoom = Some((pct as f32 / 100.0).clamp(0.1, 4.0)); } - "view.zoomDialog" => self.dialog = Some(dialogs::Dialog::new("zoom")), + "view.zoomDialog" => self.open_dialog("zoom", p.clone()), "view.fit" => self.ui.zoom = None, "review.thesaurusPane" => { let word = match p.get("word").and_then(Value::as_str) { @@ -155,9 +201,8 @@ impl SlideApp { } "view.collapseRibbon" => self.ui.ribbon_collapsed = !self.ui.ribbon_collapsed, "view.dark" => { - let on = self.flag(p, self.ui.brightness == theme::Brightness::Dark); - self.ui.brightness = if on { theme::Brightness::Dark } else { theme::Brightness::Light }; - self.restyle = true; + let on = self.flag(p, self.ui.brightness == crate::Brightness::Dark); + self.ui.brightness = if on { crate::Brightness::Dark } else { crate::Brightness::Light }; } "view.grayscale" => self.ui.grayscale = self.flag(p, self.ui.grayscale), "view.newWindow" => return doc_window::command(self, p), @@ -168,11 +213,13 @@ impl SlideApp { let from = self.show_from(p)?.unwrap_or_else(|| self.show_start_index()); self.start_show(from, false); } + if let Some(show) = self.show.as_mut() { + show.rehearse = p.get("rehearse").and_then(Value::as_bool).unwrap_or(false); + } } "show.presenter" => { self.ui.presenter_view = self.flag(p, self.ui.presenter_view); - // The browser build has one viewport: presenter view is drawn inside the page. - return Ok(json!({"on": self.ui.presenter_view, "window": !cfg!(target_arch = "wasm32")})); + return Ok(json!({"on": self.ui.presenter_view, "window": !cfg!(target_arch = "wasm32") || self.services.presenter.is_some()})); } "show.keepCursor" => { self.ui.show_keep_cursor = self.flag(p, self.ui.show_keep_cursor); @@ -216,6 +263,11 @@ impl SlideApp { return Err(format!("File › {} needs an open presentation", page.label())); } self.open_backstage(page); + if p.get("keyboard").and_then(Value::as_bool).unwrap_or(false) + && let Some(backstage) = self.backstage.as_mut() + { + backstage.focus_shown = true; + } return Ok(json!({"page": page.id()})); } "app.closePresentation" => self.close_presentation(), @@ -225,7 +277,7 @@ impl SlideApp { } return Ok(json!({"printed": self.print_pdf(p.clone())})); } - "app.about" => self.dialog = Some(dialogs::Dialog::new("about")), + "app.about" => self.open_dialog("about", p.clone()), "app.checkUpdates" => { // Nightly is updated by ArtCraft Launcher; its stable updater must stay idle. #[cfg(not(target_arch = "wasm32"))] @@ -233,28 +285,49 @@ impl SlideApp { #[cfg(target_arch = "wasm32")] return Err("updates are handled by the browser: reload the page".into()); } - "app.palette" => self.palette = Some((String::new(), 0)), - "app.preferences" => self.dialog = Some(dialogs::Dialog::new("preferences")), + "app.palette" => { + if !self.palette_open { + self.palette_state = Default::default(); + } + self.palette_open = true; + } + "app.preferences" => self.open_dialog("preferences", p.clone()), "app.openDialog" => self.pick_and_open(), + "app.forgetRecent" => { + let path = p.get("path").and_then(Value::as_str).ok_or("missing `path`")?; + if !self.ui.recent.iter().any(|recent| recent == path) { + return Err(format!("`{path}` is not in the Recent list")); + } + self.forget_recent(path); + return Ok(json!({"recent": self.ui.recent})); + } "app.insertPictureDialog" => self.pick_and_insert("picture", "insert.picture"), "app.smartArtPictureDialog" => { - if self.services.pick_open.is_none() { + if !self.host.files().can_pick() { return Err("picking a Diagram picture needs the desktop app".into()); } - self.pick_and_run("picture", "smartArt.picture", p); + self.pick_and_run("picture", "smartArt.picture", p.clone()); } "app.changePictureDialog" => self.pick_and_insert("picture", "picture.change"), "app.insertAudioDialog" => self.pick_and_insert("audio", "insert.audio"), - "app.reuseSlidesDialog" => self.pick_and_reuse(p.get("keepFormatting").and_then(Value::as_bool).unwrap_or(false)), + "app.reuseSlidesDialog" => { + let keep = p.get("keepFormatting").and_then(Value::as_bool).unwrap_or(false); + if let Some(path) = p.get("path").and_then(Value::as_str) { + // PLAN: assumed SlideApp::begin_reuse(&mut self, path: String, keep: bool) (shell-w6) + self.begin_reuse(path.to_string(), keep); + } else { + self.pick_and_reuse(keep); + } + } "app.insertVideoDialog" => self.pick_and_insert("video", "insert.video"), "app.saveAsDialog" => self.save_as_dialog("deckcraft"), - "app.exportDialog" => self.dialog = Some(dialogs::Dialog::new("export")), - "app.pasteSpecial" => self.dialog = Some(dialogs::Dialog::new("pasteSpecial")), + "app.exportDialog" => self.open_dialog("export", p.clone()), + "app.pasteSpecial" => self.open_dialog("pasteSpecial", p.clone()), "app.browseThemeDialog" => { if self.session.active().is_none() { return Err("open a presentation first".into()); } - if self.services.pick_open.is_some() { + if self.host.files().can_pick() { self.pick_and_insert("theme", "design.browseTheme"); } else { // The browser's asynchronous picker would open the file as a new document. @@ -263,16 +336,14 @@ impl SlideApp { } "app.qat" => return qat::command(self, p), "app.find" | "app.replace" if self.session.active().is_some() => { - let mut d = dialogs::Dialog::new("find"); - d.fields.insert("replace".into(), if id == "app.replace" { "1" } else { "0" }.into()); - self.dialog = Some(d); + self.open_dialog("find", json!({"replace": id == "app.replace"})); } - "app.find" | "app.replace" => self.palette = Some((String::new(), 0)), + "app.find" | "app.replace" => return self.run_ui("app.palette", &Value::Null), "app.compareDialog" => { if self.session.active().is_none() { return Err("open the presentation to compare first".into()); } - if self.services.pick_open.is_some() { + if self.host.files().can_pick() { self.pick_and_insert("open", "review.compare"); } else { // The browser's asynchronous picker would open the file as a new document. @@ -281,7 +352,7 @@ impl SlideApp { } "app.dialog" => { let d = p.get("id").and_then(Value::as_str).ok_or("missing `id`")?; - self.dialog = Some(dialogs::Dialog::new(d)); + self.open_dialog(d, p.clone()); } "app.links" => { use deckcraft_engine::links::{APP_PAGE, APPS, DISCORD, GITHUB, WEBSITE}; @@ -292,3 +363,40 @@ impl SlideApp { Ok(Value::Null) } } + +impl SlideApp { + /// Runs a fired command using the clipboard installed in this pass's context. + pub(crate) fn fire(&mut self, ctx: &egui::Context, fired: &Fired) { + if fired.phase == FirePhase::Release { + return; + } + let id = edit_command_of(&fired.command.id); + if self.session.active().is_none() && !START_SCREEN.contains(&id) { + return; + } + // The File view covers the slide: its keys edit nothing behind it. + if fired.source == FireSource::Key && self.backstage_open() && (id.starts_with("edit.") || id.starts_with("text.")) { + return; + } + if fired.source == FireSource::Palette { + CommandPalette::remember(&mut self.palette_recents, fired.command.clone()); + } + match id { + "edit.paste" => self.paste(ctx, fired.pasted.clone()), + "edit.copy" | "edit.cut" if fired.command.key_text().as_ref() == fired.command.id.as_str() => { + self.publish_clipboard(ctx, id == "edit.cut"); + } + "file.save" if fired.command.params.get("path").is_none() => self.save(), + "show.fromStart" => self.start_show(self.show_start_index(), false), + "review.spelling" => self.open_dialog("spelling", fired.command.params.clone()), + id => { + let params = if fired.command.params.is_null() { json!({}) } else { fired.command.params.clone() }; + if let Ok(reply) = self.run(id, params) + && matches!(id, "edit.copy" | "edit.cut") + { + self.offer_clipboard(ctx, &reply); + } + } + } + } +} diff --git a/crates/ui-egui/src/app/control.rs b/crates/ui-egui/src/app/control.rs index 81e6c4798..77b4ec1f8 100644 --- a/crates/ui-egui/src/app/control.rs +++ b/crates/ui-egui/src/app/control.rs @@ -1,45 +1,51 @@ -use super::{SlideApp, json}; +use craft::automation::screenshot::settle_ms; +use craft::ui::runtime::{frame, windows::WindowHost}; + +use super::SlideApp; use crate::control; impl SlideApp { - /// Drain pending control requests, executing ordinary requests and admitting screenshots for - /// later saving and reply. - pub(super) fn drain_control(&mut self, ctx: &egui::Context) { - let Some(rx) = self.control_rx.take() else { return }; - while let Ok(req) = rx.try_recv() { - // A request whose sender gave up waiting (reply timeout) must not run late (#719). - if !req.take() { - continue; - } - let reply = req.reply.clone(); - let revision = self.session.active().map(|d| d.revision); - match control::handle(self, ctx, &req) { - control::Outcome::Done(v) => { - let _ = reply.send(v); - } - control::Outcome::Screenshot { path } => { - let doc = self.session.active().map(|d| d.uid); - if let Err(e) = self.capture.admit(path, reply.clone(), doc, web_time::Instant::now()) { - let _ = reply.send(json!({"ok": false, "error": e})); - } - } - } - if self.session.active().map(|d| d.revision) != revision { - self.note_application_edit(ctx); - } + /// Drains requests between injected gestures, once a frame before its input: a request is input, which enters a + /// frame's first pass only, and the command states the frame's passes show are taken after it ran. + pub(crate) fn drain_control(&mut self, ctx: &egui::Context) { + let Some(mut channel) = self.control.take() else { return }; + let host = WindowHost::of(ctx); + if host.injected_idle() { + channel.poll_access_trees(ctx); } - self.control_rx = Some(rx); + while host.injected_idle() { + let Some(request) = channel.next_request() else { break }; + let reply = control::handle(self, ctx, &request); + channel.settle(request, reply, control::document_id(self), settle_ms(ctx.global_style().animation_time)); + } + let document = control::document_id(self); + channel.captures.note_windows(&host, document); + let finished = channel.captures.drain(craft::ui::runtime::motion::now(), document); + control::finish_captures(self, &mut channel, finished); + self.control = Some(channel); } - /// Save completed screenshots on the app thread and send exactly one reply each. - pub(super) fn drain_screenshots(&mut self) { - let doc = self.session.active().map(|d| d.uid); - let completed = self.capture.drain(web_time::Instant::now(), doc); - for c in completed { - let v = control::save_screenshot(self, c.image.as_ref(), c.path.as_deref()); - // Keep the aggregate charged through RGBA/PNG/base64 encoding and the write. - self.capture.release(c.reserved); - let _ = c.reply.send(v); + /// Polls input after each pass and issues captures only after the accepted layout. + /// A rerun contributes no capture settling pass or issue. + pub(crate) fn issue_captures(&mut self, ui: &mut egui::Ui) { + let Some(mut channel) = self.control.take() else { return }; + let host = WindowHost::of(ui.ctx()); + // PLAN: plan error: input polling belongs at UI pass end, not in the logic phase specified by writer note 1 + channel.poll_input(&host); + if frame::will_rerun(ui.ctx()) { + self.control = Some(channel); + return; } + let document = control::document_id(self); + channel.captures.note_windows(&host, document); + channel.captures.note_pass(); + let finished = channel.captures.issue(&host, craft::ui::runtime::motion::now(), document); + control::finish_captures(self, &mut channel, finished); + // A capture settles over passes and waits out its delay, and the renderer reads an issued one back as it submits + // a later frame; an idle window would draw no more of them. + if channel.captures.any_unissued() || channel.captures.any_pending() { + ui.ctx().request_repaint(); + } + self.control = Some(channel); } } diff --git a/crates/ui-egui/src/app/document_focus.rs b/crates/ui-egui/src/app/document_focus.rs deleted file mode 100644 index fee5c624b..000000000 --- a/crates/ui-egui/src/app/document_focus.rs +++ /dev/null @@ -1,125 +0,0 @@ -//! The document window (the slide canvas, the slide sorter or the notes page) as the window's one document canvas: its -//! widget, its Tab stop and when it takes the keyboard focus. - -use craft_ui::runtime::overlay::{self, OpenFilter}; - -use super::{SlideApp, ViewMode}; -use crate::framework::{document_id, focus_document, focused_widget, host_canvas}; - -/// How many passes the document asks for the focus: egui names the widget of a closed palette, dialog or menu as -/// focused for one pass after it was last drawn. -const ASKING_PASSES: u8 = 2; - -/// What the document window's focus depends on from pass to pass. -#[derive(Default)] -pub(crate) struct DocumentFocus { - /// The presentation (its uid) whose document window the pass drew; `None` on the start screen, the File tab and in - /// a slide show. - pub(super) drawn: Option, - /// The passes left in which a presentation that opened or became active asks for the focus. - opened: u8, - /// The passes left in which the document asks for the focus after a dialog, menu or popup closed. - uncovered: u8, -} - -impl SlideApp { - /// Draws the document window's widget over `rect` and declares it as the window's canvas. A press in it gives it - /// the focus, unless a dialog is open. Real presses only: with the document focused, egui makes Enter and Space - /// clicks of it. - pub(crate) fn document_widget(&mut self, ui: &egui::Ui, rect: egui::Rect, sense: egui::Sense) -> egui::Response { - let resp = ui.interact(rect, document_id(), sense); - self.document_focus.drawn = self.session.active().map(|d| d.uid); - host_canvas(ui.ctx(), self.document_keeps_tab(ui.ctx())); - if resp.is_pointer_button_down_on() && ui.input(|i| i.pointer.any_pressed()) && !self.dialog_open(ui.ctx()) { - focus_document(ui.ctx()); - } - resp - } - - /// [`Self::document_widget`] behind widgets that take the presses (the slide sorter's thumbnails): a press on any of - /// them gives the document the focus, unless a text field has it. - pub(crate) fn document_behind(&mut self, ui: &egui::Ui, rect: egui::Rect) { - self.document_widget(ui, rect, egui::Sense::focusable_noninteractive()); - let pressed = ui.input(|i| i.pointer.any_pressed()) && ui.rect_contains_pointer(rect); - if pressed && !ui.ctx().text_edit_focused() && !self.overlay_open(ui.ctx()) { - focus_document(ui.ctx()); - } - } - - /// Whether the document window is the slide being edited, where Tab can have work. - fn editing_slide(&self) -> bool { - self.backstage.is_none() && matches!(self.ui.view, ViewMode::Normal | ViewMode::Outline | ViewMode::Reading) - } - - /// Whether the focused document keeps Tab: on the slide, while the session has something for it to do. A modal - /// dialog, a menu or a popup that is up gets it instead. - fn document_keeps_tab(&self, ctx: &egui::Context) -> bool { - self.editing_slide() && self.session.tab_has_work() && !self.overlay_open(ctx) - } - - /// Whether a dialog, DeckCraft's or a modal one of the framework's, the palette or the opening overlay is up. - fn dialog_open(&self, ctx: &egui::Context) -> bool { - self.dialog.as_ref().is_some_and(|d| d.modal()) - || self.palette.is_some() - || self.opening.is_some() - || overlay::any_open(ctx, OpenFilter::Modal) - } - - /// Whether a dialog ([`Self::dialog_open`]), or an egui menu or popup, is up. - fn overlay_open(&self, ctx: &egui::Context) -> bool { - self.dialog_open(ctx) || ctx.any_popup_open() || egui::Popup::is_any_open(ctx) - } - - /// Whether the document may take the focus: no text field and no widget of another layer (the framework's update - /// notice) has it. - fn focus_is_free(ctx: &egui::Context) -> bool { - let layer = |id| ctx.read_response(id).map(|widget| widget.layer_id); - !ctx.text_edit_focused() && focused_widget(ctx).is_none_or(|id| layer(id) == layer(document_id())) - } - - /// Ends the document window's pass, after the views; `before` is the presentation the last pass drew. The pass's - /// input has changed what Tab has to do, so the document is declared again. A presentation that opened or became - /// active asks for the focus. So does the document with nothing focused, when a dialog, menu or popup has closed, and - /// while Tab has work on the slide (a ribbon field committed with Enter leaves nothing focused). All wait for the - /// last dialog, menu or popup to close. - pub(super) fn finish_document(&mut self, ctx: &egui::Context, before: Option) { - let drawn = self.document_focus.drawn; - if drawn.is_none() { - self.document_focus.opened = 0; - self.document_focus.uncovered = 0; - return; - } - let keeps_tab = self.document_keeps_tab(ctx); - host_canvas(ctx, keeps_tab); - if drawn != before { - self.document_focus.opened = ASKING_PASSES; - } - if self.overlay_open(ctx) { - self.document_focus.uncovered = ASKING_PASSES; - return; - } - let unfocused = ctx.memory(|m| m.focused().is_none()); - let DocumentFocus { opened, uncovered, .. } = &mut self.document_focus; - if *opened == 0 && *uncovered == 0 && !(unfocused && keeps_tab) { - return; - } - if unfocused || (*opened > 0 && Self::focus_is_free(ctx)) { - (*opened, *uncovered) = (0, 0); - focus_document(ctx); - } else { - (*opened, *uncovered) = (opened.saturating_sub(1), uncovered.saturating_sub(1)); - ctx.request_repaint(); - } - } - - /// While slide text is being edited, the text owns the keyboard (#93). The focus on an ordinary widget (the ribbon - /// button whose Space inserted the text box) would swallow every later key and end text entry, and with nothing - /// focused (a ribbon field committed with Enter) Tab would leave the text. The document takes the focus; a text - /// field or an open menu keeps its keys. - pub(super) fn edited_text_takes_focus(&self, ctx: &egui::Context) { - let editing = self.editing_slide() && self.session.active().is_some_and(|d| d.selection.text.is_some()); - if editing && !ctx.memory(|m| m.has_focus(document_id())) && !self.overlay_open(ctx) && Self::focus_is_free(ctx) { - focus_document(ctx); - } - } -} diff --git a/crates/ui-egui/src/app/files.rs b/crates/ui-egui/src/app/files.rs index 5d2d49d37..c39560afa 100644 --- a/crates/ui-egui/src/app/files.rs +++ b/crates/ui-egui/src/app/files.rs @@ -1,71 +1,98 @@ -use super::{ - FilePlace, FilePurpose, FileTarget, InboxEvent, LocatedPlace, PendingFile, RECENT_MAX, SlideApp, Target, UiRequest, Value, ViewMode, dialogs, - json, media, -}; +use std::cell::RefCell; +use std::path::{Path, PathBuf}; +use std::rc::Rc; +use std::sync::Arc; -#[derive(Default)] -pub(crate) struct PrintPreviews(Vec); +use craft::host::{PickId, PickRequest, Picked, WriteIntent}; +use deckcraft_engine::cmd::file::{format_for_path, mark_saved_snapshot, save_bytes}; +use deckcraft_model::Presentation; -impl PrintPreviews { - fn create(&mut self, title: &str) -> std::io::Result { - self.create_in(&std::env::temp_dir(), title) - } +use super::{FilePlace, FilePurpose, FileTarget, LocatedPlace, RECENT_MAX, SlideApp, Target, UiRequest, Value, ViewMode, json, media}; +use crate::PendingFile; - fn create_in(&mut self, base: &std::path::Path, title: &str) -> std::io::Result { - let dir = create_private_print_dir(base)?; - self.0.push(dir.clone()); - let safe: String = title.chars().map(|c| if c.is_alphanumeric() || c == ' ' || c == '-' { c } else { '_' }).collect(); - Ok(dir.join(format!("{safe} (print).pdf"))) - } - - fn discard(&mut self, path: &std::path::Path) { - if let Some(dir) = path.parent() { - let _ = std::fs::remove_dir_all(dir); - self.0.retain(|owned| owned != dir); - } - } - - pub(crate) fn cleanup(&mut self) { - for dir in self.0.drain(..) { - let _ = std::fs::remove_dir_all(dir); - } - } +/// The operation retained until its picker answers. +#[derive(Clone)] +pub(crate) enum FileOperation { + /// Open or infer an operation from the supplied file. + Apply(FilePurpose), + /// Execute the captured command on the captured place. + Command { + /// The picker purpose, including the picture-bytes parameter policy. + purpose: String, + /// The registered command id. + command: String, + /// Parameters captured before the picker opens. + params: Value, + }, + /// Offer slides from the supplied bytes without reading them again. + Reuse { + /// Whether inserted slides retain their source formatting. + keep: bool, + }, + /// Finish a document save or an exported copy. + Save(SaveTransfer), } -impl Drop for PrintPreviews { - fn drop(&mut self) { - self.cleanup(); - } +/// Serialized files and the completion shared by every copy in an export. +#[derive(Clone)] +pub(crate) struct SaveTransfer { + snapshot: Option>, + files: Vec<(String, Vec)>, + write_on_answer: bool, + save_as: bool, + batch: Rc>, } -fn create_private_print_dir(base: &std::path::Path) -> std::io::Result { - use std::sync::atomic::{AtomicU64, Ordering}; - static NEXT_DIR: AtomicU64 = AtomicU64::new(0); - - for _ in 0..128 { - let id = NEXT_DIR.fetch_add(1, Ordering::Relaxed); - let path = base.join(format!("deckcraft-print-{}-{id}", std::process::id())); - #[cfg(unix)] - let mut builder = std::fs::DirBuilder::new(); - #[cfg(not(unix))] - let builder = std::fs::DirBuilder::new(); - #[cfg(unix)] - { - use std::os::unix::fs::DirBuilderExt; - builder.mode(0o700); - } - match builder.create(&path) { - Ok(()) => return Ok(path), - Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue, - Err(e) => return Err(e), - } - } - Err(std::io::Error::new(std::io::ErrorKind::AlreadyExists, "could not allocate a unique print preview directory")) +struct SaveBatch { + uid: u64, + remaining: usize, + outcome: SaveOutcome, + instance: Option>, + deferred: bool, } +/// The closing prompt's save result, including an outstanding file ticket. +#[derive(Clone, Debug)] +pub(crate) enum SaveOutcome { + /// The service keeps a file of the serialized snapshot. + Saved, + /// The browser handed over a copy without recording a document file. + Downloaded, + /// The service could not complete the operation. + Failed(String), + /// The user dismissed the picker. + Cancelled, + /// The ticket has not answered yet. + Pending, +} + +fn succeeded(outcome: &SaveOutcome) -> bool { + matches!(outcome, SaveOutcome::Saved | SaveOutcome::Downloaded) +} + +fn captures_shapes(command: &str) -> bool { + matches!(command, "shape.fill" | "picture.change") +} + +fn open_request(purpose: &str) -> PickRequest { + let request = PickRequest::open(purpose); + match purpose { + "picture" => request.filter("Pictures", &["png", "jpg", "jpeg", "gif", "webp", "bmp", "tif", "tiff"]), + "audio" => request + .filter("Audio", &["wav", "mp3", "m4a", "m4b", "aac", "flac", "ogg", "oga", "opus", "aif", "aiff", "aifc", "caf", "wma", "weba", "mka"]), + "video" => request.filter("Video", &["mp4", "m4v", "mov", "webm", "mkv", "wmv"]), + "theme" => request.filter("Themes and presentations", &["thmx", "pptx", "potx", "ppsx"]).filter("Office Theme", &["thmx"]), + _ => request + .filter("Presentations", &["deckcraft", "pptx", "potx", "ppsx", "ppt", "pot", "pps"]) + .filter("DeckCraft", &["deckcraft"]) + .filter("PowerPoint", &["pptx", "potx", "ppsx"]) + .filter("PowerPoint 97-2003", &["ppt", "pot", "pps"]) + .filter("Outline", &["txt", "md", "rtf"]), + } +} fn purpose_of(purpose: &str) -> FilePurpose { match purpose { - "open" => FilePurpose::Open, + "document" | "open" => FilePurpose::Open, "picture" => FilePurpose::Picture, "audio" => FilePurpose::Audio, "video" => FilePurpose::Video, @@ -151,7 +178,7 @@ impl SlideApp { if path.starts_with("\\\\") || path.contains("://") { return true; } - let ok = std::path::Path::new(path).is_file(); + let ok = self.host.files().exists(Path::new(path)); if self.recent_checked.len() > 64 { let live: std::collections::HashSet<&String> = self.ui.recent.iter().collect(); self.recent_checked.retain(|p, _| live.contains(p)); @@ -172,7 +199,7 @@ impl SlideApp { pub fn close_presentation(&mut self) { match self.session.active() { None => {} - Some(d) if d.is_dirty() => self.dialog = Some(dialogs::Dialog::new("close")), + Some(d) if d.is_dirty() => self.start_closing(craft::quit::CloseScope::Close, vec![d.uid]), Some(_) => { let _ = self.run("file.close", json!({})); } @@ -186,11 +213,16 @@ impl SlideApp { } /// Exports the active presentation as `fmt` (`pdf`, `png`, `pngAll`, `jpeg`, `jpegAll`, `pptx`, - /// `deckcraft`, `outline`) through `file.export`: the save picker on the desktop, a download - /// on the web. `extra` adds `file.export` params (the PDF's layout, slides…). The - /// presentation keeps its own file. Returns whether a file was written or handed over. + /// `deckcraft`, `outline`) through the installed file service. `extra` supplies export options. + /// The presentation keeps its own file; a pending ticket returns false until it settles. pub fn export_as(&mut self, fmt: &str, extra: Value) -> bool { - let Some(slide) = self.session.active().map(|d| d.selection.slide) else { return false }; + succeeded(&self.export_copies(fmt, extra, None)) + } + + fn export_copies(&mut self, fmt: &str, extra: Value, instance: Option>) -> SaveOutcome { + let Some((uid, doc, slide, title)) = self.session.active().map(|d| (d.uid, d.doc.clone(), d.selection.slide, d.title())) else { + return SaveOutcome::Failed("no presentation is open".into()); + }; let (ext, format, all) = match fmt { "pdf" => ("pdf", "pdf", false), "png" => ("png", "png", false), @@ -202,76 +234,52 @@ impl SlideApp { "rtf" => ("rtf", "rtf", false), "deckcraft" => ("deckcraft", "deckcraft", false), "gif" => ("gif", "gif", false), - other => { - self.set_status(format!("DeckCraft can't export “{other}”")); - return false; - } + other => return self.file_failure(format!("DeckCraft can't export “{other}”")), }; let suggested = self.suggested_name(ext); - if let Some(pick) = self.services.pick_save.as_mut() { - let Some(path) = pick(&suggested) else { return false }; - let mut params = json!({"path": path, "format": format, "all": all}); - if let (Some(o), Some(x)) = (params.as_object_mut(), extra.as_object()) { - o.extend(x.clone()); - } - return match self.run("file.export", params) { - Ok(_) => { - self.set_status(format!("Exported {path}")); - true - } - Err(_) => false, - }; - } - let Some(doc) = self.session.active().map(|d| d.doc.clone()) else { return false }; - let bytes = match format { + let files = match format { "png" | "jpeg" => { - // Every slide for "all slides", one download each, named like the desktop export (#64). - let name = self.session.active().map(|d| d.title()).unwrap_or_else(|| "Presentation".into()); - let mut any = false; let transparent = extra.get("transparentBackground").and_then(Value::as_bool).unwrap_or(false); - for (file, bytes) in web_image_files(&doc, slide, all, &name, ext, transparent) { - any = self.download(&file, Ok(bytes)) || any; + web_image_files(&doc, slide, all, &title, ext, transparent) + } + _ => { + let bytes = match format { + "pdf" => deckcraft_engine::cmd::file::pdf_bytes(&doc, &extra), + "gif" => deckcraft_engine::cmd::file::gif_bytes(&doc, &extra), + other => save_bytes(&doc, other), + }; + match bytes { + Ok(bytes) => vec![(suggested.clone(), bytes)], + Err(e) => return self.file_failure(e.to_string()), } - return any; } - "pdf" => deckcraft_engine::cmd::file::pdf_bytes(&doc, &extra), - "gif" => deckcraft_engine::cmd::file::gif_bytes(&doc, &extra), - other => deckcraft_engine::cmd::file::save_bytes(&doc, other), }; - self.download(&suggested, bytes) - } - - /// Hands `bytes` to the browser as a download (web); false (with the reason in the status - /// bar) when there are no bytes or no way to download. - fn download(&mut self, name: &str, bytes: deckcraft_engine::Result>) -> bool { - match (bytes, self.services.download.as_mut()) { - (Ok(b), Some(dl)) => { - dl(name, &b); - true - } - (Err(e), _) => { - self.set_status(e.to_string()); - false - } - (Ok(_), None) => { - self.set_status("Saving a copy needs a file picker, which this window doesn't have."); - false - } - } + self.submit_save(uid, None, files, &suggested, false, instance) } /// File › Print: DeckCraft prints through a PDF. On the desktop the PDF (with the Print page's /// layout, slides and options) is written to the temporary folder and opened in the system's /// PDF viewer, which has the printers; on the web it downloads. pub fn print_pdf(&mut self, params: Value) -> bool { - let Some((title, doc)) = self.session.active().map(|d| (d.title(), d.doc.clone())) else { return false }; - let mut params = if params.is_object() { params } else { json!({}) }; - if self.services.pick_save.is_none() { - // Web: the browser hands the PDF to the user. - let bytes = deckcraft_engine::cmd::file::pdf_bytes(&doc, ¶ms); - return self.download(&format!("{title}.pdf"), bytes); + if self.session.active().is_none() { + return false; } - let preview_path = match self.print_previews.create(&title) { + let params = if params.is_object() { params } else { json!({}) }; + #[cfg(not(target_arch = "wasm32"))] + if !self.host.files().browser_saves() { + return self.print_preview(params); + } + self.export_as("pdf", params) + } + + /// Writes the print PDF to a private temporary file and opens it in the system's PDF viewer. + #[cfg(not(target_arch = "wasm32"))] + fn print_preview(&mut self, mut params: Value) -> bool { + let Some(title) = self.session.active().map(|d| d.title()) else { + return false; + }; + let title: String = title.chars().map(|c| if c.is_alphanumeric() || matches!(c, ' ' | '-') { c } else { '_' }).collect(); + let preview_path = match self.print_previews.create("deckcraft-print", &format!("{title} (print).pdf")) { Ok(path) => path, Err(e) => { self.set_status(format!("Couldn't create a private print preview: {e}")); @@ -296,21 +304,21 @@ impl SlideApp { } } + /// Pick a document or outline without borrowing a platform picker closure. pub(crate) fn pick_and_open(&mut self) { - if let Some(pick) = self.services.pick_open.as_mut() { - if let Some(path) = pick("open") { - self.open_path_in_background(&path); - } - } else if self.services.open_async.is_some() { - let id = self.begin_external_file("open"); - if let Some(f) = self.services.open_async.as_mut() { - f("open", id); - } - } + self.queue_file_pick("document", FileOperation::Apply(purpose_of("document"))); } pub fn open_path(&mut self, path: &str) -> Result<(), String> { - self.session.execute("file.open", &json!({"path": path})).map_err(|e| e.to_string())?; + let files = self.host.files(); + let loaded = deckcraft_engine::cmd::file::read_presentation_file_with( + path, + |path| files.read_metadata(Path::new(path)).map_err(|e| e.to_string()), + |path| files.read(Path::new(path)).map_err(|e| e.to_string()), + ) + .map_err(|e| e.to_string())?; + let token = self.session.stage_loaded(loaded); + self.session.execute("file.adopt", &json!({"path": path, "token": token})).map_err(|e| e.to_string())?; self.note_recent(path); Ok(()) } @@ -319,14 +327,17 @@ impl SlideApp { /// association), opened in order. When the last one is a PowerPoint Show (`.ppsx`, or the /// 97-2003 `.pps`), its slide show starts at once from where Play from Start begins, as /// PowerPoint does; anything else opens for editing, and File › Open opens a `.ppsx` for - /// editing too. Returns the files that couldn't be opened, with the reason. + /// editing too. Each file that couldn't be opened posts its reason to the status line; they are returned with it. pub fn open_from_system(&mut self, paths: &[String]) -> Vec<(String, String)> { let mut failed = Vec::new(); let mut last = None; for p in paths { match self.open_path(p) { Ok(()) => last = Some(p), - Err(e) => failed.push((p.clone(), e)), + Err(e) => { + self.set_status(e.clone()); + failed.push((p.clone(), e)); + } } } if last.is_some_and(|p| { @@ -350,51 +361,39 @@ impl SlideApp { /// Transitions › Sound › Other Sound…: pick an audio file for the selected slides. pub(crate) fn pick_transition_sound(&mut self) { - if self.services.pick_open.is_some() { - self.pick_and_insert("audio", "transition.sound"); + self.pick_and_insert("audio", "transition.sound"); + } + + /// Ask for the presentation whose slides will be offered for reuse. + pub(super) fn pick_and_reuse(&mut self, keep: bool) { + self.queue_file_pick("document", FileOperation::Reuse { keep }); + } + + /// Read a named source once before offering its slides for reuse. + pub(crate) fn begin_reuse(&mut self, path: String, keep: bool) { + let target = self.capture_file_target(); + match self.host.files().read(Path::new(&path)) { + Ok(bytes) => self.begin_reuse_bytes(&path, &bytes, keep, target), + Err(e) => self.set_status(e.to_string()), } } - /// Home › New Slide › Reuse Slides…: pick a presentation and insert all its slides after the - /// current one (desktop only: the browser picker opens what it picks as a document). - pub(super) fn pick_and_reuse(&mut self, keep: bool) { - let Some(pick) = self.services.pick_open.as_mut() else { - self.set_status("Reuse Slides needs the desktop app".to_string()); - return; - }; - let Some(path) = pick("open") else { return }; - // Read the file once: the list shown and the slides inserted come from the same bytes, even - // if the file changes while the dialog is open. Without a reader the path is used as is. - let mut source = json!({}); - match self.services.read.as_ref().map(|r| r(&path)) { - Some(Ok(bytes)) => { - let name = std::path::Path::new(&path).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default(); - source["name"] = json!(name); - source["data"] = json!(deckcraft_engine::cmd::base64_encode(&bytes)); - } - Some(Err(e)) => { - self.set_status(e.to_string()); - return; - } - None => source["path"] = json!(path), - } - // Offer the file's slides to choose from; all of them are ticked to begin with. + fn begin_reuse_bytes(&mut self, path: &str, bytes: &[u8], keep: bool, target: FileTarget) { + // Browser Contents have no native path to reopen, so reuse consumes the supplied bytes. + let name = Path::new(path).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default(); + let source = json!({"name": name, "data": deckcraft_engine::cmd::base64_encode(bytes)}); match self.session.execute("slide.reuseList", &source) { Ok(list) => { - let mut d = dialogs::Dialog::new("reuseSlides"); - d.params = json!({"path": path, "source": source, "keep": keep, "slides": list["slides"]}); - self.reuse_target = Some(self.capture_file_target()); - self.dialog = Some(d); + self.reuse_target = Some(target); + self.open_dialog("reuseSlides", json!({"path": path, "source": source, "keep": keep, "slides": list["slides"]})); } Err(e) => self.set_status(e.to_string()), } } - /// Insert the slides `picked` (indices) of `source` (the `name` + `data`, or `path`, that - /// `slide.reuseList` listed) after the slide that was current when the picker opened, in that - /// presentation, even if another one is active now; if it is closed or the slide is gone, - /// nothing is inserted. Returns whether they were inserted. - pub fn reuse_slides(&mut self, source: &Value, keep: bool, picked: &[usize]) -> bool { + /// Insert the chosen source slides at the stable place captured by the picker. + /// An error retains the chosen slides so the form can show the reason and retry. + pub fn reuse_slides(&mut self, source: &Value, keep: bool, picked: &[usize]) -> Result<(), String> { let mut args = if source.is_object() { source.clone() } else { json!({}) }; args["keepFormatting"] = json!(keep); args["slides"] = json!(picked); @@ -406,134 +405,7 @@ impl SlideApp { Ok(()) => { self.reuse_target = None; self.set_status(format!("Inserted {} slides", picked.len())); - true - } - Err(e) => { - self.set_status(e); - false - } - } - } - - pub(crate) fn pick_and_insert(&mut self, purpose: &str, cmd: &str) { - self.pick_and_run(purpose, cmd, &json!({})); - } - - /// Pick a file and run `cmd` with it (`name` + `data`, or `path`) added to `extra`. - pub(super) fn pick_and_run(&mut self, purpose: &str, cmd: &str, extra: &Value) { - if let Some(pick) = self.services.pick_open.as_mut() { - if let Some(path) = pick(purpose) { - let mut args = if extra.is_object() { extra.clone() } else { json!({}) }; - let r = match self.services.read.as_ref().map(|r| r(&path)) { - Some(Ok(bytes)) => { - let name = std::path::Path::new(&path).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default(); - args["name"] = json!(name); - args["data"] = json!(deckcraft_engine::cmd::base64_encode(&bytes)); - self.session.execute(cmd, &args) - } - _ => { - args["path"] = json!(path); - self.session.execute(cmd, &args) - } - }; - if let Err(e) = r { - self.set_status(e.to_string()); - } - } - } else if self.services.open_async.is_some() { - let id = self.begin_external_file(purpose); - // Change Picture: the picture that arrives replaces the selected one (#115). - if cmd == "picture.change" - && let Some(r) = self.pending_files.iter_mut().find(|r| r.id == id) - { - r.purpose = FilePurpose::ChangePicture; - } - if let Some(f) = self.services.open_async.as_mut() { - f(purpose, id); - } - } - } - - pub fn save_as_dialog(&mut self, format: &str) { - let name = self.session.active().map(|d| d.title()).unwrap_or_else(|| "Presentation".into()); - let ext = if format == "pptx" { "pptx" } else { "deckcraft" }; - let suggested = format!("{name}.{ext}"); - if let Some(pick) = self.services.pick_save.as_mut() { - if let Some(path) = pick(&suggested) { - match self.session.execute("file.saveAs", &json!({"path": path})) { - Ok(_) => { - self.set_status(format!("Saved {path}")); - self.ui.recent.retain(|p| *p != path); - self.ui.recent.insert(0, path); - } - Err(e) => self.set_status(e.to_string()), - } - } - } else if self.services.host_save.is_some() { - let _ = self.save_to_host(Some(ext)); - } else if let Some(dl) = self.services.download.as_mut() - && let Some(d) = self.session.active() - { - match deckcraft_engine::cmd::file::save_bytes(&d.doc, ext) { - Ok(bytes) => dl(&suggested, &bytes), - Err(e) => self.set_status(e.to_string()), - } - } - } - - /// Save every presentation with unsaved changes (asking for a location where needed). - /// Returns false if one wasn't saved (cancelled or failed). - pub fn save_all(&mut self) -> bool { - let dirty: Vec = self.session.documents().iter().enumerate().filter(|(_, d)| d.is_dirty()).map(|(i, _)| i).collect(); - for i in dirty { - self.session.set_active(i); - self.save(); - if self.session.documents().get(i).is_some_and(|d| d.is_dirty()) { - return false; - } - } - true - } - - pub fn save(&mut self) { - if self.services.host_save.is_some() { - let _ = self.save_to_host(None); - return; - } - if self.session.active().and_then(|d| d.path.clone()).is_some() { - match self.session.execute("file.save", &json!({})) { - Ok(_) => self.set_status("Saved"), - Err(e) => self.set_status(e.to_string()), - } - } else { - self.save_as_dialog("deckcraft"); - } - } - - /// Saves to the page that keeps the files ([`Services::host_save`](crate::Services::host_save)). - /// Save (`ext` `None`) writes the presentation's own file (the one the page sent, or the - /// last one saved there) in that file's format, as the desktop app does; a presentation with - /// no file of its own is a new `.deckcraft` file, the name Save suggests on the desktop. Save - /// As (`pptx`, `deckcraft`) is a new file named after the presentation. Once the page has the - /// bytes, the presentation is saved and that name is its file. Returns the name, or why it - /// wasn't saved (also shown in the status bar). - pub(super) fn save_to_host(&mut self, ext: Option<&str>) -> Result { - use deckcraft_engine::cmd::file::{format_for_path, mark_saved, save_bytes}; - let Some(d) = self.session.active() else { return Err("no presentation is open".into()) }; - let own = d.path.as_deref().and_then(|p| std::path::Path::new(p).file_name()).map(|n| n.to_string_lossy().to_string()); - let (name, save_as) = match (ext, own) { - (None, Some(own)) => (own, false), - (ext, _) => (format!("{}.{}", d.title(), ext.unwrap_or("deckcraft")), true), - }; - let saved = save_bytes(&d.doc, format_for_path(&name)).map_err(|e| e.to_string()).and_then(|bytes| { - let host = self.services.host_save.as_mut().ok_or("no page to save to")?; - host(&name, &bytes, save_as).map_err(|e| format!("Couldn't save {name}: {e}"))?; - mark_saved(&mut self.session, Some(name.clone())).map_err(|e| e.to_string()) - }); - match saved { - Ok(()) => { - self.set_status(format!("Saved {name}")); - Ok(name) + Ok(()) } Err(e) => { self.set_status(e.clone()); @@ -542,6 +414,66 @@ impl SlideApp { } } + /// Pick a file for an insertion command at the current place. + pub(crate) fn pick_and_insert(&mut self, purpose: &str, cmd: &str) { + self.pick_and_run(purpose, cmd, json!({})); + } + + /// Pick a file for a registered command, retaining its parameters and shape targets. + pub(crate) fn pick_and_run(&mut self, purpose: &str, command: &str, params: Value) { + let mut params = if params.is_object() { params } else { json!({}) }; + if captures_shapes(command) && params.get("ids").is_none() && params.get("id").is_none() { + params["ids"] = json!(self.session.active().map(|d| d.selection.shapes.clone()).unwrap_or_default()); + } + self.queue_file_pick(purpose, FileOperation::Command { purpose: purpose.into(), command: command.into(), params }); + } + + fn queue_file_pick(&mut self, purpose: &str, operation: FileOperation) { + let target = self.capture_file_target(); + let ticket = self.host.files().pick(open_request(purpose)); + self.pending_files.push(PendingFile { ticket, operation, target }); + } + + /// Ask for a new file of the active document in the requested format. + pub fn save_as_dialog(&mut self, format: &str) { + let _ = self.save_as_outcome(format, None); + } + + fn save_as_outcome(&mut self, format: &str, instance: Option>) -> SaveOutcome { + let Some((uid, snapshot)) = self.session.active().map(|d| (d.uid, d.doc.clone())) else { + return SaveOutcome::Failed("no presentation is open".into()); + }; + if self.document_save_pending(uid) { + return self.file_failure("A save of this presentation is still waiting".into()); + } + let ext = if format == "pptx" { "pptx" } else { "deckcraft" }; + let name = self.suggested_name(ext); + let bytes = match save_bytes(&snapshot, ext) { + Ok(bytes) => bytes, + Err(e) => return self.file_failure(e.to_string()), + }; + self.submit_save(uid, Some(snapshot), vec![(name.clone(), bytes)], &name, true, instance) + } + + /// Save every dirty document; outstanding tickets are retained without resubmission. + pub fn save_all(&mut self) -> bool { + let dirty: Vec = self.session.documents().iter().filter(|d| d.is_dirty()).map(|d| d.uid).collect(); + let mut complete = !self.pending_files.iter().any(|p| matches!(&p.operation, FileOperation::Save(s) if s.snapshot.is_some())); + for uid in dirty { + if !succeeded(&self.save_document(uid)) { + complete = false; + } + } + complete + } + + /// Save the active document through its installed file service. + pub fn save(&mut self) { + if let Some(uid) = self.session.active().map(|d| d.uid) { + let _ = self.save_document(uid); + } + } + /// A file the page that keeps the files sent (`?host=parent`), with the name it sent, if any. /// It opens as File › Open opens it on the desktop: a presentation as itself, an outline /// (.txt, .md, .rtf) as a new untitled presentation. The name is the presentation's file only @@ -593,11 +525,7 @@ impl SlideApp { pub(super) fn drain_requests(&mut self) { for r in std::mem::take(&mut self.session.ui_requests) { match r { - UiRequest::Dialog { id, params } => { - let mut d = dialogs::Dialog::new(&id); - d.params = params; - self.dialog = Some(d); - } + UiRequest::Dialog { id, params } => self.open_dialog(&id, params), UiRequest::Pane { id } => self.ui.pane = Some(id), UiRequest::StartShow { from } => self.start_show(from, false), UiRequest::Message { text } => self.set_status(text), @@ -617,40 +545,16 @@ impl SlideApp { } } - pub(crate) fn drain_inbox(&mut self) { - let Some(inbox) = self.services.inbox.clone() else { return }; - let events = match inbox.lock() { - Ok(mut v) => std::mem::take(&mut *v), - Err(poisoned) => std::mem::take(&mut *poisoned.into_inner()), - }; - for event in events { - match event { - InboxEvent::Cancelled { id } => self.pending_files.retain(|r| r.id != id), - InboxEvent::File(file) => self.apply_external_file(file.id, &file.name, &file.bytes), - } - } - } - - /// Remember the open presentation, the slide (or master/layout) and the operation for a - /// file the host will read asynchronously. Returns the cancellation identity the host must - /// echo on the [`InboxEvent`]. Call this when the pick or the drop starts, not when the - /// bytes arrive. - pub fn begin_external_file(&mut self, purpose: &str) -> u64 { - let id = self.next_file_id; - self.next_file_id = self.next_file_id.wrapping_add(1).max(1); - self.pending_files.push(PendingFile { id, purpose: purpose_of(purpose), target: self.capture_file_target() }); - id - } - - /// A dropped or picked file read synchronously: presentations open, media is inserted on - /// the slide that is current now. - pub fn open_or_insert_bytes(&mut self, name: &str, bytes: &[u8]) { - let id = self.begin_external_file("drop"); - self.apply_external_file(id, name, bytes); + /// Apply a drop at the place captured by the pass that receives its bytes. + pub(crate) fn open_or_insert_bytes(&mut self, name: &str, bytes: Vec) { + let target = self.capture_file_target(); + self.apply_external_file(FileOperation::Apply(purpose_of("drop")), target, name, &bytes); } fn capture_file_target(&self) -> FileTarget { - let Some(d) = self.session.active() else { return FileTarget::Absent }; + let Some(d) = self.session.active() else { + return FileTarget::Absent; + }; let place = match d.selection.target { Target::Slides => match d.current_slide() { Some(s) => FilePlace::Slide(s.id), @@ -674,8 +578,12 @@ impl SlideApp { /// True when the user is still looking at the place this request captured. fn viewing_target(&self, target: &FileTarget) -> bool { - let FileTarget::Document { doc, place } = target else { return false }; - let Some(d) = self.session.active() else { return false }; + let FileTarget::Document { doc, place } = target else { + return false; + }; + let Some(d) = self.session.active() else { + return false; + }; if d.uid != *doc { return false; } @@ -693,25 +601,45 @@ impl SlideApp { } } - fn apply_external_file(&mut self, id: u64, name: &str, bytes: &[u8]) { - let Some(pos) = self.pending_files.iter().position(|r| r.id == id) else { return }; - let req = self.pending_files.remove(pos); - let cmd = match command_for(req.purpose, name, bytes) { - Ok(cmd) => cmd, - Err(e) => { - self.set_status(e); + fn apply_external_file(&mut self, operation: FileOperation, target: FileTarget, name: &str, bytes: &[u8]) { + let (cmd, mut params, picture) = match operation { + FileOperation::Apply(purpose) => { + let cmd = match command_for(purpose, name, bytes) { + Ok(cmd) => cmd, + Err(e) => { + self.set_status(e); + return; + } + }; + let params = if cmd == "slide.fromOutline" { + json!({"text": deckcraft_engine::cmd::file::outline_text(bytes), "markdown": name.to_ascii_lowercase().ends_with(".md")}) + } else { + json!({}) + }; + (cmd.to_string(), params, false) + } + FileOperation::Command { purpose, command, params } => (command, params, purpose == "picture"), + FileOperation::Reuse { keep } => { + self.begin_reuse_bytes(name, bytes, keep, target); return; } + FileOperation::Save(_) => return, }; - let params = if cmd == "slide.fromOutline" { - json!({"text": deckcraft_engine::cmd::file::outline_text(bytes), "markdown": name.to_ascii_lowercase().ends_with(".md")}) + if cmd == "picture.change" + && let Err(e) = command_for(FilePurpose::ChangePicture, name, bytes) + { + self.set_status(e); + return; + } + params["name"] = json!(name); + params["data"] = json!(deckcraft_engine::cmd::base64_encode(bytes)); + if picture { + params["picture"] = params["data"].clone(); + } + let result = if cmd == "file.openBytes" || (self.viewing_target(&target) && !captures_shapes(&cmd)) { + self.session.execute(&cmd, ¶ms).map(|_| ()).map_err(|e| e.to_string()) } else { - json!({"name": name, "data": deckcraft_engine::cmd::base64_encode(bytes)}) - }; - let result = if cmd == "file.openBytes" || self.viewing_target(&req.target) { - self.session.execute(cmd, ¶ms).map(|_| ()).map_err(|e| e.to_string()) - } else { - self.execute_on_target(&req.target, name, cmd, ¶ms) + self.execute_on_target(&target, name, &cmd, ¶ms) }; match result { Err(e) if cmd == "file.openBytes" => self.notify(e), @@ -751,17 +679,30 @@ impl SlideApp { st.selection.text = None; st.selection.cells = None; } - let result = self.session.execute(cmd, params).map(|_| ()).map_err(|e| e.to_string()); - if view == Some(idx) { - if let (Some(sel), Some(st)) = (saved, self.session.active_mut()) { - st.selection = sel; - } - } else { - self.restore_file_view(view); + let result = self.validate_file_shapes(cmd, params).and_then(|()| self.session.execute(cmd, params).map(|_| ()).map_err(|e| e.to_string())); + if let (Some(sel), Some(st)) = (saved, self.session.active_mut()) { + st.selection = sel; } + self.restore_file_view(view); result } + fn validate_file_shapes(&self, command: &str, params: &Value) -> Result<(), String> { + if captures_shapes(command) { + let d = self.session.doc().map_err(|e| e.to_string())?; + let ids = params.get("ids").and_then(Value::as_array).map(Vec::as_slice); + let single = params.get("id").map(std::slice::from_ref); + for id in ids.or(single).unwrap_or_default() { + if let Some(id) = id.as_u64().and_then(|id| u32::try_from(id).ok()) + && d.shape(deckcraft_model::ShapeId(id)).is_none() + { + return Err("the shape it was chosen for was deleted".into()); + } + } + } + Ok(()) + } + fn restore_file_view(&mut self, view: Option) { if let Some(i) = view && i < self.session.documents().len() @@ -821,54 +762,271 @@ pub(crate) fn web_image_files( let opts = deckcraft_render::RenderOpts { scale, transparent_background: transparent && ext == "png", ..Default::default() }; let img = deckcraft_render::render_slide(doc, i, &opts); let bytes = if ext == "png" { img.to_png_at(dpi) } else { img.to_jpeg_at(92, Some(dpi)) }; - let file = if single { format!("{name}.{ext}") } else { format!("{name}{}.{ext}", k + 1) }; + let file = image_file_name(name, ext, k, single); (file, bytes) }) .collect() } -#[cfg(test)] -mod print_preview_tests { - use super::PrintPreviews; - use std::time::{SystemTime, UNIX_EPOCH}; - - #[test] - fn same_title_gets_distinct_private_paths_and_drop_cleans_them() { - let stamp = SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or_default(); - let base = std::env::temp_dir().join(format!("deckcraft-print-test-{}-{stamp}", std::process::id())); - std::fs::create_dir(&base).unwrap(); - let (first, second) = { - let mut previews = PrintPreviews::default(); - let first = previews.create_in(&base, "Same title").unwrap(); - let second = previews.create_in(&base, "Same title").unwrap(); - assert_ne!(first, second); - assert_eq!(first.file_name(), second.file_name()); - assert!(first.parent().is_some_and(|dir| dir.is_dir())); - #[cfg(unix)] - { - use std::os::unix::fs::PermissionsExt; - let mode = std::fs::metadata(first.parent().unwrap()).unwrap().permissions().mode(); - assert_eq!(mode & 0o777, 0o700); - } - (first, second) - }; - assert!(!first.parent().is_some_and(|dir| dir.exists())); - assert!(!second.parent().is_some_and(|dir| dir.exists())); - std::fs::remove_dir(base).unwrap(); +impl SlideApp { + /// Takes only answered tickets; a second pass cannot replay an answer consumed by the first. + pub(crate) fn take_file_answers(&mut self) { + let tickets: Vec = self.pending_files.iter().map(|p| p.ticket).collect(); + for ticket in tickets { + self.take_file_answer(ticket); + } } - #[test] - fn explicit_cleanup_removes_previews() { - let stamp = SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or_default(); - let base = std::env::temp_dir().join(format!("deckcraft-print-cleanup-test-{}-{stamp}", std::process::id())); - std::fs::create_dir(&base).unwrap(); - let mut previews = PrintPreviews::default(); - let path = previews.create_in(&base, "Explicit cleanup").unwrap(); - let dir = path.parent().unwrap().to_path_buf(); + fn take_file_answer(&mut self, ticket: PickId) { + let Some(answer) = self.host.files().take_answer(ticket) else { + return; + }; + let Some(at) = self.pending_files.iter().position(|p| p.ticket == ticket) else { + return; + }; + let pending = self.pending_files.remove(at); + if let FileOperation::Save(transfer) = pending.operation { + self.finish_save(transfer, answer); + return; + } + match answer { + Picked::Paths(paths) => { + for path in paths { + let name = path.to_string_lossy().to_string(); + if matches!(pending.operation, FileOperation::Apply(FilePurpose::Open)) && open_command(&name) == Some("file.openBytes") { + self.open_path_in_background(&name); + } else { + match self.host.files().read(&path) { + Ok(bytes) => self.apply_external_file(pending.operation.clone(), pending.target, &name, &bytes), + Err(e) => self.set_status(e.to_string()), + } + } + } + } + Picked::Contents(files) => { + for (name, bytes) in files { + self.apply_external_file(pending.operation.clone(), pending.target, &name, &bytes); + } + } + Picked::Failed(e) | Picked::Unavailable(e) => self.set_status(e), + Picked::Cancelled => {} + _ => self.set_status("The file picker did not return an open file"), + } + } - previews.cleanup(); + /// Saves the named document without changing which document the user is viewing. + pub(crate) fn save_document(&mut self, uid: u64) -> SaveOutcome { + if self.document_save_pending(uid) { + return SaveOutcome::Pending; + } + let Some(d) = self.session.documents().iter().find(|d| d.uid == uid) else { + let outcome = SaveOutcome::Failed("the presentation is closed".into()); + self.save_settled(uid, outcome.clone()); + return outcome; + }; + let snapshot = d.doc.clone(); + let own = d.path.clone(); + let name = own + .as_deref() + .and_then(|p| Path::new(p).file_name()) + .map(|n| n.to_string_lossy().to_string()) + .unwrap_or_else(|| format!("{}.deckcraft", d.title())); + let bytes = match save_bytes(&snapshot, format_for_path(&name)) { + Ok(bytes) => bytes, + Err(e) => { + let outcome = self.file_failure(e.to_string()); + self.save_settled(uid, outcome.clone()); + return outcome; + } + }; + if !self.host.files().browser_saves() + && let Some(path) = own.as_ref() + { + let batch = Rc::new(RefCell::new(SaveBatch { uid, remaining: 1, outcome: SaveOutcome::Saved, instance: None, deferred: false })); + let transfer = + SaveTransfer { snapshot: Some(snapshot), files: vec![(name, bytes)], write_on_answer: true, save_as: false, batch: batch.clone() }; + self.finish_save(transfer, Picked::Saved { path: PathBuf::from(path), file_type: None }); + return batch.borrow().outcome.clone(); + } + self.submit_save(uid, Some(snapshot), vec![(name.clone(), bytes)], &name, own.is_none(), None) + } - assert!(!dir.exists()); - std::fs::remove_dir(base).unwrap(); + /// Delivers terminal outcomes to the closing pump, which owns all guard transitions. + pub(crate) fn save_settled(&mut self, uid: u64, outcome: SaveOutcome) { + if !matches!(outcome, SaveOutcome::Pending) + && let Some(closing) = self.dialogs.closing.as_mut() + { + closing.settle(uid, outcome); + } + } + + /// Save As with completion intent for this particular File view. + pub(crate) fn backstage_save_as(&mut self, format: &str, instance: Arc<()>) -> SaveOutcome { + self.save_as_outcome(format, Some(instance)) + } + + /// Export with completion intent shared by every copy of this particular File view. + pub(crate) fn backstage_export_as(&mut self, format: &str, extra: Value, instance: Arc<()>) -> SaveOutcome { + self.export_copies(format, extra, Some(instance)) + } + + fn document_save_pending(&self, uid: u64) -> bool { + self.pending_files.iter().any(|p| matches!(&p.operation, FileOperation::Save(s) if s.snapshot.is_some() && s.batch.borrow().uid == uid)) + } + + fn file_failure(&mut self, reason: String) -> SaveOutcome { + self.set_status(reason.clone()); + SaveOutcome::Failed(reason) + } + + fn submit_save( + &mut self, + uid: u64, + snapshot: Option>, + files: Vec<(String, Vec)>, + suggested: &str, + save_as: bool, + instance: Option>, + ) -> SaveOutcome { + if files.is_empty() { + return self.file_failure("There are no slides to export".into()); + } + let browser = self.host.files().browser_saves(); + let batch = Rc::new(RefCell::new(SaveBatch { + uid, + remaining: if browser { files.len() } else { 1 }, + outcome: SaveOutcome::Saved, + instance, + deferred: false, + })); + let target = FileTarget::Document { doc: uid, place: FilePlace::Unspecified }; + let request = |name: &str| { + let ext = Path::new(name).extension().and_then(|s| s.to_str()).unwrap_or("deckcraft"); + PickRequest::save("document").file_name(name).suggested_extension(ext).filter(ext, &[ext]).save_as(save_as) + }; + let mut tickets = Vec::new(); + if browser { + for (name, bytes) in files { + let ticket = self.host.files().save(request(&name), bytes); + self.pending_files.push(PendingFile { + ticket, + target, + operation: FileOperation::Save(SaveTransfer { + snapshot: snapshot.clone(), + files: vec![(name, Vec::new())], + write_on_answer: false, + save_as, + batch: batch.clone(), + }), + }); + tickets.push(ticket); + } + } else { + let ticket = self.host.files().pick(request(suggested)); + self.pending_files.push(PendingFile { + ticket, + target, + operation: FileOperation::Save(SaveTransfer { snapshot, files, write_on_answer: true, save_as, batch: batch.clone() }), + }); + tickets.push(ticket); + } + // Ownership is registered before taking even an immediately available answer. + for ticket in tickets { + self.take_file_answer(ticket); + } + let mut batch = batch.borrow_mut(); + if batch.remaining == 0 { + batch.outcome.clone() + } else { + batch.deferred = true; + SaveOutcome::Pending + } + } + + fn finish_save(&mut self, transfer: SaveTransfer, picked: Picked) { + let uid = transfer.batch.borrow().uid; + let name = transfer.files.first().map(|(name, _)| name.as_str()).unwrap_or("Presentation"); + let records = picked.records_file(); + let outcome = match picked { + Picked::Saved { path, .. } => { + let result = self.write_saved_files(&transfer, &path).and_then(|()| { + if records && let Some(snapshot) = transfer.snapshot.as_ref() { + mark_saved_snapshot(&mut self.session, uid, snapshot.clone(), Some(path.to_string_lossy().to_string())) + .map_err(|e| e.to_string())?; + let path = path.to_string_lossy().to_string(); + self.ui.recent.retain(|p| p != &path); + self.ui.recent.insert(0, path); + self.ui.recent.truncate(RECENT_MAX); + } + Ok(()) + }); + match result { + Ok(()) => { + self.set_status(format!("Saved {}", path.display())); + SaveOutcome::Saved + } + Err(e) => self.file_failure(format!("Couldn't save {name}: {e}")), + } + } + Picked::Downloaded(name) => { + self.set_status(format!("Downloaded {name}")); + SaveOutcome::Downloaded + } + Picked::Failed(e) | Picked::Unavailable(e) => self.file_failure(format!("Couldn't save {name}: {e}")), + Picked::Cancelled => SaveOutcome::Cancelled, + _ => self.file_failure(format!("Couldn't save {name}: the picker did not return a save result")), + }; + if transfer.snapshot.is_some() { + self.save_settled(uid, outcome.clone()); + } + let mut batch = transfer.batch.borrow_mut(); + batch.remaining -= 1; + batch.outcome = match (&batch.outcome, &outcome) { + (SaveOutcome::Failed(_), _) | (SaveOutcome::Cancelled, SaveOutcome::Saved | SaveOutcome::Downloaded) => batch.outcome.clone(), + (_, SaveOutcome::Failed(_) | SaveOutcome::Cancelled) => outcome, + (SaveOutcome::Downloaded, _) => SaveOutcome::Downloaded, + _ => outcome, + }; + if batch.remaining == 0 + && batch.deferred + && succeeded(&batch.outcome) + && let Some(instance) = &batch.instance + && self.backstage.as_ref().is_some_and(|b| b.docs.1 == Some(uid) && Arc::ptr_eq(&b.instance, instance)) + { + self.close_backstage(); + } + } + + fn write_saved_files(&self, transfer: &SaveTransfer, path: &Path) -> Result<(), String> { + if !transfer.write_on_answer { + return Ok(()); + } + let intent = if transfer.save_as { WriteIntent::SaveAs } else { WriteIntent::Save }; + let multiple = transfer.files.len() > 1; + for (index, (name, bytes)) in transfer.files.iter().enumerate() { + let out = if multiple { + let stem = path.file_stem().unwrap_or_default().to_string_lossy(); + let ext = path.extension().or_else(|| Path::new(name).extension()).unwrap_or_default().to_string_lossy(); + path.with_file_name(image_file_name(&stem, &ext, index, false)) + } else { + path.to_path_buf() + }; + let encoded; + let bytes = if let Some(snapshot) = &transfer.snapshot + && format_for_path(name) != format_for_path(&out.to_string_lossy()) + { + // The picker may choose a different writable extension; the captured snapshot stays fixed. + encoded = save_bytes(snapshot, format_for_path(&out.to_string_lossy())).map_err(|e| e.to_string())?; + &encoded + } else { + bytes + }; + self.host.files().write(&out, bytes, intent).map_err(|e| e.to_string())?; + } + Ok(()) } } + +fn image_file_name(stem: &str, ext: &str, index: usize, single: bool) -> String { + if single { format!("{stem}.{ext}") } else { format!("{stem}{}.{ext}", index + 1) } +} diff --git a/crates/ui-egui/src/app/frame.rs b/crates/ui-egui/src/app/frame.rs index 0da3896bf..fc4d6ca01 100644 --- a/crates/ui-egui/src/app/frame.rs +++ b/crates/ui-egui/src/app/frame.rs @@ -1,78 +1,41 @@ -use super::{SlideApp, json, media, monotonic_secs, theme}; +use super::{SlideApp, json, media}; +use craft::platform::autosave::{Autosave, AutosaveDoc, INTERVAL_CHOICES_MINUTES, interval_for_minutes}; +use std::time::{Duration, Instant}; impl SlideApp { - /// Style, fonts and zoom setup. Runs in a real UI pass, not from `run_logic`, because - /// `set_fonts`/`set_visuals` only take effect for the pass that lays out the UI. - pub(super) fn ui_setup(&mut self, ctx: &egui::Context) -> bool { - let scale = self.ui.ui_scale.clamp(0.5, 3.0); - if (ctx.zoom_factor() - scale).abs() > 1e-3 { - ctx.set_zoom_factor(scale); - } - if !self.styled { - theme::install_fonts_with(ctx, &self.ui_fonts.faces); - self.styled = true; - self.restyle = true; - // Font definitions take effect at the next pass boundary. Do not paint a language - // or symbol with the old font set while the new set is still pending. - ctx.request_discard("install interface fonts before layout"); - return false; - } - if self.restyle { - theme::apply(ctx, &theme::Tokens::for_brightness(self.ui.brightness)); - self.restyle = false; - } - self.fonts_ready = true; - true - } - /// AutoRecover on a monotonic deadline, even when nothing is painted. pub(super) fn autosave_if_due(&mut self, ctx: &egui::Context) { if self.session.recovery_dir.is_none() { + self.autosave = None; return; } - let every = (self.session.prefs.recovery_minutes * 60.0).max(10.0); - let now = monotonic_secs(); - if now - self.last_recovery > every { - self.last_recovery = now; - if self.session.documents().iter().any(|d| d.is_dirty()) - && let Err(e) = self.session.execute("file.recovery.save", &json!({})) - { - self.set_status(format!("Couldn't save AutoRecover information: {e}")); + let interval = Duration::try_from_secs_f64((self.session.prefs.recovery_minutes * 60.0).max(10.0)) + .ok() + .or_else(|| INTERVAL_CHOICES_MINUTES.into_iter().max().and_then(interval_for_minutes)); + let autosave = self.autosave.get_or_insert_with(|| Autosave::new(interval)); + autosave.set_interval(interval); + let docs: Vec<_> = self.session.documents().iter().map(|d| AutosaveDoc { id: d.uid, revision: d.revision, dirty: d.is_dirty() }).collect(); + let due = autosave.due(Instant::now(), docs.iter().copied()); + let mut failure = None; + for uid in due.discard { + if let Err(error) = self.session.execute("file.recovery.discard", &json!({"uid": uid})) { + failure = Some(error.to_string()); } } - if self.session.documents().iter().any(|d| d.is_dirty()) { - let wait = (every - (monotonic_secs() - self.last_recovery)).clamp(0.5, every); - ctx.request_repaint_after(std::time::Duration::from_secs_f64(wait)); - } - } - - /// Issue due screenshots and finish pass-local UI bookkeeping. Call once at the end of a real - /// pass after layout; the outer [`Self::ui`] wrapper observes IME output after this returns. - pub(super) fn ui_end(&mut self, ctx: &egui::Context) { - self.ime_frame_viewport = None; - self.capture.observe_ui(ctx); - if !ctx.will_discard() { - let doc = self.session.active().map(|d| d.uid); - self.capture.issue(ctx, doc, web_time::Instant::now()); - } - if self.fonts_ready && !ctx.will_discard() { - self.synthetic_pending = false; - self.synthetic_injected.clear(); - self.synthetic_injected_at = None; - self.synthetic_injected_time = None; - self.synthetic_focus = None; - if self.synthetic.is_empty() { - self.synthetic_target = None; + if !due.save.is_empty() { + let result = self.session.execute("file.recovery.save", &json!({})).map(|_| ()).map_err(|error| error.to_string()); + for doc in docs.into_iter().filter(|doc| due.save.contains(&doc.id)) { + let _ = autosave.finished(doc.id, doc.revision, result.clone()); } - self.promote_next_synthetic(); - } - if self.fonts_ready && !ctx.will_discard() { - let now = ctx.input(|i| i.time); - let dt = now - self.last_time; - if dt > 0.0 { - self.perf.fps = self.perf.fps * 0.9 + (1.0 / dt).min(240.0) * 0.1; + if let Err(error) = result { + failure = Some(error); } - self.last_time = now; + } + if let Some(deadline) = autosave.deadline() { + ctx.request_repaint_after(deadline.saturating_duration_since(Instant::now())); + } + if let Some(error) = failure { + self.set_status(format!("Couldn't save AutoRecover information: {error}")); } } @@ -100,7 +63,7 @@ impl SlideApp { self.media.stop(id); } } - let playing = self.media.tick_clock(monotonic_secs(), &mut self.session); + let playing = self.media.tick_clock(self.clock.now(), &mut self.session); if playing { ctx.request_repaint_after(std::time::Duration::from_millis(15)); } diff --git a/crates/ui-egui/src/app/ime.rs b/crates/ui-egui/src/app/ime.rs deleted file mode 100644 index 4aaa6d031..000000000 --- a/crates/ui-egui/src/app/ime.rs +++ /dev/null @@ -1,706 +0,0 @@ -use super::{ - ImeCancelled, ImeComposition, ImeDescriptorKey, ImeDestination, ImeResetPhase, ImeTerminalPending, ImeTerminalStamp, SlideApp, Target, Value, - ViewMode, ime_in_ui_pass_key, -}; - -impl SlideApp { - /// Borrow faces for interface text in scripts the interface fonts lack (#101): the open - /// presentations' names and text, recent files, and what is typed or composed this frame. - pub(super) fn note_ui_text(&mut self, ctx: &egui::Context) { - let typed: String = ctx.input(|i| { - i.events - .iter() - .filter_map(|e| match e { - egui::Event::Text(t) | egui::Event::Paste(t) => Some(t.as_str()), - egui::Event::Ime(egui::ImeEvent::Preedit { text, .. } | egui::ImeEvent::Commit(text)) => Some(text.as_str()), - _ => None, - }) - .collect() - }); - self.ui_fonts.note(ctx, &typed); - for d in self.session.documents() { - self.ui_fonts.note(ctx, &d.title()); - } - for r in &self.ui.recent { - self.ui_fonts.note(ctx, r); - } - if let Some(st) = self.session.active() { - self.ui_fonts.note_doc(ctx, st); - } - self.ui_fonts.apply(ctx); - } - - /// Stable IME owner for the canvas text target: document, view, shape and table cell. - /// - /// The caret, selection, text, revision and geometry are deliberately absent, so ordinary - /// edits and caret movement keep the same owner. A new document, shape or cell is a new - /// owner; [`egui::ime_context::ImeTarget::replacement_epoch`] stays zero because that key - /// itself changes on replacement. `file.revert` keeps the ids, so a composition it settles is - /// covered by the settle interrupt and by [`Self::ime_event`]'s staleness check instead. - pub(crate) fn ime_target(&self) -> Option { - let st = self.session.active()?; - let (shape, cell, notes) = match &st.selection.text { - Some(t) => (t.shape, t.cell, t.notes), - None => (*st.selection.shapes.first()?, None, false), - }; - if st.selection.text.is_none() && st.selection.shapes.len() != 1 { - return None; - } - let target = match st.selection.target { - Target::Slides => (0u8, 0usize, 0usize), - Target::Master { master } => (1, master, 0), - Target::Layout { master, layout } => (2, master, layout), - Target::Handout => (3, 0, 0), - Target::NotesMaster => (4, 0, 0), - }; - let owner = egui::Id::unique(("deckcraft-ime", st.uid, target, shape.0, cell, notes)); - Some(egui::ime_context::ImeTarget::new(owner, 0)) - } - - /// The committed surrounding snapshot for the current edit target, or `Unavailable` when - /// there is an owner but no committed text to describe. - /// - /// An unavailable stamp carries the document revision. The tracker requires a strictly - /// increasing revision on both sides of a receipt that involves `Unavailable`; without it, a - /// wide selection or a commit that starts from a selected shape would poison the whole frame. - fn ime_receipt_stamp(&self) -> Option { - let st = self.session.active()?; - self.ime_target()?; - Some(st.selection.text.as_ref().and_then(|t| deckcraft_engine::cmd::text::ime_surrounding(st, t)).map_or_else( - || egui::ime_context::ImeMutationStamp::unavailable_at_revision(st.revision), - |s| egui::ime_context::ImeMutationStamp::from_committed(&s.text, s.cursor, s.anchor, None), - )) - } - - /// Report an application-origin edit in this frame. The tracker lets `Other` dominate any - /// earlier or later IME receipt in the same frame. - pub(super) fn note_application_edit(&mut self, ctx: &egui::Context) { - let Some(viewport) = self.ime_frame_viewport else { return }; - if let Some(target) = self.ime_target() { - let frame = ctx.cumulative_frame_nr_for(viewport); - self.ime_tracker.note_application_change(viewport, frame, target); - } - } - - /// Record the expected selection after an accepted IME event. Its own deletion may move - /// the caret/revision; that is not an application interruption of the following commit. - fn refresh_ime_terminal_selection(&mut self) { - let state = self.session.active().and_then(|st| st.selection.text.as_ref().map(|t| (st.revision, t.anchor, t.caret))); - if let (Some(pending), Some((revision, anchor, caret))) = (&mut self.ime_terminal_pending, state) { - pending.revision = revision; - pending.anchor = anchor; - pending.caret = caret; - } - } - - /// The current live destination for an IME reset fence. - fn ime_destination(&self) -> Option { - let st = self.session.active()?; - let target = self.ime_target()?; - let (anchor, caret) = st.selection.text.as_ref().map_or((None, None), |t| (Some(t.anchor), Some(t.caret))); - Some(ImeDestination { owner: target.owner, revision: st.revision, anchor, caret }) - } - - /// Use the recorded IME viewport only while it matches the current context viewport. - pub(super) fn ime_viewport_or(&self, ctx: &egui::Context) -> egui::ViewportId { - self.ime_frame_viewport.filter(|v| *v == ctx.viewport_id()).unwrap_or_else(|| ctx.viewport_id()) - } - - /// The reset guard belonging to exactly this viewport. There is deliberately no fallback to - /// another viewport's phase. - pub(crate) fn ime_reset_for(&self, viewport: egui::ViewportId) -> ImeResetPhase { - self.ime_reset.get(&viewport).copied().unwrap_or(ImeResetPhase::Clear) - } - - /// Store a non-clear reset phase for one viewport, or remove the entry when the phase is `Clear`. - pub(crate) fn set_ime_reset(&mut self, viewport: egui::ViewportId, phase: ImeResetPhase) { - if matches!(phase, ImeResetPhase::Clear) { - let _ = self.ime_reset.remove(&viewport); - } else { - self.ime_reset.insert(viewport, phase); - } - } - - /// The live stamp used to compare against the origin/interrupted terminal destination. - fn ime_terminal_stamp(&self) -> Option { - let st = self.session.active()?; - let (anchor, caret) = st.selection.text.as_ref().map_or((None, None), |t| (Some(t.anchor), Some(t.caret))); - Some(ImeTerminalStamp { owner: self.ime_target().map(|t| t.owner), revision: st.revision, anchor, caret }) - } - - /// Positive route predicate for the canvas IME producer: this pass must be one that can - /// actually paint `canvas::show` for the active document, with no modal, stock field or - /// overlay owning input. - /// - /// Sorter and Notes Page are editor views without a canvas producer, so they are named here - /// even though the retained selection still yields an `ime_target`. A hidden, unfocused or - /// closing window, a missing document/target, a focused stock field, modal dialog, palette, - /// Backstage, slide show and opening overlay lose admission too. The finalizer remains the - /// authority for this pass's actual descriptor; keeping this predicate positive means a view - /// added later is not admitted by omission simply because it does not call `canvas::show`. - pub(crate) fn ime_custom_canvas_route(&self, ctx: &egui::Context) -> bool { - matches!(self.ui.view, ViewMode::Normal | ViewMode::Outline | ViewMode::Reading) - && self.session.active().is_some() - && self.ime_target().is_some() - && ctx.input(|i| i.viewport().focused.unwrap_or(true)) - && ctx.input(|i| i.viewport().visible() != Some(false)) - && !ctx.input(|i| i.viewport().close_requested()) - && !crate::framework::widget_has_keyboard(ctx) - && self.dialog.as_ref().is_none_or(|d| !d.modal()) - && self.palette.is_none() - && self.backstage.is_none() - && self.show.is_none() - && self.opening.is_none() - } - - /// The singleton app's session, composition tracker and terminal guard belong to its owning - /// viewport. View › New Window and Presenter View render through their own immediate - /// viewports and never call `logic`/`ui`; admitting such a callback would let a render-only - /// viewport mutate root composition state while only the reset map is per-viewport. Reject it - /// before any state changes instead of pretending to support multi-view editing. - pub(super) fn root_viewport_admitted(ctx: &egui::Context) -> bool { - ctx.viewport_id() == egui::ViewportId::ROOT - } - - /// Report whether the current pass is a full UI pass for the IME-owning viewport rather than - /// standalone logic. - pub(super) fn ime_in_ui_pass(&self, ctx: &egui::Context) -> bool { - let key = ime_in_ui_pass_key(self.ime_viewport_or(ctx)); - ctx.data(|d| d.get_temp::(key).unwrap_or(false)) - } - - /// A new application-origin interruption supersedes any previous pending fence. - /// - /// This runs from the logic half of a full pass and from raw input handling, before the - /// finalizer has seen this pass's actual custom descriptor. No request is allocated here: - /// putting a token into egui `Memory` now would let egui attach it to a later stock - /// descriptor, or to a canvas this route does not paint. Retire the superseded id - /// immediately and store an unbound `Suspended { request: None }`; only the finalizer may - /// allocate its one replacement after confirming an eligible custom output. - pub(crate) fn note_ime_interruption(&mut self, ctx: &egui::Context, fresh: bool) { - let viewport = self.ime_viewport_or(ctx); - if !fresh - && matches!( - self.ime_reset_for(viewport), - ImeResetPhase::Awaiting { viewport: guard_viewport, .. } - | ImeResetPhase::Suspended { viewport: guard_viewport, .. } - if guard_viewport == viewport - ) - { - // This viewport already has a live or suspended guard. The finalizer replaces it - // once if the actual destination changed; do not churn a request per event. - return; - } - self.set_ime_reset(viewport, ImeResetPhase::Suspended { viewport, needs_rearm: true, request: None }); - } - - /// Custom admission was lost on this route. Retire the old id without inventing an - /// acknowledgement and block until a later eligible pass can request a replacement. - pub(super) fn suspend_ime_reset(&mut self, viewport: egui::ViewportId) { - if self.ime_reset_for(viewport).blocks_custom_input() { - self.set_ime_reset(viewport, ImeResetPhase::Suspended { viewport, needs_rearm: true, request: None }); - } - } - - /// An ordered completion for the exact newest request. Wrong/foreign/obsolete markers are - /// inert; this never mutates text, caret or undo history. - pub(super) fn ime_reset_completed(&mut self, request_id: egui::ImeResetId, ctx: &egui::Context) { - let viewport = self.ime_viewport_or(ctx); - if request_id.viewport_id() != viewport { - return; - } - if let ImeResetPhase::Awaiting { id, viewport: waiting_viewport, .. } = self.ime_reset_for(viewport) - && id == request_id - && waiting_viewport == viewport - { - self.set_ime_reset(viewport, ImeResetPhase::Clear); - // The exact ordered completion is the platform-reset boundary. It also releases a - // cleared-preedit terminal guard: the app no longer has to wait for the old - // Commit/Enabled/Disabled before a fresh composition may start. Events ordered - // before this marker remain rejected; a late old terminal after the reset has the - // same documented residual as any other event crossing a platform reset. - if self.ime_terminal_pending.as_ref().is_some_and(|p| p.cancelled) { - self.ime_terminal_pending = None; - } - if self.ime_composition.is_some_and(|c| c.settled) { - self.ime_composition = None; - } - self.ime_cancelled = None; - self.ime_interrupt_pending = false; - } - } - - /// Controls-only routing for a route where the custom editor cannot mutate. Markers are - /// visited in raw order; stock text/key events stay untouched for the stock widgets. - pub(super) fn route_ime_controls_only(&mut self, ctx: &egui::Context, events: &[egui::Event]) { - for e in events { - if let egui::Event::ImeResetCompleted { request_id } = e { - self.ime_reset_completed(*request_id, ctx); - } - } - } - - /// Bind a suspended reset to the actual custom descriptor, or retire it on loss. - pub(crate) fn finalize_ime_reset(&mut self, ctx: &egui::Context, custom: Option) { - let viewport = self.ime_viewport_or(ctx); - let phase = self.ime_reset_for(viewport); - let actual = ctx.output(|o| o.ime.as_ref().map(|i| ImeDescriptorKey::new(i.owner, i.context_generation, i.purpose))); - let destination = self.ime_destination(); - // The finalizer is the allocation authority, so it rechecks the positive canvas route - // and that this pass is not already known to be discarded. Sorter/Notes Page, a modal, - // palette, Backstage, show, opening overlay, hidden window, stock focus, font/layout - // discard or a missing target must suspend without putting a token into egui Memory. - let eligible = self.ime_custom_canvas_route(ctx) && !ctx.will_discard(); - let custom_output = match (eligible, custom, actual, destination) { - (true, Some(custom), Some(actual), Some(destination)) if custom == actual => Some((custom, destination)), - _ => None, - }; - let Some((output_context, destination)) = custom_output else { - match phase { - ImeResetPhase::Clear => {} - ImeResetPhase::Awaiting { .. } => { - self.set_ime_reset(viewport, ImeResetPhase::Suspended { viewport, needs_rearm: true, request: None }); - } - ImeResetPhase::Suspended { viewport: guard_viewport, request, .. } => { - // A request that was not bound to the actual custom output in this pass is - // retired locally; a later eligible activation obtains a fresh one. A guard - // stamped for another viewport (or a request issued for one) is never reused. - if guard_viewport != viewport || request.is_some() { - self.set_ime_reset(viewport, ImeResetPhase::Suspended { viewport, needs_rearm: true, request: None }); - } - } - ImeResetPhase::AllocationFailed { .. } => { - self.set_ime_reset(viewport, ImeResetPhase::Suspended { viewport, needs_rearm: true, request: None }); - } - } - return; - }; - match phase { - ImeResetPhase::Clear => {} - ImeResetPhase::Awaiting { viewport: old_viewport, destination: old_destination, output_context: old_context, .. } => { - if old_viewport != viewport || old_destination != destination || old_context != output_context { - self.request_ime_rearm(ctx, viewport, destination, output_context); - } - } - ImeResetPhase::Suspended { viewport: guard_viewport, request, needs_rearm } => { - let request = if needs_rearm && guard_viewport == viewport { - // Only a request issued for this exact viewport may be bound here. - request.filter(|id| id.viewport_id() == viewport) - } else { - None - }; - match request.or_else(|| ctx.request_ime_reset(viewport)) { - Some(id) => { - self.set_ime_reset(viewport, ImeResetPhase::Awaiting { id, viewport, destination, output_context }); - } - None => { - self.set_ime_reset(viewport, ImeResetPhase::AllocationFailed { viewport, destination, output_context }); - } - } - } - ImeResetPhase::AllocationFailed { viewport: old_viewport, destination: old_destination, output_context: old_context } => { - // Repeated idle output for the same destination does not retry allocation. - if old_viewport != viewport || old_destination != destination || old_context != output_context { - self.request_ime_rearm(ctx, viewport, destination, output_context); - } - } - } - } - - /// Request one replacement IME reset token and record `Awaiting` on success or - /// `AllocationFailed` when no token can be allocated. - fn request_ime_rearm(&mut self, ctx: &egui::Context, viewport: egui::ViewportId, destination: ImeDestination, output_context: ImeDescriptorKey) { - match ctx.request_ime_reset(viewport) { - Some(id) => self.set_ime_reset(viewport, ImeResetPhase::Awaiting { id, viewport, destination, output_context }), - None => self.set_ime_reset(viewport, ImeResetPhase::AllocationFailed { viewport, destination, output_context }), - } - } - - /// A standalone run_logic tick paints no custom geometry. Suspend once, without replaying - /// stale input; the next full UI pass can rearm from its actual descriptor. - pub(super) fn finalize_ime_logic(&mut self, ctx: &egui::Context) { - let viewport = self.ime_viewport_or(ctx); - if self.ime_reset_for(viewport).blocks_custom_input() { - // Only this viewport's guard is touched. A root/child logic tick must not suspend or - // rebind another viewport's independent reset lifetime. - self.set_ime_reset(viewport, ImeResetPhase::Suspended { viewport, needs_rearm: true, request: None }); - } - } - - /// Note compositions the application settled since the last check (a click, a key, another - /// command). Those are announced to the platform as an interrupt in [`Self::observe_ime`], - /// and a platform event for them is stale from that moment on, even in the same pass. - pub(crate) fn note_settled_composition(&mut self, ctx: &egui::Context) { - let settles = self.session.composition_settles(); - let current_stamp = self.ime_terminal_stamp(); - // `file.close` then `file.new` can replace the active uid before any pass observes the - // empty document. That is not a safe boundary for the old terminal: the platform may - // still deliver its suffix. Keep the guard bound to its retired owner and treat the new - // destination as a fresh interruption; only exact reset completion or an observed - // teardown may clear the terminal metadata. - let pending_interrupted = self.ime_terminal_pending.as_ref().is_some_and(|p| { - let reference = if p.interrupted { - p.interrupted_at - } else { - Some(ImeTerminalStamp { owner: Some(p.owner), revision: p.revision, anchor: Some(p.anchor), caret: Some(p.caret) }) - }; - reference != current_stamp - }); - if settles == self.ime_settles_seen && !pending_interrupted { - return; - } - let fresh = settles != self.ime_settles_seen; - self.ime_settles_seen = settles; - if let Some(pending) = &mut self.ime_terminal_pending { - pending.cancelled = true; - pending.interrupted = true; - // Compare later passes against the destination where interruption actually happened, - // not forever against the retired composition's origin. The destination may be absent - // (the interruption closed its target); `interrupted` keeps that distinct from "not - // interrupted yet". - pending.interrupted_at = current_stamp; - } - self.ime_interrupt_pending = true; - self.note_ime_interruption(ctx, fresh); - let cancelled = self.ime_composition.as_mut().map(|c| { - c.settled = true; - (c.owner, c.generation) - }); - if let Some((owner, generation)) = cancelled { - // Retain a tombstone beyond the first stale event: clearing the composition must - // not let the rest of this input batch commit into the next target. `observe_ime` - // retires it in the pass that publishes the matching interrupt. - self.ime_cancelled = Some(ImeCancelled { owner, generation }); - } - } - - /// An input method's event for the slide's text (#101): the preedit is shown in the text and - /// replaced on each update; the commit replaces it as one undo step. - /// - /// An event only ever changes the target its composition began in. The application settles a - /// composition itself on a click, a key, a command or a target change, and the platform may - /// still hold it: pre-edits and commits queued for that generation in the settling input batch - /// are dropped (with [`egui::Memory::interrupt_ime`]) instead of being typed into whatever is - /// selected now. After the interrupt has been published the platform is reset, so the next - /// batch is treated as new input; egui's event payload has no generation, so an OS-queued - /// event that crosses that reset cannot be distinguished from a legitimate one. - /// - /// A receipt is captured immediately before and after a successful commit or - /// delete-surrounding mutation. Preedit, rejected/failed events and no-ops never earn - /// [`egui::output::ImeChangeCause::InputMethod`]. - pub(crate) fn ime_event(&mut self, ctx: &egui::Context, e: &egui::ImeEvent) { - self.note_settled_composition(ctx); - let viewport = self.ime_frame_viewport.unwrap_or_else(|| ctx.viewport_id()); - let frame = ctx.cumulative_frame_nr_for(viewport); - let target = self.ime_target(); - let owner = target.map(|t| t.owner); - let accepted = - matches!(e, egui::ImeEvent::Commit(_) | egui::ImeEvent::DeleteSurrounding { .. } | egui::ImeEvent::DeleteSurroundingBytes { .. }); - if self.reject_stale_ime_event(ctx, e, owner) { - return; - } - // Until the exact newest reset request completes at its ordered stream position, custom - // mutations stay blocked. Platform enable/disable signals are not acknowledgements and do - // not release this guard; they still settle the old composition below. - #[allow(deprecated)] - if self.ime_reset_for(viewport).blocks_custom_input() && !matches!(e, egui::ImeEvent::Disabled | egui::ImeEvent::Enabled) { - return; - } - let before = if accepted { self.ime_receipt_stamp() } else { None }; - let r = self.apply_ime_event(e); - self.settle_ime_event_state(e, owner, r.is_ok()); - if r.is_ok() && accepted { - self.refresh_ime_terminal_selection(); - } - if let Err(e) = &r { - self.set_status(e.to_string()); - } else if accepted - && let (Some(target), Some(before), Some(after)) = (target, before, self.ime_receipt_stamp()) - && before != after - && r.as_ref().is_ok_and(|v| !v.is_null() && v.get("handled").and_then(Value::as_bool) != Some(false)) - { - // A no-op receipt (an empty commit, a zero-length delete, same text reinserted) is - // not a mutation and must not poison the frame for a real commit later in the batch. - self.ime_tracker.note_input_method_apply(viewport, frame, target, before, after); - } - } - - /// Drop an event that belongs to a composition the application already settled, or to another - /// owner; returns `true` when the event must not be applied. - /// - /// A commit or deletion belongs to the composition that began the pre-edit: another owner - /// (the user clicked elsewhere) or a composition the app already settled makes it stale. - /// While the reset is still pending, the tombstone rejects pre-edits too (the platform has - /// not yet been told to cancel its copy). `observe_ime` retires the tombstone in the pass - /// that publishes the interrupt (or in an accepted no-descriptor pass, which resets the - /// backend just the same), so a later commit-only is not lost forever: it is a - /// legitimate direct commit or a new platform composition. egui's events carry no - /// generation, so an event queued by the OS across that reset is indistinguishable from - /// one the user just typed; only events in the same input batch as the settle are rejected - /// deterministically. A cleared-preedit terminal is a distinct case: its pending owner - /// remains guarded across that output boundary until its actual commit/enable/disable - /// arrives. Publishing a reset is not evidence that the separately queued terminal was - /// delivered. With no incoming event epoch, the first ambiguous new composition after an - /// unobserved reset may be rejected; no timer guesses that it became safe. - /// The tombstone is not filtered by the *current* target: a click can change the owner in - /// the settling pass, and every remaining event of that batch still belongs to the - /// pre-reset composition. Filtering would let the event after the first dropped pre-edit - /// start composing in the new target before the platform is reset. - fn reject_stale_ime_event(&mut self, ctx: &egui::Context, e: &egui::ImeEvent, owner: Option) -> bool { - let cancelled = self.ime_cancelled; - let pending_cancelled = self.ime_terminal_pending.as_ref().is_some_and(|p| p.cancelled); - #[allow(deprecated)] - let stale = !matches!(e, egui::ImeEvent::Disabled | egui::ImeEvent::Enabled) - && (self.ime_composition.is_some_and(|c| c.settled || Some(c.owner) != owner) || cancelled.is_some() || pending_cancelled); - if !stale { - return false; - } - if pending_cancelled && matches!(e, egui::ImeEvent::Commit(_)) { - // The old terminal finally arrived: reject it and release its pending owner now, - // so a new preedit later in this same raw batch can belong to the current target. - self.ime_terminal_pending = None; - self.ime_composition = None; - self.ime_cancelled = None; - self.ime_interrupt_pending = false; - return true; - } - if pending_cancelled { - // note_settled_composition already queued the reset. Do not also latch the - // frame's memory interrupt: a terminal later in this batch can consume it and - // permit a fresh preedit without resetting that new composition at pass end. - self.ime_composition = None; - return true; - } - if let Some(c) = cancelled { - log::debug!("IGNORING IME event for settled composition owner {:?} generation {}", c.owner, c.generation); - } - self.ime_composition = None; - // Ask the backend to drop its copy, so this is one stale event and not a stream. - ctx.memory_mut(|m| m.interrupt_ime()); - true - } - - /// Apply the document mutation an IME event asks for, before any receipt or tracker state. - fn apply_ime_event(&mut self, e: &egui::ImeEvent) -> deckcraft_engine::Result { - match e { - egui::ImeEvent::Preedit { text, active_range_chars } => { - self.session.compose_text(text, active_range_chars.as_ref().map(|r| (r.start, r.end))) - } - // A commit only replaces text that is being edited. It must never start editing a - // merely selected shape: without a tracked pre-edit, a stale platform commit would - // replace that shape's whole text. - egui::ImeEvent::Commit(text) => { - if self.session.active().is_some_and(|d| d.selection.text.is_some()) { - self.session.commit_text(text) - } else { - Ok(Value::Null) - } - } - egui::ImeEvent::DeleteSurrounding { before_chars, after_chars } => { - if self.session.active().is_some_and(|d| d.selection.text.is_some()) { - self.session.delete_surrounding(*before_chars, *after_chars, false) - } else { - Ok(Value::Null) - } - } - egui::ImeEvent::DeleteSurroundingBytes { before_bytes, after_bytes } => { - if self.session.active().is_some_and(|d| d.selection.text.is_some()) { - self.session.delete_surrounding(*before_bytes, *after_bytes, true) - } else { - Ok(Value::Null) - } - } - #[allow(deprecated)] - egui::ImeEvent::Disabled | egui::ImeEvent::Enabled => { - // The platform ended (or is about to restart) its composition itself. - self.session.end_composition(); - Ok(Value::Null) - } - } - } - - /// Update the tracked composition after `e` has been applied; `applied` says whether the - /// document mutation succeeded. - fn settle_ime_event_state(&mut self, e: &egui::ImeEvent, owner: Option, applied: bool) { - match e { - // The platform ends its composition on a commit (and on Disabled/Enabled): nothing is - // left to interrupt. A pre-edit keeps (or starts) the tracked composition. - egui::ImeEvent::Commit(_) => { - self.ime_terminal_pending = None; - self.ime_composition = None; - self.ime_cancelled = None; - self.ime_interrupt_pending = false; - } - #[allow(deprecated)] - egui::ImeEvent::Disabled | egui::ImeEvent::Enabled => { - // A platform-side disable/enable already reset the composition. Do not carry an - // older app-settled interrupt into the next (possibly new) composition. - self.ime_terminal_pending = None; - self.ime_composition = None; - self.ime_cancelled = None; - self.ime_interrupt_pending = false; - } - egui::ImeEvent::Preedit { text, .. } => { - match (owner, applied, self.session.active().is_some_and(|d| d.composition.is_some())) { - (Some(owner), true, true) => { - // Updating the same composition keeps its generation. After a settle (or - // a first pre-edit) this is a new generation and clears the tombstone. - let generation = match self.ime_composition { - Some(c) if c.owner == owner && !c.settled => c.generation, - _ => { - self.ime_generation = self.ime_generation.wrapping_add(1).max(1); - self.ime_generation - } - }; - self.ime_composition = Some(ImeComposition { owner, generation, settled: false }); - self.ime_terminal_pending = None; - self.ime_cancelled = None; - } - (Some(owner), true, false) if text.is_empty() && self.ime_composition.is_some_and(|c| !c.settled && c.owner == owner) => { - // The model restored committed text, but no terminal was delivered. Keep - // this owner across passes; a later pointer/key/target change must reject - // its separately queued old delete/commit, even after an outgoing reset. - if let Some(st) = self.session.active() - && let Some(t) = &st.selection.text - { - self.ime_terminal_pending = Some(ImeTerminalPending { - owner, - revision: st.revision, - anchor: t.anchor, - caret: t.caret, - cancelled: false, - interrupted: false, - interrupted_at: None, - }); - } - } - _ => { - self.ime_composition = None; - self.ime_terminal_pending = None; - } - } - } - _ => {} - } - } - - /// Observe the canvas IME owner once per pass and publish its descriptor. - /// - /// No canvas target, a Sorter/Notes Page view, a focused egui field, a modal, the palette, - /// the Backstage view, a slide show, an opening overlay, or an unfocused/hidden window means - /// the custom owner is hidden: the tracker is told so and the next focus starts a new - /// generation. The descriptor is rebuilt from the current committed text every pass. - /// - /// A composition the application settled itself is announced once as - /// `should_interrupt_composition`, so the backend cancels the platform's copy of it. That - /// settled pass is also the active-composition tombstone's lifecycle end. A cleared-preedit - /// terminal retains its separate pending owner until the incoming terminal is observed. - pub(crate) fn observe_ime(&mut self, ctx: &egui::Context) -> Option { - let viewport = self.ime_frame_viewport.unwrap_or_else(|| ctx.viewport_id()); - self.note_settled_composition(ctx); - // The editing window going away really ends the viewport's context; a merely hidden - // owner (modal, palette, unfocused field) stays observed as unfocused instead. - if self.session.active().is_none() || ctx.input(|i| i.viewport().close_requested()) { - self.ime_interrupt_pending = false; - if let Some(old) = self.ime_viewport.take() { - self.ime_tracker.end_viewport(old); - // Explicit viewport destruction removes only that viewport's guard. - let _ = self.ime_reset.remove(&old); - } - let _ = self.ime_reset.remove(&viewport); - self.ime_composition = None; - self.ime_cancelled = None; - self.ime_terminal_pending = None; - return None; - } - if !ctx.input(|i| i.viewport().focused.unwrap_or(true)) { - // The native window itself lost focus: no custom editor is eligible this pass, even - // if the model still has a text selection and a last-pass geometry rect. - self.ime_tracker.observe(viewport, None); - return None; - } - let Some(rect) = self.ime_pending.take() else { - // No canvas editor was painted in this pass. A discarded font/layout pass publishes - // nothing the platform sees, so keep the interrupt and tombstone for a later pass. - // An accepted pass is a backend reset only when it publishes *no* IME descriptor at - // all: a focused stock `TextEdit` (notes pane, dialog, palette field) publishes its - // own `o.ime` while `ime_pending` is `None`, and that descriptor is not a reset. Gate - // retirement on the actual committed output, not on the absence of the canvas rect; - // otherwise the next legitimate commit in the focused field would be rejected. - let no_descriptor = ctx.output(|o| o.ime.is_none()); - if !ctx.will_discard() && no_descriptor { - self.ime_interrupt_pending = false; - self.ime_cancelled = None; - if self.ime_composition.is_some_and(|c| c.settled) { - self.ime_composition = None; - } - } - self.ime_tracker.observe(viewport, None); - return None; - }; - if !self.ime_custom_canvas_route(ctx) { - // The canvas can still paint behind an opening overlay or a Sorter/Notes Page - // reroute, and a forced hidden paint can run after the window lost focus or - // visibility. The positive route and the UI wrapper both reject those, so a pending - // rect must not republish the custom owner. - self.ime_tracker.observe(viewport, None); - return None; - } - let Some(st) = self.session.active() else { - self.ime_interrupt_pending = false; - self.ime_tracker.observe(viewport, None); - return None; - }; - let Some(target) = self.ime_target() else { - self.ime_interrupt_pending = false; - self.ime_cancelled = None; - self.ime_tracker.observe(viewport, None); - return None; - }; - if self.ime_viewport != Some(viewport) - && let Some(old) = self.ime_viewport.replace(viewport) - { - self.ime_tracker.end_viewport(old); - let _ = self.ime_reset.remove(&old); - } - let committed = st.selection.text.as_ref().and_then(|t| deckcraft_engine::cmd::text::ime_surrounding(st, t)); - let mut observation = - egui::ime_context::ImeObservation::new(ctx.cumulative_frame_nr_for(viewport), ctx.cumulative_pass_nr_for(viewport), target) - .purpose(egui::IMEPurpose::Normal) - .committed(committed.as_ref().map(|s| egui::ime_context::CommittedText::new(&s.text, s.cursor, s.anchor))); - if committed.is_none() { - observation = observation.unavailable_revision(st.revision); - } - let update = self.ime_tracker.observe(viewport, Some(observation))?; - // Clear the interrupt only once it is part of a settled pass's output descriptor. A - // discarded font/layout pass publishes nothing the platform sees, so keep it pending; - // that pass is not the boundary at which stale pre-edits become a new generation. - let interrupt = if ctx.will_discard() { false } else { std::mem::take(&mut self.ime_interrupt_pending) }; - if interrupt { - // This pass's output carries the backend reset. The tombstone did its job for the - // events already processed in this batch; from the next batch on every pre-edit or - // commit is a new platform generation. A late event the OS queued across the reset - // has no generation in its payload, so it cannot be rejected without also dropping - // legitimate direct commits (documented residual in `ime_event`). - self.ime_cancelled = None; - if self.ime_composition.is_some_and(|c| c.settled) { - self.ime_composition = None; - } - } - let key = ImeDescriptorKey::new(update.owner, update.context_generation, update.purpose); - ctx.output_mut(|o| { - o.ime = Some(egui::output::IMEOutput { - owner: update.owner, - context_generation: update.context_generation, - purpose: update.purpose, - rect, - cursor_rect: rect, - should_interrupt_composition: interrupt, - reset_request: None, - change_cause: update.change_cause, - surrounding_text: update.surrounding_text, - }); - }); - Some(key) - } -} diff --git a/crates/ui-egui/src/app/input.rs b/crates/ui-egui/src/app/input.rs index 701f08f32..94a0ffbc6 100644 --- a/crates/ui-egui/src/app/input.rs +++ b/crates/ui-egui/src/app/input.rs @@ -1,270 +1,51 @@ +use craft::ui::runtime::windows::WindowHost; + use super::{InputTarget, SlideApp, show}; impl SlideApp { - /// What a queued synthetic event is meant for. The control protocol hands out window - /// coordinates, so a document, slide, view, zoom or canvas-layout change between queueing and - /// the next UI pass makes the event stale. - pub(crate) fn input_target(&self) -> InputTarget { - let bits = |v: f32| if v.is_finite() { v.to_bits() } else { 0 }; + /// Reads the owners and layout that give a queued window coordinate its meaning. + pub(crate) fn input_target(&self, ctx: &egui::Context) -> InputTarget { + let bits = |value: f32| if value.is_finite() { value.to_bits() } else { 0 }; + let scroll = crate::ribbon::scroll_position(self, ctx).x; InputTarget { documents: self.session.documents().len(), - active: self.session.active().map(|d| d.uid), - slide: self.session.active().map(|d| d.selection.slide), + active: self.session.active().map(|document| document.uid), + slide: self.session.active().map(|document| document.selection.slide), view: self.ui.view, zoom: self.ui.zoom.map(bits), - canvas: self.canvas_rect.map(|r| [bits(r.min.x), bits(r.min.y), bits(r.max.x), bits(r.max.y)]), - canvas_scale: bits(self.canvas_scale), - dialog: self.dialog.as_ref().map(|d| egui::Id::unique(("dialog", d.id.as_str()))), - palette: self.palette.as_ref().map(|(q, sel)| egui::Id::unique(("palette", q.as_str(), *sel))), - backstage: self.backstage.as_ref().map(|b| egui::Id::unique(("backstage", b.page.id()))), + canvas: self.canvas_rect().map(|rect| [bits(rect.min.x), bits(rect.min.y), bits(rect.max.x), bits(rect.max.y)]), + canvas_scale: bits(self.canvas_scale()), + dialog: crate::dialogs::top_dialog(ctx), + palette_open: self.palette_open, + palette_state: self.palette_open.then(|| egui::Id::unique(("palette", &self.palette_state.query, self.palette_state.selected))), + backstage: self.backstage.as_ref().map(|backstage| egui::Id::unique(("backstage", backstage.page.id()))), ribbon_tab: egui::Id::unique(("ribbon-tab", self.ui.tab.as_str())), ribbon_collapsed: self.ui.ribbon_collapsed, - ribbon_scroll: self.ribbon_scroll.get(&self.ui.tab).copied().unwrap_or(0), + ribbon_scroll: if scroll.is_finite() { scroll.to_bits() } else { 0 }, show: self.show.as_ref().map(show::Show::input_state), - opening: self.opening.as_ref().map(|o| (egui::Id::unique(("opening", o.path.as_str())), o.generation)), + opening: self.opening.as_ref().map(|opening| opening.key), } } - /// Queue one synthetic control-channel event. The target is recorded when the batch starts, - /// before any host command in the same logic pass can change the document. - pub fn queue_input(&mut self, event: egui::Event) { - let target = self.input_target(); - // A batch that was already injected keeps the target it was injected for until its UI - // pass consumes it or retracts it. New events queued meanwhile belong to the current - // target, so they wait in a separate batch instead of joining the old one and being - // cleared with it when that batch turns out to be stale. - if self.synthetic_pending { - if self.synthetic_next_target != Some(target) { - self.synthetic_next.clear(); - self.synthetic_next_target = Some(target); - } - self.synthetic_next.push(event); + /// Records the target at admission, before the window host delivers any injected step. + pub(crate) fn note_injected(&mut self, ctx: &egui::Context) { + self.injected_target = Some(self.input_target(ctx)); + } + + /// Withdraws stale steps through the host; no input is copied or replayed on a rerun. + /// Each pass compares its current owners, including a modal opened by the preceding pass. + /// The host keeps the rest of the request whose step already ran, so a key whose press + /// ended the show still gets its release; the control channel fails a waiter only for a + /// step the host withdrew before it ran. + pub(crate) fn withdraw_if_retargeted(&mut self, ctx: &egui::Context) { + let host = WindowHost::of(ctx); + if host.injected_idle() { + self.injected_target = None; return; } - if self.synthetic.is_empty() { - self.synthetic_target = Some(target); - } else if self.synthetic_target != Some(target) { - // The unsent queue belongs to a target that has already changed; drop it (and any - // older batch still waiting behind it) rather than appending a click intended for the - // new target to a stale batch. - self.synthetic.clear(); - self.synthetic_next.clear(); - self.synthetic_next_target = None; - self.synthetic_target = Some(target); + if self.injected_target.is_some_and(|target| target != self.input_target(ctx)) { + host.withdraw_injected(host.current()); + self.injected_target = None; } - self.synthetic.push(event); - } - - /// Events admitted by the control channel but not yet injected (including a batch waiting - /// behind the one currently in flight). - pub(crate) fn synthetic_queued_len(&self) -> usize { - self.synthetic.len() + self.synthetic_next.len() - } - - /// Forget the injected or queued synthetic batch and everything recorded about it. Events - /// waiting in `synthetic_next` are a separate, newer batch and are promoted by the caller. - fn clear_synthetic_batch(&mut self) { - self.synthetic.clear(); - self.synthetic_pending = false; - self.synthetic_injected.clear(); - self.synthetic_injected_at = None; - self.synthetic_injected_time = None; - self.synthetic_target = None; - self.synthetic_focus = None; - } - - /// Start the batch that was queued behind an older one once the older batch is gone. - pub(super) fn promote_next_synthetic(&mut self) { - if self.synthetic_pending || !self.synthetic.is_empty() || self.synthetic_next.is_empty() { - return; - } - self.synthetic = std::mem::take(&mut self.synthetic_next); - self.synthetic_target = self.synthetic_next_target.take(); - self.synthetic_focus = None; - } - - /// A font/layout pass will be discarded: egui already consumed the injected events but the - /// app deliberately lays nothing out, so put them back at the head of the queue. The next - /// frame injects them again after the new fonts are installed; otherwise a control click that - /// happened to arrive on the very first frame would be acknowledged without ever reaching the - /// UI. - pub(super) fn requeue_injected_synthetic(&mut self) { - if !self.synthetic_pending { - return; - } - let mut combined = std::mem::take(&mut self.synthetic_injected); - combined.append(&mut self.synthetic); - self.synthetic = combined; - self.synthetic_pending = false; - self.synthetic_injected_at = None; - self.synthetic_injected_time = None; - self.synthetic_focus = None; - if self.synthetic.is_empty() { - self.synthetic_target = None; - self.promote_next_synthetic(); - } - } - - /// Remove exactly the recorded synthetic events from `events`. The recorded index is tried - /// first so an identical host event earlier in the batch is never removed; the last exact - /// match is only a fallback for a raw input that was rewritten around the events. - fn drain_synthetic_from(&self, events: &mut Vec) -> bool { - let injected = &self.synthetic_injected; - let n = injected.len(); - if n == 0 { - return false; - } - let exact = self.synthetic_injected_at.filter(|start| events.get(*start..*start + n).is_some_and(|w| w == injected.as_slice())); - let at = exact.or_else(|| events.windows(n).rposition(|w| w == injected.as_slice())); - if let Some(at) = at { - events.drain(at..at + n); - true - } else { - false - } - } - - /// Drop an injected batch whose document, canvas, focus or modal owner changed during - /// `logic`. eframe calls `raw_input_hook` before `App::logic`, so a control request drained - /// there can still retarget the same `RawInput`. - /// - /// This must not infer the pass phase from `ViewportInfo::visible()`: a visible root can run - /// logic-only (an overdue redraw), and a hidden root can run a full pass for a screenshot or - /// `RequestPaintWhileHidden`. A logic-only callback leaves `InputState` from the *previous* - /// pass; remove the batch only when the live input carries exactly what this pass injected - /// (same `RawInput::time` and the exact recorded event window). Otherwise keep the pending - /// bookkeeping so the next `raw_input_hook` can retract the events from the carried - /// `RawInput` before eframe delivers them in a full pass. - pub(super) fn retract_synthetic_after_logic(&mut self, ctx: &egui::Context) { - if !self.synthetic_pending { - return; - } - let current = self.input_target(); - let focus = crate::framework::focused_widget(ctx); - if self.synthetic_target == Some(current) && focus == self.synthetic_focus { - return; - } - let injected_time = self.synthetic_injected_time; - let mut removed = false; - ctx.input_mut(|i| { - // A logic-only call keeps the previous pass's `InputState`; its `raw.time` is not the - // time of the RawInput this batch was injected into. Never drain an older batch that - // happens to look similar. - if i.raw.time != injected_time { - return; - } - let mut events = std::mem::take(&mut i.events); - let ok = self.drain_synthetic_from(&mut events); - i.events = events; - if ok { - // Keep `InputState::raw` consistent with what UI code reads as `events`. - let mut raw_events = std::mem::take(&mut i.raw.events); - let _ = self.drain_synthetic_from(&mut raw_events); - i.raw.events = raw_events; - removed = true; - } - }); - if removed { - self.clear_synthetic_batch(); - self.promote_next_synthetic(); - } else { - // Logic-only (or a pass whose input does not contain the batch): the events are in - // eframe's carried RawInput. Keep `synthetic_pending`, `synthetic_injected` and the - // stale target so the next hook retracts them there. Events queued after the batch - // belong to the same stale target as well. - self.synthetic.clear(); - } - } - - /// True when the pending synthetic batch is in this pass's live `InputState`, i.e. this is - /// the full pass the batch was admitted for and egui has already derived pointer/key state - /// from it. A logic-only callback leaves the previous pass's `InputState` (with another - /// `raw.time`) and must not be mistaken for the live pass, so control/background work is - /// still drained there and the next `raw_input_hook` retracts a batch that went stale. - pub(super) fn synthetic_batch_is_live(&self, ctx: &egui::Context) -> bool { - if !self.synthetic_pending || self.synthetic_injected.is_empty() { - return false; - } - let Some(injected_time) = self.synthetic_injected_time else { return false }; - let injected = &self.synthetic_injected; - ctx.input(|i| i.raw.time == Some(injected_time) && i.events.windows(injected.len()).any(|w| w == injected.as_slice())) - } - - /// Input that belongs to the pass about to run: native dropped files and one synthetic - /// control-channel batch. The synthetic batch is injected at most once; while it is - /// unacknowledged, later passes cannot replay it. A document, canvas, focus or modal change - /// drops the whole queued batch rather than typing into the wrong place. - /// - /// The hook always injects into the `RawInput`; it does not try to guess whether eframe will - /// run this as a full or a logic-only pass. `run_logic` does not consume events but eframe - /// carries the whole `RawInput` into the next full pass, so an already-injected batch is - /// retracted at the next hook if a control request changed the target, and otherwise is - /// delivered exactly once in the next real UI pass. `ViewportInfo::visible()` is not a phase - /// signal: a hidden root still gets a full pass for a screenshot or `RequestPaintWhileHidden`. - pub fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) { - #[cfg(not(target_arch = "wasm32"))] - for f in std::mem::take(&mut raw.dropped_files) { - let name = f.path().file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| "dropped file".into()); - match f.bytes() { - Ok(bytes) => self.open_or_insert_bytes(&name, &bytes), - Err(e) => self.set_status(e), - } - } - let focus = crate::framework::focused_widget(ctx); - if self.synthetic_pending { - let current = self.input_target(); - if self.synthetic_target != Some(current) || focus != self.synthetic_focus { - // eframe keeps the whole RawInput from a logic-only pass in `pending_raw_input` - // and appends the next host input to it. The events are already in `raw.events`; - // clearing only the unsent queue would still deliver the stale click or key into - // the new document on the next full pass. Retract exactly the batch we appended. - let _ = self.drain_synthetic_from(&mut raw.events); - self.clear_synthetic_batch(); - // New control input queued for the current target while the stale batch was in - // flight is a separate batch; keep it instead of clearing it with the old one. - self.promote_next_synthetic(); - } else { - // This RawInput is the carrier for the next pass, and eframe refreshes its time - // on every call. Record the current time so `retract_synthetic_after_logic` can - // tell this full pass's live `InputState` from a logic-only callback's stale one. - self.synthetic_injected_time = raw.time; - } - } - if self.synthetic_pending || self.synthetic.is_empty() { - return; - } - let current = self.input_target(); - if self.synthetic_target != Some(current) { - // The batch was queued for a document/slide/canvas that has since changed. - self.synthetic.clear(); - self.synthetic_target = None; - self.promote_next_synthetic(); - if self.synthetic.is_empty() { - return; - } - if self.synthetic_target != Some(current) { - // The newer batch is stale too: drop it rather than delivering it to this target. - self.synthetic.clear(); - self.synthetic_target = None; - self.synthetic_next.clear(); - self.synthetic_next_target = None; - return; - } - } - self.synthetic_generation = self.synthetic_generation.wrapping_add(1).max(1); - log::debug!("injecting synthetic input batch {}", self.synthetic_generation); - let n = match self.synthetic.first() { - Some(egui::Event::PointerMoved(_) | egui::Event::PointerButton { .. }) => 1, - _ => self.synthetic.iter().position(|e| matches!(e, egui::Event::Key { pressed: false, .. })).map_or(self.synthetic.len(), |i| i + 1), - }; - let n = n.min(self.synthetic.len()); - let batch: Vec = self.synthetic.drain(..n).collect(); - let at = raw.events.len(); - raw.events.extend(batch.iter().cloned()); - self.synthetic_injected = batch; - self.synthetic_injected_at = Some(at); - self.synthetic_injected_time = raw.time; - self.synthetic_pending = true; - self.synthetic_focus = focus; } } diff --git a/crates/ui-egui/src/app/keys.rs b/crates/ui-egui/src/app/keys.rs index 4c2769e6d..8c28dd295 100644 --- a/crates/ui-egui/src/app/keys.rs +++ b/crates/ui-egui/src/app/keys.rs @@ -1,191 +1,75 @@ -use super::clipboard::OBJECTS_MARKER; -use super::{Mods, SlideApp, Value, backstage, json, menus}; -use crate::framework::widget_has_keyboard; +use super::SlideApp; +use craft::keymap::{Chord, Key, Mods as KeyMods}; +use craft::ui::runtime::focus; +use craft::ui::runtime::keys::{Intent, with_window_intents}; + +/// Alt+1 addresses slot zero; Alt+9 addresses slot eight. There is no Alt+0 slot. +pub(crate) const QAT_CLAIMS: &[Chord] = &[ + Chord::new(KeyMods::ALT, Key::Num1), + Chord::new(KeyMods::ALT, Key::Num2), + Chord::new(KeyMods::ALT, Key::Num3), + Chord::new(KeyMods::ALT, Key::Num4), + Chord::new(KeyMods::ALT, Key::Num5), + Chord::new(KeyMods::ALT, Key::Num6), + Chord::new(KeyMods::ALT, Key::Num7), + Chord::new(KeyMods::ALT, Key::Num8), + Chord::new(KeyMods::ALT, Key::Num9), +]; impl SlideApp { - /// The app shortcuts that still make sense on the empty File/start screen: create, open, - /// the command palette, preferences and the File tab itself. Document commands (save, find, - /// hyperlink, show, zoom) stay out; none of them can act on a presentation that is not open. - fn start_screen_shortcut(key: egui::Key, m: Mods) -> bool { - use egui::Key::*; - matches!( - (key, m.cmd, m.shift, m.alt), - (O, true, false, false) | (P, true, true, false) | (Comma, true, false, false) | (F, false, false, true) - ) - } - - /// File-tab navigation and document-free shortcuts, also used on the start screen. - fn route_backstage_keys(&mut self, events: Vec) { - if self.backstage.is_none() { - return; - } - // The File tab: its own keys (Esc goes back, arrows walk the side menu) and app - // shortcuts (New, Open, Command Palette…); typing, pasting or deleting would edit the - // hidden presentation. - let start_screen = self.session.active().is_none(); - for e in events { - if let egui::Event::Key { key, pressed: true, modifiers, .. } = e { - let mods = Mods { shift: modifiers.shift, alt: modifiers.alt, cmd: modifiers.command || modifiers.ctrl }; - let handled = backstage::key(self, key, mods) - // With no presentation the File home only owns the shortcuts that create or - // open one. Borrowing the whole document shortcut table here would also arm - // Save/Save As, hyperlink, find/replace, show and zoom against the empty - // start screen, which is a scope expansion no editing route needs. - || (mods.cmd || mods.alt) - && (!start_screen || Self::start_screen_shortcut(key, mods)) - && menus::ui_shortcut(self, key, mods); - if handled { - continue; - } - // Engine shortcuts that don't touch the hidden slide (Ctrl+N). - if mods.cmd - && matches!(key, egui::Key::N) - && let Err(e) = self.session.key(key_name(key), mods) - { - self.set_status(e.to_string()); - } - } - } - } - - /// Keyboard and clipboard for the slide (with nothing or the document window focused). + /// Applies only the raw input this pass receives after the framework has routed owned keys. + /// A second pass has no earlier pass's events or queued key state to replay. pub(super) fn keyboard(&mut self, ctx: &egui::Context) { - let mut events = ctx.input(|i| i.events.clone()); - if crate::framework::window_escape(ctx) { - events.push(crate::framework::ESCAPE_PRESS); + if crate::dialogs::modal_open(ctx) || self.palette_open { + return; } - // Ctrl+V with only an image on the clipboard: egui-winit sends no Paste event and swallows the - // key press, so the release of a V press never seen is the paste. Tracked even while a text - // field has focus, so that a V typed there is not taken for one. - let mut image_paste = false; - let mut pasted_image_event = false; - for e in &events { - match e { - egui::Event::PasteImage(_) => { - pasted_image_event = true; - self.v_seen = true; + if self.anim_preview.is_some() { + with_window_intents(ctx, false, |intents| { + if intents.take(Intent::Cancel) { + self.anim_preview = None; + true + } else { + false } - egui::Event::Paste(_) | egui::Event::Key { key: egui::Key::V, pressed: true, .. } => self.v_seen = true, - egui::Event::Key { key: egui::Key::V, pressed: false, modifiers, .. } => { - // Only a release with Command/Ctrl held is a paste: a bare V release is not. - let seen = std::mem::take(&mut self.v_seen); - image_paste = !seen && (modifiers.command || modifiers.ctrl); + }); + } + if self.session.active().is_none() || self.backstage_open() { + return; + } + for event in ctx.input(|input| input.events.clone()) { + if crate::dialogs::modal_open(ctx) || self.palette_open || self.backstage_open() { + break; + } + match event { + // Bound chords fire through the command catalogue and the canvas tool's key claims + // run the slide's own keys, so a key event here only keeps Tab on the slide. + egui::Event::Key { key: egui::Key::Tab, pressed: true, .. } if !focus::has_any(ctx) => { + // The slide has the keyboard, so Tab is ours (indent, tab character, next + // shape). Left to egui it would also focus the first ribbon widget, and + // every key after it would go there instead of the slide (#78). + ctx.memory_mut(|m| m.move_focus(egui::FocusDirection::None)); } - _ => {} - } - } - let viewport = self.ime_viewport_or(ctx); - if self.session.active().is_none() { - // No document: keep slide-editing input suspended, while the start screen's - // File-tab navigation and document-free shortcuts remain available. - self.suspend_ime_reset(viewport); - self.route_ime_controls_only(ctx, &events); - if self.palette.is_none() && self.dialog.as_ref().is_none_or(|d| !d.modal()) && !widget_has_keyboard(ctx) { - self.route_backstage_keys(events); - } - self.drain_requests(); - return; - } - let modal = self.dialog.as_ref().is_some_and(|d| d.modal()) || self.palette.is_some(); - self.edited_text_takes_focus(ctx); - if widget_has_keyboard(ctx) || modal { - // A stock field/modal/palette owns input now. Retire the custom fence, then visit - // controls in raw order; stock text/key events are left for the stock widgets. - self.suspend_ime_reset(viewport); - self.route_ime_controls_only(ctx, &events); - return; - } - if self.backstage.is_some() { - self.suspend_ime_reset(viewport); - self.route_ime_controls_only(ctx, &events); - self.route_backstage_keys(events); - self.drain_requests(); - return; - } - let img = if image_paste { self.services.clipboard_image.as_mut().and_then(|f| f()) } else { None }; - if let Some(png) = img { - let data = deckcraft_engine::cmd::base64_encode(&png); - if let Err(e) = self.session.execute("insert.picture", &json!({"name": "Pasted image.png", "data": data})) { - self.set_status(e.to_string()); - } - } - for e in events { - // An earlier command in this raw batch may have settled the composition. Request the - // replacement at this ordered boundary, before the current event is considered. - self.note_settled_composition(ctx); - match e { - egui::Event::ImeResetCompleted { request_id } => self.ime_reset_completed(request_id, ctx), - egui::Event::PasteImage(image) => match color_image_png(&image) { - Ok(png) => { - let params = json!({"name": "Pasted image.png", "data": deckcraft_engine::cmd::base64_encode(&png)}); - if let Err(e) = self.session.execute("insert.picture", ¶ms) { - self.set_status(e.to_string()); - } + // egui 0.37 carries a clipboard image as its own event; it inserts once. + egui::Event::PasteImage(image) if !focus::has_any(ctx) => { + if let Err(error) = self.paste_picture(&image) { + self.set_status(error); } - Err(e) => self.set_status(e), - }, - egui::Event::Text(t) => { - let revision = self.session.active().map(|d| d.revision); + } + egui::Event::Text(text) if !focus::has_any(ctx) => { if self.session.active().is_some_and(|d| d.selection.text.is_some() || d.selection.shapes.len() == 1) - && let Err(e) = self.session.type_text(&t) + && let Err(error) = self.session.type_text(&text) { - self.set_status(e.to_string()); - } - if self.session.active().map(|d| d.revision) != revision { - self.note_application_edit(ctx); + self.set_status(error.to_string()); } } - egui::Event::Ime(ime) => self.ime_event(ctx, &ime), - egui::Event::Copy => self.publish_clipboard(ctx, false), - egui::Event::Cut => self.publish_clipboard(ctx, true), - egui::Event::Paste(text) => { - // Our own marker for objects without text: paste what the session copied. - let text = if text == OBJECTS_MARKER { String::new() } else { text }; - // A picture (TIFF from Keynote, a screenshot) lands when the paste has no text. - // Text keeps its HTML (bold, italic, underline) when the host can read it. - let html = self.services.clipboard_html.as_mut().and_then(|f| f()).filter(|h| !h.is_empty()); - // egui 0.37 sends `PasteImage` directly; the services fallback stays for - // integrations that still send an empty `Paste`, and for a browser's Copy - // Image, whose text is only the picture's link. Never insert twice. - let wants_picture = text.is_empty() || super::clipboard::names_a_picture(&text, html.as_deref()); - let img = if wants_picture && !pasted_image_event { self.services.clipboard_image.as_mut().and_then(|f| f()) } else { None }; - let revision = self.session.active().map(|d| d.revision); - let r = match img { - Some(png) => self - .session - .execute("insert.picture", &json!({"name": "Pasted image.png", "data": deckcraft_engine::cmd::base64_encode(&png)})), - None => { - let mut params = json!({"text": text}); - if let Some(h) = html { - params["html"] = Value::String(h); - } - self.session.execute("edit.paste", ¶ms) - } - }; - if let Err(e) = r { - self.set_status(e.to_string()); - } - if self.session.active().map(|d| d.revision) != revision { - self.note_application_edit(ctx); - } - } - egui::Event::Key { key, pressed: true, modifiers, .. } => { - if key == egui::Key::Escape && self.anim_preview.is_some() && !modifiers.command && !modifiers.ctrl && !modifiers.alt { - self.anim_preview = None; - continue; - } - let mods = Mods { shift: modifiers.shift, alt: modifiers.alt, cmd: modifiers.command || modifiers.ctrl }; - if !self.session.tool.drawing_freeform() && menus::ui_shortcut(self, key, mods) { - continue; - } - let name = key_name(key); - let revision = self.session.active().map(|d| d.revision); - match self.session.key(name, mods) { - Ok(_) => {} - Err(e) => self.set_status(e.to_string()), - } - if self.session.active().map(|d| d.revision) != revision { - self.note_application_edit(ctx); + // The canvas composes for a selected shape (`text_host::show_selection_ime`): the first preedit starts + // editing it, and the framework editor takes the composition from there. A commit or deletion with + // nothing edited is a stale one and must not replace the shape's text. + egui::Event::Ime(egui::ImeEvent::Preedit { text, active_range_chars }) if !focus::has_any(ctx) => { + if self.session.active().is_some_and(|d| d.selection.text.is_none() && d.selection.shapes.len() == 1) + && let Err(error) = self.session.compose_text(&text, active_range_chars.map(|range| (range.start, range.end))) + { + self.set_status(error.to_string()); } } _ => {} @@ -220,14 +104,11 @@ pub fn key_name(key: egui::Key) -> &'static str { } } -/// Largest clipboard image accepted into the document: 16 megapixels, the same bound as -/// background removal. The image was already allocated by the integration; this keeps the -/// RGBA copy, PNG and base64 from multiplying an arbitrarily large paste before `insert.picture`. +/// Largest clipboard image accepted before allocating PNG and base64 copies. const MAX_PASTE_IMAGE_PIXELS: usize = 16_000_000; -/// Encode an egui color image as the PNG bytes `insert.picture` stores. -fn color_image_png(image: &egui::ColorImage) -> Result, String> { - let [w, h] = image.size; +/// Checks the paste size before making another pixel buffer. +pub(super) fn paste_image_pixels([w, h]: [usize; 2]) -> Result { let pixels = w.checked_mul(h).ok_or_else(|| "the pasted image is too large".to_string())?; if pixels == 0 { return Err("the pasted image is empty".into()); @@ -235,6 +116,16 @@ fn color_image_png(image: &egui::ColorImage) -> Result, String> { if pixels > MAX_PASTE_IMAGE_PIXELS { return Err(format!("the pasted image is {w}×{h} pixels; the limit is 16 megapixels")); } + Ok(pixels) +} + +/// Encodes a clipboard image as the PNG bytes `insert.picture` stores. +pub(super) fn color_image_png(image: &egui::ColorImage) -> Result, String> { + let pixels = paste_image_pixels(image.size)?; + if image.pixels.len() != pixels { + return Err("the pasted image has incomplete pixel data".into()); + } + let [w, h] = image.size; let rgba: Vec = image.pixels.iter().flat_map(|c| c.to_array()).collect(); Ok(deckcraft_render::Image { width: w as u32, height: h as u32, pixels: rgba }.to_png()) } diff --git a/crates/ui-egui/src/app/playback.rs b/crates/ui-egui/src/app/playback.rs index c46286807..1a9e3daf9 100644 --- a/crates/ui-egui/src/app/playback.rs +++ b/crates/ui-egui/src/app/playback.rs @@ -1,12 +1,21 @@ use super::{AnimPreview, SlideApp, Value, ViewMode, json, media, preview, show}; +use craft::ui::runtime::{frame, windows::WindowHost}; +use craft::web_host::link::LinkState; + +/// The longest a hidden show waits between logic passes, in seconds: a hidden event loop has no +/// draw to piggyback on, so a delayed repaint is the only thing that keeps its clock ticking. +const HIDDEN_WAKE_CAP_SECS: f64 = 0.1; + +/// Whether a second display can take Presenter View. Like PowerPoint, one display shows only +/// the slides: the presenter window would open on the same screen, and whichever of the two +/// windows ends up behind the other stalls the show (the compositor stops pacing a hidden +/// window). Hosts that can't count displays keep Presenter View. +pub(crate) fn second_display(ctx: &egui::Context) -> bool { + let n = WindowHost::of(ctx).monitors().len(); + n == 0 || n >= 2 +} impl SlideApp { - /// Whether ⌘A should act on the slide list: always in the sorter, in Normal view once the - /// thumbnail pane has been clicked. - pub(crate) fn slides_list_focused(&self) -> bool { - self.ui.view == ViewMode::Sorter || (self.ui.view == ViewMode::Normal && self.slides_focused) - } - /// First slide Play from Start should open: the custom show or range, skipping hidden slides. pub fn show_start_index(&self) -> usize { self.session.active().and_then(|d| deckcraft_anim::show_order(&d.doc).first().copied()).unwrap_or(0) @@ -30,24 +39,7 @@ impl SlideApp { /// Leave animation preview, stop editor-owned media, and create a show at the requested slide /// with the current reading/presenter configuration; an out-of-range slide starts an ended show. pub fn start_show(&mut self, from: usize, reading: bool) { - self.anim_preview = None; - self.media.stop_owned(media::Owner::Editor); - let presenter = self.ui.presenter_view && !reading && self.second_display(); - if let Some(d) = self.session.active() { - self.show_instance = self.show_instance.wrapping_add(1).max(1); - let mut show = show::Show::new(&d.doc, from, reading, presenter); - show.instance = self.show_instance; - show.keep_cursor = self.ui.show_keep_cursor; - self.show = Some(show); - } - } - - /// Whether a second display can take Presenter View. Like PowerPoint, one display shows only - /// the slides: the presenter window would open on the same screen, and whichever of the two - /// windows ends up behind the other stalls the show (the compositor stops pacing a hidden - /// window). Hosts that can't count displays keep Presenter View. - fn second_display(&mut self) -> bool { - self.services.displays.as_mut().and_then(|f| f()).is_none_or(|n| n >= 2) + self.start_show_with(from, reading, if self.ui.presenter_view { show::PresenterStart::Setting } else { show::PresenterStart::Off }); } /// Play custom show `name` from its first slide. Set Up Slide Show is left as it was. @@ -97,6 +89,10 @@ impl SlideApp { return false; } let Some(p) = self.anim_preview.as_mut() else { return false }; + if let Some(t) = p.held { + p.elapsed = t; + return true; + } let now = if now.is_finite() { now } else { p.started.unwrap_or(0.0) }; let start = *p.started.get_or_insert(now); let elapsed = p.from + (now - start).max(0.0); @@ -140,7 +136,8 @@ impl SlideApp { } self.close_backstage(); let duration = timeline.total_duration(); - self.anim_preview = Some(AnimPreview { uid, slide, slide_ptr: ptr, started: None, from: from_secs, elapsed: from_secs, timeline }); + self.anim_preview = + Some(AnimPreview { held: None, uid, slide, slide_ptr: ptr, started: None, from: from_secs, elapsed: from_secs, timeline }); self.set_status("Previewing animations"); Ok(json!({"playing": true, "slide": slide, "duration": duration, "from": from_secs})) } @@ -150,36 +147,70 @@ impl SlideApp { /// and advances from there. A forced hidden paint draws the current state but does not /// advance it a second time, and no paused-show product policy is invented. pub(crate) fn tick_hidden_show(&mut self, ctx: &egui::Context, now: web_time::Instant) { - let visible = show::viewport_visible(ctx); + let visible = WindowHost::of(ctx).visible(); let Some(doc) = self.session.active().map(|d| d.doc.clone()) else { return }; let Some(show) = self.show.as_mut() else { return }; - if show.presenter_grid && self.services.presenter.as_ref().is_some_and(|host| !host.is_open()) { + if show.presenter_grid && self.services.presenter.as_ref().is_some_and(|host| !matches!(host.state(), LinkState::Open | LinkState::Opening)) { // A web popup closed with its grid open must not hold auto-advance while this tab is hidden (#1866). show.presenter_grid = false; } if visible { // A visible logic-only pass (`run_logic`) carries the last full frame's input time. // Anchoring that stale time to `now` would move the hidden clock backwards if the - // window hides before the next full pass. `show::ui` already records the anchor on - // every visible full pass, where `InputState::time` is current. + // window hides before the next full pass. The show page body calls + // `observe_visible_frame` on every visible full pass with the current pass time. return; } if !show.hidden_started() { return; } - let input_time = ctx.input(|i| i.time); + let input_time = frame::clock(ctx); let show_time = show.hidden_logic_time(input_time, now); let keep = show.advance_hidden(&doc, show_time); - let time_driven = show.hidden_time_driven(&doc); if !keep { self.show = None; return; } - if time_driven { - // A hidden event loop has no draw to piggyback on. A delayed repaint keeps the - // logic clock ticking; with no paint request pending eframe services it as a - // logic-only pass, not a visible frame. - ctx.request_repaint_after_for(std::time::Duration::from_millis(100), ctx.viewport_id()); + if let Some(deadline) = show.next_wake(&doc, show_time) { + // A delayed repaint keeps the logic clock ticking; with no paint request pending + // eframe services it as a logic-only pass, not a visible frame. + frame::request_repaint_after(ctx, (deadline - show_time).clamp(0.0, HIDDEN_WAKE_CAP_SECS)); + } + } +} + +impl crate::SlideApp { + /// Holds animation preview at a requested time; `None` resumes from the playhead. + pub fn hold_anim_preview(&mut self, time: Option) -> Result { + if time.is_some() && self.anim_preview.is_none() { + self.start_anim_preview(None)?; + } + let Some(p) = self.anim_preview.as_mut() else { return Ok(json!({"held": false})) }; + if let Some(t) = time { + let t = t.clamp(0.0, p.timeline.total_duration()); + p.held = Some(t); + p.elapsed = t; + } else { + p.from = p.elapsed; + p.started = None; + p.held = None; + } + Ok(json!({"held": p.held.is_some(), "time": p.elapsed})) + } +} + +impl crate::SlideApp { + /// Starts a show with an explicit presenter mode. + pub(crate) fn start_show_with(&mut self, from: usize, reading: bool, presenter: crate::show::PresenterStart) { + self.anim_preview = None; + self.media.stop_owned(media::Owner::Editor); + if let Some(d) = self.session.active() { + self.show_instance = self.show_instance.wrapping_add(1).max(1); + let mut show = show::Show::new(&d.doc, from, reading, false); + show.presenter_start = if presenter == show::PresenterStart::Setting && reading { show::PresenterStart::Off } else { presenter }; + show.instance = self.show_instance; + show.keep_cursor = self.ui.show_keep_cursor; + self.show = Some(show); } } } diff --git a/crates/ui-egui/src/app/scheme.rs b/crates/ui-egui/src/app/scheme.rs new file mode 100644 index 000000000..b4156fb70 --- /dev/null +++ b/crates/ui-egui/src/app/scheme.rs @@ -0,0 +1,6 @@ +impl crate::SlideApp { + /// Returns the current presentation colour scheme. + pub(crate) fn color_scheme(&self) -> deckcraft_color::ColorScheme { + self.session.active().and_then(|d| d.doc.masters.first().map(|m| m.scheme())).unwrap_or_else(|| deckcraft_model::Theme::default().colors) + } +} diff --git a/crates/ui-egui/src/backstage.rs b/crates/ui-egui/src/backstage.rs index 814669728..9abe00eaa 100644 --- a/crates/ui-egui/src/backstage.rs +++ b/crates/ui-egui/src/backstage.rs @@ -1,56 +1,55 @@ -//! The File tab (Backstage, #76): a full-window view that replaces the ribbon, slides and status -//! bar until Esc or the back arrow returns to the presentation. With nothing open it is the start -//! screen: PowerPoint's start screen and File › Home are the same page. +//! The File tab replaces the editor until the user returns to the presentation. +//! With no document it is the start screen, showing the same Home page. //! //! A side menu on the left picks a page (Home, New, Open, Info, Save As, Print, Export, About); //! Save, Close and Options act at once. Every action runs an existing command through //! [`SlideApp::run`] or one of the app's file helpers ([`SlideApp::export_as`], //! [`SlideApp::print_pdf`], [`SlideApp::save_as_dialog`]); the state here is UI-only and never //! saved. Recent presentations are listed by path: nothing on disk is read until one is picked. -//! -//! Laid out after PowerPoint for Windows (observed black-box): a 160-point side menu darker than -//! the page, 40-point entries with an outline icon, the current page in the accent colour. -use egui::{Align2, Color32, CornerRadius, Key, Rect, RichText, Sense, Stroke, StrokeKind, Ui, pos2, vec2}; +use craft::menu::ribbon::{BackLook, BackstageEntry, BackstageEvent, BackstageView}; +use craft::ui::contract::{BodyCx, Show as _}; +use craft::ui::display::Text; +use egui::Ui; use serde_json::{Value, json}; use crate::SlideApp; -use crate::icons::{self, Icon}; -use crate::theme::{self, Tokens}; +use crate::icons::Icon; mod files; mod info; -mod print; +pub(crate) mod print; pub use files::split_path; use files::{home, new_page, open_page}; +pub use info::SAVE_TYPES; use info::{PROPERTIES, about, commit_props, info, save_as}; -pub use info::{SAVE_TYPES, format_bytes}; use print::{export, print}; pub use print::{print_page_size, print_params, print_slides}; -/// Width of the side menu. -pub const NAV_W: f32 = 160.0; -/// Height of a side-menu entry (the back arrow's row is a little taller). -const ITEM_H: f32 = 40.0; -const BACK_H: f32 = 46.0; -/// The widest a page's content grows. -const CONTENT_W: f32 = 1180.0; - /// A page of the File tab. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum Page { + /// Start page and recent presentations. Home, + /// Blank presentations, themes and templates. New, + /// File browsing and recent presentations. Open, + /// Presentation metadata and properties. Info, + /// A destination and format for saving. SaveAs, + /// Print settings and page previews. Print, + /// Copies in other formats. Export, + /// Product information and appearance settings. About, } impl Page { + /// Every File page accepted by the automation command. pub const ALL: [Page; 8] = [Page::Home, Page::New, Page::Open, Page::Info, Page::SaveAs, Page::Print, Page::Export, Page::About]; /// The id `app.backstage {page}` takes. @@ -67,9 +66,10 @@ impl Page { } } + /// Resolve a File page id, including its compatibility alias. pub fn parse(id: &str) -> Option { let id = id.trim(); - // Keep existing control-channel callers working after the visible page rename. + // The compatibility alias keeps saved automation requests valid. if id.eq_ignore_ascii_case("account") { return Some(Page::About); } @@ -110,11 +110,15 @@ impl Page { } /// A side-menu entry: a page, or an action that runs at once. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum Nav { + /// Shows a File page. Page(Page), + /// Saves the active presentation. Save, + /// Requests closing the active presentation. Close, + /// Opens preferences above the File view. Options, } @@ -127,6 +131,7 @@ impl Nav { Nav::Options => "Options", } } + fn icon(self) -> Icon { match self { Nav::Page(p) => p.icon(), @@ -137,58 +142,77 @@ impl Nav { } } -/// The side menu, top group then bottom group, in keyboard order. PowerPoint's Share (cloud) is -/// left out; with nothing open only Home, New and Open stay at the top. -pub fn entries(has_doc: bool) -> (Vec