mirror of
https://github.com/storytold/designcraft.git
synced 2026-12-01 19:04:21 +01:00
Merge remote-tracking branch 'origin/main' into rr-1280
This commit is contained in:
commit
f3b71a2d3f
149 files changed
+10577
-577
No files matched your search
@@ -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-----
|
||||
@@ -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"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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.
|
||||
@@ -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"]'
|
||||
@@ -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
|
||||
@@ -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 }}
|
||||
@@ -9,3 +9,7 @@ plan/
|
||||
/.claude/
|
||||
/target-*/
|
||||
/craft-fonts/
|
||||
/.nightly-tools
|
||||
/.nightly-input
|
||||
/craft-i18n
|
||||
__pycache__/
|
||||
@@ -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) |
|
||||
|
||||
Generated
+98
-126
@@ -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",
|
||||
]
|
||||
|
||||
+43
-43
@@ -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" }
|
||||
|
||||
+13
-1
@@ -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.
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
// `<sub> --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.
|
||||
//
|
||||
|
||||
@@ -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"] }
|
||||
@@ -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();
|
||||
|
||||
@@ -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<Prefs> {
|
||||
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<String>,
|
||||
/// 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<String>) -> 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<f64> {
|
||||
(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<String> {
|
||||
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");
|
||||
}
|
||||
}
|
||||
@@ -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<RecoveryDocument>) -> Result<bo
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// The page's local storage; `None` where the browser refuses it (some private modes).
|
||||
fn local_storage() -> Option<web_sys::Storage> {
|
||||
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<std::sync::Mutex<Vec<String>>>,
|
||||
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<ImportedFile> = 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 `<input type=file webkitdirectory>`, 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<u8>)> {
|
||||
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::<web_sys::HtmlInputElement>().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::<dyn FnMut()>::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:?}");
|
||||
|
||||
@@ -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.
|
||||
|
||||
+85
-10
@@ -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.<run>.<attempt>.g<sha12>`)
|
||||
//! 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.<run>.<attempt>.g<sha12>");
|
||||
}
|
||||
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<char> = 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::<String>() != 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}");
|
||||
}
|
||||
|
||||
@@ -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.<run>.<attempt>.g<sha12>` 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);
|
||||
}
|
||||
}
|
||||
@@ -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: `<App> <version> (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}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<OsString>,
|
||||
}
|
||||
|
||||
static PROFILE: OnceLock<Profile> = 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<OsString>) -> Result<Launch, String> {
|
||||
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<PathBuf, String>) -> Result<Launch, String> {
|
||||
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<OsString>, exe: Option<&Path>) -> Result<PathBuf, String> {
|
||||
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<OsString> {
|
||||
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<OsString> {
|
||||
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());
|
||||
}
|
||||
}
|
||||
+265
-29
@@ -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<eframe::wgpu::Device>,
|
||||
/// 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<egui::IconData> {
|
||||
// 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<String>) -> Option<u16> {
|
||||
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<std::ffi::OsString>,
|
||||
/// 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<Launched> {
|
||||
let argv: Vec<_> = std::env::args_os().skip(1).collect();
|
||||
// Plain `--version`, or the Launcher's `--launch-profile nightly-v1 --profile-root <dir>
|
||||
// --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 <port>` (Stable only).
|
||||
control_port: Option<u16>,
|
||||
/// `--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<String>,
|
||||
/// The graphics backends a restart asked to skip ([`gpu::SKIP_ARG`]).
|
||||
skip: Vec<String>,
|
||||
}
|
||||
|
||||
/// 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<Item = std::ffi::OsString>, 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::<Vec<_>>()) {
|
||||
if !launch.nightly
|
||||
&& let Some(result) = craft_update::self_update::finish(&designcraft_ui_egui::UPDATE_APP, &std::env::args_os().skip(1).collect::<Vec<_>>())
|
||||
{
|
||||
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");
|
||||
}
|
||||
}
|
||||
@@ -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<u8>,
|
||||
previous_unclean: bool,
|
||||
}
|
||||
|
||||
fn regular_or_missing(path: &Path) -> io::Result<bool> {
|
||||
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<Mutex<Option<Session>>>;
|
||||
|
||||
pub fn shared() -> Shared {
|
||||
shared_with(None)
|
||||
}
|
||||
|
||||
pub fn shared_with(session: Option<Session>) -> 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<Self>, 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<Option<Self>> {
|
||||
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::<std::collections::BTreeSet<_>>();
|
||||
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");
|
||||
}
|
||||
}
|
||||
@@ -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<Result<(), String>> = 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());
|
||||
}
|
||||
}
|
||||
@@ -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<PathBuf> {
|
||||
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<OsString>, exe_dir: Option<&Path>) -> Option<PathBuf> {
|
||||
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<PathBuf> {
|
||||
/// 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<PathBuf> {
|
||||
}
|
||||
|
||||
pub fn recovery_dir() -> Option<PathBuf> {
|
||||
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)
|
||||
}
|
||||
|
||||
@@ -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<Self, String> {
|
||||
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<PathBuf, String> {
|
||||
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<OsString>, key: &str) -> Result<PathBuf, String> {
|
||||
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<OsString>, key: &str, fallback: &str) -> Result<PathBuf, String> {
|
||||
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<PathBuf, String> {
|
||||
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::<Vec<_>>()
|
||||
};
|
||||
let (a, b) = (parts(a), parts(b));
|
||||
a.starts_with(&b) || b.starts_with(&a)
|
||||
}
|
||||
|
||||
fn installation_boundary(platform: Platform, exe: &Path) -> Result<PathBuf, String> {
|
||||
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<OsString>, exe: &Path) -> Result<Vec<PathBuf>, 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::<Result<Vec<_>, _>>()?;
|
||||
// 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::<Result<Vec<_>, _>>()?;
|
||||
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<Path>, label: &str) -> Result<PathBuf, String> {
|
||||
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<OsString>,
|
||||
exe: Option<&Path>,
|
||||
writable: impl FnOnce(&Path) -> std::io::Result<()>,
|
||||
) -> Result<PathBuf, String> {
|
||||
validate_for(Platform::current()?, root, env, exe, writable)
|
||||
}
|
||||
|
||||
fn validate_for(
|
||||
platform: Platform,
|
||||
root: &Path,
|
||||
env: impl Fn(&str) -> Option<OsString>,
|
||||
exe: Option<&Path>,
|
||||
writable: impl FnOnce(&Path) -> std::io::Result<()>,
|
||||
) -> Result<PathBuf, String> {
|
||||
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<String, OsString>,
|
||||
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<OsString> {
|
||||
self.env.get(key).cloned()
|
||||
}
|
||||
|
||||
fn check(&self, platform: Platform, root: &Path) -> Result<PathBuf, String> {
|
||||
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());
|
||||
}
|
||||
}
|
||||
@@ -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`.
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 827 KiB |
Binary file not shown.
Binary file not shown.
|
After Width: | Height: | Size: 99 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 44 KiB |
@@ -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."
|
||||
}
|
||||
@@ -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<CommandSpec> {
|
||||
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"))
|
||||
}
|
||||
)]
|
||||
}
|
||||
}
|
||||
@@ -451,11 +451,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
}
|
||||
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<u64> = 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;
|
||||
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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<Value> {
|
||||
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");
|
||||
|
||||
@@ -35,3 +35,5 @@ thread_local! {
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) mod eps_place_tests;
|
||||
#[cfg(test)]
|
||||
mod save_format_tests;
|
||||
@@ -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<u8>, Vec<String>)> {
|
||||
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<Document> {
|
||||
load_bytes(b).map(|(d, _)| d)
|
||||
}
|
||||
|
||||
@@ -48,9 +48,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
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)?;
|
||||
|
||||
@@ -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<Value> {
|
||||
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<Value> {
|
||||
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<Value> {
|
||||
/// anywhere.
|
||||
pub(super) fn file_save_a_copy(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
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<Value> {
|
||||
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}))
|
||||
|
||||
@@ -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::<Vec<_>>().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);
|
||||
}
|
||||
@@ -94,11 +94,14 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
/// `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<Option<HyperlinkDest>> {
|
||||
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<Opti
|
||||
(None, _) => 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();
|
||||
|
||||
@@ -28,8 +28,10 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
fn export_idml(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
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<u8>, Vec<String>)> {
|
||||
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<Option<Document>> {
|
||||
let choices: Vec<_> = doc
|
||||
.placed_items()
|
||||
@@ -503,7 +512,8 @@ fn import_interchange(s: &mut Session, bytes: Vec<u8>, 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<u8>, package: Option<&std::pat
|
||||
warnings.extend(font_warnings);
|
||||
warnings.extend(super::style::grep_style_warnings(&d));
|
||||
let warning_items: Vec<Value> = 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<u8>, Vec<u8>)> {
|
||||
let png = designcraft_render::Rendered { width: 2, height: 2, pixels: vec![255; 16] }.to_png();
|
||||
let mut session = Session::new();
|
||||
|
||||
@@ -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<CommandSpec> {
|
||||
vec![
|
||||
cmd!(
|
||||
@@ -770,33 +820,49 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
.map(LayerId)
|
||||
.or_else(|| ids.first().copied())
|
||||
.ok_or_else(|| bad("layer.merge", "no layers"))?;
|
||||
s.edit(|d, _| {
|
||||
let gone: Vec<LayerId> = 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<LayerId> = 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<LayerId> =
|
||||
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<LayerId> = 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));
|
||||
|
||||
+372
-17
@@ -57,6 +57,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
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<Arc<Vec<u8>>>, 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<u8>) -> Result<Arc<designcraft_doc::Asset>> {
|
||||
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<designcraft_doc::Asset> {
|
||||
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<Value> {
|
||||
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<String>, Vec<String>, Vec<bool>) {
|
||||
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<usize> = 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<Value> {
|
||||
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<String> = 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<AssetId> = 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::<Vec<_>>()), 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();
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -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<Vec<u8>>, 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<Vec<u8>>, page: u32, proxy: bool },
|
||||
/// Hash placed graphics that lack a `hash`, and make their proxy when requested.
|
||||
Prepare { key: SourceKey, bytes: Arc<Vec<u8>>, hash: Option<String>, 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<designcraft_render::proxy::ProxyImage> },
|
||||
}
|
||||
|
||||
/// 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<Vec<u8>>,
|
||||
hash: Option<String>,
|
||||
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<Vec<u8>>) -> 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<Pending>) {
|
||||
{
|
||||
// Taken from the end: the first placed is made first, before checks still waiting.
|
||||
let work: Vec<Work> =
|
||||
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<Outcome> {
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -50,7 +50,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"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()))?;
|
||||
|
||||
@@ -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<CommandSpec> {
|
||||
"{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<CommandSpec> {
|
||||
),
|
||||
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;
|
||||
@@ -15,6 +15,60 @@ pub(crate) fn story_of(s: &Session, p: &Value) -> Option<StoryId> {
|
||||
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<Option<StoryId>> {
|
||||
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<Option<StoryTarget>> {
|
||||
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<Option<StoryTarget>> {
|
||||
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<Option<StoryId>> {
|
||||
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<CellAddr>)> {
|
||||
hit_byte_with(s, frame, pt, compose::hit)
|
||||
|
||||
@@ -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<Value> {
|
||||
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
|
||||
|
||||
@@ -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());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -258,6 +258,9 @@ pub struct Prefs {
|
||||
pub recent_files: Vec<String>,
|
||||
/// 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.
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
@@ -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");
|
||||
}
|
||||
@@ -39,6 +39,7 @@ pub fn write<W: std::io::Write + std::io::Seek>(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<W: std::io::Write + std::io::Seek>(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::<Document>(&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)]
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
@@ -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.
|
||||
|
||||
@@ -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)> {
|
||||
|
||||
@@ -406,7 +406,7 @@ pub fn tool_definitions() -> Vec<Value> {
|
||||
"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<Value> {
|
||||
"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"),
|
||||
|
||||
+257
-31
@@ -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<f64> {
|
||||
fn find(it: &Item, g: &designcraft_doc::Graphic, around: f64, depth: usize) -> Option<f64> {
|
||||
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<vello_cpu::Pixmap>,
|
||||
plate: u8,
|
||||
to_pixels: Affine,
|
||||
area: impl FnOnce() -> Rect,
|
||||
) -> Option<(std::sync::Arc<vello_cpu::Pixmap>, (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<vello_cpu::color::PremulRgba8> {
|
||||
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<vello_cpu::Pixmap>, plate: u8) -> std::sync::Arc<vello_cpu::Pixmap> {
|
||||
// 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<vello_cpu::Pixmap>, std::sync::Arc<vello_cpu::Pixmap>);
|
||||
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<vello_cpu::Pixmap>, std::sync::Arc<vello_cpu::Pixmap>, u64);
|
||||
type Cache = (designcraft_color::cms::ColorSettings, std::collections::HashMap<(usize, u8), Entry>, usize, u64);
|
||||
static CACHE: std::sync::Mutex<Option<Cache>> = 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<vello_cpu::Pixmap>, plate: u8) ->
|
||||
}
|
||||
}
|
||||
let table = cmyk_table();
|
||||
let data: Vec<vello_cpu::color::PremulRgba8> = 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<usize> = 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<vello_cpu::Pixmap> {
|
||||
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");
|
||||
}
|
||||
}
|
||||
@@ -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<Rect> {
|
||||
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<Vec<(SpreadRef, Rect)>> {
|
||||
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() });
|
||||
|
||||
+34
-14
@@ -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<vello_cpu::Pixmap>,
|
||||
) {
|
||||
// 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();
|
||||
}
|
||||
@@ -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,
|
||||
|
||||
@@ -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(),
|
||||
|
||||
@@ -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");
|
||||
|
||||
@@ -12,7 +12,7 @@ impl DesignApp {
|
||||
#[track_caller]
|
||||
pub fn pick_and_open(&mut self, purpose: &str) -> Result<Value, String> {
|
||||
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<ImportedFile>) -> Vec<ImportedFile> {
|
||||
let mut rest = Vec::new();
|
||||
// (request, files) in arrival order; a request's files arrive together.
|
||||
let mut batches: Vec<(ImportRequest, Vec<ImportedFile>)> = 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<Value> = 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::<u64>().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##"<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20"/>"##.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<u8>) {
|
||||
app.services.inbox.as_ref().unwrap().lock().unwrap().push(ImportedFile { request, name: name.into(), bytes });
|
||||
app.drain_inbox();
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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<u64, String> {
|
||||
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<u64, String>,
|
||||
) -> Vec<(Pos2, LinkBadge, Color32)> {
|
||||
fn walk(
|
||||
doc: &Document,
|
||||
xf: &Xf,
|
||||
it: &Item,
|
||||
a: Affine,
|
||||
status: &std::collections::HashMap<u64, String>,
|
||||
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))
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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<String> {
|
||||
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<Rect> {
|
||||
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");
|
||||
}
|
||||
}
|
||||
@@ -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<Option<designcraft_render::Renderer>> = 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<u8> {
|
||||
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<Rect> = 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::<usize>(), 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::<usize>(), 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<designcraft_render::Placed> =
|
||||
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<u8> {
|
||||
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
|
||||
|
||||
@@ -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());
|
||||
}
|
||||
}
|
||||
@@ -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 {
|
||||
|
||||
@@ -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<Value, String> {
|
||||
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<Value, String> {
|
||||
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<Value, String> {
|
||||
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<String> {
|
||||
pub(crate) fn swatch_menu(ui: &mut egui::Ui, doc: &designcraft_doc::Document, id: impl egui::AsIdSalt, current: &str, width: f32) -> Option<String> {
|
||||
swatch_menu_with(ui, doc, id, current, width, None)
|
||||
}
|
||||
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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<String> = 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();
|
||||
|
||||
@@ -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", "تقسيم الملاحظة"),
|
||||
|
||||
@@ -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ě"),
|
||||
|
||||
@@ -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"),
|
||||
|
||||
@@ -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"),
|
||||
|
||||
@@ -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"),
|
||||
|
||||
@@ -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", "セルを横方向に分割"),
|
||||
|
||||
@@ -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", "უჯრის ჰორიზონტალურად გაყოფა"),
|
||||
|
||||
@@ -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"),
|
||||
|
||||
@@ -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"),
|
||||
|
||||
@@ -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", "Разделить ячейку по горизонтали"),
|
||||
|
||||
@@ -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"),
|
||||
|
||||
@@ -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", "排序"]),
|
||||
(
|
||||
|
||||
@@ -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() {
|
||||
|
||||
@@ -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", "Розділити клітинку горизонтально"),
|
||||
|
||||
@@ -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<QuitState>,
|
||||
/// A save waiting for the answer to "IDML can't keep all of this document" (`idmlLoss`).
|
||||
pub(crate) lossy_save: Option<menus::LossySave>,
|
||||
/// 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<u64>,
|
||||
/// 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<WaitingSave>,
|
||||
|
||||
@@ -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;
|
||||
|
||||
|
||||
@@ -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<Value, String> {
|
||||
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<Value, String> {
|
||||
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<Value, String> {
|
||||
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.
|
||||
|
||||
Loaded 100 of 149 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user