diff --git a/.github/nightly-linux-signing-key.asc b/.github/nightly-linux-signing-key.asc new file mode 100644 index 000000000..a1c1f31e8 --- /dev/null +++ b/.github/nightly-linux-signing-key.asc @@ -0,0 +1,16 @@ +-----BEGIN PGP PUBLIC KEY BLOCK----- + +mDMEaulK1xYJKwYBBAHaRw8BAQdAqHJeDCjY6Hx5FTn/hW+aqu6V394ubLk0Zj3C +bftDwFm0IkFydENyYWZ0IExpbnV4IFJlbGVhc2UgU2lnbmluZyBLZXmIkwQTFgoA +OxYhBCt2dBtBSq1s0z5jEhOgBcC518PtBQJq6UrXAhsBBQsJCAcCAiICBhUKCQgL +AgQWAgMBAh4HAheAAAoJEBOgBcC518PtGeUA/RjvULBTLlccc+2wtJkfjSnCV+cf +PUMEGmW7XkZWkk51AP9w2A/WLv+79nREWEpZzI8LGK5EjrNazP+sY0l7j5rFCLgz +BGrpStcWCSsGAQQB2kcPAQEHQPl7XkQ1gWsvSPf/T9b4m/UHcjJjBpSOtpYlWR56 +er5RiO8EGBYKACAWIQQrdnQbQUqtbNM+YxIToAXAudfD7QUCaulK1wIbAgCBCRAT +oAXAudfD7XYgBBkWCgAdFiEEVo3B9o+Prsx5fzx7AG2va7DvM04FAmrpStcACgkQ +AG2va7DvM07taQEA4d2VFkKRIP0g9TrE86KpnuXPap+LKqe0tfIxpdf9YxIA/0Wo +9H/iG8nH++nxC087p3HE0S+0UovxqkhXJLSr8B4JDOoA/iLRpqTdYmk6fVXMyPJo +SkOVuwZIGS6VgBdSQP0e2P2YAP41L5OoSvwdQIG3/uNrM+ieqpYeM597/hCLFs5A +ga/qCA== +=3wGQ +-----END PGP PUBLIC KEY BLOCK----- diff --git a/.github/nightly-signing-policy.json b/.github/nightly-signing-policy.json new file mode 100644 index 000000000..a5d253325 --- /dev/null +++ b/.github/nightly-signing-policy.json @@ -0,0 +1,107 @@ +{ + "schema": "craft-nightly-release-policy/v3", + "repository": "storytold/designcraft", + "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", + "signer_workflow_path": ".github/workflows/nightly-sign.yml", + "signer_tooling_revision": "be00e5ccd18b68e950c8a08532f2230e7c3d0cba", + "release_branch": "nightly-signer", + "manual_actors": [ + "bflatastic", + "dylanmtaylor", + "echelon", + "FredApps", + "skylartaylor" + ], + "max_age_seconds": 86400, + "candidate_policy": { + "schema": "craft-nightly-candidate-policy/v3", + "epoch": "designcraft-nightly-20261124-initial", + "repository": "storytold/designcraft", + "branch": "main", + "required_workflows": [ + { + "workflow_id": 380135818, + "workflow_path": ".github/workflows/ci.yml", + "jobs": [ + { + "name": "gate / gate (ubuntu-24.04)", + "app_id": 15368, + "applicability": "required" + } + ] + } + ], + "sonar": { + "organization": "storytold", + "project": "storytold_designcraft", + "app_id": 12526, + "check_name": "SonarCloud Code Analysis", + "details_url": "https://sonarcloud.io/dashboard?id=storytold_designcraft&branch=main", + "issue_types": [ + "VULNERABILITY" + ], + "accepted_conditions": [ + { + "metric": "new_security_rating", + "comparator": "GT", + "error_threshold": "1", + "maximum": "5" + } + ], + "required_conditions": [ + { + "metric": "new_reliability_rating", + "comparator": "GT", + "error_threshold": "1" + }, + { + "metric": "new_maintainability_rating", + "comparator": "GT", + "error_threshold": "1" + }, + { + "metric": "new_coverage", + "comparator": "LT", + "error_threshold": "80" + }, + { + "metric": "new_duplicated_lines_density", + "comparator": "GT", + "error_threshold": "3" + }, + { + "metric": "new_security_hotspots_reviewed", + "comparator": "LT", + "error_threshold": "100" + } + ], + "debt": [] + } + }, + "max_artifact_bytes": 2147483648, + "automatic_signer_actors": [], + "platforms": { + "windows-x86_64": { + "unsigned_artifact_name": "nightly-unsigned-windows-x86_64", + "trust": { + "publisher_subject": "CN=Learning Machines Inc, O=Learning Machines Inc, L=Atlanta, S=Georgia, C=US" + } + }, + "linux-x86_64": { + "unsigned_artifact_name": "nightly-unsigned-linux-x86_64", + "trust": { + "fingerprint": "2B76741B414AAD6CD33E631213A005C0B9D7C3ED" + } + }, + "macos-aarch64": { + "unsigned_artifact_name": "nightly-unsigned-macos-aarch64", + "trust": { + "apple_team_id": "DJ6XS33FX8" + } + } + } +} diff --git a/.github/workflows/nightly-sign.yml b/.github/workflows/nightly-sign.yml new file mode 100644 index 000000000..406a64f0f --- /dev/null +++ b/.github/workflows/nightly-sign.yml @@ -0,0 +1,45 @@ +name: DesignCraft release-ref nightly signer + +# Enabled for supervised manual dispatch on the dedicated nightly-signer branch, which only ever +# fast-forwards to reviewed main commits (never the stable release branch). +# A reusable callee does not change context; this must be a real top-level signer-branch dispatch. +on: + workflow_dispatch: + inputs: + producer_run_id: + description: Exact untrusted producer Actions run ID + required: true + type: string + producer_run_attempt: + description: Exact untrusted producer Actions run attempt + required: true + type: string + +permissions: {} + +concurrency: + group: designcraft-nightly-release + cancel-in-progress: false + +jobs: + release: + # Actual context guards: official repository, manual dispatch, real nightly-signer branch. + if: >- + github.repository == 'storytold/designcraft' && + github.event_name == 'workflow_dispatch' && + github.ref == 'refs/heads/nightly-signer' && github.ref_type == 'branch' + permissions: + contents: write + actions: read + checks: read + attestations: write + id-token: write + uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba + with: + tooling-revision: be00e5ccd18b68e950c8a08532f2230e7c3d0cba + app-name: designcraft + producer_run_id: ${{ inputs.producer_run_id }} + producer_run_attempt: ${{ inputs.producer_run_attempt }} + # 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 new file mode 100644 index 000000000..d9a8e0f37 --- /dev/null +++ b/.github/workflows/nightly.yml @@ -0,0 +1,34 @@ +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). +on: + workflow_dispatch: + +permissions: + contents: read + +jobs: + unsigned: + # Actual context guards only; no inherited/platform secrets. + if: >- + github.repository == 'storytold/designcraft' && + github.ref == 'refs/heads/main' && github.ref_type == 'branch' && + (github.event_name == 'schedule' || github.event_name == 'workflow_dispatch') + # Maximum for the reusable workflow. Its compiler narrows to contents/actions read; + # no OIDC, attestation write, release environment or platform secrets in compilation. + permissions: + contents: read + actions: read + attestations: write + id-token: write + uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba + with: + tooling-revision: be00e5ccd18b68e950c8a08532f2230e7c3d0cba + app-name: designcraft + manual-actors: '["bflatastic","dylanmtaylor","echelon","FredApps","skylartaylor"]' + craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83 + # One producer run builds every listed platform for one all-or-nothing release. The pin is the + # 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"]' diff --git a/.github/workflows/packaging-lint.yml b/.github/workflows/packaging-lint.yml index 1771a35fe..badb33439 100644 --- a/.github/workflows/packaging-lint.yml +++ b/.github/workflows/packaging-lint.yml @@ -5,9 +5,9 @@ name: Packaging lint on: push: branches: [main, release] - paths: [".github/workflows/**", "packaging/**", "assets/app-icon/**"] + paths: [".github/workflows/**", "packaging/**", "assets/app-icon/**", ".github/nightly-linux-signing-key.asc", "sonar-project.properties"] pull_request: - paths: [".github/workflows/**", "packaging/**", "assets/app-icon/**"] + paths: [".github/workflows/**", "packaging/**", "assets/app-icon/**", ".github/nightly-linux-signing-key.asc", "sonar-project.properties"] workflow_dispatch: permissions: @@ -49,3 +49,20 @@ jobs: - name: Build and check non-executable installer fixtures shell: pwsh run: ./packaging/windows/test-install-policy.ps1 -OutputDirectory (Join-Path $env:RUNNER_TEMP 'craft-install-policy-tests') + + nightly-source-contract: + name: Nightly source contracts (no build or signing) + runs-on: ubuntu-latest + timeout-minutes: 5 + permissions: + contents: read + steps: + - name: Harden runner + uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + with: + egress-policy: audit + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Enforce nightly serialization and synthetic packaging contracts + run: python3 packaging/nightly-tests.py diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 29b2c0c98..bade04f46 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -60,3 +60,4 @@ jobs: AZURE_SIGNING_ACCOUNT: ${{ secrets.AZURE_SIGNING_ACCOUNT }} AZURE_CERT_PROFILE: ${{ secrets.AZURE_CERT_PROFILE }} LINUX_SIGNING_KEY: ${{ secrets.LINUX_SIGNING_KEY }} + ARTCRAFT_SERVICES_DISPATCH_TOKEN: ${{ secrets.ARTCRAFT_SERVICES_DISPATCH_TOKEN }} diff --git a/.gitignore b/.gitignore index d47b8f373..f52f202aa 100644 --- a/.gitignore +++ b/.gitignore @@ -9,3 +9,7 @@ plan/ /.claude/ /target-*/ /craft-fonts/ +/.nightly-tools +/.nightly-input +/craft-i18n +__pycache__/ diff --git a/ASSETS.md b/ASSETS.md index 4297ab421..4f60303a0 100644 --- a/ASSETS.md +++ b/ASSETS.md @@ -65,6 +65,11 @@ Generated-in-code art is original and has no file to list: the UI icon set (`cra | `assets/app-icon/hicolor/512x512/apps/ai.storyteller.designcraft.png` | DesignCraft project owner (drawn in ArtCraft) | rendered from `assets/app-icon/designcraft.svg` by `packaging/icons.sh` | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | App icon: calico cat in a polka-dot scarf (see `assets/app-icon/README.md`) | | `assets/app-icon/hicolor/64x64/apps/ai.storyteller.designcraft.png` | DesignCraft project owner (drawn in ArtCraft) | rendered from `assets/app-icon/designcraft.svg` by `packaging/icons.sh` | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | App icon: calico cat in a polka-dot scarf (see `assets/app-icon/README.md`) | | `assets/app-icon/hicolor/scalable/apps/ai.storyteller.designcraft.svg` | DesignCraft project owner (drawn in ArtCraft) | owner's ArtCraft drawing | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | App icon: calico cat in a polka-dot scarf (see `assets/app-icon/README.md`) | +| `assets/app-icon/designcraft-nightly.png` | DesignCraft project owner (artwork); nightly derivation generated for the nightlies lead | code-generated derivative of `assets/app-icon/designcraft.svg` with the deeper nightly field (method and hashes in `assets/app-icon/nightly-provenance.json`) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | Nightly window icon, tar icon and the 256 px base of the nightly ICO/ICNS | +| `assets/app-icon/designcraft-nightly-1024.png` | DesignCraft project owner (artwork); nightly derivation generated for the nightlies lead | derived from the native 1024 tile onto Apple's 824/1024 grid, never upscaled (see `assets/app-icon/nightly-provenance.json`) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | 1024 px nightly master for the ICNS | +| `assets/app-icon/designcraft-nightly.ico` | DesignCraft project owner (artwork); nightly derivation generated for the nightlies lead | packed 16–256 px frames of `assets/app-icon/designcraft-nightly.png` (see `assets/app-icon/nightly-provenance.json`) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | Windows nightly `designcraft.exe` icon, embedded by `apps/designcraft/build.rs` | +| `assets/app-icon/designcraft-nightly.icns` | DesignCraft project owner (artwork); nightly derivation generated for the nightlies lead | packed native-size frames of the nightly PNG masters (see `assets/app-icon/nightly-provenance.json`) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | macOS nightly bundle icon (`CFBundleIconFile`) | +| `assets/app-icon/nightly-provenance.json` | nightlies lead (generated record) | generated record of the nightly icon derivation (the generator itself is not committed); holds the input/output hashes, the palette fit and the container members | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | Provenance for the four nightly icon files above | | `docs/brand/artcraft-logo.svg`, `docs/brand/artcraft-logo.png` | ArtCraft / Storyteller | ArtCraft brand kit (project owner) | ArtCraft trademark, see docs/brand/LICENSE-brand.txt (not open source) | ArtCraft wordmark (README header) | | `docs/brand/artcraft-logo-white.svg`, `docs/brand/artcraft-logo-white.png` | ArtCraft / Storyteller | ArtCraft brand kit (project owner) | ArtCraft trademark, see docs/brand/LICENSE-brand.txt (not open source) | Wordmark for dark backgrounds | | `docs/brand/artcraft-mark.svg`, `docs/brand/artcraft-mark.png` | ArtCraft / Storyteller | ArtCraft brand kit (project owner) | ArtCraft trademark, see docs/brand/LICENSE-brand.txt (not open source) | The mark; its outline is drawn in code by `crates/ui-egui/src/about.rs` (About splash, start screen) | diff --git a/Cargo.lock b/Cargo.lock index 486db4e08..b4a802771 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1083,7 +1083,7 @@ dependencies = [ [[package]] name = "craft-atomic" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1#c60e7a20063313b80a994075adb4f797b24ab4f1" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ "rustix 1.1.5", ] @@ -1091,12 +1091,12 @@ dependencies = [ [[package]] name = "craft-cfb" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1#c60e7a20063313b80a994075adb4f797b24ab4f1" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" [[package]] name = "craft-cms" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1#c60e7a20063313b80a994075adb4f797b24ab4f1" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ "md-5", "rayon", @@ -1105,12 +1105,12 @@ dependencies = [ [[package]] name = "craft-codepage" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1#c60e7a20063313b80a994075adb4f797b24ab4f1" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" [[package]] name = "craft-csv" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1#c60e7a20063313b80a994075adb4f797b24ab4f1" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ "thiserror 2.0.21", ] @@ -1118,7 +1118,7 @@ dependencies = [ [[package]] name = "craft-dds" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1#c60e7a20063313b80a994075adb4f797b24ab4f1" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ "rayon", ] @@ -1126,7 +1126,7 @@ dependencies = [ [[package]] name = "craft-designcraft-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1#c60e7a20063313b80a994075adb4f797b24ab4f1" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ "craft-document-bundle", "craft-eps", @@ -1138,7 +1138,7 @@ dependencies = [ [[package]] name = "craft-dialogs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1#c60e7a20063313b80a994075adb4f797b24ab4f1" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ "block2 0.6.2", "objc2 0.6.5", @@ -1151,14 +1151,14 @@ dependencies = [ [[package]] name = "craft-docpath" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1#c60e7a20063313b80a994075adb4f797b24ab4f1" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" [[package]] name = "craft-document-bundle" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1#c60e7a20063313b80a994075adb4f797b24ab4f1" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ - "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1)", + "craft-zip", "serde_json", "thiserror 2.0.21", "zip 9.1.1", @@ -1167,7 +1167,7 @@ dependencies = [ [[package]] name = "craft-docx" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1#c60e7a20063313b80a994075adb4f797b24ab4f1" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ "base64 0.23.1", "chrono", @@ -1176,7 +1176,7 @@ dependencies = [ "craft-offcrypto", "craft-opc", "craft-wordmodel", - "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1)", + "craft-xml", "log", "quick-xml 0.41.0", "thiserror 2.0.21", @@ -1187,10 +1187,10 @@ dependencies = [ [[package]] name = "craft-drawingml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1#c60e7a20063313b80a994075adb4f797b24ab4f1" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ "chrono", - "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1)", + "craft-xml", "kurbo", "log", "serde", @@ -1199,27 +1199,27 @@ dependencies = [ [[package]] name = "craft-eps" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1#c60e7a20063313b80a994075adb4f797b24ab4f1" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" [[package]] name = "craft-epub" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1#c60e7a20063313b80a994075adb4f797b24ab4f1" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ - "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1)", - "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1)", + "craft-xml", + "craft-zip", "thiserror 2.0.21", ] [[package]] name = "craft-file-formats" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1#c60e7a20063313b80a994075adb4f797b24ab4f1" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ "craft-eps", - "craft-idml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1)", + "craft-idml", "craft-svg", - "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1)", + "craft-zip", "serde", "serde_json", ] @@ -1227,12 +1227,12 @@ dependencies = [ [[package]] name = "craft-fonts-build" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1#c60e7a20063313b80a994075adb4f797b24ab4f1" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" [[package]] name = "craft-i18n" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1#c60e7a20063313b80a994075adb4f797b24ab4f1" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ "fixed_decimal", "icu_decimal", @@ -1255,27 +1255,17 @@ dependencies = [ [[package]] name = "craft-idml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b92907f69d6599b91ac76fb8377ac407c8ac956d#b92907f69d6599b91ac76fb8377ac407c8ac956d" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ - "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=b92907f69d6599b91ac76fb8377ac407c8ac956d)", - "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=b92907f69d6599b91ac76fb8377ac407c8ac956d)", - "thiserror 2.0.21", -] - -[[package]] -name = "craft-idml" -version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1#c60e7a20063313b80a994075adb4f797b24ab4f1" -dependencies = [ - "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1)", - "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1)", + "craft-xml", + "craft-zip", "thiserror 2.0.21", ] [[package]] name = "craft-image-codecs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1#c60e7a20063313b80a994075adb4f797b24ab4f1" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ "craft-dds", "craft-jpeg", @@ -1302,7 +1292,7 @@ dependencies = [ [[package]] name = "craft-indd" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1#c60e7a20063313b80a994075adb4f797b24ab4f1" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ "indd", ] @@ -1310,7 +1300,7 @@ dependencies = [ [[package]] name = "craft-jpeg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1#c60e7a20063313b80a994075adb4f797b24ab4f1" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ "thiserror 2.0.21", ] @@ -1318,7 +1308,7 @@ dependencies = [ [[package]] name = "craft-keymap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1#c60e7a20063313b80a994075adb4f797b24ab4f1" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ "craft-i18n", "craft-ui", @@ -1330,9 +1320,9 @@ dependencies = [ [[package]] name = "craft-math" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1#c60e7a20063313b80a994075adb4f797b24ab4f1" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ - "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1)", + "craft-xml", "roxmltree 0.21.2", "serde", ] @@ -1340,7 +1330,7 @@ dependencies = [ [[package]] name = "craft-mcp-server" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1#c60e7a20063313b80a994075adb4f797b24ab4f1" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ "serde_json", ] @@ -1348,7 +1338,7 @@ dependencies = [ [[package]] name = "craft-metadata" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1#c60e7a20063313b80a994075adb4f797b24ab4f1" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ "brotli-decompressor 6.3.1", "chrono", @@ -1360,7 +1350,7 @@ dependencies = [ [[package]] name = "craft-mime" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1#c60e7a20063313b80a994075adb4f797b24ab4f1" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ "chrono", "craft-codepage", @@ -1370,12 +1360,12 @@ dependencies = [ [[package]] name = "craft-offcrypto" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1#c60e7a20063313b80a994075adb4f797b24ab4f1" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ "aes", "base64 0.23.1", "craft-cfb", - "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1)", + "craft-xml", "getrandom 0.3.4", "hmac", "sha1 0.11.0", @@ -1387,10 +1377,10 @@ dependencies = [ [[package]] name = "craft-opc" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1#c60e7a20063313b80a994075adb4f797b24ab4f1" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ - "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1)", - "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1)", + "craft-xml", + "craft-zip", "log", "thiserror 2.0.21", ] @@ -1398,7 +1388,7 @@ dependencies = [ [[package]] name = "craft-pdf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1#c60e7a20063313b80a994075adb4f797b24ab4f1" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ "bytemuck", "craft-svg", @@ -1414,11 +1404,11 @@ dependencies = [ [[package]] name = "craft-pptx" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1#c60e7a20063313b80a994075adb4f797b24ab4f1" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ "craft-drawingml", "craft-opc", - "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1)", + "craft-xml", "kurbo", "log", "serde", @@ -1429,7 +1419,7 @@ dependencies = [ [[package]] name = "craft-prepress" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1#c60e7a20063313b80a994075adb4f797b24ab4f1" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ "craft-cms", "craft-pdf", @@ -1442,7 +1432,7 @@ dependencies = [ [[package]] name = "craft-print" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1#c60e7a20063313b80a994075adb4f797b24ab4f1" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ "craft-winprint-gdi", "log", @@ -1456,7 +1446,7 @@ dependencies = [ [[package]] name = "craft-ps" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1#c60e7a20063313b80a994075adb4f797b24ab4f1" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ "craft-eps", "kurbo", @@ -1469,7 +1459,7 @@ dependencies = [ [[package]] name = "craft-psd" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1#c60e7a20063313b80a994075adb4f797b24ab4f1" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ "encoding_rs", "flate2", @@ -1480,7 +1470,7 @@ dependencies = [ [[package]] name = "craft-rtf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1#c60e7a20063313b80a994075adb4f797b24ab4f1" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ "craft-codepage", "encoding_rs", @@ -1489,15 +1479,15 @@ dependencies = [ [[package]] name = "craft-sheet" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1#c60e7a20063313b80a994075adb4f797b24ab4f1" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" [[package]] name = "craft-svg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1#c60e7a20063313b80a994075adb4f797b24ab4f1" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ "craft-image-codecs", - "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1)", + "craft-xml", "data-url", "flate2", "gif", @@ -1515,16 +1505,17 @@ dependencies = [ [[package]] name = "craft-tiff" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1#c60e7a20063313b80a994075adb4f797b24ab4f1" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ "serde", "thiserror 2.0.21", + "tiff", ] [[package]] name = "craft-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1#c60e7a20063313b80a994075adb4f797b24ab4f1" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ "craft-fonts-build", "craft-i18n", @@ -1545,7 +1536,7 @@ dependencies = [ [[package]] name = "craft-update" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1#c60e7a20063313b80a994075adb4f797b24ab4f1" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ "chrono", "dunce", @@ -1572,7 +1563,7 @@ dependencies = [ [[package]] name = "craft-window" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1#c60e7a20063313b80a994075adb4f797b24ab4f1" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ "egui", "objc2 0.6.5", @@ -1591,7 +1582,7 @@ dependencies = [ [[package]] name = "craft-wordmodel" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1#c60e7a20063313b80a994075adb4f797b24ab4f1" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ "base64 0.23.1", "craft-math", @@ -1605,29 +1596,19 @@ dependencies = [ [[package]] name = "craft-xlsx" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1#c60e7a20063313b80a994075adb4f797b24ab4f1" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ "craft-drawingml", "craft-opc", "craft-sheet", - "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1)", + "craft-xml", "thiserror 2.0.21", ] [[package]] name = "craft-xml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b92907f69d6599b91ac76fb8377ac407c8ac956d#b92907f69d6599b91ac76fb8377ac407c8ac956d" -dependencies = [ - "quick-xml 0.41.0", - "serde", - "thiserror 2.0.21", -] - -[[package]] -name = "craft-xml" -version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1#c60e7a20063313b80a994075adb4f797b24ab4f1" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ "quick-xml 0.41.0", "serde", @@ -1637,17 +1618,7 @@ dependencies = [ [[package]] name = "craft-zip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b92907f69d6599b91ac76fb8377ac407c8ac956d#b92907f69d6599b91ac76fb8377ac407c8ac956d" -dependencies = [ - "flate2", - "thiserror 2.0.21", - "zip 9.1.1", -] - -[[package]] -name = "craft-zip" -version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1#c60e7a20063313b80a994075adb4f797b24ab4f1" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ "flate2", "thiserror 2.0.21", @@ -1798,7 +1769,7 @@ dependencies = [ [[package]] name = "designcraft" -version = "0.21.0" +version = "0.21.1" dependencies = [ "arboard", "craft-update", @@ -1816,6 +1787,7 @@ dependencies = [ "rfd", "serde", "serde_json", + "thiserror 2.0.21", "winit", "winresource", "winsafe", @@ -1823,7 +1795,7 @@ dependencies = [ [[package]] name = "designcraft-cli" -version = "0.21.0" +version = "0.21.1" dependencies = [ "craft-file-formats", "craft-image-codecs", @@ -1842,7 +1814,7 @@ dependencies = [ [[package]] name = "designcraft-color" -version = "0.21.0" +version = "0.21.1" dependencies = [ "craft-cms", "kurbo", @@ -1854,7 +1826,7 @@ dependencies = [ [[package]] name = "designcraft-compose" -version = "0.21.0" +version = "0.21.1" dependencies = [ "designcraft-color", "designcraft-doc", @@ -1874,7 +1846,7 @@ dependencies = [ [[package]] name = "designcraft-doc" -version = "0.21.0" +version = "0.21.1" dependencies = [ "chrono", "designcraft-color", @@ -1887,7 +1859,7 @@ dependencies = [ [[package]] name = "designcraft-engine" -version = "0.21.0" +version = "0.21.1" dependencies = [ "caseless", "craft-atomic", @@ -1899,7 +1871,7 @@ dependencies = [ "craft-prepress", "craft-print", "craft-svg", - "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=b92907f69d6599b91ac76fb8377ac407c8ac956d)", + "craft-xml", "designcraft-color", "designcraft-compose", "designcraft-doc", @@ -1932,7 +1904,7 @@ dependencies = [ [[package]] name = "designcraft-epub" -version = "0.21.0" +version = "0.21.1" dependencies = [ "craft-epub", "craft-mime", @@ -1943,7 +1915,7 @@ dependencies = [ [[package]] name = "designcraft-fonts" -version = "0.21.0" +version = "0.21.1" dependencies = [ "core-text", "harfrust 0.13.3", @@ -1956,7 +1928,7 @@ dependencies = [ [[package]] name = "designcraft-format" -version = "0.21.0" +version = "0.21.1" dependencies = [ "craft-designcraft-format", "designcraft-doc", @@ -1966,7 +1938,7 @@ dependencies = [ [[package]] name = "designcraft-geom" -version = "0.21.0" +version = "0.21.1" dependencies = [ "flo_curves", "kurbo", @@ -1979,11 +1951,11 @@ dependencies = [ [[package]] name = "designcraft-idml" -version = "0.21.0" +version = "0.21.1" dependencies = [ "craft-file-formats", - "craft-idml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=b92907f69d6599b91ac76fb8377ac407c8ac956d)", - "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=b92907f69d6599b91ac76fb8377ac407c8ac956d)", + "craft-idml", + "craft-xml", "designcraft-color", "designcraft-compose", "designcraft-doc", @@ -1996,7 +1968,7 @@ dependencies = [ [[package]] name = "designcraft-images" -version = "0.21.0" +version = "0.21.1" dependencies = [ "craft-cms", "craft-eps", @@ -2018,7 +1990,7 @@ dependencies = [ [[package]] name = "designcraft-mcp" -version = "0.21.0" +version = "0.21.1" dependencies = [ "craft-file-formats", "craft-mcp-server", @@ -2033,7 +2005,7 @@ dependencies = [ [[package]] name = "designcraft-pdf" -version = "0.21.0" +version = "0.21.1" dependencies = [ "chrono", "craft-cms", @@ -2059,7 +2031,7 @@ dependencies = [ [[package]] name = "designcraft-pptx" -version = "0.21.0" +version = "0.21.1" dependencies = [ "chrono", "craft-image-codecs", @@ -2080,7 +2052,7 @@ dependencies = [ [[package]] name = "designcraft-render" -version = "0.21.0" +version = "0.21.1" dependencies = [ "bytemuck", "craft-image-codecs", @@ -2101,11 +2073,11 @@ dependencies = [ [[package]] name = "designcraft-textimport" -version = "0.21.0" +version = "0.21.1" dependencies = [ "craft-docx", "craft-file-formats", - "craft-idml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=b92907f69d6599b91ac76fb8377ac407c8ac956d)", + "craft-idml", "craft-rtf", "craft-wordmodel", "craft-xlsx", @@ -2115,7 +2087,7 @@ dependencies = [ [[package]] name = "designcraft-tools" -version = "0.21.0" +version = "0.21.1" dependencies = [ "designcraft-color", "designcraft-compose", @@ -2127,7 +2099,7 @@ dependencies = [ [[package]] name = "designcraft-ui-egui" -version = "0.21.0" +version = "0.21.1" dependencies = [ "craft-dialogs", "craft-file-formats", @@ -2162,7 +2134,7 @@ dependencies = [ [[package]] name = "designcraft-web" -version = "0.21.0" +version = "0.21.1" dependencies = [ "designcraft-engine", "designcraft-format", @@ -3248,7 +3220,7 @@ dependencies = [ [[package]] name = "hayro" version = "0.7.1" -source = "git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1#c60e7a20063313b80a994075adb4f797b24ab4f1" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ "bytemuck", "hayro-interpret", @@ -3268,7 +3240,7 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a" [[package]] name = "hayro-cmap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1#c60e7a20063313b80a994075adb4f797b24ab4f1" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ "brotli", "hayro-postscript", @@ -3277,7 +3249,7 @@ dependencies = [ [[package]] name = "hayro-interpret" version = "0.7.0" -source = "git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1#c60e7a20063313b80a994075adb4f797b24ab4f1" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ "bitflags 2.13.2", "hayro-cmap", @@ -3295,7 +3267,7 @@ dependencies = [ [[package]] name = "hayro-jbig2" version = "0.3.0" -source = "git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1#c60e7a20063313b80a994075adb4f797b24ab4f1" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ "fearless_simd", "hayro-ccitt", @@ -3313,12 +3285,12 @@ dependencies = [ [[package]] name = "hayro-postscript" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1#c60e7a20063313b80a994075adb4f797b24ab4f1" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" [[package]] name = "hayro-syntax" version = "0.7.2" -source = "git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1#c60e7a20063313b80a994075adb4f797b24ab4f1" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ "flate2", "hayro-ccitt", @@ -3953,7 +3925,7 @@ dependencies = [ [[package]] name = "krilla" version = "0.8.2" -source = "git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1#c60e7a20063313b80a994075adb4f797b24ab4f1" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ "base64 0.22.1", "bumpalo", @@ -4062,7 +4034,7 @@ checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4" [[package]] name = "linesweeper" version = "0.5.0" -source = "git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1#c60e7a20063313b80a994075adb4f797b24ab4f1" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ "arrayvec", "kurbo", @@ -7319,7 +7291,7 @@ dependencies = [ [[package]] name = "vello_common" version = "0.0.8" -source = "git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1#c60e7a20063313b80a994075adb4f797b24ab4f1" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ "bytemuck", "fearless_simd", @@ -7368,7 +7340,7 @@ dependencies = [ [[package]] name = "vello_cpu" version = "0.0.8" -source = "git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1#c60e7a20063313b80a994075adb4f797b24ab4f1" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ "bytemuck", "glifo 0.1.1", @@ -8416,7 +8388,7 @@ checksum = "9440ea3e5aeabb0ac63af70daf835274065238cdd0cec83418f417eae38bacee" [[package]] name = "xtask" -version = "0.21.0" +version = "0.21.1" dependencies = [ "serde_json", ] diff --git a/Cargo.toml b/Cargo.toml index cf544a6bf..1dcb6d332 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.0" +version = "0.21.1" edition = "2024" license = "MIT OR Apache-2.0" rust-version = "1.95" @@ -12,36 +12,36 @@ 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 = "c60e7a20063313b80a994075adb4f797b24ab4f1" } +craft-mime = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d" } # Shared JSON-RPC 2.0 / MCP server framing and lifecycle. -craft-mcp-server = { git = "https://github.com/storytold/craft-libs", rev = "c60e7a20063313b80a994075adb4f797b24ab4f1", version = "=0.1.0" } +craft-mcp-server = { git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d", 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 = "c60e7a20063313b80a994075adb4f797b24ab4f1", version = "=0.1.0", default-features = false } -craft-designcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "c60e7a20063313b80a994075adb4f797b24ab4f1", version = "=0.1.0" } -craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "c60e7a20063313b80a994075adb4f797b24ab4f1", version = "=0.1.0" } -craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "c60e7a20063313b80a994075adb4f797b24ab4f1", version = "=0.1.0", features = ["read"] } -craft-epub = { git = "https://github.com/storytold/craft-libs", rev = "c60e7a20063313b80a994075adb4f797b24ab4f1", version = "=0.1.0" } -craft-idml = { git = "https://github.com/storytold/craft-libs", rev = "b92907f69d6599b91ac76fb8377ac407c8ac956d", version = "=0.1.0" } -craft-indd = { git = "https://github.com/storytold/craft-libs", rev = "c60e7a20063313b80a994075adb4f797b24ab4f1", version = "=0.1.0" } -craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "c60e7a20063313b80a994075adb4f797b24ab4f1", version = "=0.1.0", features = ["tree-render", "tree-text"] } -craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "b92907f69d6599b91ac76fb8377ac407c8ac956d", version = "=0.1.0" } -craft-rtf = { git = "https://github.com/storytold/craft-libs", rev = "c60e7a20063313b80a994075adb4f797b24ab4f1", version = "=0.1.0" } -craft-xlsx = { git = "https://github.com/storytold/craft-libs", rev = "c60e7a20063313b80a994075adb4f797b24ab4f1", version = "=0.1.0" } -craft-docx = { git = "https://github.com/storytold/craft-libs", rev = "c60e7a20063313b80a994075adb4f797b24ab4f1", version = "=0.1.0" } -craft-wordmodel = { git = "https://github.com/storytold/craft-libs", rev = "c60e7a20063313b80a994075adb4f797b24ab4f1", version = "=0.1.0" } -craft-csv = { git = "https://github.com/storytold/craft-libs", rev = "c60e7a20063313b80a994075adb4f797b24ab4f1", version = "=0.1.0" } -craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "c60e7a20063313b80a994075adb4f797b24ab4f1", version = "=0.1.0" } -craft-jpeg = { git = "https://github.com/storytold/craft-libs", rev = "c60e7a20063313b80a994075adb4f797b24ab4f1", version = "=0.1.0" } -craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "c60e7a20063313b80a994075adb4f797b24ab4f1", version = "=0.1.0" } -craft-file-formats = { git = "https://github.com/storytold/craft-libs", rev = "c60e7a20063313b80a994075adb4f797b24ab4f1", version = "=0.1.0" } -craft-opc = { git = "https://github.com/storytold/craft-libs", rev = "c60e7a20063313b80a994075adb4f797b24ab4f1", version = "=0.1.0" } -craft-pptx = { git = "https://github.com/storytold/craft-libs", rev = "c60e7a20063313b80a994075adb4f797b24ab4f1", version = "=0.1.0" } +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 = "c60e7a20063313b80a994075adb4f797b24ab4f1", version = "=0.1.0", features = ["egui", "ui"] } +craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d", version = "=0.1.0", features = ["egui", "ui"] } # 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 = "c60e7a20063313b80a994075adb4f797b24ab4f1", version = "=0.1.0", features = ["flatten"] } +craft-prepress = { git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d", 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 = "c60e7a20063313b80a994075adb4f797b24ab4f1", features = ["egui"] } +craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "33be35625e252cc4f06aa375b3b428521faea37d", features = ["egui"] } # internal designcraft-geom = { path = "crates/geom" } designcraft-color = { path = "crates/color" } @@ -99,20 +99,20 @@ 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 = "c60e7a20063313b80a994075adb4f797b24ab4f1" } +craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d" } # Atomic file replacement for saves and exports (craft-libs). -craft-atomic = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "c60e7a20063313b80a994075adb4f797b24ab4f1" } +craft-atomic = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d" } # File › Print through the system print spooler (craft-libs). -craft-print = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "c60e7a20063313b80a994075adb4f797b24ab4f1" } +craft-print = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d" } # 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 = "c60e7a20063313b80a994075adb4f797b24ab4f1" } +craft-cms = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d" } # ui # Shared frontend components; keep this dependency above the engine boundary. -craft-ui = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "c60e7a20063313b80a994075adb4f797b24ab4f1", features = ["serde"] } +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 = "c60e7a20063313b80a994075adb4f797b24ab4f1", features = ["egui"] } +craft-window = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d", features = ["egui"] } egui = "0.37" # Resizable table columns (About ▸ Contributors / Models); no image loaders. egui_extras = { version = "0.37", default-features = false } @@ -122,7 +122,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 = "c60e7a20063313b80a994075adb4f797b24ab4f1" } +craft-dialogs = { git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d" } raw-window-handle = "0.6" arboard = { version = "3.6", default-features = false } @@ -156,19 +156,19 @@ 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 = "c60e7a20063313b80a994075adb4f797b24ab4f1", version = "=0.8.2" } +krilla = { git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d", 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 = "c60e7a20063313b80a994075adb4f797b24ab4f1", version = "=0.7.1" } -hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "c60e7a20063313b80a994075adb4f797b24ab4f1", version = "=0.7.0" } -hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "c60e7a20063313b80a994075adb4f797b24ab4f1", version = "=0.7.2" } -hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "c60e7a20063313b80a994075adb4f797b24ab4f1", version = "=0.3.0" } -hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "c60e7a20063313b80a994075adb4f797b24ab4f1", version = "=0.1.0" } -hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "c60e7a20063313b80a994075adb4f797b24ab4f1", version = "=0.1.0" } -linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "c60e7a20063313b80a994075adb4f797b24ab4f1" } -vello_common = { git = "https://github.com/storytold/craft-libs", rev = "c60e7a20063313b80a994075adb4f797b24ab4f1" } -vello_cpu = { git = "https://github.com/storytold/craft-libs", rev = "c60e7a20063313b80a994075adb4f797b24ab4f1" } +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" } diff --git a/ROADMAP.md b/ROADMAP.md index 6f1735a5e..b1064589b 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -1,12 +1,17 @@ # DesignCraft roadmap - 2026-11-19: Arabic UI glyphs use installed Arabic fonts when the optional craft-fonts input is absent; Arabic-specific families keep letters and spaces in the same fallback face (#3018). +- **2026-11-18 · UI1994:** Hidden-character marks follow frame, layer and containing-group + visibility. Locked, visible layers still show marks; showing a hidden layer restores them. + Visibility checks and painting reuse one frame lookup. The canvas painter has synthetic + regression coverage, including table cells and spreads excluded from the canvas layout. + No readiness percentage change. **Stage: pre-alpha** · next: alpha, ~5–7 h away; beta ~28 points and ~420–750 h beyond that (the core-workflow gate, not the percentage: ready for real work is already ~47%) - 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-15 · **Change:** minor (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 (hidden characters follow frame, group and layer visibility (#1994); 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 - 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. @@ -14,6 +19,10 @@ 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-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 + write another story's text. No readiness percentage change. - **2026-11-14** · Files placed from disk are linked instead of embedded: the document keeps a 1024 px proxy and a content hash, opens without reading the originals, and shows link status OK, Modified or Missing, with Update, Relink, Embed and Unembed (native format 5; old embedded documents migrate on save). Several images load into one place cursor, a grid or a contact sheet; see [linked-artwork.md](docs/linked-artwork.md) and [multi-image-placement.md](docs/multi-image-placement.md). No readiness percentage change. - **2026-11-06** · Automation roots refuse `COM¹` to `LPT³` and a device name before a colon (`COM1:`, `NUL:x`). A batch-export layout of that name is written with a leading `_` on every platform. No readiness percentage change. - **2026-10-30** · Document Fonts lookup treats a bare document filename's empty parent as the current directory (#2014), preserving case-insensitive discovery and automation read-root checks. No readiness percentage change. @@ -396,6 +405,7 @@ list) · [roadmap.md](docs/roadmap.md) (milestones, plan) · [parity-checklist.m ## Progress log +- **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-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. - **2026-11-15** · Removed the obsolete gap saying pull requests have no test workflow: [CI](.github/workflows/ci.yml) runs the shared quality gate on every pull request and push to main (#1352). No readiness percentage change. - **2026-11-15** · Accepting tracked deletions or rejecting insertions follows body-text selections through the removed text, including resolving all changes, and preserves independent cell and footnote insertion points. No readiness percentage change. @@ -427,6 +437,7 @@ list) · [roadmap.md](docs/roadmap.md) (milestones, plan) · [parity-checklist.m - **2026-11-02** · Windows: the custom title bar window stays borderless, so the content is no longer drawn offset by the caption and border (black bars at the top and left, clicks landing off target). The workaround goes when winit carries the fix (storytold/winit#17). No readiness percentage change. - **2026-10-30** · The Color Picker takes an eyedropper: dragged from the picker onto the page, it takes the colour the canvas shows (proofed under Proof Colors). No readiness percentage change. - **2026-10-30** · The Color Picker is laid out as the reference app's: a field and slider for the component chosen, HSB, Lab, RGB and CMYK values, the old colour, and Add CMYK Swatch; Enter and Esc close it once. No readiness percentage change. +- **2026-10-24** · View › Story Editor › Show/Hide Paragraph Break Marks (`view.storyEditorParagraphMarks`) shows or hides a ¶ after each paragraph that a paragraph break ends in the Story Editor, as in InDesign. The marks are off until turned on, and the setting is remembered with the preferences. No readiness percentage change. - **2026-10-18** · Table of Contents gains Create PDF Bookmarks: included headings become nested page destinations, regenerated in their existing outline position on update without replacing or moving surrounding manual bookmarks. The setting survives native and IDML files. No readiness percentage change. Newest first. @@ -603,6 +614,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-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. - **2026-10-17** · File › Package writes the document's and the IDML's links relative to the package (`Links/logo.png`, `file:Links/logo.png`), so a package holds no path from the machine that made it; opening a document resolves them to the files beside it. Links › Copy Link(s) To still links by full path. (#340). No readiness percentage change. diff --git a/apps/designcraft-cli/src/main.rs b/apps/designcraft-cli/src/main.rs index 848929d53..7c031ba64 100644 --- a/apps/designcraft-cli/src/main.rs +++ b/apps/designcraft-cli/src/main.rs @@ -170,6 +170,17 @@ fn main() -> ExitCode { } } } + // The Launcher's nightly-v1 profile is a desktop-only contract. Never let its arguments fall + // through to the CLI's directory and credential discovery (which would read the stable + // profile), and answer before any subcommand parses them. A file name after `--` is a file. + if args + .iter() + .take_while(|arg| arg.as_str() != "--") + .any(|arg| arg == "--launch-profile" || arg == "--profile-root" || arg.starts_with("--launch-profile=") || arg.starts_with("--profile-root=")) + { + eprintln!("designcraft-cli: nightly-v1 is supported only by the DesignCraft desktop launcher protocol"); + return ExitCode::from(2); + } // ` --help` asks about that subcommand, which every parser but `script`'s read as an // unknown option (photocraft#423). It goes to stdout and succeeds, as `--help` does. // diff --git a/apps/designcraft-web/Cargo.toml b/apps/designcraft-web/Cargo.toml index 1667e69e3..1922096b7 100644 --- a/apps/designcraft-web/Cargo.toml +++ b/apps/designcraft-web/Cargo.toml @@ -30,4 +30,4 @@ rfd = { workspace = true } wasm-bindgen = "0.2" wasm-bindgen-futures = "0.4" js-sys = "0.3" -web-sys = { version = "0.3", features = ["Event", "EventTarget", "Window", "Document", "Element", "HtmlElement", "HtmlCanvasElement", "HtmlAnchorElement", "Blob", "BlobPropertyBag", "Url", "Location", "CssStyleDeclaration"] } +web-sys = { version = "0.3", features = ["Event", "EventTarget", "Window", "Document", "Element", "HtmlElement", "HtmlCanvasElement", "HtmlAnchorElement", "Blob", "BlobPropertyBag", "Url", "Location", "CssStyleDeclaration", "HtmlInputElement", "FileList", "File", "Storage"] } diff --git a/apps/designcraft-web/src/main.rs b/apps/designcraft-web/src/main.rs index 1b28064a9..c478d88bc 100644 --- a/apps/designcraft-web/src/main.rs +++ b/apps/designcraft-web/src/main.rs @@ -8,8 +8,14 @@ //! - no TCP control channel (browsers can't listen on sockets); //! - File → Open / Place use the browser file picker; bytes arrive asynchronously through //! `Services::inbox` (`.designcraft` → `file.openBytes`, images → `file.place`); -//! - Save and Export trigger a browser download; -//! - dropped files are read asynchronously by `web::WebShell` and delivered through the inbox. +//! - Save and Export trigger a browser download (Save in the format Preferences › File Handling +//! chooses); +//! - the Preferences dialog's settings live in the browser's local storage (`prefs_store`), as +//! the desktop app keeps them in `prefs.json`; +//! - dropped files are read asynchronously by `web::WebShell` and delivered through the inbox; +//! - linked graphics can't be read from their paths (an IDML's Links folder): they show as +//! missing, and relink from files handed over instead (Links › Relink… and Relink to Folder… +//! pick the files, `links.relinkFiles`). //! //! URL query flags: `?webgl` forces the WebGL2 backend instead of WebGPU; `?sample` opens the //! sample magazine on start. Flags match case-sensitive, percent-decoded query keys; values @@ -25,6 +31,9 @@ mod web; #[cfg(any(target_arch = "wasm32", test))] mod graphics; +#[cfg(any(target_arch = "wasm32", test))] +mod prefs_store; + #[cfg(target_arch = "wasm32")] fn main() { web::start(); diff --git a/apps/designcraft-web/src/prefs_store.rs b/apps/designcraft-web/src/prefs_store.rs new file mode 100644 index 000000000..6eb5497f3 --- /dev/null +++ b/apps/designcraft-web/src/prefs_store.rs @@ -0,0 +1,135 @@ +//! Preferences kept in the browser's local storage, as the desktop app keeps `prefs.json`: the +//! Preferences dialog's settings (Save documents as among them) survive a reload. + +use designcraft_engine::Prefs; + +/// The local storage key. +pub(crate) const KEY: &str = "designcraft.prefs"; + +/// Seconds between checks for changed preferences. +const CHECK_EVERY: f64 = 1.0; + +/// The preferences stored under [`KEY`]; `None` when there are none or they can't be read, and +/// the defaults apply. Fields a stored copy lacks (from an older version) take their defaults. +pub(crate) fn decode(stored: Option<&str>) -> Option { + serde_json::from_str(stored?).ok() +} + +/// Decides when to write the preferences back: when they differ from what was last stored, at +/// most once per [`CHECK_EVERY`] seconds of app time. +pub(crate) struct PrefsSync { + /// The JSON last read from or written to storage. + last: Option, + /// App time of the next check. + next_check: f64, +} + +impl PrefsSync { + /// Starts from what storage held at startup, so unchanged preferences aren't written back. + pub(crate) fn new(stored: Option) -> Self { + PrefsSync { last: stored, next_check: 0.0 } + } + + /// Whether to check now (app time `now`, in seconds); the next check is a second later. + pub(crate) fn due(&mut self, now: f64) -> bool { + if !now.is_finite() || now < self.next_check { + return false; + } + self.next_check = now + CHECK_EVERY; + true + } + + /// Seconds from `now` until the next check, when one is still to come; `None` when a check is + /// already due (or `now` isn't a number). The shell asks for a frame then: egui draws no frame + /// just because time passes, so a change made between checks would otherwise wait for the + /// next input before it's stored. + pub(crate) fn wait(&self, now: f64) -> Option { + (now.is_finite() && now < self.next_check).then_some(self.next_check - now) + } + + /// The JSON to store when `prefs` differ from what was last stored; `None` otherwise. Nothing + /// counts as stored until [`PrefsSync::stored`] says the write succeeded, so a write that + /// fails (or storage that isn't available) is tried again at the next check. + pub(crate) fn changed(&self, prefs: &Prefs) -> Option { + let json = serde_json::to_string(prefs).ok()?; + (self.last.as_deref() != Some(json.as_str())).then_some(json) + } + + /// `json` (from [`PrefsSync::changed`]) was written to storage. + pub(crate) fn stored(&mut self, json: String) { + self.last = Some(json); + } +} + +#[cfg(test)] +mod tests { + use super::{KEY, PrefsSync, decode}; + use designcraft_engine::{Prefs, SaveFormat}; + + #[test] + fn stored_preferences_come_back_and_bad_ones_leave_the_defaults() { + assert!(!KEY.is_empty()); + assert!(decode(None).is_none(), "nothing stored: defaults"); + assert!(decode(Some("not json")).is_none(), "unreadable: defaults"); + let old = decode(Some(r#"{"linkTextFiles": true}"#)).unwrap(); + assert!(old.link_text_files); + assert_eq!(old.save_format, SaveFormat::Designcraft, "a field an older copy lacks takes its default"); + let prefs = Prefs { save_format: SaveFormat::Idml, ..Prefs::default() }; + let json = serde_json::to_string(&prefs).unwrap(); + assert_eq!(decode(Some(&json)).unwrap().save_format, SaveFormat::Idml); + } + + #[test] + fn preferences_are_written_only_when_they_change() { + let prefs = Prefs::default(); + let stored = serde_json::to_string(&prefs).unwrap(); + let mut sync = PrefsSync::new(Some(stored)); + assert_eq!(sync.changed(&prefs), None, "unchanged since startup: nothing to write"); + let idml = Prefs { save_format: SaveFormat::Idml, ..Prefs::default() }; + let json = sync.changed(&idml).unwrap(); + assert!(json.contains(r#""saveFormat":"idml""#), "{json}"); + // The write failed (or storage was unavailable): still pending at the next check. + assert_eq!(sync.changed(&idml).as_deref(), Some(json.as_str()), "retried until stored"); + sync.stored(json); + assert_eq!(sync.changed(&idml), None, "written once"); + // Nothing stored yet: the first check writes. + assert!(PrefsSync::new(None).changed(&prefs).is_some()); + } + + #[test] + fn checks_come_at_most_once_a_second() { + let mut sync = PrefsSync::new(None); + assert!(sync.due(0.0)); + assert!(!sync.due(0.5)); + assert!(sync.due(1.0)); + assert!(!sync.due(f64::NAN), "a time that isn't a number is never due"); + } + + /// A check that isn't due yet asks for a frame at its time; a due one doesn't need to. + #[test] + fn a_check_not_yet_due_says_when_it_will_be() { + let mut sync = PrefsSync::new(None); + assert_eq!(sync.wait(0.0), None, "due at once"); + assert!(sync.due(0.0)); + assert_eq!(sync.wait(0.25), Some(0.75)); + assert_eq!(sync.wait(1.0), None); + assert_eq!(sync.wait(f64::NAN), None); + } + + /// A write that failed at a due check is retried at the next one: right after the check, + /// `wait` gives that time (the shell asks for a frame then, so an idle app retries too), and + /// the change is still pending when it comes. + #[test] + fn a_failed_write_is_retried_at_the_next_check_without_input() { + let mut sync = PrefsSync::new(None); + let prefs = Prefs { save_format: SaveFormat::Idml, ..Prefs::default() }; + assert!(sync.due(5.0)); + assert!(sync.changed(&prefs).is_some(), "a change to write"); + // The write failed: nothing marked stored. + assert_eq!(sync.wait(5.0), Some(1.0), "the next check is scheduled from the failed one"); + assert!(sync.due(6.0)); + let json = sync.changed(&prefs).expect("still pending at the next check"); + sync.stored(json); + assert!(sync.changed(&prefs).is_none(), "written: nothing pending"); + } +} diff --git a/apps/designcraft-web/src/web.rs b/apps/designcraft-web/src/web.rs index 4d4c936c1..f1eedc1b3 100644 --- a/apps/designcraft-web/src/web.rs +++ b/apps/designcraft-web/src/web.rs @@ -1,6 +1,7 @@ //! The browser shell: web `Services`, drag-and-drop, and the eframe web runner. use super::browser_policy::{has_query_flag, mime_for}; +use super::prefs_store::{self, PrefsSync}; use crate::graphics::{GraphicsState, RecoveryDocument, recovery_documents}; use designcraft_engine::Session; use designcraft_ui_egui::{DesignApp, ImportRequest, ImportedFile, Inbox, Services}; @@ -28,6 +29,8 @@ const IMAGE_EXTS: &[&str] = &[ "idml", "designcraft", ]; +/// Graphics a relink reads (the image and vector formats placing accepts). +const GRAPHIC_EXTS: &[&str] = &["png", "jpg", "jpeg", "gif", "webp", "tif", "tiff", "bmp", "psd", "svg", "pdf", "ai"]; const CANVAS_ID: &str = "designcraft_canvas"; const LOADING_ID: &str = "designcraft_loading"; @@ -73,10 +76,16 @@ pub fn start() { } let inbox: Inbox = Inbox::default(); let mut app = DesignApp::new(Session::new(), services(inbox.clone(), cc.egui_ctx.clone())); + // The preferences saved by an earlier visit (as the desktop app reads prefs.json). + let stored = local_storage().and_then(|s| s.get_item(prefs_store::KEY).ok().flatten()); + if let Some(prefs) = prefs_store::decode(stored.as_deref()) { + app.session.prefs = prefs; + } + let prefs_sync = PrefsSync::new(stored); if has_query_flag(&query(), "sample") { let _ = app.run("file.newSample", serde_json::json!({})); } - Ok(Box::new(WebShell { app, inbox, read_errors: Default::default(), graphics: creator_graphics })) + Ok(Box::new(WebShell { app, inbox, read_errors: Default::default(), graphics: creator_graphics, prefs_sync })) }), ) .await; @@ -335,6 +344,11 @@ fn add_document_recovery_controls(snapshots: Vec) -> Result Option { + web_sys::window()?.local_storage().ok().flatten() +} + fn query() -> String { web_sys::window().and_then(|w| w.location().search().ok()).unwrap_or_default() } @@ -347,6 +361,8 @@ struct WebShell { /// Why a dropped file couldn't be read, for the status bar (the read finishes outside a frame). read_errors: std::sync::Arc>>, graphics: GraphicsState, + /// Writes the preferences to local storage when they change. + prefs_sync: PrefsSync, } impl eframe::App for WebShell { @@ -357,6 +373,34 @@ impl eframe::App for WebShell { self.app.status(error); } let _ = graphics.run_if_healthy(|| self.app.logic(ctx)); + // Changed preferences go to local storage, so they survive a reload. + let now = ctx.input(|i| i.time); + if let Some(wait) = self.prefs_sync.wait(now) { + // Not due yet: a frame then checks, even if nothing else happens until then. + if let Ok(d) = std::time::Duration::try_from_secs_f64(wait) { + ctx.request_repaint_after(d); + } + } else if self.prefs_sync.due(now) + && let Some(json) = self.prefs_sync.changed(&self.app.session.prefs) + { + // Counted as stored only once written; otherwise it's tried again at the next check. + let written = match local_storage() { + Some(storage) => match storage.set_item(prefs_store::KEY, &json) { + Ok(()) => true, + Err(e) => { + log::warn!("couldn't keep the preferences in local storage: {e:?}"); + false + } + }, + None => false, + }; + if written { + self.prefs_sync.stored(json); + } else if let Some(d) = self.prefs_sync.wait(now).and_then(|w| std::time::Duration::try_from_secs_f64(w).ok()) { + // Still pending: a frame at the next check retries, even if the app is idle. + ctx.request_repaint_after(d); + } + } } fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) { @@ -418,11 +462,29 @@ fn services(inbox: Inbox, ctx: egui::Context) -> Services { rfd::AsyncFileDialog::new().add_filter("Swatch Exchange (ASE)", &["ase"]) } else if request.purpose == "shortcuts" { rfd::AsyncFileDialog::new().add_filter("Shortcut set (JSON, InDesign text)", &["json", "txt"]) + } else if request.purpose.starts_with("relink") { + rfd::AsyncFileDialog::new().add_filter("Graphics", GRAPHIC_EXTS) } else if request.purpose == "place" { rfd::AsyncFileDialog::new().add_filter("Graphics", IMAGE_EXTS) } else { rfd::AsyncFileDialog::new().add_filter("DesignCraft, IDML or InDesign", DOC_EXTS) }; + // Relink to Folder: the browser's folder picker hands over every graphic in the + // chosen folder; they arrive together, to relink in one step. + if request.purpose == "relinkFiles" { + wasm_bindgen_futures::spawn_local(async move { + let files: Vec = pick_folder_files(&request.wanted) + .await + .into_iter() + .map(|(name, bytes)| ImportedFile { request: request.clone(), name, bytes }) + .collect(); + if !files.is_empty() { + inbox.lock().unwrap_or_else(|e| e.into_inner()).extend(files); + ctx.request_repaint(); + } + }); + return; + } wasm_bindgen_futures::spawn_local(async move { // Place takes several files, loaded into the place cursor in the order chosen. let handles = if request.purpose == "place" { @@ -446,6 +508,73 @@ fn services(inbox: Inbox, ctx: egui::Context) -> Services { } } +/// The most files a chosen folder hands over for relinking, and the most bytes in all. +const MAX_FOLDER_FILES: usize = 2000; +// The bytes are copied a few times on the way (base64 for the command, then decoded), so the +// cap keeps the peak well inside the browser's memory for a tab. +const MAX_FOLDER_BYTES: f64 = 256.0 * 1024.0 * 1024.0; + +/// The graphics named in `wanted` (lower-case file names; empty: every graphic) in a folder the +/// user chooses with the browser's folder picker (an ``, which +/// every current browser supports), each named by its path in the folder. Only those files are +/// read, up to [`MAX_FOLDER_FILES`] and [`MAX_FOLDER_BYTES`]; empty when the picker is cancelled +/// or can't be shown. +async fn pick_folder_files(wanted: &[String]) -> Vec<(String, Vec)> { + let Some(document) = web_sys::window().and_then(|w| w.document()) else { return Vec::new() }; + let Some(input) = document.create_element("input").ok().and_then(|e| e.dyn_into::().ok()) else { + return Vec::new(); + }; + input.set_type("file"); + input.set_multiple(true); + if input.set_attribute("webkitdirectory", "").is_err() { + return Vec::new(); + } + // Settles when files are chosen or the picker is cancelled. The listener is this call's and + // goes when the picker settles, not kept for the page's life. (A browser that fires neither + // event leaves this call waiting; current browsers fire `cancel`.) + let mut resolve = None; + let chosen = js_sys::Promise::new(&mut |r, _reject| resolve = Some(r)); + let Some(resolve) = resolve else { return Vec::new() }; + let done = wasm_bindgen::closure::Closure::::new(move || { + let _ = resolve.call0(&wasm_bindgen::JsValue::UNDEFINED); + }); + for event in ["change", "cancel"] { + let _ = input.add_event_listener_with_callback(event, done.as_ref().unchecked_ref()); + } + input.click(); + let _ = wasm_bindgen_futures::JsFuture::from(chosen).await; + for event in ["change", "cancel"] { + let _ = input.remove_event_listener_with_callback(event, done.as_ref().unchecked_ref()); + } + drop(done); + let Some(list) = input.files() else { return Vec::new() }; + let mut out = Vec::new(); + let mut bytes = 0.0; + for i in 0..list.length() { + let Some(file) = list.get(i) else { continue }; + let name = file.name(); + let graphic = name.rsplit_once('.').is_some_and(|(_, ext)| GRAPHIC_EXTS.iter().any(|e| e.eq_ignore_ascii_case(ext))); + if !graphic || !(wanted.is_empty() || wanted.contains(&name.to_lowercase())) { + continue; + } + if out.len() >= MAX_FOLDER_FILES || bytes + file.size() > MAX_FOLDER_BYTES { + log::warn!("Relink to Folder: more graphics than can be read at once; the rest are left"); + break; + } + bytes += file.size(); + // Its path within the chosen folder tells same-named files in different folders apart. + let path = js_sys::Reflect::get(&file, &wasm_bindgen::JsValue::from_str("webkitRelativePath")) + .ok() + .and_then(|v| v.as_string()) + .filter(|p| !p.is_empty()) + .unwrap_or(name); + if let Ok(buf) = wasm_bindgen_futures::JsFuture::from(file.array_buffer()).await { + out.push((path, js_sys::Uint8Array::new(&buf).to_vec())); + } + } + out +} + /// Trigger a browser download of `bytes` named after the last component of `path`. fn download(path: &str, bytes: &[u8]) -> Result<(), String> { let js = |e: wasm_bindgen::JsValue| format!("{e:?}"); diff --git a/apps/designcraft/Cargo.toml b/apps/designcraft/Cargo.toml index b66041a04..359e00470 100644 --- a/apps/designcraft/Cargo.toml +++ b/apps/designcraft/Cargo.toml @@ -18,6 +18,8 @@ egui = { workspace = true } serde = { workspace = true } serde_json = { workspace = true } log = { workspace = true } +# Non-exhaustive identity errors for the nightly process identity (`src/process_identity.rs`). +thiserror = { workspace = true } [build-dependencies] # Icon + VERSIONINFO for designcraft.exe; build.rs only uses it when the target is Windows. @@ -40,7 +42,7 @@ craft-update = { workspace = true } # that shows it; drawing on a GPU without a monitor reset the display driver. Safe wrappers over # Win32 (MIT); the `user` feature is User32.dll only. Also the window frame for the custom title # bar (src/window_frame.rs, window styles). -winsafe = { version = "0.0.29", default-features = false, features = ["user"] } +winsafe = { version = "0.0.29", default-features = false, features = ["user", "shell"] } [target.'cfg(target_os = "macos")'.dependencies] # The same winit as eframe; only the native termination opt-in is used. diff --git a/apps/designcraft/build.rs b/apps/designcraft/build.rs index f18ce9cf3..60abb38a7 100644 --- a/apps/designcraft/build.rs +++ b/apps/designcraft/build.rs @@ -1,29 +1,104 @@ -//! Windows only: embed the app icon and version info (VERSIONINFO) into `designcraft.exe`, so it -//! shows in Explorer, the taskbar, the Start menu and Alt-Tab. +//! Windows resources, and the build-time channel and version baked into the binary. //! -//! On every other target this does nothing. A missing resource compiler is a warning, so a -//! cross-compile from macOS or Linux still links, unless `DESIGNCRAFT_REQUIRE_WINRES=1` turns it -//! into an error (for release builds). +//! `DESIGNCRAFT_BUILD_CHANNEL=nightly-v1` selects the Launcher's nightly-v1 flavor: it must come +//! with an exact `DESIGNCRAFT_VERSION` feed identity (`X.Y.Z-nightly.YYYYMMDD...g`) +//! plus the matching `DESIGNCRAFT_BUILD_SHA` and `DESIGNCRAFT_BUILD_DATE`. Unset, empty or `stable` +//! is the stable build; anything else is a build error, so a runtime environment cannot promote it. +//! +//! The icon and VERSIONINFO go into `designcraft.exe` only. A missing resource compiler is a +//! warning, so a cross-compile from macOS or Linux still links, unless `DESIGNCRAFT_REQUIRE_WINRES=1` +//! (set by the release workflow) turns it into an error. + +#[path = "src/build_channel.rs"] +mod build_channel; + +fn die(message: &str) -> ! { + eprintln!("{message}"); + std::process::exit(1); +} fn main() { println!("cargo:rerun-if-changed=build.rs"); + println!("cargo:rerun-if-env-changed=DESIGNCRAFT_BUILD_CHANNEL"); + println!("cargo:rerun-if-env-changed=DESIGNCRAFT_VERSION"); + println!("cargo:rerun-if-env-changed=DESIGNCRAFT_OVERRIDE_VERSION"); + println!("cargo:rerun-if-env-changed=DESIGNCRAFT_BUILD_SHA"); + println!("cargo:rerun-if-env-changed=DESIGNCRAFT_BUILD_DATE"); + println!("cargo:rustc-check-cfg=cfg(designcraft_nightly_v1)"); + let nightly = match std::env::var("DESIGNCRAFT_BUILD_CHANNEL").as_deref() { + Ok("nightly-v1") => { + println!("cargo:rustc-cfg=designcraft_nightly_v1"); + true + } + // An empty value (an unset CI input) means the default stable build. + Ok("stable" | "") | Err(std::env::VarError::NotPresent) => false, + // A non-UTF-8 value is as unusable as an unknown one: refuse it instead of guessing. + Ok(_) | Err(std::env::VarError::NotUnicode(_)) => die("unsupported DESIGNCRAFT_BUILD_CHANNEL (expected stable or nightly-v1)"), + }; + let built_version = if nightly { + // The shared workflow exports the prepared version as `DESIGNCRAFT_VERSION` and, for the + // binary, an override of the same value; both must agree when both are set. + let prepared = std::env::var("DESIGNCRAFT_VERSION").ok(); + let overridden = std::env::var("DESIGNCRAFT_OVERRIDE_VERSION").ok(); + if let (Some(prepared), Some(overridden)) = (&prepared, &overridden) + && prepared != overridden + { + die("DESIGNCRAFT_VERSION and DESIGNCRAFT_OVERRIDE_VERSION disagree"); + } + let Some(version) = overridden.or(prepared) else { + die("nightly-v1 requires an explicit DESIGNCRAFT_VERSION feed identity"); + }; + if !build_channel::is_nightly_version(&version) { + die("nightly-v1 requires DESIGNCRAFT_VERSION to be X.Y.Z-nightly.YYYYMMDD...g"); + } + let sha = std::env::var("DESIGNCRAFT_BUILD_SHA").unwrap_or_default(); + if sha.len() != 40 || !sha.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) { + die("nightly-v1 requires DESIGNCRAFT_BUILD_SHA to be the 40-hex source commit"); + } + if build_channel::nightly_commit(&version) != Some(&sha[..12]) { + die("DESIGNCRAFT_VERSION names a different commit than DESIGNCRAFT_BUILD_SHA"); + } + let date = std::env::var("DESIGNCRAFT_BUILD_DATE").unwrap_or_default(); + let digits: Vec = date.chars().filter(|c| c.is_ascii_digit()).collect(); + if date.len() != 10 || date.as_bytes()[4] != b'-' || date.as_bytes()[7] != b'-' || digits.iter().collect::() != date.replace('-', "") + { + die("nightly-v1 requires DESIGNCRAFT_BUILD_DATE as YYYY-MM-DD"); + } + if build_channel::nightly_date_digits(&version) != Some(&date.replace('-', "")) { + die("DESIGNCRAFT_VERSION names a different date than DESIGNCRAFT_BUILD_DATE"); + } + // A nightly-only name: `option_env!` reads the compiler's process environment, and stable + // packaging always exports DESIGNCRAFT_BUILD_SHA, which must not turn a Stable build nightly. + println!("cargo:rustc-env=DESIGNCRAFT_NIGHTLY_COMMIT={sha}"); + println!("cargo:rustc-env=DESIGNCRAFT_BUILD_DATE={date}"); + version + } else { + std::env::var("CARGO_PKG_VERSION").unwrap_or_default() + }; + // One compile-time identity for `--version`, About and the session record. + println!("cargo:rustc-env=DESIGNCRAFT_BUILT_VERSION={built_version}"); + println!("cargo:rerun-if-changed=../../assets/app-icon/designcraft.ico"); + println!("cargo:rerun-if-changed=../../assets/app-icon/designcraft-nightly.ico"); println!("cargo:rerun-if-env-changed=DESIGNCRAFT_REQUIRE_WINRES"); if std::env::var("CARGO_CFG_TARGET_OS").as_deref() != Ok("windows") { return; } let mut res = winresource::WindowsResource::new(); - res.set_icon("../../assets/app-icon/designcraft.ico") - .set("ProductName", "DesignCraft") - .set("FileDescription", "DesignCraft page layout") + res.set_icon(build_channel::windows_icon_path(nightly)) + .set("ProductName", if nightly { "DesignCraft Nightly" } else { "DesignCraft" }) + .set("FileDescription", if nightly { "DesignCraft Nightly page layout" } else { "DesignCraft page layout" }) .set("CompanyName", "Learning Machines LLC") .set("LegalCopyright", "Copyright (c) the DesignCraft authors. MIT OR Apache-2.0.") .set("OriginalFilename", "designcraft.exe") .set("InternalName", "designcraft"); + if nightly { + // The Launcher checks the PE ProductVersion against the exact feed identity, not FileVersion. + res.set("ProductVersion", &built_version); + } if let Err(e) = res.compile() { if std::env::var_os("DESIGNCRAFT_REQUIRE_WINRES").is_some() { - eprintln!("embedding Windows resources failed: {e}"); - std::process::exit(1); + die(&format!("embedding Windows resources failed: {e}")); } println!("cargo:warning=designcraft.exe built without icon/version resources: {e}"); } diff --git a/apps/designcraft/src/build_channel.rs b/apps/designcraft/src/build_channel.rs new file mode 100644 index 000000000..b13d18c6c --- /dev/null +++ b/apps/designcraft/src/build_channel.rs @@ -0,0 +1,78 @@ +//! The build-time nightly identity shared by the build script and its pure regression tests. +pub fn is_nightly_version(version: &str) -> bool { + let Some((base, suffix)) = version.split_once("-nightly.") else { return false }; + let digits = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit()); + let base: Vec<_> = base.split('.').collect(); + let parts: Vec<_> = suffix.split('.').collect(); + base.len() == 3 + && base.iter().all(|s| digits(s)) + && parts.len() == 4 + && parts[0].len() == 8 + && digits(parts[0]) + && digits(parts[1]) + && digits(parts[2]) + && parts[3].strip_prefix('g').is_some_and(|sha| sha.len() == 12 && sha.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))) +} + +/// The `X.Y.Z-nightly.YYYYMMDD...g` feed version's date digits, or `None`. +/// Used by the build script; the app itself only needs the channel and icon rules. +#[allow(dead_code)] +pub fn nightly_date_digits(version: &str) -> Option<&str> { + let suffix = version.split_once("-nightly.")?.1; + suffix.split('.').next().filter(|date| date.len() == 8) +} + +/// The commit the feed version names, without its `g` prefix. +#[allow(dead_code)] +pub fn nightly_commit(version: &str) -> Option<&str> { + version.rsplit_once(".g").map(|(_, sha)| sha).filter(|sha| sha.len() == 12) +} + +pub fn windows_icon_path(nightly: bool) -> &'static str { + if nightly { "../../assets/app-icon/designcraft-nightly.ico" } else { "../../assets/app-icon/designcraft.ico" } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn windows_resource_uses_the_flavor_specific_icon_without_changing_stable() { + assert_eq!(windows_icon_path(false), "../../assets/app-icon/designcraft.ico"); + assert_eq!(windows_icon_path(true), "../../assets/app-icon/designcraft-nightly.ico"); + } + + #[test] + fn explicit_feed_identity_is_required_for_a_nightly_build() { + assert!(is_nightly_version("0.2.1-nightly.20261124.17.1.gabcdef012345")); + for invalid in [ + "", + "0.2.1", + "0.2.1-nightly", + "0.2.1-nightly.20261124", + "0.2.1-nightly.20261124.17.1.gABCDEF012345", + "0.2.1-nightly.20261124.17.1.gabcdef012345\n", + ] { + assert!(!is_nightly_version(invalid), "{invalid:?}"); + } + } + + #[test] + fn version_cannot_inject_a_path_or_an_extra_build_directive() { + for invalid in [ + "../0.2.1-nightly.20261124.1.1.gabcdef012345", + "0.2.1-nightly.20261124.1.1.gabcdef012345/other", + "0.2.1-nightly.20261124.1.1.gabcdef012345\ncargo:rustc-cfg=other", + ] { + assert!(!is_nightly_version(invalid)); + } + } + + #[test] + fn the_feed_identity_yields_its_date_and_commit() { + assert_eq!(nightly_date_digits("0.2.1-nightly.20261124.17.1.gabcdef012345"), Some("20261124")); + assert_eq!(nightly_commit("0.2.1-nightly.20261124.17.1.gabcdef012345"), Some("abcdef012345")); + assert_eq!(nightly_date_digits("0.2.1"), None); + assert_eq!(nightly_commit("0.2.1"), None); + } +} diff --git a/apps/designcraft/src/build_flavor.rs b/apps/designcraft/src/build_flavor.rs new file mode 100644 index 000000000..0793f44ed --- /dev/null +++ b/apps/designcraft/src/build_flavor.rs @@ -0,0 +1,89 @@ +//! 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 const COMPILED: BuildFlavor = if cfg!(designcraft_nightly_v1) { BuildFlavor::NightlyV1 } else { BuildFlavor::Stable }; + +/// The version baked in by `build.rs`: the workspace version for stable, the exact feed identity for nightly. +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 +} + +pub fn version_query(args: &[OsString]) -> bool { + matches!(args, [arg] if arg == "--version" || arg == "-V") +} + +/// The line `--version` prints: ` (nightly-v1)` for nightly, stable's own form otherwise. +pub fn version_line(flavor: BuildFlavor, stable: &str, version: &str) -> String { + match flavor { + BuildFlavor::Stable => stable.to_owned(), + BuildFlavor::NightlyV1 => format!("DesignCraft {version} (nightly-v1)"), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn only_a_nightly_desktop_refusal_requests_a_native_dialog() { + assert!(needs_native_error(BuildFlavor::NightlyV1, true)); + assert!(!needs_native_error(BuildFlavor::NightlyV1, false)); + assert!(!needs_native_error(BuildFlavor::Stable, true)); + 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"; + assert_eq!(version_line(BuildFlavor::Stable, "designcraft 0.2.1", version), "designcraft 0.2.1"); + assert_eq!(version_line(BuildFlavor::NightlyV1, "designcraft 0.2.1", version), format!("DesignCraft {version} (nightly-v1)")); + assert!(version_query(&["--version".into()])); + assert!(version_query(&["-V".into()])); + assert!(!version_query(&["--".into(), "--version".into()])); + assert!(!version_query(&[])); + } + + #[test] + fn the_compiled_version_is_the_flavor_s_own() { + match COMPILED { + BuildFlavor::Stable => assert_eq!(VERSION, env!("CARGO_PKG_VERSION")), + BuildFlavor::NightlyV1 => assert!(crate::build_channel::is_nightly_version(VERSION), "{VERSION}"), + } + } +} diff --git a/apps/designcraft/src/launch_profile.rs b/apps/designcraft/src/launch_profile.rs new file mode 100644 index 000000000..f2b421433 --- /dev/null +++ b/apps/designcraft/src/launch_profile.rs @@ -0,0 +1,217 @@ +//! 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. + +use std::ffi::OsString; +use std::path::{Component, Path, PathBuf}; +use std::sync::OnceLock; + +pub const VERSION: &str = "nightly-v1"; + +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Profile { + Stable, + NightlyV1(PathBuf), +} + +impl Profile { + pub fn is_nightly(&self) -> bool { + matches!(self, Self::NightlyV1(_)) + } + + pub fn root(&self) -> Option<&Path> { + match self { + Self::Stable => None, + Self::NightlyV1(root) => Some(root), + } + } +} + +#[derive(Debug, PartialEq, Eq)] +pub struct Launch { + pub profile: Profile, + pub args: Vec, +} + +static PROFILE: OnceLock = OnceLock::new(); + +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; + } + if arg == "--launch-profile" || arg == "--profile-root" { + let slot = if arg == "--launch-profile" { &mut selector } else { &mut root }; + if slot.is_some() { + return Err("the profile selector and root must each occur exactly once".into()); + } + let value = iter.next().filter(|v| !v.is_empty()).ok_or("the profile selector/root needs a value")?; + if value.to_string_lossy().starts_with("--") { + return Err("the profile selector/root needs a value".into()); + } + *slot = Some(value.clone()); + } else if arg.to_string_lossy().starts_with("--launch-profile=") || arg.to_string_lossy().starts_with("--profile-root=") { + return Err("the nightly protocol requires separate literal selector/root argument tokens".into()); + } else { + other.push(arg.clone()); + } + } + match (selector, root) { + (None, None) => Ok(Launch { profile: Profile::Stable, args }), + (Some(version), Some(root)) if version == VERSION => { + if !delimiter || !other.is_empty() { + return Err("nightly-v1 accepts only its selector/root followed by -- and file names".into()); + } + let root = PathBuf::from(root); + if !root.is_absolute() || root.components().any(|c| matches!(c, Component::ParentDir)) { + return Err("the nightly profile root must be absolute and contain no parent traversal".into()); + } + Ok(Launch { profile: Profile::NightlyV1(root), args: std::iter::once(OsString::from("--")).chain(files).collect() }) + } + (Some(_), Some(_)) => Err("unsupported launch profile (expected nightly-v1)".into()), + _ => Err("--launch-profile and --profile-root must be supplied together".into()), + } +} + +/// The Launcher's version check: the selector/root pair followed by exactly `--version` (or `-V`), +/// answered like a plain version query. Only [`parse`]'s lexical checks apply; the root is never +/// validated or touched, and `-- --version` stays a file name. +pub fn version_query(args: &[OsString]) -> bool { + let Some((last, pair)) = args.split_last() else { return false }; + if last != "--version" && last != "-V" { + return false; + } + let lexical = pair.iter().cloned().chain(std::iter::once(OsString::from("--"))).collect(); + matches!(parse(lexical), Ok(Launch { profile: Profile::NightlyV1(_), args }) if args.len() == 1) +} + +/// Validation finishes before the caller's first startup effect. Stable never calls the nightly +/// root validator, so its old 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; + + fn args(values: &[&str]) -> Vec { + values.iter().map(OsString::from).collect() + } + + fn absolute() -> &'static str { + 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 stable_arguments_and_directory_policy_are_unchanged() { + 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 }); + } + } + + #[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]; + for flag in ["--version", "-V"] { + for form in [pair, reversed] { + let mut argv = args(form); + argv.push(flag.into()); + assert!(version_query(&argv), "{argv:?}"); + } + } + 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()); + } + + #[test] + fn failed_root_validation_never_reaches_startup_or_falls_back_to_stable() { + let reached = Cell::new(false); + let result = prepare(parse(nightly()).unwrap(), |_| Err("read-only or unsafe profile".into())).map(|_| reached.set(true)); + assert!(result.is_err()); + assert!(!reached.get()); + } + + #[test] + fn successful_root_validation_keeps_the_persistent_root_not_the_binary_tag() { + let checked = PathBuf::from(absolute()).join("checked"); + let launch = prepare(parse(nightly()).unwrap(), |_| Ok(checked.clone())).unwrap(); + assert_eq!(launch.profile.root(), Some(checked.as_path())); + assert!(launch.profile.is_nightly()); + } +} diff --git a/apps/designcraft/src/main.rs b/apps/designcraft/src/main.rs index 82d1808f5..23688b3f6 100644 --- a/apps/designcraft/src/main.rs +++ b/apps/designcraft/src/main.rs @@ -15,16 +15,24 @@ #[cfg(target_os = "macos")] mod apple_events; +// The build script includes this file by path; the crate needs it only for its tests. +#[cfg(test)] +mod build_channel; +mod build_flavor; mod clipboard_image; mod control_server; mod gpu; mod gpu_limits; +mod launch_profile; mod logging; #[cfg(target_os = "macos")] mod native_menu; +mod nightly_session; #[cfg(target_os = "macos")] mod pointer; +mod process_identity; mod profile; +mod profile_root; mod window_frame; use designcraft_engine::Session; @@ -48,6 +56,10 @@ struct App { /// (`gpu_limits::log_uncaptured_errors`). Until then wgpu's default handler panics, so a /// failing adapter still makes `gpu` start again on the next one. log_errors_after_startup: Option, + /// The Nightly session record's owner, finished on the one exit path (`on_exit`). + session: nightly_session::Shared, + /// Whether this window showed the previous Nightly session's unclean-exit notice. + unclean_notice_shown: bool, } impl eframe::App for App { @@ -107,6 +119,8 @@ impl eframe::App for App { fn on_exit(&mut self) { // A normal exit before the third frame is not a crash. self.startup.presented(); + // The one exit path, including macOS Dock Quit (`with_close_requested_on_terminate`). + nightly_session::finish_once(&self.session, self.unclean_notice_shown); if let Err(e) = preserve_documents_on_exit(&mut self.app) { log::error!("Couldn't preserve documents on exit: {e}"); eprintln!("designcraft: couldn't preserve documents on exit: {e}"); @@ -238,16 +252,18 @@ fn services() -> Services { } } -/// Desktop app ID: the Linux `.desktop` file name and hicolor icon name (Wayland matches windows by it). -const APP_ID: &str = "ai.storyteller.designcraft"; - /// The window, Dock, taskbar and Alt-Tab icon. macOS gets Apple's icon grid (transparent margin); /// elsewhere the full tile. Regenerate with `packaging/icons.sh`. fn app_icon() -> Option { + // The Nightly keeps the artwork on its deeper field, so a dock or window list shows the channel. #[cfg(target_os = "macos")] let png: &[u8] = include_bytes!("../../../assets/app-icon/designcraft-macos-512.png"); #[cfg(not(target_os = "macos"))] - let png: &[u8] = include_bytes!("../../../assets/app-icon/hicolor/256x256/apps/ai.storyteller.designcraft.png"); + let png: &[u8] = if designcraft_ui_egui::channel::is_nightly() { + include_bytes!("../../../assets/app-icon/designcraft-nightly.png") + } else { + include_bytes!("../../../assets/app-icon/hicolor/256x256/apps/ai.storyteller.designcraft.png") + }; eframe::icon_data::from_png_bytes(png).map_err(|e| log::warn!("app icon: {e}")).ok() } @@ -262,34 +278,186 @@ fn control_port_from(source: &str, value: Option) -> Option { port } +/// What [`prepare_launch`] decided before any start-up service ran. +struct Launched { + /// The arguments left for the ordinary parser (files, and `--` already removed). + args: Vec, + /// This is the Launcher's nightly-v1 build, started with its profile. + nightly: bool, + /// The Nightly session record's owner. + session: nightly_session::Shared, + /// The previous Nightly session did not end cleanly. + unclean: bool, + /// This window could not take the session record (a second Nightly is running). + session_unavailable: bool, +} + +fn desktop_session() -> bool { + cfg!(windows) + || cfg!(target_os = "macos") + || (cfg!(target_os = "linux") && ["DISPLAY", "WAYLAND_DISPLAY"].into_iter().any(|key| std::env::var_os(key).is_some_and(|v| !v.is_empty()))) +} + +/// Whether a refusal may also open a native message box. Standard error always carries the reason; +/// this only adds a box where one renders without the app's event loop. Never on macOS: rfd's alert +/// there needs the AppKit run loop this start has not reached, so a refused nightly launch hung in +/// an invisible modal instead of exiting (GridCraft Mac smoke, 2026-11-26). +fn refusal_dialog(flavor: build_flavor::BuildFlavor, desktop_session: bool, macos: bool) -> bool { + build_flavor::needs_native_error(flavor, desktop_session) && !macos +} + +/// A Nightly launch that is refused before the window: say why where the user looks. +#[allow(clippy::disallowed_types, reason = "native refusal before any window exists")] +fn report_launch_profile_error(error: &str) { + eprintln!("DesignCraft launch profile: {error}"); + if refusal_dialog(build_flavor::COMPILED, desktop_session(), cfg!(target_os = "macos")) { + // Before any window exists, so this is not the in-frame dialog clippy.toml forbids. + let _ = rfd::MessageDialog::new() + .set_title("DesignCraft Nightly") + .set_description(error) + .set_level(rfd::MessageLevel::Error) + .set_buttons(rfd::MessageButtons::Ok) + .show(); + } +} + +/// 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. +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)) + { + 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(); + 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"))) + { + report_launch_profile_error(&error); + std::process::exit(2); + } + let mut session = nightly_session::shared(); + let mut unclean = false; + let mut session_unavailable = false; + if nightly { + match nightly_session::Session::begin_with_health( + launch_profile::current().root(), + build_flavor::VERSION, + option_env!("DESIGNCRAFT_NIGHTLY_COMMIT"), + ) { + Ok((watch, unavailable)) => { + unclean = watch.as_ref().is_some_and(nightly_session::Session::previous_unclean); + session_unavailable = unavailable; + session = nightly_session::shared_with(watch); + } + Err(error) => { + // Standard error only: this runs before the log file exists. + eprintln!("designcraft: Nightly session state is unavailable: {error}"); + session_unavailable = true; + } + } + } + Some(Launched { args: launch.args, nightly, session, unclean, session_unavailable }) +} + +/// The ordinary command line, once the launch profile was selected. +#[derive(Default)] +struct AppCommand { + /// `--control ` (Stable only). + control_port: Option, + /// `--sample` (Stable only). + sample: bool, + /// A Stable `--version`/`-V`, answered before anything starts. + version: bool, + /// Documents to open, in the order they were named. + files: Vec, + /// The graphics backends a restart asked to skip ([`gpu::SKIP_ARG`]). + 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. +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. + args.next(); + } + while let Some(a) = args.next() { + let text = a.to_string_lossy().into_owned(); + match text.as_str() { + "--" if !nightly => { + command.files.extend(args.map(|rest| rest.to_string_lossy().into_owned())); + break; + } + "--control" if !nightly => command.control_port = control_port_from("--control", args.next().map(|v| v.to_string_lossy().into_owned())), + "--sample" if !nightly => command.sample = true, + "--version" | "-V" if !nightly => { + command.version = true; + break; + } + _ => match gpu::skip_arg(&text) { + Some(list) => command.skip = list, + None => command.files.push(text), + }, + } + } + command +} + fn main() -> std::process::ExitCode { - // Windows: the update helper is a copy of this program started with `--finish-update`. + let Some(launch) = prepare_launch() else { return std::process::ExitCode::SUCCESS }; + // Windows: the update helper is a copy of this program started with `--finish-update`. A + // Nightly copy is installed and updated by the Launcher, so it never runs the updater. #[cfg(windows)] - if let Some(result) = craft_update::self_update::finish(&designcraft_ui_egui::UPDATE_APP, &std::env::args_os().skip(1).collect::>()) { + if !launch.nightly + && let Some(result) = craft_update::self_update::finish(&designcraft_ui_egui::UPDATE_APP, &std::env::args_os().skip(1).collect::>()) + { std::process::exit(i32::from(result.is_err())); } // First, so every start-up record (and the engine's panic hook, installed with the first // Session) is captured; see `logging`. let logger = logging::install(); - let mut control_port = control_port_from("DESIGNCRAFT_CONTROL_PORT", std::env::var("DESIGNCRAFT_CONTROL_PORT").ok()); - let mut files = Vec::new(); - let mut sample = false; - let mut skip = Vec::new(); - let mut args = std::env::args().skip(1); - while let Some(a) = args.next() { - match a.as_str() { - "--control" => control_port = control_port_from("--control", args.next()), - "--sample" => sample = true, - "--version" => { - println!("designcraft {}", env!("CARGO_PKG_VERSION")); - return std::process::ExitCode::SUCCESS; - } - _ => match gpu::skip_arg(&a) { - Some(list) => skip = list, - None => files.push(a), - }, - } + // A Nightly launch is handed files only; its control channel, sample document and graphics + // restart options are not part of the Launcher's protocol. + let command = app_command(launch.args, launch.nightly); + if command.version { + println!("{}", build_flavor::version_line(build_flavor::COMPILED, build_flavor::STABLE_VERSION_LINE, build_flavor::VERSION)); + return std::process::ExitCode::SUCCESS; } + // A Nightly start never takes the Stable control channel, even from the environment. + let control_port = command.control_port.or_else(|| { + if launch.nightly { None } else { control_port_from("DESIGNCRAFT_CONTROL_PORT", std::env::var("DESIGNCRAFT_CONTROL_PORT").ok()) } + }); + let AppCommand { sample, files, skip, .. } = command; // A portable.txt whose DesignCraftData folder cannot be written: the platform folders are used // instead (see `profile`), and the user is told, in the log and in the status bar. let portable_note = profile::unwritable_portable_dir().map(|dir| { @@ -300,14 +468,14 @@ fn main() -> std::process::ExitCode { // leaves no file behind. Records logged until now are written to it first. if let (Some(logger), Some(dir)) = (logger, profile::config_dir()) { match logger.attach_dir(&dir.join("logs")) { - Ok(path) => log::info!("DesignCraft {}, log file {}", env!("CARGO_PKG_VERSION"), path.display()), + Ok(path) => log::info!("{} {}, log file {}", designcraft_ui_egui::channel::name(), build_flavor::VERSION, path.display()), // Standard error only by now (`attach_dir` gave up on the file); unlike `eprintln!`, never panics. Err(e) => log::warn!("no log file: {e}"), } } let mut options = eframe::NativeOptions { viewport: egui::ViewportBuilder::default() - .with_title("DesignCraft") + .with_title(designcraft_ui_egui::channel::name()) .with_inner_size([1440.0, 900.0]) .with_min_inner_size([900.0, 560.0]) .with_decorations(!cfg!(target_os = "windows")) @@ -320,7 +488,7 @@ fn main() -> std::process::ExitCode { system_font_fallback: false, ..Default::default() }; - options.viewport = options.viewport.with_app_id(APP_ID); + options.viewport = options.viewport.with_app_id(designcraft_ui_egui::channel::current().app_id()); if let Some(icon) = app_icon() { options.viewport = options.viewport.with_icon(icon); } @@ -385,10 +553,19 @@ fn main() -> std::process::ExitCode { #[cfg(target_os = "macos")] let events = &apple_events; let created = startup.clone(); + // What the app creator needs, copied out of `launch` so the closure does not borrow it. + let nightly = launch.nightly; + let session_unavailable = launch.session_unavailable; + let app_session = launch.session.clone(); + // The same record, for a start that created no window (the creator closure owns the Arc). + let exit_session = launch.session.clone(); + // Whether the previous Nightly session's notice reaches a window: always when one is shown, + // and the same answer for the exit paths below. + let unclean_notice_shown = launch.unclean; // A panic that ends the window (egui-wgpu's own) is caught here: never a crash. let run = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { eframe::run_native( - "DesignCraft", + designcraft_ui_egui::channel::name(), options, Box::new(move |cc| { let mut restarted = None; @@ -429,7 +606,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()); - app.set_startup_update_check(true); + if nightly { + // Installed and updated by the Launcher: never check the stable feed from here. + app.set_updates_managed(Some("ArtCraft Launcher")); + } else { + app.set_startup_update_check(true); + } if let Some(line) = restarted.or_else(|| created.status_line()) { app.status(line); } @@ -442,6 +624,13 @@ fn main() -> std::process::ExitCode { if let Some(note) = portable_note { app.status(note); } + // Last, so the interruption is the line the user reads. Showing it is also what + // lets this session clear the record instead of passing it on. + if unclean_notice_shown { + app.status("DesignCraft Nightly did not close cleanly last time. Recovered documents are listed below."); + } 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 @@ -472,6 +661,8 @@ fn main() -> std::process::ExitCode { movable: None, frames: 0, log_errors_after_startup: device, + session: app_session, + unclean_notice_shown, })) }), ) @@ -482,6 +673,9 @@ fn main() -> std::process::ExitCode { // Documents that arrived after the last frame, for a start again to open too. #[cfg(target_os = "macos")] startup.opening(apple_events.queued()); + // Normally `on_exit` already finished it; a graphics failure or a start without a window + // reaches this path instead, and the second call does nothing. + nightly_session::finish_once(&exit_session, unclean_notice_shown); match gpu::finish(run, &startup) { Ok(()) => std::process::ExitCode::SUCCESS, Err(e) => { @@ -509,6 +703,34 @@ mod tests { assert!(!super::KEEP_UI_PREFS.load(std::sync::atomic::Ordering::Relaxed), "ui.json can be saved once a copy is kept"); } + #[test] + fn the_launcher_separator_is_never_a_file_and_never_hides_a_named_document() { + let nightly = super::app_command(["--", "--version", "a.dc", "--control", "7979", "--sample"].map(std::ffi::OsString::from), true); + assert_eq!(nightly.files, ["--version", "a.dc", "--control", "7979", "--sample"]); + assert!(!nightly.version, "a flag after the separator is a document"); + assert_eq!(nightly.control_port, None); + assert!(!nightly.sample); + } + + #[test] + fn a_graphics_restart_after_the_separator_keeps_its_skip_list() { + 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"]); + } + + #[test] + fn stable_keeps_its_options_and_drops_a_user_separator() { + let stable = super::app_command(["--control", "7979", "--sample", "--", "--version"].map(std::ffi::OsString::from), false); + assert_eq!(stable.control_port, Some(7979)); + assert!(stable.sample); + assert_eq!(stable.files, ["--version"]); + assert!(!stable.version, "a flag after the separator is a document"); + let version = super::app_command([std::ffi::OsString::from("--version")], false); + assert!(version.version); + assert!(version.files.is_empty()); + } + #[test] fn control_port_values_that_are_not_ports_are_ignored() { assert_eq!(super::control_port_from("--control", Some("7979".into())), Some(7979)); @@ -684,3 +906,17 @@ mod exit_recovery_tests { } } } + +#[cfg(test)] +mod refusal_dialog_tests { + use super::refusal_dialog; + use crate::build_flavor::BuildFlavor; + + #[test] + fn a_refusal_never_blocks_on_a_modal_before_the_event_loop_on_macos() { + assert!(refusal_dialog(BuildFlavor::NightlyV1, true, false), "a desktop refusal still shows the box where one renders"); + assert!(!refusal_dialog(BuildFlavor::NightlyV1, true, true), "macOS has no run loop yet: the modal would hang"); + assert!(!refusal_dialog(BuildFlavor::NightlyV1, false, false), "a headless session has no box"); + assert!(!refusal_dialog(BuildFlavor::Stable, true, false), "only a nightly refusal explains itself in a box"); + } +} diff --git a/apps/designcraft/src/nightly_session.rs b/apps/designcraft/src/nightly_session.rs new file mode 100644 index 000000000..4a40b7ace --- /dev/null +++ b/apps/designcraft/src/nightly_session.rs @@ -0,0 +1,285 @@ +//! App-private Nightly session health, not telemetry or a Launcher protocol. +//! A live owner holds a separate persistent lease; secondary launches never rewrite its record. +//! Dropping the guard does not clear the marker. Only the app's controlled return path does. + +use std::fs::{File, OpenOptions}; +use std::io::{self, Read, Write as _}; +use std::path::{Path, PathBuf}; +use std::sync::{Arc, Mutex, PoisonError}; + +const RECORD: &str = "nightly-session.json"; +const LEASE: &str = "nightly-session.lock"; +const TEMPORARY: &str = "nightly-session.json.staging"; +const MAX_METADATA_BYTES: usize = 256; + +pub struct Session { + _lease: File, + path: PathBuf, + own_record: Vec, + previous_unclean: bool, +} + +fn regular_or_missing(path: &Path) -> io::Result { + match std::fs::symlink_metadata(path) { + Ok(metadata) if metadata.file_type().is_file() && !metadata.file_type().is_symlink() => Ok(true), + Ok(_) => Err(io::Error::other("Nightly session state must be a regular file, not an alias or directory")), + Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(false), + Err(error) => Err(error), + } +} + +/// Stage beside the destination and rename over it: a raced link at the record name is replaced, +/// never followed, and a reader sees either the old record or the whole new one. +fn write_record(root: &Path, name: &str, bytes: &[u8]) -> io::Result<()> { + let staging = root.join(format!("{TEMPORARY}.{}", std::process::id())); + let _ = std::fs::remove_file(&staging); + let mut file = OpenOptions::new().write(true).create_new(true).open(&staging)?; + let written = file.write_all(bytes).and_then(|()| file.sync_all()); + drop(file); + match written.and_then(|()| std::fs::rename(&staging, root.join(name))) { + Ok(()) => Ok(()), + Err(error) => { + let _ = std::fs::remove_file(&staging); + Err(error) + } + } +} + +/// The owner's session, shared by the window's exit path and the code after the event loop. +/// On macOS a quit ends the process inside AppKit's terminate, after eframe's `on_exit` and before +/// `eframe::run_native` could return, so `on_exit` finishes it there; the return path still runs +/// for a start that created no window. +pub type Shared = Arc>>; + +pub fn shared() -> Shared { + shared_with(None) +} + +pub fn shared_with(session: Option) -> Shared { + Arc::new(Mutex::new(session)) +} + +/// The controlled return ([`Session::finish`]) by whichever path comes first; later calls do nothing. +pub fn finish_once(shared: &Shared, unclean_notice_shown: bool) { + let watch = shared.lock().unwrap_or_else(PoisonError::into_inner).take(); + if let Some(watch) = watch + && let Err(error) = watch.finish(unclean_notice_shown) + { + log::warn!("Nightly session state was left intact: {error}"); + } +} + +impl Session { + /// The warning belongs to this window: a busy secondary has no health-record coverage, + /// while Stable and a lease-owning Nightly window preserve their existing result. + pub fn begin_with_health(root: Option<&Path>, version: &str, commit: Option<&str>) -> io::Result<(Option, bool)> { + let watch = Self::begin(root, version, commit)?; + let unavailable = root.is_some() && watch.is_none(); + Ok((watch, unavailable)) + } + + /// `None` is stable or another owner of this profile. Neither case touches the record. + /// The supplied root must already be the validated private Nightly profile. + pub fn begin(root: Option<&Path>, version: &str, commit: Option<&str>) -> io::Result> { + let Some(root) = root else { return Ok(None) }; + if version.is_empty() || version.len() > MAX_METADATA_BYTES || commit.is_some_and(|value| value.len() > MAX_METADATA_BYTES) { + return Err(io::Error::new(io::ErrorKind::InvalidInput, "Nightly session provenance is missing or too large")); + } + let lease_path = root.join(LEASE); + regular_or_missing(&lease_path)?; + let lease = OpenOptions::new().read(true).write(true).create(true).truncate(false).open(lease_path)?; + match lease.try_lock() { + Ok(()) => {} + Err(std::fs::TryLockError::WouldBlock) => return Ok(None), + Err(std::fs::TryLockError::Error(error)) => return Err(error), + } + let path = root.join(RECORD); + let previous_unclean = regular_or_missing(&path)?; + let own_record = serde_json::to_vec(&serde_json::json!({ + "schema_version": 1, + "channel": "nightly-v1", + "version": version, + "commit": commit.filter(|value| !value.is_empty()), + }))?; + write_record(root, RECORD, &own_record)?; + Ok(Some(Self { _lease: lease, path, own_record, previous_unclean })) + } + + pub fn previous_unclean(&self) -> bool { + self.previous_unclean + } + + /// Controlled return. If an earlier session's interruption was detected but no window showed + /// it yet (a graphics failure before the app callback), the record is left for the next owner + /// to report; otherwise this is [`Self::complete`]. + pub fn finish(self, unclean_notice_shown: bool) -> io::Result<()> { + if self.previous_unclean && !unclean_notice_shown { + return Ok(()); + } + self.complete() + } + + /// Controlled event-loop completion includes a handled start-up error, not only exit 0. + /// An unwind, abort, forced exit or killed process never calls this method. + pub fn complete(self) -> io::Result<()> { + if !regular_or_missing(&self.path)? { + return Ok(()); + } + let mut current = Vec::new(); + File::open(&self.path)?.take(self.own_record.len() as u64 + 1).read_to_end(&mut current)?; + if current != self.own_record { + return Err(io::Error::other("Nightly session state changed; leaving it intact")); + } + std::fs::remove_file(&self.path) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::atomic::{AtomicU64, Ordering}; + + struct Fixture(PathBuf); + impl Fixture { + fn new() -> Self { + static NEXT: AtomicU64 = AtomicU64::new(0); + loop { + let path = + std::env::temp_dir().join(format!("designcraft-nightly-session-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed))); + match std::fs::create_dir(&path) { + Ok(()) => return Self(path), + Err(error) if error.kind() == io::ErrorKind::AlreadyExists => continue, + Err(error) => panic!("cannot create owned fixture: {error}"), + } + } + } + } + impl Drop for Fixture { + fn drop(&mut self) { + std::fs::remove_dir_all(&self.0).unwrap(); + } + } + + #[test] + fn busy_secondary_reports_unavailable_without_replacing_the_owner_record() { + let fixture = Fixture::new(); + let (stable, warning) = Session::begin_with_health(None, "stable", None).unwrap(); + assert!(stable.is_none() && !warning); + let (first, warning) = Session::begin_with_health(Some(&fixture.0), "nightly", Some("owned-commit")).unwrap(); + assert!(!warning); + let first = first.unwrap(); + let record = std::fs::read(fixture.0.join(RECORD)).unwrap(); + let (secondary, warning) = Session::begin_with_health(Some(&fixture.0), "secondary", None).unwrap(); + assert!(secondary.is_none() && warning, "a secondary window cannot claim recorded exit/crash coverage"); + assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), record); + first.complete().unwrap(); + assert!(!fixture.0.join(RECORD).exists()); + } + + #[test] + fn controlled_completion_is_clean_but_an_unfinished_owner_is_reported_next_time() { + let fixture = Fixture::new(); + let first = Session::begin(Some(&fixture.0), "first", Some("recorded-commit")).unwrap().unwrap(); + assert!(!first.previous_unclean()); + let own = std::fs::read(fixture.0.join(RECORD)).unwrap(); + assert!(Session::begin(Some(&fixture.0), "secondary", None).unwrap().is_none()); + assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), own, "a busy secondary must not replace the owner's record"); + first.complete().unwrap(); + assert!(!fixture.0.join(RECORD).exists()); + let unfinished = Session::begin(Some(&fixture.0), "second", None).unwrap().unwrap(); + assert!(!unfinished.previous_unclean()); + drop(unfinished); // Unwind/abnormal-path ownership release, not a controlled completion. + let next = Session::begin(Some(&fixture.0), "third", None).unwrap().unwrap(); + assert!(next.previous_unclean()); + next.complete().unwrap(); + assert!(!fixture.0.join(RECORD).exists()); + } + + #[test] + fn an_interruption_no_window_showed_survives_a_handled_startup_failure() { + let fixture = Fixture::new(); + drop(Session::begin(Some(&fixture.0), "crashed", None).unwrap().unwrap()); + let failed = Session::begin(Some(&fixture.0), "gpu-failed", None).unwrap().unwrap(); + assert!(failed.previous_unclean()); + failed.finish(false).unwrap(); + let retry = Session::begin(Some(&fixture.0), "gpu-retry", None).unwrap().unwrap(); + assert!(retry.previous_unclean()); + retry.finish(true).unwrap(); + assert!(!fixture.0.join(RECORD).exists(), "a session that showed the notice clears its record"); + let clean = Session::begin(Some(&fixture.0), "clean", None).unwrap().unwrap(); + assert!(!clean.previous_unclean()); + clean.finish(false).unwrap(); + assert!(!fixture.0.join(RECORD).exists()); + } + + #[test] + fn the_exit_path_and_the_return_path_finish_the_session_once() { + let fixture = Fixture::new(); + let shared = shared(); + *shared.lock().unwrap() = Session::begin(Some(&fixture.0), "quitting", None).unwrap(); + finish_once(&shared, false); + assert!(!fixture.0.join(RECORD).exists(), "a quit that ran the exit path is a clean exit"); + let successor = Session::begin(Some(&fixture.0), "successor", None).unwrap().unwrap(); + assert!(!successor.previous_unclean()); + let record = std::fs::read(fixture.0.join(RECORD)).unwrap(); + finish_once(&shared, false); + assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), record, "the second finish must not touch a successor's record"); + successor.complete().unwrap(); + } + + #[test] + fn cleanup_never_removes_an_unknown_changed_record() { + let fixture = Fixture::new(); + let watch = Session::begin(Some(&fixture.0), "nightly", None).unwrap().unwrap(); + std::fs::write(fixture.0.join(RECORD), b"replacement owned by someone else").unwrap(); + assert!(watch.complete().is_err()); + assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), b"replacement owned by someone else"); + } + + #[test] + fn provenance_is_bounded_and_never_collects_documents_paths_or_diagnostics() { + let fixture = Fixture::new(); + assert!(Session::begin(Some(&fixture.0), &"x".repeat(MAX_METADATA_BYTES + 1), None).is_err()); + assert_eq!(std::fs::read_dir(&fixture.0).unwrap().count(), 0); + assert!(Session::begin(None, "", None).unwrap().is_none(), "stable has no session-health side effects"); + let watch = Session::begin(Some(&fixture.0), "nightly", None).unwrap().unwrap(); + let data: serde_json::Value = serde_json::from_slice(&std::fs::read(fixture.0.join(RECORD)).unwrap()).unwrap(); + let fields = data.as_object().unwrap().keys().map(String::as_str).collect::>(); + assert_eq!(fields, ["schema_version", "channel", "version", "commit"].into_iter().collect()); + assert!(data["commit"].is_null(), "missing provenance must not be invented"); + watch.complete().unwrap(); + assert_eq!(std::fs::read_dir(&fixture.0).unwrap().count(), 1, "only the lease remains"); + } + + #[test] + #[cfg(unix)] + fn reserved_state_aliases_do_not_modify_external_files() { + let fixture = Fixture::new(); + let external = fixture.0.join("stable-document"); + std::fs::write(&external, b"stable bytes").unwrap(); + for name in [LEASE, RECORD] { + let alias = fixture.0.join(name); + std::os::unix::fs::symlink(&external, &alias).unwrap(); + assert!(Session::begin(Some(&fixture.0), "nightly", None).is_err()); + assert_eq!(std::fs::read(&external).unwrap(), b"stable bytes"); + std::fs::remove_file(alias).unwrap(); + } + } + + #[test] + #[cfg(unix)] + fn a_raced_record_link_is_replaced_rather_than_followed() { + let fixture = Fixture::new(); + let external = fixture.0.join("stable-document"); + std::fs::write(&external, b"stable bytes").unwrap(); + // The record is absent when the owner begins, so the write path cannot refuse it; the + // rename over a link that appears afterwards must not follow it. + write_record(&fixture.0, RECORD, b"{}").unwrap(); + std::fs::remove_file(fixture.0.join(RECORD)).unwrap(); + std::os::unix::fs::symlink(&external, fixture.0.join(RECORD)).unwrap(); + write_record(&fixture.0, RECORD, b"nightly record").unwrap(); + assert_eq!(std::fs::read(&external).unwrap(), b"stable bytes"); + assert!(!std::fs::symlink_metadata(fixture.0.join(RECORD)).unwrap().file_type().is_symlink()); + assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), b"nightly record"); + } +} diff --git a/apps/designcraft/src/process_identity.rs b/apps/designcraft/src/process_identity.rs new file mode 100644 index 000000000..c74d63490 --- /dev/null +++ b/apps/designcraft/src/process_identity.rs @@ -0,0 +1,71 @@ +//! Set the immutable nightly Windows identity before any native window or COM service. +//! Stable deliberately leaves its implicit shortcut/path identity unchanged. + +use std::sync::OnceLock; + +#[derive(Clone, Debug, thiserror::Error)] +pub enum IdentityError { + #[error("{0}")] + Configuration(String), +} + +pub fn initialize(nightly: bool, app_id: &str) -> Result<(), IdentityError> { + configure(nightly && cfg!(windows), app_id, |id| { + static RESULT: OnceLock> = OnceLock::new(); + RESULT + .get_or_init(|| { + #[cfg(windows)] + { + winsafe::SetCurrentProcessExplicitAppUserModelID(id) + .map_err(|error| format!("cannot set the nightly Windows identity: {error}"))?; + let actual = winsafe::GetCurrentProcessExplicitAppUserModelID() + .map_err(|error| format!("cannot read back the nightly Windows identity: {error}"))?; + if actual != id { + return Err("the native Windows identity did not match the selected nightly channel".into()); + } + Ok(()) + } + #[cfg(not(windows))] + { + let _ = id; + Ok(()) + } + }) + .clone() + }) + .map_err(IdentityError::Configuration) +} + +fn configure(explicit_nightly: bool, app_id: &str, set: impl FnOnce(&str) -> Result<(), String>) -> Result<(), String> { + if explicit_nightly { set(app_id) } else { Ok(()) } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn stable_does_not_call_the_explicit_identity_api() { + configure(false, "nightly-id", |_| panic!("stable identity must remain implicit")).unwrap(); + } + + #[test] + fn nightly_applies_the_supplied_identity_once() { + let calls = std::cell::Cell::new(0); + configure(true, "nightly-id", |id| { + assert_eq!(id, "nightly-id"); + calls.set(calls.get() + 1); + Ok(()) + }) + .unwrap(); + assert_eq!(calls.get(), 1); + } + + #[test] + fn native_identity_failure_is_returned_instead_of_starting_a_window() { + let started = std::cell::Cell::new(false); + let result = configure(true, "nightly-id", |_| Err("native identity refused".into())).map(|()| started.set(true)); + assert_eq!(result.unwrap_err(), "native identity refused"); + assert!(!started.get()); + } +} diff --git a/apps/designcraft/src/profile.rs b/apps/designcraft/src/profile.rs index 1450e5077..0daa79665 100644 --- a/apps/designcraft/src/profile.rs +++ b/apps/designcraft/src/profile.rs @@ -5,13 +5,29 @@ 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. -const PORTABLE_MARKER: &str = "portable.txt"; -const PORTABLE_DATA_DIR: &str = "DesignCraftData"; +pub(crate) const PORTABLE_MARKER: &str = "portable.txt"; +pub(crate) 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). pub fn config_dir() -> Option { + if let Some(root) = crate::launch_profile::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<()> { + 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); + let _ = std::fs::remove_file(&probe); + result +} + fn config_dir_with(os: &str, env: impl Fn(&str) -> Option, exe_dir: Option<&Path>) -> Option { if let Some(root) = root_with(&env, exe_dir) { // An explicitly empty override must not fall back to the user's profile. @@ -50,13 +66,7 @@ fn marked_data_dir(exe_dir: &Path) -> Option { /// Whether `dir` exists, or can be created, and takes a new file: read-only attributes and /// permissions are only known by trying. fn writable(dir: &Path) -> bool { - if std::fs::create_dir_all(dir).is_err() { - return false; - } - let probe = dir.join(format!(".write-test-{}", std::process::id())); - let ok = std::fs::write(&probe, b"").is_ok(); - let _ = std::fs::remove_file(&probe); - ok + ensure_writable(dir).is_ok() } /// The data folder of a portable install that could not be used because it is not writable, for @@ -85,6 +95,10 @@ fn executable_dir() -> Option { } pub fn recovery_dir() -> Option { + if let Some(root) = crate::launch_profile::current().root() { + // Recovery stays inside the profile, including the per-run folder's lock. + return own_run(root.join("Recovery")); + } recovery_dir_with(root_with(|key| std::env::var_os(key), executable_dir().as_deref()), designcraft_engine::recovery::default_dir) .and_then(own_run) } diff --git a/apps/designcraft/src/profile_root.rs b/apps/designcraft/src/profile_root.rs new file mode 100644 index 000000000..1522d0070 --- /dev/null +++ b/apps/designcraft/src/profile_root.rs @@ -0,0 +1,492 @@ +//! 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/assets/app-icon/README.md b/assets/app-icon/README.md index a1086577a..863662f73 100644 --- a/assets/app-icon/README.md +++ b/assets/app-icon/README.md @@ -46,3 +46,14 @@ The app ID is `ai.storyteller.designcraft`. It's used for the hicolor icon names Edit `designcraft.svg` (or `designcraft-small.svg`), then run `packaging/icons.sh`. It needs `resvg`, and `iconutil` for the `.icns` (macOS only). It packs the `.ico` with `cargo xtask ico`. + +## Nightly channel + +`designcraft-nightly.png`, `-1024.png`, `.ico` and `.icns` are the Launcher Nightly's icons. They keep +the artwork, alpha and Mac padding unchanged and change only the background field, from the app +green `#7bb51c` to the deeper `#26400f`; there is no letter badge or crescent, and the app and the +Launcher identify the channel in text. The 1024 master is derived from the native 1024 tile onto +Apple's 824/1024 grid, never upscaled from 256. Hashes, the palette-fit method and the container +members are in [`nightly-provenance.json`](nightly-provenance.json); the stable files are not +recoloured. `build.rs` embeds `designcraft-nightly.ico` into a nightly `designcraft.exe`, and the +nightly bundle uses `designcraft-nightly.icns`. diff --git a/assets/app-icon/designcraft-nightly-1024.png b/assets/app-icon/designcraft-nightly-1024.png new file mode 100644 index 000000000..dcdb7d0c7 Binary files /dev/null and b/assets/app-icon/designcraft-nightly-1024.png differ diff --git a/assets/app-icon/designcraft-nightly.icns b/assets/app-icon/designcraft-nightly.icns new file mode 100644 index 000000000..4c2d9ce19 Binary files /dev/null and b/assets/app-icon/designcraft-nightly.icns differ diff --git a/assets/app-icon/designcraft-nightly.ico b/assets/app-icon/designcraft-nightly.ico new file mode 100644 index 000000000..4254fe811 Binary files /dev/null and b/assets/app-icon/designcraft-nightly.ico differ diff --git a/assets/app-icon/designcraft-nightly.png b/assets/app-icon/designcraft-nightly.png new file mode 100644 index 000000000..279fc86fc Binary files /dev/null and b/assets/app-icon/designcraft-nightly.png differ diff --git a/assets/app-icon/nightly-provenance.json b/assets/app-icon/nightly-provenance.json new file mode 100644 index 000000000..aa0748190 --- /dev/null +++ b/assets/app-icon/nightly-provenance.json @@ -0,0 +1,60 @@ +{ + "title": "DesignCraft nightly deep-background icons", + "author": "@nightlty-designcraft (generated for the nightlies lead)", + "license": "MIT OR Apache-2.0", + "source_commit": null, + "inputs": [ + { + "path": "assets/app-icon/hicolor/256x256/apps/ai.storyteller.designcraft.png", + "sha256": "b8407dae4f43d6f0503ec6c1df619cca34b358d8bb230c6b0d18c992aa5a7f61", + "purpose": "Windows/Linux native256 master" + }, + { + "path": "assets/app-icon/designcraft-1024.png", + "sha256": "5cf554e4ac5b9b02a5e3ef7f9491c421ac7cbdf902eb93834586eaacd3d0feca", + "purpose": "native 1024 master, padded onto Apple's 824/1024 grid for the Mac" + } + ], + "method": { + "kind": "code-generated derivative of the project-owned icon", + "original_palette": { + "ink": "#0b0b0c", + "paper": "#efe9dc", + "background": "#7bb51c" + }, + "nightly_background": "#26400f", + "transform": "Fit each pixel's ink/paper/background weights in the existing three-colour palette and rebuild it with the deeper field, keeping alpha and every foreground/detail pixel; derive the Mac 1024 master from the native 1024 tile on Apple's 824/1024 grid (not an upscale from 256) and pack native-size PNG frames into ICO/ICNS. No badge, crescent or letter.", + "generator_sha256": "a96dc21e32e581284f9b9cfc4fdf2b47cef2a06a2a8d3184274866f376131399" + }, + "outputs": { + "assets/app-icon/designcraft-nightly.png": "01a05015cda1ddf5117ab8e02b6e3cf6cf3106e90e41c91164b7245ad9d22c97", + "assets/app-icon/designcraft-nightly-1024.png": "91647d2cc680df2d416fc0fdb33afbaddc02b09090bdef80c466e58807c3ec17", + "assets/app-icon/designcraft-nightly.ico": "d100e87c2a98b4a981ddd927454fdef3bca962f490b347a13d5841fa30224d51", + "assets/app-icon/designcraft-nightly.icns": "189e20cd7db4014dd807b354abc5da57d894385dd190a630bd0932b626ffe8f2" + }, + "ico_frame_sizes": [ + 16, + 20, + 24, + 32, + 40, + 48, + 64, + 128, + 256 + ], + "icns_png_slots": { + "icp4": 16, + "icp5": 32, + "ic11": 32, + "icp6": 64, + "ic12": 64, + "ic07": 128, + "ic08": 256, + "ic13": 256, + "ic09": 512, + "ic14": 512, + "ic10": 1024 + }, + "validation": "Input/output hashes recorded; PNG dimensions and container members checked; the tiles were compared visually against the stable icon (same artwork, deeper field, Mac padding intact). Native Explorer/Finder/iconutil/app-package qualification remains unrun." +} diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 8187594ab..e88c83355 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -243,6 +243,8 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(datamerge::specs()); v.extend(interactive::specs()); v.extend(preflight::specs()); + #[cfg(test)] + v.extend(test_support::specs()); v }) } @@ -396,3 +398,29 @@ pub use layout::chapter_numbering; pub use paste_image::{IMAGE_EXTENSIONS, MAX_PASTED_PIXELS, PASTED_IMAGE_NAME, check_pasted_base64, check_pasted_size, pasted_pixels, pasted_png}; pub use paste_svg::is_svg_markup; pub(crate) use place_text::autoflow as place_text_autoflow; + +/// Test-only commands: scaffolding the engine's own tests need, never in a shipped build or in another +/// crate's tests (this module is `#[cfg(test)]`, and `cfg(test)` is not set for a dependency build). +#[cfg(test)] +mod test_support { + use serde_json::json; + + use super::*; + + /// A command that changes the document and then fails, which no shipping command does any more: + /// the engine checks what a failed command leaves behind (one undo step with its own label). + pub(super) fn specs() -> Vec { + vec![cmd!( + "test.nestedFailure", + "Nested Failure", + [], + None, + "{ids} — turns the frames into text frames, then fails", + has_selection, + |s, p| { + s.execute("object.content", &with_param(p, "type", json!("text")))?; + Err(bad("test.nestedFailure", "it fails after the command it ran")) + } + )] + } +} diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 9b2ac1a1c..451a69143 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -451,11 +451,15 @@ pub fn specs() -> Vec { } copy_items(s)?; // The whole objects are on the clipboard, so the whole objects go, not just selected points. - if p.get("ids").is_none() { + let result = if p.get("ids").is_none() { let ids: Vec = s.doc()?.selection.items.iter().map(|i| i.0).collect(); - return s.execute("edit.clear", &json!({"ids": ids})); - } - s.execute("edit.clear", p) + s.execute("edit.clear", &json!({"ids": ids})) + } else { + s.execute("edit.clear", p) + }?; + // Only a successful object Cut replaces the earlier formatted text copy. + s.text_clipboard = None; + Ok(result) }), cmd!( "edit.pasteWithoutFormatting", @@ -669,6 +673,8 @@ fn graphic_alone(frame: &designcraft_doc::Item, g: &designcraft_doc::Graphic, pa it } +#[cfg(test)] +mod object_cut_clipboard_tests; #[cfg(test)] mod text_clipboard_tests; diff --git a/crates/engine/src/cmd/edit/object_cut_clipboard_tests.rs b/crates/engine/src/cmd/edit/object_cut_clipboard_tests.rs new file mode 100644 index 000000000..4f519f087 --- /dev/null +++ b/crates/engine/src/cmd/edit/object_cut_clipboard_tests.rs @@ -0,0 +1,91 @@ +use designcraft_doc::{ItemId, OBJECT_MARK, StoryId}; +use serde_json::json; + +use crate::Session; + +fn text_frame(s: &mut Session, text: &str) -> StoryId { + let r = s.execute("frame.create", &json!({"rect": [36, 36, 236, 136], "content": "text", "text": text})).unwrap(); + StoryId(r["story"].as_u64().unwrap()) +} + +fn copy_formatted_text(s: &mut Session) -> StoryId { + let source = text_frame(s, "old text"); + let len = s.doc().unwrap().doc.story(source).unwrap().len(); + s.execute("text.select", &json!({"story": source.0, "anchor": 0, "focus": len})).unwrap(); + s.execute("type.bold", &json!({})).unwrap(); + s.execute("edit.copy", &json!({})).unwrap(); + source +} + +#[test] +fn object_cut_replaces_old_text_copy_at_a_body_caret_and_survives_undo_redo() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let source = copy_formatted_text(&mut s); + let target = text_frame(&mut s, "target"); + let cut = s.execute("frame.create", &json!({"rect": [36, 200, 86, 260]})).unwrap()["id"].as_u64().unwrap(); + s.execute("selection.set", &json!({"ids": [cut]})).unwrap(); + let before_cut = s.doc().unwrap().doc.clone(); + let original = before_cut.item(ItemId(cut)).unwrap(); + let bounds = original.bounds(); + s.execute("edit.cut", &json!({})).unwrap(); + let after_cut = s.doc().unwrap().doc.clone(); + assert!(after_cut.item(ItemId(cut)).is_none()); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc, before_cut); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc, after_cut); + + s.execute("text.select", &json!({"story": target.0, "anchor": 0, "focus": 0})).unwrap(); + // Native Paste removes its unchanged U+FFFC clipboard marker before engine execution. + s.execute("edit.paste", &json!({})).unwrap(); + let after_paste = s.doc().unwrap().doc.clone(); + let list = s.execute("anchored.list", &json!({"story": target.0})).unwrap(); + let anchors = list.as_array().unwrap(); + assert_eq!(anchors.len(), 1, "Cut must paste the shape, not the earlier text copy"); + let pos = anchors[0]["pos"].as_u64().unwrap() as usize; + let body = after_paste.story(target).unwrap(); + let anchored = body.object_at(pos).unwrap(); + assert_eq!(body.text, format!("{OBJECT_MARK}{}", after_cut.story(target).unwrap().text)); + assert!((anchored.size().0 - bounds.width()).abs() < 1e-6); + assert!((anchored.size().1 - bounds.height()).abs() < 1e-6); + assert_eq!(anchored.item.path, original.path); + assert_eq!(anchored.item.content, original.content); + assert_ne!(anchored.item.id, original.id, "Paste allocates a fresh anchored identity"); + assert_eq!(after_paste.story(source), before_cut.story(source)); + after_paste.check().unwrap(); + + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc, after_cut); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc, after_paste); +} + +#[test] +fn rejected_object_cut_keeps_the_previous_formatted_text_copy_and_redo() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let source = copy_formatted_text(&mut s); + let target = text_frame(&mut s, "target"); + s.execute("frame.create", &json!({"rect": [36, 200, 86, 260]})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.deselectAll", &json!({})).unwrap(); + let before = s.doc().unwrap().doc.clone(); + let selection = s.doc().unwrap().selection.clone(); + let history = s.execute("document.history", &json!({})).unwrap(); + assert!(!history["redo"].as_array().unwrap().is_empty()); + assert!(s.execute("edit.cut", &json!({})).is_err()); + assert_eq!(s.doc().unwrap().doc, before); + assert_eq!(s.doc().unwrap().selection, selection); + assert_eq!(s.execute("document.history", &json!({})).unwrap(), history); + + s.execute("text.select", &json!({"story": target.0, "anchor": 0, "focus": 0})).unwrap(); + s.execute("edit.paste", &json!({})).unwrap(); + let d = &s.doc().unwrap().doc; + let copied = before.story(source).unwrap(); + let pasted = d.story(target).unwrap(); + assert_eq!(pasted.text, format!("{}{}", copied.text, before.story(target).unwrap().text)); + assert_eq!(pasted.char_format_at(1), copied.char_format_at(1)); + assert!(pasted.objects.is_empty()); + d.check().unwrap(); +} diff --git a/crates/engine/src/cmd/export/flatten.rs b/crates/engine/src/cmd/export/flatten.rs index 730f28b4a..a112beb53 100644 --- a/crates/engine/src/cmd/export/flatten.rs +++ b/crates/engine/src/cmd/export/flatten.rs @@ -58,10 +58,16 @@ pub(super) fn flatten(d: &designcraft_doc::Document, cache: &designcraft_compose if whole { // Parent items involve transparency: every page of the spread as one image. let first = d.first_page_of_spread(si); - let lid = out.default_layer(); + // The page image must survive the PDF layer filter. Layers are listed top first, so + // this is the default (top) layer when it prints, else the top-most printing one. + // The spread's own items and parent items are all removed below, so the layer's + // stacking order can't change what composites. If nothing can print, leave the + // spread alone: the normal export pipeline already emits an empty page. + let Some(lid) = out.layers.iter().find(|layer| designcraft_pdf::layer_exported(layer)).map(|layer| layer.id) else { continue }; + let opts = designcraft_render::RenderOptions { printing_only: true, ..Default::default() }; let mut images = Vec::new(); for (pi, pg) in sp.pages.iter().enumerate() { - if let Some(img) = rr.render_page(d, cache, first + pi, k, false, &Default::default()) { + if let Some(img) = rr.render_page(d, cache, first + pi, k, false, &opts) { images.push((pg.bounds(), img)); } } diff --git a/crates/engine/src/cmd/export/formats.rs b/crates/engine/src/cmd/export/formats.rs index 2f9d9f88e..8828f006c 100644 --- a/crates/engine/src/cmd/export/formats.rs +++ b/crates/engine/src/cmd/export/formats.rs @@ -152,7 +152,7 @@ pub(super) fn has_story_target(s: &Session) -> std::result::Result<(), String> { pub(super) fn export_text(s: &mut Session, p: &Value) -> Result { const ID: &str = "file.exportText"; - let sid = crate::cmd::text::story_of(s, p).ok_or_else(|| bad(ID, "edit text or select a text frame"))?; + let sid = crate::cmd::text::validated_story_of(s, p, ID)?.ok_or_else(|| bad(ID, "edit text or select a text frame"))?; let doc = &s.doc()?.doc; let story = doc.stories.get(&sid).ok_or_else(|| bad(ID, format!("no story {}", sid.0)))?; let path = str_param(p, "path"); diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index b55b7f5a2..5271e729d 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -35,3 +35,5 @@ thread_local! { #[cfg(test)] pub(crate) mod eps_place_tests; +#[cfg(test)] +mod save_format_tests; diff --git a/crates/engine/src/cmd/file/bytes.rs b/crates/engine/src/cmd/file/bytes.rs index 028937364..b1985dd7b 100644 --- a/crates/engine/src/cmd/file/bytes.rs +++ b/crates/engine/src/cmd/file/bytes.rs @@ -50,6 +50,9 @@ pub fn is_document(bytes: &[u8]) -> bool { /// How much of a file [`is_document`] needs to recognise a package by its `mimetype` entry. pub const DOCUMENT_SNIFF_BYTES: u64 = 64 << 10; +/// How a refused lossy IDML save's error starts (see [`bytes_for_path`]). +pub const LOSSY_IDML_SAVE: &str = "saving as IDML would lose content"; + /// The longer side of the first-page picture saved in the file, in pixels. pub(super) const PREVIEW_PX: f64 = 320.0; @@ -71,6 +74,38 @@ pub(super) fn to_bytes_with_preview(d: &Document, cache: &crate::Cache) -> Resul Ok(bytes) } +/// The bytes a save to `path` writes: an IDML package (images embedded) for a `.idml` name, else +/// DesignCraft's own format with its first-page picture (Preferences › File Handling › Save +/// documents as). An IDML save that would lose content IDML can't hold (editorial notes, +/// endnotes) is refused unless `allow_loss`: the save marks the document saved and drops its +/// recovery copy, so the loss would be silent and for good. Also → the warnings an IDML export +/// gives (images written as links past the embedded-image limit). +pub fn bytes_for_path(d: &Document, path: &str, cache: &crate::Cache, allow_loss: bool) -> Result<(Vec, Vec)> { + match crate::SaveFormat::of_path(path) { + crate::SaveFormat::Idml => { + let lost = designcraft_idml::unwritten(d); + if !allow_loss && !lost.is_empty() { + return Err(EngineError::Other(format!( + "{LOSSY_IDML_SAVE}: IDML can't keep {} editorial note(s) and {} endnote(s); pass allowLoss to save anyway", + lost.editorial_notes, lost.endnotes + ))); + } + crate::cmd::interchange::idml_bytes(d, &designcraft_idml::ExportOptions::default()) + } + crate::SaveFormat::Designcraft => Ok((to_bytes_with_preview(d, cache)?, Vec::new())), + } +} + +/// The path a save writes to: a `.idml` name as given (written as IDML, see [`bytes_for_path`]), +/// any other with the `.designcraft` extension added when it lacks it +/// ([`with_document_extension`]). +pub fn with_save_extension(path: &str) -> String { + match crate::SaveFormat::of_path(path) { + crate::SaveFormat::Idml => path.to_string(), + crate::SaveFormat::Designcraft => with_document_extension(path), + } +} + pub fn from_bytes(b: &[u8]) -> Result { load_bytes(b).map(|(d, _)| d) } diff --git a/crates/engine/src/cmd/file/registry.rs b/crates/engine/src/cmd/file/registry.rs index f59144fe6..8b0d833cd 100644 --- a/crates/engine/src/cmd/file/registry.rs +++ b/crates/engine/src/cmd/file/registry.rs @@ -48,9 +48,15 @@ pub fn specs() -> Vec { s.prefs.recent_files.clear(); ok() }), - cmd!(noundo "file.save", "Save", ["File"], Some("Cmd+S"), "{path?} — a `path` without the .designcraft extension gets it → {path: the file written, bytes}", has_doc, file_save), - cmd!(noundo "file.saveAs", "Save As…", ["File"], Some("Cmd+Shift+S"), "{path} — a path without the .designcraft extension gets it → {path: the file written, bytes}", has_doc, file_save), - cmd!(noundo "file.saveACopy", "Save a Copy…", ["File"], None, "{path, embedLinks?: copy every linked file in (fails when one is missing or changed)} — writes the document without changing which file it is or its unsaved state; a path without the .designcraft extension gets it → {path: the file written, bytes, warnings}", has_doc, file_save_a_copy), + cmd!(noundo "file.save", "Save", ["File"], Some("Cmd+S"), "{path?, allowLoss?} — a `.idml` path is written as IDML (images embedded; refused when IDML can't keep some of the document, see file.idmlLosses, unless allowLoss); any other `path` without the .designcraft extension gets it → {path: the file written, bytes, warnings}", has_doc, file_save), + cmd!(noundo "file.saveAs", "Save As…", ["File"], Some("Cmd+Shift+S"), "{path, allowLoss?} — a `.idml` path is written as IDML (images embedded; refused when IDML can't keep some of the document, see file.idmlLosses, unless allowLoss); any other path without the .designcraft extension gets it → {path: the file written, bytes, warnings}", has_doc, file_save), + cmd!(noundo "file.saveACopy", "Save a Copy…", ["File"], None, "{path, embedLinks?: copy every linked file in (fails when one is missing or changed), allowLoss?} — writes the document without changing which file it is or its unsaved state; a `.idml` path is written as IDML (refused when IDML can't keep some of the document, unless allowLoss), any other without the .designcraft extension gets it → {path: the file written, bytes, warnings}", has_doc, file_save_a_copy), + cmd!(query "file.idmlLosses", "IDML Losses", [], None, + "{} → {editorialNotes, endnotes}: what saving the document as IDML would lose (editorial notes aren't written; endnotes become plain text in the endnote frame). A `.idml` save refuses while any is non-zero, unless allowLoss", + has_doc, |s, _| { + let lost = designcraft_idml::unwritten(&s.doc()?.doc); + Ok(json!({"editorialNotes": lost.editorial_notes, "endnotes": lost.endnotes})) + }), cmd!(noundo "file.revert", "Revert", ["File"], None, "{} — back to the last saved version (not undoable)", can_revert, file_revert), cmd!(query "file.recovery.list", "Recovery Data", [], None, "{dir?} → [{uid, path, title, saved}] unsaved documents left by a crash (default: the session's recovery folder)", always, |s, p| { let dir = recovery_dir(s, p, FolderAccess::Read)?; diff --git a/crates/engine/src/cmd/file/save.rs b/crates/engine/src/cmd/file/save.rs index 7d5b1ba19..d70c5ce7a 100644 --- a/crates/engine/src/cmd/file/save.rs +++ b/crates/engine/src/cmd/file/save.rs @@ -2,7 +2,7 @@ use super::DocState; #[cfg(not(target_arch = "wasm32"))] use super::bytes::from_bytes; -use super::bytes::{to_bytes_with_preview, with_document_extension}; +use super::bytes::{bytes_for_path, with_save_extension}; #[cfg(not(target_arch = "wasm32"))] use super::open::load_document_fonts; #[cfg(test)] @@ -13,7 +13,7 @@ pub(super) fn file_save(s: &mut Session, p: &Value) -> Result { let st = s.doc_mut()?; // Saving to the document's own file keeps its name, even one opened without the extension. let path = str_param(p, "path") - .map(with_document_extension) + .map(with_save_extension) .or_else(|| st.path.clone()) .ok_or_else(|| bad("file.save", "missing `path` (document has never been saved)"))?; // Before anything about the document changes: a refused save leaves it as it was. @@ -32,8 +32,10 @@ pub(super) fn file_save(s: &mut Session, p: &Value) -> Result { let saved = proxied.unwrap_or(saved); let changed = links_changed || proxies_made || saved.data_merge != st.doc.data_merge; let saved = if changed { Arc::new(saved) } else { st.doc.clone() }; - let warnings = crate::cmd::native_links::web_save_warnings(&saved); - let bytes = to_bytes_with_preview(&saved, &s.cache)?; + let mut warnings = crate::cmd::native_links::web_save_warnings(&saved); + let allow_loss = p.get("allowLoss").and_then(Value::as_bool).unwrap_or(false); + let (bytes, written) = bytes_for_path(&saved, &path, &s.cache, allow_loss)?; + warnings.extend(written); #[cfg(not(target_arch = "wasm32"))] crate::io::write_file(&path, &bytes).map_err(EngineError::Other)?; let st = s.doc_mut()?; @@ -61,7 +63,7 @@ pub(super) fn file_save(s: &mut Session, p: &Value) -> Result { /// anywhere. pub(super) fn file_save_a_copy(s: &mut Session, p: &Value) -> Result { let path = str_param(p, "path").ok_or_else(|| bad("file.saveACopy", "missing `path`"))?; - let path = with_document_extension(path); + let path = with_save_extension(path); let embed = match p.get("embedLinks") { None | Some(Value::Null) => false, Some(v) => v.as_bool().ok_or_else(|| bad("file.saveACopy", "`embedLinks` must be true or false"))?, @@ -77,8 +79,10 @@ pub(super) fn file_save_a_copy(s: &mut Session, p: &Value) -> Result { if let Some(proxied) = crate::cmd::native_links::with_proxies(©, || false) { copy = proxied; } - let warnings = crate::cmd::native_links::web_save_warnings(©); - let bytes = to_bytes_with_preview(©, &s.cache)?; + let mut warnings = crate::cmd::native_links::web_save_warnings(©); + let allow_loss = p.get("allowLoss").and_then(Value::as_bool).unwrap_or(false); + let (bytes, written) = bytes_for_path(©, &path, &s.cache, allow_loss)?; + warnings.extend(written); #[cfg(not(target_arch = "wasm32"))] crate::io::write_file(&path, &bytes).map_err(EngineError::Other)?; Ok(json!({"path": path, "bytes": bytes.len(), "warnings": warnings})) diff --git a/crates/engine/src/cmd/file/save_format_tests.rs b/crates/engine/src/cmd/file/save_format_tests.rs new file mode 100644 index 000000000..2248d6cb7 --- /dev/null +++ b/crates/engine/src/cmd/file/save_format_tests.rs @@ -0,0 +1,154 @@ +//! Preferences › File Handling › Save documents as (`saveFormat`): a `.idml` name is saved as +//! IDML, and with IDML chosen an opened `.idml` file is saved back to itself. + +use std::path::PathBuf; + +use serde_json::json; + +use crate::Session; + +fn temp_dir(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("dc-save-format-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir +} + +/// A new document holding a text frame with `text`. +fn document_with(s: &mut Session, text: &str) { + s.execute("file.new", &json!({})).unwrap(); + s.execute("frame.create", &json!({"rect": [72, 72, 400, 200], "content": "text", "text": text})).unwrap(); +} + +/// The text of the active document's stories, joined. +fn texts(s: &Session) -> String { + let d = &s.doc().unwrap().doc; + d.stories.values().map(|st| st.text.as_str()).collect::>().join("|") +} + +#[test] +fn a_save_to_an_idml_name_writes_idml() { + let dir = temp_dir("saveas"); + let mut s = Session::new(); + document_with(&mut s, "Hello IDML"); + let path = dir.join("Brochure.idml"); + s.execute("file.saveAs", &json!({"path": path.to_str().unwrap()})).unwrap(); + let bytes = std::fs::read(&path).unwrap(); + assert!(designcraft_idml::is_idml(&bytes), "an IDML package, not DesignCraft's format"); + assert!(!s.doc().unwrap().is_dirty(), "the document is saved"); + // Save again: the same file, as IDML. + s.execute("file.save", &json!({})).unwrap(); + assert!(designcraft_idml::is_idml(&std::fs::read(&path).unwrap())); + // It opens again with its text. + let mut t = Session::new(); + t.execute("file.open", &json!({"path": path.to_str().unwrap()})).unwrap(); + assert!(texts(&t).contains("Hello IDML"), "{}", texts(&t)); + // Any other name is DesignCraft's own format, as before. + let native = dir.join("Brochure.designcraft"); + s.execute("file.saveAs", &json!({"path": native.to_str().unwrap()})).unwrap(); + assert!(!designcraft_idml::is_idml(&std::fs::read(&native).unwrap())); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn save_a_copy_to_an_idml_name_writes_idml() { + let dir = temp_dir("copy"); + let mut s = Session::new(); + document_with(&mut s, "Copied"); + let path = dir.join("Copy.idml"); + s.execute("file.saveACopy", &json!({"path": path.to_str().unwrap()})).unwrap(); + assert!(designcraft_idml::is_idml(&std::fs::read(&path).unwrap())); + assert!(s.doc().unwrap().path.is_none(), "a copy doesn't change which file the document is"); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn with_idml_chosen_an_opened_idml_file_saves_back_to_itself() { + let dir = temp_dir("roundtrip"); + let path = dir.join("Magazine.idml"); + let p = path.to_str().unwrap(); + let mut s = Session::new(); + document_with(&mut s, "First draft"); + s.execute("file.saveAs", &json!({"path": p})).unwrap(); + + // DesignCraft's own format chosen (the default): the opened .idml starts unsaved, so Save + // never overwrites it unasked. + let mut a = Session::new(); + a.execute("file.open", &json!({"path": p})).unwrap(); + assert!(a.doc().unwrap().path.is_none()); + assert!(a.execute("file.save", &json!({})).is_err(), "Save asks for a name"); + + // IDML chosen: the document is that file, unchanged until edited, and Save writes IDML to it. + let mut b = Session::new(); + let r = b.execute("prefs.set", &json!({"saveFormat": "idml"})).unwrap(); + assert_eq!(r["saveFormat"], "idml"); + b.execute("file.open", &json!({"path": p})).unwrap(); + assert_eq!(b.doc().unwrap().path.as_deref(), Some(p)); + assert!(!b.doc().unwrap().is_dirty()); + b.execute("frame.create", &json!({"rect": [72, 300, 400, 400], "content": "text", "text": "Second draft"})).unwrap(); + b.execute("file.save", &json!({})).unwrap(); + assert!(designcraft_idml::is_idml(&std::fs::read(&path).unwrap())); + let mut c = Session::new(); + c.execute("file.open", &json!({"path": p})).unwrap(); + let t = texts(&c); + assert!(t.contains("First draft") && t.contains("Second draft"), "{t}"); + // An IDML package not named .idml opens (by its content) but stays unsaved: Save never + // writes to a file whose name doesn't say IDML. + let unnamed = dir.join("Magazine copy"); + std::fs::copy(&path, &unnamed).unwrap(); + b.execute("file.open", &json!({"path": unnamed.to_str().unwrap()})).unwrap(); + assert_eq!(b.doc().unwrap().path, None); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn the_save_format_preference_takes_only_known_formats() { + let mut s = Session::new(); + assert_eq!(s.prefs.save_format, crate::SaveFormat::Designcraft, "DesignCraft's own format by default"); + assert!(s.execute("prefs.set", &json!({"saveFormat": "pdf"})).is_err()); + assert_eq!(s.prefs.save_format, crate::SaveFormat::Designcraft, "a refused value changes nothing"); + // Preferences saved before the setting existed load with the default. + let old: crate::Prefs = serde_json::from_str(r#"{"linkTextFiles": true}"#).unwrap(); + assert_eq!(old.save_format, crate::SaveFormat::Designcraft); + assert_eq!(crate::SaveFormat::of_path("/a/B.IDML"), crate::SaveFormat::Idml); + assert_eq!(crate::SaveFormat::of_path("/a/B.designcraft"), crate::SaveFormat::Designcraft); + assert_eq!(crate::SaveFormat::of_path("/a/idml"), crate::SaveFormat::Designcraft, "a name, not an extension"); +} + +/// CodeRabbit on #1105: a save as IDML would drop editorial notes (and turn endnotes into plain +/// text), then mark the document saved and drop its recovery copy, so the loss would be silent +/// and for good. Such a save is refused unless `allowLoss`; file.idmlLosses says what it loses. +#[test] +fn an_idml_save_that_would_lose_content_is_refused_unless_allowed() { + let dir = temp_dir("lossy"); + let mut s = Session::new(); + document_with(&mut s, "Has a note"); + assert_eq!(s.execute("file.idmlLosses", &json!({})).unwrap(), json!({"editorialNotes": 0, "endnotes": 0})); + s.execute("note.new", &json!({"text": "Check this"})).unwrap(); + assert_eq!(s.execute("file.idmlLosses", &json!({})).unwrap(), json!({"editorialNotes": 1, "endnotes": 0})); + + let path = dir.join("Notes.idml"); + let copy = dir.join("Copy.idml"); + for (cmd, p) in [("file.saveAs", &path), ("file.saveACopy", ©)] { + let e = s.execute(cmd, &json!({"path": p.to_string_lossy()})).unwrap_err(); + assert!(e.to_string().starts_with(super::bytes::LOSSY_IDML_SAVE), "{cmd}: {e}"); + assert!(!p.exists(), "{cmd}: nothing written"); + } + assert!(s.doc().unwrap().is_dirty() && s.doc().unwrap().path.is_none(), "the document is as it was"); + + // Saved as DesignCraft, nothing is lost and nothing is asked. + s.execute("file.saveAs", &json!({"path": dir.join("Notes.designcraft").to_string_lossy()})).unwrap(); + // Allowed, the IDML is written; the document's own file is then IDML, and ⌘S is refused again + // while there is something to lose. + s.execute("file.saveAs", &json!({"path": path.to_string_lossy(), "allowLoss": true})).unwrap(); + assert!(designcraft_idml::is_idml(&std::fs::read(&path).unwrap())); + s.execute("endnote.insert", &json!({"text": "An endnote."})).unwrap(); + assert_eq!(s.execute("file.idmlLosses", &json!({})).unwrap(), json!({"editorialNotes": 1, "endnotes": 1})); + assert!(s.execute("file.save", &json!({})).is_err()); + assert!(s.doc().unwrap().is_dirty()); + s.execute("file.save", &json!({"allowLoss": true})).unwrap(); + assert!(!s.doc().unwrap().is_dirty()); + s.execute("file.saveACopy", &json!({"path": copy.to_string_lossy(), "allowLoss": true})).unwrap(); + assert!(copy.exists()); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/engine/src/cmd/interactive.rs b/crates/engine/src/cmd/interactive.rs index 75347b549..49eaa4b9a 100644 --- a/crates/engine/src/cmd/interactive.rs +++ b/crates/engine/src/cmd/interactive.rs @@ -94,11 +94,14 @@ pub fn specs() -> Vec { /// `url`, `email`, `page` (1-based) or `anchor` (a text anchor's id, or its name). /// /// `None` is "no destination given", which `hyperlink.edit` needs for an edit that only renames. -/// An `anchor` that is given and names none is an error, not `None`: an unknown name made -/// `hyperlink.create` fall through to `page` and an unknown id was stored as it stood, so the -/// link went to an anchor nobody has and the export quietly left it out -- and on -/// `hyperlink.edit` the `None` read as "no destination given", so the command reported success -/// and kept the old destination (noted in review). +/// A destination that *is* given and cannot be used is an error. +/// +/// The anchor half of that landed with the anchor feature (#1555): an unknown id was stored as it +/// stood and an unknown name read as no destination at all. +/// +/// The page half is this one. A page number is 1-based and the document has as many pages as it +/// has, so `page 0` became page 1 (`saturating_sub`) and a page past the end was accepted and +/// then left out of the export, since no sheet shows it. fn dest_param(id: &str, d: &designcraft_doc::Document, p: &Value) -> Result> { if let Some(u) = str_param(p, "url") { if !designcraft_doc::is_safe_link_url(u) { @@ -134,7 +137,18 @@ fn dest_param(id: &str, d: &designcraft_doc::Document, p: &Value) -> Result Err(bad(id, format!("no text anchor {a} (anchor.list names them)"))), }; } - Ok(p.get("page").and_then(Value::as_u64).map(|pg| HyperlinkDest::Page((pg as usize).saturating_sub(1)))) + match p.get("page").filter(|v| !v.is_null()) { + None => Ok(None), + Some(pg) => { + let pages = d.page_count(); + // Compared as it arrived: `n as usize` is lossy where usize is 32 bits, so on wasm + // 4294967297 became 1 and a one-page document accepted it (noted in review). + match pg.as_u64() { + Some(n) if n >= 1 && n <= pages as u64 => Ok(Some(HyperlinkDest::Page(n as usize - 1))), + _ => Err(bad(id, format!("page {pg}: the document has {pages} page(s), numbered from 1"))), + } + } + } } /// The anchor's own name, for a link to one that was not given a name. @@ -331,6 +345,34 @@ mod anchor_dest_tests { assert_eq!(s.execute("anchor.list", &json!({})).unwrap()[0]["page"], "4"); assert_eq!(link_pages(&mut s), vec![3], "the link follows the text"); + // A page number the document does not have is refused, rather than becoming page 1 or a + // link the export quietly leaves out. + let dest_err = |s: &mut Session, dest: serde_json::Value| { + let mut params = dest; + params["ids"] = json!([thumb["id"].clone()]); + s.execute("hyperlink.create", ¶ms).expect_err("refused").to_string() + }; + for (params, wanted) in [ + (json!({"page": 0}), "numbered from 1"), + (json!({"page": 99}), "the document has 4 page(s)"), + // Compared before it is narrowed: where usize is 32 bits this value truncates to 1 + // and the document accepted it as its own first page (noted in review). On a 64-bit + // host the comparison is the same either way, so this case discriminates on wasm. + (json!({"page": 4_294_967_297u64}), "the document has 4 page(s)"), + (json!({"page": u64::MAX}), "the document has 4 page(s)"), + (json!({"anchor": 12345}), "no text anchor"), + (json!({"anchor": "No Such Anchor"}), "no text anchor"), + ] { + let e = dest_err(&mut s, params.clone()); + assert!(e.contains(wanted), "{params}: {e}"); + } + // The pages it does have still work, 1-based. + let made = s.execute("hyperlink.create", &json!({"page": 4, "ids": [thumb["id"].clone()]})).unwrap()["ids"][0].clone(); + let links = s.execute("hyperlink.list", &json!({})).unwrap(); + let link = links.as_array().unwrap().iter().find(|h| h["id"] == made).expect("the new link"); + assert_eq!(link["dest"], json!({"kind": "page", "value": 3}), "page 4 is index 3"); + s.execute("hyperlink.delete", &json!({"id": made})).unwrap(); + // An anchor's id works as well as its name, and an unknown name is refused. s.execute("hyperlink.delete", &json!({"id": links[0]["id"].clone()})).unwrap(); s.execute("hyperlink.create", &json!({"anchor": anchor["id"].clone(), "ids": [thumb["id"].clone()], "name": "Thumbnail"})).unwrap(); diff --git a/crates/engine/src/cmd/interchange.rs b/crates/engine/src/cmd/interchange.rs index a33a51639..754e98647 100644 --- a/crates/engine/src/cmd/interchange.rs +++ b/crates/engine/src/cmd/interchange.rs @@ -28,8 +28,10 @@ pub fn specs() -> Vec { fn export_idml(s: &mut Session, p: &Value) -> Result { let st = s.doc()?; let opts = designcraft_idml::ExportOptions { embed_images: p.get("embedImages").and_then(Value::as_bool).unwrap_or(true) }; - let layer_doc = with_pdf_layer_variants(&st.doc, opts.embed_images)?; - let (bytes, warnings) = designcraft_idml::export_idml_report(layer_doc.as_ref().unwrap_or(&st.doc), &opts); + // A data-merge preview's fill is session state: the unfilled template is exported (as + // `file.serialize` and the saves write it). + let doc = st.preview_stash.as_deref().unwrap_or(st.doc.as_ref()); + let (bytes, warnings) = idml_bytes(doc, &opts)?; let mut out = match str_param(p, "path") { Some(path) => { #[cfg(not(target_arch = "wasm32"))] @@ -61,6 +63,13 @@ pub(crate) fn has_applicable_pdf_layer_overrides(doc: &Document) -> bool { /// quietly fall back to the file's defaults. Read and write walks also reach table-cell and /// note text. Endnote variants are prepared too, but IDML endnote structures/artwork are not /// serialized yet (see `docs/pdf-layer-visibility.md`). +/// `doc` as an IDML package, with its placed PDFs' layer choices (as Export IDML and an IDML save +/// write it). +pub(crate) fn idml_bytes(doc: &Document, opts: &designcraft_idml::ExportOptions) -> Result<(Vec, Vec)> { + let layer_doc = with_pdf_layer_variants(doc, opts.embed_images)?; + Ok(designcraft_idml::export_idml_report(layer_doc.as_ref().unwrap_or(doc), opts)) +} + fn with_pdf_layer_variants(doc: &Document, embed: bool) -> Result> { let choices: Vec<_> = doc .placed_items() @@ -503,7 +512,8 @@ fn import_interchange(s: &mut Session, bytes: Vec, package: Option<&std::pat // preview), as InDesign shows them. One preview can stand for any number of graphics: they // share its buffer. let mut previews = std::collections::HashMap::new(); - let bytes = if is_indd(&file, &bytes) { + let from_indd = is_indd(&file, &bytes); + let bytes = if from_indd { // What the converter can't read still comes over as IDML (#21). let conversion = craft_indd::convert(&bytes, &file).map_err(|e| { EngineError::Other(format!( @@ -533,8 +543,16 @@ fn import_interchange(s: &mut Session, bytes: Vec, package: Option<&std::pat warnings.extend(font_warnings); warnings.extend(super::style::grep_style_warnings(&d)); let warning_items: Vec = warnings.iter().map(|w| warning_item(&d, &story_ids, w).map_or(Value::Null, |i| json!(i.0))).collect(); - // Never save over the .idml or .indd with the native format: the document starts unsaved. - let mut st = DocState::new(d, None); + // Saving IDML (Preferences › File Handling): an opened .idml file is the document's file, and + // Save writes IDML back to it. Anything else starts unsaved, so neither a converted .indd nor a + // file that isn't named .idml is ever overwritten (nor is any .idml with the native format). + let path = match s.prefs.save_format { + crate::SaveFormat::Idml if !from_indd => { + package.and_then(std::path::Path::to_str).filter(|path| crate::SaveFormat::of_path(path) == crate::SaveFormat::Idml).map(str::to_string) + } + _ => None, + }; + let mut st = DocState::new(d, path); st.fonts = fonts; let i = s.add_document(st); Ok(json!({"index": i, "documentFonts": faces, "warnings": warnings, "warningItems": warning_items})) @@ -578,6 +596,24 @@ mod tests { use super::*; + /// During a data-merge preview, Export IDML (which the web build's Save uses with IDML chosen) + /// writes the unfilled template, as Save does: the preview's fill is session state. + #[test] + fn idml_export_during_a_data_merge_preview_writes_the_template() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let r = s.execute("frame.create", &json!({"rect": [72, 72, 400, 200], "content": "text", "text": ""})).unwrap(); + let sid = s.doc().unwrap().doc.item(designcraft_doc::ItemId(r["id"].as_u64().unwrap())).unwrap().text_frame().unwrap().story; + s.execute("data.source.select", &json!({"bytes": crate::cmd::base64_encode(b"x\nfilled-record\n"), "name": "d.csv"})).unwrap(); + s.execute("data.placeholder.add", &json!({"field": "x", "story": sid.0, "at": 0})).unwrap(); + s.execute("data.preview", &json!({"record": 1})).unwrap(); + assert_eq!(s.doc().unwrap().doc.story(sid).unwrap().text, "filled-record"); + let b64 = s.execute("file.exportIdml", &json!({})).unwrap()["base64"].as_str().unwrap().to_string(); + let back = designcraft_idml::import_idml(&crate::cmd::base64_decode(&b64)).unwrap(); + assert!(back.stories.values().all(|st| !st.text.contains("filled-record")), "the preview's fill isn't exported"); + assert_eq!(s.doc().unwrap().doc.story(sid).unwrap().text, "filled-record", "the preview stays on screen"); + } + fn linked_idml(link: &str, embed_images: bool) -> Result<(Vec, Vec)> { let png = designcraft_render::Rendered { width: 2, height: 2, pixels: vec![255; 16] }.to_png(); let mut session = Session::new(); diff --git a/crates/engine/src/cmd/layout/registry.rs b/crates/engine/src/cmd/layout/registry.rs index d79d829b8..85bacd90c 100644 --- a/crates/engine/src/cmd/layout/registry.rs +++ b/crates/engine/src/cmd/layout/registry.rs @@ -1,3 +1,7 @@ +use std::sync::Arc; + +use designcraft_doc::{Item, Story}; + use super::layers::{duplicate_layer, set_layer}; use super::margins::{adjust_layout, column_guides_unlocked, margin_boxes, move_column_guide, set_margins_columns, set_page_width}; use super::pages::{document_setup, page_options, page_size}; @@ -7,6 +11,52 @@ use super::parents::{ use super::sections::{ChapterEdit, SectionEdit, chapter_numbering, start_number}; use super::{CommandSpec, LAYER_COLORS, Layer, LayerId, Margins, Result, SpreadId, Value, bad, cmd, has_doc, json, ok, str_param}; +// A group can hold children on other layers, including in inactive states or pasted-into frames. +// Only references to removed layers change; surviving layers keep their assignments. Containers +// without such a reference stay shared with the undo history (copy-on-write only where one is). +fn item_uses_layers(it: &Item, gone: &[LayerId]) -> bool { + let mut found = false; + it.walk(&mut |i| found |= gone.contains(&i.layer)); + found +} + +fn story_uses_layers(st: &Story, gone: &[LayerId]) -> bool { + st.objects.iter().any(|o| item_uses_layers(&o.item, gone)) + || st.tables.values().any(|t| t.cells.iter().any(|c| story_uses_layers(&c.text, gone))) + || st.notes.iter().chain(&st.endnotes).any(|n| story_uses_layers(&n.text, gone)) +} + +fn merge_item_layers(it: &mut Item, gone: &[LayerId], into: LayerId) { + if gone.contains(&it.layer) { + it.layer = into; + } + for child in it.children_mut().into_iter().flatten() { + if item_uses_layers(child, gone) { + merge_item_layers(Arc::make_mut(child), gone, into); + } + } +} + +fn merge_story_layers(st: &mut Story, gone: &[LayerId], into: LayerId) { + for object in &mut st.objects { + if item_uses_layers(&object.item, gone) { + merge_item_layers(&mut Arc::make_mut(object).item, gone, into); + } + } + for table in st.tables.values_mut() { + if table.cells.iter().any(|c| story_uses_layers(&c.text, gone)) { + for cell in &mut Arc::make_mut(table).cells { + merge_story_layers(&mut cell.text, gone, into); + } + } + } + for note in st.notes.iter_mut().chain(st.endnotes.iter_mut()) { + if story_uses_layers(¬e.text, gone) { + merge_story_layers(&mut Arc::make_mut(note).text, gone, into); + } + } +} + pub fn specs() -> Vec { vec![ cmd!( @@ -770,33 +820,49 @@ pub fn specs() -> Vec { .map(LayerId) .or_else(|| ids.first().copied()) .ok_or_else(|| bad("layer.merge", "no layers"))?; - s.edit(|d, _| { + let gone: Vec = ids.iter().copied().filter(|l| *l != into).collect(); + let r = s.edit(|d, _| { if d.layer(into).is_none() || ids.iter().any(|l| d.layer(*l).is_none()) { return Err(bad("layer.merge", "no such layer")); } - let gone: Vec = ids.iter().copied().filter(|l| *l != into).collect(); for sp in d.spreads.iter_mut().chain(d.parents.iter_mut()) { - if !sp.items.iter().any(|i| gone.contains(&i.layer)) { + if !sp.items.iter().any(|i| item_uses_layers(i, &gone)) { continue; } - for it in &mut std::sync::Arc::make_mut(sp).items { - if gone.contains(&it.layer) { - std::sync::Arc::make_mut(it).layer = into; + for it in &mut Arc::make_mut(sp).items { + if item_uses_layers(it, &gone) { + merge_item_layers(Arc::make_mut(it), &gone, into); } } } + for story in d.stories.values_mut() { + if story_uses_layers(story, &gone) { + merge_story_layers(Arc::make_mut(story), &gone, into); + } + } d.layers.retain(|l| !gone.contains(&l.id)); Ok(json!({"merged": gone.len()})) - }) + })?; + // Drawing continues on the layer that now holds the active layer's objects. + let st = s.doc_mut()?; + if gone.contains(&st.active_layer) { + st.active_layer = into; + } + Ok(r) } ), cmd!("layer.deleteUnused", "Delete Unused Layers", [], None, "{} — layers without objects (one layer always stays)", has_doc, |s, _| { s.edit(|d, _| { - let used: std::collections::HashSet = - d.spreads.iter().chain(d.parents.iter()).flat_map(|sp| sp.items.iter().map(|i| i.layer)).collect(); + // Objects inside groups and objects anchored in text (cells and notes included) use their layers too. + let in_use = |id: LayerId| { + let layer = [id]; + d.spreads.iter().chain(d.parents.iter()).any(|sp| sp.items.iter().any(|i| item_uses_layers(i, &layer))) + || d.stories.values().any(|st| story_uses_layers(st, &layer)) + }; + let used: std::collections::HashSet = d.layers.iter().map(|l| l.id).filter(|id| in_use(*id)).collect(); let before = d.layers.len(); if used.is_empty() { - // Nothing anywhere: keep the first layer. + // No layer has objects: keep the first layer. d.layers.truncate(1); } else { d.layers.retain(|l| used.contains(&l.id)); diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs index f048ba98b..f85379cf6 100644 --- a/crates/engine/src/cmd/links.rs +++ b/crates/engine/src/cmd/links.rs @@ -57,6 +57,15 @@ pub fn specs() -> Vec { has_doc, relink_folder ), + cmd!( + "links.relinkFiles", + "Relink to Files", + [], + None, + "{files: [{name, base64, path?: the file's path within a chosen folder}], asset?: id} — relink from files handed over by name (the web build's file and folder pickers, which give no path on disk): with `asset`, that graphic from the first file; otherwise each missing graphic from the file whose path ends most like its link (the same name at least, any case), all in one undo step — a graphic those can't tell apart (two equally likely files, or one file named only like graphics linking to different files) stays missing. A file named like the link keeps the link's path → {relinked, notFound: [names no file matched], ambiguous: [names left missing], failed: [{name, error}: matching files that couldn't be read, their graphics left missing], unused: [files that matched nothing]}", + has_doc, + relink_files + ), cmd!( "links.update", "Update Link", @@ -236,13 +245,12 @@ pub(crate) fn give_bytes(a: &mut Asset, bytes: impl Into>>, file: Op } /// [`give_bytes`] for a graphic being placed, leaving out the work that grows with the file: the -/// graphic links to its file at once, with the file's size and time as its fingerprint and the -/// bytes just read kept in memory for drawing, and its content hash and proxy are made in the -/// background ([`super::native_links::prepare`] the returned work once the asset is in the -/// document; [`add_prepared`] adds them). A link without a hash is complete: its status goes by -/// size and time until the hash is in. Placing many press-size images would otherwise decode and -/// hash each one before the app responds again. Embedded placements, bytes without a file and -/// the web (no threads) are [`give_bytes`]. +/// graphic links to its file at once, with the bytes just read kept in memory for drawing. +/// A reliable size and time can identify those bytes until the worker makes the hash. If +/// there is no reliable time, record a hash of the bytes already read before the link can +/// be saved. The worker still makes any deferred hash and the proxy ([`super::native_links::prepare`]; +/// [`add_prepared`] adds the results). Embedded placements, bytes without a file and the web +/// (no threads) are [`give_bytes`]. #[must_use = "the hash and proxy are made only once the returned work is queued"] pub(crate) fn give_placed( a: &mut Asset, @@ -260,7 +268,7 @@ pub(crate) fn give_placed( } }; record_file(a, &bytes, file, document); - a.link_hash = None; + a.link_hash = a.link_fingerprint.is_none().then(|| crate::asset_io::content_hash(&bytes)); link_recorded(a, Arc::clone(&bytes), designcraft_doc::SourceKey::fresh(), document, |_, _| None); Some(super::native_links::Pending::of(a, bytes)) } @@ -894,24 +902,64 @@ fn relinked_asset(a: &designcraft_doc::Asset, read: &Path, document: Option<&Pat // The size and time from before the read: a change during it is seen by the next check. let before = super::datamerge::fingerprint_of(read); let (bytes, px) = reload(read)?; - let page = if designcraft_render::is_pdf(&bytes) { a.page } else { 0 }; + let mut a = relinked_from(a, &bytes, px, &read.display().to_string())?; + a.name = file_name(&read.to_string_lossy()); + let file = FileLink::of(read, before); + give_bytes(&mut a, bytes, Some(file), false, document); + Ok(Arc::new(a)) +} + +/// [`relinked_asset`] from a file handed over as bytes with its name (the browser's file and +/// folder pickers give no path). The bytes become the document's own copy. A file of the same +/// name as the link keeps the link's record, so the document still knows the file on the computer +/// the link came from; another name becomes the link. +fn relinked_bytes(a: &designcraft_doc::Asset, name: &str, bytes: Vec) -> Result> { + if designcraft_render::is_pdf(&bytes) { + designcraft_render::check_pdf_input_size(bytes.len()).map_err(|e| bad("links", format!("{name}: {e}")))?; + } + let px = designcraft_render::image_size(&bytes).ok_or_else(|| bad("links", format!("{name}: unsupported or corrupt image")))?; + let mut a = relinked_from(a, &bytes, px, name)?; + let same = a.link.as_deref().is_some_and(|old| link_file_name(old).eq_ignore_ascii_case(name)); + if !same { + a.set_link(Some(name.to_string()), None); + a.link_relative = None; + } else { + // The file's size and time on that computer aren't these bytes'. + let link = a.link.clone(); + a.set_link(link, None); + } + // The link kept may come from another platform: named after its last part, either separator. + a.name = a.link.as_deref().map_or_else(|| name.to_string(), |l| link_file_name(l).to_string()); + a.proxy = None; + a.link_hash = Some(crate::asset_io::content_hash(&bytes)); + a.storage = Storage::Embedded; + a.data = AssetData::embedded(Arc::new(bytes)); + Ok(Arc::new(a)) +} + +/// The file name at the end of a link (either kind of separator). +fn link_file_name(link: &str) -> &str { + link.rsplit(['/', '\\']).next().unwrap_or(link) +} + +/// `a` with a new file's type, page and pixel size (`px`), its PDF crop found on the new bytes +/// (`label` names the file in errors). The caller gives it the bytes and its name. +fn relinked_from(a: &designcraft_doc::Asset, bytes: &[u8], px: (u32, u32), label: &str) -> Result { + let page = if designcraft_render::is_pdf(bytes) { a.page } else { 0 }; let px = if page > 0 { - designcraft_render::pdf_page_size(&bytes, page as usize) + designcraft_render::pdf_page_size(bytes, page as usize) .map(|(w, h)| (w.round().max(1.0) as u32, h.round().max(1.0) as u32)) - .ok_or_else(|| bad("links", format!("{}: can't read PDF page {}", read.display(), u64::from(page) + 1)))? + .ok_or_else(|| bad("links", format!("{label}: can't read PDF page {}", u64::from(page) + 1)))? } else { px }; let mut a = a.clone(); - a.mime = designcraft_render::image_mime(&bytes).to_string(); + a.mime = designcraft_render::image_mime(bytes).to_string(); a.pixels = Some(px); a.page = page; - a.name = file_name(&read.to_string_lossy()); // A placed PDF keeps its crop choice; its box is found on the new file. - super::file::crop_pdf_from(&mut a, &bytes); - let file = FileLink::of(read, before); - give_bytes(&mut a, bytes, Some(file), false, document); - Ok(Arc::new(a)) + super::file::crop_pdf_from(&mut a, bytes); + Ok(a) } /// The file Update reads `a`'s bytes from: the first of a linked graphic's paths that holds a @@ -1029,6 +1077,139 @@ fn relink_folder(s: &mut Session, p: &Value) -> Result { Ok(json!({"relinked": n, "notFound": not_found})) } +/// The most files one `links.relinkFiles` takes (a Links folder is rarely more than a few hundred). +const MAX_RELINK_FILES: usize = 2000; + +/// The path components of a link or a file's path in a chosen folder, either separator. +fn path_parts(path: &str) -> Vec<&str> { + path.split(['/', '\\']).filter(|c| !c.is_empty()).collect() +} + +/// How many trailing path components `file` shares with `link` (any case): 1 for the file name +/// alone, more when its folders match the link's too. +fn shared_tail(file: &str, link: &str) -> usize { + path_parts(file).iter().rev().zip(path_parts(link).iter().rev()).take_while(|(a, b)| a.eq_ignore_ascii_case(b)).count() +} + +/// Which handed-over file each missing graphic takes (`links.relinkFiles` without `asset`). +/// A graphic takes the file whose path ends most like its link: the same name at least. Where +/// that can't tell files apart — two files of the graphic's name equally like its link, or one +/// file named only like two graphics whose links name different files — the graphic is left +/// missing and reported, rather than given another file's picture. Graphics linking to the same +/// file share it. +/// Also returns which files are named like some missing graphic (matched or not), so a file left +/// ambiguous isn't reported as matching nothing. +fn match_files(missing: &[(AssetId, String)], files: &[(String, String)]) -> (Vec<(AssetId, usize)>, Vec, Vec, Vec) { + let mut named = vec![false; files.len()]; + let mut chosen = Vec::new(); + let mut not_found = Vec::new(); + let mut ambiguous = Vec::new(); + let mut picks: Vec<(AssetId, usize, usize, &str)> = Vec::new(); + for (aid, link) in missing { + let scores: Vec<(usize, usize)> = + files.iter().enumerate().map(|(k, (_, path))| (k, shared_tail(path, link))).filter(|(_, n)| *n > 0).collect(); + for (k, _) in &scores { + if let Some(n) = named.get_mut(*k) { + *n = true; + } + } + let best = scores.iter().map(|(_, n)| *n).max().unwrap_or(0); + let top: Vec = scores.iter().filter(|(_, n)| *n == best).map(|(k, _)| *k).collect(); + match top.as_slice() { + [] => not_found.push(link_file_name(link).to_string()), + [k] => picks.push((*aid, *k, best, link.as_str())), + _ => ambiguous.push(link_file_name(link).to_string()), + } + } + let same = |x: &str, y: &str| path_parts(x).iter().map(|c| c.to_ascii_lowercase()).eq(path_parts(y).iter().map(|c| c.to_ascii_lowercase())); + for (aid, k, score, link) in &picks { + let rivals = picks.iter().filter(|(other, k2, _, _)| other != aid && k2 == k); + let top = rivals.clone().map(|(_, _, n, _)| *n).max().unwrap_or(0); + if top > *score { + // The file ends more like another graphic's link: it is that graphic's. + not_found.push(link_file_name(link).to_string()); + } else if rivals.filter(|(_, _, n, _)| *n == *score).any(|(_, _, _, link2)| !same(link2, link)) { + // Equally like graphics linking to different files: which it is can't be told. + ambiguous.push(link_file_name(link).to_string()); + } else { + chosen.push((*aid, *k)); + } + } + (chosen, not_found, ambiguous, named) +} + +fn relink_files(s: &mut Session, p: &Value) -> Result { + const ID: &str = "links.relinkFiles"; + let list = p.get("files").and_then(Value::as_array).ok_or_else(|| bad(ID, "missing files"))?; + if list.len() > MAX_RELINK_FILES { + return Err(bad(ID, format!("at most {MAX_RELINK_FILES} files"))); + } + // (file name, path within the chosen folder: the name when there is none, base64) + let mut files: Vec<(String, String)> = Vec::new(); + let mut data: Vec<&str> = Vec::new(); + for f in list { + let name = f.get("name").and_then(Value::as_str).ok_or_else(|| bad(ID, "each file needs a name"))?; + let b64 = f.get("base64").and_then(Value::as_str).ok_or_else(|| bad(ID, "each file needs base64"))?; + let path = f.get("path").and_then(Value::as_str).filter(|p| !p.is_empty()).unwrap_or(name); + files.push((link_file_name(name).to_string(), path.to_string())); + data.push(b64); + } + let st = s.doc()?; + let (d, document) = (&st.doc, st.path.as_deref().map(Path::new)); + // Every replacement is built before the edit: a bad file leaves the document as it was. + let mut fresh = Vec::new(); + let mut used = vec![false; files.len()]; + let (mut not_found, mut ambiguous, mut failed) = (Vec::new(), Vec::new(), Vec::new()); + if let Some(aid) = p.get("asset").and_then(Value::as_u64).map(AssetId) { + let a = d.assets.get(&aid).ok_or_else(|| bad(ID, "no such graphic"))?; + let ((name, _), b64) = files.first().zip(data.first()).ok_or_else(|| bad(ID, "no file"))?; + fresh.push((aid, relinked_bytes(a, name, super::base64_decode(b64))?)); + if let Some(u) = used.first_mut() { + *u = true; + } + } else { + let placed = d.used_assets(); + let mut checks = ImageChecks::new(); + // Graphics still placed: a replaced graphic kept for undo isn't relinked behind the page. + let missing: Vec<(AssetId, String)> = d + .assets + .values() + .filter(|a| placed.contains(&a.id) && image_status(a, document, &mut checks, None).0 == "missing") + .map(|a| (a.id, a.link.clone().unwrap_or_else(|| a.name.clone()))) + .collect(); + let (chosen, named); + (chosen, not_found, ambiguous, named) = match_files(&missing, &files); + // A file named like a missing graphic was meant for it, even when left ambiguous. + for (u, n) in used.iter_mut().zip(&named) { + *u |= *n; + } + for (aid, k) in chosen { + let (Some(a), Some((name, _)), Some(b64)) = (d.assets.get(&aid), files.get(k), data.get(k)) else { continue }; + if let Some(u) = used.get_mut(k) { + *u = true; + } + // A file that can't be read leaves its graphic missing and the others relinking. + match relinked_bytes(a, name, super::base64_decode(b64)) { + Ok(fresh_asset) => fresh.push((aid, fresh_asset)), + Err(e) => failed.push(json!({"name": name, "error": e.to_string()})), + } + } + } + let unused: Vec = files.iter().zip(&used).filter(|(_, u)| !**u).map(|((n, _), _)| n.clone()).collect(); + let n = fresh.len(); + if n > 0 { + s.edit(|d, _| { + for (aid, a) in fresh { + d.assets.insert(aid, a); + } + Ok(()) + })?; + s.link_checks.images.clear(); + designcraft_doc::asset_data::links_changed(); + } + Ok(json!({"relinked": n, "notFound": not_found, "ambiguous": ambiguous, "failed": failed, "unused": unused})) +} + /// Unembed reads and writes files: not on the web. fn can_unembed(s: &Session) -> std::result::Result<(), String> { has_doc(s)?; @@ -1357,6 +1538,180 @@ mod shared_asset_tests { designcraft_render::Rendered { width: w, height: h, pixels: vec![200u8; (w * h * 4) as usize] }.to_png() } + /// Two placed graphics whose linked files were never read (an IDML opened in the browser + /// without its Links folder): missing, with no picture. + fn two_missing() -> (Session, AssetId, AssetId) { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + for (name, x) in [("a.png", 72), ("b.png", 200)] { + let b = super::super::file::base64_encode(&png(4, 4 + x as u32 / 100)); + s.execute("file.place", &json!({"base64": b, "name": name, "x": x, "y": 72})).unwrap(); + s.execute("edit.deselectAll", &json!({})).unwrap(); + } + let ids: Vec = s.doc().unwrap().doc.assets.keys().copied().collect(); + s.edit(|d, _| { + for (k, id) in ids.iter().enumerate() { + let a = Arc::make_mut(d.assets.get_mut(id).unwrap()); + a.link = Some(format!("/Users/someone/Links/Pic{k}.PNG")); + a.name = format!("Pic{k}.PNG"); + a.data = AssetData::embedded(Vec::new()); + } + Ok(()) + }) + .unwrap(); + (s, ids[0], ids[1]) + } + + /// Two missing graphics linked to `links`, as [`two_missing`] but with the given links. + fn missing_with(links: [&str; 2]) -> (Session, AssetId, AssetId) { + let (mut s, a, b) = two_missing(); + s.edit(|d, _| { + for (id, link) in [(a, links[0]), (b, links[1])] { + let x = Arc::make_mut(d.assets.get_mut(&id).unwrap()); + x.link = Some(link.into()); + x.name = link_file_name(link).into(); + } + Ok(()) + }) + .unwrap(); + (s, a, b) + } + + /// Only graphics still placed are relinked: a replaced graphic kept for undo is missing too, + /// but relinking it would change nothing on the page. The journal keeps the files' names, + /// not their contents. + #[test] + fn relinks_only_placed_graphics_and_replays_from_the_journal() { + let (mut s, a, b) = two_missing(); + // b's frame is deleted: its asset stays (for undo) but nothing shows it. + s.edit(|d, _| { + for sp in &mut d.spreads { + std::sync::Arc::make_mut(sp).items.retain(|it| !matches!(&it.content, Content::Graphic(g) if g.asset == b)); + } + Ok(()) + }) + .unwrap(); + let file = |name: &str| json!({"name": name, "base64": super::super::file::base64_encode(&png(6, 6))}); + let r = s.execute("links.relinkFiles", &json!({"files": [file("pic0.png"), file("pic1.png")]})).unwrap(); + assert_eq!(r["relinked"], 1); + assert_eq!(r["unused"], json!(["pic1.png"]), "nothing placed is named pic1"); + let d = &s.doc().unwrap().doc; + assert!(!d.assets[&a].data.is_empty() && d.assets[&b].data.is_empty()); + // The journal keeps the files whole, as it does for `file.place {base64}`: replayed, the + // entry relinks again. + let (id, params) = s.journal.last().unwrap().clone(); + assert_eq!(id, "links.relinkFiles"); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(s.doc().unwrap().doc.assets[&a].data.is_empty()); + assert_eq!(s.execute(&id, ¶ms).unwrap()["relinked"], 1); + assert!(!s.doc().unwrap().doc.assets[&a].data.is_empty()); + } + + /// A matching file that can't be read (here not an image at all) is reported and leaves its + /// graphic missing; the other files still relink theirs. + #[test] + fn an_unreadable_file_leaves_the_others_relinking() { + let (mut s, a, b) = two_missing(); + let good = json!({"name": "pic0.png", "base64": super::super::file::base64_encode(&png(6, 6))}); + let bad_file = json!({"name": "pic1.png", "base64": super::super::file::base64_encode(b"not an image")}); + let r = s.execute("links.relinkFiles", &json!({"files": [good, bad_file]})).unwrap(); + assert_eq!(r["relinked"], 1, "{r}"); + assert_eq!(r["failed"].as_array().map(|f| f.iter().map(|f| f["name"].clone()).collect::>()), Some(vec![json!("pic1.png")]), "{r}"); + let d = &s.doc().unwrap().doc; + assert!(!d.assets[&a].data.is_empty() && d.assets[&b].data.is_empty()); + } + + /// Relinking to a file on disk names the graphic after that file as the platform reads + /// paths: a backslash is part of a file name on Linux and macOS. + #[cfg(unix)] + #[test] + fn a_path_relink_names_the_graphic_by_the_platform_s_file_name() { + let (mut s, a, _) = two_missing(); + let dir = std::env::temp_dir().join(format!("dc-relink-name-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("cover\\v2.png"); + std::fs::write(&path, png(4, 4)).unwrap(); + s.execute("links.relink", &json!({"asset": a.0, "path": path.to_string_lossy()})).unwrap(); + assert_eq!(s.doc().unwrap().doc.assets[&a].name, "cover\\v2.png"); + let _ = std::fs::remove_dir_all(&dir); + } + + /// Files of the same name in different folders of a chosen folder: each missing graphic takes + /// the one whose path ends like its link; where nothing tells them apart, the graphics stay + /// missing and are reported rather than given another graphic's picture. Graphics linking to + /// the same file share it. + #[test] + fn same_named_files_relink_by_folder_or_not_at_all() { + let file = |name: &str, path: &str, w: u32| json!({"name": name, "path": path, "base64": super::super::file::base64_encode(&png(w, w))}); + let px = |s: &Session, id: AssetId| s.doc().unwrap().doc.assets[&id].pixels; + let links = ["/Users/x/Vol38/Links/brand-a/logo.png", "/Users/x/Vol38/Links/brand-b/logo.png"]; + // Their folders tell them apart. + let (mut s, a, b) = missing_with(links); + let r = s + .execute( + "links.relinkFiles", + &json!({"files": [file("logo.png", "Links/brand-b/logo.png", 5), file("logo.png", "Links/brand-a/logo.png", 6)]}), + ) + .unwrap(); + assert_eq!(r["relinked"], 2); + assert_eq!((px(&s, a), px(&s, b)), (Some((6, 6)), Some((5, 5)))); + // Two files named alike with no folders: neither graphic can tell which is its own. + let (mut s, a, b) = missing_with(links); + let r = s.execute("links.relinkFiles", &json!({"files": [file("logo.png", "logo.png", 5), file("logo.png", "logo.png", 6)]})).unwrap(); + assert_eq!(r["relinked"], 0); + assert_eq!(r["ambiguous"], json!(["logo.png", "logo.png"])); + assert_eq!(r["unused"], json!([]), "files named like the graphics were meant for them"); + assert!(s.doc().unwrap().doc.assets[&a].data.is_empty() && s.doc().unwrap().doc.assets[&b].data.is_empty()); + // One file named like both, which link to different files: it can't be both. + let (mut s, a, _) = missing_with(links); + let r = s.execute("links.relinkFiles", &json!({"files": [file("logo.png", "logo.png", 5)]})).unwrap(); + assert_eq!((r["relinked"].as_u64(), r["ambiguous"].as_array().map(Vec::len)), (Some(0), Some(2))); + assert!(s.doc().unwrap().doc.assets[&a].data.is_empty()); + // ...but with its folder it is brand-b's, and brand-a's stays missing. + let r = s.execute("links.relinkFiles", &json!({"files": [file("logo.png", "brand-b/logo.png", 5)]})).unwrap(); + assert_eq!(r["relinked"], 1); + assert_eq!((r["notFound"].clone(), r["ambiguous"].clone()), (json!(["logo.png"]), json!([])), "brand-b's file isn't brand-a's"); + // Two graphics linking to the same file (another page of it, say) share it. + let (mut s, a, b) = missing_with(["/Users/x/Links/logo.png", "/Users/x/Links/logo.png"]); + let r = s.execute("links.relinkFiles", &json!({"files": [file("logo.png", "logo.png", 5)]})).unwrap(); + assert_eq!(r["relinked"], 2); + assert_eq!((px(&s, a), px(&s, b)), (Some((5, 5)), Some((5, 5)))); + } + + /// Relinking from files handed over by name (the web build): each missing graphic takes the + /// file of its name in any case, keeping its link's path, in one undo step; a file that + /// matches nothing and a graphic no file matched are reported. + #[test] + fn relinks_missing_graphics_from_files_by_name() { + let (mut s, a, b) = two_missing(); + let st = s.doc().unwrap(); + assert!(st.doc.assets.values().all(|x| status_cached(x, None, &mut ImageChecks::new()) == "missing")); + let file = |name: &str, w: u32| json!({"name": name, "base64": super::super::file::base64_encode(&png(w, w))}); + let r = s.execute("links.relinkFiles", &json!({"files": [file("pic0.png", 6), file("other.png", 3)]})).unwrap(); + assert_eq!(r["relinked"], 1); + assert_eq!(r["notFound"], json!(["Pic1.PNG"])); + assert_eq!(r["unused"], json!(["other.png"])); + let d = &s.doc().unwrap().doc; + assert_eq!(d.assets[&a].pixels, Some((6, 6))); + assert_eq!(d.assets[&a].link.as_deref(), Some("/Users/someone/Links/Pic0.PNG"), "the same file keeps its path"); + assert!(d.assets[&b].data.is_empty()); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(s.doc().unwrap().doc.assets[&a].data.is_empty(), "one undo step"); + // One graphic from a chosen file of another name: that name becomes the link. + s.execute("links.relinkFiles", &json!({"asset": b.0, "files": [file("new.png", 5)]})).unwrap(); + let d = &s.doc().unwrap().doc; + assert_eq!((d.assets[&b].pixels, d.assets[&b].link.as_deref(), d.assets[&b].name.as_str()), (Some((5, 5)), Some("new.png"), "new.png")); + // A file that isn't an image changes nothing: reported for a folder, an error for one + // chosen file. + let before = s.doc().unwrap().doc.assets.clone(); + let bad = json!({"name": "pic0.png", "base64": super::super::file::base64_encode(b"not an image")}); + let r = s.execute("links.relinkFiles", &json!({"files": [bad.clone()]})).unwrap(); + assert_eq!((r["relinked"].clone(), r["failed"][0]["name"].clone()), (json!(0), json!("pic0.png")), "{r}"); + assert!(s.execute("links.relinkFiles", &json!({"asset": a.0, "files": [bad]})).is_err()); + assert_eq!(s.doc().unwrap().doc.assets, before); + assert!(s.execute("links.relinkFiles", &json!({"files": "x"})).is_err()); + } + #[test] fn placements_of_one_file_share_an_asset_and_saves_drop_replaced_ones() { let mut s = Session::new(); diff --git a/crates/engine/src/cmd/links/tests.rs b/crates/engine/src/cmd/links/tests.rs index 8de21fb14..ee50171a3 100644 --- a/crates/engine/src/cmd/links/tests.rs +++ b/crates/engine/src/cmd/links/tests.rs @@ -868,6 +868,47 @@ fn placing_leaves_the_proxy_and_hash_to_the_background() { assert!(!s.doc().unwrap().links.checking()); } +/// A link whose modification time cannot identify its bytes must still reopen from +/// the original after an immediate save, rather than appear modified and show a proxy. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn immediate_save_preserves_a_link_without_a_trustworthy_timestamp() { + let dir = TempDir::new("save-unverified"); + let path = dir.0.join("art.png"); + let (placed_bytes, later_bytes) = same_size_pngs(); + let write_art = |bytes: &[u8]| { + std::fs::write(&path, bytes).unwrap(); + // A timestamp of zero never vouches for bytes, even on a slow test runner. + std::fs::File::options().write(true).open(&path).unwrap().set_modified(std::time::UNIX_EPOCH).unwrap(); + }; + write_art(&placed_bytes); + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let id = AssetId(s.execute("file.place", &json!({"path": path.to_string_lossy()})).unwrap()["asset"].as_u64().unwrap()); + let doc = dir.0.join("doc.designcraft"); + s.execute("file.save", &json!({"path": doc.to_string_lossy()})).unwrap(); + + let reopen = |path: &Path| { + let mut t = Session::new(); + t.execute("file.open", &json!({"path": path.to_string_lossy()})).unwrap(); + crate::cmd::native_links::wait(&mut t); + t + }; + let mut t = reopen(&doc); + assert_eq!(row(&mut t, id)["status"], "ok", "unchanged artwork must not look modified"); + let a = asset_of(&t, id); + assert!(a.data.is_linked(), "the original must not be embedded just to save it"); + assert_eq!(a.data.load().unwrap().as_slice(), placed_bytes.as_slice()); + + // Saving a copy after the disk file changes must not adopt its replacement as the original. + write_art(&later_bytes); + let copy = dir.0.join("copy.designcraft"); + s.execute("file.saveACopy", &json!({"path": copy.to_string_lossy()})).unwrap(); + assert_eq!(row(&mut reopen(©), id)["status"], "modified", "same size and timestamp do not prove identity"); + write_art(&placed_bytes); + assert_eq!(row(&mut reopen(©), id)["status"], "ok", "the copy must still refer to the placed bytes"); +} + /// Cmd-S right after placing a large photo writes a link and a proxy, not the photo. #[cfg(not(target_arch = "wasm32"))] #[test] diff --git a/crates/engine/src/cmd/native_links.rs b/crates/engine/src/cmd/native_links.rs index e6ffdef82..6d2ef5e37 100644 --- a/crates/engine/src/cmd/native_links.rs +++ b/crates/engine/src/cmd/native_links.rs @@ -12,9 +12,9 @@ //! first whose hash is the recorded one is the file, and its time is kept with the asset; when //! none matches the link is Modified and the file's bytes are never used. //! -//! Graphics placed from files link to them at once. The same thread makes their content hash -//! and proxy ([`prepare`]), and hashes linked files that an open found by size and time and that -//! have no hash yet. A save makes the proxies still missing ([`with_proxies`]), never a hash. +//! Graphics placed from files link to them at once. The same thread makes their proxies and +//! any deferred content hashes ([`prepare`]), and hashes linked files that an open found by size +//! and time and that have no hash yet. A save makes missing proxies ([`with_proxies`]), never a hash. use std::collections::BTreeMap; use std::path::{Path, PathBuf}; @@ -121,8 +121,8 @@ enum Work { /// Compare the file at `source`'s path (the first of its candidates that has the size of the /// embedded `bytes`) with the embedded bytes of a document saved before linked storage. Migrate { asset: AssetId, key: SourceKey, bytes: Arc>, source: LinkedSource, page: u32 }, - /// Hash the `bytes` of graphics just placed from a file, and make their proxy with `proxy`. - Prepare { key: SourceKey, bytes: Arc>, page: u32, proxy: bool }, + /// Hash placed graphics that lack a `hash`, and make their proxy when requested. + Prepare { key: SourceKey, bytes: Arc>, hash: Option, page: u32, proxy: bool }, } /// What a [`Work`] found. `key` is the asset's bytes' key when the check started: a result for @@ -152,12 +152,13 @@ enum Outcome { Prepared { key: SourceKey, hash: String, proxy: Option }, } -/// A graphic placed from a file whose content hash and proxy are still to be made -/// ([`super::links::give_placed`]); [`prepare`] has them made in the background. +/// A graphic placed from a file with preparation left ([`super::links::give_placed`]); +/// [`prepare`] makes the proxy and any deferred hash in the background. #[cfg_attr(target_arch = "wasm32", allow(dead_code))] pub(crate) struct Pending { key: SourceKey, bytes: Arc>, + hash: Option, page: u32, proxy: bool, } @@ -165,7 +166,7 @@ pub(crate) struct Pending { impl Pending { /// The work for `a`, linked with `bytes` just read from its file. Video and sound get no proxy. pub(super) fn of(a: &Asset, bytes: Arc>) -> Self { - Pending { key: a.data.key(), bytes, page: a.page, proxy: !media(a) } + Pending { key: a.data.key(), bytes, hash: a.link_hash.clone(), page: a.page, proxy: !media(a) } } } @@ -363,7 +364,7 @@ pub(crate) fn prepare(st: &mut DocState, pending: Vec) { { // Taken from the end: the first placed is made first, before checks still waiting. let work: Vec = - pending.into_iter().rev().map(|Pending { key, bytes, page, proxy }| Work::Prepare { key, bytes, page, proxy }).collect(); + pending.into_iter().rev().map(|Pending { key, bytes, hash, page, proxy }| Work::Prepare { key, bytes, hash, page, proxy }).collect(); let mut results = Vec::new(); if let Some(handle) = &st.links.job { let mut state = lock(&handle.0); @@ -469,8 +470,8 @@ fn check(work: Work, cancel: &AtomicBool) -> Option { let fingerprint = if super::links::settled(&before) { before } else { Fingerprint { size: len, mtime: super::links::UNVERIFIED_MTIME } }; Some(Outcome::Confirmed { asset, key, path, fingerprint, hash, proxy }) } - Work::Prepare { key, bytes, page, proxy } => { - let hash = hash_bytes(&bytes, cancel)?; + Work::Prepare { key, bytes, hash, page, proxy } => { + let hash = hash.or_else(|| hash_bytes(&bytes, cancel))?; if cancel.load(Ordering::Relaxed) { return None; } diff --git a/crates/engine/src/cmd/prefs.rs b/crates/engine/src/cmd/prefs.rs index f51ce3c70..956972b45 100644 --- a/crates/engine/src/cmd/prefs.rs +++ b/crates/engine/src/cmd/prefs.rs @@ -50,7 +50,7 @@ pub fn specs() -> Vec { "Preferences", [], None, - "{showHiddenCharacters?, typographersQuotes?, polygonSides?, starInset?, scaleStrokes?, dimensionsIncludeStroke?, transformationsAreTotals?, absolutePageNumbers?, highlightHj?, highlightKeeps?, highlightCustomTracking?, highlightSubstitutedFonts?, richBlackOutput?, favoriteFonts?: [family], recentFonts?: [family], showFontNamesInEnglish?, smartTextReflow?, autocorrect?, autocorrectList?: [[word, correction]], showAddedText?, showNoteAnchors?, cjkFeatures?: bool|null (CJK-only menu items and dialogs shown; null follows the interface language), linkTextFiles? (Create Links When Placing Text Files), recoveryMinutes?, recentFilesMax?: 0–100, defaultUnits?: {horizontalUnits?, verticalUnits?, rulerOrigin?, keyboardIncrement? (pt), kerningIncrement? (1/1000 em)} (Units & Increments of new documents)} → all application preferences", + "{showHiddenCharacters?, typographersQuotes?, polygonSides?, starInset?, scaleStrokes?, dimensionsIncludeStroke?, transformationsAreTotals?, absolutePageNumbers?, highlightHj?, highlightKeeps?, highlightCustomTracking?, highlightSubstitutedFonts?, richBlackOutput?, favoriteFonts?: [family], recentFonts?: [family], showFontNamesInEnglish?, smartTextReflow?, autocorrect?, autocorrectList?: [[word, correction]], showAddedText?, showNoteAnchors?, cjkFeatures?: bool|null (CJK-only menu items and dialogs shown; null follows the interface language), linkTextFiles? (Create Links When Placing Text Files), recoveryMinutes?, recentFilesMax?: 0–100, saveFormat?: designcraft|idml (Save documents as), defaultUnits?: {horizontalUnits?, verticalUnits?, rulerOrigin?, keyboardIncrement? (pt), kerningIncrement? (1/1000 em)} (Units & Increments of new documents)} → all application preferences", super::always, |s, p| { let cur = serde_json::to_value(&s.prefs).map_err(|e| bad("prefs.set", e.to_string()))?; diff --git a/crates/engine/src/cmd/text.rs b/crates/engine/src/cmd/text.rs index 813de0959..3399fea0e 100644 --- a/crates/engine/src/cmd/text.rs +++ b/crates/engine/src/cmd/text.rs @@ -17,9 +17,9 @@ mod opentype; mod story; use asian::{auto_tcy_cmd, grid_settings_cmd, kenten_cmd, ruby_cmd, shatai_cmd, warichu_cmd}; -pub(crate) use caret::story_of; use caret::{move_caret, para_bounds, place, release, select_around, select_at, sentence_bounds}; pub use caret::{next_char, next_word, prev_char, prev_word}; +pub(crate) use caret::{story_of, validated_story_of}; pub(crate) use edit::delete_selection; pub use edit::{PLACEHOLDER, quote_marks}; use edit::{change_case, delete, delete_surrounding, fill_placeholder, insert}; @@ -126,7 +126,7 @@ pub fn specs() -> Vec { "{story?, frame?: a text frame of the story, direction: leftToRight|rightToLeft} — column progression, independent of paragraph direction", has_doc, |s, p| { - let sid = story_of(s, p).ok_or_else(|| bad("story.setDirection", "no story"))?; + let sid = validated_story_of(s, p, "story.setDirection")?.ok_or_else(|| bad("story.setDirection", "no story"))?; let direction: designcraft_doc::TextDirection = serde_json::from_value(p.get("direction").cloned().ok_or_else(|| bad("story.setDirection", "missing direction"))?) .map_err(|e| bad("story.setDirection", e.to_string()))?; @@ -199,7 +199,7 @@ pub fn specs() -> Vec { ), cmd!(query "story.get", "Get Story", [], None, "{story? | frame?} → text, frames, paragraphs, vertical, lines, overset (the UTF-8 byte offset into `text` where it stops fitting its frames, not a character index, null when it all fits) and oversetChars (how many characters that leaves, as preflight reports them)", has_doc, |s, p| { let st = s.doc()?; - let sid = story_of(s, p).ok_or_else(|| bad("story.get", "no story"))?; + let sid = validated_story_of(s, p, "story.get")?.ok_or_else(|| bad("story.get", "no story"))?; let mut v = st.doc.story_summary(sid).ok_or(designcraft_doc::DocError::NoStory(sid))?; let cs = s.cache.get(&st.doc, sid, None); // `overset` is where the text stops fitting, not how much is left over: the two were @@ -608,3 +608,6 @@ mod alignment_shortcut_tests { assert_eq!(story_aligns(&s.doc().unwrap().doc, "Spring"), [Align::FullyJustified, Align::Left]); } } + +#[cfg(test)] +mod target_tests; diff --git a/crates/engine/src/cmd/text/caret.rs b/crates/engine/src/cmd/text/caret.rs index 29fa08cdc..7b2aeb5ce 100644 --- a/crates/engine/src/cmd/text/caret.rs +++ b/crates/engine/src/cmd/text/caret.rs @@ -15,6 +15,60 @@ pub(crate) fn story_of(s: &Session, p: &Value) -> Option { st.selection.text.map(|t| t.story) } +/// What a command that reads or edits a story was told to act on. +pub(crate) enum StoryTarget { + /// A story: named directly, or the story of a frame that holds text. + Story(StoryId), + /// An explicit frame that holds no text yet. Only Fill with Placeholder Text converts it. + TextlessFrame(ItemId), +} + +/// The `story` id `p` gives `cmd`, checked: it must be an unsigned integer naming a story. +/// +/// Ids come from callers and are hostile, and a target the document doesn't have is an error +/// rather than a quiet fall back to the selection, which read or edited another story (#1809). +fn explicit_story(doc: &designcraft_doc::Document, p: &Value, cmd: &str) -> Result> { + let Some(value) = p.get("story").filter(|v| !v.is_null()) else { return Ok(None) }; + let id = value.as_u64().ok_or_else(|| bad(cmd, "`story` must be an unsigned integer"))?; + let sid = StoryId(id); + if doc.story(sid).is_none() { + return Err(bad(cmd, format!("no such story {id}"))); + } + Ok(Some(sid)) +} + +/// The `frame` id `p` gives `cmd`, checked the same way, and what it holds: the story of a frame +/// that has text, or the frame itself when it has none. +fn explicit_frame(doc: &designcraft_doc::Document, p: &Value, cmd: &str) -> Result> { + let Some(value) = p.get("frame").filter(|v| !v.is_null()) else { return Ok(None) }; + let id = value.as_u64().ok_or_else(|| bad(cmd, "`frame` must be an unsigned integer"))?; + let item = doc.item(ItemId(id)).ok_or_else(|| bad(cmd, format!("no such frame {id}")))?; + Ok(Some(match item.text_frame() { + Some(t) => StoryTarget::Story(t.story), + None => StoryTarget::TextlessFrame(ItemId(id)), + })) +} + +/// The target `p` names for `cmd`, or `None` when it names neither and the selection decides. Both +/// ids are checked when both are given, even though `story` wins. +pub(crate) fn story_target(s: &Session, p: &Value, cmd: &str) -> Result> { + let doc = &s.doc()?.doc; + let story = explicit_story(doc, p, cmd)?; + let frame = explicit_frame(doc, p, cmd)?; + Ok(story.map(StoryTarget::Story).or(frame)) +} + +/// The story `cmd` acts on, from [`story_target`] or the selection. A frame that holds no text is +/// refused: only Fill with Placeholder Text converts one. +pub(crate) fn validated_story_of(s: &Session, p: &Value, cmd: &str) -> Result> { + let doc = &s.doc()?.doc; + explicit_story(doc, p, cmd)?; + if let Some(StoryTarget::TextlessFrame(fid)) = explicit_frame(doc, p, cmd)? { + return Err(bad(cmd, format!("frame {} holds no text", fid.0))); + } + Ok(story_of(s, p)) +} + /// Story byte at spread point `pt` in text frame `frame` (in a table cell's story when the point is in a cell). fn hit_byte(s: &Session, frame: ItemId, pt: Point) -> Option<(StoryId, usize, Option)> { hit_byte_with(s, frame, pt, compose::hit) diff --git a/crates/engine/src/cmd/text/edit.rs b/crates/engine/src/cmd/text/edit.rs index b8efeaf01..a2e481699 100644 --- a/crates/engine/src/cmd/text/edit.rs +++ b/crates/engine/src/cmd/text/edit.rs @@ -1,6 +1,6 @@ -use super::caret::{next_char, next_word, prev_char, prev_word, story_of}; +use super::caret::{StoryTarget, next_char, next_word, prev_char, prev_word, story_of, story_target}; use super::format::{apply_typing_format, format_targets, typing_format}; -use super::{Result, Session, TextSel, Value, bad, bool_or, compose, floor_char_boundary, id_param, json, ok, str_param}; +use super::{Result, Session, TextSel, Value, bad, bool_or, compose, floor_char_boundary, json, ok, str_param}; #[cfg(test)] use designcraft_doc::StoryId; @@ -381,15 +381,26 @@ dum sidera fulgent tacito per inane meatu. Arbore sub magna ludunt pueri, linquu Iamque tibi rursus ponet nova carmina vates, et longas umbras quaerit sub tegmine fagi. Omnia mutantur, nihil interit."; pub(super) fn fill_placeholder(s: &mut Session, p: &Value) -> Result { - let st = s.doc()?; - let frame = id_param(p, "frame").or_else(|| st.selection.items.first().copied()).or_else(|| st.selection.text.and_then(|t| t.frame)); - let sid = match frame.and_then(|f| st.doc.item(f)).and_then(|i| i.text_frame()) { - Some(t) => t.story, - None => { - if let Some(f) = frame { + const CMD: &str = "type.fillWithPlaceholder"; + // Every explicit id is checked before a frame is converted or a story filled (#1809). + let sid = match story_target(s, p, CMD)? { + Some(StoryTarget::Story(sid)) => sid, + target => { + // The frame the call names, else the selected frame: that order has always decided which + // story this command fills. A caret names no frame, only the story its text is in. + let frame = match target { + Some(StoryTarget::TextlessFrame(fid)) => Some(fid), + _ => { + let st = s.doc()?; + st.selection.items.first().copied().or_else(|| st.selection.text.and_then(|t| t.frame)) + } + }; + if let Some(f) = frame + && s.doc()?.doc.item(f).and_then(|i| i.text_frame()).is_none() + { s.execute("object.content", &json!({"ids": [f.0], "type": "text"}))?; } - story_of(s, p).ok_or_else(|| bad("type.fillWithPlaceholder", "select a text frame"))? + story_of(s, p).ok_or_else(|| bad(CMD, "select a text frame"))? } }; // Fill until overset with paragraphs of two to five sentences, as InDesign's placeholder text diff --git a/crates/engine/src/cmd/text/target_tests.rs b/crates/engine/src/cmd/text/target_tests.rs new file mode 100644 index 000000000..f7d1bed51 --- /dev/null +++ b/crates/engine/src/cmd/text/target_tests.rs @@ -0,0 +1,391 @@ +//! What `story.get`, `story.setDirection`, `type.fillWithPlaceholder` and `file.exportText` act on +//! when they are given a `story` or `frame` (#1809). An explicit id the document doesn't have is an +//! error: it used to fall back to the selection, so an edit landed on one story and an export wrote +//! another story's text. + +use designcraft_doc::{ItemId, StoryId}; +use serde_json::{Value, json}; + +use crate::Session; + +/// The commands that take an explicit story target. +const COMMANDS: [&str; 4] = ["file.exportText", "story.get", "story.setDirection", "type.fillWithPlaceholder"]; + +/// `p` with what a command needs to act on a story rather than only to report it. +fn acting(command: &str, mut p: Value) -> Value { + if command == "story.setDirection" { + p["direction"] = json!("rightToLeft"); + } + p +} + +/// Two stories on one page. `selected` (its text is "Selected") is selected, `other` ("Explicit") +/// is not, so a target that falls back to the selection shows. +struct Stories { + s: Session, + selected: Value, + other: Value, +} + +fn two_stories() -> Stories { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let selected = s.execute("frame.create", &json!({"rect": [0, 0, 300, 200], "content": "text", "text": "Selected"})).unwrap(); + let other = s.execute("frame.create", &json!({"rect": [0, 300, 300, 500], "content": "text", "text": "Explicit"})).unwrap(); + s.execute("selection.set", &json!({"ids": [selected["id"]]})).unwrap(); + Stories { s, selected, other } +} + +/// The first few characters of `text`, for an assertion message that a whole filler text would swamp. +fn start(text: &str) -> String { + text.chars().take(40).collect() +} + +/// The text of the story `frame` names. +fn story_text(s: &Session, frame: &Value) -> String { + let sid = StoryId(frame["story"].as_u64().unwrap()); + s.doc().unwrap().doc.story(sid).unwrap().text.clone() +} + +#[test] +fn a_target_the_document_does_not_have_is_an_error_not_the_selection() { + for command in COMMANDS { + let d = two_stories(); + let cases = [ + (json!({"story": 999999u64}), "no such story 999999"), + (json!({"frame": 999999u64}), "no such frame 999999"), + (json!({"story": d.selected["story"].clone(), "frame": 999999u64}), "no such frame 999999"), + (json!({"story": 999999u64, "frame": d.selected["id"].clone()}), "no such story 999999"), + ]; + let mut s = d.s; + for (p, message) in cases { + let before = s.doc().unwrap().doc.clone(); + let steps = s.doc().unwrap().history.undo.len(); + let error = s.execute(command, &acting(command, p.clone())).unwrap_err(); + assert!(error.to_string().contains(message), "{command} {p}: {error}"); + assert_eq!(s.doc().unwrap().doc, before, "{command} {p} acted on a story anyway"); + assert_eq!(s.doc().unwrap().history.undo.len(), steps, "{command} {p} left an undo step"); + } + } +} + +#[test] +fn a_target_that_is_not_an_unsigned_integer_is_an_error_not_the_selection() { + let not_ids = [json!("1"), json!("invalid"), json!(-1), json!(1.0), json!(1.5), json!(true), json!({}), json!([])]; + for command in COMMANDS { + for key in ["story", "frame"] { + let d = two_stories(); + let mut s = d.s; + for not_id in ¬_ids { + // Alone, and beside the other target the command could quietly use instead. + let usable = json!({"story": d.selected["story"].clone(), "frame": d.other["id"].clone()}); + for mut p in [json!({}), usable] { + p[key] = not_id.clone(); + let before = s.doc().unwrap().doc.clone(); + let steps = s.doc().unwrap().history.undo.len(); + let error = s.execute(command, &acting(command, p.clone())).unwrap_err(); + assert!(matches!(error, crate::EngineError::BadParams { .. }), "{command} {p}: {error}"); + let message = format!("`{key}` must be an unsigned integer"); + assert!(error.to_string().contains(&message), "{command} {p}: {error}"); + assert_eq!(s.doc().unwrap().doc, before, "{command} {p} acted on a story anyway"); + assert_eq!(s.doc().unwrap().history.undo.len(), steps, "{command} {p} left an undo step"); + } + } + } + } +} + +#[test] +fn an_explicit_target_wins_and_a_null_or_absent_one_uses_the_selection() { + for command in COMMANDS { + for case in ["story", "frame", "both", "null-story", "null-frame", "nulls", "absent"] { + let d = two_stories(); + let mut s = d.s; + let p = match case { + "story" => json!({"story": d.other["story"]}), + "frame" => json!({"frame": d.other["id"]}), + "both" => json!({"story": d.other["story"], "frame": d.selected["id"]}), + "null-story" => json!({"story": null, "frame": d.other["id"]}), + "null-frame" => json!({"story": d.other["story"], "frame": null}), + "nulls" => json!({"story": null, "frame": null}), + _ => json!({}), + }; + let explicit = !matches!(case, "nulls" | "absent"); + let (target, untouched) = if explicit { (&d.other, &d.selected) } else { (&d.selected, &d.other) }; + let untouched_before = s.doc().unwrap().doc.story(StoryId(untouched["story"].as_u64().unwrap())).unwrap().clone(); + let before = s.doc().unwrap().doc.clone(); + let steps = s.doc().unwrap().history.undo.len(); + let result = s.execute(command, &acting(command, p)).unwrap_or_else(|e| panic!("{command} {case}: {e}")); + match command { + "story.get" | "file.exportText" => { + let expected = if explicit { "Explicit" } else { "Selected" }; + assert_eq!(result["text"], expected, "{command} {case}"); + } + "story.setDirection" => { + let direction = s.execute("story.get", &json!({"story": target["story"]})).unwrap()["direction"].clone(); + assert_eq!(direction, "rightToLeft", "{command} {case}"); + } + _ => { + let filled = story_text(&s, target); + assert!(filled.len() > 500 && filled != "Selected" && filled != "Explicit", "{command} {case}: {}", start(&filled)); + } + } + assert_eq!( + *s.doc().unwrap().doc.story(StoryId(untouched["story"].as_u64().unwrap())).unwrap(), + untouched_before, + "{command} {case} acted on the other story" + ); + if matches!(command, "story.get" | "file.exportText") { + assert_eq!(s.doc().unwrap().doc, before, "{command} {case} changed the document"); + assert_eq!(s.doc().unwrap().history.undo.len(), steps, "{command} {case} left an undo step"); + } else { + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "{command} {case} is one undo step"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc, before, "undo takes {command} {case} back"); + } + } + } +} + +#[test] +fn a_frame_that_holds_no_text_is_refused_except_by_placeholder_text() { + for command in ["file.exportText", "story.get", "story.setDirection"] { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let text = s.execute("frame.create", &json!({"rect": [0, 0, 300, 200], "content": "text", "text": "Selected"})).unwrap(); + let graphic = s.execute("frame.create", &json!({"rect": [0, 300, 300, 500], "content": "graphic"})).unwrap(); + s.execute("selection.set", &json!({"ids": [text["id"]]})).unwrap(); + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("refused.txt"); + for mut p in [json!({"frame": graphic["id"]}), json!({"story": text["story"], "frame": graphic["id"]})] { + if command == "file.exportText" { + p["path"] = json!(path.to_string_lossy()); + } + let before = s.doc().unwrap().doc.clone(); + let error = s.execute(command, &acting(command, p.clone())).unwrap_err(); + // The message names the case, and nothing was read, edited or written. + assert!(error.to_string().contains(&format!("frame {} holds no text", graphic["id"])), "{command} {p}: {error}"); + assert_eq!(s.doc().unwrap().doc, before, "{command} {p} changed the document"); + assert!(!path.exists(), "{command} {p} wrote a file"); + } + } +} + +#[test] +fn export_with_a_story_and_a_frame_without_text_writes_nothing() { + // The case that exports another story's text on pre-fix behaviour: a valid story makes the call + // look fine, so a frame that holds no text was quietly ignored and the export went ahead. + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let text = s.execute("frame.create", &json!({"rect": [0, 0, 300, 200], "content": "text", "text": "Selected"})).unwrap(); + let graphic = s.execute("frame.create", &json!({"rect": [0, 300, 300, 500], "content": "graphic"})).unwrap(); + s.execute("selection.set", &json!({"ids": [text["id"]]})).unwrap(); + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("wrong-story.txt"); + let result = s.execute("file.exportText", &json!({"path": path.to_string_lossy(), "story": text["story"], "frame": graphic["id"]})); + assert!(result.is_err(), "the frame that holds no text must be refused: {result:?}"); + assert!(!path.exists(), "and nothing may be written"); +} + +#[test] +fn placeholder_text_converts_an_explicit_frame_that_holds_no_text() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let text = s.execute("frame.create", &json!({"rect": [0, 0, 300, 200], "content": "text", "text": "Selected"})).unwrap(); + let graphic = s.execute("frame.create", &json!({"rect": [0, 300, 300, 900], "content": "graphic"})).unwrap(); + s.execute("selection.set", &json!({"ids": [text["id"]]})).unwrap(); + let before = s.doc().unwrap().doc.clone(); + let steps = s.doc().unwrap().history.undo.len(); + s.execute("type.fillWithPlaceholder", &json!({"frame": graphic["id"]})).unwrap(); + let converted = ItemId(graphic["id"].as_u64().unwrap()); + let sid = s.doc().unwrap().doc.item(converted).and_then(|i| i.text_frame().map(|t| t.story)); + let filled = sid.and_then(|sid| s.doc().unwrap().doc.story(sid).cloned()); + let filled = filled.expect("the frame became a text frame"); + assert!(filled.text.len() > 500 && filled.text != "Selected", "the converted frame is filled: {}", start(&filled.text)); + assert_eq!(story_text(&s, &text), "Selected", "the selection is untouched"); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "converting and filling is one undo step"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc, before); +} + +#[test] +fn placeholder_text_fills_an_explicit_story_and_leaves_a_textless_frame_alone() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let selected = s.execute("frame.create", &json!({"rect": [0, 0, 300, 200], "content": "text", "text": "Selected"})).unwrap(); + let other = s.execute("frame.create", &json!({"rect": [0, 300, 300, 900], "content": "text", "text": "Explicit"})).unwrap(); + let graphic = s.execute("frame.create", &json!({"rect": [400, 0, 700, 200], "content": "graphic"})).unwrap(); + s.execute("selection.set", &json!({"ids": [selected["id"]]})).unwrap(); + s.execute("type.fillWithPlaceholder", &json!({"story": other["story"], "frame": graphic["id"]})).unwrap(); + let filled = story_text(&s, &other); + assert!(filled.len() > 500 && filled != "Explicit", "the story the call names is filled: {}", start(&filled)); + assert_eq!(story_text(&s, &selected), "Selected", "the selection is untouched"); + let left = ItemId(graphic["id"].as_u64().unwrap()); + assert!( + s.doc().unwrap().doc.item(left).and_then(|i| i.text_frame()).is_none(), + "a frame that holds no text stays as it is when a story is named" + ); +} + +#[test] +fn placeholder_text_fills_the_story_of_a_caret_with_no_frame() { + // `text.select` leaves `Selection::text` with `frame: None`, so a caret names no frame at all. + for p in [json!({}), json!({"story": null, "frame": null}), json!({"story": null}), json!({"frame": null})] { + let d = two_stories(); + let mut s = d.s; + s.execute("text.select", &json!({"story": d.selected["story"], "anchor": 0})).unwrap(); + let (items, frame) = { + let st = s.doc().unwrap(); + (st.selection.items.len(), st.selection.text.and_then(|t| t.frame)) + }; + assert_eq!(items, 0, "the caret replaces the object selection"); + assert!(frame.is_none(), "and names no frame"); + let other = story_text(&s, &d.other); + let steps = s.doc().unwrap().history.undo.len(); + s.execute("type.fillWithPlaceholder", &p).unwrap_or_else(|e| panic!("{p}: {e}")); + let filled = story_text(&s, &d.selected); + assert!(filled.len() > 500 && filled != "Selected", "{p}: the caret's story is filled: {}", start(&filled)); + assert_eq!(story_text(&s, &d.other), other, "{p}: the other story is untouched"); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "{p}: one undo step"); + } +} + +#[test] +fn placeholder_text_checks_its_target_before_converting_a_frame() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let text = s.execute("frame.create", &json!({"rect": [0, 0, 300, 200], "content": "text", "text": "Selected"})).unwrap(); + let empty = s.execute("frame.create", &json!({"rect": [0, 300, 300, 500], "content": "unassigned"})).unwrap(); + s.execute("selection.set", &json!({"ids": [text["id"]]})).unwrap(); + let before = s.doc().unwrap().doc.clone(); + let steps = s.doc().unwrap().history.undo.len(); + // The frame could become a text frame, but the story the call names does not exist: refusing + // leaves the frame unassigned rather than converting it and then failing. + let error = s.execute("type.fillWithPlaceholder", &json!({"frame": empty["id"], "story": 999999u64})).unwrap_err(); + assert_eq!(s.doc().unwrap().doc, before, "the frame must not be converted"); + assert_eq!(s.doc().unwrap().history.undo.len(), steps, "and no step may be left behind"); + assert!(error.to_string().contains("no such story 999999"), "{error}"); +} + +#[test] +fn explicit_story_targets_do_not_need_a_selection() { + for command in COMMANDS { + for key in ["story", "frame"] { + let d = two_stories(); + let mut s = d.s; + s.execute("selection.set", &json!({"ids": []})).unwrap(); + assert!(s.doc().unwrap().selection.items.is_empty()); + assert!(s.doc().unwrap().selection.text.is_none()); + let spec = crate::cmd::find_command(command).unwrap(); + let selection_gated = matches!(command, "file.exportText" | "type.fillWithPlaceholder"); + if selection_gated { + assert!((spec.enabled)(&s).is_err(), "{command}: its menu still needs a selection"); + } + let p = if key == "story" { json!({"story": d.other["story"]}) } else { json!({"frame": d.other["id"]}) }; + let before = s.doc().unwrap().doc.clone(); + let steps = s.doc().unwrap().history.undo.len(); + let result = s.execute(command, &acting(command, p)).unwrap_or_else(|e| panic!("{command} {key}: {e}")); + assert_eq!(story_text(&s, &d.selected), "Selected", "{command} {key}: the other story is untouched"); + match command { + "file.exportText" | "story.get" => { + assert_eq!(result["text"], "Explicit", "{command} {key}"); + assert_eq!(s.doc().unwrap().doc, before); + assert_eq!(s.doc().unwrap().history.undo.len(), steps); + } + _ => { + if command == "story.setDirection" { + let direction = s.execute("story.get", &json!({"story": d.other["story"]})).unwrap()["direction"].clone(); + assert_eq!(direction, "rightToLeft"); + } else { + assert!(story_text(&s, &d.other).len() > 500); + } + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc, before); + } + } + if selection_gated { + assert!((spec.enabled)(&s).is_err(), "{command}: executing an explicit target did not relax its menu"); + } + } + } +} + +#[test] +fn invalid_explicit_story_targets_without_a_selection_reach_validation() { + for command in COMMANDS { + let d = two_stories(); + let mut s = d.s; + s.execute("selection.set", &json!({"ids": []})).unwrap(); + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("unchanged.txt"); + std::fs::write(&path, "keep this file").unwrap(); + for mut p in [ + json!({"story": 999999u64}), + json!({"frame": 999999u64}), + json!({"story": "invalid"}), + json!({"frame": "invalid"}), + json!({"story": d.other["story"], "frame": 999999u64}), + json!({"story": 999999u64, "frame": d.other["id"]}), + ] { + if command == "file.exportText" { + p["path"] = json!(path.to_string_lossy()); + } + let st = s.doc().unwrap(); + let before = st.doc.clone(); + let saved = st.saved_doc.clone(); + let quiet = (st.revision, st.saved_revision, st.is_dirty(), st.selection.clone(), st.history.undo.len(), st.history.redo.len()); + let journal = s.journal.len(); + let error = s.execute(command, &acting(command, p.clone())).unwrap_err(); + assert!(matches!(error, crate::EngineError::BadParams { .. }), "{command} {p}: {error}"); + let st = s.doc().unwrap(); + assert!(std::sync::Arc::ptr_eq(&st.doc, &before), "{command} {p}: live document identity changed"); + assert!(std::sync::Arc::ptr_eq(&st.saved_doc, &saved), "{command} {p}: saved document identity changed"); + assert_eq!((st.revision, st.saved_revision, st.is_dirty(), st.selection.clone(), st.history.undo.len(), st.history.redo.len()), quiet); + assert_eq!(s.journal.len(), journal); + assert_eq!(std::fs::read_to_string(&path).unwrap(), "keep this file", "{command} {p}: export wrote before refusing"); + } + } +} + +#[test] +fn placeholder_conversion_does_not_need_a_selection() { + for content in ["graphic", "unassigned"] { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let frame = s.execute("frame.create", &json!({"rect": [0, 0, 300, 500], "content": content})).unwrap(); + s.execute("selection.set", &json!({"ids": []})).unwrap(); + let before = s.doc().unwrap().doc.clone(); + let steps = s.doc().unwrap().history.undo.len(); + let spec = crate::cmd::find_command("type.fillWithPlaceholder").unwrap(); + assert!((spec.enabled)(&s).is_err(), "the menu remains selection-based"); + s.execute("type.fillWithPlaceholder", &json!({"frame": frame["id"]})).unwrap(); + let item = s.doc().unwrap().doc.item(ItemId(frame["id"].as_u64().unwrap())).unwrap(); + let story = item.text_frame().unwrap().story; + assert!(s.doc().unwrap().doc.story(story).unwrap().text.len() > 500); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc, before, "one Undo restores the original frame"); + } +} + +#[test] +fn selection_gates_still_apply_without_an_explicit_story_target_or_document() { + for command in ["file.exportText", "type.fillWithPlaceholder"] { + let d = two_stories(); + let mut s = d.s; + s.execute("selection.set", &json!({"ids": []})).unwrap(); + for p in [json!({}), json!({"story": null}), json!({"frame": null}), json!({"story": null, "frame": null})] { + let before = s.doc().unwrap().doc.clone(); + let error = s.execute(command, &p).unwrap_err(); + assert!(matches!(error, crate::EngineError::Disabled(..)), "{command} {p}: {error}"); + assert!(std::sync::Arc::ptr_eq(&s.doc().unwrap().doc, &before)); + } + let mut empty = Session::new(); + for p in [json!({"story": 1}), json!({"frame": 1})] { + let error = empty.execute(command, &p).unwrap_err(); + assert!(matches!(error, crate::EngineError::Disabled(..)), "{command} without a document: {error}"); + assert!(empty.active().is_none()); + } + } +} diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index a095a14ff..610e41ee6 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -258,6 +258,9 @@ pub struct Prefs { pub recent_files: Vec, /// Preferences › File Handling › Number of Recent Items to Display (0 keeps no list). pub recent_files_max: u32, + /// Preferences › File Handling › Save documents as: the format Save suggests for a new + /// document, and, as IDML, an opened `.idml` file is saved back to itself. + pub save_format: SaveFormat, /// Preferences › Units & Increments set with no document open: what new documents start /// with, as InDesign's application defaults. A document keeps its own once made. pub default_units: DefaultUnits, @@ -336,6 +339,33 @@ impl Prefs { } } +/// The format a document is saved in (Preferences › File Handling). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum SaveFormat { + /// DesignCraft's own `.designcraft` package. + #[default] + Designcraft, + /// InDesign Markup (`.idml`), with the images embedded. + Idml, +} + +impl SaveFormat { + /// The file extension, without its dot. + pub fn extension(self) -> &'static str { + match self { + SaveFormat::Designcraft => "designcraft", + SaveFormat::Idml => "idml", + } + } + + /// The format a file at `path` is written in: IDML for a `.idml` name, else DesignCraft's own. + pub fn of_path(path: &str) -> SaveFormat { + let idml = std::path::Path::new(path).extension().is_some_and(|e| e.eq_ignore_ascii_case("idml")); + if idml { SaveFormat::Idml } else { SaveFormat::Designcraft } + } +} + /// A starter autocorrect list (common English typing slips). pub fn default_autocorrect() -> Vec<(String, String)> { [ @@ -388,6 +418,7 @@ impl Default for Prefs { link_text_files: false, recent_files: Vec::new(), recent_files_max: 20, + save_format: SaveFormat::Designcraft, default_units: DefaultUnits::default(), } } @@ -719,6 +750,14 @@ impl Session { /// Fails with `Disabled` unless the command is enabled or names objects or a table it can act on. fn check_enabled(&self, spec: &CommandSpec, id: &str, params: &Value) -> Result<()> { if let Err(e) = (spec.enabled)(self) { + // Explicit story/frame targets do not need a selection. Keep menu enablement + // selection-based; these handlers validate even malformed non-null targets. + if matches!(id, "file.exportText" | "type.fillWithPlaceholder") + && self.active().is_some() + && ["story", "frame"].iter().any(|key| params.get(*key).is_some_and(|v| !v.is_null())) + { + return Ok(()); + } // A table command that takes `story` and `table` acts on the table the call names, so // the selection doesn't matter: with nothing selected, the caret outside a table, or // selected rows the command can't act on, `{"table": 3}` still runs. diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 352a17a78..7d744edbe 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -217,24 +217,24 @@ fn a_command_that_fails_partway_strands_no_edits() { assert_eq!(s.doc().unwrap().history.undo.len(), 1); } -/// The same for a command that fails after a command it ran changed the document: that one -/// leaves the step to it, so it has to record one. +/// The same for a command that fails after a command it ran changed the document: that one leaves the +/// step to it, so it has to record one. `test.nestedFailure` is test-only scaffolding (`cmd.rs`): no +/// shipping command fails after a nested edit, now that Fill with Placeholder Text checks its target +/// before converting a frame. #[test] fn a_command_that_fails_after_the_one_it_ran_can_be_undone() { let mut s = session(); let empty = s.execute("frame.create", &json!({"rect": [36, 36, 136, 136], "content": "unassigned"})).unwrap()["id"].clone(); - let text = s.execute("frame.create", &json!({"rect": [36, 300, 300, 400], "content": "text", "text": "abc"})).unwrap()["id"].clone(); - s.execute("selection.set", &json!({"ids": [text]})).unwrap(); let (before, steps) = { let st = s.doc().unwrap(); (st.doc.clone(), st.history.undo.len()) }; - // Fill with Placeholder Text turns the empty frame into a text frame, then finds no such story. - assert!(s.execute("type.fillWithPlaceholder", &json!({"frame": empty, "story": 99999})).is_err()); + // It turns the empty frame into a text frame, then fails. + assert!(s.execute("test.nestedFailure", &json!({"ids": [empty]})).is_err()); let st = s.doc().unwrap(); assert_ne!(st.doc, before, "the frame was converted"); assert_eq!(st.history.undo.len(), steps + 1); - assert_eq!(st.history.undo.last().unwrap().label, "Fill with Placeholder Text"); + assert_eq!(st.history.undo.last().unwrap().label, "Nested Failure"); s.execute("edit.undo", &json!({})).unwrap(); assert_eq!(s.doc().unwrap().doc, before); } diff --git a/crates/engine/tests/it/layer_delete_unused.rs b/crates/engine/tests/it/layer_delete_unused.rs new file mode 100644 index 000000000..3b77b16b7 --- /dev/null +++ b/crates/engine/tests/it/layer_delete_unused.rs @@ -0,0 +1,138 @@ +//! Synthetic artwork created through our public commands and document APIs; no external fixtures. + +use std::sync::Arc; + +use designcraft_doc::{AnchoredObject, Document, ItemId, LayerId, Story, StoryId, Table}; +use designcraft_engine::Session; +use designcraft_render::Renderer; +use serde_json::json; + +fn new_session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"pages": 1, "facingPages": false, "width": 240, "height": 240})).unwrap(); + s +} + +fn new_layer(s: &mut Session, name: &str) -> LayerId { + LayerId(s.execute("layer.new", &json!({"name": name})).unwrap()["id"].as_u64().unwrap()) +} + +fn rectangle(s: &mut Session, rect: [i32; 4]) -> u64 { + let id = s.execute("frame.create", &json!({"rect": rect, "content": "unassigned"})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.fill", &json!({"ids": [id], "swatch": "[Black]"})).unwrap(); + id +} + +fn dark_coverage(s: &Session) -> usize { + let image = Renderer::new().render_page(&s.doc().unwrap().doc, &s.cache, 0, 1.0, false, &Default::default()).unwrap(); + image.pixels.as_chunks::<4>().0.iter().filter(|p| p[..3].iter().any(|c| *c < 220)).count() +} + +/// Every object on spreads, parents and in stories (group children and anchored objects included) is on a layer the +/// document has. +fn assert_every_object_on_a_live_layer(d: &Document) { + for sp in d.spreads.iter().chain(&d.parents) { + for it in &sp.items { + it.walk(&mut |i| assert!(d.layer(i.layer).is_some(), "object {} is on missing layer {:?}", i.id.0, i.layer)); + } + } + for (_, i) in d.anchored_items() { + assert!(d.layer(i.layer).is_some(), "anchored object {} is on missing layer {:?}", i.id.0, i.layer); + } + d.check().unwrap(); +} + +#[test] +fn a_layer_used_only_by_a_grouped_object_is_kept() { + let mut s = new_session(); + let base = s.doc().unwrap().active_layer; + let small = rectangle(&mut s, [10, 10, 20, 20]); + let child_layer = new_layer(&mut s, "Grouped only"); + let large = rectangle(&mut s, [30, 30, 210, 210]); + s.execute("selection.set", &json!({"ids": [small, large]})).unwrap(); + let group = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap(); + // The group takes the layer of its backmost object, so only its child is on the other layer. + let d = &s.doc().unwrap().doc; + assert_eq!(d.item(ItemId(group)).unwrap().layer, base); + assert_eq!(d.item(ItemId(large)).unwrap().layer, child_layer); + let baseline = dark_coverage(&s); + assert!(baseline > 0, "the fixture must show artwork"); + + s.execute("layer.deleteUnused", &json!({})).unwrap(); + let d = &s.doc().unwrap().doc; + assert!(d.layer(child_layer).is_some(), "the grouped object's layer is in use"); + assert_every_object_on_a_live_layer(d); + // Ungrouping puts the child on the page on its own layer: it must still draw. + s.execute("object.ungroup", &json!({"ids": [group]})).unwrap(); + assert_every_object_on_a_live_layer(&s.doc().unwrap().doc); + assert!(dark_coverage(&s) >= baseline * 3 / 4, "the large grouped rectangle must still draw"); + + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("delete-unused.designcraft"); + s.execute("file.saveAs", &json!({"path": path})).unwrap(); + let mut reopened = Session::new(); + reopened.execute("file.open", &json!({"path": path})).unwrap(); + assert_every_object_on_a_live_layer(&reopened.doc().unwrap().doc); + assert!(dark_coverage(&reopened) >= baseline * 3 / 4, "the reopened document must still draw it"); +} + +#[test] +fn layers_used_only_by_anchored_objects_are_kept() { + let mut s = new_session(); + let host = s.execute("frame.create", &json!({"rect": [10, 100, 200, 220], "content": "text", "text": "Host"})).unwrap(); + let sid = StoryId(host["story"].as_u64().unwrap()); + let inline_layer = new_layer(&mut s, "Anchored only"); + let inline = rectangle(&mut s, [10, 10, 20, 20]); + s.execute("anchored.insert", &json!({"ids": [inline], "story": sid.0, "pos": 0})).unwrap(); + let nested_layer = new_layer(&mut s, "Anchored in an endnote of a footnote of a cell"); + let nested = rectangle(&mut s, [30, 10, 40, 20]); + // Move the second object into the nested story containers native import makes. + s.edit(|d, _| { + let it = d.item(ItemId(nested)).unwrap().clone(); + Arc::make_mut(&mut d.spreads[0]).items.retain(|i| i.id.0 != nested); + let mut table = Table::new(d.alloc(), 1, 1, 0, 0, 40.0); + let cell = &mut table.cells[0].text; + cell.insert_note(cell.len(), "Footnote", Default::default()).unwrap(); + let note: &mut Story = &mut Arc::make_mut(&mut cell.notes[0]).text; + note.insert_endnote(note.len(), "Endnote", Default::default()).unwrap(); + Arc::make_mut(&mut note.endnotes[0]).text.insert_object(0, AnchoredObject::new(it, Default::default())); + d.story_mut(sid).unwrap().insert_table(0, table); + Ok(()) + }) + .unwrap(); + let unused = new_layer(&mut s, "Unused"); + let d = &s.doc().unwrap().doc; + d.check().unwrap(); + assert_eq!(d.anchored_item(ItemId(inline)).unwrap().layer, inline_layer); + assert_eq!(d.anchored_item(ItemId(nested)).unwrap().layer, nested_layer); + + s.execute("layer.deleteUnused", &json!({})).unwrap(); + let d = s.doc().unwrap().doc.clone(); + assert!(d.layer(inline_layer).is_some(), "the anchored object's layer is in use"); + assert!(d.layer(nested_layer).is_some(), "the nested anchored object's layer is in use"); + assert!(d.layer(unused).is_none(), "a layer nothing is on still goes"); + assert_every_object_on_a_live_layer(&d); + let reopened = designcraft_format::load(&designcraft_format::save(&d).unwrap()).unwrap(); + assert_every_object_on_a_live_layer(&reopened); +} + +#[test] +fn unused_layers_go_and_one_layer_always_stays() { + let mut s = new_session(); + let base = s.doc().unwrap().active_layer; + rectangle(&mut s, [10, 10, 20, 20]); + let unused = new_layer(&mut s, "Unused"); + s.execute("layer.deleteUnused", &json!({})).unwrap(); + let d = &s.doc().unwrap().doc; + assert!(d.layer(unused).is_none()); + assert!(d.layer(base).is_some()); + + // With nothing anywhere, every layer is unused but the document keeps one. + let mut s = new_session(); + new_layer(&mut s, "Empty"); + new_layer(&mut s, "Also empty"); + s.execute("layer.deleteUnused", &json!({})).unwrap(); + let d = &s.doc().unwrap().doc; + assert_eq!(d.layers.len(), 1); + assert!(d.layer(s.doc().unwrap().active_layer).is_some(), "drawing continues on the remaining layer"); +} diff --git a/crates/engine/tests/it/layer_merge_descendants.rs b/crates/engine/tests/it/layer_merge_descendants.rs new file mode 100644 index 000000000..001736df5 --- /dev/null +++ b/crates/engine/tests/it/layer_merge_descendants.rs @@ -0,0 +1,235 @@ +//! Synthetic artwork created through our public commands and document APIs; no external fixtures. + +use std::sync::Arc; + +use designcraft_doc::{AnchoredObject, Document, Item, ItemId, LayerId, Story, Table}; +use designcraft_engine::Session; +use designcraft_render::Renderer; +use serde_json::json; + +fn new_session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"pages": 1, "facingPages": false, "width": 240, "height": 240})).unwrap(); + s +} + +fn rectangle(s: &mut Session, rect: [i32; 4]) -> u64 { + let id = s.execute("frame.create", &json!({"rect": rect, "content": "unassigned"})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.fill", &json!({"ids": [id], "swatch": "[Black]"})).unwrap(); + id +} + +fn group(s: &mut Session, ids: &[u64]) -> u64 { + s.execute("selection.set", &json!({"ids": ids})).unwrap(); + s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap() +} + +fn dark_coverage(s: &Session) -> usize { + let image = Renderer::new().render_page(&s.doc().unwrap().doc, &s.cache, 0, 1.0, false, &Default::default()).unwrap(); + image.pixels.as_chunks::<4>().0.iter().filter(|p| p[..3].iter().any(|c| *c < 220)).count() +} + +fn items(d: &Document) -> Vec<&Item> { + let mut out = Vec::new(); + for sp in d.spreads.iter().chain(&d.parents) { + for it in &sp.items { + it.walk(&mut |i| out.push(i)); + } + } + out.extend(d.anchored_items().into_iter().map(|(_, i)| i)); + out +} + +fn assert_remapped(before: &Document, after: &Document, source: LayerId, destination: LayerId) { + let old_items = items(before); + let new_items = items(after); + assert_eq!(old_items.len(), new_items.len(), "merging must not remove descendants"); + for old in old_items { + let new = new_items.iter().find(|i| i.id == old.id).unwrap(); + assert_eq!(new.layer, if old.layer == source { destination } else { old.layer }, "only removed-layer references move"); + assert!(after.layer(new.layer).is_some(), "every descendant must keep a live layer"); + assert_eq!(new.path, old.path); + assert_eq!(new.xf, old.xf); + assert_eq!(new.fill, old.fill); + assert_eq!(new.stroke, old.stroke); + assert_eq!(new.bounds(), old.bounds()); + } + after.check().unwrap(); +} + +#[test] +fn merging_grouped_artwork_survives_ungroup_undo_redo_and_native_reopen() { + let mut s = new_session(); + let destination = s.doc().unwrap().active_layer; + let source = LayerId(s.execute("layer.new", &json!({"name": "Grouped artwork"})).unwrap()["id"].as_u64().unwrap()); + let a = rectangle(&mut s, [30, 30, 90, 90]); + let b = rectangle(&mut s, [110, 30, 170, 90]); + let g = group(&mut s, &[a, b]); + let before_merge = s.doc().unwrap().doc.clone(); + let baseline = dark_coverage(&s); + assert!(baseline > 0, "fixture must contain visible artwork"); + + s.execute("layer.merge", &json!({"ids": [destination.0, source.0], "into": destination.0})).unwrap(); + let after_merge = s.doc().unwrap().doc.clone(); + assert_remapped(&before_merge, &after_merge, source, destination); + s.execute("object.ungroup", &json!({"ids": [g]})).unwrap(); + let after_ungroup = s.doc().unwrap().doc.clone(); + for id in [a, b] { + let mut expected = before_merge.item(ItemId(id)).unwrap().clone(); + expected.layer = destination; + assert_eq!(after_ungroup.item(ItemId(id)), Some(&expected), "promoted artwork preserves identity and geometry"); + } + assert!(dark_coverage(&s) >= baseline / 2, "Ungroup must not hide the merged artwork"); + + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc, after_merge); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc, before_merge); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc, after_merge); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc, after_ungroup); + + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("merged-artwork.designcraft"); + s.execute("file.saveAs", &json!({"path": path})).unwrap(); + let mut reopened = Session::new(); + reopened.execute("file.open", &json!({"path": path})).unwrap(); + let doc = &reopened.doc().unwrap().doc; + for id in [a, b] { + let it = doc.item(ItemId(id)).unwrap(); + assert_eq!(it, after_ungroup.item(ItemId(id)).unwrap()); + assert!(doc.layer(it.layer).is_some()); + } + assert!(dark_coverage(&reopened) >= baseline / 2, "native reopen must preserve visible artwork"); +} + +#[test] +fn merging_reaches_nested_groups_on_surviving_document_and_parent_layers() { + let mut s = new_session(); + let destination = s.doc().unwrap().active_layer; + let survivor = LayerId(s.execute("layer.new", &json!({"name": "Keep separate"})).unwrap()["id"].as_u64().unwrap()); + let a = rectangle(&mut s, [10, 10, 30, 30]); + let source = LayerId(s.execute("layer.new", &json!({"name": "Merge away"})).unwrap()["id"].as_u64().unwrap()); + let b = rectangle(&mut s, [40, 10, 60, 30]); + let inner = group(&mut s, &[a, b]); + s.execute("layer.activate", &json!({"id": destination.0})).unwrap(); + let c = rectangle(&mut s, [70, 10, 90, 30]); + let outer = group(&mut s, &[inner, c]); + // The root is on a surviving layer, but a grandchild references the layer being deleted. + assert_eq!(s.doc().unwrap().doc.item(ItemId(outer)).unwrap().layer, survivor); + s.execute("layer.activate", &json!({"id": survivor.0})).unwrap(); + let p = s.execute("frame.create", &json!({"spread": {"kind": "parent", "index": 0}, "rect": [10, 50, 30, 70]})).unwrap()["id"].as_u64().unwrap(); + s.execute("layer.activate", &json!({"id": source.0})).unwrap(); + let q = s.execute("frame.create", &json!({"spread": {"kind": "parent", "index": 0}, "rect": [40, 50, 60, 70]})).unwrap()["id"].as_u64().unwrap(); + group(&mut s, &[p, q]); + let before = s.doc().unwrap().doc.clone(); + + assert_eq!(s.doc().unwrap().active_layer, source); + + s.execute("layer.merge", &json!({"ids": [source.0], "into": destination.0})).unwrap(); + let merged = s.doc().unwrap().doc.clone(); + assert_remapped(&before, &merged, source, destination); + // Drawing continues on the layer that received the merged objects, not on whichever layer is on top. + assert_eq!(s.doc().unwrap().active_layer, destination); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc, before); + assert!(s.doc().unwrap().doc.layer(s.doc().unwrap().active_layer).is_some(), "Undo leaves a live active layer"); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc, merged); + assert_eq!(s.doc().unwrap().active_layer, destination); + s.execute("object.ungroup", &json!({"ids": [outer]})).unwrap(); + s.execute("object.ungroup", &json!({"ids": [inner]})).unwrap(); + let ungrouped = &s.doc().unwrap().doc; + assert_eq!(ungrouped.item(ItemId(a)).unwrap().layer, survivor); + assert_eq!(ungrouped.item(ItemId(b)).unwrap().layer, destination); + assert_eq!(ungrouped.item(ItemId(c)).unwrap().layer, destination); +} + +#[test] +fn merging_copies_only_containers_that_reference_a_merged_layer() { + let mut s = Session::new(); + s.execute("file.new", &json!({"pages": 2, "facingPages": false})).unwrap(); + let destination = s.doc().unwrap().active_layer; + rectangle(&mut s, [10, 10, 30, 30]); + let text = s.execute("frame.create", &json!({"rect": [10, 50, 200, 300], "content": "text", "text": "Untouched"})).unwrap(); + let (frame, story) = (ItemId(text["id"].as_u64().unwrap()), designcraft_doc::StoryId(text["story"].as_u64().unwrap())); + // An auto-size frame left at a size that doesn't fit its text, as a file can open: an edit that + // needlessly copies its story makes Auto-Size refit it and move artwork on an untouched layer. + s.edit(|d, _| { + if let Some(designcraft_doc::Content::Text(tf)) = d.item_mut(frame).map(|i| &mut i.content) { + tf.options.auto_size = designcraft_doc::AutoSize::HeightOnly; + } + Ok(()) + }) + .unwrap(); + assert!(designcraft_engine::autosize::fitted(&s.doc().unwrap().doc, frame, story).is_some(), "the fixture frame must be stale"); + let source = LayerId(s.execute("layer.new", &json!({"name": "Merge away"})).unwrap()["id"].as_u64().unwrap()); + s.execute("frame.create", &json!({"spread": 1, "rect": [10, 10, 30, 30]})).unwrap(); + let before = s.doc().unwrap().doc.clone(); + + s.execute("layer.merge", &json!({"ids": [source.0], "into": destination.0})).unwrap(); + let after = s.doc().unwrap().doc.clone(); + assert_remapped(&before, &after, source, destination); + // Untouched spreads, parents and stories stay shared with the undo snapshot instead of being deep-copied. + assert!(Arc::ptr_eq(&before.spreads[0], &after.spreads[0])); + assert!(before.parents.iter().zip(&after.parents).all(|(b, a)| Arc::ptr_eq(b, a))); + assert!(before.stories.iter().all(|(id, st)| Arc::ptr_eq(st, &after.stories[id]))); + assert!(!Arc::ptr_eq(&before.spreads[1], &after.spreads[1]), "the spread holding the merged object changes"); + assert_eq!(after.item(frame), before.item(frame), "Auto-Size must not refit a frame the merge didn't touch"); +} + +#[test] +fn merging_remaps_anchored_descendants_in_cells_footnotes_and_endnotes() { + let mut s = new_session(); + let destination = s.doc().unwrap().active_layer; + let host = s.execute("frame.create", &json!({"rect": [10, 100, 200, 220], "content": "text", "text": "Host"})).unwrap(); + let sid = designcraft_doc::StoryId(host["story"].as_u64().unwrap()); + let survivor = LayerId(s.execute("layer.new", &json!({"name": "Keep anchored"})).unwrap()["id"].as_u64().unwrap()); + let a = rectangle(&mut s, [10, 10, 20, 20]); + let source = LayerId(s.execute("layer.new", &json!({"name": "Merge anchored"})).unwrap()["id"].as_u64().unwrap()); + let b = rectangle(&mut s, [30, 10, 40, 20]); + let g = group(&mut s, &[a, b]); + s.execute("anchored.insert", &json!({"ids": [g], "story": sid.0, "pos": 0})).unwrap(); + let cell_item = rectangle(&mut s, [50, 10, 60, 20]); + let footnote_item = rectangle(&mut s, [70, 10, 80, 20]); + let endnote_item = rectangle(&mut s, [90, 10, 100, 20]); + // Construct the same nested story containers used by native import and existing layer tests. + s.edit(|d, _| { + let take = |d: &mut Document, id| { + let it = d.item(ItemId(id)).unwrap().clone(); + Arc::make_mut(&mut d.spreads[0]).items.retain(|i| i.id.0 != id); + AnchoredObject::new(it, Default::default()) + }; + let cell_object = take(d, cell_item); + let footnote_object = take(d, footnote_item); + let endnote_object = take(d, endnote_item); + let mut table = Table::new(d.alloc(), 1, 1, 0, 0, 40.0); + let cell = &mut table.cells[0].text; + cell.insert_object(0, cell_object); + cell.insert_note(cell.len(), "Footnote", Default::default()).unwrap(); + let note: &mut Story = &mut Arc::make_mut(&mut cell.notes[0]).text; + note.insert_object(0, footnote_object); + note.insert_endnote(note.len(), "Endnote", Default::default()).unwrap(); + Arc::make_mut(&mut note.endnotes[0]).text.insert_object(0, endnote_object); + d.story_mut(sid).unwrap().insert_table(0, table); + Ok(()) + }) + .unwrap(); + let before = s.doc().unwrap().doc.clone(); + before.check().unwrap(); + + s.execute("layer.merge", &json!({"ids": [source.0], "into": destination.0})).unwrap(); + let merged = s.doc().unwrap().doc.clone(); + assert_remapped(&before, &merged, source, destination); + assert_eq!(merged.anchored_item(ItemId(a)).unwrap().layer, survivor); + for id in [b, cell_item, footnote_item, endnote_item] { + assert_eq!(merged.anchored_item(ItemId(id)).unwrap().layer, destination); + } + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc, before); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc, merged); + let reopened = designcraft_format::load(&designcraft_format::save(&merged).unwrap()).unwrap(); + assert_remapped(&before, &reopened, source, destination); +} diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index 5891c5d5d..09a5e4244 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -11,11 +11,19 @@ mod distribute_locks; mod export_page_input; mod insert_pages_bounds; mod insert_pages_parent; +#[cfg(not(target_arch = "wasm32"))] +mod layer_delete_unused; +#[cfg(not(target_arch = "wasm32"))] +mod layer_merge_descendants; mod param_keys; mod pdf_backend; +#[cfg(not(target_arch = "wasm32"))] +mod pdf_flatten_print_regressions; mod preflight_resolution; mod primary_frame_columns; #[cfg(not(target_arch = "wasm32"))] +mod save_readability; +#[cfg(not(target_arch = "wasm32"))] mod save_state_atomicity; mod stroke_tint_range; mod text_decorations; diff --git a/crates/engine/tests/it/pdf_flatten_print_regressions.rs b/crates/engine/tests/it/pdf_flatten_print_regressions.rs new file mode 100644 index 000000000..e1ae2d437 --- /dev/null +++ b/crates/engine/tests/it/pdf_flatten_print_regressions.rs @@ -0,0 +1,128 @@ +//! Original synthetic artwork; no external fixtures or fonts are required. +//! These tests read exported PDFs back to pixels, rather than trusting the export warning. +//! PDF encode/readback can exceed the usual integration-test budget; pages stay at 240×240. + +use std::sync::Arc; + +use designcraft_engine::{Session, cmd::base64_decode}; +use serde_json::json; + +fn artwork(parent: bool) -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"pages": 1, "facingPages": false, "width": 240, "height": 240})).unwrap(); + rectangle(&mut s, false, [30, 100, 150, 200]); + if parent { + let parent = s.doc().unwrap().doc.parents[0].id.0; + s.execute("layout.pages.applyParent", &json!({"pages": [0], "parent": parent})).unwrap(); + rectangle(&mut s, true, [30, 30, 90, 70]); + s.execute("object.opacity", &json!({"opacity": 0.5})).unwrap(); + } + s +} + +fn rectangle(s: &mut Session, parent: bool, rect: [u32; 4]) { + let spread = if parent { json!({"kind": "parent", "index": 0}) } else { json!({"kind": "doc", "index": 0}) }; + s.execute("frame.create", &json!({"spread": spread, "rect": rect, "content": "unassigned"})).unwrap(); + s.execute("object.fill", &json!({"swatch": "[Black]"})).unwrap(); +} + +fn layer(s: &mut Session, name: &str) -> u64 { + s.execute("layer.new", &json!({"name": name})).unwrap()["id"].as_u64().unwrap() +} + +// Read premultiplied PDF pixels on white, as for the operated PDF-readback evidence. +fn exported(s: &mut Session, flatten: bool) -> Vec<[u8; 3]> { + let before = s.doc().unwrap().clone(); + let document_before = serde_json::to_value(&before.doc).unwrap(); + let selection_before = serde_json::to_value(&before.selection).unwrap(); + let out = s.execute("file.exportPdf", &json!({"flatten": if flatten { json!("low") } else { json!(false) }})).unwrap(); + let after = s.doc().unwrap(); + assert!(Arc::ptr_eq(&before.doc, &after.doc), "export must keep the source document allocation"); + assert_eq!(document_before, serde_json::to_value(&after.doc).unwrap(), "export must preserve all source artwork and layer settings"); + assert_eq!(selection_before, serde_json::to_value(&after.selection).unwrap()); + assert_eq!(before.active_layer, after.active_layer); + assert_eq!(before.history.undo.len(), after.history.undo.len()); + assert_eq!(before.history.redo.len(), after.history.redo.len()); + assert_eq!(before.is_dirty(), after.is_dirty()); + let bytes = base64_decode(out["base64"].as_str().unwrap()); + let image = designcraft_render::render_pdf_page(&bytes, 0, 240).expect("read back the actual exported PDF"); + image + .data() + .iter() + .map(|p| { + let white = 255 - p.a; + [p.r.saturating_add(white), p.g.saturating_add(white), p.b.saturating_add(white)] + }) + .collect() +} + +// Separate exports are compared by appearance, not byte-for-byte: allow a few pixels of +// rasteriser or encoder drift, far fewer than any of the rectangles drawn here covers. +fn assert_same_print(a: &[[u8; 3]], b: &[[u8; 3]], what: &str) { + assert_eq!(a.len(), b.len(), "{what}"); + let differing = a.iter().zip(b).filter(|(p, q)| p.iter().zip(q.iter()).any(|(x, y)| x.abs_diff(*y) > 32)).count(); + assert!(differing <= a.len() / 200, "{what}: {differing} pixels differ"); +} + +fn dark(image: &[[u8; 3]], rect: [usize; 4]) -> usize { + let [x0, y0, x1, y1] = rect; + (y0..y1).flat_map(|y| (x0..x1).map(move |x| image[y * 240 + x])).filter(|p| p.iter().any(|c| *c < 220)).count() +} + +#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)] +#[cfg_attr(not(target_arch = "wasm32"), test)] +fn transparent_parent_artwork_survives_empty_nonprinting_and_hidden_top_layers() { + let mut s = artwork(true); + let baseline = exported(&mut s, true); + assert!(dark(&baseline, [40, 110, 140, 190]) > 0, "printable page artwork must be visible"); + assert!(dark(&baseline, [40, 40, 80, 60]) > 0, "the applied transparent parent must print too"); + let notes = layer(&mut s, "Notes"); + s.execute("layer.set", &json!({"id": notes, "printable": false})).unwrap(); + assert_same_print(&exported(&mut s, true), &baseline, "an empty nonprinting top layer must not blank the PDF"); + let hidden = layer(&mut s, "Hidden printable layer"); + s.execute("layer.set", &json!({"id": hidden, "visible": false})).unwrap(); + assert_same_print(&exported(&mut s, true), &baseline, "the raster destination must also be visible"); +} + +#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)] +#[cfg_attr(not(target_arch = "wasm32"), test)] +fn whole_page_flattening_does_not_bake_nonprinting_page_or_parent_notes_into_pdf() { + let mut s = artwork(true); + let baseline = exported(&mut s, true); + let notes = layer(&mut s, "Notes"); + rectangle(&mut s, false, [170, 170, 220, 220]); + rectangle(&mut s, true, [170, 30, 220, 70]); + s.execute("layer.set", &json!({"id": notes, "printable": false})).unwrap(); + // Keep the original destination printable, so the separate blank-output defect cannot + // hide a leak from the raster-input filter. + layer(&mut s, "Printable output"); + let excluded = exported(&mut s, true); + assert_same_print(&excluded, &baseline, "nonprinting Notes must not be baked into the exported image"); + assert_eq!(dark(&excluded, [180, 180, 210, 210]) + dark(&excluded, [180, 40, 210, 60]), 0, "no page or parent Notes ink"); + s.execute("layer.set", &json!({"id": notes, "printable": true})).unwrap(); + let printed = exported(&mut s, true); + assert!(dark(&printed, [180, 180, 210, 210]) > dark(&excluded, [180, 180, 210, 210]), "the page Notes control must be detectable when printable"); + assert!(dark(&printed, [180, 40, 210, 60]) > dark(&excluded, [180, 40, 210, 60]), "the parent Notes control must be detectable when printable"); +} + +#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)] +#[cfg_attr(not(target_arch = "wasm32"), test)] +fn a_document_without_an_exportable_layer_stays_blank_with_or_without_flattening() { + let mut s = artwork(true); + let original = s.doc().unwrap().doc.layers[0].id.0; + s.execute("layer.set", &json!({"id": original, "printable": false})).unwrap(); + let hidden = layer(&mut s, "Hidden printable layer"); + s.execute("layer.set", &json!({"id": hidden, "visible": false})).unwrap(); + let ordinary = exported(&mut s, false); + assert_eq!(dark(&ordinary, [0, 0, 240, 240]), 0, "the ordinary print pipeline excludes both layers"); + assert_eq!(dark(&exported(&mut s, true), [0, 0, 240, 240]), 0, "flattening must not make any excluded content printable"); +} + +#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)] +#[cfg_attr(not(target_arch = "wasm32"), test)] +fn ordinary_printable_artwork_keeps_its_pdf_appearance_when_flattening_is_requested() { + let mut s = artwork(false); + let ordinary = exported(&mut s, false); + assert!(dark(&ordinary, [40, 110, 140, 190]) > 0); + assert_same_print(&exported(&mut s, true), &ordinary, "opaque artwork needs no flattening and must keep printing"); +} diff --git a/crates/engine/tests/it/save_readability.rs b/crates/engine/tests/it/save_readability.rs new file mode 100644 index 000000000..8177154dc --- /dev/null +++ b/crates/engine/tests/it/save_readability.rs @@ -0,0 +1,118 @@ +use std::sync::Arc; + +use designcraft_doc::ItemId; +use designcraft_engine::{Session, cmd::base64_encode}; +use serde_json::{Value, json}; + +fn document_with_text() -> (Session, Value) { + let mut session = Session::new(); + session.execute("file.new", &json!({})).unwrap(); + let frame = session + .execute("frame.create", &json!({"rect": [0, 0, 100, 100], "content": "text", "text": "Keep this artwork", "caret": false})) + .unwrap()["id"] + .clone(); + (session, frame) +} + +fn nest_groups(session: &mut Session, mut group: Value) { + // Fixed synthetic reproduction, not a stress sweep: this legally edited document exceeded + // the reader's JSON nesting budget. Exercise commands (and native preview generation on + // Save), even if that makes this regression slower than a metadata-only format test. + for _ in 0..48 { + let sibling = session.execute("frame.create", &json!({"rect": [120, 0, 130, 10]})).unwrap()["id"].clone(); + group = session.execute("object.group", &json!({"ids": [group, sibling]})).unwrap()["id"].clone(); + } +} + +/// The readability check encodes the document without image payloads; reopening must still +/// read the real archive's embedded image bytes. +#[test] +fn a_document_with_a_placed_image_saves_and_reopens_with_its_image_bytes() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("placed.designcraft"); + let mut session = Session::new(); + session.execute("file.new", &json!({})).unwrap(); + let png = designcraft_render::Rendered { width: 4, height: 3, pixels: vec![200; 4 * 3 * 4] }.to_png(); + let placed = session.execute("file.place", &json!({"base64": base64_encode(&png), "name": "photo.png", "x": 0, "y": 0, "width": 72})).unwrap(); + let id = ItemId(placed["id"].as_u64().unwrap()); + + session.execute("file.saveAs", &json!({"path": path})).expect("a document with a placed image saves"); + assert!(!session.doc().unwrap().is_dirty()); + + let mut reopened = Session::new(); + reopened.execute("file.open", &json!({"path": path})).expect("the saved document with an image reopens"); + let doc = &reopened.doc().unwrap().doc; + let asset = doc.item(id).and_then(|item| item.graphic()).map(|graphic| graphic.asset).expect("the placed graphic survives"); + assert_eq!(doc.assets[&asset].data.load().unwrap().as_slice(), png.as_slice(), "the embedded image bytes survive"); +} + +#[test] +fn nested_group_save_is_readable_or_preserves_the_good_file_and_dirty_edits() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("nested.designcraft"); + let (mut session, root) = document_with_text(); + session.execute("file.saveAs", &json!({"path": path})).unwrap(); + let good_bytes = std::fs::read(&path).unwrap(); + let mut baseline = Session::new(); + baseline.execute("file.open", &json!({"path": path})).expect("the previous saved file must be readable"); + nest_groups(&mut session, root); + let before = session.doc().unwrap().clone(); + assert!(before.is_dirty()); + + let saved = session.execute("file.save", &json!({})); + let mut reopened = Session::new(); + match saved { + Ok(_) => { + assert!(!session.doc().unwrap().is_dirty(), "acknowledged Save is clean"); + reopened.execute("file.open", &json!({"path": path})).expect("acknowledged Save must produce a readable replacement"); + assert_eq!(*reopened.doc().unwrap().doc, *session.doc().unwrap().doc, "the complete artwork and text survive Save and reopen"); + } + Err(_) => { + let after = session.doc().unwrap(); + assert_eq!(std::fs::read(&path).unwrap(), good_bytes, "refused Save leaves previous good bytes alone"); + assert!(after.is_dirty(), "refused Save retains dirty edits"); + assert_eq!(after.path, before.path, "refused Save keeps the original path"); + assert!(Arc::ptr_eq(&after.doc, &before.doc), "refused Save keeps the edited document"); + assert!(Arc::ptr_eq(&after.saved_doc, &before.saved_doc), "refused Save does not acknowledge edits"); + assert_eq!((after.revision, after.saved_revision), (before.revision, before.saved_revision)); + reopened.execute("file.open", &json!({"path": path})).expect("refused Save must leave a readable baseline"); + assert_eq!(*reopened.doc().unwrap().doc, *baseline.doc().unwrap().doc); + } + } +} + +#[test] +fn nested_group_recovery_is_readable_or_preserves_the_previous_recoverable_checkpoint() { + let dir = tempfile::tempdir().unwrap(); + let recovery = dir.path().join("recovery"); + let (mut session, root) = document_with_text(); + session.execute("file.recovery.save", &json!({"dir": recovery})).unwrap(); + let uid = session.doc().unwrap().uid; + let checkpoint = recovery.join(format!("{uid}.designcraft")); + let metadata = recovery.join(format!("{uid}.json")); + let good_bytes = std::fs::read(&checkpoint).unwrap(); + let good_metadata = std::fs::read(&metadata).unwrap(); + let baseline = designcraft_format::load(&good_bytes).expect("the previous checkpoint must be readable"); + nest_groups(&mut session, root); + let before = session.doc().unwrap().clone(); + + let saved = session.execute("file.recovery.save", &json!({"dir": recovery})); + assert!(session.doc().unwrap().is_dirty(), "recovery must not acknowledge normal Save"); + assert!(Arc::ptr_eq(&session.doc().unwrap().doc, &before.doc), "checkpointing must not change dirty edits"); + let expected = match saved { + Ok(_) => { + let decoded = designcraft_format::load(&std::fs::read(&checkpoint).unwrap()).expect("accepted checkpoint must be readable"); + assert_eq!(decoded, *before.doc, "accepted recovery preserves the complete edited document"); + decoded + } + Err(_) => { + assert_eq!(std::fs::read(&checkpoint).unwrap(), good_bytes, "refused checkpoint replacement preserves good recovery bytes"); + assert_eq!(std::fs::read(&metadata).unwrap(), good_metadata, "refusal does not consume or replace checkpoint metadata"); + baseline + } + }; + let mut recovered = Session::new(); + let result = recovered.execute("file.recovery.open", &json!({"dir": recovery})).unwrap(); + assert!(!result["opened"].as_array().unwrap().is_empty(), "the surviving checkpoint must actually recover"); + assert_eq!(*recovered.doc().unwrap().doc, expected, "the recoverable document retains artwork and text"); +} diff --git a/crates/format/src/lib.rs b/crates/format/src/lib.rs index d42c3d25f..8be169a1e 100644 --- a/crates/format/src/lib.rs +++ b/crates/format/src/lib.rs @@ -39,6 +39,7 @@ pub fn write(out: &mut W, doc: &Document, pre } let mut compact = doc.clone(); compact.compact_assets(); + check_document_readable(&compact)?; let mut owned_assets = Vec::new(); let mut owned_proxies = Vec::new(); for asset in compact.assets.values() { @@ -59,6 +60,20 @@ pub fn write(out: &mut W, doc: &Document, pre craft_designcraft_format::write_to(out, &compact, concat!("DesignCraft ", env!("CARGO_PKG_VERSION")), preview, &assets, &proxies) } +/// The shared writer accepts deeper JSON than its bounded reader. Check the actual encoding, +/// not a group count: groups are only one of several sources of nested document data. +/// +/// Leave asset payloads and previews out of this probe. They do not affect document decoding, +/// and rereading them would duplicate potentially large image buffers and defeat streaming +/// recovery writes. This adds one serialization/compression and bounded decode of document +/// metadata only; those temporary buffers are dropped before the real archive is written. +fn check_document_readable(doc: &Document) -> Result<(), FormatError> { + let probe = craft_designcraft_format::save(doc, concat!("DesignCraft ", env!("CARGO_PKG_VERSION")), None, &[], &[])?; + craft_designcraft_format::load::(&probe) + .map(drop) + .map_err(|error| FormatError::Unsaveable(format!("the document would not reopen: {error}"))) +} + /// Required native format version for a document. Kept for app-side compatibility; inference is /// performed by the shared codec over the serialized neutral document schema. #[cfg(test)] diff --git a/crates/format/src/tests.rs b/crates/format/src/tests.rs index fd875a2c2..2a3fb2e67 100644 --- a/crates/format/src/tests.rs +++ b/crates/format/src/tests.rs @@ -936,3 +936,35 @@ fn embedded_documents_keep_their_older_version_and_version_5_loads() { let loaded = load(&save(&d).unwrap()).unwrap(); assert_eq!(loaded.assets.len(), d.assets.len()); } + +/// A document nested deeper than the reader accepts is refused before anything is written, +/// while a moderately nested one still saves and reopens. +#[test] +fn an_over_deep_document_is_refused_before_writing() { + use designcraft_doc::geom::shapes; + use designcraft_doc::{Content, Item, ItemId, Shape}; + fn nested(depth: usize) -> Document { + let mut d = Document::new(&NewDocument::default()); + let layer = d.default_layer(); + let square = || shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)); + let mut item = Item::new(ItemId(d.alloc()), layer, Shape::Rectangle, square()); + for _ in 0..depth { + let mut group = Item::new(ItemId(d.alloc()), layer, Shape::Rectangle, square()); + group.content = Content::Group { items: vec![Arc::new(item)] }; + item = group; + } + d.insert_item(SpreadRef::Doc(0), item, None).unwrap(); + d + } + + let shallow = nested(8); + load(&save(&shallow).expect("a moderately nested document saves")).expect("and reopens"); + + let deep = nested(64); + let mut out = Cursor::new(Vec::new()); + match write(&mut out, &deep, None) { + Err(FormatError::Unsaveable(message)) => assert!(message.starts_with("the document would not reopen"), "{message}"), + other => panic!("expected a refusal, got {other:?}"), + } + assert!(out.get_ref().is_empty(), "nothing is written before the refusal"); +} diff --git a/crates/idml/src/lib.rs b/crates/idml/src/lib.rs index 08d78cae9..9c8ab805f 100644 --- a/crates/idml/src/lib.rs +++ b/crates/idml/src/lib.rs @@ -62,6 +62,33 @@ pub use craft_idml::value::{base64_decode, base64_encode}; pub use export::{ExportOptions, export_idml, export_idml_report, export_idml_with}; pub use import::{Imported, import_idml, import_idml_report, import_idml_report_with_previews, import_idml_with}; +/// What an IDML package can't keep of a document (see [`unwritten`]): a save that writes IDML +/// loses it. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct Unwritten { + /// Editorial notes (Type › Notes): not written at all. + pub editorial_notes: usize, + /// Endnotes: their text stays in the endnote frame as plain text, numbers included, but the + /// references and the notes themselves are gone. + pub endnotes: usize, +} + +impl Unwritten { + /// Nothing is lost. + pub fn is_empty(&self) -> bool { + *self == Unwritten::default() + } +} + +/// What [`export_idml`] leaves out of `d`. Editorial notes and endnotes are anchored only in +/// stories (not in table cells or footnotes), so the stories are all there is to count. +pub fn unwritten(d: &designcraft_doc::Document) -> Unwritten { + d.stories.values().fold(Unwritten::default(), |u, st| Unwritten { + editorial_notes: u.editorial_notes.saturating_add(st.editorial.len()), + endnotes: u.endnotes.saturating_add(st.endnotes.len()), + }) +} + /// The IDML package mimetype (content of the first, stored `mimetype` entry). pub const MIMETYPE: &str = craft_idml::MIMETYPE; /// The DOM version written to every part. diff --git a/crates/images/src/resolution.rs b/crates/images/src/resolution.rs index d20d4a940..42b6a448d 100644 --- a/crates/images/src/resolution.rs +++ b/crates/images/src/resolution.rs @@ -3,9 +3,10 @@ //! Delegates container resolution probes to `craft-image-codecs` (`file_resolution`, which reads //! JPEG Photoshop ResolutionInfo -> XMP -> EXIF -> JFIF, PNG eXIf, WebP EXIF, and classic TIFF; //! plus `exif_resolution`, `png_probe::pixels_per_meter`, and `bmp_probe::pixels_per_meter`) and -//! PSD `ResolutionInfo` to [`crate::psd`]. JPEG EXIF orientation keeps the strict local APP1 scan -//! (`"Exif\0\0"` with complete segment bounds). GIF and files without (usable) metadata report -//! nothing and keep the pixel-is-a-point size. +//! PSD `ResolutionInfo` to [`crate::psd`]. JPEG EXIF orientation uses the shared strict APP1 +//! reader (`jpeg_probe::strict_exif_orientation`: `"Exif\0\0"` with complete segment bounds, +//! before the first scan). GIF and files without (usable) metadata report nothing and keep the +//! pixel-is-a-point size. /// Dots per inch in x and y, when the file carries usable resolution metadata. pub fn raster_resolution(bytes: &[u8]) -> Option<(f64, f64)> { @@ -29,7 +30,7 @@ pub fn raster_resolution(bytes: &[u8]) -> Option<(f64, f64)> { /// The EXIF/TIFF orientation (1–8) of `bytes`, or 1 when absent or unreadable. fn orientation(bytes: &[u8]) -> u16 { if bytes.starts_with(b"\xFF\xD8\xFF") { - return jpeg_orientation(bytes); + return craft_image_codecs::jpeg_probe::strict_exif_orientation(bytes); } if bytes.starts_with(b"\x89PNG\r\n\x1a\n") { return craft_image_codecs::png_probe::header(bytes).map_or(1, |(_, _, o)| o); @@ -43,40 +44,6 @@ fn orientation(bytes: &[u8]) -> u16 { 1 } -/// EXIF orientation from a JPEG's first APP1 `"Exif\0\0"` segment before the first scan. -fn jpeg_orientation(bytes: &[u8]) -> u16 { - let mut i = 2usize; - while i + 4 <= bytes.len() { - if bytes[i] != 0xFF { - break; - } - let marker = bytes[i + 1]; - if marker == 0xFF { - i += 1; - continue; - } - if marker == 0xD8 || (0xD0..=0xD7).contains(&marker) || marker == 0x01 { - i += 2; - continue; - } - if marker == 0xDA || marker == 0xD9 { - break; - } - let len = u16::from_be_bytes([bytes[i + 2], bytes[i + 3]]) as usize; - if len < 2 || i + 2 + len > bytes.len() { - break; - } - let seg = &bytes[i + 4..i + 2 + len]; - if marker == 0xE1 - && let Some(exif) = seg.strip_prefix(b"Exif\0\0") - { - return craft_image_codecs::exif_orientation(exif); - } - i += 2 + len; - } - 1 -} - /// PNG `pHYs` pixels-per-metre via the shared probe: meters -> dpi in `f64` (preserving exact /// placement DPI without `dpi_of_ppm` snapping). fn png_resolution(bytes: &[u8]) -> Option<(f64, f64)> { diff --git a/crates/mcp/src/tools.rs b/crates/mcp/src/tools.rs index 7f38036e3..b2c74eaea 100644 --- a/crates/mcp/src/tools.rs +++ b/crates/mcp/src/tools.rs @@ -406,7 +406,7 @@ pub fn tool_definitions() -> Vec { "ui_set", "Set UI state", &app_only( - "Change UI state: panel to open or close, brightness, status text, rulers/guides/frameEdges/baselineGrid/documentGrid/textThreads, \ + "Change UI state: panel to open or close, brightness, status text, rulers/guides/frameEdges/baselineGrid/documentGrid/textThreads/linkBadge, \ Control bar, dock expanded, screenMode, zoom, page (1-based), fit (page|spread).", ), obj( @@ -415,6 +415,7 @@ pub fn tool_definitions() -> Vec { "brightness": {"type": "string", "enum": ["dark", "mediumDark", "mediumLight", "light"]}, "rulers": {"type": "boolean"}, "guides": {"type": "boolean"}, "frameEdges": {"type": "boolean"}, "baselineGrid": {"type": "boolean"}, "documentGrid": {"type": "boolean"}, "textThreads": {"type": "boolean"}, + "linkBadge": boolean("Show the badge on linked graphics' frames (View › Extras › Show/Hide Link Badge)"), "status": string("Status bar text"), "controlBar": boolean("Show the Control bar"), "closePanel": boolean("Close the panel that is showing"), diff --git a/crates/render/src/color.rs b/crates/render/src/color.rs index 84d648128..9418a2149 100644 --- a/crates/render/src/color.rs +++ b/crates/render/src/color.rs @@ -1,5 +1,5 @@ use super::types::{Frame, Rendered}; -use super::{Affine, BlendMode, Compose, DcBlend, Document, Item, Mix, Rect, RenderContext, peniko, vello_cpu}; +use super::{Affine, BlendMode, Compose, DcBlend, Document, Item, Mix, Rect, RenderContext, fx, peniko, vello_cpu}; const CMYK_N: usize = 17; @@ -48,21 +48,136 @@ pub(crate) fn cmyk_in(table: &[[f32; 4]], rgb: [f32; 3]) -> [f32; 4] { out } +/// How far (points) any effect in `doc` can carry an image's pixels: an image is converted to a +/// plate only where the view can show it, widened by this so shadows and glows near the edge of +/// the view still find their pixels. Generous on purpose: it only makes the converted part bigger. +pub(crate) fn effect_reach(doc: &Document) -> f64 { + let mut reach = 0.0; + let mut add = |it: &Item| { + if it.effects.any() { + reach += fx::outset(it) + 144.0; + } + }; + for it in doc.spreads.iter().flat_map(|sp| &sp.items).chain(doc.parents.iter().flat_map(|p| &p.items)) { + it.walk(&mut add); + } + // Anchored objects live in their stories, not on a spread. + for o in doc.stories.values().flat_map(|s| &s.objects) { + o.item.walk(&mut add); + } + reach +} + +/// How far the effects of the object showing graphic `g` and of the groups around it can carry +/// its pixels: only those move or spread this image. None when the graphic isn't found on a page +/// (an anchored object in a story): then [`effect_reach`] covers it. +pub(crate) fn image_effect_reach(doc: &Document, g: &designcraft_doc::Graphic) -> Option { + fn find(it: &Item, g: &designcraft_doc::Graphic, around: f64, depth: usize) -> Option { + let reach = around + if it.effects.any() { fx::outset(it) + 144.0 } else { 0.0 }; + if it.graphic().is_some_and(|own| std::ptr::eq(own, g)) { + return Some(reach); + } + if depth >= 64 { + return None; + } + it.children().iter().find_map(|c| find(c, g, reach, depth + 1)) + } + doc.spreads.iter().flat_map(|sp| &sp.items).chain(doc.parents.iter().flat_map(|p| &p.items)).find_map(|it| find(it, g, 0.0, 0)) +} + +/// An image's plate (see [`plate_pixmap`]) where `area` (spread space; `to_pixels` maps it to the +/// image's pixels) can show it, and where that part starts in the image. Small images are +/// converted whole and cached. A large one (a 3840 × 5760 photo at full resolution, zoomed in) +/// would take seconds to convert and crowd the other images out of the cache, so only the part in +/// view is converted. None: none of it is in view. +pub(crate) fn plate_part( + pm: &std::sync::Arc, + plate: u8, + to_pixels: Affine, + area: impl FnOnce() -> Rect, +) -> Option<(std::sync::Arc, (u16, u16))> { + let (w, h) = (pm.width(), pm.height()); + if plate_bytes(w, h) <= PLATE_CACHE_BYTES / 8 { + return Some((plate_pixmap(pm, plate), (0, 0))); + } + // Bilinear and bicubic sampling read a few pixels around each one shown. + let r = to_pixels.transform_rect_bbox(area()).inflate(4.0, 4.0); + if !(r.x0.is_finite() && r.y0.is_finite() && r.x1.is_finite() && r.y1.is_finite()) { + return Some((plate_pixmap(pm, plate), (0, 0))); + } + let clamp = |v: f64, max: u16| v.clamp(0.0, f64::from(max)) as u16; + let (x0, y0, x1, y1) = (clamp(r.x0.floor(), w), clamp(r.y0.floor(), h), clamp(r.x1.ceil(), w), clamp(r.y1.ceil(), h)); + if x1 <= x0 || y1 <= y0 { + return None; + } + // All or nearly all of it in view (three quarters or more): convert the whole plate once and + // keep it, as long as it takes at most a quarter of the cache: both ink passes keep a plate, + // so a bigger one would push the other images out. Converting it in parts would redo nearly + // all of it on every render. + let part_area = u64::from(x1 - x0) * u64::from(y1 - y0); + let whole_area = u64::from(w) * u64::from(h); + if part_area.saturating_mul(4) >= whole_area.saturating_mul(3) && plate_bytes(w, h) <= PLATE_CACHE_BYTES / 4 { + return Some((plate_pixmap(pm, plate), (0, 0))); + } + let row = usize::from(w); + let data = pm.data(); + let mut part = Vec::with_capacity(usize::from(x1 - x0) * usize::from(y1 - y0)); + for y in usize::from(y0)..usize::from(y1) { + let start = y * row; + part.extend_from_slice(data.get(start + usize::from(x0)..start + usize::from(x1))?); + } + let table = cmyk_table(); + let part = plate_pixels(&part, &table, plate); + Some((std::sync::Arc::new(vello_cpu::Pixmap::from_parts(part, x1 - x0, y1 - y0)), (x0, y0))) +} + +/// Plate conversions cached per image and plate: at most this much derived raster memory. +pub(crate) const PLATE_CACHE_BYTES: usize = 192 << 20; + +/// What one plate of a `w` × `h` image costs the cache (premultiplied RGBA8). +fn plate_bytes(w: u16, h: u16) -> usize { + usize::from(w).saturating_mul(usize::from(h)).saturating_mul(4) +} + +/// Premultiplied pixels' ink coverage on `plate` (4: C, M and Y complements as R, G and B). +fn plate_pixels(pixels: &[vello_cpu::color::PremulRgba8], table: &[[f32; 4]], plate: u8) -> Vec { + pixels + .iter() + .map(|p| { + if p.a == 0 { + return *p; + } + let k = 255.0 / p.a as f32; + let rgb = [p.r, p.g, p.b].map(|v| (v as f32 * k / 255.0).min(1.0)); + let cmyk = cmyk_in(table, rgb); + let ink = |i: usize| ((1.0 - cmyk[i].clamp(0.0, 1.0)) * p.a as f32).round() as u8; + if plate == 4 { + return vello_cpu::color::PremulRgba8 { r: ink(0), g: ink(1), b: ink(2), a: p.a }; + } + let v = ink(plate.min(3) as usize); + vello_cpu::color::PremulRgba8 { r: v, g: v, b: v, a: p.a } + }) + .collect() +} + /// An image's ink coverage on one process plate, as grey (cached per image and plate). pub(crate) fn plate_pixmap(pm: &std::sync::Arc, plate: u8) -> std::sync::Arc { // Keep source allocations alive (their addresses are keys), invalidate on colour settings, - // and cap derived raster memory rather than merely counting differently sized images. - type Entry = (std::sync::Arc, std::sync::Arc); - type Cache = (designcraft_color::cms::ColorSettings, std::collections::HashMap<(usize, u8), Entry>, usize); - const BUDGET: usize = 64 << 20; + // and cap derived raster memory. A full cache lets go of the plates used longest ago: every + // CMYK view render draws each image twice (two ink passes), so dropping the whole cache when + // it filled made a few placed images miss on every render and converted them again each time. + type Entry = (std::sync::Arc, std::sync::Arc, u64); + type Cache = (designcraft_color::cms::ColorSettings, std::collections::HashMap<(usize, u8), Entry>, usize, u64); static CACHE: std::sync::Mutex> = std::sync::Mutex::new(None); let key = (std::sync::Arc::as_ptr(pm) as usize, plate); let settings = designcraft_color::cms::active_settings(); { let mut guard = CACHE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); - if let Some((previous, map, _)) = guard.as_ref() { + if let Some((previous, map, _, clock)) = guard.as_mut() { if *previous == settings { - if let Some((_, derived)) = map.get(&key) { + *clock += 1; + if let Some((_, derived, used_at)) = map.get_mut(&key) { + *used_at = *clock; return derived.clone(); } } else { @@ -71,37 +186,30 @@ pub(crate) fn plate_pixmap(pm: &std::sync::Arc, plate: u8) -> } } let table = cmyk_table(); - let data: Vec = pm - .data() - .iter() - .map(|p| { - if p.a == 0 { - return *p; - } - let k = 255.0 / p.a as f32; - let rgb = [p.r, p.g, p.b].map(|v| (v as f32 * k / 255.0).min(1.0)); - let cmyk = cmyk_in(&table, rgb); - let ink = |i: usize| ((1.0 - cmyk[i].clamp(0.0, 1.0)) * p.a as f32).round() as u8; - if plate == 4 { - return vello_cpu::color::PremulRgba8 { r: ink(0), g: ink(1), b: ink(2), a: p.a }; - } - let v = ink(plate.min(3) as usize); - vello_cpu::color::PremulRgba8 { r: v, g: v, b: v, a: p.a } - }) - .collect(); + #[cfg(test)] + PLATE_CONVERSIONS.with(|n| n.set(n.get() + 1)); + let data = plate_pixels(pm.data(), &table, plate); let out = std::sync::Arc::new(vello_cpu::Pixmap::from_parts(data, pm.width(), pm.height())); - let bytes = (pm.width() as usize).saturating_mul(pm.height() as usize).saturating_mul(8); - if bytes <= BUDGET { + let bytes = plate_bytes(pm.width(), pm.height()); + if bytes <= PLATE_CACHE_BYTES { let mut guard = CACHE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); - let (previous, map, used) = guard.get_or_insert_with(|| (settings.clone(), Default::default(), 0)); - if *previous != settings || used.saturating_add(bytes) > BUDGET { + let (previous, map, used, clock) = guard.get_or_insert_with(|| (settings.clone(), Default::default(), 0, 0)); + if *previous != settings { map.clear(); *used = 0; *previous = settings; } - if map.insert(key, (pm.clone(), out.clone())).is_none() { - *used += bytes; + while used.saturating_add(bytes) > PLATE_CACHE_BYTES { + let Some(oldest) = map.iter().min_by_key(|(_, e)| e.2).map(|(k, _)| *k) else { break }; + if let Some((_, gone, _)) = map.remove(&oldest) { + *used = used.saturating_sub(plate_bytes(gone.width(), gone.height())); + } } + *clock += 1; + if let Some((_, replaced, _)) = map.insert(key, (pm.clone(), out.clone(), *clock)) { + *used = used.saturating_sub(plate_bytes(replaced.width(), replaced.height())); + } + *used = used.saturating_add(bytes); } out } @@ -278,3 +386,121 @@ pub(crate) fn blend_space_view(img: &mut Rendered, area: Rect) { } } } + +#[cfg(test)] +thread_local! { + /// How many whole images [`plate_pixmap`] converted to a plate on this thread. + pub(crate) static PLATE_CONVERSIONS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +#[cfg(test)] +mod plate_tests { + use designcraft_doc::SpreadRef; + use designcraft_doc::build::NewDocument; + + use super::*; + + /// A `w` × `h` image with a different colour in every pixel. + fn ramp(w: u16, h: u16) -> std::sync::Arc { + let data = (0..usize::from(w) * usize::from(h)) + .map(|i| vello_cpu::color::PremulRgba8 { r: (i % 251) as u8, g: (i / 7 % 241) as u8, b: (i / 13 % 239) as u8, a: 255 }) + .collect(); + std::sync::Arc::new(vello_cpu::Pixmap::from_parts(data, w, h)) + } + + /// A CMYK view draws every image twice per render (two ink passes). The plate cache used to + /// count each plate twice and empty itself when full, so three placed photos missed on every + /// render and an edit took half a second; now they all stay cached. + #[test] + fn plates_of_the_images_in_view_stay_cached_across_renders() { + let images = [ramp(1600, 1200), ramp(1500, 1300), ramp(1400, 1400)]; + let before = PLATE_CONVERSIONS.with(std::cell::Cell::get); + for _ in 0..3 { + for plate in [4, 3] { + for pm in &images { + plate_pixmap(pm, plate); + } + } + } + assert_eq!(PLATE_CONVERSIONS.with(std::cell::Cell::get) - before, 6, "each image and plate is converted once"); + } + + /// A large image is converted only where the view shows it, with the same inks as converting + /// it whole. + #[test] + fn a_large_image_converts_only_the_part_in_view() { + let pm = ramp(4000, 2500); + assert!(plate_bytes(4000, 2500) > PLATE_CACHE_BYTES / 8, "large enough to be converted in parts"); + let before = PLATE_CONVERSIONS.with(std::cell::Cell::get); + let (part, at) = plate_part(&pm, 4, Affine::IDENTITY, || Rect::new(1000.0, 500.0, 1100.0, 560.0)).unwrap(); + assert_eq!(PLATE_CONVERSIONS.with(std::cell::Cell::get), before, "the whole image was not converted"); + assert_eq!(at, (996, 496)); + assert_eq!((part.width(), part.height()), (108, 68)); + let table = cmyk_table(); + let row = usize::from(pm.width()); + for (y, x) in [(0usize, 0usize), (30, 50), (67, 107)] { + let source = pm.data()[(usize::from(at.1) + y) * row + usize::from(at.0) + x]; + assert_eq!(part.data()[y * 108 + x], plate_pixels(&[source], &table, 4)[0]); + } + assert!(plate_part(&pm, 4, Affine::IDENTITY, || Rect::new(5000.0, 0.0, 5100.0, 50.0)).is_none(), "out of view: nothing"); + // All of it in view: converted whole once, then taken from the cache. + let before = PLATE_CONVERSIONS.with(std::cell::Cell::get); + for _ in 0..3 { + let (whole, at) = plate_part(&pm, 4, Affine::IDENTITY, || Rect::new(-10.0, -10.0, 4010.0, 2510.0)).unwrap(); + assert_eq!(((whole.width(), whole.height()), at), ((4000, 2500), (0, 0))); + } + assert_eq!(PLATE_CONVERSIONS.with(std::cell::Cell::get) - before, 1, "the whole plate is converted once and cached"); + // Nearly all of it in view (90 % of the width): the cached whole plate, not a new part. + let before = PLATE_CONVERSIONS.with(std::cell::Cell::get); + let (whole, at) = plate_part(&pm, 4, Affine::IDENTITY, || Rect::new(200.0, -10.0, 3800.0, 2510.0)).unwrap(); + assert_eq!(((whole.width(), whole.height()), at), ((4000, 2500), (0, 0))); + assert_eq!(PLATE_CONVERSIONS.with(std::cell::Cell::get), before, "taken from the cache"); + let small = ramp(64, 64); + let (whole, at) = plate_part(&small, 3, Affine::IDENTITY, || Rect::new(0.0, 0.0, 10.0, 10.0)).unwrap(); + assert_eq!(((whole.width(), whole.height()), at), ((64, 64), (0, 0)), "a small image is converted whole and cached"); + } + + /// A large image is widened only by the effects that move its own pixels (its object's and + /// the groups' around it), not by a big shadow elsewhere in the document. + #[test] + fn an_images_effect_reach_is_its_own() { + let mut d = Document::new(&NewDocument::default()); + let lid = d.default_layer(); + let graphic = |aid| designcraft_doc::Graphic { + layer_options: None, + asset: aid, + size: (100.0, 100.0), + xf: Affine::IDENTITY, + clip: None, + auto_fit: Default::default(), + fit_align: 4, + crop: [0.0; 4], + wrap: Default::default(), + fill: Default::default(), + }; + let item = |d: &mut Document, shadow: f64, with_graphic: bool| { + let mut it = Item::new( + designcraft_doc::ItemId(d.alloc()), + lid, + designcraft_doc::Shape::Rectangle, + designcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), + ); + if with_graphic { + it.content = designcraft_doc::Content::Graphic(graphic(designcraft_doc::AssetId(1))); + } + if shadow > 0.0 { + it.effects.drop_shadow.on = true; + it.effects.drop_shadow.distance = shadow; + } + d.insert_item(SpreadRef::Doc(0), it.clone(), None).unwrap(); + it.id + }; + let image = item(&mut d, 0.0, true); + item(&mut d, 500.0, false); + let g = d.item(image).unwrap().graphic().unwrap().clone(); + let own = d.item(image).unwrap().graphic().unwrap(); + assert_eq!(image_effect_reach(&d, own), Some(0.0), "no effect on the image's own object"); + assert!(effect_reach(&d) > 500.0, "the document-wide reach counts the other shadow"); + assert_eq!(image_effect_reach(&d, &g), None, "a graphic not in the document: the document-wide reach"); + } +} diff --git a/crates/render/src/damage.rs b/crates/render/src/damage.rs index 979780ada..44ee418f5 100644 --- a/crates/render/src/damage.rs +++ b/crates/render/src/damage.rs @@ -112,11 +112,7 @@ pub fn damage_with(old: &Document, new: &Document, cache: Option<&designcraft_co let cur = c.get(new, sid, None); let changed = designcraft_compose::Cache::changed_frames(&prev, &cur); for f in changed { - for d in [old, new] { - if d.find(f).is_some() { - out.push(frame_area(d, f)?); - } - } + out.extend(changed_frame_areas(old, new, f)?); } continue; } @@ -196,6 +192,25 @@ fn painted_bounds(it: &Item) -> Option { Some(b) } +/// The areas of changed frame `f` before and after an edit. None (repaint everything) for a +/// text frame anchored in either document: it isn't on a spread there (so it has no area of its +/// own here) but is drawn inside the text it is anchored in, wherever that is laid out, also when +/// it is on a spread in the other document. A frame that is neither on a spread nor anchored in +/// either document is drawn nowhere and adds nothing. Anchored items are searched (a scan of the +/// whole document) only in a version where the frame is not on a spread: item ids are unique in +/// a document, and anchoring takes an item off its spread. +fn changed_frame_areas(old: &Document, new: &Document, f: ItemId) -> Option> { + let mut areas = Vec::new(); + for d in [old, new] { + if d.find(f).is_some() { + areas.push(frame_area(d, f)?); + } else if d.anchored_item(f).is_some() { + return None; + } + } + Some(areas) +} + /// A text frame's area: its spread and bounds with room for glyph overhang. fn frame_area(d: &Document, f: ItemId) -> Option<(SpreadRef, Rect)> { let loc = d.find(f)?; @@ -359,6 +374,56 @@ mod tests { assert_eq!(diff, 0, "the moved text left {diff} stale channels behind"); } + #[test] + fn editing_the_story_of_an_anchored_text_frame_repaints_everything() { + let mut d = Document::new(&NewDocument { pages: 1, ..Default::default() }); + let lid = d.default_layer(); + let (_, host) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(72.0, 72.0, 300.0, 200.0), lid, "", ParaFormat::default()).unwrap(); + let (fid, sid) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(0.0, 0.0, 100.0, 40.0), lid, "Inner", ParaFormat::default()).unwrap(); + let it = d.item(fid).unwrap().clone(); + d.spread_mut(SpreadRef::Doc(0)).unwrap().items.retain(|i| i.id != fid); + d.story_mut(host).unwrap().insert_object(0, designcraft_doc::AnchoredObject::new(it, Default::default())); + d.check().unwrap(); + let cache = designcraft_compose::Cache::new(); + let _ = cache.get(&d, sid, None); + let old = d.clone(); + d.story_mut(sid).unwrap().insert(5, " text"); + assert!(damage(&old, &d).is_none()); + assert!(damage_with(&old, &d, Some(&cache)).is_none()); + } + + /// Only an anchored frame repaints everything: a frame on a spread damages its areas, and + /// one that is nowhere damages nothing. + #[test] + fn changed_frame_areas_repaint_everything_for_anchored_frames_only() { + let mut d = Document::new(&NewDocument { pages: 1, ..Default::default() }); + let lid = d.default_layer(); + let (on_spread, host) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(72.0, 72.0, 300.0, 200.0), lid, "", ParaFormat::default()).unwrap(); + let (fid, _) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(0.0, 0.0, 100.0, 40.0), lid, "Inner", ParaFormat::default()).unwrap(); + let it = d.item(fid).unwrap().clone(); + d.spread_mut(SpreadRef::Doc(0)).unwrap().items.retain(|i| i.id != fid); + d.story_mut(host).unwrap().insert_object(0, designcraft_doc::AnchoredObject::new(it, Default::default())); + assert!(changed_frame_areas(&d, &d, fid).is_none(), "anchored"); + assert_eq!(changed_frame_areas(&d, &d, on_spread).map(|a| a.len()), Some(2), "before and after"); + assert_eq!(changed_frame_areas(&d, &d, ItemId(u64::MAX)), Some(Vec::new()), "nowhere"); + } + + /// A frame on a spread in one document and anchored in the other repaints everything, both + /// ways: its anchored placement is drawn inside its host's text, outside the spread area. + #[test] + fn a_frame_moving_between_a_spread_and_an_anchor_repaints_everything() { + let mut on_spread = Document::new(&NewDocument { pages: 1, ..Default::default() }); + let lid = on_spread.default_layer(); + let (_, host) = on_spread.add_text_frame(SpreadRef::Doc(0), Rect::new(72.0, 72.0, 300.0, 200.0), lid, "", ParaFormat::default()).unwrap(); + let (fid, _) = on_spread.add_text_frame(SpreadRef::Doc(0), Rect::new(0.0, 0.0, 100.0, 40.0), lid, "Inner", ParaFormat::default()).unwrap(); + let mut anchored = on_spread.clone(); + let it = anchored.item(fid).unwrap().clone(); + anchored.spread_mut(SpreadRef::Doc(0)).unwrap().items.retain(|i| i.id != fid); + anchored.story_mut(host).unwrap().insert_object(0, designcraft_doc::AnchoredObject::new(it, Default::default())); + assert!(changed_frame_areas(&on_spread, &anchored, fid).is_none(), "spread to anchor"); + assert!(changed_frame_areas(&anchored, &on_spread, fid).is_none(), "anchor to spread"); + } + #[test] fn only_changed_frames_of_a_thread_are_damaged() { let mut d = Document::new(&NewDocument { pages: 3, facing_pages: false, ..Default::default() }); diff --git a/crates/render/src/stroke.rs b/crates/render/src/stroke.rs index 5b6d2e885..721c3ae17 100644 --- a/crates/render/src/stroke.rs +++ b/crates/render/src/stroke.rs @@ -1,4 +1,6 @@ -use super::color::{HIDDEN_LAYERS, PLATE, color_of, overprints, plate_pixmap, screen_color, set_fill_paint}; +use super::color::{ + HIDDEN_LAYERS, PLATE, color_of, effect_reach, image_effect_reach, overprints, plate_part, plate_pixmap, screen_color, set_fill_paint, +}; use super::pdf_raster::{is_pdf, shown_box_now}; use super::prepare::Prepared; use super::types::{DisplayQuality, Frame}; @@ -273,7 +275,8 @@ impl Renderer { Some(plate) => plate_pixmap(&pm, plate), None => pm, }; - paint_pixels(ctx, f, g, xf, page, width_pt, page_h, pm); + let to_image = image_space(page, width_pt, page_h, &pm); + paint_pixels(ctx, f, g, xf, page, to_image, pm); } None => loading(ctx), } @@ -293,38 +296,55 @@ impl Renderer { Prepared::Ready(coloured) => coloured, Prepared::Pending | Prepared::Failed => return loading(ctx), }; - let pm = match (coloured, PLATE.with(std::cell::Cell::get)) { - (Some(coloured), _) => coloured, - (None, Some(plate)) => plate_pixmap(&pm, plate), - (None, None) => pm, + // Where the whole image's pixels sit in graphic space (a plate part is placed inside it). + let to_image = image_space(page, page_w, page_h, &pm); + let (pm, at) = match (coloured, PLATE.with(std::cell::Cell::get)) { + (Some(coloured), _) => (coloured, (0, 0)), + (None, Some(plate)) => { + // Spread space → the image's pixels. + let to_pixels = (xf * g.xf * to_image).inverse(); + // The document is walked for effects only when a large image needs it. + let area = || { + let reach = image_effect_reach(f.doc, g).unwrap_or_else(|| effect_reach(f.doc)); + f.visible.inflate(reach, reach) + }; + match plate_part(&pm, plate, to_pixels, area) { + Some(part) => part, + None => return, + } + } + (None, None) => (pm, (0, 0)), }; - paint_pixels(ctx, f, g, xf, page, page_w, page_h, pm); + paint_pixels(ctx, f, g, xf, page, to_image * Affine::translate((f64::from(at.0), f64::from(at.1))), pm); } } -/// Draw `pm`, the pixels of a page `page_w` × `page_h` points at `page` in graphic `g`'s space. -#[allow(clippy::too_many_arguments)] +/// The pixels of `pm`, the image of a page `page_w` × `page_h` points at `page`, → graphic space (the paint transform; its inverse maps back to the pixels). +fn image_space(page: Rect, page_w: f64, page_h: f64, pm: &vello_cpu::Pixmap) -> Affine { + let sx = page_w / pm.width().max(1) as f64; + let sy = page_h / pm.height().max(1) as f64; + Affine::translate((page.x0, page.y0)) * Affine::scale_non_uniform(sx, sy) +} + +/// Draw `pm` in graphic `g`'s space, its pixels placed by `to_image`, where the page at `page` is. fn paint_pixels( ctx: &mut RenderContext, f: &Frame, g: &designcraft_doc::Graphic, xf: Affine, page: Rect, - page_w: f64, - page_h: f64, + to_image: Affine, pm: std::sync::Arc, ) { // Only where the page is: a box reaching past it (a media box larger than the crop box) // shows nothing there. let rect = Rect::new(0.0, 0.0, g.size.0, g.size.1).intersect(page); ctx.set_transform(f.view * xf * g.xf); - let sx = page_w / pm.width().max(1) as f64; - let sy = page_h / pm.height().max(1) as f64; ctx.set_paint(vello_cpu::Image { image: vello_cpu::ImageSource::Pixmap(pm), sampler: peniko::ImageSampler::default().with_quality(peniko::ImageQuality::Medium), }); - ctx.set_paint_transform(Affine::translate((page.x0, page.y0)) * Affine::scale_non_uniform(sx, sy)); + ctx.set_paint_transform(to_image); ctx.fill_rect(&rect); ctx.reset_paint_transform(); } diff --git a/crates/ui-egui/src/about.rs b/crates/ui-egui/src/about.rs index 90d6eb70f..eae44ea36 100644 --- a/crates/ui-egui/src/about.rs +++ b/crates/ui-egui/src/about.rs @@ -158,16 +158,24 @@ pub fn show(app: &mut DesignApp, ctx: &egui::Context) { let (r, _) = ui.allocate_exact_size(vec2(72.0, 72.0), Sense::hover()); paint_mark(ui, r, BRAND); ui.add_space(6.0); - ui.label(crate::rtl::widget( - ui, - egui::RichText::new(crate::i18n::tr(&app.ui.language, "DesignCraft")).font(semibold(26.0)).color(t.text_strong), - )); + // The channel's own name and version: DesignCraft (stable) or DesignCraft Nightly. + let channel = crate::channel::current(); + let app_name = match channel { + crate::channel::Channel::Stable => crate::i18n::tr(&app.ui.language, "DesignCraft").to_string(), + crate::channel::Channel::NightlyV1 => channel.name().to_string(), + }; + ui.label(crate::rtl::widget(ui, egui::RichText::new(app_name).font(semibold(26.0)).color(t.text_strong))); crate::rtl::label( ui, - egui::RichText::new(format!("{} {}", crate::i18n::tr(&app.ui.language, "Version"), env!("CARGO_PKG_VERSION"))) + egui::RichText::new(format!("{} {}", crate::i18n::tr(&app.ui.language, "Version"), crate::channel::version())) .size(12.0) .color(t.text_dim), ); + // A nightly build says which commit it was made from; the links below include Report an issue. + if let Some(commit) = crate::channel::commit() { + let short = commit.get(..12).unwrap_or(commit); + crate::rtl::label(ui, egui::RichText::new(format!("nightly-v1 · {short}")).size(11.0).color(t.text_dim)); + } ui.add_space(4.0); ui.label(crate::rtl::widget( ui, diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index e325caaa6..d23e9cde0 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -131,6 +131,8 @@ impl DesignApp { close_requested_pending: false, quit_without_asking: false, quitting: None, + lossy_save: None, + idml_loss_accepted: Default::default(), waiting_save: None, #[cfg(not(target_arch = "wasm32"))] opening: Vec::new(), diff --git a/crates/ui-egui/src/app/file_dialogs.rs b/crates/ui-egui/src/app/file_dialogs.rs index 3f17b0250..9d4db1b01 100644 --- a/crates/ui-egui/src/app/file_dialogs.rs +++ b/crates/ui-egui/src/app/file_dialogs.rs @@ -471,14 +471,17 @@ fn suggested_extension(name: &str) -> Option<&str> { } /// The file a save dialog's answer writes: `picked` with the suggested extension added when it has -/// none (Linux dialogs don't add it). A document always ends in `.designcraft`, as `file.save` -/// writes it. +/// none (Linux dialogs don't add it). A document keeps a typed `.idml` or `.designcraft` (its +/// extension decides the format `file.save` writes) and otherwise gets the suggested one, so +/// "Issue 3.1" saves as "Issue 3.1.idml" with IDML chosen (Preferences › Save documents as). #[cfg(not(target_arch = "wasm32"))] fn picked_save_path(picked: std::path::PathBuf, ext: Option<&str>) -> std::path::PathBuf { let Some(ext) = ext else { return picked }; - if ext.eq_ignore_ascii_case("designcraft") { - let p = picked.to_string_lossy(); - return designcraft_engine::cmd::with_document_extension(&p).into(); + if ext.eq_ignore_ascii_case("designcraft") || ext.eq_ignore_ascii_case("idml") { + if picked.file_name().is_none() { + return picked; + } + return crate::menus::run::with_save_extension(&picked.to_string_lossy(), ext).into(); } if picked.extension().is_some() || picked.file_name().is_none() { return picked; @@ -587,7 +590,7 @@ mod tests { fn save_dialog_answers_get_the_suggested_extension() { let save = |picked: &str, name: &str| picked_save_path(PathBuf::from(picked), suggested_extension(name)); assert_eq!(save("/d/Brochure", "Untitled.designcraft"), PathBuf::from("/d/Brochure.designcraft")); - assert_eq!(save("/d/Brochure.idml", "Untitled.designcraft"), PathBuf::from("/d/Brochure.idml.designcraft")); + assert_eq!(save("/d/Brochure.idml", "Untitled.designcraft"), PathBuf::from("/d/Brochure.idml"), "a typed .idml is written as IDML"); assert_eq!(save("/d/Brochure.designcraft", "Untitled.designcraft"), PathBuf::from("/d/Brochure.designcraft")); assert_eq!(save("/d/Brochure", "Untitled.pdf"), PathBuf::from("/d/Brochure.pdf")); assert_eq!(save("/d/Brochure.txt", "Untitled.rtf"), PathBuf::from("/d/Brochure.txt"), "another export format is kept"); diff --git a/crates/ui-egui/src/app/files.rs b/crates/ui-egui/src/app/files.rs index 54e6a006f..c35fc5c76 100644 --- a/crates/ui-egui/src/app/files.rs +++ b/crates/ui-egui/src/app/files.rs @@ -12,7 +12,7 @@ impl DesignApp { #[track_caller] pub fn pick_and_open(&mut self, purpose: &str) -> Result { if let Some(open) = self.services.open_async.as_mut() { - let request = ImportRequest { purpose: purpose.into(), target: self.session.active().map(|d| d.uid) }; + let request = ImportRequest { purpose: purpose.into(), target: self.session.active().map(|d| d.uid), wanted: Vec::new() }; open(request); return Ok(Value::Null); } @@ -129,7 +129,7 @@ impl DesignApp { designcraft_engine::cmd::has_doc(&self.session)?; if let Some(open) = self.services.open_async.as_mut() { let purpose = if kind.is_empty() { "styles".to_string() } else { format!("styles:{kind}") }; - open(ImportRequest { purpose, target: self.session.active().map(|d| d.uid) }); + open(ImportRequest { purpose, target: self.session.active().map(|d| d.uid), wanted: Vec::new() }); return Ok(Value::Null); } let kind = kind.to_string(); @@ -144,8 +144,33 @@ impl DesignApp { }) } + /// Ask an asynchronous host (web) for files for `purpose`; they arrive through the inbox. + /// `relink:{asset}` relinks that graphic from the chosen file; `relinkFiles` relinks every + /// missing graphic from the chosen files of the same names. + pub fn request_files(&mut self, purpose: &str) { + let mut request = self.import_request(purpose); + if purpose == "relinkFiles" { + // Only the missing graphics' files are read from the chosen folder. + let rows = self.session.execute("links.list", &json!({})).ok().and_then(|v| v.as_array().cloned()).unwrap_or_default(); + request.wanted = rows + .iter() + .filter(|r| r["asset"].is_u64() && r["status"] == "missing") + .filter_map(|r| r["path"].as_str().or(r["name"].as_str())) + .map(|p| file_name_of(p).to_lowercase()) + .collect(); + // Nothing to relink: don't have the host read a whole folder for nothing. + if request.wanted.is_empty() { + self.status(crate::i18n::tr(&self.ui.language, "No missing graphics to relink")); + return; + } + } + if let Some(open) = self.services.open_async.as_mut() { + open(request); + } + } + pub fn import_request(&self, purpose: &str) -> ImportRequest { - ImportRequest { purpose: purpose.into(), target: self.session.active().map(|d| d.uid) } + ImportRequest { purpose: purpose.into(), target: self.session.active().map(|d| d.uid), wanted: Vec::new() } } pub(crate) fn activate_import_target(&mut self, request: &ImportRequest) -> Result<(), String> { @@ -202,6 +227,7 @@ impl DesignApp { } let Some(inbox) = self.services.inbox.clone() else { return }; let files = std::mem::take(&mut *inbox.lock().unwrap_or_else(std::sync::PoisonError::into_inner)); + let files = self.relink_from_inbox(files); // A browser delivers one Place's files together. Several go to the place cursor, even a // PDF first with a frame selected, as a native batch's do. let batch = files.iter().filter(|f| f.request.purpose == "place").count() > 1; @@ -506,6 +532,67 @@ impl DesignApp { r } + /// Relink graphics from delivered files, returning the files left to import. Files chosen + /// to relink (`relink:{asset}`, `relinkFiles`) relink, each request's files in one undo step; + /// every other file (a dropped one too) is placed or opened as before. + fn relink_from_inbox(&mut self, files: Vec) -> Vec { + let mut rest = Vec::new(); + // (request, files) in arrival order; a request's files arrive together. + let mut batches: Vec<(ImportRequest, Vec)> = Vec::new(); + for file in files { + if !file.request.purpose.starts_with("relink") { + rest.push(file); + continue; + } + match batches.iter_mut().find(|(r, _)| r.purpose == file.request.purpose && r.target == file.request.target) { + Some((_, b)) => b.push(file), + None => batches.push((file.request.clone(), vec![file])), + } + } + for (request, batch) in batches { + if self.activate_import_target(&request).is_err() { + continue; + } + // A file from a chosen folder is named by its path in it (which tells same-named + // files apart). + let list: Vec = batch + .iter() + .map(|f| json!({"name": file_name_of(&f.name), "path": f.name, "base64": designcraft_engine::cmd::base64_encode(&f.bytes)})) + .collect(); + let mut params = json!({"files": list}); + if let Some(aid) = request.purpose.strip_prefix("relink:").and_then(|a| a.parse::().ok()) { + params["asset"] = json!(aid); + } + match self.run("links.relinkFiles", params) { + Ok(v) => { + let n = v["relinked"].as_u64().unwrap_or(0); + let unsure = v["ambiguous"].as_array().map_or(0, Vec::len); + let unread: Vec<&str> = v["failed"].as_array().map(|f| f.iter().filter_map(|f| f["name"].as_str()).collect()).unwrap_or_default(); + if !unread.is_empty() { + // Matching files that couldn't be read: their graphics stay missing. + self.status( + crate::i18n::tr(&self.ui.language, "Relinked {count}; couldn't read {files}") + .replace("{count}", &n.to_string()) + .replace("{files}", &unread.join(", ")), + ); + } else if unsure > 0 { + // Files named like graphics they couldn't be told apart for: neither + // relinked nor placed. + self.status( + crate::i18n::tr(&self.ui.language, "Relinked {count}; {unsure} left missing: same-named files couldn't be told apart") + .replace("{count}", &n.to_string()) + .replace("{unsure}", &unsure.to_string()), + ); + } else { + self.status(crate::i18n::tr(&self.ui.language, "Relinked {count}").replace("{count}", &n.to_string())); + } + } + Err(e) => self.status(e), + } + } + rest + } + /// Applies what the background checks of linked files found, shows the notice about images /// that will be saved as links once, and repaints at a low rate while checks run so the /// Links panel's statuses fill in. @@ -575,6 +662,11 @@ impl DesignApp { } } +/// The last component of a delivered file's name (either kind of separator). +fn file_name_of(name: &str) -> &str { + name.rsplit(['/', '\\']).next().unwrap_or(name) +} + /// Graphics that can wait in the place cursor, several at a time: raster images, SVG, PSD and /// EPS. A PDF can't (it may ask which page), nor can text, media or documents. pub(crate) fn is_cursor_image(name: &str) -> bool { @@ -712,6 +804,102 @@ pub(crate) mod browser_import_tests { app.run("file.new", json!({"title": "A"})).unwrap(); app } + /// The placed graphic's link made missing, as an IDML opened in the browser without its + /// Links folder leaves it. + fn make_missing(app: &mut DesignApp) -> designcraft_doc::AssetId { + let aid = *app.session.doc().unwrap().doc.assets.keys().next().unwrap(); + app.session + .edit(|d, _| { + let a = std::sync::Arc::make_mut(d.assets.get_mut(&aid).unwrap()); + a.link = Some("/Users/someone/Links/a.svg".into()); + a.name = "a.svg".into(); + a.data = designcraft_doc::AssetData::embedded(Vec::new()); + // No copy of its own: a link whose file wasn't read. + a.link_hash = None; + Ok(()) + }) + .unwrap(); + aid + } + fn items(app: &DesignApp) -> usize { + app.session.doc().unwrap().doc.spreads.iter().map(|s| s.items.len()).sum() + } + + /// With no missing graphic, Relink to Folder doesn't ask the host for a folder at all. + #[test] + fn relink_to_folder_needs_a_missing_graphic() { + let asked = std::rc::Rc::new(std::cell::RefCell::new(Vec::new())); + let mut app = app(); + let seen = asked.clone(); + app.services.open_async = Some(Box::new(move |r: ImportRequest| seen.borrow_mut().push(r))); + let b64 = designcraft_engine::cmd::base64_encode(&image()); + app.run("file.place", json!({"name": "a.svg", "base64": b64, "x": 50, "y": 50})).unwrap(); + app.request_files("relinkFiles"); + assert!(asked.borrow().is_empty()); + assert_eq!(app.ui.status, "No missing graphics to relink"); + } + + /// Relink to Folder asks the host only for the missing graphics' files, and a chosen folder's + /// files arrive named by their paths in it, which tell same-named files apart. + #[test] + fn relink_to_folder_asks_for_the_missing_names_and_matches_by_path() { + let asked = std::rc::Rc::new(std::cell::RefCell::new(Vec::new())); + let mut app = app(); + let seen = asked.clone(); + app.services.open_async = Some(Box::new(move |r: ImportRequest| seen.borrow_mut().push(r))); + let b64 = designcraft_engine::cmd::base64_encode(&image()); + app.run("file.place", json!({"name": "a.svg", "base64": b64, "x": 50, "y": 50})).unwrap(); + let aid = make_missing(&mut app); + app.request_files("relinkFiles"); + let request = asked.borrow_mut().pop().unwrap(); + assert_eq!(request.wanted, ["a.svg"]); + // The link is /Users/someone/Links/a.svg: the file in a folder named Links is the one. + let wrong = br##""##.to_vec(); + for (name, bytes) in [("Volume/Old/a.svg", wrong), ("Volume/Links/a.svg", image())] { + app.services.inbox.as_ref().unwrap().lock().unwrap().push(ImportedFile { request: request.clone(), name: name.into(), bytes }); + } + app.drain_inbox(); + let a = &app.session.doc().unwrap().doc.assets[&aid]; + assert_eq!(a.data.resident().as_deref(), Some(&image()), "the Links folder's file: {}", app.ui.status); + } + + /// The web build relinks from files it is handed: chosen with Relink… (one graphic) or + /// Relink to Folder… (several at once). A dropped image is placed as before, even one named + /// like a missing graphic. + #[test] + fn delivered_files_relink_missing_graphics() { + let mut app = app(); + let b64 = designcraft_engine::cmd::base64_encode(&image()); + app.run("file.place", json!({"name": "a.svg", "base64": b64, "x": 50, "y": 50})).unwrap(); + let aid = make_missing(&mut app); + let n = items(&app); + let has_data = |app: &DesignApp| !app.session.doc().unwrap().doc.assets[&aid].data.is_empty(); + let request = app.import_request("relinkFiles"); + deliver(&mut app, request, "a.svg", image()); + assert!(has_data(&app), "{}", app.ui.status); + assert_eq!(app.session.doc().unwrap().doc.assets[&aid].link.as_deref(), Some("/Users/someone/Links/a.svg")); + // A dropped image goes to the place cursor, as any does, even when it is named like a + // missing graphic. + make_missing(&mut app); + app.run("edit.deselectAll", json!({})).unwrap(); + let request = app.import_request("drop"); + deliver(&mut app, request, "A.SVG", image()); + assert!(!has_data(&app), "the dropped file doesn't relink"); + assert!(app.session.loaded.is_some(), "it is in the place cursor"); + assert_eq!(items(&app), n, "nothing placed yet"); + // Relink… for one graphic: the chosen file, whatever its name. + make_missing(&mut app); + let request = app.import_request(&format!("relink:{}", aid.0)); + deliver(&mut app, request, "renamed.svg", image()); + assert_eq!(app.session.doc().unwrap().doc.assets[&aid].link.as_deref(), Some("renamed.svg")); + // A matching file that can't be read is named in the status, its graphic left missing. + make_missing(&mut app); + let request = app.import_request("relinkFiles"); + deliver(&mut app, request, "a.svg", b"not an image".to_vec()); + assert!(!has_data(&app)); + assert!(app.ui.status.contains("couldn't read a.svg"), "{}", app.ui.status); + } + fn deliver(app: &mut DesignApp, request: ImportRequest, name: &str, bytes: Vec) { app.services.inbox.as_ref().unwrap().lock().unwrap().push(ImportedFile { request, name: name.into(), bytes }); app.drain_inbox(); diff --git a/crates/ui-egui/src/app/quit.rs b/crates/ui-egui/src/app/quit.rs index c1c67a493..c99c9e722 100644 --- a/crates/ui-egui/src/app/quit.rs +++ b/crates/ui-egui/src/app/quit.rs @@ -55,8 +55,9 @@ impl DesignApp { } let Some(q) = self.quitting.as_ref() else { return }; if q.saving.is_some() { - // Waiting for the save dialog; cancelled, it answers without saving and Quit stops. - if !self.file_dialogs_pending() { + // Waiting for the save dialog (or the IDML loss question); cancelled, it answers + // without saving and Quit stops. + if !self.file_dialogs_pending() && self.lossy_save.is_none() { self.cancel_quit(); } return; diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 7e2626ad7..5b3aa63f2 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -30,9 +30,9 @@ mod tool_overlays; mod view; use column_guides::{COLUMN_DRAG, ColumnDrag, column_guide_at, spread_x_across}; -use frames::{draw_frames, draw_selection}; #[cfg(test)] -use frames::{frame_x, item_canvas_xf, overset_frames, overset_marks, ported_frames, text_frames_in}; +use frames::{LinkBadge, frame_x, item_canvas_xf, overset_frames, overset_marks, ported_frames, text_frames_in}; +use frames::{draw_frames, draw_link_badge, draw_selection, link_badges, link_statuses}; use guides::{GUIDE_DRAG, GUIDE_PRESS, GuideDrag, GuidePress, guide_readout, guide_spot, moving_guides, readout_at}; #[cfg(test)] use guides::{guide_at, guide_drag_delta, guide_measure}; @@ -220,6 +220,17 @@ fn present_click(app: &mut DesignApp, ui: &egui::Ui, resp: &egui::Response, rect } } +/// View ▸ Show Link Badges: each placed graphic's link status in its corner. +fn draw_link_badges(app: &mut DesignApp, ctx: &egui::Context, painter: &egui::Painter, doc: &Document, layout: &CanvasLayout, xf: &Xf) { + if !app.ui.link_badge { + return; + } + let status = link_statuses(app, ctx, doc); + for (c, badge, col) in link_badges(doc, layout, xf, &status) { + draw_link_badge(painter, c, badge, col); + } +} + /// Lay out the canvas, scrollbars and rulers, presentation mode, fit/view state, input handling and painting. pub fn show(app: &mut DesignApp, ui: &mut egui::Ui) { let t = Tokens::get(ui.ctx()); @@ -326,6 +337,7 @@ pub fn show(app: &mut DesignApp, ui: &mut egui::Ui) { painter.circle_stroke(c, 8.0, Stroke::new(1.5, Color32::from_white_alpha(170))); painter.circle_stroke(c, 4.0, Stroke::new(1.5, Color32::from_white_alpha(170))); } + draw_link_badges(app, ui.ctx(), &painter, &doc, &layout, &xf); } draw_tool_overlays(app, &painter, &xf); ime_canvas_pass(app, ui.ctx(), &xf); diff --git a/crates/ui-egui/src/canvas/frames.rs b/crates/ui-egui/src/canvas/frames.rs index e557c9b1d..1e3772284 100644 --- a/crates/ui-egui/src/canvas/frames.rs +++ b/crates/ui-egui/src/canvas/frames.rs @@ -206,6 +206,152 @@ pub(super) fn selection_color(app: &DesignApp) -> Color32 { st.selection.items.first().and_then(|id| st.doc.item(*id)).map_or(fallback, |it| layer_color(&st.doc, it)) } +/// What a link badge shows: the chain of a linked file, or the trouble the Links panel reports. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum LinkBadge { + Linked, + Modified, + Missing, +} + +/// Reuse the Links panel's persistent worker and its per-file checks. Both surfaces see the +/// same results, without a second worker or repeated whole-file reads just for canvas badges. +pub(super) fn link_statuses(app: &mut DesignApp, ctx: &egui::Context, doc: &Document) -> std::collections::HashMap { + if !doc.assets.values().any(|a| a.link.is_some()) { + return Default::default(); + } + let Some(st) = app.session.active() else { return Default::default() }; + #[cfg(not(target_arch = "wasm32"))] + let rows = { + let doc = std::sync::Arc::clone(&st.doc); + let snapshot = crate::links_worker::Snapshot { + key: crate::links_worker::Key::new(st.uid, &doc, st.path.as_deref()), + doc: std::sync::Arc::clone(&doc), + cache: std::sync::Arc::clone(&app.session.cache), + document: st.path.as_ref().map(std::path::PathBuf::from), + }; + let refresh = app.links_worker.rows(ctx, snapshot); + if !refresh.verified.is_empty() { + designcraft_engine::cmd::remember_link_files(&mut app.session, &doc, &refresh.verified); + } + refresh.values + }; + #[cfg(target_arch = "wasm32")] + let rows = { + let _ = ctx; + designcraft_engine::cmd::preview_document_links(doc, &app.session.cache, st.path.as_deref().map(std::path::Path::new)) + }; + rows.iter() + .filter_map(|row| { + let id = row["asset"].as_u64()?; + doc.assets.get(&designcraft_doc::AssetId(id))?.link.as_ref()?; + Some((id, row["status"].as_str()?.to_owned())) + }) + .collect() +} + +/// View › Extras › Show Link Badge: every frame showing a linked file carries a badge on its top +/// edge, near the left corner, in its layer's colour, as InDesign marks placed files. A modified +/// link shows a warning and a missing one a stop instead, as in the Links panel. Returns each +/// badge's screen centre, kind and colour. +pub(super) fn link_badges( + doc: &Document, + layout: &CanvasLayout, + xf: &Xf, + status: &std::collections::HashMap, +) -> Vec<(Pos2, LinkBadge, Color32)> { + fn walk( + doc: &Document, + xf: &Xf, + it: &Item, + a: Affine, + status: &std::collections::HashMap, + out: &mut Vec<(Pos2, LinkBadge, Color32)>, + ) { + if it.hidden || doc.layer(it.layer).is_some_and(|l| !l.visible) { + return; + } + match &it.content { + Content::Group { .. } => { + for c in it.shown_children() { + walk(doc, xf, c, a * it.xf, status, out); + } + } + Content::Graphic(g) => { + if doc.assets.get(&g.asset).is_none_or(|asset| asset.link.is_none()) { + return; + } + // On the frame's own top edge (rotated with it), 16 px in from its left corner. + let b = it.inner_bounds(); + let m = a * it.xf; + let (tl, tr) = (xf.to_screen(m * Point::new(b.x0, b.y0)), xf.to_screen(m * Point::new(b.x1, b.y0))); + let len = (tr - tl).length(); + if !len.is_finite() { + return; + } + let at = if len > 0.0 { tl + (tr - tl) / len * 16.0f32.min(len / 2.0) } else { tl }; + let badge = match status.get(&g.asset.0).map(String::as_str) { + Some("missing") => LinkBadge::Missing, + Some("modified") => LinkBadge::Modified, + _ => LinkBadge::Linked, + }; + out.push((at, badge, layer_color(doc, it))); + } + _ => {} + } + } + let mut out = Vec::new(); + for slot in &layout.slots { + let Some(sp) = doc.spread(slot.spread) else { continue }; + // Parent items shown on the pages (not those a page overrides), as draw_frames finds them. + for (pi, page) in sp.pages.iter().enumerate() { + let overridden = doc.overridden_parent_items(slot.spread, pi); + for (ppi, ppg) in doc.shown_parent_pages(slot.spread, pi) { + let Some(parent) = doc.parents.get(ppi) else { continue }; + let Some(ppage) = parent.pages.get(ppg) else { continue }; + let dx = page.x - ppage.x; + for it in &parent.items { + if (parent.pages.len() > 1 && parent.page_at_x(it.bounds().center().x) != Some(ppg)) || overridden.contains(&it.id) { + continue; + } + walk(doc, xf, it, slot.xf * Affine::translate((dx, 0.0)), status, &mut out); + } + } + } + for it in &sp.items { + walk(doc, xf, it, slot.xf, status, &mut out); + } + } + out +} + +/// A link badge centred on `c`: two interlocked links on a light halo, so it reads over any +/// picture; a red stop with a question mark for a missing file, a yellow warning for a modified +/// one. Drawn in code. +pub(super) fn draw_link_badge(painter: &egui::Painter, c: Pos2, badge: LinkBadge, col: Color32) { + match badge { + LinkBadge::Linked => { + painter.rect_filled(Rect::from_center_size(c, vec2(24.0, 13.0)), 6.5, Color32::from_white_alpha(235)); + let dark = |v: u8| (f32::from(v) * 0.55) as u8; + let ink = Color32::from_rgb(dark(col.r()), dark(col.g()), dark(col.b())); + for dx in [-4.0, 4.0] { + painter.rect_stroke(Rect::from_center_size(c + vec2(dx, 0.0), vec2(12.0, 7.0)), 3.5, Stroke::new(1.8, ink), StrokeKind::Middle); + } + } + LinkBadge::Missing => { + painter.circle_filled(c, 7.0, Color32::WHITE); + painter.circle_filled(c, 6.0, Color32::from_rgb(214, 38, 38)); + painter.text(c, egui::Align2::CENTER_CENTER, "?", egui::FontId::proportional(10.0), Color32::WHITE); + } + LinkBadge::Modified => { + let tri = |h: f32| vec![c + vec2(0.0, -h), c + vec2(h * 1.1, h * 0.8), c + vec2(-h * 1.1, h * 0.8)]; + painter.add(egui::Shape::convex_polygon(tri(7.5), Color32::WHITE, Stroke::NONE)); + painter.add(egui::Shape::convex_polygon(tri(6.0), Color32::from_rgb(250, 200, 30), Stroke::NONE)); + painter.text(c + vec2(0.0, 1.0), egui::Align2::CENTER_CENTER, "!", egui::FontId::proportional(9.0), Color32::BLACK); + } + } +} + pub(super) fn layer_color(doc: &Document, it: &Item) -> Color32 { doc.layer(it.layer).map(|l| c32(l.color)).unwrap_or(Color32::from_rgb(79, 153, 255)) } diff --git a/crates/ui-egui/src/canvas/render.rs b/crates/ui-egui/src/canvas/render.rs index f33fc9ea0..9e4dcdb4e 100644 --- a/crates/ui-egui/src/canvas/render.rs +++ b/crates/ui-egui/src/canvas/render.rs @@ -95,7 +95,7 @@ pub struct DisplayKey { highlight_custom_tracking: bool, } -fn display_key(app: &DesignApp) -> DisplayKey { +pub(super) fn display_key(app: &DesignApp) -> DisplayKey { let (ui, prefs) = (&app.ui, &app.session.prefs); DisplayKey { quality: ui.display_quality, @@ -150,6 +150,11 @@ pub(super) fn image_generation(seen: &mut (u64, f64), live: u64, now: f64, rende pub(super) fn render_texture(app: &mut DesignApp, ctx: &egui::Context, rect: Rect, xf: &Xf, layout: &CanvasLayout, preview: bool) { invalidate_on_display_change(app); let Some(st) = app.session.active() else { return }; + // The copy of the canvas's pixels serves the text highlight only: none without a text + // selection, so a canvas without one holds no second full-size image. + if st.selection.text.is_none() { + app.canvas.pixels = None; + } let ppp = ctx.pixels_per_point() as f64; let doc_key = (st.uid, std::sync::Arc::as_ptr(&st.doc) as u64, st.revision, preview); let editing_parents = st.editing_parents; @@ -194,7 +199,10 @@ pub(super) fn render_texture(app: &mut DesignApp, ctx: &egui::Context, rect: Rec x0 >= -0.5 && y0 >= -0.5 && x0 + rect.width() as f64 <= s.size.0 as f64 + 0.5 && y0 + rect.height() as f64 <= s.size.1 as f64 + 0.5 } }; - if app.canvas.shown.is_some_and(|s| covers(&s)) { + // Text just selected: the highlight needs the canvas's pixels (see `upload`), so the view is + // rendered again, on the worker, to keep a copy. + let needs_pixels = app.canvas.pixels.is_none() && app.session.active().is_some_and(|st| st.selection.text.is_some()); + if app.canvas.shown.is_some_and(|s| covers(&s)) && !needs_pixels { return; } let doc_changed = app.canvas.shown.is_none_or(|s| s.doc != doc_key); @@ -313,11 +321,26 @@ fn patch_texture(app: &mut DesignApp, layout: &CanvasLayout, ppp: f64, doc_key: * Affine::scale(sh.zoom) * Affine::translate((-sh.origin.x, -sh.origin.y)); let opts = screen_options(app, layout, preview, ppp); - let img = app.canvas.patcher.render(&new, &app.session.cache, &placed, ((x1 - x0) as u32, (y1 - y0) as u32), view, &opts); + let mut img = app.canvas.patcher.render(&new, &app.session.cache, &placed, ((x1 - x0) as u32, (y1 - y0) as u32), view, &opts); + // Proof Colors as for a full upload: the repainted region (and the highlight's copy of it) + // showed the unproofed colours until the next full render. + screen_post(app, &mut img); let ci = egui::ColorImage::from_rgba_premultiplied([img.width as usize, img.height as usize], &img.pixels); if let Some(tex) = app.canvas.texture.as_mut() { tex.set_partial([x0 as usize, y0 as usize], ci, egui::TextureOptions::LINEAR); } + // The same region in the canvas's own copy of its pixels. + if let Some(all) = app.canvas.pixels.as_mut() { + let all = std::sync::Arc::make_mut(all); + let (aw, pw) = (all.width as usize, img.width as usize); + for (row, src) in img.pixels.chunks_exact(pw * 4).enumerate() { + let start = ((y0 as usize + row) * aw + x0 as usize) * 4; + if let Some(dst) = all.pixels.get_mut(start..start + pw * 4) { + dst.copy_from_slice(src); + } + } + app.canvas.pixels_generation += 1; + } done(app); app.canvas.patches += 1; app.perf.render_ms = crate::now_ms() - t0; @@ -351,4 +374,8 @@ fn upload(app: &mut DesignApp, ctx: &egui::Context, mut img: designcraft_render: Some(tex) => tex.set(ci, egui::TextureOptions::LINEAR), None => app.canvas.texture = Some(ctx.load_texture("canvas", ci, egui::TextureOptions::LINEAR)), } + // Kept only while text is selected (see `render_texture`). + let selecting = app.session.active().is_some_and(|st| st.selection.text.is_some()); + app.canvas.pixels = selecting.then(|| std::sync::Arc::new(img)); + app.canvas.pixels_generation += 1; } diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 914777616..55bd1c338 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -1,6 +1,7 @@ use designcraft_geom::Unit; use egui_kittest::{Harness, kittest::Queryable}; +use super::text_overlay::inverse_under; use super::*; /// A place-cursor drag past its 3-point threshold but short of egui's drag distance previews @@ -235,6 +236,126 @@ fn bleed_and_slug_are_preview_modes_that_show_their_area() { } } +/// A picture placed from a file carries the link badge on its frame's top edge, near the left +/// corner, as in the tutorial's chapter 10; an embedded picture has none, a missing file shows +/// the stop instead, and View › Extras hides the badges. +#[test] +fn linked_pictures_carry_the_link_badge() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let png = designcraft_render::Rendered { width: 40, height: 20, pixels: vec![200; 40 * 20 * 4] }.to_png(); + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("snowflake.png"); + std::fs::write(&path, &png).unwrap(); + let linked = app.run("frame.create", json!({"rect": [72, 72, 272, 172]})).unwrap()["id"].as_u64().unwrap(); + app.run("file.place", json!({"path": path.to_string_lossy(), "frame": linked})).unwrap(); + let embedded = app.run("frame.create", json!({"rect": [72, 300, 272, 400]})).unwrap()["id"].as_u64().unwrap(); + app.run("file.place", json!({"base64": designcraft_engine::cmd::base64_encode(&png), "name": "e.png", "frame": embedded})).unwrap(); + let ctx = egui::Context::default(); + let xf = Xf::new(Rect::from_min_size(Pos2::ZERO, vec2(1440.0, 900.0)), &View::default()); + // The check runs off the UI thread: ask until the result for this document state is in. + let badges = |app: &mut DesignApp, expected: &str| { + let doc = app.session.active().unwrap().doc.clone(); + for _ in 0..1000 { + let status = link_statuses(app, &ctx, &doc); + if !status.is_empty() && status.values().all(|s| s == expected) { + return link_badges(&doc, &CanvasLayout::new(&doc, false), &xf, &status); + } + std::thread::sleep(std::time::Duration::from_millis(2)); + } + panic!("the link check didn't finish"); + }; + let b = badges(&mut app, "ok"); + assert_eq!(b.len(), 1, "only the linked picture: {b:?}"); + assert_eq!(b[0].1, LinkBadge::Linked); + let doc = app.session.active().unwrap().doc.clone(); + let layout = CanvasLayout::new(&doc, false); + let (a, _) = item_canvas_xf(&doc, &layout, designcraft_doc::ItemId(linked)).unwrap(); + let r = doc.item(designcraft_doc::ItemId(linked)).unwrap().bounds(); + let corner = xf.to_screen(a * Point::new(r.x0, r.y0)); + let d = b[0].0 - corner; + assert!(d.y.abs() < 0.5 && d.x > 0.0 && d.x <= 16.5, "on the top edge near the left corner: {d:?}"); + // Rotated, the badge stays on the frame's own top edge, 16 px from its corner along it. + app.run("transform.set", json!({"ids": [linked], "rotation": 30})).unwrap(); + let doc = app.session.active().unwrap().doc.clone(); + let it = doc.item(designcraft_doc::ItemId(linked)).unwrap().clone(); + let (a, _) = item_canvas_xf(&doc, &CanvasLayout::new(&doc, false), designcraft_doc::ItemId(linked)).unwrap(); + let ib = it.inner_bounds(); + let (tl, tr) = (xf.to_screen(a * it.xf * Point::new(ib.x0, ib.y0)), xf.to_screen(a * it.xf * Point::new(ib.x1, ib.y0))); + let c = badges(&mut app, "ok")[0].0; + let along = (tr - tl).normalized(); + let off = c - tl; + assert!((off.dot(along) - 16.0).abs() < 0.5 && (off.x * along.y - off.y * along.x).abs() < 0.5, "on the rotated top edge: {off:?}"); + app.run("edit.undo", json!({})).unwrap(); + // A linked picture on the parent page shows its badge on the document page that shows it + // (the first page is a right-hand one: the parent's right page). + let px = app.session.active().unwrap().doc.parents[0].pages[1].x; + let pf = app.run("frame.create", json!({"rect": [px + 300.0, 500, px + 400.0, 600], "spread": {"kind": "parent", "index": 0}})).unwrap()["id"] + .as_u64() + .unwrap(); + app.run("file.place", json!({"path": path.to_string_lossy(), "frame": pf})).unwrap(); + assert_eq!(badges(&mut app, "ok").len(), 2, "the parent page's picture too"); + // The file gone: the badge says so (the check runs again once the document changes). + std::fs::remove_file(&path).unwrap(); + app.run("frame.create", json!({"rect": [400, 400, 420, 420]})).unwrap(); + assert_eq!(badges(&mut app, "missing")[0].1, LinkBadge::Missing); + // View › Extras › Hide Link Badge. + assert_eq!(crate::menus::checked(&app, "view.linkBadge", &json!({})), Some(true)); + app.run("view.linkBadge", json!({})).unwrap(); + assert!(!app.ui.link_badge); + assert_eq!(crate::menus::checked(&app, "view.linkBadge", &json!({})), Some(false)); + // Check the drawing entry point, not just the toggle's stored value. + let doc = app.session.active().unwrap().doc.clone(); + let layout = CanvasLayout::new(&doc, false); + let paint = |app: &mut DesignApp| { + let mut output = ctx.run_ui(egui::RawInput::default(), |ui| { + draw_link_badges(app, ui.ctx(), ui.painter(), &doc, &layout, &xf); + }); + output.textures_delta.clear(); + output.shapes.iter().filter(|shape| matches!(shape.shape, egui::Shape::Circle(_))).count() + }; + assert_eq!(paint(&mut app), 0, "hidden badges draw no missing-file circles"); + app.run("view.linkBadge", json!({})).unwrap(); + assert!(paint(&mut app) > 0, "shown badges draw the missing-file circles"); +} + +/// The badge is editing chrome for visible artwork, so inactive object states do not show it. +#[test] +fn link_badges_follow_the_active_object_state() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let dir = tempfile::tempdir().unwrap(); + let file = dir.path().join("state.png"); + std::fs::write(&file, designcraft_render::Rendered { width: 10, height: 10, pixels: vec![200; 400] }.to_png()).unwrap(); + let mut ids = Vec::new(); + for x in [72, 300] { + let id = app.run("frame.create", json!({"rect": [x, 72, x + 100, 172]})).unwrap()["id"].as_u64().unwrap(); + app.run("file.place", json!({"path": file, "frame": id})).unwrap(); + ids.push(id); + } + let group = app.run("object.group", json!({"ids": ids})).unwrap()["id"].as_u64().unwrap(); + let xf = Xf::new(Rect::from_min_size(Pos2::ZERO, vec2(1440.0, 900.0)), &View::default()); + let badges = |app: &DesignApp| { + let doc = &app.session.active().unwrap().doc; + link_badges(doc, &CanvasLayout::new(doc, false), &xf, &std::collections::HashMap::new()) + }; + let all = badges(&app); + assert_eq!(all.len(), 2, "ordinary groups show all linked children"); + for (active, expected) in all.iter().enumerate() { + app.session + .edit(|d, _| { + let group = d.item_mut(designcraft_doc::ItemId(group)).unwrap(); + group.states = vec!["First".into(), "Second".into()]; + group.active_state = active; + Ok(()) + }) + .unwrap(); + let shown = badges(&app); + assert_eq!(shown.len(), 1, "only the active state has a badge"); + assert_eq!(shown[0], *expected); + } +} + /// An empty graphic frame's X joins its corners: a rectangle's, and a frame slanted by /// moving its top points, as in the Zero2Graphic tutorial's row of parallelograms. #[test] @@ -3409,6 +3530,105 @@ fn trailing_spaces_show_dots_before_the_paragraph_mark() { } } +/// Capture the text shapes emitted by the hidden-character painter for the supplied canvas. +fn painted_hidden_character_marks(app: &DesignApp, doc: &Document, layout: &CanvasLayout) -> Vec { + let ctx = egui::Context::default(); + let xf = Xf::new(Rect::from_min_size(Pos2::ZERO, vec2(1440.0, 900.0)), &View::default()); + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| { + draw_hidden_characters(app, ui.painter(), &xf, doc, layout); + }); + out.textures_delta.clear(); + out.shapes + .iter() + .filter_map(|s| match &s.shape { + egui::Shape::Text(t) => Some(t.galley.text().to_owned()), + _ => None, + }) + .collect() +} + +/// #1994: hiding a frame or its layer must also hide the separately painted marks. +#[test] +fn hidden_characters_follow_frame_layer_and_group_visibility() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let frame = app.run("frame.create", json!({"rect": [36, 36, 336, 136], "content": "text", "text": "a b\tc\nd"})).unwrap(); + let id = designcraft_doc::ItemId(frame["id"].as_u64().unwrap()); + let mut doc = (*app.session.active().unwrap().doc).clone(); + let layer = doc.item(id).unwrap().layer; + let marks = |app: &DesignApp, doc: &Document| painted_hidden_character_marks(app, doc, &CanvasLayout::new(doc, false)); + let expected = marks(&app, &doc); + for mark in ["·", "»", "¶", "#"] { + assert!(expected.iter().any(|m| m == mark), "visible text draws {mark}: {expected:?}"); + } + doc.layer_mut(layer).unwrap().visible = false; + assert!(marks(&app, &doc).is_empty(), "hidden layers draw no marks"); + doc.layer_mut(layer).unwrap().visible = true; + assert_eq!(marks(&app, &doc), expected, "showing the layer restores its marks"); + doc.item_mut(id).unwrap().hidden = true; + assert!(marks(&app, &doc).is_empty(), "hidden frames draw no marks"); + doc.item_mut(id).unwrap().hidden = false; + doc.layer_mut(layer).unwrap().locked = true; + assert_eq!(marks(&app, &doc), expected, "locked but visible layers still show marks"); + + // A child stays individually visible when its containing group is hidden. + let sibling = app.run("frame.create", json!({"rect": [400, 36, 450, 86]})).unwrap(); + app.run("selection.set", json!({"ids": [id.0, sibling["id"]]})).unwrap(); + let group = app.run("object.group", json!({})).unwrap(); + let group_id = designcraft_doc::ItemId(group["id"].as_u64().unwrap()); + let mut grouped = (*app.session.active().unwrap().doc).clone(); + assert_eq!(marks(&app, &grouped), expected); + grouped.item_mut(group_id).unwrap().hidden = true; + assert!(marks(&app, &grouped).is_empty(), "hidden groups draw no child marks"); +} + +/// Parent editing and viewport culling must not paint marks for a spread absent from the layout. +#[test] +fn hidden_characters_only_paint_laid_out_spreads() { + let app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + let mut doc = Document::new(&designcraft_doc::build::NewDocument::default()); + let layer = doc.default_layer(); + let rect = DRect::new(36.0, 36.0, 336.0, 136.0); + doc.add_text_frame(SpreadRef::Doc(0), rect, layer, "a b", Default::default()).unwrap(); + let document_layout = CanvasLayout::new(&doc, false); + let parent_layout = CanvasLayout::new(&doc, true); + assert!(!painted_hidden_character_marks(&app, &doc, &document_layout).is_empty()); + assert!(painted_hidden_character_marks(&app, &doc, &parent_layout).is_empty(), "document marks stay off the parent canvas"); + doc.add_text_frame(SpreadRef::Parent(0), rect, layer, "a\tb", Default::default()).unwrap(); + let document_marks = painted_hidden_character_marks(&app, &doc, &document_layout); + let parent_marks = painted_hidden_character_marks(&app, &doc, &parent_layout); + assert_eq!(document_marks, ["·", "#"], "parent marks stay off the document canvas"); + assert_eq!(parent_marks, ["»", "#"], "only the parent frame is painted while editing parents"); + let mut culled = document_layout; + culled.slots.clear(); + assert!(painted_hidden_character_marks(&app, &doc, &culled).is_empty(), "culled spreads have no marks"); +} + +/// Table-cell marks use the same frame and layer visibility checks as ordinary story marks. +#[test] +fn hidden_characters_in_table_cells_follow_frame_visibility() { + let app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + let mut doc = Document::new(&designcraft_doc::build::NewDocument::default()); + let layer = doc.default_layer(); + let (frame, story) = doc.add_text_frame(SpreadRef::Doc(0), DRect::new(36.0, 36.0, 336.0, 336.0), layer, "", Default::default()).unwrap(); + let data = vec![vec!["a b\tc\nd".to_owned(), String::new()]]; + let table = designcraft_doc::Table::from_strings(doc.alloc(), &data, 200.0, &Default::default(), &Default::default()); + doc.story_mut(story).unwrap().insert_table(0, table); + let layout = CanvasLayout::new(&doc, false); + let expected = painted_hidden_character_marks(&app, &doc, &layout); + for mark in ["·", "»", "¶", "#"] { + assert!(expected.iter().any(|m| m == mark), "visible table cells draw {mark}: {expected:?}"); + } + assert!(expected.iter().filter(|m| *m == "#").count() >= 2, "including the empty cell's end mark"); + doc.item_mut(frame).unwrap().hidden = true; + assert!(painted_hidden_character_marks(&app, &doc, &layout).is_empty(), "hidden frames hide cell marks too"); + doc.item_mut(frame).unwrap().hidden = false; + doc.layer_mut(layer).unwrap().visible = false; + assert!(painted_hidden_character_marks(&app, &doc, &layout).is_empty(), "hidden layers hide cell marks too"); + doc.layer_mut(layer).unwrap().visible = true; + assert_eq!(painted_hidden_character_marks(&app, &doc, &layout), expected, "showing the layer restores every cell mark"); +} + /// As InDesign: an end-of-story # in every cell (after its text), a ¶ where a cell paragraph /// ends, and the table paragraph's ¶ just after the table's bottom right corner. #[test] @@ -3485,3 +3705,151 @@ fn leaving_parent_editing_for_the_left_page_of_a_spread_keeps_that_page_selected h.run_steps(3); assert_eq!(current_page(h.state()), Some(1)); } + +/// Selected text shows what lies under it inverted: paper turns black, black turns white, +/// and a half-covered pixel is half inverted. +#[test] +fn the_text_highlight_inverts_what_lies_under_it() { + let mask = [0, 0, 0, 0, 255, 255, 255, 255, 255, 255, 255, 255, 128, 128, 128, 128, 255, 255, 255, 255]; + let under = [9, 9, 9, 255, 255, 255, 255, 255, 0, 0, 0, 255, 0, 0, 0, 255, 0, 0, 0, 0]; + let out = inverse_under(&mask, &under, [80, 80, 80]); + assert_eq!(&out[0..4], &[0, 0, 0, 0], "outside the highlight: untouched"); + assert_eq!(&out[4..8], &[0, 0, 0, 255], "white paper turns black"); + assert_eq!(&out[8..12], &[255, 255, 255, 255], "black turns white"); + assert_eq!(&out[12..16], &[128, 128, 128, 128], "half covered: half the inverse"); + assert_eq!(&out[16..20], &[175, 175, 175, 255], "transparent: the inverse of the pasteboard"); +} + +/// White text on a black frame used to turn black on a black highlight. Now the highlight is +/// light there and the selected letters dark. +#[test] +fn selected_white_text_on_a_dark_fill_stays_readable() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", serde_json::json!({})).unwrap(); + let id = app + .run("frame.create", serde_json::json!({"rect": [72, 72, 400, 200], "content": "text", "text": "White text", "caret": true})) + .unwrap()["id"] + .as_u64() + .unwrap(); + app.run("edit.selectAll", serde_json::json!({})).unwrap(); + app.run("type.char", serde_json::json!({"attrs": {"size": 28, "fill": "[Paper]"}})).unwrap(); + app.run("object.fill", serde_json::json!({"ids": [id], "swatch": "[Black]"})).unwrap(); + let mut h = crate::test_window::open(app, vec2(900.0, 600.0)); + h.run_steps(6); + let app = &h.state().app; + let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()); + let canvas = app.session.layout().xf(designcraft_doc::SpreadRef::Doc(0)); + let (a, b) = (xf.to_screen(canvas * Point::new(76.0, 78.0)), xf.to_screen(canvas * Point::new(180.0, 98.0))); + let image = match h.render() { + Ok(image) => image, + // CI has a renderer: there a missing one is a failure, not a silent pass. + Err(e) if std::env::var_os("CI").is_some() => panic!("no offscreen renderer in CI: {e}"), + Err(e) => { + eprintln!("skipped: no offscreen renderer ({e})"); + return; + } + }; + let (mut light, mut dark) = (0, 0); + for y in a.y as u32..b.y as u32 { + for x in a.x as u32..b.x as u32 { + let p = image.get_pixel(x, y); + let l = (u32::from(p[0]) + u32::from(p[1]) + u32::from(p[2])) / 3; + if l > 200 { + light += 1; + } else if l < 60 { + dark += 1; + } + } + } + assert!(light > dark, "a light highlight under the selected white text: {light} light, {dark} dark"); + assert!(dark > 0, "with the letters dark on it"); +} + +/// The highlight is drawn from a render of what lies under it: a display option that changes +/// that render (Overprint Preview here) draws it again instead of keeping the old pixels. +#[test] +fn the_text_highlight_follows_the_display_options() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", serde_json::json!({})).unwrap(); + app.run("frame.create", serde_json::json!({"rect": [72, 72, 400, 200], "content": "text", "text": "Some text", "caret": true})).unwrap(); + app.run("edit.selectAll", serde_json::json!({})).unwrap(); + let mut h = crate::test_window::open(app, vec2(900.0, 600.0)); + h.run_steps(6); + let cached = |h: &Harness<'_, crate::test_window::Window>| { + h.ctx.data(|d| d.get_temp::<(egui::Id, egui::TextureHandle)>(egui::Id::unique("inverse_sel_tex"))).map(|(k, _)| k) + }; + let before = cached(&h).expect("the highlight is drawn"); + h.run_steps(2); + assert_eq!(cached(&h), Some(before), "unchanged: the cached highlight is kept"); + h.state_mut().app.ui.overprint_preview = !h.state().app.ui.overprint_preview; + h.run_steps(2); + let after = cached(&h).expect("the highlight is drawn"); + assert_ne!(after, before, "a new display option: the highlight is drawn again"); +} + +/// The highlight's plain fill (painted at `h`'s last frame) and the rects it is clipped to. +fn plain_highlights(h: &Harness<'_, crate::test_window::Window>) -> Vec { + h.output() + .shapes + .iter() + .filter(|c| matches!(&c.shape, egui::Shape::Path(p) if p.fill == super::text_overlay::PLAIN_HIGHLIGHT)) + .map(|c| c.clip_rect) + .collect() +} + +/// A selected text frame that runs past the page's left edge, in a new document. +fn text_past_the_page_edge() -> DesignApp { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", serde_json::json!({})).unwrap(); + let text = "Some text past the edge"; + app.run("frame.create", serde_json::json!({"rect": [-150, 72, 300, 200], "content": "text", "text": text, "caret": true})).unwrap(); + app.run("edit.selectAll", serde_json::json!({})).unwrap(); + app.run("type.char", serde_json::json!({"attrs": {"size": 28}})).unwrap(); + app +} + +/// In Preview the plain highlight (here with Separations Preview on) shows only on the page, as +/// the inverted one does: not on the pasteboard where the selection runs past the trim. +#[test] +fn the_plain_text_highlight_is_clipped_to_the_shown_area() { + let mut app = text_past_the_page_edge(); + app.ui.separations = Some(crate::separations::Separations::default()); + let mut h = crate::test_window::open(app, vec2(900.0, 600.0)); + h.run_steps(6); + assert!(plain_highlights(&h).iter().any(|c| c.left() < page_left(&h) - 1.0), "Normal: on the pasteboard too"); + h.state_mut().app.ui.screen_mode = ScreenMode::Preview; + h.run_steps(4); + let clips = plain_highlights(&h); + assert!(!clips.is_empty(), "the highlight is drawn"); + let left = page_left(&h); + assert!(clips.iter().all(|c| c.left() >= left - 0.5), "only on the page: {clips:?}, page from {left}"); +} + +/// The page's left edge on screen. +fn page_left(h: &Harness<'_, crate::test_window::Window>) -> f32 { + let app = &h.state().app; + let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()); + let canvas = app.session.layout().xf(designcraft_doc::SpreadRef::Doc(0)); + xf.to_screen(canvas * Point::new(0.0, 100.0)).x +} + +/// In a turned view the canvas's pixels never match, so the highlight is not rendered on the UI +/// thread: neither when text is selected nor on each zoom step, which get the plain highlight. +#[test] +fn a_turned_view_draws_the_plain_highlight_while_zooming() { + let mut h = crate::test_window::open(text_past_the_page_edge(), vec2(900.0, 600.0)); + let rendered = |h: &Harness<'_, crate::test_window::Window>| { + h.ctx.data(|d| d.get_temp::<(egui::Id, egui::TextureHandle)>(egui::Id::unique("inverse_sel_tex"))).is_some() + }; + h.state_mut().app.view_mut().unwrap().rotation = 1; + // What the unturned view drew when the window opened goes; a turned view adds nothing. + h.ctx.data_mut(|d| d.remove::<(egui::Id, egui::TextureHandle)>(egui::Id::unique("inverse_sel_tex"))); + h.run_steps(6); + assert!(!rendered(&h), "selected in a turned view: nothing rendered"); + for zoom in [1.0, 1.5, 2.0] { + h.state_mut().app.view_mut().unwrap().zoom *= zoom; + h.run_steps(2); + assert!(!plain_highlights(&h).is_empty(), "zoom ×{zoom}: the plain highlight"); + assert!(!rendered(&h), "zoom ×{zoom}: nothing rendered for it"); + } +} diff --git a/crates/ui-egui/src/canvas/text_overlay.rs b/crates/ui-egui/src/canvas/text_overlay.rs index cc6e1432d..b9ad0aa1b 100644 --- a/crates/ui-egui/src/canvas/text_overlay.rs +++ b/crates/ui-egui/src/canvas/text_overlay.rs @@ -1,6 +1,8 @@ use super::caret; use super::frames::{item_canvas_xf, layer_color, path_screen}; +use super::render::{display_key, screen_options}; use super::{Affine, CanvasLayout, Color32, DesignApp, Document, Point, Pos2, Rect, Stroke, Xf, compose, pos2}; +use crate::{ScreenMode, theme::Tokens}; pub(super) fn draw_text_selection( app: &DesignApp, @@ -38,8 +40,8 @@ pub(super) fn draw_text_selection( draw_cell_selection(app, painter, xf, doc, layout, &cs, ts, cell); return; } - let mut runs: Vec<(usize, Affine, Vec<[Point; 4]>, Vec<(usize, usize)>)> = Vec::new(); - for (fi, ft) in cs.frames.iter().enumerate() { + let mut runs: Vec<(Affine, Vec<[Point; 4]>)> = Vec::new(); + for ft in &cs.frames { let Some((a, _)) = item_canvas_xf(doc, layout, ft.frame) else { continue }; let Some(it) = doc.item(ft.frame) else { continue }; let m = a * doc.text_xf(it); @@ -73,8 +75,7 @@ pub(super) fn draw_text_selection( continue; } let mut quads = Vec::new(); - let mut glyphs = Vec::new(); - for (li, l) in ft.lines.iter().enumerate() { + for l in &ft.lines { let s = range.start.max(l.range.start); let e = range.end.min(l.range.end); if s > e || (s == e && !(l.range.end < range.end && e == l.range.end)) { @@ -91,18 +92,13 @@ pub(super) fn draw_text_selection( quads.push([Point::new(a, r.y0), Point::new(b, r.y0), Point::new(b, r.y1), Point::new(a, r.y1)]); } } - for (gi, g) in l.glyphs.iter().enumerate() { - if g.visible && g.len > 0 && g.byte >= s && g.byte < e { - glyphs.push((li, gi)); - } - } } if !quads.is_empty() { - runs.push((fi, m, quads, glyphs)); + runs.push((m, quads)); } } if !runs.is_empty() { - draw_inverse_highlight(app, painter, xf, doc, &cs, ts.story, &runs); + draw_inverse_highlight(app, painter, xf, doc, layout, ts.story, &runs); } if ts.is_caret() && let Some((fi, x, bl, asc, desc)) = compose::caret(&cs, ts.focus) @@ -172,24 +168,49 @@ fn draw_cell_selection( } } -/// InDesign draws selected text inverted: a black highlight with the selected glyphs in the -/// inverse of their colour (white for black text). The highlight and glyph outlines are -/// rasterised with `vello_cpu` into a small screen-space texture over the selection. +thread_local! { + /// Renders what lies under a text highlight, apart from the canvas renderer and its worker. + static HIGHLIGHT_RENDERER: std::cell::RefCell> = const { std::cell::RefCell::new(None) }; +} + +/// The `w` × `h` premultiplied pixels of `img` from (`x0`, `y0`), the pasteboard colour `back` +/// where that reaches past the image. +fn crop(img: &designcraft_render::Rendered, x0: i64, y0: i64, w: u32, h: u32, back: [u8; 3]) -> Vec { + let mut out = Vec::with_capacity(w as usize * h as usize * 4); + for y in 0..i64::from(h) { + for x in 0..i64::from(w) { + let (sx, sy) = (x0 + x, y0 + y); + let inside = sx >= 0 && sy >= 0 && sx < i64::from(img.width) && sy < i64::from(img.height); + let px = inside.then(|| (sy as usize * img.width as usize + sx as usize) * 4).and_then(|i| img.pixels.get(i..i + 4)); + match px { + Some(p) => out.extend_from_slice(p), + None => out.extend_from_slice(&[back[0], back[1], back[2], 255]), + } + } + } + out +} + +/// InDesign draws selected text inverted: whatever lies under the highlight (paper, the frame's +/// fill, a placed image, the selected glyphs themselves) shows in its inverse colour. Black text +/// on white paper turns white on black, and white text on a dark fill turns dark on a light +/// highlight instead of vanishing into a black bar. The area under the selection is rendered from +/// the document into a small screen-space texture and inverted inside the highlight quads. fn draw_inverse_highlight( app: &DesignApp, painter: &egui::Painter, xf: &Xf, doc: &Document, - cs: &compose::ComposedStory, + layout: &CanvasLayout, story: designcraft_doc::StoryId, - runs: &[(usize, Affine, Vec<[Point; 4]>, Vec<(usize, usize)>)], + runs: &[(Affine, Vec<[Point; 4]>)], ) { use designcraft_render::vello_cpu::{self, kurbo, peniko}; let ctx = painter.ctx(); let ppp = ctx.pixels_per_point(); let to_screen = |m: Affine, p: Point| xf.to_screen(m * p); let mut bbox = Rect::NOTHING; - for (_, m, quads, _) in runs { + for (m, quads) in runs { for q in quads { for p in q { bbox.extend_with(to_screen(*m, *p)); @@ -207,18 +228,62 @@ fn draw_inverse_highlight( ); let (w, h) = (((bbox.width() * ppp).round() as u32).clamp(1, 8192), ((bbox.height() * ppp).round() as u32).clamp(1, 8192)); let Some(st) = app.session.active() else { return }; + let preview = app.ui.screen_mode != ScreenMode::Normal; + let back = Tokens::get(ctx).pasteboard; + // Everything that changes the colours the canvas shows changes the highlight too: the display + // options the canvas texture is redrawn for (Rich Black, Overprint Preview, quality …) and + // the proof setup and pasteboard behind them. + let display = (format!("{:?}", display_key(app)), app.ui.proof_colors.then(|| format!("{:?}", app.ui.proof_setup)), back.to_array()); + // What the canvas shows under the highlight: cut from the canvas's own pixels when its texture + // is at this zoom (no second render; Preview mode's clipping included), else rendered here. + // The texture's pixel at the highlight's top left, kept in canvas space so scrolling (which + // only shifts the texture) reuses the highlight. + let from_canvas = + app.canvas.shown.zip(app.canvas.pixels.clone()).filter(|(sh, _)| (sh.zoom - xf.zoom).abs() < 1e-9 && xf.rot == 0).map(|(sh, px)| { + let c = xf.to_canvas(bbox.min); + let k = sh.zoom * ppp as f64; + (((c.x - sh.origin.x) * k).round() as i64, ((c.y - sh.origin.y) * k).round() as i64, px) + }); + // Preview, Bleed, Slug: only where each spread shows its content, as the canvas. + let clips: Vec = if app.ui.screen_mode == crate::ScreenMode::Normal { + vec![painter.clip_rect()] + } else { + layout.slots.iter().map(|slot| super::page_decor::shown_area(app, doc, xf, slot).intersect(painter.clip_rect())).collect() + }; + // Without the canvas's pixels the area would be rendered here, on the UI thread. That is not + // done on a frame of a zoom or right after text is selected, when the worker is already + // bringing a texture with its pixels, nor in a turned view, whose texture never matches (every + // zoom or selection change would render again): there, and with Separations Preview on (which + // shows a plate, not the composite the canvas pixels hold), a plain highlight. + let waiting = from_canvas.is_none() && app.canvas.pending.is_some(); + if app.ui.separations.is_some() || waiting || xf.rot != 0 { + for clip in &clips { + let painter = painter.with_clip_rect(*clip); + for (m, quads) in runs { + for q in quads { + let poly = q.map(|p| to_screen(*m, p)); + painter.add(egui::Shape::convex_polygon(poly.to_vec(), PLAIN_HIGHLIGHT, Stroke::NONE)); + } + } + } + return; + } + let at = from_canvas.as_ref().map(|(x, y, _)| (*x, *y)); let key = egui::Id::unique(("inverse_sel", st.uid, st.revision, std::sync::Arc::as_ptr(&st.doc) as usize, story.0)) - .with((runs.iter().map(|r| r.2.len() + r.3.len() * 7919).sum::(), w, h)) - .with((bbox.min.x.to_bits(), bbox.min.y.to_bits(), xf.zoom.to_bits(), st.selection.text.map(|t| (t.anchor, t.focus)))); + .with(&display) + .with((runs.iter().map(|r| r.1.len()).sum::(), w, h, preview)) + .with((at, app.canvas.pixels_generation, xf.zoom.to_bits(), xf.rot, st.selection.text.map(|t| (t.anchor, t.focus)))) + .with(at.is_none().then(|| (bbox.min.x.to_bits(), bbox.min.y.to_bits()))); let cache_id = egui::Id::unique("inverse_sel_tex"); let cached: Option<(egui::Id, egui::TextureHandle)> = ctx.data(|d| d.get_temp(cache_id)); let tex = match cached { Some((k, t)) if k == key => t, _ => { let view = xf.affine(ppp as f64, bbox.min); + // How much of each pixel the highlight covers. let mut rc = vello_cpu::RenderContext::new_with(w as u16, h as u16, vello_cpu::RenderSettings { num_threads: 0, ..Default::default() }); - rc.set_paint(peniko::Color::from_rgba8(0, 0, 0, 255)); - for (_, m, quads, _) in runs { + rc.set_paint(peniko::Color::from_rgba8(255, 255, 255, 255)); + for (m, quads) in runs { rc.set_transform(view * *m); for q in quads { let mut bp = kurbo::BezPath::new(); @@ -230,41 +295,67 @@ fn draw_inverse_highlight( rc.fill_path(&bp); } } - let db = designcraft_fonts::FontDb::global(); - for (fi, m, _, glyphs) in runs { - let Some(ft) = cs.frames.get(*fi) else { continue }; - for &(li, gi) in glyphs { - let Some(l) = ft.lines.get(li) else { continue }; - let Some(g) = l.glyphs.get(gi) else { continue }; - let Some(style) = cs.styles.get(g.style as usize) else { continue }; - let Some(c) = doc.resolve_color(&style.fill, style.fill_tint) else { continue }; - let [r, gg, b, _] = c.to_rgba8(1.0); - rc.set_paint(peniko::Color::from_rgba8(255 - r, 255 - gg, 255 - b, 255)); - let outline = db.outline(&g.face, g.gid); - let skew = - if style.skew != 0.0 { Affine::new([1.0, 0.0, -style.skew.to_radians().tan(), 1.0, 0.0, 0.0]) } else { Affine::IDENTITY }; - let shatai = style.shatai_xf(g, l.baseline).unwrap_or(Affine::IDENTITY); - let mut ga = shatai * Affine::translate((g.x, l.baseline + g.y)) * skew * Affine::scale_non_uniform(g.sx, g.sy); - if ft.vertical - && let Some(turn) = g.vertical_xf(l.baseline) - { - ga = turn * ga; - } - rc.set_transform(view * *m * ga); - rc.fill_path(&outline); - } - } rc.flush(); - let mut pm = vello_cpu::Pixmap::new(w as u16, h as u16); + let mut mask = vello_cpu::Pixmap::new(w as u16, h as u16); let mut res = vello_cpu::Resources::new(); - rc.render(&mut pm, &mut res); - let ci = egui::ColorImage::from_rgba_premultiplied([w as usize, h as usize], pm.data_as_u8_slice()); + rc.render(&mut mask, &mut res); + let under = match &from_canvas { + Some((x0, y0, px)) => crop(px, *x0, *y0, w, h, [back.r(), back.g(), back.b()]), + None => { + // Rendered with the canvas's own options and colours, on this thread only (a + // pool per frame of a drag would cost more than the render). + let placed: Vec = + layout.slots.iter().map(|s| designcraft_render::Placed { spread: s.spread, xf: s.xf }).collect(); + let opts = screen_options(app, layout, preview, ppp as f64); + let mut under = HIGHLIGHT_RENDERER.with(|r| { + let mut r = r.borrow_mut(); + r.get_or_insert_with(|| { + let mut r = designcraft_render::Renderer::new(); + r.threads = 0; + r + }) + .render(doc, &app.session.cache, &placed, (w, h), view, &opts) + }); + if app.ui.proof_colors { + designcraft_render::proof_view(&mut under, &app.ui.proof_setup); + } + under.pixels + } + }; + let pixels = inverse_under(mask.data_as_u8_slice(), &under, [back.r(), back.g(), back.b()]); + let ci = egui::ColorImage::from_rgba_premultiplied([w as usize, h as usize], &pixels); let t = crate::widgets::load_texture(ctx, "inverse_selection", ci, egui::TextureOptions::NEAREST); ctx.data_mut(|d| d.insert_temp(cache_id, (key, t.clone()))); t } }; - painter.image(tex.id(), bbox, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); + let uv = Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)); + for clip in &clips { + painter.with_clip_rect(*clip).image(tex.id(), bbox, uv, Color32::WHITE); + } +} + +/// The highlight where the inverse of what lies under it isn't at hand. +pub(super) const PLAIN_HIGHLIGHT: Color32 = Color32::from_rgba_premultiplied(35, 60, 110, 110); + +/// Premultiplied RGBA: the inverse of `under` (composited over `back` where it is transparent), +/// shown as far as `mask` (premultiplied white) covers each pixel. +pub(super) fn inverse_under(mask: &[u8], under: &[u8], back: [u8; 3]) -> Vec { + let mut out = vec![0u8; mask.len()]; + let under = under.as_chunks::<4>().0.iter().chain(std::iter::repeat(&[0u8; 4])); + for ((o, m), u) in out.as_chunks_mut::<4>().0.iter_mut().zip(mask.as_chunks::<4>().0).zip(under) { + let cover = u32::from(m[3]); + if cover == 0 { + continue; + } + let a = u32::from(u[3]); + for k in 0..3 { + let shown = (u32::from(u[k]) + u32::from(back[k]) * (255 - a) / 255).min(255); + o[k] = ((255 - shown) * cover / 255) as u8; + } + o[3] = cover as u8; + } + out } /// View → Show Hidden Characters: ¶ paragraph ends, » tabs, · spaces, ¬ forced line breaks, # end of story. @@ -274,7 +365,10 @@ pub(super) fn draw_hidden_characters(app: &DesignApp, painter: &egui::Painter, x for story in doc.stories.values() { let cs = app.session.cache.get(doc, story.id, None); for ft in &cs.frames { - let (Some((a, _)), Some(it)) = (item_canvas_xf(doc, layout, ft.frame), doc.item(ft.frame)) else { continue }; + let Some((loc, it)) = hidden_characters_frame(doc, ft.frame) else { continue }; + // Parent editing and viewport culling can leave this spread off the canvas. + let Some(slot) = layout.slot(loc.spread) else { continue }; + let a = slot.xf * doc.parent_xf(&loc); let m = a * doc.text_xf(it); let col = layer_color(doc, it); for (p, mark, centered, ascent) in frame_hidden_marks(&story.text, ft) { @@ -286,6 +380,22 @@ pub(super) fn draw_hidden_characters(app: &DesignApp, painter: &egui::Painter, x } } +/// Resolve a visible frame once for both the visibility check and painting, including its groups. +fn hidden_characters_frame(doc: &Document, frame: designcraft_doc::ItemId) -> Option<(designcraft_doc::ItemLoc, &designcraft_doc::Item)> { + let loc = doc.find(frame)?; + let spread = doc.spread(loc.spread)?; + let mut items = spread.items.as_slice(); + for &index in &loc.path { + let item = items.get(index)?; + if item.hidden || doc.layer(item.layer).is_some_and(|layer| !layer.visible) { + return None; + } + items = item.children(); + } + let item = doc.item_at(&loc)?; + Some((loc, item)) +} + /// A frame's hidden-character marks in frame space (position at the baseline, mark, centered, /// the line's ascent): its lines' marks, then its tables' — each text cell's own marks (nested /// tables included) with its # where its text ends, and a table paragraph's ¶ after the last diff --git a/crates/ui-egui/src/channel.rs b/crates/ui-egui/src/channel.rs new file mode 100644 index 000000000..b5ad34e3e --- /dev/null +++ b/crates/ui-egui/src/channel.rs @@ -0,0 +1,120 @@ +//! The window and About identity of the selected channel: Stable, or the Launcher's nightly-v1. +//! +//! The desktop selects it once, before any window exists (`main.rs`), with the version the build +//! script baked in. The web build never selects one and stays stable. Every OS name (Wayland app +//! id, Windows AUMID, About, captions) comes from here, so the two channels cannot disagree. + +use std::sync::OnceLock; +use std::sync::atomic::{AtomicU8, Ordering}; + +/// The stable `.desktop` file name, hicolor icon name and Windows identity. +pub const APP_ID: &str = "ai.storyteller.designcraft"; +/// The nightly package, bundle and Launcher identity (`ai.storyteller.designcraft.nightly`). +pub const NIGHTLY_PACKAGE_ID: &str = "ai.storyteller.designcraft.nightly"; +/// The nightly window/Wayland app id and Windows AUMID; deliberately not the package id. +pub const NIGHTLY_APP_ID: &str = "ai.storyteller.designcraft.nightly-v1"; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Channel { + Stable, + NightlyV1, +} + +impl Channel { + pub fn is_nightly(self) -> bool { + self == Self::NightlyV1 + } + + /// The OS window identity: stable's `.desktop` name, or the nightly-v1 window id. + pub fn app_id(self) -> &'static str { + match self { + Self::Stable => APP_ID, + Self::NightlyV1 => NIGHTLY_APP_ID, + } + } + + /// The name About, captions and dialogs show. + pub fn name(self) -> &'static str { + match self { + Self::Stable => "DesignCraft", + Self::NightlyV1 => "DesignCraft Nightly", + } + } +} + +/// 0 = not selected (stable), 1 = stable, 2 = nightly-v1. +static SELECTED: AtomicU8 = AtomicU8::new(0); +static IDENTITY: OnceLock<(&'static str, Option<&'static str>)> = OnceLock::new(); + +/// Select the channel once, with the version and (nightly only) commit the build baked in. +pub fn select(channel: Channel, version: &'static str, commit: Option<&'static str>) -> Result<(), String> { + if version.is_empty() { + return Err("the build channel needs a version".into()); + } + if channel.is_nightly() != commit.is_some() { + return Err("only a nightly channel carries a source commit".into()); + } + let value = if channel.is_nightly() { 2 } else { 1 }; + SELECTED.compare_exchange(0, value, Ordering::AcqRel, Ordering::Acquire).map_err(|_| "the build channel was already selected".to_string())?; + IDENTITY.set((version, commit)).map_err(|_| "the build channel was already selected".to_string()) +} + +pub fn current() -> Channel { + if SELECTED.load(Ordering::Acquire) == 2 { Channel::NightlyV1 } else { Channel::Stable } +} + +pub fn is_nightly() -> bool { + current().is_nightly() +} + +pub fn name() -> &'static str { + current().name() +} + +/// The exact build version: the workspace version for stable, the feed identity for nightly. +pub fn version() -> &'static str { + IDENTITY.get().map_or(env!("CARGO_PKG_VERSION"), |(version, _)| *version) +} + +/// The 40-hex source commit of a nightly build, if the build was given one. +pub fn commit() -> Option<&'static str> { + IDENTITY.get().and_then(|(_, commit)| *commit) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A version and a commit must match the channel, and the errors are returned rather than + /// stored, so a refusal leaves the selection untouched. + #[test] + fn select_refuses_a_missing_version_and_a_commit_that_does_not_match_the_channel() { + assert_eq!(select(Channel::Stable, "", None).unwrap_err(), "the build channel needs a version"); + assert_eq!( + select(Channel::Stable, "0.2.1", Some("0123456789abcdef0123456789abcdef01234567")).unwrap_err(), + "only a nightly channel carries a source commit" + ); + assert_eq!( + select(Channel::NightlyV1, "0.2.1-nightly.20261124.17.1.gabcdef012345", None).unwrap_err(), + "only a nightly channel carries a source commit" + ); + assert_eq!(current(), Channel::Stable, "a refused selection leaves the channel as it was"); + } + + #[test] + fn the_default_is_the_stable_identity() { + assert_eq!(current(), Channel::Stable, "the web build and tests never select a channel"); + assert_eq!(name(), "DesignCraft"); + assert_eq!(version(), env!("CARGO_PKG_VERSION")); + assert_eq!(commit(), None); + } + + #[test] + fn the_nightly_identities_are_distinct_from_stable() { + assert_ne!(Channel::NightlyV1.app_id(), Channel::Stable.app_id()); + assert_ne!(NIGHTLY_PACKAGE_ID, NIGHTLY_APP_ID); + assert_eq!(Channel::Stable.app_id(), APP_ID); + assert_eq!(Channel::NightlyV1.name(), "DesignCraft Nightly"); + assert!(Channel::NightlyV1.is_nightly() && !Channel::Stable.is_nightly()); + } +} diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 0b69db95f..41ab8ea56 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -348,6 +348,7 @@ fn handle_request(app: &mut DesignApp, ctx: &egui::Context, req: &ControlRequest ("baselineGrid", "view.baselineGrid"), ("documentGrid", "view.documentGrid"), ("textThreads", "view.textThreads"), + ("linkBadge", "view.linkBadge"), ] { if let Some(want) = p.get(k).and_then(Value::as_bool) { let cur = match k { @@ -356,6 +357,7 @@ fn handle_request(app: &mut DesignApp, ctx: &egui::Context, req: &ControlRequest "guides" => app.ui.guides, "baselineGrid" => app.ui.baseline_grid, "documentGrid" => app.ui.document_grid, + "linkBadge" => app.ui.link_badge, _ => app.ui.text_threads, }; if cur != want { diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 336cf6409..7cbc92182 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -1468,6 +1468,14 @@ pub(crate) fn general(lang: &str, ui: &mut egui::Ui, d: &mut Dialog) { if let Some(v) = columns.width(field).spinner().range(1.0, 40.0).show(ui) { d.fields.insert("columns".into(), json!(v.round().to_string())); } + // InDesign opens with the Columns count focused, so Up, Up, Return makes 3 columns + // without the mouse. Once, after the field is shown and registered this frame: + // moving focus elsewhere is not overridden on later frames. (Object Styles reuse + // this page for their Text Frame section: only Text Frame Options takes the focus.) + if d.id == "textFrameOptions" && !d.fields.contains_key("_focusColumns") { + ui.ctx().memory_mut(|m| m.request_focus(crate::widgets::NumField::editor_id(ui, "tfo_columns"))); + d.fields.insert("_focusColumns".into(), json!(true)); + } // Fixed Number: the width follows from the frame; Fixed Width: it's set here. caption_at(ui, tr("Width:"), cap2); if d.s("columnsKind") == "fixedWidth" { @@ -2855,6 +2863,32 @@ fn preferences(app: &crate::DesignApp, ui: &mut egui::Ui, d: &mut Dialog, max_he ui.add_space(6.0); ui.label(crate::rtl::widget(ui, egui::RichText::new(crate::i18n::tr(&app.ui.language, "Links")).font(semibold(12.0)))); check(ui, d, "linkTextFiles", crate::i18n::tr(&app.ui.language, "Create Links When Placing Text Files")); + ui.add_space(6.0); + ui.label(crate::rtl::widget(ui, egui::RichText::new(crate::i18n::tr(&app.ui.language, "Saving")).font(semibold(12.0)))); + ui.horizontal(|ui| { + crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Save documents as:")); + let cur = d.s("saveFormat"); + let formats = [("designcraft", "DesignCraft (.designcraft)"), ("idml", "InDesign Markup (.idml)")]; + let shown = formats.iter().find(|(v, _)| *v == cur).map_or(formats[0].1, |(_, l)| l); + craft_ui::ComboBox::from_id_salt("pref_save_format") + .selected_text(crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, shown))) + .width(220.0) + .show_ui(ui, |ui| { + for (v, l) in formats { + if ui.selectable_label(v == cur, crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, l))).clicked() { + d.fields.insert("saveFormat".into(), json!(v)); + } + } + }); + }); + crate::rtl::label( + ui, + egui::RichText::new(crate::i18n::tr( + &app.ui.language, + "InDesign Markup: new documents are saved as .idml, and an opened .idml file is saved back to itself.", + )) + .small(), + ); } "type" => { crate::rtl::label(ui, egui::RichText::new(crate::i18n::tr(&app.ui.language, "Type Options")).font(semibold(12.0))); @@ -3314,6 +3348,7 @@ pub fn show(app: &mut DesignApp, ctx: &egui::Context) { "userDictionary" => crate::i18n::tr(&app.ui.language, "User Dictionary"), "newWorkspace" => crate::i18n::tr(&app.ui.language, "New Workspace"), "closeDocument" => crate::i18n::tr(&app.ui.language, "Unsaved Changes"), + "idmlLoss" => crate::i18n::tr(&app.ui.language, "Save as IDML"), "deletePages" => crate::i18n::tr(&app.ui.language, "Warning"), "pagesPanelOptions" => crate::i18n::tr(&app.ui.language, "Panel Options"), "parentOptions" => crate::i18n::tr(&app.ui.language, "Parent Options"), @@ -3353,7 +3388,7 @@ pub fn show(app: &mut DesignApp, ctx: &egui::Context) { let available = (ctx.content_rect().size() - frame_margin - egui::vec2(16.0, 16.0)).max(egui::Vec2::splat(1.0)); let preferred_width: f32 = match d.id.as_str() { "alert" => 440.0, - "closeDocument" | "updateLink" | "deletePages" | "newWorkspace" | "pagesPanelOptions" | "parentOptions" | "insertTable" + "closeDocument" | "idmlLoss" | "updateLink" | "deletePages" | "newWorkspace" | "pagesPanelOptions" | "parentOptions" | "insertTable" | "convertTableToText" => 380.0, "insertPages" => 440.0, "convertTextToTable" => 420.0, @@ -3934,6 +3969,13 @@ pub fn show(app: &mut DesignApp, ctx: &egui::Context) { .replace("{}", &d.s("title")); crate::rtl::label(ui, text); } + "idmlLoss" => { + idml_loss_text(app, ui, &d); + ui.add_space(8.0); + // With Save Anyway: no more asking about this document until DesignCraft + // quits. + check(ui, &mut d, "dontAskAgain", crate::i18n::tr(&app.ui.language, "Don't ask again for this document")); + } "deletePages" => { let several = d.fields.get("pages").and_then(Value::as_array).is_some_and(|p| p.len() > 1); crate::rtl::label( @@ -4211,6 +4253,7 @@ pub fn show(app: &mut DesignApp, ctx: &egui::Context) { let ok_label = match d.id.as_str() { "colorTheme" => crate::i18n::tr(&app.ui.language, "Add to Swatches").to_string(), "closeDocument" => crate::i18n::tr(&app.ui.language, " Save ").to_string(), + "idmlLoss" => crate::i18n::tr(&app.ui.language, "Save Anyway").to_string(), "updateLink" => crate::i18n::tr(&app.ui.language, " Update ").to_string(), "findFont" => crate::i18n::tr(&app.ui.language, "Replace All").to_string(), "newDocument" => format!(" {} ", crate::i18n::tr(&app.ui.language, "Create")), @@ -4260,6 +4303,10 @@ pub fn show(app: &mut DesignApp, ctx: &egui::Context) { d.fields.insert("discard".into(), json!(true)); result = Some(true); } + if d.id == "idmlLoss" && ui.button(crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, "Save as DesignCraft…"))).clicked() { + d.fields.insert("asDesigncraft".into(), json!(true)); + result = Some(true); + } }); }); }); @@ -4605,6 +4652,11 @@ pub fn cancel(app: &mut DesignApp) { } } app.cancel_pdf_import(); + if d.as_ref().is_some_and(|d| d.id == "idmlLoss") + && let Err(e) = crate::menus::answer_idml_loss(app, crate::menus::LossyAnswer::Cancel) + { + app.status(e); + } if let Some(d) = d && d.id == "preferences" { @@ -4622,6 +4674,24 @@ pub fn cancel(app: &mut DesignApp) { } } +/// The IDML loss question: what saving as IDML would lose, and what the answers do. +fn idml_loss_text(app: &DesignApp, ui: &mut egui::Ui, d: &Dialog) { + let lang = &app.ui.language; + let count = |k: &str| d.fields.get(k).and_then(Value::as_u64).unwrap_or(0); + crate::rtl::label(ui, crate::i18n::tr(lang, "IDML can't keep all of this document. Saving it as IDML loses:")); + ui.add_space(4.0); + let (notes, endnotes) = (count("editorialNotes"), count("endnotes")); + if notes > 0 { + crate::rtl::label(ui, format!("• {}", crate::i18n::tr(lang, "{} editorial note(s)").replace("{}", ¬es.to_string()))); + } + if endnotes > 0 { + let text = crate::i18n::tr(lang, "{} endnote(s): their text stays as plain text in the endnote frame").replace("{}", &endnotes.to_string()); + crate::rtl::label(ui, format!("• {text}")); + } + ui.add_space(8.0); + crate::rtl::label(ui, crate::i18n::tr(lang, "Saved as DesignCraft, the document keeps everything.")); +} + fn find_change_params(d: &Dialog) -> Value { let mut p = json!({ "find": d.s("find"), "change": d.s("change"), "grep": d.b("grep"), @@ -5303,7 +5373,7 @@ fn confirm_part3(app: &mut DesignApp, d: Dialog) -> Result { return app.confirm_pdf_import(page, if crop.is_empty() { "crop".into() } else { crop }, d.b("append")); } if let Some(target) = d.fields.get("target").and_then(Value::as_u64) { - app.activate_import_target(&crate::ImportRequest { purpose: "place".into(), target: Some(target) })?; + app.activate_import_target(&crate::ImportRequest { purpose: "place".into(), target: Some(target), wanted: Vec::new() })?; } let placed = app.place_file( json!({"path": d.s("path"), "pdfPage": page, "pdfCrop": if crop.is_empty() { "crop".to_string() } else { crop }, "append": d.b("append")}), @@ -5435,6 +5505,10 @@ fn confirm_part4(app: &mut DesignApp, d: Dialog) -> Result { if d.b("cjkFeatures") != d.b("cjkFeatures.initial") { prefs["cjkFeatures"] = json!(d.b("cjkFeatures")); } + // Save documents as (File Handling): only a format the dialog shows. + if let Some(format) = Some(d.s("saveFormat")).filter(|f| f == "designcraft" || f == "idml") { + prefs["saveFormat"] = json!(format); + } // No document open: the Units & Increments new documents start with, saved with the // rest in one `prefs.set` (which checks everything before it changes anything). A value // that doesn't read, or that it refuses, keeps the dialog open to be fixed, with no @@ -5597,6 +5671,16 @@ fn confirm_part5(app: &mut DesignApp, d: Dialog) -> Result { Ok(Value::Null) } "updateLink" => crate::panels::properties::run_update_links(app, d.fields.get("target").cloned().unwrap_or_else(|| json!({}))), + "idmlLoss" => { + let answer = if d.b("asDesigncraft") { crate::menus::LossyAnswer::SaveAsDesigncraft } else { crate::menus::LossyAnswer::SaveAnyway }; + if matches!(answer, crate::menus::LossyAnswer::SaveAnyway) + && d.b("dontAskAgain") + && let Some(uid) = d.fields.get("uid").and_then(Value::as_u64) + { + app.idml_loss_accepted.insert(uid); + } + crate::menus::answer_idml_loss(app, answer) + } "closeDocument" => { // The document may have moved in the tab row (or gone) while the dialog was open. let uid = d.fields.get("uid").and_then(Value::as_u64); @@ -6608,7 +6692,7 @@ fn link_toggle(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, key: &str, linked: /// A swatch menu with a colour chip per swatch (hidden swatches left out); returns the swatch /// picked. -fn swatch_menu(ui: &mut egui::Ui, doc: &designcraft_doc::Document, id: impl egui::AsIdSalt, current: &str, width: f32) -> Option { +pub(crate) fn swatch_menu(ui: &mut egui::Ui, doc: &designcraft_doc::Document, id: impl egui::AsIdSalt, current: &str, width: f32) -> Option { swatch_menu_with(ui, doc, id, current, width, None) } diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index e432ad07c..a313b7973 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -5909,3 +5909,29 @@ fn parent_resize_exact_dialog_keeps_its_target_and_rejects_invalid_input() { assert!(app.ui.dialog.is_some()); assert!(std::sync::Arc::ptr_eq(&saved, &app.session.doc().unwrap().doc)); } + +/// #2397: opening Text Frame Options focuses the Columns count field, so Ctrl/Cmd+B, Up, Up, +/// Return changes 1 column to 3 without the mouse. +#[test] +fn text_frame_options_opens_with_the_columns_field_focused() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let r = app.run("frame.create", json!({"rect": [36, 36, 336, 236], "content": "text", "text": "Hello"})).unwrap(); + let id = designcraft_doc::ItemId(r["id"].as_u64().unwrap()); + app.run("selection.set", json!({"ids": [id.0]})).unwrap(); + crate::menus::activate(&mut app, "object.textFrameOptions", &Value::Null); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.id.as_str()), Some("textFrameOptions")); + let ctx = dialog_context("en"); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 800.0)); + dialog_frame(&mut app, &ctx, screen, vec![]); + dialog_frame(&mut app, &ctx, screen, vec![]); + let up = || egui::Event::Key { key: egui::Key::ArrowUp, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }; + dialog_frame(&mut app, &ctx, screen, vec![up()]); + dialog_frame(&mut app, &ctx, screen, vec![]); + dialog_frame(&mut app, &ctx, screen, vec![up()]); + dialog_frame(&mut app, &ctx, screen, vec![]); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!(d.n("columns"), Some(3.0), "two Up presses step 1 column to 3: {:?}", d.fields.get("columns")); + confirm(&mut app).unwrap(); + assert_eq!(app.session.doc().unwrap().doc.item(id).unwrap().text_frame().unwrap().options.columns, 3); +} diff --git a/crates/ui-egui/src/effects_dialog.rs b/crates/ui-egui/src/effects_dialog.rs index a09b87498..650219bd2 100644 --- a/crates/ui-egui/src/effects_dialog.rs +++ b/crates/ui-egui/src/effects_dialog.rs @@ -337,15 +337,15 @@ fn swatch(app: &DesignApp, ui: &mut egui::Ui, d: &mut Dialog, path: &[&str]) { } v.as_str().unwrap_or("[Black]").to_string() }; - let names: Vec = app - .session - .active() - .map_or_else(Vec::new, |st| st.doc.swatches.iter().filter(|w| !w.hidden || w.name == cur).map(|w| w.name.clone()).collect()); - craft_ui::ComboBox::from_id_salt(("fx_swatch", path.join("."))).selected_text(&cur).width(150.0).show_ui(ui, |ui| { - for n in names { - if ui.selectable_label(n == cur, &n).clicked() { - set(d, path, json!(n)); - } + let Some(doc) = app.session.active().map(|st| &st.doc) else { return }; + // The colour itself beside its name, and a chip per swatch in the menu, as the swatch menus + // elsewhere: a list of bare names hid what the shadow was coloured with. + ui.horizontal(|ui| { + let (c, g) = crate::widgets::swatch_colors(doc, &cur, 1.0); + let (r, _) = ui.allocate_exact_size(egui::vec2(16.0, 16.0), egui::Sense::hover()); + crate::widgets::paint_chip(ui.painter(), r, c, g); + if let Some(n) = crate::dialogs::swatch_menu(ui, doc, ("fx_swatch", path.join(".")), &cur, 128.0) { + set(d, path, json!(n)); } }); } @@ -935,6 +935,44 @@ mod tests { assert_eq!(fx.outer_glow.mode, designcraft_color::BlendMode::Normal); } + #[test] + fn the_shadow_colour_shows_its_swatch_beside_the_name() { + let (mut app, _) = app_with_frame(); + app.run("swatch.create", json!({"name": "Shade", "color": "#12ab34"})).unwrap(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx, "en"); + let shade = crate::widgets::swatch_colors(&app.session.doc().unwrap().doc, "Shade", 1.0).0.unwrap(); + // Does the dialog, once faded in, paint a chip of the colour `c`? + let mut time = 0.0; + let mut painted = |app: &mut DesignApp, c: egui::Color32| { + let mut found = false; + for _ in 0..20 { + time += 0.1; + let input = egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))), + time: Some(time), + ..Default::default() + }; + let mut out = ctx.run_ui(input, |ui| crate::dialogs::show(app, ui.ctx())); + out.textures_delta.clear(); + fn walk(s: &egui::epaint::Shape, c: egui::Color32) -> bool { + match s { + egui::epaint::Shape::Rect(r) => r.fill == c, + egui::epaint::Shape::Vec(v) => v.iter().any(|s| walk(s, c)), + _ => false, + } + } + found = out.shapes.iter().any(|s| walk(&s.shape, c)); + } + found + }; + open(&mut app, "dropShadow"); + assert!(!painted(&mut app, shade), "not the shadow's colour yet"); + set(app.ui.dialog.as_mut().unwrap(), &["dropShadow", "color"], json!("Shade")); + assert!(painted(&mut app, shade), "the chosen swatch's colour is shown, not only its name"); + assert_eq!(params(app.ui.dialog.as_ref().unwrap())["effects"]["dropShadow"]["color"], "Shade"); + } + #[test] fn offsets_follow_distance_and_angle_as_in_indesign() { let (mut app, _) = app_with_frame(); diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index 3616c814e..8c39414e1 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -1686,10 +1686,12 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Show/Hide Hidden Characters", "إظهار/إخفاء الأحرف المخفية"), ("Show/Hide Panels", "إظهار/إخفاء اللوحات"), ("Show/Hide Panels Except Tools", "إظهار/إخفاء اللوحات باستثناء الأدوات"), + ("Show/Hide Paragraph Break Marks", "إظهار/إخفاء علامات نهاية الفقرات"), ("Show/Hide Rulers", "إظهار/إخفاء المساطر"), ("Show/Hide Style Name Column", "إظهار/إخفاء عمود أسماء الأنماط"), ("Show/Hide Tagged Frames", "إظهار/إخفاء الإطارات الموسومة"), ("Show/Hide Text Threads", "إظهار/إخفاء روابط الإطارات النصية"), + ("Show/Hide Link Badge", "إظهار/إخفاء شارة الارتباط"), ("Smooth", "تنعيم"), ("Sort", "فرز"), ("Split Note", "تقسيم الملاحظة"), diff --git a/crates/ui-egui/src/i18n/cs.rs b/crates/ui-egui/src/i18n/cs.rs index 0f3bfa7a7..54e8ae5fa 100644 --- a/crates/ui-egui/src/i18n/cs.rs +++ b/crates/ui-egui/src/i18n/cs.rs @@ -836,10 +836,12 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Show/Hide Hidden Characters", "Zobrazit/skrýt skryté znaky"), ("Show/Hide Panels", "Zobrazit/skrýt panely"), ("Show/Hide Panels Except Tools", "Zobrazit/skrýt panely kromě nástrojů"), + ("Show/Hide Paragraph Break Marks", "Zobrazit/skrýt značky konce odstavce"), ("Show/Hide Rulers", "Zobrazit/skrýt pravítka"), ("Show/Hide Style Name Column", "Zobrazit/skrýt sloupec názvů stylů"), ("Show/Hide Tagged Frames", "Zobrazit/skrýt otagované rámečky"), ("Show/Hide Text Threads", "Zobrazit/skrýt zřetězení textu"), + ("Show/Hide Link Badge", "Zobrazit/skrýt odznak propojení"), ("Smooth", "Vyhladit"), ("Sort", "Seřadit"), ("Split Cell Horizontally", "Rozdělit buňku vodorovně"), diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index 180074d8d..6b245fc05 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -783,10 +783,12 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Show/Hide Hidden Characters", "Verborgene Zeichen ein-/ausblenden"), ("Show/Hide Panels", "Bedienfelder ein-/ausblenden"), ("Show/Hide Panels Except Tools", "Bedienfelder außer Werkzeugen ein-/ausblenden"), + ("Show/Hide Paragraph Break Marks", "Absatzendemarken ein-/ausblenden"), ("Show/Hide Rulers", "Lineale ein-/ausblenden"), ("Show/Hide Style Name Column", "Spalte mit Formatnamen ein-/ausblenden"), ("Show/Hide Tagged Frames", "Getaggte Rahmen ein-/ausblenden"), ("Show/Hide Text Threads", "Textverkettungen ein-/ausblenden"), + ("Show/Hide Link Badge", "Verknüpfungssymbol ein-/ausblenden"), ("Smooth", "Glätten"), ("Sort", "Sortieren"), ("Split Cell Horizontally", "Zelle horizontal teilen"), diff --git a/crates/ui-egui/src/i18n/hu.rs b/crates/ui-egui/src/i18n/hu.rs index 6c9ff931d..6237d3500 100644 --- a/crates/ui-egui/src/i18n/hu.rs +++ b/crates/ui-egui/src/i18n/hu.rs @@ -1522,6 +1522,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Show the Typography panel", "Tipográfia panel megjelenítése"), ("Show/Hide Baseline Grid", "Alapvonalrács megjelenítése/elrejtése"), ("Show/Hide Depth Ruler", "Mélységmérő megjelenítése/elrejtése"), + ("Show/Hide Paragraph Break Marks", "Bekezdésvégi jelek megjelenítése/elrejtése"), ("Show/Hide Frame Edges", "Keretélek megjelenítése/elrejtése"), ("Show/Hide Guides", "Segédvonalak megjelenítése/elrejtése"), ("Show/Hide Hidden Characters", "Rejtett karakterek megjelenítése/elrejtése"), diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index f79a5337b..3009419c8 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -968,10 +968,12 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Show/Hide Hidden Characters", "Mostra/nascondi caratteri nascosti"), ("Show/Hide Panels", "Mostra/nascondi pannelli"), ("Show/Hide Panels Except Tools", "Mostra/nascondi pannelli tranne Strumenti"), + ("Show/Hide Paragraph Break Marks", "Mostra/nascondi segni di fine paragrafo"), ("Show/Hide Rulers", "Mostra/nascondi righelli"), ("Show/Hide Style Name Column", "Mostra/nascondi colonna nomi stili"), ("Show/Hide Tagged Frames", "Mostra/nascondi cornici con tag"), ("Show/Hide Text Threads", "Mostra/nascondi concatenamenti testo"), + ("Show/Hide Link Badge", "Mostra/nascondi badge collegamento"), ("Smooth", "Arrotonda"), ("Sort", "Ordina"), ("Split Cell Horizontally", "Dividi cella orizzontalmente"), diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index 3dbbc852b..e06714058 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -974,10 +974,12 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Show/Hide Hidden Characters", "制御文字を表示・非表示"), ("Show/Hide Panels", "パネルを表示・非表示"), ("Show/Hide Panels Except Tools", "ツール以外のパネルを表示・非表示"), + ("Show/Hide Paragraph Break Marks", "段落の終わりのマークを表示・非表示"), ("Show/Hide Rulers", "定規を表示・非表示"), ("Show/Hide Style Name Column", "スタイル名の列を表示・非表示"), ("Show/Hide Tagged Frames", "タグ付きフレームを表示・非表示"), ("Show/Hide Text Threads", "テキストフレームの連結を表示・非表示"), + ("Show/Hide Link Badge", "リンクバッジを表示・非表示"), ("Smooth", "平滑化"), ("Sort", "並べ替え"), ("Split Cell Horizontally", "セルを横方向に分割"), diff --git a/crates/ui-egui/src/i18n/ka.rs b/crates/ui-egui/src/i18n/ka.rs index d5b7ca728..7f1ebde1b 100644 --- a/crates/ui-egui/src/i18n/ka.rs +++ b/crates/ui-egui/src/i18n/ka.rs @@ -886,10 +886,12 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Show/Hide Hidden Characters", "დამალული სიმბოლოების ჩვენება/დამალვა"), ("Show/Hide Panels", "პანელების ჩვენება/დამალვა"), ("Show/Hide Panels Except Tools", "პანელების ჩვენება/დამალვა, ხელსაწყოების გარდა"), + ("Show/Hide Paragraph Break Marks", "აბზაცის დასასრულის ნიშნების ჩვენება/დამალვა"), ("Show/Hide Rulers", "სახაზავების ჩვენება/დამალვა"), ("Show/Hide Style Name Column", "სტილების სახელების სვეტის ჩვენება/დამალვა"), ("Show/Hide Tagged Frames", "ტეგირებული ჩარჩოების ჩვენება/დამალვა"), ("Show/Hide Text Threads", "ტექსტის კავშირების ჩვენება/დამალვა"), + ("Show/Hide Link Badge", "ბმულის ნიშნის ჩვენება/დამალვა"), ("Smooth", "გლუვი"), ("Sort", "სორტირება"), ("Split Cell Horizontally", "უჯრის ჰორიზონტალურად გაყოფა"), diff --git a/crates/ui-egui/src/i18n/pl.rs b/crates/ui-egui/src/i18n/pl.rs index 72ed6463c..bd8f23e78 100644 --- a/crates/ui-egui/src/i18n/pl.rs +++ b/crates/ui-egui/src/i18n/pl.rs @@ -846,10 +846,12 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Show/Hide Hidden Characters", "Pokaż/ukryj ukryte znaki"), ("Show/Hide Panels", "Pokaż/ukryj panele"), ("Show/Hide Panels Except Tools", "Pokaż/ukryj panele oprócz narzędzi"), + ("Show/Hide Paragraph Break Marks", "Pokaż/ukryj znaczniki końca akapitu"), ("Show/Hide Rulers", "Pokaż/ukryj linijki"), ("Show/Hide Style Name Column", "Pokaż/ukryj kolumnę nazw stylów"), ("Show/Hide Tagged Frames", "Pokaż/ukryj ramki z tagami"), ("Show/Hide Text Threads", "Pokaż/ukryj powiązania tekstu"), + ("Show/Hide Link Badge", "Pokaż/ukryj znacznik łącza"), ("Smooth", "Wygładź"), ("Sort", "Sortuj"), ("Split Cell Horizontally", "Podziel komórkę w poziomie"), diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index 9a3a9ae47..88ca41495 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -1849,10 +1849,12 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Show/Hide Hidden Characters", "Mostrar/ocultar caracteres ocultos"), ("Show/Hide Panels", "Mostrar/ocultar painéis"), ("Show/Hide Panels Except Tools", "Mostrar/ocultar painéis, exceto ferramentas"), + ("Show/Hide Paragraph Break Marks", "Mostrar/ocultar marcas de fim de parágrafo"), ("Show/Hide Rulers", "Mostrar/ocultar réguas"), ("Show/Hide Style Name Column", "Mostrar/ocultar coluna de nomes de estilo"), ("Show/Hide Tagged Frames", "Mostrar/ocultar quadros marcados"), ("Show/Hide Text Threads", "Mostrar/ocultar encadeamentos de texto"), + ("Show/Hide Link Badge", "Mostrar/ocultar selo de vínculo"), ("Sort", "Ordenar"), ("Split Note", "Dividir nota"), ("Split Path", "Dividir demarcador"), diff --git a/crates/ui-egui/src/i18n/ru.rs b/crates/ui-egui/src/i18n/ru.rs index a548db053..1f3cdaeb3 100644 --- a/crates/ui-egui/src/i18n/ru.rs +++ b/crates/ui-egui/src/i18n/ru.rs @@ -826,10 +826,12 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Show/Hide Hidden Characters", "Показать/скрыть скрытые символы"), ("Show/Hide Panels", "Показать/скрыть панели"), ("Show/Hide Panels Except Tools", "Показать/скрыть панели, кроме инструментов"), + ("Show/Hide Paragraph Break Marks", "Показать/скрыть знаки конца абзаца"), ("Show/Hide Rulers", "Показать/скрыть линейки"), ("Show/Hide Style Name Column", "Показать/скрыть столбец имен стилей"), ("Show/Hide Tagged Frames", "Показать/скрыть рамки с тегами"), ("Show/Hide Text Threads", "Показать/скрыть связи текстовых рамок"), + ("Show/Hide Link Badge", "Показать/скрыть значок связи"), ("Smooth", "Сгладить"), ("Sort", "Сортировать"), ("Split Cell Horizontally", "Разделить ячейку по горизонтали"), diff --git a/crates/ui-egui/src/i18n/sv.rs b/crates/ui-egui/src/i18n/sv.rs index 4b1ce4040..e5d404e67 100644 --- a/crates/ui-egui/src/i18n/sv.rs +++ b/crates/ui-egui/src/i18n/sv.rs @@ -1458,6 +1458,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Show/Hide Frame Edges", "Visa/dölj ramkanter"), ("Show/Hide Guides", "Visa/dölj stödlinjer"), ("Show/Hide Hidden Characters", "Visa/dölj dolda tecken"), + ("Show/Hide Link Badge", "Visa/dölj länksymbol"), ("Show/Hide Panels", "Visa/dölj paneler"), ("Show/Hide Panels Except Tools", "Visa/dölj paneler utom verktyg"), ("Show/Hide Rulers", "Visa/dölj linjaler"), @@ -2532,6 +2533,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Optical Margin Size", "Storlek för optisk marginal"), ("Dismiss", "Stäng"), ("Show/Hide Depth Ruler", "Visa/dölj djuplinjal"), + ("Show/Hide Paragraph Break Marks", "Visa/dölj styckeslutstecken"), ("Show/Hide Style Name Column", "Visa/dölj kolumnen med stilnamn"), ("Split Note", "Dela anteckning"), ("Arrangement", "Arrangemang"), diff --git a/crates/ui-egui/src/i18n/table.rs b/crates/ui-egui/src/i18n/table.rs index 902efddc8..877bed06c 100644 --- a/crates/ui-egui/src/i18n/table.rs +++ b/crates/ui-egui/src/i18n/table.rs @@ -2654,6 +2654,16 @@ pub(super) const TABLE: &[(&str, [&str; 5])] = &[ "显示/隐藏面板(工具除外)", ], ), + ( + "Show/Hide Paragraph Break Marks", + [ + "Show/Hide Paragraph Break Marks", + "Afficher/Masquer les marques de fin de paragraphe", + "Mostrar/ocultar marcas de fin de párrafo", + "Show/Hide Paragraph Break Marks", + "显示/隐藏段落结束标记", + ], + ), ("Show/Hide Rulers", ["Show/Hide Rulers", "Afficher/Masquer les règles", "Show/Hide Rulers", "Show/Hide Rulers", "显示/隐藏标尺"]), ( "Show/Hide Style Name Column", @@ -2679,6 +2689,16 @@ pub(super) const TABLE: &[(&str, [&str; 5])] = &[ "Show/Hide Text Threads", ["Show/Hide Text Threads", "Afficher/Masquer le chaînage du texte", "Show/Hide Text Threads", "Show/Hide Text Threads", "显示/隐藏文本串接"], ), + ( + "Show/Hide Link Badge", + [ + "Show/Hide Link Badge", + "Afficher/Masquer le badge de lien", + "Mostrar/ocultar distintivo de vínculo", + "Show/Hide Link Badge", + "显示/隐藏链接标记", + ], + ), ("Smooth", ["Smooth", "Lisse", "Smooth", "Smooth", "平滑"]), ("Sort", ["Sort", "Trier", "Sort", "Sort", "排序"]), ( diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 8f4bdb2a5..5e8941904 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -288,6 +288,18 @@ fn links_panel_check_captions_are_localized_in_every_interface_language() { } } +/// The View › Story Editor items are translated in every interface language. +#[test] +fn story_editor_view_items_are_localized_in_every_interface_language() { + for key in ["Show/Hide Depth Ruler", "Show/Hide Style Name Column", "Show/Hide Paragraph Break Marks"] { + for (code, name) in LANGUAGES.iter().filter(|(code, _)| !code.is_empty()) { + let label = tr(code, key); + assert_ne!(label, key, "{name}: {key}"); + assert!(!label.trim().is_empty(), "{name}: {key}"); + } + } +} + /// Checks language-specific context precedence and fallback to the plain translation. #[test] fn duplicate_layer_menu_item_is_localized_in_every_interface_language() { diff --git a/crates/ui-egui/src/i18n/uk.rs b/crates/ui-egui/src/i18n/uk.rs index e6ec482ff..e48a688d4 100644 --- a/crates/ui-egui/src/i18n/uk.rs +++ b/crates/ui-egui/src/i18n/uk.rs @@ -971,10 +971,12 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Show/Hide Hidden Characters", "Показати/приховати приховані символи"), ("Show/Hide Panels", "Показати/приховати панелі"), ("Show/Hide Panels Except Tools", "Показати/приховати панелі, крім інструментів"), + ("Show/Hide Paragraph Break Marks", "Показати/приховати знаки кінця абзацу"), ("Show/Hide Rulers", "Показати/приховати лінійки"), ("Show/Hide Style Name Column", "Показати/приховати стовпець назв стилів"), ("Show/Hide Tagged Frames", "Показати/приховати фрейми з тегами"), ("Show/Hide Text Threads", "Показати/приховати зв’язки текстових фреймів"), + ("Show/Hide Link Badge", "Показати/приховати значок зв’язку"), ("Smooth", "Згладити"), ("Sort", "Сортувати"), ("Split Cell Horizontally", "Розділити клітинку горизонтально"), diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index e9f6c05df..4e2c20715 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -17,6 +17,7 @@ pub const UPDATE_APP: craft_update::app::App = craft_update::app::App { pub mod about; pub mod canvas; +pub mod channel; pub mod chrome; pub mod control; pub mod credits; @@ -312,6 +313,11 @@ pub struct DesignApp { pub(crate) quit_without_asking: bool, /// No document is discarded until every unsaved document has an up-to-date approval. quitting: Option, + /// A save waiting for the answer to "IDML can't keep all of this document" (`idmlLoss`). + pub(crate) lossy_save: Option, + /// Documents (by uid) whose IDML losses were accepted with Don't ask again: for this session + /// only, never saved. + pub(crate) idml_loss_accepted: std::collections::HashSet, /// A save asked for while the open-time checks of the document's linked files run: it runs /// once they are done, so the first save already writes the links they confirm. pub(crate) waiting_save: Option, diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 678572538..a9a17e2b8 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -10,7 +10,7 @@ mod export; mod invoke; mod keys; mod quick_apply; -mod run; +pub(crate) mod run; mod state; mod tables; mod tree; @@ -31,7 +31,7 @@ pub use keys::{forwarded_shortcuts, shortcuts}; use quick_apply::quick_commands; pub use quick_apply::{QuickItem, command_search, palette, quick_apply_items}; pub use run::run_ui; -pub(crate) use run::save_then; +pub(crate) use run::{LossyAnswer, LossySave, answer_idml_loss, save_then}; pub use state::{ checked, default_shortcut, enabled, menu_enabled, native_key_equivalent, native_menu_enabled, shortcut_label, shortcut_of, shortcut_text, tool_shortcut_label, @@ -64,6 +64,8 @@ fn cmd_item(id: &str, params: Value) -> Item { Item::Cmd { label, id: id.to_string(), params, shortcut } } +#[cfg(test)] +mod save_format_tests; #[cfg(test)] mod tests; diff --git a/crates/ui-egui/src/menus/export.rs b/crates/ui-egui/src/menus/export.rs index a80a55fc0..e35af5a62 100644 --- a/crates/ui-egui/src/menus/export.rs +++ b/crates/ui-egui/src/menus/export.rs @@ -1,14 +1,38 @@ use super::{DesignApp, Value, json}; use crate::app::file_dialogs::{Bound, with_path}; -pub(super) fn download_document(app: &mut DesignApp) -> Result { - let name = app.session.active().map(|d| format!("{}.designcraft", d.doc.title)).ok_or("no document")?; - let ser = app.run("file.serialize", json!({}))?; +/// Save in a browser: download the document in the Save documents as format, asking first when +/// that is IDML and IDML can't keep all of it; then run `after`. +pub(super) fn download_document(app: &mut DesignApp, after: super::run::After) -> Result { + use super::run::LossyAnswer; + let format = app.session.prefs.save_format; + super::run::guard_idml_loss(app, format == designcraft_engine::SaveFormat::Idml, move |app, answer| match answer { + LossyAnswer::SaveAnyway => { + download_as(app, format)?; + after(app) + } + LossyAnswer::SaveAsDesigncraft => { + download_as(app, designcraft_engine::SaveFormat::Designcraft)?; + after(app) + } + LossyAnswer::Cancel => after(app), + }) +} + +/// Download the document as `format`: an IDML package (images embedded), or DesignCraft's own +/// format. +fn download_as(app: &mut DesignApp, format: designcraft_engine::SaveFormat) -> Result { + let name = app.session.active().map(|d| format!("{}.{}", d.doc.title, format.extension())).ok_or("no document")?; + let ser = match format { + designcraft_engine::SaveFormat::Idml => app.run("file.exportIdml", json!({}))?, + designcraft_engine::SaveFormat::Designcraft => app.run("file.serialize", json!({}))?, + }; let bytes = designcraft_engine::cmd::base64_decode(ser["base64"].as_str().unwrap_or_default()); let download = app.services.download.as_mut().ok_or("no download service")?; download(&name, &bytes).map_err(|e| format!("could not download {name}: {e}"))?; - // Marks the document saved; on the web the engine doesn't touch a file system. - app.run("file.saveAs", json!({"path": name})) + // Marks the document saved; on the web the engine doesn't touch a file system. The question + // about what IDML loses was asked above. + app.run("file.saveAs", json!({"path": name, "allowLoss": true})) } /// Asks where to save `name`, then runs `export` with `p` and the chosen path. diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index cb81481e0..81ac00749 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -6,6 +6,19 @@ use super::tree::recent_label; use super::{DesignApp, ScreenMode, Value, json}; use crate::app::file_dialogs::{Bound, with_path}; +/// A path the save dialog returned, with `ext` (the Save documents as format) added unless the name +/// already ends in `.idml` or `.designcraft`: "Brochure" and "Issue 3.1" save as "Brochure.idml" +/// and "Issue 3.1.idml". A name with one of those is kept as typed; its extension decides the +/// format (see `file.save`). +pub(crate) fn with_save_extension(path: &str, ext: &str) -> String { + // Only the two save extensions count as typed: "Issue 3.1" is a name with a dot in it. + let typed = std::path::Path::new(path) + .extension() + .and_then(|e| e.to_str()) + .is_some_and(|e| e.eq_ignore_ascii_case("idml") || e.eq_ignore_ascii_case(designcraft_engine::SaveFormat::Designcraft.extension())); + if typed { path.to_string() } else { format!("{path}.{ext}") } +} + /// Type › Tabs: float the Tabs panel (placed above the selected text frame) or close it. fn toggle_tabs_panel(app: &mut DesignApp) { if app.ui.floating.iter().any(|(p, _)| p == "tabs") { @@ -31,18 +44,105 @@ fn rerun_with_path(app: &mut DesignApp, purpose: &str, id: &str, p: &Value, key: app.ask_open(purpose, Bound::Document, move |app, path| run_ui(app, &id, &with_path(&p, key, path)).unwrap_or(Ok(Value::Null))) } -/// File › Save As: asks where, saves there, then runs `after`. +/// What runs once a save has happened (or was cancelled: it checks the document's state). +pub(crate) type After = Box Result>; + +/// The answer to "IDML can't keep all of this document". +pub(crate) enum LossyAnswer { + /// Save as IDML all the same (also the answer when there is nothing to lose). + SaveAnyway, + /// Save in DesignCraft's own format instead, which keeps everything. + SaveAsDesigncraft, + Cancel, +} + +/// The continuation of a save waiting for the IDML loss question. +pub(crate) type LossySave = Box Result>; + +/// A save as IDML (`idml`) that would lose part of the active document (editorial notes, +/// endnotes: `file.idmlLosses`) asks first, and `then` runs with the answer once it is given. +/// Otherwise `then` runs now, as Save Anyway: there is nothing to lose, or the losses were +/// accepted for this document with Don't ask again (this session only). The engine refuses such +/// a save without `allowLoss`, so nothing is lost without this question (CodeRabbit on #1105). +pub(super) fn guard_idml_loss( + app: &mut DesignApp, + idml: bool, + then: impl FnOnce(&mut DesignApp, LossyAnswer) -> Result + 'static, +) -> Result { + let uid = app.session.active().map(|d| d.uid); + if idml && !uid.is_some_and(|uid| app.idml_loss_accepted.contains(&uid)) { + let mut lost = app.run("file.idmlLosses", json!({}))?; + let count = |k: &str| lost.get(k).and_then(Value::as_u64).unwrap_or(0); + if count("editorialNotes") > 0 || count("endnotes") > 0 { + lost["uid"] = json!(uid); + lost["dontAskAgain"] = json!(false); + app.ui.dialog = Some(crate::dialogs::Dialog::new("idmlLoss", lost)); + app.lossy_save = Some(Box::new(then)); + return Ok(Value::Null); + } + } + then(app, LossyAnswer::SaveAnyway) +} + +/// Whether a save to `path` writes IDML. +fn is_idml_path(path: &str) -> bool { + designcraft_engine::SaveFormat::of_path(path) == designcraft_engine::SaveFormat::Idml +} + +/// File › Save As: asks where (suggesting the `ext` format), saves there, then runs `after`. #[track_caller] -fn save_as_dialog(app: &mut DesignApp, after: impl FnOnce(&mut DesignApp) -> Result + 'static) -> Result { - let name = app.session.active().map(|d| format!("{}.designcraft", d.doc.title)).unwrap_or_default(); - app.ask_save(&name, Bound::Document, move |app, path| { - save_when_checked(app, move |app| { - app.run("file.saveAs", json!({"path": path}))?; +fn save_as_dialog(app: &mut DesignApp, ext: &str, after: After) -> Result { + let name = app.session.active().map(|d| format!("{}.{ext}", d.doc.title)).unwrap_or_default(); + app.ask_save(&name, Bound::Document, move |app, path| save_as_checked(app, path, after)) +} + +/// Save As to `path`, asking first when that is an IDML save that would lose content. +fn save_as_checked(app: &mut DesignApp, path: String, after: After) -> Result { + guard_idml_loss(app, is_idml_path(&path), move |app, answer| match answer { + LossyAnswer::SaveAnyway => save_when_checked(app, move |app| { + app.run("file.saveAs", json!({"path": path, "allowLoss": true}))?; after(app) - }) + }), + LossyAnswer::SaveAsDesigncraft => save_as_dialog(app, designcraft_engine::SaveFormat::Designcraft.extension(), after), + LossyAnswer::Cancel => after(app), }) } +/// Save the active document to its own file, asking first when that is an IDML file and the save +/// would lose content. +fn save_to_own_file(app: &mut DesignApp, after: After) -> Result { + let idml = app.session.active().and_then(|d| d.path.as_deref()).is_some_and(is_idml_path); + guard_idml_loss(app, idml, move |app, answer| match answer { + LossyAnswer::SaveAnyway => save_when_checked(app, move |app| { + app.run("file.save", json!({"allowLoss": true}))?; + after(app) + }), + LossyAnswer::SaveAsDesigncraft => save_as_dialog(app, designcraft_engine::SaveFormat::Designcraft.extension(), after), + LossyAnswer::Cancel => after(app), + }) +} + +/// Save a Copy to `path`, asking first when that is an IDML save that would lose content. +fn save_copy_checked(app: &mut DesignApp, path: String) -> Result { + guard_idml_loss(app, is_idml_path(&path), move |app, answer| match answer { + LossyAnswer::SaveAnyway => save_when_checked(app, move |app| app.run("file.saveACopy", json!({"path": path, "allowLoss": true}))), + LossyAnswer::SaveAsDesigncraft => { + let ext = designcraft_engine::SaveFormat::Designcraft.extension(); + let name = app.session.active().map(|d| format!("{} copy.{ext}", d.doc.title)).unwrap_or_default(); + app.ask_save(&name, Bound::Document, save_copy_checked) + } + LossyAnswer::Cancel => Ok(Value::Null), + }) +} + +/// The IDML loss question was answered: run the save that was waiting for it. +pub(crate) fn answer_idml_loss(app: &mut DesignApp, answer: LossyAnswer) -> Result { + match app.lossy_save.take() { + Some(then) => then(app, answer), + None => Ok(Value::Null), + } +} + /// Run `save` (a save of the active document) now, or, while the open-time checks of its linked /// files run, once they are done ([`DesignApp::run_waiting_save`]): a document saved before /// linked storage then writes the links the checks confirm in its first save, not a copy of every @@ -61,16 +161,13 @@ pub(crate) fn save_when_checked(app: &mut DesignApp, save: impl FnOnce(&mut Desi #[track_caller] pub(crate) fn save_then(app: &mut DesignApp, after: impl FnOnce(&mut DesignApp) -> Result + 'static) -> Result { if app.services.download.is_some() { - download_document(app)?; - return after(app); + return download_document(app, Box::new(after)); } if app.session.active().is_some_and(|d| d.path.is_some()) { - return save_when_checked(app, |app| { - app.run("file.save", json!({}))?; - after(app) - }); + return save_to_own_file(app, Box::new(after)); } - save_as_dialog(app, after) + let ext = app.session.prefs.save_format.extension(); + save_as_dialog(app, ext, Box::new(after)) } /// Run a UI command; `None` if `id` isn't one. @@ -195,32 +292,30 @@ fn run_ui_part1(app: &mut DesignApp, id: &str, p: &Value) -> Option download_document(app), + "app.save" | "app.saveDialog" if app.services.download.is_some() => download_document(app, Box::new(|_| Ok(Value::Null))), "app.save" => { if app.session.active().is_some_and(|d| d.path.is_some()) { - return Some(save_when_checked(app, |app| app.run("file.save", json!({})))); + return Some(save_to_own_file(app, Box::new(|_| Ok(Value::Null)))); } return run_ui(app, "app.saveDialog", p); } "app.saveDialog" => match p.get("path").and_then(Value::as_str) { - Some(path) => { - let path = path.to_owned(); - save_when_checked(app, move |app| app.run("file.saveAs", json!({"path": path}))) + Some(path) => save_as_checked(app, path.to_string(), Box::new(|_| Ok(Value::Null))), + None => { + let ext = app.session.prefs.save_format.extension(); + save_as_dialog(app, ext, Box::new(|_| Ok(Value::Null))) } - None => save_as_dialog(app, |_| Ok(Value::Null)), }, "app.quit" => { app.request_quit(); Ok(Value::Null) } "app.saveCopyDialog" => match p.get("path").and_then(Value::as_str) { - Some(path) => { - let path = path.to_owned(); - save_when_checked(app, move |app| app.run("file.saveACopy", json!({"path": path}))) - } + Some(path) => save_copy_checked(app, path.to_string()), None => { - let name = app.session.active().map(|d| format!("{} copy.designcraft", d.doc.title)).unwrap_or_default(); - app.ask_save(&name, Bound::Document, |app, path| save_when_checked(app, move |app| app.run("file.saveACopy", json!({"path": path})))) + let ext = app.session.prefs.save_format.extension(); + let name = app.session.active().map(|d| format!("{} copy.{ext}", d.doc.title)).unwrap_or_default(); + app.ask_save(&name, Bound::Document, save_copy_checked) } }, "app.exportPng" => export_png(app, p), @@ -770,6 +865,7 @@ fn run_ui_part3(app: &mut DesignApp, id: &str, p: &Value) -> Option flag(&mut app.ui.text_threads), + "view.linkBadge" => flag(&mut app.ui.link_badge), "view.hiddenCharacters" => flag(&mut app.ui.hidden_characters), "view.taggedFrames" => flag(&mut app.ui.tagged_frames), "view.storyEditorStyleColumn" => { @@ -791,6 +887,7 @@ fn run_ui_part3(app: &mut DesignApp, id: &str, p: &Value) -> Option flag(&mut app.ui.story_editor_depth_ruler), + "view.storyEditorParagraphMarks" => flag(&mut app.ui.story_editor_paragraph_marks), "window.hidePanels" | "window.hidePanelsExceptTools" => { let mode = if id == "window.hidePanels" { 1 } else { 2 }; app.ui.hidden_panels = if app.ui.hidden_panels == mode { 0 } else { mode }; diff --git a/crates/ui-egui/src/menus/save_format_tests.rs b/crates/ui-egui/src/menus/save_format_tests.rs new file mode 100644 index 000000000..13d56293e --- /dev/null +++ b/crates/ui-egui/src/menus/save_format_tests.rs @@ -0,0 +1,225 @@ +//! Preferences › File Handling › Save documents as. + +use std::sync::{Arc, Mutex}; + +use serde_json::json; + +use crate::DesignApp; + +#[test] +fn choosing_idml_makes_save_suggest_and_write_idml() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"title": "Brochure"})).unwrap(); + app.run("frame.create", json!({"rect": [72, 72, 400, 200], "content": "text", "text": "Hello"})).unwrap(); + // Preferences › File Handling: InDesign Markup. + app.run("app.preferences", json!({})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + assert_eq!(d.fields["saveFormat"], "designcraft", "DesignCraft's own format by default"); + d.fields.insert("saveFormat".into(), json!("idml")); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(app.session.prefs.save_format, designcraft_engine::SaveFormat::Idml); + // Save: the dialog suggests a .idml name; a name typed without an extension gets .idml. + let dir = tempfile::tempdir().unwrap(); + let typed = dir.path().join("Brochure").to_string_lossy().to_string(); + let suggested = Arc::new(Mutex::new(String::new())); + let seen = suggested.clone(); + app.answer_dialogs(move |request| { + let craft_dialogs::Request::File(dialog) = request else { return craft_dialogs::Answer::Cancelled }; + *seen.lock().unwrap() = dialog.file_name.clone().unwrap_or_default(); + craft_dialogs::Answer::Paths(vec![typed.clone().into()]) + }); + app.run("app.save", json!({})).unwrap(); + app.settle_dialogs(); + assert_eq!(*suggested.lock().unwrap(), "Brochure.idml"); + let path = dir.path().join("Brochure.idml"); + assert!(designcraft_idml::is_idml(&std::fs::read(&path).unwrap())); + assert_eq!(app.session.active().unwrap().path.as_deref(), Some(path.to_str().unwrap())); + // Back to DesignCraft's format: Save As suggests .designcraft again. + app.run("app.preferences", json!({})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + assert_eq!(d.fields["saveFormat"], "idml", "the dialog shows the current choice"); + d.fields.insert("saveFormat".into(), json!("designcraft")); + crate::dialogs::confirm(&mut app).unwrap(); + let seen = suggested.clone(); + app.answer_dialogs(move |request| { + let craft_dialogs::Request::File(dialog) = request else { return craft_dialogs::Answer::Cancelled }; + *seen.lock().unwrap() = dialog.file_name.clone().unwrap_or_default(); + craft_dialogs::Answer::Cancelled + }); + app.run("app.saveDialog", json!({})).unwrap(); + app.settle_dialogs(); + // Started beside the saved file. + let suggested = suggested.lock().unwrap().clone(); + assert_eq!(std::path::Path::new(&suggested).file_name().unwrap(), "Brochure.designcraft", "{suggested}"); +} + +#[test] +fn a_typed_extension_is_kept() { + assert_eq!(super::run::with_save_extension("/a/Brochure", "idml"), "/a/Brochure.idml"); + assert_eq!(super::run::with_save_extension("/a/Brochure.idml", "designcraft"), "/a/Brochure.idml"); + assert_eq!(super::run::with_save_extension("/a/Brochure.designcraft", "idml"), "/a/Brochure.designcraft"); + assert_eq!(super::run::with_save_extension("/a/Brochure.IDML", "designcraft"), "/a/Brochure.IDML"); + // A dot in the name isn't an extension: the chosen format is added. + assert_eq!(super::run::with_save_extension("/a/Issue 3.1", "idml"), "/a/Issue 3.1.idml"); + assert_eq!(super::run::with_save_extension("/a/v1.2 Brochure", "designcraft"), "/a/v1.2 Brochure.designcraft"); +} +/// The web build saves by download: the download is named and written in the chosen format. +#[test] +fn a_download_save_follows_the_save_format() { + for (format, ext) in [("idml", "idml"), ("designcraft", "designcraft")] { + let dir = tempfile::tempdir().unwrap(); + // The title is a path in the temporary folder: on the desktop, marking the download + // saved writes there too. + let title = dir.path().join("Brochure").to_string_lossy().to_string(); + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + let got: Arc)>>> = Arc::default(); + let sink = got.clone(); + app.services.download = Some(Box::new(move |name: &str, bytes: &[u8]| { + sink.lock().unwrap().push((name.to_string(), bytes.to_vec())); + Ok(()) + })); + app.run("prefs.set", json!({"saveFormat": format})).unwrap(); + app.run("file.new", json!({"title": title})).unwrap(); + app.run("frame.create", json!({"rect": [72, 72, 400, 200], "content": "text", "text": "Hello"})).unwrap(); + app.run("app.save", json!({})).unwrap(); + let got = got.lock().unwrap(); + let [(name, bytes)] = got.as_slice() else { panic!("one download: {:?}", got.len()) }; + assert!(name.ends_with(&format!("Brochure.{ext}")), "{name}"); + assert_eq!(designcraft_idml::is_idml(bytes), format == "idml", "{format}"); + assert!(!app.session.active().unwrap().is_dirty(), "the document counts as saved"); + } +} + +/// Answers every file dialog with `path` (as typed in it). +fn answer_with(app: &mut DesignApp, path: &std::path::Path) { + let path = path.to_path_buf(); + app.answer_dialogs(move |request| match request { + craft_dialogs::Request::File(_) => craft_dialogs::Answer::Paths(vec![path.clone()]), + _ => craft_dialogs::Answer::Cancelled, + }); +} + +/// A new document with a text frame holding an editorial note: IDML can't keep it. +fn document_with_a_note(app: &mut DesignApp, title: &str) { + app.run("file.new", json!({"title": title})).unwrap(); + app.run("frame.create", json!({"rect": [72, 72, 400, 200], "content": "text", "text": "Hello"})).unwrap(); + app.run("note.new", json!({"text": "Check this"})).unwrap(); +} + +/// CodeRabbit on #1105: a save as IDML that would lose editorial notes asks first. Cancel saves +/// nothing; Save Anyway writes the IDML; Save as DesignCraft… asks where and writes DesignCraft's +/// format instead, which keeps the notes. +#[test] +fn an_idml_save_that_would_lose_notes_asks_first() { + let dir = tempfile::tempdir().unwrap(); + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("prefs.set", json!({"saveFormat": "idml"})).unwrap(); + document_with_a_note(&mut app, "Notes"); + let idml = dir.path().join("Notes.idml"); + answer_with(&mut app, &idml); + + // Cancel: nothing written, still unsaved. + app.run("app.save", json!({})).unwrap(); + app.settle_dialogs(); + let d = app.ui.dialog.as_ref().expect("the IDML loss question"); + assert_eq!((d.id.as_str(), &d.fields["editorialNotes"], &d.fields["endnotes"]), ("idmlLoss", &json!(1), &json!(0))); + crate::dialogs::cancel(&mut app); + assert!(app.ui.dialog.is_none() && app.lossy_save.is_none()); + assert!(!idml.exists()); + assert!(app.session.active().unwrap().is_dirty()); + + // Save Anyway: the IDML is written and the document counts as saved. + app.run("app.save", json!({})).unwrap(); + app.settle_dialogs(); + crate::dialogs::confirm(&mut app).unwrap(); + assert!(designcraft_idml::is_idml(&std::fs::read(&idml).unwrap())); + assert!(!app.session.active().unwrap().is_dirty()); + assert_eq!(app.session.active().unwrap().path.as_deref(), Some(idml.to_str().unwrap())); + + // ⌘S to its own IDML file asks again; Save as DesignCraft… saves as DesignCraft instead. + app.run("note.new", json!({"text": "And this"})).unwrap(); + let before = std::fs::read(&idml).unwrap(); + let native = dir.path().join("Notes.designcraft"); + answer_with(&mut app, &native); + app.run("app.save", json!({})).unwrap(); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.id.as_str()), Some("idmlLoss")); + app.ui.dialog.as_mut().unwrap().fields.insert("asDesigncraft".into(), json!(true)); + crate::dialogs::confirm(&mut app).unwrap(); + app.settle_dialogs(); + assert_eq!(std::fs::read(&idml).unwrap(), before, "the IDML file is untouched"); + let saved = std::fs::read(&native).unwrap(); + assert!(!designcraft_idml::is_idml(&saved)); + assert_eq!(app.session.active().unwrap().path.as_deref(), Some(native.to_str().unwrap())); + assert!(!app.session.active().unwrap().is_dirty()); + + // Save a Copy to an IDML name asks too; Cancel writes nothing. + let copy = dir.path().join("Copy.idml"); + app.run("app.saveCopyDialog", json!({"path": copy.to_string_lossy()})).unwrap(); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.id.as_str()), Some("idmlLoss")); + crate::dialogs::cancel(&mut app); + assert!(!copy.exists()); +} + +/// In a browser, the download asks the same question; Save as DesignCraft… downloads DesignCraft's +/// format. +#[test] +fn a_download_that_would_lose_notes_asks_first() { + let dir = tempfile::tempdir().unwrap(); + let title = dir.path().join("Notes").to_string_lossy().to_string(); + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + let got: Arc)>>> = Arc::default(); + let sink = got.clone(); + app.services.download = Some(Box::new(move |name: &str, bytes: &[u8]| { + sink.lock().unwrap().push((name.to_string(), bytes.to_vec())); + Ok(()) + })); + app.run("prefs.set", json!({"saveFormat": "idml"})).unwrap(); + document_with_a_note(&mut app, &title); + app.run("app.save", json!({})).unwrap(); + assert!(got.lock().unwrap().is_empty(), "nothing downloaded before the answer"); + app.ui.dialog.as_mut().unwrap().fields.insert("asDesigncraft".into(), json!(true)); + crate::dialogs::confirm(&mut app).unwrap(); + let got = got.lock().unwrap(); + let [(name, bytes)] = got.as_slice() else { panic!("one download: {:?}", got.len()) }; + assert!(name.ends_with("Notes.designcraft"), "{name}"); + assert!(!designcraft_idml::is_idml(bytes)); + assert!(!app.session.active().unwrap().is_dirty()); +} + +/// Don't ask again (with Save Anyway) stops the question for that document, for this session +/// only (it is kept by the app, not in the document or the preferences): another document is +/// still asked about. +#[test] +fn dont_ask_again_holds_for_the_document_in_this_session() { + let dir = tempfile::tempdir().unwrap(); + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + document_with_a_note(&mut app, "Notes"); + let idml = dir.path().join("Notes.idml"); + // Not ticked: asked again next time. + app.run("app.saveDialog", json!({"path": idml.to_string_lossy()})).unwrap(); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields["dontAskAgain"], false); + crate::dialogs::confirm(&mut app).unwrap(); + app.run("note.new", json!({"text": "Two"})).unwrap(); + app.run("app.save", json!({})).unwrap(); + // Ticked, but Save as DesignCraft… chosen: it doesn't count. + let d = app.ui.dialog.as_mut().expect("asked again"); + d.fields.insert("dontAskAgain".into(), json!(true)); + d.fields.insert("asDesigncraft".into(), json!(true)); + answer_with(&mut app, &dir.path().join("Notes.designcraft")); + crate::dialogs::confirm(&mut app).unwrap(); + app.settle_dialogs(); + app.run("app.saveDialog", json!({"path": idml.to_string_lossy()})).unwrap(); + // Ticked with Save Anyway: saved, and not asked again for this document. + app.ui.dialog.as_mut().expect("still asked").fields.insert("dontAskAgain".into(), json!(true)); + crate::dialogs::confirm(&mut app).unwrap(); + app.run("note.new", json!({"text": "Three"})).unwrap(); + app.run("app.save", json!({})).unwrap(); + assert!(app.ui.dialog.is_none(), "not asked again"); + assert!(!app.session.active().unwrap().is_dirty(), "saved as IDML"); + assert!(designcraft_idml::is_idml(&std::fs::read(&idml).unwrap())); + // Another document is still asked about. + document_with_a_note(&mut app, "Other"); + app.run("app.saveDialog", json!({"path": dir.path().join("Other.idml").to_string_lossy()})).unwrap(); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.id.as_str()), Some("idmlLoss")); + crate::dialogs::cancel(&mut app); +} diff --git a/crates/ui-egui/src/menus/state.rs b/crates/ui-egui/src/menus/state.rs index ef7cf17c6..8707bd237 100644 --- a/crates/ui-egui/src/menus/state.rs +++ b/crates/ui-egui/src/menus/state.rs @@ -116,10 +116,12 @@ pub fn checked(app: &DesignApp, id: &str, params: &Value) -> Option { "view.baselineGrid" => app.ui.baseline_grid, "view.documentGrid" => app.ui.document_grid, "view.textThreads" => app.ui.text_threads, + "view.linkBadge" => app.ui.link_badge, "view.hiddenCharacters" => app.ui.hidden_characters, "view.taggedFrames" => app.ui.tagged_frames, "view.storyEditorStyleColumn" => app.ui.story_editor_style_column, "view.storyEditorDepthRuler" => app.ui.story_editor_depth_ruler, + "view.storyEditorParagraphMarks" => app.ui.story_editor_paragraph_marks, "changes.track" => app.session.active().is_some_and(|d| d.doc.settings.track_changes), // Pressed, as the Bulleted and Numbered List buttons: every paragraph the command applies // to (selected text, cells or text frames) has it. diff --git a/crates/ui-egui/src/menus/tables.rs b/crates/ui-egui/src/menus/tables.rs index e569ef788..b3ddc62b2 100644 --- a/crates/ui-egui/src/menus/tables.rs +++ b/crates/ui-egui/src/menus/tables.rs @@ -534,6 +534,7 @@ pub const MENUS: &[(&str, &[&str])] = &[ ">Extras", "ui:view.frameEdges", "ui:view.textThreads", + "ui:view.linkBadge", "<", ">Grids & Guides", "ui:view.guides", @@ -555,6 +556,7 @@ pub const MENUS: &[(&str, &[&str])] = &[ ">Story Editor", "ui:view.storyEditorStyleColumn", "ui:view.storyEditorDepthRuler", + "ui:view.storyEditorParagraphMarks", "<", ], ), diff --git a/crates/ui-egui/src/menus/tests.rs b/crates/ui-egui/src/menus/tests.rs index fd5a1a876..d5284b1c6 100644 --- a/crates/ui-egui/src/menus/tests.rs +++ b/crates/ui-egui/src/menus/tests.rs @@ -94,6 +94,7 @@ fn view_items_are_in_the_view_menu_as_in_indesign() { "view.tagMarkers", "view.storyEditorStyleColumn", "view.storyEditorDepthRuler", + "view.storyEditorParagraphMarks", ] { assert!(view.contains(&id), "{id} is in View"); assert!(!typ.contains(&id), "{id} isn't in Type"); @@ -1975,6 +1976,56 @@ fn copy_and_paste_keys_work_for_objects_without_a_native_menu() { assert!(text.contains(designcraft_doc::OBJECT_MARK), "{text:?}"); } +/// Cutting an object after copying text must leave the object's placeholder on the system +/// clipboard, as copying one does, so Paste at a caret anchors the object, not the older text. +#[test] +fn cutting_an_object_after_copying_text_pastes_the_object_at_a_caret_without_a_native_menu() { + let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", &json!({})).unwrap(); + let ctx = egui::Context::default(); + let frame = |app: &mut crate::DesignApp, events: Vec| { + let input = egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))), + events, + ..Default::default() + }; + let mut out = ctx.run_ui(input, |ui| { + app.logic(&ui.ctx().clone()); + app.ui(ui); + }); + out.textures_delta.clear(); + out.platform_output.commands + }; + let copied_text = |commands: Vec| { + commands.into_iter().find_map(|c| match c { + egui::OutputCommand::CopyText(t) => Some(t), + _ => None, + }) + }; + frame(&mut app, vec![]); + frame(&mut app, vec![]); + let source = app.session.execute("frame.create", &json!({"rect": [72, 72, 300, 160], "content": "text", "text": "old text"})).unwrap(); + let source = source["story"].as_u64().unwrap(); + let target = app.session.execute("frame.create", &json!({"rect": [72, 300, 400, 400], "content": "text", "text": "target"})).unwrap(); + let target = designcraft_doc::StoryId(target["story"].as_u64().unwrap()); + app.session.execute("text.select", &json!({"story": source, "anchor": 0, "focus": 8})).unwrap(); + frame(&mut app, vec![egui::Event::Copy]); + let rect = app.session.execute("frame.create", &json!({"rect": [72, 420, 122, 470]})).unwrap()["id"].as_u64().unwrap(); + app.session.execute("selection.set", &json!({"ids": [rect]})).unwrap(); + let cut = copied_text(frame(&mut app, vec![egui::Event::Cut])).expect("cutting objects puts their placeholder on the system clipboard"); + assert_ne!(cut, "old text", "the system clipboard no longer holds the earlier text copy"); + assert!(app.session.active().unwrap().doc.item(designcraft_doc::ItemId(rect)).is_none(), "the rectangle was cut"); + app.session.execute("tool.select", &json!({"tool": "type"})).unwrap(); + app.session.execute("text.select", &json!({"story": target.0, "anchor": 0, "focus": 0})).unwrap(); + frame(&mut app, vec![egui::Event::Paste(cut)]); + let d = app.session.active().unwrap(); + let story = d.doc.story(target).unwrap(); + assert_eq!(story.objects.len(), 1, "the cut rectangle is anchored: {:?}", story.text); + assert!(story.text.contains(designcraft_doc::OBJECT_MARK) && story.text.ends_with("target"), "{:?}", story.text); + assert!(!story.text.contains("old text"), "{:?}", story.text); + d.doc.check().unwrap(); +} + #[test] fn paste_with_no_insertion_point_makes_a_text_frame_from_other_apps_text() { // #518: text copied in another app pastes as a new, selected text frame; the text an diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index d42f1802b..17fc9745f 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -275,6 +275,7 @@ pub const UI_COMMANDS: &[(&str, &str, Option<&str>, &str)] = &[ ("view.baselineGrid", "Show/Hide Baseline Grid", Some("Cmd+Alt+'"), "{}"), ("view.documentGrid", "Show/Hide Document Grid", Some("Cmd+'"), "{}"), ("view.textThreads", "Show/Hide Text Threads", Some("Cmd+Alt+Y"), "{}"), + ("view.linkBadge", "Show/Hide Link Badge", None, "{}"), ("view.hiddenCharacters", "Show Hidden Characters", Some("Cmd+Alt+I"), "{}"), ("view.taggedFrames", "Show/Hide Tagged Frames", None, "{} — XML-tagged frames outlined in their tag colour"), ( @@ -289,6 +290,12 @@ pub const UI_COMMANDS: &[(&str, &str, Option<&str>, &str)] = &[ None, "{} — the Story Editor's vertical ruler of how deep the text reaches in its frames", ), + ( + "view.storyEditorParagraphMarks", + "Show/Hide Paragraph Break Marks", + None, + "{} — a ¶ after each paragraph that a paragraph break ends, in the Story Editor", + ), ("window.hidePanels", "Show/Hide Panels", Some("Tab"), "{} — every panel, the Tools panel included"), ("window.hidePanelsExceptTools", "Show/Hide Panels Except Tools", Some("Shift+Tab"), "{}"), ("window.nextDocument", "Next Document", Some("Cmd+F6"), "{}"), diff --git a/crates/ui-egui/src/panels/properties/links.rs b/crates/ui-egui/src/panels/properties/links.rs index 2911815b7..06d039967 100644 --- a/crates/ui-egui/src/panels/properties/links.rs +++ b/crates/ui-egui/src/panels/properties/links.rs @@ -188,14 +188,26 @@ pub fn links_panel(app: &mut DesignApp, ui: &mut egui::Ui) { p[k] = v; p }; + // A browser hands over the chosen files' bytes, not paths: they arrive through the inbox. + let browser = app.services.open_async.is_some(); if ui.button(crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, "Relink…"))).clicked() { - let target = with("path", Value::Null); - let asked = app.ask_open("relink", Bound::Document, move |app, path| { - let _ = app.run("links.relink", crate::app::file_dialogs::with_path(&target, "path", path)); - Ok(Value::Null) - }); - if let Err(e) = asked { - app.status_error("Relink", e); + if browser { + // A linked text story is read from its path, which a browser doesn't give: say so + // rather than ignore the click. + if is_text { + app.status(crate::i18n::tr(&app.ui.language, "A linked text file can't be relinked in the browser")); + } else { + app.request_files(&format!("relink:{aid}")); + } + } else { + let target = with("path", Value::Null); + let asked = app.ask_open("relink", Bound::Document, move |app, path| { + let _ = app.run("links.relink", crate::app::file_dialogs::with_path(&target, "path", path)); + Ok(Value::Null) + }); + if let Err(e) = asked { + app.status_error("Relink", e); + } } } if ui.button(crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, "Go To"))).clicked() { @@ -247,22 +259,19 @@ pub fn links_panel(app: &mut DesignApp, ui: &mut egui::Ui) { } }); ui.horizontal(|ui| { - // Choose any file in the folder: missing links are looked up there by name. + // Missing links are looked up in the chosen folder by name. In a browser, which hands over + // files rather than paths, the folder's files are chosen instead. + let browser = app.services.open_async.is_some(); if ui .button(crate::i18n::tr(&app.ui.language, "Relink to Folder…")) .on_hover_ui(|ui| { - crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Pick a file in the folder holding the moved graphics")); + crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Choose the folder holding the moved graphics")); }) .clicked() { - let asked = app.ask_open("relink", Bound::Document, |app, path| { - let Some(dir) = std::path::Path::new(&path).parent() else { return Ok(Value::Null) }; - if let Ok(v) = app.run("links.relinkFolder", json!({"dir": dir.to_string_lossy()})) { - app.status(crate::i18n::tr(&app.ui.language, "Relinked {count}").replace("{count}", &v["relinked"].to_string())); - } - Ok(Value::Null) - }); - if let Err(e) = asked { + if browser { + app.request_files("relinkFiles"); + } else if let Err(e) = relink_to_folder(app) { app.status_error("Relink", e); } } @@ -355,6 +364,18 @@ impl DesignApp { } } +/// Relink to Folder: asks for the folder holding the moved graphics and looks missing +/// links up there by name. +pub(crate) fn relink_to_folder(app: &mut DesignApp) -> Result { + let title = crate::i18n::tr(&app.ui.language, "Relink to Folder").to_string(); + app.ask_folder(&title, Bound::Document, |app, dir| { + if let Ok(v) = app.run("links.relinkFolder", json!({"dir": dir})) { + app.status(crate::i18n::tr(&app.ui.language, "Relinked {count}").replace("{count}", &v["relinked"].to_string())); + } + Ok(Value::Null) + }) +} + /// Update Link from the Links panel or the menu (`{asset}`, `{story}`, or `{}` for all): asks /// first when a linked text story edited in the layout would lose those edits, as InDesign's /// Links panel does. The `links.update` command itself doesn't ask (as in InDesign scripting). diff --git a/crates/ui-egui/src/panels/properties/object_panels.rs b/crates/ui-egui/src/panels/properties/object_panels.rs index 194fecc2e..a2756621d 100644 --- a/crates/ui-egui/src/panels/properties/object_panels.rs +++ b/crates/ui-egui/src/panels/properties/object_panels.rs @@ -548,9 +548,11 @@ pub fn effects_panel(app: &mut DesignApp, ui: &mut egui::Ui) { // Distance and Size in the document's unit, as in the Effects dialog: a bare `7` means the // same in both. let u = units(app); + // Room for a measurement with its unit (`35.278 mm`). + const MEASURE_W: f32 = 66.0; egui::Grid::new("dsg").num_columns(4).spacing(vec2(6.0, 4.0)).show(ui, |ui| { caption(ui, crate::i18n::tr(&app.ui.language, "Distance")); - if let Some(v) = measure(ui, "dsd", Some(ds.distance), u, 56.0) { + if let Some(v) = measure(ui, "dsd", Some(ds.distance), u, MEASURE_W) { let _ = app.run("object.dropShadow", json!({"on": true, "distance": v})); } caption(ui, crate::i18n::tr(&app.ui.language, "Angle")); @@ -577,7 +579,7 @@ pub fn effects_panel(app: &mut DesignApp, ui: &mut egui::Ui) { let _ = app.run("object.dropShadow", json!({"on": true, "opacity": v / 100.0})); } caption(ui, crate::i18n::tr(&app.ui.language, "Size")); - if let Some(v) = measure(ui, "dss", Some(ds.size), u, 56.0) { + if let Some(v) = measure(ui, "dss", Some(ds.size), u, MEASURE_W) { let _ = app.run("object.dropShadow", json!({"on": true, "size": v})); } ui.end_row(); diff --git a/crates/ui-egui/src/panels/properties/tests.rs b/crates/ui-egui/src/panels/properties/tests.rs index 4325c3444..12f5a0253 100644 --- a/crates/ui-egui/src/panels/properties/tests.rs +++ b/crates/ui-egui/src/panels/properties/tests.rs @@ -1630,3 +1630,38 @@ fn text_frame_section_shows_the_frame_that_shows_the_caret() { let shown = super::text::text_frame_target(&app).map(|(id, o, _)| (id, o.columns)); assert_eq!(shown, Some((ItemId(b), 3))); } + +/// #2543: Relink to Folder opens a folder picker (not a file picker) and relinks the missing +/// graphic from the chosen folder. +#[test] +fn relink_to_folder_asks_for_a_folder_and_relinks() { + use std::{cell::RefCell, rc::Rc}; + let dir = tempfile::tempdir().unwrap(); + let (from, to) = (dir.path().join("from"), dir.path().join("to")); + std::fs::create_dir_all(&from).unwrap(); + std::fs::create_dir_all(&to).unwrap(); + let png = designcraft_render::Rendered { width: 10, height: 10, pixels: vec![200; 400] }.to_png(); + let old = from.join("photo.png"); + std::fs::write(&old, &png).unwrap(); + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + app.run("file.place", json!({"path": old.to_string_lossy()})).unwrap(); + let moved = to.join("photo.png"); + std::fs::rename(&old, &moved).unwrap(); + let rows = app.session.execute("links.list", &json!({})).unwrap(); + assert_eq!(rows[0]["status"], "missing"); + let seen: Rc>> = Rc::default(); + let seen2 = seen.clone(); + let dest = to.to_string_lossy().to_string(); + app.answer_dialogs(move |request| { + let craft_dialogs::Request::File(dialog) = request else { return craft_dialogs::Answer::Cancelled }; + *seen2.borrow_mut() = Some(dialog.kind); + craft_dialogs::Answer::Paths(vec![dest.clone().into()]) + }); + super::links::relink_to_folder(&mut app).unwrap(); + app.settle_dialogs(); + assert_eq!(seen.borrow().clone(), Some(craft_dialogs::Kind::Folder), "Relink to Folder opens a folder picker"); + let rows = app.session.execute("links.list", &json!({})).unwrap(); + assert_eq!(rows[0]["status"], "ok", "{rows:?}"); + assert!(app.ui.status.contains("Relinked 1"), "status line says what happened: {:?}", app.ui.status); +} diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 53a77a6c5..5cb557c17 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -7,6 +7,9 @@ use super::{Deserialize, Point, Serialize, SnapView, Unit, canvas, dialogs, page pub struct ImportRequest { pub purpose: String, pub target: Option, + /// File names wanted, lower case (Relink to Folder: the missing graphics' names), so the host + /// reads only those from a chosen folder. Empty: any. + pub wanted: Vec, } pub struct ImportedFile { @@ -190,6 +193,8 @@ pub struct UiState { pub baseline_grid: bool, pub document_grid: bool, pub text_threads: bool, + /// View › Extras › Show Link Badge: the chain on frames showing a linked file. + pub link_badge: bool, pub hidden_characters: bool, /// View › Structure › Show Tagged Frames. pub tagged_frames: bool, @@ -238,6 +243,8 @@ pub struct UiState { /// Width of the Story Editor's style name column, in screen points (set by dragging its bar or by /// `view.storyEditorStyleColumn` `width`). pub story_editor_style_width: f32, + /// View › Story Editor › Show/Hide Paragraph Break Marks. + pub story_editor_paragraph_marks: bool, /// The Color Picker's component (its radio button, as `PickComp::key`: `h`, `s`, `b`, `l`, /// `la`, `lb`, `r`, `g`, `bl`), kept between openings and sessions, as Photoshop's picker is. pub color_picker_component: String, @@ -410,6 +417,7 @@ impl Default for UiState { baseline_grid: false, document_grid: false, text_threads: false, + link_badge: true, hidden_characters: false, tagged_frames: false, hidden_menu_items: Vec::new(), @@ -418,6 +426,7 @@ impl Default for UiState { story_editor_depth_ruler: true, story_editor_style_column: true, story_editor_style_width: story_editor::STYLE_COLUMN_WIDTH, + story_editor_paragraph_marks: false, color_picker_component: "r".into(), scripts: vec![ ("Number the pages".into(), "# A page-number frame at the bottom of the current page.\nframe.create {\"rect\": [288, 740, 324, 760], \"content\": \"text\", \"text\": \"\"}\ntext.select {\"story\": \"$0.story\", \"anchor\": 0, \"focus\": 0}\ntext.insert {\"text\": \"\\ue000\", \"raw\": true}".into()), @@ -573,6 +582,8 @@ impl CanvasCache { patches: 0, separations: separations::Preview::default(), images: (0, f64::NEG_INFINITY), + pixels: None, + pixels_generation: 0, } } } @@ -609,6 +620,10 @@ pub struct CanvasCache { /// The [`designcraft_render::images::generation`] the canvas renders with, and when it took /// it (ms): finished background decodes are taken up in batches, one render for many. pub images: (u64, f64), + /// The pixels the canvas texture shows (full resolution, as uploaded), and a counter that + /// changes with them: a text highlight inverts what it covers from these, without rendering. + pub pixels: Option>, + pub pixels_generation: u64, } #[derive(Default, Clone, Copy, Debug, Serialize)] diff --git a/crates/ui-egui/src/story_editor.rs b/crates/ui-egui/src/story_editor.rs index 3d8392322..bc3330bb4 100644 --- a/crates/ui-egui/src/story_editor.rs +++ b/crates/ui-egui/src/story_editor.rs @@ -23,6 +23,9 @@ const RULER_WIDTH: f32 = 34.0; const RULER_LABEL_GAP: f32 = 10.0; /// Color of the overset line and label. const OVERSET_RED: egui::Color32 = egui::Color32::from_rgb(230, 40, 40); +/// The mark after each paragraph that a paragraph break ends while View › Story Editor › Show Paragraph +/// Break Marks is on, as Type › Show Hidden Characters marks paragraph ends on the canvas. +const PARAGRAPH_MARK: &str = "¶"; /// The story open in the Story Editor. Story ids are counted per document, so the editor is bound /// to the document the story belongs to. @@ -79,14 +82,21 @@ pub fn show(app: &mut DesignApp, ctx: &egui::Context) { // Depth ruler: painted after the text too, beside the rows the lines start on. let ruler = depths.as_ref().map(|_| ui.allocate_exact_size(vec2(RULER_WIDTH, 0.0), egui::Sense::hover()).0); let mut text = story.text.clone(); + let font = egui::FontId::proportional(app.ui.story_editor_size.clamp(8.0, 36.0)); + // With paragraph break marks shown, the text wraps one text size short of the right edge and + // starts one text size in from the left, so a mark after a full row, left-to-right or + // right-to-left, stays within the width the text has without marks. + let marks = app.ui.story_editor_paragraph_marks; + let width = if marks { (ui.available_width() - font.size).max(font.size) } else { f32::INFINITY }; + let left = if marks { font.size.round().clamp(0.0, f32::from(i8::MAX)) as i8 } else { 0 }; // The text field has a fixed id, so it keeps its focus and caret when the columns before it // are shown or hidden. let out = egui::TextEdit::multiline(&mut text) .id(egui::Id::unique("story_editor_text")) - .font(egui::FontId::proportional(app.ui.story_editor_size.clamp(8.0, 36.0))) - .desired_width(f32::INFINITY) + .font(font.clone()) + .desired_width(width) .desired_rows(20) - .frame(egui::Frame::NONE) + .frame(egui::Frame::NONE.inner_margin(egui::Margin { left, ..egui::Margin::ZERO })) .show(ui); let r = out.response; let changed = r.changed(); @@ -125,6 +135,11 @@ pub fn show(app: &mut DesignApp, ctx: &egui::Context) { } drag.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Unknown, true, "Style name column divider")); } + if app.ui.story_editor_paragraph_marks { + for (spot, corner) in paragraph_mark_spots(&out.galley) { + ui.painter().text(out.galley_pos + spot.to_vec2(), corner, PARAGRAPH_MARK, font.clone(), t.text_dim); + } + } let overset_y = overset.filter(|_| !changed).map(|o| { let ci = char_offsets(&story.text, std::iter::once(o)); out.galley_pos.y + start_rows(&out.galley, &ci).first().map_or(0.0, |row| row.0) @@ -200,6 +215,25 @@ pub(crate) fn style_column_width(width: f32) -> f32 { if width.is_finite() { width.clamp(STYLE_COLUMN_RANGE.0, STYLE_COLUMN_RANGE.1) } else { STYLE_COLUMN_WIDTH } } +/// Where the paragraph break marks go, in galley coordinates, with the corner of the mark at that +/// point: just after the last row of every paragraph that a paragraph break ends, past any spaces at +/// its end. A right-to-left paragraph ends on the left, so its mark goes left of the row. +fn paragraph_mark_spots(galley: &egui::Galley) -> Vec<(egui::Pos2, egui::Align2)> { + galley + .rows + .iter() + .filter(|row| row.ends_with_newline) + .map(|row| { + let rect = row.rect(); + if row.rtl_paragraph { + (pos2(rect.min.x - 1.0, rect.min.y), egui::Align2::RIGHT_TOP) + } else { + (pos2(rect.max.x + 1.0, rect.min.y), egui::Align2::LEFT_TOP) + } + }) + .collect() +} + /// Vertical offset of the first laid-out row of each paragraph, from `(row y, row ends with a newline)` /// in layout order. A paragraph that wraps spans several rows, so counting characters per line /// drifts from what the editor draws; the rows themselves are the truth. @@ -668,6 +702,126 @@ mod tests { assert_eq!((app.ui.story_editor_style_column, app.ui.story_editor_style_width), (true, 400.0)); } + /// Every ¶ painted in the window: its rect and the rect it is clipped to. + fn paragraph_marks(h: &egui_kittest::Harness<'_, crate::test_window::Window>) -> Vec<(egui::Rect, egui::Rect)> { + fn walk(shape: &egui::Shape, clip: egui::Rect, out: &mut Vec<(egui::Rect, egui::Rect)>) { + match shape { + egui::Shape::Vec(shapes) => shapes.iter().for_each(|s| walk(s, clip, out)), + egui::Shape::Text(t) if t.galley.text() == super::PARAGRAPH_MARK => out.push((t.visual_bounding_rect(), clip)), + _ => {} + } + } + let mut out = Vec::new(); + for c in &h.output().shapes { + walk(&c.shape, c.clip_rect, &mut out); + } + out + } + + /// View › Story Editor › Show/Hide Paragraph Break Marks: off at first; on, a ¶ follows each of the + /// first two paragraphs and none the last; the setting is remembered. + #[test] + fn paragraph_break_marks_show_and_hide_from_the_view_menu() { + let text = format!("First\n{}\nLast", "A paragraph long enough to wrap over several rows in the editor. ".repeat(12).trim_end()); + let mut h = story_editor_harness(&text); + assert!(!h.state().app.ui.story_editor_paragraph_marks, "hidden by default"); + let before = paragraph_marks(&h); + h.state_mut().app.run("view.storyEditorParagraphMarks", json!({})).unwrap(); + h.run_steps(2); + let field = h.get_by(|n| n.role() == egui::accesskit::Role::MultilineTextInput && n.value().as_deref() == Some(text.as_str())).rect(); + let marks: Vec<_> = paragraph_marks(&h).into_iter().filter(|m| !before.contains(m)).collect(); + assert_eq!(marks.len(), 2, "one mark after each of the first two paragraphs: {marks:?}"); + let (first, second) = (marks[0].0, marks[1].0); + assert!(first.min.x > field.min.x && first.min.x < field.center().x, "the first mark follows the short first row: {first:?} in {field:?}"); + assert!( + second.min.y > first.min.y + 2.0 * first.height(), + "the second mark is below the first, past the wrapped paragraph's first rows: {first:?}, {second:?}" + ); + let app = &h.state().app; + assert_eq!(crate::menus::checked(app, "view.storyEditorParagraphMarks", &json!({})), Some(true)); + let saved = serde_json::to_vec(&app.ui).unwrap(); + assert!(crate::UiState::from_preferences_json(&saved).unwrap().story_editor_paragraph_marks); + h.state_mut().app.run("view.storyEditorParagraphMarks", json!({})).unwrap(); + h.run_steps(2); + assert_eq!(paragraph_marks(&h), before, "hiding them takes the marks away"); + } + + /// A paragraph that would just fill the editor's width wraps while the marks show, so its mark is + /// drawn within the width the text has without marks, not in the window's margin or cut off. + #[test] + fn a_mark_after_a_full_row_stays_in_the_window() { + let field = |h: &egui_kittest::Harness<'_, crate::test_window::Window>, text: &str| { + h.get_by(|n| n.role() == egui::accesskit::Role::MultilineTextInput && n.value().as_deref() == Some(text)).rect() + }; + let h = story_editor_harness("x"); + let full = field(&h, "x").width(); + let size = h.state().app.ui.story_editor_size; + let width = |s: &str| h.ctx.fonts_mut(|f| f.layout_no_wrap(s.into(), egui::FontId::proportional(size), egui::Color32::WHITE)).size().x; + let mut line = String::from("i"); + while width(&format!("{line}i")) < full - 1.0 { + line.push('i'); + } + assert!(full - width(&line) < 4.0, "the row fills the editor: {} of {full}", width(&line)); + drop(h); + let text = format!("{line}\nEnd"); + let mut h = story_editor_harness(&text); + let edge = field(&h, &text).max.x; + let before = paragraph_marks(&h); + h.state_mut().app.run("view.storyEditorParagraphMarks", json!({})).unwrap(); + h.run_steps(2); + let marks: Vec<_> = paragraph_marks(&h).into_iter().filter(|m| !before.contains(m)).collect(); + assert_eq!(marks.len(), 1, "{marks:?}"); + let (rect, clip) = marks[0]; + assert!(clip.contains_rect(rect), "the mark is not cut off: {rect:?} in {clip:?}"); + assert!(rect.max.x <= edge, "the mark stays left of the text's right edge {edge}: {rect:?}"); + } + + /// A right-to-left paragraph ends on the left, so its mark goes left of its last row, within + /// the editor even when that row starts at the text's left edge. + #[test] + fn a_right_to_left_paragraph_has_its_mark_on_the_left() { + let field = |h: &egui_kittest::Harness<'_, crate::test_window::Window>, text: &str| { + h.get_by(|n| n.role() == egui::accesskit::Role::MultilineTextInput && n.value().as_deref() == Some(text)).rect() + }; + // The right-to-left row is wider than "End", so it starts at the text's left edge. + let text = format!("{}\nEnd", "\u{628}".repeat(12)); + let mut h = story_editor_harness(&text); + let size = h.state().app.ui.story_editor_size; + let before = paragraph_marks(&h); + h.state_mut().app.run("view.storyEditorParagraphMarks", json!({})).unwrap(); + h.run_steps(2); + let field = field(&h, &text); + let marks: Vec<_> = paragraph_marks(&h).into_iter().filter(|m| !before.contains(m)).collect(); + assert_eq!(marks.len(), 1, "{marks:?}"); + let (rect, clip) = marks[0]; + assert!(rect.max.x <= field.min.x + size, "the mark is left of the row, where the paragraph ends: {rect:?} in {field:?}"); + assert!(rect.min.x >= field.min.x, "the mark stays within the editor: {rect:?} in {field:?}"); + assert!(clip.contains_rect(rect), "the mark is not cut off: {rect:?} in {clip:?}"); + } + + /// A mark goes after the last row of a wrapped paragraph and after an empty paragraph, and not + /// after the story's last paragraph, which no paragraph break ends. + #[test] + fn paragraph_marks_go_after_each_paragraph_break() { + let ctx = egui::Context::default(); + let mut galley = None; + let mut output = ctx.run_ui(egui::RawInput::default(), |ui| { + galley = Some(ui.fonts_mut(|f| f.layout("aa\nbbbb bbbb\n\ncc".into(), egui::FontId::proportional(14.0), egui::Color32::WHITE, 40.0))); + }); + output.textures_delta.clear(); + let galley = galley.expect("laid out"); + let spots = super::paragraph_mark_spots(&galley); + assert!(spots.iter().all(|s| s.1 == egui::Align2::LEFT_TOP), "{spots:?}"); + let spots: Vec<_> = spots.into_iter().map(|s| s.0).collect(); + assert_eq!(spots.len(), 3, "{spots:?}"); + let rows = &galley.rows; + assert!(rows.len() >= 5, "the second paragraph wraps: {} rows", rows.len()); + assert_eq!(spots[0], egui::pos2(rows[0].rect().max.x + 1.0, rows[0].rect().min.y)); + assert_eq!(spots[1].y, rows[2].rect().min.y, "after the wrapped row, not the paragraph's first"); + assert!(spots[1].x > rows[2].rect().min.x + 1.0); + assert_eq!(spots[2], egui::pos2(rows[3].rect().min.x + 1.0, rows[3].rect().min.y), "the empty paragraph"); + } + #[test] fn depth_marks_wait_for_composition_after_editing() { fn marks(shape: &egui::epaint::Shape, tick: egui::Color32) -> usize { diff --git a/crates/ui-egui/src/updates_ui.rs b/crates/ui-egui/src/updates_ui.rs index 5414a4815..9064eeeb9 100644 --- a/crates/ui-egui/src/updates_ui.rs +++ b/crates/ui-egui/src/updates_ui.rs @@ -25,6 +25,13 @@ pub(crate) struct Runtime { /// The web build has no updater; its Help ▸ Check for Updates opens a window with a fixed message. #[cfg(target_arch = "wasm32")] pub(crate) manual_window_open: bool, + /// A copy whose updates another program installs (a Launcher Nightly): Help ▸ Check for Updates + /// says so, and the updater never runs or offers a build that would replace this channel. + #[cfg(not(target_arch = "wasm32"))] + managed: Option<&'static str>, + /// The managed-copy message window is open. + #[cfg(not(target_arch = "wasm32"))] + managed_window_open: bool, } impl Default for Runtime { @@ -40,6 +47,10 @@ impl Default for Runtime { repaint: None, #[cfg(target_arch = "wasm32")] manual_window_open: false, + #[cfg(not(target_arch = "wasm32"))] + managed: None, + #[cfg(not(target_arch = "wasm32"))] + managed_window_open: false, } } } @@ -50,11 +61,36 @@ impl DesignApp { pub fn set_startup_update_check(&mut self, on: bool) { self.updates_rt.startup_check = on; } + + /// This copy's updates are installed by `who` (the Launcher for a Nightly): no check, no offer, + /// and Help ▸ Check for Updates explains who updates it. + #[cfg(not(target_arch = "wasm32"))] + pub fn set_updates_managed(&mut self, who: Option<&'static str>) { + self.updates_rt.managed = who; + if who.is_some() { + self.updates_rt.startup_check = false; + self.updates_rt.check_requested = false; + } + } + + /// Whether another program installs this copy's updates. + #[cfg(not(target_arch = "wasm32"))] + pub fn updates_managed(&self) -> bool { + self.updates_rt.managed.is_some() + } } pub(crate) fn check(app: &mut DesignApp) -> Result { #[cfg(not(target_arch = "wasm32"))] { + if app.updates_rt.managed.is_some() { + // Explain the Launcher instead of offering a build that would replace this channel. + app.updates_rt.managed_window_open = true; + if let Some(ctx) = &app.updates_rt.repaint { + ctx.request_repaint(); + } + return Ok(Value::Null); + } app.updates_rt.check_requested = true; if let Some(ctx) = &app.updates_rt.repaint { ctx.request_repaint(); @@ -73,6 +109,10 @@ pub(crate) fn tick(app: &mut DesignApp, ctx: &egui::Context) { { let rt = &mut app.updates_rt; rt.repaint = Some(ctx.clone()); + if rt.managed.is_some() { + // Never tick a managed copy's updater: it would offer the stable channel's build. + return; + } if std::mem::take(&mut rt.check_requested) { rt.updater.check_now(ctx); } else if rt.startup_check { @@ -95,6 +135,32 @@ fn result_window_shows(status: &Status, prompt_open: bool) -> bool { pub(crate) fn show(app: &mut DesignApp, ctx: &egui::Context) { #[cfg(not(target_arch = "wasm32"))] { + if let Some(who) = app.updates_rt.managed + && app.updates_rt.managed_window_open + { + let mut open = true; + let title = crate::i18n::tr(&app.ui.language, "DesignCraft Updates"); + let ok_label = crate::i18n::tr(&app.ui.language, "OK"); + egui::Window::new(title) + .open(&mut open) + .collapsible(false) + .resizable(false) + .pivot(egui::Align2::CENTER_CENTER) + .default_pos(ctx.content_rect().center()) + .show(ctx, |ui| { + ui.label(format!("Updates are managed by {who}.")); + ui.add_space(8.0); + if ui.button(ok_label).clicked() { + app.updates_rt.managed_window_open = false; + } + }); + if !open { + app.updates_rt.managed_window_open = false; + } + } + if app.updates_rt.managed.is_some() { + return; + } // The updater asks to close only when no document has unsaved changes; the install starts when the app exits. let clean = !app.session.documents().iter().any(|d| d.is_dirty()); match app.updates_rt.updater.show_if(ctx, clean) { @@ -144,6 +210,22 @@ mod tests { use super::*; use designcraft_engine::Session; + #[test] + #[cfg(not(target_arch = "wasm32"))] + fn a_managed_copy_never_checks_and_explains_who_updates_it() { + let mut app = DesignApp::new(Session::new(), Default::default()); + app.set_startup_update_check(true); + app.set_updates_managed(Some("ArtCraft Launcher")); + assert!(app.updates_managed()); + check(&mut app).unwrap(); + assert!(app.updates_rt.managed_window_open, "Help ▸ Check for Updates explains the Launcher"); + assert!(!app.updates_rt.check_requested, "a managed copy must not ask the stable feed"); + tick(&mut app, &egui::Context::default()); + assert!(!app.updates_rt.startup_check, "a managed copy never checks at start"); + app.set_updates_managed(None); + assert!(!app.updates_managed()); + } + #[test] fn default_runtime_is_idle() { let rt = Runtime::default(); diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index 58ac91e89..c6f28ea56 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -188,6 +188,12 @@ impl<'a> NumField<'a> { self.show_or_clear(ui).flatten() } + /// The id of the text editor a [`NumField`] with id `id` shows in `ui`: request focus on it + /// to put the keyboard there (a dialog does so once for its first field when it opens). + pub fn editor_id(ui: &Ui, id: &str) -> egui::Id { + ui.scope_id().with(id).with("te") + } + /// The spinner segment's up and down buttons; the value a click on one gives. fn spinner_segment(&self, ui: &mut Ui, rect: Rect, key: egui::Id, enabled: bool, t: &Tokens) -> Option { let name = self.name.unwrap_or(self.id); diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 706c1fc43..94ec2cec9 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -44,7 +44,7 @@ so only enable it while you use it. Transport: `apps/designcraft/src/control_ser | `ui.ime` | `{preedit?, active?: [start, end], commit?}` | Input method events as the system IME sends them: marked text (shown in place, `active` is the clause being converted, in characters) and the committed text (typed as one `text.insert`) | | `ui.paste` | `{text}` or `{image}` | What Ctrl/Cmd+V delivers from the system clipboard: text into the text being edited, SVG markup (vector art copied in Illustrator, VectorCraft or Figma) as editable paths in the middle of the view, or an image (`image`: an image file as base64) as an embedded image in the selected empty frame or in the middle of the view (`edit.pasteImage`) | | `ui.move` / `ui.click` / `ui.drag` | screen points, `button?: left\|right\|middle`, `count?: 1–255` (click/drag, default 1), `steps?: positive integer` (drag, default 8) | Real egui pointer input — reaches every widget, menu and panel | -| `ui.set` | `{brightness?, panel?, rulers?, guides?, frameEdges?, baselineGrid?, documentGrid?, textThreads?, screenMode?, zoom?, page?, fit?}` | UI state | +| `ui.set` | `{brightness?, panel?, rulers?, guides?, frameEdges?, baselineGrid?, documentGrid?, textThreads?, linkBadge?, screenMode?, zoom?, page?, fit?}` | UI state | | `ui.dialog.open` | `{id, fields?}` | Open a dialog by id (e.g. `paragraphStyleOptions` or `characterStyleOptions` with `{name, section}`, or `{new: true}` for a new style) | | `ui.dialog.set` / `ui.dialog.confirm` / `ui.dialog.cancel` | `{field, value}` | Fill and confirm the open dialog | | `ui.resize`, `ui.focus` | | Window control | @@ -53,6 +53,12 @@ so only enable it while you use it. Transport: `apps/designcraft/src/control_ser | `app.open` / `app.save` / `app.export` | | Files | | `app.quit` | | Quit without asking about unsaved changes (the `app.quit` command, like ⌘Q, asks) | +For `story.setDirection`, `story.get`, `type.fillWithPlaceholder` and `file.exportText`, a `story` or `frame` +target must be an unsigned integer ID the document has: one it doesn't have is an error naming which, never a +quiet fall back to the selection. Both are checked when both are given, and `story` wins. A frame that holds no +text is refused, except by Fill with Placeholder Text, which converts it; a null or absent target uses the +selection. + Data merge runs through `engine.execute` like any command: `data.source.select`, `data.fields`, `data.placeholder.add` / `.remove`, `data.options`, `data.preview` / `data.preview.stop`, `data.merge`. `data.merge` creates and activates a new merged document; the template stays as it was ([agents.md](agents.md#data-merge)). diff --git a/docs/gaps.md b/docs/gaps.md index b08340458..4ec0503ae 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -185,7 +185,7 @@ Kind: **F** feature · **U** UI/UX · **T** typography · **FF** file format · Profile / Edit Original, File ▸ Open PDF / Document and Print Presets / User Settings, Type ▸ Size presets, Table ▸ Table Options / Cell Options submenus, Paste Before/After, Convert Columns, Object ▸ Interactive ▸ Convert to (form fields), - View ▸ Extras badges and Story Editor options (Show/Hide Depth Ruler and Show/Hide Style Name Column are there). Overriding a + View ▸ Extras badges and Story Editor options (Show/Hide Depth Ruler, Show/Hide Style Name Column and Show/Hide Paragraph Break Marks are there). Overriding a base parent's items on a parent spread itself (overrides work on document pages only); Save as Parent; new parents for an alternate layout (its pages keep their source pages' parents). - **Estimate:** 40–70 h (most are thin wrappers over existing engine features). diff --git a/docs/linked-artwork.md b/docs/linked-artwork.md index 045c4a7e5..873d704f8 100644 --- a/docs/linked-artwork.md +++ b/docs/linked-artwork.md @@ -14,7 +14,7 @@ A graphic placed from a file is linked to it. The document stores the link, a sm Video and audio link as well, but have no image proxy (the poster frame is used when there is one). An SVG that references other files resolves them relative to the SVG's own path. -Placing reads each file once and links the graphic to it at once, as InDesign does, with the file's size and modification time as its fingerprint. The bytes just read stay in memory for drawing, so nothing is read again. Placing returns without decoding or hashing the file, so placing many large images doesn't stop the app. A background thread then makes each graphic's content hash and proxy, in placement order. Until the hash is in, the link's status goes by size and time; a time from the last 2 seconds, or none, can't vouch for the bytes, and the hash decides once it is known. A save in that time makes the proxies still missing and writes the links without a hash. When such a document is opened, a file that matches by size and time is hashed in the background, so the next save has the hash. +Placing reads each file once and links the graphic to it at once. The bytes just read stay in memory for drawing. When the file has a usable size and modification time, Place leaves both hashing and proxy generation to the background. If the time is missing or too recent to identify the bytes (within 2 seconds), Place records a hash from the bytes it already read so an immediate Save can still find the unchanged original. The background job makes any deferred hashes and proxies in placement order. A save before that job finishes makes any missing proxies; links with a usable fingerprint may still be saved without a hash. When reopened, those links are checked by size and time and hashed in the background. Linked bytes are read when a render, export or check needs them. They are held in a shared cache of 512 MiB; a file larger than the cache is read for one use and not kept. A linked file larger than 1 GiB is not loaded. @@ -77,4 +77,4 @@ The status line reports once: "N images will be saved as links to their files (L ## Web builds -The web build cannot read files, so it embeds everything it places and cannot unembed. A document with linked assets opens with their proxies. Saving it on the web keeps the link records as version 5 and warns: "N linked files are saved as links only: the web version can't read them to embed them". +The web build cannot read files, so it embeds everything it places and cannot unembed. Links › Relink… and Relink to Folder… take files from the browser's file and folder pickers instead (`links.relinkFiles`): a missing graphic takes the file whose path ends most like its link, and the bytes become the document's copy. A document with linked assets opens with their proxies. Saving it on the web keeps the link records as version 5 and warns: "N linked files are saved as links only: the web version can't read them to embed them". diff --git a/docs/nightly-release-preparation.md b/docs/nightly-release-preparation.md new file mode 100644 index 000000000..93265b51d --- /dev/null +++ b/docs/nightly-release-preparation.md @@ -0,0 +1,104 @@ +# Windows, Linux and macOS release-ref nightly: supervised manual go-live + +**Enabled for supervised manual runs, not yet qualified.** The producer (`nightly.yml`, main) and the +signer (`nightly-sign.yml`, on the dedicated `nightly-signer` branch) keep only their exact context +guards and run when one of the reviewed manual actors dispatches them. There is no schedule and no +automatic dispatch transport yet. The installed policy +[`.github/nightly-signing-policy.json`](../.github/nightly-signing-policy.json) is the v3 policy for +DesignCraft. Its `producer_workflow_id` is `nightly.yml`'s registration on `main`: + +```bash +gh api repos/storytold/designcraft/actions/workflows/nightly.yml --jq .id +``` + +The callers pass no platform secrets. The unsigned reusable caller's maximum OIDC/attestation +permissions are for its isolated attester; its compiler narrows to contents and Actions read +only, with no OIDC, attestation write, release environment or platform signing secrets. +Shared tooling is pinned to `be00e5ccd18b68e950c8a08532f2230e7c3d0cba`, the craft-common-actions +main commit that merged [#371](https://github.com/storytold/craft-common-actions/pull/371) (the +candidate is admitted on the built commit's own Sonar analysis, not main's latest) after +[#370](https://github.com/storytold/craft-common-actions/pull/370) (the Windows and macOS nightly +registry rows for the 14 apps) and +[#369](https://github.com/storytold/craft-common-actions/pull/369) (shared helper checkouts kept out +of the app's clean-source check, and macOS on `macos-15`), following +[#364](https://github.com/storytold/craft-common-actions/pull/364) (the signer may run on the +policy's signer branch) and [#363](https://github.com/storytold/craft-common-actions/pull/363) (the +multi-app pipeline, which makes the signer's `app-name` input required and admits any reviewed +registry app), with #342 (`a4f6fd51`, policy v3 and the `platforms` input) and #339 (`605d5876`) +earlier. Both callers name it in `uses` and `tooling-revision`. A pin is reviewed source +availability, not provider, queue, native signing or crypto qualification. +Existing stable workflows are unchanged. + +**First runs.** The first runs are manual dispatches in this order: `nightly.yml` on main (only a +listed manual actor passes the producer's plan step), then `nightly-sign.yml` on `nightly-signer` +with that producer run ID and attempt, by a listed manual actor. + +**Signer branch.** The signer runs on `refs/heads/nightly-signer`, not on the stable `release` +branch, so nightly signer files never need a stable release sync. The policy's `release_branch` +names it and the signer's guard requires it; this app has no automatic dispatch transport, so +nothing else targets the branch. The branch only fast-forwards to reviewed main commits, through the +settings script's `advance` (no queued signer run, a trust-closure scan, then the full diff of +`.github/` and `packaging/`), and the existing `release` environment must admit `nightly-signer` +alongside `release` before the first dispatch (a repository settings change, not a workflow one). +Its trust closure is all of `.github/` and `packaging/`, including `packaging/env.sh`, which +`import-cert.sh` sources with the Apple keys. On that branch only the pinned `nightly-sign.yml` +caller may reach an environment: no app workflow binds one, and the only caller of the shared stable +`release.yml` is `release.yml`, whose callee must carry the stable-only environment guard. The +contract tests check the in-repo part on every main PR; the settings scan also resolves the callee. +Stable releases still come only from `refs/heads/release`. History does not carry over a switch +between `release` and `nightly-signer`, so the switch happens before the first publication. + +**Manual actors.** `bflatastic`, `dylanmtaylor`, `echelon`, `FredApps` and `skylartaylor`, in the +producer's `manual-actors` and the policy's `manual_actors`. The list mirrors the release-managers +team (id 19837241), leaving out `echelon-robot`; update it by PR in both places when the team changes. + +**Admission timing.** The candidate check reads the newest CI run on the candidate commit and +main's latest finished Sonar analysis, so pick a quiet main, wait for its CI and SonarCloud analysis +to finish green, then dispatch the producer and, once it succeeds, the signer, before another main +push lands a newer analysis. + +**Platform rows.** The producer caller lists +`platforms: '["windows-x86_64","linux-x86_64","macos-aarch64"]'` on its single job: one producer +run builds every listed platform for one all-or-nothing release (one failed or +skipped platform stops that night's release, Windows included), and the release-ref signer admits +platforms only from the protected policy, so there is no separate Linux or macOS caller job and +the signer caller has no platform input. + +## Installed policy values and their sources + +Read on 2026-11-24, with `producer_workflow_id` filled on 2026-11-25; re-read anything that may have +moved (including SonarCloud debt/conditions) before `nightly-signer` is advanced to it. + +| Field | Value | Source | +|---|---|---| +| `repository_id` | `1400018213` | `gh api repos/storytold/designcraft --jq .id` | +| `producer_workflow_id` | `429745945` | `gh api repos/storytold/designcraft/actions/workflows/nightly.yml --jq .id` on `main` | +| `producer_tooling_revision`, `signer_tooling_revision`, `producer_workflow_ref` | `be00e5cc…` (the exact-analysis admission, #371 after #370 and #369, following #364 on #363) | The callers' pin | +| `manual_actors` / `automatic_signer_actors` | the five release managers / `[]` | release-managers team (id 19837241) members who can push; equals the producer caller's `manual-actors` | +| `max_age_seconds`, `max_artifact_bytes` | `86400`, `2147483648` | Go-live checklist | +| `platforms` | three rows | Storytold stable signing identities (`windows-x86_64`, `linux-x86_64`, `macos-aarch64`) | +| `candidate_policy.required_workflows` | CI (`ci.yml`, workflow `380135818`), `gate / gate (ubuntu-24.04)` | Workflow list API and recent `main` push runs | +| `candidate_policy.sonar` | `storytold` / `storytold_designcraft`, app `12526` | `sonar-project.properties` | + +## Ownership and interface + +- `.github/workflows/nightly.yml`: default-main registration of the unsigned producer, named + `DesignCraft unsigned nightly`, enabled for manual dispatch by `manual-actors`; no signing secrets + may be passed or inherited. +- `.github/workflows/nightly-sign.yml`: top-level signer registration, enabled for manual dispatch on + `nightly-signer`, which carries a reviewed main commit. It rejects wrong repository/event/actual branch, + including same-name tags. Its constant whole-run concurrency (`designcraft-nightly-release`, + `cancel-in-progress: false`) is distinct from stable. The caller itself passes no + credentials; only the shared callee's sign jobs bind the `release` environment. +- Shared reusable entrypoints are `nightly-unsigned.yml` and `nightly-release.yml` in + `storytold/craft-common-actions`. Both must resolve to a **real reviewed public immutable + commit**; the defining workflow SHA and tooling input must match. + +## Local regression checks + +`python3 packaging/nightly-release-tests.py` verifies the DesignCraft nightly callers and policy +contract locally: exact context guards, manual-actor parity, no registered schedule, no-cache and +no-platform-secret boundaries, signer root concurrency serialization, shared tooling pin parity, +and v3 policy structure/identities. It also checks that the signer runs on `nightly-signer` with the +policy's `release_branch` and the caller's `app-name`, and that the trust closure has no other route to +an environment. diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 2716c6e1d..0fdda0d72 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -315,7 +315,7 @@ Open P0 items: Vector/page formats (PDF/AI/SVG/EPS place), Export to PDF (print) | View & navigation | Screen modes | P0 | D | | View & navigation | Overprint preview | P1 | D | | View & navigation | Rulers, guides, grids toggles | P0 | D | -| View & navigation | Show/hide frame edges, threads, hidden chars | P0 | D | +| View & navigation | Show/hide frame edges, threads, link badge, hidden chars | P0 | D | | View & navigation | Structure / tag markers | P2 | D | | View & navigation | Display performance | P0 | D | | View & navigation | Navigate pages | P0 | D | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 9440d64ef..8ae70edae 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -218,7 +218,7 @@ table is the one summed. | Interactivity & digital | 100% | 40% | 30–50 | HTML export basic (#314); fixed-layout EPUB is page images; no animation, timing, media playback | | Output & production | 92% | 55% | 40–70 | PDF/X-4 only (no X-1a/X-3), with visible unembedded font detection (below); no PDF/print presets or `.joboptions`, print via craft-print (CUPS/Windows), no trapping; Output Preview panel | | XML & automation | 100% | 35% | (ecosystem dimension) | no ExtendScript/UXP; XML structure depth | -| View & navigation | 100% | 65% | 10–20 | Navigator, display badges, Show/Hide extras (content grabber, live corners) | +| View & navigation | 100% | 65% | 10–20 | Navigator, display badges other than the link badge, Show/Hide extras (content grabber, live corners) | | Undo, history, saving | 100% | 70% | 5–10 | Undo/Redo name the action | | Accessibility | 100% | 50% | 15–25 | tagged PDF exists; PDF/UA validation, reading order depth, screen-reader support in the UI | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index f5e8c7db0..13ec71eca 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,12 @@ # UI and interaction parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-02 · **Change:** patch (the Pen previews the curve while a smooth point is dragged and curves the rubber band after one, #1438; a Custom text variable defined with a number shows its digits, #2093; Table of Contents dialog: title field keeps its width, More Options toggles without losing hidden settings; Story panel; text Control panel Character/Paragraph modes; Properties ••• expands Character and Paragraph; live corners work; document views row: scrollbars, Alt pans while editing text; Tabs panel listed as present (#343); spring-loaded Zoom navigation; paragraph style override feedback and clearing) · **Target:** Adobe InDesign 2026 (21.6, Medium Dark, macOS) +- **2026-11-18 · UI1994:** Show Hidden Characters no longer paints marks for hidden text + frames, hidden layers or children of hidden groups. Visible locked layers retain their marks. + Visibility checks and painting share the resolved frame location and item. + Canvas-painter regressions check emitted marks and hide/show transitions, including table + cells, parent editing and culled spreads (#1994). + +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-19 · **Change:** patch (hidden characters follow frame, group and layer visibility (#1994); link badge on placed files; the Pen previews the curve while a smooth point is dragged and curves the rubber band after one, #1438; a Custom text variable defined with a number shows its digits, #2093; Table of Contents dialog: title field keeps its width, More Options toggles without losing hidden settings; Story panel; text Control panel Character/Paragraph modes; Properties ••• expands Character and Paragraph; live corners work; document views row: scrollbars, Alt pans while editing text; Tabs panel listed as present (#343); spring-loaded Zoom navigation; paragraph style override feedback and clearing) · **Target:** Adobe InDesign 2026 (21.6, Medium Dark, macOS) Tools, handles, snapping, nudging, modifiers, shortcuts, panels, menus, context menus and feel, against InDesign 2026. The look was measured from the running app @@ -32,6 +38,7 @@ basics of editing fail for too many users on Windows and Linux. | Direct Selection, Pen family, Pencil, Scissors | ✓ | ✓ | ~ | the Pen previews the segment while a smooth point is dragged out and curves the rubber band out of a smooth point's direction line (`pen_previews_the_curve_while_dragging_and_after_a_smooth_point`, #1438); moving reference point "0" fails (#337) | | Live corners (yellow handle) | ✓ | ✓ widget on a selected rectangle frame; diamonds drag the corner size (Shift: one corner), Alt-click steps the shape (Shift+Alt: all) | ✓ | #186 | | Content grabber, frame fitting by double-click | ✓ | ✓ | ✓ | | +| Link badge (View › Extras): a chain on each picture placed from a file; modified and missing links marked | ✓ | ✓ chain on the frame's top edge in its layer colour, a yellow warning when the file changed, a red stop when it is missing; hidden in Preview | ✓ | Learn Skills Daily course, chapter 10 | | Overset mark (red + at the out port) | selected frame only | every overset frame, groups included, while frame edges show | ✓ | a deliberate step past InDesign: grouped labels that overflow were invisible until Preflight | | Smart guides, snapping to guides/grid/baseline | ✓ | ✓ (2,049-line `snap.rs`) | ~ | vertical smart spacing between two rectangles (#188) | | Nudging with arrows, Shift ×10 | ✓ | ✓ | ✓ | | @@ -50,7 +57,7 @@ basics of editing fail for too many users on Windows and Linux. | Panels: Pages, Layers, Swatches, Color, Stroke, Character, Paragraph, Styles, Links, Effects, Text Wrap, Align, Pathfinder, Table, Index, TOC, Hyperlinks, Bookmarks, Articles, Tags, Notes, Track Changes, Object States, Buttons and Forms, Preflight, Data Merge, Library, Scripts, Glyphs, Info, Tabs, Story | ✓ | all present | ~ | Navigator, Trap Presets, Animation, Timing missing; pull-down panels can't scroll on Linux (#267) | | Dialogs: New Document, Document Setup, Preferences (all pages), Paragraph/Character/Object/Table/Cell Style Options, Export PDF, Print, Package, Find/Change | ✓ | present | ~ | a Custom text variable whose text is typed as a number shows its digits (`variables.define` takes a string, a number or a boolean for `text` and refuses anything else; #2093); generated command dialogs fill the long tail; depth varies | | Workspaces | Essentials, Essentials Classic, Advanced, Book, Digital Publishing, Interactive for PDF, Printing and Proofing, Review, Typography, Touch | ✓ named workspaces (Essentials Classic: Control panel and iconic panel groups) + custom; Window › Workspace; no Review or Touch | ~ | tab bar overlaps menus in Book/Advanced (#182) | -| Story Editor | ✓ | ✓ | ~ | depth ruler and View › Story Editor › Show/Hide Depth Ruler (`story_editor.rs` `depth_ruler_shows_and_hides_from_the_view_menu`); Show/Hide Style Name Column and dragging the column's width (`style_name_column_shows_and_hides_from_the_view_menu`, `dragging_the_style_column_bar_resizes_the_column`); Expand/Collapse All Footnotes and Show/Hide Paragraph Break Marks missing | +| Story Editor | ✓ | ✓ | ~ | depth ruler and View › Story Editor › Show/Hide Depth Ruler (`story_editor.rs` `depth_ruler_shows_and_hides_from_the_view_menu`); Show/Hide Style Name Column and dragging the column's width (`style_name_column_shows_and_hides_from_the_view_menu`, `dragging_the_style_column_bar_resizes_the_column`); Show/Hide Paragraph Break Marks (`paragraph_break_marks_show_and_hide_from_the_view_menu`); Expand/Collapse All Footnotes missing | | Undo granularity (a drag = one step) | ✓ | ✓ (Begin/Preview/Commit) | ✓ | | | Closing with unsaved changes asks | ✓ | ✓ File › Close and window/menu quit (#146, #545) | ✓ | macOS Dock Quit still bypasses the prompt (#544) | | UI scaling, System appearance | ✓ | scaling ✓ (#281); follows macOS light/dark ✗ (#237) | ~ | | diff --git a/packaging/linux/flatpak-bundle.sh b/packaging/linux/flatpak-bundle.sh index 40301a1fb..3a3f97a7c 100755 --- a/packaging/linux/flatpak-bundle.sh +++ b/packaging/linux/flatpak-bundle.sh @@ -17,6 +17,12 @@ set -euo pipefail . "$(dirname "${BASH_SOURCE[0]}")/../env.sh" HERE="$ROOT/packaging/linux" APP_ID=ai.storyteller.designcraft +FLATPAK_ID="$APP_ID" +# The remote indexes both app IDs on the stable ref branch; IDs isolate installations. +FLATPAK_BRANCH=stable +if [[ "${DESIGNCRAFT_BUILD_CHANNEL:-}" == nightly-v1 || "$VERSION" == *-nightly* ]]; then + FLATPAK_ID="$APP_ID.nightly" +fi FLATHUB=https://dl.flathub.org/repo/flathub.flatpakrepo TEST=1 @@ -52,29 +58,78 @@ rm -rf "$WORK" mkdir -p "$WORK/stage" tar -xzf "$TARBALL" -C "$WORK/stage" --strip-components=1 [[ -x "$WORK/stage/bin/designcraft" ]] || { echo "error: $TARBALL has no bin/designcraft" >&2; exit 1; } -cp "$HERE/flatpak/$APP_ID.bundle.yml" "$WORK/$APP_ID.yml" +if [[ "$FLATPAK_ID" != "$APP_ID" ]]; then + mv "$WORK/stage/bin/designcraft" "$WORK/stage/bin/designcraft-bin" + cat >"$WORK/stage/bin/designcraft" <<'WRAPPER' +#!/bin/sh +# Start the compiled nightly-v1 flavor inside the sandbox. The profile is the Launcher's protocol +# and stays in this bundle's own per-app home (ai.storyteller.designcraft.nightly), never the +# stable bundle's folder; the app refuses a DESIGNCRAFT_CONFIG_DIR override. +set -eu +real_bin=/app/libexec/designcraft +if [ "${1:-}" = "--launch-profile" ] || [ "${1:-}" = "--profile-root" ]; then + # The Launcher already supplied the protocol: pass its command line through untouched. + exec "$real_bin" "$@" +fi +if [ "${1:-}" = "--version" ] || [ "${1:-}" = "-V" ]; then + exec "$real_bin" "$@" +fi +profile_root="${XDG_DATA_HOME:-${HOME:?HOME is required}/.local/share}/designcraft-nightly" +if [ "${1:-}" = "--" ]; then + # The caller's own separator stays the only one. + exec "$real_bin" --launch-profile nightly-v1 --profile-root "$profile_root" "$@" +fi +exec "$real_bin" --launch-profile nightly-v1 --profile-root "$profile_root" -- "$@" +WRAPPER + chmod 755 "$WORK/stage/bin/designcraft" + sed -e "s|^Icon=$APP_ID$|Icon=$FLATPAK_ID|" \ + -e "s|^Name=DesignCraft$|Name=DesignCraft Nightly|" \ + -e 's|^StartupWMClass=.*|StartupWMClass=ai.storyteller.designcraft.nightly-v1|' \ + -e '/^MimeType=/d' \ + "$WORK/stage/share/applications/$APP_ID.desktop" >"$WORK/stage/share/applications/$FLATPAK_ID.desktop" + rm -f "$WORK/stage/share/applications/$APP_ID.desktop" + sed -e "s|$APP_ID|$FLATPAK_ID|g" \ + -e "s|DesignCraft|DesignCraft Nightly|g" \ + -e "s|$APP_ID.desktop|$FLATPAK_ID.desktop|g" \ + -e "s|$APP_ID|$FLATPAK_ID|g" \ + "$WORK/stage/share/metainfo/$APP_ID.metainfo.xml" >"$WORK/stage/share/metainfo/$FLATPAK_ID.metainfo.xml" + rm -f "$WORK/stage/share/metainfo/$APP_ID.metainfo.xml" + mv "$WORK/stage/share/mime/packages/$APP_ID.xml" "$WORK/stage/share/mime/packages/$FLATPAK_ID.xml" + NIGHTLY_ICON="$ROOT/assets/app-icon/designcraft-nightly.png" + if [[ ! -f "$NIGHTLY_ICON" ]]; then + NIGHTLY_ICON="$ROOT/assets/app-icon/hicolor/256x256/apps/$APP_ID.png" + fi + rm -rf "$WORK/stage/share/icons/hicolor" + install -Dm644 "$NIGHTLY_ICON" \ + "$WORK/stage/share/icons/hicolor/256x256/apps/$FLATPAK_ID.png" + sed -e "s|ai\.storyteller\.designcraft|$FLATPAK_ID|g" \ + -e 's|- install -Dm755 bin/designcraft /app/bin/designcraft|- install -Dm755 bin/designcraft-bin /app/libexec/designcraft\n - install -Dm755 bin/designcraft /app/bin/designcraft|' \ + "$HERE/flatpak/$APP_ID.bundle.yml" >"$WORK/$FLATPAK_ID.yml" +else + cp "$HERE/flatpak/$APP_ID.bundle.yml" "$WORK/$FLATPAK_ID.yml" +fi flatpak remote-add --user --if-not-exists flathub "$FLATHUB" # --disable-rofiles-fuse: no FUSE in containers and CI runners. flatpak-builder --user --install-deps-from=flathub --disable-rofiles-fuse --force-clean \ - --default-branch=stable --repo="$WORK/repo" --state-dir="$WORK/state" "$WORK/build" "$WORK/$APP_ID.yml" + --default-branch="$FLATPAK_BRANCH" --repo="$WORK/repo" --state-dir="$WORK/state" "$WORK/build" "$WORK/$FLATPAK_ID.yml" OUT="$DIST/$BASENAME.flatpak" # --runtime-repo lets `flatpak install` fetch the freedesktop runtime from Flathub if missing. -flatpak build-bundle --runtime-repo="$FLATHUB" "$WORK/repo" "$OUT" "$APP_ID" stable +flatpak build-bundle --runtime-repo="$FLATHUB" "$WORK/repo" "$OUT" "$FLATPAK_ID" "$FLATPAK_BRANCH" echo "wrote $OUT" if [[ "$OCI" = 1 ]]; then OUT_OCI="$DIST/$BASENAME-oci" rm -rf "$OUT_OCI" - flatpak build-bundle --oci "$WORK/repo" "$OUT_OCI" "$APP_ID" stable + flatpak build-bundle --oci "$WORK/repo" "$OUT_OCI" "$FLATPAK_ID" "$FLATPAK_BRANCH" echo "wrote OCI layout to $OUT_OCI" fi if [[ "$TEST" = 1 ]]; then flatpak install --user -y --noninteractive --reinstall "$OUT" - flatpak info --user "$APP_ID" - flatpak run --command=designcraft-cli "$APP_ID" --version - flatpak run --command=sh "$APP_ID" -c 'ls /app/share/applications /app/share/metainfo /app/share/mime/packages /app/share/icons/hicolor/scalable/apps' + flatpak info --user "$FLATPAK_ID" + flatpak run --command=designcraft-cli "$FLATPAK_ID" --version + flatpak run --command=sh "$FLATPAK_ID" -c 'ls /app/share/applications /app/share/metainfo /app/share/mime/packages /app/share/icons/hicolor/*/apps' fi echo "==> done" ls -lh "$OUT" diff --git a/packaging/linux/nfpm.yaml b/packaging/linux/nfpm.yaml index d7d88a24c..ac4638de3 100644 --- a/packaging/linux/nfpm.yaml +++ b/packaging/linux/nfpm.yaml @@ -3,7 +3,7 @@ # exports VERSION and NFPM_ARCH. The Arch package is built by the release workflow's makepkg job. # # nfpm package -f packaging/linux/nfpm.yaml -p deb -t dist/release/ -name: designcraft +name: ${NFPM_NAME} arch: ${NFPM_ARCH} platform: linux version: ${VERSION} @@ -65,12 +65,15 @@ overrides: - xdg-desktop-portal contents: - - src: ${STAGE}/usr/bin/designcraft - dst: /usr/bin/designcraft + - src: ${STAGE}/usr/bin/${NFPM_BIN} + dst: /usr/bin/${NFPM_BIN} file_info: { mode: 0755 } - - src: ${STAGE}/usr/bin/designcraft-cli - dst: /usr/bin/designcraft-cli + - src: ${STAGE}/usr/bin/${NFPM_CLI} + dst: /usr/bin/${NFPM_CLI} file_info: { mode: 0755 } + - src: ${STAGE}/usr/lib/ + dst: /usr/lib/ + type: tree - src: ${STAGE}/usr/share/ dst: /usr/share/ type: tree diff --git a/packaging/linux/nightly-arch-launch.sh b/packaging/linux/nightly-arch-launch.sh new file mode 100755 index 000000000..3b43fc676 --- /dev/null +++ b/packaging/linux/nightly-arch-launch.sh @@ -0,0 +1,20 @@ +#!/bin/sh +# Start the compiled nightly-v1 flavor from the Arch package. The profile is the Launcher's +# protocol (the app refuses a DESIGNCRAFT_CONFIG_DIR override), so this launcher passes the same +# pair the Launcher will. +set -eu +here="$(CDPATH='' cd -- "$(dirname -- "$0")" && pwd)" +real_bin="$here/.designcraft-nightly/designcraft" +if [ "${1:-}" = "--launch-profile" ] || [ "${1:-}" = "--profile-root" ]; then + # The Launcher already supplied the protocol: pass its command line through untouched. + exec "$real_bin" "$@" +fi +if [ "${1:-}" = "--version" ] || [ "${1:-}" = "-V" ]; then + exec "$real_bin" "$@" +fi +profile_root="${XDG_DATA_HOME:-${HOME:?HOME is required}/.local/share}/designcraft-nightly" +if [ "${1:-}" = "--" ]; then + # The caller's own separator stays the only one. + exec "$real_bin" --launch-profile nightly-v1 --profile-root "$profile_root" "$@" +fi +exec "$real_bin" --launch-profile nightly-v1 --profile-root "$profile_root" -- "$@" diff --git a/packaging/linux/nightly-arch-tar-test.sh b/packaging/linux/nightly-arch-tar-test.sh new file mode 100755 index 000000000..3c9f98106 --- /dev/null +++ b/packaging/linux/nightly-arch-tar-test.sh @@ -0,0 +1,71 @@ +#!/usr/bin/env bash +# Validate the staged Arch launcher without building or opening DesignCraft. +set -euo pipefail + +HERE="$(cd "$(dirname "$0")" && pwd)" +work="$(mktemp -d)" +trap 'rm -rf "$work"' EXIT +stage="$work/source" +dst="$work/dist" +base=designcraft-0.0.1-nightly.1-linux-x86_64 +mkdir -p "$stage/bin" "$dst" "$work/extract" + +# A local argv recorder stands in for the compiled binary. It never opens a UI. +cat >"$stage/bin/designcraft" <<'RECORDER' +#!/bin/sh +printf 'DESIGNCRAFT_CONFIG_DIR=<%s>\n' "${DESIGNCRAFT_CONFIG_DIR-UNSET}" +for arg in "$@"; do + printf '<%s>\n' "$arg" +done +RECORDER +chmod 755 "$stage/bin/designcraft" +cp "$stage/bin/designcraft" "$stage/bin/designcraft-cli" + +bash "$HERE/nightly-arch-tar.sh" "$stage" "$work/stage" "$dst" "$base" +tar -xzf "$dst/$base.tar.gz" -C "$work/extract" +bin="$work/extract/$base/bin" +# Simulate the existing Arch bin-tree copy and public launcher rename. +mkdir -p "$work/installed" +cp -R "$bin" "$work/installed/bin" +bin="$work/installed/bin" +mv "$bin/designcraft" "$bin/designcraft-nightly" +mv "$bin/designcraft-cli" "$bin/designcraft-nightly-cli" + +[[ ! -e "$stage/bin/.designcraft-nightly" ]] +cmp "$stage/bin/designcraft" "$bin/.designcraft-nightly/designcraft" +cmp "$stage/bin/designcraft-cli" "$bin/designcraft-nightly-cli" +export HOME="$work/home with space" +unset XDG_DATA_HOME DESIGNCRAFT_CONFIG_DIR +expect() { + expected="$1" + shift + actual=$(PATH="$bin:$PATH" designcraft-nightly "$@") + if [[ "$actual" != "$expected" ]]; then + printf 'expected:\n%s\nactual:\n%s\n' "$expected" "$actual" >&2 + exit 1 + fi +} +# The nightly profile is the Launcher's selector/root pair, never an environment override. +pair() { + printf 'DESIGNCRAFT_CONFIG_DIR=\n<--launch-profile>\n\n<--profile-root>\n<%s>\n<-->\n%s' "$1" "$2" +} +expect "$(pair "$HOME/.local/share/designcraft-nightly" '')" +export XDG_DATA_HOME="$work/xdg with space" +expect "$(pair "$XDG_DATA_HOME/designcraft-nightly" "$(printf '<%s>\n<%s>\n' 'doc with spaces.dc' '--other-name.dc')")" \ + 'doc with spaces.dc' '--other-name.dc' +# Version queries stay plain so a Launcher or a runner can ask before any profile exists. +expect "$(printf 'DESIGNCRAFT_CONFIG_DIR=\n<--version>\n')" --version +expect "$(printf 'DESIGNCRAFT_CONFIG_DIR=\n<-V>\n')" -V +# A caller that already uses the protocol (the Launcher) reaches the binary untouched. +expect "$(printf 'DESIGNCRAFT_CONFIG_DIR=\n<--launch-profile>\n\n<--profile-root>\n<%s>\n<-->\n<%s>\n' \ + "$work/launcher root" 'doc.dc')" \ + --launch-profile nightly-v1 --profile-root "$work/launcher root" -- doc.dc +# A caller's own separator stays the only one, and a flag after it is a document. +expect "$(pair "$XDG_DATA_HOME/designcraft-nightly" "$(printf '<%s>\n' '--version')")" -- --version +# The launcher never sets or clears the stable override itself: it passes the profile pair and +# leaves an inherited value alone, which the app then refuses with its own message. +DESIGNCRAFT_CONFIG_DIR="$work/explicit with space" expect \ + "$(printf 'DESIGNCRAFT_CONFIG_DIR=<%s>\n<--launch-profile>\n\n<--profile-root>\n<%s>\n<-->\n<%s>\n' \ + "$work/explicit with space" "$XDG_DATA_HOME/designcraft-nightly" 'sample.dc')" sample.dc + +echo "PASS: Arch Nightly handoff starts the flavor with the Launcher's profile and arguments" diff --git a/packaging/linux/nightly-arch-tar.sh b/packaging/linux/nightly-arch-tar.sh new file mode 100755 index 000000000..8bbe9f581 --- /dev/null +++ b/packaging/linux/nightly-arch-tar.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Stage the DesignCraft Nightly-only handoff for the Arch packager. +set -euo pipefail + +here="$(cd "$(dirname "$0")" && pwd)" +source_tree="$1" +work="$2" +destination="$3" +basename="$4" +stage="$work/$basename" + +mkdir -p "$work" +cp -R "$source_tree" "$stage" +mkdir "$stage/bin/.designcraft-nightly" +mv "$stage/bin/designcraft" "$stage/bin/.designcraft-nightly/designcraft" +cp "$here/nightly-arch-launch.sh" "$stage/bin/designcraft" +chmod 755 "$stage/bin/designcraft" +tar -C "$work" -czf "$destination/$basename.tar.gz" "$basename" +echo "wrote $destination/$basename.tar.gz" diff --git a/packaging/linux/nightly-launch.sh b/packaging/linux/nightly-launch.sh new file mode 100644 index 000000000..41f2ec712 --- /dev/null +++ b/packaging/linux/nightly-launch.sh @@ -0,0 +1,16 @@ +#!/bin/sh +# Nightly launcher generated by craft-common-actions scripts/nightly-launcher.sh.in. Do not edit: +# the shared nightly producer accepts this file only byte for byte as rendered for the app. +set -eu +dir=$(CDPATH='' cd -- "$(dirname -- "$0")" && pwd -P) +readonly dir +target="$dir/designcraft-bin" +readonly target +profile_root="${XDG_DATA_HOME:-$HOME/.local/share}/ai.storyteller.designcraft.nightly" +readonly profile_root +case "${1-}" in + # The ArtCraft Launcher passes its own profile and per-install root; the app validates the pair. + --launch-profile) exec "$target" "$@" ;; + --version | -V) exec "$target" --launch-profile nightly-v1 --profile-root "$profile_root" --version ;; +esac +exec "$target" --launch-profile nightly-v1 --profile-root "$profile_root" -- "$@" diff --git a/packaging/linux/nightly.sh b/packaging/linux/nightly.sh new file mode 100755 index 000000000..26a5d3b46 --- /dev/null +++ b/packaging/linux/nightly.sh @@ -0,0 +1,34 @@ +#!/usr/bin/env bash +# App-owned GUI-only nightly tar: no FUSE/AppImage, CLI, association or install hooks. +set -euo pipefail +ARCH= +while [[ $# -gt 0 ]]; do + case "$1" in + --arch) [[ $# -ge 2 ]] || { echo 'missing --arch value' >&2; exit 2; }; ARCH="$2"; shift 2 ;; + -h|--help) echo 'Usage: nightly.sh --arch x86_64'; exit 0 ;; + *) echo "unsupported nightly argument: $1" >&2; exit 2 ;; + esac +done +[[ "$ARCH" == x86_64 && "$(uname -s)" == Linux ]] || { echo 'only native Linux x86_64 nightly packaging is supported' >&2; exit 2; } +. "$(dirname "${BASH_SOURCE[0]}")/../nightly-common.sh" +nightly_init linux "$ARCH" x86_64-unknown-linux-gnu +OUTPUT="$DIST/designcraft-$VERSION-linux-x86_64-nightly.tar.gz" +[[ ! -e "$OUTPUT" && ! -L "$OUTPUT" ]] || nightly_die 'refusing to replace an existing nightly archive' +nightly_build_gui +STAGE="$NIGHTLY_WORK/stage" +mkdir -p "$STAGE" +cp "$NIGHTLY_GUI" "$STAGE/designcraft-bin" +chmod 755 "$STAGE/designcraft-bin" +# An unpacked nightly starts through the canonical shared launcher template +# (packaging/linux/nightly-launch.sh, rendered from craft-common-actions's +# scripts/nightly-launcher.sh.in): `designcraft` starts `designcraft-bin` beside it on the +# nightly-v1 profile under the Nightly package identity. +install -m755 "$ROOT/packaging/linux/nightly-launch.sh" "$STAGE/designcraft" +cp "$ROOT/assets/app-icon/designcraft-nightly.png" "$STAGE/designcraft-nightly.png" +nightly_copy_notices "$STAGE" +# The staged launcher must reach the built flavor, not just the binary it names. +packed_version="$("$STAGE/designcraft" --version)" || nightly_die 'the archive launcher could not start the built binary' +[[ "$packed_version" == "DesignCraft $VERSION (nightly-v1)" ]] || nightly_die 'the archive launcher is not the prepared nightly identity' +# The private mktemp cwd is the helper authority root, not a CLI path parent. +(cd "$NIGHTLY_WORK" && python3 "$ROOT/packaging/nightly-archive.py" linux stage archive.tar.gz) +nightly_publish_archive "$NIGHTLY_WORK/archive.tar.gz" "$OUTPUT" diff --git a/packaging/linux/package.sh b/packaging/linux/package.sh index f6c3e9cc0..a83488e15 100755 --- a/packaging/linux/package.sh +++ b/packaging/linux/package.sh @@ -13,7 +13,7 @@ # it) and declares provides/conflicts against the AUR packages. Building a second one here under # the same asset name is what made the published package depend on upload order. # -# Usage: packaging/linux/package.sh [--skip-build] [--formats "appimage deb rpm tar"] +# Usage: packaging/linux/package.sh [--skip-build] [--formats "appimage deb rpm tar"] [--arch-tar-dir DIRECTORY] # # Needs: cargo; nfpm for deb/rpm (https://nfpm.goreleaser.com); appimagetool for the AppImage # (downloaded into $CARGO_TARGET_DIR if missing). Build on an old distro (CI: Ubuntu 22.04, @@ -27,10 +27,16 @@ APP_ID=ai.storyteller.designcraft SKIP_BUILD=0 FORMATS="appimage deb rpm tar" +ARCH_TAR_DIR= while [[ $# -gt 0 ]]; do case "$1" in --skip-build) SKIP_BUILD=1; shift ;; --formats) FORMATS="$2"; shift 2 ;; + --arch-tar-dir) + [[ -n "${2:-}" ]] || { echo "error: --arch-tar-dir needs a directory" >&2; exit 2; } + ARCH_TAR_DIR="$2" + shift 2 + ;; -h | --help) sed -n '2,16p' "$0"; exit 0 ;; *) echo "unknown argument: $1" >&2; exit 2 ;; esac @@ -44,9 +50,20 @@ case "$ARCH" in *) echo "unsupported architecture $ARCH" >&2; exit 2 ;; esac export DESIGNCRAFT_MAINTAINER="${DESIGNCRAFT_MAINTAINER:-DesignCraft maintainers }" +IS_NIGHTLY=0 +if [[ "${DESIGNCRAFT_BUILD_CHANNEL:-}" == nightly-v1 || "$VERSION" == *-nightly* ]]; then + IS_NIGHTLY=1 + export DESIGNCRAFT_BUILD_CHANNEL=nightly-v1 + export DESIGNCRAFT_OVERRIDE_VERSION="$VERSION" +fi BASENAME="designcraft-$VERSION-linux-$ARCH" -echo "==> DesignCraft $VERSION for Linux $ARCH ($FORMATS)" +if [[ -n "$ARCH_TAR_DIR" && "$IS_NIGHTLY" != 1 ]]; then + echo "error: --arch-tar-dir is only for Nightly builds" >&2 + exit 2 +fi + +echo "==> DesignCraft $VERSION for Linux $ARCH ($FORMATS, channel=${DESIGNCRAFT_BUILD_CHANNEL:-stable})" has() { local fmt="$1" @@ -75,6 +92,11 @@ install -Dm755 "$BIN/designcraft" "$STAGE/usr/bin/designcraft" install -Dm755 "$BIN/designcraft-cli" "$STAGE/usr/bin/designcraft-cli" "${CROSS_COMPILE:-}strip" "$STAGE/usr/bin/designcraft" "$STAGE/usr/bin/designcraft-cli" 2>/dev/null || true install -Dm644 "$HERE/$APP_ID.desktop" "$STAGE/usr/share/applications/$APP_ID.desktop" +if [[ "$IS_NIGHTLY" = 1 ]]; then + sed -e 's|^StartupWMClass=.*|StartupWMClass=ai.storyteller.designcraft.nightly-v1|' \ + "$STAGE/usr/share/applications/$APP_ID.desktop" >"$STAGE/usr/share/applications/$APP_ID.desktop.tmp" + mv "$STAGE/usr/share/applications/$APP_ID.desktop.tmp" "$STAGE/usr/share/applications/$APP_ID.desktop" +fi install -Dm644 "$HERE/$APP_ID.mime.xml" "$STAGE/usr/share/mime/packages/$APP_ID.xml" install -Dm644 "$HERE/$APP_ID.thumbnailer" "$STAGE/usr/share/thumbnailers/$APP_ID.thumbnailer" mkdir -p "$STAGE/usr/share/metainfo" @@ -100,13 +122,88 @@ if has tar; then echo "wrote $DIST/$BASENAME.tar.gz" fi +# The Arch handoff keeps the same basename as the plain tarball in a separate directory. +# Flatpak, OCI and direct tar consumers still get the original binary, not this launcher. +if [[ -n "$ARCH_TAR_DIR" ]]; then + mkdir -p "$ARCH_TAR_DIR" + if [[ "$(cd "$ARCH_TAR_DIR" && pwd -P)" == "$(cd "$DIST" && pwd -P)" ]]; then + echo "error: the Arch tar directory must differ from the release directory" >&2 + exit 2 + fi + bash "$HERE/nightly-arch-tar.sh" "$STAGE/usr" "$WORK/arch-tar" "$ARCH_TAR_DIR" "$BASENAME" +fi + # ---- .deb / .rpm -------------------------------------------------------------------------------- if has deb || has rpm; then command -v nfpm >/dev/null || { echo "error: nfpm not found (https://nfpm.goreleaser.com/install/)" >&2; exit 1; } export VERSION export NFPM_ARCH="$DEB_ARCH" + NFPM_STAGE="$STAGE" + export NFPM_NAME="designcraft" + export NFPM_BIN="designcraft" + export NFPM_CLI="designcraft-cli" + if [[ "$IS_NIGHTLY" = 1 ]]; then + NIGHTLY_DESK_ID="$APP_ID.nightly-v1" + export NFPM_NAME="designcraft-nightly" + export NFPM_BIN="designcraft-nightly" + export NFPM_CLI="designcraft-nightly-cli" + NFPM_STAGE="$WORK/nfpm-root" + rm -rf "$NFPM_STAGE" + cp -R "$STAGE" "$NFPM_STAGE" + install -Dm755 "$NFPM_STAGE/usr/bin/designcraft" "$NFPM_STAGE/usr/lib/designcraft-nightly/designcraft" + cat >"$NFPM_STAGE/usr/bin/$NFPM_BIN" <<'WRAPPER' +#!/bin/sh +# Start the compiled nightly-v1 flavor. Its profile is the Launcher's protocol (the app refuses a +# DESIGNCRAFT_CONFIG_DIR override), so this wrapper passes the same pair the Launcher will. +set -eu +real_bin=/usr/lib/designcraft-nightly/designcraft +if [ "${1:-}" = "--launch-profile" ] || [ "${1:-}" = "--profile-root" ]; then + # The Launcher already supplied the protocol: pass its command line through untouched. + exec "$real_bin" "$@" +fi +if [ "${1:-}" = "--version" ] || [ "${1:-}" = "-V" ]; then + exec "$real_bin" "$@" +fi +profile_root="${XDG_DATA_HOME:-${HOME:?HOME is required}/.local/share}/designcraft-nightly" +if [ "${1:-}" = "--" ]; then + # The caller's own separator stays the only one. + exec "$real_bin" --launch-profile nightly-v1 --profile-root "$profile_root" "$@" +fi +exec "$real_bin" --launch-profile nightly-v1 --profile-root "$profile_root" -- "$@" +WRAPPER + chmod 755 "$NFPM_STAGE/usr/bin/$NFPM_BIN" + rm -f "$NFPM_STAGE/usr/bin/designcraft" + mv "$NFPM_STAGE/usr/bin/designcraft-cli" "$NFPM_STAGE/usr/bin/$NFPM_CLI" + mv "$NFPM_STAGE/usr/share/doc/designcraft" "$NFPM_STAGE/usr/share/doc/$NFPM_NAME" + sed -e "s#^Exec=designcraft\([[:space:]]\|$\)#Exec=$NFPM_BIN\1#" \ + -e "s|^TryExec=designcraft$|TryExec=$NFPM_BIN|" \ + -e "s|^Icon=$APP_ID$|Icon=$NIGHTLY_DESK_ID|" \ + -e "s|^Name=DesignCraft$|Name=DesignCraft Nightly|" \ + -e '/^MimeType=/d' \ + "$NFPM_STAGE/usr/share/applications/$APP_ID.desktop" >"$NFPM_STAGE/usr/share/applications/$NIGHTLY_DESK_ID.desktop" + rm -f "$NFPM_STAGE/usr/share/applications/$APP_ID.desktop" + sed -e "s|$APP_ID|$NIGHTLY_DESK_ID|g" \ + -e "s|DesignCraft|DesignCraft Nightly|g" \ + -e "s|$APP_ID.desktop|$NIGHTLY_DESK_ID.desktop|g" \ + -e "s|$APP_ID|$NIGHTLY_DESK_ID|g" \ + -e "s|designcraft|$NFPM_BIN|g" \ + "$NFPM_STAGE/usr/share/metainfo/$APP_ID.metainfo.xml" >"$NFPM_STAGE/usr/share/metainfo/$NIGHTLY_DESK_ID.metainfo.xml" + rm -f "$NFPM_STAGE/usr/share/metainfo/$APP_ID.metainfo.xml" + rm -rf "$NFPM_STAGE/usr/share/mime" "$NFPM_STAGE/usr/share/thumbnailers" + NIGHTLY_ICON="$ROOT/assets/app-icon/designcraft-nightly.png" + if [[ ! -f "$NIGHTLY_ICON" ]]; then + NIGHTLY_ICON="$ROOT/assets/app-icon/hicolor/256x256/apps/$APP_ID.png" + fi + rm -rf "$NFPM_STAGE/usr/share/icons/hicolor" + install -Dm644 "$NIGHTLY_ICON" \ + "$NFPM_STAGE/usr/share/icons/hicolor/256x256/apps/$NIGHTLY_DESK_ID.png" + fi # nfpm expands env vars in fields like `version` and `arch`, but not in `contents[].src`. - sed "s|\${STAGE}|$STAGE|g" "$HERE/nfpm.yaml" >"$WORK/nfpm.yaml" + DROP_LIB_TREE= + # shellcheck disable=SC2016 + [[ -d "$NFPM_STAGE/usr/lib" ]] || DROP_LIB_TREE='\|^ - src: \${STAGE}/usr/lib/|,+2d;' + # shellcheck disable=SC2016 + sed "${DROP_LIB_TREE}s|\${STAGE}|$NFPM_STAGE|g;s|\${NFPM_BIN}|$NFPM_BIN|g;s|\${NFPM_CLI}|$NFPM_CLI|g" "$HERE/nfpm.yaml" >"$WORK/nfpm.yaml" for fmt in deb rpm; do if has "$fmt"; then (cd "$ROOT" && nfpm package -f "$WORK/nfpm.yaml" -p "$fmt" -t "$DIST/$BASENAME.$fmt"); fi done @@ -125,10 +222,51 @@ if has appimage; then cp -R "$STAGE" "$APPDIR" # Keep sctk-adwaita's MIT notice in the AppImage. install -Dm644 "$ROOT/NOTICE" "$APPDIR/usr/share/doc/designcraft/NOTICE" - ln -s usr/bin/designcraft "$APPDIR/AppRun" - cp "$HERE/$APP_ID.desktop" "$APPDIR/$APP_ID.desktop" - cp "$ROOT/assets/app-icon/hicolor/256x256/apps/$APP_ID.png" "$APPDIR/$APP_ID.png" - ln -s "$APP_ID.png" "$APPDIR/.DirIcon" + if [[ "$IS_NIGHTLY" = 1 ]]; then + APPIMAGE_ID="$APP_ID.nightly-v1" + cat >"$APPDIR/AppRun" <<'APPRUN' +#!/bin/sh +# Start the compiled nightly-v1 flavor. A real file, never a symlink to the binary: the flavor +# needs the Launcher's profile pair, and the app refuses a DESIGNCRAFT_CONFIG_DIR override. +set -eu +APPDIR="${APPDIR:-$(cd "$(dirname "$0")" && pwd)}" +real_bin="$APPDIR/usr/bin/designcraft" +if [ "${1:-}" = "--launch-profile" ] || [ "${1:-}" = "--profile-root" ]; then + # The Launcher already supplied the protocol: pass its command line through untouched. + exec "$real_bin" "$@" +fi +if [ "${1:-}" = "--version" ] || [ "${1:-}" = "-V" ]; then + exec "$real_bin" "$@" +fi +profile_root="${XDG_DATA_HOME:-${HOME:?HOME is required}/.local/share}/designcraft-nightly" +if [ "${1:-}" = "--" ]; then + # The caller's own separator stays the only one. + exec "$real_bin" --launch-profile nightly-v1 --profile-root "$profile_root" "$@" +fi +exec "$real_bin" --launch-profile nightly-v1 --profile-root "$profile_root" -- "$@" +APPRUN + chmod 755 "$APPDIR/AppRun" + sed -e "s|^Icon=$APP_ID$|Icon=$APPIMAGE_ID|" \ + -e "s|^Name=DesignCraft$|Name=DesignCraft Nightly|" \ + -e '/^MimeType=/d' \ + "$APPDIR/usr/share/applications/$APP_ID.desktop" >"$APPDIR/usr/share/applications/$APPIMAGE_ID.desktop" + rm -f "$APPDIR/usr/share/applications/$APP_ID.desktop" + cp "$APPDIR/usr/share/applications/$APPIMAGE_ID.desktop" "$APPDIR/$APPIMAGE_ID.desktop" + NIGHTLY_ICON="$ROOT/assets/app-icon/designcraft-nightly.png" + if [[ ! -f "$NIGHTLY_ICON" ]]; then + NIGHTLY_ICON="$ROOT/assets/app-icon/hicolor/256x256/apps/$APP_ID.png" + fi + rm -rf "$APPDIR/usr/share/icons/hicolor" + install -Dm644 "$NIGHTLY_ICON" \ + "$APPDIR/usr/share/icons/hicolor/256x256/apps/$APPIMAGE_ID.png" + cp "$NIGHTLY_ICON" "$APPDIR/$APPIMAGE_ID.png" + ln -s "$APPIMAGE_ID.png" "$APPDIR/.DirIcon" + else + ln -s usr/bin/designcraft "$APPDIR/AppRun" + cp "$HERE/$APP_ID.desktop" "$APPDIR/$APP_ID.desktop" + cp "$ROOT/assets/app-icon/hicolor/256x256/apps/$APP_ID.png" "$APPDIR/$APP_ID.png" + ln -s "$APP_ID.png" "$APPDIR/.DirIcon" + fi TOOL="${APPIMAGETOOL:-$(command -v appimagetool || true)}" if [[ -z "$TOOL" ]]; then @@ -155,11 +293,24 @@ if has appimage; then # each AppImage on GitHub Releases. `latest` is the newest published release that is not a # pre-release. A fork's builds point at its own releases through GITHUB_REPOSITORY. REPO="${GITHUB_REPOSITORY:-storytold/designcraft}" - UPDATE_INFO="gh-releases-zsync|${REPO%%/*}|${REPO#*/}|latest|designcraft-*-linux-$ARCH.AppImage.zsync" + UPDATE_ARGS=() + if [[ "$IS_NIGHTLY" = 0 ]]; then + UPDATE_INFO="gh-releases-zsync|${REPO%%/*}|${REPO#*/}|latest|designcraft-*-linux-$ARCH.AppImage.zsync" + UPDATE_ARGS=(-u "$UPDATE_INFO") + else + # Nightly releases are GitHub pre-releases (`latest` only selects stable releases), so point + # zsync update metadata at pre-release tags rather than stable `latest`. + NIGHTLY_ZSYNC_PATTERN="designcraft-*-nightly*-linux-$ARCH.AppImage.zsync" + if [[ "$VERSION" != *-nightly* ]]; then + NIGHTLY_ZSYNC_PATTERN="designcraft-*-linux-$ARCH.AppImage.zsync" + fi + UPDATE_INFO="gh-releases-zsync|${REPO%%/*}|${REPO#*/}|latest-pre|$NIGHTLY_ZSYNC_PATTERN" + UPDATE_ARGS=(-u "$UPDATE_INFO") + fi # Extract-and-run: works without FUSE (containers, CI). The output embeds the static runtime, # so users don't need libfuse2 either. With zsyncmake on the host (CI installs the zsync # package) appimagetool also writes the .zsync, into its working directory, hence the cd. - (cd "$DIST" && ARCH="$ARCH" APPIMAGE_EXTRACT_AND_RUN=1 "$TOOL" --no-appstream -u "$UPDATE_INFO" "$APPDIR" "$OUT") + (cd "$DIST" && ARCH="$ARCH" APPIMAGE_EXTRACT_AND_RUN=1 "$TOOL" --no-appstream "${UPDATE_ARGS[@]}" "$APPDIR" "$OUT") echo "wrote $OUT" if [[ -s "$OUT.zsync" ]]; then echo "wrote $OUT.zsync" diff --git a/packaging/macos/nightly-lib.sh b/packaging/macos/nightly-lib.sh new file mode 100755 index 000000000..21dc0a450 --- /dev/null +++ b/packaging/macos/nightly-lib.sh @@ -0,0 +1,170 @@ +# shellcheck shell=bash +# Shared checks for the Apple-silicon Nightly scripts (nightly.sh, nightly-sign.sh, nightly-verify.sh). +# Stable packaging (package.sh, verify.sh) does not source this file. The text checks take tool output +# as arguments, so packaging/macos/nightly_sign_tests.py runs them without macOS. + +MAC_NIGHTLY_APP='DesignCraft Nightly.app' +MAC_NIGHTLY_ID='ai.storyteller.designcraft.nightly' +# The release environment's names, as stable release.yml passes them (packaging/macos/import-cert.sh). +MAC_NIGHTLY_SECRETS=(APPLE_CERTIFICATE APPLE_CERTIFICATE_PASSWORD KEYCHAIN_PASSWORD APPLE_ID APPLE_PASSWORD APPLE_TEAM_ID) + +mac_nightly_die() { printf 'error: %s\n' "$*" >&2; exit 2; } + +# The exact prepared version from the feed asset name, or failure. +mac_nightly_version_from_asset() { + local name="$1" version + [[ "$name" =~ ^designcraft-(.+)-macos-aarch64-nightly\.zip$ ]] || return 1 + version="${BASH_REMATCH[1]}" + [[ "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+-nightly\.[0-9]{8}\.[0-9]+\.[0-9]+\.g[0-9a-f]{12}$ ]] || return 1 + printf '%s\n' "$version" +} + +# Every signing and notarization value is set, and the team is one Apple team ID. No ad-hoc fallback. +mac_nightly_require_secrets() { + local name + for name in "${MAC_NIGHTLY_SECRETS[@]}"; do + [[ -n "${!name:-}" ]] || mac_nightly_die "$name is not set: Nightly signing and notarization are required, with no ad-hoc fallback" + done + [[ "$APPLE_TEAM_ID" =~ ^[A-Z0-9]{10}$ ]] || mac_nightly_die 'APPLE_TEAM_ID is not an Apple team ID' + if [[ -n "${NIGHTLY_APPLE_TEAM_ID:-}" && "$NIGHTLY_APPLE_TEAM_ID" != "$APPLE_TEAM_ID" ]]; then + mac_nightly_die 'the signing team differs from the reviewed Nightly team (NIGHTLY_APPLE_TEAM_ID)' + fi +} + +# One line of `security find-identity -v -p codesigning`: the identity is a Developer ID Application of the team. +mac_nightly_identity_is_team() { + local line="$1" identity="$2" team="$3" + [[ "$line" == *" $identity "* && "$line" == *'"Developer ID Application: '*" ($team)\""* ]] +} + +# `codesign -d --verbose=2` of the signed bundle: the Nightly identifier, a Developer ID Application of the +# team, a secure timestamp and the hardened runtime (the checks of verify.sh, made strict). +mac_nightly_check_signature() { + local details="$1" team="$2" ok=0 + grep -Fqx "Identifier=$MAC_NIGHTLY_ID" <<<"$details" || { echo "error: the bundle is not signed as $MAC_NIGHTLY_ID" >&2; ok=1; } + grep -q '^Authority=Developer ID Application:' <<<"$details" || { echo 'error: not signed with a Developer ID Application identity' >&2; ok=1; } + grep -qx "TeamIdentifier=$team" <<<"$details" || { echo 'error: signed by a different team' >&2; ok=1; } + grep -q '^Timestamp=' <<<"$details" || { echo 'error: the signature has no secure timestamp' >&2; ok=1; } + grep -Eq '^CodeDirectory .*flags=0x[0-9a-f]+\([^)]*runtime' <<<"$details" || { echo 'error: not signed with the hardened runtime' >&2; ok=1; } + return "$ok" +} + +# `spctl --assess --type execute -vv`: Gatekeeper accepts the bundle as notarized. +mac_nightly_check_assessment() { + grep -q 'accepted' <<<"$1" && grep -qx 'source=Notarized Developer ID' <<<"$1" +} + +# Limits on an archive handed to `ditto -x`, set well above a normal Nightly bundle (the stable macOS +# app is about 280 MB packed) and low enough that a hostile archive cannot fill the runner's disk. +MAC_NIGHTLY_ZIP_MAX_ARCHIVE=$((1024 * 1024 * 1024)) +MAC_NIGHTLY_ZIP_MAX_EXPANDED=$((2 * 1024 * 1024 * 1024)) +MAC_NIGHTLY_ZIP_MAX_ENTRIES=20000 + +# Before anything is unpacked: every ZIP entry is a regular file or directory inside the one Nightly +# bundle, with no absolute path, `..`, backslash or empty component, and no link or special file. +# The archive is also bounded: its size, entry count and compressed bytes (so entries cannot overlap), +# and the bytes each entry really expands to, which are counted by inflating it here, not taken from +# the header that `ditto` would trust. Only stored and deflated entries are accepted. +mac_nightly_check_zip_entries() { + python3 -I - "$1" "$MAC_NIGHTLY_APP" "$MAC_NIGHTLY_ZIP_MAX_ARCHIVE" "$MAC_NIGHTLY_ZIP_MAX_EXPANDED" "$MAC_NIGHTLY_ZIP_MAX_ENTRIES" <<'PY' \ + || mac_nightly_die 'the archive has an entry outside the bundle, a link, a special file or more data than a Nightly bundle holds' +import os, stat, struct, sys, zipfile, zlib +archive, app = sys.argv[1:3] +max_archive, max_expanded, max_entries = map(int, sys.argv[3:6]) +if os.path.getsize(archive) > max_archive: + sys.exit("the archive is larger than a Nightly bundle") +CHUNK = 1 << 20 +with zipfile.ZipFile(archive) as z, open(archive, "rb") as raw: + infos = z.infolist() + if len(infos) > max_entries: + sys.exit(f"too many entries: {len(infos)}") + if sum(info.compress_size for info in infos) > os.path.getsize(archive): + sys.exit("entries share compressed data") + expanded = 0 + for info in infos: + name = info.filename + parts = name.rstrip("/").split("/") + mode = info.external_attr >> 16 + if (name.startswith("/") or "\\" in name or "\0" in name or parts[0] != app + or any(part in ("", ".", "..") for part in parts) + or stat.S_IFMT(mode) not in (0, stat.S_IFREG, stat.S_IFDIR)): + sys.exit(f"refused entry: {name!r}") + if info.is_dir(): + if info.file_size or info.compress_size: + sys.exit(f"directory with data: {name!r}") + continue + if not info.file_size and not info.compress_size: + continue + if info.compress_type not in (zipfile.ZIP_STORED, zipfile.ZIP_DEFLATED): + sys.exit(f"unsupported compression in {name!r}") + if info.file_size > max_expanded - expanded: + sys.exit("the archive expands to more than a Nightly bundle holds") + # Inflate the entry's own compressed bytes and count what comes out. + raw.seek(info.header_offset) + header = raw.read(30) + if len(header) != 30 or header[:4] != b"PK\x03\x04": + sys.exit(f"bad local header: {name!r}") + name_len, extra_len = struct.unpack(" 0 and not inflater.eof: + data = raw.read(min(CHUNK, left)) + if not data: + sys.exit(f"truncated entry: {name!r}") + left -= len(data) + pending = data + while pending: + out = inflater.decompress(pending, CHUNK) + total += len(out) + if total > info.file_size or total > max_expanded - expanded: + sys.exit(f"entry expands past its declared size: {name!r}") + pending = inflater.unconsumed_tail + if not inflater.eof or left or inflater.unused_data or total != info.file_size: + sys.exit(f"entry size does not match its data: {name!r}") + expanded += total +PY +} + +# An unpacked payload directory holds exactly the GUI-only Nightly bundle: one thin arm64 DesignCraft +# executable, the Nightly identity and the exact version (no numeric fallback), no CLI, no links or special +# files, no document or URL types. +mac_nightly_check_bundle() { + local payload="$1" version="$2" app entries plist key value + app="$payload/$MAC_NIGHTLY_APP" + entries="$(ls -A "$payload")" + [[ "$entries" == "$MAC_NIGHTLY_APP" && -d "$app" && ! -L "$app" ]] || mac_nightly_die "the archive must hold exactly $MAC_NIGHTLY_APP" + [[ -z "$(find "$payload" ! -type f ! -type d -print -quit)" ]] || mac_nightly_die 'the bundle contains links or special files' + [[ "$(ls -A "$app/Contents/MacOS")" == DesignCraft ]] || mac_nightly_die 'Contents/MacOS must hold only the DesignCraft GUI (no CLI)' + [[ -f "$app/Contents/MacOS/DesignCraft" && -x "$app/Contents/MacOS/DesignCraft" ]] || mac_nightly_die 'missing executable GUI' + [[ "$(lipo -archs "$app/Contents/MacOS/DesignCraft")" == arm64 ]] || mac_nightly_die 'the GUI must be thin arm64' + plist="$app/Contents/Info.plist" + for key in CFBundleIdentifier CFBundleExecutable DesignCraftVersion; do + value="$(plutil -extract "$key" raw -o - "$plist")" || mac_nightly_die "Info.plist has no $key" + case "$key" in + CFBundleIdentifier) [[ "$value" == "$MAC_NIGHTLY_ID" ]] ;; + CFBundleExecutable) [[ "$value" == DesignCraft ]] ;; + DesignCraftVersion) [[ "$value" == "$version" ]] ;; + esac || mac_nightly_die "Info.plist $key is not the prepared Nightly identity" + done + for key in CFBundleDocumentTypes CFBundleURLTypes UTExportedTypeDeclarations UTImportedTypeDeclarations; do + if plutil -extract "$key" xml1 -o - "$plist" >/dev/null 2>&1; then mac_nightly_die "Nightly declares $key"; fi + done +} + +# `stapler validate` asks Apple's CloudKit service, which sometimes drops the connection (error 68) +# though the ticket is there (verify.sh). +mac_nightly_validate_staple() { + local target="$1" attempt + for attempt in 1 2 3 4 5; do + xcrun stapler validate "$target" && return 0 + [[ "$attempt" = 5 ]] || sleep $((attempt * 20)) + done + return 1 +} diff --git a/packaging/macos/nightly-sign.sh b/packaging/macos/nightly-sign.sh new file mode 100755 index 000000000..0c86f4bd6 --- /dev/null +++ b/packaging/macos/nightly-sign.sh @@ -0,0 +1,145 @@ +#!/usr/bin/env bash +# Trusted signing step for the Apple-silicon Nightly, the stable release's macOS signing route +# (import-cert.sh, then package.sh's codesign, notarytool and stapler steps): +# +# nightly-sign.sh --arch aarch64 --input /abs/designcraft--macos-aarch64-nightly.zip \ +# --output /abs//designcraft--macos-aarch64-nightly.zip +# +# Input: the unsigned archive nightly.sh made. Output: the same bundle signed with the Developer ID and +# hardened runtime, notarized, with the ticket stapled into the bundle, zipped without extended +# attributes. Writes only that file, never replacing one; the temporary keychain and work directory +# are removed on every exit. +# +# Env (all required, no ad-hoc or unnotarized fallback): APPLE_CERTIFICATE, APPLE_CERTIFICATE_PASSWORD, +# KEYCHAIN_PASSWORD, APPLE_ID, APPLE_PASSWORD, APPLE_TEAM_ID; optional NIGHTLY_APPLE_TEAM_ID (must +# equal APPLE_TEAM_ID) and RUNNER_TEMP (work directory base). +# +# Never compiles, and never runs anything from the payload: the version query runs on the signed +# bundle in a job without secrets (nightly-verify.sh). +set -euo pipefail +HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +# shellcheck source=nightly-lib.sh +. "$HERE/nightly-lib.sh" +# shellcheck source=../nightly-common.sh +. "$HERE/../nightly-common.sh" + +ARCH='' INPUT='' OUTPUT='' +while [[ $# -gt 0 ]]; do + case "$1" in + --arch | --input | --output) + [[ $# -ge 2 ]] || mac_nightly_die "missing $1 value" + case "$1" in --arch) ARCH="$2" ;; --input) INPUT="$2" ;; --output) OUTPUT="$2" ;; esac + shift 2 ;; + -h | --help) sed -n '2,18p' "$0"; exit 0 ;; + *) mac_nightly_die "unsupported argument: $1" ;; + esac +done +[[ "$ARCH" == aarch64 ]] || mac_nightly_die 'only --arch aarch64 is supported' +[[ "$INPUT" == /* && "$OUTPUT" == /* ]] || mac_nightly_die '--input and --output must be absolute paths' +NAME="$(basename -- "$INPUT")" +VERSION="$(mac_nightly_version_from_asset "$NAME")" || mac_nightly_die 'the input is not a prepared Nightly archive name' +[[ "$(basename -- "$OUTPUT")" == "$NAME" ]] || mac_nightly_die 'the output must keep the archive name' +[[ -f "$INPUT" && ! -L "$INPUT" ]] || mac_nightly_die 'the input must be a regular file' +[[ ! -e "$OUTPUT" && ! -L "$OUTPUT" ]] || mac_nightly_die 'refusing to replace an existing output' +[[ -d "$(dirname -- "$OUTPUT")" && ! -L "$(dirname -- "$OUTPUT")" ]] || mac_nightly_die 'the output directory must exist' +mac_nightly_require_secrets +[[ "$(uname -s)" == Darwin ]] || mac_nightly_die 'signing needs macOS (codesign, notarytool, stapler)' + +BASE="${RUNNER_TEMP:-${TMPDIR:-/tmp}}" +WORK="$(mktemp -d "${BASE%/}/designcraft-nightly-sign.XXXXXX")" +# The keychain name is the one packaging/macos/import-cert.sh creates. +KEYCHAIN="$WORK/designcraft-signing.keychain-db" +cleanup() { + if [[ -e "$KEYCHAIN" ]]; then security delete-keychain "$KEYCHAIN" >/dev/null 2>&1 || rm -f -- "$KEYCHAIN"; fi + rm -rf -- "$WORK" +} +trap cleanup EXIT + +# ---- identity: import-cert.sh, into this run's private directory ------------------------------ +# An empty GITHUB_ENV makes it print the identity instead of exporting it to later steps. +imported="$(GITHUB_ENV='' RUNNER_TEMP="$WORK" DIST="$WORK/dist" bash "$HERE/import-cert.sh")" +IDENTITY="$(sed -n 's/^MACOS_SIGN_IDENTITY=//p' <<<"$imported")" +[[ "$IDENTITY" =~ ^[0-9A-F]{40}$ ]] || mac_nightly_die 'import-cert.sh did not import a signing identity' +# import-cert.sh opens its own private folder under this run's RUNNER_TEMP (designcraft-signing.XXXXXX) +# and names the keychain designcraft-signing.keychain-db there; it must stay inside this run. +KEYCHAIN="$(sed -n 's/^MACOS_KEYCHAIN=//p' <<<"$imported")" +[[ "$KEYCHAIN" == "$WORK"/* && -f "$KEYCHAIN" && ! -L "$KEYCHAIN" && "$KEYCHAIN" == */designcraft-signing.keychain-db ]] \ + || mac_nightly_die 'import-cert.sh did not keep its keychain in this run' +mac_nightly_identity_is_team "$(security find-identity -v -p codesigning "$KEYCHAIN" | grep -F " $IDENTITY " || true)" "$IDENTITY" "$APPLE_TEAM_ID" \ + || mac_nightly_die "the imported identity is not a Developer ID Application of team $APPLE_TEAM_ID" +echo "==> DesignCraft Nightly $VERSION for macOS (aarch64), identity: $IDENTITY" + +# ---- the unsigned bundle --------------------------------------------------------------------------- +mac_nightly_check_zip_entries "$INPUT" +ditto -x -k --norsrc --noextattr "$INPUT" "$WORK/payload" +mac_nightly_check_bundle "$WORK/payload" "$VERSION" +APP="$WORK/payload/$MAC_NIGHTLY_APP" + +# ---- package.sh's signing and notarization, with a required Developer ID --------------------------- +sign() { + codesign --force --sign "$IDENTITY" --keychain "$KEYCHAIN" --timestamp "$@" +} + +notarize() { + local file="$1" out id status + echo "==> notarizing $(basename "$file") (this can take a few minutes)" + out="$(xcrun notarytool submit "$file" --apple-id "$APPLE_ID" --password "$APPLE_PASSWORD" \ + --team-id "$APPLE_TEAM_ID" --wait --timeout 1h --output-format json)" || true + echo "$out" + id="$(printf '%s' "$out" | plutil -extract id raw -o - - 2>/dev/null || true)" + status="$(printf '%s' "$out" | plutil -extract status raw -o - - 2>/dev/null || true)" + if [[ "$status" != "Accepted" ]]; then + if [[ -n "$id" ]]; then + # Capped: the shared signer bounds a step's output at 256 KiB. + xcrun notarytool log "$id" --apple-id "$APPLE_ID" --password "$APPLE_PASSWORD" --team-id "$APPLE_TEAM_ID" | head -c 131072 || true + fi + echo "error: notarization of $(basename "$file") failed (status: ${status:-unknown})" >&2 + exit 1 + fi +} + +# Stapling and validating both look the ticket up in Apple's CloudKit service, which can drop the +# connection right after notarization (error 68), so retry the pair (package.sh). +staple() { + local file="$1" attempt + for attempt in 1 2 3 4 5; do + if xcrun stapler staple "$file" && xcrun stapler validate "$file"; then + return + fi + if [[ "$attempt" = 5 ]]; then + echo "error: stapling $(basename "$file") failed after $attempt attempts" >&2 + exit 1 + fi + echo "stapling $(basename "$file") failed (attempt $attempt); retrying in $((attempt * 20))s" >&2 + sleep $((attempt * 20)) + done +} + +# Inside-out: the executable, then the bundle (no --deep on the final signature). +sign --options runtime --entitlements "$HERE/entitlements.plist" "$APP/Contents/MacOS/DesignCraft" +sign --options runtime --entitlements "$HERE/entitlements.plist" "$APP" +codesign --verify --strict --deep --verbose=2 "$APP" +ditto -c -k --keepParent "$APP" "$WORK/notarize.zip" +notarize "$WORK/notarize.zip" +# The ticket goes into the bundle (Contents/CodeResources): the Launcher's extract restores no xattrs. +staple "$APP" + +# ---- the final archive, checked as the Launcher unpacks it ----------------------------------------- +ditto -c -k --norsrc --noextattr --noacl --keepParent "$APP" "$WORK/final.zip" +ditto -x -k --norsrc --noextattr "$WORK/final.zip" "$WORK/check" +mac_nightly_check_bundle "$WORK/check" "$VERSION" +CHECK="$WORK/check/$MAC_NIGHTLY_APP" +codesign --verify --strict --deep --verbose=2 "$CHECK" +mac_nightly_check_signature "$(codesign -d --verbose=2 "$CHECK" 2>&1)" "$APPLE_TEAM_ID" \ + || mac_nightly_die 'the signed bundle is not the required Developer ID signature' +mac_nightly_validate_staple "$CHECK" || mac_nightly_die 'no notarization ticket is stapled into the bundle' +# spctl's lookup can lag a few seconds behind notarytool's "Accepted" (verify.sh). +for attempt in 1 2 3 4 5; do + assessment="$(spctl --assess --type execute -vv "$CHECK" 2>&1)" || true + mac_nightly_check_assessment "$assessment" && break + [[ "$attempt" = 5 ]] || sleep 10 +done +printf '%s\n' "$assessment" +mac_nightly_check_assessment "$assessment" || mac_nightly_die 'Gatekeeper does not accept the bundle as notarized' + +nightly_publish_archive "$WORK/final.zip" "$OUTPUT" diff --git a/packaging/macos/nightly-verify.sh b/packaging/macos/nightly-verify.sh new file mode 100755 index 000000000..487018c12 --- /dev/null +++ b/packaging/macos/nightly-verify.sh @@ -0,0 +1,74 @@ +#!/usr/bin/env bash +# Check an Apple-silicon Nightly archive as the Launcher unpacks it, then ask the GUI its version. +# For a job without signing material (it refuses to run with any), after nightly-sign.sh: +# +# nightly-verify.sh --input /abs/designcraft--macos-aarch64-nightly.zip --expect signed [--team ID] +# nightly-verify.sh --input /abs/designcraft--macos-aarch64-nightly.zip --expect unsigned +# +# Both: the archive holds only the GUI-only Nightly bundle with the exact DesignCraftVersion, unpacked +# without extended attributes. `signed` (the feed artifact): Developer ID of the team (--team, else +# NIGHTLY_APPLE_TEAM_ID), hardened runtime, secure timestamp, stapled ticket, Gatekeeper accepts it as +# notarized. `unsigned` (nightly.sh's compile output, e.g. pull-request CI) checks no signature. +# Last, the bundle's GUI answers its version query with an empty environment, both plainly and in the +# Launcher's form `--launch-profile nightly-v1 --profile-root --version` (the shared producer +# smoke): each must exit 0 within 15 seconds, print exactly `DesignCraft (nightly-v1)` and +# write nothing to standard error. +set -euo pipefail +HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +# shellcheck source=nightly-lib.sh +. "$HERE/nightly-lib.sh" + +INPUT='' EXPECT='' TEAM="${NIGHTLY_APPLE_TEAM_ID:-}" +while [[ $# -gt 0 ]]; do + case "$1" in + --input | --expect | --team) + [[ $# -ge 2 ]] || mac_nightly_die "missing $1 value" + case "$1" in --input) INPUT="$2" ;; --expect) EXPECT="$2" ;; --team) TEAM="$2" ;; esac + shift 2 ;; + -h | --help) sed -n '2,15p' "$0"; exit 0 ;; + *) mac_nightly_die "unsupported argument: $1" ;; + esac +done +for name in "${MAC_NIGHTLY_SECRETS[@]}" MACOS_SIGN_IDENTITY MACOS_KEYCHAIN; do + [[ -z "${!name:-}" ]] || mac_nightly_die "refusing to run the payload with signing material in the environment ($name)" +done +[[ "$EXPECT" == signed || "$EXPECT" == unsigned ]] || mac_nightly_die '--expect must be signed or unsigned' +[[ "$EXPECT" == unsigned || "$TEAM" =~ ^[A-Z0-9]{10}$ ]] || mac_nightly_die 'a signed check needs the Apple team ID (--team or NIGHTLY_APPLE_TEAM_ID)' +[[ "$INPUT" == /* && -f "$INPUT" && ! -L "$INPUT" ]] || mac_nightly_die '--input must be an absolute regular file' +VERSION="$(mac_nightly_version_from_asset "$(basename -- "$INPUT")")" || mac_nightly_die 'the input is not a prepared Nightly archive name' +[[ "$(uname -s)" == Darwin && "$(uname -m)" == arm64 ]] || mac_nightly_die 'needs an Apple silicon Mac' + +WORK="$(mktemp -d "${RUNNER_TEMP:-${TMPDIR:-/tmp}}/designcraft-nightly-verify.XXXXXX")" +trap 'rm -rf -- "$WORK"' EXIT +mac_nightly_check_zip_entries "$INPUT" +ditto -x -k --norsrc --noextattr "$INPUT" "$WORK/payload" +mac_nightly_check_bundle "$WORK/payload" "$VERSION" +APP="$WORK/payload/$MAC_NIGHTLY_APP" + +if [[ "$EXPECT" == signed ]]; then + codesign --verify --strict --deep --verbose=2 "$APP" + mac_nightly_check_signature "$(codesign -d --verbose=2 "$APP" 2>&1)" "$TEAM" \ + || mac_nightly_die 'the bundle is not the required Developer ID signature' + mac_nightly_validate_staple "$APP" || mac_nightly_die 'no notarization ticket is stapled into the bundle' + for attempt in 1 2 3 4 5; do + assessment="$(spctl --assess --type execute -vv "$APP" 2>&1)" || true + mac_nightly_check_assessment "$assessment" && break + [[ "$attempt" = 5 ]] || sleep 10 + done + printf '%s\n' "$assessment" + mac_nightly_check_assessment "$assessment" || mac_nightly_die 'Gatekeeper does not accept the bundle as notarized' +fi + +# macOS has no timeout(1): perl's alarm survives its exec and ends a query that hangs (a dialog, say). +query() { + local out + out="$(env -i HOME="$WORK/home" TMPDIR="$WORK/tmp/" PATH=/usr/bin:/bin \ + /usr/bin/perl -e 'alarm 15; exec @ARGV or die' "$APP/Contents/MacOS/DesignCraft" "$@" 2>"$WORK/stderr")" \ + || mac_nightly_die "the version query ($*) failed or did not finish within 15 s" + [[ ! -s "$WORK/stderr" ]] || mac_nightly_die "the version query ($*) wrote to standard error: $(head -c 2000 "$WORK/stderr")" + [[ "$out" == "DesignCraft $VERSION (nightly-v1)" ]] || mac_nightly_die "the version query ($*) reports '$out', not DesignCraft $VERSION (nightly-v1)" +} +mkdir -m 700 "$WORK/home" "$WORK/tmp" "$WORK/profile" +query --version +query --launch-profile nightly-v1 --profile-root "$WORK/profile" --version +echo "==> verified ($EXPECT): DesignCraft $VERSION (nightly-v1), plain and in the Launcher's profile form" diff --git a/packaging/macos/nightly.sh b/packaging/macos/nightly.sh new file mode 100755 index 000000000..c5547d2b5 --- /dev/null +++ b/packaging/macos/nightly.sh @@ -0,0 +1,51 @@ +#!/usr/bin/env bash +# App-owned GUI-only Nightly for Apple silicon, compile step only (no signing material): +# +# $DIST/designcraft--macos-aarch64-nightly.zip DesignCraft Nightly.app, unsigned +# +# Usage: packaging/macos/nightly.sh --arch aarch64 +# +# Required env (nightly-common.sh): DESIGNCRAFT_BUILD_CHANNEL=nightly-v1, DESIGNCRAFT_VERSION, +# DESIGNCRAFT_BUILD_SHA, DESIGNCRAFT_BUILD_DATE, absolute CARGO_TARGET_DIR and DIST; CRAFT_FONTS_DIR optional. +# +# Not publishable by itself: the trusted step (nightly-sign.sh) signs, notarizes and staples it. No CLI, +# DMG, document or URL types, and no stable package.sh. The bundle is not run here; the version query +# runs on the signed bundle (nightly-verify.sh). +set -euo pipefail +ARCH= +while [[ $# -gt 0 ]]; do + case "$1" in + --arch) [[ $# -ge 2 ]] || { echo 'missing --arch value' >&2; exit 2; }; ARCH="$2"; shift 2 ;; + -h|--help) sed -n '2,13p' "$0"; exit 0 ;; + *) echo "unsupported nightly argument: $1" >&2; exit 2 ;; + esac +done +[[ "$ARCH" == aarch64 && "$(uname -s)" == Darwin && "$(uname -m)" == arm64 ]] || { echo 'only native macOS aarch64 nightly packaging is supported' >&2; exit 2; } +HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +. "$HERE/../nightly-common.sh" +. "$HERE/nightly-lib.sh" +nightly_refuse_signing_env +nightly_init macos "$ARCH" aarch64-apple-darwin +# Keep in sync with LSMinimumSystemVersion in Info.plist.in (as package.sh). +export MACOSX_DEPLOYMENT_TARGET=11.0 +OUTPUT="$DIST/designcraft-$VERSION-macos-aarch64-nightly.zip" +[[ ! -e "$OUTPUT" && ! -L "$OUTPUT" ]] || nightly_die 'refusing to replace an existing nightly archive' +nightly_compile_gui + +APP="$NIGHTLY_WORK/stage/$MAC_NIGHTLY_APP" +mkdir -p "$APP/Contents/MacOS" "$APP/Contents/Resources" +cp "$NIGHTLY_GUI" "$APP/Contents/MacOS/DesignCraft" +chmod 755 "$APP/Contents/MacOS/DesignCraft" +cp "$ROOT/assets/app-icon/designcraft-nightly.icns" "$APP/Contents/Resources/designcraft-nightly.icns" +nightly_copy_notices "$APP/Contents/Resources" +# The private mktemp cwd is the helper authority root: stage the template inside it. +cp "$HERE/Info.plist.in" "$NIGHTLY_WORK/Info.plist.in" +(cd "$NIGHTLY_WORK" && python3 "$HERE/nightly_plist.py" --template Info.plist.in \ + --output "stage/$MAC_NIGHTLY_APP/Contents/Info.plist" --version "$VERSION" --source-commit "$DESIGNCRAFT_BUILD_SHA") +plutil -lint "$APP/Contents/Info.plist" +printf 'APPL????' >"$APP/Contents/PkgInfo" +mac_nightly_check_bundle "$NIGHTLY_WORK/stage" "$VERSION" + +# No resource forks, extended attributes or ACLs: the Launcher restores none, so nothing may depend on them. +ditto -c -k --norsrc --noextattr --noacl --keepParent "$APP" "$NIGHTLY_WORK/archive.zip" +nightly_publish_archive "$NIGHTLY_WORK/archive.zip" "$OUTPUT" diff --git a/packaging/macos/nightly_plist.py b/packaging/macos/nightly_plist.py new file mode 100755 index 000000000..163fa0f9f --- /dev/null +++ b/packaging/macos/nightly_plist.py @@ -0,0 +1,69 @@ +#!/usr/bin/env python3 +"""Nightly metadata: run from a private owned build cwd with a staged template. + +All file arguments must stay beneath that cwd; this is not native/signing acceptance. +""" +import argparse +import datetime +import os +from pathlib import Path +import plistlib +import re +import sys + +# The shared helper location is fixed by this script, not by CLI file arguments. +sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) +from nightly_paths import OwnedBuildRoot + +MAX_TEMPLATE_BYTES = 256 * 1024 + +IDENTIFIER = "ai.storyteller.designcraft.nightly" +ASSOCIATIONS = ("CFBundleDocumentTypes", "CFBundleURLTypes", "UTExportedTypeDeclarations", "UTImportedTypeDeclarations") +VERSION = re.compile(r"([0-9]+\.[0-9]+\.[0-9]+)-nightly\.([0-9]{8})\.[0-9]+\.[0-9]+\.g([0-9a-f]{12})\Z") + + +def render(template: bytes, version: str, commit: str) -> bytes: + match = VERSION.fullmatch(version) + if not match or not re.fullmatch(r"[0-9a-f]{40}", commit) or match[3] != commit[:12]: + raise ValueError("exact prepared Nightly version and matching source commit are required") + datetime.datetime.strptime(match[2], "%Y%m%d") + data = plistlib.loads(template) + if not isinstance(data, dict) or data.get("CFBundlePackageType") != "APPL": + raise ValueError("expected the app-owned application plist template") + for key in ASSOCIATIONS: + data.pop(key, None) + data.update( + CFBundleDisplayName="DesignCraft Nightly", + CFBundleName="DesignCraft Nightly", + CFBundleIdentifier=IDENTIFIER, + CFBundleExecutable="DesignCraft", + CFBundleIconFile="designcraft-nightly", + CFBundleShortVersionString=match[1], + CFBundleVersion=match[1], + DesignCraftVersion=version, + DesignCraftBuildCommit=commit, + ) + return plistlib.dumps(data, fmt=plistlib.FMT_XML, sort_keys=False) + + +def write_plist(template: Path, destination: Path, version: str, commit: str) -> None: + with OwnedBuildRoot() as root: + content = render(root.read_bytes(template, MAX_TEMPLATE_BYTES), version, commit) + with root.create(destination) as stream: + stream.write(content) + stream.flush() + os.fsync(stream.fileno()) + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--template", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--version", required=True) + parser.add_argument("--source-commit", required=True) + args = parser.parse_args() + write_plist(args.template, args.output, args.version, args.source_commit) + + +if __name__ == "__main__": + main() diff --git a/packaging/macos/nightly_plist_tests.py b/packaging/macos/nightly_plist_tests.py new file mode 100644 index 000000000..fa5202b49 --- /dev/null +++ b/packaging/macos/nightly_plist_tests.py @@ -0,0 +1,202 @@ +#!/usr/bin/env python3 +"""Generated metadata/sentinel fixtures; no native binary, signature, archive or network.""" +import importlib.util +import os +from pathlib import Path +import plistlib +import runpy +import sys +from unittest import mock +import tempfile +import unittest + +HERE = Path(__file__).resolve().parent +SPEC = importlib.util.spec_from_file_location("photo_nightly_plist", HERE / "nightly_plist.py") +POLICY = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(POLICY) +COMMIT = "a" * 40 +VERSION = "0.23.1-nightly.20261121.12345.1.g" + COMMIT[:12] + + +class NightlyMetadata(unittest.TestCase): + def setUp(self): + self.directory = tempfile.TemporaryDirectory() + self.addCleanup(self.directory.cleanup) + self.root = Path(self.directory.name).resolve() + previous = Path.cwd() + os.chdir(self.root) + self.addCleanup(os.chdir, previous) + self.template = self.root / "Info.plist.in" + self.original = (HERE / "Info.plist.in").read_bytes() + self.template.write_bytes(self.original) + self.output = self.root / "Info.plist" + + def test_nightly_transform_removes_associations_without_changing_stable_or_platform_metadata(self): + stable = plistlib.loads(self.original) + stable["CFBundleURLTypes"] = [{"CFBundleURLSchemes": ["generated-test-scheme"]}] + prepared = plistlib.dumps(stable) + self.template.write_bytes(prepared) + POLICY.write_plist(self.template, self.output, VERSION, COMMIT) + rendered = plistlib.loads(self.output.read_bytes()) + for key in POLICY.ASSOCIATIONS: + self.assertNotIn(key, rendered) + self.assertNotEqual(rendered["CFBundleIdentifier"], stable["CFBundleIdentifier"]) + self.assertEqual(rendered["CFBundleIdentifier"], "ai.storyteller.designcraft.nightly") + self.assertEqual(rendered["CFBundleExecutable"], "DesignCraft") + self.assertEqual(rendered["DesignCraftVersion"], VERSION) + self.assertEqual(rendered["DesignCraftBuildCommit"], COMMIT) + self.assertTrue(VERSION.startswith(rendered["CFBundleVersion"] + "-nightly.")) + for key in ("LSMinimumSystemVersion", "CFBundleLocalizations", "NSHighResolutionCapable", "NSHumanReadableCopyright"): + self.assertEqual(rendered[key], stable[key]) + self.assertEqual(self.template.read_bytes(), prepared) + self.assertEqual((HERE / "Info.plist.in").read_bytes(), self.original) + + def test_bad_identity_or_template_refuses_before_creating_output(self): + for version, commit in (("0.23.1", COMMIT), (VERSION, "b" * 40), (VERSION, "not-a-commit"), (VERSION.replace("20261121", "20261399"), COMMIT)): + with self.subTest(version=version, commit=commit): + with self.assertRaises(ValueError): + POLICY.write_plist(self.template, self.output, version, commit) + self.assertFalse(self.output.exists()) + self.assertEqual(self.template.read_bytes(), self.original) + self.template.write_bytes(plistlib.dumps({"CFBundlePackageType": "generated-not-an-app"})) + with self.assertRaises(ValueError): + POLICY.write_plist(self.template, self.output, VERSION, COMMIT) + self.assertFalse(self.output.exists()) + + def test_cli_writes_the_requested_identity_without_replacing_the_template(self): + helper = HERE / "nightly_plist.py" + argv = [str(helper), "--template", str(self.template), "--output", str(self.output), "--version", VERSION, "--source-commit", COMMIT] + with mock.patch.object(sys, "argv", argv): + runpy.run_path(str(helper), run_name="__main__") + result = plistlib.loads(self.output.read_bytes()) + self.assertEqual(result["DesignCraftVersion"], VERSION) + self.assertEqual(result["DesignCraftBuildCommit"], COMMIT) + self.assertEqual(self.template.read_bytes(), self.original) + + def test_template_alias_or_nonfile_refuses_before_output(self): + alias = self.root / "template-alias" + alias.symlink_to(self.template) + for template in (alias, self.root, self.root / "missing-template"): + with self.subTest(template=template), self.assertRaises(ValueError): + POLICY.write_plist(template, self.output, VERSION, COMMIT) + self.assertFalse(self.output.exists()) + self.assertEqual(self.template.read_bytes(), self.original) + + def test_failed_write_cleans_owned_output_but_preserves_a_replacement(self): + sentinel = b"generated replacement artifact" + for disposition in ("owned", "missing", "replacement"): + with self.subTest(disposition=disposition): + if self.output.exists(): + self.output.unlink() + + def fail_sync(_descriptor): + # macOS/Linux allow unlink of an open file: exercise the real + # cleanup ownership check, not a mocked inode comparison. + if disposition != "owned": + self.output.unlink() + if disposition == "replacement": + self.output.write_bytes(sentinel) + raise OSError("generated fsync failure") + + with mock.patch.object(POLICY.os, "fsync", side_effect=fail_sync), self.assertRaises(OSError): + POLICY.write_plist(self.template, self.output, VERSION, COMMIT) + if disposition == "replacement": + self.assertEqual(self.output.read_bytes(), sentinel) + else: + self.assertFalse(self.output.exists()) + self.assertEqual(self.template.read_bytes(), self.original) + + def test_exclusive_output_preserves_existing_bytes_and_symlink_targets(self): + sentinel = b"generated owned sentinel, not an existing app or user file" + self.output.write_bytes(sentinel) + with self.assertRaises(FileExistsError): + POLICY.write_plist(self.template, self.output, VERSION, COMMIT) + self.assertEqual(self.output.read_bytes(), sentinel) + self.output.unlink() + external = self.root / "sentinel" + external.write_bytes(sentinel) + self.output.symlink_to(external) + with self.assertRaisesRegex(ValueError, "symlinks or aliases"): + POLICY.write_plist(self.template, self.output, VERSION, COMMIT) + self.assertEqual(external.read_bytes(), sentinel) + self.assertTrue(self.output.is_symlink()) + + + def test_template_outside_build_root_refuses_before_output(self): + with tempfile.TemporaryDirectory() as external: + template = Path(external) / "Info.plist.in" + template.write_bytes(self.original) + with self.assertRaises(ValueError): + POLICY.write_plist(template, self.output, VERSION, COMMIT) + self.assertFalse(self.output.exists()) + self.assertEqual(template.read_bytes(), self.original) + + def test_output_outside_build_root_refuses_before_write(self): + with tempfile.TemporaryDirectory() as external: + output = Path(external) / "Info.plist" + with self.assertRaises(ValueError): + POLICY.write_plist(self.template, output, VERSION, COMMIT) + self.assertFalse(output.exists()) + + def test_parent_traversal_refuses_even_to_an_owned_sibling(self): + with tempfile.TemporaryDirectory(dir=self.root.parent) as external: + output = Path("..") / Path(external).name / "Info.plist" + with self.assertRaises(ValueError): + POLICY.write_plist(self.template, output, VERSION, COMMIT) + self.assertFalse((Path(external) / "Info.plist").exists()) + + def test_symlinked_output_parent_refuses(self): + with tempfile.TemporaryDirectory() as external: + alias = self.root / "alias" + alias.symlink_to(external, target_is_directory=True) + with self.assertRaises(ValueError): + POLICY.write_plist(self.template, alias / "Info.plist", VERSION, COMMIT) + self.assertFalse((Path(external) / "Info.plist").exists()) + + def test_template_read_is_bounded_before_output(self): + self.template.write_bytes(plistlib.dumps({"CFBundlePackageType": "APPL", "fixture": "x" * 300000})) + with self.assertRaises(ValueError): + POLICY.write_plist(self.template, self.output, VERSION, COMMIT) + self.assertFalse(self.output.exists()) + + def test_nonprivate_build_root_refuses(self): + self.root.chmod(0o755) + try: + with self.assertRaises(ValueError): + POLICY.write_plist(self.template, self.output, VERSION, COMMIT) + self.assertFalse(self.output.exists()) + finally: + self.root.chmod(0o700) + + + def test_output_keeps_normal_new_file_permissions_inside_private_root(self): + previous = os.umask(0o022) + try: + reference = self.root / "reference" + reference.write_bytes(b"generated ordinary output") + POLICY.write_plist(self.template, self.output, VERSION, COMMIT) + finally: + os.umask(previous) + self.assertEqual(self.output.stat().st_mode & 0o777, reference.stat().st_mode & 0o777) + + def test_open_parent_anchor_prevents_a_later_alias_redirect(self): + parent = self.root / "stage" + parent.mkdir() + retained = self.root / "retained-stage" + destination = parent / "Info.plist" + original = POLICY.OwnedBuildRoot._parent + with tempfile.TemporaryDirectory() as external: + def swap_after_parent_open(root, path): + descriptor, name = original(root, path) + if Path(path) == destination: + parent.rename(retained) + parent.symlink_to(external, target_is_directory=True) + return descriptor, name + with mock.patch.object(POLICY.OwnedBuildRoot, "_parent", swap_after_parent_open): + POLICY.write_plist(self.template, destination, VERSION, COMMIT) + self.assertFalse((Path(external) / "Info.plist").exists()) + self.assertEqual(plistlib.loads((retained / "Info.plist").read_bytes())["DesignCraftVersion"], VERSION) + + +if __name__ == "__main__": + unittest.main() diff --git a/packaging/macos/nightly_sign_tests.py b/packaging/macos/nightly_sign_tests.py new file mode 100644 index 000000000..33cf5cfbf --- /dev/null +++ b/packaging/macos/nightly_sign_tests.py @@ -0,0 +1,462 @@ +#!/usr/bin/env python3 +"""The macOS Nightly signing and verification scripts, run on any POSIX host against generated +fixtures and stand-in Apple tools (codesign, notarytool, stapler, spctl, security, ditto, plutil, +lipo) that log their arguments. This proves the scripts' order, refusals and cleanup; it is not a +real signature, notarization or Mac run.""" +import base64 +import importlib.util +import json +import os +from pathlib import Path +import plistlib +import shutil +import stat +import subprocess +import sys +import tempfile +import textwrap +import time +import unittest +import zipfile + +HERE = Path(__file__).resolve().parent +SPEC = importlib.util.spec_from_file_location("photo_mac_nightly_plist", HERE / "nightly_plist.py") +PLIST = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(PLIST) +COMMIT = "b" * 40 +VERSION = "0.23.1-nightly.20261123.4567.1.g" + COMMIT[:12] +ASSET = f"designcraft-{VERSION}-macos-aarch64-nightly.zip" +APP = "DesignCraft Nightly.app" +TEAM = "ABCDE12345" +IDENTITY = "0123456789ABCDEF0123456789ABCDEF01234567" +SECRETS = { + "APPLE_CERTIFICATE": base64.b64encode(b"generated fixture, not a certificate").decode(), + "APPLE_CERTIFICATE_PASSWORD": "generated-fixture", + "KEYCHAIN_PASSWORD": "generated-fixture", + "APPLE_ID": "fixture@example.invalid", + "APPLE_PASSWORD": "generated-fixture", + "APPLE_TEAM_ID": TEAM, +} + +# One stand-in for every Apple tool, dispatched on its own name. Each logs its argv as a JSON line. +SHIM = r""" +import json, os, plistlib, sys, zipfile +from pathlib import Path +name = Path(sys.argv[0]).name +args = sys.argv[1:] +with open(os.environ["SHIM_LOG"], "a") as log: + log.write(json.dumps([name] + args) + "\n") +team = os.environ.get("SHIM_TEAM", "") +if name == "uname": + print({"-s": "Darwin", "-m": "arm64"}.get(args[0], "Darwin")) +elif name == "lipo": + print("arm64") +elif name == "ditto": + paths = [a for a in args if not a.startswith("-")] + src, dst = paths + if "-x" in args: + with zipfile.ZipFile(src) as z: + for info in z.infolist(): + target = Path(dst) / info.filename + if info.is_dir(): + target.mkdir(parents=True, exist_ok=True) + continue + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(z.read(info)) + mode = (info.external_attr >> 16) & 0o777 + if mode: + target.chmod(mode) + else: + root = Path(src) + with zipfile.ZipFile(dst, "x") as z: + for path in sorted([root] + list(root.rglob("*"))): + arc = (Path(root.name) / path.relative_to(root)).as_posix() + if path.is_dir(): + z.writestr(zipfile.ZipInfo(arc + "/"), b"") + else: + info = zipfile.ZipInfo(arc) + info.external_attr = (path.stat().st_mode & 0xFFFF) << 16 + z.writestr(info, path.read_bytes()) +elif name == "plutil": + if args[0] == "-lint": + sys.exit(0) + key, fmt, source = args[1], args[2], args[-1] + data = sys.stdin.read() if source == "-" else Path(source).read_bytes() + value = json.loads(data) if source == "-" else plistlib.loads(data) + if key not in value: + sys.exit(1) + print(value[key] if fmt == "raw" else "") +elif name == "security": + verb = args[0] + if verb == "create-keychain": + Path(args[-1]).write_bytes(b"keychain") + elif verb == "find-identity": + print(' 1) %s "Developer ID Application: Generated Fixture (%s)"' % (os.environ["SHIM_IDENTITY"], team)) + print(" 1 valid identities found") + elif verb == "delete-keychain": + Path(args[-1]).unlink() +elif name == "codesign": + target = Path(args[-1]) + if "--sign" in args and target.suffix == ".app": + (target / "Contents/_CodeSignature").mkdir(exist_ok=True) + (target / "Contents/_CodeSignature/CodeResources").write_bytes(b"sealed") + if "-d" in args: + sys.stderr.write("Executable=%s\nIdentifier=ai.storyteller.designcraft.nightly\n" + "CodeDirectory v=20500 size=1 flags=0x10000(runtime) hashes=1+7 location=embedded\n" + "Authority=Developer ID Application: Generated Fixture (%s)\n" + "Timestamp=23 Nov 2026 at 17:00:00\nTeamIdentifier=%s\n" % (target, team, team)) +elif name == "xcrun": + if args[:2] == ["notarytool", "submit"]: + print(json.dumps({"id": "generated-id", "status": os.environ.get("SHIM_NOTARY", "Accepted")})) + elif args[:2] == ["stapler", "staple"]: + (Path(args[2]) / "Contents/CodeResources").write_bytes(b"ticket") + elif args[:2] == ["stapler", "validate"]: + sys.exit(0 if (Path(args[2]) / "Contents/CodeResources").is_file() else 1) +elif name == "spctl": + sys.stderr.write("%s: accepted\nsource=Notarized Developer ID\n" % args[-1]) +elif name == "cargo": + sys.exit(1) +# sleep: the retry waits pass at once. +""" + +TOOLS = ("uname", "lipo", "ditto", "plutil", "security", "codesign", "xcrun", "spctl", "cargo", "sleep") + + +class Fixture: + def __init__(self, test): + self.directory = tempfile.TemporaryDirectory() + test.addCleanup(self.directory.cleanup) + self.root = Path(self.directory.name).resolve() + self.bin = self.root / "bin" + self.bin.mkdir() + shim = self.bin / "shim.py" + shim.write_text(SHIM) + for tool in TOOLS: + path = self.bin / tool + path.write_text(f"#!{sys.executable}\nimport sys\nsys.argv[0] = {str(path)!r}\nexec(compile(open({str(shim)!r}).read(), 'shim', 'exec'), {{'__name__': '__main__'}})\n") + path.chmod(0o755) + self.log = self.root / "tools.log" + self.ran = self.root / "payload-ran" + self.temp = self.root / "runner-temp" + self.temp.mkdir() + self.dist = self.root / "unsigned" + self.dist.mkdir() + self.signed = self.root / "signed" + self.signed.mkdir() + self.input = self.dist / ASSET + self.output = self.signed / ASSET + # Every script runs from a directory with modules a Python helper must not import (-I). + self.cwd = self.root / "cwd" + self.cwd.mkdir() + self.hijacked = self.root / "hijacked" + for module in ("shutil", "zipfile", "stat"): + (self.cwd / f"{module}.py").write_text(f"open({str(self.hijacked)!r}, 'a').write({module!r})\n") + + def add_entry(self, info, data=b""): + """Append one raw entry to the input archive.""" + with zipfile.ZipFile(self.input, "a") as z: + z.writestr(info, data) + + def bundle(self, version=VERSION, extra=None, gui=None): + """The archive nightly.sh makes: the real template through the real plist helper.""" + stage = self.root / "stage" + shutil.rmtree(stage, ignore_errors=True) + app = stage / APP + (app / "Contents/MacOS").mkdir(parents=True) + (app / "Contents/Resources").mkdir() + exe = app / "Contents/MacOS/DesignCraft" + exe.write_text(gui or f"#!/bin/sh\ntouch {self.ran}\necho 'DesignCraft {version} (nightly-v1)'\n") + exe.chmod(0o755) + (app / "Contents/Resources/designcraft-nightly.icns").write_bytes(b"generated icon") + rendered = PLIST.render((HERE / "Info.plist.in").read_bytes(), version, COMMIT) + (app / "Contents/Info.plist").write_bytes(rendered) + for relative, data in (extra or {}).items(): + (app / relative).write_bytes(data) + (app / relative).chmod(0o755) + if self.input.exists(): + self.input.unlink() + with zipfile.ZipFile(self.input, "x") as z: + for path in sorted([app] + list(app.rglob("*"))): + arc = (Path(APP) / path.relative_to(app)).as_posix() + info = zipfile.ZipInfo(arc + ("/" if path.is_dir() else "")) + info.external_attr = (path.stat().st_mode & 0xFFFF) << 16 + z.writestr(info, b"" if path.is_dir() else path.read_bytes()) + return self.input + + def env(self, **changes): + env = {"PATH": f"{self.bin}:{os.environ['PATH']}", "HOME": str(self.root), "SHIM_LOG": str(self.log), + "SHIM_TEAM": TEAM, "SHIM_IDENTITY": IDENTITY, "RUNNER_TEMP": str(self.temp), **SECRETS} + env.update(changes) + return {key: value for key, value in env.items() if value is not None} + + def run(self, script, *args, **env): + if self.log.exists(): + self.log.unlink() + return subprocess.run(["bash", str(HERE / script), *map(str, args)], env=self.env(**env), cwd=self.cwd, + stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, timeout=120) + + def sign(self, **env): + return self.run("nightly-sign.sh", "--arch", "aarch64", "--input", self.input, "--output", self.output, **env) + + def calls(self): + if not self.log.exists(): + return [] + return [json.loads(line) for line in self.log.read_text().splitlines()] + + +def lib(function, *args): + """Run one nightly-lib.sh function; returns (exit status, stdout).""" + script = f'. {str(HERE / "nightly-lib.sh")!r}; {function} "$@"' + result = subprocess.run(["bash", "-c", script, "lib", *args], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True) + return result.returncode, result.stdout.strip() + + +DETAILS = (f"Identifier=ai.storyteller.designcraft.nightly\nCodeDirectory v=20500 size=1 flags=0x10000(runtime) hashes=1\n" + f"Authority=Developer ID Application: Generated Fixture ({TEAM})\nAuthority=Developer ID Certification Authority\n" + f"Timestamp=23 Nov 2026\nTeamIdentifier={TEAM}\n") + + +class Checks(unittest.TestCase): + def test_the_version_comes_only_from_a_prepared_nightly_asset_name(self): + self.assertEqual(lib("mac_nightly_version_from_asset", ASSET), (0, VERSION)) + for name in (f"designcraft-0.23.1-macos-aarch64.zip", f"designcraft-{VERSION}-macos-universal-nightly.zip", + f"designcraft-{VERSION}-linux-x86_64-nightly.tar.gz", ASSET.replace(".g", ".x"), "../" + ASSET): + with self.subTest(name=name): + self.assertNotEqual(lib("mac_nightly_version_from_asset", name)[0], 0) + + def test_signature_needs_every_part_of_the_developer_id_signature(self): + self.assertEqual(lib("mac_nightly_check_signature", DETAILS, TEAM)[0], 0) + for broken in (DETAILS.replace("flags=0x10000(runtime)", "flags=0x0(none)"), + DETAILS.replace("Timestamp=23 Nov 2026\n", "Signed Time=23 Nov 2026\n"), + "Identifier=designcraft-1234\nSignature=adhoc\nTeamIdentifier=not set\n", + DETAILS.replace("ai.storyteller.designcraft.nightly", "ai.storyteller.designcraft"), + DETAILS.replace("ai.storyteller.designcraft.nightly", "aiXstorytellerXdesigncraftXnightly")): + with self.subTest(broken=broken): + self.assertNotEqual(lib("mac_nightly_check_signature", broken, TEAM)[0], 0) + self.assertNotEqual(lib("mac_nightly_check_signature", DETAILS, "ZZZZZ99999")[0], 0, "another team") + + def test_gatekeeper_must_accept_the_bundle_as_notarized(self): + self.assertEqual(lib("mac_nightly_check_assessment", "x.app: accepted\nsource=Notarized Developer ID\n")[0], 0) + for text in ("x.app: accepted\nsource=Developer ID\n", "x.app: rejected\nsource=Unnotarized Developer ID\n"): + with self.subTest(text=text): + self.assertNotEqual(lib("mac_nightly_check_assessment", text)[0], 0) + + def test_the_imported_identity_must_be_a_developer_id_of_the_team(self): + line = f' 1) {IDENTITY} "Developer ID Application: Generated Fixture ({TEAM})"' + self.assertEqual(lib("mac_nightly_identity_is_team", line, IDENTITY, TEAM)[0], 0) + self.assertNotEqual(lib("mac_nightly_identity_is_team", line, IDENTITY, "ZZZZZ99999")[0], 0) + self.assertNotEqual(lib("mac_nightly_identity_is_team", line.replace("Developer ID Application", "Apple Development"), IDENTITY, TEAM)[0], 0) + + def zip_check(self, archive, **limits): + """The preflight alone, with the archive limits optionally lowered after the library is sourced.""" + lowered = "".join(f"{name}={value}; " for name, value in limits.items()) + script = f'. {str(HERE / "nightly-lib.sh")!r}; {lowered}mac_nightly_check_zip_entries "$1"' + return subprocess.run(["bash", "-c", script, "lib", str(archive)], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL).returncode + + def make_zip(self, directory, method=zipfile.ZIP_DEFLATED, files=None): + path = Path(directory) / "bundle.zip" + with zipfile.ZipFile(path, "w", method) as z: + for name, data in (files or {f"{APP}/Contents/MacOS/DesignCraft": b"x" * 4096, f"{APP}/Contents/Info.plist": b""}).items(): + z.writestr(zipfile.ZipInfo(name), data, compress_type=method) + return path + + def test_the_archive_is_bounded_before_anything_is_unpacked(self): + with tempfile.TemporaryDirectory() as directory: + for method in (zipfile.ZIP_STORED, zipfile.ZIP_DEFLATED): + with self.subTest(method=method): + path = self.make_zip(directory, method) + self.assertEqual(self.zip_check(path), 0, "a normal bundle is accepted") + self.assertNotEqual(self.zip_check(path, MAC_NIGHTLY_ZIP_MAX_ENTRIES=1), 0, "too many entries") + self.assertNotEqual(self.zip_check(path, MAC_NIGHTLY_ZIP_MAX_EXPANDED=1000), 0, "too much expanded data") + self.assertNotEqual(self.zip_check(path, MAC_NIGHTLY_ZIP_MAX_ARCHIVE=10), 0, "too large an archive") + bzip = self.make_zip(directory, zipfile.ZIP_BZIP2) + self.assertNotEqual(self.zip_check(bzip), 0, "only stored and deflated entries are inflated and counted") + + def test_an_entry_whose_header_understates_its_size_is_refused(self): + import struct + size = 3_000_000 + with tempfile.TemporaryDirectory() as directory: + path = self.make_zip(directory, files={f"{APP}/Contents/MacOS/DesignCraft": b"\0" * size}) + self.assertEqual(self.zip_check(path), 0) + data = bytearray(path.read_bytes()) + packed, understated = struct.pack("> 16 + self.assertTrue(mode & stat.S_IXUSR) + + def test_every_signing_and_notarization_secret_is_required(self): + for name in SECRETS: + with self.subTest(missing=name): + self.assert_refused_untouched(self.f.sign(**{name: None})) + self.assertEqual(self.f.calls(), [], "no tool runs before the configuration is complete") + self.assert_refused_untouched(self.f.sign(NIGHTLY_APPLE_TEAM_ID="ZZZZZ99999")) + self.assert_refused_untouched(self.f.sign(APPLE_TEAM_ID="not-a-team")) + + def test_refuses_another_team_s_identity(self): + self.assert_refused_untouched(self.f.sign(SHIM_TEAM="ZZZZZ99999")) + + def test_never_replaces_an_output_or_renames_the_asset(self): + self.f.output.write_bytes(b"generated existing artifact") + result = self.f.sign() + self.assertNotEqual(result.returncode, 0) + self.assertEqual(self.f.output.read_bytes(), b"generated existing artifact") + self.f.output.unlink() + renamed = self.f.run("nightly-sign.sh", "--arch", "aarch64", "--input", self.f.input, "--output", self.f.signed / "other.zip") + self.assertNotEqual(renamed.returncode, 0) + relative = self.f.run("nightly-sign.sh", "--arch", "aarch64", "--input", self.f.input.name, "--output", self.f.output) + self.assertNotEqual(relative.returncode, 0) + self.assertEqual(list(self.f.signed.iterdir()), []) + + def test_refuses_a_payload_that_is_not_the_exact_gui_only_nightly(self): + cases = { + "cli": dict(extra={"Contents/MacOS/designcraft-cli": b"generated cli"}), + "version": dict(version=VERSION.replace("4567", "4568")), + } + for label, change in cases.items(): + with self.subTest(label=label): + self.f.bundle(**change) + self.unsigned = self.f.input.read_bytes() + self.assert_refused_untouched(self.f.sign()) + + def test_refuses_links_traversal_and_foreign_entries_before_unpacking(self): + link = zipfile.ZipInfo(f"{APP}/Contents/Resources/link") + link.external_attr = (stat.S_IFLNK | 0o777) << 16 + fifo = zipfile.ZipInfo(f"{APP}/Contents/Resources/fifo") + fifo.external_attr = (stat.S_IFIFO | 0o644) << 16 + for label, info in (("link", link), ("special", fifo), ("traversal", zipfile.ZipInfo(f"{APP}/../outside")), + ("absolute", zipfile.ZipInfo("/tmp/outside")), ("foreign root", zipfile.ZipInfo("Other.app/x"))): + with self.subTest(label=label): + self.f.bundle() + self.f.add_entry(info, b"/etc/passwd") + self.unsigned = self.f.input.read_bytes() + result = self.f.sign() + self.assert_refused_untouched(result) + self.assertNotIn("ditto", [call[0] for call in self.f.calls()], "refused before unpacking") + + def test_a_rejected_notarization_publishes_nothing_and_removes_the_keychain(self): + result = self.f.sign(SHIM_NOTARY="Invalid") + self.assert_refused_untouched(result, signed=True) + self.assertIn(["xcrun", "notarytool", "log"], [call[:3] for call in self.f.calls()]) + self.assertNotIn(["xcrun", "stapler", "staple"], [call[:3] for call in self.f.calls()]) + + +class Verify(unittest.TestCase): + def setUp(self): + self.f = Fixture(self) + + def verify(self, *args, **env): + return self.f.run("nightly-verify.sh", "--input", self.f.input, *args, **{name: None for name in SECRETS}, **env) + + def test_asks_the_gui_its_version_with_an_empty_environment(self): + self.f.bundle(gui=f"#!/bin/sh\n[ -z \"$INHERITED\" ] || exit 9\necho 'DesignCraft {VERSION} (nightly-v1)'\n") + result = self.verify("--expect", "unsigned", INHERITED="generated") + self.assertEqual(result.returncode, 0, result.stdout) + self.f.bundle(gui="#!/bin/sh\necho 'DesignCraft 0.23.1 (stable)'\n") + self.assertNotEqual(self.verify("--expect", "unsigned").returncode, 0) + + def test_the_launcher_profile_form_must_answer_promptly_and_cleanly(self): + answer = f"echo 'DesignCraft {VERSION} (nightly-v1)'" + # The shared producer smoke's exact form, with a fresh profile directory. + exact = ('#!/bin/sh\nif [ "$1" = --launch-profile ]; then\n' + ' [ "$#" = 5 ] && [ "$2" = nightly-v1 ] && [ "$3" = --profile-root ] && [ -d "$4" ] && [ "$5" = --version ] || exit 7\n' + f'fi\n{answer}\n') + self.f.bundle(gui=exact) + result = self.verify("--expect", "unsigned") + self.assertEqual(result.returncode, 0, result.stdout) + hangs = f'#!/bin/sh\n[ "$1" != --launch-profile ] || exec /bin/sleep 60\n{answer}\n' + self.f.bundle(gui=hangs) + started = time.monotonic() + result = self.verify("--expect", "unsigned") + self.assertNotEqual(result.returncode, 0) + self.assertIn("within 15 s", result.stdout) + self.assertLess(time.monotonic() - started, 45, "a hanging query is ended, not waited for") + noisy = f'#!/bin/sh\n[ "$1" != --launch-profile ] || echo refusal >&2\n{answer}\n' + self.f.bundle(gui=noisy) + result = self.verify("--expect", "unsigned") + self.assertNotEqual(result.returncode, 0) + self.assertIn("standard error", result.stdout) + + def test_a_signed_check_needs_the_signature_ticket_and_team(self): + self.f.bundle() + self.assertNotEqual(self.verify("--expect", "signed").returncode, 0, "no team to check against") + self.assertNotEqual(self.verify("--expect", "signed", "--team", TEAM).returncode, 0, "no stapled ticket") + self.f.bundle(extra={"Contents/CodeResources": b"ticket"}) + self.assertEqual(self.verify("--expect", "signed", "--team", TEAM).returncode, 0) + self.assertNotEqual(self.verify("--expect", "signed", "--team", TEAM, SHIM_TEAM="ZZZZZ99999").returncode, 0) + + def test_refuses_to_run_the_payload_beside_signing_material(self): + self.f.bundle() + for name in ("APPLE_PASSWORD", "APPLE_CERTIFICATE", "MACOS_KEYCHAIN"): + with self.subTest(name=name): + result = self.f.run("nightly-verify.sh", "--input", self.f.input, "--expect", "unsigned", + **{**{key: None for key in SECRETS}, name: "generated"}) + self.assertNotEqual(result.returncode, 0) + self.assertFalse(self.f.ran.exists()) + self.assertEqual(self.f.calls(), []) + + +class Build(unittest.TestCase): + def test_compilation_refuses_signing_material_before_building(self): + f = Fixture(self) + for name in ("APPLE_CERTIFICATE", "APPLE_PASSWORD", "MACOS_SIGN_IDENTITY", "WINDOWS_CERTIFICATE", "AZURE_CLIENT_SECRET", "LINUX_SIGNING_KEY"): + with self.subTest(name=name): + result = f.run("nightly.sh", "--arch", "aarch64", **{**{key: None for key in SECRETS}, name: "generated"}, + DESIGNCRAFT_BUILD_CHANNEL="nightly-v1", DESIGNCRAFT_VERSION=VERSION) + self.assertNotEqual(result.returncode, 0) + self.assertIn(name, result.stdout) + self.assertNotIn("cargo", [call[0] for call in f.calls()]) + + +if __name__ == "__main__": + unittest.main() diff --git a/packaging/nightly-archive-tests.py b/packaging/nightly-archive-tests.py new file mode 100644 index 000000000..880b38dcc --- /dev/null +++ b/packaging/nightly-archive-tests.py @@ -0,0 +1,233 @@ +#!/usr/bin/env python3 +"""Synthetic app-owned archive/output tests; no native build or executable launch.""" +import gzip +import importlib.util +import os +import runpy +import sys +from unittest import mock +from pathlib import Path +import subprocess +import tarfile +import tempfile +import unittest + +HERE = Path(__file__).resolve().parent +SPEC = importlib.util.spec_from_file_location("photo_nightly_archive", HERE / "nightly-archive.py") +ARCHIVE = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(ARCHIVE) + + +class ArchivePolicy(unittest.TestCase): + def setUp(self): + self.scratch = tempfile.TemporaryDirectory() + self.addCleanup(self.scratch.cleanup) + self.root = Path(self.scratch.name).resolve() + previous = Path.cwd() + os.chdir(self.root) + self.addCleanup(os.chdir, previous) + self.stage = self.root / "stage" + self.stage.mkdir() + self.output = self.root / "nightly.tar.gz" + # DesignCraft ships no ATTRIBUTION.md (its credits are the About window's). + self.required = {"designcraft", "designcraft-bin", "designcraft-nightly.png", "README.md", "LICENSE-MIT", "LICENSE-APACHE", "NOTICE"} + for name in self.required: + (self.stage / name).write_bytes(b"generated fixture: " + name.encode()) + for executable in ("designcraft", "designcraft-bin"): + (self.stage / executable).chmod(0o755) + + def test_flat_regular_ustar_with_all_notices(self): + (self.stage / "OFL-Font.txt").write_text("generated fixture license", encoding="utf-8") + ARCHIVE.linux_archive(self.stage, self.output) + with tarfile.open(self.output) as archive: + self.assertEqual({m.name for m in archive}, self.required | {"OFL-Font.txt"}) + self.assertTrue(all(m.isfile() and not m.pax_headers for m in archive)) + self.assertEqual(archive.extractfile("designcraft").read(), (self.stage / "designcraft").read_bytes()) + # The launcher and the compiled binary are two distinct files in one flat archive. + self.assertNotEqual(archive.extractfile("designcraft").read(), archive.extractfile("designcraft-bin").read()) + with gzip.open(self.output, "rb") as stream: + while (header := stream.read(512)) != bytes(512): + self.assertEqual(len(header), 512) + self.assertIn(header[156:157], {b"0", b"\0"}) + self.assertEqual(header[257:263], b"ustar\0") + size = int(header[124:136].rstrip(b"\0 ").lstrip(b" ") or b"0", 8) + stream.read(((size + 511) // 512) * 512) + + def test_each_required_member_is_required_before_output(self): + for name in self.required: + with self.subTest(name=name): + content = (self.stage / name).read_bytes() + (self.stage / name).unlink() + with self.assertRaisesRegex(ValueError, "required"): + ARCHIVE.linux_archive(self.stage, self.output) + self.assertFalse(self.output.exists()) + (self.stage / name).write_bytes(content) + + def test_unexpected_cli_portable_or_installer_member_refuses(self): + for name in ["designcraft-cli", "portable.txt", "designcraft.desktop"]: + with self.subTest(name=name): + bad = self.stage / name + bad.write_bytes(b"generated fixture") + with self.assertRaisesRegex(ValueError, "unexpected"): + ARCHIVE.linux_archive(self.stage, self.output) + self.assertFalse(self.output.exists()) + bad.unlink() + + def test_symlink_refuses_before_output(self): + icon = self.stage / "designcraft-nightly.png" + icon.unlink() + icon.symlink_to(self.stage / "README.md") + with self.assertRaisesRegex(ValueError, "regular file|symlinks or aliases"): + ARCHIVE.linux_archive(self.stage, self.output) + self.assertFalse(self.output.exists()) + + def test_directory_refuses_before_output(self): + icon = self.stage / "designcraft-nightly.png" + icon.unlink() + icon.mkdir() + with self.assertRaisesRegex(ValueError, "regular file"): + ARCHIVE.linux_archive(self.stage, self.output) + self.assertFalse(self.output.exists()) + + def test_long_notice_refuses_before_output(self): + (self.stage / ("OFL-" + "x" * 100 + ".txt")).write_bytes(b"fixture") + with self.assertRaisesRegex(ValueError, "short regular"): + ARCHIVE.linux_archive(self.stage, self.output) + self.assertFalse(self.output.exists()) + + def test_case_colliding_notices_refuse_before_output(self): + for name in ["OFL-Font.txt", "OFL-font.txt"]: + (self.stage / name).write_bytes(b"fixture") + with self.assertRaisesRegex(ValueError, "case-colliding"): + ARCHIVE.linux_archive(self.stage, self.output) + self.assertFalse(self.output.exists()) + + def test_cli_dispatches_only_the_supported_archive_kind(self): + helper = HERE / "nightly-archive.py" + with mock.patch.object(sys, "argv", [str(helper), "linux", str(self.stage), str(self.output)]): + runpy.run_path(str(helper), run_name="__main__") + with tarfile.open(self.output) as archive: + self.assertEqual({member.name for member in archive}, self.required) + refused = self.root / "refused.tar.gz" + for args in ([str(helper)], [str(helper), "unknown", str(self.stage), str(refused)]): + with self.subTest(args=args), mock.patch.object(sys, "argv", args): + with self.assertRaises(SystemExit): + runpy.run_path(str(helper), run_name="__main__") + self.assertFalse(refused.exists()) + + def test_existing_archive_is_unchanged(self): + self.output.write_bytes(b"owned earlier artifact") + with self.assertRaises(FileExistsError): + ARCHIVE.linux_archive(self.stage, self.output) + self.assertEqual(self.output.read_bytes(), b"owned earlier artifact") + + + def test_archive_output_outside_build_root_refuses(self): + with tempfile.TemporaryDirectory() as external: + output = Path(external) / "nightly.tar.gz" + with self.assertRaises(ValueError): + ARCHIVE.linux_archive(self.stage, output) + self.assertFalse(output.exists()) + + def test_archive_stage_outside_build_root_refuses(self): + with tempfile.TemporaryDirectory() as external: + stage = Path(external) + for name in self.required: + (stage / name).write_bytes(b"generated external fixture") + with self.assertRaises(ValueError): + ARCHIVE.linux_archive(stage, self.output) + self.assertFalse(self.output.exists()) + + def test_archive_stage_alias_refuses(self): + alias = self.root / "stage-alias" + alias.symlink_to(self.stage, target_is_directory=True) + with self.assertRaises(ValueError): + ARCHIVE.linux_archive(alias, self.output) + self.assertFalse(self.output.exists()) + + def test_archive_output_parent_alias_refuses(self): + with tempfile.TemporaryDirectory() as external: + alias = self.root / "output-alias" + alias.symlink_to(external, target_is_directory=True) + with self.assertRaises(ValueError): + ARCHIVE.linux_archive(self.stage, alias / "nightly.tar.gz") + self.assertFalse((Path(external) / "nightly.tar.gz").exists()) + + def test_archive_parent_traversal_refuses(self): + with tempfile.TemporaryDirectory(dir=self.root.parent) as external: + output = Path("..") / Path(external).name / "nightly.tar.gz" + with self.assertRaises(ValueError): + ARCHIVE.linux_archive(self.stage, output) + self.assertFalse((Path(external) / "nightly.tar.gz").exists()) + + def test_nonflat_member_name_refuses(self): + stage_root = os.path.realpath(self.stage) + with open(self.stage / "README.md", "rb") as incoming: + for bad in ("../escape", "/absolute", "nested/name", "x/../README.md", "", ".", ".."): + with self.subTest(name=bad), self.assertRaises(ValueError): + ARCHIVE.member_info(stage_root, bad, incoming) + + def test_member_header_matches_what_gettarinfo_records(self): + stage_root = os.path.realpath(self.stage) + for name in sorted(self.required): + with self.subTest(name=name), open(self.stage / name, "rb") as incoming: + ours = ARCHIVE.member_info(stage_root, name, incoming) + with tarfile.open(fileobj=__import__("io").BytesIO(), mode="w") as reference: + theirs = reference.gettarinfo(fileobj=incoming, arcname=name) + self.assertEqual(ours.get_info(), theirs.get_info()) + + def test_member_read_budget_refuses_before_output(self): + (self.stage / "OFL-Large.txt").write_bytes(b"x" * 65) + with mock.patch.object(ARCHIVE, "MAX_MEMBER_BYTES", 64, create=True): + with self.assertRaises(ValueError): + ARCHIVE.linux_archive(self.stage, self.output) + self.assertFalse(self.output.exists()) + + + def test_member_growth_is_rechecked_before_copy_and_output_is_cleaned(self): + growing = self.stage / "OFL-Growing.txt" + growing.write_bytes(b"x" * 32) + original = ARCHIVE.member_info + + def grow_before_stat(stage_root, name, incoming): + if name == growing.name: + growing.write_bytes(b"x" * 65) + return original(stage_root, name, incoming) + + with mock.patch.object(ARCHIVE, "MAX_MEMBER_BYTES", 64), \ + mock.patch.object(ARCHIVE, "member_info", grow_before_stat): + with self.assertRaises(ValueError): + ARCHIVE.linux_archive(self.stage, self.output) + self.assertFalse(self.output.exists()) + + +class ExclusiveOutput(unittest.TestCase): + def setUp(self): + self.scratch = tempfile.TemporaryDirectory() + self.addCleanup(self.scratch.cleanup) + self.root = Path(self.scratch.name) + self.source = self.root / "input archive" + self.output = self.root / "final archive" + self.source.write_bytes(b"generated archive fixture" * 1024) + + def publish(self): + return subprocess.run(["bash", "-c", 'set -euo pipefail; source "$1"; nightly_publish_archive "$2" "$3"', "test", str(HERE / "nightly-common.sh"), str(self.source), str(self.output)], capture_output=True, text=True, timeout=15) + + def test_success_copies_exact_bytes(self): + result = self.publish() + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(self.output.read_bytes(), self.source.read_bytes()) + + def test_existing_output_is_never_replaced(self): + self.output.write_bytes(b"existing artifact") + self.assertNotEqual(self.publish().returncode, 0) + self.assertEqual(self.output.read_bytes(), b"existing artifact") + + def test_missing_source_does_not_leave_a_fake_empty_artifact(self): + self.source.unlink() + self.assertNotEqual(self.publish().returncode, 0) + self.assertFalse(self.output.exists()) + + +if __name__ == "__main__": + unittest.main() diff --git a/packaging/nightly-archive.py b/packaging/nightly-archive.py new file mode 100755 index 000000000..cbbfa72a2 --- /dev/null +++ b/packaging/nightly-archive.py @@ -0,0 +1,132 @@ +#!/usr/bin/env python3 +"""Flat Linux archive policy, invoked from its private owned build cwd. + +The stage and archive must both remain under that independently chosen root. +No native build, platform signing, or malicious-same-UID sandbox is implied. +""" +import grp +import gzip +import os +import pathlib +import pwd +import re +import stat +import sys +import tarfile + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) +from nightly_paths import OwnedBuildRoot + +APP_DOCS = {"README.md", "LICENSE", "LICENSE-MIT", "LICENSE-APACHE", "COPYRIGHT", "NOTICE", "ATTRIBUTION.md"} +MAX_MEMBER_BYTES = 512 * 1024 * 1024 +MAX_TOTAL_BYTES = 1024 * 1024 * 1024 +MAX_MEMBERS = 128 + + +def notice(name): + return name in APP_DOCS or re.fullmatch(r"OFL-[A-Za-z0-9_.-]+\.txt", name) is not None + + +def checked_entries(root, stage): + entries = sorted(root.children(stage, MAX_MEMBERS), key=lambda item: item.name) + folded = set() + total = 0 + for entry in entries: + name = entry.name + if name not in {"designcraft", "designcraft-bin", "designcraft-nightly.png"} and not notice(name): + raise ValueError(f"unexpected nightly member: {name}") + if len(name.encode("utf-8")) > 100: + raise ValueError(f"nightly member must be a short regular file: {name}") + with root.reader(entry, MAX_MEMBER_BYTES) as stream: + total += os.fstat(stream.fileno()).st_size + if total > MAX_TOTAL_BYTES: + raise ValueError("nightly stage exceeds its read bound") + if name.casefold() in folded: + raise ValueError(f"case-colliding nightly member: {name}") + folded.add(name.casefold()) + required = {"designcraft", "designcraft-bin", "designcraft-nightly.png", "README.md", "LICENSE-MIT", "LICENSE-APACHE", "NOTICE"} + if not required.issubset({item.name for item in entries}): + raise ValueError("required GUI/icon/notices missing") + return entries + + +def member_info(stage_root, name, incoming): + """Header for one stage file, built from the file this run opened rather than from the archive. + + Members are flat names that resolve directly inside the stage they came from. + """ + if os.path.isabs(name) or os.path.basename(name) != name or name in ("", ".", ".."): + raise ValueError(f"nightly member name must be a flat file name: {name}") + destination = os.path.realpath(os.path.join(stage_root, name)) + if not destination.startswith(stage_root + os.sep) or os.path.dirname(destination) != stage_root: + raise ValueError(f"nightly member resolves outside its stage: {name}") + status = os.fstat(incoming.fileno()) + if not stat.S_ISREG(status.st_mode): + raise ValueError(f"nightly member must be a regular file: {name}") + # The same fields TarFile.gettarinfo records for a regular file. + # The header keeps the validated stage name, not the resolved one: a stage symlink must + # never rename a member or leave a required name out of the archive. + info = tarfile.TarInfo(name) + info.type = tarfile.REGTYPE + info.mode = stat.S_IMODE(status.st_mode) + info.uid, info.gid = status.st_uid, status.st_gid + info.size = status.st_size + info.mtime = status.st_mtime + try: + info.uname = pwd.getpwuid(status.st_uid).pw_name + except KeyError: + pass + try: + info.gname = grp.getgrgid(status.st_gid).gr_name + except KeyError: + pass + return info + + +def verify_headers(root, output): + # Bounded ordinary headers, not a transparent PAX/GNU-normalizing reader. + total = 0 + count = 0 + with root.reader(output, MAX_TOTAL_BYTES) as incoming, gzip.GzipFile(fileobj=incoming) as stream: + while True: + header = stream.read(512) + if header == b"\0" * 512: + break + if len(header) != 512 or header[156:157] not in {b"0", b"\0"}: + raise ValueError("non-ordinary TAR record was emitted") + size = int(header[124:136].rstrip(b"\0 ").lstrip(b" ") or b"0", 8) + count += 1 + total += size + if count > MAX_MEMBERS or size > MAX_MEMBER_BYTES or total > MAX_TOTAL_BYTES: + raise ValueError("archive exceeds its bounded member budget") + remaining = ((size + 511) // 512) * 512 + while remaining: + chunk = stream.read(min(remaining, 1024 * 1024)) + if not chunk: + raise ValueError("truncated TAR member") + remaining -= len(chunk) + + +def linux_archive(stage, output): + with OwnedBuildRoot() as root: + entries = checked_entries(root, stage) + stage_root = os.path.realpath(os.path.join(root.directory, stage)) + total = 0 + with root.create(output) as outgoing: + with tarfile.open(fileobj=outgoing, mode="w:gz", format=tarfile.USTAR_FORMAT) as archive: + for entry in entries: + with root.reader(entry, MAX_MEMBER_BYTES) as incoming: + info = member_info(stage_root, entry.name, incoming) + total += info.size + if info.size > MAX_MEMBER_BYTES or total > MAX_TOTAL_BYTES: + raise ValueError("nightly stage grew beyond its read bound") + archive.addfile(info, incoming) + outgoing.flush() + os.fsync(outgoing.fileno()) + verify_headers(root, output) + + +if __name__ == "__main__": + if len(sys.argv) != 4 or sys.argv[1] != "linux": + raise SystemExit("usage: nightly-archive.py linux STAGE OUTPUT (from owned private build cwd)") + linux_archive(pathlib.Path(sys.argv[2]), pathlib.Path(sys.argv[3])) diff --git a/packaging/nightly-common.sh b/packaging/nightly-common.sh new file mode 100755 index 000000000..9c524433e --- /dev/null +++ b/packaging/nightly-common.sh @@ -0,0 +1,95 @@ +# shellcheck shell=bash +# Shared setup for app-owned native nightly archives; stable packaging does not source this file. + +nightly_die() { printf 'error: %s\n' "$*" >&2; exit 2; } + +nightly_init() { + local os="$1" arch="$2" target="$3" date_digits + [[ "${DESIGNCRAFT_BUILD_CHANNEL:-}" == nightly-v1 ]] || nightly_die 'DESIGNCRAFT_BUILD_CHANNEL must be nightly-v1' + [[ "${DESIGNCRAFT_VERSION:-}" =~ ^[0-9]+\.[0-9]+\.[0-9]+-nightly\.[0-9]{8}\.[0-9]+\.[0-9]+\.g[0-9a-f]{12}$ ]] || nightly_die 'an exact prepared nightly version is required' + [[ "${DESIGNCRAFT_BUILD_SHA:-}" =~ ^[0-9a-f]{40}$ ]] || nightly_die 'an exact source commit is required' + [[ "${DESIGNCRAFT_VERSION##*.g}" == "${DESIGNCRAFT_BUILD_SHA:0:12}" ]] || nightly_die 'version/source commit mismatch' + [[ "${DESIGNCRAFT_BUILD_DATE:-}" =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2}$ ]] || nightly_die 'the original run-created UTC date is required' + date_digits="${DESIGNCRAFT_VERSION#*-nightly.}" + date_digits="${date_digits%%.*}" + [[ "${DESIGNCRAFT_BUILD_DATE//-/}" == "$date_digits" ]] || nightly_die 'version/original-run date mismatch' + [[ "${CARGO_TARGET_DIR:-}" == /* && "$CARGO_TARGET_DIR" != / ]] || nightly_die 'an absolute owned CARGO_TARGET_DIR base is required' + [[ "${DIST:-}" == /* && "$DIST" != / ]] || nightly_die 'an absolute DIST output directory is required' + [[ "/$CARGO_TARGET_DIR/" != *'/../'* && "/$DIST/" != *'/../'* ]] || nightly_die 'output paths must not contain parent traversal' + ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" + [[ "$(git -C "$ROOT" rev-parse HEAD)" == "$DESIGNCRAFT_BUILD_SHA" ]] || nightly_die 'prepared source is not the checked-out commit' + [[ -z "$(git -C "$ROOT" status --porcelain)" ]] || nightly_die 'nightly packaging requires the frozen clean source' + if [[ -n "${CRAFT_FONTS_DIR:-}" && ! -d "$CRAFT_FONTS_DIR/fonts" ]]; then + nightly_die 'declared CRAFT_FONTS_DIR has no fonts directory' + fi + # env.sh retains the established notice copier. Required values above prohibit its stable fallbacks. + . "$ROOT/packaging/env.sh" + export CARGO_TARGET_DIR="$CARGO_TARGET_DIR/nightly-v1/$os-$arch" + NIGHTLY_RUST_TARGET="$target" + mkdir -p "$CARGO_TARGET_DIR" + NIGHTLY_WORK="$(mktemp -d "$CARGO_TARGET_DIR/nightly-package.XXXXXX")" + trap 'rm -rf -- "$NIGHTLY_WORK"' EXIT +} + +# Compile only: the version query runs on the unpacked payload (Linux) or the signed bundle +# (macOS, packaging/macos/nightly-verify.sh). DesignCraft's GUI needs no optional features. +nightly_compile_gui() { + # The guard sits here as well as in the entrypoints: no caller may compile with signing material. + nightly_refuse_signing_env + (cd "$ROOT" && DESIGNCRAFT_BUILD_CHANNEL=nightly-v1 cargo build --release --locked -p designcraft --target "$NIGHTLY_RUST_TARGET") + NIGHTLY_GUI="$CARGO_TARGET_DIR/$NIGHTLY_RUST_TARGET/release/designcraft" + [[ -f "$NIGHTLY_GUI" && ! -L "$NIGHTLY_GUI" ]] || nightly_die 'the owned GUI build did not produce a regular executable' + [[ "$(git -C "$ROOT" rev-parse HEAD)" == "$DESIGNCRAFT_BUILD_SHA" && -z "$(git -C "$ROOT" status --porcelain)" ]] || nightly_die 'source changed during the build' +} + +nightly_build_gui() { + nightly_compile_gui + local actual + actual="$("$NIGHTLY_GUI" --version)" || nightly_die 'side-effect-free nightly version verification failed' + [[ "$actual" == "DesignCraft $VERSION (nightly-v1)" ]] || nightly_die 'the built version/flavor is not the prepared identity' + [[ "$(git -C "$ROOT" rev-parse HEAD)" == "$DESIGNCRAFT_BUILD_SHA" && -z "$(git -C "$ROOT" status --porcelain)" ]] || nightly_die 'source changed during the version query' +} + +# Signing material never reaches compilation (the Windows -CheckBuildEnvironment rule). +nightly_refuse_signing_env() { + local name + # The signing names release.yml passes, for every platform, and import-cert.sh's outputs. + for name in APPLE_CERTIFICATE APPLE_CERTIFICATE_PASSWORD KEYCHAIN_PASSWORD APPLE_ID APPLE_PASSWORD APPLE_TEAM_ID \ + MACOS_SIGN_IDENTITY MACOS_KEYCHAIN WINDOWS_CERTIFICATE WINDOWS_CERTIFICATE_PASSWORD AZURE_TENANT_ID AZURE_CLIENT_ID \ + AZURE_CLIENT_SECRET AZURE_SIGNING_ENDPOINT AZURE_SIGNING_ACCOUNT AZURE_CERT_PROFILE LINUX_SIGNING_KEY; do + [[ -z "${!name:-}" ]] || nightly_die "compilation must not receive signing configuration ($name); sign in the separate trusted step" + done +} + +# DesignCraft has no ATTRIBUTION.md of its own (its credits are the About window's), so the +# required app notices are the licence, the notice file and the readme; an ATTRIBUTION.md is copied +# when a checkout does have one. +nightly_copy_notices() { + local destination="$1" required + for required in README.md LICENSE-MIT LICENSE-APACHE NOTICE; do + [[ -f "$ROOT/$required" && ! -L "$ROOT/$required" ]] || nightly_die "missing regular app notice: $required" + done + copy_docs "$destination" +} + +nightly_publish_archive() { + # Exclusive creation: never replace an existing artifact, even if another writer raced the preflight. + python3 -I - "$1" "$2" <<'PY' +import os, shutil, sys +source, destination = sys.argv[1:] +created = False +try: + # Open the input first: a missing source must not leave an empty final artifact. + with open(source, 'rb') as incoming: + with open(destination, 'xb') as output: + created = True + shutil.copyfileobj(incoming, output, length=1024 * 1024) + output.flush() + os.fsync(output.fileno()) +except BaseException: + if created: + os.unlink(destination) + raise +PY + printf 'Nightly artifact: %s\n' "$2" +} diff --git a/packaging/nightly-launcher-tests.py b/packaging/nightly-launcher-tests.py new file mode 100644 index 000000000..ed8c3d40a --- /dev/null +++ b/packaging/nightly-launcher-tests.py @@ -0,0 +1,208 @@ +#!/usr/bin/env python3 +"""Synthetic contract for the Linux nightly launchers: no native build or executable launch. + +The unpacked tar's `designcraft` is craft-common-actions's canonical launcher template +(scripts/nightly-launcher.sh.in) rendered for this app, which the shared nightly producer accepts +byte for byte; `TarTemplate` pins its exact argv. Every distro format (deb/rpm wrapper, AppImage +AppRun, Arch launcher, Flatpak wrapper) must start the compiled nightly-v1 flavor the Launcher's +way, because the app refuses a DESIGNCRAFT_CONFIG_DIR override and refuses a bare start as stable. +""" +import os +import re +import shutil +import subprocess +import tempfile +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +LINUX = ROOT / "packaging/linux" +CHANNEL = ROOT / "crates/ui-egui/src/channel.rs" + +EXEC = 'exec "$real_bin" --launch-profile nightly-v1 --profile-root "$profile_root" -- "$@"' +PROFILE_ROOT = 'profile_root="${XDG_DATA_HOME:-${HOME:?HOME is required}/.local/share}/designcraft-nightly"' +PASSTHROUGH = 'if [ "${1:-}" = "--launch-profile" ] || [ "${1:-}" = "--profile-root" ]; then' + + +def body(path, marker): + lines = (ROOT / path).read_text(encoding="utf-8").splitlines() + opening = [index for index, line in enumerate(lines) if f"<<'{marker}'" in line] + if len(opening) != 1: + raise AssertionError(f"{path}: expected exactly one <<'{marker}' here-document") + end = lines.index(marker, opening[0] + 1) + return lines[opening[0] + 1:end] + + +def launchers(): + """(label, the launcher's own lines) for every Linux nightly start path.""" + return { + "deb/rpm wrapper": body("packaging/linux/package.sh", "WRAPPER"), + "AppImage AppRun": body("packaging/linux/package.sh", "APPRUN"), + "Arch launcher": (LINUX / "nightly-arch-launch.sh").read_text(encoding="utf-8").splitlines(), + "Flatpak wrapper": body("packaging/linux/flatpak-bundle.sh", "WRAPPER"), + } + + +TAR_LAUNCHER = LINUX / "nightly-launch.sh" +TAR_IDENTITY = "ai.storyteller.designcraft.nightly" +RECORDER = '#!/bin/sh\nfor arg in "$@"; do printf "<%s>\\n" "$arg"; done\n' + + +def constant(name): + source = CHANNEL.read_text(encoding="utf-8") + found = re.search(r'pub const ' + name + r': &str = "([^"]+)";', source) + if found is None: + raise AssertionError(f"channel.rs has no {name}") + return found.group(1) + + +class LinuxLaunchers(unittest.TestCase): + def test_every_format_execs_the_launcher_pair(self): + for label, lines in launchers().items(): + with self.subTest(launcher=label): + self.assertIn(EXEC, lines) + self.assertEqual(sum(line == EXEC for line in lines), 1, "one start path per format") + + def test_no_format_redirects_the_profile_through_the_stable_override(self): + for label, lines in launchers().items(): + with self.subTest(launcher=label): + redirected = [line for line in lines if not line.lstrip().startswith("#") and re.match(r"\s*(export\s+)?DESIGNCRAFT_CONFIG_DIR=", line)] + self.assertEqual(redirected, [], "a non-empty override is refused by the app") + + def test_the_version_query_is_answered_before_the_profile_prelude(self): + for label, lines in launchers().items(): + with self.subTest(launcher=label): + query = next(index for index, line in enumerate(lines) if '= "--version"' in line and '= "-V"' in line) + self.assertLess(query, lines.index(EXEC), "a headless runner asks for the version first") + + def test_every_format_uses_the_same_absolute_channel_profile(self): + for label, lines in launchers().items(): + with self.subTest(launcher=label): + self.assertIn(PROFILE_ROOT, lines) + + def test_the_nightly_window_id_is_the_packaged_desktop_class(self): + app_id = constant("NIGHTLY_APP_ID") + package = (LINUX / "package.sh").read_text(encoding="utf-8") + flatpak = (LINUX / "flatpak-bundle.sh").read_text(encoding="utf-8") + self.assertIn(f"StartupWMClass={app_id}", package) + self.assertIn(f"StartupWMClass={app_id}", flatpak) + # The stable entry keeps its own class, so the two windows never share one. + stable = (LINUX / "ai.storyteller.designcraft.desktop").read_text(encoding="utf-8") + self.assertIn(f"StartupWMClass={constant('APP_ID')}\n", stable) + + def test_the_flatpak_bundle_id_is_the_nightly_package_id(self): + flatpak = (LINUX / "flatpak-bundle.sh").read_text(encoding="utf-8") + self.assertIn('FLATPAK_ID="$APP_ID.nightly"', flatpak) + self.assertEqual(f"{constant('APP_ID')}.nightly", constant("NIGHTLY_PACKAGE_ID")) + + def test_the_tar_archive_carries_the_launcher_beside_its_binary(self): + policy = (ROOT / "packaging/nightly-archive.py").read_text(encoding="utf-8") + self.assertIn('{"designcraft", "designcraft-bin", "designcraft-nightly.png"}', policy) + self.assertIn('"designcraft-bin", "designcraft-nightly.png", "README.md"', policy) + nightly = (LINUX / "nightly.sh").read_text(encoding="utf-8") + self.assertIn('cp "$NIGHTLY_GUI" "$STAGE/designcraft-bin"', nightly) + self.assertIn('install -m755 "$ROOT/packaging/linux/nightly-launch.sh" "$STAGE/designcraft"', nightly, + "the tar installs the canonical template, not its own copy of the protocol") + + def test_every_format_passes_an_existing_profile_pair_through(self): + for label, lines in launchers().items(): + with self.subTest(launcher=label): + self.assertEqual(sum(line == PASSTHROUGH for line in lines), 1, "a caller's own profile pair is never doubled") + +class TarTemplate(unittest.TestCase): + """The plain nightly tar's launcher: the canonical shared template, byte for byte.""" + + def setUp(self): + scratch = tempfile.TemporaryDirectory() + self.addCleanup(scratch.cleanup) + self.root = Path(scratch.name).resolve() + self.tree = self.root / "unpacked" + self.tree.mkdir() + self.program = self.tree / "designcraft-bin" + self.program.write_text(RECORDER, encoding="utf-8") + self.program.chmod(0o755) + self.command = self.tree / "designcraft" + shutil.copyfile(TAR_LAUNCHER, self.command) + self.command.chmod(0o755) + self.home = self.root / "home with space" + self.home.mkdir() + + def execute(self, *arguments, env=None): + environment = {"HOME": str(self.home), "PATH": "/usr/bin:/bin", **(env or {})} + environment = {key: value for key, value in environment.items() if value is not None} + return subprocess.run([str(self.command), *arguments], cwd="/", env=environment, + capture_output=True, text=True, timeout=15) + + def argv(self, *arguments, env=None): + run = self.execute(*arguments, env=env) + self.assertEqual(run.returncode, 0, run.stderr) + return run.stdout.splitlines() + + def profile(self, data_home=None): + return str(Path(data_home or self.home / ".local/share") / TAR_IDENTITY) + + def test_the_file_is_the_rendered_template(self): + source = TAR_LAUNCHER.read_text(encoding="utf-8") + self.assertIn("# Nightly launcher generated by craft-common-actions scripts/nightly-launcher.sh.in.", source) + self.assertIn('target="$dir/designcraft-bin"', source) + self.assertIn(' --launch-profile) exec "$target" "$@" ;;', source) + self.assertIn(f'profile_root="${{XDG_DATA_HOME:-$HOME/.local/share}}/{TAR_IDENTITY}"', source) + for placeholder in ("@BINARY@", "@APP_ID@"): + self.assertNotIn(placeholder, source) + + def test_a_launch_adds_the_profile_pair_and_the_files_follow_the_delimiter(self): + files = ["doc with spaces.dc", "--other-name.dc"] + self.assertEqual(self.argv(*files), + ["<--launch-profile>", "", "<--profile-root>", f"<{self.profile()}>", "<-->", + *[f"<{name}>" for name in files]]) + self.assertEqual(self.argv(), + ["<--launch-profile>", "", "<--profile-root>", f"<{self.profile()}>", "<-->"]) + + def test_the_profile_follows_xdg_data_home(self): + data_home = self.root / "xdg with space" + self.assertEqual(self.argv("doc.dc", env={"XDG_DATA_HOME": str(data_home)})[3], + f"<{self.profile(data_home)}>") + + def test_both_version_spellings_ask_for_one_plain_version(self): + for flag in ("--version", "-V"): + with self.subTest(flag=flag): + self.assertEqual(self.argv(flag), + ["<--launch-profile>", "", "<--profile-root>", + f"<{self.profile()}>", "<--version>"]) + + def test_the_launchers_own_profile_line_passes_through_untouched(self): + # The ArtCraft Launcher starts the tar's entry point with its own profile pair and per-install + # root; the template hands that line to the GUI unchanged. + managed = "/launcher/root/designcraft" + for supplied in (["--launch-profile", "nightly-v1", "--profile-root", managed, "--"], + ["--launch-profile", "nightly-v1", "--profile-root", managed, "--", "doc.dc"], + ["--launch-profile"]): + with self.subTest(supplied=supplied): + self.assertEqual(self.argv(*supplied), [f"<{name}>" for name in supplied]) + + def test_every_other_line_still_gets_the_templates_own_profile(self): + # Only a line that opens with `--launch-profile` exactly is the Launcher's. + for arguments in (["--profile-root", "/launcher/root/designcraft", "--"], + ["--launch-profile=nightly-v1"], ["--help"]): + with self.subTest(arguments=arguments): + self.assertEqual(self.argv(*arguments), + ["<--launch-profile>", "", "<--profile-root>", f"<{self.profile()}>", "<-->", + *[f"<{name}>" for name in arguments]]) + + def test_it_starts_only_the_binary_beside_it(self): + self.program.unlink() + for arguments in ((), ("--version",), ("doc.dc",)): + with self.subTest(arguments=arguments): + run = self.execute(*arguments) + self.assertNotEqual(run.returncode, 0, run.stdout) + self.assertEqual(run.stdout, "") + + def test_no_data_folder_means_no_launch(self): + run = self.execute("doc.dc", env={"HOME": None}) + self.assertNotEqual(run.returncode, 0) + self.assertEqual(run.stdout, "") + self.assertIn("HOME", run.stderr) + + +if __name__ == "__main__": + unittest.main() diff --git a/packaging/nightly-release-tests.py b/packaging/nightly-release-tests.py new file mode 100755 index 000000000..8cb5e9a37 --- /dev/null +++ b/packaging/nightly-release-tests.py @@ -0,0 +1,732 @@ +#!/usr/bin/env python3 +"""Local nightly workflow and signing-policy contract tests for DesignCraft.""" +import copy +import json +from pathlib import Path +import re +import unittest + +ROOT = Path(__file__).resolve().parents[1] +INSTALLED_POLICY = ROOT / ".github/nightly-signing-policy.json" + +# The dedicated signer branch the installed policy names and the signer guard requires. +SIGNER_BRANCH = "nightly-signer" + +NIGHTLY_PLATFORMS = ("windows-x86_64", "linux-x86_64", "macos-aarch64") +NIGHTLY_TRUST = { + "windows-x86_64": ( + "publisher_subject", + "CN=Learning Machines Inc, O=Learning Machines Inc, L=Atlanta, S=Georgia, C=US", + ), + "linux-x86_64": ("fingerprint", "2B76741B414AAD6CD33E631213A005C0B9D7C3ED"), + "macos-aarch64": ("apple_team_id", "DJ6XS33FX8"), +} + +# Mirrors the storytold release-managers team (id 19837241) minus echelon-robot. +# Update by PR, in the caller and the policy, when the team changes. +RELEASE_MANAGERS = ["bflatastic", "dylanmtaylor", "echelon", "FredApps", "skylartaylor"] + + +def assert_nightly_serialization(source): + """Fail closed unless this app's plain root concurrency block retains its contract.""" + lines = source.splitlines() + roots = [index for index, line in enumerate(lines) if line.startswith("concurrency:")] + if len(roots) != 1 or lines[roots[0]] != "concurrency:": + raise ValueError("one plain root concurrency block is required") + values = {} + for line in lines[roots[0] + 1:]: + if not line.strip() or line.lstrip().startswith("#"): + continue + if not line[0].isspace(): + break + row = re.fullmatch(r" (group|cancel-in-progress): ([^#]+?)(?: +#.*)?", line) + if row is None or row[1] in values: + raise ValueError("malformed or duplicate nightly concurrency entry") + values[row[1]] = row[2].rstrip() + if values != { + "group": "designcraft-nightly-release", + "cancel-in-progress": "false", + }: + raise ValueError("nightly serialization must use its stable group and no cancellation") + + +def job_conditions(jobs): + """Each job-level `if:` as (block indicator or None, the whole expression YAML would read).""" + lines = jobs.splitlines() + found = [] + for index, line in enumerate(lines): + head = re.fullmatch(r" if:(?: (.*))?", line) + if head is None: + continue + value = (head[1] or "").strip() + continuation = [] + for follow in lines[index + 1:]: + if follow.strip() and len(follow) - len(follow.lstrip(" ")) <= 4: + break + continuation.append(follow.strip()) + indicator = value if re.fullmatch(r"[>|][+-]?", value) else None + parts = continuation if indicator else [value] + continuation + found.append((indicator, " ".join(part for part in parts if part))) + return found + + +def producer_platforms(source): + """Read the one producer job's literal platform list; a narrow source guard, not YAML.""" + rows = re.findall(r"(?m)^ platforms: (.*)$", source) + if len(rows) != 1: + raise ValueError("exactly one producer platform list is required") + literal = re.fullmatch(r"'(\[[^']*\])'", rows[0]) + if literal is None: + raise ValueError("the platform list must be one single-quoted literal") + platforms = json.loads(literal[1]) + if not isinstance(platforms, list) or json.dumps(platforms, separators=(",", ":")) != literal[1]: + raise ValueError("the platform list must be compact JSON") + if len(set(platforms)) != len(platforms) or not set(platforms) <= set(NIGHTLY_PLATFORMS): + raise ValueError("platforms must be distinct known nightly targets") + if "windows-x86_64" not in platforms: + raise ValueError("the Windows row stays in the producer") + return platforms + + +def reviewed_manual_actors(caller_source, policy): + """The one reviewed manual-actor list, identical in the producer caller and the policy.""" + rows = re.findall(r"(?m)^ manual-actors: '(\[[^']*\])'$", caller_source) + if len(rows) != 1: + raise ValueError("exactly one literal manual-actors list is required") + caller = json.loads(rows[0]) + if caller != policy["manual_actors"]: + raise ValueError("caller and policy must grant the same actors in the same order") + if caller != RELEASE_MANAGERS: + raise ValueError("manual actors must be exactly the reviewed release managers") + if caller != sorted(caller, key=str.lower) or len({login.lower() for login in caller}) != len(caller): + raise ValueError("manual actors must be distinct and sorted case-insensitively") + if set(caller) & {login for login in policy["automatic_signer_actors"]}: + raise ValueError("manual and automatic actors overlap") + return caller + + +def caller_pin(name): + return re.findall( + r"(?m)^ tooling-revision: ([0-9a-f]{40})$", + (ROOT / ".github/workflows" / name).read_text(), + )[0] + + +class TrustedSourcePreparation(unittest.TestCase): + def test_one_producer_and_one_signer_job_carry_every_platform(self): + for name, job in (("nightly.yml", "unsigned"), ("nightly-sign.yml", "release")): + jobs = (ROOT / ".github/workflows" / name).read_text().split("\njobs:\n", 1)[1] + with self.subTest(workflow=name): + self.assertEqual( + re.findall(r"(?m)^ ([^\s#][^:]*):", jobs), + [job], + "a platform is a list entry, not a separately activatable job", + ) + signer = (ROOT / ".github/workflows/nightly-sign.yml").read_text() + self.assertNotRegex(signer, r"(?m)^\s*platforms?:", "the release policy, not the caller, admits platforms") + + def test_malformed_or_narrowed_platform_lists_are_rejected(self): + source = (ROOT / ".github/workflows/nightly.yml").read_text() + current = 'platforms: \'["windows-x86_64","linux-x86_64","macos-aarch64"]\'' + self.assertIn(current, source) + for new in ( + 'platforms: \'["linux-x86_64"]\'', + 'platforms: \'["linux-x86_64","macos-aarch64"]\'', + 'platforms: \'["windows-x86_64","linux-x86_64","linux-x86_64"]\'', + 'platforms: \'["windows-x86_64","macos-x86_64"]\'', + 'platforms: \'["windows-x86_64","linux-arm64"]\'', + 'platforms: \'["windows-x86_64", "linux-x86_64"]\'', + 'platforms: ["windows-x86_64","linux-x86_64"]', + "platforms: ${{ vars.NIGHTLY_PLATFORMS }}", + 'platforms: \'{"windows-x86_64":1}\'', + current + "\n " + current, + ): + with self.subTest(change=new), self.assertRaises(ValueError): + producer_platforms(source.replace(current, new)) + with self.assertRaises(ValueError): + producer_platforms(source.replace(" " + current + "\n", "")) + + def test_continuation_lines_of_any_scalar_form_reach_the_guard_checks(self): + for name in ("nightly.yml", "nightly-sign.yml"): + source = (ROOT / ".github/workflows" / name).read_text() + expected = NightlyEnabledCallers.GUARDS[name] + guard = re.search(r"(?m)^ if: >-\n(?: [^\n]*\n)+", source)[0] + for replacement in (guard + " || true\n", " if: " + expected + "\n || true\n"): + jobs = source.replace(guard, replacement).split("\njobs:\n", 1)[1] + with self.subTest(workflow=name, replacement=replacement[-30:]): + (indicator, expression), = job_conditions(jobs) + self.assertFalse(indicator == ">-" and " ".join(expression.split()) == expected) + + def test_no_nightly_schedule_is_registered(self): + for name, event in (("nightly.yml", "workflow_dispatch"), ("nightly-sign.yml", "workflow_dispatch")): + source = (ROOT / ".github/workflows" / name).read_text() + events = source.split("\non:\n", 1)[1].split("\npermissions:", 1)[0] + triggers = [ + line + for line in events.splitlines() + if line.startswith(" ") + and not line.startswith(" ") + and line.strip() + and not line.lstrip().startswith("#") + ] + with self.subTest(workflow=name): + self.assertEqual(triggers, [f" {event}:"], "schedule/activation needs explicit review") + + def test_signer_serialization_contract_is_enforced(self): + assert_nightly_serialization((ROOT / ".github/workflows/nightly-sign.yml").read_text()) + + def test_weakened_or_malformed_serialization_is_rejected(self): + source = (ROOT / ".github/workflows/nightly-sign.yml").read_text() + for old, new in ( + ("cancel-in-progress: false", "cancel-in-progress: false\n queue: max"), + ("cancel-in-progress: false", "cancel-in-progress: true"), + ("cancel-in-progress: false", "cancel-in-progress: ${{ github.event_name == 'push' }}"), + ("cancel-in-progress: false\n", ""), + ("group: designcraft-nightly-release", "group: ${{ github.run_id }}"), + ("group: designcraft-nightly-release", "group: release-${{ github.ref }}"), + ("concurrency:\n", "concurrency: ${{ github.run_id }}\n"), + ("concurrency:\n", " concurrency:\n"), + ): + with self.subTest(change=new), self.assertRaises(ValueError): + assert_nightly_serialization(source.replace(old, new)) + + def test_no_cache_actions_or_cache_setup_options_in_app_trusted_closure(self): + for name in ("nightly.yml", "nightly-sign.yml"): + source = (ROOT / ".github/workflows" / name).read_text() + executable = "\n".join(line for line in source.splitlines() if not line.lstrip().startswith("#")) + with self.subTest(workflow=name): + self.assertNotRegex(executable, r"(?im)^\s*(?:-\s*)?uses:\s*[^\n]*cache") + self.assertNotRegex(executable, r"(?im)^\s*[^\s:#]*cache[^\s:#]*:") + self.assertNotRegex(executable, r"(?im)^\s*(?:environment|secrets):") + self.assertNotIn("secrets.", executable) + + +class NightlyTrustAnchors(unittest.TestCase): + """The public stable identities each platform's signed nightly must carry (all three platforms).""" + + def setUp(self): + self.policy = json.loads(INSTALLED_POLICY.read_text()) + + def test_each_platform_row_names_its_fixed_artifact_kind_and_stable_identity(self): + self.assertEqual(set(self.policy["platforms"]), set(NIGHTLY_TRUST)) + for platform, (field, value) in NIGHTLY_TRUST.items(): + row = self.policy["platforms"][platform] + with self.subTest(platform=platform): + self.assertEqual( + row["unsigned_artifact_name"], + f"nightly-unsigned-{platform}", + "the artifact kind is fixed by platform, never a caller pattern", + ) + self.assertEqual(row["trust"], {field: value}, "trust must be stable's public identity") + + def test_trust_values_have_the_shapes_the_shared_signer_accepts(self): + rows = self.policy["platforms"] + self.assertRegex(rows["macos-aarch64"]["trust"]["apple_team_id"], r"^[A-Z0-9]{10}$") + self.assertRegex(rows["linux-x86_64"]["trust"]["fingerprint"], r"^[0-9A-F]{40}$") + subject = rows["windows-x86_64"]["trust"]["publisher_subject"] + self.assertTrue(0 < len(subject) <= 1024 and not set(subject) & {"\r", "\n", "\0"}) + + def test_both_callers_use_one_shared_pin_in_uses_and_tooling_revision(self): + pins = set() + for name, callee in (("nightly.yml", "nightly-unsigned.yml"), ("nightly-sign.yml", "nightly-release.yml")): + source = (ROOT / ".github/workflows" / name).read_text() + uses = re.findall( + r"(?m)^ uses: storytold/craft-common-actions/\.github/workflows/" + + re.escape(callee) + + r"@(\S+)$", + source, + ) + tooling = re.findall(r"(?m)^ tooling-revision: (\S+)$", source) + with self.subTest(workflow=name): + self.assertEqual(len(uses), 1) + self.assertEqual(tooling, uses, "the defining workflow SHA and tooling input must match") + pins.update(uses) + self.assertEqual(len(pins), 1, "producer and signer must pin the same shared commit") + self.assertRegex(pins.pop(), r"^[0-9a-f]{40}$", "pin a full immutable commit, never a branch or placeholder") + + +class NightlyEnabledCallers(unittest.TestCase): + """Producer and signer run only in their exact context, for the reviewed manual actors.""" + + GUARDS = { + "nightly.yml": ( + "github.repository == 'storytold/designcraft' && github.ref == 'refs/heads/main' && " + "github.ref_type == 'branch' && (github.event_name == 'schedule' || " + "github.event_name == 'workflow_dispatch')" + ), + "nightly-sign.yml": ( + "github.repository == 'storytold/designcraft' && github.event_name == 'workflow_dispatch' && " + "github.ref == 'refs/heads/" + SIGNER_BRANCH + "' && github.ref_type == 'branch'" + ), + } + + def test_enabled_jobs_keep_exact_context_guards(self): + for name, expected in self.GUARDS.items(): + jobs = (ROOT / ".github/workflows" / name).read_text().split("\njobs:\n", 1)[1] + guards = job_conditions(jobs) + with self.subTest(workflow=name): + self.assertEqual(len(guards), 1) + indicator, expression = guards[0] + self.assertEqual(indicator, ">-") + self.assertEqual(" ".join(expression.split()), expected, "guards may only change with review") + + def test_manual_actors_are_the_release_managers_in_caller_and_policy(self): + source = (ROOT / ".github/workflows/nightly.yml").read_text() + policy = json.loads(INSTALLED_POLICY.read_text()) + self.assertEqual(reviewed_manual_actors(source, policy), RELEASE_MANAGERS) + self.assertEqual(policy["automatic_signer_actors"], [], "no automatic signer without a schedule") + + def test_an_actor_outside_the_release_managers_is_refused(self): + source = (ROOT / ".github/workflows/nightly.yml").read_text() + policy = json.loads(INSTALLED_POLICY.read_text()) + caller = json.dumps(RELEASE_MANAGERS, separators=(",", ":")) + widened = sorted(RELEASE_MANAGERS + ["echelon-robot"], key=str.lower) + for change in ("caller", "policy", "both", "order", "case"): + mutated_source, mutated_policy = source, copy.deepcopy(policy) + if change in ("caller", "both"): + mutated_source = source.replace(caller, json.dumps(widened, separators=(",", ":"))) + if change in ("policy", "both"): + mutated_policy["manual_actors"] = widened + if change == "order": + mutated_policy["manual_actors"] = list(reversed(RELEASE_MANAGERS)) + if change == "case": + mutated_policy["manual_actors"] = [login.lower() for login in RELEASE_MANAGERS] + with self.subTest(change=change), self.assertRaises(ValueError): + reviewed_manual_actors(mutated_source, mutated_policy) + + +class NightlyInstalledPolicy(unittest.TestCase): + """The installed v3 policy matches the callers, the repository and its documented sources.""" + + def setUp(self): + self.assertFalse(INSTALLED_POLICY.is_symlink()) + self.policy = json.loads(INSTALLED_POLICY.read_text()) + + def test_exact_v3_fields_and_repository_identity(self): + expected = { + "schema", + "repository", + "repository_id", + "producer_workflow_id", + "producer_workflow_path", + "producer_tooling_revision", + "producer_workflow_ref", + "signer_workflow_path", + "signer_tooling_revision", + "release_branch", + "manual_actors", + "automatic_signer_actors", + "max_age_seconds", + "candidate_policy", + "max_artifact_bytes", + "platforms", + } + self.assertEqual(set(self.policy), expected) + self.assertEqual(self.policy["schema"], "craft-nightly-release-policy/v3") + self.assertEqual(self.policy["repository"], "storytold/designcraft") + self.assertEqual(self.policy["release_branch"], SIGNER_BRANCH, "the signer runs on its dedicated branch") + # Both read from the GitHub API (the repository and nightly.yml's registration on main). + for key in ("repository_id", "producer_workflow_id"): + with self.subTest(key=key): + self.assertIs(type(self.policy[key]), int) + self.assertGreater(self.policy[key], 0) + self.assertNotEqual(self.policy["producer_workflow_id"], + self.policy["candidate_policy"]["required_workflows"][0]["workflow_id"], + "the producer is not its own quality workflow") + + def test_paths_and_tooling_match_the_callers(self): + pin = caller_pin("nightly.yml") + self.assertEqual(caller_pin("nightly-sign.yml"), pin) + self.assertEqual(self.policy["producer_workflow_path"], ".github/workflows/nightly.yml") + self.assertEqual(self.policy["signer_workflow_path"], ".github/workflows/nightly-sign.yml") + self.assertEqual(self.policy["producer_tooling_revision"], pin) + self.assertEqual(self.policy["signer_tooling_revision"], pin) + self.assertEqual( + self.policy["producer_workflow_ref"], + "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@" + pin, + ) + + def test_platforms_equal_the_producer(self): + built = producer_platforms((ROOT / ".github/workflows/nightly.yml").read_text()) + self.assertEqual(built, list(NIGHTLY_PLATFORMS)) + self.assertEqual(set(self.policy["platforms"]), set(built)) + + def test_bounds(self): + self.assertIs(type(self.policy["max_age_seconds"]), int) + self.assertTrue(0 < self.policy["max_age_seconds"] <= 604800) + self.assertIs(type(self.policy["max_artifact_bytes"]), int) + self.assertTrue(0 < self.policy["max_artifact_bytes"] <= 16 * 1024**3) + + def test_candidate_workflows_run_on_every_main_push(self): + candidate = self.policy["candidate_policy"] + self.assertEqual( + set(candidate), + {"schema", "epoch", "repository", "branch", "required_workflows", "sonar"}, + ) + self.assertEqual(candidate["schema"], "craft-nightly-candidate-policy/v3") + self.assertEqual((candidate["repository"], candidate["branch"]), ("storytold/designcraft", "main")) + self.assertTrue(isinstance(candidate["epoch"], str) and 0 < len(candidate["epoch"]) <= 128) + rows = candidate["required_workflows"] + self.assertTrue(rows) + for row in rows: + with self.subTest(workflow=row["workflow_path"]): + self.assertEqual(set(row), {"workflow_id", "workflow_path", "jobs"}) + self.assertIs(type(row["workflow_id"]), int) + self.assertNotEqual(row["workflow_path"], self.policy["producer_workflow_path"]) + source = (ROOT / row["workflow_path"]).read_text() + push = re.search(r"(?m)^ push:\n((?: .*\n)+)", source) + self.assertIsNotNone(push, "a required workflow must run on main pushes") + self.assertIn(" branches: [main]\n", push[1]) + self.assertNotRegex(push[1], r"paths", "a path filter would leave candidates without a run") + names = [job["name"] for job in row["jobs"]] + self.assertEqual(len(names), len(set(names))) + for job in row["jobs"]: + self.assertEqual(set(job), {"name", "app_id", "applicability"}) + self.assertEqual((job["app_id"], job["applicability"]), (15368, "required")) + + def test_sonar_identity_and_reviewed_scope(self): + sonar = self.policy["candidate_policy"]["sonar"] + properties = dict( + line.split("=", 1) + for line in (ROOT / "sonar-project.properties").read_text().splitlines() + if line and not line.startswith("#") + ) + self.assertEqual(sonar["organization"], properties["sonar.organization"]) + self.assertEqual(sonar["project"], properties["sonar.projectKey"]) + self.assertEqual((sonar["app_id"], sonar["check_name"]), (12526, "SonarCloud Code Analysis")) + self.assertEqual( + sonar["details_url"], + "https://sonarcloud.io/dashboard?id=" + sonar["project"] + "&branch=main", + ) + accepted = { + "bugs": "BUG", + "vulnerabilities": "VULNERABILITY", + "code_smells": "CODE_SMELL", + "security_rating": "VULNERABILITY", + "new_security_rating": "VULNERABILITY", + } + self.assertEqual({accepted[c["metric"]] for c in sonar["accepted_conditions"]}, set(sonar["issue_types"])) + metrics = [c["metric"] for c in sonar["accepted_conditions"] + sonar["required_conditions"]] + self.assertEqual(len(metrics), len(set(metrics))) + keys = [item["key"] for item in sonar["debt"]] + self.assertEqual(len(keys), len(set(keys))) + for item in sonar["debt"]: + with self.subTest(issue=item["key"]): + self.assertEqual(set(item), {"key", "rule", "component", "type", "severity", "hash"}) + self.assertTrue(item["component"].startswith(sonar["project"] + ":")) + self.assertIn(item["type"], sonar["issue_types"]) + self.assertRegex(item["hash"], r"^[0-9a-f]{32}$") + + def test_sonar_policy_keeps_the_shared_candidate_contract(self): + """The Sonar shape craft-common-actions' candidate contract() admits, refused here first. + + An empty issue scope, an accepted condition outside the reviewed issue types, a metric in both + lists, a missing live gate condition or a widened security bound is refused at admission, so + this suite must catch it before a nightly run can. `debt` stays empty, so any unresolved + vulnerability on main is still refused; accepting the new-code rating only records the + reviewed A threshold instead of demanding a clean rating the live gate does not. + """ + sonar = self.policy["candidate_policy"]["sonar"] + accepted = {"bugs": "BUG", "vulnerabilities": "VULNERABILITY", "code_smells": "CODE_SMELL", + "security_rating": "VULNERABILITY", "new_security_rating": "VULNERABILITY"} + gate = {"new_reliability_rating", "new_security_rating", "new_maintainability_rating", + "new_coverage", "new_duplicated_lines_density", "new_security_hotspots_reviewed"} + self.assertTrue(sonar["issue_types"], "an empty issue scope is refused as unreviewed") + self.assertEqual(len(sonar["issue_types"]), len(set(sonar["issue_types"]))) + metrics = {} + for field in ("accepted_conditions", "required_conditions"): + for condition in sonar[field]: + with self.subTest(field=field, metric=condition.get("metric")): + expected = {"metric", "comparator", "error_threshold"} + if field == "accepted_conditions": + expected.add("maximum") + self.assertEqual(set(condition), expected) + self.assertNotIn(condition["metric"], metrics, "one condition per gate metric") + metrics[condition["metric"]] = condition + self.assertIn(condition["comparator"], ("GT", "LT")) + self.assertRegex(condition["error_threshold"], r"^(?:0|[1-9][0-9]*)(?:\.[0-9]+)?$") + if field != "accepted_conditions": + continue + self.assertIn(condition["metric"], accepted, "an accepted metric outside the reviewed map") + self.assertIn(accepted[condition["metric"]], sonar["issue_types"], + "an accepted failure must lie inside the reviewed issue scope") + self.assertEqual(condition["comparator"], "GT") + self.assertRegex(condition["maximum"], r"^(?:0|[1-9][0-9]*)(?:\.[0-9]+)?$") + maximum = float(condition["maximum"]) + if condition["metric"] in ("security_rating", "new_security_rating"): + self.assertEqual(int(maximum), maximum, "the A..E bound is a whole rating") + self.assertTrue(1 <= maximum <= 5, "the security bound stays A..E") + self.assertEqual(condition["error_threshold"], "1", "the reviewed A threshold stays") + else: + self.assertLessEqual(maximum, len(sonar["debt"]), "accepted failures exceed the reviewed debt") + self.assertEqual({accepted[c["metric"]] for c in sonar["accepted_conditions"]}, set(sonar["issue_types"]), + "accepted conditions and reviewed issue types must cover the same scope") + self.assertEqual(set(metrics), gate, "every live gate condition stays gated exactly once") + + +SHARED = "storytold/craft-common-actions/.github/workflows/" +# App workflows reviewed to call the shared stable release.yml. That callee must carry the +# stable-only environment guard (dry runs and non-release refs bind no environment); the +# nightly-signer settings scan checks the resolved callee before creating or advancing the branch. +REVIEWED_STABLE_RELEASE_CALLERS = {"release.yml"} + + +def app_workflows(): + return {path.name: path.read_text() for path in sorted((ROOT / ".github/workflows").glob("*.y*ml"))} + + +WORKFLOW_KEY = re.compile(r'''("(?:[^"\\]|\\.)*"|'(?:[^']|'')*'|[^\s'"#{}\[\],:&*!|>%@`?-][^:#,{}]*?|-[^\s:#][^:#,{}]*?)\s*:(?:\s+(.*))?$''') + + +def _workflow_key(text): + if text.startswith('"'): + return None if "\\" in text else text[1:-1] + if text.startswith("'"): + return text[1:-1].replace("''", "'") + return text + + +def _workflow_value(text): + """A one-line scalar value without its comment and quotes; None when escaped or unterminated.""" + text = text.strip() + if text.startswith('"'): + quoted = re.match(r'"((?:[^"\\]|\\.)*)"\s*(?:#.*)?$', text) + return None if quoted is None or "\\" in quoted.group(1) else quoted.group(1) + if text.startswith("'"): + quoted = re.match(r"'((?:[^']|'')*)'\s*(?:#.*)?$", text) + return None if quoted is None else quoted.group(1).replace("''", "'") + return re.split(r"\s+#", text, maxsplit=1)[0].strip() + + +def _strip_comment(text): + """(text without its comment, unterminated) using a quote-aware scan. + + As in YAML, a quote opens a quoted scalar only where a scalar starts (line start or after + `:`, `-`, `,`, `{` or `[`), and a `#` starts a comment only outside quotes, at the start or + after whitespace. + """ + quote, index = None, 0 + while index < len(text): + char = text[index] + if quote == '"': + if char == "\\": + index += 2 + continue + if char == '"': + quote = None + elif quote == "'": + if char == "'": + if text[index + 1:index + 2] == "'": + index += 2 + continue + quote = None + elif char in "\"'" and text[:index].rstrip()[-1:] in ("", ":", "-", ",", "{", "["): + quote = char + elif char == "#" and (index == 0 or text[index - 1] in " \t"): + return text[:index].rstrip(), False + index += 1 + return text.rstrip(), quote is not None + + +FLOW_QUOTED = re.compile(r"\"(?:[^\"\\]|\\.)*\"|'(?:[^']|'')*'") +FLOW_FORBIDDEN_KEYS = {"environment", "uses"} + + +def workflow_entries(source): + """Every mapping entry in a workflow, plus the YAML forms this reader refuses. + + A narrow reader, not a YAML parser (none ships with the runner's Python). Each entry is + (line, key, value, multiline): plain, single- and double-quoted keys and one-line values in + block and simple one-line flow mappings. Block scalar bodies are skipped, and an entry whose + value is a block scalar or continues on the next lines is marked multiline. It refuses whatever + could hide a key from it: escaped double-quoted keys, explicit `?` keys, merge keys, anchors, + aliases, tags, tab indentation and nested or multi-line flow. + """ + lines = source.splitlines() + entries, refused, block = [], [], None + + def continues(index, indent): + for follow in lines[index + 1:]: + stripped = follow.strip() + if not stripped or stripped.startswith("#"): + continue + deeper = len(follow) - len(follow.lstrip(" ")) > indent + return deeper and not stripped.startswith("- ") and WORKFLOW_KEY.match(stripped) is None + return False + + for index, raw in enumerate(lines): + number = index + 1 + stripped = raw.strip() + indent = len(raw) - len(raw.lstrip(" ")) + if block is not None: + if not stripped or indent > block: + continue + block = None + if not stripped or stripped.startswith("#"): + continue + if "\t" in raw[:indent + 1]: + refused.append(f"line {number}: tab indentation"); continue + body, unterminated = _strip_comment(stripped) + if unterminated: + refused.append(f"line {number}: unterminated or multi-line quoted scalar"); continue + if not body: + continue + while body.startswith("- "): + body = body[2:].lstrip() + if body == "?" or body.startswith("? "): + refused.append(f"line {number}: explicit key"); continue + match = WORKFLOW_KEY.match(body) + value = body + if match is not None: + key, value = _workflow_key(match.group(1)), match.group(2) or "" + if key is None: + refused.append(f"line {number}: escaped double-quoted key"); continue + if key == "<<": + refused.append(f"line {number}: merge key"); continue + plain = re.sub(r"\$\{\{.*?\}\}", "", value).strip() + bare = re.sub(r"\"(?:[^\"\\]|\\.)*\"|'(?:[^']|'')*'", "''", plain) + if re.match(r"[&*!]", plain): + refused.append(f"line {number}: anchor, alias or tag") + is_block = re.fullmatch(r"[|>][0-9+-]*", plain) is not None + if match is not None: + entries.append((number, key, _workflow_value(value), + is_block or ((value == "" or not is_block) and continues(index, indent)))) + if "{" in bare and bare != "{}": + masked = re.fullmatch(r"\{([^{}\[\]]*)\}", FLOW_QUOTED.sub("''", value.strip())) + flow = re.fullmatch(r"\{([^{}\[\]]*)\}", value.strip()) + if any(set(scalar[1:-1]) & set("#{}[],") for scalar in FLOW_QUOTED.findall(value)): + refused.append(f"line {number}: flow mapping quoted scalar with # or flow punctuation") + elif masked is None or flow is None: + refused.append(f"line {number}: nested or multi-line flow mapping") + else: + # The masked text only proves the shape: a quoted key ("uses", 'environment') keeps + # its identity, so the entries are read from the original mapping text, never ''. + for item in flow.group(1).split(","): + entry = WORKFLOW_KEY.match(item.strip()) + key = _workflow_key(entry.group(1)) if entry else None + if key is None: + refused.append(f"line {number}: unreadable flow mapping entry") + elif key in FLOW_FORBIDDEN_KEYS: + refused.append(f"line {number}: {key} in a flow mapping (must be block style)") + else: + entries.append((number, key, _workflow_value(entry.group(2) or ""), False)) + if match is not None and is_block: + block = indent + return entries, refused + + +def workflow_keys(source): + """(line, key) for every mapping entry, plus the refused YAML forms.""" + entries, refused = workflow_entries(source) + return [(number, key) for number, key, _, _ in entries], refused + + +SHARED_CALLEE = re.compile(r"storytold/craft-common-actions/\.github/workflows/([\w.-]+\.ya?ml)@(\S+)", re.IGNORECASE) +INSPECTED_KEYS = {"environment", "uses"} + + +def trust_closure_problems(workflows): + """The nightly-signer trust-closure scan over app workflow sources; empty when the tree is safe. + + Every key it inspects comes from workflow_entries(), never a regex over the raw text. + """ + problems, stable_callers, signer_calls = [], set(), 0 + for name, source in workflows.items(): + entries, refused = workflow_entries(source) + problems.extend(name + " uses YAML the scan cannot read (" + reason + ")" for reason in refused) + for number, key, value, multiline in entries: + if key not in INSPECTED_KEYS: + continue + if key == "environment": + problems.append(f"{name} binds an environment directly (line {number})") + continue + if value is None or multiline: + problems.append(f"{name} has a uses value the scan cannot read (line {number})") + continue + callee = SHARED_CALLEE.fullmatch(value) + if callee is None: + if re.search(r"craft-common-actions", value, re.IGNORECASE) and re.search(r"workflows/(nightly-)?release\.ya?ml", value, re.IGNORECASE): + problems.append(f"{name} has an unrecognised shared release caller (line {number})") + continue + workflow, ref = callee.group(1), callee.group(2) + if workflow.lower() in ("nightly-release.yml", "nightly-release.yaml"): + if name == "nightly-sign.yml": + signer_calls += 1 + if name != "nightly-sign.yml" or not re.fullmatch(r"[0-9a-f]{40}", ref): + problems.append(name + " calls nightly-release.yml@" + ref) + if workflow.lower() in ("release.yml", "release.yaml"): + stable_callers.add(name) + if ref != "main" and not re.fullmatch(r"[0-9a-f]{40}", ref): + problems.append(name + " calls release.yml@" + ref + "; use @main or a reviewed full SHA") + if stable_callers != REVIEWED_STABLE_RELEASE_CALLERS: + problems.append("shared release.yml callers are " + ", ".join(sorted(stable_callers))) + if signer_calls != 1: + problems.append("nightly-sign.yml must call nightly-release.yml exactly once") + return problems + + +class NightlySignerBranchTrustClosure(unittest.TestCase): + """On refs/heads/nightly-signer, only the pinned signer caller may reach an environment.""" + + def test_trust_closure_scan_passes_on_this_tree(self): + self.assertEqual(trust_closure_problems(app_workflows()), []) + + def test_trust_closure_scan_refuses_each_route_into_an_environment(self): + tree = app_workflows() + bad = { + "a workflow binds an environment": {**tree, "extra.yml": "jobs:\n x:\n runs-on: ubuntu-latest\n environment: release\n"}, + "a double-quoted environment key": {**tree, "extra.yml": 'jobs:\n x:\n runs-on: ubuntu-latest\n "environment": release\n'}, + "a single-quoted environment key": {**tree, "extra.yml": "jobs:\n x:\n runs-on: ubuntu-latest\n 'environment' : release\n"}, + "an environment mapping": {**tree, "extra.yml": "jobs:\n x:\n runs-on: ubuntu-latest\n environment:\n name: release\n"}, + "an environment in a flow mapping": {**tree, "extra.yml": "jobs:\n x: {runs-on: ubuntu-latest, environment: release}\n"}, + "an escaped key": {**tree, "extra.yml": 'jobs:\n x:\n runs-on: ubuntu-latest\n "environ\\u006dent": release\n'}, + "a merge key": {**tree, "extra.yml": "base: &b\n runs-on: ubuntu-latest\njobs:\n x:\n <<: *b\n"}, + "an explicit key": {**tree, "extra.yml": "jobs:\n x:\n ? environment\n : release\n"}, + "a nested flow mapping": {**tree, "extra.yml": "jobs:\n x: {steps: [{run: a}]}\n"}, + "a double-quoted uses key copying the signer": {**tree, "extra.yml": 'jobs:\n x:\n "uses": ' + SHARED + "nightly-release.yml@" + "a" * 40 + "\n"}, + "a single-quoted uses key": {**tree, "extra.yml": "jobs:\n x:\n 'uses': " + SHARED + "nightly-release.yml@" + "a" * 40 + "\n"}, + "a quoted uses value": {**tree, "extra.yml": 'jobs:\n x:\n uses: "' + SHARED + "nightly-release.yml@" + "a" * 40 + '"\n'}, + "uses in a flow mapping": {**tree, "extra.yml": "jobs:\n x: {uses: " + SHARED + "nightly-release.yml@" + "a" * 40 + "}\n"}, + "a differently cased owner": {**tree, "extra.yml": "jobs:\n x:\n uses: Storytold/Craft-Common-Actions/.github/workflows/nightly-release.yml@" + "a" * 40 + "\n"}, + "a folded uses value": {**tree, "extra.yml": "jobs:\n x:\n uses: >-\n " + SHARED + "nightly-release.yml@" + "a" * 40 + "\n"}, + "a continued uses value": {**tree, "extra.yml": "jobs:\n x:\n uses: " + SHARED + "\n nightly-release.yml@" + "a" * 40 + "\n"}, + "a quoted second signer call": {**tree, "nightly-sign.yml": tree["nightly-sign.yml"] + " again:\n \"uses\": " + SHARED + "nightly-release.yml@" + "a" * 40 + "\n"}, + "a hash inside a quoted flow scalar": {**tree, "extra.yml": 'jobs:\n x: {name: "a} # b", runs-on: ubuntu-latest, environment: release, steps: []}\n'}, + "a single-quoted hash in a flow scalar": {**tree, "extra.yml": "jobs:\n x: {name: 'a # b', runs-on: ubuntu-latest}\n"}, + "a comma inside a quoted flow scalar": {**tree, "extra.yml": 'jobs:\n x: {name: "a, environment: release", runs-on: ubuntu-latest}\n'}, + "a bracket inside a quoted flow scalar": {**tree, "extra.yml": 'jobs:\n x: {name: "[a]", runs-on: ubuntu-latest}\n'}, + "an unterminated quote": {**tree, "extra.yml": 'jobs:\n x:\n name: "a\n b"\n runs-on: ubuntu-latest\n'}, + "environment in any flow mapping": {**tree, "extra.yml": "jobs:\n x:\n runs-on: ubuntu-latest\n with: {environment: release}\n"}, + "a double-quoted environment key in a flow mapping": {**tree, "extra.yml": 'jobs:\n x:\n runs-on: ubuntu-latest\n with: {"environment": release}\n'}, + "a single-quoted environment key in a flow mapping": {**tree, "extra.yml": "jobs:\n x:\n runs-on: ubuntu-latest\n with: {'environment': release}\n"}, + "a double-quoted uses key in a flow mapping": {**tree, "extra.yml": 'jobs:\n x: {"uses": ' + SHARED + "nightly-release.yml@" + "a" * 40 + "}\n"}, + "uses in any flow mapping": {**tree, "extra.yml": "jobs:\n x:\n steps:\n - {uses: actions/checkout@v4}\n"}, + "another caller of the signer": {**tree, "extra.yml": "jobs:\n x:\n uses: " + SHARED + "nightly-release.yml@" + "a" * 40 + "\n"}, + "a mutable signer pin": {**tree, "nightly-sign.yml": re.sub(r"nightly-release\.yml@[0-9a-f]{40}", "nightly-release.yml@main", tree["nightly-sign.yml"])}, + "a new stable release caller": {**tree, "extra.yml": "jobs:\n x:\n uses: " + SHARED + "release.yml@main\n"}, + "a stable caller on a branch or tag ref": {**tree, "release.yml": tree["release.yml"].replace(SHARED + "release.yml@main", SHARED + "release.yml@v1")}, + } + for label, workflows in bad.items(): + with self.subTest(case=label): + self.assertTrue(trust_closure_problems(workflows)) + + def test_quoted_keys_in_a_flow_mapping_are_read_not_masked(self): + entries, refused = workflow_entries('jobs:\n x: {runs-on: ubuntu-latest, "name": build}\n') + self.assertEqual(refused, []) + self.assertIn((2, "name", "build", False), entries, "a quoted key keeps its identity") + self.assertIn((2, "runs-on", "ubuntu-latest", False), entries) + _, refused = workflow_entries("jobs:\n x: {runs-on: ubuntu-latest, 'environment': release}\n") + self.assertEqual(refused, ["line 2: environment in a flow mapping (must be block style)"]) + + def test_signer_guard_and_policy_name_the_same_branch(self): + app = json.loads(INSTALLED_POLICY.read_text())["repository"].split("/", 1)[1] + sign = (ROOT / ".github/workflows/nightly-sign.yml").read_text() + (_, guard), = job_conditions(sign.split("\njobs:\n", 1)[1]) + self.assertIn("github.ref == 'refs/heads/" + SIGNER_BRANCH + "'", guard) + self.assertNotIn("refs/heads/release", sign, "the signer no longer runs on the stable branch") + self.assertEqual(re.findall(r"(?m)^ app-name: (\S+)$", sign), [app], "the shared signer needs the reviewed registry app") + self.assertEqual(json.loads(INSTALLED_POLICY.read_text())["release_branch"], SIGNER_BRANCH) + + +if __name__ == "__main__": + unittest.main(verbosity=2) diff --git a/packaging/nightly-tests.py b/packaging/nightly-tests.py new file mode 100644 index 000000000..5b3ba68c8 --- /dev/null +++ b/packaging/nightly-tests.py @@ -0,0 +1,26 @@ +#!/usr/bin/env python3 +"""Run the existing synthetic packaging suites together; no app build or signing.""" +import importlib.util +from pathlib import Path +import unittest + + +def main() -> int: + here = Path(__file__).resolve().parent + suite = unittest.TestSuite() + for name, relative in ( + ("designcraft_archive_suite", "nightly-archive-tests.py"), + ("designcraft_launcher_suite", "nightly-launcher-tests.py"), + ("designcraft_plist_suite", "macos/nightly_plist_tests.py"), + ("designcraft_release_dispatch_suite", "nightly-release-tests.py"), + ("designcraft_mac_sign_suite", "macos/nightly_sign_tests.py"), + ): + spec = importlib.util.spec_from_file_location(name, here / relative) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + suite.addTests(unittest.defaultTestLoader.loadTestsFromModule(module)) + return 0 if unittest.TextTestRunner(verbosity=2).run(suite).wasSuccessful() else 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/packaging/nightly_paths.py b/packaging/nightly_paths.py new file mode 100644 index 000000000..792198589 --- /dev/null +++ b/packaging/nightly_paths.py @@ -0,0 +1,139 @@ +"""POSIX packaging I/O rooted at a caller-owned private working directory. + +The build launcher chooses cwd independently of file arguments (Linux uses its +mktemp directory). This is not a sandbox against root or a malicious same-UID +caller, and inode-check/unlink cleanup is not an atomic replacement-race primitive. +""" +import contextlib +import os +from pathlib import Path +import stat + + +def _component(name): + # A descriptor-relative open must name exactly one entry in its directory. + if not name or name in (".", "..") or os.path.basename(name) != name: + raise ValueError("build path components must be single names") + return os.path.basename(name) + + +class OwnedBuildRoot: + def __enter__(self): + self.directory = Path.cwd() + self.fd = os.open(".", os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW) + info = os.fstat(self.fd) + if info.st_uid != os.geteuid() or stat.S_IMODE(info.st_mode) & 0o077: + os.close(self.fd) + raise ValueError("packaging cwd must be an owned private build directory") + return self + + def __exit__(self, *_error): + os.close(self.fd) + + def _relative(self, path): + path = Path(path) + try: + relative = path.relative_to(self.directory) if path.is_absolute() else path + except ValueError as error: + raise ValueError("path is outside the owned build directory") from error + if not relative.parts or ".." in relative.parts: + raise ValueError("empty or parent-traversing build path") + # Check an independently selected root, never the supplied filename's parent. + try: + parent = (self.directory / relative).parent.resolve(strict=True) + except OSError as error: + raise ValueError("build path parent must exist") from error + if not parent.is_relative_to(self.directory): + raise ValueError("resolved path escapes the owned build directory") + return relative + + def _checked_parts(self, path): + relative = self._relative(path) + root = os.path.realpath(self.directory) + lexical = os.path.join(root, *relative.parts) + target = os.path.realpath(lexical) + if target == root or os.path.commonpath([root, target]) != root: + raise ValueError("resolved path escapes the owned build directory") + if target != lexical: + raise ValueError("build path must not pass through symlinks or aliases") + return [_component(part) for part in os.path.relpath(target, root).split(os.sep)] + + def _parent(self, path): + parts = self._checked_parts(path) + current = os.dup(self.fd) + try: + for part in parts[:-1]: + next_fd = os.open(_component(part), os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=current) + os.close(current) + current = next_fd + return current, parts[-1] + except OSError as error: + os.close(current) + raise ValueError("build path parents must be non-symlink directories") from error + + @contextlib.contextmanager + def reader(self, path, limit): + parent, name = self._parent(path) + try: + try: + descriptor = os.open(_component(name), os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=parent) + except OSError as error: + raise ValueError("build input must be a regular file without aliases") from error + finally: + os.close(parent) + info = os.fstat(descriptor) + if not stat.S_ISREG(info.st_mode) or info.st_size > limit: + os.close(descriptor) + raise ValueError("build input must be a regular file within its read bound") + with os.fdopen(descriptor, "rb") as stream: + yield stream + + def read_bytes(self, path, limit): + with self.reader(path, limit) as stream: + data = stream.read(limit + 1) + if len(data) > limit: + raise ValueError("build input grew beyond its read bound") + return data + + def children(self, path, limit): + relative = self._relative(path) + parent, name = self._parent(path) + try: + try: + descriptor = os.open(_component(name), os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=parent) + except OSError as error: + raise ValueError("build stage must be a non-symlink directory") from error + finally: + os.close(parent) + try: + entries = [] + with os.scandir(descriptor) as iterator: + for entry in iterator: + if len(entries) >= limit: + raise ValueError("too many build stage members") + entries.append(self.directory / relative / entry.name) + return entries + finally: + os.close(descriptor) + + @contextlib.contextmanager + def create(self, path): + parent, name = self._parent(path) + name = _component(name) + try: + descriptor = os.open(name, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o666, dir_fd=parent) + info = os.fstat(descriptor) + identity = (info.st_dev, info.st_ino) + try: + with os.fdopen(descriptor, "wb") as stream: + yield stream + except BaseException: + try: + current = os.stat(name, dir_fd=parent, follow_symlinks=False) + if (current.st_dev, current.st_ino) == identity: + os.unlink(_component(name), dir_fd=parent) + except FileNotFoundError: + pass + raise + finally: + os.close(parent) diff --git a/packaging/windows/nightly-package-tests.ps1 b/packaging/windows/nightly-package-tests.ps1 new file mode 100644 index 000000000..91dc350a4 --- /dev/null +++ b/packaging/windows/nightly-package-tests.ps1 @@ -0,0 +1,96 @@ +param([Parameter(Mandatory=$true)][string] $FixtureRoot) +. (Join-Path $PSScriptRoot 'nightly.ps1') -FunctionsOnly +function Assert([bool] $Value, [string] $Message) { if (-not $Value) { throw $Message } } +$spec = Get-NightlyArchiveSpec '0.23.1-nightly.20261120.17.1.gabcdef012345' 'x64' +Assert ($spec.Archive -eq 'designcraft-0.23.1-nightly.20261120.17.1.gabcdef012345-windows-x86_64-nightly.zip') 'wrong nightly artifact name' +Assert ($spec.Executables.Count -eq 1 -and $spec.Executables[0] -eq 'designcraft.exe') 'nightly must not ship the unqualified CLI' +Assert ($spec.AppId -eq 'ai.storyteller.designcraft.nightly-v1') 'nightly identity is not distinct' +foreach ($arch in @('x86', 'arm64')) { + $refused = $false + try { Get-NightlyArchiveSpec '0.23.1' $arch | Out-Null } catch { $refused = $true } + Assert $refused 'unsupported target was accepted' +} +foreach ($bad in @('', '0.23.1', '../other', '0.23.1/elsewhere')) { + $refused = $false + try { Get-NightlyArchiveSpec $bad 'x64' | Out-Null } catch { $refused = $true } + Assert $refused 'unsafe artifact version was accepted' +} +Assert-NightlyFlavor 'DesignCraft Nightly' 'DesignCraft 0.23.1-nightly.20261120.17.1.gabcdef012345 (nightly-v1)' '0.23.1-nightly.20261120.17.1.gabcdef012345' +foreach ($pair in @(@('DesignCraft', 'DesignCraft 0.23.1 (nightly-v1)'), @('DesignCraft Nightly', 'DesignCraft 0.23.1'))) { + $refused = $false + try { Assert-NightlyFlavor $pair[0] $pair[1] '0.23.1-nightly.20261120.17.1.gabcdef012345' } catch { $refused = $true } + Assert $refused 'stable or mismatched build flavor was accepted' +} +$sha = 'abcdef0123456789abcdef0123456789abcdef01' +$good = '0.23.1-nightly.20261120.17.1.gabcdef012345' +Assert-NightlySource $good $sha '2026-11-20' $sha '' +$cases = @( + @('missing commit', $good, '', '2026-11-20', $sha, ''), + @('short commit', $good, 'abcdef012345', '2026-11-20', $sha, ''), + @('uppercase commit', $good, $sha.ToUpper(), '2026-11-20', $sha.ToUpper(), ''), + @('version names another commit', '0.23.1-nightly.20261120.17.1.g000000000000', $sha, '2026-11-20', $sha, ''), + @('missing date', $good, $sha, '', $sha, ''), + @('date differs from version', $good, $sha, '2026-11-21', $sha, ''), + @('other commit checked out', $good, $sha, '2026-11-20', ('0' * 40), ''), + @('dirty tree', $good, $sha, '2026-11-20', $sha, ' M apps/designcraft/src/main.rs') +) +foreach ($case in $cases) { + $refused = $false + try { Assert-NightlySource $case[1] $case[2] $case[3] $case[4] $case[5] } catch { $refused = $true } + Assert $refused "source identity accepted: $($case[0])" +} +Write-Output 'nightly packaging spec, target/version refusal, source identity and flavor-binding tests passed' + +# Exercise the SAME production notice copier with the real repository layout, then inspect a ZIP. +if (-not $FixtureRoot -or -not [IO.Path]::IsPathRooted($FixtureRoot)) { throw 'supply an owned absolute -FixtureRoot for the notices/ZIP regression' } +$testRoot = Join-Path $FixtureRoot ("nightly-notices-" + [Guid]::NewGuid().ToString('N')) +try { + $repo = Join-Path $testRoot 'app' + $fontRepo = Join-Path $testRoot 'craft-fonts' + $family = Join-Path $fontRepo 'fonts\ExampleFamily' + $stage = Join-Path $testRoot 'stage' + New-Item -ItemType Directory -Force -Path $repo, $family, $stage | Out-Null + # DesignCraft has no LICENSE of its own: the same required set the production copier demands. + $rootNames = @('README.md', 'LICENSE-MIT', 'LICENSE-APACHE', 'NOTICE', 'ATTRIBUTION.md') + foreach ($name in $rootNames) { Set-Content -LiteralPath (Join-Path $repo $name) -Value "root-notice-$name" } + Set-Content -LiteralPath (Join-Path $family 'OFL.txt') -Value 'font-notice-example' + Copy-NightlyNotices $repo $fontRepo $stage + foreach ($name in @($rootNames) + @('OFL-ExampleFamily.txt')) { + Assert (Test-Path -LiteralPath (Join-Path $stage $name)) "missing staged notice $name" + } + $zip = Join-Path $testRoot 'notices.zip' + Compress-Archive -Path (Join-Path $stage '*') -DestinationPath $zip + $archive = [IO.Compression.ZipFile]::OpenRead($zip) + try { + $names = @($archive.Entries | ForEach-Object { $_.FullName }) + foreach ($name in @($rootNames) + @('OFL-ExampleFamily.txt')) { Assert ($name -in $names) "missing archived notice $name" } + foreach ($forbidden in @('portable.txt', 'designcraft-cli.exe')) { Assert ($forbidden -notin $names) "unexpected payload $forbidden" } + $entry = $archive.GetEntry('OFL-ExampleFamily.txt') + $reader = [IO.StreamReader]::new($entry.Open()) + try { Assert ($reader.ReadToEnd().Contains('font-notice-example')) 'wrong font license bytes in ZIP' } finally { $reader.Dispose() } + } finally { $archive.Dispose() } +} finally { + if (Test-Path -LiteralPath $testRoot) { Remove-Item -LiteralPath $testRoot -Recurse -Force } +} +Write-Output 'nightly mock-repository root and font notices are present in stage and ZIP' + +# The source state comes from git itself: the checked-out commit, then a dirty tree. +$gitRoot = Join-Path $FixtureRoot ("nightly-source-" + [Guid]::NewGuid().ToString('N')) +try { + New-Item -ItemType Directory -Force -Path $gitRoot | Out-Null + git -C $gitRoot init -q; git -C $gitRoot -c user.name=fixture -c user.email=fixture@invalid commit -q --allow-empty -m fixture + if ($LASTEXITCODE -ne 0) { throw 'cannot create the git fixture' } + $head = (git -C $gitRoot rev-parse HEAD).Trim() + $state = Get-NightlySourceState $gitRoot + Assert ($state.Head -ceq $head -and -not $state.Status) 'clean checkout not reported as clean at HEAD' + $version = '0.23.1-nightly.20261120.17.1.g' + $head.Substring(0, 12) + Assert-NightlySource $version $head '2026-11-20' $state.Head $state.Status + Set-Content -LiteralPath (Join-Path $gitRoot 'untracked.txt') -Value 'dirty' + $state = Get-NightlySourceState $gitRoot + $refused = $false + try { Assert-NightlySource $version $head '2026-11-20' $state.Head $state.Status } catch { $refused = $true } + Assert $refused 'a dirty checkout was accepted' +} finally { + if (Test-Path -LiteralPath $gitRoot) { Remove-Item -LiteralPath $gitRoot -Recurse -Force } +} +Write-Output 'nightly source state is read from git and a dirty checkout is refused' diff --git a/packaging/windows/nightly-signing-tests.ps1 b/packaging/windows/nightly-signing-tests.ps1 new file mode 100644 index 000000000..65c29d8cc --- /dev/null +++ b/packaging/windows/nightly-signing-tests.ps1 @@ -0,0 +1,90 @@ +param( + [Parameter(Mandatory=$true)][string] $FixtureRoot, + [string] $PackagingRoot = $PSScriptRoot, + [switch] $PhaseGuardOnly +) +$ErrorActionPreference = 'Stop' +. (Join-Path $PackagingRoot 'nightly.ps1') -FunctionsOnly +$sign = Join-Path $PackagingRoot 'sign.ps1' +$names = @('WINDOWS_CERTIFICATE','WINDOWS_CERTIFICATE_PASSWORD','AZURE_TENANT_ID','AZURE_CLIENT_ID','AZURE_CLIENT_SECRET','AZURE_SIGNING_ENDPOINT','AZURE_SIGNING_ACCOUNT','AZURE_CERT_PROFILE') +function Clear-SigningFixtures { foreach ($name in $names) { [Environment]::SetEnvironmentVariable($name, $null) } } +function Assert-Policy([bool] $Value, [string] $Message) { if (-not $Value) { throw $Message } } +function Invoke-Refusal([scriptblock] $Operation, [string] $Message) { + $errorText = '' + try { & $Operation | Out-Null } catch { $errorText = $_.Exception.Message } + Assert-Policy ($errorText.Contains($Message)) "expected refusal: $Message; got: $errorText" +} +function global:cargo { $global:SigningFixtureCargoCalls++; throw 'FIXTURE_COMPILER_BOUNDARY' } +function global:Invoke-WebRequest { throw 'fixture must not perform signing downloads' } +$global:SigningFixtureCargoCalls = 0 +if (-not [IO.Path]::IsPathRooted($FixtureRoot)) { throw 'use an owned absolute FixtureRoot' } +$root = Join-Path $FixtureRoot ('signing-policy-' + [Guid]::NewGuid().ToString('N')) +New-Item -ItemType Directory -Path $root | Out-Null +# The fixture mocks Cargo, but nightly.ps1 checks the same source identity a packaging run does: +# the version names this checkout's commit and the run's UTC date, and the tree is clean. Deriving +# them here keeps the fixture reaching the mocked compiler instead of failing in source validation. +$sha = "$(git -C $PSScriptRoot rev-parse HEAD)".Trim() +$runDate = (Get-Date).ToUniversalTime().ToString('yyyyMMdd') +$version = "0.23.1-nightly.$runDate.12345.1.g$($sha.Substring(0, 12))" +$env:DESIGNCRAFT_VERSION = $version +$env:DESIGNCRAFT_BUILD_SHA = $sha +$env:DESIGNCRAFT_BUILD_DATE = "$($runDate.Substring(0, 4))-$($runDate.Substring(4, 2))-$($runDate.Substring(6, 2))" +function Invoke-Build([switch] $BuildOnly) { + $arguments = @{Arch='x64';Version=$version;Target='x86_64-pc-windows-msvc';TargetDir=$root;Dist=(Join-Path $root 'dist')} + if ($BuildOnly) { $arguments.BuildOnly = $true } + & (Join-Path $PackagingRoot 'nightly.ps1') @arguments +} +try { + Clear-SigningFixtures + Invoke-Refusal { Invoke-Build } 'requires -BuildOnly' + Assert-Policy ($global:SigningFixtureCargoCalls -eq 0) 'default mode invoked Cargo' + Write-Output 'PASS: explicit-build-phase-required' + if ($PhaseGuardOnly) { return } + + foreach ($name in @('WINDOWS_CERTIFICATE','WINDOWS_CERTIFICATE_PASSWORD','AZURE_CLIENT_SECRET')) { + Clear-SigningFixtures + [Environment]::SetEnvironmentVariable($name, 'generated-fixture-not-a-secret') + Invoke-Refusal { Invoke-Build -BuildOnly } 'Compilation must not receive signing credentials' + Assert-Policy ($global:SigningFixtureCargoCalls -eq 0) 'key-bearing compilation reached Cargo' + } + Write-Output 'PASS: credentials-rejected-before-compilation' + + Clear-SigningFixtures + Invoke-Refusal { Invoke-Build -BuildOnly } 'FIXTURE_COMPILER_BOUNDARY' + Assert-Policy ($global:SigningFixtureCargoCalls -eq 1) 'clean compilation did not reach the mocked compiler boundary' + Assert-Policy (-not (Test-Path (Join-Path $root 'dist'))) 'mocked compilation produced an artifact' + Write-Output 'PASS: secret-free-build-reaches-only-mocked-boundary' + + Clear-SigningFixtures + Invoke-Refusal { & $sign -Required -CheckOnly } 'Nightly signing is required' + $env:AZURE_CLIENT_SECRET = 'generated-partial-fixture' + Invoke-Refusal { & $sign -Required -CheckOnly } 'Nightly signing is required' + Write-Output 'PASS: required-signer-refuses-missing-and-partial-configuration' + + Clear-SigningFixtures + $env:WINDOWS_CERTIFICATE = 'generated-presence-fixture-not-a-certificate' + & $sign -Required -CheckOnly + Clear-SigningFixtures + foreach ($name in $names | Where-Object { $_.StartsWith('AZURE_') }) { [Environment]::SetEnvironmentVariable($name, 'generated-presence-fixture') } + & $sign -Required -CheckOnly + Clear-SigningFixtures + Write-Output 'PASS: supported-configuration-presence-without-signing' + + # Load the policy function without signing. These objects are not crypto evidence. + . $sign -CheckOnly + foreach ($value in @($null, [pscustomobject]@{Status='NotSigned';SignerCertificate='fixture'}, [pscustomobject]@{Status='HashMismatch';SignerCertificate='fixture'}, [pscustomobject]@{Status='Valid';SignerCertificate=$null})) { + Invoke-Refusal { Assert-AuthenticodeSignature $value } 'valid Authenticode signature' + } + Assert-AuthenticodeSignature ([pscustomobject]@{Status='Valid';SignerCertificate='generated-public-certificate-placeholder'}) + Write-Output 'PASS: required-signature-policy-rejects-invalid-or-missing-signer' + + $file = Join-Path $root 'owned-sentinel.exe' + [IO.File]::WriteAllText($file, 'generated sentinel, not a real executable') + $before = (Get-FileHash -LiteralPath $file -Algorithm SHA256).Hash + & $sign -Files $file + Assert-Policy ((Get-FileHash -LiteralPath $file -Algorithm SHA256).Hash -ceq $before) 'optional stable policy changed unsigned bytes' + Write-Output 'PASS: stable-optional-policy-preserves-owned-bytes' +} finally { + Clear-SigningFixtures + Remove-Item -LiteralPath $root -Recurse -Force +} diff --git a/packaging/windows/nightly.ps1 b/packaging/windows/nightly.ps1 new file mode 100644 index 000000000..0226a269d --- /dev/null +++ b/packaging/windows/nightly.ps1 @@ -0,0 +1,143 @@ +<# First nightly target only: Windows x86_64 GUI ZIP. No MSI, CLI, portable marker or association registration. #> +param( + [string] $Arch = 'x64', + [string] $Version, + [string] $Target, + [string] $TargetDir, + [string] $Dist, + [switch] $SkipBuild, + [switch] $BuildOnly, + [switch] $FunctionsOnly +) +$ErrorActionPreference = 'Stop' + +function Get-NightlyArchiveSpec([string] $Version, [string] $Arch) { + if ($Arch -ne 'x64') { throw 'nightly-v1 supports only Windows x86_64' } + if (-not $Version -or $Version -cnotmatch '^\d+\.\d+\.\d+-nightly\.\d{8}\.\d+\.\d+\.g[0-9a-f]{12}\z') { throw 'invalid nightly artifact version' } + return @{ + Archive = "designcraft-$Version-windows-x86_64-nightly.zip" + UnsignedArchive = "designcraft-$Version-windows-x86_64-nightly.unsigned.zip" + Executables = @('designcraft.exe') + Channel = 'nightly-v1' + AppId = 'ai.storyteller.designcraft.nightly-v1' + } +} + +# The same source identity the Linux helper enforces (nightly-common.sh): the version names the +# commit being built, the date is the original run's, and the tree is clean. +function Assert-NightlySource([string] $Version, [string] $Sha, [string] $BuildDate, [string] $Head, [string] $Status) { + if ($Sha -cnotmatch '^[0-9a-f]{40}\z') { throw 'an exact source commit is required (DESIGNCRAFT_BUILD_SHA)' } + if ($Version -cnotmatch '^\d+\.\d+\.\d+-nightly\.\d{8}\.\d+\.\d+\.g[0-9a-f]{12}\z') { throw 'invalid nightly artifact version' } + if ($Version.Substring($Version.Length - 12) -cne $Sha.Substring(0, 12)) { throw 'version/source commit mismatch' } + if ($BuildDate -cnotmatch '^\d{4}-\d{2}-\d{2}\z') { throw 'the original run-created UTC date is required (DESIGNCRAFT_BUILD_DATE)' } + $versionDate = ($Version -split '-nightly\.', 2)[1].Substring(0, 8) + if ($BuildDate.Replace('-', '') -cne $versionDate) { throw 'version/original-run date mismatch' } + if ($Head -cne $Sha) { throw 'prepared source is not the checked-out commit' } + if ($Status) { throw 'nightly packaging requires the frozen clean source' } +} + +function Get-NightlySourceState([string] $RepositoryRoot) { + $head = git -C $RepositoryRoot rev-parse HEAD + if ($LASTEXITCODE -ne 0) { throw 'cannot read the checked-out commit' } + $status = git -C $RepositoryRoot status --porcelain + if ($LASTEXITCODE -ne 0) { throw 'cannot read the source tree status' } + return @{ Head = "$head".Trim(); Status = ($status | Out-String).Trim() } +} + +function Assert-NightlyFlavor([string] $ProductName, [string] $VersionOutput, [string] $ExpectedVersion) { + if ($ProductName -ne 'DesignCraft Nightly' -or $VersionOutput -cne "DesignCraft $ExpectedVersion (nightly-v1)") { + throw 'the executable is not the compiled nightly-v1 flavor' + } +} + +# DesignCraft has no LICENSE or ATTRIBUTION.md of its own, so the required notices are the readme, +# the two licences and NOTICE; LICENSE/COPYRIGHT/ATTRIBUTION.md are copied when a checkout has one. +function Copy-NightlyNotices([string] $RepositoryRoot, [string] $FontRepository, [string] $Destination) { + foreach ($name in 'README.md', 'LICENSE-MIT', 'LICENSE-APACHE', 'NOTICE') { + $source = Join-Path $RepositoryRoot $name + if (-not (Test-Path -LiteralPath $source -PathType Leaf)) { throw "missing app notice: $name" } + Copy-Item -LiteralPath $source -Destination $Destination + } + foreach ($optional in 'LICENSE', 'COPYRIGHT', 'ATTRIBUTION.md') { + $source = Join-Path $RepositoryRoot $optional + if (Test-Path -LiteralPath $source -PathType Leaf) { Copy-Item -LiteralPath $source -Destination $Destination } + } + if ($FontRepository) { + $fonts = Join-Path $FontRepository 'fonts' + if (-not (Test-Path -LiteralPath $fonts -PathType Container)) { throw 'CRAFT_FONTS_DIR has no fonts directory for the bundled notices' } + foreach ($family in Get-ChildItem -LiteralPath $fonts -Directory) { + $license = Join-Path $family.FullName 'OFL.txt' + if (Test-Path -LiteralPath $license) { Copy-Item -LiteralPath $license -Destination (Join-Path $Destination "OFL-$($family.Name).txt") } + } + } +} + +if ($FunctionsOnly) { return } +if (-not $env:DESIGNCRAFT_VERSION -or $Version -cne $env:DESIGNCRAFT_VERSION) { throw 'nightly-v1 requires explicit DESIGNCRAFT_VERSION, not the Cargo version fallback' } +$Spec = Get-NightlyArchiveSpec $Version $Arch +if ($SkipBuild) { throw 'nightly-v1 forbids -SkipBuild; the executable flavor must be built in this operation' } +if ($Target -ne 'x86_64-pc-windows-msvc') { throw 'nightly-v1 target must be x86_64-pc-windows-msvc' } +if (-not $BuildOnly) { throw 'Nightly compilation requires -BuildOnly; final archives are produced in the separate trusted signing job' } +# No key values may enter compilation. This produces an internal intermediate, not a feed artifact. +& (Join-Path $PSScriptRoot 'sign.ps1') -CheckBuildEnvironment +$Root = (Resolve-Path (Join-Path $PSScriptRoot '..\..')).Path +$Source = Get-NightlySourceState $Root +Assert-NightlySource $Version $env:DESIGNCRAFT_BUILD_SHA $env:DESIGNCRAFT_BUILD_DATE $Source.Head $Source.Status +$oldChannel = $env:DESIGNCRAFT_BUILD_CHANNEL +$oldVersion = $env:DESIGNCRAFT_VERSION +$oldOverride = $env:DESIGNCRAFT_OVERRIDE_VERSION +try { + $env:DESIGNCRAFT_BUILD_CHANNEL = 'nightly-v1' + # The build script accepts either name for the prepared version, and refuses a disagreement. + $env:DESIGNCRAFT_VERSION = $Version + $env:DESIGNCRAFT_OVERRIDE_VERSION = $Version + $env:DESIGNCRAFT_REQUIRE_WINRES = '1' + $env:CARGO_TARGET_X86_64_PC_WINDOWS_MSVC_RUSTFLAGS = '-C target-feature=+crt-static' + cargo build --release --locked -p designcraft --target $Target + if ($LASTEXITCODE -ne 0) { throw "nightly cargo build failed: $LASTEXITCODE" } +} finally { + $env:DESIGNCRAFT_BUILD_CHANNEL = $oldChannel + $env:DESIGNCRAFT_VERSION = $oldVersion + $env:DESIGNCRAFT_OVERRIDE_VERSION = $oldOverride +} +$Source = Get-NightlySourceState $Root +try { Assert-NightlySource $Version $env:DESIGNCRAFT_BUILD_SHA $env:DESIGNCRAFT_BUILD_DATE $Source.Head $Source.Status } +catch { throw "source changed during the build: $_" } +$Exe = Join-Path $TargetDir "$Target\release\designcraft.exe" +$pe = [System.IO.File]::ReadAllBytes($Exe) +if ($pe.Length -lt 64) { throw 'truncated nightly PE executable' } +$offset = [BitConverter]::ToInt32($pe, 0x3C) +if ($offset -lt 0 -or $offset -gt $pe.Length - 0x5E) { throw 'invalid nightly PE header offset' } +if ([BitConverter]::ToUInt16($pe, $offset + 4) -ne 0x8664 -or [BitConverter]::ToUInt16($pe, $offset + 0x5C) -ne 2) { + throw 'nightly executable must be x86_64 Windows GUI' +} +$VersionInfo = (Get-Item -LiteralPath $Exe).VersionInfo +$ProductName = $VersionInfo.ProductName +if ($VersionInfo.ProductVersion -cne $Version) { throw 'nightly PE ProductVersion differs from the feed identity' } +# Check the embedded build flavor before invoking even the side-effect-free version query. +if ($ProductName -ne 'DesignCraft Nightly') { throw 'nightly executable is missing the embedded build flavor' } +$VersionOutput = (& $Exe --version | Out-String).Trim() +if ($LASTEXITCODE -ne 0) { throw 'nightly --version query failed' } +Assert-NightlyFlavor $ProductName $VersionOutput $Version +$Stage = Join-Path $TargetDir 'windows-package\nightly-v1-x86_64' +if (Test-Path -LiteralPath $Stage) { Remove-Item -LiteralPath $Stage -Recurse -Force } +New-Item -ItemType Directory -Force -Path $Stage | Out-Null +Copy-Item -LiteralPath $Exe -Destination (Join-Path $Stage 'designcraft.exe') +# Signing happens only in the separate trusted step, using sign.ps1 -Required. +# The intermediate's filename cannot satisfy the feed-ready archive contract. +Copy-NightlyNotices $Root $env:CRAFT_FONTS_DIR $Stage +if ((Get-ChildItem -LiteralPath $Stage -Filter '*.exe').Count -ne 1 -or (Test-Path (Join-Path $Stage 'portable.txt'))) { + throw 'nightly stage contains an unexpected executable or portable fallback marker' +} +New-Item -ItemType Directory -Force -Path $Dist | Out-Null +$Zip = Join-Path $Dist $Spec.UnsignedArchive +if (Test-Path -LiteralPath $Zip) { throw 'Nightly output already exists; refusing to replace prepared artifact bytes' } +Compress-Archive -Path (Join-Path $Stage '*') -DestinationPath $Zip +$Archive = [System.IO.Compression.ZipFile]::OpenRead($Zip) +try { + $Names = @($Archive.Entries | ForEach-Object { $_.FullName }) + if ('designcraft.exe' -notin $Names -or 'designcraft-cli.exe' -in $Names -or 'portable.txt' -in $Names) { + throw 'nightly ZIP payload violates the GUI-only profile contract' + } +} finally { $Archive.Dispose() } +Write-Output "Nightly build intermediate (not publishable): $Zip ($VersionOutput)" diff --git a/packaging/windows/package.ps1 b/packaging/windows/package.ps1 index 922790512..a49203909 100644 --- a/packaging/windows/package.ps1 +++ b/packaging/windows/package.ps1 @@ -21,9 +21,12 @@ #> param( [ValidateSet('x64', 'x86', 'arm64')] [string] $Arch = 'x64', - [switch] $SkipBuild + [switch] $SkipBuild, + [switch] $Nightly, + [switch] $BuildOnly ) $ErrorActionPreference = 'Stop' +if ($BuildOnly -and -not $Nightly) { throw '-BuildOnly is only for secret-free nightly compilation' } $Root = (Resolve-Path (Join-Path $PSScriptRoot '..\..')).Path function Invoke-Native([string] $What, [scriptblock] $Block) { @@ -50,12 +53,22 @@ $Dist = if ($env:DIST) { $env:DIST } else { Join-Path $Root 'dist\release' } $TargetDir = if ($env:CARGO_TARGET_DIR) { $env:CARGO_TARGET_DIR } else { Join-Path $Root 'target' } New-Item -ItemType Directory -Force -Path $Dist | Out-Null -if (-not $env:DESIGNCRAFT_BUILD_SHA) { $env:DESIGNCRAFT_BUILD_SHA = (git -C $Root rev-parse HEAD 2>$null) } -if (-not $env:DESIGNCRAFT_BUILD_DATE) { $env:DESIGNCRAFT_BUILD_DATE = (Get-Date).ToUniversalTime().ToString('yyyy-MM-dd') } +# Nightly requires the prepared commit and original run date explicitly; nightly.ps1 checks both. +if (-not $Nightly) { + if (-not $env:DESIGNCRAFT_BUILD_SHA) { $env:DESIGNCRAFT_BUILD_SHA = (git -C $Root rev-parse HEAD 2>$null) } + if (-not $env:DESIGNCRAFT_BUILD_DATE) { $env:DESIGNCRAFT_BUILD_DATE = (Get-Date).ToUniversalTime().ToString('yyyy-MM-dd') } +} Write-Output "DesignCraft $Version for Windows $Arch ($Target)" +if ($Nightly) { + & (Join-Path $PSScriptRoot 'nightly.ps1') -Arch $Arch -Version $Version -Target $Target -TargetDir $TargetDir -Dist $Dist -SkipBuild:$SkipBuild -BuildOnly:$BuildOnly + return +} + if (-not $SkipBuild) { + $env:DESIGNCRAFT_BUILD_CHANNEL = 'stable' + # Static CRT: no VC++ redistributable needed. Scoped to the target so host build scripts and # proc-macros are unaffected. $flagVar = 'CARGO_TARGET_' + ($Target.ToUpper() -replace '-', '_') + '_RUSTFLAGS' @@ -83,6 +96,9 @@ foreach ($check in @(@('designcraft.exe', 2), @('designcraft-cli.exe', 3))) { if ($h.Subsystem -ne $check[1]) { throw "$($check[0]) has PE subsystem $($h.Subsystem), expected $($check[1])" } Write-Output "ok $($check[0]): $Arch, PE subsystem $($h.Subsystem)" } +if ((Get-Item -LiteralPath (Join-Path $Bin 'designcraft.exe')).VersionInfo.ProductName -eq 'DesignCraft Nightly') { + throw 'a nightly executable cannot be packaged as stable' +} $Stage = Join-Path $TargetDir "windows-package\$Arch" Remove-Item -Recurse -Force $Stage -ErrorAction SilentlyContinue New-Item -ItemType Directory -Force -Path $Stage | Out-Null diff --git a/packaging/windows/sign.ps1 b/packaging/windows/sign.ps1 index 81efe520a..7f37f8805 100644 --- a/packaging/windows/sign.ps1 +++ b/packaging/windows/sign.ps1 @@ -9,7 +9,9 @@ AZURE_SIGNING_ENDPOINT (e.g. https://eus.codesigning.azure.net), AZURE_SIGNING_ACCOUNT, AZURE_CERT_PROFILE With neither, it prints a warning and leaves the files unsigned (exit code 0), so test builds - still produce installers. + still produce installers. Nightly callers require signing with -Required and can + check signing configuration with -Required -CheckOnly. Compilation uses the + separate -CheckBuildEnvironment mode, without importing signing keys. This is the one place to adapt when the signing setup changes (an HSM/cloud key, a different timestamp server, ...). Optional overrides: WINDOWS_TIMESTAMP_URL, SIGNTOOL (path to signtool.exe). @@ -18,8 +20,11 @@ pwsh packaging/windows/sign.ps1 dist/designcraft.exe dist/Designcraft.msi #> param( - [Parameter(Mandatory = $true, ValueFromRemainingArguments = $true)] - [string[]] $Files + [Parameter(Position = 0, ValueFromRemainingArguments = $true)] + [string[]] $Files, + [switch] $Required, + [switch] $CheckOnly, + [switch] $CheckBuildEnvironment ) $ErrorActionPreference = 'Stop' @@ -27,6 +32,12 @@ function Write-Warn([string] $Message) { if ($env:GITHUB_ACTIONS) { Write-Output "::warning::$Message" } else { Write-Warning $Message } } +function Assert-AuthenticodeSignature($Signature) { + if (-not $Signature -or [string]$Signature.Status -cne 'Valid' -or -not $Signature.SignerCertificate) { + throw 'Required signing must produce a valid Authenticode signature and signer certificate' + } +} + function Find-SignTool { if ($env:SIGNTOOL) { return $env:SIGNTOOL } $onPath = Get-Command signtool.exe -ErrorAction SilentlyContinue @@ -44,11 +55,28 @@ function Invoke-SignTool([string[]] $Arguments) { if ($LASTEXITCODE -ne 0) { throw "signtool $($Arguments[0]) failed with exit code $LASTEXITCODE" } } -$Files = $Files | ForEach-Object { (Resolve-Path $_).Path } -$haveCert = [bool]$env:WINDOWS_CERTIFICATE $azureVars = 'AZURE_TENANT_ID', 'AZURE_CLIENT_ID', 'AZURE_CLIENT_SECRET', 'AZURE_SIGNING_ENDPOINT', 'AZURE_SIGNING_ACCOUNT', 'AZURE_CERT_PROFILE' +if ($CheckBuildEnvironment) { + if ($Required -or $CheckOnly -or $Files) { throw '-CheckBuildEnvironment is separate from signing' } + $names = @('WINDOWS_CERTIFICATE', 'WINDOWS_CERTIFICATE_PASSWORD') + $azureVars + if ($names | Where-Object { [Environment]::GetEnvironmentVariable($_) }) { + throw 'Compilation must not receive signing credentials; use a separate trusted signing step' + } + return +} +$haveCert = [bool]$env:WINDOWS_CERTIFICATE $haveAzure = -not ($azureVars | Where-Object { -not [Environment]::GetEnvironmentVariable($_) }) +if ($Required -and -not $haveCert -and -not $haveAzure) { + throw 'Nightly signing is required: configure WINDOWS_CERTIFICATE or the complete existing Azure signing configuration' +} +if ($CheckOnly) { + if ($Files) { throw '-CheckOnly does not sign files' } + return +} +if (-not $Files) { throw 'At least one file is required for signing' } +$Files = $Files | ForEach-Object { (Resolve-Path $_).Path } + if (-not $haveCert -and -not $haveAzure) { Write-Warn "Windows signing secrets not set (WINDOWS_CERTIFICATE or AZURE_*): leaving unsigned: $($Files -join ', ')" exit 0 @@ -96,6 +124,9 @@ try { Invoke-SignTool ($common + @('/tr', $ts, '/dlib', $dlib.FullName, '/dmdf', $metadata) + $Files) } Invoke-SignTool (@('verify', '/pa', '/v') + $Files) + if ($Required) { + foreach ($file in $Files) { Assert-AuthenticodeSignature (Get-AuthenticodeSignature -LiteralPath $file) } + } } finally { Remove-Item -Recurse -Force $tmp -ErrorAction SilentlyContinue diff --git a/sonar-project.properties b/sonar-project.properties index f1095122d..92ba6637b 100644 --- a/sonar-project.properties +++ b/sonar-project.properties @@ -1,2 +1,3 @@ sonar.projectKey=storytold_designcraft sonar.organization=storytold +sonar.coverage.exclusions=packaging/** diff --git a/xtask/src/pdf_deps.rs b/xtask/src/pdf_deps.rs index 0329e0f7f..ec9c46693 100644 --- a/xtask/src/pdf_deps.rs +++ b/xtask/src/pdf_deps.rs @@ -5,8 +5,8 @@ use std::process::Command; use serde_json::Value; const REPO: &str = "https://github.com/storytold/craft-libs"; -const REV: &str = "c60e7a20063313b80a994075adb4f797b24ab4f1"; -const COMMIT: &str = "c60e7a20063313b80a994075adb4f797b24ab4f1"; +const REV: &str = "33be35625e252cc4f06aa375b3b428521faea37d"; +const COMMIT: &str = "33be35625e252cc4f06aa375b3b428521faea37d"; const PACKAGES: &[(&str, &str)] = &[ ("craft-pdf", "0.1.0"), ("krilla", "0.8.2"),