diff --git a/.cargo/config.toml b/.cargo/config.toml index 35049cbcb..9c41044f8 100644 --- a/.cargo/config.toml +++ b/.cargo/config.toml @@ -1,2 +1,7 @@ +# Local builds pick up the optional craft-fonts checkout next to this repo (Inter etc.). When the +# directory is missing the build warns and carries on with egui's bundled fonts and system fonts. +[env] +CRAFT_FONTS_DIR = { value = "../craft-fonts", relative = true } + [alias] xtask = "run --package xtask --" diff --git a/.github/nightly-signing-policy.json b/.github/nightly-signing-policy.json index a5d253325..d42e27e8a 100644 --- a/.github/nightly-signing-policy.json +++ b/.github/nightly-signing-policy.json @@ -4,10 +4,10 @@ "repository_id": 1400018213, "producer_workflow_id": 429745945, "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", @@ -83,7 +83,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", @@ -95,7 +97,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/nightly-dispatch.yml b/.github/workflows/nightly-dispatch.yml new file mode 100644 index 000000000..769d93fe1 --- /dev/null +++ b/.github/workflows/nightly-dispatch.yml @@ -0,0 +1,71 @@ +name: Dispatch release-ref nightly + +# Transport only, never authorization. No checkout, payload parsing or release environment. +on: + workflow_run: + workflows: [DesignCraft unsigned nightly] + types: [completed] + branches: [main] + +permissions: {} + +jobs: + dispatch: + if: >- + github.repository == 'storytold/designcraft' && + 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/designcraft', '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/designcraft', 'wrong event repository') + producer = event.get('workflow_run', {}) + require(producer.get('head_repository', {}).get('full_name') == 'storytold/designcraft', '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/designcraft/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': 'designcraft-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 406a64f0f..e5d9c3824 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: designcraft 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 d9a8e0f37..867290568 100644 --- a/.github/workflows/nightly.yml +++ b/.github/workflows/nightly.yml @@ -1,8 +1,9 @@ name: DesignCraft unsigned nightly -# Enabled for supervised manual runs by the reviewed manual actors only; no schedule yet. -# A later explicit opt-in may add a cadence (and turn on nightly-dispatch.yml with it). +# Automated daily schedule at 01:30 UTC plus supervised manual runs by the reviewed manual actors. on: + schedule: + - cron: '30 1 * * *' workflow_dispatch: permissions: @@ -22,9 +23,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: designcraft manual-actors: '["bflatastic","dylanmtaylor","echelon","FredApps","skylartaylor"]' craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83 @@ -32,3 +33,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 c5731a0ae..c3c8ec6a0 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/Cargo.lock b/Cargo.lock index b4a802771..c4aee4617 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -225,6 +225,22 @@ dependencies = [ "libc", ] +[[package]] +name = "annotate-snippets" +version = "0.11.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "710e8eae58854cdc1790fcb56cca04d712a17be849eeb81da2a724bf4bae2bc4" +dependencies = [ + "anstyle", + "unicode-width", +] + +[[package]] +name = "anstyle" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" + [[package]] name = "anyhow" version = "1.0.104" @@ -256,7 +272,7 @@ dependencies = [ "objc2-foundation 0.3.2", "parking_lot", "percent-encoding", - "windows-sys 0.61.2", + "windows-sys 0.52.0", "wl-clipboard-rs", "x11rb", ] @@ -342,7 +358,7 @@ dependencies = [ "futures-lite", "parking", "polling", - "rustix 1.1.5", + "rustix 1.1.6", "slab", "windows-sys 0.61.2", ] @@ -373,7 +389,7 @@ dependencies = [ "cfg-if", "event-listener", "futures-lite", - "rustix 1.1.5", + "rustix 1.1.6", ] [[package]] @@ -399,7 +415,7 @@ dependencies = [ "cfg-if", "futures-core", "futures-io", - "rustix 1.1.5", + "rustix 1.1.6", "signal-hook-registry", "slab", "windows-sys 0.61.2", @@ -513,6 +529,25 @@ version = "1.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" +[[package]] +name = "bindgen" +version = "0.72.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "993776b509cfb49c750f11b8f07a46fa23e0a1386ffc01fb1e7d343efc387895" +dependencies = [ + "annotate-snippets", + "bitflags 2.13.2", + "cexpr", + "clang-sys", + "itertools 0.13.0", + "proc-macro2", + "quote", + "regex", + "rustc-hash 2.1.3", + "shlex 1.3.0", + "syn 2.0.119", +] + [[package]] name = "bit-set" version = "0.8.0" @@ -580,6 +615,12 @@ version = "2.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" +[[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" @@ -722,6 +763,16 @@ version = "1.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" +[[package]] +name = "calendrical_calculations" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5abbd6eeda6885048d357edc66748eea6e0268e3dd11f326fff5bd248d779c26" +dependencies = [ + "core_maths", + "displaydoc", +] + [[package]] name = "calloop" version = "0.13.0" @@ -744,7 +795,7 @@ checksum = "43b32313e937c8721c9d17ee9bf60699a6402b4b7c2cb6ac1bee0ffcaa4b4e5e" dependencies = [ "bitflags 2.13.2", "polling", - "rustix 1.1.5", + "rustix 1.1.6", "tracing", ] @@ -767,7 +818,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "138efcf0940a02ebf0cc8d1eff41a1682a46b431630f4c52450d6265876021fa" dependencies = [ "calloop 0.14.5", - "rustix 1.1.5", + "rustix 1.1.6", "wayland-backend", "wayland-client", ] @@ -796,7 +847,26 @@ dependencies = [ "find-msvc-tools", "jobserver", "libc", - "shlex", + "shlex 2.0.1", +] + +[[package]] +name = "cexpr" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6fac387a98bb7c37292057cffc56d62ecb629900026402633ae9160df93a8766" +dependencies = [ + "nom 7.1.3", +] + +[[package]] +name = "cfg-expr" +version = "0.20.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "edd44d82755fb9210fb10d9daf8dd7e522da0efe1d5f263cffc5db07725663ff" +dependencies = [ + "smallvec", + "target-lexicon", ] [[package]] @@ -855,6 +925,17 @@ dependencies = [ "inout", ] +[[package]] +name = "clang-sys" +version = "1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "157a8ba7b480713b56f4c09fd13fc3e0a22a5dfab8097ba61cbc5feef950788a" +dependencies = [ + "glob", + "libc", + "libloading", +] + [[package]] name = "clipboard-win" version = "5.4.3" @@ -979,6 +1060,12 @@ version = "0.10.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "be95d4a884358a21a199689323c29e9256b4a1b315e22f183d155422041d3a9a" +[[package]] +name = "cookie-factory" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9885fa71e26b8ab7855e2ec7cae6e9b380edff76cd052e07c683a0319d51b3a2" + [[package]] name = "core-foundation" version = "0.9.4" @@ -1029,6 +1116,19 @@ 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-text" version = "20.1.0" @@ -1080,23 +1180,60 @@ dependencies = [ "libc", ] +[[package]] +name = "craft-appkit" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=0be123b5f29cd203a2beba10277c8c539ce528b4#0be123b5f29cd203a2beba10277c8c539ce528b4" +dependencies = [ + "block2 0.6.2", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "objc2-foundation 0.3.2", +] + [[package]] name = "craft-atomic" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" +source = "git+https://github.com/storytold/craft-libs?rev=0be123b5f29cd203a2beba10277c8c539ce528b4#0be123b5f29cd203a2beba10277c8c539ce528b4" dependencies = [ - "rustix 1.1.5", + "rustix 1.1.6", +] + +[[package]] +name = "craft-behavior" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=0be123b5f29cd203a2beba10277c8c539ce528b4#0be123b5f29cd203a2beba10277c8c539ce528b4" +dependencies = [ + "accesskit", + "bitflags 2.13.2", + "craft-host", + "craft-keymap", + "craft-theme", + "craft-tracked", + "craft-ui-macros", + "emath", + "kurbo", + "serde", + "smallvec", ] [[package]] name = "craft-cfb" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" +source = "git+https://github.com/storytold/craft-libs?rev=0be123b5f29cd203a2beba10277c8c539ce528b4#0be123b5f29cd203a2beba10277c8c539ce528b4" + +[[package]] +name = "craft-cloud-ui" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=0be123b5f29cd203a2beba10277c8c539ce528b4#0be123b5f29cd203a2beba10277c8c539ce528b4" +dependencies = [ + "egui", +] [[package]] name = "craft-cms" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" +source = "git+https://github.com/storytold/craft-libs?rev=0be123b5f29cd203a2beba10277c8c539ce528b4#0be123b5f29cd203a2beba10277c8c539ce528b4" dependencies = [ "md-5", "rayon", @@ -1105,12 +1242,32 @@ dependencies = [ [[package]] name = "craft-codepage" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" +source = "git+https://github.com/storytold/craft-libs?rev=0be123b5f29cd203a2beba10277c8c539ce528b4#0be123b5f29cd203a2beba10277c8c539ce528b4" + +[[package]] +name = "craft-color-ui" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=0be123b5f29cd203a2beba10277c8c539ce528b4#0be123b5f29cd203a2beba10277c8c539ce528b4" +dependencies = [ + "craft-behavior", + "craft-cms", + "craft-host", + "craft-i18n", + "craft-keymap", + "craft-platform", + "craft-settings", + "craft-theme", + "craft-ui", + "craft-window", + "egui", + "serde", + "serde_json", +] [[package]] name = "craft-csv" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" +source = "git+https://github.com/storytold/craft-libs?rev=0be123b5f29cd203a2beba10277c8c539ce528b4#0be123b5f29cd203a2beba10277c8c539ce528b4" dependencies = [ "thiserror 2.0.21", ] @@ -1118,7 +1275,7 @@ dependencies = [ [[package]] name = "craft-dds" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" +source = "git+https://github.com/storytold/craft-libs?rev=0be123b5f29cd203a2beba10277c8c539ce528b4#0be123b5f29cd203a2beba10277c8c539ce528b4" dependencies = [ "rayon", ] @@ -1126,7 +1283,7 @@ dependencies = [ [[package]] name = "craft-designcraft-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" +source = "git+https://github.com/storytold/craft-libs?rev=0be123b5f29cd203a2beba10277c8c539ce528b4#0be123b5f29cd203a2beba10277c8c539ce528b4" dependencies = [ "craft-document-bundle", "craft-eps", @@ -1138,25 +1295,36 @@ dependencies = [ [[package]] name = "craft-dialogs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" +source = "git+https://github.com/storytold/craft-libs?rev=0be123b5f29cd203a2beba10277c8c539ce528b4#0be123b5f29cd203a2beba10277c8c539ce528b4" dependencies = [ "block2 0.6.2", + "craft-appkit", + "craft-atomic", + "craft-host", + "craft-i18n", + "craft-platform", + "futures-lite", + "log", "objc2 0.6.5", "objc2-app-kit 0.3.2", "objc2-foundation 0.3.2", "raw-window-handle", "rfd", + "zbus", ] [[package]] name = "craft-docpath" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" +source = "git+https://github.com/storytold/craft-libs?rev=0be123b5f29cd203a2beba10277c8c539ce528b4#0be123b5f29cd203a2beba10277c8c539ce528b4" +dependencies = [ + "serde", +] [[package]] name = "craft-document-bundle" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" +source = "git+https://github.com/storytold/craft-libs?rev=0be123b5f29cd203a2beba10277c8c539ce528b4#0be123b5f29cd203a2beba10277c8c539ce528b4" dependencies = [ "craft-zip", "serde_json", @@ -1167,7 +1335,7 @@ dependencies = [ [[package]] name = "craft-docx" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" +source = "git+https://github.com/storytold/craft-libs?rev=0be123b5f29cd203a2beba10277c8c539ce528b4#0be123b5f29cd203a2beba10277c8c539ce528b4" dependencies = [ "base64 0.23.1", "chrono", @@ -1187,7 +1355,7 @@ dependencies = [ [[package]] name = "craft-drawingml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" +source = "git+https://github.com/storytold/craft-libs?rev=0be123b5f29cd203a2beba10277c8c539ce528b4#0be123b5f29cd203a2beba10277c8c539ce528b4" dependencies = [ "chrono", "craft-xml", @@ -1199,12 +1367,12 @@ dependencies = [ [[package]] name = "craft-eps" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" +source = "git+https://github.com/storytold/craft-libs?rev=0be123b5f29cd203a2beba10277c8c539ce528b4#0be123b5f29cd203a2beba10277c8c539ce528b4" [[package]] name = "craft-epub" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" +source = "git+https://github.com/storytold/craft-libs?rev=0be123b5f29cd203a2beba10277c8c539ce528b4#0be123b5f29cd203a2beba10277c8c539ce528b4" dependencies = [ "craft-xml", "craft-zip", @@ -1214,7 +1382,7 @@ dependencies = [ [[package]] name = "craft-file-formats" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" +source = "git+https://github.com/storytold/craft-libs?rev=0be123b5f29cd203a2beba10277c8c539ce528b4#0be123b5f29cd203a2beba10277c8c539ce528b4" dependencies = [ "craft-eps", "craft-idml", @@ -1224,17 +1392,48 @@ dependencies = [ "serde_json", ] +[[package]] +name = "craft-font-catalog" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=0be123b5f29cd203a2beba10277c8c539ce528b4#0be123b5f29cd203a2beba10277c8c539ce528b4" +dependencies = [ + "harfrust 0.13.3", + "kurbo", + "skrifa 0.47.0", + "thiserror 2.0.21", + "unicode-bidi", + "unicode-segmentation", + "windows-registry", +] + [[package]] name = "craft-fonts-build" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" +source = "git+https://github.com/storytold/craft-libs?rev=0be123b5f29cd203a2beba10277c8c539ce528b4#0be123b5f29cd203a2beba10277c8c539ce528b4" + +[[package]] +name = "craft-host" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=0be123b5f29cd203a2beba10277c8c539ce528b4#0be123b5f29cd203a2beba10277c8c539ce528b4" +dependencies = [ + "bitflags 2.13.2", + "craft-i18n", + "egui", + "serde", + "toml", + "web-time", +] [[package]] name = "craft-i18n" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" +source = "git+https://github.com/storytold/craft-libs?rev=0be123b5f29cd203a2beba10277c8c539ce528b4#0be123b5f29cd203a2beba10277c8c539ce528b4" dependencies = [ + "chrono", "fixed_decimal", + "icu_calendar", + "icu_collator", + "icu_datetime", "icu_decimal", "icu_locale_core", "icu_locale_fallback", @@ -1244,6 +1443,7 @@ dependencies = [ "icu_provider", "icu_provider_adapters", "icu_provider_blob", + "icu_time", "log", "objc2-foundation 0.3.2", "sys-locale", @@ -1255,7 +1455,7 @@ dependencies = [ [[package]] name = "craft-idml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" +source = "git+https://github.com/storytold/craft-libs?rev=0be123b5f29cd203a2beba10277c8c539ce528b4#0be123b5f29cd203a2beba10277c8c539ce528b4" dependencies = [ "craft-xml", "craft-zip", @@ -1265,7 +1465,7 @@ dependencies = [ [[package]] name = "craft-image-codecs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" +source = "git+https://github.com/storytold/craft-libs?rev=0be123b5f29cd203a2beba10277c8c539ce528b4#0be123b5f29cd203a2beba10277c8c539ce528b4" dependencies = [ "craft-dds", "craft-jpeg", @@ -1292,7 +1492,7 @@ dependencies = [ [[package]] name = "craft-indd" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" +source = "git+https://github.com/storytold/craft-libs?rev=0be123b5f29cd203a2beba10277c8c539ce528b4#0be123b5f29cd203a2beba10277c8c539ce528b4" dependencies = [ "indd", ] @@ -1300,7 +1500,7 @@ dependencies = [ [[package]] name = "craft-jpeg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" +source = "git+https://github.com/storytold/craft-libs?rev=0be123b5f29cd203a2beba10277c8c539ce528b4#0be123b5f29cd203a2beba10277c8c539ce528b4" dependencies = [ "thiserror 2.0.21", ] @@ -1308,10 +1508,13 @@ dependencies = [ [[package]] name = "craft-keymap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" +source = "git+https://github.com/storytold/craft-libs?rev=0be123b5f29cd203a2beba10277c8c539ce528b4#0be123b5f29cd203a2beba10277c8c539ce528b4" dependencies = [ + "craft-host", "craft-i18n", - "craft-ui", + "craft-tracked", + "craft-ui-macros", + "craft-xml", "egui", "serde", "serde_json", @@ -1320,7 +1523,7 @@ dependencies = [ [[package]] name = "craft-math" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" +source = "git+https://github.com/storytold/craft-libs?rev=0be123b5f29cd203a2beba10277c8c539ce528b4#0be123b5f29cd203a2beba10277c8c539ce528b4" dependencies = [ "craft-xml", "roxmltree 0.21.2", @@ -1330,15 +1533,33 @@ dependencies = [ [[package]] name = "craft-mcp-server" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" +source = "git+https://github.com/storytold/craft-libs?rev=0be123b5f29cd203a2beba10277c8c539ce528b4#0be123b5f29cd203a2beba10277c8c539ce528b4" dependencies = [ "serde_json", ] +[[package]] +name = "craft-menu" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=0be123b5f29cd203a2beba10277c8c539ce528b4#0be123b5f29cd203a2beba10277c8c539ce528b4" +dependencies = [ + "craft-behavior", + "craft-host", + "craft-i18n", + "craft-keymap", + "craft-quit", + "craft-theme", + "craft-ui", + "craft-window", + "egui", + "serde", + "serde_json", +] + [[package]] name = "craft-metadata" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" +source = "git+https://github.com/storytold/craft-libs?rev=0be123b5f29cd203a2beba10277c8c539ce528b4#0be123b5f29cd203a2beba10277c8c539ce528b4" dependencies = [ "brotli-decompressor 6.3.1", "chrono", @@ -1350,17 +1571,26 @@ dependencies = [ [[package]] name = "craft-mime" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" +source = "git+https://github.com/storytold/craft-libs?rev=0be123b5f29cd203a2beba10277c8c539ce528b4#0be123b5f29cd203a2beba10277c8c539ce528b4" dependencies = [ "chrono", "craft-codepage", "encoding_rs", ] +[[package]] +name = "craft-nightly" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=0be123b5f29cd203a2beba10277c8c539ce528b4#0be123b5f29cd203a2beba10277c8c539ce528b4" +dependencies = [ + "uds_windows", + "winsafe", +] + [[package]] name = "craft-offcrypto" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" +source = "git+https://github.com/storytold/craft-libs?rev=0be123b5f29cd203a2beba10277c8c539ce528b4#0be123b5f29cd203a2beba10277c8c539ce528b4" dependencies = [ "aes", "base64 0.23.1", @@ -1377,7 +1607,7 @@ dependencies = [ [[package]] name = "craft-opc" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" +source = "git+https://github.com/storytold/craft-libs?rev=0be123b5f29cd203a2beba10277c8c539ce528b4#0be123b5f29cd203a2beba10277c8c539ce528b4" dependencies = [ "craft-xml", "craft-zip", @@ -1388,7 +1618,7 @@ dependencies = [ [[package]] name = "craft-pdf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" +source = "git+https://github.com/storytold/craft-libs?rev=0be123b5f29cd203a2beba10277c8c539ce528b4#0be123b5f29cd203a2beba10277c8c539ce528b4" dependencies = [ "bytemuck", "craft-svg", @@ -1397,14 +1627,46 @@ dependencies = [ "hayro-syntax", "krilla", "krilla-svg", + "serde", "thiserror 2.0.21", "usvg 0.47.0", ] +[[package]] +name = "craft-platform" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=0be123b5f29cd203a2beba10277c8c539ce528b4#0be123b5f29cd203a2beba10277c8c539ce528b4" +dependencies = [ + "async-channel", + "async-io", + "async-process", + "core-graphics2", + "craft-atomic", + "craft-docpath", + "craft-host", + "craft-i18n", + "craft-theme", + "futures-lite", + "js-sys", + "log", + "objc2-app-kit 0.3.2", + "rfd", + "serde", + "serde_json", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", + "web-time", + "windows", + "x11rb", + "xcap", + "zbus", +] + [[package]] name = "craft-pptx" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" +source = "git+https://github.com/storytold/craft-libs?rev=0be123b5f29cd203a2beba10277c8c539ce528b4#0be123b5f29cd203a2beba10277c8c539ce528b4" dependencies = [ "craft-drawingml", "craft-opc", @@ -1419,7 +1681,7 @@ dependencies = [ [[package]] name = "craft-prepress" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" +source = "git+https://github.com/storytold/craft-libs?rev=0be123b5f29cd203a2beba10277c8c539ce528b4#0be123b5f29cd203a2beba10277c8c539ce528b4" dependencies = [ "craft-cms", "craft-pdf", @@ -1432,13 +1694,19 @@ dependencies = [ [[package]] name = "craft-print" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" +source = "git+https://github.com/storytold/craft-libs?rev=0be123b5f29cd203a2beba10277c8c539ce528b4#0be123b5f29cd203a2beba10277c8c539ce528b4" dependencies = [ + "craft-host", "craft-winprint-gdi", + "js-sys", "log", "miniz_oxide 0.9.1", "roxmltree 0.21.2", + "serde", + "serde_json", "tempfile", + "wasm-bindgen", + "web-sys", "winprint", "winsafe", ] @@ -1446,7 +1714,7 @@ dependencies = [ [[package]] name = "craft-ps" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" +source = "git+https://github.com/storytold/craft-libs?rev=0be123b5f29cd203a2beba10277c8c539ce528b4#0be123b5f29cd203a2beba10277c8c539ce528b4" dependencies = [ "craft-eps", "kurbo", @@ -1459,7 +1727,7 @@ dependencies = [ [[package]] name = "craft-psd" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" +source = "git+https://github.com/storytold/craft-libs?rev=0be123b5f29cd203a2beba10277c8c539ce528b4#0be123b5f29cd203a2beba10277c8c539ce528b4" dependencies = [ "encoding_rs", "flate2", @@ -1467,24 +1735,54 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-quit" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=0be123b5f29cd203a2beba10277c8c539ce528b4#0be123b5f29cd203a2beba10277c8c539ce528b4" +dependencies = [ + "dispatch2", + "egui", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "wasm-bindgen", + "web-sys", +] + [[package]] name = "craft-rtf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" +source = "git+https://github.com/storytold/craft-libs?rev=0be123b5f29cd203a2beba10277c8c539ce528b4#0be123b5f29cd203a2beba10277c8c539ce528b4" dependencies = [ "craft-codepage", "encoding_rs", ] +[[package]] +name = "craft-settings" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=0be123b5f29cd203a2beba10277c8c539ce528b4#0be123b5f29cd203a2beba10277c8c539ce528b4" +dependencies = [ + "craft-atomic", + "craft-host", + "dirs", + "log", + "serde", + "serde_json", + "toml", + "toml_edit", + "web-sys", + "web-time", +] + [[package]] name = "craft-sheet" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" +source = "git+https://github.com/storytold/craft-libs?rev=0be123b5f29cd203a2beba10277c8c539ce528b4#0be123b5f29cd203a2beba10277c8c539ce528b4" [[package]] name = "craft-svg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" +source = "git+https://github.com/storytold/craft-libs?rev=0be123b5f29cd203a2beba10277c8c539ce528b4#0be123b5f29cd203a2beba10277c8c539ce528b4" dependencies = [ "craft-image-codecs", "craft-xml", @@ -1502,57 +1800,218 @@ dependencies = [ "vectorcraft-pathops", ] +[[package]] +name = "craft-theme" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=0be123b5f29cd203a2beba10277c8c539ce528b4#0be123b5f29cd203a2beba10277c8c539ce528b4" +dependencies = [ + "bitflags 2.13.2", + "craft-tracked", + "craft-ui-macros", + "ecolor", + "log", + "serde", + "serde_json", + "smallvec", +] + [[package]] name = "craft-tiff" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" +source = "git+https://github.com/storytold/craft-libs?rev=0be123b5f29cd203a2beba10277c8c539ce528b4#0be123b5f29cd203a2beba10277c8c539ce528b4" dependencies = [ "serde", "thiserror 2.0.21", "tiff", ] +[[package]] +name = "craft-tracked" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=0be123b5f29cd203a2beba10277c8c539ce528b4#0be123b5f29cd203a2beba10277c8c539ce528b4" + [[package]] name = "craft-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" +source = "git+https://github.com/storytold/craft-libs?rev=0be123b5f29cd203a2beba10277c8c539ce528b4#0be123b5f29cd203a2beba10277c8c539ce528b4" dependencies = [ - "craft-fonts-build", + "craft-cloud-ui", + "craft-ui-canvas", + "craft-ui-contract", + "craft-ui-panels", + "craft-ui-patterns", + "craft-ui-shell", + "craft-ui-widgets", +] + +[[package]] +name = "craft-ui-canvas" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=0be123b5f29cd203a2beba10277c8c539ce528b4#0be123b5f29cd203a2beba10277c8c539ce528b4" +dependencies = [ + "craft-behavior", "craft-i18n", + "craft-keymap", + "craft-theme", + "craft-ui-macros", + "craft-ui-panels", "egui", - "epaint", - "js-sys", - "log", - "objc2 0.6.5", - "objc2-app-kit 0.3.2", - "objc2-foundation 0.3.2", "serde", + "serde_json", +] + +[[package]] +name = "craft-ui-contract" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=0be123b5f29cd203a2beba10277c8c539ce528b4#0be123b5f29cd203a2beba10277c8c539ce528b4" +dependencies = [ + "accesskit", + "craft-behavior", + "craft-codepage", + "craft-font-catalog", + "craft-fonts-build", + "craft-host", + "craft-i18n", + "craft-keymap", + "craft-platform", + "craft-quit", + "craft-settings", + "craft-svg", + "craft-theme", + "craft-tracked", + "craft-ui-macros", + "craft-window", + "egui", + "epaint_default_fonts", + "flate2", + "inventory", + "log", + "scoped-tls", + "serde", + "serde_json", + "siphasher", "skrifa 0.44.0", - "wasm-bindgen", + "smallvec", + "toml", + "typeid", "wasm-bindgen-futures", - "web-sys", + "web-time", +] + +[[package]] +name = "craft-ui-macros" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=0be123b5f29cd203a2beba10277c8c539ce528b4#0be123b5f29cd203a2beba10277c8c539ce528b4" +dependencies = [ + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "craft-ui-panels" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=0be123b5f29cd203a2beba10277c8c539ce528b4#0be123b5f29cd203a2beba10277c8c539ce528b4" +dependencies = [ + "craft-behavior", + "craft-host", + "craft-i18n", + "craft-keymap", + "craft-quit", + "craft-theme", + "craft-ui-macros", + "craft-ui-widgets", + "egui", + "serde", + "serde_json", +] + +[[package]] +name = "craft-ui-patterns" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=0be123b5f29cd203a2beba10277c8c539ce528b4#0be123b5f29cd203a2beba10277c8c539ce528b4" +dependencies = [ + "craft-behavior", + "craft-host", + "craft-i18n", + "craft-keymap", + "craft-pdf", + "craft-theme", + "craft-ui-macros", + "craft-ui-panels", + "egui", + "serde", + "serde_json", + "toml", + "toml_edit", + "zeroize", +] + +[[package]] +name = "craft-ui-shell" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=0be123b5f29cd203a2beba10277c8c539ce528b4#0be123b5f29cd203a2beba10277c8c539ce528b4" +dependencies = [ + "craft-behavior", + "craft-host", + "craft-i18n", + "craft-platform", + "craft-svg", + "craft-theme", + "craft-ui-macros", + "craft-ui-panels", + "craft-window", + "egui", + "raw-window-handle", + "serde", + "web-time", +] + +[[package]] +name = "craft-ui-widgets" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=0be123b5f29cd203a2beba10277c8c539ce528b4#0be123b5f29cd203a2beba10277c8c539ce528b4" +dependencies = [ + "craft-behavior", + "craft-host", + "craft-i18n", + "craft-keymap", + "craft-svg", + "craft-theme", + "craft-ui-contract", + "craft-ui-macros", + "egui", + "log", + "serde", + "smallvec", ] [[package]] name = "craft-update" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" +source = "git+https://github.com/storytold/craft-libs?rev=0be123b5f29cd203a2beba10277c8c539ce528b4#0be123b5f29cd203a2beba10277c8c539ce528b4" dependencies = [ + "base64 0.22.1", "chrono", + "craft-host", + "craft-theme", + "craft-ui", "dunce", + "ed25519-dalek", "egui", "flate2", - "getrandom 0.3.4", "image", "log", "plist", - "rustix 1.1.5", + "rustix 1.1.6", "semver", "serde", "serde_json", "sha2 0.10.9", "tar", "tempfile", + "toml", "ureq", "verifysign", "winreg", @@ -1560,15 +2019,36 @@ dependencies = [ "zip 9.1.1", ] +[[package]] +name = "craft-win32" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=0be123b5f29cd203a2beba10277c8c539ce528b4#0be123b5f29cd203a2beba10277c8c539ce528b4" +dependencies = [ + "winsafe", +] + [[package]] name = "craft-window" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" +source = "git+https://github.com/storytold/craft-libs?rev=0be123b5f29cd203a2beba10277c8c539ce528b4#0be123b5f29cd203a2beba10277c8c539ce528b4" dependencies = [ + "craft-appkit", + "craft-atomic", + "craft-behavior", + "craft-host", + "craft-settings", + "craft-win32", "egui", + "muda", "objc2 0.6.5", "objc2-app-kit 0.3.2", + "objc2-foundation 0.3.2", + "raw-window-handle", + "serde", + "serde_json", "wayland-client", + "winsafe", + "x11rb", ] [[package]] @@ -1582,7 +2062,7 @@ dependencies = [ [[package]] name = "craft-wordmodel" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" +source = "git+https://github.com/storytold/craft-libs?rev=0be123b5f29cd203a2beba10277c8c539ce528b4#0be123b5f29cd203a2beba10277c8c539ce528b4" dependencies = [ "base64 0.23.1", "craft-math", @@ -1596,7 +2076,7 @@ dependencies = [ [[package]] name = "craft-xlsx" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" +source = "git+https://github.com/storytold/craft-libs?rev=0be123b5f29cd203a2beba10277c8c539ce528b4#0be123b5f29cd203a2beba10277c8c539ce528b4" dependencies = [ "craft-drawingml", "craft-opc", @@ -1608,7 +2088,7 @@ dependencies = [ [[package]] name = "craft-xml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" +source = "git+https://github.com/storytold/craft-libs?rev=0be123b5f29cd203a2beba10277c8c539ce528b4#0be123b5f29cd203a2beba10277c8c539ce528b4" dependencies = [ "quick-xml 0.41.0", "serde", @@ -1618,7 +2098,7 @@ dependencies = [ [[package]] name = "craft-zip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" +source = "git+https://github.com/storytold/craft-libs?rev=0be123b5f29cd203a2beba10277c8c539ce528b4#0be123b5f29cd203a2beba10277c8c539ce528b4" dependencies = [ "flate2", "thiserror 2.0.21", @@ -1720,6 +2200,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 0.10.7", + "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 = "data-url" version = "0.3.2" @@ -1769,11 +2276,11 @@ dependencies = [ [[package]] name = "designcraft" -version = "0.21.1" +version = "0.22.0" dependencies = [ "arboard", + "craft-nightly", "craft-update", - "craft-window", "designcraft-engine", "designcraft-ui-egui", "eframe", @@ -1795,7 +2302,7 @@ dependencies = [ [[package]] name = "designcraft-cli" -version = "0.21.1" +version = "0.22.0" dependencies = [ "craft-file-formats", "craft-image-codecs", @@ -1814,7 +2321,7 @@ dependencies = [ [[package]] name = "designcraft-color" -version = "0.21.1" +version = "0.22.0" dependencies = [ "craft-cms", "kurbo", @@ -1826,7 +2333,7 @@ dependencies = [ [[package]] name = "designcraft-compose" -version = "0.21.1" +version = "0.22.0" dependencies = [ "designcraft-color", "designcraft-doc", @@ -1846,7 +2353,7 @@ dependencies = [ [[package]] name = "designcraft-doc" -version = "0.21.1" +version = "0.22.0" dependencies = [ "chrono", "designcraft-color", @@ -1859,7 +2366,7 @@ dependencies = [ [[package]] name = "designcraft-engine" -version = "0.21.1" +version = "0.22.0" dependencies = [ "caseless", "craft-atomic", @@ -1904,7 +2411,7 @@ dependencies = [ [[package]] name = "designcraft-epub" -version = "0.21.1" +version = "0.22.0" dependencies = [ "craft-epub", "craft-mime", @@ -1915,7 +2422,7 @@ dependencies = [ [[package]] name = "designcraft-fonts" -version = "0.21.1" +version = "0.22.0" dependencies = [ "core-text", "harfrust 0.13.3", @@ -1928,7 +2435,7 @@ dependencies = [ [[package]] name = "designcraft-format" -version = "0.21.1" +version = "0.22.0" dependencies = [ "craft-designcraft-format", "designcraft-doc", @@ -1938,7 +2445,7 @@ dependencies = [ [[package]] name = "designcraft-geom" -version = "0.21.1" +version = "0.22.0" dependencies = [ "flo_curves", "kurbo", @@ -1951,7 +2458,7 @@ dependencies = [ [[package]] name = "designcraft-idml" -version = "0.21.1" +version = "0.22.0" dependencies = [ "craft-file-formats", "craft-idml", @@ -1968,7 +2475,7 @@ dependencies = [ [[package]] name = "designcraft-images" -version = "0.21.1" +version = "0.22.0" dependencies = [ "craft-cms", "craft-eps", @@ -1990,7 +2497,7 @@ dependencies = [ [[package]] name = "designcraft-mcp" -version = "0.21.1" +version = "0.22.0" dependencies = [ "craft-file-formats", "craft-mcp-server", @@ -2005,7 +2512,7 @@ dependencies = [ [[package]] name = "designcraft-pdf" -version = "0.21.1" +version = "0.22.0" dependencies = [ "chrono", "craft-cms", @@ -2031,7 +2538,7 @@ dependencies = [ [[package]] name = "designcraft-pptx" -version = "0.21.1" +version = "0.22.0" dependencies = [ "chrono", "craft-image-codecs", @@ -2052,7 +2559,7 @@ dependencies = [ [[package]] name = "designcraft-render" -version = "0.21.1" +version = "0.22.0" dependencies = [ "bytemuck", "craft-image-codecs", @@ -2073,7 +2580,7 @@ dependencies = [ [[package]] name = "designcraft-textimport" -version = "0.21.1" +version = "0.22.0" dependencies = [ "craft-docx", "craft-file-formats", @@ -2087,7 +2594,7 @@ dependencies = [ [[package]] name = "designcraft-tools" -version = "0.21.1" +version = "0.22.0" dependencies = [ "designcraft-color", "designcraft-compose", @@ -2099,13 +2606,21 @@ dependencies = [ [[package]] name = "designcraft-ui-egui" -version = "0.21.1" +version = "0.22.0" dependencies = [ + "craft-behavior", + "craft-color-ui", "craft-dialogs", "craft-file-formats", + "craft-host", "craft-keymap", + "craft-menu", "craft-prepress", + "craft-theme", "craft-ui", + "craft-ui-panels", + "craft-ui-shell", + "craft-ui-widgets", "craft-update", "craft-window", "designcraft-color", @@ -2134,7 +2649,7 @@ dependencies = [ [[package]] name = "designcraft-web" -version = "0.21.1" +version = "0.22.0" dependencies = [ "designcraft-engine", "designcraft-format", @@ -2186,6 +2701,27 @@ dependencies = [ "ctutils", ] +[[package]] +name = "dirs" +version = "7.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8d57d423b3c82e89b9a24ca3091fee61f456a26edbd28d26c65906f4bc1dcd8f" +dependencies = [ + "dirs-sys", +] + +[[package]] +name = "dirs-sys" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e01a3366d27ee9890022452ee61b2b63a67e6f13f58900b651ff5665f0bb1fab" +dependencies = [ + "libc", + "option-ext", + "redox_users", + "windows-sys 0.59.0", +] + [[package]] name = "dispatch" version = "0.2.0" @@ -2245,6 +2781,61 @@ version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d8b14ccef22fc6f5a8f4d7d768562a182c04ce9a3b3157b91390b52ddfdf1a76" +[[package]] +name = "drm" +version = "0.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "80bc8c5c6c2941f70a55c15f8d9f00f9710ebda3ffda98075f996a0e6c92756f" +dependencies = [ + "bitflags 2.13.2", + "bytemuck", + "drm-ffi", + "drm-fourcc", + "libc", + "rustix 0.38.44", +] + +[[package]] +name = "drm" +version = "0.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a41816e58f47f49acfd956651055ddcf137c4882c2098c30c448817af21183a" +dependencies = [ + "bitflags 2.13.2", + "bytemuck", + "bytemuck_derive", + "drm-ffi", + "drm-fourcc", + "libc", + "rustix 1.1.6", +] + +[[package]] +name = "drm-ffi" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "51a91c9b32ac4e8105dec255e849e0d66e27d7c34d184364fb93e469db08f690" +dependencies = [ + "drm-sys", + "rustix 1.1.6", +] + +[[package]] +name = "drm-fourcc" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0aafbcdb8afc29c1a7ee5fbe53b5d62f4565b35a042a662ca9fecd0b54dae6f4" + +[[package]] +name = "drm-sys" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ecc8e1361066d91f5ffccff060a3c3be9c3ecde15be2959c1937595f7a82a9f8" +dependencies = [ + "libc", + "linux-raw-sys 0.9.4", +] + [[package]] name = "dunce" version = "1.0.5" @@ -2254,16 +2845,40 @@ checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" [[package]] name = "ecolor" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" +source = "git+https://github.com/storytold/egui.git?rev=14c39fed181756be6f357c284354e0ab55b64443#14c39fed181756be6f357c284354e0ab55b64443" 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 0.10.9", + "subtle", + "zeroize", +] + [[package]] name = "eframe" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" +source = "git+https://github.com/storytold/egui.git?rev=14c39fed181756be6f357c284354e0ab55b64443#14c39fed181756be6f357c284354e0ab55b64443" dependencies = [ "ahash", "bytemuck", @@ -2298,7 +2913,7 @@ dependencies = [ [[package]] name = "egui" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" +source = "git+https://github.com/storytold/egui.git?rev=14c39fed181756be6f357c284354e0ab55b64443#14c39fed181756be6f357c284354e0ab55b64443" dependencies = [ "accesskit", "ahash", @@ -2317,7 +2932,7 @@ dependencies = [ [[package]] name = "egui-wgpu" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" +source = "git+https://github.com/storytold/egui.git?rev=14c39fed181756be6f357c284354e0ab55b64443#14c39fed181756be6f357c284354e0ab55b64443" dependencies = [ "ahash", "bytemuck", @@ -2336,7 +2951,7 @@ dependencies = [ [[package]] name = "egui-winit" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" +source = "git+https://github.com/storytold/egui.git?rev=14c39fed181756be6f357c284354e0ab55b64443#14c39fed181756be6f357c284354e0ab55b64443" dependencies = [ "accesskit_winit", "arboard", @@ -2362,7 +2977,7 @@ dependencies = [ [[package]] name = "egui_extras" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" +source = "git+https://github.com/storytold/egui.git?rev=14c39fed181756be6f357c284354e0ab55b64443#14c39fed181756be6f357c284354e0ab55b64443" dependencies = [ "ahash", "egui", @@ -2375,7 +2990,7 @@ dependencies = [ [[package]] name = "egui_glow" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" +source = "git+https://github.com/storytold/egui.git?rev=14c39fed181756be6f357c284354e0ab55b64443#14c39fed181756be6f357c284354e0ab55b64443" dependencies = [ "bytemuck", "egui", @@ -2388,7 +3003,7 @@ dependencies = [ [[package]] name = "egui_kittest" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" +source = "git+https://github.com/storytold/egui.git?rev=14c39fed181756be6f357c284354e0ab55b64443#14c39fed181756be6f357c284354e0ab55b64443" dependencies = [ "dify", "eframe", @@ -2414,11 +3029,23 @@ checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" [[package]] name = "emath" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" +source = "git+https://github.com/storytold/egui.git?rev=14c39fed181756be6f357c284354e0ab55b64443#14c39fed181756be6f357c284354e0ab55b64443" dependencies = [ "bytemuck", ] +[[package]] +name = "embedded-io" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef1a6892d9eef45c8fa6b9e0086428a2cca8491aca8f787c534a3d6d0bcb3ced" + +[[package]] +name = "embedded-io" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "edd0f118536f44f5ccd48bcb8b111bdc3de888b58c74639dfb034a357d0f206d" + [[package]] name = "encoding_rs" version = "0.8.42" @@ -2483,7 +3110,7 @@ dependencies = [ [[package]] name = "epaint" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" +source = "git+https://github.com/storytold/egui.git?rev=14c39fed181756be6f357c284354e0ab55b64443#14c39fed181756be6f357c284354e0ab55b64443" dependencies = [ "ahash", "bytemuck", @@ -2509,7 +3136,7 @@ dependencies = [ [[package]] name = "epaint_default_fonts" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" +source = "git+https://github.com/storytold/egui.git?rev=14c39fed181756be6f357c284354e0ab55b64443#14c39fed181756be6f357c284354e0ab55b64443" [[package]] name = "equivalent" @@ -2524,7 +3151,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -2616,6 +3243,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" @@ -2906,6 +3539,30 @@ dependencies = [ "slab", ] +[[package]] +name = "gbm" +version = "0.18.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce852e998d3ca5e4a97014fb31c940dc5ef344ec7d364984525fd11e8a547e6a" +dependencies = [ + "bitflags 2.13.2", + "drm 0.14.1", + "drm-fourcc", + "gbm-sys", + "libc", + "wayland-backend", + "wayland-server", +] + +[[package]] +name = "gbm-sys" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c13a5f2acc785d8fb6bf6b7ab6bfb0ef5dad4f4d97e8e70bb8e470722312f76f" +dependencies = [ + "libc", +] + [[package]] name = "generic-array" version = "0.14.7" @@ -2922,7 +3579,7 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1bd49230192a3797a9a4d6abe9b3eed6f7fa4c8a8a4947977c6f80025f92cbd8" dependencies = [ - "rustix 1.1.5", + "rustix 1.1.6", "windows-link", ] @@ -2986,6 +3643,15 @@ dependencies = [ "weezl", ] +[[package]] +name = "gl" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a94edab108827d67608095e269cf862e60d920f144a5026d3dbcfd8b877fb404" +dependencies = [ + "gl_generator", +] + [[package]] name = "gl_generator" version = "0.14.0" @@ -3031,6 +3697,12 @@ dependencies = [ "vello_common 0.2.0", ] +[[package]] +name = "glob" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b" + [[package]] name = "glow" version = "0.17.0" @@ -3220,7 +3892,7 @@ dependencies = [ [[package]] name = "hayro" version = "0.7.1" -source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" +source = "git+https://github.com/storytold/craft-libs?rev=0be123b5f29cd203a2beba10277c8c539ce528b4#0be123b5f29cd203a2beba10277c8c539ce528b4" dependencies = [ "bytemuck", "hayro-interpret", @@ -3240,7 +3912,7 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a" [[package]] name = "hayro-cmap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" +source = "git+https://github.com/storytold/craft-libs?rev=0be123b5f29cd203a2beba10277c8c539ce528b4#0be123b5f29cd203a2beba10277c8c539ce528b4" dependencies = [ "brotli", "hayro-postscript", @@ -3249,7 +3921,7 @@ dependencies = [ [[package]] name = "hayro-interpret" version = "0.7.0" -source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" +source = "git+https://github.com/storytold/craft-libs?rev=0be123b5f29cd203a2beba10277c8c539ce528b4#0be123b5f29cd203a2beba10277c8c539ce528b4" dependencies = [ "bitflags 2.13.2", "hayro-cmap", @@ -3267,7 +3939,7 @@ dependencies = [ [[package]] name = "hayro-jbig2" version = "0.3.0" -source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" +source = "git+https://github.com/storytold/craft-libs?rev=0be123b5f29cd203a2beba10277c8c539ce528b4#0be123b5f29cd203a2beba10277c8c539ce528b4" dependencies = [ "fearless_simd", "hayro-ccitt", @@ -3285,12 +3957,12 @@ dependencies = [ [[package]] name = "hayro-postscript" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" +source = "git+https://github.com/storytold/craft-libs?rev=0be123b5f29cd203a2beba10277c8c539ce528b4#0be123b5f29cd203a2beba10277c8c539ce528b4" [[package]] name = "hayro-syntax" version = "0.7.2" -source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" +source = "git+https://github.com/storytold/craft-libs?rev=0be123b5f29cd203a2beba10277c8c539ce528b4#0be123b5f29cd203a2beba10277c8c539ce528b4" dependencies = [ "flate2", "hayro-ccitt", @@ -3487,6 +4159,39 @@ dependencies = [ "cc", ] +[[package]] +name = "icu_calendar" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "58655df2f728e46e4eee80bddebefacf52ec3e77cdb925014b47c5a5905eb55c" +dependencies = [ + "calendrical_calculations", + "displaydoc", + "icu_locale_core", + "icu_provider", + "serde", + "tinystr", + "zerovec", +] + +[[package]] +name = "icu_collator" +version = "2.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08984ed58ac439ebf3e13d2cf26b0c46a60afcd21721c1d14087c0b240344dda" +dependencies = [ + "icu_collections", + "icu_locale_core", + "icu_normalizer", + "icu_properties", + "icu_provider", + "serde", + "smallvec", + "utf16_iter", + "utf8_iter", + "zerovec", +] + [[package]] name = "icu_collections" version = "2.3.0" @@ -3495,12 +4200,37 @@ checksum = "fa68d21081c4a05d5a901a1c62add574c77048b6a1c67be3b50ce0b60d4ca513" dependencies = [ "displaydoc", "potential_utf", + "serde", "utf8_iter", "yoke", "zerofrom", "zerovec", ] +[[package]] +name = "icu_datetime" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c44df99c4c5297b05653d1a1629f13bdc9fd4044acfbbaf30b15194a1eed4cd6" +dependencies = [ + "displaydoc", + "fixed_decimal", + "icu_calendar", + "icu_decimal", + "icu_locale_core", + "icu_pattern", + "icu_plurals", + "icu_provider", + "icu_time", + "potential_utf", + "serde", + "smallvec", + "tinystr", + "writeable", + "zerotrie", + "zerovec", +] + [[package]] name = "icu_decimal" version = "2.3.0" @@ -3562,6 +4292,7 @@ dependencies = [ "icu_normalizer_data", "icu_properties", "icu_provider", + "serde", "smallvec", "utf16_iter", "utf8_iter", @@ -3612,6 +4343,7 @@ dependencies = [ "icu_locale_core", "icu_properties_data", "icu_provider", + "serde", "zerotrie", "zerovec", ] @@ -3664,6 +4396,22 @@ dependencies = [ "zerovec", ] +[[package]] +name = "icu_time" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af37e1c3b9f3ab564b619fdf4b22de169f6381eb0f7048e3ca454290c438126b" +dependencies = [ + "calendrical_calculations", + "displaydoc", + "icu_calendar", + "icu_locale_core", + "icu_provider", + "serde", + "zerotrie", + "zerovec", +] + [[package]] name = "idna" version = "1.1.0" @@ -3751,6 +4499,15 @@ dependencies = [ "hybrid-array", ] +[[package]] +name = "inventory" +version = "0.3.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6928282826c822ad91bf1c9a1cb90a30ba1c26770749929b4656cd6be829cd7c" +dependencies = [ + "rustversion", +] + [[package]] name = "ipnet" version = "2.12.2" @@ -3776,6 +4533,15 @@ dependencies = [ "once_cell", ] +[[package]] +name = "itertools" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186" +dependencies = [ + "either", +] + [[package]] name = "itertools" version = "0.14.0" @@ -3870,9 +4636,9 @@ dependencies = [ [[package]] name = "jpeg-encoder" -version = "0.6.1" +version = "0.7.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b454d911ac55068f53495488d8ccd0646eaa540c033a28ee15b07838afafb01f" +checksum = "a0370574b86f7eca156b9f298392b5e69a23f8c86f3f865add60bbc2e79467a6" [[package]] name = "js-sys" @@ -3925,7 +4691,7 @@ dependencies = [ [[package]] name = "krilla" version = "0.8.2" -source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" +source = "git+https://github.com/storytold/craft-libs?rev=0be123b5f29cd203a2beba10277c8c539ce528b4#0be123b5f29cd203a2beba10277c8c539ce528b4" dependencies = [ "base64 0.22.1", "bumpalo", @@ -4025,6 +4791,54 @@ dependencies = [ "redox_syscall 0.9.5", ] +[[package]] +name = "libspa" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "882f7427e7989dcc9d388b7f05c4630390a1d7696f9ffa469cd4a7a48f0b4c40" +dependencies = [ + "bitflags 2.13.2", + "cc", + "cookie-factory", + "libc", + "libspa-sys", + "nom 8.0.0", + "rustix 1.1.6", + "system-deps", +] + +[[package]] +name = "libspa-sys" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b6e17bdaf63ed0d5e4144022624032b41fd9733112e8c74ac26fc9bf1291924" +dependencies = [ + "bindgen", + "cc", + "system-deps", +] + +[[package]] +name = "libwayshot-xcap" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea8a46e4d016ef464e386e4970f5415fe0939c2d63abe0c2f539c05ef88c5fe5" +dependencies = [ + "drm 0.15.0", + "gbm", + "gl", + "image", + "khronos-egl", + "memmap2", + "rustix 1.1.6", + "thiserror 2.0.21", + "tracing", + "wayland-backend", + "wayland-client", + "wayland-protocols", + "wayland-protocols-wlr", +] + [[package]] name = "linebender_resource_handle" version = "0.1.1" @@ -4034,7 +4848,7 @@ checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4" [[package]] name = "linesweeper" version = "0.5.0" -source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" +source = "git+https://github.com/storytold/craft-libs?rev=0be123b5f29cd203a2beba10277c8c539ce528b4#0be123b5f29cd203a2beba10277c8c539ce528b4" dependencies = [ "arrayvec", "kurbo", @@ -4049,6 +4863,12 @@ version = "0.4.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab" +[[package]] +name = "linux-raw-sys" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd945864f07fe9f5371a27ad7b52a172b4b499999f1d97574c9fa68373937e12" + [[package]] name = "linux-raw-sys" version = "0.12.1" @@ -4141,6 +4961,12 @@ dependencies = [ "walkdir", ] +[[package]] +name = "minimal-lexical" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" + [[package]] name = "miniz_oxide" version = "0.8.9" @@ -4314,6 +5140,16 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2bf50223579dc7cdcfb3bfcacf7069ff68243f8c363f62ffa99cf000a6b9c451" +[[package]] +name = "nom" +version = "7.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a" +dependencies = [ + "memchr", + "minimal-lexical", +] + [[package]] name = "nom" version = "8.0.0" @@ -4329,7 +5165,7 @@ version = "0.50.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" dependencies = [ - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -4405,8 +5241,8 @@ dependencies = [ "block2 0.5.1", "libc", "objc2 0.5.3", - "objc2-core-data", - "objc2-core-image", + "objc2-core-data 0.2.2", + "objc2-core-image 0.2.2", "objc2-foundation 0.2.2", "objc2-quartz-core 0.2.2", ] @@ -4419,9 +5255,48 @@ checksum = "d49e936b501e5c5bf01fda3a9452ff86dc3ea98ad5f283e1455153142d97518c" dependencies = [ "bitflags 2.13.2", "block2 0.6.2", + "libc", "objc2 0.6.5", + "objc2-cloud-kit 0.3.2", + "objc2-core-data 0.3.2", "objc2-core-foundation", "objc2-core-graphics", + "objc2-core-image 0.3.2", + "objc2-core-text", + "objc2-core-video", + "objc2-foundation 0.3.2", + "objc2-quartz-core 0.3.2", +] + +[[package]] +name = "objc2-av-foundation" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "478ae33fcac9df0a18db8302387c666b8ef08a3e2d62b510ca4fc278a384b6c0" +dependencies = [ + "bitflags 2.13.2", + "block2 0.6.2", + "dispatch2", + "objc2 0.6.5", + "objc2-avf-audio", + "objc2-core-audio-types", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-core-image 0.3.2", + "objc2-core-video", + "objc2-foundation 0.3.2", + "objc2-image-io", + "objc2-media-toolbox", + "objc2-quartz-core 0.3.2", +] + +[[package]] +name = "objc2-avf-audio" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13a380031deed8e99db00065c45937da434ca987c034e13b87e4441f9e4090be" +dependencies = [ + "objc2 0.6.5", "objc2-foundation 0.3.2", ] @@ -4438,6 +5313,17 @@ dependencies = [ "objc2-foundation 0.2.2", ] +[[package]] +name = "objc2-cloud-kit" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73ad74d880bb43877038da939b7427bba67e9dd42004a18b809ba7d87cee241c" +dependencies = [ + "bitflags 2.13.2", + "objc2 0.6.5", + "objc2-foundation 0.3.2", +] + [[package]] name = "objc2-contacts" version = "0.2.2" @@ -4449,6 +5335,28 @@ dependencies = [ "objc2-foundation 0.2.2", ] +[[package]] +name = "objc2-core-audio" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1eebcea8b0dbff5f7c8504f3107c68fc061a3eb44932051c8cf8a68d969c3b2" +dependencies = [ + "dispatch2", + "objc2 0.6.5", + "objc2-core-audio-types", + "objc2-core-foundation", +] + +[[package]] +name = "objc2-core-audio-types" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a89f2ec274a0cf4a32642b2991e8b351a404d290da87bb6a9a9d8632490bd1c" +dependencies = [ + "bitflags 2.13.2", + "objc2 0.6.5", +] + [[package]] name = "objc2-core-data" version = "0.2.2" @@ -4461,6 +5369,17 @@ dependencies = [ "objc2-foundation 0.2.2", ] +[[package]] +name = "objc2-core-data" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b402a653efbb5e82ce4df10683b6b28027616a2715e90009947d50b8dd298fa" +dependencies = [ + "bitflags 2.13.2", + "objc2 0.6.5", + "objc2-foundation 0.3.2", +] + [[package]] name = "objc2-core-foundation" version = "0.3.2" @@ -4468,7 +5387,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536" dependencies = [ "bitflags 2.13.2", + "block2 0.6.2", "dispatch2", + "libc", "objc2 0.6.5", ] @@ -4479,10 +5400,13 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e022c9d066895efa1345f8e33e584b9f958da2fd4cd116792e15e07e4720a807" dependencies = [ "bitflags 2.13.2", + "block2 0.6.2", "dispatch2", + "libc", "objc2 0.6.5", "objc2-core-foundation", "objc2-io-surface", + "objc2-metal 0.3.2", ] [[package]] @@ -4497,6 +5421,16 @@ dependencies = [ "objc2-metal 0.2.2", ] +[[package]] +name = "objc2-core-image" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5d563b38d2b97209f8e861173de434bd0214cf020e3423a52624cd1d989f006" +dependencies = [ + "objc2 0.6.5", + "objc2-foundation 0.3.2", +] + [[package]] name = "objc2-core-location" version = "0.2.2" @@ -4509,6 +5443,49 @@ dependencies = [ "objc2-foundation 0.2.2", ] +[[package]] +name = "objc2-core-media" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05ec576860167a15dd9fce7fbee7512beb4e31f532159d3482d1f9c6caedf31d" +dependencies = [ + "bitflags 2.13.2", + "block2 0.6.2", + "dispatch2", + "objc2 0.6.5", + "objc2-core-audio", + "objc2-core-audio-types", + "objc2-core-foundation", + "objc2-core-video", +] + +[[package]] +name = "objc2-core-text" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0cde0dfb48d25d2b4862161a4d5fcc0e3c24367869ad306b0c9ec0073bfed92d" +dependencies = [ + "bitflags 2.13.2", + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-core-graphics", +] + +[[package]] +name = "objc2-core-video" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d425caf1df73233f29fd8a5c3e5edbc30d2d4307870f802d18f00d83dc5141a6" +dependencies = [ + "bitflags 2.13.2", + "block2 0.6.2", + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-io-surface", + "objc2-metal 0.3.2", +] + [[package]] name = "objc2-encode" version = "4.1.0" @@ -4536,10 +5513,22 @@ checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272" dependencies = [ "bitflags 2.13.2", "block2 0.6.2", + "libc", "objc2 0.6.5", "objc2-core-foundation", ] +[[package]] +name = "objc2-image-io" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32b0446e98cf4a784cc7a0177715ff317eeaa8463841c616cfc78aa4f953c4ea" +dependencies = [ + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-core-graphics", +] + [[package]] name = "objc2-io-surface" version = "0.3.2" @@ -4563,6 +5552,18 @@ dependencies = [ "objc2-foundation 0.2.2", ] +[[package]] +name = "objc2-media-toolbox" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "edd9fdde720df3da7046bb9097811000c1e7ab5cd579fa89d96b27d56781fb30" +dependencies = [ + "objc2 0.6.5", + "objc2-core-audio-types", + "objc2-core-foundation", + "objc2-core-media", +] + [[package]] name = "objc2-metal" version = "0.2.2" @@ -4633,9 +5634,9 @@ dependencies = [ "bitflags 2.13.2", "block2 0.5.1", "objc2 0.5.3", - "objc2-cloud-kit", - "objc2-core-data", - "objc2-core-image", + "objc2-cloud-kit 0.2.2", + "objc2-core-data 0.2.2", + "objc2-core-image 0.2.2", "objc2-core-location", "objc2-foundation 0.2.2", "objc2-link-presentation", @@ -4709,6 +5710,12 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe" +[[package]] +name = "option-ext" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d" + [[package]] name = "orbclient" version = "0.3.55" @@ -4754,7 +5761,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967" dependencies = [ "libc", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -5009,6 +6016,41 @@ dependencies = [ "futures-io", ] +[[package]] +name = "pipewire" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bde71084c4e25959d68f1ea54daa75e5ecdb338e5caf0b5510143b79baa32d5c" +dependencies = [ + "bitflags 2.13.2", + "libc", + "libspa", + "libspa-sys", + "pipewire-sys", + "rustix 1.1.6", +] + +[[package]] +name = "pipewire-sys" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ce653f53e63e5b93853218092ee9a8906a5d082c92f3f1db26316955dd63ce0" +dependencies = [ + "bindgen", + "libspa-sys", + "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" @@ -5057,7 +6099,7 @@ dependencies = [ "concurrent-queue", "hermit-abi", "pin-project-lite", - "rustix 1.1.5", + "rustix 1.1.6", "windows-sys 0.61.2", ] @@ -5104,6 +6146,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6764c3b5dd454e283a30e6dfe78e9b31096d9e32036b5d1eaac7a6119ccb9a24" dependencies = [ "cobs", + "embedded-io 0.4.0", + "embedded-io 0.6.1", "serde", ] @@ -5316,7 +6360,7 @@ dependencies = [ "once_cell", "socket2", "tracing", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -5356,6 +6400,9 @@ 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" @@ -5495,6 +6542,16 @@ dependencies = [ "bitflags 2.13.2", ] +[[package]] +name = "redox_users" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60dc65c0ff1a7ae1294b0c67b9f14baf70b644404010370171787bfac1038fc0" +dependencies = [ + "libredox", + "thiserror 2.0.21", +] + [[package]] name = "regex" version = "1.13.1" @@ -5715,15 +6772,15 @@ dependencies = [ [[package]] name = "rustix" -version = "1.1.5" +version = "1.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "891efababe418670775f199f0d233d84843c227a0949a883ce15b37c78d6629d" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" dependencies = [ "bitflags 2.13.2", "errno", "libc", "linux-raw-sys 0.12.1", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -5782,7 +6839,7 @@ dependencies = [ "security-framework", "security-framework-sys", "webpki-root-certs", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -6067,6 +7124,12 @@ dependencies = [ "digest 0.11.3", ] +[[package]] +name = "shlex" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" + [[package]] name = "shlex" version = "2.0.1" @@ -6381,7 +7444,7 @@ dependencies = [ "libc", "log", "memmap2", - "rustix 1.1.5", + "rustix 1.1.6", "thiserror 2.0.21", "wayland-backend", "wayland-client", @@ -6610,6 +7673,19 @@ dependencies = [ "libc", ] +[[package]] +name = "system-deps" +version = "7.0.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "396a35feb67335377e0251fcbc1092fc85c484bd4e3a7a54319399da127796e7" +dependencies = [ + "cfg-expr", + "heck 0.5.0", + "pkg-config", + "toml", + "version-compare", +] + [[package]] name = "tar" version = "0.4.46" @@ -6627,6 +7703,12 @@ version = "0.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c1bbb9f3c5c463a01705937a24fdabc5047929ac764b2d5b9cf681c1f5041ed5" +[[package]] +name = "target-lexicon" +version = "0.13.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "adb6935a6f5c20170eeceb1a3835a49e12e19d792f6dd344ccc76a985ca5a6ca" + [[package]] name = "tempfile" version = "3.27.0" @@ -6634,10 +7716,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" dependencies = [ "fastrand", - "getrandom 0.4.3", + "getrandom 0.3.4", "once_cell", - "rustix 1.1.5", - "windows-sys 0.61.2", + "rustix 1.1.6", + "windows-sys 0.52.0", ] [[package]] @@ -6900,8 +7982,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e3641d5bbb5349a79e1020a242d251efbc546ad8048d133958323ce9c40a9c9c" dependencies = [ "indexmap", + "serde_core", + "serde_spanned", "toml_datetime", "toml_parser", + "toml_writer", "winnow", ] @@ -7004,7 +8089,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b8765b90061cba6c22b5831f675da109ae5561588290f9fa2317adab2714d5a6" dependencies = [ "memchr", - "nom", + "nom 8.0.0", "petgraph", ] @@ -7038,6 +8123,12 @@ version = "0.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9ce898823d8cd0f028662d2f349694b1af0a5cc9be83f1d213a00d3147445e1e" +[[package]] +name = "typeid" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc7d623258602320d5c55d1bc22793b57daff0ec7efc270ea7d55ce1d5f5471c" + [[package]] name = "typenum" version = "1.20.1" @@ -7291,7 +8382,7 @@ dependencies = [ [[package]] name = "vello_common" version = "0.0.8" -source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" +source = "git+https://github.com/storytold/craft-libs?rev=0be123b5f29cd203a2beba10277c8c539ce528b4#0be123b5f29cd203a2beba10277c8c539ce528b4" dependencies = [ "bytemuck", "fearless_simd", @@ -7340,7 +8431,7 @@ dependencies = [ [[package]] name = "vello_cpu" version = "0.0.8" -source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" +source = "git+https://github.com/storytold/craft-libs?rev=0be123b5f29cd203a2beba10277c8c539ce528b4#0be123b5f29cd203a2beba10277c8c539ce528b4" dependencies = [ "bytemuck", "glifo 0.1.1", @@ -7376,6 +8467,12 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "version-compare" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03c2856837ef78f57382f06b2b8563a2f512f7185d732608fd9176cb3b8edf0e" + [[package]] name = "version_check" version = "0.9.5" @@ -7528,7 +8625,7 @@ checksum = "38a91b4eaddff87b1cd1074985e3713da4af2c49742d1b356b2c01670a67a078" dependencies = [ "cc", "downcast-rs", - "rustix 1.1.5", + "rustix 1.1.6", "scoped-tls", "smallvec", "wayland-sys", @@ -7541,7 +8638,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e3c36a0f861ad76d0901f2800b46321410d9f73f2ea88aac0650d86c32688073" dependencies = [ "bitflags 2.13.2", - "rustix 1.1.5", + "rustix 1.1.6", "wayland-backend", "wayland-scanner", ] @@ -7563,7 +8660,7 @@ version = "0.31.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4a52d18780be9b1314328a3de5f930b73d2200112e3849ca6cb11822793fb34d" dependencies = [ - "rustix 1.1.5", + "rustix 1.1.6", "wayland-client", "xcursor", ] @@ -7643,6 +8740,19 @@ dependencies = [ "quote", ] +[[package]] +name = "wayland-server" +version = "0.31.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0dde9c29be0f723a573977de51ee455bf3dfa03652730a74f9dd3b337e374d75" +dependencies = [ + "bitflags 2.13.2", + "downcast-rs", + "rustix 1.1.6", + "wayland-backend", + "wayland-scanner", +] + [[package]] name = "wayland-sys" version = "0.31.11" @@ -7650,7 +8760,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d8eab23fefc9e41f8e841df4a9c707e8a8c4ed26e944ef69297184de2785e3be" dependencies = [ "dlib", + "libc", "log", + "memoffset", "once_cell", "pkg-config", ] @@ -7889,13 +9001,19 @@ dependencies = [ "web-sys", ] +[[package]] +name = "widestring" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72069c3113ab32ab29e5584db3c6ec55d416895e60715417b5b883a357c3e471" + [[package]] name = "winapi-util" version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -8233,7 +9351,7 @@ dependencies = [ "libc", "log", "os_pipe", - "rustix 1.1.5", + "rustix 1.1.6", "thiserror 2.0.21", "tree_magic_mini", "wayland-backend", @@ -8292,7 +9410,7 @@ dependencies = [ "libc", "libloading", "once_cell", - "rustix 1.1.5", + "rustix 1.1.6", "x11rb-protocol", ] @@ -8334,7 +9452,49 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32e45ad4206f6d2479085147f02bc2ef834ac85886624a23575ae137c8aa8156" dependencies = [ "libc", - "rustix 1.1.5", + "rustix 1.1.6", +] + +[[package]] +name = "xcap" +version = "0.9.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da270fd7c8581d43d731cb690bcc791fc0a7b3bc96e131a4b6552d0379640a9e" +dependencies = [ + "dispatch2", + "image", + "libwayshot-xcap", + "log", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "objc2-av-foundation", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-core-media", + "objc2-core-video", + "objc2-foundation 0.3.2", + "percent-encoding", + "pipewire", + "rand", + "scopeguard", + "serde", + "thiserror 2.0.21", + "url", + "widestring", + "windows", + "xcb", + "zbus", +] + +[[package]] +name = "xcb" +version = "1.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6c2ad15e0e922856ee89afe862b8992334bbe7953adad56cd1199358cb30566" +dependencies = [ + "bitflags 2.13.2", + "libc", + "quick-xml 0.41.0", ] [[package]] @@ -8388,7 +9548,7 @@ checksum = "9440ea3e5aeabb0ac63af70daf835274065238cdd0cec83418f417eae38bacee" [[package]] name = "xtask" -version = "0.21.1" +version = "0.22.0" dependencies = [ "serde_json", ] @@ -8444,7 +9604,7 @@ dependencies = [ "hex", "libc", "ordered-stream", - "rustix 1.1.5", + "rustix 1.1.6", "serde", "serde_repr", "tracing", @@ -8757,14 +9917,14 @@ dependencies = [ [[patch.unused]] name = "egui_demo_lib" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" +source = "git+https://github.com/storytold/egui.git?rev=14c39fed181756be6f357c284354e0ab55b64443#14c39fed181756be6f357c284354e0ab55b64443" [[patch.unused]] name = "egui_inspection" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" +source = "git+https://github.com/storytold/egui.git?rev=14c39fed181756be6f357c284354e0ab55b64443#14c39fed181756be6f357c284354e0ab55b64443" [[patch.unused]] name = "egui_system_font_provider" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" +source = "git+https://github.com/storytold/egui.git?rev=14c39fed181756be6f357c284354e0ab55b64443#14c39fed181756be6f357c284354e0ab55b64443" diff --git a/Cargo.toml b/Cargo.toml index 1dcb6d332..be339a301 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,7 +4,7 @@ members = ["crates/*", "apps/*", "xtask"] default-members = ["crates/*", "apps/designcraft", "apps/designcraft-cli", "xtask"] [workspace.package] -version = "0.21.1" +version = "0.22.0" edition = "2024" license = "MIT OR Apache-2.0" rust-version = "1.95" @@ -12,36 +12,40 @@ repository = "https://github.com/storytold/designcraft" [workspace.dependencies] # Shared RFC 4648 encoding; document decoding policies remain local. -craft-mime = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d" } +craft-mime = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "0be123b5f29cd203a2beba10277c8c539ce528b4" } # Shared JSON-RPC 2.0 / MCP server framing and lifecycle. -craft-mcp-server = { git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d", version = "=0.1.0" } +craft-mcp-server = { git = "https://github.com/storytold/craft-libs", rev = "0be123b5f29cd203a2beba10277c8c539ce528b4", version = "=0.1.0" } # Shared reader and writer; publish the immutable revision before this consumer. -craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d", version = "=0.1.0", default-features = false } -craft-designcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d", version = "=0.1.0" } -craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d", version = "=0.1.0" } -craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d", version = "=0.1.0", features = ["read"] } -craft-epub = { git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d", version = "=0.1.0" } -craft-idml = { git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d", version = "=0.1.0" } -craft-indd = { git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d", version = "=0.1.0" } -craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d", version = "=0.1.0", features = ["tree-render", "tree-text"] } -craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d", version = "=0.1.0" } -craft-rtf = { git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d", version = "=0.1.0" } -craft-xlsx = { git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d", version = "=0.1.0" } -craft-docx = { git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d", version = "=0.1.0" } -craft-wordmodel = { git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d", version = "=0.1.0" } -craft-csv = { git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d", version = "=0.1.0" } -craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d", version = "=0.1.0" } -craft-jpeg = { git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d", version = "=0.1.0" } -craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d", version = "=0.1.0" } -craft-file-formats = { git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d", version = "=0.1.0" } -craft-opc = { git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d", version = "=0.1.0" } -craft-pptx = { git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d", version = "=0.1.0" } -# Shared keyboard bindings: chords, overrides, conflicts, egui dispatch, the Keyboard Shortcuts dialog. -craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d", version = "=0.1.0", features = ["egui", "ui"] } +craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "0be123b5f29cd203a2beba10277c8c539ce528b4", version = "=0.1.0", default-features = false } +craft-designcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "0be123b5f29cd203a2beba10277c8c539ce528b4", version = "=0.1.0" } +craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "0be123b5f29cd203a2beba10277c8c539ce528b4", version = "=0.1.0" } +craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "0be123b5f29cd203a2beba10277c8c539ce528b4", version = "=0.1.0", features = ["read"] } +craft-epub = { git = "https://github.com/storytold/craft-libs", rev = "0be123b5f29cd203a2beba10277c8c539ce528b4", version = "=0.1.0" } +craft-idml = { git = "https://github.com/storytold/craft-libs", rev = "0be123b5f29cd203a2beba10277c8c539ce528b4", version = "=0.1.0" } +craft-indd = { git = "https://github.com/storytold/craft-libs", rev = "0be123b5f29cd203a2beba10277c8c539ce528b4", version = "=0.1.0" } +craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "0be123b5f29cd203a2beba10277c8c539ce528b4", version = "=0.1.0", features = ["tree-render", "tree-text"] } +craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "0be123b5f29cd203a2beba10277c8c539ce528b4", version = "=0.1.0" } +craft-rtf = { git = "https://github.com/storytold/craft-libs", rev = "0be123b5f29cd203a2beba10277c8c539ce528b4", version = "=0.1.0" } +craft-xlsx = { git = "https://github.com/storytold/craft-libs", rev = "0be123b5f29cd203a2beba10277c8c539ce528b4", version = "=0.1.0" } +craft-docx = { git = "https://github.com/storytold/craft-libs", rev = "0be123b5f29cd203a2beba10277c8c539ce528b4", version = "=0.1.0" } +craft-wordmodel = { git = "https://github.com/storytold/craft-libs", rev = "0be123b5f29cd203a2beba10277c8c539ce528b4", version = "=0.1.0" } +craft-csv = { git = "https://github.com/storytold/craft-libs", rev = "0be123b5f29cd203a2beba10277c8c539ce528b4", version = "=0.1.0" } +craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "0be123b5f29cd203a2beba10277c8c539ce528b4", version = "=0.1.0" } +craft-jpeg = { git = "https://github.com/storytold/craft-libs", rev = "0be123b5f29cd203a2beba10277c8c539ce528b4", version = "=0.1.0" } +craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "0be123b5f29cd203a2beba10277c8c539ce528b4", version = "=0.1.0" } +craft-file-formats = { git = "https://github.com/storytold/craft-libs", rev = "0be123b5f29cd203a2beba10277c8c539ce528b4", version = "=0.1.0" } +craft-opc = { git = "https://github.com/storytold/craft-libs", rev = "0be123b5f29cd203a2beba10277c8c539ce528b4", version = "=0.1.0" } +craft-pptx = { git = "https://github.com/storytold/craft-libs", rev = "0be123b5f29cd203a2beba10277c8c539ce528b4", version = "=0.1.0" } +# Shared keyboard bindings: chords, overrides, conflicts, key matching. On the next pin, so the framework's Keyboard +# Shortcuts dialog (craft-menu) edits the same `Keymap` type the app dispatches from. +craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "0be123b5f29cd203a2beba10277c8c539ce528b4", version = "=0.1.0", features = ["egui"] } +craft-menu = { git = "https://github.com/storytold/craft-libs", rev = "0be123b5f29cd203a2beba10277c8c539ce528b4" } # Separations, ink coverage and the ink manager; same revision as craft-pdf and the krilla patch. -craft-prepress = { git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d", version = "=0.1.0", features = ["flatten"] } +craft-prepress = { git = "https://github.com/storytold/craft-libs", rev = "0be123b5f29cd203a2beba10277c8c539ce528b4", version = "=0.1.0", features = ["flatten"] } # 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 = "33be35625e252cc4f06aa375b3b428521faea37d", features = ["egui"] } +craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "0be123b5f29cd203a2beba10277c8c539ce528b4", features = ["ui"] } +# Shared nightly-v1 profile isolation, launch protocol, and security fence (craft-libs). +craft-nightly = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "0be123b5f29cd203a2beba10277c8c539ce528b4" } # internal designcraft-geom = { path = "crates/geom" } designcraft-color = { path = "crates/color" } @@ -99,20 +103,33 @@ qrcodegen = "1.8" quick-xml = "0.41" zip = { version = "3", default-features = false, features = ["deflate"] } # Which paths stored in documents may be followed (craft-libs). -craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d" } +craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "0be123b5f29cd203a2beba10277c8c539ce528b4" } # Atomic file replacement for saves and exports (craft-libs). -craft-atomic = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d" } +craft-atomic = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "0be123b5f29cd203a2beba10277c8c539ce528b4" } # File › Print through the system print spooler (craft-libs). -craft-print = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d" } +craft-print = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "0be123b5f29cd203a2beba10277c8c539ce528b4" } # ICC colour management: working spaces, transforms, black point compensation (craft-libs). -craft-cms = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d" } +craft-cms = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "0be123b5f29cd203a2beba10277c8c539ce528b4" } # ui +# The craft UI framework, the whole interface on every target, from the SDK crates the components name rather than +# the `craft` facade: the facade's `ui` feature pulls `craft-ui-patterns`, which depends on craft-pdf at that rev and +# so resolves a second `craft-pdf` beside the app's pinned one (xtask's pdf-deps gate allows exactly one). These +# crates pull none of that. +craft-ui-widgets = { git = "https://github.com/storytold/craft-libs", rev = "0be123b5f29cd203a2beba10277c8c539ce528b4" } +craft-ui-panels = { git = "https://github.com/storytold/craft-libs", rev = "0be123b5f29cd203a2beba10277c8c539ce528b4" } +# The shell's title bar, which draws the application bar's frame and moves the window by it. +craft-ui-shell = { git = "https://github.com/storytold/craft-libs", rev = "0be123b5f29cd203a2beba10277c8c539ce528b4" } +# The framework's colour components: the Color Picker, colour wells and their popover. +craft-color-ui = { git = "https://github.com/storytold/craft-libs", rev = "0be123b5f29cd203a2beba10277c8c539ce528b4", features = ["ui"] } +craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "0be123b5f29cd203a2beba10277c8c539ce528b4", default-features = false } +craft-behavior = { git = "https://github.com/storytold/craft-libs", rev = "0be123b5f29cd203a2beba10277c8c539ce528b4" } +craft-host = { git = "https://github.com/storytold/craft-libs", rev = "0be123b5f29cd203a2beba10277c8c539ce528b4" } +craft-window-sdk = { package = "craft-window", git = "https://github.com/storytold/craft-libs", rev = "0be123b5f29cd203a2beba10277c8c539ce528b4", features = ["ui", "appkit"] } # Shared frontend components; keep this dependency above the engine boundary. -craft-ui = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d", features = ["serde"] } -# The application bar as the window's title bar (craft-libs). -craft-window = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d", features = ["egui"] } +# The craft UI framework umbrella (contract, widgets, panels, patterns, shell). +craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "0be123b5f29cd203a2beba10277c8c539ce528b4" } egui = "0.37" # Resizable table columns (About ▸ Contributors / Models); no image loaders. egui_extras = { version = "0.37", default-features = false } @@ -122,7 +139,7 @@ egui_kittest = "0.37" web-time = "1" rfd = "0.17" # Native file and message dialogs that never block the event loop (craft-libs). -craft-dialogs = { git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d" } +craft-dialogs = { git = "https://github.com/storytold/craft-libs", rev = "0be123b5f29cd203a2beba10277c8c539ce528b4" } raw-window-handle = "0.6" arboard = { version = "3.6", default-features = false } @@ -156,30 +173,30 @@ debug = 0 # Opt-in cancelable macOS termination on the pinned winit 0.30 line. [patch.crates-io] -krilla = { git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d", version = "=0.8.2" } +krilla = { git = "https://github.com/storytold/craft-libs", rev = "0be123b5f29cd203a2beba10277c8c539ce528b4", version = "=0.8.2" } winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" } # The hayro crates from craft-libs' vendor/ directory (pdfcraft's, plus the plate mode and decode # limits craft-pdf and craft-prepress need); same revision as craft-pdf. -hayro = { git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d", version = "=0.7.1" } -hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d", version = "=0.7.0" } -hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d", version = "=0.7.2" } -hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d", version = "=0.3.0" } -hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d", version = "=0.1.0" } -hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d", version = "=0.1.0" } -linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d" } -vello_common = { git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d" } -vello_cpu = { git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d" } -ecolor = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } -emath = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } -epaint = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } -epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } -egui = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } -egui-winit = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } -egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } -egui_glow = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } -egui_extras = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } -egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } -egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } -eframe = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } -egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } -egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } +hayro = { git = "https://github.com/storytold/craft-libs", rev = "0be123b5f29cd203a2beba10277c8c539ce528b4", version = "=0.7.1" } +hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "0be123b5f29cd203a2beba10277c8c539ce528b4", version = "=0.7.0" } +hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "0be123b5f29cd203a2beba10277c8c539ce528b4", version = "=0.7.2" } +hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "0be123b5f29cd203a2beba10277c8c539ce528b4", version = "=0.3.0" } +hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "0be123b5f29cd203a2beba10277c8c539ce528b4", version = "=0.1.0" } +hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "0be123b5f29cd203a2beba10277c8c539ce528b4", version = "=0.1.0" } +linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "0be123b5f29cd203a2beba10277c8c539ce528b4" } +vello_common = { git = "https://github.com/storytold/craft-libs", rev = "0be123b5f29cd203a2beba10277c8c539ce528b4" } +vello_cpu = { git = "https://github.com/storytold/craft-libs", rev = "0be123b5f29cd203a2beba10277c8c539ce528b4" } +ecolor = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" } +emath = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" } +epaint = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" } +epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" } +egui = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" } +egui-winit = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" } +egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" } +egui_glow = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" } +egui_extras = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" } +egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" } +egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" } +eframe = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" } +egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" } +egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" } diff --git a/NOTICE b/NOTICE index 3b19745fa..882e2a764 100644 --- a/NOTICE +++ b/NOTICE @@ -130,6 +130,22 @@ list (author, source, license) is in ASSETS.md. AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +- Indic hyphenation patterns, embedded through the hypher crate (features "hindi", "marathi", + "bengali", "assamese", "gujarati", "panjabi", "oriya", "tamil", "telugu", "kannada", + "malayalam"): hyph-hi.tex, hyph-mr.tex, hyph-bn.tex, hyph-as.tex, hyph-gu.tex, hyph-pa.tex, + hyph-or.tex, hyph-ta.tex, hyph-te.tex, hyph-kn.tex and hyph-ml.tex 0.9.0 (2016-01-16) from + hyph-utf8, https://github.com/hyphenation/tex-hyphen. Copyright (C) 2016 Santhosh Thottingal. + Available under the MIT License: Permission is hereby granted, free of charge, to any person obtaining a copy of this + software and associated documentation files (the "Software"), to deal in the Software without + restriction, including without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the + Software is furnished to do so, subject to the following conditions: The above copyright notice + and this permission notice shall be included in all copies or substantial portions of the + Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, + INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE + AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - German hyphenation patterns, embedded through the hypher crate (feature "german"): hyph-de-1996.tex 2024-02-28, German reformed orthography (2006), from hyph-utf8, https://github.com/typst/hypher/blob/d81cc506416bffef2a75ee2dc969d4b41bc36613/patterns/hyph-de-1996.tex. diff --git a/ROADMAP.md b/ROADMAP.md index b00cecd69..69fd59e59 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -11,8 +11,7 @@ - 2026-10-23: placed-artwork layer options survive IDML and native round trips per placement, independently of shared assets. Unsupported visibility overrides are explicit import/preflight/PDF warnings; format 4 prevents older native readers from silently discarding them. Rendering parity is still open; see [graphic-layer-options.md](docs/graphic-layer-options.md). - FID1: PDF export normalizes mixed emitted gradient color spaces to RGB with an explicit warning; homogeneous device-space gradients retain their components. Linear/radial, midpoint, archival and print policies have synthetic regression coverage. -> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-11-19 · **Change:** minor (hidden characters follow frame, group and layer visibility (#1994); obsolete CI gap removed; tracked-change selection mapping; Croatian hyphenation (hyph-hr); Pages panel parents and alternate layouts; File ▸ Export Layouts and Versions; placed graphic layer-option preservation and explicit rendering warnings; File ▸ Open Recent; .indd and .indt open through indd-utils; text threads by hand; the alpha gate waits on Primary Text Frame page fixes; Japanese print, import and table controls localized; Live corners (#186); Optical kerning from outlines (#181); window and menu quit confirmation; failed writes preserve live save and collection state; spring-loaded Zoom navigation; orderly native exit recovery; Pages panel parents; cancelable macOS Dock Quit; text stroke behind fill; Based on Parent; object styles carry effects; table anchors keep their own paragraphs; grouped HTML/EPUB reading order; Links source paths; XLSX cached cell values retain numeric precision and text; automation roots refuse superscript COM/LPT names and a device name before a colon) · **Target:** Adobe InDesign 2026 -> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-11-15 · **Change:** minor (DesignCraft v0.21.0 version preparation; links and buttons accept only web and mail schemes, and PDF export writes only http, https and mailto link targets; a save asked for while open-time link checks run waits for them, then writes linked files, with `links.progress`; the MCP server caps one request line at 4 MiB; `table.setCell` is a no-op when every value already matches, preserving character formats and a shared-edge stroke; File ▸ Place and `edit.pasteImage` size a raster by its stored resolution; live captions refresh on a committed gesture, inside groups, with the caret clamped; drop caps and vertical justification skip a baseline grid the lines cannot count; image warm accounting counts an image's cached levels once; parity scores unchanged; previous: obsolete CI gap removed; tracked-change selection mapping; Pages panel parents and alternate layouts; File ▸ Export Layouts and Versions; placed graphic layer-option preservation and explicit rendering warnings; File ▸ Open Recent; .indd and .indt open through indd-utils; text threads by hand; the alpha gate waits on Primary Text Frame page fixes; Japanese print, import and table controls localized; Live corners (#186); Optical kerning from outlines (#181); window and menu quit confirmation; failed writes preserve live save and collection state; spring-loaded Zoom navigation; orderly native exit recovery; Pages panel parents; cancelable macOS Dock Quit; text stroke behind fill; Based on Parent; object styles carry effects; table anchors keep their own paragraphs; grouped HTML/EPUB reading order; Links source paths; XLSX cached cell values retain numeric precision and text; automation roots refuse superscript COM/LPT names and a device name before a colon) · **Target:** Adobe InDesign 2026 +> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-11-19 · **Change:** minor (DesignCraft v0.21.0 version preparation; links and buttons accept only web and mail schemes, and PDF export writes only http, https and mailto link targets; a save asked for while open-time link checks run waits for them, then writes linked files, with `links.progress`; the MCP server caps one request line at 4 MiB; `table.setCell` is a no-op when every value already matches, preserving character formats and a shared-edge stroke; File ▸ Place and `edit.pasteImage` size a raster by its stored resolution; live captions refresh on a committed gesture, inside groups, with the caret clamped; drop caps and vertical justification skip a baseline grid the lines cannot count; image warm accounting counts an image's cached levels once; parity scores unchanged; hidden characters follow frame, group and layer visibility (#1994); obsolete CI gap removed; tracked-change selection mapping; Croatian hyphenation (hyph-hr); Pages panel parents and alternate layouts; File ▸ Export Layouts and Versions; placed graphic layer-option preservation and explicit rendering warnings; File ▸ Open Recent; .indd and .indt open through indd-utils; text threads by hand; the alpha gate waits on Primary Text Frame page fixes; Japanese print, import and table controls localized; Live corners (#186); Optical kerning from outlines (#181); window and menu quit confirmation; failed writes preserve live save and collection state; spring-loaded Zoom navigation; orderly native exit recovery; Pages panel parents; cancelable macOS Dock Quit; text stroke behind fill; Based on Parent; object styles carry effects; table anchors keep their own paragraphs; grouped HTML/EPUB reading order; Links source paths; XLSX cached cell values retain numeric precision and text; automation roots refuse superscript COM/LPT names and a device name before a colon) · **Target:** Adobe InDesign 2026 - AR1.1: Kashida justification tests verify space fallback without Tatweel fonts using an isolated font database, while retaining elongation assertions when fonts support it. - AR1: Arabic IDML controls now retain character direction, kashida switches, diacritic offsets/forms, paragraph policy values and independent story/table directions. Shaping preserves joining context and script/language selection; paragraph-level bidi, contextual digit conversion, mark-safe elongation, RTL columns/tables and physical column insertion have regression coverage. Vendor-specific justification and diacritic presets remain explicit preflight warnings; see docs/arabic-typography.md. @@ -20,6 +19,7 @@ DesignCraft aims at full Adobe InDesign parity — and to be better: faster, open (documented JSON format + IDML), scriptable by agents (MCP), and available on the web. +- **2026-11-30** · Hindi, Marathi, Bengali, Assamese, Gujarati, Punjabi, Odia, Tamil, Telugu, Kannada and Malayalam text hyphenates with Santhosh Thottingal's MIT-licensed hyph-utf8 patterns through `hypher`, between syllables and never inside a conjunct. A word of these scripts split at a line end takes no hyphen and keeps no room for one; Sinhala and other scripts keep theirs. Hyphenate Across Column off now also holds when a syllable ends in a glyph drawn out of order (the vowel sign of वि). Original work by dileep2in (#3048). No readiness percentage change. - **2026-11-15** · Story targets are checked before they are used: `story.setDirection`, `story.get`, `type.fillWithPlaceholder` and `file.exportText` refuse a `story` or `frame` the document doesn't have instead of acting on the selected frame's story, so an edit can no longer land on the wrong story and an export cannot @@ -408,6 +408,8 @@ list) · [roadmap.md](docs/roadmap.md) (milestones, plan) · [parity-checklist.m ## Progress log +- **2026-11-30** · The view follows the caret (#3405): when typing, the arrow keys, undo or a command such as Insert Footnote takes the caret to where its line isn't in view, the view scrolls just enough to show the whole line, keeping zoom, as in InDesign. Scrolling away by hand, or showing another document, doesn't pull the view back. No readiness percentage change. +- **2026-11-29** · With the Type tool, a click (Shift or not) on empty page or on the pasteboard deselects, dropping the caret and the frame holding it, as in InDesign; before, the frame stayed selected until another frame was clicked or the tool changed. Deselecting is not an undo step, and a drag from empty canvas still draws a new text frame. No readiness percentage change. - **2026-11-18** · View › Extras › Show/Hide Link Badge: frames showing a linked picture carry a link badge on their top edge, a warning when the file changed and a stop when it is missing; hidden in Preview. No readiness percentage change. - **2026-11-16** · Fitting a bottom-aligned text frame from its top handle keeps its bottom edge and text in place (#2880): double-clicking any selection handle passes the opposite local reference point (`ref` 0..=8) to `object.fit`, menu/panel/scripting fits without `ref` anchor to vertical justification (`Bottom`/`Center`/`Top`/`Justify`), and `transform.resize` keeps unchanged edges pinned across its `1e-3` scale clamp and flips. No readiness percentage change. - **2026-11-13** · A placed Photoshop file comes in at its own resolution (ResolutionInfo), as other rasters do since #1991: a 300 ppi PSD was placed four times too large at 72 ppi. No readiness percentage change. @@ -620,6 +622,7 @@ Newest first. - **2026-10-17** · Cross-references keep text typed over their generated text (IDML import and export), with the page number still live, as InDesign shows them until updated; a cross-reference whose destination is gone shows its saved text and page instead of "??"; and a cross-reference's text breaks at its spaces instead of inside words. No readiness percentage change. - **2026-10-17** · Parent pages: while parents are edited, the document pages' hidden characters, spelling squiggles and other overlays no longer pile onto the right parent page. No readiness percentage change. - **2026-10-16** · A Direct Selection click on an image whose frame is already selected selects the image, so Delete removes only the image and leaves the empty frame, as in InDesign. No readiness percentage change. +- **2026-10-16** · Inline and other anchored objects can be selected and resized on the page: the Selection tool clicks one where it sits in the text and shows its handles, a handle drag shows an outline and the size, and on release the frame takes it (cropping from the sides that moved; Cmd scales the content, Shift keeps proportions) and the text reflows, and Delete removes it from the text. Anchored Object Options and Release act on the selected object. Before, a click selected the text frame around it. No readiness percentage change. - **2026-10-18** · Web build: linked graphics relink from files handed over — Links › Relink… opens the browser's file picker for one graphic, Relink to Folder… its folder picker (each missing graphic takes the file whose path in the folder ends like its link; same-named files nothing tells apart are left missing and reported); one undo step per batch. New `links.relinkFiles`. Before, both buttons did nothing in the browser, so an IDML opened without its Links folder had no way to get its pictures. No readiness percentage change. - **2026-10-16** · Type › Reload Fonts (`font.reload`): fonts installed, edited or removed while DesignCraft runs are read again without a restart, and the open documents recompose with them (#328, #547). An edited font file is noticed by its length and modification time; bundled, added and document fonts stay as they are. InDesign does this by itself, so noticing changes automatically is still open (gap 6). No readiness percentage change. - **2026-10-16** · Parents can be deleted from their Pages-panel context menu or `layout.parents.delete {id}`. Applied-page and based-on references are cleared, local override copies survive, and Undo restores the parent. Addresses the deletion portion of #956; no readiness percentage change. diff --git a/apps/designcraft-web/src/web.rs b/apps/designcraft-web/src/web.rs index f1eedc1b3..03003b0a1 100644 --- a/apps/designcraft-web/src/web.rs +++ b/apps/designcraft-web/src/web.rs @@ -82,6 +82,10 @@ pub fn start() { app.session.prefs = prefs; } let prefs_sync = PrefsSync::new(stored); + + // The craft UI framework's runtime, before the context's first pass (it refuses to install inside + // one): the whole interface is the framework's, in the browser as on the desktop. + app.install_framework(&cc.egui_ctx); if has_query_flag(&query(), "sample") { let _ = app.run("file.newSample", serde_json::json!({})); } diff --git a/apps/designcraft/Cargo.toml b/apps/designcraft/Cargo.toml index 359e00470..67ff12f47 100644 --- a/apps/designcraft/Cargo.toml +++ b/apps/designcraft/Cargo.toml @@ -11,6 +11,7 @@ default-run = "designcraft" workspace = true [dependencies] +craft-nightly = { workspace = true } designcraft-engine = { workspace = true } designcraft-ui-egui = { workspace = true } eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit", "wayland", "x11", "links", "clipboard"] } @@ -56,7 +57,6 @@ objc2-app-kit = { version = "0.3", default-features = false, features = ["std", # Files dragged in from the Finder: the pointer's place on the screen (src/pointer.rs). objc2-foundation = { version = "0.3", default-features = false, features = ["std", "NSArray", "NSGeometry"] } # The window's `movable` flag follows the application bar's controls. -craft-window = { workspace = true } # Finder double-clicks, Open With, Dock drops and `open -a DesignCraft brochure.idml` arrive as a # kAEOpenDocuments Apple event, which winit 0.30 doesn't handle. This crate (also used by PhotoCraft, # PdfCraft and WordCraft) registers the handler behind a safe API (Objective-C interop needs unsafe, diff --git a/apps/designcraft/src/build_flavor.rs b/apps/designcraft/src/build_flavor.rs index 0793f44ed..ae6093c9c 100644 --- a/apps/designcraft/src/build_flavor.rs +++ b/apps/designcraft/src/build_flavor.rs @@ -1,12 +1,8 @@ //! 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!(designcraft_nightly_v1) { BuildFlavor::NightlyV1 } else { BuildFlavor::Stable }; @@ -16,14 +12,6 @@ pub const VERSION: &str = env!("DESIGNCRAFT_BUILT_VERSION"); /// The plain `designcraft --version` line, unchanged for stable. pub const STABLE_VERSION_LINE: &str = concat!("designcraft ", env!("CARGO_PKG_VERSION")); -pub fn require_profile(flavor: BuildFlavor, profile: &Profile) -> Result<(), String> { - match (flavor, profile.is_nightly()) { - (BuildFlavor::NightlyV1, false) => Err("Open DesignCraft Nightly from ArtCraft Launcher".into()), - (BuildFlavor::Stable, true) => Err("This is a stable DesignCraft 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 } @@ -42,7 +30,7 @@ pub fn version_line(flavor: BuildFlavor, stable: &str, version: &str) -> String #[cfg(test)] mod tests { - use super::*; + use super::{BuildFlavor, COMPILED, VERSION, needs_native_error, version_line, version_query}; #[test] fn only_a_nightly_desktop_refusal_requests_a_native_dialog() { @@ -52,22 +40,6 @@ mod tests { assert!(!needs_native_error(BuildFlavor::Stable, false)); } - #[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()); - } - - #[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()); - } - #[test] fn nightly_version_query_is_unambiguous_and_never_reinterprets_file_arguments() { let version = "0.2.1-nightly.20261124.17.1.gabcdef012345"; diff --git a/apps/designcraft/src/launch_profile.rs b/apps/designcraft/src/launch_profile.rs index f2b421433..98816e326 100644 --- a/apps/designcraft/src/launch_profile.rs +++ b/apps/designcraft/src/launch_profile.rs @@ -1,127 +1,94 @@ -//! 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. +//! DesignCraft's `craft-nightly` isolation specification. +//! +//! Nightly builds self-isolate into `craft_nightly::canonical_profile_root("designcraft")` on +//! direct launch and also accept ArtCraft Launcher's `--launch-profile nightly-v1 --profile-root` +//! arguments, fenced away from stable settings, installs, and portable layouts. use std::ffi::OsString; -use std::path::{Component, Path, PathBuf}; -use std::sync::OnceLock; +use std::path::{Component, PathBuf}; -pub const VERSION: &str = "nightly-v1"; +use craft_nightly::AppProfileSpec; -#[derive(Clone, Debug, PartialEq, Eq)] -pub enum Profile { - Stable, - NightlyV1(PathBuf), +const FOLDER_ONLY_ENTRIES: &[&str] = &["Recovery", "logs"]; + +/// Builds DesignCraft's [`AppProfileSpec`] for `craft-nightly` startup parsing and fencing. +pub fn spec() -> AppProfileSpec { + AppProfileSpec { + app_id: "designcraft", + display_name: "DesignCraft", + stable_dir_names: &["DesignCraft", "designcraft"], + stable_package_id: designcraft_ui_egui::channel::APP_ID, + nightly_package_id: designcraft_ui_egui::channel::NIGHTLY_PACKAGE_ID, + profile_root_env: None, + forbidden_env_vars: &["DESIGNCRAFT_CONFIG_DIR"], + portable_markers: &[crate::profile::PORTABLE_MARKER], + folder_only_entries: FOLDER_ONLY_ENTRIES, + extra_forbidden_roots: extra_forbidden_roots_with(|key| std::env::var_os(key)), + } } -impl Profile { - pub fn is_nightly(&self) -> bool { - matches!(self, Self::NightlyV1(_)) - } +fn abs_env(env: &impl Fn(&str) -> Option, key: &str) -> Option { + let value = env(key).filter(|v| !v.is_empty())?; + let path = PathBuf::from(value); + (path.is_absolute() && !path.components().any(|c| matches!(c, Component::ParentDir))).then_some(path) +} - pub fn root(&self) -> Option<&Path> { - match self { - Self::Stable => None, - Self::NightlyV1(root) => Some(root), +fn extra_forbidden_roots_with(env: impl Fn(&str) -> Option) -> Vec { + #[cfg(target_os = "windows")] + { + let mut roots = Vec::new(); + if let Some(local) = abs_env(&env, "LOCALAPPDATA") { + roots.push(local.join("Programs").join("ArtCraft").join("DesignCraft")); } - } -} - -#[derive(Debug, PartialEq, Eq)] -pub struct Launch { - pub profile: Profile, - pub args: Vec, -} - -static PROFILE: OnceLock = OnceLock::new(); - -pub fn current() -> &'static Profile { - PROFILE.get().unwrap_or(&Profile::Stable) -} - -pub fn install(profile: Profile) -> Result<(), String> { - PROFILE.set(profile).map_err(|_| "the launch profile was already selected".into()) -} - -/// 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; + for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] { + if let Some(base) = abs_env(&env, key) { + roots.push(base.join("ArtCraft").join("DesignCraft")); + } } - 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()); + roots + } + + #[cfg(all(unix, not(target_os = "macos")))] + { + let mut roots = vec![PathBuf::from("/usr/bin/designcraft"), PathBuf::from("/usr/local/bin/designcraft"), PathBuf::from("/opt/designcraft")]; + if let Some(home) = abs_env(&env, "HOME") { + roots.push(home.join(".var/app/ai.storyteller.designcraft")); } + roots } - 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() }) + + #[cfg(target_os = "macos")] + { + let mut roots = vec![PathBuf::from("/Applications/DesignCraft.app")]; + if let Some(home) = abs_env(&env, "HOME") { + let library = home.join("Library"); + roots.push(library.join("Preferences/DesignCraft.plist")); + roots.push(library.join("Preferences/ai.storyteller.designcraft.plist")); + roots.push(library.join("Saved Application State/ai.storyteller.designcraft.savedState")); + roots.push(home.join("Applications/DesignCraft.app")); } - (Some(_), Some(_)) => Err("unsupported launch profile (expected nightly-v1)".into()), - _ => Err("--launch-profile and --profile-root must be supplied together".into()), + roots } -} -/// 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; + #[cfg(not(any(unix, target_os = "windows")))] + { + let _ = env; + Vec::new() } - 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 portable/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. DesignCraft has no -/// agent SDK folder of its own, so the stable boundary is its settings folder, install folders and -/// portable data only. -pub fn validate_root(root: &Path, env: impl Fn(&str) -> Option, exe: Option<&Path>) -> Result { - crate::profile_root::validate(root, env, exe, crate::profile::ensure_writable) } #[cfg(test)] mod tests { - use super::*; - use std::cell::Cell; + use std::ffi::OsString; + use std::path::Path; + use std::sync::atomic::{AtomicU64, Ordering}; + + use craft_nightly::{ + BuildFlavor, NIGHTLY_V1_CONTRACT, Profile, ProfileError, StartupOptions, canonical_profile_root, launch_arguments, parse_startup, + validate_and_prepare_root, + }; + + use super::{FOLDER_ONLY_ENTRIES, spec}; fn args(values: &[&str]) -> Vec { values.iter().map(OsString::from).collect() @@ -131,87 +98,118 @@ mod tests { if cfg!(windows) { r"C:\NightlyData\profiles\designcraft" } else { "/nightly-data/profiles/designcraft" } } - fn nightly() -> Vec { - args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--"]) + #[test] + fn spec_preserves_designcraft_isolation_boundaries() { + let s = spec(); + assert_eq!(s.app_id, "designcraft"); + assert_eq!(s.display_name, "DesignCraft"); + assert_eq!(s.stable_dir_names, &["DesignCraft", "designcraft"]); + assert_eq!(s.stable_package_id, designcraft_ui_egui::channel::APP_ID); + assert_eq!(s.nightly_package_id, designcraft_ui_egui::channel::NIGHTLY_PACKAGE_ID); + assert_eq!(s.profile_root_env, None); + assert_eq!(s.forbidden_env_vars, &["DESIGNCRAFT_CONFIG_DIR"]); + assert_eq!(s.portable_markers, &[crate::profile::PORTABLE_MARKER]); + assert_eq!(s.folder_only_entries, FOLDER_ONLY_ENTRIES); } #[test] - fn stable_arguments_and_directory_policy_are_unchanged() { + fn direct_nightly_launch_self_isolates_into_canonical_profile_root() { + let s = spec(); + let expected_root = canonical_profile_root("designcraft").unwrap(); + let user_args = args(&["brochure.designcraft", "poster.idml"]); + let launch = parse_startup(BuildFlavor::NightlyV1, &s, user_args.clone(), &StartupOptions::new()).unwrap(); + assert_eq!(launch.profile, Profile::NightlyV1(expected_root)); + assert_eq!(launch.passthrough_args, user_args); + assert!(launch.leading_flags.is_empty()); + } + + #[test] + fn explicit_launcher_arguments_are_parsed_without_reinterpreting_file_names() { + let s = spec(); + let root = Path::new(absolute()); + let user_args = args(&["--profile-root", "design with spaces.designcraft"]); + let argv = launch_arguments(root, &user_args); + let launch = parse_startup(BuildFlavor::NightlyV1, &s, argv, &StartupOptions::new()).unwrap(); + assert_eq!(launch.profile, Profile::NightlyV1(root.to_path_buf())); + assert_eq!(launch.passthrough_args, user_args); + } + + #[test] + fn stable_build_keeps_normal_args_and_refuses_nightly_flags() { + let s = spec(); for argv in [args(&[]), args(&["--sample", "a.idml"]), args(&["--", "--launch-profile", "file.designcraft"])] { - 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, &s, argv.clone(), &StartupOptions::new()).unwrap(); + assert_eq!(launch.profile, Profile::Stable); + assert_eq!(launch.passthrough_args, argv); } + let nightly_argv = launch_arguments(Path::new(absolute()), &[]); + let err = parse_startup(BuildFlavor::Stable, &s, nightly_argv, &StartupOptions::new()).unwrap_err(); + assert!(matches!(err, ProfileError::NightlyFlagsInStableBuild)); } #[test] - fn exact_version_and_root_are_parsed_without_reinterpreting_file_names() { - let mut argv = nightly(); - argv.extend(args(&["--profile-root", "design with spaces.designcraft"])); - let launch = parse(argv).unwrap(); - assert_eq!(launch.profile, Profile::NightlyV1(PathBuf::from(absolute()))); - assert_eq!(launch.args, args(&["--", "--profile-root", "design with spaces.designcraft"])); - } - - #[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(), "--new-instance", "--"]), - args(&["--launch-profile", VERSION, "--profile-root", absolute()]), - args(&["--launch-profile=", VERSION, "--profile-root", absolute(), "--"]), - ] { - assert!(parse(argv).is_err()); - } - } - - #[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]; + fn version_queries_are_recognized_for_plain_and_launcher_invocations() { + let s = spec(); + let root = Path::new(absolute()); for flag in ["--version", "-V"] { - for form in [pair, reversed] { - let mut argv = args(form); - argv.push(flag.into()); - assert!(version_query(&argv), "{argv:?}"); - } + let plain = parse_startup(BuildFlavor::NightlyV1, &s, args(&[flag]), &StartupOptions::new()).unwrap(); + assert!(plain.is_version_query(), "plain {flag}"); + + let via_launcher = parse_startup(BuildFlavor::NightlyV1, &s, launch_arguments(root, &args(&[flag])), &StartupOptions::new()).unwrap(); + assert!(via_launcher.is_version_query(), "launcher {flag}"); + + let without_sep = parse_startup( + BuildFlavor::NightlyV1, + &s, + args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), flag]), + &StartupOptions::new(), + ) + .unwrap(); + assert!(without_sep.is_version_query(), "launcher without separator {flag}"); } - 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(), "--new-instance", "--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"]), - ] { - assert!(!version_query(&argv), "{argv:?}"); - } - // Outside the query the strict protocol still refuses the version flag. - assert!(parse(args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version"])).is_err()); + let file_named_version = parse_startup(BuildFlavor::NightlyV1, &s, args(&["--", "--version"]), &StartupOptions::new()).unwrap(); + assert!(!file_named_version.is_version_query()); } #[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()); - } + fn nightly_profile_reopens_after_saving_settings_and_session_state() { + static NEXT: AtomicU64 = AtomicU64::new(0); + let base = std::fs::canonicalize(std::env::temp_dir()).unwrap_or_else(|_| std::env::temp_dir()); + let root = base.join(format!("designcraft-nightly-reopen-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed))); + let _ = std::fs::remove_dir_all(&root); + let s = spec(); - #[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()); + let confirmed = validate_and_prepare_root(&root, &s).unwrap(); + assert_eq!(confirmed, root); + for name in ["ui.json", "prefs.json", "nightly-session.lock", "nightly-session.json"] { + std::fs::write(confirmed.join(name), b"saved profile data").unwrap(); + } + for name in FOLDER_ONLY_ENTRIES { + std::fs::create_dir(confirmed.join(name)).unwrap(); + } + assert_eq!(validate_and_prepare_root(&root, &s).unwrap(), confirmed); + for name in ["ui.json", "prefs.json", "nightly-session.lock", "nightly-session.json"] { + assert_eq!(std::fs::read(confirmed.join(name)).unwrap(), b"saved profile data", "{name} changed when reopening"); + } + + for name in FOLDER_ONLY_ENTRIES { + let path = confirmed.join(name); + std::fs::remove_dir(&path).unwrap(); + std::fs::write(&path, b"not a directory").unwrap(); + assert!(validate_and_prepare_root(&root, &s).is_err(), "{name} must stay a directory"); + std::fs::remove_file(&path).unwrap(); + std::fs::create_dir(&path).unwrap(); + } + + let invalid = confirmed.join("ordinary-file"); + std::fs::write(&invalid, b"existing file").unwrap(); + let argv = launch_arguments(&invalid, &[]); + assert!(craft_nightly::current().is_none()); + let result = craft_nightly::prepare_launch(BuildFlavor::NightlyV1, &s, argv, &StartupOptions::new()); + assert!(matches!(result, Err(ProfileError::NotADirectory(_)))); + assert!(craft_nightly::current().is_none()); + assert_eq!(std::fs::read(invalid).unwrap(), b"existing file"); + + let _ = std::fs::remove_dir_all(&root); } } diff --git a/apps/designcraft/src/main.rs b/apps/designcraft/src/main.rs index 23688b3f6..36c7c91e8 100644 --- a/apps/designcraft/src/main.rs +++ b/apps/designcraft/src/main.rs @@ -32,7 +32,6 @@ mod nightly_session; mod pointer; mod process_identity; mod profile; -mod profile_root; mod window_frame; use designcraft_engine::Session; @@ -47,9 +46,6 @@ struct App { /// Documents and quit requests from Finder, the Dock and Open With. #[cfg(target_os = "macos")] apple_events: fmv_macos_events::Inbox, - /// The window's `movable` flag as last set; see `craft_window::title_bar`. - #[cfg(target_os = "macos")] - movable: Option, /// Frames begun so far. frames: u32, /// The device whose uncaptured errors are logged once the window is past its start-up frames @@ -104,14 +100,14 @@ impl eframe::App for App { self.startup.opening(apple_events::poll(&self.apple_events, &mut self.app, ui.ctx())); } } + #[cfg(target_os = "macos")] + self.app.set_input_source(selected_input_source()); self.app.ui(ui); self.startup.leave(); #[cfg(target_os = "macos")] if self.app.take_ime_discard() { discard_marked_text(); } - #[cfg(target_os = "macos")] - craft_window::title_bar::sync_movable(ui.ctx(), &mut self.movable); // After the frame, never inside it: the dialog answers on a later frame. On macOS Save and // message boxes are sheets on this window. self.app.show_file_dialogs(Some(&*frame)); @@ -140,6 +136,15 @@ fn discard_marked_text() { } } +/// The keyboard input source macOS has selected (its ID), or `None` without a key window. Space +/// in a Japanese input mode types an ideographic space, which winit reports as a plain one. +#[cfg(target_os = "macos")] +fn selected_input_source() -> Option { + let mtm = objc2::MainThreadMarker::new()?; + let id = objc2_app_kit::NSTextInputContext::currentInputContext(mtm)?.selectedKeyboardInputSource()?; + Some(id.to_string()) +} + /// Orderly OS termination can bypass egui's cancelable close event. Finish only a complete, /// current quit plan; otherwise preserve every live document, including edits after the timer. fn preserve_documents_on_exit(app: &mut DesignApp) -> Result<(), String> { @@ -322,41 +327,37 @@ fn report_launch_profile_error(error: &str) { } /// Select the immutable launch profile before any start-up service or side effect: the version -/// answer first, then the profile, the Windows identity, the fenced root and the session record. +/// answer first, then `craft-nightly` startup/fencing (self-isolating direct nightly launches into +/// the canonical profile root and honoring Launcher `--launch-profile`/`--profile-root` flags), +/// the Windows identity, channel selection, and the session record. fn prepare_launch() -> Option { 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 logging, root validation, process identity or any window. A - // headless runner otherwise hung on macOS and exited 2 on Linux. - if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && (build_flavor::version_query(&argv) || launch_profile::version_query(&argv)) - { + // Plain `--version`/`-V` on Nightly: answered before root resolution, process identity, or any + // window, even in minimal environments without a home directory. + if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && build_flavor::version_query(&argv) { + use std::io::Write as _; + let line = build_flavor::version_line(build_flavor::COMPILED, build_flavor::STABLE_VERSION_LINE, build_flavor::VERSION); + let _ = writeln!(std::io::stdout(), "{line}"); + return None; + } + let spec = launch_profile::spec(); + let launch = craft_nightly::prepare_launch(build_flavor::COMPILED, &spec, argv, &craft_nightly::StartupOptions::new()).unwrap_or_else(|error| { + report_launch_profile_error(&error.to_string()); + std::process::exit(2) + }); + if launch.is_version_query() { use std::io::Write as _; let line = build_flavor::version_line(build_flavor::COMPILED, build_flavor::STABLE_VERSION_LINE, build_flavor::VERSION); let _ = writeln!(std::io::stdout(), "{line}"); return None; } - let launch = launch_profile::parse(argv) - .and_then(|launch| { - build_flavor::require_profile(build_flavor::COMPILED, &launch.profile)?; - if launch.profile.is_nightly() { - process_identity::initialize(true, designcraft_ui_egui::channel::NIGHTLY_APP_ID).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 nightly = launch.profile.is_nightly(); + if nightly && let Err(error) = process_identity::initialize(true, designcraft_ui_egui::channel::NIGHTLY_APP_ID) { + report_launch_profile_error(&error.to_string()); + std::process::exit(2); + } let channel = if nightly { designcraft_ui_egui::channel::Channel::NightlyV1 } else { designcraft_ui_egui::channel::Channel::Stable }; - if let Err(error) = launch_profile::install(launch.profile) - .and_then(|()| designcraft_ui_egui::channel::select(channel, build_flavor::VERSION, option_env!("DESIGNCRAFT_NIGHTLY_COMMIT"))) - { + if let Err(error) = designcraft_ui_egui::channel::select(channel, build_flavor::VERSION, option_env!("DESIGNCRAFT_NIGHTLY_COMMIT")) { report_launch_profile_error(&error); std::process::exit(2); } @@ -365,7 +366,7 @@ fn prepare_launch() -> Option { let mut session_unavailable = false; if nightly { match nightly_session::Session::begin_with_health( - launch_profile::current().root(), + craft_nightly::current_root(), build_flavor::VERSION, option_env!("DESIGNCRAFT_NIGHTLY_COMMIT"), ) { @@ -381,7 +382,7 @@ fn prepare_launch() -> Option { } } } - Some(Launched { args: launch.args, nightly, session, unclean, session_unavailable }) + Some(Launched { args: launch.passthrough_args, nightly, session, unclean, session_unavailable }) } /// The ordinary command line, once the launch profile was selected. @@ -399,16 +400,14 @@ struct AppCommand { skip: Vec, } -/// Read the arguments left after the launch profile. A Nightly start's first argument is the -/// separator `launch_profile::parse` put there: it is never a document, and an option after it was -/// named by the Launcher as a file. Stable keeps its control, sample and version options and drops -/// a user's own separator, so a literal `--` is never opened as a document. +/// Read the arguments left after `craft-nightly` strips any launcher protocol header and `--` +/// separator. A direct Nightly launch may still start with a user-supplied `--`, which is dropped +/// once so it is never opened as a document. Stable keeps its control, sample and version options +/// and drops a user's own separator, so a literal `--` is never opened as a document. fn app_command(args: impl IntoIterator, nightly: bool) -> AppCommand { let mut command = AppCommand::default(); - let mut args = args.into_iter(); - if nightly { - // `parse` puts the protocol's separator first; skipping it keeps a restart's `--gpu-skip=` - // (appended after that separator) in the ordinary arm below. + let mut args = args.into_iter().peekable(); + if nightly && args.peek().is_some_and(|a| a == "--") { args.next(); } while let Some(a) = args.next() { @@ -606,6 +605,12 @@ fn main() -> std::process::ExitCode { session.recovery_dir = profile::recovery_dir(); let recovered = session.execute("file.recovery.open", &serde_json::json!({})).ok(); let mut app = DesignApp::new(session, services()); + // The window's frame, which the framework's title bar follows: set once, before the runtime is installed. + app.integrated_titlebar = cfg!(target_os = "macos"); + app.custom_titlebar = cfg!(target_os = "windows"); + // The craft UI framework's runtime, before the context's first pass (it refuses to install + // inside one): the whole interface is the framework's. + app.install_framework(&cc.egui_ctx); if nightly { // Installed and updated by the Launcher: never check the stable feed from here. app.set_updates_managed(Some("ArtCraft Launcher")); @@ -631,8 +636,6 @@ fn main() -> std::process::ExitCode { } else if session_unavailable && nightly { log::warn!("another DesignCraft Nightly holds this profile's session record"); } - app.integrated_titlebar = cfg!(target_os = "macos"); - app.custom_titlebar = cfg!(target_os = "windows"); // The custom title bar's undecorated window must stay borderless, or its caption // and border offset the content and the pointer on some Windows systems (#1295). app.services.window_frame = window_frame::service(cc, app.custom_titlebar); @@ -657,8 +660,6 @@ fn main() -> std::process::ExitCode { startup: created, #[cfg(target_os = "macos")] apple_events: events.connect(&cc.egui_ctx), - #[cfg(target_os = "macos")] - movable: None, frames: 0, log_errors_after_startup: device, session: app_session, @@ -710,6 +711,9 @@ mod tests { assert!(!nightly.version, "a flag after the separator is a document"); assert_eq!(nightly.control_port, None); assert!(!nightly.sample); + + let direct = super::app_command(["a.dc", "b.idml"].map(std::ffi::OsString::from), true); + assert_eq!(direct.files, ["a.dc", "b.idml"]); } #[test] @@ -717,6 +721,10 @@ mod tests { let nightly = super::app_command(["--", "a.dc", "--gpu-skip=vulkan,gl"].map(std::ffi::OsString::from), true); assert_eq!(nightly.files, ["a.dc"]); assert_eq!(nightly.skip, ["vulkan", "gl"]); + + let direct = super::app_command(["a.dc", "--gpu-skip=vulkan,gl"].map(std::ffi::OsString::from), true); + assert_eq!(direct.files, ["a.dc"]); + assert_eq!(direct.skip, ["vulkan", "gl"]); } #[test] diff --git a/apps/designcraft/src/profile.rs b/apps/designcraft/src/profile.rs index 0daa79665..d0eb9fa78 100644 --- a/apps/designcraft/src/profile.rs +++ b/apps/designcraft/src/profile.rs @@ -6,21 +6,20 @@ use std::path::{Path, PathBuf}; /// A file with this name next to the executable makes the install portable: settings, logs and /// recovery data are kept in [`PORTABLE_DATA_DIR`] beside it. The Windows portable zip ships one. pub(crate) const PORTABLE_MARKER: &str = "portable.txt"; -pub(crate) const PORTABLE_DATA_DIR: &str = "DesignCraftData"; +const PORTABLE_DATA_DIR: &str = "DesignCraftData"; -/// The settings folder. A Launcher nightly profile replaces every data root at once: settings, -/// logs, GPU state and recovery all live under it, so the fence in `profile_root` covers the -/// whole of Nightly's user state (the engine's `Prefs`, `ui.json` and `recovery` included). +/// The settings folder. A nightly profile replaces every data root at once: settings, logs, GPU +/// state and recovery all live under it, so the `craft-nightly` fence covers the whole of +/// Nightly's user state (the engine's `Prefs`, `ui.json` and `recovery` included). pub fn config_dir() -> Option { - if let Some(root) = crate::launch_profile::current().root() { + if let Some(root) = craft_nightly::current_root() { return Some(root.to_path_buf()); } config_dir_with(std::env::consts::OS, |key| std::env::var_os(key), executable_dir().as_deref()) } -/// Whether `dir` exists, or can be created, and takes a new file. The nightly profile validator -/// uses this same probe (`profile_root`), so a profile is accepted only where settings can land. -pub(crate) fn ensure_writable(dir: &Path) -> std::io::Result<()> { +/// Whether `dir` exists, or can be created, and takes a new file. +fn ensure_writable(dir: &Path) -> std::io::Result<()> { std::fs::create_dir_all(dir)?; let probe = dir.join(format!(".write-test-{}", std::process::id())); let result = std::fs::OpenOptions::new().write(true).create_new(true).open(&probe).map(drop); @@ -95,7 +94,7 @@ fn executable_dir() -> Option { } pub fn recovery_dir() -> Option { - if let Some(root) = crate::launch_profile::current().root() { + if let Some(root) = craft_nightly::current_root() { // Recovery stays inside the profile, including the per-run folder's lock. return own_run(root.join("Recovery")); } diff --git a/apps/designcraft/src/profile_root.rs b/apps/designcraft/src/profile_root.rs deleted file mode 100644 index 1522d0070..000000000 --- a/apps/designcraft/src/profile_root.rs +++ /dev/null @@ -1,492 +0,0 @@ -//! App-owned nightly profile fences; no stable fallback, migration or process environment changes. - -use std::ffi::OsString; -use std::path::{Component, Path, PathBuf}; - -use crate::profile::{PORTABLE_DATA_DIR, PORTABLE_MARKER}; - -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum Platform { - Windows, - Linux, - Mac, -} - -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 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")); - } - Ok(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("DesignCraft"))) - .collect::, _>>()?; - // The MSI's per-machine folder (install-policy.wxi, ProgramFiles6432Folder) and a - // per-user install folder. A custom folder is not known here; the executable's own - // folder is fenced below. - roots.push(required_base(env, "LOCALAPPDATA")?.join("Programs").join("ArtCraft").join("DesignCraft")); - 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("DesignCraft")); - } - } - 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("designcraft"))) - .collect::, _>>()?; - roots.extend(["/usr/bin/designcraft", "/usr/local/bin/designcraft", "/opt/designcraft"].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.designcraft")); - roots - } - Platform::Mac => { - let home = required_base(env, "HOME")?; - let library = home.join("Library"); - vec![ - library.join("Application Support/DesignCraft"), - library.join("Caches/DesignCraft"), - library.join("Caches/ai.storyteller.designcraft"), - library.join("Preferences/DesignCraft.plist"), - library.join("Preferences/ai.storyteller.designcraft.plist"), - library.join("Saved Application State/ai.storyteller.designcraft.savedState"), - home.join("Applications/DesignCraft.app"), - PathBuf::from("/Applications/DesignCraft.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 (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")?; - } - Ok(()) -} - -/// Recognise the shared portable data namespace in both the supplied and resolved path. -/// This is not an inventory of arbitrary custom stable overrides or a Launcher ownership proof. -fn is_portable_layout(path: &Path, platform: Platform) -> bool { - // A folder under a portable copy belongs to that copy too. Above the chosen folder itself, a - // marker only counts beside a DesignCraft executable, so an unrelated portable.txt higher up - // (in a user folder or at a drive root) does not refuse the profile. - path.ancestors().enumerate().any(|(depth, ancestor)| { - ancestor.join(PORTABLE_MARKER).is_file() - && (depth == 0 || ["designcraft.exe", "designcraft", "DesignCraft.app"].iter().any(|exe| ancestor.join(exe).exists())) - }) || 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 probe (`profile::ensure_writable`). 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 env("DESIGNCRAFT_CONFIG_DIR").is_some_and(|v| !v.is_empty()) { - // The stable override would silently point every write at another app's data. - return Err("nightly-v1 cannot be combined with DESIGNCRAFT_CONFIG_DIR".into()); - } - // The nightly bundle's own sandbox is the one Flatpak that may reach this code: its per-app - // home is private. Any other id means a native package (or the stable bundle) started here, - // whose runtime socket namespace is not this profile's. - let foreign_sandbox = - env("FLATPAK_ID").filter(|value| !value.is_empty()).is_some_and(|id| id != designcraft_ui_egui::channel::NIGHTLY_PACKAGE_ID); - if platform != Platform::Windows && foreign_sandbox { - return Err("nightly-v1 starts only in its own Flatpak bundle, not inside another app's sandbox".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 DesignCraft installation or its DesignCraftData 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()); - } - // Existing aliases under the profile must not redirect a write outside it. - 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")?; - let mut create = std::fs::DirBuilder::new(); - create.recursive(true); - #[cfg(unix)] - { - use std::os::unix::fs::DirBuilderExt as _; - create.mode(0o700); - } - 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()); - } - private_subdirectory(&confirmed, "Recovery", "recovery 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::sync::atomic::{AtomicU64, Ordering}; - - struct Fixture { - root: PathBuf, - env: BTreeMap, - exe: PathBuf, - } - - impl Fixture { - fn new() -> Self { - static NEXT: AtomicU64 = AtomicU64::new(0); - let root = loop { - let candidate = - std::env::temp_dir().join(format!("designcraft-profile-policy-{}-{}", 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}"), - } - }; - let home = root.join("home"); - let exe = root.join("install/designcraft"); - 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 } - } - - 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()) - } - } - - impl Drop for Fixture { - fn drop(&mut self) { - // Only the directory successfully created by this fixture is owned for removal. - std::fs::remove_dir_all(&self.root).unwrap(); - } - } - - #[test] - fn every_stable_data_root_is_refused_on_every_platform() { - let fixture = Fixture::new(); - let home = fixture.home(); - let cases = [ - (Platform::Windows, fixture.root.join("roaming/DesignCraft")), - (Platform::Windows, fixture.root.join("local/DesignCraft")), - (Platform::Windows, fixture.root.join("local/Programs/ArtCraft/DesignCraft")), - (Platform::Linux, home.join(".config/designcraft")), - (Platform::Linux, home.join(".local/share/designcraft")), - (Platform::Linux, home.join(".cache/designcraft")), - (Platform::Linux, home.join(".local/state/designcraft")), - (Platform::Linux, home.join(".var/app/ai.storyteller.designcraft")), - (Platform::Linux, PathBuf::from("/opt/designcraft")), - (Platform::Mac, home.join("Library/Application Support/DesignCraft")), - (Platform::Mac, home.join("Library/Caches/DesignCraft")), - (Platform::Mac, home.join("Library/Preferences/ai.storyteller.designcraft.plist")), - (Platform::Mac, home.join("Library/Saved Application State/ai.storyteller.designcraft.savedState")), - (Platform::Mac, home.join("Applications/DesignCraft.app")), - ]; - for (platform, stable) in cases { - for candidate in [stable.clone(), stable.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(), "{platform:?} accepted {candidate:?}"); - assert!(!probed.get(), "a refused root must not be probed for writing"); - } - } - } - - #[test] - fn the_installation_folder_and_grandparent_overlaps_are_refused() { - let fixture = Fixture::new(); - let install = fixture.exe.parent().unwrap().to_path_buf(); - for platform in [Platform::Windows, Platform::Linux, Platform::Mac] { - assert!(fixture.check(platform, &install).is_err(), "the install folder itself"); - assert!(fixture.check(platform, &install.join("profile")).is_err(), "a folder inside the install"); - assert!(fixture.check(platform, &fixture.root.join("nightly")).is_ok(), "a sibling of the install is private"); - } - } - - #[test] - fn prefix_and_case_lookalikes_are_not_stable_overlaps() { - let fixture = Fixture::new(); - for platform in [Platform::Windows, Platform::Linux, Platform::Mac] { - // `DesignCraftBackups` only starts with the stable folder's name. - assert!(fixture.check(platform, &fixture.home().join("Library/Application Support/DesignCraftBackups/nightly")).is_ok()); - assert!(fixture.check(platform, &fixture.root.join("data-craft/nightly")).is_ok()); - } - // Case folding differs by platform: Windows and macOS fold, Linux does not. - let folded = fixture.root.join("roaming/designcraft"); - assert!(fixture.check(Platform::Windows, &folded).is_err()); - assert!(fixture.check(Platform::Linux, &folded).is_ok(), "a different case is a different Linux path"); - } - - #[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_MARKER), b"owned portable fixture").unwrap(); - std::fs::write(stable_data.join("ui.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("ui.json")).unwrap(), b"stable settings must not change"); - } - } - let private = fixture.root.join("DesignCraftData-backup-name/nightly"); - assert!(fixture.check(Platform::Linux, &private).is_ok(), "a merely similar name is not a portable settings component"); - } - - #[test] - fn the_stable_settings_override_and_a_flatpak_instance_are_refused() { - let fixture = Fixture::new(); - let target = fixture.root.join("nightly"); - for value in ["/somewhere/else", ""] { - let env = |key: &str| if key == "DESIGNCRAFT_CONFIG_DIR" { Some(OsString::from(value)) } else { fixture.get(key) }; - let result = validate_for(Platform::Linux, &target, env, Some(&fixture.exe), |_| Ok(())); - if value.is_empty() { - assert!(result.is_ok(), "an empty override is not a stable data redirection"); - } else { - let error = result.unwrap_err(); - assert!(error.contains("DESIGNCRAFT_CONFIG_DIR"), "{error}"); - } - } - let flatpak = |key: &str| if key == "FLATPAK_ID" { Some(OsString::from("ai.storyteller.designcraft")) } else { fixture.get(key) }; - assert!(validate_for(Platform::Linux, &target, flatpak, Some(&fixture.exe), |_| Ok(())).is_err()); - assert!(validate_for(Platform::Windows, &target, flatpak, Some(&fixture.exe), |_| Ok(())).is_ok(), "Windows has no Flatpak namespace"); - // The nightly bundle's own sandbox is private; a lookalike id is still another app's. - let nightly_bundle = - |key: &str| if key == "FLATPAK_ID" { Some(OsString::from(designcraft_ui_egui::channel::NIGHTLY_PACKAGE_ID)) } else { fixture.get(key) }; - assert!(validate_for(Platform::Linux, &target, nightly_bundle, Some(&fixture.exe), |_| Ok(())).is_ok()); - let lookalike = - |key: &str| if key == "FLATPAK_ID" { Some(OsString::from("ai.storyteller.designcraft.nightly-v1")) } else { fixture.get(key) }; - assert!(validate_for(Platform::Linux, &target, lookalike, Some(&fixture.exe), |_| Ok(())).is_err()); - } - - #[cfg(unix)] - #[test] - fn recovery_aliases_cannot_redirect_to_stable_or_outward_data() { - let fixture = Fixture::new(); - let stable = fixture.home().join(".local/share/designcraft/Recovery"); - std::fs::create_dir_all(&stable).unwrap(); - std::fs::write(stable.join("stable-autosave"), b"stable recovery bytes").unwrap(); - for target in [stable.clone(), fixture.root.to_path_buf(), fixture.root.join("Recovery/../../elsewhere")] { - let profile = fixture.root.join(format!("profile-{}", target.file_name().unwrap().to_string_lossy().replace('.', "_"))); - std::fs::create_dir_all(&profile).unwrap(); - std::os::unix::fs::symlink(&target, profile.join("Recovery")).unwrap(); - assert!(fixture.check(Platform::Linux, &profile).is_err(), "{target:?}"); - assert_eq!(std::fs::read(stable.join("stable-autosave")).unwrap(), b"stable recovery bytes"); - } - } - - #[cfg(unix)] - #[test] - fn a_created_profile_is_private_and_a_failed_write_probe_never_falls_back() { - let fixture = Fixture::new(); - let probe = fixture.root.join("profile for probe"); - let error = validate_for(Platform::Linux, &probe, |key| fixture.get(key), Some(&fixture.exe), |_| Err(std::io::Error::other("read-only"))) - .unwrap_err(); - assert!(error.contains("not writable"), "{error}"); - use std::os::unix::fs::PermissionsExt; - assert_eq!(std::fs::metadata(&probe).unwrap().permissions().mode() & 0o777, 0o700); - } - - #[test] - fn relative_and_parent_traversing_are_refused_and_link_ancestors_are_resolved() { - let fixture = Fixture::new(); - for candidate in [PathBuf::from("relative/nightly"), fixture.root.join("a/../nightly")] { - assert!(fixture.check(Platform::Linux, &candidate).is_err(), "{candidate:?}"); - } - #[cfg(unix)] - { - let elsewhere = fixture.root.join("elsewhere"); - std::fs::create_dir_all(&elsewhere).unwrap(); - std::os::unix::fs::symlink(&elsewhere, fixture.root.join("linked")).unwrap(); - // `canonical_future` resolves the existing ancestors before anything is created, so a - // root reached through a link is validated and created at the link's real location. - // That location is what the fence checks, and it is where every write then lands. - let resolved = fixture.check(Platform::Linux, &fixture.root.join("linked/nightly")).unwrap(); - assert_eq!(resolved, std::fs::canonicalize(elsewhere.join("nightly")).unwrap()); - assert!(resolved.is_dir()); - assert_eq!(std::fs::canonicalize(fixture.root.join("linked")).unwrap(), elsewhere); - } - } - - #[test] - fn a_valid_profile_is_returned_resolved_and_created() { - let fixture = Fixture::new(); - let chosen = fixture.root.join("launcher data/profiles/designcraft"); - let resolved = fixture.check(Platform::Linux, &chosen).unwrap(); - assert_eq!(resolved, std::fs::canonicalize(&chosen).unwrap()); - assert!(resolved.is_dir()); - } -} diff --git a/crates/compose/Cargo.toml b/crates/compose/Cargo.toml index 9f1f7dd39..48116b1fe 100644 --- a/crates/compose/Cargo.toml +++ b/crates/compose/Cargo.toml @@ -21,7 +21,7 @@ log = { workspace = true } regex = { workspace = true } fancy-regex = { workspace = true } miniz_oxide = "0.8" -hypher = { version = "0.1.8", default-features = false, features = ["alloc", "croatian", "dutch", "french", "german", "greek", "italian", "portuguese", "spanish", "norwegian", "danish"] } +hypher = { version = "0.1.8", default-features = false, features = ["alloc", "croatian", "dutch", "french", "german", "greek", "italian", "portuguese", "spanish", "norwegian", "danish", "hindi", "marathi", "bengali", "assamese", "gujarati", "panjabi", "oriya", "tamil", "telugu", "kannada", "malayalam"] } [dev-dependencies] designcraft-fonts = { workspace = true, features = ["testing"] } diff --git a/crates/compose/src/breaker.rs b/crates/compose/src/breaker.rs index bd9351119..5d4a0f465 100644 --- a/crates/compose/src/breaker.rs +++ b/crates/compose/src/breaker.rs @@ -1,6 +1,7 @@ //! Line breaking: the paragraph composer (Knuth–Plass total fit), the single-line composer //! (greedy first fit) and balanced ragged lines. All work on a paragraph's glyphs and a per-line -//! measure function. +//! measure function. Where a breaker needs source text, pass the full story because glyph byte +//! offsets are story-relative. //! //! Justification uses *prioritised* elastic material (plan: typography §5.2): word spaces first, //! then letter spacing (every glyph gets elastic width from the paragraph's letter-spacing range), @@ -360,13 +361,50 @@ fn right_hang(g: &Glyph, sp: &Spacing) -> f64 { g.cjk_hang.max(hang_right(g, sp)) - g.moji.end } +/// May a line break after the dot at glyph `i`, as in a web address? It takes three letters right +/// before the dot and two right after it, so that abbreviations ("e.g.", "U.S.A.", "Ph.D.") and +/// decimals stay whole. +pub(super) fn dot_break(text: &str, glyphs: &[Glyph], i: usize) -> bool { + let dot = &glyphs[i]; + if dot.ch != '.' || dot.generated_text.is_some() || dot.list_label || glyphs.get(i + 1).is_some_and(|next| next.byte == dot.byte) { + return false; + } + // Only the first glyph owns the source bytes. Generated glyphs stop the letter run. + let owns_text = |g: &&Glyph| g.len > 0 || g.generated_text.is_some() || g.list_label; + let source = |g: &Glyph| { + if g.generated_text.is_some() || g.list_label { + return None; + } + text.get(g.byte..g.byte.checked_add(g.len)?) + }; + let before = glyphs[..i].iter().rev().skip_while(|g| g.byte == dot.byte).filter(owns_text).map_while(source).flat_map(|s| s.chars().rev()); + let after = glyphs[i + 1..].iter().filter(owns_text).map_while(source).flat_map(str::chars); + has_dot_letters(before, 3) && has_dot_letters(after, 2) +} + +fn has_dot_letters(chars: impl Iterator, minimum: usize) -> bool { + // Some combining marks have the Unicode Alphabetic property as well. + static MARK: std::sync::LazyLock> = std::sync::LazyLock::new(|| regex::Regex::new(r"\A\p{M}\z").ok()); + let Some(mark) = MARK.as_ref() else { return false }; + chars + .filter(|&c| c.is_ascii() || !mark.is_match(c.encode_utf8(&mut [0; 4]))) + .take_while(|&c| c.is_alphabetic() && !is_cjk(c)) + .take(minimum) + .count() + == minimum +} + /// The part of a hyphen after `g` (of width `hw`) that hangs past the line's end. fn hyphen_hang(g: &Glyph, hw: f64, sp: &Spacing) -> f64 { if sp.optical { hw * hang('-').1 * optical_scale(g, sp) } else { 0.0 } } -/// Advance of the hyphen glyph that would follow `g` (cached per face). +/// Advance of the hyphen glyph that would follow `g` (cached per face); none after a letter of +/// an Indian script, whose broken words take no hyphen ([`crate::shape::breaks_without_hyphen`]). fn hyphen_width(g: &Glyph, cache: &mut Vec<(u32, f64)>) -> f64 { + if crate::shape::breaks_without_hyphen(g) { + return 0.0; + } let id = g.face.id(); let units = match cache.iter().find(|c| c.0 == id) { Some(c) => c.1, @@ -398,7 +436,7 @@ fn push_inword(it: &mut Vec, ig: &mut Vec, p: Item, g: usize, sp: & /// Build Knuth items. `item_glyph[k]` = glyph index of item k (penalties: the glyph *before* which the break happens). /// `emergency_after[i]` allows an emergency break after glyph `i` (see [`overlong_words`]). -fn items(glyphs: &[Glyph], hyph_after: &[bool], emergency_after: &[bool], sp: &Spacing) -> (Vec, Vec) { +fn items(text: &str, glyphs: &[Glyph], hyph_after: &[bool], emergency_after: &[bool], sp: &Spacing) -> (Vec, Vec) { let mut it: Vec = Vec::with_capacity(glyphs.len() * 2 + 2); let mut ig = Vec::with_capacity(glyphs.len() * 2 + 2); let n = glyphs.len(); @@ -487,7 +525,10 @@ fn items(glyphs: &[Glyph], hyph_after: &[bool], emergency_after: &[bool], sp: &S p.hang = right_hang(g, sp); p.edge_elastic = crate::mojikumi::end_elastic(g, sp.justify, !sp.push_out_only()); push_inword(&mut it, &mut ig, p, i + 1, sp); - } else if matches!(g.ch, '\u{2013}' | '\u{2014}' | '/') || g.break_after.unwrap_or_else(|| cjk_break(g, &glyphs[i + 1], sp)) { + } else if matches!(g.ch, '\u{2013}' | '\u{2014}' | '/') + || dot_break(text, glyphs, i) + || g.break_after.unwrap_or_else(|| cjk_break(g, &glyphs[i + 1], sp)) + { let mut p = Item::penalty(0.0, 0.0, false); p.hang = right_hang(g, sp); p.edge_elastic = crate::mojikumi::end_elastic(g, sp.justify, !sp.push_out_only()); @@ -535,17 +576,17 @@ struct Node { } /// Knuth–Plass total-fit line breaking. `width(line)` gives each line's measure. -pub fn knuth_plass(glyphs: &[Glyph], hyph_after: &[bool], sp: &Spacing, width: &dyn Fn(usize) -> f64) -> Vec { +pub fn knuth_plass(text: &str, glyphs: &[Glyph], hyph_after: &[bool], sp: &Spacing, width: &dyn Fn(usize) -> f64) -> Vec { if glyphs.is_empty() { return vec![Break { start: 0, end: 0, next: 0, hyphen: false, forced: true }]; } - let (mut items, mut ig) = items(glyphs, hyph_after, &[], sp); + let (mut items, mut ig) = items(text, glyphs, hyph_after, &[], sp); // A word gets emergency breaks only when no line could hold it: beside a wrap object some // lines are slivers much narrower than the measure, and a word that fits a full line goes // there instead of being split. let widest = (0..=glyphs.len().min(64)).map(width).fold(1.0, f64::max); if let Some(emergency_after) = overlong_words(&items, &ig, glyphs, widest) { - (items, ig) = self::items(glyphs, hyph_after, &emergency_after, sp); + (items, ig) = self::items(text, glyphs, hyph_after, &emergency_after, sp); } for tolerance in [2.5, 12.0, f64::INFINITY] { if let Some(b) = @@ -554,15 +595,15 @@ pub fn knuth_plass(glyphs: &[Glyph], hyph_after: &[bool], sp: &Spacing, width: & return b; } } - greedy(glyphs, hyph_after, sp, width, &|_, _, _| 0.0) + greedy(text, glyphs, hyph_after, sp, width, &|_, _, _| 0.0) } /// Width of the first word of `glyphs` after any leading spaces, fully shrunk (the boxes up to /// the first break opportunity, emergency breaks aside, and the hyphen a break there adds). -pub fn first_word_width(glyphs: &[Glyph], hyph_after: &[bool], sp: &Spacing) -> f64 { +pub fn first_word_width(text: &str, glyphs: &[Glyph], hyph_after: &[bool], sp: &Spacing) -> f64 { // A word this long is wider than any line; the rest of the paragraph doesn't matter. let n = glyphs.len().min(256); - let (items, _) = items(glyphs.get(..n).unwrap_or(glyphs), hyph_after.get(..n).unwrap_or(hyph_after), &[], sp); + let (items, _) = items(text, glyphs.get(..n).unwrap_or(glyphs), hyph_after.get(..n).unwrap_or(hyph_after), &[], sp); let mut w = 0.0; let mut started = false; for it in &items { @@ -887,9 +928,12 @@ fn breaks_from_positions(items: &[Item], ig: &[usize], glyphs: &[Glyph], chain: let (end, hyphen, forced) = match it.kind { Kind::Penalty => { let e = ig[b].min(n); - // A flagged penalty with width = an inserted hyphen (not an explicit '-'). + // A flagged penalty with width = an inserted hyphen (not an explicit '-'). A + // hyphenation point after a letter of an Indian script inserts one of no width + // (no hyphen is drawn there) but is still a hyphenated break: `auto` tells it from + // the break after an explicit '-'. let explicit = e > 0 && matches!(glyphs[e - 1].ch, '-' | '\u{2010}'); - (e, it.flagged && it.w > 0.0 && !explicit || (it.flagged && e > 0 && glyphs[e - 1].ch == SOFT_HYPHEN), it.p <= -INF) + (e, it.flagged && (it.w > 0.0 || it.auto) && !explicit || (it.flagged && e > 0 && glyphs[e - 1].ch == SOFT_HYPHEN), it.p <= -INF) } Kind::Glue | Kind::Box => (ig[b], false, false), }; @@ -929,6 +973,7 @@ fn emergency_split(glyphs: &[Glyph], start: usize, i: usize) -> usize { /// `tab(line, x, i)` is the advance of the tab glyph `i` when it starts `x` from the start of /// line `line`: tabs have no width until they reach their stop, which depends on where they sit. pub fn greedy( + text: &str, glyphs: &[Glyph], hyph_after: &[bool], sp: &Spacing, @@ -954,8 +999,14 @@ pub fn greedy( let mut last_space: Option<(usize, f64)> = None; // (break position, line width there) let mut i = start; let mut brk: Option<(usize, bool, bool)> = None; + // The last glyph before `i` that is not a soft hyphen, kept as `i` advances. + let mut plain = glyphs[..start].iter().rposition(|p| p.ch != SOFT_HYPHEN); while i < n { let g = &glyphs[i]; + let before = plain; + if g.ch != SOFT_HYPHEN { + plain = Some(i); + } if is_forced(g.ch) { brk = Some((i + 1, false, true)); break; @@ -1005,13 +1056,18 @@ pub fn greedy( if i + 1 < n && !glyphs[i + 1].is_space() && !g.no_break && g.break_after != Some(false) { if g.ch == SOFT_HYPHEN { if may_hyphenate(hyphens) { - let hw = hyphen_width(g, &mut hy_cache); + // Line layout draws the hyphen after `line.last()`, this soft hyphen, in its + // face and size, so it is measured with it. None is drawn after a word of + // an Indian script (the letter before the soft hyphens). + let indic = before.is_some_and(|b| crate::shape::breaks_without_hyphen(&glyphs[b])); + let hw = if indic { 0.0 } else { hyphen_width(g, &mut hy_cache) }; let hy = (hw - hyphen_hang(g, hw, sp)).max(0.0); if x + hy <= w + shrink + FIT_EPS { last_ok = Some((i + 1, true)); } } } else if matches!(g.ch, '-' | '\u{2010}' | '\u{2013}' | '\u{2014}' | '/') + || dot_break(text, glyphs, i) || g.break_after.unwrap_or_else(|| cjk_break(g, &glyphs[i + 1], sp)) { last_ok = Some((i + 1, false)); @@ -1064,15 +1120,15 @@ pub fn line_width(glyphs: &[Glyph], b: &Break) -> f64 { /// Balance Ragged Lines: keep the composer's line count but make the lines as even as possible, /// by composing against the narrowest measure that still yields that many lines. -pub fn balanced(glyphs: &[Glyph], hyph_after: &[bool], sp: &Spacing, width: &dyn Fn(usize) -> f64) -> Vec { - let base = knuth_plass(glyphs, hyph_after, sp, width); +pub fn balanced(text: &str, glyphs: &[Glyph], hyph_after: &[bool], sp: &Spacing, width: &dyn Fn(usize) -> f64) -> Vec { + let base = knuth_plass(text, glyphs, hyph_after, sp, width); let n = base.len(); if n < 2 || glyphs.len() > 3000 || base[..n - 1].iter().any(|b| b.forced) { return base; } let ok = |f: f64| -> Option> { let w = |j: usize| width(j) * f; - let br = knuth_plass(glyphs, hyph_after, sp, &w); + let br = knuth_plass(text, glyphs, hyph_after, sp, &w); (br.len() == n && br.iter().enumerate().all(|(j, b)| line_width(glyphs, b) <= w(j) + 0.01)).then_some(br) }; let (mut lo, mut hi) = (0.3, 1.0); diff --git a/crates/compose/src/cache.rs b/crates/compose/src/cache.rs index 5c662028e..f1c8aff28 100644 --- a/crates/compose/src/cache.rs +++ b/crates/compose/src/cache.rs @@ -114,6 +114,7 @@ fn doc_signature(doc: &Document) -> u64 { (Arc::as_ptr(sp) as usize).hash(&mut h); } (Arc::as_ptr(&doc.styles) as usize).hash(&mut h); + doc.title.hash(&mut h); format!("{:?}", doc.text_variables).hash(&mut h); sections_hash(doc).hash(&mut h); // The compositions the indexes are built from also depend on these (see `signature`). @@ -169,6 +170,15 @@ fn numbering_signature(starts: &NumberStarts, story: &Story) -> Vec { sig } +/// Document-level state a story's text variables depend on. +fn vars_signature(doc: &Document) -> usize { + use std::hash::{Hash, Hasher}; + let mut h = std::collections::hash_map::DefaultHasher::new(); + format!("{:?}", doc.text_variables).hash(&mut h); + doc.title.hash(&mut h); + h.finish() as usize +} + /// Everything page names and section markers are made from. fn sections_hash(doc: &Document) -> u64 { use std::hash::{Hash, Hasher}; @@ -255,6 +265,9 @@ impl Cache { if let Some(starts) = &starts { sig.push(hash_of(&numbering_signature(starts, ns))); } + if crate::vars::has_vars(ns) { + sig.extend([doc.page_count(), vars_signature(doc)]); + } keep_items.extend(k.into_iter().filter(|it| kept.insert(Arc::as_ptr(it)))); keep_stories.push(ns.clone()); } @@ -302,12 +315,9 @@ impl Cache { let with_vars = crate::vars::has_vars(story); let running = with_vars && crate::vars::has_running(doc, story); if with_vars { - // Variables depend on the page count, sections and definitions (and running headers on - // the whole document). - use std::hash::{Hash, Hasher}; - let mut h = std::collections::hash_map::DefaultHasher::new(); - format!("{:?}", doc.text_variables).hash(&mut h); - sig.extend([doc.page_count(), h.finish() as usize]); + // Variables depend on the page count, title, sections and definitions (and running + // headers on the whole document). + sig.extend([doc.page_count(), vars_signature(doc)]); if running { sig.push(doc_signature(doc) as usize); } diff --git a/crates/compose/src/hyphen.rs b/crates/compose/src/hyphen.rs index 25f76097f..8046573f2 100644 --- a/crates/compose/src/hyphen.rs +++ b/crates/compose/src/hyphen.rs @@ -10,6 +10,10 @@ //! Flipo, Bernard Gaulle, Arthur Reutenauer), MIT; Italian is `hyph-it.tex` 4.9 from hyph-utf8 //! (Claudio Beccari), LPPL or MIT, taken under MIT. A word with an elision (`l'imprimerie`) //! hyphenates after its apostrophe. +//! Hindi, Marathi, Bengali, Assamese, Gujarati, Punjabi, Odia, Tamil, Telugu, Kannada and +//! Malayalam are Santhosh Thottingal's `hyph-{hi,mr,bn,as,gu,pa,or,ta,te,kn,ml}.tex` 0.9.0 from +//! hyph-utf8, MIT. Viramas, nuktas and the zero-width (non-)joiner count as word characters +//! ([`is_indic_joiner`]), so a word is not split at its conjuncts. //! German uses `hyph-de-1996.tex` (2024-02-28, Deutschsprachige Trennmustermannschaft, MIT): //! despite the filename, these are the reformed 2006 spelling patterns. Only the two 2006 reform //! names and German locale codes without a reform year or with 2006 use this set. Traditional, @@ -138,7 +142,21 @@ fn is_apostrophe(c: char) -> bool { } fn is_word_char(c: char) -> bool { - c.is_alphabetic() || is_apostrophe(c) + c.is_alphabetic() || is_apostrophe(c) || is_indic_joiner(c) +} + +/// Signs inside Indic words that Unicode doesn't class as alphabetic: each script's virama (which +/// joins consonants into conjuncts), its nukta, Malayalam's vertical and circular viramas, and the +/// zero-width joiner and non-joiner that select conjunct and chillu forms. Without them a word +/// such as विद्यार्थी splits at every conjunct into fragments too short to hyphenate. +fn is_indic_joiner(c: char) -> bool { + matches!( + c, + '\u{094D}' | '\u{09CD}' | '\u{0A4D}' | '\u{0ACD}' | '\u{0B4D}' | '\u{0BCD}' | '\u{0C4D}' | '\u{0CCD}' | '\u{0D4D}' // viramas + | '\u{0D3B}' | '\u{0D3C}' // Malayalam vertical and circular viramas + | '\u{093C}' | '\u{09BC}' | '\u{0A3C}' | '\u{0ABC}' | '\u{0B3C}' | '\u{0C3C}' | '\u{0CBC}' // nuktas + | '\u{200C}' | '\u{200D}' // ZWNJ, ZWJ + ) } /// Unrestricted break points of one lowercase core (letters and `'` only, no leading/trailing `'`). @@ -821,6 +839,64 @@ mod tests { } } + #[test] + fn indic_languages_use_the_hyph_utf8_patterns() { + for (name, code, lang) in [ + ("Hindi", "hi", hypher::Lang::Hindi), + ("Marathi", "mr", hypher::Lang::Marathi), + ("Bengali", "bn", hypher::Lang::Bengali), + ("Assamese", "as", hypher::Lang::Assamese), + ("Gujarati", "gu", hypher::Lang::Gujarati), + ("Punjabi", "pa", hypher::Lang::Panjabi), + ("Odia", "or", hypher::Lang::Oriya), + ("Oriya", "or_IN", hypher::Lang::Oriya), + ("Tamil", "ta", hypher::Lang::Tamil), + ("Telugu", "te", hypher::Lang::Telugu), + ("Kannada", "kn", hypher::Lang::Kannada), + ("Malayalam", "ml_IN", hypher::Lang::Malayalam), + ] { + assert_eq!(Lang::for_language(name), Some(Lang::Patterns(lang)), "{name}"); + assert_eq!(Lang::for_language(code), Some(Lang::Patterns(lang)), "{code}"); + } + assert_eq!(Lang::for_language("Sanskrit"), None, "no Sanskrit patterns are built in"); + } + + /// A virama joins consonants inside a word: the word is hyphenated whole, between syllables, + /// never inside a conjunct. Before viramas counted as word characters, विद्यार्थी was + /// hyphenated as the fragments वि, द, यार and थी, which gave it no break at all. + #[test] + fn indic_words_hyphenate_between_syllables_across_their_conjuncts() { + let lang = |name: &str| Lang::for_language(name).unwrap(); + assert_eq!(marked("विद्यार्थी", lang("Hindi")), "वि-द्या-र्थी"); + assert_eq!(marked("प्रधानमंत्री", lang("Hindi")), "प्र-धा-न-मं-त्री"); + assert_eq!(marked("महाराष्ट्र", lang("Marathi")), "महा-रा-ष्ट्र"); + assert_eq!(marked("വിദ്യാർത്ഥി", lang("Malayalam")), "വി-ദ്യാർ-ത്ഥി"); + assert_eq!(marked("തിരുവനന്തപുരം", lang("Malayalam")), "തി-രു-വ-ന-ന്ത-പു-രം"); + assert_eq!(marked("தொழில்நுட்பம்", lang("Tamil")), "தொ-ழில்-நுட்-பம்"); + // The default Before Last limit keeps the final য় with the ল before it. + assert_eq!(marked("বিশ্ববিদ্যালয়", lang("Bengali")), "বি-শ্ব-বি-দ্যা-লয়"); + assert_eq!(marked("విశ్వవిద్యాలయం", lang("Telugu")), "వి-శ్వ-వి-ద్యా-ల-యం"); + assert_eq!(marked("ವಿಶ್ವವಿದ್ಯಾಲಯ", lang("Kannada")), "ವಿ-ಶ್ವ-ವಿ-ದ್ಯಾ-ಲಯ"); + assert_eq!(marked("વિશ્વવિદ્યાલય", lang("Gujarati")), "વિ-શ્વ-વિ-દ્યા-લય"); + } + + /// A zero-width joiner or non-joiner (old-style Malayalam chillus, explicit half forms) and a + /// nukta stay inside the word they're in, so no break lands next to them. + #[test] + fn indic_joiners_and_nuktas_do_not_split_words() { + for c in ['\u{094D}', '\u{0D4D}', '\u{0BCD}', '\u{093C}', '\u{200C}', '\u{200D}'] { + assert!(is_word_char(c), "U+{:04X}", c as u32); + } + let hi = Lang::for_language("Hindi").unwrap(); + let (pts, _) = word_breaks_in("पढ़ना", hi); + assert!(!pts.contains(&2), "no break between ढ and its nukta: {pts:?}"); + assert!(pts.contains(&3), "पढ़-ना: {pts:?}"); + // Old chillu encoding (ന + virama + ZWJ): the word stays one word. + let ml = Lang::for_language("Malayalam").unwrap(); + let (pts, _) = word_breaks_in("അവന്\u{200D}റെ", ml); + assert!(pts.iter().all(|&p| !matches!("അവന്\u{200D}റെ".chars().nth(p), Some('\u{200D}' | '\u{0D4D}'))), "{pts:?}"); + } + #[test] fn norwegian_uses_the_hyph_no_patterns() { let nb = Lang::for_language("Norwegian: Bokmål").unwrap(); diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index df1736750..3802eb0c2 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -1749,11 +1749,11 @@ fn apply_nested_line_styles(input: NestedLineStyleInput<'_, '_, '_>) { let ind = pp.left_indent + if j == 0 { pp.first_line_indent } else { 0.0 }; tab_advance(&pp.tabs, pp.left_indent, ind + x, gl.get(i + 1..).unwrap_or_default()).0 }; - breaker::greedy(&gl, &hy, &spacing, &width, &tab) + breaker::greedy(&story.text, &gl, &hy, &spacing, &width, &tab) } else if pp.balance_ragged && !spacing.justify { - breaker::balanced(&gl, &hy, &spacing, &width) + breaker::balanced(&story.text, &gl, &hy, &spacing, &width) } else { - breaker::knuth_plass(&gl, &hy, &spacing, &width) + breaker::knuth_plass(&story.text, &gl, &hy, &spacing, &width) }; // Byte where line `k` starts (the paragraph end past the last line). let byte_at = @@ -1832,6 +1832,7 @@ struct ParagraphLines<'a> { drop_cap: Option<&'a DropCap>, base_chars: &'a designcraft_doc::CharProps, mark_chars: &'a designcraft_doc::CharProps, + mark_em: &'a MarkEm, mark_leading: f64, base_leading: f64, last_line_mark: Option, @@ -1856,6 +1857,7 @@ enum LinePlacement { } struct PositionLineInput<'a, 'font> { + text: &'a str, frame: &'a FrameSpec, column: Rect, glyphs: &'a [Glyph], @@ -1886,6 +1888,7 @@ struct PositionLineInput<'a, 'font> { db: &'a ScopedFonts<'font>, mark_leading: f64, mark_chars: &'a designcraft_doc::CharProps, + mark_em: &'a MarkEm, last_line_mark: Option, } @@ -1899,6 +1902,7 @@ struct LinePosition { fn position_line(input: PositionLineInput<'_, '_>) -> LinePosition { let PositionLineInput { + text, frame: f, column: col, glyphs, @@ -1929,6 +1933,7 @@ fn position_line(input: PositionLineInput<'_, '_>) -> LinePosition { db, mark_leading, mark_chars, + mark_em, last_line_mark, } = input; let (mut x0, mut x1) = (col.x0, col.x1); @@ -1936,7 +1941,7 @@ fn position_line(input: PositionLineInput<'_, '_>) -> LinePosition { let need = if f.exclusions.is_empty() && f.outline.is_none() { 0.0 } else { - let w = breaker::first_word_width(glyphs.get(s..).unwrap_or_default(), hyph_after.get(s..).unwrap_or_default(), spacing); + let w = breaker::first_word_width(text, glyphs.get(s..).unwrap_or_default(), hyph_after.get(s..).unwrap_or_default(), spacing); if w > col.width() - ind { 0.0 } else { w } }; let holds = |&(a, b): &(f64, f64)| b - a - ind + 0.01 >= need; @@ -1981,7 +1986,7 @@ fn position_line(input: PositionLineInput<'_, '_>) -> LinePosition { Some(mark) if j + 1 == breaks.len() => next_lead.max(mark), _ => next_lead, }; - let (next_reference, next_model) = cjk_line_reference(next_glyphs); + let (next_reference, next_model) = line_reference(next_glyphs, mark_em, pp, f.vertical); down += prev_aki.unwrap_or(next_lead) + prev - next_reference; prev = next_reference; prev_aki = aki_below(next_model, next_lead); @@ -2036,6 +2041,7 @@ fn position_line(input: PositionLineInput<'_, '_>) -> LinePosition { } struct BreakInput<'a> { + text: &'a str, glyphs: &'a [Glyph], hyphens: &'a [bool], props: &'a designcraft_doc::ParaProps, @@ -2050,7 +2056,7 @@ struct BreakInput<'a> { } fn choose_paragraph_breaks(input: BreakInput<'_>) -> Vec { - let BreakInput { glyphs, hyphens, props: pp, slots, column: col, drop_cap, line_no, col_first_line, rtl, has_tabs, spacing } = input; + let BreakInput { text, glyphs, hyphens, props: pp, slots, column: col, drop_cap, line_no, col_first_line, rtl, has_tabs, spacing } = input; let width = |j: usize| -> f64 { let (x0, x1) = slots.get(j).copied().unwrap_or((col.x0, col.x1)); let indent = pp.left_indent @@ -2079,11 +2085,11 @@ fn choose_paragraph_breaks(input: BreakInput<'_>) -> Vec { }; tab_advance(&pp.tabs, pp.left_indent, x0 + indent + x - col.x0, glyphs.get(i + 1..).unwrap_or_default()).0 }; - breaker::greedy(glyphs, hyphens, spacing, &width, &tab) + breaker::greedy(text, glyphs, hyphens, spacing, &width, &tab) } else if pp.balance_ragged && !spacing.justify { - breaker::balanced(glyphs, hyphens, spacing, &width) + breaker::balanced(text, glyphs, hyphens, spacing, &width) } else { - breaker::knuth_plass(glyphs, hyphens, spacing, &width) + breaker::knuth_plass(text, glyphs, hyphens, spacing, &width) } } @@ -2395,6 +2401,7 @@ fn place_paragraph_lines(shared: PlacementShared<'_, '_>, paragraph: ParagraphLi drop_cap, base_chars, mark_chars, + mark_em, mark_leading, base_leading, last_line_mark, @@ -2479,6 +2486,7 @@ fn place_paragraph_lines(shared: PlacementShared<'_, '_>, paragraph: ParagraphLi let est_jump = cur.jump(f, base_leading, est_asc, est_tops); let slots = estimate_slots(f, col, est_first, est_jump, base_leading, base_chars.size, est_band, &glyphs[g0..], rtl, &carry); let breaks = choose_paragraph_breaks(BreakInput { + text: &story.text, glyphs: &glyphs[g0..], hyphens: &hyph_after[g0..], props: pp, @@ -2502,9 +2510,10 @@ fn place_paragraph_lines(shared: PlacementShared<'_, '_>, paragraph: ParagraphLi Some(m) if k + 1 == breaks.len() => lead.max(m), _ => lead, }; - let (reference, model) = cjk_line_reference(line_glyphs); + let (reference, model) = line_reference(line_glyphs, mark_em, pp, f.vertical); let advance = if cur.last_baseline.is_some() { cur.aki_below.unwrap_or(lead) } else { lead }; let position = position_line(PositionLineInput { + text: &story.text, frame: f, column: col, glyphs, @@ -2535,6 +2544,7 @@ fn place_paragraph_lines(shared: PlacementShared<'_, '_>, paragraph: ParagraphLi db, mark_leading, mark_chars, + mark_em, last_line_mark, }); let LinePosition { x0, x1, baseline, grid_end, continues } = position; @@ -2717,8 +2727,13 @@ fn place_paragraph_lines(shared: PlacementShared<'_, '_>, paragraph: ParagraphLi cur.last_descent = desc; cur.pending = 0.0; cur.grid_next = grid_end.map(|end| (baseline, end)); - hyphen_at = - e.checked_sub(1).filter(|&i| b.hyphen && hyph_after.get(i) == Some(&true)).and_then(|i| glyphs.get(i)).map(|g| g.byte + g.len); + // The end of the cluster that owns the break glyph (a glyph without bytes of its own is + // part of the cluster before it), which is what `suppress_hyphens` compares against. + hyphen_at = e + .checked_sub(1) + .filter(|&i| b.hyphen && hyph_after.get(i) == Some(&true)) + .and_then(|i| glyphs.get(..=i)?.iter().rev().find(|g| g.len > 0)) + .map(|g| g.byte + g.len); line_no += 1; // An Indent to Here character in this line moves the start of the lines after it: // break them again with that indent (it holds into the next columns too). @@ -2788,6 +2803,7 @@ struct ShapedParagraph { base_size: f64, spacing: Spacing, mark_chars: designcraft_doc::CharProps, + mark_em: MarkEm, mark_leading: f64, last_line_mark: Option, para_box: Option, @@ -2989,8 +3005,19 @@ fn shape_paragraph(input: ParagraphShapeInput<'_, '_>) -> ShapedParagraph { suppress_hyphens(&mut hyph_after, &glyphs, suppressed_hyphens); let base_size = base_chars.size; let spacing = spacing_for(pp, base_size, story, cjk); - // An empty paragraph takes its height from its paragraph mark's character format. - let mark_chars = if glyphs.is_empty() { doc.styles.resolve_char(base_chars, story.char_format_of(prange.start)) } else { base_chars.clone() }; + // An empty line takes its height from its paragraph mark's character format, the one character + // it holds: an empty paragraph's line, the line left once a drop cap that is the whole + // paragraph is split off, and the line a trailing forced line break leaves. + let mark_chars = if glyphs.is_empty() || glyphs.last().is_some_and(|g| g.ch == designcraft_doc::story::FORCED_LINE_BREAK) { + doc.styles.resolve_char(base_chars, story.char_format_of(prange.end)) + } else { + base_chars.clone() + }; + let mark_em = { + let mark = story.text.get(prange.end..).and_then(|t| t.chars().next()).unwrap_or('\n'); + let (face, height) = shape::em_face(db, &doc.styles, &mark_chars, mark, &doc.settings.advanced_type); + MarkEm { face, height, model: mark_chars.leading_model } + }; let mark_leading = match mark_chars.leading { designcraft_doc::Leading::Auto => mark_chars.size * pp.auto_leading, designcraft_doc::Leading::Points(v) => v, @@ -3022,6 +3049,7 @@ fn shape_paragraph(input: ParagraphShapeInput<'_, '_>) -> ShapedParagraph { base_size, spacing, mark_chars, + mark_em, mark_leading, last_line_mark, para_box, @@ -3472,6 +3500,7 @@ fn compose_run( base_size, spacing, mark_chars, + mark_em, mark_leading, last_line_mark, para_box: _, @@ -3641,6 +3670,7 @@ fn compose_run( drop_cap: drop_cap.as_ref(), base_chars: &base_chars, mark_chars: &mark_chars, + mark_em: &mark_em, mark_leading, base_leading, last_line_mark, @@ -4114,6 +4144,7 @@ fn apply_desired_spacing(glyphs: &mut [Glyph], pp: &ParaProps) { g.adv += g.space * (ws - 1.0); } else if !g.is_space() && g.adv > 0.0 { g.adv = g.adv * gs + ls * g.space; + g.track *= gs; g.sx *= gs; g.dx *= gs; } @@ -4754,8 +4785,12 @@ fn em_box_top(face: &designcraft_fonts::FontFace, size: f64) -> f64 { /// Em box relative to the baseline. Font ascender/descender proportions locate it; /// the box's total extent is the em, rather than the font's optional line gap. fn cjk_em_box(g: &Glyph) -> (f64, f64) { - let height = g.face.units_per_em() * g.sy.abs(); - let top = -height * g.ascent / (g.ascent + g.descent).max(1e-9); + em_box(g.face.units_per_em() * g.sy.abs(), g.ascent, g.descent) +} +/// An em box `height` tall relative to the baseline, placed by the font's `ascent` and `descent` +/// proportions (see [`cjk_em_box`]). +fn em_box(height: f64, ascent: f64, descent: f64) -> (f64, f64) { + let top = -height * ascent / (ascent + descent).max(1e-9); (top, top + height) } /// The ideographic character face (ICF) box relative to the baseline: the em box of @@ -4797,16 +4832,53 @@ fn cjk_alignment_shift(g: &Glyph, reference: &Glyph) -> f64 { fn cjk_line_reference(line: &[Glyph]) -> (f64, designcraft_doc::cjk::LeadingModel) { use designcraft_doc::cjk::LeadingModel as L; let Some(g) = line.iter().max_by(|a, b| a.size.total_cmp(&b.size)) else { return (0.0, L::Roman) }; - let (top, bottom) = cjk_em_box(g); - let reference = match g.leading_model { + (leading_reference(g.leading_model, cjk_em_box(g)), g.leading_model) +} + +/// The paragraph mark's em box, which an empty line measures leading from: the face and em box +/// height the mark is shaped with (a composite font's entry, a superscript or subscript at its +/// Advanced Type size; see [`shape::em_face`]) and its leading model. +struct MarkEm { + face: std::sync::Arc, + height: f64, + model: designcraft_doc::cjk::LeadingModel, +} + +/// [`cjk_line_reference`] of a line of paragraph `pp`. An empty line (an empty paragraph, or the +/// line a trailing forced line break leaves) has no character to measure from: it measures from +/// its paragraph mark's em box under the mark's leading model (`mark`), as in InDesign, so it +/// keeps the leading like any other line instead of moving by the em box's offset from the +/// baseline. In `vertical` text that is the upright em box, as for the upright characters around +/// it. Only the Japanese composers use a leading model. +fn line_reference(line: &[Glyph], mark: &MarkEm, pp: &ParaProps, vertical: bool) -> (f64, designcraft_doc::cjk::LeadingModel) { + use designcraft_doc::cjk::LeadingModel as L; + if !line.is_empty() { + return cjk_line_reference(line); + } + if !pp.composer.japanese() || mark.model == L::Roman { + return (0.0, L::Roman); + } + // Placed by the proportions the shaper gives the glyphs: upright ones fill the em box. + let (ascent, descent) = if vertical { + let (top, bottom) = mark.face.em_box(); + (top, -bottom) + } else { + (mark.face.ascent, mark.face.descent) + }; + (leading_reference(mark.model, em_box(mark.height, ascent, descent)), mark.model) +} + +/// Where `model` measures leading from, for an em box at `top..bottom` from the baseline. +fn leading_reference(model: designcraft_doc::cjk::LeadingModel, (top, bottom): (f64, f64)) -> f64 { + use designcraft_doc::cjk::LeadingModel as L; + match model { L::Roman => 0.0, // "Space below" measures from the em box top (Em Box Top/Right), "space above" from its // bottom (Em Box Bottom/Left). L::AkiBelow => top, L::AkiAbove => bottom, L::Center | L::CenterDown => (top + bottom) / 2.0, - }; - (reference, g.leading_model) + } } fn line_metrics( @@ -5270,7 +5342,12 @@ fn layout_line( g.shift += cjk_alignment_shift(g, &reference); } } - if hyphen && let Some(g) = line.last() { + // No hyphen after a word of an Indian script (its last letter before any soft hyphens). + let marked = line.iter().rev().find(|g| g.ch != shape::SOFT_HYPHEN).is_none_or(|g| !shape::breaks_without_hyphen(g)); + if hyphen + && marked + && let Some(g) = line.last() + { let h = shape::hyphen_after(g); line.push(h); } @@ -5381,9 +5458,12 @@ fn layout_line( let mut x = x0 + offset; let bidi = bidi_info.has_rtl(); let mut pens = Vec::with_capacity(if bidi { line.len() } else { 0 }); + // The tracking each placed advance carries, scaled with it. + let mut tracks = Vec::with_capacity(if bidi { line.len() } else { 0 }); for (i, g) in line.iter().enumerate() { if bidi { pens.push(x); + tracks.push(g.track * scale[i]); } let mut p = place(g, x); if scale[i] != 1.0 { @@ -5406,7 +5486,7 @@ fn layout_line( } if bidi { pens.push(x); - reorder_visual(&line, &mut out, &pens, x0 + offset, bidi_info); + reorder_visual(&line, &mut out, &pens, &tracks, x0 + offset, bidi_info); } for (i, leader) in &leaders { if let Some((g, p)) = line.get(*i).zip(out.get(*i)) { @@ -5432,13 +5512,45 @@ fn joins_prev(c: char) -> bool { | 0x06C0 | 0x06C3..=0x06CB | 0x06CD | 0x06CF | 0x06D2 | 0x06D3) } -/// Where kashidas go on a line: one join per word, after a seen or sad when there is one, else the -/// word's last join (indices of the glyph before the join). +/// Arabic combining marks, which sit on a letter and never take part in a join. +fn is_arabic_mark(c: char) -> bool { + matches!(c as u32, 0x064B..=0x065F | 0x0670) +} + +/// Letters whose initial and medial forms are a tooth (ب ت ث ن ي ئ). +fn is_tooth(c: char) -> bool { + matches!(c as u32, 0x0626 | 0x0628 | 0x062A | 0x062B | 0x0646 | 0x064A) +} + +/// How well Arabic typography takes a kashida at the join of `g` and `n`, from 0 (best) to 4, or +/// `None` where one must not go. `prev` is the letter before `g` and `next` the one after `n`. +fn kashida_rank(prev: Option, g: char, n: char, next: Option) -> Option { + let medial = prev.is_some_and(joins_next); + let last = !(joins_next(n) && next.is_some_and(joins_prev)); + let forbidden = n == '\u{0648}' + || (last && matches!(n as u32, 0x0649 | 0x064A | 0x0646)) + || (is_tooth(g) && matches!(n as u32, 0x0631 | 0x0632 | 0x0635 | 0x0636 | 0x0639 | 0x063A | 0x0641 | 0x0642)) + || g == '\u{0643}' + || (g == '\u{0644}' && (!medial || matches!(n as u32, 0x0644 | 0x062F))); + if forbidden { + return None; + } + Some(match n as u32 { + 0x0629 | 0x0647 if last => 0, + 0x0627 if last => 1, + 0x0631 | 0x0632 => 2, + _ if !last && is_tooth(g) && is_tooth(n) => 3, + _ => 4, + }) +} + +/// Where kashidas go on a line: one join per word, the best by [`kashida_rank`] and the later in +/// the word among equals (indices of the glyph before the join). fn kashida_points(line: &[Glyph]) -> Vec { let mut out = Vec::new(); - let mut best: Option<(bool, usize)> = None; + let mut best: Option<(u8, usize)> = None; for (i, g) in line.iter().enumerate() { - if g.is_space() { + if g.is_space() || g.ch == '\t' || g.ch == story::RIGHT_INDENT_TAB { if let Some((_, k)) = best.take() { out.push(k); } @@ -5456,9 +5568,12 @@ fn kashida_points(line: &[Glyph]) -> Vec { if !joins_next(g.ch) || !joins_prev(n.ch) || (g.ch == '\u{0644}' && matches!(n.ch, '\u{0622}' | '\u{0623}' | '\u{0625}' | '\u{0627}')) { continue; } - let seen = matches!(g.ch as u32, 0x0633..=0x0636); - if best.is_none_or(|(s, _)| !s || seen) { - best = Some((seen, i)); + let letter = |p: &&Glyph, cluster: &Glyph| p.byte != cluster.byte && !is_arabic_mark(p.ch); + let prev = line.get(..i).and_then(|l| l.iter().rev().find(|p| letter(p, g))).map(|p| p.ch); + let next = line.get(i + 2..).and_then(|l| l.iter().find(|p| letter(p, n))).map(|p| p.ch); + let Some(rank) = kashida_rank(prev, g.ch, n.ch, next) else { continue }; + if best.is_none_or(|(r, _)| rank <= r) { + best = Some((rank, i)); } } out.extend(best.map(|b| b.1)); @@ -5466,9 +5581,9 @@ fn kashida_points(line: &[Glyph]) -> Vec { } /// Bidi: put a laid-out line (glyphs in text order, `pens` their pen positions and then the end -/// position) into visual order from `start`, cluster by cluster (Unicode Bidirectional -/// Algorithm, rule L2). -fn reorder_visual(line: &[Glyph], out: &mut [PlacedGlyph], pens: &[f64], start: f64, info: &unicode_bidi::BidiInfo<'_>) { +/// position, `tracks` the tracking in their placed advances) into visual order from `start`, +/// cluster by cluster (Unicode Bidirectional Algorithm, rule L2). +fn reorder_visual(line: &[Glyph], out: &mut [PlacedGlyph], pens: &[f64], tracks: &[f64], start: f64, info: &unicode_bidi::BidiInfo<'_>) { use unicode_bidi::{BidiInfo, Level}; // Clusters: runs of glyphs from the same source character. let mut units: Vec> = Vec::new(); @@ -5487,13 +5602,30 @@ fn reorder_visual(line: &[Glyph], out: &mut [PlacedGlyph], pens: &[f64], start: let width = |u: &std::ops::Range| pens[u.end] - pens[u.start]; let mut cur = start; let mut shifts = vec![0.0; line.len()]; + // The glyph whose advance ends at `cur`: the last one of the cluster drawn there. + let mut left: Option = None; for &k in &order { let u = &units[k]; + let rtl = levels[k].is_rtl(); + // Tracking is space after the character in reading order (#2884): right-to-left, that + // is at its left. The space leaves the cluster's advance for the advance of whatever is + // drawn left of it (at the start of the line, nothing), so advances stay end to end. + let track: f64 = if rtl { u.clone().filter_map(|i| tracks.get(i)).sum() } else { 0.0 }; + if track != 0.0 { + if let Some(o) = left.and_then(|l| out.get_mut(l)) { + o.adv += track; + } + for i in u.clone() { + out[i].adv -= tracks.get(i).copied().unwrap_or(0.0); + } + cur += track; + } for i in u.clone() { shifts[i] = cur - pens[u.start]; - out[i].rtl = levels[k].is_rtl(); + out[i].rtl = rtl; } - cur += width(u); + cur += width(u) - track; + left = u.end.checked_sub(1); } for (p, d) in out.iter_mut().zip(shifts) { p.x += d; @@ -5785,6 +5917,7 @@ fn split_drop_cap( let k = if k.is_finite() && k > 0.0 { k.min(1000.0) } else { 1.0 }; for g in dc.iter_mut().chain(after.iter_mut()) { g.adv *= k; + g.track *= k; g.dx *= k; g.dy *= k; g.sx *= k; @@ -5835,10 +5968,22 @@ impl DropCap { /// The drop cap's glyphs set from `at` (right to left: mirrored, its first character on the right). fn place_drop_cap(dc: &DropCap, at: f64, rtl: bool) -> Vec { let mut x = at; + // Right to left, the edge the next letter ends at and the tracking of the letter before it in + // reading order: that space is at its left (#2884), so in the advance of the letter drawn there. + let mut right = at + dc.width; + let mut carried = 0.0; let mut out = Vec::with_capacity(dc.glyphs.len()); for g in &dc.glyphs { - let pen = if rtl { at + at + dc.width - x - g.adv } else { x }; + let (pen, adv) = if rtl { + let adv = g.adv - g.track + carried; + carried = g.track; + right -= adv; + (right, adv) + } else { + (x, g.adv) + }; let mut p = place(g, pen); + p.adv = adv; p.y += dc.drop; p.rtl = rtl; out.push(p); @@ -5965,13 +6110,18 @@ fn foreign_ranges( .collect() } -/// Leave out the hyphenation points after the glyphs that end at story bytes `at`. +/// Leave out the hyphenation points after the glyphs that end at story bytes `at`. A glyph +/// without bytes of its own (len 0) is part of the cluster before it and ends where that does. fn suppress_hyphens(hy: &mut [bool], glyphs: &[Glyph], at: &[usize]) { if at.is_empty() { return; } + let mut end = 0; for (h, g) in hy.iter_mut().zip(glyphs) { - if *h && at.contains(&(g.byte + g.len)) { + if g.len > 0 || end == 0 { + end = g.byte + g.len; + } + if *h && at.contains(&end) { *h = false; } } @@ -6059,7 +6209,7 @@ fn hyphenation_points( } // A discretionary hyphen in a word (or right before it) replaces automatic hyphenation. let discretionary = glyphs[i..j].iter().any(|g| g.ch == shape::SOFT_HYPHEN) || (i > 0 && glyphs[i - 1].ch == shape::SOFT_HYPHEN); - let (a, b) = (glyphs[i].byte, glyphs[j - 1].byte + glyphs[j - 1].len); + let (a, b) = (glyphs[i].byte, glyphs[i..j].iter().map(|g| g.byte + g.len).max().unwrap_or(glyphs[i].byte)); if !discretionary && b > a && b <= text.len() && text.is_char_boundary(a) && text.is_char_boundary(b) { let word = &text[a..b]; // The whitespace-delimited token the word sits in: a Latin run with a Korean particle @@ -6095,13 +6245,17 @@ fn hyphenation_points( } }; if !pts.is_empty() { - // char index p → byte → the first glyph whose cluster ends at that byte. Both - // indexed once per word: looking each point up by scanning was quadratic in - // a long word's length. + // char index p → byte → the last glyph of the cluster that ends at that byte. + // A cluster's first glyph owns its bytes and the glyphs after it (len 0) are + // the rest of it: a Devanagari syllable such as वि is drawn as the ि sign + // before the व, so the break goes after the last of them, not between them. + // Both indexed once per word: looking each point up by scanning was quadratic + // in a long word's length. let char_bytes: Vec = word.char_indices().map(|(bi, _)| bi).collect(); let mut glyph_ending_at: HashMap = HashMap::new(); for k in (i..j).filter(|&k| glyphs[k].len > 0) { - glyph_ending_at.entry(glyphs[k].byte + glyphs[k].len).or_insert(k); + let last = (k + 1..j).take_while(|&m| glyphs[m].len == 0).last().unwrap_or(k); + glyph_ending_at.entry(glyphs[k].byte + glyphs[k].len).or_insert(last); } for &p in pts.iter() { let byte = a + char_bytes.get(p).copied().unwrap_or(word.len()); @@ -6135,8 +6289,9 @@ fn rule_decos(doc: &Document, r: &designcraft_doc::Rule, rect: Rect, (color, tin let mut line = designcraft_geom::BezPath::new(); line.move_to((rect.x0, y)); line.line_to((rect.x1, y)); - let path = match &kind { - StrokeType::Dashed { pattern } if StrokeType::expandable_dashes(pattern, len) => { + let dashes = kind.dashes(w).filter(|p| StrokeType::expandable_dashes(p, len)); + let path = match (&kind, dashes) { + (StrokeType::Dashed { .. }, Some(pattern)) => { let mut p = designcraft_geom::BezPath::new(); let (mut x, mut k, mut on) = (rect.x0, 0, true); while x < rect.x1 { @@ -6151,7 +6306,7 @@ fn rule_decos(doc: &Document, r: &designcraft_doc::Rule, rect: Rect, (color, tin } Some(p) } - StrokeType::Dotted if StrokeType::expandable_dashes(&[w, w], len) => { + (StrokeType::Dotted, _) if StrokeType::expandable_dashes(&[w, w], len) => { let mut p = designcraft_geom::BezPath::new(); let mut x = rect.x0 + w / 2.0; while x <= rect.x1 - w / 2.0 + 1e-9 { @@ -6160,7 +6315,7 @@ fn rule_decos(doc: &Document, r: &designcraft_doc::Rule, rect: Rect, (color, tin } Some(p) } - k => k.outline(&line, w, 0.05), + (k, _) => k.outline(&line, w, 0.05), }; out.push(Deco { rect, color, tint, path, ..Deco::default() }); out diff --git a/crates/compose/src/parabox.rs b/crates/compose/src/parabox.rs index 4a5b0e8d1..52fa35a63 100644 --- a/crates/compose/src/parabox.rs +++ b/crates/compose/src/parabox.rs @@ -354,10 +354,7 @@ fn stroke_outline(path: &BezPath, w: f64, kind: &StrokeType, cap: Cap, join: Joi Join::Bevel => kurbo::Join::Bevel, }); let dashes: Option> = match kind { - StrokeType::Dashed { pattern } => { - let p: Vec = pattern.iter().copied().filter(|v| v.is_finite() && *v >= 0.0).collect(); - Some(if p.iter().sum::() > 1e-3 { p } else { vec![3.0 * w, 2.0 * w] }) - } + StrokeType::Dashed { .. } => kind.dashes(w), StrokeType::Dotted => match dots(path, w) { Some(d) => return d, None => None, diff --git a/crates/compose/src/shape.rs b/crates/compose/src/shape.rs index 1de4b823c..9bb3e1f8b 100644 --- a/crates/compose/src/shape.rs +++ b/crates/compose/src/shape.rs @@ -71,6 +71,9 @@ pub struct Glyph { pub allow_kashidas: bool, pub safe_tatweel_before: bool, pub shaping_rtl: bool, + /// Tracking and manual kerning included in `adv`, the space after the character in reading + /// order. Right-to-left, that is at the glyph's left (see `reorder_visual`). + pub track: f64, /// The character's language as a BCP 47 tag ([`designcraft_doc::language_tag`]). pub lang: Option<&'static str>, /// Upright in a vertical frame: shaped top to bottom (`adv` is its vertical advance) and hung @@ -929,6 +932,10 @@ fn shape_run_raw( } designcraft_doc::OBJECT_MARK => { let mut g = control_glyph(&primary, p, auto_leading, styles.at(i), i, c); + // Bidi-neutral like U+FFFC (the object replacement character), not a strong + // left-to-right character as its private-use mark is: an inline object in + // right-to-left text keeps its place in the reading order. + g.display_char = '\u{FFFC}'; if let Some(o) = sub.objects.get(&i).filter(|o| !o.custom) { let auto = matches!(p.leading, Leading::Auto); match o.y_offset { @@ -1074,6 +1081,35 @@ fn shape_cached( out } +/// Size of a small capital drawn by us, as a fraction of the type size, close to InDesign's own. +const SMALL_CAPS_SIZE: f64 = 0.7; + +/// Faces whose small caps we must draw, by face id. Reading a font's feature list parses its GSUB, +/// which is not something to do once per run per line. +static SMALL_CAPS_MISSING: RwLock> = RwLock::new(Vec::new()); + +/// How much a glyph shrinks when we draw its small caps: the lowercase letters of a Small Caps run, +/// and nothing else. Only the glyph and its advance change — the +/// line box is measured from the unscaled size, so turning it on never moves the leading. +fn small_caps_shrink(small: bool, ch: char) -> f64 { + if small && ch.is_lowercase() { SMALL_CAPS_SIZE } else { 1.0 } +} + +/// Whether this run's Small Caps have to be drawn instead of taken from the font: the font's own +/// `smcp` is used whenever it has one. OpenType All Small Caps only applies a font's own small caps. +fn small_caps_drawn_by_us(face: &FontFace, p: &CharProps) -> bool { + if p.capitalization != Capitalization::SmallCaps { + return false; + } + let id = face.id(); + if let Some((_, missing)) = SMALL_CAPS_MISSING.read().unwrap_or_else(std::sync::PoisonError::into_inner).iter().find(|e| e.0 == id) { + return *missing; + } + let missing = !designcraft_fonts::font_features(face).tags.contains("smcp"); + SMALL_CAPS_MISSING.write().unwrap_or_else(std::sync::PoisonError::into_inner).push((id, missing)); + missing +} + fn metrics(face: &FontFace, p: &CharProps, auto_leading: TypeEnv) -> (f64, f64, f64, f64, f64, f64, f64, f64) { let (size, shift) = effective_size(p, &auto_leading.adv); let k = size / face.upem; @@ -1094,6 +1130,23 @@ pub struct TypeEnv { pub glyph_fallback: bool, } +/// The face and em box height a character `c` with `p` is shaped with: a composite font +/// resolved to its entry for `c` (font, size and vertical scale), and a superscript or subscript +/// at its Advanced Type size, as [`shape_para`] shapes it. A shaped glyph's em box is +/// `units_per_em * sy`, which is this height. +pub(crate) fn em_face(db: &ScopedFonts<'_>, styles: &Styles, p: &CharProps, c: char, adv: &designcraft_doc::AdvancedType) -> (Arc, f64) { + let resolved; + let p = match styles.composite_font(&p.font_family) { + Some(font) => { + resolved = composite_props(db, p, font.entry(c)); + &resolved + } + None => p, + }; + let (size, _) = effective_size(p, adv); + (db.face(&p.font_family, &p.font_style), size * p.v_scale) +} + /// Synthesised super/subscript: size and shift from Advanced Type (percent of the font size). fn effective_size(p: &CharProps, adv: &designcraft_doc::AdvancedType) -> (f64, f64) { match p.position { @@ -1145,6 +1198,7 @@ fn control_glyph(face: &Arc, p: &CharProps, auto_leading: TypeEnv, sty allow_kashidas: p.allow_kashidas, safe_tatweel_before: false, shaping_rtl: false, + track: 0.0, lang: designcraft_doc::language_tag(&p.language), upright: false, list_label: false, @@ -1199,7 +1253,11 @@ fn shape_segment( let tracking = p.tracking / 1000.0 * p.size; let manual = if let Kerning::Manual(v) = p.kerning { v / 1000.0 * p.size } else { 0.0 }; let src = replacement.unwrap_or(&text[range.clone()]); - let caps = p.capitalization == Capitalization::AllCaps; + // A font with no small caps of its own gets them drawn: the letter is uppercased and set + // smaller, the way InDesign does it, which is why All Caps worked on such a font and Small + // Caps looked like nothing happened (#2438). + let small = small_caps_drawn_by_us(face, p); + let caps = p.capitalization == Capitalization::AllCaps || small; let feats = features_for(p); // Upright in vertical text, Horizontal Kana takes the vertical kana alternates instead. let mut upright_feats = feats.clone(); @@ -1253,19 +1311,22 @@ fn shape_segment( let end = shaped[gi + 1..].iter().map(|r| r.cluster).find(|&c| c > sg.cluster).unwrap_or(src.len()); Box::from(src.get(sg.cluster..end).unwrap_or("")) }); + let shrink = small_caps_shrink(small, src.get(sg.cluster..).and_then(|s| s.chars().next()).unwrap_or(ch)); // Upright: down the line is the shaper's -y, across it (text space -y) its x. - let mut adv = if up { -(sg.y_advance as f64) * k_v } else { sg.x_advance as f64 * k * hs }; + let mut adv = if up { -(sg.y_advance as f64) * k_v * shrink } else { sg.x_advance as f64 * k * hs * shrink }; let (dx, dy) = if up { - (-(sg.y_offset as f64) * k_v, -(sg.x_offset as f64) * k * hs) + (-(sg.y_offset as f64) * k_v * shrink, -(sg.x_offset as f64) * k * hs * shrink) } else { - (sg.x_offset as f64 * k * hs, -(sg.y_offset as f64) * k * p.v_scale) + (sg.x_offset as f64 * k * hs * shrink, -(sg.y_offset as f64) * k * p.v_scale * shrink) }; let (ascent, descent) = if up { (em_top * k_v, -em_bottom * k_v) } else { (ascent, descent) }; let body = adv; + let mut track = 0.0; if ch == SOFT_HYPHEN { adv = 0.0; } else if last_in_cluster { - adv += tracking + manual; + track = tracking + manual; + adv += track; } let mark = face.glyph_is_mark(sg.gid); let mark_x = if mark { p.diacritic_x_offset.clamp(-1000.0, 1000.0) / 1000.0 * p.size * hs } else { 0.0 }; @@ -1280,8 +1341,8 @@ fn shape_segment( adv, dx: dx + mark_x, dy: dy - mark_y, - sx: k * hs, - sy: k * p.v_scale, + sx: k * hs * shrink, + sy: k * p.v_scale * shrink, shift, ascent, typo_ascent: face.typo_ascent * k, @@ -1319,6 +1380,7 @@ fn shape_segment( allow_kashidas: p.allow_kashidas, safe_tatweel_before: sg.safe_tatweel_before, shaping_rtl: sg.rtl, + track, lang, upright: up, list_label: false, @@ -1427,12 +1489,21 @@ fn fit_auto_tcy(glyphs: &mut [Glyph], auto: &[std::ops::Range]) { } } +/// Whether a word broken after `g` takes no hyphen mark: Indian scripts (Devanagari, Bengali, +/// Gurmukhi, Gujarati, Odia, Tamil, Telugu, Kannada and Malayalam). Their words split between +/// syllables at a line end without a hyphen, so nothing is drawn there and no room is kept for +/// one. Latin and other scripts keep the hyphen. +pub(crate) fn breaks_without_hyphen(g: &Glyph) -> bool { + matches!(g.ch as u32, 0x0900..=0x0D7F) +} + /// A hyphen glyph in the face/size of `g`, placed after it (zero source length). pub(crate) fn hyphen_after(g: &Glyph) -> Glyph { let gid = designcraft_fonts::first_glyph(&g.face, &['-', '\u{2010}']); let mut h = g.clone(); h.gid = gid; h.adv = g.face.advance(gid) * g.sx; + h.track = 0.0; h.dx = 0.0; h.dy = 0.0; h.byte = g.byte + g.len; diff --git a/crates/compose/src/table.rs b/crates/compose/src/table.rs index 341a116b6..8eb8831ce 100644 --- a/crates/compose/src/table.rs +++ b/crates/compose/src/table.rs @@ -304,8 +304,10 @@ pub(crate) fn place_table( let sum = |a: usize, b: usize| heights[a..b].iter().sum::(); let footer_h = sum(body_end, nr); let o = &table.options; + // InDesign measures Space Before from the previous line's baseline (the descenders may hang + // into it), as it measures text after the table from the table's bottom. let mut y = match cur.last_baseline { - Some(b) => b + cur.last_descent + cur.pending + o.space_before, + Some(b) => b + cur.pending + o.space_before, None => col.y0, }; let mut frag_rows: Vec<(usize, f64, bool)> = Vec::new(); // (row, y, repeated) @@ -328,22 +330,24 @@ pub(crate) fn place_table( let mut reserve = column_reserve(notes, cur, col); let mut r = header; loop { - if r >= body_end { - break; - } - let ge = group_end[r].min(body_end).max(r + 1); - let gh = sum(r, ge); let bottom = col.y1 - reserve; - let at_col_top = cur.last_baseline.is_none() && (top - col.y0).abs() < 1e-6; - if y + gh + footer_h <= bottom + 0.01 || (body_placed == 0 && at_col_top && reserve == 0.0) { - if y + gh + footer_h > bottom + 0.01 && body_placed == 0 && at_col_top && y + gh > bottom + 0.01 { - // A row group taller than an empty column can never fit. - return false; + if r >= body_end { + // A table with no body rows still has to fit its header and footer rows inside the column. + if y + footer_h <= bottom + 0.01 { + break; + } + } else { + let ge = group_end[r].min(body_end).max(r + 1); + let gh = sum(r, ge); + // A non-final fragment without repeating footers does not emit the footer rows; + // every other fragment must keep its footer rows inside the column too. + let need_footer = if o.repeat_footer || ge == body_end { footer_h } else { 0.0 }; + if y + gh + need_footer <= bottom + 0.01 { + place_rows(r..ge, &mut y, false, &mut frag_rows); + body_placed += 1; + r = ge; + continue; } - place_rows(r..ge, &mut y, false, &mut frag_rows); - body_placed += 1; - r = ge; - continue; } // Continue in the next column / frame. if body_placed > 0 { @@ -391,6 +395,7 @@ fn clip_overset(lay: &CellLayout, clip_height: f64) -> Arc { frame.lines.truncate(keep); frame.objects.retain(|o| o.line < keep); frame.tables.retain(|table| table.line < keep); + frame.notes.retain(|note| keep > 0 && note.rect.y1 <= clip_height + 0.01); frame.range.end = frame.lines.last().map_or(frame.range.start, |l| l.range.end); } if let Some(at) = overset_at { @@ -1144,6 +1149,134 @@ mod height_tests { assert!(placed.text.frames[0].tables.is_empty()); } } + + #[test] + fn footer_rows_never_overflow_the_frame() { + for repeat_footer in [false, true] { + // Single body row (70 pt) fits alone in a 100 pt frame, but body + footer (110 pt) does not. + let mut table = Table::new(77, 1, 1, 0, 1, 100.0); + table.options.repeat_footer = repeat_footer; + table.rows[0].mode = RowHeightMode::Exactly; + table.rows[0].height = 70.0; + table.rows[1].mode = RowHeightMode::Exactly; + table.rows[1].height = 40.0; + let composed = compose_table(table, 100.0); + assert!(composed.is_overset(), "repeat_footer={repeat_footer}: body+footer taller than frame must overset"); + assert!( + composed.frames[0].tables.is_empty(), + "repeat_footer={repeat_footer}: must not emit rows past the frame bottom: {:?}", + composed.frames[0].tables.first().map(|t| t.rect) + ); + } + + // Multiple body rows with repeating footer: first body row fits alone, but adding the + // repeated footer exceeds the frame. + let mut table = Table::new(78, 2, 1, 0, 1, 100.0); + table.options.repeat_footer = true; + table.rows[0].mode = RowHeightMode::Exactly; + table.rows[0].height = 70.0; + table.rows[1].mode = RowHeightMode::Exactly; + table.rows[1].height = 70.0; + table.rows[2].mode = RowHeightMode::Exactly; + table.rows[2].height = 40.0; + let composed = compose_table(table, 100.0); + assert!(composed.is_overset()); + assert!( + composed.frames[0].tables.is_empty(), + "repeating footer must not overflow the frame: {:?}", + composed.frames[0].tables.first().map(|t| t.rect) + ); + + // Threaded frames: when frame 0 is too short for body + footer, the table flows to frame 1. + let mut doc = Document::new(&NewDocument::default()); + let layer = doc.default_layer(); + let (f1, sid) = doc.add_text_frame(SpreadRef::Doc(0), Rect::new(0.0, 0.0, 200.0, 100.0), layer, "", ParaFormat::default()).unwrap(); + let (f2, _) = doc.add_text_frame(SpreadRef::Doc(0), Rect::new(0.0, 150.0, 200.0, 350.0), layer, "", ParaFormat::default()).unwrap(); + doc.thread(f1, f2).unwrap(); + let mut table = Table::new(79, 1, 1, 0, 1, 100.0); + table.rows[0].mode = RowHeightMode::Exactly; + table.rows[0].height = 70.0; + table.rows[1].mode = RowHeightMode::Exactly; + table.rows[1].height = 40.0; + doc.story_mut(sid).unwrap().insert_table(0, table); + let composed = crate::compose_story(&doc, sid, &ComposeOptions::default()); + assert!(!composed.is_overset()); + assert!(composed.frames[0].tables.is_empty()); + assert_eq!(composed.frames[1].tables.len(), 1); + assert!(composed.frames[1].tables[0].rect.y1 <= 350.0 + 0.01); + + // Non-repeating footer: frame 0 takes a body row without reserving footer space, and + // frame 1 takes the final body row plus the footer. + let mut doc = Document::new(&NewDocument::default()); + let layer = doc.default_layer(); + let (f1, sid) = doc.add_text_frame(SpreadRef::Doc(0), Rect::new(0.0, 0.0, 200.0, 100.0), layer, "", ParaFormat::default()).unwrap(); + let (f2, _) = doc.add_text_frame(SpreadRef::Doc(0), Rect::new(0.0, 150.0, 200.0, 250.0), layer, "", ParaFormat::default()).unwrap(); + doc.thread(f1, f2).unwrap(); + let mut table = Table::new(80, 2, 1, 0, 1, 100.0); + table.options.repeat_footer = false; + table.rows[0].mode = RowHeightMode::Exactly; + table.rows[0].height = 70.0; + table.rows[1].mode = RowHeightMode::Exactly; + table.rows[1].height = 20.0; + table.rows[2].mode = RowHeightMode::Exactly; + table.rows[2].height = 30.0; + doc.story_mut(sid).unwrap().insert_table(0, table); + let composed = crate::compose_story(&doc, sid, &ComposeOptions::default()); + assert!(!composed.is_overset()); + assert_eq!(composed.frames[0].tables.len(), 1); + assert!(composed.frames[0].tables[0].rect.y1 <= 100.0 + 0.01); + assert!(composed.frames[0].tables[0].cell(2, 0).is_none()); + assert_eq!(composed.frames[1].tables.len(), 1); + assert!(composed.frames[1].tables[0].rect.y1 <= 250.0 + 0.01); + assert!(composed.frames[1].tables[0].cell(1, 0).is_some()); + assert!(composed.frames[1].tables[0].cell(2, 0).is_some()); + } + + #[test] + fn header_and_footer_only_table_never_overflows_the_frame() { + let mut table = Table::new(81, 2, 1, 0, 0, 100.0); + table.rows[0].kind = designcraft_doc::RowKind::Header; + table.rows[0].mode = RowHeightMode::Exactly; + table.rows[0].height = 70.0; + table.rows[1].kind = designcraft_doc::RowKind::Footer; + table.rows[1].mode = RowHeightMode::Exactly; + table.rows[1].height = 50.0; + + let composed = compose_table(table.clone(), 100.0); + assert!(composed.is_overset(), "header+footer table taller than frame must overset"); + assert!( + composed.frames[0].tables.is_empty(), + "must not emit header/footer rows past the frame bottom: {:?}", + composed.frames[0].tables.first().map(|t| t.rect) + ); + + let mut doc = Document::new(&NewDocument::default()); + let layer = doc.default_layer(); + let (f1, sid) = doc.add_text_frame(SpreadRef::Doc(0), Rect::new(0.0, 0.0, 200.0, 100.0), layer, "", ParaFormat::default()).unwrap(); + let (f2, _) = doc.add_text_frame(SpreadRef::Doc(0), Rect::new(0.0, 150.0, 200.0, 350.0), layer, "", ParaFormat::default()).unwrap(); + doc.thread(f1, f2).unwrap(); + doc.story_mut(sid).unwrap().insert_table(0, table); + let composed = crate::compose_story(&doc, sid, &ComposeOptions::default()); + assert!(!composed.is_overset()); + assert!(composed.frames[0].tables.is_empty()); + assert_eq!(composed.frames[1].tables.len(), 1); + assert!(composed.frames[1].tables[0].rect.y1 <= 350.0 + 0.01); + } + + #[test] + fn overset_exact_cell_hides_overflowing_cell_footnotes() { + let mut cell = text_cell("Reference.", 4.0); + cell.text.insert_note(5, "Cell footnote that does not fit.", ParaFormat::default()); + let full = measure(&cell, 92.0); + assert_eq!(full.text.frames[0].notes.len(), 1); + let mut table = single_table(cell); + table.rows[0].mode = RowHeightMode::Exactly; + table.rows[0].height = 24.0; + let composed = compose_table(table, 200.0); + let placed = composed.frames[0].tables[0].cell(0, 0).unwrap(); + assert!(placed.overset); + assert!(placed.text.frames[0].notes.is_empty(), "overset cell footnote must not extend below the cell"); + } } #[cfg(test)] diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs index 0a1f67184..c5387751a 100644 --- a/crates/compose/src/tests.rs +++ b/crates/compose/src/tests.rs @@ -2434,6 +2434,20 @@ fn table_rows_fit_their_content() { assert!(tf.strokes.len() >= 4 * 3 + 4); } +/// A table starts Space Before below the previous line's baseline, as in InDesign (not below its +/// descenders). +#[test] +fn table_starts_space_before_below_the_previous_baseline() { + let mut t = designcraft_doc::Table::new(77, 2, 2, 0, 0, 100.0); + t.options.space_before = 4.0; + let (d, sid, _) = table_doc(Rect::new(0.0, 0.0, 300.0, 600.0), t); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + let f = &cs.frames[0]; + let above = f.lines.iter().filter(|l| l.baseline < f.tables[0].rect.y0).map(|l| l.baseline).fold(f64::NEG_INFINITY, f64::max); + assert!(above.is_finite(), "a line above the table"); + assert!((f.tables[0].rect.y0 - (above + 4.0)).abs() < 1e-6, "{} vs {}", f.tables[0].rect.y0, above); +} + #[test] fn table_columns_scale_to_the_text_column() { let (d, sid, _) = table_doc(Rect::new(0.0, 0.0, 200.0, 1000.0), filled(2, 4, 0, 600.0)); @@ -3702,6 +3716,110 @@ fn right_to_left_runs_are_ordered_visually() { assert!(g.windows(2).all(|w| w[0].cluster <= w[1].cluster), "{:?}", g.iter().map(|g| g.cluster).collect::>()); } +/// #2884: tracking is space after the character in reading order. Right to left that is at its +/// left, between it and the character read after it, mirroring left to right. +#[test] +fn tracking_in_right_to_left_text_follows_the_character_in_reading_order() { + use designcraft_doc::TextDirection; + let lines = |text: &str, direction: TextDirection, align: Align, tracked: std::ops::Range| { + let para = ParaAttrs { direction: Some(direction), align: Some(align), ..Default::default() }; + let (mut d, sid, _) = doc_with(text, Rect::new(36.0, 36.0, 500.0, 200.0), para); + d.story_mut(sid).unwrap().format_chars(tracked, |f| f.over.tracking = Some(1000.0)); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + all_lines(&cs)[0].clone() + }; + let x_of = |l: &Line, byte: usize| l.glyphs.iter().find(|g| g.byte == byte && g.len > 0).map(|g| g.x).unwrap(); + let width = |l: &Line| l.glyphs.iter().map(|g| g.adv).sum::(); + // Alef, bet, gimel, dalet, he (two bytes each); tracking on bet. + let text = "\u{5D0}\u{5D1}\u{5D2}\u{5D3}\u{5D4}"; + let bytes = [0, 2, 4, 6, 8]; + for align in [Align::Right, Align::Left] { + let plain = lines(text, TextDirection::RightToLeft, align, 0..0); + let tracked = lines(text, TextDirection::RightToLeft, align, 2..4); + // Tracking 1000 is one em: what it adds to the line. + let em = width(&tracked) - width(&plain); + assert!(em > 1.0, "{align:?}: the tracking widens the line by {em}"); + // The space opens between bet and gimel (read after it); every other pair keeps its gap. + for w in bytes.windows(2) { + let gap = |l: &Line| x_of(l, w[0]) - x_of(l, w[1]); + let want = if w[0] == 2 { gap(&plain) + em } else { gap(&plain) }; + assert!((gap(&tracked) - want).abs() < 0.01, "{align:?}: bytes {w:?} are {} apart, not {want}", gap(&tracked)); + } + // Advances stay end to end on the line, so carets, selections and rules have no gap. + let mut drawn: Vec<&PlacedGlyph> = tracked.glyphs.iter().filter(|g| g.len > 0).collect(); + drawn.sort_by(|a, b| a.x.total_cmp(&b.x)); + for w in drawn.windows(2) { + assert!((w[0].x + w[0].adv - w[1].x).abs() < 0.01, "{align:?}: advances of bytes {} and {} don't meet", w[0].byte, w[1].byte); + } + // The caret after bet is at bet's left edge, the one before it at its right edge. + assert!((crate::caret_x(&tracked, 4) - x_of(&tracked, 2)).abs() < 0.01, "{align:?}: caret after bet"); + assert!((crate::caret_x(&tracked, 2) - x_of(&tracked, 0)).abs() < 0.01, "{align:?}: caret before bet"); + } + // Left to right, the same: the space opens between b and c. + let plain = lines("abcde", TextDirection::LeftToRight, Align::Left, 0..0); + let tracked = lines("abcde", TextDirection::LeftToRight, Align::Left, 1..2); + let em = width(&tracked) - width(&plain); + for (a, b) in [(0, 1), (1, 2), (2, 3), (3, 4)] { + let gap = |l: &Line| x_of(l, b) - x_of(l, a); + let want = if a == 1 { gap(&plain) + em } else { gap(&plain) }; + assert!((gap(&tracked) - want).abs() < 0.01, "left to right: bytes {a}, {b}"); + } +} + +/// #2884 review: a justified line whose glyphs are scaled moves the tracking as scaled, so every +/// advance keeps the glyph's own share; and a right-to-left drop cap puts a letter's tracking at +/// its left, as the line does. +#[test] +fn right_to_left_tracking_follows_glyph_scaling_and_drop_caps() { + use designcraft_doc::TextDirection; + let rtl = |align: Align| ParaAttrs { direction: Some(TextDirection::RightToLeft), align: Some(align), ..Default::default() }; + let text = "\u{5D0}\u{5D1}\u{5D2}\u{5D3}\u{5D4}"; + // Two words, then a third the measure leaves for the next line. + let words = format!("{text} \u{5D5}\u{5D6} {text}"); + let line = |para: ParaAttrs, width: f64, tracked: std::ops::Range| { + let (mut d, sid, _) = doc_with(&words, Rect::new(0.0, 0.0, width, 200.0), para); + d.story_mut(sid).unwrap().format_chars(tracked, |f| f.over.tracking = Some(1000.0)); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + all_lines(&cs)[0].clone() + }; + let glyph = |l: &Line, byte: usize| l.glyphs.iter().find(|g| g.byte == byte && g.len > 0).cloned().unwrap(); + // The first two words on a line of their own, justified by scaling their glyphs about a third + // (the word space is fixed). + let plain = line(rtl(Align::Right), 500.0, 2..4); + let two: f64 = plain.glyphs.iter().filter(|g| g.byte < 15).map(|g| g.adv).sum(); + let scaled = ParaAttrs { + glyph_scale_min: Some(1.0), + glyph_scale_max: Some(2.0), + word_space_max: Some(1.0), + word_space_min: Some(1.0), + ..rtl(Align::RightJustified) + }; + let just = line(scaled, two * 1.3, 2..4); + assert!(just.range.end <= 16, "the first two words are a line of their own: {:?}", just.range); + for byte in [0, 2, 4, 6, 8, 11, 13] { + let (p, j) = (glyph(&plain, byte), glyph(&just, byte)); + let k = j.sx / p.sx; + assert!(k > 1.05, "byte {byte}: the glyph is scaled by {k}"); + assert!((j.adv - p.adv * k).abs() < 0.01, "byte {byte}: advance {} is not {} scaled by {k}", j.adv, p.adv); + } + // A two-letter drop cap with tracking on its first letter (alef): the space opens between alef + // and bet, read after it, and their advances still meet. + let cap = |tracked: std::ops::Range| { + let para = ParaAttrs { drop_cap_lines: Some(2), drop_cap_chars: Some(2), ..rtl(Align::Right) }; + let (mut d, sid, _) = doc_with(&format!("{text} {}", "\u{5D5}".repeat(200)), Rect::new(0.0, 0.0, 300.0, 400.0), para); + d.story_mut(sid).unwrap().format_chars(tracked, |f| f.over.tracking = Some(1000.0)); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + all_lines(&cs)[0].clone() + }; + let (untracked, tracked) = (cap(0..0), cap(0..2)); + let (a0, b0, a1, b1) = (glyph(&untracked, 0), glyph(&untracked, 2), glyph(&tracked, 0), glyph(&tracked, 2)); + assert!(a1.x > b1.x, "alef is right of bet"); + let em = (a1.x - b1.x) - (a0.x - b0.x); + assert!(em > 1.0, "the tracking opens a space between alef and bet: {em}"); + assert!((b1.x + b1.adv - a1.x).abs() < 0.01, "bet's advance meets alef: {} vs {}", b1.x + b1.adv, a1.x); + assert!((a1.adv - a0.adv).abs() < 0.01, "alef's advance is its own: {} vs {}", a1.adv, a0.adv); +} + #[test] fn bidi_matches_the_reference_order() { use unicode_bidi::{BidiInfo, Level}; @@ -4475,6 +4593,33 @@ fn inline_objects_still_clear_the_bottom_edge() { assert_eq!(cs.line_count(), 0); } +/// An inline object is bidi-neutral, as U+FFFC is: in a right-to-left paragraph it keeps its place +/// in the reading order between Latin text and the Arabic after it. Its private-use mark is a +/// strong left-to-right character, which joined it to the Latin run before it, so it was drawn on +/// the far side of that run. +#[test] +fn an_inline_object_keeps_its_place_in_right_to_left_text() { + let text = "ab \u{0628}"; + let para = ParaAttrs { direction: Some(designcraft_doc::TextDirection::RightToLeft), ..Default::default() }; + let (mut d, sid, _) = doc_with(text, Rect::new(0.0, 0.0, 300.0, 100.0), para); + d.settings.glyph_fallback = true; + let it = designcraft_doc::Item::new( + ItemId(d.alloc()), + d.default_layer(), + designcraft_doc::Shape::Rectangle, + designcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 6.0, 6.0)), + ); + let at = 3; + d.story_mut(sid).unwrap().insert_object(at, designcraft_doc::AnchoredObject::new(it, designcraft_doc::AnchorPosition::Inline { y_offset: 0.0 })); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + let line = &cs.frames[0].lines[0]; + let x = |byte: usize| line.glyphs.iter().find(|g| g.byte == byte).map(|g| g.x).unwrap(); + let beh = text.find('\u{0628}').unwrap() + designcraft_doc::OBJECT_MARK.len_utf8(); + let (latin, object, arabic) = (x(0), x(at), x(beh)); + // Read right to left: the Latin text, the object, then the Arabic letter. + assert!(arabic < object && object < latin, "arabic {arabic}, object {object}, latin {latin}"); +} + #[test] fn custom_anchors_do_not_change_bottom_baseline_fitting() { let (mut d, sid, _) = baseline_fit_doc("Text", 10.0); @@ -5703,6 +5848,203 @@ fn empty_paragraph_uses_its_own_mark_not_the_previous_one() { assert!((lines[1].baseline - lines[0].baseline - 8.0).abs() < 1e-6, "{} {}", lines[0].baseline, lines[1].baseline); } +/// Under a leading model an empty paragraph keeps the leading like any other line: its line +/// measures from its paragraph mark's em box, as in InDesign. It used to measure from its +/// baseline, so the empty line moved by the em box's offset and the line after it back by as +/// much. The other composers set lines baseline to baseline whatever the model. +#[test] +fn an_empty_paragraph_keeps_the_leading_under_a_leading_model() { + use designcraft_doc::cjk::LeadingModel; + let text = "Aaa\n\nBbb\nCcc"; + for model in [LeadingModel::AkiBelow, LeadingModel::AkiAbove, LeadingModel::Center] { + for para in [japanese(), ParaAttrs::default()] { + let (mut d, sid, _) = doc_with(text, Rect::new(0.0, 0.0, 300.0, 300.0), para); + d.story_mut(sid).unwrap().format_chars(0..text.len(), |f| { + f.over.leading = Some(designcraft_doc::Leading::Points(16.0)); + f.over.leading_model = Some(model); + }); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + let base: Vec = all_lines(&cs).iter().map(|l| l.baseline).collect(); + assert_eq!(base.len(), 4, "{model:?}"); + for w in base.windows(2) { + assert!((w[1] - w[0] - 16.0).abs() < 1e-6, "{model:?}: {base:?}"); + } + } + } +} + +/// Baselines of `text` set in a Hangul test font under the Japanese composer with Aki Below and +/// 20 pt leading. +fn hangul_lines(text: &str) -> Vec { + let chars: Vec = "가나".chars().collect(); + let font = designcraft_fonts::testing::font_with("DC Test Korean Lines", &chars).unwrap(); + designcraft_fonts::FontDb::global().add_font(font); + let (mut d, sid, _) = doc_with(text, Rect::new(0.0, 0.0, 300.0, 500.0), japanese()); + d.story_mut(sid).unwrap().format_chars(0..text.len(), |f| { + f.over.font_family = Some("DC Test Korean Lines".into()); + f.over.language = Some("Korean".into()); + f.over.leading = Some(designcraft_doc::Leading::Points(20.0)); + f.over.leading_model = Some(designcraft_doc::cjk::LeadingModel::AkiBelow); + }); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + all_lines(&cs).iter().map(|l| l.baseline).collect() +} + +/// Hangul text under Aki Below: an empty paragraph between two lines keeps the leading, so the +/// baselines match those of three lines of text. The empty paragraph rose and the line after it +/// dropped back by as much. +#[test] +fn an_empty_hangul_paragraph_keeps_the_leading_under_aki_below() { + let (text, empty) = (hangul_lines("가나\n가나\n가나"), hangul_lines("가나\n\n가나")); + assert_eq!(empty.len(), 3); + for (a, b) in text.iter().zip(&empty) { + assert!((a - b).abs() < 1e-6, "{text:?} vs {empty:?}"); + } +} + +/// The empty line a trailing forced line break leaves measures from its paragraph mark's em box, +/// like an empty paragraph, so it keeps the leading too. It measured from the paragraph style's +/// characters: text formatted with a leading model the style doesn't have moved that line by the +/// em box's offset from the baseline, and the line after it back by as much. +#[test] +fn a_trailing_forced_line_breaks_empty_line_keeps_the_leading_under_a_leading_model() { + use designcraft_doc::cjk::LeadingModel; + use designcraft_doc::story::FORCED_LINE_BREAK; + let text = format!("Aaa{FORCED_LINE_BREAK}\nBbb\nCcc"); + for model in [LeadingModel::AkiBelow, LeadingModel::AkiAbove, LeadingModel::Center] { + let (mut d, sid, _) = doc_with(&text, Rect::new(0.0, 0.0, 300.0, 300.0), japanese()); + d.story_mut(sid).unwrap().format_chars(0..text.len(), |f| { + f.over.leading = Some(designcraft_doc::Leading::Points(16.0)); + f.over.leading_model = Some(model); + }); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + let base: Vec = all_lines(&cs).iter().map(|l| l.baseline).collect(); + assert_eq!(base.len(), 4, "{model:?}"); + for w in base.windows(2) { + assert!((w[1] - w[0] - 16.0).abs() < 1e-6, "{model:?}: {base:?}"); + } + } +} + +/// An empty line whose paragraph mark is larger than the text around it takes its auto leading +/// from the mark: an empty paragraph's line, and the line a trailing forced line break leaves. +/// The line after it goes back to the text's own leading. +#[test] +fn an_empty_line_takes_its_auto_leading_from_a_larger_paragraph_mark() { + use designcraft_doc::story::FORCED_LINE_BREAK; + for text in ["Aaa\n\nBbb".to_string(), format!("Aaa{FORCED_LINE_BREAK}\nBbb")] { + let (mut d, sid, _) = doc_with(&text, Rect::new(0.0, 0.0, 300.0, 300.0), ParaAttrs::default()); + let mark = text.find("\nB").unwrap(); + let story = d.story_mut(sid).unwrap(); + story.format_chars(0..text.len(), |f| f.over.size = Some(10.0)); + story.format_chars(mark..mark + 1, |f| f.over.size = Some(20.0)); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + let base: Vec = all_lines(&cs).iter().map(|l| l.baseline).collect(); + assert_eq!(base.len(), 3, "{text:?}: {base:?}"); + assert!((base[1] - base[0] - 24.0).abs() < 1e-6, "{text:?}: {base:?}"); + assert!((base[2] - base[1] - 12.0).abs() < 1e-6, "{text:?}: {base:?}"); + } +} + +/// A paragraph that holds only a drop cap is left with an empty line once the drop cap is split +/// off: that line takes its auto leading from the paragraph mark, as an empty paragraph's does. It +/// read the format of the paragraph's first character, the drop cap. +#[test] +fn a_drop_cap_only_paragraph_takes_its_leading_from_the_mark() { + let text = "Aaa\nW\nBbb"; + let (mut d, sid, _) = doc_with(text, Rect::new(0.0, 0.0, 300.0, 300.0), ParaAttrs::default()); + let cap = text.find('W').unwrap(); + let story = d.story_mut(sid).unwrap(); + story.format_chars(0..text.len(), |f| f.over.size = Some(10.0)); + story.format_chars(cap..cap + 1, |f| f.over.size = Some(40.0)); + story.format_chars(cap + 1..cap + 2, |f| f.over.size = Some(20.0)); + story.paras[1].para.drop_cap_lines = Some(2); + story.paras[1].para.drop_cap_chars = Some(1); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + let base: Vec = all_lines(&cs).iter().map(|l| l.baseline).collect(); + assert!(base.len() >= 2, "{base:?}"); + // The 20 pt mark's auto leading (24 pt), not the 40 pt drop cap's (48 pt). + assert!((base[1] - base[0] - 24.0).abs() < 1e-6, "{base:?}"); +} + +/// Under a leading model the lines of `text` (all formatted by `format`, with a 16 pt leading) +/// are 16 pt apart, empty lines included. +fn assert_leading_kept(text: &str, mut d: Document, sid: StoryId, format: impl Fn(&mut designcraft_doc::CharFormat)) { + use designcraft_doc::cjk::LeadingModel; + for model in [LeadingModel::AkiBelow, LeadingModel::AkiAbove, LeadingModel::Center] { + d.story_mut(sid).unwrap().format_chars(0..text.len(), |f| { + format(f); + f.over.leading = Some(designcraft_doc::Leading::Points(16.0)); + f.over.leading_model = Some(model); + }); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + let base: Vec = all_lines(&cs).iter().map(|l| l.baseline).collect(); + assert_eq!(base.len(), 4, "{model:?}"); + for w in base.windows(2) { + assert!((w[1] - w[0] - 16.0).abs() < 1e-6, "{model:?}: {base:?}"); + } + } +} + +/// A superscript or subscript paragraph mark is shaped at the Advanced Type size, like the text +/// around it: an empty line measures from that em box, so it keeps the leading. It measured from +/// the em box at the full size, so it moved against the superscript lines beside it. +#[test] +fn an_empty_superscript_paragraph_keeps_the_leading_under_a_leading_model() { + use designcraft_doc::Position; + let text = "Aaa\n\nBbb\nCcc"; + for position in [Position::Superscript, Position::Subscript] { + let (d, sid, _) = doc_with(text, Rect::new(0.0, 0.0, 300.0, 300.0), japanese()); + assert_leading_kept(text, d, sid, |f| f.over.position = Some(position)); + } +} + +/// A paragraph mark in a composite font is measured with the composite font's entry (its font, +/// relative size and vertical scale), as shaping sets the text around it, so an empty line keeps +/// the leading. It measured the composite font's name, a substitute face, at the plain size. +#[test] +fn an_empty_paragraph_in_a_composite_font_keeps_the_leading_under_a_leading_model() { + use designcraft_doc::cjk::{CompositeFont, CompositeFontEntry}; + let text = "Aaa\n\nBbb\nCcc"; + let (mut d, sid, _) = doc_with(text, Rect::new(0.0, 0.0, 300.0, 300.0), japanese()); + std::sync::Arc::make_mut(&mut d.styles).composite_fonts.push(CompositeFont { + name: "Scaled".into(), + entries: vec![CompositeFontEntry { + family: designcraft_fonts::DEFAULT_FAMILY.into(), + relative_size: 1.5, + vertical_scale: 1.2, + ..Default::default() + }], + }); + assert_leading_kept(text, d, sid, |f| f.over.font_family = Some("CompositeFont/Scaled".into())); +} + +/// In a vertical frame an empty paragraph measures from the upright em box (the font's +/// ideographic em box), as the upright characters around it do. It measured from the font's +/// ascender and descender, so it moved against the lines beside it. +#[test] +fn an_empty_paragraph_keeps_the_leading_under_a_leading_model_in_vertical_text() { + use designcraft_doc::cjk::LeadingModel; + let family = vertical_test_font(); + let text = "一\n\n二\n日"; + for model in [LeadingModel::AkiBelow, LeadingModel::AkiAbove, LeadingModel::Center] { + let (mut d, sid, _) = doc_with(text, Rect::new(0.0, 0.0, 300.0, 300.0), japanese()); + d.story_mut(sid).unwrap().vertical = true; + d.story_mut(sid).unwrap().format_chars(0..text.len(), |f| { + f.over.font_family = Some(family.into()); + f.over.leading = Some(designcraft_doc::Leading::Points(16.0)); + f.over.leading_model = Some(model); + }); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + assert!(cs.frames[0].vertical); + let base: Vec = all_lines(&cs).iter().map(|l| l.baseline).collect(); + assert_eq!(base.len(), 4, "{model:?}"); + for w in base.windows(2) { + assert!((w[1] - w[0] - 16.0).abs() < 1e-6, "{model:?}: {base:?}"); + } + } +} + #[test] fn german_2006_text_gets_german_hyphenation() { let text = "Silbentrennung Fußgänger Bäcker Fenster Donaudampfschifffahrt Silbentrennung"; @@ -5811,6 +6153,85 @@ fn croatian_text_gets_croatian_hyphenation() { } } +/// Hindi and Malayalam text set in its language hyphenates between syllables, never inside a +/// conjunct: each hyphenated line ends in a prefix the patterns allow, with no hyphen drawn +/// after it (Indian scripts split words at a line end without one). +#[test] +fn indian_language_text_hyphenates_between_syllables() { + for (language, word, prefixes) in [("Hindi", "विद्यार्थी", &["वि", "विद्या"][..]), ("Malayalam", "വിദ്യാർത്ഥി", &["വി", "വിദ്യാർ"][..])] + { + let text = [word; 8].join(" "); + let (mut d, sid, _) = doc_with(&text, Rect::new(36.0, 36.0, 76.0, 700.0), ParaAttrs::default()); + let st = d.story_mut(sid).unwrap(); + let n = st.len(); + st.format_chars(0..n, |f| f.over.language = Some(language.into())); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + // The part of the word before each hyphenated line end: a line can start inside the word + // (वि / द्या / र्थी), so it is read from the word's start, not the line's. + let breaks: Vec<&str> = all_lines(&cs) + .into_iter() + .filter(|l| l.hyphenated) + .map(|l| { + let end = text[..l.range.end].trim_end().len(); + &text[text[..end].rfind(' ').map_or(0, |s| s + 1)..end] + }) + .collect(); + assert!(!breaks.is_empty(), "{language} text is hyphenated"); + for b in breaks { + assert!(prefixes.contains(&b), "{language}: {b:?} is a syllable prefix of {word}"); + } + for l in all_lines(&cs).into_iter().filter(|l| l.hyphenated) { + assert!(l.glyphs.iter().all(|g| g.rendered_char != '-'), "{language}: no hyphen drawn on {:?}", &text[l.range.clone()]); + } + } +} + +/// With hyphenation across columns off, no column of Hindi text ends in a hyphenated break. The +/// break goes after a syllable's last glyph, which has no bytes of its own (the vowel sign of वि +/// is drawn before the consonant), so the rejected break is recorded at its cluster's end. +#[test] +fn hyphenate_across_column_off_holds_for_indian_scripts() { + let text = ["विद्यार्थी विश्वविद्यालय अंतरराष्ट्रीय प्रधानमंत्री स्वतंत्रता"; 6].join(" "); + let ends = |across: bool, composer: designcraft_doc::Composer| { + let mut ends = 0; + for h in (20..240).step_by(3) { + let para = ParaAttrs { + align: Some(Align::Left), + hyph_weight: Some(0.0), + hyph_across_column: Some(across), + composer: Some(composer), + ..Default::default() + }; + let (mut d, sid, fid) = doc_with(&text, Rect::new(0.0, 0.0, 120.0, h as f64), para); + d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.columns = 2; + let st = d.story_mut(sid).unwrap(); + let n = st.len(); + st.format_chars(0..n, |f| f.over.language = Some("Hindi".into())); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + let col0: Vec<&Line> = all_lines(&cs).into_iter().filter(|l| l.column == 0).collect(); + ends += usize::from(col0.last().is_some_and(|l| l.hyphenated)); + } + ends + }; + for c in [designcraft_doc::Composer::Paragraph, designcraft_doc::Composer::SingleLine] { + assert!(ends(true, c) > 0, "{c:?}: Hindi columns end in hyphenated breaks with it on"); + assert_eq!(ends(false, c), 0, "{c:?}"); + } +} + +/// Latin text keeps its hyphen at a hyphenated line end. +#[test] +fn latin_text_still_draws_its_hyphen() { + let text = "internationalization internationalization internationalization"; + let (d, sid, _) = doc_with(text, Rect::new(36.0, 36.0, 106.0, 700.0), ParaAttrs::default()); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + let hyphenated: Vec<&Line> = all_lines(&cs).into_iter().filter(|l| l.hyphenated).collect(); + assert!(!hyphenated.is_empty(), "English text is hyphenated"); + for l in hyphenated { + assert_eq!(l.glyphs.iter().rev().find(|g| g.visible).map(|g| g.rendered_char), Some('-'), "{:?}", &text[l.range.clone()]); + } +} + #[test] fn cjk_aki_adds_space_without_scaling_outlines() { let (mut d, sid, _) = doc_with("AB", Rect::new(0.0, 0.0, 300.0, 100.0), ParaAttrs::default()); @@ -7596,6 +8017,42 @@ fn mojikumi_does_not_restore_fullwidth_blanks_to_narrow_tracked_punctuation() { } } +/// Taking a closing bracket into a line (push-in) closes up the middle dot's quarter ems first, +/// then the comma's half em, and never the full stop's (JLREQ 3.8.3). +#[test] +fn mojikumi_push_in_reduces_middle_dots_first_and_never_a_full_stop() { + let family = "Mojikumi Reduction"; + let font = designcraft_fonts::testing::font_mapping(family, &[('漢', '‰'), ('・', '‰'), ('、', '‰'), ('。', '‰'), ('」', '‰')]).unwrap(); + designcraft_fonts::FontDb::global().add_font(font); + let first = "漢・漢、漢。漢漢」"; + let para = ParaAttrs { mojikumi: Some("LineEndAllOneHalfEmEnum".into()), kinsoku_type: Some("KinsokuPushInFirst".into()), ..Default::default() }; + let compose = |text: &str, width: f64| { + let (mut d, sid, _) = doc_with(text, Rect::new(0.0, 0.0, width, 300.0), para.clone()); + d.story_mut(sid).unwrap().format_chars(0..text.len(), |f| f.over.font_family = Some(family.into())); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + let line = all_lines(&cs)[0].clone(); + let em = line.glyphs[0].face.units_per_em() * line.glyphs[0].sx; + (line, em) + }; + let (natural, em) = compose(first, 500.0); + let width = natural.end_x - natural.x0; + let quarter = em / 4.0; + // How far each glyph of the first line moved, for a line `less` points short. + let moved = |less: f64| { + let (line, _) = compose(&format!("{first}漢漢漢"), width - less); + assert_eq!(line.range.end, first.len(), "the bracket is taken in"); + line.glyphs.iter().zip(&natural.glyphs).map(|(a, b)| a.x - b.x).collect::>() + }; + let near = |a: f64, b: f64| (a - b).abs() < 0.01; + // Less than the middle dot's two quarter ems: all of it comes from around the dot. + let d = moved(quarter); + assert!(near(d[2], -quarter) && d[2..].iter().all(|&x| near(x, -quarter)), "{d:?}"); + // More: the dot's half em, then the comma's; the full stop's half em stays. + let d = moved(2.0 * quarter + 3.0); + assert!(near(d[2], -2.0 * quarter) && near(d[4], -2.0 * quarter - 3.0), "{d:?}"); + assert!(d[4..].iter().all(|&x| near(x, -2.0 * quarter - 3.0)), "{d:?}"); +} + #[test] fn mojikumi_one_em_line_end_set_sets_closing_punctuation_full_width_at_line_end() { let family = "Mojikumi Full Stop"; @@ -8125,6 +8582,74 @@ fn a_word_longer_than_the_line_breaks_at_the_column_edge() { } } +#[test] +fn a_web_address_breaks_after_a_dot_between_letters_but_a_decimal_stays_whole() { + use designcraft_doc::Composer; + let width = |t: &str| { + let l = &tracked_lines(t, 1e5, ParaAttrs::default(), 0.0)[0]; + l.end_x - l.x0 + }; + let host = "visit example.org/x1"; + let measure = width("visit example.") + 1.0; + for composer in [Composer::Paragraph, Composer::SingleLine] { + let para = ParaAttrs { composer: Some(composer), ..Default::default() }; + let lines = tracked_lines(host, measure, para.clone(), 0.0); + assert_eq!(&host[lines[0].range.clone()].trim_end(), &"visit example.", "{composer:?}"); + let dec = "pay 12.50 now"; + let lines = tracked_lines(dec, width("pay 12.") + 1.0, para.clone(), 0.0); + assert!(lines.iter().all(|l| !dec[l.range.clone()].trim().ends_with('.')), "{composer:?}"); + let para = ParaAttrs { hyphenate: Some(false), ..para }; + for (text, head) in + [("see the e.g. note", "see the e."), ("made in the U.S.A. today", "made in the U."), ("she holds a Ph.D. now", "she holds a Ph.")] + { + let lines = tracked_lines(text, width(head) + 1.0, para.clone(), 0.0); + let words: Vec<_> = lines.iter().flat_map(|l| text[l.range.clone()].split_whitespace()).collect(); + assert_eq!(words, text.split_whitespace().collect::>(), "{composer:?}"); + } + } +} + +#[test] +fn accented_abbreviations_stay_whole_in_both_composers() { + use designcraft_doc::Composer; + for composer in [Composer::Paragraph, Composer::SingleLine] { + let para = ParaAttrs { composer: Some(composer), hyphenate: Some(false), ..Default::default() }; + for prefix in ["Pé", "Pe\u{301}"] { + let head = format!("read {prefix}."); + let wide = tracked_lines(&head, 1e5, para.clone(), 0.0); + let width = wide[0].end_x - wide[0].x0 + 1.0; + let text = format!("{head}Do now"); + let lines = tracked_lines(&text, width, para.clone(), 0.0); + let words: Vec<_> = lines.iter().flat_map(|l| text[l.range.clone()].split_whitespace()).collect(); + assert_eq!(words, text.split_whitespace().collect::>(), "{composer:?}: {text}"); + } + } +} + +#[test] +fn dot_break_counts_source_letters_once_per_shaping_cluster() { + // Model a ligature on either side of the dot, including a multibyte letter. + let text = "aéb.De"; + let mut glyphs = shape_for_script_test(text); + glyphs.retain(|g| g.len > 0 && !matches!(g.byte, 1 | 6)); + glyphs[0].len = "aé".len(); + glyphs[3].len = "De".len(); + assert!(breaker::dot_break(text, &glyphs, 2)); + glyphs[0].len = 2; // Ends inside é. + assert!(!breaker::dot_break(text, &glyphs, 2)); + + let text = "Pe\u{301}.Do"; + let mut glyphs = shape_for_script_test(text); + glyphs.retain(|g| g.len > 0 && g.byte != 2); + let base = glyphs.iter().position(|g| g.byte == 1 && g.len > 0).unwrap(); + glyphs[base].len = "e\u{301}".len(); + let mut extra = glyphs[base].clone(); + extra.len = 0; + glyphs.insert(base + 1, extra); + let dot = glyphs.iter().position(|g| g.ch == '.').unwrap(); + assert!(!breaker::dot_break(text, &glyphs, dot)); +} + #[test] fn a_line_that_exactly_fills_the_measure_fits() { use designcraft_doc::Composer; @@ -10511,6 +11036,49 @@ fn cross_reference_text_breaks_at_its_spaces() { } } +/// A font with small caps of its own keeps them (Source Sans 3 has `smcp`), and one without gets +/// them drawn: the lowercase letters are set as capitals at 70%, while a capital already in the run +/// keeps its size. That is the case the report hit, where All Caps worked and Small Caps did nothing. +#[test] +fn small_caps_come_from_the_font_or_are_drawn_when_it_has_none() { + use designcraft_doc::Capitalization; + let text = "ab A"; + + let composed = |family: &str, caps: Capitalization| { + let (mut d, sid, _) = doc_with(text, Rect::new(72.0, 36.0, 372.0, 136.0), ParaAttrs::default()); + d.story_mut(sid).unwrap().format_chars(0..text.len(), |f| { + f.over.font_family = Some(family.into()); + f.over.size = Some(20.0); + f.over.capitalization = Some(caps); + }); + let cs = compose_story(&d, sid, &Default::default()); + cs.frames[0].lines[0].glyphs.iter().map(|g| (g.byte, g.gid, g.adv, g.sx, g.rendered_char)).collect::>() + }; + + // Inter ships without `smcp`; Source Sans 3 has it. + let plain = composed("Inter", Capitalization::Normal); + let small = composed("Inter", Capitalization::SmallCaps); + let at = |gs: &[(usize, u32, f64, f64, char)], byte: usize| gs.iter().find(|g| g.0 == byte).cloned().unwrap(); + let (_, a_plain, _adv_plain, _, _) = at(&plain, 0); + let (_, cap_plain, adv_cap, _, _) = at(&plain, 3); + let (_, small_a, adv_a, sx_a, ch_a) = at(&small, 0); + let (_, small_cap, adv_upper, sx_cap, _) = at(&small, 3); + assert_eq!(ch_a, 'a', "the run still reads a"); + assert_eq!(small_a, cap_plain, "the a is drawn with the glyph of an A"); + assert_eq!(small_a, small_cap, "the same glyph the run's own A uses"); + assert!((adv_a / adv_cap - 0.7).abs() < 1e-6, "the small a takes 70%: {} / {}", adv_a, adv_cap); + assert!((adv_upper - adv_cap).abs() < 1e-9, "the capital keeps its advance: {} vs {}", adv_upper, adv_cap); + assert!((sx_a / sx_cap - 0.7).abs() < 1e-6, "and its drawing is scaled by the same 0.7"); + assert_ne!(a_plain, cap_plain, "in the plain run the two letters differ"); + + // With Source Sans 3 the font sets them: its `smcp` gives a small-capital glyph of its own, + // not the uppercased A we would draw. + let named = composed("Source Sans 3", Capitalization::SmallCaps); + let (_, a_named, _, _, _) = at(&named, 0); + assert_ne!(a_named, cap_plain, "the a takes the font's small capital, not an uppercased A"); + assert_ne!(a_named, a_plain, "and it is not the plain a either"); +} + /// A story numbering list `list` (continuing across stories; Upper Roman, no tab after the /// number) in a frame at `r` on `page`. fn listed_story(d: &mut Document, page: usize, r: Rect, text: &str, list: &str) -> StoryId { @@ -10575,6 +11143,66 @@ fn a_neighbours_numbering_moves_the_text_its_objects_wrap() { assert_eq!(line_layout(&cache.get(&d, b, None)), fresh); } +#[test] +fn a_neighbours_file_name_variable_moves_the_text_its_objects_wrap() { + // Regression: a variable-free story wrapped by a neighbour's anchored object kept its cached + // lines when the document title changed, though a longer File Name pushed the object's anchor + // onto the next line. + let long = [LOREM; 3].join(" "); + let mut d = Document::new(&NewDocument { pages: 1, facing_pages: false, title: "A".into(), ..Default::default() }); + let lid = d.default_layer(); + let var = designcraft_doc::vars::var_char(d.variable("File Name").unwrap()).unwrap(); + let (fa, a) = + d.add_text_frame(SpreadRef::Doc(0), Rect::new(0.0, 0.0, 80.0, 400.0), lid, &format!("{var} Anchor"), ParaFormat::default()).unwrap(); + let (_, b) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(320.0, 0.0, 620.0, 400.0), lid, &long, ParaFormat::default()).unwrap(); + let left = all_lines(&compose_story(&d, b, &ComposeOptions::default()))[0].x0; + let area = d.item(fa).unwrap().text_area(); + let end = d.story(a).unwrap().len(); + anchor_box(&mut d, a, end, left - area.x0, 20.0, true, WrapMode::BoundingBox); + let cache = Cache::new(); + let before = line_layout(&cache.get(&d, b, None)); + assert_eq!(before, line_layout(&compose_story(&d, b, &ComposeOptions::default()))); + d.title = "A Much Longer Document File Name".into(); + let fresh = line_layout(&compose_story(&d, b, &ComposeOptions::default())); + assert_ne!(fresh, before, "the longer file name moves the wrapping object"); + assert_eq!(line_layout(&cache.get(&d, b, None)), fresh); +} + +#[test] +fn cached_cell_and_footnote_file_name_variables_update_on_rename() { + // Regression: a story whose only File Name variable sits in a table cell or footnote kept its + // cached composition after a title change because `has_vars` inspected only outer `story.text`. + let glyphs = |cs: &ComposedStory| -> usize { + cs.frames.iter().flat_map(|f| f.lines.iter()).map(|l| l.glyphs.iter().filter(|g| g.visible && g.adv > 0.0).count()).sum() + }; + + // Table cell only. + let (mut d, sid, _) = table_doc(Rect::new(0.0, 0.0, 400.0, 400.0), designcraft_doc::Table::new(77, 1, 1, 0, 0, 300.0)); + d.title = "Short".into(); + let var = designcraft_doc::vars::var_char(d.variable("File Name").unwrap()).unwrap().to_string(); + Arc::make_mut(d.story_mut(sid).unwrap().tables.values_mut().next().unwrap()).cell_mut(0, 0).unwrap().text.insert(0, &var); + let cache = Cache::new(); + let before = glyphs(&cache.get(&d, sid, None).frames[0].tables[0].cells[0].text); + d.title = "CatalogEdition".into(); + let fresh = glyphs(&compose_story(&d, sid, &ComposeOptions::default()).frames[0].tables[0].cells[0].text); + let after = glyphs(&cache.get(&d, sid, None).frames[0].tables[0].cells[0].text); + assert!(fresh > before, "rename lengthens the cell text: {before} -> {fresh}"); + assert_eq!(after, fresh); + + // Footnote only. + let (mut d, sid, _) = doc_with("Body text.", Rect::new(36.0, 36.0, 400.0, 400.0), ParaAttrs::default()); + d.title = "Short".into(); + let var = designcraft_doc::vars::var_char(d.variable("File Name").unwrap()).unwrap().to_string(); + d.story_mut(sid).unwrap().insert_note(4, &var, ParaFormat::default()); + let cache = Cache::new(); + let before = glyphs(&cache.get(&d, sid, None).frames[0].notes[0].text); + d.title = "CatalogEdition".into(); + let fresh = glyphs(&compose_story(&d, sid, &ComposeOptions::default()).frames[0].notes[0].text); + let after = glyphs(&cache.get(&d, sid, None).frames[0].notes[0].text); + assert!(fresh > before, "rename lengthens the footnote text: {before} -> {fresh}"); + assert_eq!(after, fresh); +} + #[test] fn many_stories_in_continuing_lists_compose_quickly() { // Regression: each story's cache lookup searched the whole item tree per story and per list diff --git a/crates/compose/src/vars.rs b/crates/compose/src/vars.rs index bd9e32ccd..96b817eb9 100644 --- a/crates/compose/src/vars.rs +++ b/crates/compose/src/vars.rs @@ -9,14 +9,31 @@ use designcraft_doc::{Document, SpreadRef, Story, StoryId}; use crate::ComposedStory; -/// Does the story contain any text variable instance? -pub fn has_vars(st: &Story) -> bool { - st.text.chars().any(|c| var_index(c).is_some()) +const MAX_NESTING: usize = 32; + +fn story_any(st: &Story, depth: usize, f: &impl Fn(&Story) -> bool) -> bool { + if f(st) { + return true; + } + if depth >= MAX_NESTING { + return false; + } + st.tables.values().flat_map(|t| &t.cells).any(|c| story_any(&c.text, depth + 1, f)) + || st.notes.iter().chain(&st.endnotes).any(|n| story_any(&n.text, depth + 1, f)) } -/// Does the story contain a running-header variable instance? +/// Does the story (or any embedded table cell, footnote or endnote) contain a text variable +/// instance? +pub fn has_vars(st: &Story) -> bool { + story_any(st, 0, &|s| s.text.chars().any(|c| var_index(c).is_some())) +} + +/// Does the story (or any embedded table cell, footnote or endnote) contain a running-header +/// variable instance? pub fn has_running(doc: &Document, st: &Story) -> bool { - st.text.chars().filter_map(var_index).any(|i| matches!(doc.text_variables.get(i).map(|v| &v.kind), Some(VarKind::RunningHeader { .. }))) + story_any(st, 0, &|s| { + s.text.chars().filter_map(var_index).any(|i| matches!(doc.text_variables.get(i).map(|v| &v.kind), Some(VarKind::RunningHeader { .. }))) + }) } /// Absolute page showing story byte `pos` of a composed story. diff --git a/crates/compose/tests/autocraft_regression_2486.rs b/crates/compose/tests/autocraft_regression_2486.rs new file mode 100644 index 000000000..01ab607d7 --- /dev/null +++ b/crates/compose/tests/autocraft_regression_2486.rs @@ -0,0 +1,71 @@ +//! Justified Arabic puts its one kashida per word at the join typography prefers, and none where +//! every join is forbidden (#2486). + +use std::collections::BTreeSet; + +use designcraft_compose::{ComposeOptions, compose_story}; +use designcraft_doc::build::NewDocument; +use designcraft_doc::{Align, Document, ParaAttrs, ParaFormat, SpreadRef, TextDirection}; +use designcraft_fonts::FontDb; +use designcraft_fonts::testing::font_mapping; +use designcraft_geom::Rect; + +const FAMILY: &str = "DC Kashida Rules"; + +/// Installs a font that draws every Arabic letter used below as a Latin letter, and the tatweel as +/// an underscore, so the test does not depend on the fonts of the machine. +fn install_font() { + let letters = "ابتثحدرزسصضعغفقكلمنهةوىي"; + let mut glyphs: Vec<(char, char)> = letters.chars().zip('a'..='z').collect(); + glyphs.extend([('\u{0640}', '_'), (' ', ' ')]); + FontDb::global().add_font(font_mapping(FAMILY, &glyphs).unwrap()); +} + +/// The positions (in letters) of the letters before which kashidas are drawn when `word`, repeated +/// on justified lines of several widths, is stretched. +fn kashida_letters(word: &str) -> BTreeSet { + let text = vec![word; 40].join(" "); + let mut found = BTreeSet::new(); + for width in (60..=140).step_by(4) { + let mut d = Document::new(&NewDocument::default()); + let lid = d.default_layer(); + let para = ParaAttrs { align: Some(Align::RightJustified), direction: Some(TextDirection::RightToLeft), ..Default::default() }; + let rect = Rect::new(0.0, 0.0, f64::from(width), 800.0); + let (_, sid) = d.add_text_frame(SpreadRef::Doc(0), rect, lid, &text, ParaFormat { para, ..Default::default() }).unwrap(); + d.story_mut(sid).unwrap().format_chars(0..text.len(), |f| f.over.font_family = Some(FAMILY.into())); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + assert!(cs.frames[0].lines.len() > 2, "{word} at {width}"); + for g in cs.frames[0].lines.iter().flat_map(|l| &l.glyphs) { + if g.len == 0 && g.gid == g.face.glyph_for('\u{0640}') { + let start = text[..g.byte].rfind(' ').map_or(0, |s| s + 1); + found.insert(text[start..g.byte].chars().count()); + } + } + } + found +} + +#[test] +fn kashidas_follow_the_typographic_rules() { + install_font(); + let words = [ + ("تصوم", None), + ("نقود", None), + ("يوم", None), + ("لبني", Some(1)), + ("هين", Some(0)), + ("الكتاب", Some(3)), + ("مدرسة", Some(3)), + ("بكر", Some(0)), + ("بلد", Some(0)), + ("بتم", Some(0)), + ("بيت", Some(0)), + ("بنت", Some(0)), + ("كبير", Some(1)), + ("تبر", Some(0)), + ("سير", Some(0)), + ]; + for (word, expected) in words { + assert_eq!(kashida_letters(word), expected.into_iter().collect::>(), "{word}"); + } +} diff --git a/crates/doc/src/attrs/language.rs b/crates/doc/src/attrs/language.rs index a116bf754..e8b1ffe52 100644 --- a/crates/doc/src/attrs/language.rs +++ b/crates/doc/src/attrs/language.rs @@ -89,6 +89,17 @@ pub fn language_tag(language: &str) -> Option<&'static str> { "hebrew" => "he", "georgian" => "ka", "esperanto" => "eo", + "hindi" => "hi", + "marathi" => "mr", + "bengali" | "bangla" => "bn", + "assamese" => "as", + "gujarati" => "gu", + "punjabi" | "panjabi" => "pa", + "odia" | "oriya" => "or", + "tamil" => "ta", + "telugu" => "te", + "kannada" => "kn", + "malayalam" => "ml", _ => return None, }) } diff --git a/crates/doc/src/attrs/tests.rs b/crates/doc/src/attrs/tests.rs index 78c62b77b..fa6cf9649 100644 --- a/crates/doc/src/attrs/tests.rs +++ b/crates/doc/src/attrs/tests.rs @@ -94,6 +94,32 @@ fn language_names_map_to_bcp47_tags() { assert_eq!(language_tag(""), None); } +/// Indian languages by the names the Language menu and IDML use, so their text gets the font's +/// localized forms (Marathi ल and श) and hyphenates with its own patterns. +#[test] +fn indian_language_names_map_to_their_tags() { + for (name, tag) in [ + ("Hindi", "hi"), + ("Marathi", "mr"), + ("Bengali", "bn"), + ("Bangla", "bn"), + ("Assamese", "as"), + ("Gujarati", "gu"), + ("Punjabi", "pa"), + ("Panjabi", "pa"), + ("Odia", "or"), + ("Oriya", "or"), + ("Tamil", "ta"), + ("Telugu", "te"), + ("Kannada", "kn"), + ("Malayalam", "ml"), + ("$ID/Malayalam", "ml"), + ] { + assert_eq!(language_tag(name), Some(tag), "{name}"); + } + assert_eq!(language_tag("hi_IN"), Some("hi-IN")); +} + #[test] fn chinese_japanese_and_korean_names_map_in_their_common_spellings() { for (name, tag) in [ diff --git a/crates/doc/src/item/paint.rs b/crates/doc/src/item/paint.rs index dfbf5751a..1a483b428 100644 --- a/crates/doc/src/item/paint.rs +++ b/crates/doc/src/item/paint.rs @@ -191,6 +191,27 @@ impl StrokeType { && length / period <= MAX_DASH_PERIODS } + /// The dash pattern to draw for a dashed stroke `weight` points wide, or `None` for a type + /// that is not dashed. + /// + /// A dashed stroke with no pattern of its own is drawn three weights on, two off: that is + /// what `type: "dashed"` on a table cell stroke and a dashed paragraph border have always + /// resolved to, and it is the only pattern an IDML `StrokeStyle/$ID/Dashed` carries (the + /// built-in dashed styles name no array). Without it such a stroke drew solid (#1467). + pub fn dashes(&self, weight: f64) -> Option> { + let StrokeType::Dashed { pattern } = self else { return None }; + let kept: Vec = pattern.iter().copied().filter(|v| v.is_finite() && *v >= 0.0).collect(); + // No pattern at all (or only zeros, which no command accepts and only a file can carry): + // the dashes come from the weight. A pattern that is there but degenerate is left alone, + // so [`StrokeType::expandable_dashes`] still draws it solid rather than expanding 10^8 + // dashes along an edge. + if kept.iter().all(|v| *v == 0.0) { + let w = weight.max(1.0); + return Some(vec![w * 3.0, w * 2.0]); + } + Some(kept) + } + /// The bands of a striped type (start, width as fractions of the weight). pub fn bands(&self) -> Option> { Some(match self { @@ -355,3 +376,27 @@ impl Stroke { self.swatch == designcraft_color::swatch::NONE || self.weight <= 0.0 } } + +/// A dashed stroke with no pattern of its own — an IDML `StrokeStyle/$ID/Dashed`, or +/// `type: "dashed"` with no array — dashes by its weight instead of drawing solid (#1467). +#[test] +fn a_dashed_stroke_without_a_pattern_dashes_by_its_weight() { + let dashed = |p: Vec| StrokeType::Dashed { pattern: p }; + assert_eq!(dashed(vec![]).dashes(1.0), Some(vec![3.0, 2.0])); + assert_eq!(dashed(vec![]).dashes(4.0), Some(vec![12.0, 8.0])); + // A hairline still dashes visibly: the weight counts as at least a point. + assert_eq!(dashed(vec![]).dashes(0.25), Some(vec![3.0, 2.0])); + // Only zeros is nothing specified too (no command accepts such a pattern). + assert_eq!(dashed(vec![0.0, 0.0]).dashes(2.0), Some(vec![6.0, 4.0])); + // A pattern of its own is kept, as are the entries of a degenerate one, which + // `expandable_dashes` then refuses so that it draws solid rather than expanding forever. + assert_eq!(dashed(vec![6.0, 3.0]).dashes(2.0), Some(vec![6.0, 3.0])); + assert_eq!(dashed(vec![1e-6, 1e-6]).dashes(2.0), Some(vec![1e-6, 1e-6])); + assert!(!StrokeType::expandable_dashes(&[1e-6, 1e-6], 200.0)); + // Negative and non-finite entries are dropped, as every drawing site did before. + assert_eq!(dashed(vec![6.0, -1.0, f64::NAN, 3.0]).dashes(1.0), Some(vec![6.0, 3.0])); + // Nothing else has dashes. + assert_eq!(StrokeType::Solid.dashes(1.0), None); + assert_eq!(StrokeType::Dotted.dashes(1.0), None); + assert_eq!(StrokeType::Style { name: "x".into() }.dashes(1.0), None); +} diff --git a/crates/doc/src/mojikumi.rs b/crates/doc/src/mojikumi.rs index 9ef52355b..af2a97da3 100644 --- a/crates/doc/src/mojikumi.rs +++ b/crates/doc/src/mojikumi.rs @@ -146,7 +146,25 @@ impl<'a> Rules<'a> { } let punctuation = trailing(left).max(leading(right)); if punctuation > 0.0 { - return Aki { min: 0.0, desired: punctuation, max: punctuation, priority: 1, discrete: false }; + // The Japanese sets take a line in at the quarter ems of middle dots (・:;) first, then + // at the half ems of brackets and commas, and don't reduce the space after a full stop + // (JLREQ 3.8.3). !? share the first tier: JLREQ sets them solid (Table 1) and + // gives the quarter em only as an alternative (3.1.6), so reducing it first returns + // to that default. The tier follows the character classes, not the blank's size. The + // Chinese sets reduce all punctuation blanks together. + let japanese = self.base != Base::Chinese; + // After: closing brackets (2, 28 」, 29 )), full stops (6 。, 31 .) and commas + // (21 、, 30 ,). Before: opening brackets (1, 26 「, 27 (). + let bracket_or_comma = matches!(left, 2 | 6 | 21 | 28..=31) || matches!(right, 1 | 26 | 27); + // Full stops: 6 。 and 31 .. + let full_stop = matches!(left, 6 | 31); + return Aki { + min: if japanese && full_stop { punctuation } else { 0.0 }, + desired: punctuation, + max: punctuation, + priority: if japanese && bracket_or_comma { 2 } else { 1 }, + discrete: false, + }; } let roman = |c| matches!(c, 18 | 25); let ideograph = |c| matches!(c, 3 | 7..=9 | 11 | 12 | 24 | 33); @@ -331,4 +349,38 @@ mod tests { assert_eq!((a.min, a.desired, a.max, a.priority), (b.min, b.desired, b.max, b.priority), "{l}/{r}"); } } + + #[test] + fn middle_dots_reduce_first_and_a_full_stops_space_never() { + let styles = Styles::default(); + for set in ["LineEndAllOneHalfEmEnum", "LineEndAllOneEmEnum"] { + let rules = Rules::resolve(&styles, set).unwrap().unwrap(); + let aki = |a: char, b: char| rules.pair(class(a), class(b)); + // Middle dots' quarter ems, then brackets' and commas' half ems, then wa-ō aki. + let (dot, after_dot, comma, close, open, wa_ou) = + (aki('漢', '・'), aki('・', '漢'), aki('、', '漢'), aki('」', '漢'), aki('漢', '「'), aki('漢', 'A')); + assert!(dot.priority == after_dot.priority && dot.priority < comma.priority, "{set}"); + assert!(comma.priority == close.priority && close.priority == open.priority && open.priority < wa_ou.priority, "{set}"); + assert_eq!((dot.min, comma.min, close.min, open.min), (0.0, 0.0, 0.0, 0.0), "{set}"); + // The tier follows the class: :;!? share the middle dots' tier, and a bracket's half + // em beside one of them stays with the brackets. + for (a, b) in [('漢', ':'), (';', '漢'), ('漢', '!'), ('?', '漢')] { + assert_eq!(aki(a, b).priority, dot.priority, "{set}: {a}{b}"); + } + assert_eq!(aki('!', '「').priority, open.priority, "{set}: !「"); + // After a full stop the half em stays, before an opening bracket too. + for b in ['漢', '「'] { + let a = aki('。', b); + assert_eq!((a.min, a.desired), (0.5, 0.5), "{set}: 。{b}"); + } + } + // The Chinese sets are unchanged: every punctuation blank reduces together, to nothing. + for set in ["SimpChineseDefault", "TradChineseDefault"] { + let rules = Rules::resolve(&styles, set).unwrap().unwrap(); + for (a, b) in [('漢', '・'), ('、', '漢'), ('」', '漢'), ('漢', '「'), ('。', '漢')] { + let aki = rules.pair(class(a), class(b)); + assert_eq!((aki.min, aki.priority), (0.0, 1), "{set}: {a}{b}"); + } + } + } } diff --git a/crates/doc/src/selection.rs b/crates/doc/src/selection.rs index a2dcf29da..51e79f9f6 100644 --- a/crates/doc/src/selection.rs +++ b/crates/doc/src/selection.rs @@ -71,6 +71,16 @@ impl TextSel { } } +/// An anchored object (inline, above line or custom) selected as an object: the `index`-th of +/// `story`'s [`crate::Story::objects`]. It lives in the text, not on a spread, so it isn't one of +/// [`Selection::items`]. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AnchoredSel { + pub story: StoryId, + pub index: usize, +} + #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct Selection { @@ -100,11 +110,14 @@ pub struct Selection { /// the other. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub guides: Vec, + /// An anchored object selected with the Selection tool. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub anchored: Option, } impl Selection { pub fn is_empty(&self) -> bool { - self.items.is_empty() && self.text.is_none() && self.cells.is_none() + self.items.is_empty() && self.text.is_none() && self.cells.is_none() && self.anchored.is_none() } pub fn len(&self) -> usize { self.items.len() diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index e88c83355..a86bff2a8 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -85,6 +85,13 @@ use crate::{EngineError, Result, Session}; pub type Run = fn(&mut Session, &Value) -> Result; pub type Enabled = fn(&Session) -> std::result::Result<(), String>; +/// Internal success-postpass policy; no command-info/serialized API change. +#[derive(Clone, Copy)] +pub(crate) enum SuccessPasses { + Always, + IfDocumentChanged(fn(&Session, &Value) -> Option), +} + pub struct CommandSpec { pub id: &'static str, pub label: &'static str, @@ -97,6 +104,8 @@ pub struct CommandSpec { pub journal: bool, /// Record an undo step when the document changes. pub undoable: bool, + /// Opt-in only: an unchanged handler must not trigger unrelated pending layout work. + pub(crate) success_passes: SuccessPasses, } #[derive(Clone, Debug, Serialize)] @@ -147,6 +156,12 @@ pub fn has_selection(s: &Session) -> std::result::Result<(), String> { has_doc(s)?; if s.active().is_some_and(|d| !d.selection.items.is_empty()) { Ok(()) } else { Err(NOTHING_SELECTED.into()) } } +/// Objects or ruler guides: Step and Repeat copies either, so a page with only a guide selected +/// keeps the command awake. +pub fn has_selection_or_guides(s: &Session) -> std::result::Result<(), String> { + has_doc(s)?; + if s.active().is_some_and(|d| !d.selection.items.is_empty() || !d.selection.guides.is_empty()) { Ok(()) } else { Err(NOTHING_SELECTED.into()) } +} pub fn has_text(s: &Session) -> std::result::Result<(), String> { has_doc(s)?; if s.active().is_some_and(|d| d.selection.text.is_some()) { Ok(()) } else { Err("no text insertion point".into()) } @@ -161,14 +176,20 @@ pub fn has_text_or_frames(s: &Session) -> std::result::Result<(), String> { } macro_rules! cmd { + (on_document_change($noop:expr) $id:literal, $label:literal, [$($m:literal),*], $sc:expr, $params:literal, $en:expr, $run:expr) => { + $crate::cmd::CommandSpec { + success_passes: $crate::cmd::SuccessPasses::IfDocumentChanged($noop), + ..$crate::cmd::cmd!($id, $label, [$($m),*], $sc, $params, $en, $run) + } + }; ($id:literal, $label:literal, [$($m:literal),*], $sc:expr, $params:literal, $en:expr, $run:expr) => { - $crate::cmd::CommandSpec { id: $id, label: $label, menu: &[$($m),*], shortcut: $sc, params: $params, enabled: $en, run: $run, journal: true, undoable: true } + $crate::cmd::CommandSpec { id: $id, label: $label, menu: &[$($m),*], shortcut: $sc, params: $params, enabled: $en, run: $run, journal: true, undoable: true, success_passes: $crate::cmd::SuccessPasses::Always } }; (query $id:literal, $label:literal, [$($m:literal),*], $sc:expr, $params:literal, $en:expr, $run:expr) => { - $crate::cmd::CommandSpec { id: $id, label: $label, menu: &[$($m),*], shortcut: $sc, params: $params, enabled: $en, run: $run, journal: false, undoable: false } + $crate::cmd::CommandSpec { id: $id, label: $label, menu: &[$($m),*], shortcut: $sc, params: $params, enabled: $en, run: $run, journal: false, undoable: false, success_passes: $crate::cmd::SuccessPasses::Always } }; (noundo $id:literal, $label:literal, [$($m:literal),*], $sc:expr, $params:literal, $en:expr, $run:expr) => { - $crate::cmd::CommandSpec { id: $id, label: $label, menu: &[$($m),*], shortcut: $sc, params: $params, enabled: $en, run: $run, journal: true, undoable: false } + $crate::cmd::CommandSpec { id: $id, label: $label, menu: &[$($m),*], shortcut: $sc, params: $params, enabled: $en, run: $run, journal: true, undoable: false, success_passes: $crate::cmd::SuccessPasses::Always } }; } pub(crate) use cmd; diff --git a/crates/engine/src/cmd/anchored.rs b/crates/engine/src/cmd/anchored.rs index 45922647f..9c07d02bb 100644 --- a/crates/engine/src/cmd/anchored.rs +++ b/crates/engine/src/cmd/anchored.rs @@ -2,7 +2,9 @@ use std::sync::Arc; -use designcraft_doc::{AnchorPosition, AnchoredObject, Document, Item, ItemId, OBJECT_MARK, SpreadRef, StoryId, TextSel, anchored::AnchorAlign}; +use designcraft_doc::{ + AnchorPosition, AnchoredObject, AnchoredSel, Content, Document, Item, ItemId, OBJECT_MARK, SpreadRef, StoryId, TextSel, anchored::AnchorAlign, +}; use designcraft_geom::Affine; use serde_json::{Value, json}; @@ -25,7 +27,7 @@ pub fn specs() -> Vec { "Anchored Object Options…", ["Object", "Anchored Object"], None, - "{story?, index? (default: the object at the insertion point), position?: inline|aboveLine|custom, yOffset?, align?: left|center|right, spaceBefore?, spaceAfter?, xRelative? | yRelative?: anchor|textFrame|columnEdge|pageMargin|pageEdge, xOffset?, objectPoint? | refPoint?: 0..8, keepWithinColumn?, spineRelative? (custom: the settings describe a left-hand page and mirror on a right-hand page)}", + "{story?, index? (default: the selected anchored object, else the one at the insertion point), position?: inline|aboveLine|custom, yOffset?, align?: left|center|right, spaceBefore?, spaceAfter?, xRelative? | yRelative?: anchor|textFrame|columnEdge|pageMargin|pageEdge, xOffset?, objectPoint? | refPoint?: 0..8, keepWithinColumn?, spineRelative? (custom: the settings describe a left-hand page and mirror on a right-hand page)}", has_doc, options ), @@ -34,10 +36,28 @@ pub fn specs() -> Vec { "Release", ["Object", "Anchored Object"], None, - "{story?, index? (default: the object at the insertion point)} — puts the object back on the page where it is now and removes it from the text", + "{story?, index? (default: the selected anchored object, else the one at the insertion point)} — puts the object back on the page where it is now and removes it from the text", has_doc, release ), + cmd!( + noundo "anchored.select", + "Select Anchored Object", + [], + None, + "{story, index} — selects the anchored object as an object (the Selection tool clicking it); Delete removes it from the text, anchored.resize / options / release act on it", + has_doc, + select + ), + cmd!( + "anchored.resize", + "Resize Anchored Object", + [], + None, + "{story?, index? (default: the selected anchored object), from: rect, to: rect (the object's bounds before and after, in its own space: [x0, y0, x1, y1]), content?: bool (scale its content with it; default: the frame alone resizes and crops it from the sides that moved)} — the text then places it again and reflows around it", + has_doc, + resize + ), cmd!(query "anchored.list", "Anchored Objects", [], None, "{story?} → [{story, index, pos, position, size}]", has_doc, |s, p| { let d = &s.doc()?.doc; let only = p.get("story").and_then(Value::as_u64).map(StoryId); @@ -174,12 +194,43 @@ fn insert(s: &mut Session, p: &Value) -> Result { }) } -/// `{story, index}`, or the anchored object at (or just before) the text insertion point. +/// Whether the `k`-th anchored object of story `sid` can't be selected or changed: it, or the text +/// frame holding it, is locked or on a locked layer (as for other page items). +fn is_locked(s: &Session, sid: StoryId, k: usize) -> Result { + let d = &s.doc()?.doc; + let locked = |it: &designcraft_doc::Item| it.locked || d.layer(it.layer).is_some_and(|l| l.locked); + let o = d.story(sid).and_then(|st| st.objects.get(k)).ok_or_else(|| bad("anchored", "no such anchored object"))?; + if locked(&o.item) { + return Ok(true); + } + // The frame composition placed it in; before it is placed, any of the story's frames. + let cs = s.cache.get(d, sid, None); + let host = cs.frames.iter().find(|ft| ft.objects.iter().any(|x| x.index == k)).map(|ft| ft.frame); + let frames: Vec = match host { + Some(f) => vec![f], + None => d.story(sid).map(|st| st.frames.clone()).unwrap_or_default(), + }; + Ok(frames.iter().filter_map(|f| d.item(*f)).any(locked)) +} + +/// [`is_locked`] as the error a command returns. +fn check_unlocked(s: &Session, sid: StoryId, k: usize, cmd: &str) -> Result<()> { + if is_locked(s, sid, k)? { + return Err(bad(cmd, "the anchored object or its frame is locked, or on a locked layer")); + } + Ok(()) +} + +/// `{story, index}`, else the selected anchored object, else the one at (or just before) the text +/// insertion point. fn object_ref(s: &Session, p: &Value, cmd: &str) -> Result<(StoryId, usize)> { if let (Some(sid), Some(k)) = (p.get("story").and_then(Value::as_u64), p.get("index").and_then(Value::as_u64)) { - return Ok((StoryId(sid), k as usize)); + return Ok((StoryId(sid), usize::try_from(k).map_err(|_| bad(cmd, "index out of range"))?)); } let st = s.doc()?; + if let Some(a) = st.selection.anchored { + return Ok((a.story, a.index)); + } let t = st .selection .text @@ -195,8 +246,90 @@ fn object_ref(s: &Session, p: &Value, cmd: &str) -> Result<(StoryId, usize)> { Ok((t.story, story.text[..at].matches(OBJECT_MARK).count())) } +fn select(s: &mut Session, p: &Value) -> Result { + let sid = p.get("story").and_then(Value::as_u64).map(StoryId).ok_or_else(|| bad("anchored.select", "missing story"))?; + let k = p.get("index").and_then(Value::as_u64).and_then(|k| usize::try_from(k).ok()).ok_or_else(|| bad("anchored.select", "missing index"))?; + if s.doc()?.doc.story(sid).and_then(|x| x.objects.get(k)).is_none() { + return Err(bad("anchored.select", "no such anchored object")); + } + check_unlocked(s, sid, k, "anchored.select")?; + let st = s.doc_mut()?; + st.selection = designcraft_doc::Selection { anchored: Some(AnchoredSel { story: sid, index: k }), ..Default::default() }; + st.bump_revision(); + Ok(Value::Null) +} + +/// Resize an anchored object's frame from its bounds `from` to `to` (its own space): the content +/// keeps its place while the edges move, so a frame made narrower from the left crops the +/// picture's left side. Its top-left then returns to the origin, where composition places it, +/// and the text reflows around the new size. +fn resize(s: &mut Session, p: &Value) -> Result { + let (sid, k) = object_ref(s, p, "anchored.resize")?; + check_unlocked(s, sid, k, "anchored.resize")?; + let from = super::rect_param(p, "from").ok_or_else(|| bad("anchored.resize", "missing from"))?; + let to = super::rect_param(p, "to").ok_or_else(|| bad("anchored.resize", "missing to"))?; + let finite = |r: designcraft_geom::Rect| [r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite()); + if !finite(from) || !finite(to) || from.width().abs() < 1e-9 || from.height().abs() < 1e-9 { + return Err(bad("anchored.resize", "degenerate or non-finite rect")); + } + // At least a point each way, at most the largest page InDesign allows. + const MIN: f64 = 1.0; + const MAX: f64 = 15552.0; + let sx = to.width().abs().clamp(MIN, MAX) / from.width().abs(); + let sy = to.height().abs().clamp(MIN, MAX) / from.height().abs(); + // The dragged edges move and the content stays where it was on the page (InDesign crops a + // picture from the side whose handle moved). Then the text places the object again by its + // top-left, so after a left or top handle the frame and picture shift together. + let m = Affine::translate((to.x0.min(to.x1), to.y0.min(to.y1))) * Affine::scale_non_uniform(sx, sy) * Affine::translate((-from.x0, -from.y0)); + let content = p.get("content").and_then(Value::as_bool).unwrap_or(false); + let strokes = s.prefs.scale_strokes; + s.edit(|d, _| { + let st = d.story_mut(sid).ok_or(designcraft_doc::DocError::NoStory(sid))?; + let o = st.objects.get_mut(k).ok_or_else(|| bad("anchored.resize", "no such anchored object"))?; + let o = Arc::make_mut(o); + let it = &mut o.item; + if content { + super::object::scale_item(it, m, (sx * sy).sqrt(), strokes); + } else if matches!(it.content, Content::Group { .. }) { + it.xf = m * it.xf; + } else { + let inner = it.xf.inverse() * m * it.xf; + super::object::bake(it, inner); + let r = it.inner_bounds(); + if let Content::Graphic(g) = &mut it.content + && let Some(xf) = g.fitted(r, g.auto_fit) + { + g.xf = xf; + } + } + // Composition places the object by its top-left: keep that at the origin. + let b = it.bounds(); + it.xf = Affine::translate((-b.x0, -b.y0)) * it.xf; + let size = o.size(); + st.rev = st.rev.wrapping_add(1); + Ok(json!({"size": [size.0, size.1]})) + }) +} + +/// Delete a selected anchored object: its mark leaves the text, and the object with it. +pub(crate) fn delete(s: &mut Session, a: AnchoredSel) -> Result { + // A locked object keeps its place in the text (Delete does nothing to it, as to a locked item). + check_unlocked(s, a.story, a.index, "edit.clear")?; + let pos = { + let st = s.doc()?.doc.story(a.story).ok_or_else(|| bad("edit.clear", "no such story"))?; + st.text.match_indices(OBJECT_MARK).nth(a.index).map(|(i, _)| i).ok_or_else(|| bad("edit.clear", "no such anchored object"))? + }; + s.edit(|d, sel| { + let st = d.story_mut(a.story).ok_or(designcraft_doc::DocError::NoStory(a.story))?; + st.delete(pos..pos + OBJECT_MARK.len_utf8()); + *sel = designcraft_doc::Selection::default(); + Ok(json!({"deleted": 1})) + }) +} + fn options(s: &mut Session, p: &Value) -> Result { let (sid, k) = object_ref(s, p, "anchored.options")?; + check_unlocked(s, sid, k, "anchored.options")?; let cur = s.doc()?.doc.story(sid).and_then(|st| st.objects.get(k).cloned()).ok_or_else(|| bad("anchored.options", "no such anchored object"))?; let position = position_param(p, &cur.position)?; s.edit(|d, _| { @@ -210,6 +343,7 @@ fn options(s: &mut Session, p: &Value) -> Result { fn release(s: &mut Session, p: &Value) -> Result { let (sid, k) = object_ref(s, p, "anchored.release")?; + check_unlocked(s, sid, k, "anchored.release")?; let d0 = s.doc()?.doc.clone(); let st = d0.story(sid).ok_or_else(|| bad("anchored.release", "no such story"))?; let obj = st.objects.get(k).cloned().ok_or_else(|| bad("anchored.release", "no such anchored object"))?; @@ -259,6 +393,233 @@ fn release(s: &mut Session, p: &Value) -> Result { mod tests { use super::*; + /// A text frame whose story holds a 24 × 40 inline box: (session, story). + fn inline_box() -> (Session, StoryId) { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let r = s.execute("frame.create", &json!({"rect": [72, 72, 400, 400], "content": "text", "text": "Before after and more words."})).unwrap(); + let sid = s.doc().unwrap().doc.item(ItemId(r["id"].as_u64().unwrap())).unwrap().text_frame().unwrap().story; + let r = s.execute("frame.create", &json!({"rect": [450, 450, 474, 490]})).unwrap(); + s.execute("anchored.insert", &json!({"ids": [r["id"]], "story": sid.0, "pos": 7})).unwrap(); + (s, sid) + } + + /// Review of #1195: an anchored selection follows its object through edits of the story. An + /// object inserted before it moves it along; resizing it keeps it selected; deleting its + /// text deletes it from the selection too, so Delete never takes another object. + #[test] + fn an_anchored_selection_follows_its_object() { + let (mut s, sid) = inline_box(); + let id = |s: &Session, k: usize| s.doc().unwrap().doc.story(sid).unwrap().objects[k].item.id; + s.execute("anchored.select", &json!({"story": sid.0, "index": 0})).unwrap(); + let selected = id(&s, 0); + // Another object anchored at the start of the story, before the selected one. + let r = s.execute("frame.create", &json!({"rect": [450, 300, 470, 320]})).unwrap(); + s.execute("anchored.insert", &json!({"ids": [r["id"]], "story": sid.0, "pos": 0})).unwrap(); + // The selected object is now the second. + let st = s.doc_mut().unwrap(); + st.selection = designcraft_doc::Selection { anchored: Some(AnchoredSel { story: sid, index: 1 }), ..Default::default() }; + assert_eq!(id(&s, 1), selected); + // An edit that inserts an object before it: the selection moves with it. + s.edit(|d, _| { + let st = d.story_mut(sid).unwrap(); + let first = (*st.objects[0]).clone(); + let mut copy = first; + copy.item.id = ItemId(9_999); + st.insert_object(0, copy); + Ok(()) + }) + .unwrap(); + let a = s.doc().unwrap().selection.anchored.unwrap(); + assert_eq!((a.index, id(&s, a.index)), (2, selected), "follows its object"); + // Resizing keeps it selected. + s.execute("anchored.resize", &json!({"from": [0, 0, 24, 40], "to": [0, 0, 30, 40]})).unwrap(); + assert_eq!(s.doc().unwrap().selection.anchored.map(|a| a.index), Some(2)); + // Its text deleted with the object: nothing stays selected, rather than another object. + let pos = s.doc().unwrap().doc.story(sid).unwrap().text.match_indices(designcraft_doc::OBJECT_MARK).nth(2).unwrap().0; + s.edit(|d, _| { + d.story_mut(sid).unwrap().delete(pos..pos + designcraft_doc::OBJECT_MARK.len_utf8()); + Ok(()) + }) + .unwrap(); + assert_eq!(s.doc().unwrap().selection.anchored, None); + let _ = s.execute("edit.clear", &json!({})); + assert_eq!(s.doc().unwrap().doc.story(sid).unwrap().objects.len(), 2, "Delete took nothing"); + } + + /// A locked anchored object, one on a locked layer, or one in a locked frame or a frame on a + /// locked layer can't be selected, resized, deleted, changed in Anchored Object Options or + /// released: it stays in the text with its marker. + #[test] + fn locked_anchored_objects_are_left_alone() { + type Lock = fn(&mut designcraft_doc::Document, StoryId); + let lock_object: Lock = |d, sid| Arc::make_mut(&mut d.story_mut(sid).unwrap().objects[0]).item.locked = true; + let lock_object_layer: Lock = |d, sid| { + let layer = d.story(sid).unwrap().objects[0].item.layer; + d.layers.iter_mut().find(|l| l.id == layer).unwrap().locked = true; + }; + let lock_frame: Lock = |d, sid| { + let f = d.story(sid).unwrap().frames[0]; + d.item_mut(f).unwrap().locked = true; + }; + let lock_frame_layer: Lock = |d, sid| { + let f = d.story(sid).unwrap().frames[0]; + let layer = d.item(f).unwrap().layer; + d.layers.iter_mut().find(|l| l.id == layer).unwrap().locked = true; + }; + for (what, lock) in + [("object", lock_object), ("its layer", lock_object_layer), ("its frame", lock_frame), ("its frame's layer", lock_frame_layer)] + { + let (mut s, sid) = inline_box(); + // Selected before it is locked, so Delete and Resize meet the lock themselves. + s.execute("anchored.select", &json!({"story": sid.0, "index": 0})).unwrap(); + s.edit(|d, _| { + lock(d, sid); + Ok(Value::Null) + }) + .unwrap(); + assert!(s.execute("anchored.select", &json!({"story": sid.0, "index": 0})).is_err(), "{what}: select"); + assert!(s.execute("anchored.resize", &json!({"from": [0, 0, 24, 40], "to": [0, 0, 24, 60]})).is_err(), "{what}: resize"); + assert!(s.execute("edit.clear", &json!({})).is_err(), "{what}: delete"); + // Anchored Object Options and Release (on the selected object, as from the menu). + assert!(s.execute("anchored.options", &json!({"position": "aboveLine"})).is_err(), "{what}: options"); + assert!(s.execute("anchored.release", &json!({})).is_err(), "{what}: release"); + let st = s.doc().unwrap().doc.story(sid).unwrap().clone(); + assert_eq!(st.objects.len(), 1, "{what}: the object stays"); + assert_eq!(st.text.matches(OBJECT_MARK).count(), 1, "{what}: and its marker"); + assert_eq!(st.objects[0].size(), (24.0, 40.0), "{what}: at its size"); + assert!(matches!(st.objects[0].position, AnchorPosition::Inline { .. }), "{what}: inline still"); + } + } + + /// Placing a graphic selects the new frame alone: a selected anchored object is deselected. + #[test] + fn placing_a_graphic_deselects_an_anchored_object() { + let (mut s, sid) = inline_box(); + s.execute("anchored.select", &json!({"story": sid.0, "index": 0})).unwrap(); + // A video (any bytes: media is placed by its name) gets a media frame of its own. + let b64 = crate::cmd::base64_encode(b"not really a video"); + let r = s.execute("file.place", &json!({"name": "clip.mp4", "base64": b64, "x": 500, "y": 500})).unwrap(); + let sel = s.doc().unwrap().selection.clone(); + assert_eq!(sel.items, [ItemId(r["id"].as_u64().unwrap())]); + assert_eq!(sel.anchored, None, "not both the new frame and the anchored object"); + } + + #[test] + fn a_selected_inline_object_resizes_and_the_line_follows() { + let (mut s, sid) = inline_box(); + s.execute("anchored.select", &json!({"story": sid.0, "index": 0})).unwrap(); + let sel = s.doc().unwrap().selection.clone(); + assert_eq!(sel.anchored, Some(AnchoredSel { story: sid, index: 0 })); + assert!(sel.items.is_empty() && sel.text.is_none() && !sel.is_empty()); + // Taller by its bottom handle: the line grows to fit it; its top-left stays at the origin. + let r = s.execute("anchored.resize", &json!({"from": [0, 0, 24, 40], "to": [0, 0, 24, 60]})).unwrap(); + assert_eq!(r["size"], json!([24.0, 60.0])); + let d = s.doc().unwrap().doc.clone(); + let b = d.story(sid).unwrap().objects[0].item.bounds(); + assert!(b.x0.abs() < 1e-9 && b.y0.abs() < 1e-9, "{b:?}"); + let cs = s.cache.get(&d, sid, None); + let o = &cs.frames[0].objects[0]; + assert!(cs.frames[0].lines[o.line].ascent >= 60.0); + // Narrower from its left handle: still at the origin, 10 pt wide. + s.execute("anchored.resize", &json!({"from": [0, 0, 24, 60], "to": [14, 0, 24, 60]})).unwrap(); + let o = s.doc().unwrap().doc.story(sid).unwrap().objects[0].clone(); + assert_eq!(o.size(), (10.0, 60.0)); + assert!(o.item.bounds().x0.abs() < 1e-9); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc.story(sid).unwrap().objects[0].size(), (24.0, 40.0)); + } + + #[test] + fn a_left_or_top_handle_crops_that_side_of_the_picture() { + let (mut s, sid) = inline_box(); + let graphic = designcraft_doc::Graphic { + asset: designcraft_doc::AssetId(1), + size: (24.0, 40.0), + xf: Affine::IDENTITY, + clip: None, + auto_fit: Default::default(), + fit_align: 4, + crop: [0.0; 4], + wrap: Default::default(), + fill: Default::default(), + layer_options: Default::default(), + }; + s.edit(|d, _| { + let it = &mut Arc::make_mut(&mut d.story_mut(sid).unwrap().objects[0]).item; + // At the frame's top-left, in its inner space. + let inner = it.inner_bounds(); + it.content = Content::Graphic(designcraft_doc::Graphic { xf: Affine::translate((inner.x0, inner.y0)), ..graphic.clone() }); + Ok(Value::Null) + }) + .unwrap(); + // The picture's top-left relative to the frame's. + let offset = |s: &Session| { + let it = s.doc().unwrap().doc.story(sid).unwrap().objects[0].item.clone(); + let Content::Graphic(g) = &it.content else { panic!() }; + let b = it.bounds(); + ((it.xf * g.xf) * designcraft_geom::Point::ORIGIN - designcraft_geom::Point::new(b.x0, b.y0), b) + }; + s.execute("anchored.select", &json!({"story": sid.0, "index": 0})).unwrap(); + // The left handle 10 pt right and the top handle 20 pt down: the picture stayed put while + // those edges moved, so its left 10 and top 20 points are cropped. + s.execute("anchored.resize", &json!({"from": [0, 0, 24, 40], "to": [10, 20, 24, 40]})).unwrap(); + let (d, b) = offset(&s); + assert!((b.width() - 14.0).abs() < 1e-9 && (b.height() - 20.0).abs() < 1e-9 && b.x0.abs() < 1e-9 && b.y0.abs() < 1e-9, "{b:?}"); + assert!((d.x + 10.0).abs() < 1e-9 && (d.y + 20.0).abs() < 1e-9, "{d:?}"); + // The right and bottom handles leave the picture at the frame's top-left. + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("anchored.resize", &json!({"from": [0, 0, 24, 40], "to": [0, 0, 30, 50]})).unwrap(); + let (d, _) = offset(&s); + assert!(d.x.abs() < 1e-9 && d.y.abs() < 1e-9, "{d:?}"); + } + + #[test] + fn delete_removes_a_selected_anchored_object_from_the_text() { + let (mut s, sid) = inline_box(); + let before = s.doc().unwrap().doc.story(sid).unwrap().text.clone(); + s.execute("anchored.select", &json!({"story": sid.0, "index": 0})).unwrap(); + assert_eq!(s.execute("edit.clear", &json!({})).unwrap()["deleted"], 1); + let st = s.doc().unwrap().doc.story(sid).unwrap().clone(); + assert!(st.objects.is_empty() && !st.text.contains(OBJECT_MARK)); + assert!(s.doc().unwrap().selection.is_empty()); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc.story(sid).unwrap().text, before); + s.doc().unwrap().doc.check().unwrap(); + } + + #[test] + fn options_and_release_act_on_the_selected_anchored_object() { + let (mut s, sid) = inline_box(); + s.execute("anchored.select", &json!({"story": sid.0, "index": 0})).unwrap(); + s.execute("anchored.options", &json!({"position": "aboveLine"})).unwrap(); + assert!(matches!(s.doc().unwrap().doc.story(sid).unwrap().objects[0].position, AnchorPosition::AboveLine { .. })); + s.execute("anchored.release", &json!({})).unwrap(); + assert!(s.doc().unwrap().doc.story(sid).unwrap().objects.is_empty()); + assert_eq!(s.doc().unwrap().selection.items.len(), 1, "the released item is selected"); + } + + #[test] + fn selecting_items_drops_an_anchored_selection_and_bad_input_is_refused() { + let (mut s, sid) = inline_box(); + assert!(s.execute("anchored.select", &json!({"story": sid.0, "index": 5})).is_err()); + assert!(s.execute("anchored.select", &json!({"story": 999_999, "index": 0})).is_err()); + s.execute("anchored.select", &json!({"story": sid.0, "index": 0})).unwrap(); + for bad in [ + json!({"from": [0, 0, 0, 40], "to": [0, 0, 24, 40]}), + json!({"from": [0, 0, 24, 40], "to": [0, 0, "wide", 40]}), + json!({"to": [0, 0, 1, 1]}), + ] { + assert!(s.execute("anchored.resize", &bad).is_err(), "{bad}"); + } + // Dragged inside out or to nothing: at least a point each way. + s.execute("anchored.resize", &json!({"from": [0, 0, 24, 40], "to": [24, 40, 24, 40]})).unwrap(); + assert_eq!(s.doc().unwrap().doc.story(sid).unwrap().objects[0].size(), (1.0, 1.0)); + s.execute("selection.set", &json!({"ids": []})).unwrap(); + assert!(s.doc().unwrap().selection.anchored.is_none()); + } + #[test] fn inline_object_flows_with_text_and_releases() { let mut s = Session::new(); diff --git a/crates/engine/src/cmd/datamerge/fill.rs b/crates/engine/src/cmd/datamerge/fill.rs index eb4cabb5a..21a883a91 100644 --- a/crates/engine/src/cmd/datamerge/fill.rs +++ b/crates/engine/src/cmd/datamerge/fill.rs @@ -21,6 +21,10 @@ use crate::EngineError; pub struct Maps { pub items: HashMap, pub stories: HashMap, + /// Each source text frame's place in its story's thread, for the stories copied so far. + source_ranks: HashMap, + /// The same place, by the id of the frame's copy. + frame_ranks: HashMap, } #[derive(Clone, Debug, PartialEq)] @@ -104,6 +108,7 @@ fn renumber_in(dst: &mut designcraft_doc::Document, src: &designcraft_doc::Docum } } designcraft_doc::remap_story_assets(&mut st, &assets); + maps.source_ranks.extend(st.frames.iter().enumerate().map(|(i, f)| (*f, i))); st.frames.clear(); // Mapped first: the map is the seen-set that stops story recursion. maps.stories.insert(tf.story, n); @@ -112,8 +117,13 @@ fn renumber_in(dst: &mut designcraft_doc::Document, src: &designcraft_doc::Docum n }; tf.story = new_sid; + // Frames are copied in page and nesting order, which can differ from the thread order: + // each copy goes where its source frame is in the source story's thread. + let rank = maps.source_ranks.get(&old).copied().unwrap_or(usize::MAX); + maps.frame_ranks.insert(new_id, rank); if let Some(st) = dst.story_mut(new_sid) { - st.frames.push(new_id); + let at = st.frames.partition_point(|f| maps.frame_ranks.get(f).is_some_and(|r| *r <= rank)); + st.frames.insert(at, new_id); } } Content::Graphic(g) => { @@ -130,16 +140,20 @@ fn renumber_in(dst: &mut designcraft_doc::Document, src: &designcraft_doc::Docum } } -/// Fresh ids for the objects anchored in story copy `st`, its table cells, footnotes and endnotes (#1522). +/// Fresh ids for the objects anchored in story copy `st`, its table cells, footnotes and endnotes, and +/// the cells and notes inside those at any depth (#1522). The texts are walked with a stack, so a deeply +/// nested file can't exhaust the call stack. fn renumber_anchored(dst: &mut designcraft_doc::Document, src: &designcraft_doc::Document, st: &mut Story, maps: &mut Maps) { - let mut fresh = |t: &mut Story| { - for o in &mut t.objects { + let mut texts = vec![st]; + while let Some(t) = texts.pop() { + let Story { objects, tables, notes, endnotes, .. } = t; + for o in objects.iter_mut() { renumber_in(dst, src, &mut Arc::make_mut(o).item, maps, false); } - }; - st.for_each_text_mut(&mut fresh); - for n in &mut st.endnotes { - Arc::make_mut(n).text.for_each_text_mut(&mut fresh); + for table in tables.values_mut() { + texts.extend(Arc::make_mut(table).cells.iter_mut().map(|c| &mut c.text)); + } + texts.extend(notes.iter_mut().chain(endnotes.iter_mut()).map(|n| &mut Arc::make_mut(n).text)); } } diff --git a/crates/engine/src/cmd/datamerge/tests.rs b/crates/engine/src/cmd/datamerge/tests.rs index afafb43d6..0d777cefa 100644 --- a/crates/engine/src/cmd/datamerge/tests.rs +++ b/crates/engine/src/cmd/datamerge/tests.rs @@ -1567,6 +1567,103 @@ fn merged_records_give_anchored_objects_their_own_ids() { designcraft_format::load(&designcraft_format::save(doc).unwrap()).unwrap(); } +/// A record's copy gives the objects anchored in an endnote of a table cell or of a footnote ids of +/// their own, and maps them, so placeholders on them follow the copy. +#[test] +fn record_copies_renumber_objects_anchored_in_nested_endnotes() { + use designcraft_doc::{AnchoredObject, ItemId, SpreadRef}; + use std::sync::Arc; + + let mut s = Session::new(); + new_doc(&mut s, 1); + let made = text_frame(&mut s, [36.0, 36.0, 400.0, 300.0], "Body", None); + let (frame, sid) = (ItemId(made["id"].as_u64().unwrap()), StoryId(made["story"].as_u64().unwrap())); + let a = exec(&mut s, "frame.create", json!({"rect": [450, 450, 474, 490]}))["id"].as_u64().unwrap(); + let b = exec(&mut s, "frame.create", json!({"rect": [480, 450, 504, 490]}))["id"].as_u64().unwrap(); + let mut src = s.doc().unwrap().doc.as_ref().clone(); + let d = &mut src; + let take = |d: &mut designcraft_doc::Document, id: u64| { + let it = d.item(ItemId(id)).cloned().unwrap(); + Arc::make_mut(&mut d.spreads[0]).items.retain(|i| i.id.0 != id); + AnchoredObject::new(it, Default::default()) + }; + let in_cell = take(d, a); + let in_footnote = take(d, b); + let mut table = designcraft_doc::Table::new(d.alloc(), 1, 1, 0, 0, 40.0); + let cell = &mut table.cells[0].text; + cell.insert_endnote(cell.len(), "Cell endnote", Default::default()).unwrap(); + Arc::make_mut(&mut cell.endnotes[0]).text.insert_object(0, in_cell); + let st = d.story_mut(sid).unwrap(); + st.insert_note(st.len(), "Footnote", Default::default()).unwrap(); + let note = &mut Arc::make_mut(&mut st.notes[0]).text; + note.insert_endnote(note.len(), "Footnote endnote", Default::default()).unwrap(); + Arc::make_mut(&mut note.endnotes[0]).text.insert_object(0, in_footnote); + st.insert_table(0, table); + src.check().unwrap(); + + let mut dst = src.clone(); + let it = src.item(frame).cloned().unwrap(); + let mut maps = super::fill::Maps::default(); + super::fill::copy_item(&mut dst, &src, &it, SpreadRef::Doc(0), designcraft_geom::Vec2::new(0.0, 0.0), &mut maps).unwrap(); + let ids: Vec = dst.anchored_items().into_iter().map(|(_, i)| i.id.0).collect(); + let unique: std::collections::BTreeSet<_> = ids.iter().collect(); + assert_eq!((ids.len(), unique.len()), (4, 4), "the copies have ids of their own: {ids:?}"); + for old in [a, b] { + assert!(maps.items.contains_key(&ItemId(old)), "object {old} is mapped to its copy"); + } + dst.check().unwrap(); +} + +/// A story threaded through anchored text frames in two table cells keeps its thread order in a +/// record's copy, so its text flows through the copied frames in the same order, whichever cell +/// holds the first frame. +#[test] +fn record_copies_keep_the_thread_order_of_frames_anchored_in_cells() { + for first_in_first_cell in [true, false] { + thread_order_of_frames_anchored_in_cells(first_in_first_cell); + } +} + +fn thread_order_of_frames_anchored_in_cells(first_in_first_cell: bool) { + use designcraft_doc::{AnchoredObject, ItemId, SpreadRef}; + use std::sync::Arc; + + let mut s = Session::new(); + new_doc(&mut s, 1); + let made = text_frame(&mut s, [36.0, 36.0, 400.0, 300.0], "Body", None); + let (frame, sid) = (ItemId(made["id"].as_u64().unwrap()), StoryId(made["story"].as_u64().unwrap())); + let first = text_frame(&mut s, [450.0, 450.0, 500.0, 490.0], "Threaded text", None); + let second = text_frame(&mut s, [450.0, 500.0, 500.0, 540.0], "", None); + exec(&mut s, "text.thread", json!({"from": first["id"], "to": second["id"]})); + let (a, b) = (first["id"].as_u64().unwrap(), second["id"].as_u64().unwrap()); + let thread = StoryId(first["story"].as_u64().unwrap()); + let mut src = s.doc().unwrap().doc.as_ref().clone(); + assert_eq!(src.story(thread).unwrap().frames, vec![ItemId(a), ItemId(b)]); + let d = &mut src; + let take = |d: &mut designcraft_doc::Document, id: u64| { + let it = d.item(ItemId(id)).cloned().unwrap(); + Arc::make_mut(&mut d.spreads[0]).items.retain(|i| i.id.0 != id); + AnchoredObject::new(it, Default::default()) + }; + let in_first = take(d, a); + let in_second = take(d, b); + let mut table = designcraft_doc::Table::new(d.alloc(), 1, 2, 0, 0, 80.0); + let (left, right) = if first_in_first_cell { (in_first, in_second) } else { (in_second, in_first) }; + table.cells[0].text.insert_object(0, left); + table.cells[1].text.insert_object(0, right); + d.story_mut(sid).unwrap().insert_table(0, table); + src.check().unwrap(); + + let mut dst = src.clone(); + let it = src.item(frame).cloned().unwrap(); + let mut maps = super::fill::Maps::default(); + super::fill::copy_item(&mut dst, &src, &it, SpreadRef::Doc(0), designcraft_geom::Vec2::new(0.0, 0.0), &mut maps).unwrap(); + let copy = maps.stories[&thread]; + let expected = vec![maps.items[&ItemId(a)], maps.items[&ItemId(b)]]; + assert_eq!(dst.story(copy).unwrap().frames, expected, "the copy's frames keep the thread order ({first_in_first_cell})"); + dst.check().unwrap(); +} + /// A record previewed into an image placeholder whose frame wraps with an Alpha Channel contour /// gets the image's outline, as an edit would. #[test] diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 8331c4be9..92f7eea2b 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -277,6 +277,7 @@ pub fn specs() -> Vec { st.history.redo.push(HistoryEntry { label: e.label.clone(), doc: st.doc.clone(), selection: st.selection.clone() }); let mut doc = e.doc; super::rulers::keep_zero_point(&st.doc, &mut doc); + super::file::keep_title(&st.doc, &mut doc); st.doc = doc; st.selection = e.selection; st.bump_revision(); @@ -290,6 +291,7 @@ pub fn specs() -> Vec { st.history.undo.push(HistoryEntry { label: e.label.clone(), doc: st.doc.clone(), selection: st.selection.clone() }); let mut doc = e.doc; super::rulers::keep_zero_point(&st.doc, &mut doc); + super::file::keep_title(&st.doc, &mut doc); st.doc = doc; st.selection = e.selection; st.bump_revision(); @@ -329,6 +331,7 @@ pub fn specs() -> Vec { } st.selection.text = None; st.selection.cells = None; + st.selection.anchored = None; st.bump_revision(); ok() }), @@ -337,6 +340,7 @@ pub fn specs() -> Vec { let st = s.doc_mut()?; st.selection.text = None; st.selection.cells = None; + st.selection.anchored = None; if let Some(i) = st.selection.items.iter().position(|x| *x == id) { st.selection.items.remove(i); // Its points go with it: arrow keys and Delete act on the selected points. @@ -406,6 +410,12 @@ pub fn specs() -> Vec { if s.doc()?.selection.text.is_some() && p.get("ids").is_none() { return super::text::delete_selection(s); } + // A selected anchored object leaves the text. + if p.get("ids").is_none() + && let Some(a) = s.doc()?.selection.anchored + { + return super::anchored::delete(s, a); + } if p.get("ids").is_none() && s.doc()?.selection.items.is_empty() && !s.doc()?.selection.guides.is_empty() { return s.execute("guide.delete", &json!({})); } diff --git a/crates/engine/src/cmd/export/formats.rs b/crates/engine/src/cmd/export/formats.rs index 8828f006c..e30d12ec5 100644 --- a/crates/engine/src/cmd/export/formats.rs +++ b/crates/engine/src/cmd/export/formats.rs @@ -28,24 +28,9 @@ pub(super) fn print_booklet(s: &mut Session, p: &Value) -> Result { /// HTML and reflowable EPUB read embedded bytes only: every used linked asset gets its output /// bytes embedded, and EPS its preview. The session's own assets stay as they are. fn eps_previews(d: &designcraft_doc::Document) -> (Cow<'_, designcraft_doc::Document>, Vec) { - // Match the exporter's reading order (including Article exclusions), not every asset - // in the document: unused or hidden graphics must not prevent an export. - let mut used = std::collections::BTreeSet::new(); - for block in designcraft_epub::reading_order(d) { - let designcraft_epub::Block::Image(id) = block else { - continue; - }; - let Some(it) = d.item(id) else { continue }; - let designcraft_doc::Content::Graphic(g) = &it.content else { - continue; - }; - used.insert(g.asset); - if d.assets.get(&g.asset).is_some_and(|a| designcraft_doc::media_kind(&a.mime).is_some()) - && let Some(poster) = it.media.as_ref().and_then(|m| m.poster) - { - used.insert(poster); - } - } + // Match the exporter's reading order and visible story content (including Article exclusions), + // not every asset in the document: unused or hidden graphics must not prevent an export. + let used = designcraft_epub::used_assets(d); let mut out = Cow::Borrowed(d); let mut warnings = Vec::new(); for id in used { @@ -81,6 +66,10 @@ fn eps_previews(d: &designcraft_doc::Document) -> (Cow<'_, designcraft_doc::Docu let a = Arc::make_mut(a); if eps { a.mime = "image/png".into(); + } else if got.proxied + && let Some(proxy) = &a.proxy + { + a.mime = proxy.mime.clone(); } a.data = designcraft_doc::AssetData::embedded(data); } diff --git a/crates/engine/src/cmd/export/linked_tests.rs b/crates/engine/src/cmd/export/linked_tests.rs index 4509a2fd1..d6a064185 100644 --- a/crates/engine/src/cmd/export/linked_tests.rs +++ b/crates/engine/src/cmd/export/linked_tests.rs @@ -168,3 +168,78 @@ fn a_package_copies_a_modified_link_from_disk_with_a_warning() { assert_eq!(std::fs::read(out.join("Links/art.png")).unwrap(), changed); assert!(r.to_string().contains("file on disk"), "{r}"); } + +#[test] +fn html_and_epub_export_linked_inline_anchored_image_and_report_changes_or_missing() { + use std::io::Read; + + let dir = Dir::new("anchored-svg"); + let svg_path = dir.0.join("dot.svg"); + let svg = br#""#; + std::fs::write(&svg_path, svg).unwrap(); + + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let text_frame = s.execute("frame.create", &json!({"rect": [72, 72, 400, 200], "content": "text", "text": " Text"})).unwrap(); + let story = text_frame["story"].as_u64().unwrap(); + let graphic_frame = s.execute("frame.create", &json!({"rect": [500, 72, 512, 84], "content": "graphic"})).unwrap()["id"].as_u64().unwrap(); + let placed = s.execute("file.place", &json!({"path": svg_path.to_string_lossy(), "frame": graphic_frame})).unwrap(); + let aid = AssetId(placed["asset"].as_u64().unwrap()); + s.execute("anchored.insert", &json!({"ids": [graphic_frame], "story": story, "pos": 0, "position": "inline"})).unwrap(); + assert!(s.doc().unwrap().doc.assets[&aid].data.is_linked()); + + // Linked inline anchored SVG exports cleanly in HTML and EPUB without mutating the document. + let before = s.doc().unwrap().doc.clone(); + let html = s.execute("file.exportHtml", &json!({})).unwrap(); + assert!(html["warnings"].as_array().unwrap().is_empty(), "{}", warnings(&html)); + let body = html["text"].as_str().unwrap(); + let encoded = body.split("data:image/svg+xml;base64,").nth(1).expect("inline SVG data URI").split('"').next().unwrap(); + assert_eq!(crate::cmd::base64_decode(encoded), svg); + assert!(Arc::ptr_eq(&before, &s.doc().unwrap().doc)); + + let epub = s.execute("file.exportEpub", &json!({})).unwrap(); + let mut z = zip::ZipArchive::new(std::io::Cursor::new(crate::cmd::base64_decode(epub["base64"].as_str().unwrap()))).unwrap(); + let mut xhtml = String::new(); + z.by_name("OEBPS/content.xhtml").unwrap().read_to_string(&mut xhtml).unwrap(); + assert!(xhtml.contains(""#; + std::fs::write(&svg_path, updated).unwrap(); + let html = s.execute("file.exportHtml", &json!({})).unwrap(); + assert!(warnings(&html).contains("file on disk"), "{}", warnings(&html)); + let encoded = html["text"].as_str().unwrap().split("data:image/svg+xml;base64,").nth(1).expect("updated SVG data URI").split('"').next().unwrap(); + assert_eq!(crate::cmd::base64_decode(encoded), updated); + + // Delete the linked file while a proxy exists: exports the proxy with the proxy's MIME type and warns. + let proxy_mime = s.doc().unwrap().doc.assets[&aid].proxy.as_ref().expect("proxy built").mime.clone(); + assert_ne!(proxy_mime, "image/svg+xml"); + std::fs::remove_file(&svg_path).unwrap(); + let html = s.execute("file.exportHtml", &json!({})).unwrap(); + assert!(warnings(&html).contains("preview"), "{}", warnings(&html)); + let body = html["text"].as_str().unwrap(); + assert!(body.contains(&format!("data:{proxy_mime};base64,")), "proxy MIME used: {body}"); + assert!(!body.contains("data:image/svg+xml;base64,")); + + // Without a proxy, the missing linked graphic is omitted with an explicit warning. + s.edit(|d, _| { + Arc::make_mut(d.assets.get_mut(&aid).unwrap()).proxy = None; + Ok(()) + }) + .unwrap(); + let html = s.execute("file.exportHtml", &json!({})).unwrap(); + assert!(!html["text"].as_str().unwrap().contains("