diff --git a/.github/workflows/house-rules.yml b/.github/workflows/house-rules.yml new file mode 100644 index 000000000..de64ad3ee --- /dev/null +++ b/.github/workflows/house-rules.yml @@ -0,0 +1,28 @@ +name: House rules + +on: + push: + branches: [main] + paths: + - AGENTS.md + - CLAUDE.md + - .github/workflows/house-rules.yml + pull_request: + paths: + - AGENTS.md + - CLAUDE.md + - .github/workflows/house-rules.yml + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: house-rules-${{ github.ref }} + cancel-in-progress: true + +jobs: + house-rules: + uses: storytold/craft-common-actions/.github/workflows/house-rules.yml@main + with: + rust: true diff --git a/.github/workflows/packaging-lint.yml b/.github/workflows/packaging-lint.yml index ea61d8430..1771a35fe 100644 --- a/.github/workflows/packaging-lint.yml +++ b/.github/workflows/packaging-lint.yml @@ -27,6 +27,10 @@ jobs: name: Windows installation policy (no app build) runs-on: windows-latest 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 diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 622ace75c..29b2c0c98 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1,6 +1,10 @@ name: Release on: + # A nightly dry run on main: every release build except macOS, nothing signed or released + # (craft-common-actions release.yml `dry-run`). Finds release-only breakage before release day. + schedule: + - cron: "24 1 * * *" push: branches: [release] workflow_dispatch: @@ -18,59 +22,28 @@ concurrency: cancel-in-progress: false jobs: - git-sources: - name: Git dependencies come from storytold - runs-on: ubuntu-latest + # Regenerates contributors/contributors.json for the release commit; every build bundles it. + credits: permissions: contents: read - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - persist-credentials: false - - name: Git dependencies come from storytold - run: | - set -euo pipefail - test -f Cargo.lock || { echo "Cargo.lock is missing"; exit 1; } - # Source replacement, patches and path overrides in cargo config never show up - # in Cargo.lock. Parsed rather than grepped: TOML has many spellings of one key. - # Cargo still reads the legacy .cargo/config. - python3 - <<'PY' - import os, sys, tomllib - for path in (".cargo/config", ".cargo/config.toml"): - if not os.path.exists(path): - continue - config = tomllib.load(open(path, "rb")) - replaced = [name for name, source in config.get("source", {}).items() - if isinstance(source, dict) and "replace-with" in source] - if replaced or "patch" in config or "paths" in config: - print(f"{path} replaces, patches or overrides a source") - sys.exit(1) - PY - # Fails when Cargo.lock is out of date with the manifests. - cargo metadata --locked --format-version 1 > /dev/null - python3 - <<'PY' - import sys, tomllib - lock = tomllib.load(open("Cargo.lock", "rb")) - bad = sorted({p["source"] for p in lock.get("package", []) - if p.get("source", "").startswith("git+") - and not p["source"].startswith("git+https://github.com/storytold/")}) - if bad: - print("Git dependencies outside github.com/storytold:", *bad, sep="\n") - sys.exit(1) - PY + pull-requests: read + uses: storytold/craft-common-actions/.github/workflows/refresh-contributors.yml@main release: - needs: git-sources + needs: credits permissions: contents: write + packages: write # Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos. uses: storytold/craft-common-actions/.github/workflows/release.yml@main with: + dry-run: ${{ github.event_name == 'schedule' }} app-name: designcraft app-title: DesignCraft craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83 web-craft-fonts: true version: ${{ inputs.version }} + contributors-artifact: ${{ needs.credits.outputs.artifact-name }} secrets: APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }} APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }} @@ -86,3 +59,4 @@ jobs: AZURE_SIGNING_ENDPOINT: ${{ secrets.AZURE_SIGNING_ENDPOINT }} AZURE_SIGNING_ACCOUNT: ${{ secrets.AZURE_SIGNING_ACCOUNT }} AZURE_CERT_PROFILE: ${{ secrets.AZURE_CERT_PROFILE }} + LINUX_SIGNING_KEY: ${{ secrets.LINUX_SIGNING_KEY }} diff --git a/.github/workflows/sonarcloud.yml b/.github/workflows/sonarcloud.yml index e78fe1ea3..c5731a0ae 100644 --- a/.github/workflows/sonarcloud.yml +++ b/.github/workflows/sonarcloud.yml @@ -18,4 +18,6 @@ jobs: sonarcloud: # Tracked at @main so org-wide CI improvements propagate without PR churn. uses: storytold/craft-common-actions/.github/workflows/sonarcloud.yml@main + with: + fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83 secrets: inherit diff --git a/.github/workflows/windows-arm64.yml b/.github/workflows/windows-arm64.yml index 211ed988d..668e904d2 100644 --- a/.github/workflows/windows-arm64.yml +++ b/.github/workflows/windows-arm64.yml @@ -26,8 +26,8 @@ permissions: jobs: windows-arm64: - # Immutable supporting workflow revision until the new install contract lands upstream. - uses: storytold/craft-common-actions/.github/workflows/windows-arm64.yml@8bb4e5ab95443171104ad88113fe1ef9b0e5ce3f + # Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos. + uses: storytold/craft-common-actions/.github/workflows/windows-arm64.yml@main with: app-name: designcraft app-dir: DesignCraft diff --git a/AGENTS.md b/AGENTS.md index 0be7fa87b..fff6f71a0 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,15 +1,65 @@ + +## House rules + +These apply in every Craft repository. A later rule may be stricter, not weaker. The source is `standards/house-rules-core.md` in `storytold/craft-contrib`. Propose changes there, not in a copy. + +1. **A person is accountable.** Whoever runs an agent answers for what it opens and for its review comments. +2. **Check, then claim.** Before writing code, read the issue comments, search pull requests for `#N` and the keywords, and check recent commits on `main`. Comment on the issue first. Release a claim you will not finish. +3. **Verify, don't guess.** Open a definition before using it. Confirm the cause in the code, even when someone names a location. +4. **Keep fixes narrow and tested.** Fix what the issue describes, where the bug is. Add a test that fails without the fix. +5. **Review the diff before opening a pull request.** Identifiers exist as used, the test fails without the fix, nothing unrelated changed, and the description is true. +6. **Look for a better pull request.** If another fixes the same thing, close yours when it is better or equal, and say why. +7. **Report only what ran.** Say what you tested and what you could not run. Without a local build or test, say so and rely on CI before marking ready. +8. **`main` changes through a pull request.** Do not push to it. Branch protection enforces this. There is no exception. +9. **Stop and ask only about** licensing outside the allowlist, publishing, releases, a new remote, secrets, spending money, destructive git, and anything else hard to undo. Otherwise keep working. `plan/` is a gitignored notebook, not rules. Without it, do not ask for it and do not stop. +10. **Keep secrets and personal details out** of the repository, logs and requests. +11. **CI stays shared.** Workflows call `storytold/craft-common-actions`. Do not change CI in a feature or fix pull request. If CI cannot cover a change, open an issue there. +12. **Guards say why.** A check that looks removable says what it prevents. Read that before changing it. +13. **Instructions must be readable by everyone.** No notes about one machine, and no links to files a reader cannot open. `craftrules` is retired. Do not link to it. +14. **Keep pull requests moving.** Concurrent pull requests are fine; unanswered actionable feedback is not. Respond in 7 days, a reminder at 14, closure eligible at 30, from when an actionable request waits on the author. Suggestions and unconfirmed bot findings do not start the clock. A fix, explanation or agreed plan resets it; unrelated activity does not. Waiting on a reviewer or maintainer pauses it and does not count against the author. A maintainer decides closure; it is never automatic. Reuse search results, do not poll, and stop at a rate limit. +15. **No agent attribution.** A pull request does not say an agent wrote it. A repository rule may not require that. + + +## Rust Craft repositories + +These apply to native Craft apps and to shared Rust libraries. Select them by repository type. A repository that merely contains some Rust does not take this block. Rules later in a repository's file may be stricter, but not weaker. The source is `standards/house-rules-rust.md` in [storytold/craft-contrib](https://github.com/storytold/craft-contrib). + +1. **Never crash.** Non-test code does not panic and has no `unsafe`, except where the repository file names an exception. Return errors, treat input as hostile, and bound recursion and allocations. New production crate roots copy the `deny` attribute from an existing crate: `clippy::unwrap_used`, `clippy::expect_used`, `clippy::panic`, `clippy::unimplemented`, `clippy::todo`, `clippy::unreachable`. Every crash fix comes with a test that panicked before the fix. +2. **Clean room.** Learn from observed behaviour and public specifications. Do not copy another product's code, assets, strings or artwork. Check a dependency's licence before adding it. +3. **Assets and fonts.** Every asset is original or suitably licensed, and is recorded in `ATTRIBUTION.md` in the same change. Font files live in [storytold/craft-fonts](https://github.com/storytold/craft-fonts), not in the app repository. +4. **Rust only for native Craft apps.** No handwritten JavaScript or TypeScript, and no Tauri, Electron or webview shell, in those apps. Shared tooling follows its documented technical scope and maintainer-approved exceptions. Craft PR Review's existing Tauri and TypeScript UI is one such exception. It does not relax this rule for native apps. Preserve any existing web build. +5. **Time goes through `chrono`.** Do not hand-roll calendar conversion. For dates beyond what `chrono` can represent, follow [standards/time.md](https://github.com/storytold/craft-contrib/blob/main/standards/time.md). +6. **Contributor credits.** Add or edit only your own person's entry in `contributors/people.toml`, and only after asking them. Never guess a name or hand-edit `contributors.json`. + +## Licence allowlist + +Dependencies and assets use SPDX identifiers. An expression is allowed when every identifier is in this list. A repository may name a shorter list. It may not add an identifier here by editing its own copy of these rules. + +- `ISC` +- `MIT` +- `BSD-2-Clause` +- `BSD-3-Clause` +- `Apache-2.0` +- `OFL-1.1` +- `Ubuntu-font-1.0` +- `Bitstream-Vera` +- `CC0-1.0` +- `CC-BY-4.0` +- `CC-BY-SA-4.0` +- `LicenseRef-Public-Domain` + +`LicenseRef-Storyteller-Trademark` is not in this list. It covers Storyteller brand marks only, where a repository already says so. + + # DesignCraft — instructions for agents DesignCraft is a clean-room, open-source, Rust-native page-layout application targeting Adobe InDesign parity — and superiority (speed, openness, agent control). It runs natively on macOS, Windows and Linux, and on the web via WASM. Siblings with the same conventions: `../vectorcraft` (Illustrator-class), `../photocraft` (Photoshop), `../pdfcraft` (Acrobat), `../filmcraft` (Premiere), `../lightcraft` (Lightroom). ## Start every session here -1. Read `plan/STATUS.md` (current milestone, next task), then the task in `plan/execution-plan.md` and the relevant `plan/architecture.md` section. Behaviour reference: `plan/indesign/*.md` (`11-observed-ui.md` holds measured observations of the running app). -2. Follow the autonomous operation protocol (`plan/execution-plan.md` §7). Don't stop to ask unless §7 lists the decision as the user's. - -`plan/` is gitignored (local only). +Read [`ROADMAP.md`](ROADMAP.md) and [`docs/gaps.md`](docs/gaps.md). `plan/` is an optional gitignored notebook (status, execution notes, `plan/indesign/*.md`). Do not ask for it and do not stop when it is absent. ## Never crash -People trust DesignCraft with their layouts; a crash loses their work. **This outranks feature work**: never ship a feature through a panic path, and fix a crash before building on top of it. Standard: [`craftrules/standards/never-crash.md`](https://github.com/storytold/craftrules/blob/main/standards/never-crash.md). +People trust DesignCraft with their layouts; a crash loses their work. **This outranks feature work**: never ship a feature through a panic path, and fix a crash before building on top of it. - **No panics in non-test code:** no `unwrap()`, `expect()`, `panic!`, `unreachable!`, `todo!`, `unimplemented!`; no `unsafe` (`unsafe_code = "forbid"`). The one exception is a provably infallible literal (a constant regex, `write!` to a `String`): `#[allow(clippy::expect_used)]` + `.expect("why it cannot fail")`. - **Errors are `Result`** through the crate's error type and `?` (`ok_or(..)?`, `let … else`, `if let`, `map_err` for context). An unfinished feature returns an "unsupported" error. Don't `unwrap_or_default()` where a silent default would corrupt a document; return an error. - **Input-derived numbers are hostile** (files, commands, MCP/control params, settings): `get()` instead of `[i]`/`[a..b]`, slice strings at char boundaries, checked/saturating arithmetic for lengths and offsets, no division by zero or NaN casts, cap input-sized allocations. @@ -21,40 +71,46 @@ People trust DesignCraft with their layouts; a crash loses their work. **This ou ## Non-negotiables - **Clean-room.** InDesign is installed on the dev machine and may be *observed* black-box: run it, use its UI with synthetic documents, take screenshots (by window id) stored only under `plan/indesign/screenshots/` (never committed). Never read, disassemble or copy anything inside the InDesign bundle (names/listings only), never copy Adobe icons, artwork, presets or wording beyond feature names, never commit files produced by InDesign. Never copy GPL/AGPL/LGPL code (Scribus, LibreOffice, Ghostscript…). - **Assets:** no Adobe iconography or images — ever. Every asset is original / OSI / CC0 / redistributable CC (except the ArtCraft trademarks in `docs/brand/`, under `docs/brand/LICENSE-brand.txt`) and has a row in `ASSETS.md` (`cargo xtask assets` enforces it). Prefer art generated in code. -- **Fonts live in [`storytold/craft-fonts`](https://github.com/storytold/craft-fonts)**, never in this repo: don't commit new font files (the Latin UI/document fonts already in `assets/fonts/` stay). It is an optional build input, never a `Cargo.toml` dependency: `CRAFT_FONTS_DIR=/abs/path/to/craft-fonts cargo build` makes `crates/fonts/build.rs` embed its fonts as `designcraft_fonts::CRAFT_FONTS` (Japanese: BIZ UDPGothic for the UI, Mincho first for document text; web builds embed BIZ UDPGothic Regular only). Unset, `CRAFT_FONTS` is empty and the app uses its bundled and system fonts; code and tests must work that way (tests on its glyphs skip). Releases build with it. Standard: [craftrules `standards/fonts.md`](https://github.com/storytold/craftrules/blob/main/standards/fonts.md). -- **Shared test corpora.** Real-file test oracles (Photoshop-authored PSDs, etc.) live in [`storytold/photocraft-corpus`](https://github.com/storytold/photocraft-corpus), explained in [craftrules `standards/test-corpora.md`](https://github.com/storytold/craftrules/blob/main/standards/test-corpora.md). Never commit large binary fixtures to this repo; fetch them pinned by commit and sha256-verified, as PhotoCraft does with `cargo xtask corpus`. +- **Fonts live in [`storytold/craft-fonts`](https://github.com/storytold/craft-fonts)**, never in this repo: don't commit new font files (the Latin UI/document fonts already in `assets/fonts/` stay). It is an optional build input, never a `Cargo.toml` dependency: `CRAFT_FONTS_DIR=/abs/path/to/craft-fonts cargo build` makes `crates/fonts/build.rs` embed its fonts as `designcraft_fonts::CRAFT_FONTS` (Japanese: BIZ UDPGothic for the UI, Mincho first for document text; web builds embed BIZ UDPGothic Regular only). Unset, `CRAFT_FONTS` is empty and the app uses its bundled and system fonts; code and tests must work that way (tests on its glyphs skip). Releases build with it. +- **Shared test corpora.** Real-file test oracles (Photoshop-authored PSDs, etc.) live in [`storytold/photocraft-corpus`](https://github.com/storytold/photocraft-corpus). Never commit large binary fixtures to this repo; fetch them pinned by commit and sha256-verified, as PhotoCraft does with `cargo xtask corpus`. - **Everything is a command.** User-visible behaviour = a command in `crates/engine/src/cmd/*` (id, label, menu path, shortcut, params doc, `enabled`, `run`) + tests. Tools emit commands (Begin/Preview/Commit). UI-only commands live in `crates/ui-egui/src/menus.rs` (`UI_COMMANDS`). The control channel and MCP reach all of them. - **Layering** is enforced by `cargo xtask layers`. Nothing below L6 depends on egui/eframe/winit/rfd. The UI crate is swappable. - **The UI is thin**: panels read engine state and act through `app.run(id, params)`. Colours come from `theme::Tokens`. -- **Time goes through `chrono`** (workspace dependency). Never hand-roll UTC/calendar conversion (days-to-date algorithms, leap-year math). A crate owns only its output format string. The one exception is range extension: past the years chrono can represent, shift the date by whole 400-year Gregorian cycles (146,097 days, after which the calendar repeats), let chrono compute the month and day, and add the cycles back to the year (splitting seconds into hours, minutes and seconds is plain arithmetic). - **Rust only** (no handwritten JS/TS). **Never break wasm** (`cargo xtask wasm`). - **Quality gates** before every commit: `cargo xtask ci` (fmt, clippy -D warnings, tests, assets, layers, wasm). One task id per commit (`M2.1: type tool caret navigation`). ## Running and looking at the app - `cargo run --release -p designcraft -- --sample --control 7979` (sample magazine + control channel). - Drive it: JSON lines on `127.0.0.1:7979`, e.g. `{"id":1,"method":"engine.execute","params":{"command":"frame.create","params":{"rect":[36,36,300,200],"content":"text"}}}` then `{"id":2,"method":"ui.screenshot","params":{"path":"/tmp/shot.png"}}`. Methods: `crates/ui-egui/src/control.rs`, docs: `docs/control-protocol.md`. -- **For UI work, look at the result** (take `ui.screenshot`, read the PNG) and compare with `plan/indesign/02-ui-ux.md` / `11-observed-ui.md`. If no frame is presented (screen locked) use `ui.render` or `designcraft-cli run --sample --all-pages DIR`. +- **For UI work, look at the result** (take `ui.screenshot`, read the PNG) and, when available, compare with `plan/indesign/02-ui-ux.md` / `11-observed-ui.md`. Without those optional notes, verify the intended behaviour against the task and committed documentation. If no frame is presented (screen locked) use `ui.render` or `designcraft-cli run --sample --all-pages DIR`. - Headless: `designcraft-cli run --sample --cmd 'frame.create={"rect":[0,0,100,100]}' --export out.png`. -- Shell gotcha: `mv`/`cp` are aliased interactive here — use `/bin/mv -f` / `/bin/cp -f`. - Parallel agents: separate `CARGO_TARGET_DIR` per agent; edit only the crates you own; delete your target dir when done (disk). ## Roadmap -`ROADMAP.md` (committed) is the one-page summary: stage, headline numbers, dimensions, languages, progress log. It follows craftrules' [`standards/progress-docs.md`](https://github.com/storytold/craftrules/blob/main/standards/progress-docs.md). Details: `docs/target-app-parity.md` (assessment), `docs/gaps.md` (ranked work list: pick from the top), `docs/roadmap.md` (milestones, current focus), `docs/parity-checklist.md` (presence checklist, `cargo xtask parity`), and the typography, file-format, UI, hardware and localization parity docs in `docs/`. When work lands, update the affected docs and their status lines, delete or shrink the closed gap, and add a progress-log line to ROADMAP.md. +`ROADMAP.md` (committed) is the one-page summary: stage, headline numbers, dimensions, languages, progress log. Details: `docs/target-app-parity.md` (assessment), `docs/gaps.md` (ranked work list: pick from the top), `docs/roadmap.md` (milestones, current focus), `docs/parity-checklist.md` (presence checklist, `cargo xtask parity`), and the typography, file-format, UI, hardware and localization parity docs in `docs/`. When work lands, update the affected docs and their status lines, delete or shrink the closed gap, and add a progress-log line to ROADMAP.md. ## Contributor credits (About window) - About ▸ Contributors/Models are compiled into the binary from `contributors/contributors.json` - (commit stats; generated, never hand-edit) and `contributors/people.toml` (names people chose for + (commit stats; never hand-edit) and `contributors/people.toml` (names people chose for themselves). See `docs/contributors.md`. - **Agents working for a contributor:** when you prepare a PR, check whether your human's GitHub username has a `[people.]` entry in `contributors/people.toml`. If not, ask them once whether they want to be credited by more than their username: a real name, a display name, and/or their public GitHub profile name (`sync_github_name = true`). If yes, add **only their own** entry - (copy the template at the top of the file, or run - `python3 ../../craftrules/scripts/contributors.py --add-me . --real-name "…" --sync-github-name`) + (copy the template at the top of the file) and include it in their PR, committed as them. If no, change nothing: they are credited as `@username` anyway. - Never add, edit, guess or copy anyone else's entry or name (not from git config, commit authors or GitHub profiles). Never hand-edit `contributors.json`. -- Maintainers refresh the stats with `python3 ../../craftrules/scripts/contributors.py .` (it also - re-verifies who wrote each `people.toml` entry; `--check` only verifies). + +## CI workflows +- Workflows in `.github/workflows/` call the shared workflows in [`storytold/craft-common-actions`](https://github.com/storytold/craft-common-actions) at `@main`, with their inputs and secrets. No other jobs: if no shared workflow does what's needed, it doesn't go here. +- Don't add or change CI in a feature or fix PR. If the existing workflows can't build or test a change, link an existing craft-common-actions issue or PR, or open a new issue, or a PR only for a small fix that is safe for every app and does not increase CI time. +- Some workflow files here still run their own jobs. Don't add to them. Moving a job into craft-common-actions is its own task, never part of another PR, and the job stays here until a shared workflow runs it. + +New workspace crates include `workspace = true` under `[lints]` in `Cargo.toml`. Production crate roots declare the crate-level lint attributes before modules; crate-level `//!` documentation may precede them. + +## Shared libraries + +Before adding or changing file-format, codec, protocol, or reusable UI code, check `storytold/craft-libs` and its open PRs first; reuse or extend the shared library rather than duplicating it locally, keep app-specific policy and model mapping in the app, and preserve behavior, security/resource limits, attribution, and regression coverage during cutovers. diff --git a/ASSETS.md b/ASSETS.md index 356309cee..4297ab421 100644 --- a/ASSETS.md +++ b/ASSETS.md @@ -2,12 +2,13 @@ Every non-code asset in this repository (fonts, images, example art, presets) is listed here with its author, source and licence. `cargo xtask assets` (part of `cargo xtask ci`) fails if an asset file is missing from this table. -**Policy (mandatory):** DesignCraft contains **no Adobe iconography, images, artwork, presets, swatch libraries or ICC profiles**. Every asset is original work by DesignCraft contributors or third-party material under an open licence (OSI open source, public domain / CC0, or Creative Commons that allows redistribution). Screenshots of Adobe software are never committed. Font files are not added here: shared fonts live in [storytold/craft-fonts](https://github.com/storytold/craft-fonts), an optional build input (`CRAFT_FONTS_DIR`, see AGENTS.md and craftrules [`standards/fonts.md`](https://github.com/storytold/craftrules/blob/main/standards/fonts.md)). The one exception is the ArtCraft brand files in `docs/brand/`: ArtCraft trademarks, not open source, used under `docs/brand/LICENSE-brand.txt`. +**Policy (mandatory):** DesignCraft contains **no Adobe iconography, images, artwork, presets, swatch libraries or ICC profiles**. Every asset is original work by DesignCraft contributors or third-party material under an open licence (OSI open source, public domain / CC0, or Creative Commons that allows redistribution). Screenshots of Adobe software are never committed. Font files are not added here: shared fonts live in [storytold/craft-fonts](https://github.com/storytold/craft-fonts), an optional build input (`CRAFT_FONTS_DIR`, see AGENTS.md). The one exception is the ArtCraft brand files in `docs/brand/`: ArtCraft trademarks, not open source, used under `docs/brand/LICENSE-brand.txt`. Generated-in-code art is original and has no file to list: the UI icon set (`crates/ui-egui/src/icons.rs`), default swatches, and the sample magazine's imagery (`crates/engine/src/sample.rs`). | Asset | Author | Source | Licence | Notes | |---|---|---|---|---| +| German hyphenation patterns (embedded by `hypher` 0.1.8, feature `german`) | Deutschsprachige Trennmustermannschaft: Stephan Hennig, Werner Lemberg, Günter Milde, Sander van Geloven, Georg Pfeiffer, Gisbert W. Selke, Tobias Wendorf, Keno Wehr | https://github.com/typst/hypher/blob/d81cc506416bffef2a75ee2dc969d4b41bc36613/patterns/hyph-de-1996.tex | MIT (copyright 2013–2024; full text in NOTICE) | Version 2024-02-28; reformed German spelling (2006), despite the `de-1996` filename; no separate old-spelling or Swiss patterns | | `epaint_default_fonts/fonts/egui-icons.ttf` (egui dependency) | John Slegers (emoji-icon-font) | https://github.com/storytold/egui/blob/173cc7375d35dc5fbc5b5d0994fdf787f547c5d1/crates/epaint_default_fonts/fonts/egui-icons.txt; original https://github.com/jslegers/emoji-icon-font | MIT (full text in NOTICE) | Small special-icon subset embedded by default_fonts | | `epaint_default_fonts/fonts/emoji-icon-font.ttf` (egui dependency) | John Slegers | https://github.com/storytold/egui/blob/173cc7375d35dc5fbc5b5d0994fdf787f547c5d1/crates/epaint_default_fonts/fonts/emoji-icon-font-mit-license.txt; original https://github.com/jslegers/emoji-icon-font | MIT (full text in NOTICE) | Parent face embedded by monochrome_emoji_fonts | | `crates/ui-egui/src/i18n/uk.rs` (332 common phrases) | VectorCraft contributors | https://github.com/storytold/vectorcraft/blob/01f329aa99fa0c9517311c7b6cf7233ffc207742/crates/ui-egui/src/i18n/uk.tsv | MIT OR Apache-2.0 | Adapted for DesignCraft context; remaining Ukrainian phrases are original or credited below | @@ -51,10 +52,10 @@ Generated-in-code art is original and has no file to list: the UI icon set (`cra | `assets/app-icon/LICENSE.txt` | (licence text) | this project | — | Licence for the app icon | | `assets/app-icon/designcraft-1024.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/designcraft-macos-512.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/designcraft-small.svg` | DesignCraft project owner (drawn in ArtCraft) | owner's ArtCraft drawing, vectorised with craftrules `assets/logo-options/_tools/vectorize_tile.py` | 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-small.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.icns` | 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/designcraft.ico` | 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/designcraft.svg` | DesignCraft project owner (drawn in ArtCraft) | owner's ArtCraft drawing, vectorised with craftrules `assets/logo-options/_tools/vectorize_tile.py` | 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.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/hicolor/128x128/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/16x16/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/24x24/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`) | @@ -63,7 +64,7 @@ Generated-in-code art is original and has no file to list: the UI icon set (`cra | `assets/app-icon/hicolor/48x48/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/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, vectorised with craftrules `assets/logo-options/_tools/vectorize_tile.py` | 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`) | | `docs/brand/artcraft-logo.svg`, `docs/brand/artcraft-logo.png` | ArtCraft / Storyteller | ArtCraft brand kit (project owner) | ArtCraft trademark, see docs/brand/LICENSE-brand.txt (not open source) | ArtCraft wordmark (README header) | | `docs/brand/artcraft-logo-white.svg`, `docs/brand/artcraft-logo-white.png` | ArtCraft / Storyteller | ArtCraft brand kit (project owner) | ArtCraft trademark, see docs/brand/LICENSE-brand.txt (not open source) | Wordmark for dark backgrounds | | `docs/brand/artcraft-mark.svg`, `docs/brand/artcraft-mark.png` | ArtCraft / Storyteller | ArtCraft brand kit (project owner) | ArtCraft trademark, see docs/brand/LICENSE-brand.txt (not open source) | The mark; its outline is drawn in code by `crates/ui-egui/src/about.rs` (About splash, start screen) | diff --git a/CLAUDE.md b/CLAUDE.md index bed556afb..43c994c2d 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1,41 +1 @@ -# DesignCraft — instructions for agents - -DesignCraft is a clean-room, open-source, Rust-native page-layout application targeting Adobe InDesign parity — and superiority (speed, openness, agent control). It runs natively on macOS, Windows and Linux, and on the web via WASM. Siblings with the same conventions: `../vectorcraft` (Illustrator-class), `../photocraft` (Photoshop), `../pdfcraft` (Acrobat), `../filmcraft` (Premiere), `../lightcraft` (Lightroom). - -## Start every session here -1. Read `plan/STATUS.md` (current milestone, next task), then the task in `plan/execution-plan.md` and the relevant `plan/architecture.md` section. Behaviour reference: `plan/indesign/*.md` (`11-observed-ui.md` holds measured observations of the running app). -2. Follow the autonomous operation protocol (`plan/execution-plan.md` §7). Don't stop to ask unless §7 lists the decision as the user's. - -`plan/` is gitignored (local only). - -## Never crash -People trust DesignCraft with their layouts; a crash loses their work. **This outranks feature work**: never ship a feature through a panic path, and fix a crash before building on top of it. Standard: [`craftrules/standards/never-crash.md`](https://github.com/storytold/craftrules/blob/main/standards/never-crash.md). -- **No panics in non-test code:** no `unwrap()`, `expect()`, `panic!`, `unreachable!`, `todo!`, `unimplemented!`; no `unsafe` (`unsafe_code = "forbid"`). The one exception is a provably infallible literal (a constant regex, `write!` to a `String`): `#[allow(clippy::expect_used)]` + `.expect("why it cannot fail")`. -- **Errors are `Result`** through the crate's error type and `?` (`ok_or(..)?`, `let … else`, `if let`, `map_err` for context). An unfinished feature returns an "unsupported" error. Don't `unwrap_or_default()` where a silent default would corrupt a document; return an error. -- **Input-derived numbers are hostile** (files, commands, MCP/control params, settings): `get()` instead of `[i]`/`[a..b]`, slice strings at char boundaries, checked/saturating arithmetic for lengths and offsets, no division by zero or NaN casts, cap input-sized allocations. -- **Bound recursion** (seen-sets or depth limits for nested or cyclic documents). **Locks:** `lock().unwrap_or_else(PoisonError::into_inner)` or an error; thread joins are `Result`s. -- **Last-resort guard:** escaped panics during command execution and file import/export become an error, never a lost document. It's a safety net, not a licence. -- **Prove it:** every crash fix lands with a small synthetic regression test that panicked before the fix. -- Clean crates carry `#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]`; new production crate roots must include the attribute before modules or other crate items, with crate-level `//!` documentation allowed before it. Every new workspace crate must also include `[lints] workspace = true` in `Cargo.toml` to inherit `[workspace.lints]`. Tests may `unwrap` (`clippy.toml`). - -## Non-negotiables -- **Clean-room.** InDesign is installed on the dev machine and may be *observed* black-box: run it, use its UI with synthetic documents, take screenshots (by window id) stored only under `plan/indesign/screenshots/` (never committed). Never read, disassemble or copy anything inside the InDesign bundle (names/listings only), never copy Adobe icons, artwork, presets or wording beyond feature names, never commit files produced by InDesign. Never copy GPL/AGPL/LGPL code (Scribus, LibreOffice, Ghostscript…). -- **Assets:** no Adobe iconography or images — ever. Every asset is original / OSI / CC0 / redistributable CC (except the ArtCraft trademarks in `docs/brand/`, under `docs/brand/LICENSE-brand.txt`) and has a row in `ASSETS.md` (`cargo xtask assets` enforces it). Prefer art generated in code. -- **Fonts live in [`storytold/craft-fonts`](https://github.com/storytold/craft-fonts)**, never in this repo: don't commit new font files (the Latin UI/document fonts already in `assets/fonts/` stay). It is an optional build input, never a `Cargo.toml` dependency: `CRAFT_FONTS_DIR=/abs/path/to/craft-fonts cargo build` makes `crates/fonts/build.rs` embed its fonts as `designcraft_fonts::CRAFT_FONTS` (Japanese: BIZ UDPGothic for the UI, Mincho first for document text; web builds embed BIZ UDPGothic Regular only). Unset, `CRAFT_FONTS` is empty and the app uses its bundled and system fonts; code and tests must work that way (tests on its glyphs skip). Releases build with it. Standard: [craftrules `standards/fonts.md`](https://github.com/storytold/craftrules/blob/main/standards/fonts.md). -- **Shared test corpora.** Real-file test oracles (Photoshop-authored PSDs, etc.) live in [`storytold/photocraft-corpus`](https://github.com/storytold/photocraft-corpus), explained in [craftrules `standards/test-corpora.md`](https://github.com/storytold/craftrules/blob/main/standards/test-corpora.md). Never commit large binary fixtures to this repo; fetch them pinned by commit and sha256-verified, as PhotoCraft does with `cargo xtask corpus`. -- **Everything is a command.** User-visible behaviour = a command in `crates/engine/src/cmd/*` (id, label, menu path, shortcut, params doc, `enabled`, `run`) + tests. Tools emit commands (Begin/Preview/Commit). UI-only commands live in `crates/ui-egui/src/menus.rs` (`UI_COMMANDS`). The control channel and MCP reach all of them. -- **Layering** is enforced by `cargo xtask layers`. Nothing below L6 depends on egui/eframe/winit/rfd. The UI crate is swappable. -- **The UI is thin**: panels read engine state and act through `app.run(id, params)`. Colours come from `theme::Tokens`. -- **Rust only** (no handwritten JS/TS). **Never break wasm** (`cargo xtask wasm`). -- **Quality gates** before every commit: `cargo xtask ci` (fmt, clippy -D warnings, tests, assets, layers, wasm). One task id per commit (`M2.1: type tool caret navigation`). - -## Running and looking at the app -- `cargo run --release -p designcraft -- --sample --control 7979` (sample magazine + control channel). -- Drive it: JSON lines on `127.0.0.1:7979`, e.g. `{"id":1,"method":"engine.execute","params":{"command":"frame.create","params":{"rect":[36,36,300,200],"content":"text"}}}` then `{"id":2,"method":"ui.screenshot","params":{"path":"/tmp/shot.png"}}`. Methods: `crates/ui-egui/src/control.rs`, docs: `docs/control-protocol.md`. -- **For UI work, look at the result** (take `ui.screenshot`, read the PNG) and compare with `plan/indesign/02-ui-ux.md` / `11-observed-ui.md`. If no frame is presented (screen locked) use `ui.render` or `designcraft-cli run --sample --all-pages DIR`. -- Headless: `designcraft-cli run --sample --cmd 'frame.create={"rect":[0,0,100,100]}' --export out.png`. -- Shell gotcha: `mv`/`cp` are aliased interactive here — use `/bin/mv -f` / `/bin/cp -f`. -- Parallel agents: separate `CARGO_TARGET_DIR` per agent; edit only the crates you own; delete your target dir when done (disk). - -## Roadmap -`ROADMAP.md` (committed) is the one-page summary: stage, headline numbers, dimensions, languages, progress log. It follows craftrules' [`standards/progress-docs.md`](https://github.com/storytold/craftrules/blob/main/standards/progress-docs.md). Details: `docs/target-app-parity.md` (assessment), `docs/gaps.md` (ranked work list: pick from the top), `docs/roadmap.md` (milestones, current focus), `docs/parity-checklist.md` (presence checklist, `cargo xtask parity`), and the typography, file-format, UI, hardware and localization parity docs in `docs/`. When work lands, update the affected docs and their status lines, delete or shrink the closed gap, and add a progress-log line to ROADMAP.md. +@AGENTS.md diff --git a/Cargo.lock b/Cargo.lock index 1c361aef2..7f96b25db 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -116,6 +116,17 @@ version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" +[[package]] +name = "aes" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc0fc36d7440d015b45468ba08a21e80e056ebbd014c611c6298bb7503e04bd1" +dependencies = [ + "cipher", + "cpubits", + "cpufeatures 0.3.1", +] + [[package]] name = "ahash" version = "0.8.12" @@ -150,13 +161,28 @@ version = "2.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cc7bb162ec39d46ab1ca8c77bf72e890535becd1751bb45f64c597edb4c8c6b3" +[[package]] +name = "alloc-no-stdlib" +version = "3.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2fb6cfd47bf496ff64095c20eaba0c201404ee38714d4142fcfa1dc334fcc7a" + [[package]] name = "alloc-stdlib" version = "0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0e76a019e91224d279006ff972f1e984179a6e9feb050adba6ce8274aef23195" dependencies = [ - "alloc-no-stdlib", + "alloc-no-stdlib 2.0.4", +] + +[[package]] +name = "alloc-stdlib" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b5c1865780388bfa186411ab5f247819487fc4864c6e9c3106611fa347586e1" +dependencies = [ + "alloc-no-stdlib 3.0.0", ] [[package]] @@ -230,7 +256,7 @@ dependencies = [ "objc2-foundation 0.3.2", "parking_lot", "percent-encoding", - "windows-sys 0.61.2", + "windows-sys 0.52.0", "wl-clipboard-rs", "x11rb", ] @@ -536,6 +562,12 @@ dependencies = [ "serde", ] +[[package]] +name = "bit_field" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb2907cc03d08cdb1c6724ad0670ce67c4a71e1c45a6d7635224011714cfc4b1" + [[package]] name = "bitflags" version = "1.3.2" @@ -557,6 +589,15 @@ dependencies = [ "generic-array", ] +[[package]] +name = "block-buffer" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa" +dependencies = [ + "hybrid-array", +] + [[package]] name = "block2" version = "0.5.1" @@ -618,9 +659,9 @@ version = "8.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5cc91aac060a7a1e25823bdccbfb6af1875b88f17c6daac97894eed8207166b3" dependencies = [ - "alloc-no-stdlib", - "alloc-stdlib", - "brotli-decompressor", + "alloc-no-stdlib 2.0.4", + "alloc-stdlib 0.2.4", + "brotli-decompressor 5.0.3", ] [[package]] @@ -629,8 +670,18 @@ version = "5.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3a32acac15fe1967bc3986b2a6347dffc965602354ea6f450ad07e8bfd253583" dependencies = [ - "alloc-no-stdlib", - "alloc-stdlib", + "alloc-no-stdlib 2.0.4", + "alloc-stdlib 0.2.4", +] + +[[package]] +name = "brotli-decompressor" +version = "6.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75c74c9c51b9140663e196b5fb88bc94c334d7a497c8311cb759d8557874747f" +dependencies = [ + "alloc-no-stdlib 3.0.0", + "alloc-stdlib 0.3.0", ] [[package]] @@ -794,6 +845,16 @@ dependencies = [ "windows-link", ] +[[package]] +name = "cipher" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e8cf2a2c93cd704877c0858356ed03480ff301ee950b43f1cbe4573b088bfa6c" +dependencies = [ + "crypto-common 0.2.2", + "inout", +] + [[package]] name = "clipboard-win" version = "5.4.3" @@ -812,6 +873,12 @@ dependencies = [ "cc", ] +[[package]] +name = "cmov" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a" + [[package]] name = "cmpv2" version = "0.2.0" @@ -830,7 +897,7 @@ version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7b77c319abfd5219629c45c34c89ba945ed3c5e49fcde9d16b6c3885f118a730" dependencies = [ - "const-oid", + "const-oid 0.9.6", "der", "spki", "x509-cert", @@ -906,6 +973,12 @@ version = "0.9.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8" +[[package]] +name = "const-oid" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be95d4a884358a21a199689323c29e9256b4a1b315e22f183d155422041d3a9a" + [[package]] name = "core-foundation" version = "0.9.4" @@ -983,6 +1056,12 @@ dependencies = [ "libm", ] +[[package]] +name = "cpubits" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15b85f9c39137c3a891689859392b1bd49812121d0d61c9caf00d46ed5ce06ae" + [[package]] name = "cpufeatures" version = "0.2.17" @@ -1009,14 +1088,50 @@ dependencies = [ "rustix 1.1.5", ] +[[package]] +name = "craft-cfb" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=7ad4765ee55496d0ccdb7659ad7a6375c7bbb484#7ad4765ee55496d0ccdb7659ad7a6375c7bbb484" + [[package]] name = "craft-cms" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0" +source = "git+https://github.com/storytold/craft-libs?rev=a5ac3aa05cf3ec013961a85599ddd9e0b5c03813#a5ac3aa05cf3ec013961a85599ddd9e0b5c03813" dependencies = [ + "md-5", "rayon", ] +[[package]] +name = "craft-codepage" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=bfea7d9800a9f14e496209f9df30e9ef45655701#bfea7d9800a9f14e496209f9df30e9ef45655701" + +[[package]] +name = "craft-codepage" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=f0f4758c01581d79577b9bf5046c06f4e77b1f18#f0f4758c01581d79577b9bf5046c06f4e77b1f18" + +[[package]] +name = "craft-csv" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=387c64892b30fdad491b263cc3d9eac660d88dcc#387c64892b30fdad491b263cc3d9eac660d88dcc" +dependencies = [ + "thiserror 2.0.21", +] + +[[package]] +name = "craft-designcraft-format" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=b1b4602a71d19e09ad33f7752a10d6598cf39b2b#b1b4602a71d19e09ad33f7752a10d6598cf39b2b" +dependencies = [ + "craft-document-bundle", + "craft-eps 0.1.0 (git+https://github.com/storytold/craft-libs?rev=b1b4602a71d19e09ad33f7752a10d6598cf39b2b)", + "serde", + "serde_json", + "thiserror 2.0.21", +] + [[package]] name = "craft-dialogs" version = "0.1.0" @@ -1035,6 +1150,108 @@ name = "craft-docpath" version = "0.1.0" source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0" +[[package]] +name = "craft-document-bundle" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=b1b4602a71d19e09ad33f7752a10d6598cf39b2b#b1b4602a71d19e09ad33f7752a10d6598cf39b2b" +dependencies = [ + "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=b1b4602a71d19e09ad33f7752a10d6598cf39b2b)", + "serde_json", + "thiserror 2.0.21", + "zip 9.1.1", +] + +[[package]] +name = "craft-docx" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=7ad4765ee55496d0ccdb7659ad7a6375c7bbb484#7ad4765ee55496d0ccdb7659ad7a6375c7bbb484" +dependencies = [ + "base64 0.23.1", + "chrono", + "craft-drawingml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=7ad4765ee55496d0ccdb7659ad7a6375c7bbb484)", + "craft-math", + "craft-offcrypto", + "craft-opc 0.1.0 (git+https://github.com/storytold/craft-libs?rev=7ad4765ee55496d0ccdb7659ad7a6375c7bbb484)", + "craft-wordmodel", + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=7ad4765ee55496d0ccdb7659ad7a6375c7bbb484)", + "log", + "quick-xml 0.41.0", + "thiserror 2.0.21", + "unicode-bidi", + "zeroize", +] + +[[package]] +name = "craft-drawingml" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=2b9a325f57624804ed423aded16695eddb815119#2b9a325f57624804ed423aded16695eddb815119" +dependencies = [ + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=2b9a325f57624804ed423aded16695eddb815119)", + "kurbo", + "log", + "serde", +] + +[[package]] +name = "craft-drawingml" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=7ad4765ee55496d0ccdb7659ad7a6375c7bbb484#7ad4765ee55496d0ccdb7659ad7a6375c7bbb484" +dependencies = [ + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=7ad4765ee55496d0ccdb7659ad7a6375c7bbb484)", + "kurbo", + "log", + "serde", +] + +[[package]] +name = "craft-drawingml" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=f6cab1980#f6cab1980bbe422cc00c4b19d9f0f9ba337e1316" +dependencies = [ + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=f6cab1980)", + "kurbo", + "log", + "serde", +] + +[[package]] +name = "craft-eps" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=b1b4602a71d19e09ad33f7752a10d6598cf39b2b#b1b4602a71d19e09ad33f7752a10d6598cf39b2b" + +[[package]] +name = "craft-eps" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=ba24fe2435adb3c81ad6057faf36365fbba736cf#6d0b33c0cd63ae4250c180a04eb4a4d66ab81448" + +[[package]] +name = "craft-eps" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=eed3c28cf016723d004d6f2c79c61424c15d4558#eed3c28cf016723d004d6f2c79c61424c15d4558" + +[[package]] +name = "craft-epub" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=ba24fe2435adb3c81ad6057faf36365fbba736cf#6d0b33c0cd63ae4250c180a04eb4a4d66ab81448" +dependencies = [ + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba24fe2435adb3c81ad6057faf36365fbba736cf)", + "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba24fe2435adb3c81ad6057faf36365fbba736cf)", + "thiserror 2.0.21", +] + +[[package]] +name = "craft-file-formats" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=eed3c28cf016723d004d6f2c79c61424c15d4558#eed3c28cf016723d004d6f2c79c61424c15d4558" +dependencies = [ + "craft-eps 0.1.0 (git+https://github.com/storytold/craft-libs?rev=eed3c28cf016723d004d6f2c79c61424c15d4558)", + "craft-idml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=eed3c28cf016723d004d6f2c79c61424c15d4558)", + "craft-svg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=eed3c28cf016723d004d6f2c79c61424c15d4558)", + "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=eed3c28cf016723d004d6f2c79c61424c15d4558)", + "serde", + "serde_json", +] + [[package]] name = "craft-fonts-build" version = "0.1.0" @@ -1063,6 +1280,156 @@ dependencies = [ "writeable", ] +[[package]] +name = "craft-idml" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=899e396b9e2710fcdf1ad9b6249d6c456b7ca9a2#899e396b9e2710fcdf1ad9b6249d6c456b7ca9a2" +dependencies = [ + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=899e396b9e2710fcdf1ad9b6249d6c456b7ca9a2)", + "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=899e396b9e2710fcdf1ad9b6249d6c456b7ca9a2)", + "thiserror 2.0.21", +] + +[[package]] +name = "craft-idml" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=eed3c28cf016723d004d6f2c79c61424c15d4558#eed3c28cf016723d004d6f2c79c61424c15d4558" +dependencies = [ + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=eed3c28cf016723d004d6f2c79c61424c15d4558)", + "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=eed3c28cf016723d004d6f2c79c61424c15d4558)", + "thiserror 2.0.21", +] + +[[package]] +name = "craft-image-codecs" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=a5ac3aa05cf3ec013961a85599ddd9e0b5c03813#a5ac3aa05cf3ec013961a85599ddd9e0b5c03813" +dependencies = [ + "craft-jpeg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a5ac3aa05cf3ec013961a85599ddd9e0b5c03813)", + "craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a5ac3aa05cf3ec013961a85599ddd9e0b5c03813)", + "exr", + "flate2", + "half", + "image", + "image-webp", + "jpeg-encoder", + "png", + "rayon", + "serde_json", + "thiserror 2.0.21", + "tiff", + "zune-core", + "zune-jpeg", + "zune-jpegxl", +] + +[[package]] +name = "craft-image-codecs" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=bfea7d9800a9f14e496209f9df30e9ef45655701#bfea7d9800a9f14e496209f9df30e9ef45655701" +dependencies = [ + "craft-jpeg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=bfea7d9800a9f14e496209f9df30e9ef45655701)", + "craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=bfea7d9800a9f14e496209f9df30e9ef45655701)", + "exr", + "flate2", + "half", + "image", + "image-webp", + "jpeg-encoder", + "png", + "rayon", + "serde_json", + "thiserror 2.0.21", + "tiff", + "zune-core", + "zune-jpeg", + "zune-jpegxl", +] + +[[package]] +name = "craft-image-codecs" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=cc23ffd4d26f3074808e2187d332564817624f8f#cc23ffd4d26f3074808e2187d332564817624f8f" +dependencies = [ + "craft-jpeg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=cc23ffd4d26f3074808e2187d332564817624f8f)", + "exr", + "flate2", + "half", + "image", + "image-webp", + "jpeg-encoder", + "png", + "rayon", + "serde_json", + "thiserror 2.0.21", + "tiff", + "zune-core", + "zune-jpeg", + "zune-jpegxl", +] + +[[package]] +name = "craft-image-codecs" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=eed3c28cf016723d004d6f2c79c61424c15d4558#eed3c28cf016723d004d6f2c79c61424c15d4558" +dependencies = [ + "craft-jpeg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=eed3c28cf016723d004d6f2c79c61424c15d4558)", + "exr", + "flate2", + "half", + "image", + "image-webp", + "jpeg-encoder", + "png", + "rayon", + "serde_json", + "thiserror 2.0.21", + "tiff", + "zune-core", + "zune-jpeg", + "zune-jpegxl", +] + +[[package]] +name = "craft-indd" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=47bf5650b0d503b97bfb5e841746c4957897d11f#47bf5650b0d503b97bfb5e841746c4957897d11f" +dependencies = [ + "indd", +] + +[[package]] +name = "craft-jpeg" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=a5ac3aa05cf3ec013961a85599ddd9e0b5c03813#a5ac3aa05cf3ec013961a85599ddd9e0b5c03813" +dependencies = [ + "thiserror 2.0.21", +] + +[[package]] +name = "craft-jpeg" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=bfea7d9800a9f14e496209f9df30e9ef45655701#bfea7d9800a9f14e496209f9df30e9ef45655701" +dependencies = [ + "thiserror 2.0.21", +] + +[[package]] +name = "craft-jpeg" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=cc23ffd4d26f3074808e2187d332564817624f8f#cc23ffd4d26f3074808e2187d332564817624f8f" +dependencies = [ + "thiserror 2.0.21", +] + +[[package]] +name = "craft-jpeg" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=eed3c28cf016723d004d6f2c79c61424c15d4558#eed3c28cf016723d004d6f2c79c61424c15d4558" +dependencies = [ + "thiserror 2.0.21", +] + [[package]] name = "craft-keymap" version = "0.1.0" @@ -1075,23 +1442,145 @@ dependencies = [ "serde_json", ] +[[package]] +name = "craft-math" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=7ad4765ee55496d0ccdb7659ad7a6375c7bbb484#7ad4765ee55496d0ccdb7659ad7a6375c7bbb484" +dependencies = [ + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=7ad4765ee55496d0ccdb7659ad7a6375c7bbb484)", + "serde", +] + +[[package]] +name = "craft-metadata" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=a5ac3aa05cf3ec013961a85599ddd9e0b5c03813#a5ac3aa05cf3ec013961a85599ddd9e0b5c03813" +dependencies = [ + "brotli-decompressor 6.3.1", + "chrono", + "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a5ac3aa05cf3ec013961a85599ddd9e0b5c03813)", + "quick-xml 0.41.0", + "serde", +] + +[[package]] +name = "craft-metadata" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=bfea7d9800a9f14e496209f9df30e9ef45655701#bfea7d9800a9f14e496209f9df30e9ef45655701" +dependencies = [ + "brotli-decompressor 6.3.1", + "chrono", + "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=bfea7d9800a9f14e496209f9df30e9ef45655701)", + "quick-xml 0.41.0", + "serde", +] + +[[package]] +name = "craft-mime" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=f0f4758c01581d79577b9bf5046c06f4e77b1f18#f0f4758c01581d79577b9bf5046c06f4e77b1f18" +dependencies = [ + "chrono", + "craft-codepage 0.1.0 (git+https://github.com/storytold/craft-libs?rev=f0f4758c01581d79577b9bf5046c06f4e77b1f18)", + "encoding_rs", +] + +[[package]] +name = "craft-offcrypto" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=7ad4765ee55496d0ccdb7659ad7a6375c7bbb484#7ad4765ee55496d0ccdb7659ad7a6375c7bbb484" +dependencies = [ + "aes", + "base64 0.23.1", + "craft-cfb", + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=7ad4765ee55496d0ccdb7659ad7a6375c7bbb484)", + "getrandom 0.3.4", + "hmac", + "sha1 0.11.0", + "sha2 0.11.1", + "thiserror 2.0.21", + "zeroize", +] + +[[package]] +name = "craft-opc" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=2b9a325f57624804ed423aded16695eddb815119#2b9a325f57624804ed423aded16695eddb815119" +dependencies = [ + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=2b9a325f57624804ed423aded16695eddb815119)", + "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=2b9a325f57624804ed423aded16695eddb815119)", + "log", + "thiserror 2.0.21", +] + +[[package]] +name = "craft-opc" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=7ad4765ee55496d0ccdb7659ad7a6375c7bbb484#7ad4765ee55496d0ccdb7659ad7a6375c7bbb484" +dependencies = [ + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=7ad4765ee55496d0ccdb7659ad7a6375c7bbb484)", + "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=7ad4765ee55496d0ccdb7659ad7a6375c7bbb484)", + "log", + "thiserror 2.0.21", +] + +[[package]] +name = "craft-opc" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=8abfa9d0f14bafbfc3449fc552ffeafb9ca6a551#8abfa9d0f14bafbfc3449fc552ffeafb9ca6a551" +dependencies = [ + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=8abfa9d0f14bafbfc3449fc552ffeafb9ca6a551)", + "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=8abfa9d0f14bafbfc3449fc552ffeafb9ca6a551)", + "log", + "thiserror 2.0.21", +] + +[[package]] +name = "craft-opc" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=f6cab1980#f6cab1980bbe422cc00c4b19d9f0f9ba337e1316" +dependencies = [ + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=f6cab1980)", + "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=f6cab1980)", + "log", + "thiserror 2.0.21", +] + [[package]] name = "craft-pdf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0" +source = "git+https://github.com/storytold/craft-libs?rev=a5ac3aa05cf3ec013961a85599ddd9e0b5c03813#a5ac3aa05cf3ec013961a85599ddd9e0b5c03813" dependencies = [ "bytemuck", + "craft-svg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a5ac3aa05cf3ec013961a85599ddd9e0b5c03813)", "hayro", "hayro-interpret", "hayro-syntax", "krilla", + "krilla-svg", + "thiserror 2.0.21", + "usvg 0.47.0", +] + +[[package]] +name = "craft-pptx" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=f6cab1980#f6cab1980bbe422cc00c4b19d9f0f9ba337e1316" +dependencies = [ + "craft-drawingml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=f6cab1980)", + "craft-opc 0.1.0 (git+https://github.com/storytold/craft-libs?rev=f6cab1980)", + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=f6cab1980)", + "kurbo", + "log", + "serde", + "serde_json", "thiserror 2.0.21", ] [[package]] name = "craft-prepress" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0" +source = "git+https://github.com/storytold/craft-libs?rev=a5ac3aa05cf3ec013961a85599ddd9e0b5c03813#a5ac3aa05cf3ec013961a85599ddd9e0b5c03813" dependencies = [ "craft-cms", "craft-pdf", @@ -1114,6 +1603,93 @@ dependencies = [ "winsafe", ] +[[package]] +name = "craft-psd" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=d15bf1f35b17b759870f9e5111b9a5d243f64888#d15bf1f35b17b759870f9e5111b9a5d243f64888" +dependencies = [ + "encoding_rs", + "flate2", + "rayon", + "thiserror 2.0.21", +] + +[[package]] +name = "craft-rtf" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=bfea7d9800a9f14e496209f9df30e9ef45655701#bfea7d9800a9f14e496209f9df30e9ef45655701" +dependencies = [ + "craft-codepage 0.1.0 (git+https://github.com/storytold/craft-libs?rev=bfea7d9800a9f14e496209f9df30e9ef45655701)", + "encoding_rs", +] + +[[package]] +name = "craft-sheet" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=2b9a325f57624804ed423aded16695eddb815119#2b9a325f57624804ed423aded16695eddb815119" + +[[package]] +name = "craft-svg" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=a5ac3aa05cf3ec013961a85599ddd9e0b5c03813#a5ac3aa05cf3ec013961a85599ddd9e0b5c03813" +dependencies = [ + "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a5ac3aa05cf3ec013961a85599ddd9e0b5c03813)", + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a5ac3aa05cf3ec013961a85599ddd9e0b5c03813)", + "flate2", + "kurbo", + "roxmltree 0.21.2", + "thiserror 2.0.21", + "usvg 0.48.1", + "vectorcraft-geom", + "vectorcraft-pathops", +] + +[[package]] +name = "craft-svg" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=cc23ffd4d26f3074808e2187d332564817624f8f#cc23ffd4d26f3074808e2187d332564817624f8f" +dependencies = [ + "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=cc23ffd4d26f3074808e2187d332564817624f8f)", + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=cc23ffd4d26f3074808e2187d332564817624f8f)", + "flate2", + "kurbo", + "resvg 0.48.1", + "roxmltree 0.21.2", + "thiserror 2.0.21", + "usvg 0.48.1", +] + +[[package]] +name = "craft-svg" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=eed3c28cf016723d004d6f2c79c61424c15d4558#eed3c28cf016723d004d6f2c79c61424c15d4558" +dependencies = [ + "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=eed3c28cf016723d004d6f2c79c61424c15d4558)", + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=eed3c28cf016723d004d6f2c79c61424c15d4558)", + "flate2", + "kurbo", + "roxmltree 0.21.2", + "thiserror 2.0.21", +] + +[[package]] +name = "craft-tiff" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=a5ac3aa05cf3ec013961a85599ddd9e0b5c03813#a5ac3aa05cf3ec013961a85599ddd9e0b5c03813" +dependencies = [ + "serde", + "thiserror 2.0.21", +] + +[[package]] +name = "craft-tiff" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=bfea7d9800a9f14e496209f9df30e9ef45655701#bfea7d9800a9f14e496209f9df30e9ef45655701" +dependencies = [ + "serde", + "thiserror 2.0.21", +] + [[package]] name = "craft-ui" version = "0.1.0" @@ -1138,19 +1714,21 @@ dependencies = [ [[package]] name = "craft-update" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0" +source = "git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280#e98299546f5c5c3c22388d16507f8b5e61a5f280" dependencies = [ "chrono", "dunce", "egui", "flate2", "getrandom 0.3.4", + "image", "log", "plist", + "rustix 1.1.5", "semver", "serde", "serde_json", - "sha2", + "sha2 0.10.9", "tar", "tempfile", "ureq", @@ -1179,6 +1757,195 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "craft-wordmodel" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=7ad4765ee55496d0ccdb7659ad7a6375c7bbb484#7ad4765ee55496d0ccdb7659ad7a6375c7bbb484" +dependencies = [ + "base64 0.23.1", + "craft-math", + "log", + "serde", + "serde_json", + "thiserror 2.0.21", + "unicode-segmentation", +] + +[[package]] +name = "craft-xlsx" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=2b9a325f57624804ed423aded16695eddb815119#2b9a325f57624804ed423aded16695eddb815119" +dependencies = [ + "craft-drawingml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=2b9a325f57624804ed423aded16695eddb815119)", + "craft-opc 0.1.0 (git+https://github.com/storytold/craft-libs?rev=2b9a325f57624804ed423aded16695eddb815119)", + "craft-sheet", + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=2b9a325f57624804ed423aded16695eddb815119)", + "thiserror 2.0.21", +] + +[[package]] +name = "craft-xml" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=2b9a325f57624804ed423aded16695eddb815119#2b9a325f57624804ed423aded16695eddb815119" +dependencies = [ + "quick-xml 0.41.0", + "thiserror 2.0.21", +] + +[[package]] +name = "craft-xml" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=7ad4765ee55496d0ccdb7659ad7a6375c7bbb484#7ad4765ee55496d0ccdb7659ad7a6375c7bbb484" +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=899e396b9e2710fcdf1ad9b6249d6c456b7ca9a2#899e396b9e2710fcdf1ad9b6249d6c456b7ca9a2" +dependencies = [ + "quick-xml 0.41.0", + "thiserror 2.0.21", +] + +[[package]] +name = "craft-xml" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=8abfa9d0f14bafbfc3449fc552ffeafb9ca6a551#8abfa9d0f14bafbfc3449fc552ffeafb9ca6a551" +dependencies = [ + "quick-xml 0.41.0", + "thiserror 2.0.21", +] + +[[package]] +name = "craft-xml" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=a5ac3aa05cf3ec013961a85599ddd9e0b5c03813#a5ac3aa05cf3ec013961a85599ddd9e0b5c03813" +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=ba24fe2435adb3c81ad6057faf36365fbba736cf#6d0b33c0cd63ae4250c180a04eb4a4d66ab81448" +dependencies = [ + "quick-xml 0.41.0", + "thiserror 2.0.21", +] + +[[package]] +name = "craft-xml" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=cc23ffd4d26f3074808e2187d332564817624f8f#cc23ffd4d26f3074808e2187d332564817624f8f" +dependencies = [ + "quick-xml 0.41.0", + "thiserror 2.0.21", +] + +[[package]] +name = "craft-xml" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=eed3c28cf016723d004d6f2c79c61424c15d4558#eed3c28cf016723d004d6f2c79c61424c15d4558" +dependencies = [ + "quick-xml 0.41.0", + "thiserror 2.0.21", +] + +[[package]] +name = "craft-xml" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=f6cab1980#f6cab1980bbe422cc00c4b19d9f0f9ba337e1316" +dependencies = [ + "quick-xml 0.41.0", + "thiserror 2.0.21", +] + +[[package]] +name = "craft-zip" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=2b9a325f57624804ed423aded16695eddb815119#2b9a325f57624804ed423aded16695eddb815119" +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=7ad4765ee55496d0ccdb7659ad7a6375c7bbb484#7ad4765ee55496d0ccdb7659ad7a6375c7bbb484" +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=899e396b9e2710fcdf1ad9b6249d6c456b7ca9a2#899e396b9e2710fcdf1ad9b6249d6c456b7ca9a2" +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=8abfa9d0f14bafbfc3449fc552ffeafb9ca6a551#8abfa9d0f14bafbfc3449fc552ffeafb9ca6a551" +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=b1b4602a71d19e09ad33f7752a10d6598cf39b2b#b1b4602a71d19e09ad33f7752a10d6598cf39b2b" +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=ba24fe2435adb3c81ad6057faf36365fbba736cf#6d0b33c0cd63ae4250c180a04eb4a4d66ab81448" +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=eed3c28cf016723d004d6f2c79c61424c15d4558#eed3c28cf016723d004d6f2c79c61424c15d4558" +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=f6cab1980#f6cab1980bbe422cc00c4b19d9f0f9ba337e1316" +dependencies = [ + "flate2", + "thiserror 2.0.21", + "zip 9.1.1", +] + [[package]] name = "crc32fast" version = "1.5.3" @@ -1250,6 +2017,24 @@ dependencies = [ "typenum", ] +[[package]] +name = "crypto-common" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "ctutils" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "261af4dc7a06ea8a527a8717d8cbba3417530d6ea14e1edb3de6b67806be474f" +dependencies = [ + "cmov", +] + [[package]] name = "cursor-icon" version = "1.2.0" @@ -1268,7 +2053,7 @@ version = "0.7.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb" dependencies = [ - "const-oid", + "const-oid 0.9.6", "der_derive", "flagset", "pem-rfc7468", @@ -1305,7 +2090,7 @@ dependencies = [ [[package]] name = "designcraft" -version = "0.14.0" +version = "0.21.0" dependencies = [ "arboard", "craft-update", @@ -1319,6 +2104,7 @@ dependencies = [ "muda", "objc2 0.6.5", "objc2-app-kit 0.3.2", + "objc2-foundation 0.3.2", "rfd", "serde", "serde_json", @@ -1329,8 +2115,10 @@ dependencies = [ [[package]] name = "designcraft-cli" -version = "0.14.0" +version = "0.21.0" dependencies = [ + "craft-file-formats", + "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=bfea7d9800a9f14e496209f9df30e9ef45655701)", "designcraft-color", "designcraft-compose", "designcraft-doc", @@ -1340,12 +2128,13 @@ dependencies = [ "designcraft-mcp", "designcraft-pdf", "designcraft-render", + "image", "serde_json", ] [[package]] name = "designcraft-color" -version = "0.14.0" +version = "0.21.0" dependencies = [ "craft-cms", "kurbo", @@ -1357,7 +2146,7 @@ dependencies = [ [[package]] name = "designcraft-compose" -version = "0.14.0" +version = "0.21.0" dependencies = [ "designcraft-color", "designcraft-doc", @@ -1377,7 +2166,7 @@ dependencies = [ [[package]] name = "designcraft-doc" -version = "0.14.0" +version = "0.21.0" dependencies = [ "chrono", "designcraft-color", @@ -1390,13 +2179,20 @@ dependencies = [ [[package]] name = "designcraft-engine" -version = "0.14.0" +version = "0.21.0" dependencies = [ "caseless", "craft-atomic", + "craft-csv", "craft-docpath", + "craft-file-formats", + "craft-indd", + "craft-mime", "craft-prepress", "craft-print", + "craft-svg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=cc23ffd4d26f3074808e2187d332564817624f8f)", + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=899e396b9e2710fcdf1ad9b6249d6c456b7ca9a2)", + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a5ac3aa05cf3ec013961a85599ddd9e0b5c03813)", "designcraft-color", "designcraft-compose", "designcraft-doc", @@ -1414,13 +2210,12 @@ dependencies = [ "hayro-cmap", "hayro-interpret", "hayro-syntax", - "indd", "kurbo", "log", - "quick-xml 0.41.0", "same-file", "serde", "serde_json", + "sha2 0.10.9", "tempfile", "thiserror 2.0.21", "unicode-segmentation", @@ -1430,9 +2225,10 @@ dependencies = [ [[package]] name = "designcraft-epub" -version = "0.14.0" +version = "0.21.0" dependencies = [ - "chrono", + "craft-epub", + "craft-mime", "designcraft-color", "designcraft-doc", "zip 3.0.0", @@ -1440,7 +2236,7 @@ dependencies = [ [[package]] name = "designcraft-fonts" -version = "0.14.0" +version = "0.21.0" dependencies = [ "core-text", "harfrust 0.13.3", @@ -1453,19 +2249,17 @@ dependencies = [ [[package]] name = "designcraft-format" -version = "0.14.0" +version = "0.21.0" dependencies = [ + "craft-designcraft-format", "designcraft-doc", - "designcraft-images", - "serde", "serde_json", - "thiserror 2.0.21", "zip 3.0.0", ] [[package]] name = "designcraft-geom" -version = "0.14.0" +version = "0.21.0" dependencies = [ "flo_curves", "kurbo", @@ -1478,40 +2272,48 @@ dependencies = [ [[package]] name = "designcraft-idml" -version = "0.14.0" +version = "0.21.0" dependencies = [ + "craft-file-formats", + "craft-idml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=899e396b9e2710fcdf1ad9b6249d6c456b7ca9a2)", + "craft-svg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=cc23ffd4d26f3074808e2187d332564817624f8f)", + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=899e396b9e2710fcdf1ad9b6249d6c456b7ca9a2)", "designcraft-color", "designcraft-compose", "designcraft-doc", "designcraft-geom", "designcraft-images", "log", - "quick-xml 0.41.0", "thiserror 2.0.21", "zip 3.0.0", ] [[package]] name = "designcraft-images" -version = "0.14.0" +version = "0.21.0" dependencies = [ "craft-cms", + "craft-eps 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba24fe2435adb3c81ad6057faf36365fbba736cf)", + "craft-file-formats", + "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=bfea7d9800a9f14e496209f9df30e9ef45655701)", + "craft-psd", + "craft-svg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=cc23ffd4d26f3074808e2187d332564817624f8f)", "designcraft-color", "designcraft-fonts", "flate2", "image", + "jpeg-decoder", "log", "quick-xml 0.41.0", - "resvg", + "skrifa 0.47.0", "tiff", - "zune-core", - "zune-jpeg", ] [[package]] name = "designcraft-mcp" -version = "0.14.0" +version = "0.21.0" dependencies = [ + "craft-file-formats", "designcraft-engine", "designcraft-geom", "designcraft-render", @@ -1523,10 +2325,11 @@ dependencies = [ [[package]] name = "designcraft-pdf" -version = "0.14.0" +version = "0.21.0" dependencies = [ "chrono", "craft-cms", + "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=bfea7d9800a9f14e496209f9df30e9ef45655701)", "craft-pdf", "craft-prepress", "designcraft-color", @@ -1535,22 +2338,25 @@ dependencies = [ "designcraft-fonts", "designcraft-geom", "designcraft-images", + "flate2", "hayro-cmap", "hayro-interpret", - "hayro-syntax", "image", - "krilla-svg", "kurbo", "log", + "skrifa 0.47.0", "thiserror 2.0.21", "tiff", ] [[package]] name = "designcraft-pptx" -version = "0.14.0" +version = "0.21.0" dependencies = [ "chrono", + "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=bfea7d9800a9f14e496209f9df30e9ef45655701)", + "craft-opc 0.1.0 (git+https://github.com/storytold/craft-libs?rev=8abfa9d0f14bafbfc3449fc552ffeafb9ca6a551)", + "craft-pptx", "designcraft-color", "designcraft-compose", "designcraft-doc", @@ -1566,8 +2372,10 @@ dependencies = [ [[package]] name = "designcraft-render" -version = "0.14.0" +version = "0.21.0" dependencies = [ + "bytemuck", + "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=bfea7d9800a9f14e496209f9df30e9ef45655701)", "craft-pdf", "designcraft-color", "designcraft-compose", @@ -1585,16 +2393,21 @@ dependencies = [ [[package]] name = "designcraft-textimport" -version = "0.14.0" +version = "0.21.0" dependencies = [ + "craft-docx", + "craft-file-formats", + "craft-idml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=899e396b9e2710fcdf1ad9b6249d6c456b7ca9a2)", + "craft-rtf", + "craft-wordmodel", + "craft-xlsx", "designcraft-doc", - "quick-xml 0.41.0", "zip 3.0.0", ] [[package]] name = "designcraft-tools" -version = "0.14.0" +version = "0.21.0" dependencies = [ "designcraft-color", "designcraft-compose", @@ -1606,9 +2419,10 @@ dependencies = [ [[package]] name = "designcraft-ui-egui" -version = "0.14.0" +version = "0.21.0" dependencies = [ "craft-dialogs", + "craft-file-formats", "craft-keymap", "craft-prepress", "craft-ui", @@ -1622,8 +2436,10 @@ dependencies = [ "designcraft-geom", "designcraft-idml", "designcraft-render", + "designcraft-textimport", "designcraft-tools", "egui", + "egui_extras", "egui_kittest", "log", "raw-window-handle", @@ -1638,7 +2454,7 @@ dependencies = [ [[package]] name = "designcraft-web" -version = "0.14.0" +version = "0.21.0" dependencies = [ "designcraft-engine", "designcraft-format", @@ -1674,8 +2490,20 @@ version = "0.10.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" dependencies = [ - "block-buffer", - "crypto-common", + "block-buffer 0.10.4", + "crypto-common 0.1.7", +] + +[[package]] +name = "digest" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" +dependencies = [ + "block-buffer 0.12.1", + "const-oid 0.10.3", + "crypto-common 0.2.2", + "ctutils", ] [[package]] @@ -1851,6 +2679,19 @@ dependencies = [ "winit", ] +[[package]] +name = "egui_extras" +version = "0.37.0" +source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" +dependencies = [ + "ahash", + "egui", + "enum-map", + "itertools 0.15.0", + "log", + "profiling", +] + [[package]] name = "egui_glow" version = "0.37.0" @@ -1918,6 +2759,26 @@ version = "1.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "66b7e2430c6dff6a955451e2cfc438f09cea1965a9d6f87f7e3b90decc014099" +[[package]] +name = "enum-map" +version = "3.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4532960034c15ba2f55e9eee631040ecc473c32e6c4b200828c759840f13a06" +dependencies = [ + "enum-map-derive", +] + +[[package]] +name = "enum-map-derive" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7127272f64b3e098f7d81f350d672081b879bff896d219c42370dc858b1af9ff" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + [[package]] name = "enumflags2" version = "0.7.12" @@ -1983,7 +2844,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -2021,6 +2882,22 @@ dependencies = [ "pin-project-lite", ] +[[package]] +name = "exr" +version = "1.74.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb29d0be702adf92c645d9b2f93472906ba83d400e59f98adb3770ce5c18c2f6" +dependencies = [ + "bit_field", + "half", + "lebe", + "miniz_oxide 0.8.9", + "multiversion", + "rayon-core", + "smallvec", + "zune-inflate", +] + [[package]] name = "fancy-regex" version = "0.19.2" @@ -2222,6 +3099,17 @@ dependencies = [ "ttf-parser", ] +[[package]] +name = "fontdb" +version = "0.24.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2660c5e9157bf76d2db1294e4a9feba604ef610819a3b591088d0d8392a3290f" +dependencies = [ + "log", + "slotmap", + "tinyvec", +] + [[package]] name = "foreign-types" version = "0.5.0" @@ -2387,9 +3275,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" dependencies = [ "cfg-if", + "js-sys", "libc", "r-efi 5.3.0", "wasip2", + "wasm-bindgen", ] [[package]] @@ -2650,7 +3540,7 @@ dependencies = [ [[package]] name = "hayro" version = "0.7.1" -source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0" +source = "git+https://github.com/storytold/craft-libs?rev=a5ac3aa05cf3ec013961a85599ddd9e0b5c03813#a5ac3aa05cf3ec013961a85599ddd9e0b5c03813" dependencies = [ "bytemuck", "hayro-interpret", @@ -2670,7 +3560,7 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a" [[package]] name = "hayro-cmap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0" +source = "git+https://github.com/storytold/craft-libs?rev=a5ac3aa05cf3ec013961a85599ddd9e0b5c03813#a5ac3aa05cf3ec013961a85599ddd9e0b5c03813" dependencies = [ "brotli", "hayro-postscript", @@ -2679,7 +3569,7 @@ dependencies = [ [[package]] name = "hayro-interpret" version = "0.7.0" -source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0" +source = "git+https://github.com/storytold/craft-libs?rev=a5ac3aa05cf3ec013961a85599ddd9e0b5c03813#a5ac3aa05cf3ec013961a85599ddd9e0b5c03813" dependencies = [ "bitflags 2.13.2", "hayro-cmap", @@ -2697,7 +3587,7 @@ dependencies = [ [[package]] name = "hayro-jbig2" version = "0.3.0" -source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0" +source = "git+https://github.com/storytold/craft-libs?rev=a5ac3aa05cf3ec013961a85599ddd9e0b5c03813#a5ac3aa05cf3ec013961a85599ddd9e0b5c03813" dependencies = [ "fearless_simd", "hayro-ccitt", @@ -2715,12 +3605,12 @@ dependencies = [ [[package]] name = "hayro-postscript" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0" +source = "git+https://github.com/storytold/craft-libs?rev=a5ac3aa05cf3ec013961a85599ddd9e0b5c03813#a5ac3aa05cf3ec013961a85599ddd9e0b5c03813" [[package]] name = "hayro-syntax" version = "0.7.2" -source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0" +source = "git+https://github.com/storytold/craft-libs?rev=a5ac3aa05cf3ec013961a85599ddd9e0b5c03813#a5ac3aa05cf3ec013961a85599ddd9e0b5c03813" dependencies = [ "flate2", "hayro-ccitt", @@ -2768,6 +3658,15 @@ version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" +[[package]] +name = "hmac" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6303bc9732ae41b04cb554b844a762b4115a61bfaa81e3e83050991eeb56863f" +dependencies = [ + "digest 0.11.3", +] + [[package]] name = "http" version = "1.5.0" @@ -2807,6 +3706,15 @@ version = "1.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" +[[package]] +name = "hybrid-array" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17" +dependencies = [ + "typenum", +] + [[package]] name = "hyper" version = "1.12.0" @@ -3111,6 +4019,7 @@ dependencies = [ "moxcms", "num-traits", "png", + "qoi", "tiff", "zune-core", "zune-jpeg", @@ -3132,10 +4041,16 @@ version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "09e54e57b4c48b40f7aec75635392b12b3421fa26fe8b4332e63138ed278459c" +[[package]] +name = "imagesize" +version = "0.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65b27460c2c92b037f3f94c538ed9a3342f3fdf923606781629ccb35f82d042a" + [[package]] name = "indd" version = "0.1.0" -source = "git+https://github.com/storytold/indd-utils?branch=main#7f3060e5bce78d21ea70e0d5eacb96edce15dfbe" +source = "git+https://github.com/storytold/indd-utils?rev=7f3060e5bce78d21ea70e0d5eacb96edce15dfbe#7f3060e5bce78d21ea70e0d5eacb96edce15dfbe" [[package]] name = "indexmap" @@ -3147,6 +4062,15 @@ dependencies = [ "hashbrown 0.17.1", ] +[[package]] +name = "inout" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a580c13f0ffc335ef42dd3f6b1a41b726051c5e1656d9a3aa6fddb3c5dfbbf9" +dependencies = [ + "hybrid-array", +] + [[package]] name = "ipnet" version = "2.12.2" @@ -3264,6 +4188,18 @@ dependencies = [ "libc", ] +[[package]] +name = "jpeg-decoder" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00810f1d8b74be64b13dbf3db89ac67740615d6c891f0e7b6179326533011a07" + +[[package]] +name = "jpeg-encoder" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b454d911ac55068f53495488d8ccd0646eaa540c033a28ee15b07838afafb01f" + [[package]] name = "js-sys" version = "0.3.106" @@ -3315,7 +4251,7 @@ dependencies = [ [[package]] name = "krilla" version = "0.8.2" -source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0" +source = "git+https://github.com/storytold/craft-libs?rev=a5ac3aa05cf3ec013961a85599ddd9e0b5c03813#a5ac3aa05cf3ec013961a85599ddd9e0b5c03813" dependencies = [ "base64 0.22.1", "bumpalo", @@ -3324,7 +4260,7 @@ dependencies = [ "gif", "hayro-write", "image-webp", - "imagesize", + "imagesize 0.14.0", "indexmap", "pdf-writer", "png", @@ -3334,7 +4270,7 @@ dependencies = [ "skrifa 0.42.1", "smallvec", "subsetter", - "tiny-skia-path", + "tiny-skia-path 0.12.0", "xmp-writer", "yoke", "zune-jpeg", @@ -3347,13 +4283,13 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1237d7c37b16ca9fbc2e72dde13a10d321f9a44aceee35c062bc0a43bfc7ce16" dependencies = [ "flate2", - "fontdb", + "fontdb 0.23.0", "krilla", - "resvg", + "resvg 0.47.0", "skrifa 0.42.1", "smallvec", - "tiny-skia", - "usvg", + "tiny-skia 0.12.0", + "usvg 0.47.0", ] [[package]] @@ -3375,6 +4311,12 @@ version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" +[[package]] +name = "lebe" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a79a3332a6609480d7d0c9eab957bca6b455b91bb84e66d19f5ff66294b85b8" + [[package]] name = "libc" version = "0.2.191" @@ -3476,6 +4418,16 @@ version = "0.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4050469837a6ff301cd14c1f8f24f88549e6d548f24f64e2148eb0f72cebc51f" +[[package]] +name = "md-5" +version = "0.10.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf" +dependencies = [ + "cfg-if", + "digest 0.10.7", +] + [[package]] name = "memchr" version = "2.8.3" @@ -3575,6 +4527,28 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "multiversion" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eb8a68be21d0755f83bfe47e79b896cc732687cf1903f0e50585e8d6ecc53076" +dependencies = [ + "multiversion-macros", + "target-features", +] + +[[package]] +name = "multiversion-macros" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a05e0c3c3e4edaa21d87c645852ed0b0c3663752bcc6ec43353bd6189dce35e1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", + "target-features", +] + [[package]] name = "multiversion_no_op" version = "1.0.0" @@ -3682,7 +4656,7 @@ version = "0.50.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" dependencies = [ - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -4107,7 +5081,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967" dependencies = [ "libc", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -4570,6 +5544,15 @@ version = "0.1.30" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea" +[[package]] +name = "qoi" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f6d64c71eb498fe9eae14ce4ec935c555749aef511cca85b5568910d6e48001" +dependencies = [ + "bytemuck", +] + [[package]] name = "qrcodegen" version = "1.8.0" @@ -4660,7 +5643,7 @@ dependencies = [ "once_cell", "socket2", "tracing", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -4929,8 +5912,26 @@ dependencies = [ "pico-args", "rgb", "svgtypes", - "tiny-skia", - "usvg", + "tiny-skia 0.12.0", + "usvg 0.47.0", + "zune-jpeg", +] + +[[package]] +name = "resvg" +version = "0.48.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67e3803f97b999e80cbf7c6ecdd07a8102204d92e1633cf48783720c521196bd" +dependencies = [ + "bytemuck", + "gif", + "image-webp", + "log", + "pico-args", + "rgb", + "svgtypes", + "tiny-skia 0.12.0", + "usvg 0.48.1", "zune-jpeg", ] @@ -5049,7 +6050,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys 0.12.1", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -5108,7 +6109,7 @@ dependencies = [ "security-framework", "security-framework-sys", "webpki-root-certs", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -5207,6 +6208,17 @@ version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" +[[package]] +name = "sctk-adwaita" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6277f0217056f77f1d8f49f2950ac6c278c0d607c45f5ee99328d792ede24ec" +dependencies = [ + "log", + "smithay-client-toolkit 0.19.2", + "tiny-skia 0.11.4", +] + [[package]] name = "security-framework" version = "3.7.0" @@ -5346,7 +6358,18 @@ checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8" dependencies = [ "cfg-if", "cpufeatures 0.2.17", - "digest", + "digest 0.10.7", +] + +[[package]] +name = "sha1" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aacc4cc499359472b4abe1bf11d0b12e688af9a805fa5e3016f9a386dc2d0214" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.1", + "digest 0.11.3", ] [[package]] @@ -5357,7 +6380,18 @@ checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" dependencies = [ "cfg-if", "cpufeatures 0.2.17", - "digest", + "digest 0.10.7", +] + +[[package]] +name = "sha2" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d7069beb7d6ac7b9acd1039986e73443f24234f41074da099d6f994ac9ad19" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.1", + "digest 0.11.3", ] [[package]] @@ -5411,12 +6445,12 @@ checksum = "da90c3d9af638898a5fdc347479b18f950bb0dde11ecf2244f94cd28135da53b" dependencies = [ "aws-lc-rs", "base64 0.22.1", - "const-oid", + "const-oid 0.9.6", "der", - "digest", + "digest 0.10.7", "pem", "rand_core 0.10.1", - "sha2", + "sha2 0.10.9", "signature", "sigstore-types", "spki", @@ -5485,7 +6519,7 @@ dependencies = [ "chrono", "cmpv2", "cms", - "const-oid", + "const-oid 0.9.6", "der", "hex", "rand", @@ -5524,7 +6558,7 @@ dependencies = [ "base64 0.22.1", "chrono", "cms", - "const-oid", + "const-oid 0.9.6", "hex", "pem", "rustls-pki-types", @@ -5914,6 +6948,12 @@ dependencies = [ "xattr", ] +[[package]] +name = "target-features" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c1bbb9f3c5c463a01705937a24fdabc5047929ac764b2d5b9cf681c1f5041ed5" + [[package]] name = "tempfile" version = "3.27.0" @@ -5921,10 +6961,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" dependencies = [ "fastrand", - "getrandom 0.4.3", + "getrandom 0.3.4", "once_cell", "rustix 1.1.5", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -6029,6 +7069,20 @@ dependencies = [ "time-core", ] +[[package]] +name = "tiny-skia" +version = "0.11.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "83d13394d44dae3207b52a326c0c85a8bf87f1541f23b0d143811088497b09ab" +dependencies = [ + "arrayref", + "arrayvec", + "bytemuck", + "cfg-if", + "log", + "tiny-skia-path 0.11.4", +] + [[package]] name = "tiny-skia" version = "0.12.0" @@ -6041,7 +7095,18 @@ dependencies = [ "cfg-if", "log", "png", - "tiny-skia-path", + "tiny-skia-path 0.12.0", +] + +[[package]] +name = "tiny-skia-path" +version = "0.11.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c9e7fc0c2e86a30b117d0462aa261b72b7a99b7ebd7deb3a14ceda95c5bdc93" +dependencies = [ + "arrayref", + "bytemuck", + "strict-num", ] [[package]] @@ -6454,8 +7519,8 @@ dependencies = [ "base64 0.22.1", "data-url", "flate2", - "fontdb", - "imagesize", + "fontdb 0.23.0", + "imagesize 0.14.0", "kurbo", "log", "pico-args", @@ -6465,7 +7530,7 @@ dependencies = [ "siphasher", "strict-num", "svgtypes", - "tiny-skia-path", + "tiny-skia-path 0.12.0", "ttf-parser", "unicode-bidi", "unicode-script", @@ -6473,6 +7538,33 @@ dependencies = [ "xmlwriter", ] +[[package]] +name = "usvg" +version = "0.48.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "977d0a4abdef933f424a99fe09f95576e089b90aebc6f016a3bc813762493e91" +dependencies = [ + "base64 0.23.1", + "data-url", + "fontdb 0.24.0", + "harfrust 0.12.0", + "imagesize 0.15.0", + "kurbo", + "log", + "pico-args", + "roxmltree 0.21.2", + "simplecss", + "siphasher", + "skrifa 0.44.0", + "strict-num", + "svgtypes", + "tiny-skia-path 0.12.0", + "unicode-bidi", + "unicode-script", + "unicode-vo", + "xmlwriter", +] + [[package]] name = "utf16_iter" version = "1.0.5" @@ -6502,6 +7594,27 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "vectorcraft-geom" +version = "0.18.0" +source = "git+https://github.com/storytold/vectorcraft.git?rev=6b3a6b8788ebcb420d69449199cbdf323888d27e#6b3a6b8788ebcb420d69449199cbdf323888d27e" +dependencies = [ + "kurbo", + "serde", + "thiserror 2.0.21", +] + +[[package]] +name = "vectorcraft-pathops" +version = "0.18.0" +source = "git+https://github.com/storytold/vectorcraft.git?rev=6b3a6b8788ebcb420d69449199cbdf323888d27e#6b3a6b8788ebcb420d69449199cbdf323888d27e" +dependencies = [ + "kurbo", + "linesweeper", + "thiserror 2.0.21", + "vectorcraft-geom", +] + [[package]] name = "vello_common" version = "0.0.8" @@ -7111,7 +8224,7 @@ version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -7358,6 +8471,7 @@ dependencies = [ "raw-window-handle", "redox_syscall 0.4.1", "rustix 0.38.44", + "sctk-adwaita", "smithay-client-toolkit 0.19.2", "smol_str", "tracing", @@ -7522,9 +8636,9 @@ version = "0.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1301e935010a701ae5f8655edc0ad17c44bad3ac5ce8c39185f75453b720ae94" dependencies = [ - "const-oid", + "const-oid 0.9.6", "der", - "sha1", + "sha1 0.10.7", "signature", "spki", "tls_codec", @@ -7602,7 +8716,7 @@ checksum = "9440ea3e5aeabb0ac63af70daf835274065238cdd0cec83418f417eae38bacee" [[package]] name = "xtask" -version = "0.14.0" +version = "0.21.0" dependencies = [ "serde_json", ] @@ -7868,7 +8982,6 @@ dependencies = [ "nix", "typed-path", "windows-sys 0.61.2", - "zopfli", ] [[package]] @@ -7901,6 +9014,15 @@ version = "0.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d56377fd46368984a170bc5aac5567e52ca5da874caa60bea39fcbca78fb658b" +[[package]] +name = "zune-inflate" +version = "0.2.54" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73ab332fe2f6680068f3582b16a24f90ad7096d5d39b974d1c0aff0125116f02" +dependencies = [ + "simd-adler32", +] + [[package]] name = "zune-jpeg" version = "0.5.15" @@ -7910,6 +9032,15 @@ dependencies = [ "zune-core", ] +[[package]] +name = "zune-jpegxl" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cba11ecd07cc23351500e840ae03841b7e4997923ec8e4832ee3ae199ea0b6b4" +dependencies = [ + "zune-core", +] + [[package]] name = "zvariant" version = "5.15.1" @@ -7956,11 +9087,6 @@ name = "egui_demo_lib" version = "0.37.0" source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" -[[patch.unused]] -name = "egui_extras" -version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" - [[patch.unused]] name = "egui_inspection" version = "0.37.0" diff --git a/Cargo.toml b/Cargo.toml index 139d06f01..512ba8145 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,20 +4,41 @@ members = ["crates/*", "apps/*", "xtask"] default-members = ["crates/*", "apps/designcraft", "apps/designcraft-cli", "xtask"] [workspace.package] -version = "0.14.0" +version = "0.21.0" edition = "2024" license = "MIT OR Apache-2.0" rust-version = "1.95" 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 = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" } # Shared reader and writer; publish the immutable revision before this consumer. -craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0", version = "=0.1.0", default-features = false } +craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "a5ac3aa05cf3ec013961a85599ddd9e0b5c03813", version = "=0.1.0", default-features = false } +craft-designcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "b1b4602a71d19e09ad33f7752a10d6598cf39b2b", version = "=0.1.0" } +craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "ba24fe2435adb3c81ad6057faf36365fbba736cf", version = "=0.1.0" } +craft-epub = { git = "https://github.com/storytold/craft-libs", rev = "ba24fe2435adb3c81ad6057faf36365fbba736cf", version = "=0.1.0" } +craft-idml = { git = "https://github.com/storytold/craft-libs", rev = "899e396b9e2710fcdf1ad9b6249d6c456b7ca9a2", version = "=0.1.0" } +craft-indd = { git = "https://github.com/storytold/craft-libs", rev = "47bf5650b0d503b97bfb5e841746c4957897d11f", version = "=0.1.0" } +craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "cc23ffd4d26f3074808e2187d332564817624f8f", version = "=0.1.0", features = ["tree-render", "tree-text"] } +craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "899e396b9e2710fcdf1ad9b6249d6c456b7ca9a2", version = "=0.1.0" } +craft-xml-dtd = { package = "craft-xml", git = "https://github.com/storytold/craft-libs", rev = "a5ac3aa05cf3ec013961a85599ddd9e0b5c03813", version = "=0.1.0" } +craft-rtf = { git = "https://github.com/storytold/craft-libs", rev = "bfea7d9800a9f14e496209f9df30e9ef45655701", version = "=0.1.0" } +craft-xlsx = { git = "https://github.com/storytold/craft-libs", rev = "2b9a325f57624804ed423aded16695eddb815119", version = "=0.1.0" } +craft-docx = { git = "https://github.com/storytold/craft-libs", rev = "7ad4765ee55496d0ccdb7659ad7a6375c7bbb484", version = "=0.1.0" } +craft-wordmodel = { git = "https://github.com/storytold/craft-libs", rev = "7ad4765ee55496d0ccdb7659ad7a6375c7bbb484", version = "=0.1.0" } +craft-csv = { git = "https://github.com/storytold/craft-libs", rev = "387c64892b30fdad491b263cc3d9eac660d88dcc", version = "=0.1.0" } +craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "bfea7d9800a9f14e496209f9df30e9ef45655701", version = "=0.1.0" } +craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "d15bf1f35b17b759870f9e5111b9a5d243f64888", version = "=0.1.0" } +craft-file-formats = { git = "https://github.com/storytold/craft-libs", rev = "eed3c28cf016723d004d6f2c79c61424c15d4558", version = "=0.1.0" } +craft-opc = { git = "https://github.com/storytold/craft-libs", rev = "8abfa9d0f14bafbfc3449fc552ffeafb9ca6a551", version = "=0.1.0" } +craft-pptx = { git = "https://github.com/storytold/craft-libs", rev = "f6cab1980", 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 = "92d392cff132eaf53e13afff77f38b5c11b73aa0", 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 = "92d392cff132eaf53e13afff77f38b5c11b73aa0", version = "=0.1.0", features = ["flatten"] } -craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0", features = ["egui"] } +craft-prepress = { git = "https://github.com/storytold/craft-libs", rev = "a5ac3aa05cf3ec013961a85599ddd9e0b5c03813", 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 = "e98299546f5c5c3c22388d16507f8b5e61a5f280", features = ["egui"] } # internal designcraft-geom = { path = "crates/geom" } designcraft-color = { path = "crates/color" } @@ -63,22 +84,17 @@ skrifa = "0.47" harfrust = "0.13" vello_cpu = "0.2" vello_common = { version = "0.2", default-features = false } -image = { version = "0.25", default-features = false, features = ["png", "jpeg", "webp", "gif", "tiff", "bmp"] } +# Decoded image buffers become pixmap pixels without a copy; the version vello_common uses. +bytemuck = { version = "1.25", features = ["extern_crate_alloc"] } +image = { version = "0.25", default-features = false } # CMYK TIFF samples for PDF export (`image` decodes them to RGB); the version `image` uses. tiff = "0.11" -# SVG (same usvg as krilla-svg). -resvg = { version = "0.47", default-features = false, features = ["text"] } -krilla-svg = "=0.8.1" # Boolean operations on Bézier paths (Pathfinder). flo_curves = "0.8" # QR codes (Object › Generate QR Code); MIT. qrcodegen = "1.8" quick-xml = "0.41" zip = { version = "3", default-features = false, features = ["deflate"] } -# INDD/INDT → IDML conversion for File › Open: storytold/indd-utils, tracking its main branch -# (MIT OR Apache-2.0, no dependencies, builds for wasm). -indd = { git = "https://github.com/storytold/indd-utils", branch = "main" } - # Which paths stored in documents may be followed (craft-libs). craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" } # Atomic file replacement for saves and exports (craft-libs). @@ -87,7 +103,7 @@ craft-atomic = { version = "0.1.0", git = "https://github.com/storytold/craft-li craft-print = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" } # 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 = "92d392cff132eaf53e13afff77f38b5c11b73aa0" } +craft-cms = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "a5ac3aa05cf3ec013961a85599ddd9e0b5c03813" } # ui # Shared frontend components; keep this dependency above the engine boundary. @@ -95,7 +111,8 @@ craft-ui = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", # 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 = "92d392cff132eaf53e13afff77f38b5c11b73aa0", features = ["egui"] } egui = "0.37" -egui_extras = { version = "0.37", default-features = false, features = ["svg"] } +# Resizable table columns (About ▸ Contributors / Models); no image loaders. +egui_extras = { version = "0.37", default-features = false } eframe = { version = "0.37", default-features = false } egui_kittest = "0.37" # Monotonic clock on native and web (`Instant`); screenshot settlement must not use wall time. @@ -136,16 +153,16 @@ 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 = "92d392cff132eaf53e13afff77f38b5c11b73aa0", version = "=0.8.2" } +krilla = { git = "https://github.com/storytold/craft-libs", rev = "a5ac3aa05cf3ec013961a85599ddd9e0b5c03813", 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 = "92d392cff132eaf53e13afff77f38b5c11b73aa0", version = "=0.7.1" } -hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0", version = "=0.7.0" } -hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0", version = "=0.7.2" } -hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0", version = "=0.3.0" } -hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0", version = "=0.1.0" } -hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0", version = "=0.1.0" } +hayro = { git = "https://github.com/storytold/craft-libs", rev = "a5ac3aa05cf3ec013961a85599ddd9e0b5c03813", version = "=0.7.1" } +hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "a5ac3aa05cf3ec013961a85599ddd9e0b5c03813", version = "=0.7.0" } +hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "a5ac3aa05cf3ec013961a85599ddd9e0b5c03813", version = "=0.7.2" } +hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "a5ac3aa05cf3ec013961a85599ddd9e0b5c03813", version = "=0.3.0" } +hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "a5ac3aa05cf3ec013961a85599ddd9e0b5c03813", version = "=0.1.0" } +hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "a5ac3aa05cf3ec013961a85599ddd9e0b5c03813", version = "=0.1.0" } ecolor = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } emath = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } epaint = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } diff --git a/NOTICE b/NOTICE index fc46bcdf3..833424333 100644 --- a/NOTICE +++ b/NOTICE @@ -32,6 +32,20 @@ list (author, source, license) is in ASSETS.md. AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +- Dutch hyphenation patterns, embedded through the hypher crate (feature "dutch"): + hyph-nl.tex 1.1 from hyph-utf8, https://github.com/hyphenation/tex-hyphen. + Copyright (C) 1996 Piet Tutelaers. MIT License: + Permission is hereby granted, free of charge, to any person obtaining a copy of this software + and associated documentation files (the "Software"), to deal in the Software without + restriction, including without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the + Software is furnished to do so, subject to the following conditions: The above copyright notice + and this permission notice shall be included in all copies or substantial portions of the + Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, + INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE + AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - Portuguese hyphenation patterns, embedded through the hypher crate (feature "portuguese"): hyph-pt.tex 1.4 from hyph-utf8, https://github.com/hyphenation/tex-hyphen. Copyright (C) 1987, 1994, 1996, 2015 Pedro J. de Rezende, 1996, 2015 J. Joao Dias Almeida, @@ -68,12 +82,70 @@ list (author, source, license) is in ASSETS.md. HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +- French hyphenation patterns, embedded through the hypher crate (feature "french"): + hyph-fr.tex 2.13 from hyph-utf8, https://github.com/hyphenation/tex-hyphen. + Copyright (C) 1994-2002 Daniel Flipo, Bernard Gaulle, 2016 Arthur Reutenauer. MIT License: + Permission is hereby granted, free of charge, to any person obtaining a copy of this software + and associated documentation files (the "Software"), to deal in the Software without + restriction, including without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the + Software is furnished to do so, subject to the following conditions: The above copyright notice + and this permission notice shall be included in all copies or substantial portions of the + Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, + INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE + AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +- Italian hyphenation patterns, embedded through the hypher crate (feature "italian"): + hyph-it.tex 4.9 from hyph-utf8, https://github.com/hyphenation/tex-hyphen. + Copyright (C) 2008-2011 Claudio Beccari. Available under the LPPL (1.3 or later) or the MIT + License; taken here under the MIT License: Permission is hereby granted, free of charge, to any person obtaining a copy of this software + and associated documentation files (the "Software"), to deal in the Software without + restriction, including without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the + Software is furnished to do so, subject to the following conditions: The above copyright notice + and this permission notice shall be included in all copies or substantial portions of the + Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, + INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE + AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - Norwegian hyphenation patterns, embedded through the hypher crate (feature "norwegian"): hyph-no.tex from hyph-utf8, https://github.com/hyphenation/tex-hyphen. Copyright (C) Rune Kleveland and Ole Michael Selberg. Copying and distribution of this file, with or without modification, is permitted in any medium without royalty provided the copyright notice and this notice are preserved (additionally distributed under the LaTeX Project Public License in CTAN distributions). +- Danish hyphenation patterns, embedded through the hypher crate (feature "danish"): + hyph-da.tex 2011-01-11 from hyph-utf8, https://github.com/hyphenation/tex-hyphen. + Copyright (C) 1994 Frank Jensen. Available under LPPL 1.3 or later, or the MIT License, taken + under MIT: Permission is hereby granted, free of charge, to any person obtaining a copy of this + software and associated documentation files (the "Software"), to deal in the Software without + restriction, including without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the + Software is furnished to do so, subject to the following conditions: The above copyright notice + and this permission notice shall be included in all copies or substantial portions of the + Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, + INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE + AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +- German hyphenation patterns, embedded through the hypher crate (feature "german"): + hyph-de-1996.tex 2024-02-28, German reformed orthography (2006), from hyph-utf8, + https://github.com/typst/hypher/blob/d81cc506416bffef2a75ee2dc969d4b41bc36613/patterns/hyph-de-1996.tex. + Copyright (c) 2013-2024 Stephan Hennig, Werner Lemberg, Günter Milde, Sander van Geloven, + Georg Pfeiffer, Gisbert W. Selke, Tobias Wendorf, Keno Wehr. MIT License: + Permission is hereby granted, free of charge, to any person obtaining a copy of this software + and associated documentation files (the "Software"), to deal in the Software without + restriction, including without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the + Software is furnished to do so, subject to the following conditions: The above copyright notice + and this permission notice shall be included in all copies or substantial portions of the + Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, + INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE + AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - Japanese fonts (craft-fonts): builds made with craft-fonts (CRAFT_FONTS_DIR; all official releases) embed the fonts listed in https://github.com/storytold/craft-fonts/blob/main/ATTRIBUTION.md (BIZ UDPGothic, BIZ UDMincho, @@ -115,6 +187,37 @@ Assets already bundled through Hayro's default features retain their licences: Adobe and contributor names do not endorse or promote this product. Per-file hashes and sources are recorded in ASSETS.md. +Linux Wayland window decorations +------------------------------- +sctk-adwaita 0.10.1 (https://github.com/PolyMeilex/sctk-adwaita, +commit d5f343c45c04d4a026db57f76760819b7325db00) is used by winit on Linux +for vector window controls. Its title-font features are disabled: no Cantarell +font is embedded by this dependency and no font file is added to this repo. + +sctk-adwaita's MIT licence: + +MIT License + +Copyright (c) 2022 Bartłomiej Maryńczak + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + Bundled egui font icons The pinned egui dependency includes egui-icons.ttf, a small subset of John Slegers' diff --git a/README.md b/README.md index cd0f56479..92dcae7bf 100644 --- a/README.md +++ b/README.md @@ -69,7 +69,7 @@ ## The sample magazine Every page below was laid out by DesignCraft from code (`crates/engine/src/sample.rs`) and exported -by its own renderer. Try it yourself with `File → New → Sample Document`, or start the app with +by its own renderer. Try it yourself with `Help → Sample Document`, or start the app with `--sample`. @@ -123,9 +123,7 @@ Japanese text (UI and documents) uses fonts from [storytold/craft-fonts](https://github.com/storytold/craft-fonts), an optional build input (font files are never committed here; see the public [craft-fonts integration guide](https://github.com/storytold/craft-fonts/blob/main/docs/integration.md) -for build instructions and craftrules -[`standards/fonts.md`](https://github.com/storytold/craftrules/blob/main/standards/fonts.md) -for the shared standard): +for build instructions): ```sh git clone https://github.com/storytold/craft-fonts ../craft-fonts @@ -250,11 +248,11 @@ egui frontend is a separate crate, so the UI can be swapped without touching the |---|---| | L0 | `geom` (paths, units & measurement parsing, corner options) · `color` (CMYK/RGB/Lab, swatches, tints, gradients) | | L1 | `doc` (spreads, pages, parents, layers, frames, stories, styles) · `fonts` (font DB, shaping, outlines) | -| L2 | `compose` (the text engine) | -| L3 | `render` (vello_cpu) | +| L2 | `compose` (the text engine) · `images` | +| L3 | `render` (vello_cpu) · `pdf` · `idml` · `epub` · `pptx` · `textimport` · `format` | | L4 | `tools` (pointer events → commands + overlays) | | L5 | `engine` (session, history, command registry) | -| L6 | `ui-egui` (publishing UI, control channel) | +| L6 | `ui-egui` (publishing UI, control channel) · `mcp` | | L7 | `apps/designcraft`, `apps/designcraft-cli`, `apps/designcraft-web` | - **Status and milestones:** [ROADMAP.md](ROADMAP.md) (stage: pre-alpha); feature assessment: [`docs/target-app-parity.md`](docs/target-app-parity.md); known gaps: [`docs/gaps.md`](docs/gaps.md) @@ -282,7 +280,7 @@ Installers and executables are code-signed. | Build | File | Notes | |---|---|---| -| App, universal (Apple silicon + Intel) | `designcraft--macos-universal.dmg` | Signed and notarized | +| App and bundled CLI, universal (Apple silicon + Intel) | `designcraft--macos-universal.dmg` | Signed and notarized | | Command-line tool, universal | `designcraft-cli--macos-universal.zip` | Signed and notarized | ### Linux @@ -338,7 +336,16 @@ stand on its own. | | **LightCraft** | Photo library and raw development | [GitHub](https://github.com/storytold/lightcraft) | [Website](https://getartcraft.com/apps/lightcraft) | | | **PdfCraft** | Reading, organizing and protecting PDFs | [GitHub](https://github.com/storytold/pdfcraft) | [Website](https://getartcraft.com/apps/pdfcraft) | | | **EffectCraft** | Motion graphics and visual effects | [GitHub](https://github.com/storytold/effectcraft) | [Website](https://getartcraft.com/apps/effectcraft) | -| | **DesignCraft** | **Page layout and publishing · you are here** | [GitHub](https://github.com/storytold/designcraft) | [Website](https://getartcraft.com/apps/designcraft) | +| | **DesignCraft** | Page layout and publishing | [GitHub](https://github.com/storytold/designcraft) | [Website](https://getartcraft.com/apps/designcraft) | +| | **FigCraft** | Interface design and prototyping | [GitHub](https://github.com/storytold/figcraft) | [Website](https://getartcraft.com/apps/figcraft) | +| | **WordCraft** | Word processing and documents | [GitHub](https://github.com/storytold/wordcraft) | [Website](https://getartcraft.com/apps/wordcraft) | +| | **SoundCraft** | Audio recording and editing | [GitHub](https://github.com/storytold/soundcraft) | [Website](https://getartcraft.com/apps/soundcraft) | +| | **DeckCraft** | Presentations and slide decks | [GitHub](https://github.com/storytold/deckcraft) | [Website](https://getartcraft.com/apps/deckcraft) | +| | **CADCraft** | Computer-aided design | [GitHub](https://github.com/storytold/cadcraft) | [Website](https://getartcraft.com/apps/cadcraft) | +| | **GridCraft** | Spreadsheets and data | [GitHub](https://github.com/storytold/gridcraft) | [Website](https://getartcraft.com/apps/gridcraft) | +| | **TextureCraft** | 3D texture painting | [GitHub](https://github.com/storytold/texturecraft) | [Website](https://getartcraft.com/apps/texturecraft) | +| | **Craft Anything** | See how any software works, then build your own | [GitHub](https://github.com/storytold/craft-anything) | [Website](https://getartcraft.com/apps/craft-anything) | +| | **SolidCraft** | Parametric 3D CAD by Tangency Labs (community app) | [GitHub](https://github.com/tangency-labs/solidcraft) | | And [**ArtCraft**](https://getartcraft.com/) itself, our AI image and video studio for artists who want real control. diff --git a/ROADMAP.md b/ROADMAP.md index 613ba4148..ccae629f9 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -1,15 +1,16 @@ # DesignCraft roadmap -- **2026-10-29 · UI1994:** Hidden-character marks follow frame, layer and containing-group +- **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. No readiness percentage change. + 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-10-29 · **Change:** minor (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) · **Target:** Adobe InDesign 2026 +> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-11-18 · **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 - 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. @@ -17,6 +18,23 @@ 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-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. +- **2026-10-27** · Automatic recovery writes off the interface thread, straight to disk: on a + 190-page catalogue with 4.2 GB of placed files an autosave was 3.6 GB deflated in RAM on the + interface thread, which stopped the window answering for 30-100 s after an edit. It is now a + background write (`file.recovery.save {background}`, `file.recovery.progress`), the caller + blocked for 109 ms instead, and Save, Close and Revert cancel a snapshot still being written. + No readiness percentage change. +- **2026-10-28** · Inline table rows leave room for column and spanning footnotes, continuing in + the next column or frame when needed (#1901). Cell-local footnotes contribute to row height + and sit inside the cell rather than outside its measuring frame. Vertical justification keeps + paragraphs and table fragments above the footnote area. No readiness percentage change. +- **2026-10-28** · Duplicate, paste, parent overrides and data merge give anchored objects in the + copied story fresh ids (#1522). Copies used to keep the original's ids, and the saved file then + failed to open with "duplicate item id". Files already saved that way still don't open; no + readiness percentage change. - **2026-10-25** · The application bar uses craft-window's shared title-bar code. A drag that starts on a floating panel over the bar moves the panel, not the window, and in full screen the bar no longer zooms or moves the window. No readiness percentage change. @@ -47,13 +65,13 @@ DesignCraft aims at full Adobe InDesign parity — and to be better: faster, ope default layer queries find a placed PDF anywhere in mixed selections. Regression tests cover IDML export after rejection and both selection orders. -## Status (2026-10-01) +## Status (2026-10-21) **Working today** - Document model: facing/non-facing spreads, parent pages with page-number markers, sections, layers, frames (text / graphic / unassigned), threaded stories, paragraph/character/object styles with based-on, swatches (process/spot/tints/gradients), corner options, text wrap, drop shadow, opacity/blend. - Text engine: Knuth–Plass paragraph composer and single-line composer, dictionary hyphenation (public-domain Moby list + our own trained Liang patterns), justification with word/letter/glyph-scaling ranges, keep options (keep with next, keep lines together, widows/orphans), balance ragged lines, optical margin alignment, hyphenation zone/limit, columns, threading across frames and spreads, tabs, bullets/numbering, rules, shading, baseline grid, first-baseline options, vertical justification, wrap exclusions, overset detection, caret/hit testing. - FID2: IDML underline/strikethrough Text Color resets survive style inheritance and roundtrip. Raster and PDF paint underlines behind glyphs, retain strikethrough above, and center rules on their offsets; synthetic overlap tests cover both backends. -- Rendering: vello_cpu (SIMD, multithreaded) — pages, items, images with mip levels, gradients, composed text. +- Rendering: vello_cpu (SIMD, multithreaded) — pages, items, images with mip levels (only the levels drawn are cached; the canvas decodes on background threads and shows a light box or another cached level meanwhile), gradients, composed text. - UI (egui): application bar + menus, Control panel (object and text modes), Tools panel with flyouts, document tabs, rulers, pasteboard, guides (margins, columns, bleed, baseline grid), frame edges, selection handles, text ports and threads, Properties / Pages / Layers dock, Swatches, Styles, Character, Paragraph, Stroke, Text Wrap panels, New Document and Preferences dialogs, Quick Apply (⌘Return), 4 brightness themes. - Pen tool, Direct Selection anchor/handle editing, rotate from corners, Rotate/Scale/Shear tools, Eyedropper, snapping & smart guides, Align/Distribute, Find/Change (text + GREP), Story Editor, Paragraph Style Options, Effects panel, hidden characters, native macOS menu bar, measured InDesign 2026 look (Medium Dark): Properties sections per selection state, 21 pt spinner fields with arithmetic, Contextual Task Bar, inverse (black) text selection, Pages panel with drag-and-drop reorder / parent apply, Layers panel with per-object rows. - Tools: Selection (click, marquee, move, Alt-duplicate, resize handles), Direct Selection, Type (draw frame, click caret, select, type), Rectangle/Ellipse/Polygon (+ frame variants), Line, Hand, Zoom. @@ -64,7 +82,7 @@ DesignCraft aims at full Adobe InDesign parity — and to be better: faster, ope - EPUB 3 (reflowable) export: stories in reading order, CSS from paragraph/character styles, images, navigation (`file.exportEpub`, CLI `--export x.epub`). - Data Merge (one linked CSV, TSV, text, or Excel file; text, image, QR, and hyperlink placeholders; preview; a new document with one record per page or records tiled on a single page), spell checking (public-domain Moby list + document dictionary, suggestions), Step and Repeat (count or grid), snippets, object styles, Numbering & Section Options. - Footnotes: Type › Insert Footnote (caret moves into the note), Document Footnote Options (numbering style incl. symbols, start/restart per page/spread/section, prefix/suffix, reference position/character style, paragraph style, separator, spacing, first baseline, rule above); notes composed at the bottom of the referencing column with the body text making room; edited in place on the canvas; rendered, exported to PDF (real text) and IDML (InDesign's structure, verified opening in InDesign 2026) and imported from IDML; `footnote.*` commands. -- Paragraph Rules: Rule Above / Rule Below (on, weight, colour, tint, column or text width, offset, left/right indent) set in Type › Paragraph Rules…, the Paragraph panel menu and Paragraph Style Options › Paragraph Rules; inherited style values shown, and `type.para` / `style.paragraph.edit` change only the rule fields named. +- Paragraph Rules: Rule Above / Rule Below (on, weight, colour, tint, column or text width, offset, left/right indent) set in Type › Paragraph Rules…, the Paragraph panel menu (⌥⌘J) and Paragraph Style Options › Paragraph Rules; inherited style values shown, and `type.para` / `style.paragraph.edit` change only the rule fields named. - Cross-references and text anchors: Insert Cross-Reference (paragraph by style, or text anchor), 11 formats with InDesign's building blocks (full/partial paragraph, paragraph text/number, page number, anchor name, chapter, file name) plus user formats; resolved live at composition — never out of date, no Update step; unresolved destinations show `??`; PDF link annotations to the destination page; IDML export/import as InDesign cross-reference sources, hyperlinks, text destinations and formats (verified in InDesign 2026); `xref.*` / `anchor.*` commands. - Index: page references (topic from the selection or up to 4 levels, sort keys; current page, to end of story, next n paragraphs, suppressed, See / See also), Generate / Update Index (section headings, nested or run-in, page ranges merged, Index Title / Section Head / Level 1–4 styles); IDML export/import as InDesign topics, page references and topic cross-references (verified in InDesign 2026); `index.*` commands. - Text clipboard keeps formatting (character/paragraph formats, footnotes, cross-references, index markers, tables) and falls back to plain text when the system clipboard changed; Paste without Formatting (⇧⌘V); Change Case (UPPERCASE, lowercase, Title Case, Sentence case — formatting kept); Type › Insert Special Character / White Space / Break Character submenus. @@ -87,7 +105,7 @@ DesignCraft aims at full Adobe InDesign parity — and to be better: faster, ope - Control panel scale X/Y, rotation and shear fields (`transform.info`, absolute `transform.set {scaleX, scaleY, rotation, shear}` about the reference point) and Preferences › Transformations are Totals for nested objects and placed graphics. - Variable fonts: each named instance is a style (Font menu, shaping with feature variations, metrics, outlines) and embeds at its axis settings in PDF; free axis sliders still to come. - Object ▸ Select (first/next above, next/last below, container, content, previous/next in group), full Object ▸ Convert Shape (`object.convertShape`), Table ▸ Split Cell Horizontally/Vertically. -- Attributes panel (`object.attributes`: Overprint Fill/Stroke/Gap, Nonprinting), with Overprint Gap in Overprint Preview and IDML; PDF export writes them as `/op` and `/OP` with `/OPM 1`. +- Attributes panel (`object.attributes`: Overprint Fill/Stroke/Gap, Nonprinting), with Overprint Gap in Overprint Preview and IDML; PDF export writes them as `/op` and `/OP` with `/OPM 1`. Preflight warns about white or [Paper] set to overprint (`whiteOverprint`): a fill, stroke or gap, or ruby and kenten, that lays down no ink and would vanish on press. - Page Numbering View (Preferences: section or absolute): page labels everywhere follow it; Go to Page takes section names, numbers or `+n`. - Preferences › Advanced Type (document `advancedType`: superscript/subscript size and position; IDML TextPreference); subscripts now drop 33.3% like InDesign. - Preferences › Composition › Highlight: keep violations, H&J violations (three shades), custom tracking/kerning, substituted fonts. @@ -99,7 +117,7 @@ DesignCraft aims at full Adobe InDesign parity — and to be better: faster, ope - Endnotes (`endnote.insert/edit/delete/list/options`, Type ▸ Insert Endnote): references number through the document, the endnote frame on a new last page lists them under a heading; IDML keeps the listed text only. - Editorial notes (`note.new/edit/delete/convertToText/list`, Notes panel): anchored in text, flagged on screen, never printed or exported. - File ▸ Print Booklet (`file.printBooklet`): saddle-stitch or 2-up consecutive printer spreads as PDF, padded with blanks, with a gap between pages. -- Edit ▸ Transparency Blend Space (`edit.transparencyBlendSpace`; RGB for web/mobile documents; IDML TransparencyPreference) — exported PDFs blend in that space: CMYK print exports write their transparency groups and page groups in DeviceCMYK (PDF/X-4 also carries the CMYK working space as its `GTS_PDFX` output intent); RGB exports give pages with transparency a DeviceRGB page group. On screen, spreads with transparency in a CMYK blend space are shown through the working CMYK profile (their colors keep to its gamut, as when composited in CMYK). +- Edit ▸ Transparency Blend Space (`edit.transparencyBlendSpace`; RGB for web/mobile documents; IDML TransparencyPreference) — exported PDFs blend in that space: CMYK print exports write their transparency groups and page groups in DeviceCMYK (PDF/X-4 also carries the CMYK working space as its `GTS_PDFX` output intent; plain print, PDF/X-4, booklet and CMYK-containing RGB exports attach the working CMYK profile as `/DefaultCMYK`); RGB exports give pages with transparency a DeviceRGB page group. On screen, spreads with transparency in a CMYK blend space are shown through the working CMYK profile (their colors keep to its gamut, as when composited in CMYK). - High Contrast interface theme (fifth Interface Color Theme: black chrome, white text, yellow selection). - Place Excel workbooks (.xlsx): the first worksheet's used range becomes a table (shared/inline strings, numbers, booleans). - Object Library (`library.new/open/add/place/remove/list/json/close`, Library panel): `.dclib` files of snippets that keep stories, styles, swatches and images. @@ -132,7 +150,7 @@ DesignCraft aims at full Adobe InDesign parity — and to be better: faster, ope - Linked stories (Edit ▸ Place and Link, `story.placeAndLink/links/updateLink/unlink`): child stories copy a parent, show out of date in the Links panel and update. - Edit ▸ Menus (`window.hideMenuItem`): hide menu items; menus with hidden items end in Show All Menu Items. - View ▸ Separations Preview (`view.separations`, Window ▸ Output ▸ Separations Preview, `ink.separations`): the plates the print PDF puts on film, spot plates included. Each visible spread is exported as Export PDF writes it and separated with craft-prepress, so the Ink Manager's aliases and spots to process, overprint and the flattener show as printed. All inks as printed, one plate as film, or an ink limit in red over gray; the panel lists the plates with each ink's percentage under the pointer. -- Language (Character panel ▸ Language, Properties ▸ Character, `type.char {language}`): text in other languages isn't hyphenated or spell-checked with the English dictionaries, typographer's quotes follow the language (German „…“, French and Russian «…», Swiss, Spanish, Dutch, Nordic, Japanese and Traditional Chinese 「…」, Simplified Chinese “…”), the font's localized forms (OpenType `locl`: Turkish i, Bulgarian Cyrillic, Japanese / Chinese / Korean glyph variants) follow it too, and so does the fallback for CJK characters the font lacks (with Draw Missing Glyphs from Fallback Fonts on): Japanese, Simplified Chinese, Traditional Chinese and Korean each try their own installed system fonts (Japanese starts with the craft-fonts Japanese faces, Mincho first, when built with them; Hangul, kana and Bopomofo pick their language's fonts whatever the language). Language names from IDML keep their spelling; locale codes as InDesign writes them for some languages (`de_DE_2006`, `nl_NL_2005`; any `ll`, `ll_CC`, `ll-CC`) are their language and region for all of the above, and Chinese is also recognised in its common spellings ("Simplified Chinese", "Chinese (Traditional)", `zh_CN`, `zh-Hant`). Spanish is hyphenated with Javier Bezos's Liang patterns (`hyph-es.tex` 5.0, MIT) through the `hypher` crate; hyphenation for other languages isn't bundled yet. +- Language (Character panel ▸ Language, Properties ▸ Character, `type.char {language}`): text in other languages isn't hyphenated or spell-checked with the English dictionaries, typographer's quotes follow the language (German „…“, French and Russian «…», Swiss, Spanish, Dutch, Nordic, Japanese and Traditional Chinese 「…」, Simplified Chinese “…”), the font's localized forms (OpenType `locl`: Turkish i, Bulgarian Cyrillic, Japanese / Chinese / Korean glyph variants) follow it too, and so does the fallback for CJK characters the font lacks (with Draw Missing Glyphs from Fallback Fonts on): Japanese, Simplified Chinese, Traditional Chinese and Korean each try their own installed system fonts (Japanese starts with the craft-fonts Japanese faces, Mincho first, when built with them; Hangul, kana and Bopomofo pick their language's fonts whatever the language). Language names from IDML keep their spelling; locale codes as InDesign writes them for some languages (`de_DE_2006`, `nl_NL_2005`; any `ll`, `ll_CC`, `ll-CC`) are their language and region for all of the above, and Chinese is also recognised in its common spellings ("Simplified Chinese", "Chinese (Traditional)", `zh_CN`, `zh-Hant`). English, Spanish, Portuguese, Norwegian, Greek and German (2006 reform) hyphenate. German uses `hyph-de-1996.tex` 2024-02-28 (MIT) through `hypher`; the filename denotes the reformed 2006 rules. Other languages have no bundled patterns. - Books (`book.new/open/add/remove/list/styleSource/paginate/syncStyles/exportPdf`, Book panel): `.dcbook` files, continuous page numbering, style sync from a style source, one merged PDF. - Track Changes (`changes.track/list/acceptAll/rejectAll`, Type ▸ Track Changes): typing is marked added (highlighted on screen), deletions are kept but hidden from layout and exports until accepted or rejected. Per-change accept/reject and authors aren't there yet. - Track Changes: per-change Accept / Reject (`changes.accept`, `changes.reject`) and a Track Changes panel listing every change. @@ -257,6 +275,7 @@ same references), and from the app's JSON control channel. See [docs/agents.md]( > **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-12 · **Change:** minor (text stroke behind fill) · **Target:** Adobe InDesign 2026 > **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-13 · **Change:** minor (text threads by hand; the alpha gate waits on Primary Text Frame page fixes; Links source paths) · **Target:** Adobe InDesign 2026 > **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-13 · **Change:** minor (table anchors keep their own paragraphs) · **Target:** Adobe InDesign 2026 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-13 · **Change:** minor (CLI bundled with the macOS app) · **Target:** Adobe InDesign 2026 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. @@ -347,15 +366,14 @@ A string without a translation shows in English and fails no check; `cargo xtask | Hindi | hi | none | 0% | | Arabic | ar | partial (RTL UI and composition) | 85% | | French | fr | partial | 83% | -| Portuguese (Brazil) | pt-br | partial | 61% | +| Portuguese (Brazil) | pt-br | partial | ~100% | | Indonesian | id | none | 0% | | Japanese | ja | partial | 95% | | German | de | partial | 83% | | Korean | ko | none | 0% | | Vietnamese | vi | none | 0% | -Also shipped: Czech (99%), Italian (85%), Ukrainian (83%), Polish (99%). -Also shipped: Italian (85%), Ukrainian (83%), Georgian (100%). +Also shipped (2026-11-04 `i18n-report`, of 2,939): Czech (69%), Italian (68%), Ukrainian (65%), Polish (64%), Georgian (98%), Swedish (98%), Hungarian (65%), Russian (63%). ## Upcoming @@ -364,11 +382,10 @@ Ranked; detail and estimates in [docs/roadmap.md](docs/roadmap.md), the full lis 1. **Alpha gate:** Primary Text Frame page fixes: autoflow adds pages users can't delete (#165) (5–7 h) 2. Basic editing on every platform: copy/paste, context menus, caret formatting (30–50 h) -3. CI running `cargo xtask ci` on pull requests (4–8 h) -4. INDD real-file corpus: measure what `.indd` files keep through indd-utils (10–30 h) -5. IDML real-file corpus and fixes (60–100 h) -6. Composition oracle against InDesign; optical kerning tuning; overset rule (70–125 h) -7. Start on any GPU; find every installed font (25–50 h) +3. INDD real-file corpus: measure what `.indd` files keep through indd-utils (10–30 h) +4. IDML real-file corpus and fixes (60–100 h) +5. Composition oracle against InDesign; optical kerning tuning; overset rule (70–125 h) +6. Start on any GPU; find every installed font (25–50 h) ## Documents @@ -383,13 +400,72 @@ list) · [roadmap.md](docs/roadmap.md) (milestones, plan) · [parity-checklist.m ## Progress log +- **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. +- **2026-11-15** · Format follow-ups to the craft-libs cutover (craft-libs#778; ported from #2734 by Dylan M. Taylor): IDML export keeps CDATA image contents and table spans such as `inf` reach the table edge; DOCX plain-text import leaves out deleted tracked changes and expands inline objects; an XLSX number cell that isn't a number shows as written; unmarked CMYK JPEGs keep the shared decoder's ink polarity; PPTX export writes exact opacity; PDF export repins craft-pdf and craft-prepress to craft-libs main. No readiness percentage change. +- **2026-11-14** · `object.stroke` refuses a tint or gap tint outside 0 to 1, a weight outside 0 to 1000 pt, a miter limit outside 1 to 500, a gap overprint that isn't true or false, and an alignment, cap, join or arrowhead name it doesn't have, instead of clamping the numbers and skipping the names. The Stroke panel's Weight and Miter Limit fields keep their values in those ranges. No readiness percentage change. +- **2026-11-14** · Photo books no longer freeze the canvas (#1411; based on #2051 by texjer). The image cache keeps only the mip level each image is drawn at, for every format and display quality: a TIFF, PNG, PSD or CMYK JPEG used to keep its full decode too (48 MB for a 12 MP photo), so after about a dozen photos each edit evicted and decoded them again on the render thread. The canvas no longer waits for decodes: an image not cached at its size shows a light box or another cached level and decodes on one of three background threads (within the same in-flight memory limit as the decodes ahead of a render), and finished decodes are drawn in batches, at most one canvas render every 250 ms. Zooming into an image decodes it at most twice. Thumbnails and exports still wait for every image. No readiness percentage change. +- **2026-11-14** · IDML export keeps each endnote reference as its number in superscript text, as the endnote frame lists it, instead of dropping it; the endnotes are still written as plain text, without IDML's endnote elements (#2753). No readiness percentage change. +- **2026-11-14** · Object › Text Frame Options shows the inset spacing (one Inset for a non-rectangular frame), the column width and gutter and the paragraph spacing limit in the document's ruler units, as the Properties panel does, instead of always in picas, and a bare number typed in any of its measure fields is in those units (#2739). No readiness percentage change. +- **2026-11-12** · A render decodes the placed images in view that are not cached yet on several threads before it draws, instead of one after another while drawing. Page thumbnails, image exports and the first canvas frame of a page with six 24 MP photos take about 1.2 s instead of 2.8 s. No readiness percentage change. +- **2026-11-13** · PDF exports outside PDF/X-1a and PDF/A-2b attach the CMYK working space's ICC profile as `/DefaultCMYK` (`[/ICCBased …]`) on every page, inherited `/Pages` resource dict, Form XObject, SMask form, tiling pattern, and Type3 font resource scope (#2743). Plain print exports and booklets embed one shared Flate-compressed `/N 4` profile stream without adding `/OutputIntents` or `/Trapped`; PDF/X-4 reuses its catalog `/DestOutputProfile`; RGB-blend documents attach `/DefaultCMYK` when they draw in `DeviceCMYK` and skip it for pure RGB. Viewers that honor `/DefaultCMYK` instead of `/OutputIntents` (including Apple Quartz and MuPDF) now render CMYK colors consistently with the working space across both plain and PDF/X-4 exports. No readiness percentage change. +- **2026-11-12** · Properties › Text Frame shows the frame's inset spacing (Top, Bottom, Left and Right with a link that makes all four the same; one Inset for a non-rectangular frame) and four Vertical Justification buttons (Top, Center, Bottom, Justify), and the section also shows with the Type tool in a frame, where it changes the frame that shows the insertion point. No readiness percentage change. +- **2026-11-12** · An edit of a long threaded story composes the paragraphs it can change and copies the other lines from the composition before the edit; every typed character composed the whole story. In a 240-paragraph story a typed character composes 3 paragraphs (240 before). An edit that moves lines into other frames composes on until a paragraph starts in the same frame and place as before, or to the story's end, and stories with footnotes, tables, anchored objects, balanced columns or keep options that move lines are composed whole. No readiness percentage change. +- **2026-11-12** · Composing a story with endnotes, anchored objects or cross-references counts their marks in one pass over the story, instead of counting again from the story start for every paragraph. No readiness percentage change. +- **2026-11-12** · Center, Bottom and Justify vertical justification in a shaped frame test each moved line against the outline down to its baseline. The descenders of earlier lines may cross the outline, as the last line's do, so an outline that narrows under an earlier line no longer holds the text higher by that line's descent. No readiness percentage change. +- **2026-11-12** · Type shortcuts: Justify All Lines ⇧⌘F, Insert White Space › Em Space ⇧⌘M and En Space ⇧⌘N (shown in the menu, enabled at an insertion point), Paragraph Rules… ⌥⌘J (shown in the Paragraph panel menu). On the Mac a menu-bar insert (Em/En Space, Current Page Number) no longer types into the document while a text field has focus, a dialog or Quick Apply is open, or an input method is composing. An alignment the paragraphs already have records no undo step (#1138). No readiness percentage change. +- **2026-11-12** · A placed JPEG drawn at a half, a quarter or an eighth of its pixel size or less is decoded at that size straight from its compressed blocks, so the canvas, page thumbnails and loaded-graphic thumbnails no longer decode and keep the full-size picture for it. CMYK JPEGs and the full size still decode in full. No readiness percentage change. +- **2026-11-12** · A decoded placed image becomes a screen pixmap in its own buffer, premultiplied in place, and opaque pixels are left as they are: 120 ms becomes 7 ms for a 24-megapixel opaque photo, with the same pixels. No readiness percentage change. +- **2026-11-12** · With the insertion point in footnote text, the table commands (Insert Row, Delete Column, Merge Cells, Table Options, Select Table, table styles) are disabled, as they are outside a table, instead of failing with "no table 18446744073709551615". A call that names a table still runs. No readiness percentage change. +- **2026-11-12** · The status bar's preflight count and the Preflight panel take their issues from a check on a background worker, which checks the newest state of the document and shows the issues last found meanwhile. Moving or resizing a frame and typing no longer wait for a check of the whole document on every drag step and keystroke. No readiness percentage change. + +- **2026-11-12** · Object › Text Frame Options… (Cmd+B) opens with the Type tool in a frame, so inset spacing and vertical justification can be changed while typing; it changes the frame that shows the insertion point, or every frame that holds part of the selected text (#2396). No readiness percentage change. +- **2026-11-05** · Document tabs that overflow the bar scroll (trackpad, wheel, arrows), keep the active tab in view and list every open document in a menu. No readiness percentage change. +- **2026-11-04** · Striped strokes retain out-and-back cubic segments whose second control point is away from the coincident endpoints and first control point. A geometry regression checks the offset extent and both stripe bands. No readiness percentage change. +- **2026-11-04** · Esperanto is a text language (Character › Language, `type.char {language: "Esperanto"}`, IDML `$ID/Esperanto`): tag `eo`, English-style quotes; not hyphenated yet (#1201). No readiness percentage change. + +- **2026-11-02** · EPUB Export Options names a cover image file (PNG or JPEG, typed or chosen with Choose…) for the reflowable export; left empty, the first page stays the cover (#1934). No readiness percentage change. +- **2026-11-02** · The Pen shows the segment a dragged smooth point shapes while it is dragged, and its rubber band curves out of a smooth point's direction line (#1438, first item). No readiness percentage change. +- **2026-11-02** · A Custom text variable defined with a number (a typed `2026` reaches the command as one) shows its digits instead of nothing (#2093, first item). No readiness percentage change. +- **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-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. +- **2026-11-12** · An idle canvas frame no longer does work for the spreads out of view (part of #1343): page shadows, paper, guides, margins, frame edges and overset marks are painted for the spreads and objects in view, and only their stories are looked up. In a 400-page document with two frames a page, an idle frame painted 5,099 shapes and looked up 400 stories; it now paints 311 and looks up 1, the same as in a 4-page document. No readiness percentage change. +- **2026-11-06** · Preflight warns about white or [Paper] set to overprint (#2401): a fill, stroke or stroke gap, or ruby and kenten, in [Paper] or a colour that lays down no ink (C=0 M=0 Y=0 K=0, a 0% tint; a spot ink, such as a white ink or a varnish, prints whatever colour stands in for it), is reported as `whiteOverprint`, since it disappears on press. Text itself has no overprint, so white text in a frame set to Overprint Fill still knocks out and prints, and is not reported. Preflight no longer says PDF export drops ruby and kenten overprint, which it writes. No readiness percentage change. +- **2026-11-04** · Interface Language › Português (Brasil) translates the whole interface: 996 strings the catalog lacked (tool names, window and guide commands, Keyboard Shortcuts sets, panel docking, Edit › Menus paths, the Japanese typesetting dialogs, special characters, Load Styles, Data Merge, Preflight, font replacement, the Package summary, OpenType features, page presets, About) and File › New's unit names, and a path is "demarcador" throughout. `cargo xtask i18n-report` counts 2,936 of 2,939 strings for pt-BR (1,933 before); only the Control panel's `IT`, `VA` and `Y:` captions stay English, as in every language. No readiness percentage change. +- **2026-11-03** · `type.char` says when the font it applies isn't available (#2189): it returns `{"warnings": ["Missing font: Courier Prime (using Source Sans 3)"]}`, or `Missing font style: …` for a style the family doesn't have, in preflight's words. The font is still applied, as before, so Find Font and preflight list it. A script that asked for a font the machine doesn't have exported in the substitute with no word about it. No readiness percentage change. +- **2026-11-02** · Packaged PDFs report their export warnings in the package result and Instructions.txt, and soft drop shadows and feathers in them are tested. Frame and text-range hyperlinks keep their source bounds when the frame is rasterized, including inside groups. No readiness percentage change. +- **2026-11-01** · Parent page resizing (#1620): Properties, the Page Tool Control panel and on-page handles resize the selected parent page independently of document pages. Stable parent IDs, repeated resizing, anchors and liquid rules are preserved on the current command modules. Inline parent margin editing targets only the selected parent page and preserves opposite-page margins and document overrides; document commands retain their first-page default before the canvas is initialized. No readiness percentage change. +- **2026-10-31** · `font.list` reports the embedding licence of the face that sets each font's text: its OS/2 `fsType` and what the bits mean (`restrictedLicence`, `bitmapOnly`, `noSubsetting`, `editable`, `previewPrint`; null when the font is missing or has no OS/2 table). A script or host that makes PDFs can check every face, bundled and installed ones included, without reading font files. Export behaviour is unchanged. No readiness percentage change. +- **2026-10-31** · A `.designcraft` file opened from bytes (`file.openBytes` with its file name, as a browser or host passes it) is titled without the extension, as an IDML file opened that way is. Saving it in the browser downloaded `Brochure.designcraft.designcraft`, and the File Name variable showed the doubled name. Browser Open and Drop pass the full file name, so only the engine removes the extension and a repeated suffix is kept in the title. Native and IDML content takes priority over a misleading `.indd` or `.indt` extension. No readiness percentage change. +- **2026-10-30** · Import warnings about a story have a Show button: it closes the warnings (the status line keeps them) and selects the story's first frame, fitted in the window. `file.open` returns `warningItems`, the frame each IDML or InDesign warning is about (or null), matching the converter's INDD story numbers (`story 30892`, written to IDML as `u78ac`) and IDML `Self` names to the imported stories. No readiness percentage change. +- **2026-10-30** · Parent pages: a running-header variable shows its name in angle brackets on the parent itself (it was blank), as InDesign shows it; on the document pages, and in text with no page, it shows its text as before. No readiness percentage change. +- **2026-10-30** · Without facing pages, a page of a multi-page spread shows the parent page in its place, as in InDesign: the second page of a two-page spread shows the parent's second page. Every single-sided page showed the parent's first page, so an InDesign book set up without facing pages but laid out in two-page spreads repeated the left parent page's items (a black heading bar) on its right pages and lost the right parent page's. No readiness percentage change. +- **2026-10-30** · Dropping images from the file manager works as in InDesign: images dropped together load the place cursor in the order they came, and one image dropped off a frame that takes it loads the place cursor instead of being placed at once (on a frame it still fills it). Documents and text files dropped keep opening and flowing as before. Ported from #1307 and #1666; see [multi-image placement](docs/multi-image-placement.md). No readiness percentage change. +- **2026-10-30** · File › Place Contact Sheet… puts every image loaded in the place cursor on new pages, in a grid of equal frames (`place.contactSheet`), as one undo step. Ported from #1392; see [multi-image placement](docs/multi-image-placement.md). No readiness percentage change. +- **2026-10-30** · Placing several images works as in InDesign. File › Place takes several files, and they load the place cursor in the order chosen: it shows the first one's thumbnail with how many are loaded ("(6)"), each click places the next, arrow keys while dragging lay out a grid (`place.grid`), and Escape unloads the rest (`place.cancel`). Switching, opening or closing a document unloads it too, back to the Selection tool. A drag with the cursor draws the frame at the graphic's proportions, with its scale. Ported from #1307, #1392 and #1432 (multi-image placement, cursor thumbnail and count); see [multi-image placement](docs/multi-image-placement.md). No readiness percentage change. +- **2026-10-30** · macOS: a file dragged in from the Finder fills the frame it is dropped on. winit sends no pointer events during such a drag, so the drop asks the system where the pointer is (`Services::pointer`, from `NSEvent.mouseLocation`), at any UI scale. No readiness percentage change. +- **2026-10-30** · File > Package opens a dialog, as the reference app's: a Summary of fonts, links and images and inks, pages for each, a Printing Instructions step, and a PDF made with the options of a preset (#1514, #1515). +- **2026-10-30** · IDML import reads TOC separators and entry styles written with the `$ID/` prefix or as `Properties` children, and the TOC separator notation (`^t`, `^y`, `^m`, `^>`) is shared by the dialog and IDML, with a special-character menu on the separator field (#1249, #1255). +- **2026-10-30** · Spreads show a line at each edge where two of their pages meet, on the canvas only (it isn't printed or exported), so the page boundaries inside a spread are visible while laying out across them, in the spread edge's colour. Right-to-left spreads and pages of different sizes put it on the edge the pages share; pages that don't touch, as an imported spread can keep them, get none (#1838). No readiness percentage change. +- **2026-10-29** · Inserting text with many returns no longer takes time that grows with their square (part of #1588): each return copied its paragraph's format with its own insert, moving every format after it. Splitting 20,000 returns into paragraphs took 15.8 s; placing a text file of them now takes 0.2 s, and one of a million returns 5.5 s. No readiness percentage change. +- **2026-10-28** · A placed image whose pixels would decode past 1 GiB of RGBA (256 Mpx) is refused from its header, before decoding (#1586). A 288 KB 23,000 px gray PNG used to hang the first draw for 9 s and take the app to 4.5 GB; it now draws as an empty frame, and PDF export skips it with a warning. A 300 ppi A0 scan still fits. No readiness percentage change. +- **2026-10-28** · Discretionary hyphens (U+00AD) break in the single-line composer with automatic hyphenation on or off, matching the paragraph composer. Unbroken soft hyphens remain invisible and zero-width, and words containing them keep only their discretionary break points (#1955). No readiness percentage change. +- **2026-10-28** · Autoflow no longer sizes the rest of a story by a frame that a Start Paragraph option (next column, frame, page, or odd or even page) ends early (#1209). With a title before a chapter that starts on the next odd page, it estimated a page per few characters, added up to 2000 pages (the autoflow limit) and removed them again: placing 2000 words took 36 s in the app, now 0.4 s, with the same pages. It looks past tracked-deleted paragraphs for the option, as composing does, and asks for every frame that start options and breaks force in one round: 200 one-line chapters on their own pages take 9 ms (58 ms before). A break and the start option it meets count once, and breaks that tracked changes delete or a hidden condition hides don't count. No readiness percentage change. +- **2026-10-28** · IDML export writes the document's default `StoryPreference` in `Resources/Preferences.xml`, as InDesign does. Only each story carried one, and IDML readers that take the spread reading order from the document's (Okapi's IDML filter) failed on DesignCraft's files. No readiness percentage change. - **2026-10-27** · An iconic panel's flyout stays open while you work in the canvas or a text field: Auto-Collapse Iconic Panels is off by default, and preferences saved with it on start with it off. Preferences › Interface › Panels holds the setting next to the column bar's menu item. No readiness percentage change. +- **2026-10-26** · Inner Shadow, Inner Glow (from the edges) and Bevel and Emboss on a frame holding an image follow what the image paints: a transparent part is outside the object, so the effect lines the image's opaque edge, not the frame (#1622). Satin and a centred Inner Glow still follow the frame. No readiness percentage change. +- **2026-10-25** · Duplicate Layer (`layer.duplicate`; the layer's context menu in the Layers panel, or a layer dropped on Create New Layer) adds a copy named after the layer with " copy" added ("Art copy" for Art) above the layer, with its settings, a copy of every object on it and copies of its ruler guides, on document and parent pages, in one undo step. Copied frames stay threaded to the copies of frames on the same layer and are not threaded to frames on other layers. A copied override of a parent item overrides that item's copy, and pages hide the copy where they hide the parent item. Hyperlinks on copied objects and text get copies that go to the same destinations. No readiness percentage change. - **2026-10-24** · Column rules run from the top line's ascent to the bottom line's descent, as InDesign draws them, instead of from the top to the bottom of the columns, on screen, in PDF and in PowerPoint export. The top and bottom insets shorten the rule from those lines. Existing documents draw their column rules at the new length. No readiness percentage change. +- **2026-10-24** · Table › Cell Options › Diagonal Lines… (`table.setCell` `diagonal`, `table.getCellDiagonal`): as in InDesign, a cell can carry a diagonal line from the top left corner to the bottom right, from the top right to the bottom left, or both, with the weight, type, color, tint, gap color and gap tint that cell edges take, drawn in front of the cell's contents or behind them. The lines draw on screen and in PDF and are saved in the native format. No readiness percentage change. - **2026-10-20** · Edit › Keyboard Shortcuts is craft-keymap's shared dialog: commands grouped by menu with Show and Filter, recording that asks before taking a key from another command, undo and redo, named shortcut sets (edits of Default become Custom; an imported set becomes a set of its own), an on-screen US keyboard, InDesign Show Set files reviewed before they apply, JSON export and an HTML summary. ui.json keeps the `shortcuts` map earlier versions read, for the active set. No readiness percentage change. - **2026-10-19** · Import InDesign Set… runs on craft-keymap's importer: a set's Window menu panel items (Layers F7, Pages F12, Swatches F5) and Tools items set the panel and tool shortcuts, all of an item's Default keys apply, and the report adds numeric keypad keys read as main keys and likely commands for unmatched items (`window.importShortcuts`). On InDesign's Windows defaults it matches 366 of 1,629 items (was 233) and changes 23 commands. No readiness percentage change. - **2026-10-19** · Keyboard shortcuts run on the shared craft-keymap crate. Panels take shortcuts, with InDesign's defaults where the key is free (Swatches F5, Color F6, Layers F7, Info F8, Stroke F10, Paragraph Styles F11, Character Styles Shift+F11, Pages F12, Align Shift+F7); tool keys are editable in Edit › Keyboard Shortcuts and `window.setShortcut`, and tools sharing a key take turns (B). Saved shortcuts load unchanged. No readiness percentage change. +- **2026-10-17** · HU1: initial Hungarian (`hu` / Magyar) interface localization (updated 2026-11-01): 1,906 catalog entries, four context captions and all 37 tool labels. AI-assisted; the initial catalog was personally reviewed in the app by Veress Róbert, a native Hungarian speaker with over 30 years of DTP experience. Uncatalogued strings keep their English fallback. Hungarian spelling and hyphenation are separate work in #1484. No readiness percentage change. - **2026-10-16** · Edit › Keyboard Shortcuts imports a set saved by InDesign's Show Set (.txt, Windows or Mac key names, UTF-8 or UTF-16): matched commands take its Default shortcuts or lose theirs, other commands give up keys it takes, and a report lists what it changed and the items it could not match (`window.importShortcuts`, #1180). Tool keys stay fixed. No readiness percentage change. - **2026-10-20** · PDF/X-1a:2003 export (craft-libs#194): `file.exportPdf {standard: "x1a"}`, the Export PDF dialog's PDF/X-1a:2003 preset and standard. The PDF/X-4 print file is flattened in its inks by craft-prepress (no transparency; spot, process, overprint and live text kept; complex regions as DeviceN images at the Transparency Flattener preset's resolution), then written as PDF 1.4 with the X-1a identification and checked; `validate-pdf --standard x1a`. Soft drop shadows reach the flattener in their swatch's inks; other soft effects are still RGB images. No readiness percentage change. - **2026-10-20** · Print color (craft-libs#190): CMYK print PDFs blend in DeviceCMYK through craft-pdf's print settings instead of byte rewrites, with the CMYK working space as the output intent in PDF/X-4 only; overprint (Overprint Fill, Stroke and Gap, overprinting text, 100% [Black]) is written as `/op` `/OP` `/OPM 1`; Knockout Group writes `/K true` instead of becoming an image; File › Print prints the PDF Export PDF writes. No readiness percentage change. @@ -401,6 +477,10 @@ Newest first. - **2026-10-24** · Renaming a paragraph or character style, or moving it into a style group, keeps its Export Tagging under the new name, and undo puts it back under the old one. Deleting a tagged style drops its tagging and leaves the replacement style's own tagging as it was. No readiness percentage change. - **2026-10-24** · Quick Apply and the application bar's search leave out the interface commands that failed or reset a setting when chosen there: those that need a workspace, a command and shortcut, a menu item, a panel, a window edge, an app page, a recent file or a swatch they can't give them, a Contextual Task Bar place, and Interface Color Theme, UI Scaling, Reset Shortcuts, the flattener preset, Screen Mode and Zoom To, which without a value switched to the dark theme, set 100%, cleared every custom shortcut or the preset, or went to Normal mode or 100% zoom. Each stays in the menu, panel or dialog that gives it the value. No readiness percentage change. - **2026-10-24** · EPUB Export Options › Split Document, a dialog before File › Export EPUB… saves (`document.epubSplit`, stored with the document): off, a single paragraph style, or based on paragraph style export tags, with Paragraph Style Options › Export Tagging's Split Document flag marking those styles. A reflowable EPUB is one content file unless Split Document is on; the split before each top-level h1 from #791 is gone. A split before a list item or preformatted line no longer leaves an unclosed list or block in a content file. IDML import and export keep the setting and the flag, and Load Styles the flag. No readiness percentage change. +- **2026-10-24** · Linux file managers show a `.designcraft` file's first page instead of a blank icon: the packages install a freedesktop thumbnailer (`share/thumbnailers/ai.storyteller.designcraft.thumbnailer`) that runs `designcraft-cli thumbnail FILE OUT.png SIZE`, which writes the `preview.png` saving already puts in the file, fitted to the size asked for and never enlarged. A file without a preview fails, so the file manager keeps the file type's icon (#1782). No readiness percentage change. +- **2026-10-20** · File ▸ Export Layouts and Versions (`file.exportBatch`): export alternate layouts one by one, all in one PDF or as a PDF each, in several versions at once (press PDF with marks and bleed, PDF with bleed only, screen PDF, PNG, JPEG), each in its own folder and named from the layouts; the dialog lists the files before writing and saves the setup as an export preset. Print can print chosen layouts, together or as a job each. No readiness percentage change. +- **2026-10-19** · Parents and alternate layouts in the Pages panel. Add parents (B, C…) with one click, duplicate them (`layout.parents.duplicate`) and rename their prefix and name in Parent Options (`layout.parents.options {prefix, name}`), from the parents' context menu or the panel menu. Alternate layouts show as columns side by side, each with a menu to create, duplicate (`layout.alternate.duplicate`), rename or resize (`layout.alternate.options`) and delete (`layout.alternate.delete`) it. Sections now follow their pages when pages are inserted or deleted. No readiness percentage change. +- **2026-10-18** · Placing an image or media without coordinates, or clicking the loaded place cursor, no longer turns a line into a frame: lines and paths whose points all lie on one line are left as they are and the content gets a new frame. Frames, and open paths that enclose an area, take the content as before. No readiness percentage change. - **2026-10-18** · Repeated placed-PDF layer variants are prepared once per asset and hidden-name set, with recovery warnings retained. All-visible named layers keep their original source bytes, including PDFs whose cross-reference tables the reader repairs, in plain, PDF/X-4, booklet and book-merge output. Layer changes that require writing still reject an unusable cross-reference table with a file-named damage error; the first placement error is retained (#906). No readiness percentage change. - **2026-10-18** · Placed PDF optional-content defaults and per-frame overrides survive plain and PDF/X-4 vector export, including repeated placements, booklet output and book merging (#906). Source usage-application arrays are accepted; groups without a catalog configuration stay visible. Missing or unreadable default configurations and unsupported base states use all-ON defaults with a file-named export warning, retaining explicit frame overrides. Readable groups omitted from the catalog list are added with a distinct file-named warning, preserving their default ON/OFF states. Concurrent recovery warnings are combined. Malformed ON data is recoverable when a known ON base and empty OFF list prove it cannot hide artwork; missing display names are generated without changing known visibility when no override needs name matching. Contradictory states, unresolved references and ambiguous name overrides still fail export. Print-usage adjustments and IDML layer overrides remain follow-ups. No readiness percentage change. @@ -408,6 +488,7 @@ Newest first. - **2026-10-23** · `designcraft-cli mcp` takes `--automation-read-root` and `--automation-write-root` more than once, as the suite's other apps do (#1552): a path inside any root of its kind passes, and the roots' common parent, `..` or a link out of them and the other kind's roots stay refused. No readiness percentage change. - **2026-10-23** · Layout › Go Back and Go Forward (Cmd+Page Up / Cmd+Page Down, Ctrl on Windows and Linux) retrace the jumps between pages (Go to Page, the page and spread commands, the Pages panel) as InDesign's do, returning to where the view was on each page at the current zoom; a new jump after going back drops the pages ahead, scrolling adds no entry, and pages deleted since are skipped. No readiness percentage change. - **2026-10-24** · The Story Editor has InDesign's vertical depth ruler between the style column and the text, and View › Story Editor › Show/Hide Depth Ruler (`view.storyEditorDepthRuler`) shows or hides it in the Story Editor, remembered with the preferences. The ruler is marked in the document's vertical ruler units with how deep the story's text fills its frames, counted through its columns and threaded frames (lines set side by side, in the sub-columns of a split paragraph or on both sides of a wrap object, count once), and is shaded down to the overset point, where a red line now crosses the editor. No readiness percentage change. +- **2026-10-24** · View › Story Editor › Show/Hide Style Name Column (`view.storyEditorStyleColumn`) shows or hides the Story Editor's column of paragraph style names, as in InDesign, and dragging the bar between the column and the text makes the column wider or narrower (40 to 400 points; the command's `width` sets it too). Both settings are remembered with the preferences, so the editor opens with the same column the next time. No readiness percentage change. - **2026-10-24** · Split Note (`note.split {story, id, at}`, the Notes panel's Split Note button): as in InDesign, a note splits in two at the insertion point in its text. DesignCraft moves the text after it into a new note by the same author, anchored right after the first. No readiness percentage change. - **2026-10-24** · Type › Notes › Previous Note and Next Note (`note.previous`, `note.next`): as in InDesign, they move the insertion point from note to note in the story, putting the caret after the note's anchor. Each item is unavailable when no note lies in its direction in the story, or when the insertion point is in a table cell or a footnote. No readiness percentage change. - **2026-10-24** · Type › Notes › Convert to Note (`note.convertFromText {author?}`): as in InDesign, the selected text leaves the story and becomes the text of a new note, whose anchor takes its place; Convert Note to Text puts it back. DesignCraft refuses a selection in a table cell, or one that holds a note, footnote, endnote, anchored object, index marker, text anchor, cross-reference or table. No readiness percentage change. @@ -416,8 +497,11 @@ Newest first. - **2026-10-24** · Optical Margin Alignment per story with a size (`story.options {opticalMargin, opticalMarginSize}`, off by default): when it is on, the story's paragraphs hang punctuation and letter edges by amounts set for that type size, except paragraphs with Ignore Optical Margin (`ignoreOpticalMargin` in `type.para` and paragraph styles). Table cells and footnotes don't take the story setting yet. When it is off, the per-paragraph switch still hangs at the text's own size. IDML imports and exports both (`StoryPreference/@OpticalMarginAlignment`, `@OpticalMarginSize`, `IgnoreEdgeAlignment`) (#947). No readiness percentage change. - **2026-10-24** · Text frames: a custom baseline grid's Relative To (Text Frame Options › Baseline Options, `object.textFrameOptions {baselineGrid: {relativeTo}}`, IDML `BaselineFrameGridRelativeOption`) measures the grid's start from the top of the page, the top margin, the top of the frame or its top inset. Text Frame Options had no custom baseline grid controls, imports dropped the setting and every frame grid started from the page top, so grid-aligned text in a frame measured from its own top sat on the wrong lines. No readiness percentage change. - **2026-10-24** · Paragraph Style Options › Indents and Spacing has an Align to Grid menu: None, All Lines or First Line Only. It shows the style's current setting. A First Line Only style could be set only in the CJK Grid Settings section, which shows only with CJK features on, or through commands. No readiness percentage change. +- **2026-10-24** · A guide pulled out of a ruler keeps the resize cursor across it until it is dropped; the tool's cursor took over as soon as the pointer left the ruler, so the drag looked as if it had stopped. No readiness percentage change. - **2026-10-24** · Anchored text frames, such as marginal notes, compose where their host story places them: they align to the baseline grid at that position, and page-number markers and spine-relative alignment inside them read the host's page. They composed against a grid measured from their stored position and on no page, so a note set to Only Align First Line to Grid could sit a fraction of a line off the body text's grid line. No readiness percentage change. - **2026-10-24** · Tables: a gradient swatch in a cell fill draws as a gradient on the canvas and in PDF, in one gradient space for the whole table, so it runs across cells without restarting. Cells showed the gradient's first stop as a solid colour. No readiness percentage change. +- **2026-10-25** · Table › Go to Row… (`table.goToRow {row, section?}`): as in InDesign, a dialog takes a row number and, when the table has header or footer rows, the section is chosen from a menu. The menu lists Body Rows and those of Header Rows and Footer Rows that the table has. DesignCraft counts the row from 1 within its section and selects it, and the view scrolls the row to its middle at the same zoom, on the page in view or another. A row number past the section's last row is refused. No readiness percentage change. +- **2026-10-22** · Paragraph Style Options › Paragraph Shading and Paragraph Border are laid out as InDesign's: headed with the page's name; Tint is a spinner with InDesign's presets and has Overprint beside it (shading, border and gap; a new attribute each, kept through IDML; PDF export warns it doesn't overprint yet); Corner Size and Shape is InDesign's two-by-two grid of corner icons, sizes and shape menus showing each shape's glyph, with the link in the middle; offsets and weights have spinners. Found in the Learn Skills Daily course, chapter 41. No readiness percentage change. - **2026-10-24** · New documents start with Hyphenate Capitalized Words, Hyphenate Last Word and Hyphenate Across Column off in [Basic Paragraph], as in InDesign. Opened and imported files keep the values they carry. No readiness percentage change. - **2026-10-24** · The baseline grid's Relative To setting applies: with Top Margin, the grid starts at each page's own top margin in text composition, on the canvas and for snapping. It started at the page top, so grid-aligned text sat on the wrong lines and a page could fit one line fewer. No readiness percentage change. - **2026-10-24** · Custom-positioned anchored objects honour Relative to Spine (`anchored.options {spineRelative}`, IDML `SpineRelative`): the settings describe a left-hand page and mirror on a right-hand page, so marginal notes stay in the outside margin on both pages of a spread. On right-hand pages they took the left-hand placement and landed in the inside margin, across the spine or over the body text. No readiness percentage change. @@ -425,17 +509,30 @@ Newest first. - **2026-10-23** · File › File Info… edits the document's Document Title, Author, Description, Keywords, Copyright Notice and Copyright Info URL (`file.info`), and the document saves them. PDF export (PDF/X-4 and Print Booklet included) writes the title, author, description and keywords into the PDF's document information and XMP. EPUB export takes the title and author from File Info, and HTML export takes the title. A title or author given to the export replaces File Info's, and an empty Document Title leaves the document's name as the title. No readiness percentage change. - **2026-10-23** · Save and export dialogs (Save As, Save a Copy, Export PDF and the other exports, Package, libraries and books) start in the active document's folder once it has been saved, and for a document never saved in the folder of the last file saved or exported, remembered across sessions (#1653). A folder deleted since falls back to the system's choice. No readiness percentage change. - **2026-10-22** · Autoflow (Shift-click with the loaded text cursor, autoflow on Place, `text.thread {autoflow}`) fills the pages that follow before it adds any, as InDesign does: one frame per column on each following page, whatever else the page holds, then new pages at the end of the document. It inserted pages right after the story's last frame, in front of the document's own pages. Frames it set past the end of the text go again; a page the document had stays, and a page autoflow added only for such a frame goes with it. Smart Text Reflow of the primary text frame is unchanged. No readiness percentage change. +- **2026-10-18** · German text hyphenates using the MIT-licensed 2006 reform patterns (`hyph-de-1996.tex`) through `hypher`. Explicit 2006 names and plain/2006 locale codes reach both composers; traditional and unknown spelling variants stay unhyphenated. Tests cover this distinction, umlauts, ß, compounds, reformed ck/st breaks and paragraph limits. Six of InDesign's ~40 hyphenation languages. No readiness percentage change. - **2026-10-16** · Edit › Keyboard Shortcuts imports a set saved by InDesign's Show Set (.txt, Windows or Mac key names, UTF-8 or UTF-16): matched commands take its Default shortcuts or lose theirs, other commands give up keys it takes, and a report lists what it changed and the items it could not match (`window.importShortcuts`, #1180). Tool keys stay fixed. No readiness percentage change. - **2026-10-23** · Translations: a missing string shows in English and fails no test; `cargo xtask i18n-report`, run by `cargo xtask ci`, prints the missing strings per language. Tests keep duplicate-key and placeholder checks and the language mechanics (lookup, context captions, plural captions, right-to-left). No readiness percentage change. +- **2026-10-23** · Show Hidden Characters marks table cells as InDesign does: every cell shows its own spaces, tabs and paragraph returns and an end-of-story # after its text (an empty cell shows just the #), and the table paragraph's ¶ sits after the table's bottom right corner. Cells showed no marks. No readiness percentage change. +- **2026-10-23** · Tables: with the Type tool in a cell, Shift+Tab goes back a cell (it went on to the next one) and Esc toggles between the text and the cell, as in InDesign: the insertion point selects its cell, and selected cells select the text of the first one (`table.toggleSelection`). Esc left the table for the frame. No readiness percentage change. +- **2026-10-23** · Direct Selection shows a path's direction handles as InDesign: both handles of each selected anchor and, on its neighbours, the handle shaping the segment to it; no handles with no anchor selected, and handles that don't show can't be grabbed. The tool draws the path and its points without the bounding box. Found in the Learn Skills Daily course, chapter 43. No readiness percentage change. +- **2026-10-23** · Tables: Convert Text to Table… and Convert Table to Text… open InDesign's dialogs (they converted at once, with tabs and paragraphs only). Column and Row Separator take Tab, Comma, Paragraph or any characters typed; Number of Columns, available when both separators are the same, fills rows of that many cells (a list of paragraphs into two columns); Convert Text to Table also applies a Table Style. `table.convertFromText` takes `rowSeparator`, `columns` and `tableStyle`, and `table.convertToText` its separators. Convert Text to Table is available only with text selected outside a table. No readiness percentage change. +- **2026-10-23** · Tables: the Table menu follows InDesign's order (Cell Options before Insert, Delete and Select; Merge, Unmerge and Split before Convert Cell Type and Convert Rows; Distribute Rows Evenly before Distribute Columns Evenly), and its first item is Insert Table… with InDesign's Cmd+Alt+Shift+T, which opens the dialog (the shortcut ran `table.insert` with its defaults, behind the dialog). The Table panel stays in Window › Type & Tables (Shift+F9). The Insert Table dialog is laid out as InDesign's: Body Rows and Columns, then Header and Footer Rows, as numbers with spinners and right-aligned labels, and a Table Style applied to the new table. No readiness percentage change. - **2026-10-22** · Hyphenation Settings, as in InDesign: the Paragraph panel menu's Hyphenation… (`app.hyphenationDialog`) sets the selected paragraphs' Hyphenate, Words with at Least, After First, Before Last, Hyphen Limit, Hyphenation Zone, the Better Spacing ↔ Fewer Hyphens slider (InDesign's 0–10 steps), Hyphenate Capitalized Words, Last Word and Across Column, with Preview, as one undo step; Paragraph Style Options › Hyphenation has the same form. The panel menu lists its items in InDesign's order. Replicated from a hyphenation tutorial: the same text in Minion Pro breaks into the same lines as InDesign's with hyphenation on, off, and at Fewer Hyphens. No readiness percentage change. - **2026-10-22** · Hyphenate Across Column (Hyphenation Settings; IDML HyphenateAcrossColumns) is applied: with it off, a paragraph whose line ending in an automatic hyphen would end a column or frame is re-composed without that hyphenation point, so the word moves on whole, as in InDesign. Opened and imported files keep their own setting, so their layouts don't change. No readiness percentage change. - **2026-10-22** · The Paragraph panel is laid out as InDesign's: the nine alignment buttons in groups; indent, spacing and drop cap fields by their icons in two columns, with Space Between Paragraphs Using Same Style (Ignore or a space); Shading and Border with the Paragraph Borders and Shading button and colour; Hyphenate with Do Not Align / Align to Baseline Grid. Its panel menu follows InDesign's order: Paragraph and Single-line Composer, Only Align First Line to Grid, Balance Ragged Lines, Optical Margin Alignment, Justification…, Keep Options…, Span Columns…, Hyphenation…, Drop Caps and Nested Styles…, GREP Styles… (these three now open for the selected paragraphs), Paragraph Rules…, Paragraph Borders and Shading…, Bullets and Numbering…, Restart/Continue Numbering, Define Lists… and the paragraph direction. Convert Bullets and Numbering to Text is listed but not available yet. No readiness percentage change. +- **2026-10-22** · Preferences › Units & Increments with no document open, as in InDesign: the ruler units (horizontal and vertical), the ruler origin and the cursor-key and kerning increments set there are what new documents start with, and New Document opens in those units. They are kept with the application preferences (`prefs.set {defaultUnits}`); a document keeps its own once made. Reported by a reader who works in inches and had to change every file. No readiness percentage change. +- **2026-10-22** · French and Italian text is hyphenated, with hyph-utf8's patterns through hypher (hyph-fr 2.13 and hyph-it 4.9, MIT): for the Language set in the Character panel (French, French: Canadian, French: Swiss, Italian, or fr / it locale codes). A word with an elision hyphenates after its apostrophe (l'im-pri-me-rie, dell'im-pa-gi-na-zio-ne), in French and Italian only; other languages leave apostrophe words unbroken. Gap 13 shrinks. No readiness percentage change. - **2026-10-22** · A ruler guide dragged with the Selection tools, out of a ruler, on its own or with other selected guides, snaps along its axis as objects do (#1221): to other ruler guides, margins, columns, bleed, page and object edges and centers (with the smart-guide mark) and the document grid, within the snap zone and following Snap to Guides and Smart Guides. Shift snaps to the ruler's ticks and Cmd suspends snapping. The preview line, the position readout and the drop use the same snapped position. No readiness percentage change. - **2026-10-22** · macOS: the app menu has a Language submenu after Settings… with each interface language in its own name and the current one checked, as in the suite's other apps; Preferences › General › Interface Language stays. No readiness percentage change. - **2026-10-23** · Type › Text Variables › Convert Variable to Text (`variables.convertToText`): the variable instances in the selected text, in a story, a table cell or a footnote, become plain text of the value each shows on its own page (a running header on page 3 becomes page 3's heading). `variables.convertAllToText {name}` does the same for every instance of one variable in the document, as the Text Variables dialog's Convert to Text button. The variable stays defined; one undo step. No readiness percentage change. - **2026-10-22** · macOS menu bar: the menus keep working after the interface language or Show CJK Features changes (a rebuilt menu bar lost every click, Quit included), and its key equivalents are the shortcuts in effect, so a shortcut moved in the Keyboard Shortcuts editor leaves its old menu item. No readiness percentage change. +- **2026-10-20** · MCP: every tool states all four behaviour hints (read-only, destructive, idempotent, open-world), input schemas are closed, and a misspelt key inside a `batch` step, a `pointer` event or `mods` is refused (`-32602`) like a top-level one instead of being ignored; a JSON script step with a key other than `command`/`params` is an error. A panic outside a command is a tool error instead of ending the server. No readiness percentage change. - **2026-10-22** · Paragraph rules: Rule Above's offset is measured from the first line's baseline to the rule's bottom edge, as in InDesign. Rules sat one ascent too high and crossed the previous paragraph's text (reported from an imported INDD document). No readiness percentage change. +- **2026-10-20** · The Links panel lists a document's links at once and takes their statuses from a check of the local and network files on a background worker, showing the last ones found meanwhile. It keeps the size and time of a graphic's file with the document, so an unchanged link needs no read even on the first check after opening (a file with a new time but the same size is compared once and then remembered, so a copied or restored folder stays OK). External changes are polled every two seconds, or as long as the last check took on a slow share; a document edit shows at once, and a selection change (Go To) starts no check. No readiness percentage change. - **2026-10-21** · Ruler guides are selected like objects (#1282): a click with the Selection tools selects a guide (also where it crosses an object), Shift-click adds or removes one, a new guide from the rulers is selected, a marquee that touches no object selects the guides it crosses, and Edit › Select All Guides (⌥⌘G, `guide.selectAll`) selects every unlocked guide on the spread. Selected guides draw thicker in their layer's color, drag together (all of them shown moving), nudge with the arrow keys and go with Delete, each as one undo step (`guide.select`, `guide.deselect`, `guide.moveBy`, `guide.delete {}`). With one guide selected the Control bar's X (vertical guide) or Y (horizontal guide) field and Properties › Transform show where it is, as the rulers measure, and typing a value moves it there. No readiness percentage change. +- **2026-10-21** · Properties for points selected with Direct Selection, as InDesign's: the title is "Anchor Point(s)", and the panel shows Transform, Appearance, Convert Points (Plain, Corner, Smooth, Symmetrical) and the Delete Point(s) quick action (`path.deletePoints`, one undo step). Found in Zero2Graphic's *How to Page Layout design in Adobe InDesign 2022 CC*. No readiness percentage change. +- **2026-10-20** · Direct Selection selects anchor points: a marquee selects the points inside it on every path it reaches, a click selects one point and Shift+click adds or removes one, selected points show solid, and dragging one (Shift: at 45° steps) or pressing the arrow keys moves them all in one step (`selection.set {anchors}`, `path.moveAnchors {points}`). No readiness percentage change. +- **2026-10-19** · A PDF export can repeat its bytes: it recorded the second it was made in, so exporting one document twice gave different files though the pages matched. `SOURCE_DATE_EPOCH` stands in for the clock when the export is given no date, as the reproducible-builds specification defines it; a date passed in still wins, and a malformed value is ignored rather than refusing the export. The timestamp was the only thing that differed, so the files are now identical byte for byte. No readiness percentage change. - **2026-10-17** · PDF/X-4 export warns about fonts drawing visible text without an embedded font program, including placed PDF forms; `validate-pdf` reports the font and page (#909). Invisible OCR text is exempt. Detection only: fonts are not embedded or outlined automatically. @@ -448,11 +545,65 @@ Newest first. - **2026-10-16** · Lock Guides and Lock Column Guides are commands in View ▸ Grids & Guides (`view.lockGuides`, ⌥⌘;, and `view.lockColumnGuides`), so the control channel and MCP reach them. Lock Column Guides is an undo step, is saved with the document, on in new ones, and read from and written to IDML's `ColumnGuideLocked`, which export always wrote as locked (#1096). No readiness percentage change. - **2026-10-16** · IDML: a page keeps column guides that were dragged off centre (InDesign's Custom columns). They were divided evenly on import, so the gutter sprang back to the middle; the imported positions now place the columns, with the canvas guides, snapping and text placement following them, and they are written back on export. Layout › Margins and Columns re-divides them evenly when the count or gutter changes, as InDesign's does. No readiness percentage change. - **2026-10-16** · IDML: custom column positions are checked before they are used (#1096). A set must give two edges per column, ascending from the left margin to the right one; any other (a wrong count, unsorted or non-numeric values, a list longer than 216 columns allow, or positions left behind by a margin or page-size change) is the even split, in the canvas, on import and on export, instead of columns drawn outside the margins. No readiness percentage change. +- **2026-10-21** · Layer Options has InDesign's Lock Guides: the layer's ruler guides can't be moved or deleted while its objects stay editable (`layer.set {lockGuides}`), and IDML reads and writes the layer's `LockGuides` (it was always written as false). The options are arranged as InDesign's: Show Layer and Show Guides, Lock Layer and Lock Guides, Print Layer. Found in the Learn Skills Daily course, chapter 32. No readiness percentage change. +- **2026-10-20** · Smart guides: an edge being drawn or resized snaps to the page's centre line, as in InDesign, so a frame drawn from the top margin to the middle of the page stops there instead of at the nearest baseline grid line. No readiness percentage change. +- **2026-10-21** · An empty graphic frame's X joins its corners, so a frame slanted with Direct Selection keeps its X corner to corner, as InDesign draws it; it used to stay across the old rectangle. Found in Zero2Graphic's *How to Page Layout design in Adobe InDesign 2022 CC*. No readiness percentage change. +- **2026-10-21** · Paragraph Border and Paragraph Shading link their four sides as InDesign's: the stroke weights, offsets and corners have the "Make all settings the same" link, on when the four are the same, so a side typed in sets all four; with the link off a side is set alone (a border with only a thick left side). Found in the Learn Skills Daily course, chapter 40. No readiness percentage change. +- **2026-10-21** · Paragraph rules have InDesign's Type (solid, thick/thin stripes, dashed, dotted, straight hash, wavy, or a stroke style of the document), Gap Color and Gap Tint, and Keep In Frame (rule above); the Paragraph Rules page is laid out as InDesign's (Weight and Type, Color and Tint, Gap Color and Gap Tint, Width and Offset, Left and Right Indent). IDML reads and writes them (`RuleAboveType`, `RuleBelowGapColor`, `KeepRuleAboveInFrame`…). Found in the Learn Skills Daily course, chapter 20. No readiness percentage change. +- **2026-10-21** · New Character Style with text selected starts from what the text has of its own over its paragraph style, as InDesign's ("[None] + Bold + color"), and Apply Style to Selection gives the text the new style, with no override left. A new style's dialog is titled New Paragraph Style / New Character Style. `type.selectionAttrs` reports the text's own character attributes (`ownChars`). Found in the Learn Skills Daily course, chapter 22. No readiness percentage change. +- **2026-10-21** · New Paragraph Style with text selected starts from it, as InDesign's (Based On [No Paragraph Style], every setting of the text that differs) and Apply Style to Selection gives the paragraph the new style; General has Next Style and Reset To Base; Basic Character Formats is in two columns (Size | Leading, Kerning | Tracking, Case | Position). `style.paragraph.edit` honours `nextStyle` (it was ignored) and takes `resetToBase`. Found in the Learn Skills Daily course, chapter 20. No readiness percentage change. +- **2026-10-21** · Find/Change has InDesign's Change and Change/Find: Change changes the text Find Next found and keeps it selected, Change/Find also finds the next match, and the search keeps its domain (a selection or story) across them. The Search list reads Document, Story and Selection. `find.change` takes `found`. Found in the Learn Skills Daily course, chapter 22. No readiness percentage change. +- **2026-10-21** · Find/Change has InDesign's Find Format: Specify Attributes opens Find Format Settings (the same Style Options and character sections as Change Format Settings), and only text with the format is found. With nothing in Find what, each stretch of text with the format is found, so Change All can restyle every word in a character style. `find.find`, `find.next` and `find.change` take `findFormat {charStyle?, paraStyle?, chars?}`. Found in the Learn Skills Daily course, chapter 22. No readiness percentage change. +- **2026-10-21** · Find/Change has InDesign's Change Format. Specify Attributes opens Change Format Settings: Style Options (the character and paragraph style to apply, [Any Style] for none), then Basic and Advanced Character Formats, Character Color, OpenType Features, Underline and Strikethrough Options. The box shows the format ("Character Style: eggs"), and Change All gives it to the changed text. With a Change Format and nothing in Change to, the found text stays and is only formatted, as InDesign's (an ⓘ beside Change to says so). `find.change` takes `charStyle` and `paraStyle`. Found in the Learn Skills Daily course, chapter 22. No readiness percentage change. +- **2026-10-21** · Preferences › Interface follows InDesign's: Appearance has a Color Theme swatch per interface theme (a click shows it at once, Cancel goes back) and Panels sets the Tools panel to a single or double column; UI Size moves to a UI Scaling section of its own. Interface held only UI Size, and the theme could be changed only from the Window menu. Found in the Learn Skills Daily course, chapter 26. No readiness percentage change. +- **2026-10-21** · Preferences › File Handling shows Number of Recent Items to Display as a whole number ("20"; it read "20.0"). Found in the Learn Skills Daily course, chapter 26. No readiness percentage change. +- **2026-10-21** · Insert Pages… opens InDesign's dialog: Pages, Insert (After Page, Before Page, At Start of Document, At End of Document) with the page by name, and Parent ([None] or a parent), set to the page in view and its parent. It was a form asking for a page index and a parent id, and pages could not go before the first page; `layout.pages.insert` takes `before` (0: at the start). Found in the Learn Skills Daily course, chapter 25. No readiness percentage change. +- **2026-10-21** · Spelling (Check Spelling and Dynamic Spelling) no longer flags everyday words the bundled hyphenation word list lacks: "we", "us", "if", titles such as "Mr", and words such as email, online, website, database, desktop and download, with their plurals and other forms. Contractions typed with a typographer's apostrophe (don’t, we’re), which Use Typographer's Quotes produces by default, count like their straight-apostrophe forms. Dynamic Spelling used to underline most words of an ordinary sentence. Found in the Learn Skills Daily course, chapter 26. No readiness percentage change. +- **2026-10-21** · While a parent is shown, the status bar's page box and Properties › Page name it ("A-Parent") instead of page 1, as InDesign's; their lists have the parents after the pages, and choosing one shows that parent (a page leaves the parents). Found in the Learn Skills Daily course, chapter 25. No readiness percentage change. +- **2026-10-21** · Effects dialog: the Angle field of the shadows, Bevel and Emboss, Satin and Gradient Feather has InDesign's dial beside it, its radius pointing where the light comes from; a click or drag on it sets the angle. Found in the Learn Skills Daily course, chapter 14. No readiness percentage change. +- **2026-10-21** · A double-click on a Fill or Stroke chip of Properties › Appearance opens the Color Picker with its colour, as in InDesign (a click still opens the swatches); for selected text, its own chips open it for the text. Found in the Learn Skills Daily course, chapter 23. No readiness percentage change. +- **2026-10-20** · Properties › Appearance: with several text frames selected, the Fill and Stroke popups offer Apply To Frame or Text, as with one frame, so their text can be coloured at once, as in InDesign. No readiness percentage change. +- **2026-10-20** · Properties › Appearance: the arrow beside Opacity opens a slider under the field, as in InDesign, instead of the Effects panel; a drag shows the opacity live and is one undo step (the Opacity link still opens Effects). No readiness percentage change. +- **2026-10-20** · Properties › Frame Fitting has InDesign's Auto-Fit checkbox and Options button (Frame Fitting Options); the app's checkboxes are now named and ticked-or-not for screen readers. No readiness percentage change. +- **2026-10-20** · Properties › Text Wrap shows the four wrap offsets under the wrap buttons, with the link that makes them the same, as InDesign's Properties panel does (greyed with no wrap). No readiness percentage change. +- **2026-10-21** · Properties › Bullets and Numbering › Options opens the Bullets and Numbering dialog for the selected paragraphs, as InDesign's, instead of the Paragraph panel. Found in the Learn Skills Daily course, chapter 21. No readiness percentage change. +- **2026-10-20** · Properties › Appearance: the corner shape list shows each shape's glyph beside its name, drawn as InDesign draws them (Fancy has its own glyph now), and the stroke type list shows each type's line; both dropdowns are named for screen readers. No readiness percentage change. +- **2026-10-21** · Properties › Align: the Align To button shows what the objects align to, one glyph each for the selection, the key object, the margins, the page and the spread, as InDesign's. Found in the Learn Skills Daily course, chapter 12. No readiness percentage change. +- **2026-10-20** · Object › Corner Options opens a Corner Options dialog laid out as InDesign's: each corner's size and shape, the link button that makes all four the same, and Preview. The Corner link in Properties › Appearance opens it too (it opened a Rectangle size dialog). No readiness percentage change. +- **2026-10-20** · The Object menu is in InDesign's order and groups; Paths has Join, Open Path and Close Path (Convert Shape lists only shapes, as InDesign's does) and a Convert Point submenu (Plain, Corner, Smooth, Symmetrical) is added. No readiness percentage change. +- **2026-10-20** · Layout › Create Guides puts its guides on both pages of the spread in view, as InDesign does; "This page" in Apply to narrows them to one page. No readiness percentage change. +- **2026-10-21** · Object › Fitting › Clear Frame Fitting Options (`object.clearFittingOptions`): the frames' auto-fit, crop amounts and reference point go back to their defaults, and the picture stays where it is. The Fitting submenu is grouped as InDesign's. Found in the Learn Skills Daily course, chapter 11. No readiness percentage change. +- **2026-10-21** · Swatches panel rows show InDesign's columns, drawn in code: a crossed pencil on the swatches that can't be edited ([None], [Registration], [Black]), the colour type (process or spot) and the colour mode (CMYK, RGB, Gray, or [None]'s and [Registration]'s own glyphs), in place of a lock and "CMYK" text. Tint reads 100 with nothing selected. No readiness percentage change. +- **2026-10-21** · With a gradient fill or stroke, the Color panel shows the stop selected in the Gradient panel (the stop before a selected midpoint) with its values, and its C/M/Y/K or R/G/B sliders and spectrum colour that stop, keeping the others, as in InDesign. It showed "[None] — choose a colour on the ramp", and a spectrum click replaced the whole gradient with a flat colour. Found in the Learn Skills Daily course, chapter 24. No readiness percentage change. +- **2026-10-20** · A new document's Swatches panel lists InDesign's defaults: [None], [Registration], [Paper], [Black] and six process colours (C=100, M=100, Y=100, C=15 M=100 Y=100, C=75 M=5 Y=100, C=100 M=90 Y=10); the extra M=100 Y=100, C=100 Y=100 and C=100 M=100 swatches are gone. No readiness percentage change. +- **2026-10-21** · The readout beside the cursor while drawing or measuring ("W: 3.13 cm") is InDesign's light grey box with white text, measured from the tutorials' frames; High Contrast keeps it black. It was a dark translucent box. No readiness percentage change. +- **2026-10-20** · Drawing a frame or shape shows its width and height in the document's ruler units, to two decimals and on two lines ("W: 6.08 cm", "H: 6.08 cm"), as InDesign does; it was always whole points. No readiness percentage change. +- **2026-10-20** · Type tool: a drag that starts in an empty frame draws a new text frame over it, as in InDesign; a click still turns the frame into a text frame. No readiness percentage change. +- **2026-10-20** · Measures in centimetres show four decimals, as InDesign's fields do (a 1p gutter reads 0.4233 cm, not 0.423 cm). No readiness percentage change. +- **2026-10-21** · Text Frame Options is laid out as InDesign's, with Preview: General, Column Rules, Baseline Options, Auto-Size; framed Columns (Number and Width, Gutter and Maximum, Balance Columns), Inset Spacing (Top/Bottom, the link, Left/Right) and Vertical Justification (Align, Paragraph Spacing Limit) with spinner fields; Fixed Number shows each column's width as the fields change. Preview shows the change on the page until OK (one undo step) or Cancel. Justify honours the Paragraph Spacing Limit (`paragraphSpacingLimit` on `object.textFrameOptions`): the space goes between paragraphs up to the limit, the rest between lines. Found in the Learn Skills Daily course, chapter 18. No readiness percentage change. +- **2026-10-21** · Swatches panel: a swatch is renamed in place, as in InDesign: click it, then click its name again (a slow double-click), type, and Enter (Escape keeps the name). Everything that uses it follows; a double-click still opens Swatch Options, and [None], [Registration], [Paper] and [Black] keep their names. Found in the Learn Skills Daily course, chapter 23. No readiness percentage change. +- **2026-10-20** · The loaded place cursor shows a thumbnail of the graphic, as InDesign's does; dragging with it draws the frame at the graphic's proportions from where the drag started, with its scale beside the pointer, and places exactly that frame. No readiness percentage change. +- **2026-10-21** · Drop Shadow, Inner Shadow and Outer Glow have a blend mode, as InDesign's (Effects dialog › Blending › Mode; `mode` on `object.dropShadow`, `object.innerShadow`, `object.outerGlow`; IDML `BlendMode`). New shadows start Multiply and new outer glows Screen in white ([Paper]); effects saved before keep Normal, so documents look as they did. Found in the Learn Skills Daily course, chapter 14. No readiness percentage change. +- **2026-10-14** · The Pages panel labels spreads as InDesign does ("2–3", "2, 1" across a section start, "8, A"), marks each section's first page with a triangle, and scrolls to the page in view. No readiness percentage change. +- **2026-10-18** · Double-clicking a section triangle in the Pages panel opens that page’s numbering options, including from parent-page editing. No readiness percentage change. +- **2026-10-18** · TOC separators preserve right-indent tabs through the dialog and IDML, including localized `$ID/^y` values. A separator picker exposes Tab Character, Right Indent Tab, Em Space and En Space. Existing paragraph tab leaders now work with the tutorial's TOC workflow. No readiness percentage change. +- **2026-10-21** · The Package dialog's Include PDF (Print) has a PDF Preset (the Export PDF presets, the last one used first), as InDesign's Select PDF Preset; `file.package` takes `pdf: {…file.exportPdf options}`, refusing bad options before writing anything. The packaged PDF always had the default settings. Found in the Learn Skills Daily course, chapter 27. No readiness percentage change. +- **2026-10-21** · File › Package… opens InDesign's Package dialog: Summary counts the fonts, links and images and inks the package carries, with a warning where some are missing or modified, and Fonts, Links and Images and Colors and Inks list them (Show Problems Only). Create Printing Instructions asks for the contact details and instructions that go into the package's Instructions.txt, and Include IDML / Include PDF (Print) choose the copies it carries. Package… went straight to the folder picker with fixed options. Found in the Learn Skills Daily course, chapter 27. No readiness percentage change. +- **2026-10-21** · Object styles nest a paragraph style, as InDesign's: Object Style Options › Paragraph Styles chooses the style a text frame's text takes when the object style is applied, and Apply Next Style gives the first paragraph that style and each paragraph after it the Next Style of the one before (`style.object.create` / `edit`: `paragraphStyle`, `applyNextStyle`; IDML `ApplyNextParagraphStyle`). Object Style Options › Text Frame General Options sets columns, insets, vertical justification and Ignore Text Wrap (`textFrame`). Editing either moves the frames that still follow the style; text in another paragraph style is an override that Clear Overrides puts back. Found in the Learn Skills Daily course, chapter 39. No readiness percentage change. +- **2026-10-21** · Window › Styles › Object Styles: InDesign's Object Styles panel (the selected object's style, `+` when overridden; a click applies a style, a double-click opens its options; the default graphic and text frame styles marked; Clear Overrides; Create New Style, ⌥/Alt-click for the dialog) and its New Object Style / Object Style Options dialog (Style Name; Basic Attributes Fill, Stroke, Stroke & Corner Options, each included by its checkbox; Effects for Object with the effects' pages; Style Settings; Apply Style to Selection). UI command `objectStyle.dialog`. Found in the Learn Skills Daily course, chapter 15. No readiness percentage change. +- **2026-10-21** · Object styles carry Corner Options (`corners`), taken from the selection by `style.object.create` and written to IDML (`EnableStrokeAndCornerOptions`, `TopLeftCornerOption`…). `style.object.edit` also changes a style's fill, stroke and corners and renames it (`rename`); the items using the style that haven't overridden an attribute follow each change, as in InDesign. Found in the Learn Skills Daily course, chapter 15. No readiness percentage change. - **2026-10-21** · Properties › Character and Paragraph: ••• (More Options) expands the section in place, as InDesign's: Character adds vertical and horizontal scale, baseline shift, skew, language and OpenType, and All Caps, Small Caps, Superscript, Subscript, Underline and Strikethrough; Paragraph adds the left, right, first line and last line indents, space before and after, the drop cap's lines and characters, Align to Baseline Grid and Hyphenate. It used to open the Character or Paragraph panel; the language field moved under ••• as in InDesign. Found in the Learn Skills Daily course, chapter 16. No readiness percentage change. - **2026-10-21** · The text Control panel has InDesign's two modes: A (Character Formatting Controls: font and style, size and leading, All Caps/Superscript/Underline and Small Caps/Subscript/Strikethrough, kerning and tracking, vertical and horizontal scale, baseline shift and skew, character style and language) and ¶ (Paragraph Formatting Controls: the nine alignments, left/first line and right/last line indents, space before and after, the drop cap's lines and characters, paragraph style, Hyphenate and Align to Baseline Grid). It used to show a fixed mix of both. Found in the Learn Skills Daily course, chapter 16. No readiness percentage change. - **2026-10-20** · With the Type tool, the Control panel's font size, leading and tracking fields have a spinner and a list of common values, as in InDesign (auto leading in parentheses). No readiness percentage change. - **2026-10-21** · The ¶ (Paragraph Formatting Controls) mode of the text Control panel has InDesign's Bulleted List and Numbered List buttons (with the default hanging indent) and Shading and Border: a checkbox, a button opening Paragraph Borders and Shading on that tab, and the colour. Found in the Learn Skills Daily course, chapter 21. No readiness percentage change. - **2026-10-21** · The Bulleted and Numbered List buttons (Properties, and Type › Bulleted & Numbered Lists › Apply Bullets / Apply Numbers) work as InDesign's: a paragraph with no indents gets the default hanging indent (0.25 in, −0.25 in), so the text lines up after the bullet instead of at the next default tab stop, and pressing the button again removes the list and that indent (`list.bullets`, `list.numbers`). Found in the Learn Skills Daily course, chapter 21. No readiness percentage change. +- **2026-10-18** · Table of Contents offers More Options / Fewer Options, preserving page-number, separator, sorting and level settings while their controls are hidden. No readiness percentage change. +- **2026-10-18** · Table of Contents reserves the title field's width so Contents is readable next to its style picker; the grid previously squeezed it to a few characters. No readiness percentage change. +- **2026-10-17** · Inline and anchored objects paint under their frame's text, on screen and in PDF, as InDesign draws them: a picture whose frame reaches into the next line (a negative Y offset) no longer hides the top of that line. No readiness percentage change. +- **2026-10-17** · Running headers: *first/last on page* read a page in text order (story order, then column by column), not by height — a multi-column page's right header showed the lowest entry of column 1 instead of the page's last entry. No readiness percentage change. +- **2026-10-17** · Cross-references keep text typed over their generated text (IDML import and export), with the page number still live, as InDesign shows them until updated; a cross-reference whose destination is gone shows its saved text and page instead of "??"; and a cross-reference's text breaks at its spaces instead of inside words. No readiness percentage change. +- **2026-10-17** · Parent pages: while parents are edited, the document pages' hidden characters, spelling squiggles and other overlays no longer pile onto the right parent page. No readiness percentage change. +- **2026-10-16** · A Direct Selection click on an image whose frame is already selected selects the image, so Delete removes only the image and leaves the empty frame, as in InDesign. No readiness percentage change. - **2026-10-16** · 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. @@ -462,9 +613,14 @@ Newest first. - **2026-10-16** · Layout: autoflow, inserted pages and new parents follow dragged column guides (#1096). Autoflow sets one frame per dragged column and counts the pages it adds from them; Insert Pages and New Parent keep the custom positions with the column count and gutter; `document.inspect` reports each page's gutter, column rects and whether its columns are custom. No readiness percentage change. - **2026-10-16** · Lock Guides and Lock Column Guides are commands in View ▸ Grids & Guides (`view.lockGuides`, ⌥⌘;, and `view.lockColumnGuides`), so the control channel and MCP reach them. Lock Column Guides is saved with the document, on in new ones, and read from and written to IDML's `ColumnGuideLocked`, which export always wrote as locked (#1096). No readiness percentage change. +- **2026-10-15** · Swedish interface (`sv`, Preferences ▸ General ▸ Interface Language ▸ Svenska): menus, panels, + dialogs and messages, 2,857 of the 2,891 interface strings (99%) in the missing-translations report; the other 34 + show in English. AI-drafted with Claude Code from the English source; spot-checked by a native speaker, not every + string reviewed. No readiness percentage change. - **2026-10-16** · Threading: the loaded text cursor threads into a text frame inside a group (it hit the group and showed it could not thread); a plain click still selects the group (#1075). Gap 27 closed. No readiness percentage change. - **2026-10-16** · Greek text hyphenates. The patterns were never compiled in, so Greek set unhyphenated however narrow the column; `"Greek"`, `"Greek: Greece"`, `el` and `el-GR` all resolve now and ανθρωπος breaks αν-θρω-πος. They are the monotonic patterns (hyph-el-monoton, Dimitrios Filippou, under MIT), which is what polytonic text hyphenates by too. Five of InDesign's ~40 hyphenation languages. No readiness percentage change. - **2026-10-16** · A swatch applied to a placed greyscale or bitmap image colours it, as in InDesign: IDML's `` is read and written, greyscale pixels become a tint of the swatch on opaque white and a bitmap's white lets the frame show through, on screen and in PDF (spot swatches print on their plate). Colour images keep their colours. Applying the swatch from the Swatches panel comes next. No readiness percentage change. +- **2026-10-15** · Anchored objects wrap their own story as their anchor lines are set, as in InDesign: the layout no longer depends on where an earlier composition put them (a long story whose pictures moved between frames from pass to pass never settled). No readiness percentage change. - **2026-10-15** · Color Theme: the toolbar tool previews up to five colours from a placed raster and adds them as one undoable swatch group. Local deterministic extraction; transparent padding is ignored. No readiness percentage change. - **2026-10-15** · Applying text styles removes matching local formatting so capture sources inherit later edits; real overrides and named character styles remain. @@ -524,6 +680,8 @@ Newest first. - **2026-10-15** · Flex Layout (InDesign 2026): Object › Flex Layout (Add to, Convert to, Remove) and a Flex Layout panel laid out as InDesign's, also in Properties. A container lays out its objects by direction, wrap, justification, the alignment grid, Fixed/Auto width and height, padding and spacing, after every edit; Add detects aligned objects (direction, Auto size, Space Between at their spacing); resizing a container reflows its objects instead of scaling them; dragging an object in one reorders it. Montilla Design's tutorial replays step for step. No readiness percentage change. - **2026-10-15** · IDML: the CJK leading model InDesign writes on [No paragraph style] of every document (Aki Below) only applies when the document uses a Japanese composer, as in InDesign; a Western document's paragraphs after a size change no longer sit lower than in InDesign (Montilla Design's Flex Layout file: its captions came out overset). No readiness percentage change. - **2026-10-15** · IDML: linked images in a subfolder beside the package load when the package is opened on another machine (a link to `/images/logo.png` finds `images/logo.png` next to the .idml); they showed as missing. No readiness percentage change. +- **2026-10-14** · Numbering & Section Options opened on a page that doesn't start a section is New Section, as in InDesign: Start Section on, 1 offered, and the start numbers stay editable (typing one chooses it). No readiness percentage change. +- **2026-10-14** · The Direct Selection tool pressed on a corner or anchor of an object that isn't selected selects it and pulls just that point, as in InDesign (it moved the whole object). No readiness percentage change. - **2026-10-14** · Overset text is marked on every frame that ends an overset story, selected or not and inside groups too (the red mark at the out port, with frame edges shown); a selected group shows the in/out ports of the text frames inside it. InDesign shows it only on the selected frame, which hides overset labels in grouped objects until Preflight. No readiness percentage change. - **2026-10-14** · Load Swatches adds the colors of an `.ase` file that repeat a name or have none: a repeated name gets a number (`Red 2`), and a color without a name is named by its value (`C=0 M=0 Y=0 K=55`). Before, a repeated name kept one of its colors, and only the first unnamed color was added, with an empty name. No readiness percentage change. - **2026-10-14** · Objects snap to the bleed guide's four sides while moving, resizing or drawing; snapping and the canvas share one bleed rectangle (`Spread::bleed_rect`). No readiness percentage change. @@ -597,6 +755,7 @@ Newest first. - **2026-10-13** · A parent can be based on another parent (`layout.parents.options`). Pages draw the base parent's items, then the parent's, then their own, on screen and in PDF and image export; chains work, cycles are refused, overrides reach base items, `document.inspect` reports `basedOn`, and IDML round-trips it. No readiness percentage change. - **2026-10-13** · The Text Wrap panel is laid out as InDesign's: the wrap buttons with Invert, and the four offsets (Top, Left, Bottom, Right) showing the object's values, with the link button that sets them all the same. It used to show a single offset, always 0. No readiness percentage change. - **2026-10-13** · Layout ▸ Table of Contents opens a real dialog: title and title style, Include Paragraph Styles and Other Styles lists with Add and Remove, and per style its entry style, page number position (after, before, none), separator and level. Replace Existing regenerates the current table of contents in place; otherwise OK makes a new frame on the page in view. IDML export writes the definition as a TOC style that import reads back, so Update works after a round trip. No readiness percentage change. +- **2026-10-13** · The macOS app bundles its matching headless CLI in `Contents/MacOS`, signed before the app and checked during packaging. The separate CLI ZIP remains available; documented commands use the bundled executable directly. macOS scope of #387; no readiness percentage change. - **2026-10-12** · Placed Excel tables and Excel data-merge records keep numeric precision, including small values, and preserve numeric-looking cached formula strings as text. No readiness percentage change. - **2026-10-12** · The engine's atomic writer, used by saves and exports (documents, snippets, books, libraries, swatches, XML, interchange, MCP, desktop and CLI writes), delegates to craft-libs/craft-atomic. Failed writes retain the original; new files follow the umask and replaced files keep their permissions. Recovery checkpoints and package output keep their own no-follow writers. No readiness percentage change. - **2026-10-12** · The Effects dialog, as in InDesign: Object › Effects (Transparency…, Drop Shadow… and the rest, and their shortcuts) and the Effects panel's fx button open it on the chosen effect, turned on. Transparency and every effect in one window, in the document's units, with X/Y offsets, Preview on the page, Cancel putting things back, and OK as one undo step (`object.effects`). Shadows default to InDesign's 120° light angle. No readiness percentage change. @@ -696,14 +855,14 @@ Newest first. - **2026-10-10 (UI.4–UI.5):** Panel tabs can move into other groups, split the dock, float, resize and return to their saved locations through shared docking transactions. Layouts persist in custom workspaces; UI and control commands share the same validated action path. Shared pane geometry and widget-state theme application retain all five palettes and local fonts. Split panes send keyboard input only to the focused canvas and scope contextual toolbar IDs per pane. No readiness percentage change. - **2026-10-10** · Version 0.6.0; releases add a Linux riscv64 tar.gz (cross-compiled, CLI smoke-tested under QEMU). -- **2026-10-10** · Readiness per audience: full ~47% (method aligned with the standard, was +- **2026-10-10** · Readiness per audience: full ~47% (method corrected, was 42%), mainstream practitioner ~42%, essentials user ~54%, each with hours to ~95%. -- **2026-10-10** · Stage re-normalized to **pre-alpha** under craftrules' core-workflow gate: text +- **2026-10-10** · Stage re-normalized to **pre-alpha** under the core-workflow gate: text can't be threaded by hand (no out-port click, no thread command). - **2026-10-10** · Full re-measure against InDesign 2026 21.6 (menu dump, bundle formats and localizations, 124 issues): breadth ~80%, ready ~42% (down from the ~83% "including depth" of - 2026-10-04, on user evidence and the INDD gap); progress docs restructured to the craftrules - standard (`docs/parity.md` → `docs/parity-checklist.md`; new target-app-parity, gaps, roadmap, + 2026-10-04, on user evidence and the INDD gap); progress docs restructured + (`docs/parity.md` → `docs/parity-checklist.md`; new target-app-parity, gaps, roadmap, architecture, typography, file-format, UI, hardware and localization docs). Landed today: split columns (#295), PDF export options dialog (#196), column rules (#274), Paragraph Rules dialog (#263), Character Style Options (#144), PDF/X-4 RGB handling (#223), Spanish @@ -730,12 +889,13 @@ Newest first. | Date | Change | Summary | |---|---|---| +| 2026-11-15 | minor | Track Changes resolution maps body selections through removed text and preserves nested text positions | | 2026-10-12 | minor | Manual text threading landed; alpha distance 15–25 h → 5–7 h (Primary Text Frame page fixes, #165) | | 2026-10-11 | minor | Localized Japanese print, import and table controls; readiness estimates unchanged | -| 2026-10-10 | minor | Full number 42% → 47% (method aligned with the standard: plain weighted sum, no new evidence); readiness table with hours per audience | +| 2026-10-10 | minor | Full number 42% → 47% (plain weighted sum, no new evidence); readiness table with hours per audience | | 2026-10-10 | minor | Headline adds mainstream practitioner (~42%) and essentials user (~54%); method in docs/target-app-parity.md | | 2026-10-10 | minor | Stage alpha → pre-alpha under the new core-workflow gate: manual text threading is missing; alpha gate table added to docs/roadmap.md | -| 2026-10-10 | major | Restructured to the progress-docs standard; full re-measure; the "Working today" inventory moved to docs/target-app-parity.md, milestones to docs/roadmap.md, the CLI/MCP section left to docs/agents.md (which already covered it) | +| 2026-10-10 | major | Progress docs restructured; full re-measure; the "Working today" inventory moved to docs/target-app-parity.md, milestones to docs/roadmap.md, the CLI/MCP section left to docs/agents.md (which already covered it) | | 2026-10-04 | major | Parity estimate: breadth 99%, depth ~83%, ~170 h | | 2026-10-01 | major | First roadmap: status, milestones | @@ -747,3 +907,5 @@ The shared craft-installer UI preserves this revision's install options and prov - **2026-10-15** · Windows recovery folders validate the identity of the live locked file without reading it through a second handle. Missing or replaced locks disable writes and cleanup; regression tests cover retained exclusive locking and replacement-file protection. No readiness percentage change. - PDF reader infrastructure: pinned shared parsing/rasterization, transformed page-box geometry and explicit failures for known incomplete layered-PDF exports. Application ownership and parity targets are unchanged. + +- Format reuse: HTML data URIs and file serialization use craft-mime Base64 encoding; existing decoder policies and document budgets remain unchanged. diff --git a/apps/designcraft-cli/Cargo.toml b/apps/designcraft-cli/Cargo.toml index 7aaa454cb..d214b9d84 100644 --- a/apps/designcraft-cli/Cargo.toml +++ b/apps/designcraft-cli/Cargo.toml @@ -22,4 +22,7 @@ designcraft-compose = { workspace = true } designcraft-format = { workspace = true } designcraft-pdf = { workspace = true } designcraft-mcp = { workspace = true } +craft-file-formats = { workspace = true } +craft-image-codecs = { workspace = true } +image = { workspace = true } serde_json = { workspace = true } diff --git a/apps/designcraft-cli/examples/pdf_export.rs b/apps/designcraft-cli/examples/pdf_export.rs index c427741a2..328a97154 100644 --- a/apps/designcraft-cli/examples/pdf_export.rs +++ b/apps/designcraft-cli/examples/pdf_export.rs @@ -30,8 +30,20 @@ fn main() -> Result<(), String> { } let doc = stress::synthetic(&spec)?; let bytes = designcraft_format::save(&doc).map_err(|e| e.to_string())?; - let dir = std::env::temp_dir().join(format!("designcraft-pdf-bench-{}", std::process::id())); - std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?; + // A new private folder (never one that was there already, which someone else could have + // made with a link in it): the files written here are the benchmark's alone. + let nanos = std::time::SystemTime::UNIX_EPOCH.elapsed().map_or(0, |d| d.as_nanos()); + let dir = std::env::temp_dir().join(format!("designcraft-pdf-bench-{}-{nanos}", std::process::id())); + #[cfg(unix)] + let mut builder = std::fs::DirBuilder::new(); + #[cfg(not(unix))] + let builder = std::fs::DirBuilder::new(); + #[cfg(unix)] + { + use std::os::unix::fs::DirBuilderExt; + builder.mode(0o700); + } + builder.create(&dir).map_err(|e| format!("{}: {e}", dir.display()))?; let file = dir.join("stress.designcraft"); let keep = out.is_some(); let pdf = out.map_or_else(|| dir.join("stress.pdf"), std::path::PathBuf::from); diff --git a/apps/designcraft-cli/src/main.rs b/apps/designcraft-cli/src/main.rs index 9ce15674c..848929d53 100644 --- a/apps/designcraft-cli/src/main.rs +++ b/apps/designcraft-cli/src/main.rs @@ -16,6 +16,8 @@ //! designcraft-cli bench FILE [--runs N] # the same measurements on one document //! designcraft-cli validate-pdf FILE.pdf [--standard x4|x1a] # the built-in PDF/X-4 or PDF/X-1a checks (default: the //! # file's own GTS_PDFXVersion) +//! designcraft-cli thumbnail FILE.designcraft OUT.png [SIZE] # the file's first-page preview, fitted to SIZE +//! # (the freedesktop thumbnailer for Linux file managers) //! designcraft-cli links # Discord, website, app page and GitHub links //! designcraft-cli --version # print the version //! ``` @@ -40,7 +42,7 @@ use designcraft_engine::Session; use serde_json::{Value, json}; /// The usage block. Shared by `--help` (stdout, success) and an unknown command (stderr, failure). -const USAGE: &str = "usage: designcraft-cli run [--in FILE | --sample] [--cmd ID[=JSON]]... [--page N] [--scale S] [--pdf-options JSON] [--export OUT] [--all-pages DIR]\n (--page, --scale and --pdf-options apply to the exports that follow them)\n designcraft-cli commands [FILTER]\n designcraft-cli describe COMMAND\n designcraft-cli script [FILE|-] [--in FILE | --sample] [--connect PORT] [--save OUT] [--export OUT] [--keep-going]\n designcraft-cli app [--port PORT] COMMAND [JSON] | --method METHOD [JSON]\n designcraft-cli mcp [--connect PORT] [--sample] [--automation-read-root DIR]... [--automation-write-root DIR]...\n the roots confine every file the agent's commands read (open, placed images, data sources, libraries) and\n write (save, export, package) to those folders, links followed. Each may be given more than once; a kind\n left out grants none of its access.\n They run the in-process server, so they conflict with --connect (a running app is not confined by them).\n designcraft-cli perf [--pages N] [--runs N] [--strict]\n designcraft-cli bench FILE [--runs N]\n designcraft-cli validate-pdf FILE.pdf # built-in PDF/X-4 checks (including visible unembedded fonts)\n designcraft-cli links\n designcraft-cli --version"; +const USAGE: &str = "usage: designcraft-cli run [--in FILE | --sample] [--cmd ID[=JSON]]... [--page N] [--scale S] [--pdf-options JSON] [--export OUT] [--all-pages DIR]\n (--page, --scale and --pdf-options apply to the exports that follow them)\n designcraft-cli commands [FILTER]\n designcraft-cli describe COMMAND\n designcraft-cli script [FILE|-] [--in FILE | --sample] [--connect PORT] [--save OUT] [--export OUT] [--keep-going]\n designcraft-cli app [--port PORT] COMMAND [JSON] | --method METHOD [JSON]\n designcraft-cli mcp [--connect PORT] [--sample] [--automation-read-root DIR]... [--automation-write-root DIR]...\n the roots confine every file the agent's commands read (open, placed images, data sources, libraries) and\n write (save, export, package) to those folders, links followed. Each may be given more than once; a kind\n left out grants none of its access.\n They run the in-process server, so they conflict with --connect (a running app is not confined by them).\n designcraft-cli perf [--pages N] [--frames N] [--chars N] [--images N] [--runs N] [--strict]\n designcraft-cli bench FILE [--runs N]\n designcraft-cli validate-pdf FILE.pdf [--standard x4|x1a] # built-in PDF/X checks (including visible unembedded fonts; the standard defaults to the file's own)\n designcraft-cli thumbnail FILE.designcraft OUT.png [SIZE] # the saved first-page preview, at most SIZE px\n designcraft-cli links\n designcraft-cli --version"; /// `script --help`: the script syntax, otherwise only in `describe script.run` and docs/agents.md. const SCRIPT_HELP: &str = r#"usage: designcraft-cli script [FILE|-] [--in FILE | --sample] [--connect PORT] [--save OUT] [--export OUT] [--keep-going] @@ -96,8 +98,94 @@ fn stdout_failed(e: std::io::Error) -> ! { std::process::exit(1); } +/// Options whose value is a path, and so can be written `./-name` when it starts with `-`, the +/// shell's own way out. None of them has an `--opt=value` form (the automation roots, parsed in +/// [`automation_args`], do and say so themselves). +const PATH_OPTIONS: [&str; 4] = ["--in", "--export", "--all-pages", "--save"]; + +/// An option's value, refusing the next token when it is another option: `--export --scale` used +/// to write a file called `--scale`. +fn value(a: &str, next: Option<&String>) -> Result { + match next { + None => Err(format!("{a} needs a value")), + Some(v) if !can_be_value(v) => { + // The way out is worth offering only where the value could be such a name. + let out = if PATH_OPTIONS.contains(&a) { format!("; if you did mean that name, write `./{v}`") } else { String::new() }; + Err(format!("{a} needs a value and `{v}` is another option{out}")) + } + Some(v) => Ok(v.clone()), + } +} + +/// Whether a token can be an option's value. A negative number can; anything else that starts +/// with `-` is another option. `-inf` and `-nan` parse as numbers too, so a bad `--scale` still +/// reaches the check that reports it rather than being called an option. +fn can_be_value(v: &str) -> bool { + !(v.starts_with('-') && v.len() > 1 && v.parse::().is_err()) +} + +/// Whether `sub` is a subcommand [`USAGE`] lists. Read from the usage text rather than written +/// out again, so a subcommand added there cannot be missing here. +fn is_subcommand(sub: &str) -> bool { + !sub.starts_with('-') && USAGE.lines().any(|line| usage_subcommand(line) == Some(sub)) +} + +/// The subcommand a `USAGE` line introduces, if it introduces one. +fn usage_subcommand(line: &str) -> Option<&str> { + let trimmed = line.trim_start(); + trimmed + .strip_prefix("usage: designcraft-cli ") + .or_else(|| trimmed.strip_prefix("designcraft-cli ")) + .and_then(|rest| rest.split_whitespace().next()) +} + +/// The usage lines for one subcommand, for ` --help`. Each line of [`USAGE`] names its +/// subcommand, and the indented lines after it belong to it. +fn usage_for(sub: &str) -> String { + let mut out = Vec::new(); + let mut keep = false; + for line in USAGE.lines() { + if let Some(named) = usage_subcommand(line) { + keep = named == sub; + } + if keep { + out.push(line); + } + } + if out.is_empty() { USAGE.to_string() } else { out.join("\n") } +} + fn main() -> ExitCode { - let args: Vec = std::env::args().skip(1).collect(); + // `std::env::args` panics on an argument that is not UTF-8 ("called `Result::unwrap()` on an + // `Err` value"), which a Latin-1 file name on Linux or macOS is. Such a name cannot be passed + // through to the engine, whose paths are `str`, so it is a usage error here rather than a + // crash (photocraft#1108). + let mut args: Vec = Vec::new(); + for arg in std::env::args_os().skip(1) { + match arg.into_string() { + Ok(a) => args.push(a), + Err(bad) => { + eprintln!("designcraft-cli: `{}` is not valid UTF-8, so it cannot be used as an argument", bad.to_string_lossy()); + return ExitCode::FAILURE; + } + } + } + // ` --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. + // + // Only for a subcommand that exists. Without that, `designcraft-cli typo --help` printed the + // whole usage and *succeeded*, so a misspelled command was an error on its own and not an + // error with `--help` after it -- and a script checking the exit status would carry on + // (noted in review). An unknown one now falls through to the dispatch, which fails as it + // does for `typo` alone. + if let Some(sub) = args.first().map(String::as_str) + && !matches!(sub, "--help" | "-h" | "help" | "script") + && is_subcommand(sub) + && args[1..].iter().any(|a| a == "--help" || a == "-h") + { + outln!("{}", usage_for(sub)); + return ExitCode::SUCCESS; + } match args.first().map(String::as_str) { Some("--version" | "-V" | "version") => { outln!("designcraft-cli {}", env!("CARGO_PKG_VERSION")); @@ -124,6 +212,7 @@ fn main() -> ExitCode { Some("perf") => report(perf::perf(&args[1..])), Some("bench") => report(perf::bench(&args[1..])), Some("validate-pdf") => report(validate_pdf(args.get(1..).unwrap_or_default())), + Some("thumbnail") => report(thumbnail(&args[1..])), Some("links") => { use designcraft_engine::links::{APP_PAGE, DISCORD, GITHUB, ISSUES, WEBSITE}; outln!("Discord {DISCORD}\nWebsite {WEBSITE}\nApp page {APP_PAGE}\nGitHub {GITHUB}\nIssues {ISSUES}"); @@ -156,7 +245,6 @@ fn report(r: Result<(), String>) -> ExitCode { fn validate_pdf(args: &[String]) -> Result<(), String> { const USAGE: &str = "usage: designcraft-cli validate-pdf FILE.pdf [--standard x4|x1a]"; - const X1A: &[u8] = b"/GTS_PDFXVersion(PDF/X-1:"; let mut path = None; let mut standard = None; let mut it = args.iter(); @@ -172,7 +260,7 @@ fn validate_pdf(args: &[String]) -> Result<(), String> { let standard = match standard.map(designcraft_pdf::Standard::parse) { Some(Some(s)) => s, Some(None) => return Err(USAGE.into()), - None if bytes.windows(X1A.len()).any(|w| w == X1A) => designcraft_pdf::Standard::PdfX1a, + None if designcraft_pdf::pdfx_version(&bytes).is_some_and(|v| v.starts_with("PDF/X-1:")) => designcraft_pdf::Standard::PdfX1a, None => designcraft_pdf::Standard::PdfX4, }; let (name, issues) = match standard { @@ -188,6 +276,62 @@ fn validate_pdf(args: &[String]) -> Result<(), String> { if valid { Ok(()) } else { Err(format!("{path} failed {name} validation")) } } +/// `thumbnail FILE OUT [SIZE]`: the first-page preview saved in a `.designcraft` file, as a PNG +/// whose longer side is at most SIZE pixels (never enlarged). It is the freedesktop thumbnailer +/// (`packaging/linux/ai.storyteller.designcraft.thumbnailer`), so it only reads the preview: a file +/// without one fails, and the file manager keeps the file type's icon. +fn thumbnail(args: &[String]) -> Result<(), String> { + const USAGE: &str = "usage: designcraft-cli thumbnail FILE.designcraft OUT.png [SIZE]"; + let [input, out, rest @ ..] = args else { return Err(USAGE.into()) }; + let size = match rest { + [] => None, + [s] => Some(s.parse::().ok().filter(|s| *s > 0).ok_or_else(|| format!("bad SIZE `{s}`: expected a positive number of pixels"))?), + _ => return Err(USAGE.into()), + }; + if names_the_same_file(input.as_ref(), out.as_ref()) { + return Err(format!("{out} is the document {input}: the thumbnail would replace it")); + } + let file = std::fs::File::open(input).map_err(|e| format!("{input}: {e}"))?; + let preview = designcraft_format::read_preview(std::io::BufReader::new(file)) + .ok_or_else(|| format!("{input} has no preview (a DesignCraft file saved before they had one, or not a DesignCraft file)"))?; + let png = fit_png(preview, size).map_err(|e| format!("{input}: the preview can't be read: {e}"))?; + designcraft_engine::atomic::write_atomic(std::path::Path::new(out), &png).map_err(|e| format!("{out}: {e}")) +} + +/// Whether `out` is the file `input` names: the same path, a symlink to it or, on Unix, a hard +/// link (the same device and inode). An `out` that doesn't exist yet can't be the input. +fn names_the_same_file(input: &std::path::Path, out: &std::path::Path) -> bool { + let (Ok(a), Ok(b)) = (std::fs::canonicalize(input), std::fs::canonicalize(out)) else { return false }; + if a == b { + return true; + } + #[cfg(unix)] + { + use std::os::unix::fs::MetadataExt; + if let (Ok(a), Ok(b)) = (std::fs::metadata(&a), std::fs::metadata(&b)) { + return (a.dev(), a.ino()) == (b.dev(), b.ino()); + } + } + false +} + +/// `png` with its longer side brought down to `size`. A picture already that small is returned +/// as it is; it is decoded anyway, so a broken one is an error rather than an unreadable thumbnail. +fn fit_png(png: Vec, size: Option) -> Result, String> { + // The preview comes from the file: it may claim any size. + let info = craft_image_codecs::inspect_raster(&png).map_err(|e| e.to_string())?.ok_or("invalid PNG preview")?; + if info.width > 4096 || info.height > 4096 { + return Err("preview is larger than 4096 pixels".into()); + } + let decoded = craft_image_codecs::decode(&png).map_err(|e| e.to_string())?; + let Some(size) = size.filter(|s| decoded.width().max(decoded.height()) > *s) else { return Ok(png) }; + let rgba = image::RgbaImage::from_raw(decoded.width(), decoded.height(), decoded.to_rgba8()).ok_or("invalid PNG pixel data")?; + let resized = image::DynamicImage::ImageRgba8(rgba).resize(size, size, image::imageops::FilterType::Triangle).to_rgba8(); + let encoded = craft_image_codecs::Image::from_u8(resized.width(), resized.height(), craft_image_codecs::ChannelLayout::Rgba, resized.into_raw()) + .map_err(|e| e.to_string())?; + craft_image_codecs::encode(&encoded, craft_image_codecs::Format::Png, &Default::default()).map_err(|e| e.to_string()) +} + /// `mcp` (headless, in-process engine) or `mcp --connect PORT|HOST:PORT` (drive a running app /// started with `designcraft --control PORT`). JSON-RPC on stdin/stdout; logs on stderr. fn mcp(args: &[String]) -> Result<(), String> { @@ -202,7 +346,7 @@ fn mcp(args: &[String]) -> Result<(), String> { continue; } match a.as_str() { - "--connect" => connect = Some(it.next().ok_or("--connect needs a port or host:port")?), + "--connect" => connect = Some(value(&a, it.next().as_ref())?), "--sample" => sample = true, other => { return Err(format!( @@ -252,22 +396,29 @@ so drop --connect (or use --connect without the roots)" /// They apply to the exports that follow them, so one after the last export would do nothing. fn option_after_last_export(args: &[String]) -> Option<&str> { let mut unused = None; - let mut it = args.iter(); + let mut it = args.iter().peekable(); + // A value is skipped only where the next token can be one. Taking it whatever it is read + // `--scale --export out.png` as --scale applied to no export, so a missing value was + // reported as the order of the options -- and "put it before its --export" is advice for a + // list that already does that (photocraft#7071). while let Some(a) = it.next() { + let is_opt = matches!(a.as_str(), "--page" | "--scale" | "--pdf-options" | "--export" | "--all-pages" | "--in" | "--cmd"); match a.as_str() { - "--page" | "--scale" | "--pdf-options" => { - unused = unused.or(Some(a.as_str())); - it.next(); - } - "--export" | "--all-pages" => { - unused = None; - it.next(); - } - "--in" | "--cmd" => { - it.next(); - } + "--page" | "--scale" | "--pdf-options" => unused = unused.or(Some(a.as_str())), + "--export" | "--all-pages" => unused = None, _ => {} } + if is_opt { + match it.peek() { + Some(v) if can_be_value(v.as_str()) => { + it.next(); + } + // The option has no value. That is what is wrong with the line, so this check + // stands aside and lets `value()` say so: reporting the order instead advised + // moving an option that is already where it belongs (photocraft#7071). + _ => return None, + } + } } unused } @@ -307,7 +458,28 @@ impl Export { } } +/// Every option that takes a value has one, checked before anything runs. Found later, a missing +/// value is reported only after the exports before it have been written -- and `run --export +/// first.png --scale --export second.png` would then have overwritten an existing `first.png` on +/// an invocation that fails (noted in review). +fn values_present(args: &[String]) -> Result<(), String> { + let mut i = 0; + while let Some(a) = args.get(i) { + i += 1; + if !matches!(a.as_str(), "--in" | "--cmd" | "--export" | "--all-pages" | "--page" | "--scale" | "--pdf-options") { + continue; + } + value(a, args.get(i))?; + // Step over the value, so one that looks like an option is not checked as one. + i += 1; + } + Ok(()) +} + fn run(args: &[String]) -> Result<(), String> { + // Before the order check and before any export: a value error is about the line as written, + // and reporting it must not cost a file that was already there. + values_present(args)?; if let Some(opt) = option_after_last_export(args) { return Err(format!( "{opt} has no --export or --all-pages after it; options apply to the exports that follow them, so put it before its --export" @@ -328,7 +500,7 @@ fn run(args: &[String]) -> Result<(), String> { // Earlier --cmd results, for `$N.path` references. let mut results: Vec = Vec::new(); while let Some(a) = it.next() { - let mut val = || it.next().cloned().ok_or_else(|| format!("{a} needs a value")); + let mut val = || value(a, it.next()); match a.as_str() { "--in" => { let p = val()?; @@ -426,8 +598,8 @@ fn export(s: &mut Session, out: &str, page: usize, scale: f64) -> Result<(), Str let img = r .render_page(&st.doc, &s.cache, page, scale, true, &designcraft_render::RenderOptions { printing_only: true, ..Default::default() }) .ok_or("no such page")?; - let lower = out.to_lowercase(); - let bytes = if lower.ends_with(".jpg") || lower.ends_with(".jpeg") { img.to_jpeg(90) } else { img.to_png() }; + let jpeg = craft_file_formats::detect(out, &[]) == Some(craft_file_formats::Format::Jpeg); + let bytes = if jpeg { img.to_jpeg(90) } else { img.to_png() }; designcraft_engine::atomic::write_atomic(std::path::Path::new(out), &bytes).map_err(|e| format!("{out}: {e}"))?; eprintln!("wrote {out} ({}×{}, {:.1} ms, {} glyphs)", img.width, img.height, t.elapsed().as_secs_f64() * 1000.0, r.stats.glyphs); Ok(()) @@ -470,11 +642,11 @@ fn script(args: &[String]) -> Result<(), String> { let mut keep_going = false; let mut it = args.iter(); while let Some(a) = it.next() { - let mut val = || it.next().cloned().ok_or_else(|| format!("{a} needs a value")); + let mut val = || value(a, it.next()); match a.as_str() { "--in" => { let p = val()?; - let cmd = if p.to_lowercase().ends_with(".idml") { "file.openIdml" } else { "file.open" }; + let cmd = if craft_file_formats::detect(&p, &[]) == Some(craft_file_formats::Format::Idml) { "file.openIdml" } else { "file.open" }; setup.push((cmd.into(), json!({"path": p}))); } "--sample" => setup.push(("file.newSample".into(), json!({}))), @@ -520,11 +692,15 @@ fn script(args: &[String]) -> Result<(), String> { let report = if keep_going { // Run every step; failures become {"error": …} results. let mut results: Vec = Vec::new(); - for st in &steps { + let mut failed = None; + for (i, st) in steps.iter().enumerate() { let r = designcraft_engine::script::resolve(&st.params, &results).and_then(|p| exec(b, &st.command, p)); - results.push(r.unwrap_or_else(|e| json!({"error": e, "command": st.command}))); + results.push(r.unwrap_or_else(|e| { + failed.get_or_insert_with(|| (i, st.command.clone(), e.clone())); + json!({"error": e, "command": st.command}) + })); } - designcraft_engine::script::Report { results, failed: None } + designcraft_engine::script::Report { results, failed } } else { designcraft_engine::script::run(&steps, |id, p| exec(b, id, p)) }; @@ -534,7 +710,7 @@ fn script(args: &[String]) -> Result<(), String> { } for (kind, out) in &export { let p = json!({"path": out}); - match kind { + let r = match kind { // PNG / JPEG of the first page. Export::Image => b.call("app.export", p)?, Export::Pdf => exec(b, "file.exportPdf", p)?, @@ -543,6 +719,11 @@ fn script(args: &[String]) -> Result<(), String> { Export::Pptx => exec(b, "file.exportPptx", p)?, Export::Command(cmd) => exec(b, cmd, p)?, }; + // What the export itself reports (effects rasterised, transparency flattened…) goes + // to stderr, as `run --export` prints it: the report on stdout covers only the steps. + for w in r["warnings"].as_array().into_iter().flatten() { + eprintln!("warning: {}", w.as_str().unwrap_or_default()); + } } } outln!("{}", serde_json::to_string_pretty(&report.to_json()).unwrap_or_default()); diff --git a/apps/designcraft-cli/src/perf.rs b/apps/designcraft-cli/src/perf.rs index 3a3afe931..d67fffa4b 100644 --- a/apps/designcraft-cli/src/perf.rs +++ b/apps/designcraft-cli/src/perf.rs @@ -97,6 +97,9 @@ fn row(rows: &mut Vec, name: impl Into, ms: f64, budget: Option Result, String> { + if doc.spreads.is_empty() { + return Err("cannot benchmark a document with no spreads".into()); + } let mut rows = vec![]; let cores = std::thread::available_parallelism().map_or(1, std::num::NonZeroUsize::get); let chars: usize = doc.stories.values().map(|s| s.text.len()).sum(); diff --git a/apps/designcraft-cli/src/stress.rs b/apps/designcraft-cli/src/stress.rs index c9d5b3015..ce3e7ed7d 100644 --- a/apps/designcraft-cli/src/stress.rs +++ b/apps/designcraft-cli/src/stress.rs @@ -169,7 +169,7 @@ pub fn synthetic(spec: &Spec) -> Result { id, name: format!("art-{k}.png"), mime: "image/png".into(), - data: Arc::new(data), + data: designcraft_doc::AssetData::embedded(data), pixels: Some((aw, ah)), ..Default::default() }), diff --git a/apps/designcraft-cli/tests/it/args.rs b/apps/designcraft-cli/tests/it/args.rs new file mode 100644 index 000000000..a854f2aba --- /dev/null +++ b/apps/designcraft-cli/tests/it/args.rs @@ -0,0 +1,395 @@ +//! What the command line does with its arguments, pinned. +//! +//! Every assertion here was measured, not intended: these tests say what the parser does today, +//! including where that is odd (an unknown option taken as a filter, a `--opt=value` form that +//! only the automation roots have). They exist so that moving to a derived parser — the work +//! photocraft#7071 lists, which this parser needs too — changes the surface where that is the +//! point and nowhere else. +//! +//! They assert the exit code, which stream the output went to, and that an error names the +//! argument it is about. They do not assert wording, so a message can be improved without +//! editing a test, except in the few places where the wording *is* the behaviour and the test +//! says so. +//! +//! `tests/cli.rs` holds what the subcommands then do: exports, scripts, the MCP server. + +use std::process::{Command, Stdio}; + +/// `designcraft-cli` with stdin closed, so a subcommand that reads a script does not wait. +fn cli() -> Command { + let mut c = Command::new(env!("CARGO_BIN_EXE_designcraft-cli")); + c.stdin(Stdio::null()); + c +} + +/// What one invocation did. +struct Ran { + code: Option, + out: String, + err: String, +} + +fn run(args: &[&str]) -> Ran { + let out = cli().args(args).output().unwrap_or_else(|e| panic!("{args:?}: {e}")); + Ran { code: out.status.code(), out: String::from_utf8_lossy(&out.stdout).into_owned(), err: String::from_utf8_lossy(&out.stderr).into_owned() } +} + +impl Ran { + /// Succeeded, said nothing on stderr; gives back what it printed. + fn succeeded(self, what: &str) -> String { + assert_eq!(self.code, Some(0), "{what}: {:?}", self.err); + assert_eq!(self.err, "", "{what} wrote to stderr"); + self.out + } + + /// Failed with the usage exit code, said nothing on stdout; gives back the complaint. + fn failed(self, what: &str) -> String { + assert_eq!(self.code, Some(1), "{what}: expected a usage failure, got {:?} / {:?}", self.out, self.err); + assert_eq!(self.out, "", "{what} wrote to stdout"); + self.err + } +} + +/// A port with nothing listening on it, so `--connect` and `--port` fail the same way every time. +fn closed_port() -> String { + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let port = listener.local_addr().unwrap().port(); + drop(listener); + port.to_string() +} + +/// A directory of this test's own, removed when the test ends. +fn temp_dir(name: &str) -> std::path::PathBuf { + let dir = std::env::temp_dir().join(format!("dc-args-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir +} + +/// Every subcommand, in the order the usage block lists them. +const SUBCOMMANDS: [&str; 10] = ["run", "commands", "describe", "script", "app", "mcp", "perf", "bench", "validate-pdf", "links"]; + +#[test] +fn with_no_arguments_it_prints_the_usage_block_and_fails() { + let err = run(&[]).failed("no arguments"); + assert!(err.starts_with("usage: designcraft-cli run"), "{err:?}"); + // The usage block names every subcommand, which is how ` --help` finds its lines. + for sub in SUBCOMMANDS { + assert!(err.contains(&format!("designcraft-cli {sub}")), "usage names {sub}: {err:?}"); + } + // An empty argument is a command nobody has, not a request for help. + run(&[""]).failed("an empty argument"); +} + +#[test] +fn help_goes_to_stdout_and_succeeds_in_all_three_spellings() { + let long = run(&["--help"]).succeeded("--help"); + assert!(long.starts_with("usage: designcraft-cli run"), "{long:?}"); + // The community links are under the usage block, for someone who has nowhere else to ask. + assert!(long.contains("Community:") && long.contains("discord"), "{long:?}"); + for spelling in ["-h", "help"] { + assert_eq!(run(&[spelling]).succeeded(spelling), long, "{spelling} prints the same help"); + } +} + +#[test] +fn an_unknown_command_fails_with_the_same_text_on_stderr() { + let usage = run(&["--help"]).succeeded("--help"); + for unknown in ["bogus", "-x", "--nope", "Run"] { + let err = run(&[unknown]).failed(unknown); + assert_eq!(err, usage, "{unknown}: the same usage, on stderr"); + // Asking for help about a command nobody has is still that command: ` --help` + // answered with the whole usage block on stdout and succeeded, which skipped the + // unknown-command failure entirely (noted in review). + for spelling in ["--help", "-h"] { + let err = run(&[unknown, spelling]).failed(&format!("{unknown} {spelling}")); + assert_eq!(err, usage, "{unknown} {spelling}: the same usage, on stderr"); + } + } + // A real subcommand still answers about itself, and only about itself. + for sub in SUBCOMMANDS.iter().filter(|s| **s != "script") { + let text = run(&[sub, "--help"]).succeeded(sub); + assert!(text.contains(&format!("designcraft-cli {sub}")), "{sub} --help describes {sub}: {text:?}"); + assert_ne!(text, usage, "{sub} --help is about {sub}, not the whole usage block"); + } +} + +#[test] +fn the_version_is_the_crate_version() { + let expected = format!("designcraft-cli {}\n", env!("CARGO_PKG_VERSION")); + for spelling in ["--version", "-V", "version"] { + assert_eq!(run(&[spelling]).succeeded(spelling), expected, "{spelling}"); + } +} + +/// ` --help` asks about that subcommand. It answers from the usage block, on stdout, and +/// nothing else happens: no export is written, no port is dialled, no measurement is taken, and a +/// file named earlier in the same line is not opened or complained about (photocraft#423). +#[test] +fn every_subcommand_answers_help_without_running_anything() { + let dir = temp_dir("help"); + let png = dir.join("ran.png"); + let dead = closed_port(); + let cases: [(&str, Vec<&str>); 10] = [ + ("run", vec!["run", "--sample", "--export", png.to_str().unwrap()]), + ("commands", vec!["commands"]), + ("describe", vec!["describe", "file.open"]), + ("script", vec!["script", "no-such-script.dcs"]), + ("app", vec!["app", "--port", &dead, "document.list"]), + ("mcp", vec!["mcp", "--connect", &dead]), + ("perf", vec!["perf", "--pages", "1", "--runs", "1"]), + ("bench", vec!["bench", "no-such-document.designcraft"]), + ("validate-pdf", vec!["validate-pdf", "no-such-file.pdf"]), + ("links", vec!["links"]), + ]; + for (sub, args) in cases { + for flag in ["--help", "-h"] { + let mut args = args.clone(); + args.push(flag); + let what = format!("{sub} {flag}"); + let out = run(&args).succeeded(&what); + assert!(out.contains(&format!("designcraft-cli {sub}")), "{what} names it: {out:?}"); + assert!(!out.contains("unknown option"), "{what}: {out:?}"); + // None of the work the rest of the line asks for was done. + assert!(!png.exists(), "{what} exported a file"); + assert!(!out.contains("cannot connect") && !out.contains("render threads"), "{what}: {out:?}"); + // Either operating system's wording, so this catches a file the help path opened on + // Windows as well as on unix. + assert!(!out.contains("No such file") && !out.contains("cannot find the file"), "{what}: {out:?}"); + } + } + // `script`'s own help is longer than one usage line: it documents the script syntax, which is + // otherwise only in `describe script.run` and the docs. + let out = run(&["script", "--help"]).succeeded("script --help"); + assert!(out.contains("Script text, one step per line"), "{out:?}"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// The subcommands that have options refuse an option they do not know, and name it. +#[test] +fn an_unknown_option_is_refused_by_name() { + let cases: [Vec<&str>; 5] = [ + vec!["run", "--nope"], + vec!["script", "-", "--nope"], + vec!["mcp", "--nope"], + vec!["perf", "--nope"], + vec!["bench", "f.designcraft", "--nope"], + ]; + for args in cases { + let err = run(&args).failed(&format!("{args:?}")); + assert!(err.contains("--nope"), "{args:?}: {err:?}"); + assert!(err.contains("unknown"), "{args:?}: {err:?}"); + } +} + +/// The subcommands whose argument is a word, not an option, take an unknown option as that word: +/// `commands --nope` filters the command list by `--nope` and finds nothing. Each of these would +/// be an error under the rule photocraft#7071 settles on; today they are not, and a change of +/// mind shows up here. +#[test] +fn the_subcommands_that_take_a_word_read_an_unknown_option_as_that_word() { + // A filter that matches no command: an empty list, successfully. + assert_eq!(run(&["commands", "--nope"]).succeeded("commands --nope").trim(), "[]"); + // A command id nobody has. + let err = run(&["describe", "--nope"]).failed("describe --nope"); + assert!(err.contains("no command `--nope`"), "{err:?}"); + // A path nobody has. `--nope` has to fail the way an ordinary missing path fails, because + // that is what shows it reached the file system as a path instead of being read as an + // option. Asserting only that the complaint names `--nope` does not show that: a parser that + // rejected unknown options would name it too (noted in review). + // + // So the two are compared with the name taken out. That holds the shape of the failure + // without asserting the operating system's wording for a missing file -- Windows says "The + // system cannot find the file specified" -- which an earlier round of review rightly took + // out of this test. `failed` already checks the exit code and that stdout stayed empty. + let as_option = run(&["validate-pdf", "--nope"]).failed("validate-pdf --nope"); + let as_path = run(&["validate-pdf", "nope.pdf"]).failed("validate-pdf nope.pdf"); + assert!(as_option.contains("--nope"), "{as_option:?}"); + assert_eq!( + as_option.replace("--nope", ""), + as_path.replace("nope.pdf", ""), + "`--nope` must fail as a missing path does, not as an option" + ); + // A method name for the running app, so the error is about reaching the app. + let dead = closed_port(); + let err = run(&["app", "--port", &dead, "--nope"]).failed("app --nope"); + assert!(err.contains("cannot connect"), "{err:?}"); + // And `links`, which takes nothing, ignores what it is given. + let out = run(&["links", "--nope"]).succeeded("links --nope"); + assert_eq!(out, run(&["links"]).succeeded("links")); +} + +/// There is no `--opt=value` form. The two automation roots are the exception: they have one, +/// because a folder whose name starts with `-` has no other way in there. +#[test] +fn only_the_automation_roots_have_an_opt_equals_value_form() { + let cases: [(&str, Vec<&str>); 3] = [ + ("--scale=2", vec!["run", "--scale=2", "--sample"]), + ("--pages=2", vec!["perf", "--pages=2"]), + ("--save=out.designcraft", vec!["script", "-", "--save=out.designcraft"]), + ]; + for (token, args) in cases { + let err = run(&args).failed(&format!("{args:?}")); + assert!(err.contains("unknown"), "{args:?}: {err:?}"); + // The whole token is named, `=value` and all, so it is clear what was not understood. + assert!(err.contains(token), "{args:?}: {err:?}"); + } + // The roots read the value after `=`: an empty one is refused as a folder, which is the + // parser having taken it rather than ignoring the form. + let err = run(&["mcp", "--automation-read-root="]).failed("empty root"); + assert!(err.contains("--automation-read-root") && err.contains("folder"), "{err:?}"); + // A root given more than once adds another folder, in either spelling, rather than the last + // one winning or the repeat being refused: the roots are repeatable (`...` in the usage), and + // `mcp_automation_roots_take_several_folders` covers what the extra folder grants. This PR + // first pinned the older behaviour, where a second root was an error; upstream has made them + // repeatable since, so what is pinned here is today's. + // + // Checked by what fails rather than by letting the server start: the stray token after the + // roots is the error, which shows both roots were taken. + for second in [vec!["--automation-read-root=b"], vec!["--automation-read-root", "b"]] { + let mut args = vec!["mcp", "--automation-read-root=a"]; + args.extend(second.iter().copied()); + args.push("stray"); + let err = run(&args).failed(&format!("{second:?}")); + assert!(err.contains("stray"), "the stray token is what fails: {err:?}"); + assert!(!err.contains("twice"), "a repeated root is not refused any more: {err:?}"); + } +} + +/// An option that needs a value and has none says which option, and nothing runs. +#[test] +fn a_missing_value_names_its_option() { + let dir = temp_dir("missing"); + let png = dir.join("out.png"); + let cases: [(&str, Vec<&str>); 9] = [ + ("--export", vec!["run", "--sample", "--export"]), + ("--in", vec!["run", "--in"]), + ("--all-pages", vec!["run", "--sample", "--all-pages"]), + // Before an export, too: the order of the options is nothing to judge until this one has + // a value, so it is not reported as an export it is not in front of. + ("--scale", vec!["run", "--sample", "--scale", "--export", png.to_str().unwrap()]), + ("--page", vec!["run", "--sample", "--page"]), + ("--save", vec!["script", "-", "--save"]), + ("--connect", vec!["script", "-", "--connect"]), + ("--port", vec!["app", "--port"]), + ("--pages", vec!["perf", "--pages"]), + ]; + for (option, args) in cases { + let err = run(&args).failed(&format!("{args:?}")); + assert!(err.contains(option), "{args:?} names {option}: {err:?}"); + assert!(err.contains("needs"), "{args:?}: {err:?}"); + } + assert!(!png.exists(), "nothing is exported"); + + // A missing value after an export is found before that export runs: the line writes nothing, + // as a malformed line always did. + let first = dir.join("first.png"); + let line = ["run", "--sample", "--export", first.to_str().unwrap(), "--scale", "--export", png.to_str().unwrap()]; + let err = run(&line).failed("a missing value after an export"); + assert!(err.contains("--scale needs a value"), "{err:?}"); + assert!(!first.exists(), "the export before it was not written"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// `--help` wins wherever it appears after the subcommand, even where an option would take it as +/// its value: `run --in -h` prints `run`'s usage and opens nothing. +#[test] +fn help_wins_even_where_an_option_would_take_it_as_a_value() { + for flag in ["-h", "--help"] { + let out = run(&["run", "--in", flag]).succeeded(&format!("run --in {flag}")); + assert!(out.contains("designcraft-cli run"), "{out:?}"); + } + // And each subcommand's usage lists every option it takes. + let perf = run(&["perf", "--help"]).succeeded("perf --help"); + for option in ["--pages", "--frames", "--chars", "--images", "--runs", "--strict"] { + assert!(perf.contains(option), "perf --help lists {option}: {perf:?}"); + } + let validate = run(&["validate-pdf", "--help"]).succeeded("validate-pdf --help"); + assert!(validate.contains("--standard"), "{validate:?}"); +} + +/// An option that takes no value does not swallow the token after it: that token is read as the +/// next argument, and refused if it is not one. +#[test] +fn a_flag_that_takes_no_value_leaves_the_next_token_alone() { + let err = run(&["run", "--sample", "extra", "--export", "out.png"]).failed("run --sample extra"); + assert!(err.contains("extra"), "{err:?}"); + let err = run(&["perf", "--strict", "3"]).failed("perf --strict 3"); + assert!(err.contains('3'), "{err:?}"); +} + +/// A value flag given twice keeps the last value. (The automation roots are the exception, above.) +#[test] +fn a_repeated_value_flag_keeps_the_last_value() { + let dir = temp_dir("repeat"); + let at = |args: &[&str], name: &str| -> Vec { + let path = dir.join(name); + let mut full: Vec<&str> = vec!["run", "--sample"]; + full.extend_from_slice(args); + let out = path.to_str().unwrap(); + full.extend(["--export", out]); + let ran = run(&full); + assert_eq!(ran.code, Some(0), "{full:?}: {:?}", ran.err); + std::fs::read(&path).unwrap() + }; + // `--scale`: the size of the image says which value was used. + let one = at(&[], "1.png"); + let three = at(&["--scale", "3"], "3.png"); + assert_eq!(at(&["--scale", "2", "--scale", "3"], "23.png"), three, "the last --scale won"); + assert_ne!(three, one, "and --scale 3 is not --scale 1"); + // `--page`: which page was exported says it. + let second = at(&["--page", "1"], "p1.png"); + assert_ne!(second, one, "page 1 of the sample is not page 0"); + assert_eq!(at(&["--page", "1", "--page", "0"], "p10.png"), one, "the last --page won"); + // `--connect` and `--port`: the address the error names says it. + let (a, b) = (closed_port(), closed_port()); + for args in [vec!["mcp", "--connect", &a, "--connect", &b], vec!["app", "--port", &a, "--port", &b, "document.list"]] { + let err = run(&args).failed(&format!("{args:?}")); + assert!(err.contains(&format!("127.0.0.1:{b}")), "{args:?} dialled the last port: {err:?}"); + } + let _ = std::fs::remove_dir_all(&dir); +} + +/// The flags that are meant to repeat each take effect, in order. +#[test] +fn the_repeatable_flags_all_take_effect() { + let dir = temp_dir("each"); + let (a, b) = (dir.join("a.png"), dir.join("b.png")); + let ran = run(&[ + "run", + "--sample", + "--cmd", + "document.list", + "--cmd", + "document.list", + "--export", + a.to_str().unwrap(), + "--export", + b.to_str().unwrap(), + ]); + assert_eq!(ran.code, Some(0), "{:?}", ran.err); + // One result line per `--cmd`, in the order given. + let results: Vec<&str> = ran.out.lines().collect(); + assert_eq!(results.len(), 2, "{results:?}"); + assert_eq!(results[0], results[1]); + // And one file per `--export`. + assert_eq!(std::fs::read(&a).unwrap(), std::fs::read(&b).unwrap()); + assert_eq!(ran.err.lines().filter(|l| l.starts_with("wrote ")).count(), 2, "{:?}", ran.err); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A subcommand given nothing to do does nothing, quietly or with its own usage line. `run` with +/// no arguments is the one that says nothing at all: there is no document to act on and nothing +/// was asked of it. +#[test] +fn a_subcommand_with_nothing_to_do_says_so_or_says_nothing() { + assert_eq!(run(&["run"]).succeeded("run"), ""); + // `script` with no file reads stdin, which is closed here: an empty script, run. + let out = run(&["script"]).succeeded("script"); + assert!(out.contains("\"completed\": 0"), "{out:?}"); + // The two that need an argument print the usage line for themselves. + for sub in ["describe", "bench", "validate-pdf"] { + let err = run(&[sub]).failed(sub); + assert!(err.contains(&format!("designcraft-cli {sub}")), "{sub}: {err:?}"); + } +} diff --git a/apps/designcraft-cli/tests/it/cli.rs b/apps/designcraft-cli/tests/it/cli.rs index 861cb514f..f12732578 100644 --- a/apps/designcraft-cli/tests/it/cli.rs +++ b/apps/designcraft-cli/tests/it/cli.rs @@ -7,6 +7,31 @@ fn cli() -> Command { Command::new(env!("CARGO_BIN_EXE_designcraft-cli")) } +#[test] +fn bench_without_spreads_reports_an_error_instead_of_panicking() { + struct Fixture(std::path::PathBuf); + impl Drop for Fixture { + fn drop(&mut self) { + let _ = std::fs::remove_file(&self.0); + } + } + let path = std::env::temp_dir().join(format!("dc-cli-empty-bench-{}.designcraft", std::process::id())); + assert!(std::fs::symlink_metadata(&path).is_err_and(|error| error.kind() == std::io::ErrorKind::NotFound)); + let fixture = Fixture(path); + let mut document = designcraft_doc::Document::new(&Default::default()); + document.spreads.clear(); + document.check().unwrap(); + let bytes = designcraft_format::save(&document).unwrap(); + assert!(designcraft_format::load(&bytes).unwrap().spreads.is_empty()); + std::fs::write(&fixture.0, bytes).unwrap(); + + let out = cli().args(["bench", fixture.0.to_str().unwrap(), "--runs", "1"]).output().unwrap(); + + let err = String::from_utf8_lossy(&out.stderr); + assert_eq!(out.status.code(), Some(1), "{err}"); + assert!(err.contains("cannot benchmark a document with no spreads"), "{err}"); +} + #[test] fn script_from_stdin_with_references_saves_and_exports() { let dir = std::env::temp_dir().join(format!("dc-cli-{}", std::process::id())); @@ -95,6 +120,35 @@ fn export_to_an_unknown_file_type_is_an_error() { let _ = std::fs::remove_dir_all(&dir); } +/// `run --export` prints what the PDF export reports, and `script --export` dropped it: the same +/// PDF with a drop shadow came out of a script with nothing on stderr. +#[test] +fn script_export_prints_the_export_warnings_as_run_does() { + let dir = std::env::temp_dir().join(format!("dc-cli-warnings-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let steps = [ + r#"frame.create={"rect": [72, 72, 300, 200]}"#, + r#"object.fill={"ids": ["$0.id"], "swatch": "[Black]"}"#, + r#"object.dropShadow={"ids": ["$0.id"], "on": true, "distance": 8, "size": 6}"#, + ]; + let script = dir.join("shadow.dcs"); + std::fs::write(&script, steps.join("\n")).unwrap(); + let pdf = dir.join("shadow.pdf"); + let pdf = pdf.to_str().unwrap(); + let mut run = vec!["run"]; + for step in steps { + run.extend(["--cmd", step]); + } + run.extend(["--export", pdf]); + for args in [run, vec!["script", script.to_str().unwrap(), "--export", pdf]] { + let out = cli().args(&args).output().unwrap(); + let err = String::from_utf8_lossy(&out.stderr); + assert!(out.status.success(), "{}: {err}", args[0]); + assert!(err.contains("warning: 1 object(s) with soft effects"), "{}: {err}", args[0]); + } + let _ = std::fs::remove_dir_all(&dir); +} + /// With `--connect` the exports happen in the running app. `--export copy.designcraft` saves a /// copy there: Save As would make the copy the file the open document saves to from then on. #[test] @@ -122,11 +176,49 @@ fn script_export_of_the_document_in_the_running_app_saves_a_copy() { #[test] fn failing_script_exits_nonzero_with_the_step() { let mut child = cli().args(["script", "-"]).stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped()).spawn().unwrap(); - child.stdin.take().unwrap().write_all(b"document.inspect\nno.such.command\n").unwrap(); + child.stdin.take().unwrap().write_all(b"document.inspect\nno.such.command\ndocument.inspect\n").unwrap(); let out = child.wait_with_output().unwrap(); assert!(!out.status.success()); let v: serde_json::Value = serde_json::from_slice(&out.stdout).unwrap(); assert_eq!(v["failedIndex"], 1); + assert_eq!(v["completed"], 1); +} + +#[test] +fn keep_going_reports_the_first_failure_and_does_not_write_outputs() { + struct Outputs([std::path::PathBuf; 2]); + impl Drop for Outputs { + fn drop(&mut self) { + for path in &self.0 { + let _ = std::fs::remove_file(path); + } + } + } + let root = std::env::temp_dir(); + let name = format!("dc-cli-keep-going-{}", std::process::id()); + let paths = [root.join(format!("{name}.designcraft")), root.join(format!("{name}.png"))]; + assert!(paths.iter().all(|path| !path.exists())); + let outputs = Outputs(paths); + + let mut child = cli() + .args(["script", "-", "--keep-going", "--save", outputs.0[0].to_str().unwrap(), "--export", outputs.0[1].to_str().unwrap()]) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .unwrap(); + child.stdin.take().unwrap().write_all(b"no.such.command\ndocument.inspect\nno.other.command\n").unwrap(); + let out = child.wait_with_output().unwrap(); + + assert!(!out.status.success()); + let v: serde_json::Value = serde_json::from_slice(&out.stdout).unwrap(); + assert_eq!(v["completed"], 3); + assert_eq!(v["failedIndex"], 0); + assert_eq!(v["failedCommand"], "no.such.command"); + assert!(v["results"][0]["error"].is_string()); + assert!(v["results"][1].is_object() && v["results"][1]["error"].is_null()); + assert!(v["results"][2]["error"].is_string()); + assert!(outputs.0.iter().all(|path| !path.exists()), "--save and --export require a successful script"); } #[test] @@ -556,3 +648,251 @@ fn usage_lists_the_automation_root_flags() { let usage = String::from_utf8_lossy(&out.stdout); assert!(usage.contains("--automation-read-root DIR") && usage.contains("--automation-write-root DIR"), "{usage}"); } + +/// Width and height from a PNG's IHDR chunk. +fn png_size(png: &[u8]) -> (u32, u32) { + assert!(png.starts_with(b"\x89PNG\r\n\x1a\n"), "not a PNG"); + let be = |at: usize| u32::from_be_bytes(png[at..at + 4].try_into().unwrap()); + (be(16), be(20)) +} + +/// Linux file managers (Dolphin, Nautilus, Thunar) draw a `.designcraft` file's icon through the +/// freedesktop thumbnailer, which runs `designcraft-cli thumbnail %i %o %s` (#1782). The picture is +/// the first-page preview the file already holds, fitted to the size asked for and never enlarged. +#[test] +fn thumbnail_writes_the_saved_preview_fitted_to_the_size() { + let dir = std::env::temp_dir().join(format!("dc-cli-thumb-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let doc = dir.join("a.designcraft"); + make_document(&doc); + let preview = designcraft_format::read_preview(std::fs::File::open(&doc).unwrap()).unwrap(); + let (pw, ph) = png_size(&preview); + assert!(pw.max(ph) > 128, "the saved preview is {pw}×{ph}"); + + let small = dir.join("small.png"); + let out = cli().arg("thumbnail").arg(&doc).arg(&small).arg("128").output().unwrap(); + assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr)); + let (w, h) = png_size(&std::fs::read(&small).unwrap()); + assert_eq!(w.max(h), 128, "{w}×{h} from a {pw}×{ph} preview"); + // The page's proportions stay. + let ratio = |a: u32, b: u32| f64::from(a) / f64::from(b); + assert!((ratio(w, h) - ratio(pw, ph)).abs() < 0.02, "{w}×{h} from a {pw}×{ph} preview"); + + let large = dir.join("large.png"); + let out = cli().arg("thumbnail").arg(&doc).arg(&large).arg("1024").output().unwrap(); + assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr)); + assert_eq!(std::fs::read(&large).unwrap(), preview, "a preview smaller than the size is written as saved"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A file saved without a preview (by an older version, or not by DesignCraft) has no picture: the +/// thumbnailer fails and writes nothing, so the file manager keeps the file type's icon. +#[test] +fn thumbnail_of_a_file_without_a_preview_fails_and_writes_nothing() { + let dir = std::env::temp_dir().join(format!("dc-cli-thumb-none-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let with = dir.join("with.designcraft"); + make_document(&with); + let doc = designcraft_format::load(&std::fs::read(&with).unwrap()).unwrap(); + let without = dir.join("without.designcraft"); + std::fs::write(&without, designcraft_format::save(&doc).unwrap()).unwrap(); + let text = dir.join("notes.designcraft"); + std::fs::write(&text, "not a document").unwrap(); + for input in [&without, &text] { + let png = dir.join("out.png"); + let out = cli().arg("thumbnail").arg(input).arg(&png).arg("256").output().unwrap(); + let err = String::from_utf8_lossy(&out.stderr); + assert!(!out.status.success(), "{}", input.display()); + assert!(err.contains("no preview"), "{}: {err}", input.display()); + assert!(!png.exists(), "{}", input.display()); + } + let _ = std::fs::remove_dir_all(&dir); +} + +/// `thumbnail a.designcraft a.designcraft` would replace the document with a PNG. An output that +/// names the input, by the same path, through a symlink or (on Unix) as a hard link, is refused +/// before anything is read or written, and the document keeps its bytes. +#[test] +fn thumbnail_refuses_an_output_that_names_the_input() { + let dir = std::env::temp_dir().join(format!("dc-cli-thumb-self-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let doc = dir.join("a.designcraft"); + make_document(&doc); + let saved = std::fs::read(&doc).unwrap(); + #[cfg(unix)] + let mut outs = vec![doc.clone(), dir.join(".").join("a.designcraft")]; + #[cfg(not(unix))] + let outs = vec![doc.clone(), dir.join(".").join("a.designcraft")]; + #[cfg(unix)] + { + let link = dir.join("link.png"); + std::os::unix::fs::symlink(&doc, &link).unwrap(); + outs.push(link); + let hard = dir.join("hard.png"); + std::fs::hard_link(&doc, &hard).unwrap(); + outs.push(hard); + } + for out_path in &outs { + let out = cli().arg("thumbnail").arg(&doc).arg(out_path).arg("128").output().unwrap(); + let err = String::from_utf8_lossy(&out.stderr); + assert_eq!(out.status.code(), Some(1), "{}: {err}", out_path.display()); + assert!(err.contains("is the document"), "{}: {err}", out_path.display()); + assert!(std::fs::read(&doc).unwrap() == saved, "{} changed the document", out_path.display()); + assert!(std::fs::read(out_path).unwrap() == saved, "{} was written", out_path.display()); + } + let _ = std::fs::remove_dir_all(&dir); +} + +/// Another existing file at the output path is still replaced by the thumbnail. +#[test] +fn thumbnail_replaces_another_existing_file() { + let dir = std::env::temp_dir().join(format!("dc-cli-thumb-other-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let doc = dir.join("a.designcraft"); + make_document(&doc); + let png = dir.join("old.png"); + std::fs::write(&png, b"an older thumbnail").unwrap(); + let out = cli().arg("thumbnail").arg(&doc).arg(&png).arg("128").output().unwrap(); + assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr)); + let (w, h) = png_size(&std::fs::read(&png).unwrap()); + assert_eq!(w.max(h), 128, "{w}×{h}"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// The argument bugs photocraft#7071 lists, measured here: every one of them was live in this +/// parser too. Each case names the photocraft issue it comes from. +#[test] +fn the_argument_parser_refuses_what_it_cannot_mean() { + let dir = std::env::temp_dir().join(format!("dc-cli-args-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + + // photocraft#423: ` --help` was read as an unknown option. It asks about the + // subcommand, goes to stdout and succeeds. + for sub in ["run", "commands", "describe", "app", "mcp", "perf", "bench", "validate-pdf", "links"] { + let out = cli().args([sub, "--help"]).output().unwrap(); + assert!(out.status.success(), "{sub} --help: {}", String::from_utf8_lossy(&out.stderr)); + let text = String::from_utf8_lossy(&out.stdout); + assert!(text.contains(&format!("designcraft-cli {sub}")), "{sub} --help names it: {text:?}"); + assert!(!text.contains("unknown option"), "{sub} --help: {text:?}"); + } + // `script --help` keeps its own longer help, which it had already. + let out = cli().args(["script", "--help"]).output().unwrap(); + assert!(out.status.success() && String::from_utf8_lossy(&out.stdout).contains("Script text, one step per line")); + + // photocraft#6944: an option took the next token whatever it was, so `--export --scale` + // wrote a file called `--scale` in the working directory. + let out = cli().current_dir(&dir).args(["run", "--sample", "--export", "--scale"]).output().unwrap(); + assert!(!out.status.success(), "{}", String::from_utf8_lossy(&out.stdout)); + let err = String::from_utf8_lossy(&out.stderr); + assert!(err.contains("another option") && err.contains("./--scale"), "{err:?}"); + assert!(!dir.join("--scale").exists(), "nothing was written"); + assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 0, "and no other file either"); + + // A name that really does start with `-` is still reachable, the way the shell reaches one. + let out = cli().current_dir(&dir).args(["run", "--sample", "--export", "./-dash.png"]).output().unwrap(); + assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr)); + assert!(dir.join("-dash.png").is_file(), "{:?}", std::fs::read_dir(&dir).unwrap().flatten().map(|e| e.file_name()).collect::>()); + + // A missing value is found before anything runs, so an export earlier on the line does not + // happen: reported later, `--export first.png --scale --export second.png` wrote first.png + // and only then failed, overwriting a file that was already there (noted in review). + let first = dir.join("first.png"); + std::fs::write(&first, b"older file").unwrap(); + let out = + cli().current_dir(&dir).args(["run", "--sample", "--export", first.to_str().unwrap(), "--scale", "--export", "second.png"]).output().unwrap(); + let err = String::from_utf8_lossy(&out.stderr); + assert!(!out.status.success(), "{err:?}"); + assert!(err.contains("--scale needs a value"), "{err:?}"); + assert_eq!(std::fs::read(&first).unwrap(), b"older file", "the file that was already there is untouched"); + assert!(!dir.join("second.png").exists(), "and nothing else is written"); + std::fs::remove_file(&first).unwrap(); + + // A missing value is still a missing value, with the message it had. + let out = cli().args(["run", "--sample", "--export"]).output().unwrap(); + assert!(!out.status.success()); + assert!(String::from_utf8_lossy(&out.stderr).contains("--export needs a value")); + + // And a missing value in front of an export is still a missing value: the order of the + // options is beside the point until `--scale` has one, and "put it before its --export" was + // advice for a list that already does that. + let out = cli().current_dir(&dir).args(["run", "--sample", "--scale", "--export", "out.png"]).output().unwrap(); + let err = String::from_utf8_lossy(&out.stderr); + assert!(!out.status.success(), "{err:?}"); + assert!(err.contains("--scale needs a value"), "{err:?}"); + assert!(!err.contains("has no --export"), "{err:?}"); + // `./--export` is a file name, which is no way out of a missing `--scale`. + assert!(!err.contains("./"), "{err:?}"); + assert!(!dir.join("out.png").exists(), "and nothing is exported"); + + let _ = std::fs::remove_dir_all(&dir); +} + +/// photocraft#1108: an argument that is not UTF-8 panicked in `std::env::args` ("called +/// `Result::unwrap()` on an `Err` value"). Such a name cannot reach the engine, whose paths are +/// `str`, so it is a usage error. +#[cfg(unix)] +#[test] +fn an_argument_that_is_not_utf8_is_an_error_not_a_panic() { + use std::ffi::OsStr; + use std::os::unix::ffi::OsStrExt; + + let out = cli().arg("info").arg(OsStr::from_bytes(b"/tmp/caf\xe9.designcraft")).output().unwrap(); + let err = String::from_utf8_lossy(&out.stderr); + assert_eq!(out.status.code(), Some(1), "an error, not a panic (101): {err:?}"); + assert!(err.contains("not valid UTF-8"), "{err:?}"); + assert!(!err.contains("panicked"), "{err:?}"); +} + +/// ` --help` answers about that subcommand, which is right where the subcommand exists. For +/// one that does not, it printed the whole usage and **succeeded**, so `typo` on its own was an +/// error while `typo --help` was not, and a script checking the exit status carried on past a +/// misspelled command (noted in review). +#[test] +fn an_unknown_subcommand_is_an_error_even_with_help_after_it() { + for sub in ["typo", "nonsense", "valdiate-pdf", "runn"] { + for help in ["--help", "-h"] { + let out = cli().arg(sub).arg(help).output().unwrap(); + assert_eq!(out.status.code(), Some(1), "{sub} {help} must fail"); + assert!(out.stdout.is_empty(), "{sub} {help} must not answer on stdout: {:?}", String::from_utf8_lossy(&out.stdout)); + let err = String::from_utf8_lossy(&out.stderr); + assert!(err.contains("usage: designcraft-cli"), "{sub} {help}: {err:?}"); + } + } + + // Every subcommand the usage lists still answers on stdout and succeeds, so this is not a + // block on subcommand help. The list is read from the usage text, as the code's own check is. + let subs: Vec<&str> = USAGE_SUBCOMMANDS.iter().copied().filter(|s| !s.starts_with('-')).collect(); + assert!(subs.len() >= 8, "the usage lists {} subcommands", subs.len()); + for sub in subs { + let out = cli().arg(sub).arg("--help").output().unwrap(); + assert_eq!(out.status.code(), Some(0), "{sub} --help must succeed: {:?}", String::from_utf8_lossy(&out.stderr)); + assert!(!out.stdout.is_empty(), "{sub} --help must answer on stdout"); + } +} + +/// A subcommand's help has to name the options that subcommand accepts. `validate-pdf` takes +/// `--standard x4|x1a` -- its own usage string and the module docs both say so -- but the line in +/// the global `USAGE`, which is what `validate-pdf --help` slices out, left it off, so the option +/// was hidden from the only place a user would look (noted in review). +#[test] +fn subcommand_help_names_the_options_that_subcommand_takes() { + let help = |sub: &str| { + let out = cli().arg(sub).arg("--help").output().unwrap(); + assert_eq!(out.status.code(), Some(0), "{sub} --help: {:?}", String::from_utf8_lossy(&out.stderr)); + String::from_utf8_lossy(&out.stdout).into_owned() + }; + let v = help("validate-pdf"); + assert!(v.contains("--standard"), "validate-pdf --help hides --standard: {v:?}"); + // The option is refused for a value it cannot mean, so the help and the parser agree on it. + let out = cli().arg("validate-pdf").arg("x.pdf").arg("--standard").arg("x9").output().unwrap(); + assert_eq!(out.status.code(), Some(1), "an unknown standard is refused"); + + // A couple of others, so this is about subcommand help in general and not one line. + assert!(help("run").contains("--cmd"), "run --help hides --cmd"); + assert!(help("mcp").contains("--automation-read-root"), "mcp --help hides its roots"); +} + +/// The subcommands the binary's usage text lists. Kept here rather than imported because the +/// binary is not a library; the assertion above on the count is what notices if it drifts. +const USAGE_SUBCOMMANDS: &[&str] = &["run", "commands", "describe", "script", "app", "mcp", "perf", "bench", "validate-pdf", "links"]; diff --git a/apps/designcraft-cli/tests/it/main.rs b/apps/designcraft-cli/tests/it/main.rs index 26710c101..e8761f4e1 100644 --- a/apps/designcraft-cli/tests/it/main.rs +++ b/apps/designcraft-cli/tests/it/main.rs @@ -1 +1,2 @@ +mod args; mod cli; diff --git a/apps/designcraft-web/src/browser_policy.rs b/apps/designcraft-web/src/browser_policy.rs index 524df6cc5..ca82c71ca 100644 --- a/apps/designcraft-web/src/browser_policy.rs +++ b/apps/designcraft-web/src/browser_policy.rs @@ -1,4 +1,4 @@ -//! Pure browser startup and download metadata policies. +//! Browser startup, download metadata, and atomic import policies. /// Query flags are case-sensitive decoded keys. Values are ignored: `?sample=false` /// still enables sample startup, and repeated keys have the same presence semantics. @@ -65,3 +65,40 @@ mod tests { } } } + +/// Read a drop in order, publishing nothing unless every file can be read. +pub(crate) async fn read_batch(files: impl IntoIterator, mut read: F) -> Result, E> +where + F: FnMut(T) -> Fut, + Fut: std::future::Future>, +{ + let mut result = Vec::new(); + for file in files { + result.push(read(file).await?); + } + Ok(result) +} + +#[cfg(test)] +mod batch_tests { + #[test] + fn failed_read_aborts_the_whole_batch() { + use std::{ + future::Future, + task::{Context, Poll, Waker}, + }; + let mut seen = Vec::new(); + let result = { + let future = super::read_batch([1, 2, 3], |n| { + seen.push(n); + std::future::ready(if n == 2 { Err("read failed") } else { Ok(n) }) + }); + let mut future = std::pin::pin!(future); + future.as_mut().poll(&mut Context::from_waker(Waker::noop())) + }; + assert_eq!(result, Poll::Ready(Err("read failed"))); + assert_eq!(seen, [1, 2]); + let mut success = std::pin::pin!(super::read_batch([3, 1], |n| std::future::ready(Ok::<_, ()>(n)))); + assert_eq!(success.as_mut().poll(&mut Context::from_waker(Waker::noop())), Poll::Ready(Ok(vec![3, 1]))); + } +} diff --git a/apps/designcraft-web/src/web.rs b/apps/designcraft-web/src/web.rs index 19bc3a122..4d4c936c1 100644 --- a/apps/designcraft-web/src/web.rs +++ b/apps/designcraft-web/src/web.rs @@ -76,7 +76,7 @@ pub fn start() { if has_query_flag(&query(), "sample") { let _ = app.run("file.newSample", serde_json::json!({})); } - Ok(Box::new(WebShell { app, inbox, graphics: creator_graphics })) + Ok(Box::new(WebShell { app, inbox, read_errors: Default::default(), graphics: creator_graphics })) }), ) .await; @@ -344,12 +344,18 @@ fn query() -> String { struct WebShell { app: DesignApp, inbox: Inbox, + /// Why a dropped file couldn't be read, for the status bar (the read finishes outside a frame). + read_errors: std::sync::Arc>>, graphics: GraphicsState, } impl eframe::App for WebShell { fn logic(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) { let graphics = self.graphics.clone(); + let errors = std::mem::take(&mut *self.read_errors.lock().unwrap_or_else(|e| e.into_inner())); + if let Some(error) = errors.into_iter().last() { + self.app.status(error); + } let _ = graphics.run_if_healthy(|| self.app.logic(ctx)); } @@ -357,18 +363,34 @@ impl eframe::App for WebShell { let _ = self.graphics.run_if_healthy(|| { // Dropped files belong to this host iteration's raw input, not to stale logic input: // read them here once, before the batch is saved as pending for a hidden pass. - for f in std::mem::take(&mut raw.dropped_files) { + // Files dropped together arrive together, in their order, so several images load the + // place cursor as one batch. + let dropped = std::mem::take(&mut raw.dropped_files); + if !dropped.is_empty() { let request = self.app.import_request("drop"); let inbox = self.inbox.clone(); + let read_errors = self.read_errors.clone(); let ctx = ctx.clone(); wasm_bindgen_futures::spawn_local(async move { - let name = f.path().file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| "dropped".into()); - match f.bytes_async().await { - Ok(bytes) => { - inbox.lock().unwrap_or_else(|e| e.into_inner()).push(ImportedFile { request, name, bytes }); + let files = crate::browser_policy::read_batch(dropped, |f| { + let request = request.clone(); + async move { + let name = f.path().file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| "dropped".into()); + let bytes = f.bytes_async().await.map_err(|e| format!("couldn't read dropped file {name}: {e}"))?; + Ok::<_, String>(ImportedFile { request, name, bytes }) + } + }) + .await; + match files { + Ok(files) => { + inbox.lock().unwrap_or_else(|e| e.into_inner()).extend(files); + ctx.request_repaint(); + } + Err(error) => { + log::error!("{error}"); + read_errors.lock().unwrap_or_else(|e| e.into_inner()).push(error); ctx.request_repaint(); } - Err(e) => log::error!("couldn't read dropped file {name}: {e}"), } }); } @@ -402,11 +424,18 @@ fn services(inbox: Inbox, ctx: egui::Context) -> Services { rfd::AsyncFileDialog::new().add_filter("DesignCraft, IDML or InDesign", DOC_EXTS) }; wasm_bindgen_futures::spawn_local(async move { - let Some(file) = dialog.pick_file().await else { - return; + // Place takes several files, loaded into the place cursor in the order chosen. + let handles = if request.purpose == "place" { + dialog.pick_files().await.unwrap_or_default() + } else { + dialog.pick_file().await.into_iter().collect() }; - let bytes = file.read().await; - inbox.lock().unwrap_or_else(|e| e.into_inner()).push(ImportedFile { request, name: file.file_name(), bytes }); + let mut files = Vec::with_capacity(handles.len()); + for file in handles { + let bytes = file.read().await; + files.push(ImportedFile { request: request.clone(), name: file.file_name(), bytes }); + } + inbox.lock().unwrap_or_else(|e| e.into_inner()).extend(files); ctx.request_repaint(); }); })), diff --git a/apps/designcraft/Cargo.toml b/apps/designcraft/Cargo.toml index d706374c7..b66041a04 100644 --- a/apps/designcraft/Cargo.toml +++ b/apps/designcraft/Cargo.toml @@ -27,7 +27,8 @@ winresource = "0.1" # Not called here: craft-dialogs shows the dialogs. rfd's default features keep its Wayland # support on, so portal dialogs get the window as their parent. rfd = { workspace = true } -arboard = { workspace = true } +# `image-data`: Edit › Paste reads bitmaps from the clipboard (src/clipboard_image.rs). +arboard = { workspace = true, features = ["image-data"] } [target.'cfg(all(unix, not(target_os = "macos")))'.dependencies] # The same winit eframe uses: to pick the X11 backend (file drag-and-drop) in main.rs. @@ -37,7 +38,8 @@ winit = { version = "0.30", default-features = false, features = ["x11"] } craft-update = { workspace = true } # EnumDisplayDevices (src/gpu.rs): which GPU drives the display, so the window draws on the GPU # 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. +# 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"] } [target.'cfg(target_os = "macos")'.dependencies] @@ -45,9 +47,12 @@ winsafe = { version = "0.0.29", default-features = false, features = ["user"] } winit = { version = "0.30", default-features = false } muda = { version = "0.21", default-features = false } # The input context, to drop the IME's marked text when the Type tool ends a composition. The -# versions muda uses, through safe methods. +# versions muda uses, through safe methods. `NSPasteboard`: the pasteboard's change count, which +# tells Paste whether anything was copied since an object Copy (src/clipboard_image.rs). objc2 = "0.6" -objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "NSResponder", "NSTextInputContext"] } +objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "NSEvent", "NSPasteboard", "NSResponder", "NSScreen", "NSTextInputContext"] } +# Files dragged in from the Finder: the pointer's place on the screen (src/pointer.rs). +objc2-foundation = { version = "0.3", default-features = false, features = ["std", "NSArray", "NSGeometry"] } # The window's `movable` flag follows the application bar's controls. craft-window = { workspace = true } # Finder double-clicks, Open With, Dock drops and `open -a DesignCraft brochure.idml` arrive as a @@ -55,3 +60,8 @@ craft-window = { workspace = true } # PdfCraft and WordCraft) registers the handler behind a safe API (Objective-C interop needs unsafe, # which the workspace forbids). Pinned exactly: review the diff before bumping. fmv-macos-events = "=0.1.0" + +[target.'cfg(target_os = "linux")'.dependencies] +# Native GNOME/Wayland controls without a bundled title font. +winit = { version = "0.30", default-features = false, features = ["wayland-csd-adwaita-notitle"] } + diff --git a/apps/designcraft/src/clipboard_image.rs b/apps/designcraft/src/clipboard_image.rs new file mode 100644 index 000000000..0e8339ff4 --- /dev/null +++ b/apps/designcraft/src/clipboard_image.rs @@ -0,0 +1,135 @@ +//! The system clipboard's image for Edit › Paste (`Services::clipboard_image`): a bitmap +//! (Windows `CF_DIBV5` or `PNG`, the macOS pasteboard's TIFF or PNG, `image/png` on X11), else the +//! first image file of files copied in a file manager. The read runs on its own thread, and Paste +//! waits for it at most [`WAIT`], so an application that is slow to hand over the clipboard does +//! not freeze the window. While a read that timed out is still waiting, Paste starts no other. + +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::mpsc; +use std::time::Duration; + +use designcraft_ui_egui::ClipboardImage; + +/// How long Paste waits for the clipboard's image. +const WAIT: Duration = Duration::from_millis(1500); + +/// The largest image file Paste reads from a copied file list, in bytes. +const MAX_FILE_BYTES: u64 = 256 << 20; + +/// A clipboard read is running. +static READING: AtomicBool = AtomicBool::new(false); + +/// The clipboard's image, or `None` when it holds none or does not answer within [`WAIT`]. +pub fn read() -> Option { + within(&READING, WAIT, read_now) +} + +/// Clears the in-flight flag when the read's thread ends. +struct Reading(&'static AtomicBool); + +impl Drop for Reading { + fn drop(&mut self) { + self.0.store(false, Ordering::Release); + } +} + +/// `read`'s result when it arrives within `wait`. A read that takes longer finishes on its own +/// thread and is dropped; until it does, `busy` stays set and no other read starts. +fn within(busy: &'static AtomicBool, wait: Duration, read: impl FnOnce() -> Option + Send + 'static) -> Option { + if busy.swap(true, Ordering::AcqRel) { + log::warn!("clipboard image: the previous read has not finished"); + return None; + } + let (tx, rx) = mpsc::channel(); + let spawned = std::thread::Builder::new().name("clipboard image".into()).spawn(move || { + let _reading = Reading(busy); + let _ = tx.send(read()); + }); + if let Err(e) = spawned { + busy.store(false, Ordering::Release); + log::warn!("clipboard image: no thread to read it: {e}"); + return None; + } + match rx.recv_timeout(wait) { + Ok(image) => image, + Err(mpsc::RecvTimeoutError::Timeout) => { + log::warn!("clipboard image: the clipboard did not answer within {} ms", wait.as_millis()); + None + } + Err(mpsc::RecvTimeoutError::Disconnected) => None, + } +} + +/// The general pasteboard's change count, which AppKit raises with every copy. +#[cfg(target_os = "macos")] +pub fn change_count() -> Option { + i64::try_from(objc2_app_kit::NSPasteboard::generalPasteboard().changeCount()).ok() +} + +fn read_now() -> Option { + let mut clipboard = arboard::Clipboard::new().ok()?; + if let Ok(image) = clipboard.get_image() { + let width = u32::try_from(image.width).ok()?; + let height = u32::try_from(image.height).ok()?; + return Some(ClipboardImage::Pixels { width, height, rgba: image.bytes.into_owned() }); + } + first_image_file(&clipboard.get().file_list().ok()?) +} + +/// The first of `paths` that is an image file no larger than [`MAX_FILE_BYTES`], with its name. +fn first_image_file(paths: &[PathBuf]) -> Option { + paths.iter().find_map(|path| { + let ext = path.extension()?.to_str()?.to_ascii_lowercase(); + if !designcraft_engine::cmd::IMAGE_EXTENSIONS.contains(&ext.as_str()) || std::fs::metadata(path).ok()?.len() > MAX_FILE_BYTES { + return None; + } + // At most one byte past the limit is read, should the file grow after the size check. + let bytes = designcraft_engine::io::read_capped(path, MAX_FILE_BYTES).ok().filter(|b| b.len() as u64 <= MAX_FILE_BYTES)?; + Some(ClipboardImage::File { name: file_name(path), bytes }) + }) +} + +fn file_name(path: &Path) -> String { + path.file_name().map_or_else(|| path.to_string_lossy().into_owned(), |n| n.to_string_lossy().into_owned()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_read_that_does_not_answer_is_given_up_and_no_second_one_starts_meanwhile() { + static BUSY: AtomicBool = AtomicBool::new(false); + let (release, blocked) = mpsc::channel::<()>(); + // The read waits for a message that is only sent after Paste has given up on it. + assert_eq!(within(&BUSY, Duration::ZERO, move || blocked.recv().ok().map(|()| 1)), None); + let (started, ran) = mpsc::channel::<()>(); + let second = within(&BUSY, Duration::from_secs(60), move || started.send(()).ok().map(|()| 2)); + assert_eq!(second, None, "refused while the first read waits"); + assert!(ran.try_recv().is_err(), "the second read never ran"); + let _ = release.send(()); + while BUSY.load(Ordering::Acquire) { + std::thread::yield_now(); + } + assert_eq!(within(&BUSY, Duration::from_secs(60), || Some(3)), Some(3), "an answer is taken as soon as it comes"); + } + + #[test] + fn a_copied_file_list_pastes_its_first_image_file() { + let stamp = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos(); + let dir = std::env::temp_dir().join(format!("designcraft-clipboard-files-{}-{stamp}", std::process::id())); + std::fs::create_dir(&dir).unwrap(); + let (text, missing, png) = (dir.join("notes.txt"), dir.join("gone.png"), dir.join("Photo.PNG")); + std::fs::write(&text, b"text").unwrap(); + std::fs::write(&png, b"png bytes").unwrap(); + let picked = first_image_file(&[text, missing, png.clone()]); + let none = first_image_file(&[dir.join("a.txt")]); + let _ = std::fs::remove_dir_all(&dir); + match picked { + Some(ClipboardImage::File { name, bytes }) => assert_eq!((name.as_str(), bytes.as_slice()), ("Photo.PNG", b"png bytes".as_slice())), + _ => panic!("the image file is picked"), + } + assert!(none.is_none()); + } +} diff --git a/apps/designcraft/src/gpu.rs b/apps/designcraft/src/gpu.rs index 907117b0c..93586e585 100644 --- a/apps/designcraft/src/gpu.rs +++ b/apps/designcraft/src/gpu.rs @@ -678,7 +678,12 @@ fn restart_without<'a>(graphics_failed: bool, frames: u64, picked: Option<&'a st /// ended it. pub fn finish(outcome: Result, startup: &Startup) -> Result<(), String> { let (why, graphics_failed) = match outcome { - Ok(Ok(())) => return Ok(()), + // The window closed normally, perhaps before its first frame or before the app was + // created (so `on_exit` never ran): no driver fault took this start down (#2116). + Ok(Ok(())) => { + startup.presented(); + return Ok(()); + } Ok(Err(e @ eframe::Error::Wgpu(_))) => (e.to_string(), true), Ok(Err(e)) => (e.to_string(), false), Err(panic) => (panic, GRAPHICS_PANIC.load(Ordering::Relaxed)), diff --git a/apps/designcraft/src/gpu/backend.rs b/apps/designcraft/src/gpu/backend.rs index 6aa250dd4..06c477064 100644 --- a/apps/designcraft/src/gpu/backend.rs +++ b/apps/designcraft/src/gpu/backend.rs @@ -14,8 +14,9 @@ //! fallback off. //! //! The fallback: before the window is created, `gpu.json` in the settings directory records the -//! backend being tried; once a frame has been presented, or the graphics failed with an error the -//! app caught (see `gpu::finish`), that entry is cleared. An entry still there at the next start +//! backend being tried; once a frame has been presented, the window closed normally (even before +//! its first frame), or the graphics failed with an error the app caught (see `gpu::finish`), that +//! entry is cleared. An entry still there at the next start //! means the previous start never got that far — the driver crashed, or the app was killed //! meanwhile — so that backend joins `failed`, the next candidate is tried and the status bar says //! so. Backends a restart left out (`--gpu-skip=`, see `gpu`) aren't chosen for that start but @@ -538,6 +539,23 @@ mod tests { let _ = std::fs::remove_dir_all(path.parent().expect("dir")); } + /// A window closed before its first frame (#2116): the app was created slowly or not at all, + /// so neither a frame nor `on_exit` cleared the record, but eframe ended cleanly. No driver + /// fault took that start down, so the next start keeps the backend. + #[test] + fn a_start_that_ends_cleanly_before_its_first_frame_does_not_fail_its_backend() { + let path = temp_path("clean-end"); + let fallback = Fallback::begin_unforced(Some(path.clone()), V, &[]).expect("candidates"); + let first = fallback.backend; + assert_eq!(read(&path).trying, Some(first)); + let startup = super::super::Startup::new(Some(fallback), Vec::new()); + assert_eq!(super::super::finish(Ok(Ok(())), &startup), Ok(())); + assert_eq!(read(&path).trying, None, "a clean end leaves no backend being tried"); + let c = choose(candidates(), &read(&path), V, &[]).expect("candidates"); + assert_eq!((c.backend, c.record.failed, c.switched_from), (first, Vec::new(), None)); + let _ = std::fs::remove_dir_all(path.parent().expect("dir")); + } + #[test] fn without_a_path_nothing_is_written_and_a_bad_path_is_not_fatal() { let mut s = Fallback::begin_unforced(None, V, &[]).expect("candidates"); diff --git a/apps/designcraft/src/gpu_limits.rs b/apps/designcraft/src/gpu_limits.rs index 5615e5650..13eca4719 100644 --- a/apps/designcraft/src/gpu_limits.rs +++ b/apps/designcraft/src/gpu_limits.rs @@ -6,6 +6,11 @@ //! (9048×5757 between 250 % and 100 % monitors), then failed `Surface::configure`, and wgpu's //! default error handler panics: the app closed with the documents in it. DirectX 12, Vulkan and //! Metal hardware offer 16384. +//! +//! The same goes for buffers: egui-wgpu doubles its vertex buffer when a frame outgrows it, and +//! wgpu's default largest buffer is 256 MiB. A frame of a 160-page catalogue with 137 MB of vertices +//! asked for a 275 MB buffer, and egui-wgpu panicked when the device refused it. DirectX 12 and +//! Vulkan hardware offer far more. use eframe::{ NativeOptions, @@ -14,21 +19,23 @@ use eframe::{ }; use std::sync::{Arc, Mutex, PoisonError}; -/// `required` with the largest texture side the adapter's `supported` limits offer. Taking the -/// adapter's own value also never asks a smaller (downlevel) adapter for more than it has. -pub fn surface_texture_limits(mut required: Limits, supported: &Limits) -> Limits { +/// `required` with the largest texture side and buffer the adapter's `supported` limits offer. +/// Taking the adapter's own values also never asks a smaller (downlevel) adapter for more than it +/// has. +pub fn adapter_size_limits(mut required: Limits, supported: &Limits) -> Limits { required.max_texture_dimension_2d = supported.max_texture_dimension_2d; + required.max_buffer_size = supported.max_buffer_size; required } -/// Makes the device eframe creates ask for the adapter's largest texture side -/// ([`surface_texture_limits`]), keeping eframe's other device requirements. -pub fn request_adapter_texture_size(options: &mut NativeOptions) { +/// Makes the device eframe creates ask for the adapter's largest texture side and buffer +/// ([`adapter_size_limits`]), keeping eframe's other device requirements. +pub fn request_adapter_sizes(options: &mut NativeOptions) { if let WgpuSetup::CreateNew(create) = &mut options.wgpu_options.wgpu_setup { let device_descriptor = Arc::clone(&create.device_descriptor); create.device_descriptor = Arc::new(move |adapter| { let mut descriptor = device_descriptor(adapter); - descriptor.required_limits = surface_texture_limits(descriptor.required_limits, &adapter.limits()); + descriptor.required_limits = adapter_size_limits(descriptor.required_limits, &adapter.limits()); descriptor }); } @@ -62,7 +69,7 @@ mod tests { let eframe_request = Limits { max_texture_dimension_2d: 8192, ..base.clone() }; for side in [4096, 8192, 16384, 32768] { let supported = Limits { max_texture_dimension_2d: side, ..base.clone() }; - let limits = surface_texture_limits(eframe_request.clone(), &supported); + let limits = adapter_size_limits(eframe_request.clone(), &supported); assert_eq!(limits.max_texture_dimension_2d, side); // The drag's 9048×5757 surface fits from 16384 up. assert_eq!(side >= 16384, 9048 <= limits.max_texture_dimension_2d); @@ -73,12 +80,27 @@ mod tests { } } + #[test] + fn largest_buffer_is_the_adapters_own() { + // egui-wgpu grew its vertex buffer to 275 MB for 137 MB of vertices: more than wgpu's + // default 256 MiB, within what DirectX 12 hardware offers. A downlevel adapter offering + // less is asked for no more. + let eframe_request = Limits::default(); + for size in [128 << 20, 256 << 20, 2 << 30] { + let supported = Limits { max_buffer_size: size, ..Limits::default() }; + let limits = adapter_size_limits(eframe_request.clone(), &supported); + assert_eq!(limits.max_buffer_size, size); + assert_eq!(size >= 2 << 30, limits.max_buffer_size >= 275_114_400); + assert!(limits.check_limits(&supported)); + } + } + #[test] fn native_options_keep_creating_their_own_device() { // The wrapper only replaces the device descriptor: eframe still creates the instance, // adapter and device, and main.rs can still choose the backends. let mut options = NativeOptions::default(); - request_adapter_texture_size(&mut options); + request_adapter_sizes(&mut options); assert!(matches!(options.wgpu_options.wgpu_setup, WgpuSetup::CreateNew(_))); } } diff --git a/apps/designcraft/src/logging.rs b/apps/designcraft/src/logging.rs index 04238e853..03303a4a0 100644 --- a/apps/designcraft/src/logging.rs +++ b/apps/designcraft/src/logging.rs @@ -121,10 +121,22 @@ pub fn rotate(dir: &Path) -> std::io::Result<(PathBuf, File)> { Ok((path, file)) } -/// One formatted log line: ` [] : \n`. +/// One formatted log line: ` [] : \n`. A message +/// of several lines (a backtrace) continues on lines that start with a tab, so a line break in +/// what a message quotes (a file name, an identifier out of a document) can't pass for the start +/// of another record; other control characters are written as escapes. pub fn format_line(ts: &str, level: log::Level, thread: &str, target: &str, message: &str) -> String { let message = message.strip_suffix('\n').unwrap_or(message); - format!("{ts} {level:<5} [{thread}] {target}: {message}\n") + let mut text = String::with_capacity(message.len()); + for c in message.chars() { + match c { + '\n' => text.push_str("\n\t"), + '\t' => text.push(c), + c if c.is_control() => text.push_str(&c.escape_default().to_string()), + c => text.push(c), + } + } + format!("{ts} {level:<5} [{thread}] {target}: {text}\n") } /// Where formatted lines go besides standard error: kept in memory until a file is attached, @@ -357,7 +369,12 @@ mod tests { "2026-10-08T07:59:17.728Z ERROR [main] designcraft_engine::guard: command `frame.create` panicked: boom\n" ); // A multi-line message (a panic with a backtrace) keeps its lines; the record still ends in one newline. - assert!(format_line("t", log::Level::Error, "w", "x", "a\nb\n").ends_with("x: a\nb\n")); + assert!(format_line("t", log::Level::Error, "w", "x", "a\nb\n").ends_with("x: a\n\tb\n")); + // A name out of a document can't write a second record: its line breaks continue this + // one and a carriage return or an escape sequence is spelled out. + let forged = + format_line("t", log::Level::Warn, "w", "x", "cannot open `a.designcraft\n2026-01-01T00:00:00.000Z INFO [main] x: all good\r\u{1b}[0m`"); + assert_eq!(forged, "t WARN [w] x: cannot open `a.designcraft\n\t2026-01-01T00:00:00.000Z INFO [main] x: all good\\r\\u{1b}[0m`\n"); } #[test] diff --git a/apps/designcraft/src/main.rs b/apps/designcraft/src/main.rs index 5f056aab3..5f465e46d 100644 --- a/apps/designcraft/src/main.rs +++ b/apps/designcraft/src/main.rs @@ -15,13 +15,17 @@ #[cfg(target_os = "macos")] mod apple_events; +mod clipboard_image; mod control_server; mod gpu; mod gpu_limits; mod logging; #[cfg(target_os = "macos")] mod native_menu; +#[cfg(target_os = "macos")] +mod pointer; mod profile; +mod window_frame; use designcraft_engine::Session; use designcraft_ui_egui::{DesignApp, Services}; @@ -224,6 +228,11 @@ fn services() -> Services { read: Some(Box::new(|p: &str| std::fs::read(p).map_err(|e| e.to_string()))), write: Some(Box::new(|p: &str, b: &[u8]| designcraft_engine::atomic::write_atomic(std::path::Path::new(p), b).map_err(|e| e.to_string()))), clipboard_text: Some(Box::new(|| arboard::Clipboard::new().and_then(|mut c| c.get_text()).ok())), + clipboard_image: Some(Box::new(clipboard_image::read)), + #[cfg(target_os = "macos")] + clipboard_change: Some(Box::new(clipboard_image::change_count)), + #[cfg(target_os = "macos")] + pointer: Some(Box::new(pointer::screen_position)), ..Default::default() } } @@ -255,7 +264,7 @@ fn control_port_from(source: &str, value: Option) -> Option { fn main() -> std::process::ExitCode { // Windows: the update helper is a copy of this program started with `--finish-update`. #[cfg(windows)] - if let Some(result) = craft_update::self_update::finish(&craft_update::suite::DESIGNCRAFT, &std::env::args_os().skip(1).collect::>()) { + if let Some(result) = craft_update::self_update::finish(&designcraft_ui_egui::UPDATE_APP, &std::env::args_os().skip(1).collect::>()) { std::process::exit(i32::from(result.is_err())); } // First, so every start-up record (and the engine's panic hook, installed with the first @@ -314,9 +323,9 @@ fn main() -> std::process::ExitCode { if let Some(icon) = app_icon() { options.viewport = options.viewport.with_icon(icon); } - // The adapter's largest texture side instead of eframe's 8192, so a window across several - // monitors keeps its surface (see `gpu_limits`). - gpu_limits::request_adapter_texture_size(&mut options); + // The adapter's largest texture side and buffer instead of eframe's 8192 and wgpu's 256 MiB, so a + // window across several monitors keeps its surface and a large frame its vertex buffer (see `gpu_limits`). + gpu_limits::request_adapter_sizes(&mut options); // The graphics backend, decided before the window exists: a driver that faults takes the // process down before any Rust code can catch it (see `gpu::backend`). let fallback = gpu::backend::Fallback::begin( @@ -395,6 +404,12 @@ fn main() -> std::process::ExitCode { info.driver, info.driver_info ); + let limits = rs.device.limits(); + log::info!( + "graphics: largest texture side {}, largest buffer {} MiB", + limits.max_texture_dimension_2d, + limits.max_buffer_size >> 20 + ); created.started_with(info.backend); created.created(&cc.egui_ctx); if !skip.is_empty() { @@ -428,6 +443,9 @@ fn main() -> std::process::ExitCode { } app.integrated_titlebar = cfg!(target_os = "macos"); app.custom_titlebar = cfg!(target_os = "windows"); + // The custom title bar's undecorated window must stay borderless, or its caption + // and border offset the content and the pointer on some Windows systems (#1295). + app.services.window_frame = window_frame::service(cc, app.custom_titlebar); if let Some(port) = control_port { let rx = control_server::start(port, cc.egui_ctx.clone()); app = app.with_control(rx); diff --git a/apps/designcraft/src/native_menu.rs b/apps/designcraft/src/native_menu.rs index e127776ba..65c3945c1 100644 --- a/apps/designcraft/src/native_menu.rs +++ b/apps/designcraft/src/native_menu.rs @@ -41,9 +41,10 @@ struct RecentMenu { separator: Option, } -/// Accelerator for "Cmd+Shift+]" (modifier-less shortcuts stay in the app so typing works). +/// Accelerator for "Cmd+Shift+]". Shortcuts the bar would never see, such as modifier-less ones +/// or Option on a character key, stay in the app (`menus::native_key_equivalent`). fn accel(sc: &str) -> Option { - if !(sc.contains("Cmd") || sc.contains("Ctrl") || sc.contains("Alt")) { + if !menus::native_key_equivalent(sc) { return None; } Accelerator::from_str(&sc.replace("Cmd", "CMD").replace("Alt", "ALT").replace("Shift", "SHIFT").replace("Ctrl", "CTRL")).ok() @@ -230,10 +231,12 @@ fn build( path: &str, recent: &mut Option, ) { - for e in entries { + for (i, e) in entries.iter().enumerate() { match e { Item::Sep => { - let _ = parent.append(&PredefinedMenuItem::separator()); + if menus::has_shown_item(app, &entries[i + 1..]) { + let _ = parent.append(&PredefinedMenuItem::separator()); + } } Item::Sub(label, children) => { let sub = Submenu::new(menu_title(app, label), true); diff --git a/apps/designcraft/src/pointer.rs b/apps/designcraft/src/pointer.rs new file mode 100644 index 000000000..3725cfbaa --- /dev/null +++ b/apps/designcraft/src/pointer.rs @@ -0,0 +1,43 @@ +//! macOS: where the pointer is on the screen, for files dragged in from the Finder. winit sends no +//! pointer events during a drag, so the drop asks AppKit (`NSEvent.mouseLocation`) instead. + +use objc2::MainThreadMarker; +use objc2_app_kit::{NSEvent, NSScreen}; + +/// The pointer, in points from the top left of the main display (where winit, and so egui's +/// `inner_rect`, put the origin). `None` off the main thread or with no display. +pub fn screen_position() -> Option { + let mtm = MainThreadMarker::new()?; + // AppKit's origin is the bottom left of the first screen, the one with the menu bar. + let height = NSScreen::screens(mtm).firstObject()?.frame().size.height; + let at = NSEvent::mouseLocation(); + from_appkit(at.x, at.y, height) +} + +/// A point in AppKit's global coordinates (origin at the bottom left of the main display, the one +/// with the menu bar, y up) in winit's (origin at its top left, y down), given that display's +/// height. Only the main display's height: winit flips window positions the same way +/// (`flip_window_screen_coordinates`, against `CGMainDisplayID`), whatever display the window is +/// on, so a display left of or above the main one gives negative coordinates in both. +fn from_appkit(x: f64, y: f64, main_height: f64) -> Option { + let y = main_height - y; + (x.is_finite() && y.is_finite()).then(|| egui::pos2(x as f32, y as f32)) +} + +#[cfg(test)] +mod tests { + use super::from_appkit; + + #[test] + fn appkit_points_flip_against_the_main_display_only() { + // The main display is 1000 points high: its top left is (0, 0), its bottom left (0, 1000). + assert_eq!(from_appkit(0.0, 1000.0, 1000.0), Some(egui::pos2(0.0, 0.0))); + assert_eq!(from_appkit(200.0, 100.0, 1000.0), Some(egui::pos2(200.0, 900.0))); + // A second display above the main one, and one to its left: negative, as winit reports a + // window there. + assert_eq!(from_appkit(300.0, 1200.0, 1000.0), Some(egui::pos2(300.0, -200.0))); + assert_eq!(from_appkit(-800.0, 500.0, 1000.0), Some(egui::pos2(-800.0, 500.0))); + assert_eq!(from_appkit(f64::NAN, 0.0, 1000.0), None); + assert_eq!(from_appkit(0.0, 0.0, f64::INFINITY), None); + } +} diff --git a/apps/designcraft/src/window_frame.rs b/apps/designcraft/src/window_frame.rs new file mode 100644 index 000000000..c50e1870c --- /dev/null +++ b/apps/designcraft/src/window_frame.rs @@ -0,0 +1,352 @@ +//! Keeps the custom (undecorated) title bar window truly borderless (#1295). +//! +//! winit 0.30 gives an undecorated window the `WS_CAPTION | WS_BORDER` styles and hides the +//! non-client area by spreading the client rect over it (`WM_NCCALCSIZE`). On some systems +//! (reported: Windows 10 LTSB, Intel HD Graphics 4600, 1366 × 768) the desktop compositor still +//! reserves that frame for the window surface: the content is drawn offset by the caption and +//! border, leaving black bars at the window's top-left, while the pointer keeps the un-offset +//! client coordinates, so it no longer points at what is drawn under it. +//! +//! winit 0.27 — before rust-windowing/winit#2419 — simply omitted those styles for undecorated +//! windows, and there was no offset. [`service`] restores that: it strips `WS_CAPTION` and +//! `WS_BORDER` and forces Windows to recalculate the frame. winit puts them back whenever it +//! changes the window flags (maximize, restore, …), so the returned guard checks every frame. +//! +//! Windows sizes a maximize by the frame its styles describe, so a window maximized while its +//! caption is gone is sized without one: its rect covers the whole monitor, taskbar included. +//! The shell reads a caption-less window covering its monitor as a full-screen app and drops the +//! taskbar's backdrop behind it — a black band on stock Windows 11, a glitched unresponsive one +//! under ExplorerPatcher (photocraft#3144). The guard therefore also trims a parked maximize's rect back to +//! the work area plus its own frame, clear of the taskbar. winit pins the client area to the work +//! area either way (`WM_NCCALCSIZE`), so the app's pixels do not move. +//! +//! An auto-hidden taskbar reserves no work area, so that trim leaves the maximize covering the +//! whole monitor, and the shell, taking it for a full-screen app, no longer reveals the taskbar +//! when the pointer reaches its edge (photocraft#4845). On each edge with an auto-hidden taskbar the guard +//! instead stops the window one pixel short of the monitor, as other custom-frame apps do. +//! +//! The long-term fix is in winit itself (storytold/winit#17); this module goes when that lands. +//! +//! The Windows calls go through safe `winsafe` wrappers; the workspace forbids `unsafe`, and +//! winsafe can't wrap a raw handle without it, so the window is found by its handle instead. + +pub use platform::service; + +#[cfg(target_os = "windows")] +mod platform { + use designcraft_ui_egui::WindowFrameFn; + use eframe::wgpu::rwh::{HasWindowHandle, RawWindowHandle}; + use winsafe::prelude::Handle; + use winsafe::{AtomStr, HWND, HwndPlace, POINT, SIZE, co}; + + /// A rect in desktop coordinates: `(left, top, right, bottom)`, right and bottom exclusive. + type Rect = (i32, i32, i32, i32); + + /// A monitor edge. + #[derive(Clone, Copy, Debug, PartialEq, Eq)] + enum Edge { + Left, + Top, + Right, + Bottom, + } + + /// A guard that keeps the window borderless each frame, or `None` when the app uses the + /// system title bar (the window is decorated) or its handle can't be found. + pub fn service(cc: &eframe::CreationContext<'_>, custom_titlebar: bool) -> Option { + if !custom_titlebar { + return None; + } + let target = match cc.window_handle().ok()?.as_raw() { + RawWindowHandle::Win32(h) => h.hwnd.get(), + _ => return None, + }; + let hwnd = find_window(target)?; + reapply(&hwnd); + Some(Box::new(move || reapply(&hwnd))) + } + + /// The top-level window with the given raw handle. `EnumWindows` hands out real `HWND`s, so + /// this matches winit's own window without wrapping a raw handle (which needs `unsafe`). + fn find_window(target: isize) -> Option { + let mut found = None; + let _ = winsafe::EnumWindows(|hwnd| { + if hwnd.ptr() as isize == target { + found = Some(hwnd); + false + } else { + true + } + }); + found + } + + /// One pass of the per-frame guard: the styles winit put back come off again, and a parked + /// maximize stays clear of the taskbar. + fn reapply(hwnd: &HWND) { + strip(hwnd); + keep_clear_of_the_taskbar(hwnd); + } + + /// Removes `WS_CAPTION`/`WS_BORDER` and has Windows recalculate the frame. A no-op once they + /// are gone, so it is cheap to call every frame. + fn strip(hwnd: &HWND) { + let style = hwnd.style(); + let without = borderless(style); + if without.raw() == style.raw() { + return; + } + hwnd.set_style(without); + let _ = hwnd.SetWindowPos( + HwndPlace::None, + POINT::new(), + SIZE::new(), + co::SWP::FRAMECHANGED | co::SWP::NOCOPYBITS | co::SWP::NOMOVE | co::SWP::NOSIZE | co::SWP::NOZORDER | co::SWP::NOACTIVATE, + ); + } + + /// How far a parked maximize reaches past a monitor/work-area edge: the resize + /// border (about 8 pt at 100 %, more with DPI). Past that, a maximized window's rect is not + /// parked but being dragged or snapped, and is left alone. + const FRAME: i32 = 32; + + /// Keep a parked maximize inside all four work-area edges, including a top taskbar. + fn keep_clear_of_the_taskbar(hwnd: &HWND) { + if !hwnd.IsZoomed() { + return; + } + let (Ok(r), Ok(mi)) = (hwnd.GetWindowRect(), hwnd.MonitorFromWindow(co::MONITOR::DEFAULTTONEAREST).GetMonitorInfo()) else { + return; + }; + let (m, w) = (mi.rcMonitor, mi.rcWork); + let (rect, monitor, work) = ((r.left, r.top, r.right, r.bottom), (m.left, m.top, m.right, m.bottom), (w.left, w.top, w.right, w.bottom)); + // The taskbars (a couple of `FindWindowEx` calls) are only looked up while the window + // covers the whole monitor, which a trimmed maximize no longer does. + let Some((left, top, right, bottom)) = clamped_rect(rect, monitor, work) + .or_else(|| covers(rect, monitor).then(|| short_of_autohide_taskbars(rect, monitor, work, &taskbar_edges(monitor))).flatten()) + else { + return; + }; + let (Some(width), Some(height)) = (right.checked_sub(left), bottom.checked_sub(top)) else { + return; + }; + // Moving the outer frame while winit pins the client rect to the work area must + // not copy the old frame's pixels into the custom title bar. + let _ = hwnd.SetWindowPos( + HwndPlace::None, + POINT { x: left, y: top }, + SIZE { cx: width, cy: height }, + co::SWP::FRAMECHANGED | co::SWP::NOCOPYBITS | co::SWP::NOZORDER | co::SWP::NOACTIVATE, + ); + let _ = hwnd.InvalidateRect(None, false); + } + + /// Return the corrected outer rect in desktop coordinates, preserving the resize border. + /// Each edge must be parked just outside either the monitor or work-area edge. Accepting + /// both makes the guard idempotent and handles Windows already correcting some edges. + /// Dragged/snapped windows are left alone; no monitor-origin or DPI assumptions are needed. + fn clamped_rect(rect: (i32, i32, i32, i32), monitor: (i32, i32, i32, i32), work: (i32, i32, i32, i32)) -> Option<(i32, i32, i32, i32)> { + let (l, t, r, b) = rect; + let (ml, mt, mr, mb) = monitor; + let (wl, wt, wr, wb) = work; + if ml >= mr || mt >= mb || wl < ml || wt < mt || wr > mr || wb > mb || wl >= wr || wt >= wb { + return None; + } + // Infer the frame from an edge without a taskbar. On an obstructed edge, the + // monitor and work-area offsets can both look like valid borders (e.g. auto-hide). + let border = [ + (ml == wl).then(|| ml.checked_sub(l)).flatten(), + (mt == wt).then(|| mt.checked_sub(t)).flatten(), + (mr == wr).then(|| r.checked_sub(mr)).flatten(), + (mb == wb).then(|| b.checked_sub(mb)).flatten(), + ] + .into_iter() + .flatten() + .filter(|n| (0..=FRAME).contains(n)) + .min()?; + let parked = |monitor: Option, work: Option| monitor == Some(border) || work == Some(border); + if !parked(ml.checked_sub(l), wl.checked_sub(l)) + || !parked(mt.checked_sub(t), wt.checked_sub(t)) + || !parked(r.checked_sub(mr), r.checked_sub(wr)) + || !parked(b.checked_sub(mb), b.checked_sub(wb)) + { + return None; + } + let corrected = (wl.checked_sub(border)?, wt.checked_sub(border)?, wr.checked_add(border)?, wb.checked_add(border)?); + (corrected != rect).then_some(corrected) + } + + /// Whether `rect` reaches every edge of `monitor`: what the shell takes for a full-screen app. + fn covers(rect: Rect, monitor: Rect) -> bool { + rect.0 <= monitor.0 && rect.1 <= monitor.1 && rect.2 >= monitor.2 && rect.3 >= monitor.3 + } + + /// The edges of `monitor` that have a taskbar (the primary `Shell_TrayWnd` or a secondary + /// monitor's `Shell_SecondaryTrayWnd`), shown or hidden. + fn taskbar_edges(monitor: Rect) -> Vec { + let mut edges = Vec::new(); + for class in ["Shell_TrayWnd", "Shell_SecondaryTrayWnd"] { + let mut after: Option = None; + // One taskbar per monitor; the bound only guards against a misbehaving shell. + for _ in 0..64 { + let Ok(Some(tray)) = HWND::NULL.FindWindowEx(after.as_ref(), AtomStr::from_str(class), None) else { + break; + }; + if let Ok(r) = tray.GetWindowRect() { + edges.extend(taskbar_edge((r.left, r.top, r.right, r.bottom), monitor)); + } + after = Some(tray); + } + } + edges + } + + /// The edge of `monitor` a taskbar with rect `taskbar` sits on: the one nearest its centre, + /// or `None` when it is on another monitor. An auto-hidden taskbar is parked mostly past its + /// edge with a sliver left on screen, so its centre may lie outside the monitor. + fn taskbar_edge(taskbar: Rect, monitor: Rect) -> Option { + let (tl, tt, tr, tb) = (i64::from(taskbar.0), i64::from(taskbar.1), i64::from(taskbar.2), i64::from(taskbar.3)); + let (ml, mt, mr, mb) = (i64::from(monitor.0), i64::from(monitor.1), i64::from(monitor.2), i64::from(monitor.3)); + if tl >= tr || tt >= tb || ml >= mr || mt >= mb || tr <= ml || tl >= mr || tb <= mt || tt >= mb { + return None; + } + // Doubled centre and distances, so nothing rounds. + let (cx, cy) = (tl + tr, tt + tb); + [(Edge::Left, cx - 2 * ml), (Edge::Top, cy - 2 * mt), (Edge::Right, 2 * mr - cx), (Edge::Bottom, 2 * mb - cy)] + .into_iter() + .min_by_key(|&(_, distance)| distance) + .map(|(edge, _)| edge) + } + + /// A maximize covering its monitor, trimmed to stop one pixel short of each edge where a + /// taskbar reserves no work area (it auto-hides), so the shell still reveals it there. + /// `None` when there is nothing to trim. + fn short_of_autohide_taskbars(rect: Rect, monitor: Rect, work: Rect, taskbars: &[Edge]) -> Option { + if !covers(rect, monitor) { + return None; + } + let (mut l, mut t, mut r, mut b) = rect; + for edge in taskbars { + match edge { + Edge::Left if work.0 == monitor.0 => l = monitor.0.checked_add(1)?, + Edge::Top if work.1 == monitor.1 => t = monitor.1.checked_add(1)?, + Edge::Right if work.2 == monitor.2 => r = monitor.2.checked_sub(1)?, + Edge::Bottom if work.3 == monitor.3 => b = monitor.3.checked_sub(1)?, + _ => {} + } + } + let trimmed = (l, t, r, b); + (l < r && t < b && trimmed != rect).then_some(trimmed) + } + + /// `style` without the OS title bar and frame (`WS_CAPTION`, which already includes + /// `WS_BORDER`). The sizing border (`WS_THICKFRAME`) stays, so edge resizing and Aero snap + /// keep working, as they did with winit 0.27's undecorated windows. + fn borderless(style: co::WS) -> co::WS { + style & !(co::WS::CAPTION | co::WS::BORDER) + } + + #[cfg(test)] + mod tests { + use super::{Edge, borderless, clamped_rect, short_of_autohide_taskbars, taskbar_edge}; + use winsafe::co; + + #[test] + fn the_borderless_style_drops_the_caption_and_border_only() { + // `WS_CAPTION` is 0x00c0_0000 and already contains `WS_BORDER` (0x0080_0000). + let decorated = co::WS::CAPTION | co::WS::BORDER | co::WS::SYSMENU | co::WS::THICKFRAME | co::WS::MAXIMIZEBOX | co::WS::MINIMIZEBOX; + let bare = borderless(decorated); + assert!(!bare.has(co::WS::CAPTION), "caption gone"); + assert!(!bare.has(co::WS::BORDER), "border gone"); + assert!(bare.has(co::WS::THICKFRAME), "edge resizing kept"); + assert!(bare.has(co::WS::MAXIMIZEBOX) && bare.has(co::WS::SYSMENU), "window buttons kept"); + // Already borderless: unchanged, so the per-frame call does nothing. + assert_eq!(bare.raw(), borderless(bare).raw()); + } + + #[test] + fn a_maximize_respects_taskbars_on_every_edge() { + let monitor = (0, 0, 1920, 1080); + let rect = (-8, -8, 1928, 1088); + for (work, expected) in [ + ((0, 0, 1920, 1046), (-8, -8, 1928, 1054)), + ((0, 48, 1920, 1080), (-8, 40, 1928, 1088)), + ((0, 2, 1920, 1080), (-8, -6, 1928, 1088)), + ((0, 0, 1920, 1078), (-8, -8, 1928, 1086)), + ((48, 0, 1920, 1080), (40, -8, 1928, 1088)), + ((0, 0, 1872, 1080), (-8, -8, 1880, 1088)), + ] { + assert_eq!(clamped_rect(rect, monitor, work), Some(expected)); + assert_eq!(clamped_rect(expected, monitor, work), None, "already corrected"); + } + } + + #[test] + fn a_top_taskbar_keeps_its_offset_at_other_origins_and_frame_sizes() { + let monitor = (-1920, -1080, 0, 0); + let work = (-1920, -1032, 0, 0); + for border in [0, 8, 16, 32] { + let rect = (-1920 - border, -1080 - border, border, border); + let expected = (-1920 - border, -1032 - border, border, border); + assert_eq!(clamped_rect(rect, monitor, work), Some(expected)); + assert_eq!(clamped_rect(expected, monitor, work), None); + } + } + + #[test] + fn a_maximize_without_a_reserved_taskbar_is_left_alone() { + let monitor = (0, 0, 1920, 1080); + assert_eq!(clamped_rect((-8, -8, 1928, 1088), monitor, monitor), None); + } + + #[test] + fn a_maximize_being_dragged_or_snapped_is_left_alone() { + let monitor = (0, 0, 1920, 1080); + let work = (0, 48, 1920, 1080); + assert_eq!(clamped_rect((100, 200, 1100, 900), monitor, work), None, "moved"); + assert_eq!(clamped_rect((-500, -8, 1428, 1088), monitor, work), None, "dragged"); + assert_eq!(clamped_rect((0, 48, 960, 1080), monitor, work), None, "half-screen"); + } + + #[test] + fn a_maximize_leaves_a_pixel_strip_on_an_auto_hidden_taskbar_edge() { + // photocraft#4845: an auto-hidden taskbar reserves no work area. + let monitor = (0, 0, 1920, 1080); + let rect = (-8, -8, 1928, 1088); + for (edge, expected) in [ + (Edge::Bottom, (-8, -8, 1928, 1079)), + (Edge::Top, (-8, 1, 1928, 1088)), + (Edge::Left, (1, -8, 1928, 1088)), + (Edge::Right, (-8, -8, 1919, 1088)), + ] { + assert_eq!(short_of_autohide_taskbars(rect, monitor, monitor, &[edge]), Some(expected)); + assert_eq!(short_of_autohide_taskbars(expected, monitor, monitor, &[edge]), None, "already trimmed"); + } + assert_eq!(short_of_autohide_taskbars(rect, monitor, monitor, &[]), None, "no taskbar"); + // A taskbar that reserves its work area is the clamp's job. + assert_eq!(short_of_autohide_taskbars(rect, monitor, (0, 0, 1920, 1032), &[Edge::Bottom]), None); + assert_eq!(short_of_autohide_taskbars((0, 0, 960, 1080), monitor, monitor, &[Edge::Bottom]), None, "half-screen"); + } + + #[test] + fn a_taskbar_sits_on_the_monitor_edge_nearest_its_centre() { + let monitor = (0, 0, 1920, 1080); + assert_eq!(taskbar_edge((0, 1032, 1920, 1080), monitor), Some(Edge::Bottom), "shown"); + assert_eq!(taskbar_edge((0, 1078, 1920, 1126), monitor), Some(Edge::Bottom), "auto-hidden"); + assert_eq!(taskbar_edge((0, -46, 1920, 2), monitor), Some(Edge::Top)); + assert_eq!(taskbar_edge((-60, 0, 2, 1080), monitor), Some(Edge::Left)); + assert_eq!(taskbar_edge((1918, 0, 1980, 1080), monitor), Some(Edge::Right)); + assert_eq!(taskbar_edge((1920, 1032, 3840, 1080), monitor), None, "other monitor"); + assert!(taskbar_edge((i32::MIN, i32::MIN, i32::MAX, i32::MAX), monitor).is_some(), "no overflow"); + } + } +} + +#[cfg(not(target_os = "windows"))] +mod platform { + use designcraft_ui_egui::WindowFrameFn; + + pub fn service(_cc: &eframe::CreationContext<'_>, _custom_titlebar: bool) -> Option { + None + } +} diff --git a/assets/app-icon/README.md b/assets/app-icon/README.md index e0ee414a0..a1086577a 100644 --- a/assets/app-icon/README.md +++ b/assets/app-icon/README.md @@ -22,10 +22,8 @@ transparent margin. ## Provenance -The owner drew the cat in ArtCraft. The 2880 px drawing, keyed to the three-colour palette, lives -outside this repo in craftrules at `assets/app-icons/designcraft/source.png`. It was vectorised with -craftrules' `assets/logo-options/_tools/vectorize_tile.py`: `designcraft.svg` is traced at 2048 px and -`designcraft-small.svg` at 1024 px. Design rules: craftrules `standards/icon-design.md`. +The owner drew the cat in ArtCraft. `designcraft.svg` is traced from the drawing at 2048 px and +`designcraft-small.svg` at 1024 px. ## Files diff --git a/contributors/people.toml b/contributors/people.toml index 79acd86b0..edae2a69a 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -1,13 +1,10 @@ -# Contributor names for the About window (craftrules standards/contributors.md). +# Contributor names for the About window. # # Everyone who contributes is credited by GitHub username automatically. Anything more is up to # you: add YOUR OWN entry below, in your own PR (commit it yourself). Never add someone else; a # maintainer may add a person only when that person asked, recording where in consent_source. # -# Easiest: python3 ../../craftrules/scripts/contributors.py --add-me . \ -# [--real-name "Ada Lovelace"] [--display-name "Ada"] [--sync-github-name] -# -# Or copy this block, replacing your-github-username (every field is optional): +# Copy this block, replacing your-github-username (every field is optional): # # [people.your-github-username] # real_name = "Your Name" # shown when the viewer picks "Real name" @@ -66,8 +63,34 @@ real_name = "Marco Arnulfo" display_name = "Marco Arnulfo" sync_github_name = false +[people.macrobi] +real_name = "Veress Róbert" +display_name = "Veress Róbert" +sync_github_name = false + [people.4waymedia] real_name = "Paul Gemignani" [people.skylartaylor] display_name = "skylartaylor" + +[people.y-az] +real_name = "Youssef Azriouil" +display_name = "youssef" + +[people.dylanmtaylor] +sync_github_name = true + +[people.Tom-R-Main] +sync_github_name = true + +[people.JonRC] +real_name = "Jonathan Cardoso" +display_name = "Jonathan Cardoso" + +[people.adikshan11] +real_name = "Adithya Shankaran" +sync_github_name = true + +[people.gmrmad1] +real_name = "Madhav Agarwal" diff --git a/crates/color/src/cms/lab.rs b/crates/color/src/cms/lab.rs index 0cbbace7d..5ba921276 100644 --- a/crates/color/src/cms/lab.rs +++ b/crates/color/src/cms/lab.rs @@ -23,7 +23,9 @@ impl Lab { } /// Hue angle in degrees 0..360. pub fn hue(&self) -> f32 { - self.b.atan2(self.a).to_degrees().rem_euclid(360.0) + let h = self.b.atan2(self.a).to_degrees().rem_euclid(360.0); + // f32 rounding can turn a tiny negative angle into exactly 360.0. + if h >= 360.0 { 0.0 } else { h } } pub fn from_lch(l: f32, c: f32, h_deg: f32) -> Self { let h = h_deg.to_radians(); @@ -174,6 +176,13 @@ pub fn delta_e2000(x: Lab, y: Lab) -> f32 { mod tests { use super::*; + #[test] + fn hue_tiny_negative_b_stays_below_360() { + let h = Lab::new(50.0, 10.0, -1e-6).hue(); + assert!((0.0..360.0).contains(&h), "hue {h}"); + assert_eq!(h, 0.0); + } + #[test] fn white_and_black() { let w = srgb_to_lab([1.0, 1.0, 1.0]); diff --git a/crates/color/src/gradient.rs b/crates/color/src/gradient.rs index 6243101ef..be3ce9543 100644 --- a/crates/color/src/gradient.rs +++ b/crates/color/src/gradient.rs @@ -72,23 +72,45 @@ impl Default for Gradient { impl Gradient { /// Colour and opacity at `t` (honours midpoints). pub fn sample(&self, t: f32) -> (Color, f32) { + self.sample_in(None, t) + } + + /// For each window `(stops[k], stops[k + 1])`, the largest end offset of windows `0..=k`: the + /// first window whose end reaches `t` is the first `k` where this does, so a binary search + /// finds it (stops in any order). + fn window_ends(&self) -> Vec { + let mut end = f32::NAN; + self.stops + .iter() + .skip(1) + .map(|s| { + end = end.max(s.offset); + end + }) + .collect() + } + + /// [`Self::sample`], with [`Self::window_ends`] given when it was worked out once (else a scan). + fn sample_in(&self, ends: Option<&[f32]>, t: f32) -> (Color, f32) { let stops = &self.stops; - if stops.is_empty() { + let Some(first) = stops.first() else { return (Color::BLACK, 1.0); + }; + if t <= first.offset { + return (first.color, first.opacity); } - if t <= stops[0].offset { - return (stops[0].color, stops[0].opacity); - } - for w in stops.windows(2) { - let (a, b) = (&w[0], &w[1]); - if t <= b.offset { - let span = (b.offset - a.offset).max(1e-6); - let u = (t - a.offset) / span; - // Map through the midpoint: u=mid → 0.5. - let m = a.midpoint.clamp(0.01, 0.99); - let v = if u < m { 0.5 * u / m } else { 0.5 + 0.5 * (u - m) / (1.0 - m) }; - return (a.color.lerp(&b.color, v), a.opacity + (b.opacity - a.opacity) * v); - } + // The first window whose end offset is at or past `t` (none for a NaN `t`). + let k = match ends { + None => stops.windows(2).position(|w| t <= w[1].offset).unwrap_or(stops.len()), + Some(ends) => ends.partition_point(|e| matches!(e.partial_cmp(&t), None | Some(std::cmp::Ordering::Less))), + }; + if let (Some(a), Some(b)) = (stops.get(k), stops.get(k + 1)) { + let span = (b.offset - a.offset).max(1e-6); + let u = (t - a.offset) / span; + // Map through the midpoint: u=mid → 0.5. + let m = a.midpoint.clamp(0.01, 0.99); + let v = if u < m { 0.5 * u / m } else { 0.5 + 0.5 * (u - m) / (1.0 - m) }; + return (a.color.lerp(&b.color, v), a.opacity + (b.opacity - a.opacity) * v); } match stops.last() { Some(l) => (l.color, l.opacity), @@ -97,14 +119,16 @@ impl Gradient { } /// Stops expanded so that midpoints are represented as explicit stops (for renderers without midpoints). pub fn expanded_stops(&self) -> Vec<(f32, Color, f32)> { + let ends = self.window_ends(); let mut out = Vec::new(); for (i, s) in self.stops.iter().enumerate() { out.push((s.offset, s.color, s.opacity)); + let mid = s.midpoint.clamp(0.01, 0.99); if let Some(n) = self.stops.get(i + 1) - && (s.midpoint - 0.5).abs() > 1e-3 + && (mid - 0.5).abs() > 1e-3 { - let t = s.offset + (n.offset - s.offset) * s.midpoint; - let (c, o) = self.sample(t); + let t = s.offset + (n.offset - s.offset) * mid; + let (c, o) = self.sample_in(Some(&ends), t); out.push((t, c, o)); } } @@ -115,6 +139,7 @@ impl Gradient { pub fn display_stops(&self) -> Vec<(f32, Color, f32)> { const STEPS: usize = 16; let stops = self.expanded_stops(); + let ends = self.window_ends(); let mut out: Vec<(f32, Color, f32)> = Vec::with_capacity(stops.len() * STEPS); for (i, s) in stops.iter().enumerate() { out.push(*s); @@ -124,7 +149,7 @@ impl Gradient { } for j in 1..STEPS { let t = s.0 + (n.0 - s.0) * j as f32 / STEPS as f32; - let (c, a) = self.sample(t); + let (c, a) = self.sample_in(Some(&ends), t); out.push((t, c, a)); } } @@ -215,8 +240,71 @@ impl GradientPaint { #[cfg(test)] mod tests { + /// The sampler as it was: the first window whose end reaches `t`, by a scan. + fn sample_by_scan(g: &super::Gradient, t: f32) -> (super::Color, f32) { + let stops = &g.stops; + if stops.is_empty() { + return (super::Color::BLACK, 1.0); + } + if t <= stops[0].offset { + return (stops[0].color, stops[0].opacity); + } + for w in stops.windows(2) { + let (a, b) = (&w[0], &w[1]); + if t <= b.offset { + let span = (b.offset - a.offset).max(1e-6); + let u = (t - a.offset) / span; + let m = a.midpoint.clamp(0.01, 0.99); + let v = if u < m { 0.5 * u / m } else { 0.5 + 0.5 * (u - m) / (1.0 - m) }; + return (a.color.lerp(&b.color, v), a.opacity + (b.opacity - a.opacity) * v); + } + } + stops.last().map_or((super::Color::BLACK, 1.0), |l| (l.color, l.opacity)) + } + + /// The search finds the window the scan found, for stops in order, out of order, repeated + /// and NaN; and many stops expand in linear time. + #[test] + fn sampling_by_search_matches_the_scan() { + use super::{Color, Gradient, GradientKind, GradientStop}; + let offsets = [0.0, 0.3, 0.2, 0.2, f32::NAN, 0.9, 0.5, 1.0, 0.95]; + let stops: Vec = offsets + .iter() + .enumerate() + .map(|(i, &o)| GradientStop { midpoint: 0.3, ..GradientStop::new(o, Color::rgb8((i * 25) as u8, 0, 255 - (i * 25) as u8)) }) + .collect(); + for n in 0..=stops.len() { + let g = Gradient { kind: GradientKind::Linear, stops: stops[..n].to_vec() }; + for t in [-1.0, 0.0, 0.1, 0.2, 0.25, 0.3, 0.6, 0.9, 0.93, 1.0, 2.0, f32::NAN, f32::INFINITY] { + // Compared as printed: a NaN offset gives NaN components on both sides. + let a = format!("{:?}", g.sample_in(Some(&g.window_ends()), t)); + let b = format!("{:?}", sample_by_scan(&g, t)); + assert_eq!(format!("{:?}", g.sample(t)), b, "{n} stops at {t} (scan)"); + assert_eq!(a, b, "{n} stops at {t}"); + } + } + let many = Gradient { + kind: GradientKind::Linear, + stops: (0..100_000).map(|i| GradientStop { midpoint: 0.3, ..GradientStop::new(i as f32 / 100_000.0, Color::BLACK) }).collect(), + }; + let t = std::time::Instant::now(); + assert_eq!(many.expanded_stops().len(), 199_999); + assert!(t.elapsed() < std::time::Duration::from_secs(2), "{:?}", t.elapsed()); + } + use super::*; + #[test] + fn expanded_stops_clamp_out_of_range_midpoint() { + for mid in [2.0, -1.0] { + let mut g = Gradient::default(); + g.stops[0].midpoint = mid; + let offsets: Vec = g.expanded_stops().iter().map(|s| s.0).collect(); + assert!(offsets.windows(2).all(|w| w[0] <= w[1]), "{offsets:?}"); + assert!(offsets.iter().all(|o| (0.0..=1.0).contains(o)), "{offsets:?}"); + } + } + #[test] fn sample_endpoints_and_mid() { let g = Gradient::default(); diff --git a/crates/color/src/lib.rs b/crates/color/src/lib.rs index d085c5c48..c83d93f0c 100644 --- a/crates/color/src/lib.rs +++ b/crates/color/src/lib.rs @@ -118,6 +118,8 @@ impl Color { } else { 60.0 * ((r - g) / d + 4.0) }; + // A tiny negative `rem_euclid` input can round up to exactly 6.0 (hue 360). + let h = if h >= 360.0 { 0.0 } else { h }; let s = if max <= 0.0 { 0.0 } else { d / max }; [h, s, max] } @@ -251,6 +253,12 @@ impl Paint { mod tests { use super::*; + #[test] + fn hsb_hue_stays_below_360() { + let h = Color::rgb(1.0, 0.0, 1e-8).to_hsb()[0]; + assert!((0.0..360.0).contains(&h), "hue {h}"); + } + #[test] fn hex_roundtrip() { let c = Color::from_hex("#ff8000").unwrap(); diff --git a/crates/color/src/swatch.rs b/crates/color/src/swatch.rs index e47bf4eef..1847a4134 100644 --- a/crates/color/src/swatch.rs +++ b/crates/color/src/swatch.rs @@ -96,7 +96,9 @@ pub fn value_name(c: Color) -> String { Color::Cmyk { c, m, y, k } => cmyk_name(c, m, y, k), other => { let [r, g, b] = other.to_rgb(); - format!("R={} G={} B={}", (r * 255.0).round(), (g * 255.0).round(), (b * 255.0).round()) + // `+ 0.0` turns -0.0 into 0.0 so it prints as "0", not "-0". + let p = |v: f32| (v * 255.0).round() + 0.0; + format!("R={} G={} B={}", p(r), p(g), p(b)) } } } @@ -143,7 +145,9 @@ pub fn apply_tint(c: Color, tint: f32) -> Color { } } -/// A new document's swatches, in panel order. +/// A new document's swatches, in panel order: InDesign's four specials, then its six process +/// colours (cyan, magenta, yellow, red, green and blue as C=15 M=100 Y=100, C=75 M=5 Y=100 and +/// C=100 M=90 Y=10). pub fn default_swatches() -> Vec { let special = |name: &str, value: SwatchValue| Swatch { name: name.into(), value, locked: true, named: true, hidden: false }; let mut v = vec![ @@ -152,17 +156,9 @@ pub fn default_swatches() -> Vec { special(PAPER, SwatchValue::Paper { color: Color::WHITE }), special(BLACK, SwatchValue::Color { color: Color::cmyk(0.0, 0.0, 0.0, 1.0), color_type: ColorType::Process }), ]; - for (c, m, y, k) in [ - (1.0, 0.0, 0.0, 0.0), - (0.0, 1.0, 0.0, 0.0), - (0.0, 0.0, 1.0, 0.0), - (0.0, 1.0, 1.0, 0.0), - (1.0, 0.0, 1.0, 0.0), - (1.0, 1.0, 0.0, 0.0), - (0.15, 1.0, 1.0, 0.0), - (0.75, 0.05, 1.0, 0.0), - (1.0, 0.9, 0.1, 0.0), - ] { + for (c, m, y, k) in + [(1.0, 0.0, 0.0, 0.0), (0.0, 1.0, 0.0, 0.0), (0.0, 0.0, 1.0, 0.0), (0.15, 1.0, 1.0, 0.0), (0.75, 0.05, 1.0, 0.0), (1.0, 0.9, 0.1, 0.0)] + { v.push(Swatch::cmyk(c, m, y, k)); } v @@ -172,6 +168,11 @@ pub fn default_swatches() -> Vec { mod tests { use super::*; + #[test] + fn value_name_has_no_negative_zero() { + assert_eq!(value_name(Color::rgb(-0.001, 0.5, 1.0)), "R=0 G=128 B=255"); + } + #[test] fn defaults_start_with_specials() { let s = default_swatches(); @@ -181,6 +182,27 @@ mod tests { assert!(s.iter().any(|s| s.name == "C=100 M=0 Y=0 K=0")); } + /// The Swatches panel of a new InDesign document (Zero2Graphic's page layout tutorial, 3:22). + #[test] + fn defaults_are_indesigns_ten() { + let names: Vec = default_swatches().into_iter().map(|s| s.name).collect(); + assert_eq!( + names, + [ + "[None]", + "[Registration]", + "[Paper]", + "[Black]", + "C=100 M=0 Y=0 K=0", + "C=0 M=100 Y=0 K=0", + "C=0 M=0 Y=100 K=0", + "C=15 M=100 Y=100 K=0", + "C=75 M=5 Y=100 K=0", + "C=100 M=90 Y=10 K=0", + ] + ); + } + #[test] fn resolves_tints_and_specials() { let mut s = default_swatches(); diff --git a/crates/compose/Cargo.toml b/crates/compose/Cargo.toml index b7017f80f..cd34918aa 100644 --- a/crates/compose/Cargo.toml +++ b/crates/compose/Cargo.toml @@ -21,7 +21,7 @@ log = { workspace = true } regex = { workspace = true } fancy-regex = { workspace = true } miniz_oxide = "0.8" -hypher = { version = "0.1.8", default-features = false, features = ["alloc", "greek", "portuguese", "spanish", "norwegian"] } +hypher = { version = "0.1.8", default-features = false, features = ["alloc", "dutch", "french", "german", "greek", "italian", "portuguese", "spanish", "norwegian", "danish"] } [dev-dependencies] designcraft-fonts = { workspace = true, features = ["testing"] } diff --git a/crates/compose/src/breaker.rs b/crates/compose/src/breaker.rs index 9b453ff0a..bd9351119 100644 --- a/crates/compose/src/breaker.rs +++ b/crates/compose/src/breaker.rs @@ -53,8 +53,12 @@ pub struct Spacing { pub optical_size: Option, /// Korean text breaks between syllables instead of at spaces. pub korean_char_breaks: bool, - /// 0: minimum adjustment; 1: push in; 2: push out first; 3: push out only. + /// JIS X 4051 禁則処理 type: 0: minimum adjustment (調整量優先); 1: push in first (追い込み + /// 優先, the default); 2: push out first (追い出し優先); 3: push out only (追い出しのみ). pub kinsoku_priority: u8, + /// The paragraph has CJK text, so the 禁則 priority biases its breaks. A Latin paragraph's + /// breaks are left alone by the (default) push-in-first policy. + pub kinsoku_cjk: bool, } impl Default for Spacing { @@ -77,19 +81,25 @@ impl Default for Spacing { optical: false, optical_size: None, korean_char_breaks: false, - kinsoku_priority: 0, + kinsoku_priority: 1, + kinsoku_cjk: false, } } } impl Spacing { + /// Push out only: the 追い込み (compression that would pull the next character in) is + /// unavailable, so every line end is pushed out (and no line is compressed at its end). + pub(crate) fn push_out_only(&self) -> bool { + self.kinsoku_cjk && self.kinsoku_priority == 3 + } /// Per-tier (word, letter, glyph) stretch and shrink of glyph `g` as a box. fn box_elastic(&self, g: &Glyph) -> ([f64; 3], [f64; 3]) { if g.locked_advance { return ([0.0; 3], [0.0; 3]); } let moji_stretch = if self.justify { g.moji.stretch } else { 0.0 }; - let moji_shrink = if self.kinsoku_priority == 3 { 0.0 } else { g.moji.shrink }; + let moji_shrink = if self.push_out_only() { 0.0 } else { g.moji.shrink }; if !self.justify { return ([0.0; 3], [moji_shrink, 0.0, 0.0]); } @@ -276,13 +286,18 @@ fn kinsoku_allows(a: char, b: char) -> bool { !NO_START.contains(b) && !NO_END.contains(a) } +/// Hangul: Jamo, compatibility Jamo, the syllables, and Jamo Extended-A/B. Shared with the +/// paragraph's CJK gate so the two classifications cannot drift apart. +pub(crate) fn is_hangul(c: char) -> bool { + matches!(c as u32, 0x1100..=0x11FF | 0x3130..=0x318F | 0xA960..=0xA97F | 0xAC00..=0xD7FF) +} + /// Hangul, and Han ideographs (hanja) in Korean text: Korean is set word by word (KLREQ), so /// these letters break like Western ones, at spaces. fn korean_letter(g: &Glyph) -> bool { - let c = g.ch as u32; - let hangul = matches!(c, 0x1100..=0x11FF | 0x3130..=0x318F | 0xA960..=0xA97F | 0xAC00..=0xD7FF); - let han = matches!(c, 0x3400..=0x4DBF | 0x4E00..=0x9FFF | 0xF900..=0xFAFF | 0x20000..=0x3FFFF); - hangul || (han && g.lang.is_some_and(|t| designcraft_doc::language_subtag(t) == "ko")) + let c = g.ch; + let han = matches!(c as u32, 0x3400..=0x4DBF | 0x4E00..=0x9FFF | 0xF900..=0xFAFF | 0x20000..=0x3FFFF); + is_hangul(c) || (han && g.lang.is_some_and(|t| designcraft_doc::language_subtag(t) == "ko")) } /// Is the place between glyphs `a` and `b` one where CJK text may break (next to an ideograph, kana @@ -395,7 +410,14 @@ fn items(glyphs: &[Glyph], hyph_after: &[bool], emergency_after: &[bool], sp: &S for i in (0..n).rev() { hangs[i] = glyphs[i].is_space() && glyphs.get(i + 1).is_none_or(|nx| hangs[i + 1] || is_forced(nx.ch)); } + // The last glyph that isn't a soft hyphen, kept as the loop goes (a run of soft hyphens + // searched back over all of them for every one). + let mut last_plain: Option<&Glyph> = None; for (i, g) in glyphs.iter().enumerate() { + // Set before the soft-hyphen case below reads it; a soft hyphen leaves it as it was. + if g.ch != SOFT_HYPHEN { + last_plain = Some(g); + } let prev_hang = if i > 0 { right_hang(&glyphs[i - 1], sp) } else { 0.0 }; if hangs[i] { continue; @@ -406,7 +428,7 @@ fn items(glyphs: &[Glyph], hyph_after: &[bool], emergency_after: &[bool], sp: &S let mut p = Item::penalty(0.0, -INF, false); p.hang = prev_hang; if let Some(prev) = i.checked_sub(1).and_then(|j| glyphs.get(j)) { - p.edge_elastic = crate::mojikumi::end_elastic(prev, sp.justify, sp.kinsoku_priority != 3); + p.edge_elastic = crate::mojikumi::end_elastic(prev, sp.justify, !sp.push_out_only()); } it.push(p); ig.push(i + 1); @@ -420,7 +442,7 @@ fn items(glyphs: &[Glyph], hyph_after: &[bool], emergency_after: &[bool], sp: &S let mut gl = Item::glue(w, st, sh); gl.hang = prev_hang; if let Some(prev) = i.checked_sub(1).and_then(|j| glyphs.get(j)) { - gl.edge_elastic = crate::mojikumi::end_elastic(prev, sp.justify, sp.kinsoku_priority != 3); + gl.edge_elastic = crate::mojikumi::end_elastic(prev, sp.justify, !sp.push_out_only()); } gl.over = sp.space_overflow(g); last_space = it.len(); @@ -433,7 +455,7 @@ fn items(glyphs: &[Glyph], hyph_after: &[bool], emergency_after: &[bool], sp: &S let mut p = Item::penalty(0.0, 0.0, false); p.hang = prev_hang; if let Some(prev) = i.checked_sub(1).and_then(|j| glyphs.get(j)) { - p.edge_elastic = crate::mojikumi::end_elastic(prev, sp.justify, sp.kinsoku_priority != 3); + p.edge_elastic = crate::mojikumi::end_elastic(prev, sp.justify, !sp.push_out_only()); } last_space = it.len(); it.push(p); @@ -444,7 +466,7 @@ fn items(glyphs: &[Glyph], hyph_after: &[bool], emergency_after: &[bool], sp: &S continue; } if g.ch == SOFT_HYPHEN { - let hw = glyphs[..i].iter().rev().find(|g| g.ch != SOFT_HYPHEN).map_or(g.size * 0.33, |p| hyphen_width(p, &mut hy_cache)); + let hw = last_plain.map_or(g.size * 0.33, |p| hyphen_width(p, &mut hy_cache)); let mut p = Item::penalty(hw, sp.hyphen_penalty, true); p.auto = true; p.zone_from = last_space; @@ -455,7 +477,7 @@ fn items(glyphs: &[Glyph], hyph_after: &[bool], emergency_after: &[bool], sp: &S let (st, sh) = sp.box_elastic(g); let mut bx = Item::boxed(g.adv, st, sh); bx.hang = hang_left(g, sp) - g.moji.start; - bx.start_elastic = crate::mojikumi::start_elastic(g, sp.justify, sp.kinsoku_priority != 3); + bx.start_elastic = crate::mojikumi::start_elastic(g, sp.justify, !sp.push_out_only()); it.push(bx); ig.push(i); let next_is_space = glyphs.get(i + 1).is_none_or(|n| n.is_space()); @@ -463,12 +485,12 @@ fn items(glyphs: &[Glyph], hyph_after: &[bool], emergency_after: &[bool], sp: &S if matches!(g.ch, '-' | '\u{2010}') { let mut p = Item::penalty(0.0, 50.0, true); p.hang = right_hang(g, sp); - p.edge_elastic = crate::mojikumi::end_elastic(g, sp.justify, sp.kinsoku_priority != 3); + p.edge_elastic = crate::mojikumi::end_elastic(g, sp.justify, !sp.push_out_only()); push_inword(&mut it, &mut ig, p, i + 1, sp); } else if matches!(g.ch, '\u{2013}' | '\u{2014}' | '/') || g.break_after.unwrap_or_else(|| cjk_break(g, &glyphs[i + 1], sp)) { let mut p = Item::penalty(0.0, 0.0, false); p.hang = right_hang(g, sp); - p.edge_elastic = crate::mojikumi::end_elastic(g, sp.justify, sp.kinsoku_priority != 3); + p.edge_elastic = crate::mojikumi::end_elastic(g, sp.justify, !sp.push_out_only()); push_inword(&mut it, &mut ig, p, i + 1, sp); } else if hyph_after[i] { let hw = hyphen_width(g, &mut hy_cache); @@ -490,7 +512,7 @@ fn items(glyphs: &[Glyph], hyph_after: &[bool], emergency_after: &[bool], sp: &S let mut p = Item::penalty(0.0, -INF, false); p.hang = if n > 0 { right_hang(&glyphs[n - 1], sp) } else { 0.0 }; if let Some(g) = glyphs.last() { - p.edge_elastic = crate::mojikumi::end_elastic(g, sp.justify, sp.kinsoku_priority != 3); + p.edge_elastic = crate::mojikumi::end_elastic(g, sp.justify, !sp.push_out_only()); } it.push(p); ig.push(n); @@ -631,11 +653,19 @@ fn hyphen_allowed(it: Item, n: Node, sp: &Spacing, widths: &[f64], items: &[Item } /// Fitness class and cumulative penalty for a candidate line break. -fn break_demerits(n: Node, r: f64, pp: f64, flagged: bool, priority: u8) -> (usize, f64) { - let preference = match priority { - 1 if r > 0.0 => 4.0, - 2 if r < 0.0 => 4.0, - _ => 1.0, +fn break_demerits(n: Node, r: f64, pp: f64, flagged: bool, priority: u8, cjk: bool) -> (usize, f64) { + // 禁則 priority (JIS X 4051): push-in-first rates breaks whose line would have to be + // stretched (r > 0: the next character is pushed out) worse than ones it can reach by + // compressing (追い込み); push-out-first the other way. Adjustment-amount mode and a + // paragraph without CJK text rate every candidate by its adjustment alone. + let preference = if !cjk { + 1.0 + } else { + match priority { + 1 if r > 0.0 => 4.0, + 2 if r < 0.0 => 4.0, + _ => 1.0, + } }; let bad = preference * 100.0 * r.abs().powi(3); let lp = 10.0 + bad; @@ -763,7 +793,7 @@ fn kp_pass(input: PassInput<'_>) -> Option> { if flagged && !hyphen_allowed(it, n, sp, &sw, items, target) { continue; } - let (fit, total) = break_demerits(n, r, pp, flagged, sp.kinsoku_priority); + let (fit, total) = break_demerits(n, r, pp, flagged, sp.kinsoku_priority, sp.kinsoku_cjk); let hs = if flagged { (n.hyphens as usize + 1).min(states - 1) } else { 0 }; let slot = &mut best[fit * states + hs]; if slot.is_none_or(|(bd, _)| total < bd) { @@ -918,7 +948,7 @@ pub fn greedy( while start < n { let w = width(line).max(1.0); let mut x = -hang_left(&glyphs[start], sp) + glyphs[start].moji.start; - let mut shrink = crate::mojikumi::start_elastic(&glyphs[start], sp.justify, sp.kinsoku_priority != 3)[1]; + let mut shrink = crate::mojikumi::start_elastic(&glyphs[start], sp.justify, !sp.push_out_only())[1]; let mut last_natural: Option<(usize, bool)> = None; let mut last_ok: Option<(usize, bool)> = None; // (break position = end glyph, hyphen) let mut last_space: Option<(usize, f64)> = None; // (break position, line width there) @@ -945,9 +975,10 @@ pub fn greedy( } let hang_r = right_hang(g, sp); let adv = if g.ch == '\t' { tab(line, x, i) } else { g.adv }; - let end_shrink = crate::mojikumi::end_elastic(g, sp.justify, sp.kinsoku_priority != 3)[1]; + let end_shrink = crate::mojikumi::end_elastic(g, sp.justify, !sp.push_out_only())[1]; let available = shrink + sp.box_elastic(g).1.iter().sum::() + end_shrink; - if sp.kinsoku_priority == 2 + if sp.kinsoku_cjk + && sp.kinsoku_priority == 2 && x + adv - hang_r > w + FIT_EPS && let Some((end, hyphen)) = last_natural { @@ -972,7 +1003,15 @@ pub fn greedy( x += adv; shrink += sp.box_elastic(g).1.iter().sum::(); if i + 1 < n && !glyphs[i + 1].is_space() && !g.no_break && g.break_after != Some(false) { - if matches!(g.ch, '-' | '\u{2010}' | '\u{2013}' | '\u{2014}' | '/') + if g.ch == SOFT_HYPHEN { + if may_hyphenate(hyphens) { + let hw = hyphen_width(g, &mut hy_cache); + let hy = (hw - hyphen_hang(g, hw, sp)).max(0.0); + if x + hy <= w + shrink + FIT_EPS { + last_ok = Some((i + 1, true)); + } + } + } else if matches!(g.ch, '-' | '\u{2010}' | '\u{2013}' | '\u{2014}' | '/') || g.break_after.unwrap_or_else(|| cjk_break(g, &glyphs[i + 1], sp)) { last_ok = Some((i + 1, false)); diff --git a/crates/compose/src/cache.rs b/crates/compose/src/cache.rs index 66122ccf4..b46f6ad9a 100644 --- a/crates/compose/src/cache.rs +++ b/crates/compose/src/cache.rs @@ -5,13 +5,19 @@ //! wrapping item on the frames' spreads, and the same for every story whose anchored objects wrap //! its text ([`crate::wrap::neighbours`]). An anchored frame's entry also records where its host //! story's composition places it. Entries hold clones of those `Arc`s, so the pointers -//! can't be reused by other allocations while the entry lives. +//! can't be reused by other allocations while the entry lives. The document's Alpha Channel +//! outlines count by serial number, which no other outline shares. +//! +//! When only the story itself differs from an entry's (an edit of its text or formatting), the +//! new composition starts from the entry's and composes the paragraphs the edit can change +//! ([`crate::reuse`]). -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; use std::sync::{Arc, Mutex, PoisonError}; use designcraft_doc::{Document, Item, Story, StoryId, Styles}; +use crate::reuse::{Reuse, Trace}; use crate::vars::RunningIndex; use crate::{ComposeOptions, ComposedStory}; @@ -39,11 +45,36 @@ impl From> for ShownOn { /// (`true`) or not. type Key = (StoryId, ShownOn, bool); +/// The hosts and wrap neighbours already resolved while answering one [`Cache::get_on`], by +/// story, whether other stories wrap it, and depth. A story reached from many others (frames of +/// many stories anchored in it, at several levels) is resolved once instead of once per path to +/// it. +type Resolved = HashMap<(StoryId, bool, usize), Arc>; + struct Entry { sig: Vec, _keep: (Arc, Arc, Vec>, Vec>), out: Arc, stamp: u64, + /// For composing the story again after an edit ([`crate::reuse`]). + trace: Option>, +} + +/// The story an entry was composed from, its composition and that composition's trace. +type Before = (Arc, Arc, Arc); + +/// How many leading values of a [`signature`] identify the story's own allocation and revision; +/// the rest is everything else the composition was made from. +const STORY_SIG: usize = 2; + +impl Entry { + /// What composing for `sig` can take from this entry: set when only the story itself differs + /// (an edit of its text or formatting) and the entry's composition left a trace. + fn before(&self, sig: &[usize]) -> Option { + let trace = self.trace.as_ref()?; + (self.sig.len() == sig.len() && self.sig.get(STORY_SIG..) == sig.get(STORY_SIG..)) + .then(|| (self._keep.0.clone(), self.out.clone(), trace.clone())) + } } #[derive(Default)] @@ -56,6 +87,17 @@ pub struct Cache { /// The composition each story (page-independent key) had before its latest recomposition, /// with the story revision it was composed from (repaint only the frames an edit changed). previous: Mutex, Arc)>>, + /// A cache this one reads without writing to: a composition or index found there for the same + /// inputs is used, and anything composed is kept here only. + base: Option>, +} + +/// A signature's hash, standing in for it in another story's signature. +fn hash_of(sig: &[usize]) -> usize { + use std::hash::{Hash, Hasher}; + let mut h = std::collections::hash_map::DefaultHasher::new(); + sig.hash(&mut h); + h.finish() as usize } /// Identity of everything a running header can depend on (stories, spreads, styles, variables). @@ -71,6 +113,21 @@ fn doc_signature(doc: &Document) -> u64 { (Arc::as_ptr(&doc.styles) as usize).hash(&mut h); format!("{:?}", doc.text_variables).hash(&mut h); sections_hash(doc).hash(&mut h); + // The compositions the indexes are built from also depend on these (see `signature`). + let g = &doc.settings.baseline_grid; + (doc.font_scope, g.relative_to == designcraft_doc::GridRelative::TopMargin, g.start.to_bits(), g.increment.to_bits()).hash(&mut h); + outlines_hash(doc).hash(&mut h); + h.finish() +} + +/// The Alpha Channel outlines text wraps around: a relink traces a new one while the items and +/// stories stay the same. +fn outlines_hash(doc: &Document) -> u64 { + use std::hash::{Hash, Hasher}; + let mut h = std::collections::hash_map::DefaultHasher::new(); + for o in &doc.alpha_outlines { + o.serial.hash(&mut h); + } h.finish() } @@ -90,6 +147,18 @@ impl Cache { Self::default() } + /// An empty cache that also uses what `base` holds for the same inputs, and never changes + /// `base`. A reader of an older state of the document composes that state here instead of + /// replacing the compositions of the current state in `base`. + pub fn over(base: Arc) -> Self { + Cache { base: Some(base), ..Self::default() } + } + + /// The cache given to [`Cache::over`]. + pub fn base(&self) -> Option<&Arc> { + self.base.as_ref() + } + /// The composed story, from cache or freshly composed. `page` is the absolute page a /// parent-page item is shown on (its page number markers and variables are that page's), or /// `None` for a story's own frames. Pages are identified by index, not name: names repeat when @@ -100,29 +169,52 @@ impl Cache { /// [`Cache::get`] for any [`ShownOn`]. pub fn get_on(&self, doc: &Document, sid: StoryId, on: ShownOn) -> Arc { - self.get_with(doc, sid, on, true, 0) + self.get_with(doc, sid, on, true, 0, &mut Resolved::new()) + } + + /// [`Cache::get_with`] for a host or a wrap neighbour (shown in its own frames), once per + /// traversal. + fn resolve(&self, doc: &Document, sid: StoryId, cross: bool, depth: usize, resolved: &mut Resolved) -> Arc { + if let Some(c) = resolved.get(&(sid, cross, depth)) { + return c.clone(); + } + let c = self.get_with(doc, sid, ShownOn::Own, cross, depth, resolved); + resolved.insert((sid, cross, depth), c.clone()); + c + } + + /// Where the host story places anchored text frame `fid`, one of story `sid`'s frames; `None` for + /// a frame on a spread. + pub fn placement(&self, doc: &Document, sid: StoryId, fid: designcraft_doc::ItemId) -> Option { + let mut resolved = Resolved::new(); + let placed = crate::placed::placements(doc, sid, &mut |host| self.resolve(doc, host, true, 1, &mut resolved)); + placed.into_iter().find_map(|(id, p)| (id == fid).then_some(p)) } /// [`Cache::get_on`], wrapped by other stories' anchored objects only when `cross` is set, for /// a story `depth` hosts down from the story asked for. - fn get_with(&self, doc: &Document, sid: StoryId, on: ShownOn, cross: bool, depth: usize) -> Arc { + fn get_with(&self, doc: &Document, sid: StoryId, on: ShownOn, cross: bool, depth: usize, resolved: &mut Resolved) -> Arc { let Some(story) = doc.stories.get(&sid) else { return Arc::new(ComposedStory { story: sid, ..Default::default() }) }; let (mut sig, mut keep_items) = signature(doc, story); let neighbours = if cross { crate::wrap::neighbours(doc, sid) } else { Vec::new() }; let mut keep_stories = Vec::new(); + // A neighbour's signature goes in as its hash, and its items only once each: stories on + // one spread share its wrapping items, so copying every neighbour's whole signature and + // items made each entry as large as all of theirs together. + let mut kept: HashSet<*const Item> = keep_items.iter().map(Arc::as_ptr).collect(); for n in &neighbours { if let Some(ns) = doc.stories.get(n) { let (s, k) = signature(doc, ns); sig.push(usize::MAX - 1); - sig.extend(s); - keep_items.extend(k); + sig.push(hash_of(&s)); + keep_items.extend(k.into_iter().filter(|it| kept.insert(Arc::as_ptr(it)))); keep_stories.push(ns.clone()); } } // Anchored frames compose where their host story places them, so the host is composed // first and the placements are part of the signature. let placed = if depth < crate::placed::MAX_DEPTH { - crate::placed::placements(doc, sid, &mut |host| self.get_with(doc, host, ShownOn::Own, true, depth + 1)) + crate::placed::placements(doc, sid, &mut |host| self.resolve(doc, host, true, depth + 1, resolved)) } else { Vec::new() }; @@ -215,33 +307,46 @@ impl Cache { std::hash::Hash::hash(&doc.list_start(sid, &l.name), &mut h); sig.push(std::hash::Hasher::finish(&h) as usize); } - { + let before = { let mut g = self.map.lock().unwrap_or_else(PoisonError::into_inner); g.1 += 1; let stamp = g.1; - if let Some(e) = g.0.get_mut(&key) + match g.0.get_mut(&key) { + Some(e) if e.sig == sig => { + e.stamp = stamp; + return e.out.clone(); + } + Some(e) => e.before(&sig), + None => None, + } + }; + if let Some(base) = &self.base { + let g = base.map.lock().unwrap_or_else(PoisonError::into_inner); + if let Some(e) = g.0.get(&key) && e.sig == sig { - e.stamp = stamp; return e.out.clone(); } } // Parent-page items are composed per page: markers show its name, variables need its index. let page = page.filter(|_| with_vars); let running = running.then(|| self.running_index(doc)); - let others: Vec> = neighbours.iter().map(|n| self.neighbour(doc, *n, depth)).collect(); - let out = Arc::new(crate::wrap::compose_among( + let others: Vec> = neighbours.iter().map(|n| self.neighbour(doc, *n, depth, resolved)).collect(); + let (out, trace) = crate::wrap::compose_among_traced( doc, sid, &ComposeOptions { page_name, section_marker, page, running, label: None, xrefs: with_xrefs.then(|| self.xref_index(doc)), placed }, &others.iter().map(|o| &**o).collect::>(), - )); + before.as_ref().map(|(story, composed, trace)| Reuse { story, composed, trace }), + ); + let (out, trace) = (Arc::new(out), trace.map(Arc::new)); let mut g = self.map.lock().unwrap_or_else(PoisonError::into_inner); let stamp = g.1; if g.0.len() > 4096 { g.0.retain(|_, e| stamp - e.stamp < 64); } - let replaced = g.0.insert(key, Entry { sig, _keep: (story.clone(), doc.styles.clone(), keep_items, keep_stories), out: out.clone(), stamp }); + let replaced = + g.0.insert(key, Entry { sig, _keep: (story.clone(), doc.styles.clone(), keep_items, keep_stories), out: out.clone(), stamp, trace }); drop(g); // Only the composition that is shown (not one made for another story's wrap). if key.1 == ShownOn::Own @@ -315,13 +420,13 @@ impl Cache { /// Story `sid` composed for the wrap of its anchored objects in other stories: without other /// stories' anchored objects (no cycles), and outside the cache when it needs the document-wide /// indexes (they compose every story). - fn neighbour(&self, doc: &Document, sid: StoryId, depth: usize) -> Arc { + fn neighbour(&self, doc: &Document, sid: StoryId, depth: usize, resolved: &mut Resolved) -> Arc { let indexed = doc.stories.get(&sid).is_some_and(|st| crate::xref::has_xrefs(st) || (crate::vars::has_vars(st) && crate::vars::has_running(doc, st))); if indexed { Arc::new(crate::wrap::compose_among(doc, sid, &ComposeOptions::default(), &[])) } else { - self.get_with(doc, sid, ShownOn::Own, false, depth) + self.resolve(doc, sid, false, depth, resolved) } } @@ -339,6 +444,12 @@ impl Cache { { return r.clone(); } + if let Some(base) = &self.base + && let Some((s, r)) = &*base.xrefs.lock().unwrap_or_else(PoisonError::into_inner) + && *s == sig + { + return r.clone(); + } let r = Arc::new(crate::xref::XrefIndex::build(doc, &|sid| self.get(doc, sid, None))); *self.xrefs.lock().unwrap_or_else(PoisonError::into_inner) = Some((sig, r.clone())); r @@ -352,6 +463,12 @@ impl Cache { { return r.clone(); } + if let Some(base) = &self.base + && let Some((s, r)) = &*base.running.lock().unwrap_or_else(PoisonError::into_inner) + && *s == sig + { + return r.clone(); + } let r = Arc::new(RunningIndex::build(doc, &|sid| self.get(doc, sid, None))); *self.running.lock().unwrap_or_else(PoisonError::into_inner) = Some((sig, r.clone())); r @@ -376,6 +493,7 @@ fn signature(doc: &Document, story: &Arc) -> (Vec, Vec>) sections_hash(doc) as usize, doc.font_scope as usize, usize::from(g.relative_to == designcraft_doc::GridRelative::TopMargin), + outlines_hash(doc) as usize, ]; sig.extend([g.start, g.increment].into_iter().flat_map(bits)); let mut keep = Vec::new(); diff --git a/crates/compose/src/grep.rs b/crates/compose/src/grep.rs index 6f9e8f9e3..5a56920dc 100644 --- a/crates/compose/src/grep.rs +++ b/crates/compose/src/grep.rs @@ -13,6 +13,9 @@ //! - Lookahead, lookbehind, atomic groups, possessive quantifiers, backreferences and `\K` are //! supported. Backtracking is capped ([`BACKTRACK_LIMIT`]), so a pathological pattern stops //! with an error instead of hanging. +//! - Subroutine calls and recursion (`\g`, `\g<1>`, `\g<-1>`) are not part of the dialect +//! and are refused: the regex engine inlines each call while compiling, so a short pattern whose +//! groups call each other more than once expands exponentially. use std::fmt; use std::ops::Range; @@ -30,6 +33,11 @@ pub const BACKTRACK_LIMIT: usize = 200_000; /// on every relayout (#1598). A paragraph cannot usefully carry more styled runs than this, and /// a scan that reaches it stops with what it has. pub const MAX_MATCHES_PER_PARAGRAPH: usize = 4096; +/// Searches [`Grep::find_nonempty`] may run per match it is allowed to return. Empty matches +/// don't count toward that match limit, but each one is still a search (a lookaround can scan the +/// rest of the paragraph): without this a pattern that only ever matches empty searched once per +/// character, quadratic in the paragraph's length. +pub const SEARCHES_PER_MATCH: usize = 4; /// Compiled program size cap (bytes) for the underlying regex engine. const SIZE_LIMIT: usize = 4 << 20; @@ -363,7 +371,13 @@ impl Grep { (false, true) => "(?m)", (false, false) => "", }; - let re = fancy_regex::RegexBuilder::new(&format!("{flags}{pat}")) + let pat = format!("{flags}{pat}"); + // Refused before compiling: the compiler inlines every subroutine call (to a fixed depth), + // so `(a\g<1>\g<1>)` costs time and memory exponential in that depth. + if fancy_regex::Expr::parse_tree(&pat).is_ok_and(|t| t.contains_subroutines) { + return Err(err("GREP: subroutine calls and recursion are not supported")); + } + let re = fancy_regex::RegexBuilder::new(&pat) .backtrack_limit(BACKTRACK_LIMIT) .delegate_size_limit(SIZE_LIMIT) .delegate_dfa_size_limit(SIZE_LIMIT) @@ -385,26 +399,69 @@ impl Grep { self.re.find_iter(text).take(limit).map(|m| m.map(|m| m.range()).map_err(run_err)).collect() } - /// Non-empty matches in `text`, at most `limit` of them: an empty match styles nothing, so it - /// doesn't count toward a GREP style's cap. - pub fn find_nonempty(&self, text: &str, limit: usize) -> Result>, GrepError> { - self.re - .find_iter(text) - .filter(|m| !m.as_ref().is_ok_and(|m| m.range().is_empty())) - .take(limit) - .map(|m| m.map(|m| m.range()).map_err(run_err)) - .collect() + /// The first match starting at or after byte `start`, with its replacement: `template` + /// expanded as [`Self::replacements`] does. + pub fn replacement_at(&self, text: &str, start: usize, template: &str) -> Result, String)>, GrepError> { + if start > text.len() || !text.is_char_boundary(start) { + return Ok(None); + } + let Some(caps) = self.re.captures_from_pos(text, start).map_err(run_err)? else { return Ok(None) }; + Ok(caps.get(0).map(|m| (m.range(), fancy_regex::Expander::default().expansion(template, &caps)))) } - /// Matches in `text` and their replacements, `template` expanded per match (`$1`…; see - /// [`translate_replacement`]). Stops after the first match when `first_only`. - pub fn replacements(&self, text: &str, template: &str, first_only: bool) -> Result, String)>, GrepError> { + /// Non-empty matches in `text`, at most `limit` of them: an empty match styles nothing, so it + /// doesn't count toward a GREP style's cap. Empty matches still cost a search each, so the + /// scan stops after `limit` × [`SEARCHES_PER_MATCH`] searches in all. + /// + /// The flag is true when the search budget ran out with text left to scan, so the matches may + /// be incomplete (reaching `limit` is not flagged: the caller sees the full vector). + pub fn find_nonempty(&self, text: &str, limit: usize) -> Result<(Vec>, bool), GrepError> { + let mut it = self.re.find_iter(text); + let mut out = Vec::new(); + for _ in 0..limit.saturating_mul(SEARCHES_PER_MATCH) { + if out.len() >= limit { + return Ok((out, false)); + } + let Some(m) = it.next() else { return Ok((out, false)) }; + let r = m.map_err(run_err)?.range(); + if !r.is_empty() { + out.push(r); + } + } + let more = out.len() < limit && it.next().transpose().map_err(run_err)?.is_some(); + Ok((out, more)) + } + + /// Matches in `text` that `keep` accepts and their replacements, `template` expanded per match + /// (`$1`…; see [`translate_replacement`]). Stops after the first kept match when `first_only`, + /// and with an error once the expanded replacements pass `max_bytes` in all (before any more + /// are made). + pub fn replacements( + &self, + text: &str, + template: &str, + first_only: bool, + max_bytes: usize, + keep: impl Fn(&Range) -> bool, + ) -> Result, String)>, GrepError> { let exp = fancy_regex::Expander::default(); let mut out = Vec::new(); + let mut bytes = 0usize; for caps in self.re.captures_iter(text) { let caps = caps.map_err(run_err)?; let Some(m) = caps.get(0) else { continue }; - out.push((m.range(), exp.expansion(template, &caps))); + if !keep(&m.range()) { + continue; + } + // Written into a buffer that refuses bytes past the budget, so an oversized + // expansion is rejected before it is allocated. + let mut w = BoundedBuf { buf: Vec::new(), left: max_bytes.saturating_sub(bytes) }; + if exp.write_expansion(&mut w, template, &caps).is_err() { + return Err(err(format!("the replacements would put more than {max_bytes} bytes in"))); + } + bytes += w.buf.len(); + let expanded = String::from_utf8(w.buf).map_err(|_| err("the replacement is not valid UTF-8".to_string()))?; + out.push((m.range(), expanded)); if first_only { break; } @@ -413,6 +470,27 @@ impl Grep { } } +/// A byte sink that fails a write that would pass its remaining budget (nothing is copied then). +struct BoundedBuf { + buf: Vec, + left: usize, +} + +impl std::io::Write for BoundedBuf { + fn write(&mut self, data: &[u8]) -> std::io::Result { + if data.len() > self.left { + return Err(std::io::ErrorKind::OutOfMemory.into()); + } + self.left -= data.len(); + self.buf.extend_from_slice(data); + Ok(data.len()) + } + + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } +} + fn run_err(e: fancy_regex::Error) -> GrepError { err(format!("GREP search stopped: {e}")) } @@ -484,7 +562,39 @@ mod tests { assert_eq!(g.find_all("axb A.B a.b", 1).unwrap().first(), Some(&(4..7))); let g = grep(r"(\d+)\h(\l+)"); let tpl = translate_replacement(r"$2~S$1x\r\$$"); - assert_eq!(g.replacements("5 kg", &tpl, false).unwrap(), [(0..4, "kg\u{A0}5x\n$$".to_string())]); + assert_eq!(g.replacements("5 kg", &tpl, false, usize::MAX, |_| true).unwrap(), [(0..4, "kg\u{A0}5x\n$$".to_string())]); + // The total expanded size is bounded while the replacements are made, over the matches kept. + let g = grep("a"); + assert!(g.replacements("aaaa", "xxxx", false, 15, |_| true).is_err()); + assert_eq!(g.replacements("aaaa", "xxxx", false, 16, |_| true).unwrap().len(), 4); + assert_eq!(g.replacements("aaaa", "xxxx", false, 8, |m| m.start < 2).unwrap().len(), 2); + assert_eq!(g.replacements("aaaa", "xxxx", true, 4, |m| m.start >= 2).unwrap(), [(2..3, "xxxx".to_string())]); + } + + #[test] + fn subroutine_calls_are_refused() { + // Each group calls itself twice: compiling inlines 2^depth copies. + for p in [r"(a\g<1>\g<1>)", r"(?a\g\g)", r"(?a|b\g)", r"(a)(b)\g<-1>", r"(a)\g<1>"] { + let t = std::time::Instant::now(); + let e = Grep::new(p, GrepOptions::default()).unwrap_err(); + assert!(e.0.contains("subroutine"), "{p}: {e}"); + assert!(t.elapsed().as_secs() < 5, "{p}"); + } + // Backreferences and groups are still fine. + assert_eq!(found(r"(a)\1", "xaa"), ["aa"]); + assert_eq!(found(r"(?a)\k", "xaa"), ["aa"]); + } + + #[test] + fn empty_matches_use_up_the_search_budget() { + // A pattern that matches empty at every character: the non-empty match at the end is + // found within the budget and not past it. + let g = grep("a*"); + let near = format!("{}a", "b".repeat(10 * SEARCHES_PER_MATCH - 2)); + let (ms, exhausted) = g.find_nonempty(&near, 10).unwrap(); + assert_eq!((ms.len(), ms[0].clone(), exhausted), (1, near.len() - 1..near.len(), false)); + let far = format!("{}a", "b".repeat(10 * SEARCHES_PER_MATCH + 50)); + assert_eq!(g.find_nonempty(&far, 10).unwrap(), (vec![], true), "the scan stops at the search budget and says so"); } #[test] diff --git a/crates/compose/src/hyphen.rs b/crates/compose/src/hyphen.rs index 3f07f4b40..a709995f4 100644 --- a/crates/compose/src/hyphen.rs +++ b/crates/compose/src/hyphen.rs @@ -3,9 +3,17 @@ //! `hyph-es.tex` 5.0 from hyph-utf8, MIT; Portuguese is `hyph-pt.tex` 1.4 from hyph-utf8 (Pedro J. //! de Rezende, J. Joao Dias Almeida, Leonardo Araujo, Aline Benevides), BSD-3-Clause; Norwegian is //! `hyph-no.tex` from hyph-utf8 (Rune Kleveland, Ole Michael Selberg), permissive (see NOTICE); -//! Greek is `hyph-el-monoton.tex` 5.0 from hyph-utf8 (Dimitrios Filippou), LPPL or MIT, taken +//! Danish is `hyph-da.tex` 2011-01-11 from hyph-utf8 (Frank Jensen), LPPL or MIT, taken under MIT; +//! Dutch is Piet Tutelaers's `hyph-nl.tex` 1.1 from hyph-utf8, MIT; Greek is `hyph-el-monoton.tex` 5.0 from hyph-utf8 (Dimitrios Filippou), LPPL or MIT, taken //! under MIT. Those are the **monotonic** patterns, which is what `hypher` maps `el` to, so -//! polytonic text hyphenates by them as well. +//! polytonic text hyphenates by them as well. French is `hyph-fr.tex` 2.13 from hyph-utf8 (Daniel +//! Flipo, Bernard Gaulle, Arthur Reutenauer), MIT; Italian is `hyph-it.tex` 4.9 from hyph-utf8 +//! (Claudio Beccari), LPPL or MIT, taken under MIT. A word with an elision (`l'imprimerie`) +//! hyphenates after its apostrophe. +//! German uses `hyph-de-1996.tex` (2024-02-28, Deutschsprachige Trennmustermannschaft, MIT): +//! despite the filename, these are the reformed 2006 spelling patterns. Only the two 2006 reform +//! names and German locale codes without a reform year or with 2006 use this set. Traditional, +//! 1901 and unknown German variants have no automatic hyphenation; no old-spelling set is bundled. //! //! English lookup order for each word: //! 1. the **dictionary** ([`Dictionary::en_us`]) — the public-domain Moby Hyphenator II word list @@ -84,6 +92,11 @@ impl Lang { } let tag = designcraft_doc::language_tag(language)?; let sub = designcraft_doc::language_subtag(tag); + // language_tag deliberately drops spelling variants for shaping and quotes. Hyphenation + // must retain that distinction: the 2006 patterns are wrong for traditional ck/st breaks. + if sub == "de" && !german_2006_language(language) { + return None; + } if sub == "en" { return Some(Lang::English); } @@ -95,6 +108,15 @@ impl Lang { } } +/// Accept explicit reform names and unqualified German locales (our modern default), but never +/// silently substitute reform patterns for another spelling variant imported from IDML. +fn german_2006_language(language: &str) -> bool { + let language = language.trim(); + let normalized = language.strip_prefix("$ID/").unwrap_or(language).to_lowercase(); + let words: Vec<&str> = normalized.split(|c: char| !c.is_alphanumeric()).filter(|w| !w.is_empty()).collect(); + matches!(words.as_slice(), ["german", "2006", "reform"] | ["german", "swiss", "2006", "reform"] | ["de"] | ["de", _] | ["de", _, "2006"]) +} + /// Where a word's break points came from. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Source { @@ -119,8 +141,14 @@ fn core_breaks(core: &[char], lang: Lang) -> (Vec, Source) { return (vec![], Source::None); } if let Lang::Patterns(l) = lang { - if core.contains(&'\'') { - return (vec![], Source::None); + if let Some(ap) = core.iter().rposition(|&c| c == '\'') { + // An elision (French "l'", Italian "dell'"): the word after the apostrophe hyphenates, + // with no break up to it. Elsewhere (German "Rock'n'Roll") an apostrophe word gets none. + if !matches!(l, hypher::Lang::French | hypher::Lang::Italian) { + return (vec![], Source::None); + } + let (pts, src) = if ap + 1 < n { core_breaks(&core[ap + 1..], lang) } else { (vec![], Source::None) }; + return (pts.into_iter().map(|p| p + ap + 1).collect(), src); } let s: String = core.iter().collect(); let mut out = Vec::new(); @@ -196,6 +224,135 @@ pub fn word_breaks_in(word: &str, lang: Lang) -> (Vec, Source) { (out, src) } +/// Whether a whitespace-delimited token is one no language's hyphenation should break. +/// +/// Korean attaches particles straight onto Latin words ("News와", "PDF로"), and notices are full +/// of addresses. With the paragraph language left at the default English -- which is what an +/// ordinary Korean document has -- a word run inside such a token was hyphenated as English, +/// giving `New-` / `s와` and `library.exam-` / `ple.kr` (#1688). +/// +/// A token is kept whole when it carries Hangul, kana or Han, or when it reads as an address: a +/// URL with a scheme, an e-mail address, a dotted domain, a `/`-rooted path or a Windows drive +/// path. Breaking at a hyphen the author typed is still allowed; this only stops hyphens being +/// invented inside the token. +pub fn keep_whole(token: &str) -> bool { + let cjk = |c: char| { + matches!(c as u32, + 0xAC00..=0xD7A3 // Hangul syllables + | 0x1100..=0x11FF // Hangul Jamo + | 0x3130..=0x318F // Hangul compatibility Jamo + | 0xA960..=0xA97F // Hangul Jamo Extended-A + | 0xD7B0..=0xD7FF // Hangul Jamo Extended-B + | 0x3040..=0x30FF // kana + | 0xFF66..=0xFF9F // halfwidth katakana + | 0x4E00..=0x9FFF // CJK unified ideographs + | 0x3400..=0x4DBF + | 0xF900..=0xFAFF + | 0x20000..=0x3FFFF) // supplementary ideographs + }; + if token.chars().any(cjk) { + return true; + } + // Prose punctuation around a token is not part of the address inside it: `(https://...)` was + // not recognised because the bracket came first, and `library.example.kr,` because the comma + // ended the last label. Only this classification ignores it; the text keeps + // every character it had. + let wrapper = |c: char| { + matches!(c, '(' | ')' | '[' | ']' | '{' | '}' | '"' | '\'' | ',' | ';' | ':' | '!' | '?' | '\u{201C}' | '\u{201D}' | '\u{2018}' | '\u{2019}') + }; + // Full stops count with the wrapper characters at the end, so `(library.example.kr).` loses + // both its closing bracket and the sentence's full stop. + let token = token.trim_start_matches(wrapper).trim_end_matches(|c: char| wrapper(c) || c == '.'); + let lower = token.to_ascii_lowercase(); + if lower.starts_with("http://") || lower.starts_with("https://") || lower.starts_with("ftp://") || lower.starts_with("www.") { + return true; + } + // An e-mail address: one `@` with something either side, no space (tokens have none). + if let Some((user, host)) = token.split_once('@') { + return !user.is_empty() && host.contains('.'); + } + // A path, rooted or with a drive letter. + if token.starts_with('/') || token.starts_with('\\') { + return true; + } + let mut cs = token.chars(); + if let (Some(a), Some(b), Some(c)) = (cs.next(), cs.next(), cs.next()) + && a.is_ascii_alphabetic() + && b == ':' + && (c == '/' || c == '\\') + { + return true; + } + // A domain: dot-separated labels up to the first `/`, whose last label is a short run of + // letters -- "example.kr", "library.example.kr". Ordinary prose ("end. Next") never reaches + // here, because a token holds no space. + // Judged as written, not lower-cased: a domain's last label is lower-case letters, so `Mr.Smith` + // is not one and stays a word to hyphenate. + let host = token.split('/').next().unwrap_or(""); + let labels: Vec<&str> = host.trim_end_matches('.').split('.').collect(); + labels.len() >= 2 + && labels.iter().all(|l| !l.is_empty() && l.chars().all(|c| c.is_ascii_alphanumeric() || c == '-')) + && labels.last().is_some_and(|tld| tld.len() <= 6 && tld.chars().all(|c| c.is_ascii_lowercase())) +} + +/// Whether a paragraph is set in Korean, so automatic hyphenation does not apply to it. +/// +/// Korean is set word by word and is not hyphenated (KLREQ). A paragraph with at least as many +/// Hangul syllables as Latin letters is treated as Korean however its language is set, since an +/// ordinary Korean document leaves the paragraph language at the default English (#1688). +pub fn mostly_hangul(text: &str) -> bool { + mostly_hangul_chars(text.chars()) +} + +/// [`mostly_hangul`] over characters, for judging the text that is actually set: hidden text has +/// no glyphs, and counting it let hidden Korean turn hyphenation off for the visible English +/// around it, and hidden Latin keep it on for visible Korean. +pub fn mostly_hangul_chars(chars: impl Iterator) -> bool { + let (mut hangul, mut latin) = (0usize, 0usize); + for c in chars { + match c as u32 { + _ if crate::breaker::is_hangul(c) => hangul += 1, + _ if c.is_ascii_alphabetic() => latin += 1, + _ => {} + } + } + hangul > 0 && hangul >= latin +} + +/// [`mostly_hangul`] over a paragraph's set glyphs, given as `(source byte, character, +/// generated)` so it can be tested without a font. +/// +/// One vote per set character, not per glyph. Shaping makes a cluster several glyphs over one +/// character and each repeats that character, so a syllable shaped into three glyphs voted three +/// times -- and since the test is `hangul >= latin`, that can turn hyphenation off for a +/// paragraph that is mostly Latin. Consecutive glyphs on one source byte are one character. +/// +/// Generated glyphs do not vote: a list bullet or number, or a footnote label, is not the +/// paragraph's own text, and `prepend_label` gives it the paragraph's *first* byte -- so counting +/// it would also swallow the real first character in the deduplication. +/// +/// **Approximation.** A ligature is one glyph over several characters, so those characters vote +/// once between them and Latin is under-counted. That can change the answer: 16 Hangul with +/// `office hyphenation` is 17 Latin letters, and a font that shapes `fi` counts at most 16, so +/// the paragraph classifies as Korean and loses its hyphens. Fixing it needs +/// the visible source characters each cluster stands for; `byte..byte + len` is not that, because +/// the glyph after a hidden run spans it -- measured, every byte of the paragraph came out +/// covered -- which would revive the hidden-text bug this function was changed to avoid. +pub fn korean_paragraph(glyphs: impl Iterator) -> bool { + let mut chars: Vec = Vec::new(); + let mut last: Option = None; + for (byte, ch, generated) in glyphs { + if generated { + continue; + } + if last != Some(byte) { + chars.push(ch); + } + last = Some(byte); + } + mostly_hangul_chars(chars.into_iter()) +} + /// Allowed hyphenation points in `word` as char indices (a hyphen goes before that char), with /// the paragraph limits applied to each letter run. pub fn hyphen_points(word: &str, lim: &Limits) -> Vec { @@ -211,6 +368,7 @@ pub fn hyphen_points_in(word: &str, lim: &Limits, lang: Lang) -> Vec { } let min_before = lim.after_first.max(1); let min_after = lim.before_last.max(1); + let elides = matches!(lang, Lang::Patterns(hypher::Lang::French | hypher::Lang::Italian)); // Run bounds of each point's letter run (trimmed of apostrophes). let run_of = |p: usize| { let mut a = p; @@ -227,6 +385,10 @@ pub fn hyphen_points_in(word: &str, lim: &Limits, lang: Lang) -> Vec { while b > a && is_apostrophe(chars[b - 1]) { b -= 1; } + // After an elision the word is the part after its last apostrophe: the limits count that. + if elides && let Some(ap) = chars[a..b].iter().rposition(|&c| is_apostrophe(c)) { + a += ap + 1; + } (a, b) }; pts.into_iter() @@ -287,6 +449,25 @@ fn heuristic_points(c: &[char]) -> Vec { return vec![]; } let v: Vec = c.iter().map(|&x| is_vowel(x)).collect(); + // A trailing silent `ed`, `es` or `e` comes off the right part. Which one depends only on how + // the word ends, so the right part's core is `c[i..n - silent]` (nothing comes off a right + // part shorter than the ending). Prefix sums of vowels and UTF-8 lengths then answer "does the + // core have a vowel" and "is it longer than one byte" without building each suffix, which was + // quadratic in the word's length. + let ends = |s: &str| c.ends_with(&s.chars().collect::>()); + let silent = if ends("ed") || ends("es") { + 2 + } else if ends("e") { + 1 + } else { + 0 + }; + let mut vowels = vec![0_usize; n + 1]; + let mut bytes = vec![0_usize; n + 1]; + for (k, ch) in c.iter().enumerate() { + vowels[k + 1] = vowels[k] + usize::from(v[k]); + bytes[k + 1] = bytes[k] + ch.len_utf8(); + } let mut out = vec![]; for i in 1..n { let ok = if v[i - 1] && !v[i] { @@ -297,9 +478,8 @@ fn heuristic_points(c: &[char]) -> Vec { false }; // Both parts need a sounded vowel: a trailing silent `e`, `ed` or `es` doesn't count. - let right: String = c[i..].iter().collect(); - let core = right.strip_suffix("ed").or_else(|| right.strip_suffix("es")).or_else(|| right.strip_suffix('e')).unwrap_or(&right); - if ok && core.chars().any(is_vowel) && core.len() > 1 && v[..i].iter().any(|x| *x) { + let core_end = if n - i >= silent { n - silent } else { n }; + if ok && vowels[core_end] > vowels[i] && bytes[core_end] - bytes[i] > 1 && vowels[i] > 0 { out.push(i); } } @@ -308,6 +488,65 @@ fn heuristic_points(c: &[char]) -> Vec { #[cfg(test)] mod tests { + /// A token no language's hyphenation should break: Korean particles on Latin words, and the + /// addresses a notice is full of (#1688). + #[test] + fn a_token_with_hangul_or_an_address_is_kept_whole() { + for t in [ + "News\u{C640}", // News와 + "PDF\u{B85C}", // PDF로 + "\u{C77C}\u{BCF8}\u{C5B4}", // 일본어 + "https://example.kr/page", + "www.example.kr", + "library.example.kr", + "mail@example.kr", + "/usr/share/fonts", + "C:\\Users\\Hong", + "example.kr", + ] { + assert!(keep_whole(t), "{t} should be kept whole"); + } + // Ordinary words, including ones with a hyphen or a full stop, are still hyphenated. + for t in ["hyphenation", "well-known", "sentence.", "Mr.", "re-examine", "3.5"] { + assert!(!keep_whole(t), "{t} should not be protected"); + } + + // An address wrapped in prose punctuation is the same address. + for t in [ + "library.example.kr,", + "(https://example.kr/page)", + "\u{201C}www.example.kr\u{201D}", + "mail@example.kr;", + "example.kr.", + // A bracket and then the sentence's full stop. + "(library.example.kr).", + "[https://example.kr]", + ] { + assert!(keep_whole(t), "{t} should be kept whole"); + } + + // Halfwidth katakana and a supplementary ideograph are CJK too. + for t in ["News\u{FF76}", "\u{20B9F}\u{C640}", "x\u{FF9F}"] { + assert!(keep_whole(t), "{t:?} should be kept whole"); + } + + // A domain's last label is lower-case letters as written: a name run into the next word + // after a full stop is not one, and its words still hyphenate. + for t in ["Mr.Smith", "Section.Introduction", "End.Next"] { + assert!(!keep_whole(t), "{t} is not an address"); + } + } + + /// A Korean paragraph gets no automatic hyphens whatever its language is set to (#1688). + #[test] + fn a_paragraph_that_is_mostly_hangul_is_not_hyphenated() { + assert!(mostly_hangul("\u{C774}\u{BC88} \u{D1B5}\u{C9C0}\u{BB38}\u{C740} News\u{C640} \u{AD00}\u{B828}")); + assert!(!mostly_hangul("An English paragraph about hyphenation and composition")); + // A Latin paragraph with a Korean word in it is still hyphenated as Latin. + assert!(!mostly_hangul("The Korean word \u{D55C}\u{AD6D} appears once in this English sentence")); + assert!(!mostly_hangul("")); + } + use super::*; fn h(w: &str) -> String { @@ -379,6 +618,82 @@ mod tests { assert!(hyphen_points("typography", &lim).is_empty()); } + /// Only French and Italian elide at an apostrophe; other languages leave such words unbroken. + #[test] + fn apostrophe_words_hyphenate_only_in_french_and_italian() { + let de = Lang::for_language("German: 2006 Reform").unwrap(); + assert!(hyphen_points_in("Rock'n'Roll", &Limits::default(), de).is_empty()); + let fr = Lang::for_language("French").unwrap(); + assert!(!hyphen_points_in("l'information", &Limits::default(), fr).is_empty()); + } + + #[test] + fn german_2006_uses_reformed_patterns() { + let de = Lang::for_language("German: 2006 Reform").unwrap(); + assert_eq!(de, Lang::Patterns(hypher::Lang::German)); + for name in [ + "$ID/German: 2006 Reform", + " german: 2006 reform ", + "de", + "de-DE", + "de_AT", + "de_CH", + "de_DE_2006", + "German: Swiss 2006 Reform", + "$ID/German: Swiss 2006 Reform", + "de_CH_2006", + ] { + assert_eq!(Lang::for_language(name), Some(de), "{name}"); + } + for (word, expected) in [ + ("Silbentrennung", "Sil-ben-tren-nung"), + ("Zucker", "Zu-cker"), + ("Bäcker", "Bä-cker"), + ("Fenster", "Fens-ter"), + ("Straße", "Stra-ße"), + ("Fußgänger", "Fuß-gän-ger"), + ("Donaudampfschifffahrt", "Do-nau-dampf-schiff-fahrt"), + ("SILBENTRENNUNG", "SIL-BEN-TREN-NUNG"), + ] { + let pts = hyphen_points_in(word, &Limits::default(), de); + let actual: String = word.chars().enumerate().map(|(i, c)| if pts.contains(&i) { format!("-{c}") } else { c.to_string() }).collect(); + assert_eq!(actual, expected, "{word}"); + } + } + + #[test] + fn non_2006_german_has_no_bundled_hyphenation() { + for name in [ + "German", + "German: Traditional", + "$ID/German: Traditional", + "German: Swiss", + "German: 1901", + "German: 1996 Reform", + "German: Unknown", + "German: Traditional 2006 Reform", + "de_DE_1901", + "de-CH-1901", + "de_AT_1996", + "de_DE_2099", + ] { + assert_eq!(designcraft_doc::language_subtag(designcraft_doc::language_tag(name).unwrap()), "de", "{name}"); + assert_eq!(Lang::for_language(name), None, "{name}: do not use 2006 ck/st breaks for unsupported spelling variants"); + } + } + + #[test] + fn german_2006_respects_paragraph_limits() { + let de = Lang::for_language("de_DE_2006").unwrap(); + let lim = Limits { after_first: 4, before_last: 5, ..Limits::default() }; + assert_eq!(hyphen_points_in("Silbentrennung", &lim, de), vec![6]); + let lim = Limits { min_word: 15, ..Limits::default() }; + assert!(hyphen_points_in("Silbentrennung", &lim, de).is_empty()); + let lim = Limits { capitalized: false, ..Limits::default() }; + assert!(hyphen_points_in("Silbentrennung", &lim, de).is_empty()); + assert!(!hyphen_points_in("silbentrennung", &lim, de).is_empty()); + } + #[test] fn spanish_uses_the_bezos_patterns() { let es = Lang::for_language("Spanish").unwrap(); @@ -393,7 +708,7 @@ mod tests { assert_eq!(h("desesperación"), "de-ses-pe-ra-ción"); assert_eq!(h("teatro"), "tea-tro", "a vowel run stays whole"); assert_eq!(h("calle"), "ca-lle", "ll stays whole"); - assert!(Lang::for_language("French").is_none(), "only languages built in"); + assert!(Lang::for_language("Swedish").is_none(), "only languages built in"); } #[test] @@ -415,6 +730,18 @@ mod tests { assert_eq!(h("pós-graduação"), "pós-gra-du-a-ção", "each part of a compound"); } + #[test] + fn danish_uses_the_hyph_da_patterns() { + let da = Lang::for_language("Danish").unwrap(); + assert_eq!(da, Lang::Patterns(hypher::Lang::Danish)); + assert_eq!(da, Lang::for_language("da").unwrap()); + assert_ne!(da, Lang::English); + assert_ne!(da, Lang::for_language("Norwegian").unwrap()); + for w in ["bacheloruddannelser", "industrialiseringens", "samarbejdspartnere"] { + assert!(!hyphen_points_in(w, &Limits::default(), da).is_empty(), "{w} gets break points"); + } + } + #[test] fn norwegian_uses_the_hyph_no_patterns() { let nb = Lang::for_language("Norwegian: Bokmål").unwrap(); @@ -435,9 +762,221 @@ mod tests { assert_eq!(h("beveger"), "be-ve-ger"); } + /// The paragraph limits count the letters of the word after an elision, not the elided prefix. + #[test] + fn elision_limits_apply_to_the_word_after_it() { + let fr = Lang::for_language("French").unwrap(); + let lim = Limits { min_word: 5, after_first: 3, before_last: 2, capitalized: true }; + assert_eq!(hyphen_points_in("l'imprimerie", &lim, fr), vec![7, 9]); + let lim = Limits { min_word: 11, ..Limits::default() }; + assert!(hyphen_points_in("l'imprimerie", &lim, fr).is_empty()); + } + + /// A word with an elision ("l'", "dell'") hyphenates as the word after it. + fn marked(w: &str, l: Lang) -> String { + let pts = hyphen_points_in(w, &Limits::default(), l); + w.chars().enumerate().map(|(i, c)| if pts.contains(&i) { format!("-{c}") } else { c.to_string() }).collect() + } + + #[test] + fn french_uses_the_hyph_fr_patterns() { + let fr = Lang::for_language("French").unwrap(); + for name in ["fr", "fr_FR", "French: Canadian", "French: Swiss"] { + assert_eq!(Lang::for_language(name), Some(fr), "{name}"); + } + assert_eq!(marked("hyphénation", fr), "hy-phé-na-tion"); + assert_eq!(marked("typographie", fr), "ty-po-gra-phie"); + assert_eq!(marked("Développement", fr), "Dé-ve-lop-pe-ment"); + assert_eq!(marked("anticonstitutionnellement", fr), "an-ti-cons-ti-tu-tion-nel-le-ment"); + assert_eq!(marked("paragraphe", fr), "pa-ra-graphe", "no break before a final mute syllable of two letters"); + assert_eq!(marked("l'imprimerie", fr), "l'im-pri-me-rie", "after an elision"); + assert_eq!(marked("l’imprimerie", fr), "l’im-pri-me-rie", "a typographer's apostrophe too"); + } + + #[test] + fn italian_uses_the_hyph_it_patterns() { + let it = Lang::for_language("Italian").unwrap(); + for name in ["it", "it_IT"] { + assert_eq!(Lang::for_language(name), Some(it), "{name}"); + } + assert_ne!(it, Lang::for_language("French").unwrap()); + assert_eq!(marked("sillabazione", it), "sil-la-ba-zio-ne"); + assert_eq!(marked("tipografia", it), "ti-po-gra-fia"); + assert_eq!(marked("Repubblica", it), "Re-pub-bli-ca"); + assert_eq!(marked("impaginazione", it), "im-pa-gi-na-zio-ne"); + assert_eq!(marked("dell'impaginazione", it), "dell'im-pa-gi-na-zio-ne", "after an elision"); + } + + #[test] + fn dutch_uses_the_hyph_nl_patterns() { + let nl = Lang::for_language("Dutch").unwrap(); + // InDesign writes the 2005 spelling as `nl_NL_2005`. + assert_eq!(nl, Lang::for_language("nl_NL_2005").unwrap()); + assert_ne!(nl, Lang::for_language("Spanish").unwrap()); + let h = |w: &str| { + let pts = hyphen_points_in(w, &Limits::default(), nl); + w.chars().enumerate().map(|(i, c)| if pts.contains(&i) { format!("-{c}") } else { c.to_string() }).collect::() + }; + assert_eq!(h("uitspraak"), "uit-spraak"); + assert_eq!(h("kinderen"), "kin-de-ren"); + assert_eq!(h("leesvaardigheid"), "lees-vaar-dig-heid"); + assert_eq!(h("zelfvertrouwen"), "zelf-ver-trou-wen"); + assert_eq!(h("Ontwikkelen"), "Ont-wik-ke-len"); + // Long compounds break at their parts and at the syllables inside them. + assert_eq!(h("arbeidsongeschiktheidsverzekering"), "ar-beids-on-ge-schikt-heids-ver-ze-ke-ring"); + assert_eq!(h("ziekenhuisopname"), "zie-ken-huis-op-na-me"); + assert_eq!(h("gemeenteraadsverkiezingen"), "ge-meen-te-raads-ver-kie-zin-gen"); + assert_eq!(h("kinderdagverblijf"), "kin-der-dag-ver-blijf"); + } + #[test] fn heuristic_fallback() { let c: Vec = "happen".chars().collect(); assert_eq!(heuristic_points(&c), vec![3]); } + + /// The heuristic as it was written before the prefix sums, building each right part. + fn heuristic_by_suffixes(c: &[char]) -> Vec { + let n = c.len(); + if n < 4 || !c.iter().all(|c| c.is_alphabetic()) { + return vec![]; + } + let v: Vec = c.iter().map(|&x| is_vowel(x)).collect(); + let mut out = vec![]; + for i in 1..n { + let ok = if v[i - 1] && !v[i] { + (i + 1 < n && v[i + 1]) || (i + 2 < n && onset_pair(c[i], c[i + 1]) && v[i + 2]) + } else if !v[i - 1] && !v[i] { + i >= 2 && v[i - 2] && i + 1 < n && v[i + 1] && !onset_pair(c[i - 1], c[i]) && c[i - 1] != c[i] + || (c[i - 1] == c[i] && i >= 2 && v[i - 2]) + } else { + false + }; + let right: String = c[i..].iter().collect(); + let core = right.strip_suffix("ed").or_else(|| right.strip_suffix("es")).or_else(|| right.strip_suffix('e')).unwrap_or(&right); + if ok && core.chars().any(is_vowel) && core.len() > 1 && v[..i].iter().any(|x| *x) { + out.push(i); + } + } + out + } + + #[test] + fn heuristic_matches_building_each_suffix() { + for w in [ + "happen", + "typography", + "zzzzed", + "bakes", + "baked", + "flute", + "strengths", + "aeiou", + "rhythms", + "bookkeeper", + "naïveté", + "çabcde", + "ABCDE", + "plopped", + "staples", + "queued", + "ed", + "eded", + "abed", + "abes", + "cafés", + "aed", + "xaxed", + "xaxes", + "xaxe", + "ŝtupoe", + "ŝtupoed", + "ababababed", + ] { + let c: Vec = w.chars().collect(); + assert_eq!(heuristic_points(&c), heuristic_by_suffixes(&c), "{w}"); + } + } + + /// A very long word (no dictionary or pattern entry) takes time linear in its length. + #[test] + fn heuristic_on_a_long_word_is_linear() { + let c: Vec = "taco".repeat(100_000).chars().collect(); + let t = std::time::Instant::now(); + let pts = heuristic_points(&c); + assert!(!pts.is_empty()); + assert!(t.elapsed().as_secs() < 5, "{:?}", t.elapsed()); + } +} + +#[cfg(test)] +mod korean_paragraph_tests { + use super::korean_paragraph; + + /// `(byte, ch, generated)` per glyph, which is all the classification reads -- so these cases + /// need no font and state the counting rules directly. + fn k(glyphs: &[(usize, char, bool)]) -> bool { + korean_paragraph(glyphs.iter().copied()) + } + + /// One character per source byte, however many glyphs shaping made of it. A syllable shaped + /// into three glyphs voted three times, which could classify a mostly-Latin paragraph as + /// Korean. + #[test] + fn glyphs_of_one_cluster_vote_once() { + // Two Hangul characters, the first shaped into three glyphs, against three Latin letters. + let clustered = [ + (0, '\u{AC00}', false), + (0, '\u{AC00}', false), + (0, '\u{AC00}', false), + (3, '\u{B098}', false), + (6, 'a', false), + (7, 'b', false), + (8, 'c', false), + ]; + assert!(!k(&clustered), "two Hangul against three Latin is not Korean"); + // Counting each glyph instead gives four Hangul against three, which flips it -- so the + // deduplication is what decides this case. + let per_glyph: Vec = clustered.iter().map(|(_, c, _)| *c).collect(); + assert!(super::mostly_hangul_chars(per_glyph.into_iter()), "per-glyph counting would call it Korean"); + } + + /// A generated label is not the paragraph's own text, and `prepend_label` gives it the + /// paragraph's *first* byte -- so counting it also swallowed the real first character in the + /// deduplication. + #[test] + fn a_generated_label_neither_votes_nor_hides_the_first_character() { + // A footnote label at byte 0, then two Hangul characters (the first also at byte 0) and + // two Latin letters. Two against two is Korean, since the test is `hangul >= latin` -- + // and losing one Hangul character to the label makes it one against two, which is not. + let labelled = [(0, '1', true), (0, '\u{AC00}', false), (3, '\u{B098}', false), (6, 'a', false), (7, 'b', false)]; + assert!(k(&labelled), "two Hangul against two Latin is Korean"); + // Without the exclusion the label takes byte 0, the Hangul character there is deduplicated + // away, and one Hangul against two Latin is no longer Korean. + let counted: Vec = { + let mut out = Vec::new(); + let mut last = None; + for (b, c, _) in labelled { + if last != Some(b) { + out.push(c); + } + last = Some(b); + } + out + }; + assert!(!super::mostly_hangul_chars(counted.into_iter()), "counting the label loses the first character"); + } + + /// The remaining approximation, pinned so it is visible rather than surprising: a ligature is + /// one glyph over several characters, so Latin is under-counted and this paragraph classifies + /// as Korean although it has more Latin letters. + #[test] + fn a_ligature_under_counts_latin_which_is_a_known_approximation() { + // Two Hangul characters against three Latin letters shaped as one `ffi` glyph. + let ligated = [(0, '\u{AC00}', false), (3, '\u{B098}', false), (6, '\u{FB03}', false)]; + assert!(k(&ligated), "the ligature counts as one character, so this reads as Korean"); + // Spelled out, the same text is not Korean -- which is the error the approximation makes. + let spelled = [(0, '\u{AC00}', false), (3, '\u{B098}', false), (6, 'f', false), (7, 'f', false), (8, 'i', false)]; + assert!(!k(&spelled), "the same characters unligated are not Korean"); + } } diff --git a/crates/compose/src/hyphen/dict.rs b/crates/compose/src/hyphen/dict.rs index 83a54d443..1b45c7edb 100644 --- a/crates/compose/src/hyphen/dict.rs +++ b/crates/compose/src/hyphen/dict.rs @@ -15,6 +15,9 @@ pub struct Dictionary { const MAGIC: &[u8] = b"DCHYPH1\n"; +/// Most bytes a serialized dictionary may inflate to (the bundled English one is far smaller). +pub const MAX_INFLATED_BYTES: usize = 64 << 20; + impl Dictionary { /// Build from `(lowercase word, break mask)` pairs (sorted and de-duplicated here; the first /// entry of a duplicate wins). @@ -76,9 +79,11 @@ impl Dictionary { miniz_oxide::deflate::compress_to_vec(&raw, 10) } - /// Deserialize data written by [`Dictionary::to_bytes`]. + /// Deserialize data written by [`Dictionary::to_bytes`]. At most [`MAX_INFLATED_BYTES`] are + /// inflated: a few compressed bytes can stand for gigabytes. pub fn from_bytes(data: &[u8]) -> Result { - let raw = miniz_oxide::inflate::decompress_to_vec(data).map_err(|e| format!("hyphenation dictionary: inflate failed: {e:?}"))?; + let raw = miniz_oxide::inflate::decompress_to_vec_with_limit(data, MAX_INFLATED_BYTES) + .map_err(|e| format!("hyphenation dictionary: inflate failed (or over {} MB): {e:?}", MAX_INFLATED_BYTES >> 20))?; let body = raw.strip_prefix(MAGIC).ok_or("hyphenation dictionary: bad header")?; let mut d = Dictionary { words: String::with_capacity(body.len()), offs: vec![0], masks: Vec::new() }; let mut cur: Vec = Vec::new(); @@ -147,4 +152,15 @@ mod tests { assert_eq!(back.get("naïveté").map(|m| hyphenated("naïveté", m)), Some("naïve-té".to_string())); assert!(back.get("dog").is_none()); } + + /// Data that inflates past the limit is refused instead of being inflated to the end. + #[test] + fn an_inflation_bomb_is_refused() { + let mut raw = MAGIC.to_vec(); + raw.resize(MAX_INFLATED_BYTES + 1, b'a'); + let bomb = miniz_oxide::deflate::compress_to_vec(&raw, 10); + assert!(bomb.len() < 1 << 20, "{}", bomb.len()); + let e = Dictionary::from_bytes(&bomb).err().unwrap_or_default(); + assert!(e.contains("inflate failed"), "{e}"); + } } diff --git a/crates/compose/src/kenten.rs b/crates/compose/src/kenten.rs index 1053c26b8..69994aa7a 100644 --- a/crates/compose/src/kenten.rs +++ b/crates/compose/src/kenten.rs @@ -123,6 +123,7 @@ fn shape_mark(face: FaceRef, text: &str, m: &KentenMark, b: &PlacedGlyph) -> Vec let ch = text.get(sg.cluster..).and_then(|t| t.chars().next()).unwrap_or(' '); let adv = f64::from(sg.x_advance) * sx; out.push(PlacedGlyph { + list_label: false, rendered_char: ch, face, gid: sg.gid, diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index 88becd85f..17ad2f76b 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -24,6 +24,7 @@ mod outline; mod overlay; mod parabox; mod placed; +mod reuse; mod ruby; pub mod shape; pub mod shatai; @@ -164,6 +165,10 @@ pub struct PlacedGlyph { /// How far after its pen position the glyph is drawn (CJK aki, ruby parent spacing): its /// advance starts at `x - dx`. pub dx: f64, + /// Part of the bullet or number the paragraph's list adds (see [`shape::Glyph::list_label`]). + /// It carries the first character's offset and no length, so anything selecting glyphs by + /// byte range has to leave it out or it reaches text outside the range. + pub list_label: bool, } impl PlacedGlyph { @@ -268,6 +273,8 @@ pub struct Deco { pub path: Option, /// Shown on screen only (not printed or exported). pub nonprinting: bool, + /// Set to overprint (paragraph shading or border); PDF export doesn't overprint yet. + pub overprint: bool, } #[derive(Clone, Debug, Default)] @@ -362,6 +369,9 @@ pub struct Exclusion { /// An anchored object in the frame's own story: it wraps only lines that start after this /// story byte (its anchor). pub after: Option, + /// For an anchored object in the frame's own story: the baseline of the line holding its + /// anchor when the exclusion was taken from it. + pub anchor_baseline: Option, } impl Exclusion { @@ -380,17 +390,50 @@ pub struct Contour { /// The frame path of an outline taken from a placed graphic: the frame clips the graphic, so /// the outline counts only within it (empty: no clip). pub clip: Vec>, + /// The placed graphic's clipping path, for an outline traced from the graphic's pixels: the + /// outline counts only inside it too (empty: none). An inverted clipping path is filled + /// even-odd ([`designcraft_doc::Graphic::clip_region`]). + pub graphic_clip: Vec>, + pub graphic_clip_even_odd: bool, pub offset: f64, } +/// A filled shape: closed polylines and their fill rule (non-zero, or even-odd). +#[derive(Clone, Copy)] +struct Region<'a> { + rings: &'a [Vec], + even_odd: bool, +} + +impl Region<'_> { + fn nonzero(rings: &[Vec]) -> Region<'_> { + Region { rings, even_odd: false } + } + + /// Is a point with this winding number filled? + fn fills(self, winding: i32) -> bool { + if self.even_odd { winding % 2 != 0 } else { winding != 0 } + } +} + /// Points a contour outline may have; a larger outline wraps around its bounding box. -const MAX_CONTOUR_POINTS: usize = 8192; +pub const MAX_CONTOUR_POINTS: usize = 8192; + +/// Edge visits a clipped contour may take for one line band; past it, the line's spans come from +/// the two shapes' projections instead of their intersection. +const MAX_CLIPPED_WORK: usize = 1 << 20; impl Contour { /// The outline of `path` (after `to_inner`), flattened; None if it is empty or too detailed. fn of(path: &designcraft_geom::BezPath, to_inner: designcraft_geom::Affine, offset: f64) -> Option { let rings = flatten_rings(path, to_inner)?; - offset.is_finite().then_some(Contour { rings, clip: Vec::new(), offset: offset.max(0.0) }) + offset.is_finite().then_some(Contour { + rings, + clip: Vec::new(), + graphic_clip: Vec::new(), + graphic_clip_even_odd: false, + offset: offset.max(0.0), + }) } /// This outline counted only within `frame` (after `to_inner`); unclipped if the frame is @@ -402,18 +445,41 @@ impl Contour { } } + /// This outline counted only inside the graphic's clipping region `clip` (after `to_inner`), + /// filled even-odd when `even_odd` is set; unchanged if the region is empty or too detailed. + fn within_graphic_clip(self, clip: &designcraft_geom::BezPath, even_odd: bool, to_inner: designcraft_geom::Affine) -> Contour { + match flatten_rings(clip, to_inner) { + Some(graphic_clip) => Contour { graphic_clip, graphic_clip_even_odd: even_odd, ..self }, + None => self, + } + } + /// The outline mapped by `a`. fn transformed(self, a: designcraft_geom::Affine) -> Contour { let map = |rings: Vec>| rings.into_iter().map(|r| r.into_iter().map(|p| a * p).collect()).collect(); - Contour { rings: map(self.rings), clip: map(self.clip), offset: self.offset } + Contour { + rings: map(self.rings), + clip: map(self.clip), + graphic_clip: map(self.graphic_clip), + graphic_clip_even_odd: self.graphic_clip_even_odd, + offset: self.offset, + } + } + + /// The clips the outline counts within. + fn clips(&self) -> impl Iterator> { + let frame = (!self.clip.is_empty()).then(|| Region::nonzero(&self.clip)); + let graphic = (!self.graphic_clip.is_empty()).then_some(Region { rings: &self.graphic_clip, even_odd: self.graphic_clip_even_odd }); + frame.into_iter().chain(graphic) } fn bounds(&self) -> Rect { - let Some(r) = rings_bounds(&self.rings) else { return Rect::ZERO }; - let r = match rings_bounds(&self.clip) { - Some(c) => r.intersect(c), - None => r, - }; + let Some(mut r) = rings_bounds(&self.rings) else { return Rect::ZERO }; + for c in self.clips() { + if let Some(b) = rings_bounds(c.rings) { + r = r.intersect(b); + } + } r.inflate(self.offset, self.offset) } @@ -423,12 +489,301 @@ impl Contour { fn band_extent(&self, y0: f64, y1: f64) -> Option<(f64, f64)> { let (y0, y1) = (y0 - self.offset, y1 + self.offset); let (mut lo, mut hi) = rings_band_extent(&self.rings, y0, y1)?; - if !self.clip.is_empty() { - let (a, b) = rings_band_extent(&self.clip, y0, y1)?; + for c in self.clips() { + let (a, b) = rings_band_extent(c.rings, y0, y1)?; (lo, hi) = (lo.max(a), hi.min(b)); } (lo <= hi).then_some((lo - self.offset, hi + self.offset)) } + + /// Occupied intervals across the whole line band, preserving gaps between parts of a + /// concave or compound outline. Project boundary edges and the filled middle slice: any + /// area that starts or ends inside the band is bounded by those projected edges. + fn band_spans(&self, y0: f64, y1: f64) -> Vec<(f64, f64)> { + let (low, high) = (y0 - self.offset, y1 + self.offset); + if !low.is_finite() || !high.is_finite() || high < low { + return self.band_extent(y0, y1).into_iter().collect(); + } + let mut spans = rings_band_spans(Region::nonzero(&self.rings), low, high); + // Extremely fragmented imported paths use the conservative outer extent, bounding the + // work of subtracting intervals from every line. A traced 128-column mask stays below it. + if spans.len() > 128 { + return self.band_extent(y0, y1).into_iter().collect(); + } + let clips: Vec = self.clips().collect(); + if !clips.is_empty() { + let projected: Vec> = clips.iter().map(|c| rings_band_spans(*c, low, high)).collect(); + // A fragmented clip, or shapes too detailed to compare within each line's budget, + // take the common part of the projections, which can block more than the clips show. + let mut shapes = vec![Region::nonzero(&self.rings)]; + shapes.extend(&clips); + let exact = if projected.iter().any(|p| p.len() > 128) { None } else { clipped_band_spans(&shapes, low, high) }; + spans = exact.unwrap_or_else(|| projected.iter().fold(spans, |s, p| intersect_spans(&s, p))); + } + merge_spans(spans.into_iter().map(|(a, b)| (a - self.offset, b + self.offset)).collect()) + } +} + +/// The sorted spans in both `a` and `b` (each sorted and merged). A zero-width span (a vertical +/// open path) is kept where the other covers it. +fn intersect_spans(a: &[(f64, f64)], b: &[(f64, f64)]) -> Vec<(f64, f64)> { + let mut out = Vec::new(); + let (mut i, mut j) = (0, 0); + while let (Some(&(p, q)), Some(&(r, s))) = (a.get(i), b.get(j)) { + let (lo, hi) = (p.max(r), q.min(s)); + if lo < hi || (lo == hi && (p == q || r == s)) { + out.push((lo, hi)); + } + if q < s { + i += 1; + } else { + j += 1; + } + } + out +} + +/// Occupied intervals across the band `y0..y1` of the part of the plane inside every one of +/// `shapes` (an outline and its clips). A vertical line through a point of that part either +/// crosses the middle of the band inside all the shapes, or stops inside the band on an edge of +/// one shape that lies inside the others. The spans are the middle slice of all the shapes and +/// the parts of each shape's edges in the band that lie inside the others, so a part of the +/// outline outside a clip blocks nothing, even where it shares x positions with the clip in the +/// same band. Only the edges that reach the band are visited. None when that takes more than +/// [`MAX_CLIPPED_WORK`] edge visits. +fn clipped_band_spans(shapes: &[Region], y0: f64, y1: f64) -> Option> { + let middle = y0 * 0.5 + y1 * 0.5; + let mut slices = shapes.iter().map(|s| merge_spans(middle_spans(*s, middle))); + let first = slices.next()?; + let mut spans = slices.fold(first, |a, b| intersect_spans(&a, &b)); + let banded: Vec = shapes.iter().map(|s| BandEdges::of(*s, y0, y1)).collect(); + let mut budget = MAX_CLIPPED_WORK; + for k in 0..banded.len() { + edges_inside(&banded, k, y0, y1, &mut budget, &mut spans)?; + } + Some(merge_spans(spans)) +} + +/// The edges of a shape that reach a line band, with a margin above and below. Every point +/// [`segment_inside`] tests lies within the margin, and an edge that doesn't reach a point's y +/// neither crosses the ray from it nor passes within a hair of it, so these edges give the same +/// inside and on-edge answers as the whole shape for those points. +struct BandEdges { + edges: Vec<(Point, Point)>, + even_odd: bool, +} + +impl BandEdges { + /// Margin added above and below the band; well above the side step in [`segment_inside`]. + const MARGIN: f64 = 1e-3; + + fn of(shape: Region, y0: f64, y1: f64) -> BandEdges { + let (lo, hi) = (y0 - Self::MARGIN, y1 + Self::MARGIN); + let mut edges = Vec::new(); + for ring in shape.rings { + let Some(&last) = ring.last() else { continue }; + let mut a = last; + for &b in ring { + if a.y.max(b.y) >= lo && a.y.min(b.y) <= hi { + edges.push((a, b)); + } + a = b; + } + } + BandEdges { edges, even_odd: shape.even_odd } + } + + /// Is a point with this winding number filled? + fn fills(&self, winding: i32) -> bool { + if self.even_odd { winding % 2 != 0 } else { winding != 0 } + } +} + +/// Takes `n` edge visits from `budget`; None when it doesn't hold that many. +fn spend(budget: &mut usize, n: usize) -> Option<()> { + *budget = budget.checked_sub(n)?; + Some(()) +} + +/// Pushes to `out` the x-ranges of the parts of the edges of `shapes[k]` within the band `y0..y1` +/// that bound the part of the plane inside all of `shapes` ([`segment_inside`]). None when +/// `budget` runs out. +fn edges_inside(shapes: &[BandEdges], k: usize, y0: f64, y1: f64, budget: &mut usize, out: &mut Vec<(f64, f64)>) -> Option<()> { + let n = shapes.iter().map(|o| o.edges.len()).sum::().max(1); + for &(a, b) in &shapes.get(k)?.edges { + let dy = b.y - a.y; + if a.y.max(b.y) >= y0 && a.y.min(b.y) <= y1 { + let (t0, t1) = if dy.abs() < 1e-12 { + (0.0, 1.0) + } else { + let (u, v) = ((y0 - a.y) / dy, (y1 - a.y) / dy); + (u.min(v).clamp(0.0, 1.0), u.max(v).clamp(0.0, 1.0)) + }; + let (p, q) = (a + (b - a) * t0, a + (b - a) * t1); + segment_inside(p, q, shapes, k, n, budget, out)?; + } + } + Some(()) +} + +/// Pushes to `out` the x-ranges of the parts of segment `p`–`q`, an edge of `shapes[k]`, that +/// bound the part of the plane inside all of `shapes` (`n` edges in all). The segment is split +/// where it meets the other shapes' edges, and each piece is tested at its middle: it counts when +/// the points just beside it on one side are inside all the shapes. Where `shapes[k]` has no area +/// on either side (an open path), it counts when it is inside the other shapes or on their +/// boundary. Each pass over the edges takes `n` from `budget`; None when it runs out. +fn segment_inside(p: Point, q: Point, shapes: &[BandEdges], k: usize, n: usize, budget: &mut usize, out: &mut Vec<(f64, f64)>) -> Option<()> { + let r = q - p; + let len2 = r.hypot2(); + if !len2.is_finite() { + return Some(()); + } + let at = |t: f64| p + r * t; + let in_others = |pt: Point| shapes.iter().enumerate().all(|(i, s)| i == k || inside_or_on(s, pt)); + spend(budget, n)?; + if len2 < 1e-24 { + if in_others(p) { + out.push((p.x, p.x)); + } + return Some(()); + } + // A step to either side of the segment, well above rounding at page coordinates. + let side = r.turn_90() * (1e-6 / len2.sqrt()); + let bounds_the_part = |m: Point| { + let own = shapes.get(k); + let in_own = |pt: Point| own.is_some_and(|s| inside_or_on(s, pt)); + let (a, b) = (m + side, m - side); + match (in_own(a), in_own(b)) { + (false, false) => in_others(m), + (ia, ib) => (ia && in_others(a)) || (ib && in_others(b)), + } + }; + let (ylo, yhi) = (p.y.min(q.y), p.y.max(q.y)); + let mut ts = vec![0.0, 1.0]; + for &(c, d) in shapes.iter().enumerate().filter(|(i, _)| *i != k).flat_map(|(_, s)| &s.edges) { + if c.y.max(d.y) >= ylo - 1e-9 && c.y.min(d.y) <= yhi + 1e-9 { + let e = d - c; + let denom = r.cross(e); + let w = c - p; + if denom.abs() > 1e-12 * (len2 * e.hypot2()).sqrt() { + let (t, u) = (w.cross(e) / denom, w.cross(r) / denom); + if (-1e-9..=1.0 + 1e-9).contains(&u) && (0.0..=1.0).contains(&t) { + ts.push(t); + } + } else if w.cross(r).abs() <= 1e-9 * len2.sqrt() { + // Collinear: the edge's ends split the segment. + for t in [w.dot(r) / len2, (d - p).dot(r) / len2] { + if (0.0..=1.0).contains(&t) { + ts.push(t); + } + } + } + } + } + ts.sort_by(f64::total_cmp); + ts.dedup_by(|a, b| (*a - *b).abs() < 1e-12); + for w in ts.windows(2) { + let (u, v) = (w[0], w[1]); + spend(budget, 3 * n)?; + if bounds_the_part(at(u * 0.5 + v * 0.5)) { + let (x0, x1) = (at(u).x, at(v).x); + out.push((x0.min(x1), x0.max(x1))); + } + } + Some(()) +} + +/// Is `pt`, a point within the band of `shape`'s edges, inside the shape or within a hair of one +/// of its edges? +fn inside_or_on(shape: &BandEdges, pt: Point) -> bool { + let mut winding = 0i32; + for &(a, b) in &shape.edges { + let e = b - a; + let len2 = e.hypot2(); + let t = if len2 > 0.0 { ((pt - a).dot(e) / len2).clamp(0.0, 1.0) } else { 0.0 }; + if (a + e * t - pt).hypot2() < 1e-18 { + return true; + } + if (a.y <= pt.y && pt.y < b.y) || (b.y <= pt.y && pt.y < a.y) { + let x = a.x + (pt.y - a.y) / e.y * e.x; + if x > pt.x { + winding += if e.y > 0.0 { 1 } else { -1 }; + } + } + } + shape.fills(winding) +} + +/// Sorted, overlapping spans joined. Zero-width spans (a vertical edge of an open path) are kept: +/// the wrap offset widens them, and without one they still split the line there. +fn merge_spans(mut spans: Vec<(f64, f64)>) -> Vec<(f64, f64)> { + spans.retain(|(a, b)| a.is_finite() && b.is_finite() && b >= a); + spans.sort_by(|a, b| a.0.total_cmp(&b.0)); + let mut out: Vec<(f64, f64)> = Vec::new(); + for (a, b) in spans { + if let Some(last) = out.last_mut().filter(|last| a <= last.1 + 1e-9) { + last.1 = last.1.max(b); + } else { + out.push((a, b)); + } + } + out +} + +fn rings_band_spans(shape: Region, y0: f64, y1: f64) -> Vec<(f64, f64)> { + let mut spans = middle_spans(shape, y0 * 0.5 + y1 * 0.5); + for ring in shape.rings { + let Some(&last) = ring.last() else { continue }; + let mut a = last; + for &b in ring { + let dy = b.y - a.y; + if a.y.max(b.y) >= y0 && a.y.min(b.y) <= y1 { + let (t0, t1) = if dy.abs() < 1e-12 { + (0.0, 1.0) + } else { + let (u, v) = ((y0 - a.y) / dy, (y1 - a.y) / dy); + (u.min(v).clamp(0.0, 1.0), u.max(v).clamp(0.0, 1.0)) + }; + let (x0, x1) = (a.x + t0 * (b.x - a.x), a.x + t1 * (b.x - a.x)); + spans.push((x0.min(x1), x0.max(x1))); + } + a = b; + } + } + merge_spans(spans) +} + +/// The intervals of the line at height `middle` inside `shape`, unsorted. +fn middle_spans(shape: Region, middle: f64) -> Vec<(f64, f64)> { + let mut spans = Vec::new(); + let mut crossings = Vec::new(); + for ring in shape.rings { + let Some(&last) = ring.last() else { continue }; + let mut a = last; + for &b in ring { + let dy = b.y - a.y; + if (a.y <= middle && middle < b.y) || (b.y <= middle && middle < a.y) { + let x = a.x + (middle - a.y) / dy * (b.x - a.x); + if x.is_finite() { + crossings.push((x, if dy > 0.0 { 1i32 } else { -1 })); + } + } + a = b; + } + } + crossings.sort_by(|a, b| a.0.total_cmp(&b.0)); + let mut winding = 0i32; + let mut previous = None; + for (x, delta) in crossings { + if shape.fills(winding) + && let Some(start) = previous + { + spans.push((start, x)); + } + winding += delta; + previous = Some(x); + } + spans } /// The closed polylines of `path` (after `to_inner`), flattened; None if it is empty or too detailed. @@ -491,19 +846,39 @@ fn rings_band_extent(rings: &[Vec], y0: f64, y1: f64) -> Option<(f64, f64 /// The wrap exclusion of `other` (an item whose inner space maps to the spread by `xf`) for a /// frame whose inner space is reached from the spread by `inv`. `left_page` places the object on /// a left page (for the spine sides). -pub fn exclusion(other: &Item, xf: Affine, inv: Affine, left_page: bool) -> Exclusion { +pub fn exclusion(doc: &Document, other: &Item, xf: Affine, inv: Affine, left_page: bool) -> Exclusion { let group = other.shape == designcraft_doc::Shape::Group; let b = if group { (xf * other.xf.inverse()).transform_rect_bbox(other.bounds()) } else { other.path.transformed(xf).bounds().unwrap_or(Rect::ZERO) }; - wrap_exclusion(&other.wrap, b, || (!group).then(|| contour_path(other, other.wrap.contour)), xf, inv, left_page) + let e = wrap_exclusion(&other.wrap, b, || (!group).then(|| contour_path(doc, other, &other.wrap)), xf, inv, left_page); + nothing_visible_wraps_nothing(doc, other, &other.wrap, e) } /// The wrap exclusion of the graphic placed in frame `it` (arguments as for [`exclusion`]): around /// the part of the graphic the frame shows. None if there is no graphic or it is not shown. -pub fn graphic_exclusion(it: &Item, xf: Affine, inv: Affine, left_page: bool) -> Option { +pub fn graphic_exclusion(doc: &Document, it: &Item, xf: Affine, inv: Affine, left_page: bool) -> Option { let g = it.graphic()?; let shown = g.shown_bounds(it.inner_bounds())?; - Some(wrap_exclusion(&g.wrap, xf.transform_rect_bbox(shown), || Some(contour_path(it, g.wrap.contour)), xf, inv, left_page)) + let e = wrap_exclusion(&g.wrap, xf.transform_rect_bbox(shown), || Some(contour_path(doc, it, &g.wrap)), xf, inv, left_page); + Some(nothing_visible_wraps_nothing(doc, it, &g.wrap, e)) +} + +/// An Alpha Channel contour around an image with no pixel more opaque than the threshold leaves +/// the text alone (the exclusion's mode becomes None). +fn nothing_visible_wraps_nothing(doc: &Document, it: &Item, wrap: &designcraft_doc::TextWrap, mut e: Exclusion) -> Exclusion { + if wrap.mode == WrapMode::Contour + && wrap.contour == designcraft_doc::ContourType::AlphaChannel + && wrap.path.is_none() + && let Some(g) = it.graphic() + && let Some(o) = doc.alpha_outline(g.asset, wrap.alpha_threshold) + && o.width > 0 + && o.height > 0 + && o.outer.subpaths.is_empty() + { + e.mode = WrapMode::None; + e.contour = None; + } + e } /// The exclusion of `wrap` around an object with spread-space bounds `b`; `outline` gives its @@ -511,7 +886,7 @@ pub fn graphic_exclusion(it: &Item, xf: Affine, inv: Affine, left_page: bool) -> fn wrap_exclusion( wrap: &designcraft_doc::TextWrap, b: Rect, - outline: impl FnOnce() -> Option<(designcraft_geom::BezPath, Option)>, + outline: impl FnOnce() -> Option, xf: Affine, inv: Affine, left_page: bool, @@ -529,37 +904,71 @@ fn wrap_exclusion( if let Some(custom) = wrap.path.as_ref().and_then(|p| Contour::of(&p.to_bezpath(), inv * xf, 0.0)) { let rect = custom.bounds(); let contour = matches!(wrap.mode, WrapMode::BoundingBox | WrapMode::Contour).then_some(custom); - return Exclusion { rect, mode: wrap.mode, side, contour, after: None }; + return Exclusion { rect, mode: wrap.mode, side, contour, after: None, anchor_baseline: None }; } - let contour = if wrap.mode == WrapMode::Contour { outline() } else { None }.and_then(|(path, frame)| { - let c = Contour::of(&path, inv * xf, o[0])?; - Some(match frame { - Some(frame) => c.within(&frame, inv * xf), - None => c, - }) + let contour = if wrap.mode == WrapMode::Contour { outline() } else { None }.and_then(|src| { + let mut c = Contour::of(&src.path, inv * xf, o[0])?; + if let Some(frame) = &src.frame { + c = c.within(frame, inv * xf); + } + if let Some((clip, even_odd)) = &src.graphic_clip { + c = c.within_graphic_clip(clip, *even_odd, inv * xf); + } + Some(c) }); let rect = contour.as_ref().map_or_else(|| inv.transform_rect_bbox(r), Contour::bounds); - Exclusion { rect, mode: wrap.mode, side, contour, after: None } + Exclusion { rect, mode: wrap.mode, side, contour, after: None, anchor_baseline: None } } -/// The outline a contour wrap of `kind` around frame `it` follows, in the frame's inner space, and -/// for an outline taken from the placed graphic, the frame path that clips it. Bounding Box -/// follows the part of the placed graphic the frame shows; Same As Clipping follows the graphic's -/// clipping path when it has one; detected edges, alpha channels and image paths need the image, -/// so they follow the frame's path (as other frames do). -fn contour_path(it: &Item, kind: designcraft_doc::ContourType) -> (designcraft_geom::BezPath, Option) { +/// The outline a contour wrap follows, in the frame's inner space, with what clips it. +struct Outline { + path: designcraft_geom::BezPath, + /// For an outline taken from the placed graphic: the frame path that clips it. + frame: Option, + /// For an outline traced from the graphic's pixels: the graphic's clipping region, and + /// whether it is filled even-odd. + graphic_clip: Option<(designcraft_geom::BezPath, bool)>, +} + +impl Outline { + fn clipped_by(path: designcraft_geom::BezPath, frame: designcraft_geom::BezPath) -> Outline { + Outline { path, frame: Some(frame), graphic_clip: None } + } +} + +/// The outline a contour wrap of `kind` around frame `it` follows. Bounding Box follows the part +/// of the placed graphic the frame shows; Same As Clipping follows the graphic's clipping path +/// when it has one; Alpha Channel follows the image's traced outline when the engine has traced +/// one, within the graphic's clipping path too; detected edges and image paths follow the frame's +/// path (as other frames do). +fn contour_path(doc: &Document, it: &Item, wrap: &designcraft_doc::TextWrap) -> Outline { let frame = designcraft_geom::corners::apply(&it.path, &it.corners); + let kind = wrap.contour; + if kind == designcraft_doc::ContourType::AlphaChannel + && let Some(g) = it.graphic() + && let Some(o) = doc.alpha_outline(g.asset, wrap.alpha_threshold) + && o.width > 0 + && o.height > 0 + { + let to_graphic = Affine::scale_non_uniform(g.size.0 / f64::from(o.width), g.size.1 / f64::from(o.height)); + let mut path = o.outer.to_bezpath(); + if wrap.inside_edges { + path.extend(o.holes.to_bezpath().iter()); + } + // The clipping path hides the pixels outside it. + return Outline { graphic_clip: g.clip_region(), ..Outline::clipped_by(g.xf * to_graphic * path, frame) }; + } if kind == designcraft_doc::ContourType::SameAsClipping && let Some((path, _)) = it.graphic().and_then(|g| g.clip_region()) { - return (path, Some(frame)); + return Outline::clipped_by(path, frame); } if kind == designcraft_doc::ContourType::BoundingBox && let Some(r) = it.graphic().and_then(|g| g.shown_bounds(it.inner_bounds())) { - return (designcraft_geom::kurbo::Shape::to_path(&r, 0.1), Some(frame)); + return Outline::clipped_by(designcraft_geom::kurbo::Shape::to_path(&r, 0.1), frame); } - (frame, None) + Outline { path: frame, frame: None, graphic_clip: None } } /// One frame of the thread, ready for composition. @@ -579,8 +988,10 @@ pub struct FrameSpec { pub page_name: Option, /// Marker text of the section the frame's page is in (None on parent pages). pub section_marker: Option, - /// Absolute document page the frame is on (None on parent pages). + /// Absolute document page the frame is on (None on parent pages and the pasteboard). pub page: Option, + /// The frame is on a parent spread. + pub parent: bool, /// Baseline grid in inner space: (first grid line y, increment). pub grid: Option<(f64, f64)>, /// The frame is on a left page (for towards/away-from-spine alignment). @@ -593,6 +1004,13 @@ pub struct FrameSpec { } impl FrameSpec { + /// The baseline grid when the text area can be counted in its steps: a step so small, or a + /// first line so far off, that the count is more than an f64 holds is no grid (as for the lines). + fn countable_grid(&self) -> Option<(f64, f64)> { + self.grid + .filter(|&(g_start, inc)| inc > 0.0 && inc.is_finite() && [self.area.y0, self.area.y1].iter().all(|y| ((y - g_start) / inc).is_finite())) + } + pub fn columns(&self) -> Vec { let a = self.area; // Primary frames inherit the document limit (216), beyond the interactive frame editor's 40. @@ -642,20 +1060,32 @@ const MAX_WRAP_DEPTH: usize = 64; /// the spread; `skip` is the text frame being wrapped; `left_page` tells whether a spread x is on /// a left page. #[allow(clippy::too_many_arguments)] -fn wrap_obstacles(it: &Item, parent: Affine, inv: Affine, skip: ItemId, left_page: &dyn Fn(f64) -> bool, depth: usize, out: &mut Vec) { +fn wrap_obstacles( + doc: &Document, + it: &Item, + parent: Affine, + inv: Affine, + skip: ItemId, + left_page: &dyn Fn(f64) -> bool, + depth: usize, + out: &mut Vec, +) { if it.id == skip || it.hidden || depth > MAX_WRAP_DEPTH { return; } let xf = parent * it.xf; let left = || left_page(parent.transform_rect_bbox(it.bounds()).center().x); + // An exclusion whose mode came back None (nothing visible to wrap) is left out. if it.wrap.mode != WrapMode::None { - out.push(exclusion(it, xf, inv, left())); + out.extend(Some(exclusion(doc, it, xf, inv, left())).filter(|e| e.mode != WrapMode::None)); } match &it.content { - Content::Graphic(g) if g.wrap.mode != WrapMode::None => out.extend(graphic_exclusion(it, xf, inv, left())), + Content::Graphic(g) if g.wrap.mode != WrapMode::None => { + out.extend(graphic_exclusion(doc, it, xf, inv, left()).filter(|e| e.mode != WrapMode::None)) + } Content::Group { .. } => { for c in it.shown_children() { - wrap_obstacles(c, xf, inv, skip, left_page, depth + 1, out); + wrap_obstacles(doc, c, xf, inv, skip, left_page, depth + 1, out); } } _ => {} @@ -672,7 +1102,7 @@ fn frame_wrap_exclusions(doc: &Document, sp: &designcraft_doc::Spread, item: &It if doc.layer(other.layer).is_some_and(|l| !l.visible) { continue; } - wrap_obstacles(other, Affine::IDENTITY, inv, item.id, &left, 0, exclusions); + wrap_obstacles(doc, other, Affine::IDENTITY, inv, item.id, &left, 0, exclusions); } let a = item.text_area(); exclusions.retain(|e| { @@ -786,10 +1216,7 @@ pub(crate) fn frame_specs_placed(doc: &Document, sid: StoryId, placed: &[(ItemId // area (all four insets) still bounds the lines. let outline = match &tf.options.path { Some(_) => None, - None => { - let bp = if item.corners.is_none() { item.path.to_bezpath() } else { designcraft_geom::corners::apply(&item.path, &item.corners) }; - FrameOutline::new(&bp, tf.options.inset[0]) - } + None => FrameOutline::of_item(item, tf.options.inset[0]), }; // Vertical type: composed in the turned box; wraps and page rects turned with it. let vertical = doc.frame_vertical(item); @@ -815,6 +1242,7 @@ pub(crate) fn frame_specs_placed(doc: &Document, sid: StoryId, placed: &[(ItemId page_name, section_marker, page, + parent: matches!(spread_ref, Some(designcraft_doc::SpreadRef::Parent(_))), grid, left_page, right_page, @@ -828,16 +1256,31 @@ pub(crate) fn frame_specs_placed(doc: &Document, sid: StoryId, placed: &[(ItemId /// objects ([`wrap`]). /// Anchored frames are composed where their host story places them (unless `opts` places them). pub fn compose_story(doc: &Document, sid: StoryId, opts: &ComposeOptions) -> ComposedStory { - compose_story_at(doc, sid, opts, 0) + compose_story_at(doc, sid, opts, 0, &mut HashMap::new()) } -/// [`compose_story`] for a story `depth` hosts down from the story asked for. -fn compose_story_at(doc: &Document, sid: StoryId, opts: &ComposeOptions, depth: usize) -> ComposedStory { +/// [`compose_story`] for a story `depth` hosts down from the story asked for. `hosts` holds the +/// hosts already composed (by story and depth) while composing the story asked for, so a host +/// that many anchored frames lead to is composed once. +fn compose_story_at( + doc: &Document, + sid: StoryId, + opts: &ComposeOptions, + depth: usize, + hosts: &mut HashMap<(StoryId, usize), Arc>, +) -> ComposedStory { let others: Vec = wrap::neighbours(doc, sid).into_iter().map(|o| wrap::compose_among(doc, o, &ComposeOptions::default(), &[])).collect(); let others: Vec<&ComposedStory> = others.iter().collect(); if opts.placed.is_empty() && depth < placed::MAX_DEPTH { - let placed = placed::placements(doc, sid, &mut |host| Arc::new(compose_story_at(doc, host, &ComposeOptions::default(), depth + 1))); + let placed = placed::placements(doc, sid, &mut |host| { + if let Some(c) = hosts.get(&(host, depth + 1)) { + return c.clone(); + } + let c = Arc::new(compose_story_at(doc, host, &ComposeOptions::default(), depth + 1, hosts)); + hosts.insert((host, depth + 1), c.clone()); + c + }); if !placed.is_empty() { return wrap::compose_among(doc, sid, &ComposeOptions { placed, ..opts.clone() }, &others); } @@ -860,15 +1303,70 @@ struct SubstitutionInput<'a> { frame: Option<&'a FrameSpec>, opts: &'a ComposeOptions, var_story: bool, - var_cache: &'a mut HashMap, Arc>>, + var_cache: &'a mut HashMap<(Option, bool), Arc>>, notes: &'a mut Notes, + /// The marks in the story before `range`. + marks: MarkCounts, +} + +/// Endnote references, anchored-object marks and cross-reference marks in a stretch of story text. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +struct MarkCounts { + endnotes: usize, + objects: usize, + xrefs: usize, +} + +#[cfg(test)] +thread_local! { + /// Bytes of story text [`MarkCounts::of`] has read on this thread. + static MARK_BYTES_SCANNED: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +impl MarkCounts { + /// The marks in `text`. + fn of(text: &str) -> Self { + #[cfg(test)] + MARK_BYTES_SCANNED.with(|n| n.set(n.get() + text.len())); + let mut m = Self::default(); + for c in text.chars() { + match c { + designcraft_doc::ENDNOTE_REF => m.endnotes += 1, + designcraft_doc::OBJECT_MARK => m.objects += 1, + designcraft_doc::XREF_MARK => m.xrefs += 1, + _ => {} + } + } + m + } + + /// The marks before each paragraph of `ranges` (the story's paragraphs, in order), read in + /// one pass over the story. Empty when the story holds no endnotes, anchored objects or + /// cross-references. + fn before_paragraphs(story: &Story, ranges: &[Range]) -> Vec { + if story.endnotes.is_empty() && story.objects.is_empty() && story.xrefs.is_empty() { + return Vec::new(); + } + let mut total = Self::default(); + ranges + .iter() + .map(|r| { + let before = total; + let m = story.text.get(r.clone()).map_or_else(Self::default, Self::of); + total = Self { endnotes: total.endnotes + m.endnotes, objects: total.objects + m.objects, xrefs: total.xrefs + m.xrefs }; + before + }) + .collect() + } } fn paragraph_substitution(input: SubstitutionInput<'_>) -> SubstCtx { - let SubstitutionInput { doc, story, range: prange, props: pp, frame: cur_frame, opts, var_story, var_cache, notes } = input; + let SubstitutionInput { doc, story, range: prange, props: pp, frame: cur_frame, opts, var_story, var_cache, notes, marks } = input; let var_values = if var_story { let page = opts.page.or_else(|| cur_frame.and_then(|f| f.page)); - var_cache.entry(page).or_insert_with(|| std::sync::Arc::new(vars::values(doc, page, opts.running.as_deref()))).clone() + // A parent page itself (not composed for one of the pages it applies to). + let parent = page.is_none() && cur_frame.is_some_and(|f| f.parent); + var_cache.entry((page, parent)).or_insert_with(|| std::sync::Arc::new(vars::values_shown(doc, page, parent, opts.running.as_deref()))).clone() } else { Default::default() }; @@ -885,13 +1383,13 @@ fn paragraph_substitution(input: SubstitutionInput<'_>) -> SubstCtx { }; if !story.endnotes.is_empty() { // Endnote reference numbers continue through the document. - let first = doc.endnote_start(story.id).saturating_add(story.text[..prange.start].matches(designcraft_doc::ENDNOTE_REF).count() as u32); + let first = doc.endnote_start(story.id).saturating_add(u32::try_from(marks.endnotes).unwrap_or(u32::MAX)); for (k, (i, _)) in story.text[prange.clone()].match_indices(designcraft_doc::ENDNOTE_REF).enumerate() { sub.notes.insert(prange.start + i, doc.endnote_options.label(first.saturating_add(k as u32))); } } if !story.objects.is_empty() { - let before = story.text[..prange.start].matches(designcraft_doc::OBJECT_MARK).count(); + let before = marks.objects; for (k, (i, _)) in story.text[prange.clone()].match_indices(designcraft_doc::OBJECT_MARK).enumerate() { let Some(o) = story.objects.get(before + k) else { continue }; let (w, h) = o.size(); @@ -904,7 +1402,7 @@ fn paragraph_substitution(input: SubstitutionInput<'_>) -> SubstCtx { } } if !story.xrefs.is_empty() { - sub.xrefs = xref::texts_in(doc, story, prange.clone(), opts.xrefs.as_deref()); + sub.xrefs = xref::texts_after(doc, story, prange.clone(), marks.xrefs, opts.xrefs.as_deref()); } if notes.active() { notes.number_refs(doc, prange.clone(), cur_frame.and_then(|f| f.page), &mut sub); @@ -930,18 +1428,25 @@ fn line_has_wrapping_exclusion(frame: &FrameSpec, range: Range, column: R }) } -fn previous_visible_break(doc: &Document, story: &Story, ranges: &[Range], deleted: &[bool], pi: usize) -> Option { +/// The visible break ending the last placed paragraph before `pi`, which sends `pi` on. +pub fn previous_visible_break(doc: &Document, story: &Story, ranges: &[Range], deleted: &[bool], pi: usize) -> Option { (0..pi).rev().find(|&p| !deleted.get(p).copied().unwrap_or(false)).and_then(|p| { let range = ranges.get(p)?; - let (index, character) = story.text.get(range.clone())?.char_indices().next_back()?; - let start = break_start(character)?; - let (_, chars) = doc.styles.resolve_para(story.paras.get(p)?); - let props = doc.styles.resolve_char(&chars, story.char_format_at(range.start + index + character.len_utf8())); - let gone = props.change == designcraft_doc::ChangeMark::Deleted || doc.conditions_hide(&props.conditions); - (!gone).then_some(start) + let (index, _) = story.text.get(range.clone())?.char_indices().next_back()?; + visible_break(doc, story, p, range.start + index) }) } +/// The start option of the break at byte `at` in paragraph `p`, unless deleted or hidden. +pub fn visible_break(doc: &Document, story: &Story, p: usize, at: usize) -> Option { + let character = story.text.get(at..)?.chars().next()?; + let start = break_start(character)?; + let (_, chars) = doc.styles.resolve_para(story.paras.get(p)?); + let props = doc.styles.resolve_char(&chars, story.char_format_at(at + character.len_utf8())); + let gone = props.change == designcraft_doc::ChangeMark::Deleted || doc.conditions_hide(&props.conditions); + (!gone).then_some(start) +} + fn named_list_labels(doc: &Document, story: &Story, ranges: &[Range], deleted: &[bool]) -> Vec> { let mut counters: std::collections::HashMap = std::collections::HashMap::new(); story @@ -999,6 +1504,9 @@ fn frame_columns_and_text(frames: &[FrameSpec], direction: designcraft_doc::Text } struct ParagraphProgressInput<'a> { + /// Nothing is left to lay: the rest of the story is in place, or the pass is abandoned + /// ([`reuse::Pass::step`]). + done: bool, paragraph: usize, count: usize, balance_frames: usize, @@ -1018,7 +1526,10 @@ enum ParagraphProgress { } fn paragraph_progress(input: ParagraphProgressInput<'_>) -> ParagraphProgress { - let ParagraphProgressInput { paragraph, count, balance_frames, trial, limits, cursor, columns, frames, out, may_retry } = input; + let ParagraphProgressInput { done, paragraph, count, balance_frames, trial, limits, cursor, columns, frames, out, may_retry } = input; + if done { + return ParagraphProgress::Complete; + } if paragraph < count { return ParagraphProgress::Continue; } @@ -1099,7 +1610,7 @@ fn place_table_paragraph(input: TableParagraphInput<'_>) -> TableParagraphResult } let at_top = cursor.last_baseline.is_none(); let start_at = (cursor.fi, cursor.col); - if !table::place_table(doc, table, anchor, paragraph, props, frames, columns, cursor, out, opts) { + if !table::place_table(doc, table, anchor, paragraph, props, frames, columns, cursor, out, notes, opts) { if let Some(j) = trial_failed(trial, limits, *balance_runs < balance_budget) { *balance_runs += 1; rewind(j, snaps, note_snaps, notes, out, cursor, list_counter, force_col, line_cap, no_hyph); @@ -1133,6 +1644,8 @@ struct NestedLineStyleInput<'a, 'b, 'font> { range: Range, props: &'a designcraft_doc::ParaProps, para_chars: &'a designcraft_doc::CharProps, + /// The paragraph has CJK text, so its 禁則 priority applies. + cjk: bool, drop_end: usize, base_leading: f64, base_cap: f64, @@ -1158,6 +1671,7 @@ fn apply_nested_line_styles(input: NestedLineStyleInput<'_, '_, '_>) { range: prange, props: pp, para_chars: base_chars, + cjk, drop_end, base_leading, base_cap, @@ -1180,11 +1694,14 @@ fn apply_nested_line_styles(input: NestedLineStyleInput<'_, '_, '_>) { let cols_here = &cols[cur.fi]; let col = span_rect(cols_here, cols_here[cur.col.min(cols_here.len() - 1)], pp.span_columns); let col = SplitCfg::of(pp).map_or(col, |c| c.sub_rect(col, 0)); - let spacing = spacing_for(pp, base_chars.size, story); + let spacing = spacing_for(pp, base_chars.size, story, cjk); let mut lines: Vec<(std::ops::Range, String)> = Vec::new(); for _ in 0..3 { // The same drop cap, spacing, hyphenation and breaker as the layout below. let mut gl = sp.glyphs.clone(); + // Classified before the drop cap is split off: `split_drop_cap` takes those glyphs out + // of the vector, and the drop cap's character still votes (#1688). + let korean = hyphen::korean_paragraph(gl.iter().map(|g| (g.byte, g.ch, g.list_label || g.generated_text.is_some()))); let dc = split_drop_cap(db, &mut gl, drop_end, pp.drop_cap_lines, base_leading, base_cap, drop_grid, drop_align, drop_tabs); let width = |j: usize| { let ind = match &dc { @@ -1196,7 +1713,7 @@ fn apply_nested_line_styles(input: NestedLineStyleInput<'_, '_, '_>) { }; apply_desired_spacing(&mut gl, pp); mojikumi::apply(&mut gl, &doc.styles, &pp.mojikumi); - let mut hy = hyphenation_points(&story.text, &gl, pp, hyph_exceptions, &foreign_ranges(doc, story, prange.clone(), base_chars)); + let mut hy = hyphenation_points(&story.text, &gl, pp, hyph_exceptions, &foreign_ranges(doc, story, prange.clone(), base_chars), korean); suppress_hyphens(&mut hy, &gl, suppressed_hyphens); let breaks = if pp.composer.single_line() || gl.iter().any(|g| g.ch == '\t') || gl.len() > 4000 { let tab = |j: usize, x: f64, i: usize| { @@ -1408,8 +1925,14 @@ fn position_line(input: PositionLineInput<'_, '_>) -> LinePosition { if cur.last_baseline.is_some() { baseline += cur.last_reference - reference; } - let grid = f.grid.filter(|&(_, inc)| { - inc > 0.0 && inc.is_finite() && (pp.grid_align == GridAlign::AllLines || (pp.grid_align == GridAlign::FirstLineOnly && line_no == 0)) + // A step so small that the column holds more steps than an f64 can count is no grid: the + // line is placed as it is without one. + let countable = |g_start: f64, inc: f64| [baseline, col.y0, col.y1].iter().all(|y| ((y - g_start) / inc).is_finite()); + let grid = f.grid.filter(|&(g_start, inc)| { + inc > 0.0 + && inc.is_finite() + && countable(g_start, inc) + && (pp.grid_align == GridAlign::AllLines || (pp.grid_align == GridAlign::FirstLineOnly && line_no == 0)) }); if let Some((g_start, inc)) = grid { let n = pp.grid_gyoudori.min(grid::MAX_GYOUDORI); @@ -1803,6 +2326,8 @@ fn place_sub_objects( } } +/// Sets one paragraph's lines, column after column and frame after frame. It stops when the +/// paragraph ends, when the frames run out, or when an earlier paragraph has to be set again. fn place_paragraph_lines(shared: PlacementShared<'_, '_>, paragraph: ParagraphLines<'_>) -> LinePlacement { let PlacementShared { doc, @@ -1835,7 +2360,7 @@ fn place_paragraph_lines(shared: PlacementShared<'_, '_>, paragraph: ParagraphLi let ParagraphLines { paragraph: pi, range: prange, - props: pp, + props: para_props, glyphs, hyph_after, drop_cap, @@ -1864,7 +2389,10 @@ fn place_paragraph_lines(shared: PlacementShared<'_, '_>, paragraph: ParagraphLi let mut hyphen_at: Option = None; let has_tabs = glyphs.iter().any(|g| g.ch == '\t'); let mut first_line_rect: Option<(usize, f64, f64, f64)> = None; // frame, baseline, ascent, x-span - let rtl = pp.direction == designcraft_doc::TextDirection::RightToLeft; + let rtl = para_props.direction == designcraft_doc::TextDirection::RightToLeft; + // The paragraph's settings with the start-side indent an Indent to Here character set for + // the lines after it (InDesign's ^i): those lines start where the character sits. + let mut indented: Option = None; // Paragraph gyoudori: the (frame, column) of the block and the grid line after it. let mut para_block: Option<((usize, usize), f64)> = None; // Segments of a line already placed (beside an object with text on both sides) that the @@ -1898,6 +2426,10 @@ fn place_paragraph_lines(shared: PlacementShared<'_, '_>, paragraph: ParagraphLi no_hyph, }); } + let pp = indented.as_ref().unwrap_or(para_props); + // The Indent to Here character sits past the drop cap, so the lines that start at it + // aren't indented by the drop cap again. + let beside_cap = drop_cap.filter(|_| indented.is_none()); let f = &frames[cur.fi]; let base = cols[cur.fi][cur.col.min(cols[cur.fi].len() - 1)]; let col = cur.clip(base); @@ -1923,7 +2455,7 @@ fn place_paragraph_lines(shared: PlacementShared<'_, '_>, paragraph: ParagraphLi props: pp, slots: &slots, column: col, - drop_cap, + drop_cap: beside_cap, line_no, col_first_line, rtl, @@ -1931,6 +2463,8 @@ fn place_paragraph_lines(shared: PlacementShared<'_, '_>, paragraph: ParagraphLi spacing, }); let mut moved = false; + // Set by a line with an Indent to Here character, for the lines broken again after it. + let mut reindented = None; for (k, b) in breaks.iter().enumerate() { let (s, e) = (g0 + b.start, g0 + b.end); let line_glyphs = &glyphs[s..e.max(s)]; @@ -2046,7 +2580,7 @@ fn place_paragraph_lines(shared: PlacementShared<'_, '_>, paragraph: ParagraphLi let col_w = notes.area(&cols[cur.fi], cur.col).map_or(0.0, |r| r.width()); let note_column = NoteColumn { frame_index: cur.fi, column_index: cur.col, width: col_w, frame: f }; // A drop cap sits at the start-side indent; the first-line indent doesn't move it. - let beside = drop_cap.filter(|dc| line_no < dc.lines && col_first_line == 0).map(|dc| dc.indent()); + let beside = beside_cap.filter(|dc| line_no < dc.lines && col_first_line == 0).map(|dc| dc.indent()); let first_line = if line_no == 0 { pp.first_line_indent } else { 0.0 }; let (ind_l, ind_r) = match beside { Some(w) if rtl => (pp.left_indent, pp.right_indent + w), @@ -2098,6 +2632,7 @@ fn place_paragraph_lines(shared: PlacementShared<'_, '_>, paragraph: ParagraphLi } ruby::annotate(db, styles_tab, &story.text, &mut placed, doc.settings.glyph_fallback, f.vertical); kenten::annotate(db, styles_tab, &mut placed, doc.settings.glyph_fallback); + let here_props = indent_here(&placed, pp, x0, x1, rtl); let range_end = if last { prange.end } else { glyphs.get(g0 + b.next).map(|g| g.byte).unwrap_or(prange.end) }; let range_start = glyphs.get(s).map(|g| g.byte).unwrap_or(prange.start).min(range_end); let range_start = if line_no == 0 { prange.start } else { range_start }; @@ -2156,6 +2691,10 @@ fn place_paragraph_lines(shared: PlacementShared<'_, '_>, paragraph: ParagraphLi hyphen_at = e.checked_sub(1).filter(|&i| b.hyphen && hyph_after.get(i) == Some(&true)).and_then(|i| glyphs.get(i)).map(|g| g.byte + g.len); line_no += 1; + // An Indent to Here character in this line moves the start of the lines after it: + // break them again with that indent (it holds into the next columns too). + let reindent = here_props.is_some(); + reindented = here_props.or(reindented); // A column / frame / page break inside the paragraph: the rest of it continues in the // new column/frame/page, re-broken there. (A break that ends the paragraph moves the // next paragraph instead.) @@ -2169,12 +2708,13 @@ fn place_paragraph_lines(shared: PlacementShared<'_, '_>, paragraph: ParagraphLi } // An own-story anchored object anchored in this line wraps the lines after it, // which were broken without it: break them again. - if k + 1 < breaks.len() && line_has_wrapping_exclusion(f, range_start..range_end, col, baseline) { + if k + 1 < breaks.len() && (reindent || line_has_wrapping_exclusion(f, range_start..range_end, col, baseline)) { g0 += b.next; moved = true; break; } } + indented = reindented.or(indented); if !moved { break; } @@ -2265,6 +2805,10 @@ fn shape_paragraph(input: ParagraphShapeInput<'_, '_>) -> ShapedParagraph { }, &mut table, ); + // The paragraph's script decides whether its 禁則 priority applies. Classify the shaped + // glyphs before split_drop_cap removes the drop cap and prepend_label adds the list + // label: a CJK drop cap is part of the paragraph, a generated label is not. + let cjk = paragraph_is_cjk(&sp.glyphs); // An empty paragraph has no glyphs of its own, so its only addressable character is its // hidden paragraph mark (the `\n` just past `prange.end`). A leading/size override applied // there (e.g. selecting the pilcrow to adjust line height) still needs to set the line's @@ -2285,7 +2829,7 @@ fn shape_paragraph(input: ParagraphShapeInput<'_, '_>) -> ShapedParagraph { let face = db.face(&base_chars.font_family, &base_chars.font_style); face.cap_height * base_chars.size / face.upem * base_chars.v_scale }; - let drop_grid = cur_frame.and_then(|f| f.grid).filter(|_| pp.grid_align == GridAlign::AllLines).map(|g| g.1); + let drop_grid = cur_frame.and_then(FrameSpec::countable_grid).filter(|_| pp.grid_align == GridAlign::AllLines).map(|g| g.1); // Align Left Edge (left-to-right paragraphs). let drop_align = pp.drop_cap_align_left && pp.direction == designcraft_doc::TextDirection::LeftToRight; // Tab stops for the drop cap, with the start-side indent (the right one, right to left). @@ -2297,6 +2841,7 @@ fn shape_paragraph(input: ParagraphShapeInput<'_, '_>) -> ShapedParagraph { range: prange.clone(), props: pp, para_chars: base_chars, + cjk, drop_end, base_leading, base_cap, @@ -2319,6 +2864,8 @@ fn shape_paragraph(input: ParagraphShapeInput<'_, '_>) -> ShapedParagraph { g.and_then(|g| table.styles.get(g.style as usize)).map_or((base_chars.fill.clone(), base_chars.fill_tint), |s| (s.fill.clone(), s.fill_tint)) }; let (above, below) = (text_color(sp.glyphs.iter().find(|g| g.len > 0)), text_color(sp.glyphs.iter().rev().find(|g| g.len > 0))); + // Classified before the drop cap is split off (see the same call in the measuring loop above). + let korean = hyphen::korean_paragraph(sp.glyphs.iter().map(|g| (g.byte, g.ch, g.list_label || g.generated_text.is_some()))); let drop_cap = split_drop_cap( db, &mut sp.glyphs, @@ -2408,10 +2955,11 @@ fn shape_paragraph(input: ParagraphShapeInput<'_, '_>) -> ShapedParagraph { ); apply_desired_spacing(&mut glyphs, pp); mojikumi::apply(&mut glyphs, &doc.styles, &pp.mojikumi); - let mut hyph_after = hyphenation_points(&story.text, &glyphs, pp, hyph_exceptions, &foreign_ranges(doc, story, prange.clone(), base_chars)); + let mut hyph_after = + hyphenation_points(&story.text, &glyphs, pp, hyph_exceptions, &foreign_ranges(doc, story, prange.clone(), base_chars), korean); suppress_hyphens(&mut hyph_after, &glyphs, suppressed_hyphens); let base_size = base_chars.size; - let spacing = spacing_for(pp, base_size, story); + let spacing = spacing_for(pp, base_size, story, cjk); // An empty paragraph takes its height from its paragraph mark's character format. let mark_chars = if glyphs.is_empty() { doc.styles.resolve_char(base_chars, story.char_format_of(prange.start)) } else { base_chars.clone() }; let mark_leading = match mark_chars.leading { @@ -2562,7 +3110,12 @@ fn finish_paragraph(input: ParagraphFinishInput<'_>) -> ParagraphFinish { .map(|l| if r.column_width { (l.x0, l.x1) } else { (l.x0, l.end_x) }) .unwrap_or((0.0, 0.0)); let (color, tint) = rule_color(r, above); - ft.decos.push(Deco { rect: Rect::new(col.0 + r.left_indent, y - r.weight, col.1 - r.right_indent, y), color, tint, ..Deco::default() }); + // Keep In Frame: not above the frame, as InDesign's (its top, not the text area's + // below the top inset). + let top = frames.get(fi).map_or(f64::NEG_INFINITY, |f| f.area.y0 - if f.vertical { 0.0 } else { f.opts.inset[0] }); + let y = if r.keep_in_frame && y - r.weight < top { top + r.weight } else { y }; + let rect = Rect::new(col.0 + r.left_indent, y - r.weight, col.1 - r.right_indent, y); + ft.decos.extend(rule_decos(doc, r, rect, (color, tint), above)); } } if pp.rule_below.on @@ -2573,7 +3126,7 @@ fn finish_paragraph(input: ParagraphFinishInput<'_>) -> ParagraphFinish { let y = l.baseline + r.offset; let (x0, x1) = if r.column_width { (l.x0, l.x1) } else { (l.x0, l.end_x) }; let (color, tint) = rule_color(r, below); - ft.decos.push(Deco { rect: Rect::new(x0 + r.left_indent, y, x1 - r.right_indent, y + r.weight), color, tint, ..Deco::default() }); + ft.decos.extend(rule_decos(doc, r, Rect::new(x0 + r.left_indent, y, x1 - r.right_indent, y + r.weight), (color, tint), below)); } // The end of a split block: text after it continues below its deepest sub-column, which // are balanced first. A block that ends the story fills its sub-columns in turn. @@ -2620,6 +3173,40 @@ fn finish_paragraph(input: ParagraphFinishInput<'_>) -> ParagraphFinish { } fn compose_with_db(doc: &Document, story: &Story, frames: &[FrameSpec], opts: &ComposeOptions, db: &FontDb) -> ComposedStory { + compose_run(doc, story, frames, opts, db, None, false).map(|(out, _)| out).unwrap_or_default() +} + +/// [`compose`], leaving a trace for composing the story again after an edit when it can +/// ([`reuse`]). With `before` (the story before an edit, its composition and trace), only the +/// paragraphs the edit can change are composed, when the trace covers the edit. +pub(crate) fn compose_traced( + doc: &Document, + story: &Story, + frames: &[FrameSpec], + opts: &ComposeOptions, + before: Option>, +) -> (ComposedStory, Option) { + let db = FontDb::global(); + if before.is_some() + && let Some(done) = compose_run(doc, story, frames, opts, db, before.as_ref(), true) + { + return done; + } + compose_run(doc, story, frames, opts, db, None, true).unwrap_or_default() +} + +/// Compose `story` into `frames`, from its start or from what `before` holds for it; with +/// `traced`, also give the trace when the composition can leave one. `None` only with `before`: +/// its trace does not cover the edit, so the story has to be composed from its start. +fn compose_run( + doc: &Document, + story: &Story, + frames: &[FrameSpec], + opts: &ComposeOptions, + db: &FontDb, + before: Option<&reuse::Reuse<'_>>, + traced: bool, +) -> Option<(ComposedStory, Option)> { let db = &db.scoped(doc.font_scope); let mut out = ComposedStory { story: story.id, rev: story.rev, text_len: story.text.len(), ..Default::default() }; let mut styles_tab: Vec = Vec::new(); @@ -2648,6 +3235,8 @@ fn compose_with_db(doc: &Document, story: &Story, frames: &[FrameSpec], opts: &C let mut list_counter = ListCounter::default(); // Named lists number independently of layout: one pass up front, for the labels. let named_labels = named_list_labels(doc, story, ¶_ranges, &deleted); + // Endnote, anchored-object and cross-reference marks before each paragraph, for their numbers. + let marks_before = MarkCounts::before_paragraphs(story, ¶_ranges); // Border and shading of each paragraph set, drawn once the lines are in place. let mut boxes: Vec> = vec![None; np]; // Keep options: paragraphs are re-laid from a snapshot when a keep is violated, either forced @@ -2667,7 +3256,7 @@ fn compose_with_db(doc: &Document, story: &Story, frames: &[FrameSpec], opts: &C let var_story = vars::has_vars(story); let mut notes = Notes::new(doc, story); let mut note_snaps: Vec<(u32, Option, usize)> = Vec::with_capacity(np); - let mut var_cache: std::collections::HashMap, std::sync::Arc>> = Default::default(); + let mut var_cache: std::collections::HashMap<(Option, bool), std::sync::Arc>> = Default::default(); // Column balancing above spanning paragraphs: settled and trial bottoms by band, the search // in progress, and a budget for the re-lays. let mut limits: Rc> = Rc::default(); @@ -2686,6 +3275,17 @@ fn compose_with_db(doc: &Document, story: &Story, frames: &[FrameSpec], opts: &C // and in split columns. let mut span_paras = vec![false; np]; let mut split_paras = vec![false; np]; + // Each paragraph's Align to Baseline Grid (vertical justification moves grid-aligned lines by + // whole grid steps). + let mut grid_paras = vec![GridAlign::None; np]; + // Composing again after an edit starts at the paragraph above it ([`reuse`]). The entries + // for the paragraphs before that one are never read: going back over a paragraph abandons the + // pass. + let plain = traced && reuse::plain(story, frames, opts, &named_labels, &deleted); + let (mut pass, start) = reuse::Pass::new(before, story, plain, reuse::Start { pi, cur, list_counter, info }, &mut out, &mut styles_tab); + (pi, cur, list_counter, info) = (start.pi, start.cur, start.list_counter, start.info); + snaps.extend((0..pi).map(|_| Snapshot::take(&out, &cur, &list_counter))); + note_snaps.resize(pi, (notes.num, notes.key, 0)); 'paras: while pi <= np { cur.pi = pi; cur.limits = Rc::clone(&limits); @@ -2696,8 +3296,12 @@ fn compose_with_db(doc: &Document, story: &Story, frames: &[FrameSpec], opts: &C note_snaps.truncate(pi); note_snaps.push((notes.num, notes.key, notes.placed.len())); info.truncate(pi); + // Whether nothing is left to lay: the rest of the story is in place, copied from its + // composition before an edit, or that composition turned out not to hold for this one. + let done = pass.step((pi, np), snaps.last(), &mut out, &mut styles_tab, &mut info); // A balancing trial whose band ran past its frame: re-lay the band with more room. - if trial.as_ref().is_some_and(|t| cur.fi > t.key.0) + if !done + && trial.as_ref().is_some_and(|t| cur.fi > t.key.0) && let Some(j) = trial_failed(&mut trial, &mut limits, balance_runs < balance_budget) { balance_runs += 1; @@ -2706,6 +3310,7 @@ fn compose_with_db(doc: &Document, story: &Story, frames: &[FrameSpec], opts: &C continue 'paras; } match paragraph_progress(ParagraphProgressInput { + done, paragraph: pi, count: np, balance_frames, @@ -2791,7 +3396,10 @@ fn compose_with_db(doc: &Document, story: &Story, frames: &[FrameSpec], opts: &C var_story, var_cache: &mut var_cache, notes: &mut notes, + marks: marks_before.get(pi).copied().unwrap_or_default(), }); + #[cfg(test)] + reuse::SHAPED.with(|n| n.set(n.get() + 1)); let shaped = shape_paragraph(ParagraphShapeInput { db, doc, @@ -2845,6 +3453,7 @@ fn compose_with_db(doc: &Document, story: &Story, frames: &[FrameSpec], opts: &C // it, a paragraph moves on to the next sub-column. let split_cfg = SplitCfg::of(&pp); split_paras[pi] = split_cfg.is_some(); + grid_paras[pi] = pp.grid_align; if cur.split.is_some_and(|s| Some(s.cfg) != split_cfg) { cur.split = None; } @@ -3063,17 +3672,21 @@ fn compose_with_db(doc: &Document, story: &Story, frames: &[FrameSpec], opts: &C cur.pending += if spans_in_current_frame || ends_split { pp.space_after.max(pp.span_space_after) } else { pp.space_after }; pi += 1; } - finish_composition(FinishInput { - doc, - story, - frames, - cols: &cols, - notes: &mut notes, - out: &mut out, - boxes: &boxes, - span_paras: &span_paras, - split_paras: &split_paras, - styles_tab, + pass.trace(reuse::plain_end(&span_paras, &split_paras, &boxes), &snaps, info).map(|trace| { + let out = finish_composition(FinishInput { + doc, + story, + frames, + cols: &cols, + notes: &mut notes, + out: &mut out, + boxes: &boxes, + span_paras: &span_paras, + split_paras: &split_paras, + grid_paras: &grid_paras, + styles_tab, + }); + (out, trace) }) } @@ -3087,12 +3700,15 @@ struct FinishInput<'a> { boxes: &'a [Option], span_paras: &'a [bool], split_paras: &'a [bool], + grid_paras: &'a [GridAlign], styles_tab: Vec, } fn finish_composition(input: FinishInput<'_>) -> ComposedStory { - let FinishInput { doc, story, frames, cols, notes, out, boxes, span_paras, split_paras, styles_tab } = input; + let FinishInput { doc, story, frames, cols, notes, out, boxes, span_paras, split_paras, grid_paras, styles_tab } = input; notes.finish(doc, story, frames, cols, out); + // The story byte of each anchored object's mark, found once for every frame that holds one. + let mut marks: Option> = None; // Ranges, content heights and vertical justification. for (fi, ft) in out.frames.iter_mut().enumerate() { let f = &frames[fi]; @@ -3108,7 +3724,12 @@ fn finish_composition(input: FinishInput<'_>) -> ComposedStory { let before: Vec = ft.tables.iter().map(|t| ft.lines.get(t.line).map_or(0.0, |l| l.baseline)).collect(); let spanned = ft.columns.len() > 1 && ft.lines.iter().any(|l| span_paras.get(l.para) == Some(&true)) || ft.lines.iter().any(|l| split_paras.get(l.para) == Some(&true)); - vertical_justify(ft, f, spanned); + let anchors: &[usize] = if ft.objects.is_empty() { + &[] + } else { + marks.get_or_insert_with(|| story.text.match_indices(designcraft_doc::OBJECT_MARK).map(|(i, _)| i).collect()) + }; + vertical_justify(ft, f, spanned, &doc.footnote_options, grid_paras, anchors); for (t, b) in ft.tables.iter_mut().zip(before) { let now = ft.lines.get(t.line).map_or(b, |l| l.baseline); t.shift(now - b); @@ -3289,15 +3910,22 @@ pub fn column_rule_rects(columns: &[Rect], lines: &[Line], opts: &TextFrameOptio continue; } // Vertical bands of the paragraphs whose lines cross this gutter. + // Grouped by paragraph through an index, in first-seen order: searching the bands for + // each line was quadratic in the number of paragraphs. let mut spans: Vec<(usize, f64, f64)> = Vec::new(); + let mut band_of: HashMap = HashMap::new(); for l in lines.iter().filter(|l| l.x0 < cx && l.x1 > cx) { let (t, z) = (l.baseline - l.ascent, l.baseline + l.descent); - match spans.iter_mut().find(|s| s.0 == l.para) { - Some(s) => { + match band_of.get(&l.para) { + Some(&k) => { + let s = &mut spans[k]; s.1 = s.1.min(t); s.2 = s.2.max(z); } - None => spans.push((l.para, t, z)), + None => { + band_of.insert(l.para, spans.len()); + spans.push((l.para, t, z)); + } } } spans.sort_by(|p, q| p.1.total_cmp(&q.1)); @@ -3332,8 +3960,9 @@ fn optical_for(pp: &ParaProps, story: &Story) -> (bool, Option) { } } -/// Breaker parameters from the paragraph's settings. -fn spacing_for(pp: &ParaProps, base_size: f64, story: &Story) -> Spacing { +/// Breaker parameters from the paragraph's settings; `cjk` says the paragraph has CJK text (so +/// its 禁則 priority applies). +fn spacing_for(pp: &ParaProps, base_size: f64, story: &Story, cjk: bool) -> Spacing { let (optical, optical_size) = optical_for(pp, story); Spacing { justify: pp.align.is_justified(), @@ -3355,15 +3984,51 @@ fn spacing_for(pp: &ParaProps, base_size: f64, story: &Story) -> Spacing { optical, optical_size, korean_char_breaks: pp.korean_char_breaks, + kinsoku_cjk: cjk, + // JIS X 4051 禁則処理: the empty value is InDesign's default and the UI's "Push In First", + // and 調整量優先 (adjustment amount) is the breaker's minimum-adjustment mode 0. kinsoku_priority: match pp.kinsoku_type.as_str() { - "KinsokuPushInFirst" => 1, + "" | "KinsokuPushInFirst" => 1, "KinsokuPushOutFirst" => 2, "KinsokuPushOutOnly" => 3, + "KinsokuPrioritizeAdjustmentAmount" => 0, _ => 0, }, } } +/// Whether the paragraph's own shaped glyphs contain CJK text, the gate for its 禁則 priority. +/// Called before `split_drop_cap` and `prepend_label`, so a drop cap counts and generated list +/// and story labels do not. A text variable or page number keeps its marker in [`Glyph::ch`], so +/// its replacement text is what the paragraph shows; inspect that too. +fn paragraph_is_cjk(glyphs: &[Glyph]) -> bool { + glyphs.iter().any(|g| is_cjk_char(g.ch) || g.generated_text.as_deref().is_some_and(|text| text.chars().any(is_cjk_char))) +} + +/// Is `c` CJK text (the scripts the 禁則 line-start/line-end rules are about): ideographs, kana, +/// CJK punctuation and full/half-width forms, bopomofo, Hangul. +fn is_cjk_char(c: char) -> bool { + // Hangul comes from the breaker's classification (Jamo including Extended-A/B, syllables), + // so the two sets agree. Bopomofo is 0x3100..=0x312F; 0x3130..=0x318F is Hangul. + breaker::is_hangul(c) + || matches!( + c as u32, + 0x2E80..=0x2FFF + | 0x3000..=0x30FF + | 0x3100..=0x312F + | 0x3190..=0x33FF + | 0x3400..=0x4DBF + | 0x4E00..=0x9FFF + | 0xA000..=0xA4CF + | 0xF900..=0xFAFF + | 0xFE30..=0xFE4F + | 0xFF00..=0xFFEF + // Extension B and later (U+20000..): the same range as the breaker's Han check, + // so the kinsoku settings apply to a paragraph of supplementary-plane text alone. + | 0x20000..=0x3FFFF + ) +} + /// Desired word spacing, letter spacing and glyph scaling apply to every line (any alignment). fn apply_desired_spacing(glyphs: &mut [Glyph], pp: &ParaProps) { for i in 0..glyphs.len() { @@ -3483,8 +4148,8 @@ fn rewind( } /// Paragraphs that tracked changes delete: all their text is deleted, and so is their return or -/// the return before them (then they join a paragraph and add nothing to it). -fn deleted_paras(story: &Story, ranges: &[Range]) -> Vec { +/// the return before them (then they join a paragraph and add nothing to it). Composing skips them. +pub fn deleted_paras(story: &Story, ranges: &[Range]) -> Vec { let mut spans: Vec> = Vec::new(); for (r, f) in story.runs() { if f.over.change != Some(designcraft_doc::ChangeMark::Deleted) { @@ -3510,7 +4175,7 @@ fn deleted_paras(story: &Story, ranges: &[Range]) -> Vec { } /// Where a placed paragraph sits (for keep resolution). -#[derive(Clone, Debug)] +#[derive(Clone, Debug, PartialEq)] struct ParaInfo { start: (usize, usize), /// Started at the top of a column (moving it can't help). @@ -4253,9 +4918,10 @@ fn wrap_slot( #[allow(clippy::too_many_arguments)] fn free_slots(f: &FrameSpec, col: Rect, y0: f64, y1: f64, desc: f64, size: f64, rtl: bool, line_start: usize) -> Vec<(f64, f64)> { // A shaped frame: the parts of the band its outline covers (a concave one can give several), - // descenders included: they stay inside the frame. + // descenders included: they stay inside the frame. The part of the band above the column's + // top is not tested, as in a rectangular frame: a Cap Height first line reaches above it. let mut free = match &f.outline { - Some(o) => o.intervals(col.x0, col.x1, y0, y1 + desc.max(0.0)), + Some(o) => o.intervals(col.x0, col.x1, y0.max(col.y0).min(y1), y1 + desc.max(0.0)), None => vec![(col.x0, col.x1)], }; let mut cut = f.outline.is_some(); @@ -4265,39 +4931,40 @@ fn free_slots(f: &FrameSpec, col: Rect, y0: f64, y1: f64, desc: f64, size: f64, let blocked = match ex.mode { WrapMode::JumpToNextColumn if y1 > r.y0 && r.x0 < col.x1 && r.x1 > col.x0 => return vec![], WrapMode::BoundingBox | WrapMode::Contour if overlaps_band => match &ex.contour { - Some(c) => c.band_extent(y0, y1), - None => Some((r.x0, r.x1)), + Some(c) => c.band_spans(y0, y1), + None => vec![(r.x0, r.x1)], }, - _ => None, + _ => Vec::new(), }; - let Some((a, b)) = blocked.filter(|&(a, b)| a < col.x1 && b > col.x0) else { continue }; - cut = true; - // One-sided wraps also block the column on the other side of the object. - let text_left = match ex.side { - WrapSide::LeftSide => Some(true), - WrapSide::RightSide => Some(false), - WrapSide::LargestArea => Some(r.x0 - col.x0 >= col.x1 - r.x1), - WrapSide::BothSides | WrapSide::TowardsSpine | WrapSide::AwayFromSpine => None, - }; - let (a, b) = match text_left { - Some(true) => (a, b.max(col.x1)), - Some(false) => (a.min(col.x0), b), - None => (a, b), - }; - let mut next = Vec::with_capacity(free.len() + 1); - for (fa, fb) in free { - if b <= fa || a >= fb { - next.push((fa, fb)); - continue; - } - if a > fa { - next.push((fa, a)); - } - if b < fb { - next.push((b, fb)); + for (a, b) in blocked.into_iter().filter(|&(a, b)| a < col.x1 && b > col.x0) { + cut = true; + // One-sided wraps also block the column on the other side of the object. + let text_left = match ex.side { + WrapSide::LeftSide => Some(true), + WrapSide::RightSide => Some(false), + WrapSide::LargestArea => Some(r.x0 - col.x0 >= col.x1 - r.x1), + WrapSide::BothSides | WrapSide::TowardsSpine | WrapSide::AwayFromSpine => None, + }; + let (a, b) = match text_left { + Some(true) => (a, b.max(col.x1)), + Some(false) => (a.min(col.x0), b), + None => (a, b), + }; + let mut next = Vec::with_capacity(free.len() + 1); + for (fa, fb) in free { + if b <= fa || a >= fb { + next.push((fa, fb)); + continue; + } + if a > fa { + next.push((fa, a)); + } + if b < fb { + next.push((b, fb)); + } } + free = next; } - free = next; } if cut { free.retain(|(a, b)| b - a >= size * 1.5); @@ -4614,7 +5281,7 @@ fn layout_line( let mut offset = 0.0; // Kashidas: in justified Arabic, the joins of words take the extra length first. let kashidas = if justify_this { allocate_kashidas(&line, &mut add, pp, seg, &mut extra) } else { Vec::new() }; - if (justify_this || squeeze_last) && (extra >= 0.0 || sp.kinsoku_priority != 3) { + if (justify_this || squeeze_last) && (extra >= 0.0 || !sp.push_out_only()) { extra = mojikumi::distribute(line.get_mut(seg..).unwrap_or_default(), extra, add.get_mut(seg..).unwrap_or_default()); } if (justify_this || squeeze_last) && !spaces.is_empty() { @@ -4817,6 +5484,12 @@ fn tab_leader(tab: &Glyph, leader: &str, x: f64, w: f64, origin: f64, out: &mut while at + pw <= end + 0.01 && n < 2000 { for &(gid, adv) in &glyphs { out.push(PlacedGlyph { + // The leader fills a tab, so it belongs to whatever that tab belongs to. Saying + // `false` for the tab of a list label made the leader claim to be the + // paragraph's own text while carrying the paragraph-start byte, so a PDF link + // starting at the first text character swept the leader positions into its + // rectangle (noted in review). + list_label: tab.list_label, rendered_char: '\t', face: tab.face, gid, @@ -4930,6 +5603,34 @@ fn distribute(line: &[Glyph], spaces: &[usize], extra: f64, sp: &Spacing, add: & } } +/// The paragraph settings for the lines after the `placed` line when it holds an Indent to Here +/// character (the last one, if several): the start-side indent reaches the character, measured +/// from the start edge of the line's segment `x0..x1`. Like the paragraph's own indents it then +/// applies from each later line's segment, so beside a text wrap it starts at the wrap's edge. +/// `None` when there is none or the indent is unchanged. +fn indent_here(placed: &[PlacedGlyph], pp: &designcraft_doc::ParaProps, x0: f64, x1: f64, rtl: bool) -> Option { + // The placed glyphs are in the line's order (bidi only moves them): the drop cap's, then a + // list label's, which is set beside the drop cap, then the text's. A character in the drop + // cap or the label counts too, and one in the label comes after one in the drop cap. + let x = placed.iter().rev().find(|g| g.rendered_char == story::INDENT_HERE)?.x; + let indent = if rtl { x1 - x } else { x - x0 }; + if !indent.is_finite() { + return None; + } + let indent = indent.max(0.0); + let current = if rtl { pp.right_indent } else { pp.left_indent }; + if (indent - current).abs() < 0.01 { + return None; + } + let mut props = pp.clone(); + if rtl { + props.right_indent = indent; + } else { + props.left_indent = indent; + } + Some(props) +} + fn place(g: &Glyph, x: f64) -> PlacedGlyph { let visible = !(g.ch == '\t' || g.ch == '\n' @@ -4953,6 +5654,7 @@ fn place(g: &Glyph, x: f64) -> PlacedGlyph { len: g.len, generated_text: g.generated_text.clone(), visible, + list_label: g.list_label, upright: g.upright, tcy: g.tcy, rtl: false, @@ -5240,26 +5942,21 @@ fn suppress_hyphens(hy: &mut [bool], glyphs: &[Glyph], at: &[usize]) { } } -fn hyphenation_points( - text: &str, - glyphs: &[Glyph], - pp: &ParaProps, - exceptions: &HashMap>, - foreign: &[(Range, Option)], -) -> Vec { - let mut out = vec![false; glyphs.len()]; - if !pp.hyphenate { - return out; - } - let lim = hyphen::Limits { - min_word: pp.hyph_min_word as usize, - after_first: pp.hyph_after_first as usize, - before_last: pp.hyph_before_last as usize, - capitalized: pp.hyph_capitalized, - }; - // Words repeat a lot: remember their points per set of limits. - static CACHE: Mutex), Box<[usize]>>)>> = Mutex::new(Vec::new()); +/// Hyphenation points of `word`, remembered per set of limits: words repeat a lot. The points of +/// a word not seen yet are worked out without holding the cache's lock, so a long word in one +/// paragraph doesn't hold up hyphenation in others. +fn cached_hyphen_points(lim: &hyphen::Limits, lang: hyphen::Lang, word: &str) -> Arc<[usize]> { + type Words = HashMap<(hyphen::Lang, Box), Arc<[usize]>>; + static CACHE: Mutex> = Mutex::new(Vec::new()); let key = (lim.min_word, lim.after_first, lim.before_last, lim.capitalized); + let word_key = (lang, Box::::from(word)); + { + let guard = CACHE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + if let Some(pts) = guard.iter().find(|e| e.0 == key).and_then(|e| e.1.get(&word_key)) { + return pts.clone(); + } + } + let pts: Arc<[usize]> = hyphen::hyphen_points_in(word, lim, lang).into(); let mut guard = CACHE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); let idx = match guard.iter().position(|e| e.0 == key) { Some(i) => i, @@ -5275,6 +5972,41 @@ fn hyphenation_points( if cache.len() > 100_000 { cache.clear(); } + cache.insert(word_key, pts.clone()); + pts +} + +fn hyphenation_points( + text: &str, + glyphs: &[Glyph], + pp: &ParaProps, + exceptions: &HashMap>, + foreign: &[(Range, Option)], + korean: bool, +) -> Vec { + let mut out = vec![false; glyphs.len()]; + if !pp.hyphenate { + return out; + } + // Korean is set word by word and is not hyphenated (KLREQ). An ordinary Korean document + // leaves the paragraph language at the default English, so the paragraph's own text decides + // rather than its language setting (#1688). + // + // Decided by the caller, from the paragraph's glyphs *before* its drop cap is split off: + // `split_drop_cap` takes those glyphs out of the vector, so classifying here lost the drop + // cap's character -- 15 Hangul against 15 Latin became 14 against 15, and the paragraph + // hyphenated its English. See `hyphen::korean_paragraph`. + if korean { + return out; + } + let lim = hyphen::Limits { + min_word: pp.hyph_min_word as usize, + after_first: pp.hyph_after_first as usize, + before_last: pp.hyph_before_last as usize, + capitalized: pp.hyph_capitalized, + }; + // The token the last word run sat in, and whether it is kept whole (see below). + let mut token: Option<(usize, usize, bool)> = None; let mut i = 0; while i < glyphs.len() { if !glyphs[i].is_letter() || glyphs[i].len == 0 { @@ -5295,21 +6027,52 @@ fn hyphenation_points( let (a, b) = (glyphs[i].byte, glyphs[j - 1].byte + glyphs[j - 1].len); if !discretionary && b > a && b <= text.len() && text.is_char_boundary(a) && text.is_char_boundary(b) { let word = &text[a..b]; + // The whitespace-delimited token the word sits in: a Latin run with a Korean particle + // on it ("News와") or inside an address is not a word to hyphenate (#1688). Found once + // per token and reused for the word runs inside it: unspaced CJK text is one token + // however many Latin words it holds, and scanning it again for each was quadratic. + let keep = match token { + Some((start, end, keep)) if start <= a && b <= end => keep, + _ => { + let start = text[..a].rfind(char::is_whitespace).map_or(0, |i| i + text[i..].chars().next().map_or(1, char::len_utf8)); + let end = text[b..].find(char::is_whitespace).map_or(text.len(), |i| b + i); + let keep = hyphen::keep_whole(&text[start..end]); + token = Some((start, end, keep)); + keep + } + }; + if keep { + i = j.max(i + 1); + continue; + } // Do not hyphenate the paragraph's last word unless allowed. let is_last_word = !pp.hyph_last_word && glyphs[j..].iter().all(|g| !g.is_letter()); let lang = foreign.iter().find(|(r, _)| r.contains(&a)).map_or(Some(hyphen::Lang::English), |(_, l)| *l); if !is_last_word && let Some(lang) = lang { let user = (!exceptions.is_empty()).then(|| exceptions.get(&word.to_lowercase())).flatten(); + let cached; let pts: &[usize] = match user { // User dictionary exceptions win over the patterns and the built-in list. Some(v) => v, - None => cache.entry((lang, word.into())).or_insert_with(|| hyphen::hyphen_points_in(word, &lim, lang).into_boxed_slice()), + None => { + cached = cached_hyphen_points(&lim, lang, word); + &cached + } }; - for &p in pts.iter() { - // char index p → byte → glyph whose cluster ends at that byte. - let byte = a + word.char_indices().nth(p).map(|(bi, _)| bi).unwrap_or(word.len()); - if let Some(k) = (i..j).find(|&k| glyphs[k].byte + glyphs[k].len == byte && glyphs[k].len > 0) { - out[k] = true; + if !pts.is_empty() { + // char index p → byte → the first glyph whose cluster ends at that byte. Both + // indexed once per word: looking each point up by scanning was quadratic in + // a long word's length. + let char_bytes: Vec = word.char_indices().map(|(bi, _)| bi).collect(); + let mut glyph_ending_at: HashMap = HashMap::new(); + for k in (i..j).filter(|&k| glyphs[k].len > 0) { + glyph_ending_at.entry(glyphs[k].byte + glyphs[k].len).or_insert(k); + } + for &p in pts.iter() { + let byte = a + char_bytes.get(p).copied().unwrap_or(word.len()); + if let Some(&k) = glyph_ending_at.get(&byte) { + out[k] = true; + } } } } @@ -5319,8 +6082,66 @@ fn hyphenation_points( out } -/// `spanned`: a paragraph spans the frame's columns, so the lines move together. -fn vertical_justify(ft: &mut FrameText, f: &FrameSpec, spanned: bool) { +/// A paragraph rule drawn in `rect` (its length and weight) with its Type: the gap colour under +/// it, then the line, as dashes, dots, stripes, waves or hash marks. A pattern that can't be laid +/// out along the rule draws solid. +/// `(color, tint)` is the rule's (Text Color already resolved); `text`, the colour of the text +/// the rule goes with, for a gap in Text Color. +fn rule_decos(doc: &Document, r: &designcraft_doc::Rule, rect: Rect, (color, tint): (String, f32), text: &(String, f32)) -> Vec { + use designcraft_doc::StrokeType; + let kind = doc.stroke_kind(&r.kind); + let (w, len) = (rect.height(), rect.width()); + let mut out = Vec::new(); + if !matches!(kind, StrokeType::Solid) && r.gap_color != designcraft_color::swatch::NONE && w > 0.0 && len > 0.0 { + let gap = if r.gap_color == designcraft_doc::TEXT_COLOR { text.0.clone() } else { r.gap_color.clone() }; + out.push(Deco { rect, color: gap, tint: r.gap_tint, ..Deco::default() }); + } + let y = rect.center().y; + let mut line = designcraft_geom::BezPath::new(); + line.move_to((rect.x0, y)); + line.line_to((rect.x1, y)); + let path = match &kind { + StrokeType::Dashed { pattern } if StrokeType::expandable_dashes(pattern, len) => { + let mut p = designcraft_geom::BezPath::new(); + let (mut x, mut k, mut on) = (rect.x0, 0, true); + while x < rect.x1 { + let step = pattern[k % pattern.len()]; + if on && step > 0.0 { + let r = Rect::new(x, rect.y0, (x + step).min(rect.x1), rect.y1); + p.extend(designcraft_geom::Shape::path_elements(&r, 0.1)); + } + x += step; + k += 1; + on = !on; + } + Some(p) + } + StrokeType::Dotted if StrokeType::expandable_dashes(&[w, w], len) => { + let mut p = designcraft_geom::BezPath::new(); + let mut x = rect.x0 + w / 2.0; + while x <= rect.x1 - w / 2.0 + 1e-9 { + p.extend(designcraft_geom::Shape::path_elements(&designcraft_geom::kurbo::Circle::new((x, y), w / 2.0), 0.1)); + x += 2.0 * w; + } + Some(p) + } + k => k.outline(&line, w, 0.05), + }; + out.push(Deco { rect, color, tint, path, ..Deco::default() }); + out +} + +/// `spanned`: a paragraph spans the frame's columns, so the lines move together. `anchors`: the +/// story byte of each anchored object's mark, by object index. +/// `grid_aligns`: each paragraph's Align to Baseline Grid setting. +fn vertical_justify( + ft: &mut FrameText, + f: &FrameSpec, + spanned: bool, + notes: &designcraft_doc::FootnoteOptions, + grid_aligns: &[GridAlign], + anchors: &[usize], +) { if ft.lines.is_empty() || f.opts.vertical_justification == VerticalJustification::Top { return; } @@ -5330,43 +6151,450 @@ fn vertical_justify(ft: &mut FrameText, f: &FrameSpec, spanned: bool) { // Per column (or all lines together). let ncols = if spanned { 1 } else { ft.columns.len().max(1) as u32 }; for c in 0..ncols { + let (rooms, follow) = wrap_rooms(ft, f, c, spanned, anchors); let idx: Vec = ft.lines.iter().enumerate().filter(|(_, l)| spanned || l.column == c).map(|(i, _)| i).collect(); - let (Some(&a), Some(_)) = (idx.first(), idx.last()) else { continue }; - let bottom = idx.iter().map(|&i| ft.lines[i].baseline + ft.lines[i].descent).fold(f64::NEG_INFINITY, f64::max); - let space = f.area.y1 - bottom; + if idx.is_empty() { + continue; + } + let note_top = ft + .notes + .iter() + .filter(|n| spanned || notes.span_columns || n.column == c) + .map(|n| n.rect.y0 - notes.space_before) + .fold(f64::INFINITY, f64::min); + let limit = note_top.min(f.area.y1); + let tables = ft.tables.iter().filter(|t| spanned || t.column == c).map(|t| t.rect.y1).fold(f64::NEG_INFINITY, f64::max); + let last_baseline = idx.iter().map(|&i| ft.lines[i].baseline).fold(tables, f64::max); + let ink_bottom = idx.iter().map(|&i| ft.lines[i].baseline + ft.lines[i].descent).fold(tables, f64::max); + // The bottom of the text is the last baseline, as the top is the first baseline: the + // descenders of the last line hang below it, into the bottom inset and past it, in shaped + // frames as in rectangular ones. Above footnotes, and in vertical frames, the descenders + // stay inside the text area, as when the lines are fitted. + // `space`: the room under the bottom of the text. + let inside = f.vertical || note_top <= f.area.y1; + let space = if inside { limit - ink_bottom } else { limit - last_baseline }; + // Center and Bottom move the lines together: the nearest text wrap under them is the + // bottom of the room they move down into, so the room is the least any line has before a + // wrap stops it. Justify checks each row's room below. + let space = match f.opts.vertical_justification { + VerticalJustification::Justify => space, + _ => idx.iter().map(|&i| rooms[i]).fold(space, f64::min), + }; if space <= 0.0 { continue; } - let _ = a; - match f.opts.vertical_justification { - VerticalJustification::Center => idx.iter().for_each(|&i| ft.lines[i].baseline += space / 2.0), - VerticalJustification::Bottom => idx.iter().for_each(|&i| ft.lines[i].baseline += space), - VerticalJustification::Justify => { - // Segments of one line (beside an object) share a row and move together. - let rows: Vec = idx - .iter() - .scan((0usize, f64::NAN), |(row, prev), &i| { - let b = ft.lines[i].baseline; - if !prev.is_nan() && (b - *prev).abs() > 1e-9 { - *row += 1; + // Segments of one line (beside an object) share a row and move together. + let rows: Vec = idx + .iter() + .scan((0usize, f64::NAN), |(row, prev), &i| { + let b = ft.lines[i].baseline; + if !prev.is_nan() && (b - *prev).abs() > 1e-9 { + *row += 1; + } + *prev = b; + Some(*row) + }) + .collect(); + let n = rows.last().copied().unwrap_or(0); + // Paragraph Spacing Limit: with Justify the space goes between paragraphs, up to the limit + // each; what is left spreads over every line (all of it with no limit). + let mut starts = vec![false; n + 1]; + for (&i, &k) in idx.iter().zip(&rows) { + if k > 0 && ft.lines[i].first_in_para { + starts[k] = true; + } + } + let gaps = starts.iter().filter(|s| **s).count(); + let para_limit = f.opts.vj_paragraph_spacing_limit.max(0.0); + // How far each row moves when the text takes `space` more room. + let shifts = |space: f64| -> Vec { + match f.opts.vertical_justification { + VerticalJustification::Center => vec![space / 2.0; n + 1], + VerticalJustification::Bottom => vec![space; n + 1], + VerticalJustification::Justify if n > 0 => { + let para = if gaps > 0 && para_limit > 0.0 { (space / gaps as f64).min(para_limit) } else { 0.0 }; + let per = (space - para * gaps as f64) / n as f64; + let mut shift = vec![0.0; n + 1]; + for k in 1..=n { + shift[k] = shift[k - 1] + per + if starts[k] { para } else { 0.0 }; + } + shift + } + _ => vec![0.0; n + 1], + } + }; + // Only the last row's descenders hang below the bottom of the text: an earlier line whose + // ink reaches below the last baseline (tight leading) isn't moved past the text area. + // In a shaped frame each moved line's slot stays inside the outline from its top down to + // its baseline: a frame that narrows towards the bottom holds the text higher. Every moved + // line's descenders may cross the outline, as the last line's do below the bottom of the + // text; above footnotes, and in vertical frames, they stay inside. + let in_outline = |l: &Line, dy: f64| match &f.outline { + Some(o) => { + let b = l.baseline + dy; + let desc = if inside { l.descent.max(0.0) } else { 0.0 }; + let tol = 1e-6; + o.intervals(l.x0, l.x1, (b - l.ascent).max(f.area.y0).min(b), b + desc).iter().any(|&(a, z)| a <= l.x0 + tol && z >= l.x1 - tol) + } + None => true, + }; + // Each row moves no further than a text wrap under it allows. An object that moves with its + // anchor's row (Justify) lets a later row move its room plus how far the object moves. + let mut row_of = vec![None; ft.lines.len()]; + for (&i, &k) in idx.iter().zip(&rows) { + row_of[i] = Some(k); + } + let follow: Vec<(usize, usize, f64, f64)> = follow + .iter() + .filter_map(|&(i, a, room, pin)| Some((row_of.get(i).copied().flatten()?, row_of.get(a).copied().flatten()?, room.max(0.0), pin))) + .collect(); + // The object moves only once its anchor's row has moved `pin`. + let clear = |shift: &[f64]| { + idx.iter().zip(&rows).all(|(&i, &k)| shift[k] <= rooms[i].max(0.0) + 1e-9) + && follow.iter().all(|&(k, m, room, pin)| shift[k] <= room + (shift[m] - pin).max(0.0) + 1e-9) + }; + // The lowest lines are tested first: they are the ones a narrowing outline stops. + let fits = |shift: &[f64]| { + idx.iter().zip(&rows).rev().all(|(&i, &k)| { + let l = &ft.lines[i]; + shift[k] <= 0.0 || ((k == n || l.baseline + l.descent + shift[k] <= limit + 1e-9) && in_outline(l, shift[k])) + }) && clear(shift) + }; + // The room in 0..=`top` at which a moved line's band (from its top down to its baseline, or + // to its descent where `inside`), widened by the outline's inset, reaches one of the + // outline's corner heights: between two of these each line's fit changes only along the + // outline's straight edges. Empty when there are more than `MAX_BAND_BREAKS`. + const MAX_BAND_BREAKS: usize = 256; + let band_breaks = |o: &FrameOutline, top: f64| -> Vec { + let corners = o.corner_heights(); + let d = o.inset(); + // Each row's shift is linear in the room, apart from Justify's turn where the space + // between paragraphs reaches the Paragraph Spacing Limit. + let mut knots = vec![0.0, top]; + let turn = gaps as f64 * para_limit; + if f.opts.vertical_justification == VerticalJustification::Justify && turn > 0.0 && turn < top { + knots.insert(1, turn); + } + let at: Vec> = knots.iter().map(|&c| shifts(c)).collect(); + let mut out = Vec::new(); + for (&i, &k) in idx.iter().zip(&rows) { + let l = &ft.lines[i]; + let desc = if inside { l.descent.max(0.0) } else { 0.0 }; + for &y in &corners { + for v in [y + d - (l.baseline - l.ascent), y - d - (l.baseline + desc)] { + for (c, s) in knots.windows(2).zip(at.windows(2)) { + let (s0, s1) = (s[0][k], s[1][k]); + if s1 > s0 && v > s0 && v < s1 { + out.push(c[0] + (v - s0) * (c[1] - c[0]) / (s1 - s0)); + } } - *prev = b; - Some(*row) - }) - .collect(); - let n = rows.last().copied().unwrap_or(0); - if n > 0 { - let per = space / n as f64; - for (&i, &k) in idx.iter().zip(&rows) { - ft.lines[i].baseline += per * k as f64; + } + if out.len() > MAX_BAND_BREAKS { + return Vec::new(); } } } - _ => {} + out + }; + // In a rectangular frame fit decreases monotonically as the shift grows. A shaped + // frame can narrow and widen again, so scan from the largest shift before refining the + // first fitting interval. The scan takes even steps, the band breaks and a room on each + // side of every band break, so a band that fits over less room than one step is found + // too. This also bounds the room used for baseline-grid quantization and preserves + // clearance from fixed and anchor-following wraps. + let most_room = |top: f64| -> f64 { + if fits(&shifts(top)) { + return top; + } + let (mut lo, mut hi) = if let Some(o) = &f.outline { + let steps = top.ceil().clamp(64.0, 512.0) as usize; + // Each try is marked when it is a band break; only the gaps next to a break get a + // try in their middle. + let mut marked: Vec<(f64, bool)> = (0..steps).map(|j| (top * j as f64 / steps as f64, false)).collect(); + marked.extend(band_breaks(o, top).into_iter().map(|c| (c, true))); + marked.push((top, false)); + marked.sort_by(|a, b| a.0.total_cmp(&b.0)); + marked.dedup_by(|a, b| { + let same = (a.0 - b.0).abs() < 1e-9; + b.1 |= same && a.1; + same + }); + let mut tries: Vec = marked.windows(2).filter(|w| w[0].1 || w[1].1).map(|w| (w[0].0 + w[1].0) / 2.0).collect(); + tries.extend(marked.iter().map(|m| m.0)); + tries.sort_by(f64::total_cmp); + let mut found = (0.0, top); + for w in tries.windows(2).rev() { + if fits(&shifts(w[0])) { + found = (w[0], w[1]); + break; + } + } + found + } else { + (0.0, top) + }; + for _ in 0..60 { + let mid = (lo + hi) / 2.0; + if fits(&shifts(mid)) { + lo = mid; + } else { + hi = mid; + } + } + lo + }; + // Lines aligned to the baseline grid move by whole grid steps, so they stay on the grid. + // With Justify only the last row has to land on the grid (the first row doesn't move). + let on_grid = |i: usize| { + let line = &ft.lines[i]; + match grid_aligns.get(line.para) { + Some(GridAlign::AllLines) => true, + Some(GridAlign::FirstLineOnly) => line.first_in_para, + _ => false, + } + }; + let center = f.opts.vertical_justification == VerticalJustification::Center; + let step = f.countable_grid().map(|(_, inc)| inc).filter(|_| match f.opts.vertical_justification { + VerticalJustification::Justify => idx.iter().zip(&rows).any(|(&i, &k)| k == n && on_grid(i)), + _ => idx.iter().any(|&i| on_grid(i)), + }); + let shift = match step { + None => shifts(most_room(space)), + // A step so small that the room holds more steps than an f64 can count: the lines take + // the room as they do without a grid, and stay within one step of a grid line. + Some(inc) if !(space / inc).is_finite() => shifts(most_room(space)), + Some(inc) => { + // The room one grid step takes: Center moves the lines by half the room. + let unit = if center { 2.0 * inc } else { inc }; + let room = most_room(if center { 2.0 * space } else { space }); + // The last baseline stays above the bottom of the text, and the rows above it fit. + let most = (space / inc + 1e-9).floor().min((room / unit + 1e-9).floor()).max(0.0); + // Bottom and Justify take the lowest grid line, Center the one nearest the middle. + let target = if center { (space / 2.0 / inc).round().min(most) } else { most }; + // A shaped frame can narrow and widen again, so the target step may not fit: take + // the fitting step nearest it, up to `most` (the lower one on a tie, and no step + // when that is as near), and leave the lines in place when none within + // `MAX_GRID_TRIES` steps of it fits. + const MAX_GRID_TRIES: usize = 512; + let mut steps = 0.0; + for d in 0..MAX_GRID_TRIES { + let (below, above) = (target - d as f64, target + d as f64); + if below <= 0.0 { + break; + } + if fits(&shifts(below * unit)) { + steps = below; + break; + } + if d > 0 && above <= most && fits(&shifts(above * unit)) { + steps = above; + break; + } + } + // With no step taken the lines stay put, even when Center's doubled step overflows. + shifts(if steps > 0.0 { steps * unit } else { 0.0 }) + } + }; + let before: Vec = idx.iter().map(|&i| ft.lines[i].baseline).collect(); + for (&i, &k) in idx.iter().zip(&rows) { + ft.lines[i].baseline += shift[k]; + } + // A drop cap moves with its line. + for (&i, b) in idx.iter().zip(before) { + let line = &mut ft.lines[i]; + let dy = line.baseline - b; + if let Some(dc) = &mut line.drop_cap { + dc.baseline += dy; + dc.rect.y0 += dy; + dc.rect.y1 += dy; + } } } } +/// How far each line of column `c` (every column when `spanned`) may move down before a text +/// wrap stops it, by index in `ft.lines` (infinite without one); a table fragment's room counts +/// for its line. No line moves into a wrap under its slot. As when lines are set around a wrap, a +/// line's band runs from its top to its baseline, so a baseline may come down to a wrap's top; a +/// table fragment stops with its bottom there. A wrap without a contour counts by its bounding +/// box. Beside or under a contour, the line moves down only as far as its band stays clear of the +/// contour on its way down (to 0.01 pt). Only wraps that reach into a line's column (or the +/// columns it spans) count, as when the lines are set. An anchored object that moves with the +/// lines being justified (inline, above the line, or positioned from its anchor) is skipped, +/// except under Justify, where it moves with the row of its anchor's line: its wrap is taken where +/// the object sits before the lines move, and its rooms go in the second list as (line, anchor's +/// line, room, pin), so a line moves down at most the room plus how far the anchor's row moves +/// past `pin`. An object positioned from its anchor and kept within its column moves with its +/// anchor's row until it stops at the column's bottom, so in every mode a line moves down at most +/// the room under it plus the distance the object can move. Held at the column's top, the object +/// moves only after its anchor's row has moved `pin` (0 for the other objects), and until then a +/// line keeps the whole room. Justify keeps the first row in place, so its room stays infinite. `anchors` holds the story byte of each anchored object's mark, by object index. +fn wrap_rooms(ft: &FrameText, f: &FrameSpec, c: u32, spanned: bool, anchors: &[usize]) -> (Vec, Vec<(usize, usize, f64, f64)>) { + const EPS: f64 = 1e-6; + // One-sided wraps also block the column on the other side of the object: the x-range wrap + // `e` keeps text out of in column `col`, from the object's x-range `a..b` there (None when that + // range misses the column). + let sided = |e: &Exclusion, col: Rect, (a, b): (f64, f64)| -> Option<(f64, f64)> { + let r = e.rect; + (a < col.x1 && b > col.x0).then_some(match e.side { + WrapSide::LeftSide => (a, f64::INFINITY), + WrapSide::RightSide => (f64::NEG_INFINITY, b), + WrapSide::LargestArea if r.x0 - col.x0 >= col.x1 - r.x1 => (a, f64::INFINITY), + WrapSide::LargestArea => (f64::NEG_INFINITY, b), + WrapSide::BothSides | WrapSide::TowardsSpine | WrapSide::AwayFromSpine => (a, b), + }) + }; + // The x-range a wrap under the text keeps it out of in column `col`; None when text may stay beside it. + let blocked = |e: &Exclusion, col: Rect| -> Option<(f64, f64)> { + let r = e.rect; + match e.mode { + WrapMode::None => None, + WrapMode::JumpObject | WrapMode::JumpToNextColumn => (r.x0 < col.x1 && r.x1 > col.x0).then_some((f64::NEG_INFINITY, f64::INFINITY)), + WrapMode::BoundingBox | WrapMode::Contour => sided(e, col, (r.x0, r.x1)), + } + }; + let in_col = |k: u32| spanned || k == c; + let justify = f.opts.vertical_justification == VerticalJustification::Justify; + // The object whose mark is at each story byte, placed on one of these lines (the first one + // listed). + let mut by_anchor = HashMap::new(); + for o in ft.objects.iter().filter(|o| ft.lines.get(o.line).is_some_and(|l| in_col(l.column))) { + if let Some(&a) = anchors.get(o.index) { + by_anchor.entry(a).or_insert(o); + } + } + // An own-story anchored object whose anchor is on one of these lines and whose position + // follows its line moves with the text: the index in `ft.lines` of its anchor's line, how + // much lower the object was when the wrap was taken (an earlier pass placed the object after + // moving the lines), and, for one kept within its column, how far its line moves before the + // object leaves the column's top and how far the object then moves before it stops at the + // column's bottom (none and infinite for the others). + let moves_with_text = |e: &Exclusion| -> Option<(usize, f64, f64, f64)> { + let o = *by_anchor.get(&e.after?)?; + let l = ft.lines.get(o.line)?; + let now = l.baseline; + let dy = e.anchor_baseline.map_or(0.0, |b| b - now); + match &o.object.position { + designcraft_doc::AnchorPosition::Inline { .. } | designcraft_doc::AnchorPosition::AboveLine { .. } => { + Some((o.line, dy, 0.0, f64::INFINITY)) + } + designcraft_doc::AnchorPosition::Custom { y_relative, keep_within_column, y_offset, object_point, .. } + if *y_relative == designcraft_doc::anchored::AnchorRelative::Anchor => + { + if !keep_within_column { + return Some((o.line, dy, 0.0, f64::INFINITY)); + } + // Placed as the lines' final positions place it: from its anchor's baseline, + // held between the column's top and bottom. + let col = ft.columns.get(l.column as usize).copied().unwrap_or(f.area); + let h = o.size.1; + let ofy = [0.0, 0.5, 1.0][(*object_point / 3).min(2) as usize]; + let (lo, hi) = (col.y0, (col.y1 - h).max(col.y0)); + let place = |b: f64| b + y_offset - h * ofy; + let raw = place(now); + let y = raw.clamp(lo, hi); + let then = e.anchor_baseline.map_or(y, |b| place(b).clamp(lo, hi)); + Some((o.line, then - y, (lo - raw).max(0.0), (hi - y).max(0.0))) + } + designcraft_doc::AnchorPosition::Custom { .. } => None, + } + }; + // Each wrap's object is looked up once, not for every line. + let moving: Vec> = f.exclusions.iter().map(moves_with_text).collect(); + // Justify keeps the first row (its segments and a table on them) in place, so wraps under it + // set no limit. + let first = ft.lines.iter().find(|l| in_col(l.column)).map(|l| l.baseline); + let fixed = |line: usize| justify && ft.lines.get(line).zip(first).is_some_and(|(l, b)| (l.baseline - b).abs() <= 1e-9); + // (line, story byte, column, slot x-range, top, bottom) of each line (its band runs from its + // top to its baseline) and table fragment. + let lines = ft + .lines + .iter() + .enumerate() + .filter(|(_, l)| in_col(l.column)) + .map(|(i, l)| (i, l.range.start, l.column, l.x0, l.x1, l.baseline - l.ascent, l.baseline)); + let tables = ft.tables.iter().filter(|t| in_col(t.column)).map(|t| (t.line, t.anchor, t.column, t.rect.x0, t.rect.x1, t.rect.y0, t.rect.y1)); + let mut rooms = vec![f64::INFINITY; ft.lines.len()]; + let mut follow = Vec::new(); + for (line, start, k, x0, x1, top, bottom) in lines.chain(tables) { + let Some(&before) = rooms.get(line) else { continue }; + if fixed(line) { + continue; + } + let mut room = before; + // A line that spans columns reaches past its own column. + let col = ft.columns.get(k as usize).copied().unwrap_or(f.area); + let col = Rect { x0: col.x0.min(x0), x1: col.x1.max(x1), ..col }; + let meets = |(a, b): (f64, f64)| a < x1 - EPS && b > x0 + EPS; + for (e, &anchor) in f.exclusions.iter().zip(&moving).filter(|(e, _)| e.wraps_line(start)) { + // Center and Bottom move every row as far: only an object kept within its column, which + // can stop at the column's edges, holds the lines back. + if anchor.is_some_and(|(_, _, _, slack)| slack == f64::INFINITY) && !justify { + continue; + } + // The wrap where its object sits before the lines move (moved up by `dy`), and how + // far it lets this line move down (relative to its anchor's row for an object that + // moves with the text). + let dy = anchor.map_or(0.0, |(_, dy, _, _)| dy); + let cap = if anchor.is_some() { f64::INFINITY } else { room }; + let mut room_e = f64::INFINITY; + let r = Rect { y0: e.rect.y0 - dy, y1: e.rect.y1 - dy, ..e.rect }; + if let (WrapMode::BoundingBox | WrapMode::Contour, Some(contour)) = (e.mode, &e.contour) + && r.y1 > top + && sided(e, col, (r.x0, r.x1)).is_some_and(meets) + { + // A contour beside or under this line whose box reaches the line's slot (the + // contour stays inside its box). Moved down by `d`, the line's band sweeps from its + // top to its baseline plus `d`; the parts of the contour there only grow with `d`, + // so the furthest clear move is found by bisection to 0.01 pt. As when the line is + // set, the gaps between parts of the contour stay open. + let hits = |d: f64| contour.band_spans(top + dy, bottom + d + dy).into_iter().any(|x| sided(e, col, x).is_some_and(meets)); + let (mut lo, mut hi) = ((r.y0 - bottom).max(0.0), (r.y1 - top).min(f.area.y1 - bottom).min(cap)); + if lo < hi && hits(hi) { + if hits(lo) { + hi = lo; + } + for _ in 0..64 { + if hi - lo <= 0.01 { + break; + } + let mid = (lo + hi) / 2.0; + if hits(mid) { + hi = mid; + } else { + lo = mid; + } + } + room_e = lo; + } + } else if r.y0 >= bottom - EPS { + // A wrap at or under this line. + if blocked(e, col).is_some_and(meets) { + room_e = r.y0 - bottom; + } + } + match anchor { + // An object kept within its column moves once its line has moved `pin` (to leave + // the column's top) and stops after moving `slack` (at the column's bottom). + Some((a, _, pin, slack)) if room_e.is_finite() => { + if room_e >= pin { + if justify { + follow.push((line, a, room_e, pin)); + } + room = room.min(room_e + slack); + } else { + room = room.min(room_e); + } + } + Some(_) => {} + None => room = room.min(room_e), + } + } + rooms[line] = room; + } + (rooms, follow) +} + // ---------- caret and hit testing (Type tool) ---------- /// Two stacked glyphs this far apart in `y` sit on different rows (warichu). @@ -5881,6 +7109,7 @@ mod column_allocation_safety_tests { page_name: None, section_marker: None, page: None, + parent: false, grid: None, left_page: false, right_page: false, diff --git a/crates/compose/src/notes.rs b/crates/compose/src/notes.rs index a385a9093..67f922637 100644 --- a/crates/compose/src/notes.rs +++ b/crates/compose/src/notes.rs @@ -14,7 +14,7 @@ //! With Span Footnotes Across Columns the notes of a frame share one area across all its columns, //! composed at the frame's text width: every column of the frame makes room for it. -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; use std::ops::Range; use std::sync::Arc; @@ -146,11 +146,13 @@ impl Notes { } /// Footnote indices referenced by a line's glyphs. + /// In the order they first appear; a set keeps a line with many references linear. pub fn refs_in(&self, glyphs: &[Glyph]) -> Vec { let mut v: Vec = Vec::new(); + let mut seen = HashSet::new(); for g in glyphs.iter().filter(|g| g.ch == FOOTNOTE_REF && g.len > 0) { if let Ok(k) = self.refs.binary_search(&g.byte) - && !v.contains(&k) + && seen.insert(k) { v.push(k); } @@ -176,6 +178,7 @@ impl Notes { page_name: f.page_name.clone(), section_marker: f.section_marker.clone(), page: f.page, + parent: f.parent, grid: None, left_page: f.left_page, right_page: f.right_page, diff --git a/crates/compose/src/outline.rs b/crates/compose/src/outline.rs index bfc709710..dc7d97ac3 100644 --- a/crates/compose/src/outline.rs +++ b/crates/compose/src/outline.rs @@ -59,11 +59,32 @@ impl FrameOutline { Some(FrameOutline { edges, inset }) } + /// The outline of `item`'s path with its corner options applied, or None when that is the + /// item's own rectangle. The composer and the Properties panel's one Inset field both use it. + pub fn of_item(item: &designcraft_doc::Item, inset: f64) -> Option { + let bp = if item.corners.is_none() { item.path.to_bezpath() } else { designcraft_geom::corners::apply(&item.path, &item.corners) }; + FrameOutline::new(&bp, inset) + } + /// The outline mapped by `xf` (into a vertical frame's turned box). pub fn transformed(&self, xf: Affine) -> FrameOutline { FrameOutline { edges: self.edges.iter().map(|&(a, b)| (xf * a, xf * b)).collect(), inset: self.inset } } + /// The distance kept between text and the outline. + pub fn inset(&self) -> f64 { + self.inset + } + + /// The heights of the outline's corners, sorted and without repeats: the inside intervals of a + /// scanline change linearly between two of them. + pub fn corner_heights(&self) -> Vec { + let mut ys: Vec = self.edges.iter().map(|(a, _)| a.y).collect(); + ys.sort_by(f64::total_cmp); + ys.dedup_by(|a, b| (*a - *b).abs() < 1e-9); + ys + } + /// The parts of `[x0, x1]` inside the outline over the whole band `[y0, y1]`, at least the /// inset away from it: the inside intervals at every height of the band are intersected, and /// the inset is kept by testing the heights within the inset above and below the band, each diff --git a/crates/compose/src/overlay.rs b/crates/compose/src/overlay.rs index b09ef908e..558bf5bec 100644 --- a/crates/compose/src/overlay.rs +++ b/crates/compose/src/overlay.rs @@ -2,7 +2,7 @@ //! through or up to a delimiter) and GREP styles (every match of a pattern). use std::cell::RefCell; -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; use std::ops::Range; use designcraft_doc::{GrepStyle, NestedStyle, NestedUntil}; @@ -47,7 +47,9 @@ fn with_pattern(pattern: &str, f: impl FnOnce(&mut Option) -> R) -> R { }) } -fn is_event(u: &NestedUntil, c: char, prev: Option, next: Option) -> bool { +/// Whether `c` ends one unit of `u`. `delims` is the character set of a [`NestedUntil::Chars`] +/// delimiter, indexed once per nested style. +fn is_event(u: &NestedUntil, delims: &HashSet, c: char, prev: Option, next: Option) -> bool { match u { NestedUntil::Sentences => matches!(c, '.' | '!' | '?') && next.is_none_or(char::is_whitespace), NestedUntil::Words => c.is_whitespace() && prev.is_some_and(|p| !p.is_whitespace()), @@ -60,7 +62,7 @@ fn is_event(u: &NestedUntil, c: char, prev: Option, next: Option) -> NestedUntil::EnSpace => c == '\u{2002}', // Counted by position, not by character (see `overlays`). NestedUntil::Dropcap => false, - NestedUntil::Chars(s) => s.contains(c), + NestedUntil::Chars(_) => delims.contains(&c), } } @@ -81,18 +83,25 @@ pub(crate) fn overlays(text: &str, range: Range, nested: &[NestedStyle], // Through the drop cap runs to its end; up to it (it starts the paragraph) is nothing. stop = if ns.through { drop_end.max(pos).min(end) } else { pos }; } else { + // Streamed up to the delimiter, with one character of lookahead: copying the rest of + // the paragraph for every nested style multiplied its length by the number of styles. + let delims: HashSet = match &ns.until { + NestedUntil::Chars(s) => s.chars().collect(), + _ => HashSet::new(), + }; let mut count = 0; - let chars: Vec<(usize, char)> = text[pos..end].char_indices().map(|(i, c)| (pos + i, c)).collect(); - for (k, &(i, c)) in chars.iter().enumerate() { - let prev = if k > 0 { Some(chars[k - 1].1) } else { None }; - let next = chars.get(k + 1).map(|x| x.1); - if is_event(&ns.until, c, prev, next) { + let mut prev = None; + let mut chars = text[pos..end].char_indices().map(|(i, c)| (pos + i, c)).peekable(); + while let Some((i, c)) = chars.next() { + let next = chars.peek().map(|x| x.1); + if is_event(&ns.until, &delims, c, prev, next) { count += 1; if count >= ns.count.max(1) { stop = if ns.through { i + c.len_utf8() } else { i }; break; } } + prev = Some(c); } } if stop > pos && !ns.style.is_empty() { @@ -107,7 +116,10 @@ pub(crate) fn overlays(text: &str, range: Range, nested: &[NestedStyle], with_pattern(&g.pattern, |slot| { let Some(re) = slot else { return }; match re.find_nonempty(text.get(range.start..end).unwrap_or(""), crate::grep::MAX_MATCHES_PER_PARAGRAPH) { - Ok(ms) => { + Ok((ms, exhausted)) => { + if exhausted { + log::warn!("GREP style {:?} ran out of search budget in one paragraph; the rest may not be styled", g.pattern); + } if ms.len() == crate::grep::MAX_MATCHES_PER_PARAGRAPH { log::warn!("GREP style {:?} matched more than {} times in one paragraph; the rest are not styled", g.pattern, ms.len()); } @@ -161,6 +173,19 @@ mod tests { assert!(has_last, "the most recently used pattern is still cached"); } + /// Nested styles that stop where they start (up to a delimiter the paragraph starts with) + /// read one character each, not the rest of the paragraph. + #[test] + fn nested_styles_stopping_at_once_do_not_rescan_the_paragraph() { + let text = format!("x{}\n", "y".repeat(200_000)); + let delim: String = ('a'..='z').chain('A'..='Z').filter(|c| *c != 'y').collect(); + let rule = NestedStyle { style: "S".into(), through: false, count: 1, until: NestedUntil::Chars(delim) }; + let nested = vec![rule; 5000]; + let t = std::time::Instant::now(); + assert!(overlays(&text, 0..text.len(), &nested, &[], 0).is_empty(), "each style styles nothing"); + assert!(t.elapsed().as_secs() < 5, "{:?}", t.elapsed()); + } + #[test] fn nested_and_grep_ranges() { let text = "Q: what is 42? A drop of 7 words.\n".to_string(); diff --git a/crates/compose/src/parabox.rs b/crates/compose/src/parabox.rs index f6b90e127..4a5b0e8d1 100644 --- a/crates/compose/src/parabox.rs +++ b/crates/compose/src/parabox.rs @@ -32,6 +32,7 @@ struct Shading { bottom: BoxBottom, clip: bool, nonprinting: bool, + overprint: bool, } #[derive(Clone, Debug, PartialEq)] @@ -51,6 +52,8 @@ struct Border { display_if_splits: bool, gap_color: String, gap_tint: f32, + overprint: bool, + gap_overprint: bool, } fn finite(v: f64) -> f64 { @@ -72,6 +75,7 @@ impl ParaBox { bottom: pp.shading_bottom, clip: pp.shading_clip, nonprinting: pp.shading_nonprinting, + overprint: pp.shading_overprint, }); let border = pp.border_on.then(|| Border { color: pp.border_color.clone(), @@ -88,6 +92,8 @@ impl ParaBox { display_if_splits: pp.border_display_if_splits, gap_color: pp.border_gap_color.clone(), gap_tint: pp.border_gap_tint, + overprint: pp.border_overprint, + gap_overprint: pp.border_gap_overprint, }); Some(ParaBox { shading, border, merge: pp.border_merge }) } @@ -136,7 +142,7 @@ fn shading_deco(s: &Shading, part: &Part<'_>, frames: &[FrameSpec], first_part: // Corners stay square where the box is cut by a split. let corners = cut_corners(s.corners, !first_part, !last_part); let path = (!corners.iter().all(Corner::is_none)).then(|| box_outline(rect, &corners, [true; 4])); - return Some(Deco { rect, color: s.color.clone(), tint: s.tint, path, nonprinting: s.nonprinting }); + return Some(Deco { rect, color: s.color.clone(), tint: s.tint, path, nonprinting: s.nonprinting, overprint: s.overprint }); } None } @@ -149,15 +155,14 @@ fn border_decos(bd: &Border, part: &Part<'_>, first_part: bool, last_part: bool, let open_top = !first_part && !bd.display_if_splits; let open_bottom = !last_part && !bd.display_if_splits; for (path, gap) in border_paths(bd, o, open_top, open_bottom) { - let (color, tint) = if gap { (bd.gap_color.clone(), bd.gap_tint) } else { (bd.color.clone(), bd.tint) }; - decos.push((part.fi, false, Deco { rect: path.bounding_box(), color, tint, path: Some(path), nonprinting: false })); + let (color, tint, overprint) = + if gap { (bd.gap_color.clone(), bd.gap_tint, bd.gap_overprint) } else { (bd.color.clone(), bd.tint, bd.overprint) }; + decos.push((part.fi, false, Deco { rect: path.bounding_box(), color, tint, path: Some(path), nonprinting: false, overprint })); } if is_plain(bd, open_top, open_bottom) { - decos.extend( - plain_edges(bd, o, open_top, open_bottom) - .into_iter() - .map(|rect| (part.fi, false, Deco { rect, color: bd.color.clone(), tint: bd.tint, path: None, nonprinting: false })), - ); + decos.extend(plain_edges(bd, o, open_top, open_bottom).into_iter().map(|rect| { + (part.fi, false, Deco { rect, color: bd.color.clone(), tint: bd.tint, path: None, nonprinting: false, overprint: bd.overprint }) + })); } } @@ -353,10 +358,10 @@ fn stroke_outline(path: &BezPath, w: f64, kind: &StrokeType, cap: Cap, join: Joi let p: Vec = pattern.iter().copied().filter(|v| v.is_finite() && *v >= 0.0).collect(); Some(if p.iter().sum::() > 1e-3 { p } else { vec![3.0 * w, 2.0 * w] }) } - StrokeType::Dotted => { - st = st.with_caps(kurbo::Cap::Round); - Some(vec![0.0, 2.0 * w]) - } + StrokeType::Dotted => match dots(path, w) { + Some(d) => return d, + None => None, + }, _ => None, }; if let Some(d) = dashes { @@ -367,3 +372,142 @@ fn stroke_outline(path: &BezPath, w: f64, kind: &StrokeType, cap: Cap, join: Joi } kurbo::stroke(path.iter(), &st, &kurbo::StrokeOpts::default(), TOL) } + +/// Round dots `w` wide along `path`, about `2w` apart and evenly spaced by arc length: around a +/// closed subpath the spacing divides its length exactly, an open one has a dot at each end. +/// `None` (stroke solid) when there would be more than [`MAX_DASHES`] dots. +fn dots(path: &BezPath, w: f64) -> Option { + use kurbo::{ParamCurve, ParamCurveArclen, PathEl, PathSeg}; + // Subpaths as (segments, closed). + let mut subs: Vec<(Vec, bool)> = Vec::new(); + let (mut start, mut cur) = (kurbo::Point::ZERO, kurbo::Point::ZERO); + for el in path.elements() { + let seg = match *el { + PathEl::MoveTo(p) => { + subs.push((Vec::new(), false)); + (start, cur) = (p, p); + continue; + } + PathEl::LineTo(p) => PathSeg::Line(kurbo::Line::new(cur, p)), + PathEl::QuadTo(a, p) => PathSeg::Quad(kurbo::QuadBez::new(cur, a, p)), + PathEl::CurveTo(a, b, p) => PathSeg::Cubic(kurbo::CubicBez::new(cur, a, b, p)), + PathEl::ClosePath => { + if let Some(s) = subs.last_mut() { + s.1 = true; + if cur.distance(start) > 1e-9 { + s.0.push(PathSeg::Line(kurbo::Line::new(cur, start))); + } + } + cur = start; + continue; + } + }; + cur = seg.end(); + if let Some(s) = subs.last_mut() { + s.0.push(seg); + } + } + const ACC: f64 = 1e-4; + let mut out = BezPath::new(); + let mut count = 0.0; + for (segs, closed) in subs { + let lens: Vec = segs.iter().map(|s| s.arclen(ACC)).collect(); + let total: f64 = lens.iter().sum(); + if !(total.is_finite() && total > 1e-9) { + continue; + } + let n = (total / (2.0 * w)).round().max(1.0); + count += n + 1.0; + if count > MAX_DASHES { + return None; + } + let step = total / n; + let dots = if closed { n as usize } else { n as usize + 1 }; + let (mut k, mut before) = (0, 0.0); + for i in 0..dots { + let s = i as f64 * step; + while k + 1 < segs.len() && before + lens.get(k).copied().unwrap_or(0.0) < s { + before += lens.get(k).copied().unwrap_or(0.0); + k += 1; + } + let (Some(seg), Some(&l)) = (segs.get(k), lens.get(k)) else { continue }; + let t = if l > 1e-12 { seg.inv_arclen((s - before).clamp(0.0, l), ACC) } else { 0.0 }; + out.extend(kurbo::Circle::new(seg.eval(t), w / 2.0).path_elements(TOL)); + } + } + Some(out) +} + +#[cfg(test)] +mod dotted_tests { + use super::*; + + /// The centres of the dots (one subpath each) of a dotted outline. + fn dot_centres(p: &BezPath) -> Vec { + let mut out = Vec::new(); + let mut cur = BezPath::new(); + for el in p.elements() { + if matches!(el, kurbo::PathEl::MoveTo(_)) && !cur.elements().is_empty() { + out.push(cur.bounding_box().center()); + cur = BezPath::new(); + } + cur.push(*el); + } + if !cur.elements().is_empty() { + out.push(cur.bounding_box().center()); + } + out + } + + /// Distance along the outline of `r`, clockwise from its top left corner, of point `q` on it. + fn along(r: Rect, q: kurbo::Point) -> f64 { + let (w, h) = (r.width(), r.height()); + if (q.y - r.y0).abs() < 1e-6 { + q.x - r.x0 + } else if (q.x - r.x1).abs() < 1e-6 { + w + q.y - r.y0 + } else if (q.y - r.y1).abs() < 1e-6 { + w + h + r.x1 - q.x + } else { + 2.0 * w + h + r.y1 - q.y + } + } + + fn assert_even(gaps: &[f64], expected: f64) { + for g in gaps { + assert!((g - expected).abs() < 0.05, "uneven dot gaps {gaps:?}, expected {expected}"); + } + } + + #[test] + fn dotted_box_border_dots_are_evenly_spaced() { + let r = Rect::new(0.0, 0.0, 100.3, 37.7); + let path = box_outline(r, &[Corner::default(); 4], [true; 4]); + let len = 2.0 * (r.width() + r.height()); + let out = stroke_outline(&path, 1.0, &StrokeType::Dotted, Cap::Butt, Join::Miter, len); + let mut s: Vec = dot_centres(&out).into_iter().map(|q| along(r, q)).collect(); + s.sort_by(f64::total_cmp); + let n = (len / 2.0).round() as usize; + assert_eq!(s.len(), n, "dot count"); + let mut gaps: Vec = s.windows(2).map(|p| p[1] - p[0]).collect(); + gaps.push(s[0] + len - s[n - 1]); + assert_even(&gaps, len / n as f64); + } + + #[test] + fn dotted_edge_dots_are_evenly_spaced_and_reach_both_ends() { + for (w, l) in [(1.0, 50.3), (2.5, 37.7), (0.7, 100.3)] { + let mut p = BezPath::new(); + p.move_to((0.0, 0.0)); + p.line_to((l, 0.0)); + let out = stroke_outline(&p, w, &StrokeType::Dotted, Cap::Butt, Join::Miter, l); + let mut xs: Vec = dot_centres(&out).into_iter().map(|q| q.x).collect(); + xs.sort_by(f64::total_cmp); + let n = (l / (2.0 * w)).round() as usize; + assert_eq!(xs.len(), n + 1, "dot count for w {w}, length {l}"); + assert!(xs[0].abs() < 0.05 && (xs[n] - l).abs() < 0.05, "ends {xs:?}"); + let gaps: Vec = xs.windows(2).map(|p| p[1] - p[0]).collect(); + assert_even(&gaps, l / n as f64); + } + } +} diff --git a/crates/compose/src/placed.rs b/crates/compose/src/placed.rs index 200ff6e3c..0207f3af4 100644 --- a/crates/compose/src/placed.rs +++ b/crates/compose/src/placed.rs @@ -4,6 +4,7 @@ //! own story is composed against that placement (page, page side, page rect, baseline grid), so //! the host story is composed first. +use std::collections::HashMap; use std::sync::Arc; use designcraft_doc::{Document, Item, ItemId, SpreadRef, StoryId}; @@ -23,33 +24,54 @@ pub struct Placement { pub xf: Affine, } -/// The placements of `sid`'s anchored frames, from their host stories composed by `host`. +/// The placements of `sid`'s anchored frames, from their host stories composed by `host`. Each +/// host is asked for once, however many of the frames it holds. pub(crate) fn placements(doc: &Document, sid: StoryId, host: &mut dyn FnMut(StoryId) -> Arc) -> Vec<(ItemId, Placement)> { let Some(st) = doc.story(sid) else { return Vec::new() }; let mut anchored = None; + let mut hosts: HashMap> = HashMap::new(); let mut out = Vec::new(); for &fid in &st.frames { if doc.find(fid).is_some() { continue; } let items = anchored.get_or_insert_with(|| doc.anchored_items()); - // A frame anchored in its own story would need its own composition to place it. - let Some(owner) = items.iter().find_map(|(owner, it)| (it.id == fid).then_some(*owner)).filter(|o| *o != sid) else { continue }; - if let Some(p) = locate(doc, &host(owner), fid) { + if let Some(p) = locate(doc, items, sid, fid, &mut hosts, host, 0) { out.push((fid, p)); } } out } -/// Where `cs` (a host story's composition) places item `fid`: in its frames' anchored objects, -/// footnotes and table cells. -fn locate(doc: &Document, cs: &ComposedStory, fid: ItemId) -> Option { +/// Where the host story of `fid`, an anchored frame of story `sid`, places it: in its frames' +/// anchored objects, footnotes and table cells. A host frame that is itself anchored is placed +/// the same way first, up to [`MAX_DEPTH`] hosts out. `items` is [`Document::anchored_items`]. +fn locate( + doc: &Document, + items: &[(StoryId, &Item)], + sid: StoryId, + fid: ItemId, + hosts: &mut HashMap>, + host: &mut dyn FnMut(StoryId) -> Arc, + depth: usize, +) -> Option { + if depth > MAX_DEPTH { + return None; + } + // A frame anchored in its own story would need its own composition to place it. + let owner = items.iter().find_map(|(owner, it)| (it.id == fid).then_some(*owner)).filter(|o| *o != sid)?; + let cs = hosts.entry(owner).or_insert_with(|| host(owner)).clone(); cs.frames.iter().find_map(|ft| { - let loc = doc.find(ft.frame)?; - let frame = doc.item_at(&loc)?; - let xf = in_frame(ft, doc.parent_xf(&loc) * doc.text_xf(frame), fid, 0)?; - Some(Placement { spread: loc.spread, xf }) + if let Some(loc) = doc.find(ft.frame) { + let frame = doc.item_at(&loc)?; + let xf = in_frame(ft, doc.parent_xf(&loc) * doc.text_xf(frame), fid, 0)?; + return Some(Placement { spread: loc.spread, xf }); + } + // The host frame is anchored too: find `fid` in it before placing the frame. + let local = in_frame(ft, Affine::IDENTITY, fid, 0)?; + let frame = items.iter().find_map(|(_, it)| (it.id == ft.frame).then_some(*it))?; + let outer = locate(doc, items, owner, ft.frame, hosts, host, depth + 1)?; + Some(Placement { spread: outer.spread, xf: outer.xf * doc.text_xf(frame) * local }) }) } diff --git a/crates/compose/src/reuse.rs b/crates/compose/src/reuse.rs new file mode 100644 index 000000000..4ac5a078c --- /dev/null +++ b/crates/compose/src/reuse.rs @@ -0,0 +1,738 @@ +//! Composing an edited story from the composition it had before the edit. +//! +//! A composition that laid every paragraph once leaves a [`Trace`]: the state it had before each +//! paragraph. Composing the story again after an edit starts at the paragraph before the first +//! changed one, in the state the trace holds for it and with the lines above it copied. It stops +//! at the first paragraph after the edit that it reaches in the state the trace holds for that +//! paragraph, and copies the lines from there on with their story offsets moved by the length of +//! the edit. The result is the composition a full pass over the edited story gives. +//! +//! Only plain stories are traced ([`plain`]): the features left out carry state between +//! paragraphs that the trace does not hold, or move lines after they are set. A composition that +//! goes back over a paragraph (keep options, column balancing, hyphenation across columns) +//! leaves no trace, and one that does so while it reuses a trace is abandoned for a full pass. + +use std::rc::Rc; + +use designcraft_doc::{CharRun, ListCounter, Story, VerticalJustification}; + +use crate::{Above, Band, ComposeOptions, ComposedStory, Cursor, FrameSpec, Line, ParaInfo, RunStyle, Snapshot}; + +#[cfg(test)] +thread_local! { + /// Paragraphs shaped on this thread (tests count the work an edit causes). + pub(crate) static SHAPED: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// The composition's state before a paragraph: the cursor, the list numbering, and how much of +/// the cursor's frame and of the run style table is filled. +#[derive(Clone, Debug)] +struct Mark { + fi: usize, + col: usize, + last_baseline: Option, + last_descent: f64, + last_reference: f64, + aki_below: Option, + pending: f64, + band: Band, + grid_next: Option<(f64, f64)>, + list_counter: ListCounter, + lines: usize, + decos: usize, + styles: usize, +} + +fn bits(v: Option) -> Option { + v.map(f64::to_bits) +} + +fn above_bits(a: Option) -> Option<[Option; 6]> { + a.map(|a| { + [ + Some(a.top.to_bits()), + Some(a.baseline.to_bits()), + Some(a.descent.to_bits()), + Some(a.reference.to_bits()), + bits(a.aki_below), + Some(a.pending.to_bits()), + ] + }) +} + +impl Mark { + /// The state `snap` holds with `styles` run styles in the table, or `None` when it has state + /// a mark does not hold (a split-column block, balanced column bottoms, tables). + fn of(snap: &Snapshot, styles: usize) -> Option { + let c = &snap.cur; + if c.split.is_some() || !c.limits.is_empty() || !c.split_limits.is_empty() || snap.tables != 0 { + return None; + } + Some(Mark { + fi: c.fi, + col: c.col, + last_baseline: c.last_baseline, + last_descent: c.last_descent, + last_reference: c.last_reference, + aki_below: c.aki_below, + pending: c.pending, + band: c.band, + grid_next: c.grid_next, + list_counter: snap.list_counter.clone(), + lines: snap.lines, + decos: snap.decos, + styles, + }) + } + + fn cursor(&self, pi: usize) -> Cursor { + Cursor { + fi: self.fi, + col: self.col, + last_baseline: self.last_baseline, + last_descent: self.last_descent, + last_reference: self.last_reference, + aki_below: self.aki_below, + pending: self.pending, + pi, + band: self.band, + limits: Rc::default(), + split: None, + split_limits: Rc::default(), + grid_next: self.grid_next, + } + } + + /// The mark with its paragraph numbers after the edit. + fn moved(&self, plan: &Plan) -> Mark { + let band = Band { para: plan.moved(self.band.para), tail: self.band.tail.map(|(p, c)| (plan.moved(p), c)), ..self.band }; + Mark { band, ..self.clone() } + } + + /// Whether composing on from `self` and from `other` sets the same lines. Numbers are + /// compared by their bits: a difference too small to show still changes what follows. + fn same(&self, other: &Mark) -> bool { + let (a, b) = (&self.band, &other.band); + self.fi == other.fi + && self.col == other.col + && bits(self.last_baseline) == bits(other.last_baseline) + && self.last_descent.to_bits() == other.last_descent.to_bits() + && self.last_reference.to_bits() == other.last_reference.to_bits() + && bits(self.aki_below) == bits(other.aki_below) + && self.pending.to_bits() == other.pending.to_bits() + && a.para == b.para + && a.line0 == b.line0 + && above_bits(a.above) == above_bits(b.above) + && a.tail == b.tail + && self.grid_next.map(|(x, y)| (x.to_bits(), y.to_bits())) == other.grid_next.map(|(x, y)| (x.to_bits(), y.to_bits())) + && self.list_counter == other.list_counter + && self.lines == other.lines + && self.decos == other.decos + && self.styles == other.styles + } +} + +/// What a composition leaves for composing the story again after an edit: its state before each +/// paragraph it laid (and after the last one), and where each paragraph sits. +#[derive(Debug)] +pub(crate) struct Trace { + marks: Vec, + info: Vec, +} + +/// A story as it was before an edit, its composition and that composition's trace. +#[derive(Clone, Copy)] +pub(crate) struct Reuse<'a> { + pub story: &'a Story, + pub composed: &'a ComposedStory, + pub trace: &'a Trace, +} + +/// How much of the composition before an edit holds for the edited story. +pub(crate) struct Plan { + /// The paragraph composing starts at. + pub resume: usize, + /// The first paragraph (numbered as in the edited story) that may take the lines it had + /// before the edit: the one before it is unchanged too. + pub rejoin: usize, + /// Paragraphs and bytes the edit added. + paras: isize, + bytes: isize, + /// The first paragraph the edit left as it was, numbered as before the edit. + old_tail: usize, +} + +impl Plan { + /// The number after the edit of paragraph `p` of the story before it. + fn moved(&self, p: usize) -> usize { + if p >= self.old_tail { p.wrapping_add_signed(self.paras) } else { p } + } + + /// The number before the edit of paragraph `pi` of the edited story's unchanged end. + fn before(&self, pi: usize) -> Option { + pi.checked_add_signed(self.paras.checked_neg()?) + } +} + +/// Whether a composition of `story` in `frames` can leave a trace, or use one. Footnotes, +/// endnotes, tables and anchored objects carry state of their own; named lists and tracked +/// deletions reach across paragraphs; vertical justification and column rules change a frame +/// after its lines are set; type on a path sizes its frame from the story; balanced columns are +/// laid more than once. +pub(crate) fn plain(story: &Story, frames: &[FrameSpec], opts: &ComposeOptions, labels: &[Option], deleted: &[bool]) -> bool { + story.notes.is_empty() + && story.endnotes.is_empty() + && story.objects.is_empty() + && story.tables.is_empty() + && opts.label.is_none() + && labels.iter().all(Option::is_none) + && !deleted.contains(&true) + && frames.iter().all(|f| { + let o = &f.opts; + o.vertical_justification == VerticalJustification::Top && !o.column_rule && o.path.is_none() && !(o.balance_columns && o.columns > 1) + }) +} + +/// Whether the paragraphs a composition laid are ones a trace covers: none spans or splits +/// columns (`span`, `split`, by paragraph) or has a border or shading (`boxes`), which are drawn +/// once every line is set. +pub(crate) fn plain_end(span: &[bool], split: &[bool], boxes: &[Option]) -> bool { + !span.contains(&true) && !split.contains(&true) && boxes.iter().all(Option::is_none) +} + +/// Bytes of text from the start of both run lists (in the order given) that have the same +/// character formats. +fn same_formats<'a>(mut old: impl Iterator, mut new: impl Iterator) -> usize { + let mut same = 0usize; + let (mut a, mut b): (Option<(&CharRun, usize)>, Option<(&CharRun, usize)>) = (None, None); + loop { + if a.is_none_or(|(_, left)| left == 0) { + a = old.find(|r| r.len > 0).map(|r| (r, r.len)); + } + if b.is_none_or(|(_, left)| left == 0) { + b = new.find(|r| r.len > 0).map(|r| (r, r.len)); + } + let (Some((ra, la)), Some((rb, lb))) = (a, b) else { return same }; + if ra.format != rb.format { + return same; + } + let step = la.min(lb); + same += step; + (a, b) = (Some((ra, la - step)), Some((rb, lb - step))); + } +} + +fn returns(text: &str) -> usize { + text.bytes().filter(|b| *b == b'\n').count() +} + +impl Reuse<'_> { + /// Where composing `new` (the story after the edit) starts and may stop, or `None` when the + /// edit changed something a trace does not cover. + pub(crate) fn plan(&self, new: &Story) -> Option { + let old = self.story; + if old.frames != new.frames + || old.direction != new.direction + || old.vertical != new.vertical + || old.optical_margin != new.optical_margin + || old.anchors != new.anchors + || old.xrefs != new.xrefs + || old.index_refs != new.index_refs + || old.editorial != new.editorial + { + return None; + } + let (o, n) = (old.text.as_bytes(), new.text.as_bytes()); + if old.paras.len() != returns(&old.text) + 1 || new.paras.len() != returns(&new.text) + 1 { + return None; + } + // The unchanged start: the same text in the same character formats, then whole paragraphs + // with the same paragraph formats. + let mut head = o.iter().zip(n).take_while(|(a, b)| a == b).count().min(same_formats(old.chars.iter(), new.chars.iter())); + while !new.text.is_char_boundary(head) { + head -= 1; + } + let whole = returns(new.text.get(..head)?); + let first = old.paras.iter().zip(&new.paras).take(whole).take_while(|(a, b)| a == b).count(); + if first < whole { + // A paragraph format changed above the first changed character. + head = match first.checked_sub(1) { + Some(k) => n.iter().enumerate().filter(|(_, b)| **b == b'\n').nth(k).map(|(i, _)| i + 1)?, + None => 0, + }; + } + // The unchanged end, which the unchanged start does not overlap. + let room = o.len().min(n.len()).checked_sub(head)?; + let mut tail = o + .iter() + .rev() + .zip(n.iter().rev()) + .take_while(|(a, b)| a == b) + .count() + .min(same_formats(old.chars.iter().rev(), new.chars.iter().rev())) + .min(room); + while !new.text.is_char_boundary(n.len() - tail) { + tail -= 1; + } + let after = returns(new.text.get(n.len() - tail..)?); + let after = old.paras.iter().rev().zip(new.paras.iter().rev()).take(after).take_while(|(a, b)| a == b).count(); + let (old_paras, new_paras) = (old.paras.len(), new.paras.len()); + Some(Plan { + // One paragraph above the first changed one: setting a paragraph reads the one after it. + resume: first.saturating_sub(1).min(self.trace.marks.len().checked_sub(1)?), + rejoin: new_paras.checked_sub(after)? + 1, + paras: isize::try_from(new_paras).ok()?.checked_sub(isize::try_from(old_paras).ok()?)?, + bytes: isize::try_from(n.len()).ok()?.checked_sub(isize::try_from(o.len()).ok()?)?, + old_tail: old_paras.checked_sub(after)?, + }) + } + + /// Put `out` and `styles` back as they were before paragraph `plan.resume`, and give the + /// cursor, list numbering and paragraph positions of that moment. `None` when the composition + /// before the edit does not match `out`'s frames. + pub(crate) fn restore(&self, plan: &Plan, out: &mut ComposedStory, styles: &mut Vec) -> Option<(Cursor, ListCounter, Vec)> { + let mark = self.trace.marks.get(plan.resume)?; + let before = self.composed; + if before.frames.len() != out.frames.len() || before.frames.iter().zip(&out.frames).any(|(a, b)| a.frame != b.frame) { + return None; + } + let info = self.trace.info.get(..plan.resume)?.to_vec(); + *styles = before.styles.get(..mark.styles)?.to_vec(); + for (i, (to, from)) in out.frames.iter_mut().zip(&before.frames).enumerate().take(mark.fi.saturating_add(1)) { + let (lines, decos) = if i < mark.fi { (from.lines.len(), from.decos.len()) } else { (mark.lines, mark.decos) }; + to.lines = from.lines.get(..lines)?.iter().map(|l| moved_line(l, 0, 0)).collect(); + to.decos = from.decos.get(..decos)?.to_vec(); + } + Some((mark.cursor(plan.resume), mark.list_counter.clone(), info)) + } + + /// At paragraph `pi` of the edited story, in the state `snap` with `styles` and `info` as + /// they are: when the composition before the edit was in that state before the same + /// paragraph, copy what it set from there on into `out`, `styles` and `info`, and say so. + /// + /// The copied lines keep their run-style indexes, so this needs `styles` to equal the old + /// table up to that point. A run style that the edit uses for the first time takes a new + /// index, and the story then composes on until the old composition added the same style at + /// the same index, or to its end. The result is the same; only the time differs. + pub(crate) fn rejoin( + &self, + plan: &Plan, + pi: usize, + snap: &Snapshot, + out: &mut ComposedStory, + styles: &mut Vec, + info: &mut Vec, + ) -> bool { + let before = self.composed; + let Some(k) = plan.before(pi) else { return false }; + let (Some(old), Some(new)) = (self.trace.marks.get(k), Mark::of(snap, styles.len())) else { return false }; + // The paragraph above is where it was, and no chain of keep-with-next paragraphs reaches + // back through it into the changed text. + let last = |v: &[ParaInfo], i: usize| i.checked_sub(1).and_then(|i| v.get(i).cloned()); + let same_above = matches!((last(&self.trace.info, k), last(info, pi)), (Some(a), Some(b)) if a == b && a.keep_with_next == 0); + if !same_above || info.len() != pi || !old.moved(plan).same(&new) || before.styles.get(..old.styles) != Some(styles.as_slice()) { + return false; + } + for (i, (to, from)) in out.frames.iter_mut().zip(&before.frames).enumerate().skip(old.fi) { + let (lines, decos) = if i == old.fi { (old.lines, old.decos) } else { (0, 0) }; + to.lines.extend(from.lines.get(lines..).unwrap_or_default().iter().map(|l| moved_line(l, plan.bytes, plan.paras))); + to.decos.extend(from.decos.get(decos..).unwrap_or_default().iter().cloned()); + } + out.overset_at = before.overset_at.map(|b| b.wrapping_add_signed(plan.bytes)); + styles.clone_from(&before.styles); + info.extend(self.trace.info.get(k..).unwrap_or_default().iter().cloned()); + true + } +} + +/// `line` with its story offsets and paragraph number moved, and without the keep-violation +/// flag, which is set again for the whole story once it is composed. +fn moved_line(line: &Line, bytes: isize, paras: isize) -> Line { + let at = |b: usize| b.wrapping_add_signed(bytes); + let mut l = Line { keep_violation: false, ..line.clone() }; + l.range = at(l.range.start)..at(l.range.end); + l.para = l.para.wrapping_add_signed(paras); + if bytes != 0 { + for g in &mut l.glyphs { + g.byte = at(g.byte); + } + } + if let Some(cap) = &mut l.drop_cap { + cap.end = at(cap.end); + } + l +} + +/// What one composition keeps for its trace, and what it reuses of the composition before an +/// edit. +pub(crate) struct Pass<'a> { + before: Option<(&'a Reuse<'a>, Plan)>, + /// The composition was to reuse the one before an edit and cannot: its result is not used. + abandoned: bool, + /// A trace is wanted and nothing rules one out so far. + traced: bool, + /// Run styles in the table before each paragraph. + styles: Vec, + /// The paragraph the next step should be at: another one means the layout went back over a + /// paragraph. + next: usize, + /// The paragraph the lines copied from before the edit start at. + rejoined: Option, +} + +/// Where a composition starts: the paragraph, the cursor, the list numbering and the positions +/// of the paragraphs above. +pub(crate) struct Start { + pub pi: usize, + pub cur: Cursor, + pub list_counter: ListCounter, + pub info: Vec, +} + +impl<'a> Pass<'a> { + /// The bookkeeping for composing `story`, and where to start. `traced`: a trace is wanted and + /// the story is [`plain`]. `fresh` is the start of the story. With `before`, `out` and + /// `styles` are filled with what holds from before the edit and the start is the paragraph + /// above the edit; when `before` cannot be used the pass is abandoned at its first step. + pub(crate) fn new( + before: Option<&'a Reuse<'a>>, + story: &Story, + traced: bool, + fresh: Start, + out: &mut ComposedStory, + styles: &mut Vec, + ) -> (Pass<'a>, Start) { + let mut pass = Pass { before: None, abandoned: false, traced, styles: Vec::with_capacity(story.paras.len() + 1), next: 0, rejoined: None }; + let Some(b) = before else { return (pass, fresh) }; + let resumed = traced.then(|| b.plan(story)).flatten().and_then(|plan| Some((b.restore(&plan, out, styles)?, plan))); + let Some(((cur, list_counter, info), plan)) = resumed else { + pass.abandoned = true; + return (pass, fresh); + }; + let pi = plan.resume; + // The counts for the paragraphs above are never read: their marks are kept as they are. + pass.styles.resize(pi, 0); + pass.next = pi; + pass.before = Some((b, plan)); + (pass, Start { pi, cur, list_counter, info }) + } + + /// Before paragraph `pi` of `count` is laid, in the state `snap`: whether nothing is left to + /// lay, because the rest of the story is in place (copied from the composition before the + /// edit into `out`, `styles` and `info`) or because the pass is abandoned. + pub(crate) fn step( + &mut self, + (pi, count): (usize, usize), + snap: Option<&Snapshot>, + out: &mut ComposedStory, + styles: &mut Vec, + info: &mut Vec, + ) -> bool { + self.styles.truncate(pi); + self.styles.push(styles.len()); + if pi != self.next { + // The layout went back over a paragraph. + self.traced = false; + self.abandoned |= self.before.is_some(); + } + self.next = pi + 1; + if self.abandoned { + return true; + } + if pi < count + && let (Some((before, plan)), Some(snap)) = (&self.before, snap) + && pi >= plan.rejoin + && before.rejoin(plan, pi, snap, out, styles, info) + { + self.rejoined = Some(pi); + return true; + } + false + } + + /// The trace of the finished composition, when it laid every paragraph once and `plain_end` + /// (no paragraph it laid uses something a trace does not cover): `snaps` holds the state + /// before each paragraph it laid itself, `info` every paragraph's position. The paragraphs + /// above the one a reusing composition started at keep the marks they had, and those after + /// the one it rejoined at the marks that followed before the edit. The outer `None` is for an + /// abandoned pass and for a reusing one that leaves no trace: the story has to be composed + /// from its start. + pub(crate) fn trace(self, plain_end: bool, snaps: &[Snapshot], info: Vec) -> Option> { + if self.abandoned { + return None; + } + let trace = if self.traced && plain_end { self.marks(snaps).map(|marks| Trace { marks, info }) } else { None }; + if self.before.is_some() && trace.is_none() { + return None; + } + Some(trace) + } + + fn marks(&self, snaps: &[Snapshot]) -> Option> { + let reused = self.before.as_ref(); + let start = reused.map_or(0, |(_, plan)| plan.resume); + let mut marks = Vec::with_capacity(snaps.len()); + if let Some((before, _)) = reused { + marks.extend(before.trace.marks.get(..start)?.iter().cloned()); + } + for (snap, styles) in snaps.iter().zip(&self.styles).skip(start) { + marks.push(Mark::of(snap, *styles)?); + } + if let (Some((before, plan)), Some(pi)) = (reused, self.rejoined) { + let k = plan.before(pi)?; + marks.extend(before.trace.marks.get(k + 1..)?.iter().map(|m| m.moved(plan))); + } + // Lines are only ever added to the cursor's frame, so the frames above it are complete. + marks.windows(2).all(|w| w[0].fi <= w[1].fi).then_some(marks) + } +} + +#[cfg(test)] +mod tests { + use designcraft_doc::build::NewDocument; + use designcraft_doc::{Align, Document, ItemId, ListType, ParaFormat, SpreadRef, StartParagraph, Story, StoryId, VerticalJustification}; + use designcraft_geom::Rect; + + use super::SHAPED; + use crate::Cache; + + const SENTENCE: &str = "The quick brown fox jumps over the lazy dog while the workbook keeps growing page by page."; + + /// A story of `paras` paragraphs of two to five lines, threaded through `frames` frames of 31 + /// lines each. + fn threaded(paras: usize, frames: usize) -> (Document, StoryId, Vec) { + let mut d = Document::new(&NewDocument::default()); + let lid = d.default_layer(); + let text = (0..paras).map(|i| vec![SENTENCE; 2 + i % 4].join(" ")).collect::>().join("\n"); + let rect = |i: usize| Rect::new(i as f64 * 600.0, 0.0, i as f64 * 600.0 + 540.0, 456.0); + let (first, sid) = d.add_text_frame(SpreadRef::Doc(0), rect(0), lid, &text, ParaFormat::default()).unwrap(); + let mut ids = vec![first]; + for i in 1..frames { + let (next, _) = d.add_text_frame(SpreadRef::Doc(0), rect(i), lid, "", ParaFormat::default()).unwrap(); + d.thread(ids[i - 1], next).unwrap(); + ids.push(next); + } + (d, sid, ids) + } + + /// What `f` returns and the paragraphs it shaped. + fn shaped(f: impl FnOnce() -> T) -> (T, usize) { + SHAPED.with(|n| n.set(0)); + let out = f(); + (out, SHAPED.with(|n| n.get())) + } + + /// Compose the edited story through `cache`, which holds its composition before the edit, and + /// check the result against composing it whole. Gives the paragraphs the cache shaped. + fn check(cache: &Cache, d: &Document, sid: StoryId, what: &str) -> usize { + let (cached, n) = shaped(|| cache.get(d, sid, None)); + let whole = Cache::new().get(d, sid, None); + assert_eq!(cached.frames.len(), whole.frames.len(), "{what}"); + for (fi, (a, b)) in cached.frames.iter().zip(&whole.frames).enumerate() { + assert_eq!(a.lines.len(), b.lines.len(), "{what}: lines in frame {fi}"); + for (li, (x, y)) in a.lines.iter().zip(&b.lines).enumerate() { + assert_eq!(format!("{x:?}"), format!("{y:?}"), "{what}: frame {fi} line {li}"); + } + } + assert!(format!("{cached:?}") == format!("{whole:?}"), "{what}: the composition differs from composing the story whole"); + n + } + + #[test] + fn a_typed_character_composes_the_paragraphs_around_it() { + for paras in [60, 240] { + let (mut d, sid, _) = threaded(paras, paras / 4); + let cache = Cache::new(); + let (first, whole) = shaped(|| cache.get(&d, sid, None)); + assert!(!first.is_overset()); + assert!(first.frames.iter().filter(|f| !f.lines.is_empty()).count() > paras / 12); + assert_eq!(whole, paras); + let len = d.story(sid).unwrap().len(); + for at in [10, len / 2, len - 1] { + d.story_mut(sid).unwrap().insert(at, "x"); + let n = check(&cache, &d, sid, "a typed character"); + assert!(n <= 3, "{n} of {paras} paragraphs composed for a character typed at {at}"); + } + } + } + + /// The preflight cache reads an unchanged composition through its base, while edits + /// composed in the reader keep their own incremental trace and never replace the base. + #[test] + fn a_read_through_cache_keeps_incremental_edits_local() { + use std::sync::Arc; + let (mut d, sid, _) = threaded(60, 15); + let original = d.clone(); + let base = Arc::new(Cache::new()); + let first = base.get(&original, sid, None); + let reader = Cache::over(Arc::clone(&base)); + assert!(Arc::ptr_eq(&reader.get(&d, sid, None), &first)); + d.story_mut(sid).unwrap().insert(10, "x"); + check(&reader, &d, sid, "first edit in reader"); + d.story_mut(sid).unwrap().insert(11, "y"); + let n = check(&reader, &d, sid, "second edit in reader"); + assert!(n <= 3, "reader shaped {n} paragraphs instead of reusing its trace"); + assert!(Arc::ptr_eq(&base.get(&original, sid, None), &first)); + assert!(base.composed_for(&d, sid).is_none()); + } + + #[test] + fn characters_typed_one_after_another_each_compose_the_paragraphs_around_them() { + let (mut d, sid, _) = threaded(80, 20); + let cache = Cache::new(); + cache.get(&d, sid, None); + let at = d.story(sid).unwrap().len() / 2; + for (i, c) in "one two\nthree".chars().enumerate() { + d.story_mut(sid).unwrap().insert(at + i, &c.to_string()); + let n = check(&cache, &d, sid, "typing"); + // A return adds a line, which moves the paragraphs below it in their frame: they are + // composed up to the end of the story. + assert!(c == '\n' || n <= 4, "{n} of 80 paragraphs composed for {c:?}"); + } + } + + #[test] + fn an_edit_that_moves_lines_composes_up_to_the_next_frame_the_text_starts_in() { + let (mut d, sid, _) = threaded(100, 24); + // Chapters of five paragraphs, each starting in the next frame. + let starts: Vec = + d.story(sid).unwrap().para_ranges().iter().enumerate().filter(|(i, _)| *i > 0 && i % 5 == 0).map(|(_, r)| r.start).collect(); + for at in starts { + d.story_mut(sid).unwrap().format_paras(at..at, |p| p.para.start_paragraph = Some(StartParagraph::NextFrame)); + } + let cache = Cache::new(); + let (first, whole) = shaped(|| cache.get(&d, sid, None)); + assert!(!first.is_overset()); + assert_eq!(whole, 100); + let at = d.story(sid).unwrap().para_ranges()[52].start + 20; + d.story_mut(sid).unwrap().insert(at, &format!(" {SENTENCE} {SENTENCE}")); + let n = check(&cache, &d, sid, "two more lines in a chapter"); + assert!(n <= 6, "{n} of 100 paragraphs composed for lines added to one chapter"); + } + + #[test] + fn edits_give_the_composition_of_the_edited_story() { + let (mut d, sid, _) = threaded(40, 12); + let original = d.clone(); + let cache = Cache::new(); + cache.get(&d, sid, None); + let edits: [(&str, fn(&mut Story)); 15] = [ + ("a character", |s| s.insert(s.len() / 2, "x")), + ("a return", |s| s.insert(s.len() / 2, "\n")), + ("a long insertion", |s| s.insert(s.len() / 3, &format!(" {SENTENCE} {SENTENCE} {SENTENCE}"))), + ("several paragraphs", |s| s.insert(s.len() / 3, &format!("\n{SENTENCE}\n{SENTENCE}\n"))), + ("a deleted character", |s| s.delete(s.len() / 2..s.len() / 2 + 1)), + ("a deleted return", |s| { + let at = s.text[..s.len() / 2].rfind('\n').unwrap(); + s.delete(at..at + 1); + }), + ("a deletion across paragraphs", |s| s.delete(s.len() / 4..s.len() / 4 + 900)), + ("a replacement", |s| s.replace(s.len() / 2..s.len() / 2 + 40, "replaced")), + ("larger type", |s| s.format_chars(s.len() / 2..s.len() / 2 + 60, |f| f.over.size = Some(18.0))), + ("a centered paragraph", |s| s.format_paras(s.len() / 2..s.len() / 2, |p| p.para.align = Some(Align::Center))), + ("text at the start", |s| s.insert(0, "Start. ")), + ("text at the end", |s| s.insert(s.len(), " End.")), + ("a two-byte character", |s| s.insert(s.len() / 2, "\u{e9}")), + ("everything deleted", |s| s.delete(0..s.len())), + ("text in an empty story", |s| s.insert(0, "Again.")), + ]; + for (what, edit) in edits { + edit(d.story_mut(sid).unwrap()); + check(&cache, &d, sid, what); + } + // Undo puts an earlier story back. + check(&cache, &original, sid, "the story before the edits"); + } + + #[test] + fn edits_in_and_above_overset_text_compose_right() { + let (mut d, sid, _) = threaded(60, 3); + let cache = Cache::new(); + assert!(cache.get(&d, sid, None).is_overset()); + let len = d.story(sid).unwrap().len(); + d.story_mut(sid).unwrap().insert(len - 10, "x"); + let n = check(&cache, &d, sid, "a character in overset text"); + assert!(n <= 1, "{n} paragraphs composed for a character typed in overset text"); + d.story_mut(sid).unwrap().insert(200, &format!(" {SENTENCE}")); + check(&cache, &d, sid, "a line added above overset text"); + d.story_mut(sid).unwrap().delete(100..len / 2); + check(&cache, &d, sid, "a deletion that brings overset text into the frames"); + } + + /// Stories with features a trace does not cover are composed whole after an edit. + #[test] + fn edits_of_stories_a_trace_does_not_cover_compose_right() { + let setups: [(&str, fn(&mut Document, StoryId, &[ItemId])); 6] = [ + ("keep options", |d, sid, _| { + let s = d.story_mut(sid).unwrap(); + s.format_paras(0..s.len(), |p| { + p.para.keep_with_next = Some(1); + p.para.keep_lines_together = Some(true); + }); + }), + ("balanced columns", |d, _, frames| { + for f in frames { + let o = &mut d.item_mut(*f).unwrap().text_frame_mut().unwrap().options; + (o.columns, o.balance_columns) = (2, true); + } + }), + ("vertical justification", |d, _, frames| { + for f in frames { + d.item_mut(*f).unwrap().text_frame_mut().unwrap().options.vertical_justification = VerticalJustification::Center; + } + }), + ("a numbered list", |d, sid, _| { + let s = d.story_mut(sid).unwrap(); + s.format_paras(0..s.len(), |p| p.para.list_type = Some(ListType::Numbers)); + }), + ("a footnote", |d, sid, _| { + d.story_mut(sid).unwrap().insert_note(300, "A synthetic footnote.", ParaFormat::default()); + }), + ("a column rule", |d, _, frames| { + for f in frames { + let o = &mut d.item_mut(*f).unwrap().text_frame_mut().unwrap().options; + (o.columns, o.column_rule) = (2, true); + } + }), + ]; + for (what, setup) in setups { + let (mut d, sid, frames) = threaded(30, 10); + setup(&mut d, sid, &frames); + let cache = Cache::new(); + cache.get(&d, sid, None); + let mid = d.story(sid).unwrap().len() / 2; + d.story_mut(sid).unwrap().insert(mid, "x"); + check(&cache, &d, sid, what); + d.story_mut(sid).unwrap().insert(mid, &format!("\n{SENTENCE} {SENTENCE}\n")); + check(&cache, &d, sid, what); + d.story_mut(sid).unwrap().delete(mid / 2..mid); + check(&cache, &d, sid, what); + } + } + + #[test] + fn a_run_of_mixed_edits_composes_right_after_each() { + let (mut d, sid, _) = threaded(40, 14); + let cache = Cache::new(); + cache.get(&d, sid, None); + let texts = ["x", " word", "\n", " several words in a row here", "\n\n", "A sentence. "]; + let mut seed = 0x2545_f491_u64; + let mut next = |below: usize| { + seed = seed.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1_442_695_040_888_963_407); + (seed >> 33) as usize % below.max(1) + }; + for step in 0..60 { + let s = d.story_mut(sid).unwrap(); + let at = next(s.len() + 1); + match next(4) { + 0 | 1 => s.insert(at, texts[next(texts.len())]), + 2 => s.delete(at..(at + next(120)).min(s.len())), + _ => { + let size = 9.0 + next(10) as f64; + s.format_chars(at..(at + next(60)).min(s.len()), |f| f.over.size = Some(size)); + } + } + check(&cache, &d, sid, &format!("step {step}")); + } + } +} diff --git a/crates/compose/src/ruby.rs b/crates/compose/src/ruby.rs index 47c48a728..47b7c21c1 100644 --- a/crates/compose/src/ruby.rs +++ b/crates/compose/src/ruby.rs @@ -648,6 +648,7 @@ pub(crate) fn annotate( let style = ruby_style(styles, &st, &spec, shaped.size, missing); for (r, off) in shaped.glyphs.iter().zip(offsets) { extra.push(PlacedGlyph { + list_label: false, rendered_char: r.ch, face: shaped.face, gid: r.gid, diff --git a/crates/compose/src/shape.rs b/crates/compose/src/shape.rs index d972cad30..1de4b823c 100644 --- a/crates/compose/src/shape.rs +++ b/crates/compose/src/shape.rs @@ -317,6 +317,20 @@ impl StyleTable<'_> { } } +/// What a substitute face's own name says about its style, for choosing a CJK fallback chain. +/// +/// `None` for the bundled default and last-resort families: they stand in for a font that could +/// not be resolved at all, so their names say nothing about what the document asked for. Without +/// this, "Source Sans 3" made every unresolved family look like a sans one (#1692, noted in +/// review). +fn style_of_substitute(family: &str) -> Option { + let standin = [designcraft_fonts::DEFAULT_FAMILY, designcraft_fonts::FALLBACK_FAMILY]; + if standin.iter().any(|s| s.eq_ignore_ascii_case(family)) { + return None; + } + designcraft_fonts::sans_by_name(family) +} + /// Resolve and shape one paragraph. Its drop cap ends at byte `drop.0` (`range.start` without /// one) and takes the character style `drop.1` ("" = none). pub(crate) struct ShapeInput<'a, 'font> { @@ -385,6 +399,7 @@ fn resolve_pieces(input: &ShapeInput<'_, '_>, table: &mut StyleTable<'_>) -> (Ve overlays.push((range.start..drop_cap.0, s.to_string())); } // Each run, cut where nested / GREP styles start and end. + let bands = overlay_bands(&overlays); let mut segments: Vec<(usize, usize, Option<&str>, &designcraft_doc::CharFormat)> = Vec::new(); for (rr, fmt) in story.runs() { let a = rr.start.max(range.start); @@ -396,14 +411,16 @@ fn resolve_pieces(input: &ShapeInput<'_, '_>, table: &mut StyleTable<'_>) -> (Ve segments.push((a, b, None, fmt)); continue; } - let mut cuts: Vec = overlays.iter().flat_map(|(r, _)| [r.start, r.end]).filter(|x| *x > a && *x < b).collect(); - cuts.push(a); - cuts.push(b); - cuts.sort_unstable(); - cuts.dedup(); - for w in cuts.windows(2) { - let top = overlays.iter().rev().find(|(r, _)| r.start <= w[0] && w[0] < r.end).map(|(_, s)| s.as_str()); - segments.push((w[0], w[1], top, fmt)); + // The band holding `a`, then each following band up to `b`. Bands start at 0, so one + // holds `a`, and each ends where the next starts (the last one at `b`). + let mut k = bands.partition_point(|(at, _)| *at <= a).saturating_sub(1); + let mut at = a; + while at < b { + let to = bands.get(k + 1).map_or(b, |(next, _)| (*next).min(b)); + let top = bands.get(k).and_then(|(_, top)| *top).map(|i| overlays[i].1.as_str()); + segments.push((at, to, top, fmt)); + at = to; + k += 1; } } // Resolve every segment, then shape runs of segments that differ only in how they are @@ -810,8 +827,19 @@ fn shape_run_raw( // The language picks the fallback for CJK characters the primary font lacks. Without // fallback, the primary font sets them: the shaper gives its .notdef (glyph 0). let lang = designcraft_doc::language_tag(&p.language); + // A missing Korean face is replaced by one of its own style: the requested name says whether + // it was Dotum/Gothic or Batang/Myungjo, and if it does not, the substitute's own name does, + // which keeps today's chain (#1692). + // The substitute's own name is consulted only when it is a real substitute: a requested + // family that resolves to nothing comes back as the bundled default, whose name holds "Sans", + // and every unclassified missing font would then have taken the sans chain (noted in review). + let prefer_sans = designcraft_fonts::sans_by_name(&p.font_family).or_else(|| style_of_substitute(&primary.family)); let fallback = |c: char| { - if auto_leading.glyph_fallback { db.fallback_for(c, primary.id(), lang).unwrap_or_else(|| primary.clone()) } else { primary.clone() } + if auto_leading.glyph_fallback { + db.fallback_for_styled(c, primary.id(), lang, prefer_sans).unwrap_or_else(|| primary.clone()) + } else { + primary.clone() + } }; let strong = |c| match unicode_bidi::bidi_class(c) { unicode_bidi::BidiClass::AL => Some(true), @@ -1141,8 +1169,11 @@ fn shape_segment( if let Some(label) = replacement.filter(|_| auto_leading.glyph_fallback) { let lang = designcraft_doc::language_tag(&p.language); let mut segments: Vec<(usize, usize, Arc)> = Vec::new(); + // The same for every character of the label: worked out once, not per character. + let prefer_sans = designcraft_fonts::sans_by_name(&p.font_family).or_else(|| style_of_substitute(&face.family)); for (at, c) in label.char_indices() { - let selected = if face.covers(c) { face.clone() } else { db.fallback_for(c, face.id(), lang).unwrap_or_else(|| face.clone()) }; + let selected = + if face.covers(c) { face.clone() } else { db.fallback_for_styled(c, face.id(), lang, prefer_sans).unwrap_or_else(|| face.clone()) }; if let Some((_, end, previous)) = segments.last_mut().filter(|(_, _, previous)| previous.id() == selected.id()) { *end = at + c.len_utf8(); let _ = previous; @@ -1201,7 +1232,12 @@ fn shape_segment( for (gi, sg) in shaped.iter().enumerate() { let up = upright.get(gi).copied().unwrap_or(false); let (byte, len, ch) = if replacement.is_some() { - (range.start, if gi == 0 { range.len() } else { 0 }, text[range.start..].chars().next().unwrap_or(' ')) + let marker = text[range.start..].chars().next().unwrap_or(' '); + // A cross-reference's text is real text in InDesign: its spaces are word spaces the + // line may break at (text variables and page numbers stay whole). The first glyph + // keeps the marker, as it owns the marker's bytes. + let space = gi > 0 && marker == designcraft_doc::XREF_MARK && src.get(sg.cluster..).is_some_and(|t| t.starts_with(' ')); + (range.start, if gi == 0 { range.len() } else { 0 }, if space { ' ' } else { marker }) } else { let cl = range.start + sg.cluster; let end = shaped[gi + 1..].iter().map(|r| range.start + r.cluster).find(|&c| c > cl).unwrap_or(range.end); @@ -1421,3 +1457,89 @@ fn digit_mode(p: &designcraft_doc::CharProps, arabic_context: Option) -> d _ => Digits::Native, } } + +/// The stretches between `overlays`' boundaries, as `(start, overlay on top)` sorted by start: +/// a stretch runs to the next one's start, and the one on top is the last overlay covering it +/// (later ones win). One sweep over the boundaries; picking the top overlay by scanning them all +/// for each stretch was quadratic when a GREP style matched every character. +fn overlay_bands(overlays: &[(std::ops::Range, String)]) -> Vec<(usize, Option)> { + let mut starts: Vec<(usize, usize)> = Vec::new(); + let mut ends: Vec<(usize, usize)> = Vec::new(); + for (i, (r, _)) in overlays.iter().enumerate().filter(|(_, (r, _))| r.start < r.end) { + starts.push((r.start, i)); + ends.push((r.end, i)); + } + starts.sort_unstable(); + ends.sort_unstable(); + let mut cuts: Vec = starts.iter().chain(&ends).map(|x| x.0).collect(); + cuts.push(0); + cuts.sort_unstable(); + cuts.dedup(); + let mut active = std::collections::BTreeSet::new(); + let (mut s, mut e) = (0, 0); + let mut out = Vec::with_capacity(cuts.len()); + for at in cuts { + while e < ends.len() && ends[e].0 <= at { + active.remove(&ends[e].1); + e += 1; + } + while s < starts.len() && starts[s].0 <= at { + active.insert(starts[s].1); + s += 1; + } + out.push((at, active.last().copied())); + } + out +} + +#[cfg(test)] +mod tests { + use super::overlay_bands; + + /// The band sweep picks the same top overlay as checking every overlay at each boundary. + #[test] + fn overlay_bands_match_the_last_covering_overlay() { + let overlays: Vec<(std::ops::Range, String)> = [(2..9, "a"), (0..4, "b"), (4..4, "empty"), (3..6, "c"), (8..12, "d"), (5..7, "e")] + .into_iter() + .map(|(r, s)| (r, s.to_string())) + .collect(); + let bands = overlay_bands(&overlays); + for at in 0..14 { + let k = bands.partition_point(|(start, _)| *start <= at) - 1; + let want = overlays.iter().rposition(|(r, _)| r.start <= at && at < r.end); + assert_eq!(bands[k].1, want, "at {at}"); + } + } + + /// One overlay per character (a GREP style matching every character) sweeps in one pass. + #[test] + fn many_overlays_are_banded_quickly() { + let n = 200_000; + let overlays: Vec<(std::ops::Range, String)> = (0..n).map(|i| (i..i + 1, "s".to_string())).collect(); + let t = std::time::Instant::now(); + let bands = overlay_bands(&overlays); + assert_eq!(bands.len(), n + 1); + assert_eq!(bands[n / 2], (n / 2, Some(n / 2))); + assert!(t.elapsed().as_secs() < 5); + } +} + +#[cfg(test)] +mod style_of_substitute_tests { + use super::style_of_substitute; + + /// A face that stands in for a font that could not be resolved says nothing about the style + /// the document asked for. `FALLBACK_FAMILY` is "Source Sans 3" and `DEFAULT_FAMILY` is + /// "Source Serif 4", so reading their names would have forced the sans chain on every + /// unresolved family -- and the serif one on the other (#1692, noted in review). + #[test] + fn a_stand_in_face_says_nothing_about_the_requested_style() { + assert_eq!(style_of_substitute(designcraft_fonts::FALLBACK_FAMILY), None); + assert_eq!(style_of_substitute(designcraft_fonts::DEFAULT_FAMILY), None); + assert_eq!(style_of_substitute("source sans 3"), None, "however it is spelled"); + // A real substitute still speaks for itself. + assert_eq!(style_of_substitute("Malgun Gothic"), Some(true)); + assert_eq!(style_of_substitute("Batang"), Some(false)); + assert_eq!(style_of_substitute("Helvetica"), None, "a name that says neither"); + } +} diff --git a/crates/compose/src/table.rs b/crates/compose/src/table.rs index c620622a3..341a116b6 100644 --- a/crates/compose/src/table.rs +++ b/crates/compose/src/table.rs @@ -5,6 +5,7 @@ //! cell (or its fixed height); rows that don't fit continue in the next column / frame, repeating //! header (and footer) rows. Rows tied together by row spans never split. +use std::collections::HashMap; use std::sync::Arc; use designcraft_doc::{Align, Cell, CellStroke, Document, ItemId, ParaProps, RowHeightMode, Table, TextFrameOptions, VerticalJustification}; @@ -33,6 +34,10 @@ pub struct PlacedCell { pub repeated: bool, /// Graphic cell content (drawn at `clip`'s top left, clipped to it). pub graphic: Option, + /// The cell's diagonal lines (Cell Options › Diagonal Lines), corner to corner of `rect`. + pub diagonals: Vec, + /// Whether the diagonals are drawn over the cell's contents (otherwise under them). + pub diagonals_in_front: bool, } /// One cell edge (or the table border) to stroke. @@ -52,6 +57,9 @@ pub struct TableFrag { pub column: u32, pub rect: Rect, pub cells: Vec, + /// The table rows in the fragment, each with its top and bottom; repeated header and footer + /// rows are left out. + pub rows: Vec<(usize, f64, f64)>, pub strokes: Vec, /// Index of the fragment's (glyph-less) line in the frame's lines. pub line: usize, @@ -87,6 +95,14 @@ impl TableFrag { c.rect = c.rect + v; c.clip = c.clip + v; c.origin += v; + for s in &mut c.diagonals { + s.a += v; + s.b += v; + } + } + for r in &mut self.rows { + r.1 += dy; + r.2 += dy; } for s in &mut self.strokes { s.a += v; @@ -122,7 +138,7 @@ impl CellLineExtent { /// Compose a cell story at width `w` (content space, top-left at the origin). fn compose_cell(doc: &Document, cell: &Cell, w: f64, opts: &ComposeOptions, (left_page, right_page): (bool, bool)) -> CellLayout { - let spec = FrameSpec { + let mut spec = FrameSpec { id: ItemId(0), area: Rect::new(0.0, 0.0, w.max(1.0), 1.0e6), opts: TextFrameOptions { first_baseline: cell.first_baseline, first_baseline_min: cell.first_baseline_min, ..TextFrameOptions::default() }, @@ -132,12 +148,21 @@ fn compose_cell(doc: &Document, cell: &Cell, w: f64, opts: &ComposeOptions, (lef page_name: opts.page_name.clone(), section_marker: opts.section_marker.clone(), page: opts.page, + parent: false, grid: None, left_page, right_page, page_rect: None, }; - let cs = crate::compose(doc, &cell.text, std::slice::from_ref(&spec), opts); + let mut cs = crate::compose(doc, &cell.text, std::slice::from_ref(&spec), opts); + // The measuring frame is deliberately tall. Recompose at the actual content height so + // cell-local footnotes sit inside the row rather than at the measuring frame's bottom. + if let Some(frame) = cs.frames.first().filter(|f| !f.notes.is_empty()) { + let body = frame.lines.iter().map(|l| l.baseline + l.descent).fold(0.0, f64::max); + let note_top = frame.notes.first().map_or(spec.area.y1, |n| n.rect.y0); + spec.area.y1 = body + doc.footnote_options.space_before + (spec.area.y1 - note_top); + cs = crate::compose(doc, &cell.text, std::slice::from_ref(&spec), opts); + } let line_heights: Vec = cs .frames .first() @@ -157,7 +182,8 @@ fn compose_cell(doc: &Document, cell: &Cell, w: f64, opts: &ComposeOptions, (lef .unwrap_or_default(); // Check all lines: a large descender or lowered inline object on an earlier line can // extend below the final baseline when leading is fixed. - let content_h = line_heights.iter().copied().fold(0.0, f64::max); + let note_bottom = cs.frames.first().map_or(0.0, |f| f.notes.iter().map(|n| n.rect.y1).fold(0.0, f64::max)); + let content_h = line_heights.iter().copied().fold(note_bottom, f64::max); CellLayout { text: Arc::new(cs), content_h, line_heights } } @@ -174,6 +200,7 @@ pub(crate) fn place_table( cols: &[Vec], cur: &mut Cursor, out: &mut ComposedStory, + notes: &mut crate::notes::Notes, opts: &ComposeOptions, ) -> bool { if cur.fi >= frames.len() || table.nrows() == 0 || table.ncols() == 0 { @@ -292,6 +319,13 @@ pub(crate) fn place_table( } }; place_rows(0..header, &mut y, false, &mut frag_rows); + // Table rows do not add story footnotes; cell-local notes are composed separately. + let column_reserve = |notes: &mut crate::notes::Notes, cur: &Cursor, col: Rect| { + let note_w = notes.area(&cols[cur.fi], cur.col).map_or(col.width(), |a| a.width()); + let column = crate::notes::NoteColumn { frame_index: cur.fi, column_index: cur.col, width: note_w, frame: &frames[cur.fi] }; + notes.reserve(doc, column, &[], opts) + }; + let mut reserve = column_reserve(notes, cur, col); let mut r = header; loop { if r >= body_end { @@ -299,9 +333,10 @@ pub(crate) fn place_table( } let ge = group_end[r].min(body_end).max(r + 1); let gh = sum(r, ge); + let bottom = col.y1 - reserve; let at_col_top = cur.last_baseline.is_none() && (top - col.y0).abs() < 1e-6; - if y + gh + footer_h <= col.y1 + 0.01 || (body_placed == 0 && at_col_top) { - if y + gh + footer_h > col.y1 + 0.01 && body_placed == 0 && at_col_top && y + gh > col.y1 + 0.01 { + if y + gh + footer_h <= bottom + 0.01 || (body_placed == 0 && at_col_top && reserve == 0.0) { + if y + gh + footer_h > bottom + 0.01 && body_placed == 0 && at_col_top && y + gh > bottom + 0.01 { // A row group taller than an empty column can never fit. return false; } @@ -324,6 +359,7 @@ pub(crate) fn place_table( return false; } col = col_rect(cur); + reserve = column_reserve(notes, cur, col); y = col.y0; top = y; frag_rows.clear(); @@ -384,7 +420,13 @@ fn emit( out: &mut ComposedStory, ) { let nc = table.ncols(); - let ry = |r: usize| rows.iter().find(|x| x.0 == r).map(|x| x.1); + // Each row's top (its first occurrence in the fragment), indexed once: looking it up per cell + // by scanning the rows was quadratic in a fragment's row count. + let mut row_top: HashMap = HashMap::with_capacity(rows.len()); + for &(r, y, _) in rows { + row_top.entry(r).or_insert(y); + } + let ry = |r: usize| row_top.get(&r).copied(); let header = table.header_rows(); let body = table.body_rows(); let nbody = body.len(); @@ -440,6 +482,14 @@ fn emit( overset, repeated, graphic: cell.graphic.clone(), + diagonals: cell + .diagonal + .segments(rect) + .into_iter() + .filter(|_| cell.diagonal.stroke.is_visible()) + .map(|(a, b)| StrokeSeg { a, b, stroke: cell.diagonal.stroke.clone() }) + .collect(), + diagonals_in_front: cell.diagonal.in_front, }); } } @@ -473,6 +523,7 @@ fn emit( column: cur.col as u32, rect: Rect::new(x0, top, right, bottom), cells, + rows: rows.iter().filter(|r| !r.2).map(|&(r, y, _)| (r, y, y + heights[r])).collect(), strokes, line, first, diff --git a/crates/compose/src/table/border_tests.rs b/crates/compose/src/table/border_tests.rs index 5a28d7274..336b0803d 100644 --- a/crates/compose/src/table/border_tests.rs +++ b/crates/compose/src/table/border_tests.rs @@ -31,6 +31,42 @@ fn explicit_cell_edges_override_table_border_without_changing_native_defaults() assert_eq!(right.stroke.weight, 2.0, "unoverridden right edge keeps the table border"); } +#[test] +fn diagonal_lines_cross_the_placed_cell_corner_to_corner() { + let mut table = Table::new(77, 2, 2, 0, 0, 100.0); + let stroke = CellStroke { weight: 3.0, ..Default::default() }; + let cell = table.cell_mut(0, 0).unwrap(); + cell.col_span = 2; + cell.diagonal = designcraft_doc::CellDiagonal { lines: designcraft_doc::DiagonalLines::Crossed, stroke: stroke.clone(), in_front: false }; + table.cell_mut(1, 0).unwrap().diagonal.lines = designcraft_doc::DiagonalLines::TopLeft; + table.cell_mut(1, 0).unwrap().diagonal.stroke.color = designcraft_color::swatch::NONE.into(); + let composed = compose_table(table); + let fragment = &composed.frames[0].tables[0]; + let merged = fragment.cells.iter().find(|c| (c.row, c.col) == (0, 0)).unwrap(); + let r = merged.rect; + let ends: Vec<_> = merged.diagonals.iter().map(|s| (s.a, s.b)).collect(); + assert_eq!(ends, [(Point::new(r.x0, r.y0), Point::new(r.x1, r.y1)), (Point::new(r.x1, r.y0), Point::new(r.x0, r.y1))], "across the merged cell"); + assert!(merged.diagonals.iter().all(|s| s.stroke == stroke) && !merged.diagonals_in_front); + assert!(fragment.cells.iter().filter(|c| c.row == 1).all(|c| c.diagonals.is_empty()), "none, or an invisible stroke, draws nothing"); + assert!(fragment.strokes.iter().all(|s| s.a.x == s.b.x || s.a.y == s.b.y), "the edges stay edges"); +} + +#[test] +fn diagonal_lines_move_with_their_cell_in_a_bottom_justified_frame() { + let mut table = Table::new(77, 1, 1, 0, 0, 100.0); + table.cell_mut(0, 0).unwrap().diagonal.lines = designcraft_doc::DiagonalLines::TopLeft; + let mut doc = Document::new(&NewDocument::default()); + let layer = doc.default_layer(); + let (fid, sid) = doc.add_text_frame(SpreadRef::Doc(0), Rect::new(0.0, 0.0, 200.0, 300.0), layer, "", ParaFormat::default()).unwrap(); + doc.item_mut(fid).unwrap().text_frame_mut().unwrap().options.vertical_justification = VerticalJustification::Bottom; + doc.story_mut(sid).unwrap().insert_table(0, table); + let composed = crate::compose_story(&doc, sid, &ComposeOptions::default()); + let cell = &composed.frames[0].tables[0].cells[0]; + assert!(cell.rect.y0 > 100.0, "the table sits at the bottom: {:?}", cell.rect); + let s = &cell.diagonals[0]; + assert_eq!((s.a, s.b), (Point::new(cell.rect.x0, cell.rect.y0), Point::new(cell.rect.x1, cell.rect.y1))); +} + #[test] fn merged_cell_keeps_explicit_border_suppression() { let mut table = Table::new(77, 2, 2, 0, 0, 100.0); diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs index 3083261fb..f8cb4f3ce 100644 --- a/crates/compose/src/tests.rs +++ b/crates/compose/src/tests.rs @@ -46,6 +46,18 @@ fn all_lines(cs: &ComposedStory) -> Vec<&Line> { cs.frames.iter().flat_map(|f| f.lines.iter()).collect() } +/// A long run of soft hyphens composes: each one's hyphen width comes from the last other glyph, +/// kept as the breaker goes (it searched back over the whole run for every one). +#[test] +fn a_run_of_soft_hyphens_composes() { + let text = format!("Word{}end", "\u{AD}".repeat(3_900)); + let (d, sid, _) = doc_with(&text, Rect::new(36.0, 36.0, 300.0, 700.0), ParaAttrs::default()); + let t = std::time::Instant::now(); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + assert!(t.elapsed() < std::time::Duration::from_secs(20), "{:?}", t.elapsed()); + assert!(!all_lines(&cs).is_empty()); +} + #[test] fn composes_simple_paragraph() { let (d, sid, _) = doc_with(LOREM, Rect::new(36.0, 36.0, 300.0, 700.0), ParaAttrs::default()); @@ -501,6 +513,7 @@ fn hostile_wrap_geometry_terminates() { side: WrapSide::BothSides, contour: None, after: None, + anchor_baseline: None, }; let f = &mut specs[0]; f.exclusions.push(ex(f64::NAN, f64::NAN, f64::NAN, f64::NAN, WrapMode::JumpObject)); @@ -561,6 +574,498 @@ fn wrap_on_both_sides_sets_text_left_then_right_of_the_object() { assert!(!cs.is_overset()); } +/// A 60 × 200 pt frame at the origin holding `text` with vertical justification `vj`, and a bar +/// at `bar` whose text wrap `wrap` keeps 1 mm above it: (baseline, descent) of each line, the +/// text area and the wrap's top (None when the bar doesn't wrap the frame). +fn bar_chart_lines( + text: &str, + vj: designcraft_doc::VerticalJustification, + wrap: WrapMode, + side: WrapSide, + bar: Rect, +) -> (Vec<(f64, f64)>, Rect, Option) { + let (mut d, sid, fid) = doc_with(text, Rect::new(0.0, 0.0, 60.0, 200.0), ParaAttrs::default()); + d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.vertical_justification = vj; + let lid = d.default_layer(); + let id = ItemId(d.alloc()); + let mut it = designcraft_doc::Item::new(id, lid, designcraft_doc::Shape::Rectangle, designcraft_geom::shapes::rectangle(bar)); + it.wrap.mode = wrap; + it.wrap.side = side; + it.wrap.offsets = [72.0 / 25.4, 0.0, 0.0, 0.0]; + d.insert_item(SpreadRef::Doc(0), it, None).unwrap(); + let spec = frame_specs(&d, sid).remove(0); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + assert!(!cs.is_overset()); + let lines = all_lines(&cs).iter().map(|l| (l.baseline, l.descent)).collect(); + (lines, spec.area, spec.exclusions.first().map(|e| e.rect.y0)) +} + +/// Bottom, Center and Justify keep the lines out of a text wrap under them: a number aligned to +/// the bottom of its frame sits on the wrap's top offset over a bar instead of on the bar (#1831), +/// with every wrap mode that stops text there. +#[test] +fn vertical_justification_stops_at_a_wrap_under_the_text() { + use designcraft_doc::VerticalJustification::{Bottom, Center, Justify, Top}; + let bar = Rect::new(0.0, 150.0, 60.0, 300.0); + for wrap in [WrapMode::BoundingBox, WrapMode::Contour, WrapMode::JumpObject, WrapMode::JumpToNextColumn] { + let run = |vj, text| bar_chart_lines(text, vj, wrap, WrapSide::BothSides, bar); + let (top, _, wrap_top) = run(Top, "42"); + let wrap_top = wrap_top.unwrap(); + assert!((wrap_top - (150.0 - 72.0 / 25.4)).abs() < 1e-6, "{wrap:?}: the wrap's top is 1 mm above the bar: {wrap_top}"); + + let (bottom, _, _) = run(Bottom, "42"); + let b = bottom[0].0; + assert!((b - wrap_top).abs() < 1e-6, "{wrap:?}: Bottom put the baseline at {b}, not on the wrap's top at {wrap_top}"); + assert!(b > top[0].0 + 50.0, "{wrap:?}: Bottom moved the line down: {b}, {}", top[0].0); + + // Center takes half the room Bottom takes. + let (center, _, _) = run(Center, "42"); + assert!((center[0].0 - top[0].0 - (b - top[0].0) / 2.0).abs() < 1e-6, "{wrap:?}: Center at {}, Bottom at {b}", center[0].0); + + // Justify keeps the first baseline and puts the last where Bottom puts it. + let (top2, _, _) = run(Top, "12\n34"); + let (bottom2, _, _) = run(Bottom, "12\n34"); + let (justify, _, _) = run(Justify, "12\n34"); + assert_eq!(justify.len(), 2); + assert!((justify[0].0 - top2[0].0).abs() < 1e-6, "{wrap:?}: Justify moved the first line: {justify:?}"); + assert!((justify[1].0 - bottom2[1].0).abs() < 1e-6, "{wrap:?}: Justify {justify:?}, Bottom {bottom2:?}"); + assert!(justify[1].0 <= wrap_top + 1e-6); + } +} + +/// Without a wrap, or beside one, Bottom still moves the text down to the text area's bottom. +#[test] +fn vertical_justification_passes_wraps_that_do_not_stop_the_text() { + use designcraft_doc::VerticalJustification::Bottom; + // Wrap off: the number goes down over the bar. + let (lines, area, wrap_top) = bar_chart_lines("42", Bottom, WrapMode::None, WrapSide::BothSides, Rect::new(0.0, 150.0, 60.0, 300.0)); + assert!(wrap_top.is_none()); + assert!((lines[0].0 - area.y1).abs() < 1e-6, "{lines:?}, bottom {}", area.y1); + // A bar on the right half from the frame's top: the number is set beside it and goes down + // beside it. + let (lines, area, wrap_top) = bar_chart_lines("42", Bottom, WrapMode::BoundingBox, WrapSide::BothSides, Rect::new(30.0, 0.0, 60.0, 300.0)); + assert!(wrap_top.is_some()); + assert!((lines[0].0 - area.y1).abs() < 1e-6, "{lines:?}, bottom {}", area.y1); +} + +/// A one-sided wrap in the second column leaves the first column's lines free to go down, as it +/// leaves them when they are set. +#[test] +fn vertical_justification_passes_a_one_sided_wrap_in_another_column() { + let (mut d, sid, fid) = doc_with("One", Rect::new(0.0, 0.0, 400.0, 200.0), ParaAttrs::default()); + let o = &mut d.item_mut(fid).unwrap().text_frame_mut().unwrap().options; + o.columns = 2; + o.vertical_justification = designcraft_doc::VerticalJustification::Bottom; + let lid = d.default_layer(); + let mut it = designcraft_doc::Item::new( + ItemId(d.alloc()), + lid, + designcraft_doc::Shape::Rectangle, + designcraft_geom::shapes::rectangle(Rect::new(250.0, 100.0, 350.0, 300.0)), + ); + it.wrap.mode = WrapMode::BoundingBox; + it.wrap.side = WrapSide::RightSide; + d.insert_item(SpreadRef::Doc(0), it, None).unwrap(); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + let l = all_lines(&cs)[0]; + assert_eq!(l.column, 0); + assert!((l.baseline - 200.0).abs() < 1e-6, "baseline {}", l.baseline); +} + +/// Beside a contour that widens further down, Bottom moves a line only as far as its band stays +/// clear of the contour. +#[test] +fn vertical_justification_stops_where_a_contour_beside_the_text_widens() { + use designcraft_doc::VerticalJustification::{Bottom, Top}; + // Right edge fixed at 60, left edge x = 55 − 50y/190 from y = 0 down to y = 190. + let edge = |y: f64| 55.0 - 50.0 * y / 190.0; + let pts = [Point::new(55.0, 0.0), Point::new(60.0, 0.0), Point::new(60.0, 190.0), Point::new(5.0, 190.0)]; + let run = |vj| { + let (mut d, sid, fid) = doc_with("42", Rect::new(0.0, 0.0, 60.0, 200.0), ParaAttrs::default()); + d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.vertical_justification = vj; + let lid = d.default_layer(); + let path = designcraft_geom::path::PathData::single(designcraft_geom::path::SubPath::polyline(&pts, true)); + let mut it = designcraft_doc::Item::new(ItemId(d.alloc()), lid, designcraft_doc::Shape::Polygon, path); + it.wrap.mode = WrapMode::Contour; + it.wrap.side = WrapSide::BothSides; + d.insert_item(SpreadRef::Doc(0), it, None).unwrap(); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + assert!(!cs.is_overset()); + let l = all_lines(&cs)[0]; + (l.baseline, l.x1) + }; + let (top, x1) = run(Top); + assert!(x1 <= edge(top) + 1e-6, "Top sets the line clear of the contour: x1 {x1}, edge {}", edge(top)); + let (bottom, x1) = run(Bottom); + assert!(bottom >= top - 1e-6 && bottom < 190.0, "Bottom at {bottom}, Top at {top}"); + assert!(x1 <= edge(bottom) + 1e-6, "Bottom moved the line into the contour: baseline {bottom}, x1 {x1}, edge {}", edge(bottom)); +} + +/// Under a contour whose box starts beside the column and which widens into it further down, +/// Bottom moves a line down to where the contour meets its slot, not to the top of the box. +#[test] +fn vertical_justification_stops_where_a_contour_under_the_text_meets_it() { + // Left edge x = 70 − 40(y − 100)/90 from y = 100 down to y = 190: it crosses the column's + // right edge (60) at y = 122.5. + let pts = [Point::new(70.0, 100.0), Point::new(80.0, 100.0), Point::new(80.0, 190.0), Point::new(30.0, 190.0)]; + let (mut d, sid, fid) = doc_with("42", Rect::new(0.0, 0.0, 60.0, 200.0), ParaAttrs::default()); + d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.vertical_justification = designcraft_doc::VerticalJustification::Bottom; + let lid = d.default_layer(); + let path = designcraft_geom::path::PathData::single(designcraft_geom::path::SubPath::polyline(&pts, true)); + let mut it = designcraft_doc::Item::new(ItemId(d.alloc()), lid, designcraft_doc::Shape::Polygon, path); + it.wrap.mode = WrapMode::Contour; + it.wrap.side = WrapSide::BothSides; + d.insert_item(SpreadRef::Doc(0), it, None).unwrap(); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + assert!(!cs.is_overset()); + let b = all_lines(&cs)[0].baseline; + assert!(b <= 122.5 + 1e-6, "Bottom moved the baseline to {b}, past where the contour meets the column at 122.5"); + assert!(b > 122.0, "Bottom stopped the line at {b}, short of where the contour meets the column at 122.5"); +} + +/// A line set in the open middle of a U-shaped contour goes down between its arms: Bottom stops +/// it on the contour's base, not where the line starts because the arms span its slot. +#[test] +fn vertical_justification_moves_a_line_down_between_the_arms_of_a_contour() { + use designcraft_doc::VerticalJustification::{Bottom, Top}; + // Arms 0..15 and 45..60 from y = 0, joined by a base from y = 170 down to y = 190. + let pts = [ + Point::new(0.0, 0.0), + Point::new(15.0, 0.0), + Point::new(15.0, 170.0), + Point::new(45.0, 170.0), + Point::new(45.0, 0.0), + Point::new(60.0, 0.0), + Point::new(60.0, 190.0), + Point::new(0.0, 190.0), + ]; + let run = |vj| { + let (mut d, sid, fid) = doc_with("42", Rect::new(0.0, 0.0, 60.0, 200.0), ParaAttrs::default()); + d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.vertical_justification = vj; + let lid = d.default_layer(); + let path = designcraft_geom::path::PathData::single(designcraft_geom::path::SubPath::polyline(&pts, true)); + let mut it = designcraft_doc::Item::new(ItemId(d.alloc()), lid, designcraft_doc::Shape::Polygon, path); + it.wrap.mode = WrapMode::Contour; + it.wrap.side = WrapSide::BothSides; + d.insert_item(SpreadRef::Doc(0), it, None).unwrap(); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + assert!(!cs.is_overset()); + let l = all_lines(&cs)[0]; + (l.baseline, l.x0, l.x1) + }; + let (top, x0, x1) = run(Top); + assert!(x0 >= 15.0 - 1e-6 && x1 <= 45.0 + 1e-6, "Top sets the line between the arms: {x0}..{x1}"); + let (b, x0, x1) = run(Bottom); + assert!(x0 >= 15.0 - 1e-6 && x1 <= 45.0 + 1e-6, "Bottom keeps the line between the arms: {x0}..{x1}"); + assert!(b <= 170.0 + 1e-6, "Bottom moved the baseline to {b}, into the contour's base at 170"); + assert!(b > 169.9, "Bottom stopped the line at {b} (Top at {top}), short of the contour's base at 170"); +} + +/// An object anchored in the text and positioned from its anchor moves down with the lines, so +/// Center places lines above it as it places them without its wrap. +#[test] +fn vertical_justification_passes_an_anchored_object_that_moves_with_the_text() { + let baselines = |wrap| { + let (mut d, sid, fid) = doc_with("One\nTwo", Rect::new(0.0, 0.0, 300.0, 400.0), ParaAttrs::default()); + d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.vertical_justification = designcraft_doc::VerticalJustification::Center; + // Hung 40 pt under the first line's baseline, under the second line. + anchor_box(&mut d, sid, 1, 0.0, 40.0, true, wrap); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + all_lines(&cs).iter().map(|l| l.baseline).collect::>() + }; + let plain = baselines(WrapMode::None); + let wrapped = baselines(WrapMode::BoundingBox); + assert_eq!(plain.len(), 2); + assert!(plain[0] > 150.0, "Center moved the lines down: {plain:?}"); + assert_eq!(plain.len(), wrapped.len()); + assert!(plain.iter().zip(&wrapped).all(|(a, b)| (a - b).abs() < 1e-6), "without the wrap {plain:?}, with it {wrapped:?}"); +} + +/// Justify keeps the first line in place, so a wrap between it and the next line does not stop +/// the later lines from spreading down to the text area's bottom. +#[test] +fn vertical_justify_passes_a_wrap_under_the_first_line() { + let (mut d, sid, fid) = doc_with("One\nTwo\nSix", Rect::new(0.0, 0.0, 300.0, 400.0), ParaAttrs::default()); + d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.vertical_justification = designcraft_doc::VerticalJustification::Justify; + let lid = d.default_layer(); + let mut it = designcraft_doc::Item::new( + ItemId(d.alloc()), + lid, + designcraft_doc::Shape::Rectangle, + designcraft_geom::shapes::rectangle(Rect::new(0.0, 20.0, 300.0, 40.0)), + ); + it.wrap.mode = WrapMode::JumpObject; + d.insert_item(SpreadRef::Doc(0), it, None).unwrap(); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + let lines = all_lines(&cs); + assert_eq!(lines.len(), 3); + assert!( + lines[0].baseline < 20.0 && lines[1].baseline - lines[1].ascent >= 40.0 - 1e-6, + "{:?}", + lines.iter().map(|l| l.baseline).collect::>() + ); + let last = lines[2]; + assert!((last.baseline - 400.0).abs() < 1e-6, "{:?}", lines.iter().map(|l| l.baseline).collect::>()); +} + +/// Justify moves each row by its own share of the space, so a wrap between the second and third +/// rows limits the second row's move, not the third's. +#[test] +fn vertical_justify_limits_each_row_by_the_wrap_under_it() { + use designcraft_doc::VerticalJustification::{Justify, Top}; + let para = ParaAttrs { space_before: Some(40.0), ..Default::default() }; + let run = |vj, bar: Option| { + let (mut d, sid, fid) = doc_with("One\nTwo\nSix", Rect::new(0.0, 0.0, 300.0, 400.0), para.clone()); + d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.vertical_justification = vj; + if let Some(bar) = bar { + let lid = d.default_layer(); + let mut it = + designcraft_doc::Item::new(ItemId(d.alloc()), lid, designcraft_doc::Shape::Rectangle, designcraft_geom::shapes::rectangle(bar)); + it.wrap.mode = WrapMode::JumpObject; + d.insert_item(SpreadRef::Doc(0), it, None).unwrap(); + } + let cs = compose_story(&d, sid, &ComposeOptions::default()); + all_lines(&cs).iter().map(|l| (l.baseline, l.ascent, l.descent)).collect::>() + }; + let top = run(Top, None); + assert_eq!(top.len(), 3); + let b2 = top[1].0; + let (b3, a3, _) = top[2]; + // A bar 20 pt under the second baseline, clear of the third line. + let bar = Rect::new(0.0, b2 + 20.0, 300.0, b2 + 30.0); + assert!(b3 - a3 > bar.y1, "the third line starts under the bar: {top:?}"); + let set = run(Top, Some(bar)); + assert!(set.iter().zip(&top).all(|(a, b)| (a.0 - b.0).abs() < 1e-6), "the bar moves no line: {set:?}"); + let justify = run(Justify, Some(bar)); + assert!((justify[0].0 - top[0].0).abs() < 1e-6, "{justify:?}"); + // The second row's baseline comes down to the bar; the third row moves twice as far. + let moved = justify[1].0 - b2; + assert!((moved - 20.0).abs() < 1e-6, "the second row moved {moved}: {justify:?}"); + assert!((justify[2].0 - b3 - 2.0 * moved).abs() < 1e-6, "{justify:?}"); +} + +/// Each anchored object's own position decides whether its wrap moves with the text: a fixed +/// object without a wrap on the same line leaves the moving one skipped. +#[test] +fn vertical_justification_matches_each_wrap_to_its_anchored_object() { + let baselines = |wrap| { + let (mut d, sid, fid) = doc_with("One\nTwo", Rect::new(0.0, 0.0, 300.0, 400.0), ParaAttrs::default()); + d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.vertical_justification = designcraft_doc::VerticalJustification::Center; + // A fixed object from the frame's top, then one hung 40 pt under the first line. + anchor_box(&mut d, sid, 1, 150.0, 0.0, false, WrapMode::None); + anchor_box(&mut d, sid, 1 + OBJECT_LEN, 0.0, 40.0, true, wrap); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + assert_eq!(cs.frames[0].objects.len(), 2); + all_lines(&cs).iter().map(|l| l.baseline).collect::>() + }; + let plain = baselines(WrapMode::None); + let wrapped = baselines(WrapMode::BoundingBox); + assert!(plain[0] > 150.0, "Center moved the lines down: {plain:?}"); + assert_eq!(plain.len(), wrapped.len()); + assert!(plain.iter().zip(&wrapped).all(|(a, b)| (a - b).abs() < 1e-6), "without the wrap {plain:?}, with it {wrapped:?}"); +} + +/// An object positioned from its anchor but kept within its column can stop at the column's +/// bottom, so Bottom does not move the lines after its anchor into it. +#[test] +fn vertical_justification_stops_at_an_anchored_object_kept_within_its_column() { + let (mut d, sid, fid) = doc_with("One\nTwo", Rect::new(0.0, 0.0, 300.0, 400.0), ParaAttrs::default()); + d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.vertical_justification = designcraft_doc::VerticalJustification::Bottom; + anchor_box(&mut d, sid, 1, 0.0, 40.0, true, WrapMode::BoundingBox); + if let designcraft_doc::AnchorPosition::Custom { keep_within_column, .. } = + &mut std::sync::Arc::make_mut(&mut d.story_mut(sid).unwrap().objects[0]).position + { + *keep_within_column = true; + } + let cs = compose_story(&d, sid, &ComposeOptions::default()); + let lines = all_lines(&cs); + let o = &cs.frames[0].objects[0]; + let (top, bottom) = (o.origin.y, o.origin.y + 60.0); + assert!(bottom <= 400.0 + 1e-6, "the object stays in the column: {top}..{bottom}"); + let l = lines[1]; + assert!( + l.baseline <= top + 1e-6 || l.baseline - l.ascent >= bottom - 1e-6, + "the second line at {} meets the object at {top}..{bottom}", + l.baseline + ); +} + +/// An object positioned from its anchor and kept within its column moves with its anchor's line +/// until it reaches the column's bottom, so Bottom moves the lines above it down that far, not +/// only as far as where the object starts. +#[test] +fn vertical_justification_moves_an_object_kept_within_its_column_until_it_stops() { + use designcraft_doc::VerticalJustification::{Bottom, Center, Justify}; + for vj in [Bottom, Center, Justify] { + let (mut d, sid, fid) = doc_with("One\nTwo", Rect::new(0.0, 0.0, 300.0, 400.0), ParaAttrs::default()); + d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.vertical_justification = vj; + // Hung 40 pt under the first baseline, under the second line, and far above the column's + // bottom. + anchor_box(&mut d, sid, 1, 0.0, 40.0, true, WrapMode::BoundingBox); + if let designcraft_doc::AnchorPosition::Custom { keep_within_column, .. } = + &mut std::sync::Arc::make_mut(&mut d.story_mut(sid).unwrap().objects[0]).position + { + *keep_within_column = true; + } + let cs = compose_story(&d, sid, &ComposeOptions::default()); + let lines = all_lines(&cs); + let o = &cs.frames[0].objects[0]; + let (top, bottom) = (o.origin.y, o.origin.y + 60.0); + let l = lines[1]; + assert!(l.baseline <= top + 1e-6, "{vj:?}: the second line at {} meets the object at {top}..{bottom}", l.baseline); + match vj { + // The object stops at the column's bottom and the second line comes down onto it. + Bottom => { + assert!((bottom - 400.0).abs() < 1e-6, "{vj:?}: the object stopped at {top}..{bottom}, above the column's bottom"); + assert!(l.baseline > top - 0.01, "{vj:?}: the second line stopped at {}, above the object at {top}", l.baseline); + } + // Justify keeps the first line, and the object anchored in it, in place; the second + // line comes down onto the object. + Justify => { + assert!((top - lines[0].baseline - 40.0).abs() < 1e-6, "{vj:?}: the object moved to {top}..{bottom}"); + assert!(l.baseline > top - 0.01, "{vj:?}: the second line stopped at {}, above the object at {top}", l.baseline); + } + // Center moves the lines half of the room under them: the object moves with them. + _ => assert!(bottom < 400.0 - 1e-6 && l.baseline > 150.0, "{vj:?}: second line at {}, object at {top}..{bottom}", l.baseline), + } + } +} + +/// An object anchored in the first line, positioned from its anchor and kept within its column, +/// is held at the column's top. Justify keeps the first line in place, so the object stays there, +/// and the second line comes down onto the wider lower part of its contour. +#[test] +fn vertical_justify_keeps_the_room_under_an_object_held_at_the_columns_top() { + use designcraft_doc::anchored::AnchorRelative as R; + let (mut d, sid, fid) = doc_with("One\nTwo", Rect::new(0.0, 0.0, 300.0, 400.0), ParaAttrs::default()); + d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.vertical_justification = designcraft_doc::VerticalJustification::Justify; + // Beside the lines at x 250..300 down to y 100, then x 100..300 down to y 160. + let pts = [ + Point::new(150.0, 0.0), + Point::new(200.0, 0.0), + Point::new(200.0, 160.0), + Point::new(0.0, 160.0), + Point::new(0.0, 100.0), + Point::new(150.0, 100.0), + ]; + let lid = d.default_layer(); + let path = designcraft_geom::path::PathData::single(designcraft_geom::path::SubPath::polyline(&pts, true)); + let mut it = designcraft_doc::Item::new(ItemId(d.alloc()), lid, designcraft_doc::Shape::Polygon, path); + it.wrap.mode = WrapMode::Contour; + it.wrap.side = WrapSide::BothSides; + // 50 pt above the first baseline, so the column's top holds it. + let position = designcraft_doc::AnchorPosition::Custom { + x_relative: R::TextFrame, + y_relative: R::Anchor, + x_offset: 100.0, + y_offset: -50.0, + object_point: 0, + ref_point: 0, + keep_within_column: true, + spine_relative: false, + }; + d.story_mut(sid).unwrap().insert_object(1, designcraft_doc::AnchoredObject::new(it, position)); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + let lines = all_lines(&cs); + assert_eq!(lines.len(), 2); + let top = cs.frames[0].objects[0].origin.y; + assert!(lines[0].baseline < 50.0 && top.abs() < 1e-6, "the object is held at the column's top: {top}, {}", lines[0].baseline); + let wide = top + 100.0; + let b = lines[1].baseline; + assert!(b <= wide + 1e-6, "Justify moved the second line to {b}, into the contour's wider part at {wide}"); + assert!(b > wide - 0.01, "Justify stopped the second line at {b}, short of the contour's wider part at {wide}"); +} + +/// Justify keeps the first line in place and moves later lines further, so an object anchored in +/// the first line and hung under the last one still stops the lines after its anchor. +#[test] +fn vertical_justify_stops_at_an_object_anchored_above_the_lines_it_wraps() { + let (mut d, sid, fid) = doc_with("One\nTwo\nSix", Rect::new(0.0, 0.0, 300.0, 400.0), ParaAttrs::default()); + d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.vertical_justification = designcraft_doc::VerticalJustification::Justify; + anchor_box(&mut d, sid, 1, 0.0, 50.0, true, WrapMode::BoundingBox); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + let lines = all_lines(&cs); + assert_eq!(lines.len(), 3); + let top = cs.frames[0].objects[0].origin.y; + assert!((top - lines[0].baseline - 50.0).abs() < 1e-6, "the object hangs 50 pt under the first line: {top}, {}", lines[0].baseline); + let last = lines[2].baseline; + assert!(last <= top + 1e-6, "Justify moved the last line to {last}, into the object at {top}"); + assert!(last > lines[0].baseline + 40.0, "Justify spread the lines: {:?}", lines.iter().map(|l| l.baseline).collect::>()); +} + +/// Justify moves an object anchored in the second line with that line, so the third line spreads +/// down until it meets the object where it ends up, not where it started. +#[test] +fn vertical_justify_follows_an_object_anchored_in_a_later_line() { + let (mut d, sid, fid) = doc_with("One\nTwo\nSix", Rect::new(0.0, 0.0, 300.0, 400.0), ParaAttrs::default()); + d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.vertical_justification = designcraft_doc::VerticalJustification::Justify; + anchor_box(&mut d, sid, 5, 0.0, 40.0, true, WrapMode::BoundingBox); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + let lines = all_lines(&cs); + assert_eq!(lines.len(), 3); + let baselines = lines.iter().map(|l| l.baseline).collect::>(); + let top = cs.frames[0].objects[0].origin.y; + assert!((top - lines[1].baseline - 40.0).abs() < 1e-6, "the object hangs 40 pt under the second line: {top}, {baselines:?}"); + let last = lines[2].baseline; + assert!((top - last).abs() < 1e-6, "Justify moved the last line to {last}, not down to the object at {top}: {baselines:?}"); +} + +/// An Alpha Channel contour counts only where the graphic's clipping path shows the image: here +/// the visible pixels are in the right half and the clipping path shows the left half, so the +/// image wraps nothing; inverted, the clipping path shows the right half and the image wraps. +#[test] +fn an_alpha_channel_contour_stops_at_the_clipping_path() { + use designcraft_geom::{PathData, Point, SubPath}; + let rect = |x0: f64, x1: f64| { + PathData::single(SubPath::polyline(&[Point::new(x0, 0.0), Point::new(x1, 0.0), Point::new(x1, 200.0), Point::new(x0, 200.0)], true)) + }; + let lines_beside = |invert: bool| { + let (mut d, sid, _) = doc_with(&[LOREM; 4].join(" "), Rect::new(0.0, 0.0, 300.0, 800.0), ParaAttrs::default()); + let lid = d.default_layer(); + let asset = designcraft_doc::AssetId(d.alloc()); + let mut it = designcraft_doc::Item::new( + ItemId(d.alloc()), + lid, + designcraft_doc::Shape::Rectangle, + designcraft_geom::shapes::rectangle(Rect::new(150.0, 100.0, 300.0, 300.0)), + ); + let mut clip = designcraft_doc::ClippingPath::new(designcraft_doc::ClippingKind::DetectEdges, rect(0.0, 75.0)); + clip.invert = invert; + it.content = designcraft_doc::Content::Graphic(designcraft_doc::Graphic { + layer_options: None, + asset, + size: (150.0, 200.0), + xf: designcraft_geom::Affine::translate((150.0, 100.0)), + clip: Some(std::sync::Arc::new(clip)), + auto_fit: Default::default(), + fit_align: 0, + crop: [0.0; 4], + wrap: Default::default(), + fill: Default::default(), + }); + it.wrap.mode = WrapMode::Contour; + it.wrap.side = WrapSide::LeftSide; + it.wrap.contour = designcraft_doc::ContourType::AlphaChannel; + d.insert_item(SpreadRef::Doc(0), it, None).unwrap(); + d.alpha_outlines.push(std::sync::Arc::new(designcraft_doc::AlphaOutline { + asset, + threshold: designcraft_doc::DEFAULT_ALPHA_THRESHOLD, + width: 150, + height: 200, + outer: rect(75.0, 150.0), + holes: PathData::default(), + source: designcraft_doc::SourceKey(0), + serial: designcraft_doc::AlphaOutline::next_serial(), + })); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + cs.frames[0].lines.iter().filter(|l| l.baseline - l.ascent > 100.0 && l.baseline + l.descent < 300.0).map(|l| l.x1).collect::>() + }; + let shown_left = lines_beside(false); + assert!(!shown_left.is_empty() && shown_left.iter().all(|x| *x > 260.0), "nothing visible wraps nothing: {shown_left:?}"); + let shown_right = lines_beside(true); + assert!(!shown_right.is_empty() && shown_right.iter().all(|x| *x <= 225.0 + 1e-6), "the right half wraps: {shown_right:?}"); +} + /// Same As Clipping follows a placed graphic's clipping path: beside a triangle that widens /// downwards, text reaches further in at the narrow top than at the wide bottom. #[test] @@ -994,6 +1499,137 @@ fn hyphen_limit_is_a_hard_constraint() { } } +/// Each paragraph's own text decides, not the story's: a Korean document's English paragraphs +/// still hyphenate, and a mostly-English story's Korean paragraphs still do not (noted in review +/// of #1688). +#[test] +fn hyphenation_follows_each_paragraph_not_the_story() { + let rect = Rect::new(0.0, 0.0, 90.0, 100_000.0); + let para = ParaAttrs { align: Some(Align::LeftJustified), hyphenate: Some(true), ..Default::default() }; + // 이번 통지문은 아래와 같습니다 / an English paragraph that wants hyphenation + let korean = "\u{C774}\u{BC88} \u{D1B5}\u{C9C0}\u{BB38}\u{C740} \u{C544}\u{B798}\u{C640} \u{AC19}\u{C2B5}\u{B2C8}\u{B2E4}"; + let english = "This notice about hyphenation and composition continues for a while in English"; + let hyphens = |text: &str| { + let (d, sid, _) = doc_with(text, rect, para.clone()); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + let lines = all_lines(&cs); + // Which paragraph each hyphenated line belongs to: the Korean one is first. + lines.iter().filter(|l| l.hyphenated).count() + }; + // The English paragraph in a Korean document still hyphenates: the story is mostly Hangul, + // but that paragraph is not. + let mixed = format!("{korean}\n{english}"); + assert!(hyphens(&mixed) > 0, "the English paragraph of a Korean document still hyphenates"); + // And the Korean paragraph alone invents none. + assert_eq!(hyphens(korean), 0, "a Korean paragraph invents no hyphens"); +} + +/// The paragraph's *glyphs* decide, not its source text: hidden conditional text is not set, so +/// it does not get a vote. Reading the source let hidden Korean turn hyphenation off for the +/// visible English around it (noted in review of #1688). +#[test] +fn hidden_text_does_not_decide_whether_a_paragraph_hyphenates() { + let rect = Rect::new(0.0, 0.0, 90.0, 100_000.0); + let para = ParaAttrs { align: Some(Align::LeftJustified), hyphenate: Some(true), ..Default::default() }; + // 이번 통지문은 아래와 같습니다 — repeated, so the Hangul outweighs the English after it + // (`mostly_hangul` wants at least as many Hangul characters as ASCII letters). + let korean = "\u{C774}\u{BC88} \u{D1B5}\u{C9C0}\u{BB38}\u{C740} \u{C544}\u{B798}\u{C640} \u{AC19}\u{C2B5}\u{B2C8}\u{B2E4} ".repeat(6); + let english = "This notice about hyphenation and composition continues for a while in English"; + let text = format!("{korean}{english}"); + + let hyphens = |hide: bool| { + let (mut d, sid, _) = doc_with(&text, rect, para.clone()); + d.conditions.push(designcraft_doc::Condition { name: "Draft".into(), color: [255, 0, 0], visible: !hide }); + let story = d.story_mut(sid).expect("the story is there"); + let chars = designcraft_doc::CharAttrs { conditions: Some(vec!["Draft".into()]), ..Default::default() }; + story.chars = vec![ + designcraft_doc::CharRun { len: korean.len(), format: designcraft_doc::CharFormat { over: chars, ..Default::default() } }, + designcraft_doc::CharRun { len: english.len(), format: designcraft_doc::CharFormat::default() }, + ]; + let cs = compose_story(&d, sid, &ComposeOptions::default()); + all_lines(&cs).iter().filter(|l| l.hyphenated).count() + }; + + // Shown, the Hangul outweighs the English and the paragraph is not hyphenated. + assert_eq!(hyphens(false), 0, "a visibly Korean paragraph invents no hyphens"); + // Hidden, the only text set is English, and it hyphenates like any English paragraph. + assert!(hyphens(true) > 0, "hidden Korean does not turn hyphenation off for the visible English"); +} + +/// `split_drop_cap` takes the drop cap's glyphs out of the vector, so classifying the paragraph +/// after it ran lost that character's vote: with the Hangul and Latin counts level, dropping one +/// Hangul character made the paragraph read as Latin and its English words took automatic hyphens +/// (noted in review). The classification is made before the split. +#[test] +fn a_drop_cap_still_counts_when_a_paragraph_is_judged_korean() { + let rect = Rect::new(0.0, 0.0, 90.0, 100_000.0); + // English long enough that it really does hyphenate in a 90 pt column -- the run + // `hidden_text_does_not_decide_whether_a_paragraph_hyphenates` uses for the same reason. A + // short run leaves no hyphens whichever way the paragraph is classified, so the test would + // pass without testing anything (measured: it did). + let english = "This notice about hyphenation and composition continues for a while in English"; + let letters = english.chars().filter(char::is_ascii_alphabetic).count(); + // One Hangul syllable per Latin letter, so the counts are level -- which `hangul >= latin` + // calls Korean, and one character either way decides it. + let korean: String = "\u{AC00}\u{B098}\u{B2E4}\u{B77C}\u{B9C8}".chars().cycle().take(letters).collect(); + assert_eq!(korean.chars().count(), letters, "the two counts are level at {letters}"); + let text = format!("{korean} {english}"); + + let hyphens = |para: ParaAttrs| { + let (d, sid, _) = doc_with(&text, rect, para); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + all_lines(&cs).iter().filter(|l| l.hyphenated).count() + }; + let base = ParaAttrs { align: Some(Align::LeftJustified), hyphenate: Some(true), ..Default::default() }; + + // Level counts read as Korean, so nothing hyphenates. + assert_eq!(hyphens(base.clone()), 0, "level counts read as Korean"); + // The paragraph opens on a Hangul character, so that character is the drop cap. It is still + // set, just larger, so the answer must not change. + let with_cap = ParaAttrs { drop_cap_lines: Some(2), drop_cap_chars: Some(1), ..base.clone() }; + assert_eq!(hyphens(with_cap), 0, "a drop cap does not turn the paragraph Latin"); + + // And the fixture really is poised on the boundary: one Latin letter more and the English + // hyphenates, so the assertions above are not passing for want of any hyphen at all. + let tipped = format!("{korean} {english}x"); + let (d, sid, _) = doc_with(&tipped, rect, base); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + assert!(all_lines(&cs).iter().any(|l| l.hyphenated), "one more Latin letter tips it and hyphens appear"); +} + +/// A Korean notice leaves its paragraphs at the default English language, so English +/// hyphenation broke the Latin words Korean particles attach to and the addresses such a document +/// is full of: `New-` / `s와`, `library.exam-` / `ple.kr` (#1688). The lines may now be looser -- +/// that is the cost of not hyphenating, and what #1691 is about -- but no hyphen is invented +/// inside those tokens. +#[test] +fn korean_text_and_addresses_are_not_hyphenated() { + // Narrow enough that every line has to break somewhere. + let rect = Rect::new(0.0, 0.0, 90.0, 100_000.0); + let para = ParaAttrs { align: Some(Align::LeftJustified), hyphenate: Some(true), ..Default::default() }; + let hyphens_in = |text: &str| { + let (d, sid, _) = doc_with(text, rect, para.clone()); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + all_lines(&cs).iter().filter(|l| l.hyphenated).count() + }; + + // 이번 통지문은 News와 관련된 library.example.kr 주소를 포함합니다 + let korean = "\u{C774}\u{BC88} \u{D1B5}\u{C9C0}\u{BB38}\u{C740} News\u{C640} \u{AD00}\u{B828}\u{B41C} library.example.kr \u{C8FC}\u{C18C}\u{B97C} \u{D3EC}\u{D568}\u{D569}\u{B2C8}\u{B2E4}"; + assert_eq!(hyphens_in(korean), 0, "a Korean paragraph invents no hyphens"); + + // An English paragraph holding the same address: the prose still hyphenates, the address does + // not, so the protection is about the token and not about turning hyphenation off. + let english = "This notice about hyphenation and composition mentions library.example.kr somewhere inside a long sentence"; + assert!(hyphens_in(english) > 0, "English prose is still hyphenated"); + let (d, sid, _) = doc_with(english, rect, para.clone()); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + for l in all_lines(&cs).iter().filter(|l| l.hyphenated) { + let upto = &english[..l.range.end.min(english.len())]; + let token = upto.rsplit(char::is_whitespace).next().unwrap_or(""); + assert!(!"library.example.kr".starts_with(token) || token.is_empty(), "a hyphen was invented inside the address: {token:?}"); + } +} + #[test] fn hyphenation_zone_limits_ragged_hyphens() { let text = CORPUS.join(" "); @@ -1103,21 +1739,95 @@ fn hyphenate_across_column_off_keeps_nested_line_styles_on_their_lines() { } #[test] -fn discretionary_hyphen_replaces_automatic_points() { - let text = "aaaa bbbb cccc extraordi\u{AD}narily dddd eeee"; - let para = ParaAttrs { align: Some(Align::Left), ..Default::default() }; - let (d, sid, _) = doc_with(text, Rect::new(0.0, 0.0, 120.0, 1000.0), para); - let cs = compose_story(&d, sid, &ComposeOptions::default()); - let soft = text.find('\u{AD}').unwrap(); - for l in all_lines(&cs) { - if l.hyphenated { - let last = l.glyphs.iter().rfind(|g| g.len > 0).unwrap(); - assert!(last.byte + last.len >= soft && last.byte <= soft + 2, "{:?}", &text[l.range.clone()]); +fn discretionary_hyphen_breaks_with_both_composers_and_hyphenation_settings() { + let text = "Wir möchten uns ganz besonders herzlich bei folgenden Personen bedanken, die auf unterschied\u{ad}lichste Weise zur Entstehung dieses Lehrbuches beigetragen haben:"; + let soft_end = text.find('\u{ad}').unwrap() + '\u{ad}'.len_utf8(); + for composer in [Composer::SingleLine, Composer::Paragraph] { + for hyphenate in [false, true] { + let para = ParaAttrs { composer: Some(composer), hyphenate: Some(hyphenate), ..Default::default() }; + let (mut d, sid, _) = doc_with(text, Rect::new(0.0, 0.0, 430.0, 1000.0), para); + d.story_mut(sid).unwrap().format_chars(0..text.len(), |f| f.over.size = Some(9.5)); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + let first = all_lines(&cs)[0]; + assert_eq!(first.range.end, soft_end, "{composer:?}, hyphenate={hyphenate}: {:?}", &text[first.range.clone()]); + assert!(first.hyphenated); + let hyphen = first.glyphs.last().unwrap(); + assert!(hyphen.visible && hyphen.len == 0 && hyphen.adv > 0.0); } } - // Hyphenation points of the word itself: none besides the discretionary one. - let lines = all_lines(&cs); - assert!(lines.iter().filter(|l| l.hyphenated).count() <= 1); +} + +#[test] +fn discretionary_hyphen_before_cjk_single_line() { + discretionary_hyphen_before_cjk(Composer::SingleLine); +} + +#[test] +fn discretionary_hyphen_before_cjk_paragraph() { + discretionary_hyphen_before_cjk(Composer::Paragraph); +} + +fn discretionary_hyphen_before_cjk(composer: Composer) { + let text = "abc\u{ad}\u{65e5}\u{672c}\u{8a9e}\u{65e5}\u{672c}\u{8a9e}"; + let soft_end = text.find('\u{ad}').unwrap() + '\u{ad}'.len_utf8(); + for hyphenate in [false, true] { + let para = ParaAttrs { composer: Some(composer), hyphenate: Some(hyphenate), ..Default::default() }; + let (d, sid, _) = doc_with(text, Rect::new(0.0, 0.0, 24.0, 1000.0), para); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + let first = all_lines(&cs)[0]; + assert_eq!(first.range.end, soft_end, "{composer:?}, hyphenate={hyphenate}: {:?}", &text[first.range.clone()]); + assert!(first.hyphenated, "{composer:?}, hyphenate={hyphenate}"); + let hyphen = first.glyphs.last().unwrap(); + assert!(hyphen.visible && hyphen.len == 0 && hyphen.adv > 0.0); + } +} + +#[test] +fn discretionary_hyphen_is_invisible_and_zero_width_when_unbroken() { + for composer in [Composer::SingleLine, Composer::Paragraph] { + let mut widths = Vec::new(); + for text in ["unterschiedlichste", "unterschied\u{ad}lichste"] { + let (d, sid, _) = doc_with(text, Rect::new(0.0, 0.0, 1000.0, 100.0), ParaAttrs { composer: Some(composer), ..Default::default() }); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + let lines = all_lines(&cs); + assert_eq!(lines.len(), 1); + assert!(!lines[0].hyphenated); + if let Some(soft) = text.find('\u{ad}') { + let glyph = lines[0].glyphs.iter().find(|g| g.byte == soft).unwrap(); + assert!(!glyph.visible && glyph.adv == 0.0); + } + widths.push(lines[0].end_x); + } + assert!((widths[0] - widths[1]).abs() < 1e-6, "{composer:?}: {widths:?}"); + } +} + +#[test] +fn discretionary_hyphen_replaces_automatic_points() { + let text = "aaaa bbbb cccc extraordi\u{AD}narily dddd eeee"; + let soft = text.find('\u{AD}').unwrap(); + for composer in [Composer::SingleLine, Composer::Paragraph] { + let mut discretionary_breaks = 0; + let mut automatic_breaks = 0; + for width in (90..181).step_by(10) { + for discretionary in [false, true] { + let source = if discretionary { text.to_string() } else { text.replace('\u{AD}', "") }; + let para = ParaAttrs { composer: Some(composer), hyphenate: Some(true), align: Some(Align::Left), ..Default::default() }; + let (d, sid, _) = doc_with(&source, Rect::new(0.0, 0.0, f64::from(width), 1000.0), para); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + for l in all_lines(&cs).into_iter().filter(|l| l.hyphenated) { + if discretionary { + assert_eq!(l.range.end, soft + '\u{AD}'.len_utf8(), "{composer:?}: {:?}", &source[l.range.clone()]); + discretionary_breaks += 1; + } else { + automatic_breaks += 1; + } + } + } + } + assert!(discretionary_breaks > 0, "{composer:?}: discretionary breaks exercised"); + assert!(automatic_breaks > 0, "{composer:?}: pattern breaks exercised without U+00AD"); + } } #[test] @@ -1832,6 +2542,141 @@ fn tab_leaders_fill_the_gap() { assert!(last_dot < num_x, "leaders stop before the page number"); } +#[test] +fn indent_to_here_starts_the_paragraphs_later_lines_at_the_character() { + // "1.", Indent to Here, then text long enough to wrap: every line after the first starts + // where the character sits, in this frame and the next one (#2080). + let text = format!("1.\u{e005}{}", [LOREM; 3].join(" ")); + let para = ParaAttrs { left_indent: Some(6.0), ..Default::default() }; + let (mut d, sid, a) = doc_with(&text, Rect::new(72.0, 36.0, 272.0, 96.0), para.clone()); + let lid = d.default_layer(); + let (b, _) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(72.0, 200.0, 272.0, 800.0), lid, "", ParaFormat::default()).unwrap(); + d.thread(a, b).unwrap(); + let cs = compose_story(&d, sid, &Default::default()); + assert!(!cs.is_overset()); + assert!(cs.frames[0].lines.len() > 1 && !cs.frames[1].lines.is_empty(), "the text wraps into the second frame"); + let lines = all_lines(&cs); + let here = lines[0].glyphs.iter().find(|g| g.byte == 2 && g.len > 0).unwrap().x; + assert!(here > 72.0 + 6.0 + 1.0, "the character follows the number"); + for (i, line) in lines.iter().enumerate().skip(1) { + let start = line.glyphs.iter().find(|g| g.visible).unwrap().x; + assert!((start - here).abs() < 0.01, "line {i} starts at {start}, not at the indent {here}"); + assert!(line.end_x <= 272.0 + 0.01, "line {i} fits the narrower measure"); + } + // Without the character the later lines keep the paragraph's own indent. + let (plain, psid, _) = doc_with(&text.replace('\u{e005}', " "), Rect::new(72.0, 36.0, 272.0, 400.0), para); + let pcs = compose_story(&plain, psid, &Default::default()); + let start = pcs.frames[0].lines[1].glyphs.iter().find(|g| g.visible).unwrap().x; + assert!((start - 78.0).abs() < 0.01, "plain second line starts at {start}"); +} + +/// Where each line after the first starts, and the Indent to Here character's x on the first. +fn indent_to_here_starts(text: &str, para: ParaAttrs) -> (f64, Vec) { + let (d, sid, _) = doc_with(text, Rect::new(72.0, 36.0, 272.0, 600.0), para); + let cs = compose_story(&d, sid, &Default::default()); + let lines = all_lines(&cs); + assert!(lines.len() > 4, "the text wraps"); + let byte = text.find('\u{e005}').unwrap(); + let here = lines[0].glyphs.iter().find(|g| g.byte == byte && g.len > 0).unwrap().x; + let starts = lines.iter().skip(1).map(|l| l.glyphs.iter().find(|g| g.visible).unwrap().x).collect(); + (here, starts) +} + +#[test] +fn indent_to_here_after_a_tab_hangs_the_text_after_the_number() { + // The usual hanging number: "1.", a tab to the next stop, then Indent to Here. + let tabs = vec![designcraft_doc::TabStop { position: 24.0, align: TabAlign::Left, leader: String::new(), align_on: String::new() }]; + let (here, starts) = indent_to_here_starts(&format!("1.\t\u{e005}{LOREM}"), ParaAttrs { tabs: Some(tabs), ..Default::default() }); + assert!((here - (72.0 + 24.0)).abs() < 0.01, "the character sits at the tab stop: {here}"); + for (i, start) in starts.iter().enumerate() { + assert!((start - here).abs() < 0.01, "line {} starts at {start}, not at {here}", i + 1); + } +} + +#[test] +fn indent_to_here_beside_a_drop_cap_is_not_indented_by_the_drop_cap_again() { + // A three-line drop cap, then Indent to Here on the first line: the lines beside the drop + // cap and the lines below it all start at the character, none further in. + let (here, starts) = indent_to_here_starts(&format!("Drop \u{e005}{LOREM}"), drop_cap(3, 1)); + for (i, start) in starts.iter().enumerate() { + assert!((start - here).abs() < 0.01, "line {} starts at {start}, not at {here}", i + 1); + } +} + +#[test] +fn indent_to_here_inside_the_drop_cap_indents_the_lines_below_it() { + // A two-character drop cap whose second character is Indent to Here: the lines beside the + // drop cap and the ones below it all start at the character, at the drop cap's edge. + let (here, starts) = indent_to_here_starts(&format!("A\u{e005}{LOREM}"), drop_cap(3, 2)); + assert!(here > 72.0 + 10.0, "the character sits past the drop cap: {here}"); + assert!(starts.len() > 3, "lines below the drop cap"); + for (i, start) in starts.iter().enumerate() { + assert!((start - here).abs() < 0.01, "line {} starts at {start}, not at {here}", i + 1); + } +} + +#[test] +fn indent_to_here_in_a_list_number_indents_to_the_generated_character() { + // "^#.^i^t": the paragraph's later lines start where the number's Indent to Here sits, + // right after "1.", not at the text after the tab. + let mut para = numbered(designcraft_doc::NumberStyle::Arabic, "^#.^i^t"); + para.list_tab = Some(Some(36.0)); + let (d, sid, _) = doc_with(LOREM, Rect::new(72.0, 36.0, 272.0, 600.0), para); + let cs = compose_story(&d, sid, &Default::default()); + let lines = all_lines(&cs); + assert!(lines.len() > 3, "the text wraps"); + let label = |c: char| lines[0].glyphs.iter().find(|g| g.len == 0 && g.rendered_char == c).unwrap(); + let (dot, here) = (label('.'), label('\u{e005}').x); + assert!((here - (dot.x + dot.adv)).abs() < 0.01, "the character follows the number: {here}"); + let text = lines[0].glyphs.iter().find(|g| g.len > 0).unwrap().x; + assert!((text - (72.0 + 36.0)).abs() < 0.01 && here < text - 1.0, "the text after the tab is further in: {text}"); + for (i, line) in lines.iter().enumerate().skip(1) { + let start = line.glyphs.iter().find(|g| g.visible).unwrap().x; + assert!((start - here).abs() < 0.01, "line {i} starts at {start}, not at {here}"); + } +} + +#[test] +fn indent_to_here_in_a_list_number_after_one_in_the_drop_cap_wins() { + // The drop cap "A^i" sits at the indent and the number "1.^i" follows it on the first line, + // so the number's character is the line's last one: the later lines start there, not at + // the drop cap's. + let mut para = ParaAttrs { drop_cap_lines: Some(3), drop_cap_chars: Some(2), ..numbered(designcraft_doc::NumberStyle::Arabic, "^#.^i^t") }; + para.list_tab = Some(Some(36.0)); + let (d, sid, _) = doc_with(&format!("A\u{e005}{LOREM}"), Rect::new(72.0, 36.0, 272.0, 600.0), para); + let cs = compose_story(&d, sid, &Default::default()); + let lines = all_lines(&cs); + assert!(lines.len() > 4, "the text wraps below the drop cap"); + let marker = |label: bool| lines[0].glyphs.iter().find(|g| g.rendered_char == '\u{e005}' && (g.len == 0) == label).unwrap().x; + let (in_cap, in_label) = (marker(false), marker(true)); + assert!(in_label > in_cap + 1.0, "the number follows the drop cap: {in_cap} then {in_label}"); + for (i, line) in lines.iter().enumerate().skip(1) { + let start = line.glyphs.iter().find(|g| g.visible).unwrap().x; + assert!((start - in_label).abs() < 0.01, "line {i} starts at {start}, not at {in_label}"); + } +} + +#[test] +fn indent_to_here_in_a_right_to_left_paragraph_indents_from_the_right() { + // Hebrew words (the bidi classes decide the order; no Hebrew font has to be present): the + // lines after the first end where the character sits, measured from the right edge. + let words = "שלום עולם ".repeat(40); + let text = format!("שלום \u{e005}{words}"); + let para = ParaAttrs { direction: Some(designcraft_doc::TextDirection::RightToLeft), align: Some(Align::Right), ..Default::default() }; + let (d, sid, _) = doc_with(&text, Rect::new(72.0, 36.0, 272.0, 600.0), para); + let cs = compose_story(&d, sid, &Default::default()); + let lines = all_lines(&cs); + assert!(lines.len() > 3, "the text wraps"); + let byte = text.find('\u{e005}').unwrap(); + let here = lines[0].glyphs.iter().find(|g| g.byte == byte && g.len > 0).unwrap().x; + assert!(here < 272.0 - 1.0, "the character follows the first word: {here}"); + let right_edge = |l: &Line| l.glyphs.iter().filter(|g| g.visible).map(|g| g.x + g.adv).fold(f64::MIN, f64::max); + for (i, line) in lines.iter().enumerate().skip(1) { + let end = right_edge(line); + assert!((end - here).abs() < 0.01, "line {i} ends at {end}, not at {here}"); + } +} + #[test] fn right_indent_tab_leaders_follow_stop_precedence_without_moving_text() { let text = "Intro\u{e006}12"; @@ -1994,6 +2839,700 @@ fn footnotes_sit_at_the_column_bottom_and_push_text() { assert!(note_caret(&cs, n.id, 0).is_some()); } +fn justified_content_clears_footnotes(mode: designcraft_doc::VerticalJustification, table: bool) { + for span in [false, true] { + let (mut d, sid, fid) = doc_with("First paragraph.\nSecond paragraph.", Rect::new(0.0, 0.0, 420.0, 240.0), ParaAttrs::default()); + d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.columns = 2; + d.footnote_options.span_columns = span; + d.footnote_options.space_before = 60.0; + let st = d.story_mut(sid).unwrap(); + st.insert_note(5, "Synthetic footnote.", ParaFormat::default()); + if table { + let mut t = designcraft_doc::Table::new(77, 1, 1, 0, 0, 180.0); + t.rows[0].mode = designcraft_doc::RowHeightMode::Exactly; + t.rows[0].height = 90.0; + st.insert_table(st.len(), t); + } + let top = compose_story(&d, sid, &ComposeOptions::default()); + d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.vertical_justification = mode; + + let cs = compose_story(&d, sid, &ComposeOptions::default()); + + assert!(!cs.is_overset()); + let ft = cs.frame(fid).unwrap(); + let original = top.frame(fid).unwrap(); + assert_eq!(ft.notes.len(), 1); + assert_eq!(ft.notes[0].rect, original.notes[0].rect, "footnotes must not move"); + let limit = ft.notes[0].rect.y0 - d.footnote_options.space_before; + assert!(ft.lines.iter().all(|l| l.baseline + l.descent <= limit + 0.01), "lines overlap footnotes in {mode:?}, span {span}"); + assert!(ft.tables.iter().flat_map(|t| &t.cells).all(|c| c.rect.y1 <= limit + 0.01), "cells overlap footnotes in {mode:?}, span {span}"); + assert!(ft.lines.last().unwrap().baseline > original.lines.last().unwrap().baseline + 0.01, "content must still move down"); + if table { + assert_eq!(ft.tables.len(), 1); + assert!(ft.tables[0].rect.y1 > original.tables[0].rect.y1 + 0.01, "table must still move down"); + } + } +} + +#[test] +fn bottom_justified_paragraphs_clear_footnotes() { + justified_content_clears_footnotes(designcraft_doc::VerticalJustification::Bottom, false); +} + +#[test] +fn bottom_justified_tables_clear_footnotes() { + justified_content_clears_footnotes(designcraft_doc::VerticalJustification::Bottom, true); +} + +#[test] +fn center_justified_tables_clear_footnotes() { + justified_content_clears_footnotes(designcraft_doc::VerticalJustification::Center, true); +} + +#[test] +fn vertically_justified_tables_clear_footnotes() { + justified_content_clears_footnotes(designcraft_doc::VerticalJustification::Justify, true); +} + +#[test] +fn vertical_justification_counts_table_fragment_bottoms() { + use designcraft_doc::VerticalJustification::{Bottom, Center, Justify}; + let (mut d, sid, fid) = doc_with("Reference.", Rect::new(0.0, 0.0, 200.0, 240.0), ParaAttrs::default()); + let st = d.story_mut(sid).unwrap(); + st.insert_note(5, "Synthetic footnote.", ParaFormat::default()); + let mut table = designcraft_doc::Table::new(77, 1, 1, 0, 0, 180.0); + table.rows[0].mode = designcraft_doc::RowHeightMode::Exactly; + table.rows[0].height = 120.0; + st.insert_table(st.len(), table); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + for mode in [Bottom, Center, Justify] { + let mut ft = cs.frame(fid).unwrap().clone(); + let t = &ft.tables[0]; + let (anchor, bottom, baseline) = (t.line, t.rect.y1, t.rect.y0); + // Exercise a fragment extending below its anchor, without a later text line hiding it. + ft.lines.truncate(anchor + 1); + ft.lines[anchor].baseline = baseline; + let mut spec = frame_specs(&d, sid).remove(0); + spec.opts.vertical_justification = mode; + + vertical_justify(&mut ft, &spec, false, &d.footnote_options, &[], &[]); + + let moved = ft.lines[anchor].baseline - baseline; + let limit = ft.notes[0].rect.y0 - d.footnote_options.space_before; + assert!(moved > 0.01); + assert!(bottom + moved <= limit + 0.01, "fragment overlaps footnotes in {mode:?}"); + } +} + +/// Center, Bottom and Justify place the text between its first baseline (where Top sets it) and +/// its last baseline: Bottom and Justify put the last baseline on the bottom inset, and Center +/// leaves as much room under the last baseline as above the first line (#1999). +#[test] +fn vertical_justification_measures_to_the_last_baseline() { + use designcraft_doc::VerticalJustification::{self, Bottom, Center, Justify, Top}; + let compose_inset = |mode: VerticalJustification, first: FirstBaseline, bottom_inset: f64| { + let (mut d, sid, fid) = doc_with("Typography\ngypsy", Rect::new(0.0, 0.0, 200.0, 300.0), ParaAttrs::default()); + let o = &mut d.item_mut(fid).unwrap().text_frame_mut().unwrap().options; + o.vertical_justification = mode; + o.first_baseline = first; + o.inset = [6.0, 6.0, bottom_inset, 6.0]; + let area = frame_specs(&d, sid)[0].area; + let cs = compose_story(&d, sid, &ComposeOptions::default()); + (area, all_lines(&cs).iter().map(|l| (l.baseline, l.descent)).collect::>()) + }; + let compose_with = |mode, first| compose_inset(mode, first, 9.0); + for first in [FirstBaseline::Ascent, FirstBaseline::CapHeight] { + let (area, top) = compose_with(Top, first); + assert!((area.y1 - 291.0).abs() < 1e-9, "the bottom inset bounds the text area: {area:?}"); + assert_eq!(top.len(), 2); + let last = |v: &[(f64, f64)]| v[v.len() - 1]; + + let (_, bottom) = compose_with(Bottom, first); + assert!((last(&bottom).0 - area.y1).abs() < 1e-6, "{first:?}: Bottom puts the last baseline on the inset: {bottom:?}"); + assert!(last(&bottom).0 + last(&bottom).1 > area.y1 + 1.0, "{first:?}: the descenders reach into the inset"); + assert!((bottom[1].0 - bottom[0].0 - (top[1].0 - top[0].0)).abs() < 1e-6, "{first:?}: Bottom keeps the leading"); + + let (_, justify) = compose_with(Justify, first); + assert!((justify[0].0 - top[0].0).abs() < 1e-6, "{first:?}: Justify keeps the first baseline: {justify:?}"); + assert!((last(&justify).0 - area.y1).abs() < 1e-6, "{first:?}: Justify puts the last baseline on the inset: {justify:?}"); + + let (_, center) = compose_with(Center, first); + let shift = center[0].0 - top[0].0; + assert!(shift > 1.0); + assert!((center[1].0 - top[1].0 - shift).abs() < 1e-6, "{first:?}: Center moves every line alike"); + assert!((area.y1 - last(¢er).0 - shift).abs() < 1e-6, "{first:?}: Center leaves equal room above and below: {center:?}"); + + // A bottom inset smaller than the descent: the last baseline still sits on the inset, and + // the descenders reach past the frame's edge. + for inset in [0.0, 1.0] { + for mode in [Bottom, Justify] { + let (area, lines) = compose_inset(mode, first, inset); + let (b, desc) = last(&lines); + assert!(desc > inset + 0.5); + assert!((b - area.y1).abs() < 1e-6, "{first:?} {mode:?} inset {inset}: last baseline at {b}, inset at {}", area.y1); + } + } + } +} + +/// With tight leading an earlier line's descenders can reach below the last baseline: Bottom keeps +/// them inside the text area, and only the last line's descenders hang into the bottom inset. +#[test] +fn vertical_justification_keeps_earlier_descenders_inside() { + use designcraft_doc::VerticalJustification::{self, Bottom, Center, Justify}; + let compose_with = |mode: VerticalJustification| { + let (mut d, sid, fid) = doc_with("Big\nx", Rect::new(0.0, 0.0, 200.0, 300.0), ParaAttrs::default()); + let o = &mut d.item_mut(fid).unwrap().text_frame_mut().unwrap().options; + o.vertical_justification = mode; + o.inset = [6.0; 4]; + let st = d.story_mut(sid).unwrap(); + st.format_chars(0..3, |f| f.over.size = Some(48.0)); + st.format_chars(4..5, |f| f.over.leading = Some(designcraft_doc::Leading::Points(2.0))); + let area = frame_specs(&d, sid)[0].area; + let cs = compose_story(&d, sid, &ComposeOptions::default()); + let lines: Vec<(f64, f64)> = all_lines(&cs).iter().map(|l| (l.baseline, l.descent)).collect(); + assert_eq!(lines.len(), 2); + if mode != Justify { + assert!(lines[0].0 + lines[0].1 > lines[1].0 + 1.0, "the first line's ink reaches below the last baseline: {lines:?}"); + } + (area, lines[0].0 + lines[0].1, lines[1].0) + }; + // Bottom moves both lines until the first line's ink meets the text area's bottom. + let (area, ink, _) = compose_with(Bottom); + assert!((ink - area.y1).abs() < 1e-6, "Bottom: first line's ink ends at {ink}, text area at {}", area.y1); + // Center moves both lines, as far as the first line's ink allows. + let (area, ink, _) = compose_with(Center); + assert!(ink <= area.y1 + 1e-6, "Center: first line's ink ends at {ink}, text area at {}", area.y1); + // Justify leaves the first line where it is, so the last baseline still reaches the inset. + let (area, _, last) = compose_with(Justify); + assert!((last - area.y1).abs() < 1e-6, "Justify: last baseline at {last}, text area at {}", area.y1); +} + +/// With Align to Baseline Grid, Center and Bottom move the lines by whole grid steps, so every +/// line stays on the grid: Bottom puts the last baseline on the lowest grid line above the bottom +/// inset, and Center on the grid line nearest the centered place. Justify keeps the first and last +/// lines on the grid and spreads the lines between them. +#[test] +fn vertical_justification_keeps_grid_aligned_lines_on_the_grid() { + use designcraft_doc::GridAlign; + use designcraft_doc::VerticalJustification::{self, Bottom, Center, Justify, Top}; + let compose_with = |mode: VerticalJustification, align: GridAlign| { + let mut area = Rect::ZERO; + let (lines, grid) = grid_doc("One\nTwo\nThree", ParaAttrs { grid_align: Some(align), ..Default::default() }, |d, sid| { + let spec = frame_specs(d, sid).remove(0); + area = spec.area; + d.item_mut(spec.id).unwrap().text_frame_mut().unwrap().options.vertical_justification = mode; + }); + (area, lines.iter().map(|l| l.baseline).collect::>(), grid) + }; + let (area, top, grid) = compose_with(Top, GridAlign::AllLines); + let inc = grid.1; + assert_eq!(top.len(), 3); + assert!(top.iter().all(|&b| on_grid(b, grid)), "Top: {top:?}"); + assert!(!on_grid(area.y1, grid), "the bottom inset is between grid lines: {area:?}"); + + let (_, bottom, _) = compose_with(Bottom, GridAlign::AllLines); + assert!(bottom.iter().all(|&b| on_grid(b, grid)), "Bottom keeps every line on the grid: {bottom:?}"); + let last = bottom[2]; + assert!(last <= area.y1 + 1e-6 && last > area.y1 - inc, "Bottom: last baseline {last} on the lowest grid line above {}", area.y1); + assert!((bottom[1] - bottom[0] - (top[1] - top[0])).abs() < 1e-6, "Bottom keeps the leading"); + + let (_, center, _) = compose_with(Center, GridAlign::AllLines); + assert!(center.iter().all(|&b| on_grid(b, grid)), "Center keeps every line on the grid: {center:?}"); + let shift = center[0] - top[0]; + let ideal = (area.y1 - top[2]) / 2.0; + assert!(shift > 1.0 && (shift - ideal).abs() <= inc / 2.0 + 1e-6, "Center: moved {shift}, centered at {ideal}"); + assert!(center[2] <= area.y1 + 1e-6); + + let (_, justify, _) = compose_with(Justify, GridAlign::AllLines); + assert!((justify[0] - top[0]).abs() < 1e-6, "Justify keeps the first baseline: {justify:?}"); + assert!(on_grid(justify[2], grid), "Justify keeps the last line on the grid: {justify:?}"); + assert!(justify[2] <= area.y1 + 1e-6 && justify[2] > area.y1 - inc, "Justify: last baseline {} near {}", justify[2], area.y1); + assert!((justify[1] - justify[0] - (justify[2] - justify[1])).abs() < 1e-6, "Justify spreads the lines evenly: {justify:?}"); + + // First lines only: each paragraph here is one line, so Bottom keeps every line on the grid. + let (_, first_only, _) = compose_with(Bottom, GridAlign::FirstLineOnly); + assert!(first_only.iter().all(|&b| on_grid(b, grid)), "Bottom, first lines only: {first_only:?}"); + + // Justify with a paragraph that wraps: with all lines aligned the last line lands on the grid; + // with first lines only it is not a first line, so it goes down to the bottom inset. + let wrapped = "The first line of this paragraph sits on the baseline grid, and the lines after it keep the leading they have."; + let justify_wrapped = |align: GridAlign| { + let (lines, _) = grid_doc(wrapped, ParaAttrs { grid_align: Some(align), ..Default::default() }, |d, sid| { + let spec = frame_specs(d, sid).remove(0); + d.item_mut(spec.id).unwrap().text_frame_mut().unwrap().options.vertical_justification = Justify; + }); + lines.iter().map(|l| l.baseline).collect::>() + }; + let all = justify_wrapped(GridAlign::AllLines); + assert!(all.len() >= 2, "the paragraph wraps: {all:?}"); + let last = all[all.len() - 1]; + assert!(on_grid(last, grid) && last <= area.y1 + 1e-6 && last > area.y1 - inc, "Justify, all lines: last baseline {last}"); + let first_lines = justify_wrapped(GridAlign::FirstLineOnly); + assert!(first_lines.len() >= 2, "the paragraph wraps: {first_lines:?}"); + let last = first_lines[first_lines.len() - 1]; + assert!((last - area.y1).abs() < 1e-6 && !on_grid(last, grid), "Justify, first lines only: last baseline {last}, inset at {}", area.y1); + + // Without grid alignment the last baseline goes down to the bottom inset. + let (_, free, _) = compose_with(Bottom, GridAlign::None); + assert!((free[2] - area.y1).abs() < 1e-6, "Bottom without the grid: {free:?}"); +} + +/// A grid increment too small for the room to be counted in steps, or too large to double, leaves +/// a grid-aligned line at a finite place inside the text area with Bottom, Center and Justify. +#[test] +fn vertical_justification_with_an_extreme_grid_increment_stays_finite() { + use designcraft_doc::GridAlign; + use designcraft_doc::VerticalJustification::{self, Bottom, Center, Justify, Top}; + // The grid starts at the line's natural baseline, so the line sits on it before it moves. + let (natural, grid) = grid_doc("One", ParaAttrs { grid_align: Some(GridAlign::None), ..Default::default() }, |_, _| {}); + let natural = natural[0].baseline; + let start = natural - grid.0; + let compose_with = |mode: VerticalJustification, inc: f64| { + let mut area = Rect::ZERO; + let (lines, _) = grid_doc("One", ParaAttrs { grid_align: Some(GridAlign::AllLines), ..Default::default() }, |d, sid| { + let spec = frame_specs(d, sid).remove(0); + area = spec.area; + let opts = &mut d.item_mut(spec.id).unwrap().text_frame_mut().unwrap().options; + opts.baseline_grid = Some(designcraft_doc::FrameBaselineGrid::new(start, inc)); + opts.vertical_justification = mode; + }); + (area, lines[0].baseline) + }; + for inc in [1e-310, 1e308] { + let (_, top) = compose_with(Top, inc); + assert!((top - natural).abs() < 1e-6, "Top with increment {inc:e}: baseline {top}, natural {natural}"); + for mode in [Bottom, Center, Justify] { + let (area, b) = compose_with(mode, inc); + assert!(b.is_finite() && b >= top - 1e-6 && b <= area.y1 + 1e-6, "{mode:?} with increment {inc:e}: baseline {b}, text area {area:?}"); + } + } + // A step far smaller than the room: Bottom takes the room as it does without a grid. + let (area, b) = compose_with(Bottom, 1e-310); + assert!((b - area.y1).abs() < 1e-6, "Bottom with a tiny increment: baseline {b}, text area {area:?}"); + // A step far larger than the room: the line does not move. + let (_, b) = compose_with(Center, 1e308); + assert!((b - natural).abs() < 1e-6, "Center with a huge increment: baseline {b}, natural {natural}"); + + // A grid that starts away from the line, with a step too small to count the distance: the line + // is placed as it is without a grid. + for mode in [Top, Bottom, Center, Justify] { + let mut area = Rect::ZERO; + let (lines, _) = grid_doc("One", ParaAttrs { grid_align: Some(GridAlign::AllLines), ..Default::default() }, |d, sid| { + let spec = frame_specs(d, sid).remove(0); + area = spec.area; + let opts = &mut d.item_mut(spec.id).unwrap().text_frame_mut().unwrap().options; + opts.baseline_grid = Some(designcraft_doc::FrameBaselineGrid::new(start - 5.0, 1e-310)); + opts.vertical_justification = mode; + }); + let b = lines[0].baseline; + assert!(b.is_finite() && b >= natural - 1e-6 && b <= area.y1 + 1e-6, "{mode:?}, grid away from the line: baseline {b}, text area {area:?}"); + if mode == Top { + assert!((b - natural).abs() < 1e-6, "Top, grid away from the line: baseline {b}, natural {natural}"); + } + } + + // A grid whose first line is too far off to count the text area in its 0.7 pt steps: Bottom + // takes the room as it does without a grid. + let mut area = Rect::ZERO; + let (lines, _) = grid_doc("One", ParaAttrs { grid_align: Some(GridAlign::AllLines), ..Default::default() }, |d, sid| { + let spec = frame_specs(d, sid).remove(0); + area = spec.area; + let opts = &mut d.item_mut(spec.id).unwrap().text_frame_mut().unwrap().options; + opts.baseline_grid = Some(designcraft_doc::FrameBaselineGrid::new(-1.7e308, 0.7)); + opts.vertical_justification = Bottom; + }); + let b = lines[0].baseline; + assert!((b - area.y1).abs() < 1e-6, "Bottom with a far-off grid: baseline {b}, text area {area:?}"); +} + +/// In a shaped frame that narrows and widens again, Align to Baseline Grid takes the grid step +/// nearest the place Bottom or Center would choose at which the line's slot fits the outline: +/// Bottom goes up past steps in the narrow part, and Center goes down a step when the step nearest +/// the middle is in the narrow part and the next one fits. +#[test] +fn vertical_justification_on_the_grid_skips_steps_that_leave_a_shaped_frame() { + use designcraft_doc::GridAlign; + use designcraft_doc::VerticalJustification::{self, Bottom, Center, Top}; + use designcraft_geom::{Anchor, PathData, Point, SubPath}; + // Full width down to 100 pt, a waist at 150 pt, full width again from 200 to 230 pt, then a + // point at 300 pt. + let pts = [(0.0, 0.0), (300.0, 0.0), (300.0, 100.0), (200.0, 150.0), (300.0, 200.0), (300.0, 230.0), (150.0, 300.0)]; + let pts: Vec<(f64, f64)> = pts.iter().copied().chain([(0.0, 230.0), (0.0, 200.0), (100.0, 150.0), (0.0, 100.0)]).collect(); + let compose_with = |mode: VerticalJustification, inc: f64| { + let para = ParaAttrs { grid_align: Some(GridAlign::AllLines), ..Default::default() }; + let (mut d, sid, fid) = doc_with("Typography", Rect::new(0.0, 0.0, 300.0, 300.0), para); + let it = d.item_mut(fid).unwrap(); + it.path = PathData::single(SubPath { anchors: pts.iter().map(|&(x, y)| Anchor::corner(Point::new(x, y))).collect(), closed: true }); + let o = &mut it.text_frame_mut().unwrap().options; + o.inset = [0.0; 4]; + o.baseline_grid = Some(designcraft_doc::FrameBaselineGrid::new(0.0, inc)); + o.vertical_justification = mode; + let grid = frame_specs(&d, sid)[0].grid.unwrap(); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + let l = all_lines(&cs)[0]; + (grid, l.baseline, l.baseline - l.ascent) + }; + let lower = |b: f64, band_top: f64| band_top >= 200.0 - 1e-6 && b <= 230.0 + 1e-6; + + // A 40 pt grid: the lowest room ends between 160 and 200 pt, and the steps above it down to + // 120 pt put the line in the waist. + let (grid, top, _) = compose_with(Top, 40.0); + assert!(on_grid(top, grid), "Top: baseline {top} on the grid {grid:?}"); + let (_, b, band_top) = compose_with(Bottom, 40.0); + assert!(on_grid(b, grid), "Bottom: baseline {b} on the grid {grid:?}"); + assert!(b <= 100.0 + 1e-6 || lower(b, band_top), "Bottom: the line's band {band_top}..{b} reaches into the narrow part"); + assert!(b > top, "Bottom moves the line down a grid step that fits: {b}, Top at {top}"); + + // A 45 pt grid: the step nearest the middle puts the baseline at 180 pt, in the waist; the + // step below it fits in the lower full-width part. + let (grid, b, band_top) = compose_with(Center, 45.0); + assert!(on_grid(b, grid), "Center: baseline {b} on the grid {grid:?}"); + assert!(lower(b, band_top), "Center: the line's band {band_top}..{b} is not in the lower full-width part"); +} + +/// A corner radius leaves a Cap Height first line where it sits in a rectangular frame, with Top +/// and with Center: a line's band above the text area isn't held to the frame's outline (#1999). +/// Center puts the last baseline halfway between where Top sets it and the bottom inset, also in +/// a frame too short for the descenders below it. +#[test] +fn a_corner_radius_keeps_a_cap_height_line_in_place() { + use designcraft_doc::VerticalJustification::{self, Bottom, Center, Justify, Top}; + use designcraft_geom::corners::{CornerOptions, CornerShape}; + let mm = 72.0 / 25.4; + let compose_tall = |height: f64, radius: f64, mode: VerticalJustification| { + let rect = Rect::new(0.0, 0.0, 29.553 * mm, height); + let (mut d, sid, fid) = doc_with("137mm", rect, ParaAttrs::default()); + let item = d.item_mut(fid).unwrap(); + item.corners = CornerOptions::uniform(CornerShape::Rounded, radius); + let o = &mut item.text_frame_mut().unwrap().options; + o.vertical_justification = mode; + o.first_baseline = FirstBaseline::CapHeight; + o.inset = [0.0; 4]; + d.story_mut(sid).unwrap().format_chars(0.."137mm".len(), |f| { + f.over.size = Some(19.0); + f.over.leading = Some(designcraft_doc::Leading::Points(19.0)); + }); + let spec = frame_specs(&d, sid).remove(0); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + assert!(!cs.is_overset()); + (spec.outline.is_some(), spec.area, cs.frames[0].lines[0].baseline) + }; + let compose_with = |radius: f64, mode: VerticalJustification| compose_tall(9.593 * mm, radius, mode); + let (square, area, top) = compose_with(0.0, Top); + let (rounded, _, rounded_top) = compose_with(0.1 * mm, Top); + assert!(!square && rounded, "only the radius gives the frame an outline"); + assert!((rounded_top - top).abs() < 1e-6, "Top: {rounded_top} with a radius, {top} without"); + let (_, _, center) = compose_with(0.0, Center); + let (_, _, rounded_center) = compose_with(0.1 * mm, Center); + assert!((center - (area.y1 + top) / 2.0).abs() < 1e-6, "Center: the last baseline halfway between {top} and {}: {center}", area.y1); + assert!((rounded_center - center).abs() < 1e-6, "Center: {rounded_center} with a radius, {center} without"); + + // Frames too short for the descenders under a centered last baseline. + for height in [22.0, 20.0, 19.0] { + let (_, area, top) = compose_tall(height, 0.0, Top); + let (_, _, center) = compose_tall(height, 0.0, Center); + assert!((center - (area.y1 + top) / 2.0).abs() < 1e-6, "{height} pt: Center at {center}, Top at {top}, inset at {}", area.y1); + } + + // A corner radius doesn't change where Bottom and Justify put the last baseline: on the + // bottom inset, as in a rectangular frame, with the descenders in the inset. Each radius is + // smaller than the inset, so the rounded corner stays clear of the text area. + for (insets, big) in [([6.0; 4], 4.0), ([0.0, 0.0, 12.0, 0.0], 6.0)] { + for mode in [Bottom, Justify] { + let compose_frame = |radius: f64| { + let (mut d, sid, fid) = doc_with("Typography\ngypsy", Rect::new(0.0, 0.0, 200.0, 100.0), ParaAttrs::default()); + let item = d.item_mut(fid).unwrap(); + item.corners = CornerOptions::uniform(CornerShape::Rounded, radius); + let o = &mut item.text_frame_mut().unwrap().options; + o.vertical_justification = mode; + o.inset = insets; + let area = frame_specs(&d, sid)[0].area; + let cs = compose_story(&d, sid, &ComposeOptions::default()); + (area, all_lines(&cs).iter().map(|l| l.baseline).collect::>()) + }; + let (area, square) = compose_frame(0.0); + for radius in [0.1 * mm, big] { + let (_, rounded) = compose_frame(radius); + assert_eq!(rounded.len(), square.len()); + for (r, s) in rounded.iter().zip(&square) { + assert!((r - s).abs() < 1e-6, "{mode:?} insets {insets:?} radius {radius}: {rounded:?} with a radius, {square:?} without"); + } + } + let last = square[square.len() - 1]; + assert!((last - area.y1).abs() < 1e-6, "{mode:?} insets {insets:?}: last baseline at {last}, inset at {}", area.y1); + } + } +} + +/// In a shaped frame, Center, Bottom and Justify keep each moved line's slot inside the outline: +/// a triangle that narrows downward holds the lines where their slots still fit, and one that +/// widens downward lets Bottom put the last baseline on the frame's bottom. +#[test] +fn vertical_justification_keeps_lines_inside_a_shaped_frame() { + use designcraft_doc::VerticalJustification::{self, Bottom, Center, Justify}; + use designcraft_geom::{Anchor, PathData, Point, SubPath}; + let r = Rect::new(0.0, 0.0, 300.0, 300.0); + let compose_with = |tri: [Point; 3], mode: VerticalJustification| { + let (mut d, sid, fid) = doc_with("Typography\ngypsy", r, ParaAttrs::default()); + let it = d.item_mut(fid).unwrap(); + it.path = PathData::single(SubPath { anchors: tri.iter().map(|&p| Anchor::corner(p)).collect(), closed: true }); + let o = &mut it.text_frame_mut().unwrap().options; + o.vertical_justification = mode; + o.inset = [0.0; 4]; + let spec = frame_specs(&d, sid).remove(0); + assert!(spec.outline.is_some()); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + let lines: Vec = all_lines(&cs).into_iter().cloned().collect(); + assert!(lines.len() >= 2, "{mode:?}: {lines:?}"); + (spec.area, lines) + }; + // Narrowing downward: |x - 150| <= (300 - y) / 2 over each slot's band, from the line's top to + // its baseline. + let down = [Point::new(0.0, 0.0), Point::new(300.0, 0.0), Point::new(150.0, 300.0)]; + for mode in [Center, Bottom, Justify] { + let (area, lines) = compose_with(down, mode); + for (k, l) in lines.iter().enumerate() { + let bottom = l.baseline; + let top = (l.baseline - l.ascent).max(area.y0); + for (x, y) in [(l.x0, top), (l.x1, top), (l.x0, bottom), (l.x1, bottom)] { + assert!((x - 150.0).abs() <= (300.0 - y) / 2.0 + 1e-3, "{mode:?}: line {k} corner ({x}, {y}) outside the triangle: {lines:?}"); + } + } + } + // Widening downward: moving down keeps every slot inside, so Bottom goes all the way. + let up = [Point::new(150.0, 0.0), Point::new(300.0, 300.0), Point::new(0.0, 300.0)]; + let (area, lines) = compose_with(up, Bottom); + let last = lines[lines.len() - 1].baseline; + assert!((last - area.y1).abs() < 1e-6, "Bottom: last baseline at {last}, frame bottom at {}: {lines:?}", area.y1); + + // Narrowing at a waist, full width again from 200 to 260 pt, then a point: Bottom sets the + // lines in the lower full-width part, past the waist. + let pts = [(0.0, 0.0), (300.0, 0.0), (300.0, 100.0), (200.0, 150.0), (300.0, 200.0), (300.0, 260.0), (150.0, 300.0)]; + let pts: Vec<(f64, f64)> = pts.iter().copied().chain([(0.0, 260.0), (0.0, 200.0), (100.0, 150.0), (0.0, 100.0)]).collect(); + let (mut d, sid, fid) = doc_with("Typography\ngypsy", r, ParaAttrs::default()); + let it = d.item_mut(fid).unwrap(); + it.path = PathData::single(SubPath { anchors: pts.iter().map(|&(x, y)| Anchor::corner(Point::new(x, y))).collect(), closed: true }); + let o = &mut it.text_frame_mut().unwrap().options; + o.vertical_justification = Bottom; + o.inset = [0.0; 4]; + let cs = compose_story(&d, sid, &ComposeOptions::default()); + let lines = all_lines(&cs); + let (first, last) = (lines[0], lines[lines.len() - 1]); + assert!(first.baseline - first.ascent >= 200.0 - 1e-6, "Bottom: first line top at {}", first.baseline - first.ascent); + assert!((last.baseline - 260.0).abs() < 1e-3, "Bottom: last baseline at {}", last.baseline); +} + +/// In a shaped frame, Center and Bottom move every line until its slot reaches the outline at its +/// baseline: an earlier line's descenders may cross the outline, as the last line's do. A frame +/// full width down to 20 pt and half width below it holds the first line's baseline at 20 pt. +#[test] +fn vertical_justification_lets_earlier_descenders_cross_a_shaped_frame() { + use designcraft_doc::VerticalJustification::{Bottom, Center}; + use designcraft_geom::{Anchor, PathData, Point, SubPath}; + let pts = [(0.0, 0.0), (300.0, 0.0), (300.0, 20.0), (150.0, 20.0), (150.0, 300.0), (0.0, 300.0)]; + for mode in [Center, Bottom] { + let (mut d, sid, fid) = doc_with("Typography\ngypsy", Rect::new(0.0, 0.0, 300.0, 300.0), ParaAttrs::default()); + let it = d.item_mut(fid).unwrap(); + it.path = PathData::single(SubPath { anchors: pts.iter().map(|&(x, y)| Anchor::corner(Point::new(x, y))).collect(), closed: true }); + let o = &mut it.text_frame_mut().unwrap().options; + o.vertical_justification = mode; + o.inset = [0.0; 4]; + assert!(frame_specs(&d, sid)[0].outline.is_some()); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + let lines = all_lines(&cs); + assert_eq!(lines.len(), 2, "{mode:?}: {lines:?}"); + let (first, last) = (lines[0], lines[1]); + assert!((first.x1 - 300.0).abs() < 1e-6 && (last.x1 - 150.0).abs() < 1e-6, "{mode:?}: slots {lines:?}"); + assert!(first.descent > 1.0, "{mode:?}: {first:?}"); + assert!((first.baseline - 20.0).abs() < 1e-3, "{mode:?}: first baseline at {}, step at 20", first.baseline); + assert!(last.baseline <= 300.0 + 1e-6, "{mode:?}: last baseline at {}", last.baseline); + } +} + +/// In a tall shaped frame, Bottom finds a band that the line fits in over less room than one step +/// of an even scan: in a frame that is half width from 40 pt down, apart from a full-width band +/// only 0.25 pt taller than the line at 1,800 pt, the line moves into that band. +#[test] +fn vertical_justification_finds_a_narrow_band_in_a_tall_shaped_frame() { + use designcraft_doc::VerticalJustification::{self, Bottom, Top}; + use designcraft_geom::{Anchor, PathData, Point, SubPath}; + let compose_with = |pts: &[(f64, f64)], mode: VerticalJustification| -> Vec { + let (mut d, sid, fid) = doc_with("Typography", Rect::new(0.0, 0.0, 300.0, 2000.0), ParaAttrs::default()); + let it = d.item_mut(fid).unwrap(); + if !pts.is_empty() { + it.path = PathData::single(SubPath { anchors: pts.iter().map(|&(x, y)| Anchor::corner(Point::new(x, y))).collect(), closed: true }); + } + let o = &mut it.text_frame_mut().unwrap().options; + o.vertical_justification = mode; + o.inset = [0.0; 4]; + assert_eq!(frame_specs(&d, sid)[0].outline.is_some(), !pts.is_empty()); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + assert!(!cs.is_overset(), "{mode:?}"); + all_lines(&cs).into_iter().cloned().collect() + }; + let ascent = compose_with(&[], Top)[0].ascent; + assert!(ascent > 1.0, "ascent {ascent}"); + let (y0, y1) = (1800.0, 1800.0 + ascent + 0.25); + let pts = + [(0.0, 0.0), (300.0, 0.0), (300.0, 40.0), (150.0, 40.0), (150.0, y0), (300.0, y0), (300.0, y1), (150.0, y1), (150.0, 2000.0), (0.0, 2000.0)]; + let lines = compose_with(&pts, Bottom); + assert_eq!(lines.len(), 1, "{lines:?}"); + let l = &lines[0]; + assert!((l.x1 - 300.0).abs() < 1e-6, "slot {l:?}"); + assert!(l.baseline - l.ascent >= y0 - 1e-6 && l.baseline <= y1 + 1e-6, "baseline at {}, band {y0}..{y1}", l.baseline); +} + +/// In a shaped frame with a text wrap under the text, Center, Bottom and Justify keep the lines +/// inside the outline and out of the wrap together: in a triangle that widens downward, Bottom and +/// Justify put the last baseline on the wrap's top and Center moves half as far; in one that +/// narrows downward, the outline stops the lines above the wrap, where they stop without it. +#[test] +fn vertical_justification_keeps_a_shaped_frame_and_a_wrap_under_the_text_together() { + use designcraft_doc::VerticalJustification::{self, Bottom, Center, Justify, Top}; + use designcraft_geom::{Anchor, PathData, Point, SubPath}; + let compose_with = |tri: [Point; 3], mode: VerticalJustification, bar: bool| { + let (mut d, sid, fid) = doc_with("Typography\ngypsy", Rect::new(0.0, 0.0, 300.0, 300.0), ParaAttrs::default()); + let it = d.item_mut(fid).unwrap(); + it.path = PathData::single(SubPath { anchors: tri.iter().map(|&p| Anchor::corner(p)).collect(), closed: true }); + let o = &mut it.text_frame_mut().unwrap().options; + o.vertical_justification = mode; + o.inset = [0.0; 4]; + if bar { + let lid = d.default_layer(); + let mut it = designcraft_doc::Item::new( + ItemId(d.alloc()), + lid, + designcraft_doc::Shape::Rectangle, + designcraft_geom::shapes::rectangle(Rect::new(0.0, 250.0, 300.0, 400.0)), + ); + it.wrap.mode = WrapMode::JumpObject; + d.insert_item(SpreadRef::Doc(0), it, None).unwrap(); + } + let cs = compose_story(&d, sid, &ComposeOptions::default()); + assert!(!cs.is_overset(), "{mode:?}"); + let lines: Vec = all_lines(&cs).into_iter().cloned().collect(); + assert!(lines.len() >= 2, "{mode:?}: {lines:?}"); + lines + }; + let up = [Point::new(150.0, 0.0), Point::new(300.0, 300.0), Point::new(0.0, 300.0)]; + let top = compose_with(up, Top, true); + let top_last = top[top.len() - 1].baseline; + for mode in [Bottom, Justify] { + let lines = compose_with(up, mode, true); + let last = lines[lines.len() - 1].baseline; + assert!((last - 250.0).abs() < 1e-3, "{mode:?}: last baseline at {last}, wrap top at 250: {lines:?}"); + for (k, l) in lines.iter().enumerate() { + let bottom = if k + 1 == lines.len() { l.baseline } else { l.baseline + l.descent }; + let top = l.baseline - l.ascent; + for (x, y) in [(l.x0, top), (l.x1, top), (l.x0, bottom), (l.x1, bottom)] { + assert!((x - 150.0).abs() <= y / 2.0 + 1e-3, "{mode:?}: line {k} corner ({x}, {y}) outside the triangle: {lines:?}"); + } + } + } + let center = compose_with(up, Center, true); + let center_last = center[center.len() - 1].baseline; + assert!((center_last - (top_last + 250.0) / 2.0).abs() < 1e-3, "Center: last baseline at {center_last}, Top at {top_last}"); + + let down = [Point::new(0.0, 0.0), Point::new(300.0, 0.0), Point::new(150.0, 300.0)]; + for mode in [Center, Bottom, Justify] { + let with = compose_with(down, mode, true); + let without = compose_with(down, mode, false); + assert!(without[without.len() - 1].baseline < 250.0, "{mode:?}: {without:?}"); + assert_eq!(with.len(), without.len()); + for (a, b) in with.iter().zip(&without) { + assert!((a.baseline - b.baseline).abs() < 1e-3, "{mode:?}: {with:?} with the wrap, {without:?} without"); + } + } +} + +#[test] +fn table_rows_clear_footnotes_and_continue_in_the_next_column() { + for span in [false, true] { + for row_height in [24.0, 150.0] { + let (mut d, sid, fid) = doc_with("First paragraph.\nSecond paragraph.", Rect::new(0.0, 0.0, 420.0, 200.0), ParaAttrs::default()); + d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.columns = 2; + d.footnote_options.span_columns = span; + let st = d.story_mut(sid).unwrap(); + st.insert_note(5, "First synthetic footnote.", ParaFormat::default()); + st.insert_note(25, "Second synthetic footnote.", ParaFormat::default()); + let mut table = designcraft_doc::Table::new(77, 8, 1, 0, 0, 180.0); + for row in &mut table.rows { + row.mode = designcraft_doc::RowHeightMode::Exactly; + row.height = row_height; + } + st.insert_table(st.len(), table); + let (next, _) = + d.add_text_frame(SpreadRef::Doc(0), Rect::new(0.0, 220.0, 420.0, 1720.0), d.default_layer(), "", ParaFormat::default()).unwrap(); + d.thread(fid, next).unwrap(); + + let cs = compose_story(&d, sid, &ComposeOptions::default()); + + assert!(!cs.is_overset()); + let ft = cs.frame(fid).unwrap(); + assert_eq!(ft.notes.len(), 2); + let top = ft.notes[0].rect.y0 - d.footnote_options.space_before; + for frag in &ft.tables { + if span || frag.column == 0 { + assert!(frag.cells.iter().all(|c| c.rect.y1 <= top + 0.01), "rows overlap footnotes: {:?}, top {top}", frag.rect); + } + } + assert!(cs.frames.iter().skip(1).any(|f| !f.tables.is_empty()) || ft.tables.iter().any(|t| t.column == 1)); + let rows: Vec<_> = cs.frames.iter().flat_map(|f| &f.tables).flat_map(|t| &t.cells).filter(|c| !c.repeated).map(|c| c.row).collect(); + assert_eq!(rows, (0..8).collect::>()); + if row_height == 150.0 { + assert!(!ft.tables.iter().any(|t| t.column == 0), "the whole table moves when no row fits"); + } + } + } +} + +#[test] +fn table_reports_overset_when_every_remaining_column_has_footnotes() { + let (mut d, sid, fid) = doc_with("Reference.", Rect::new(0.0, 0.0, 420.0, 200.0), ParaAttrs::default()); + d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.columns = 3; + d.footnote_options.span_columns = true; + d.footnote_options.space_before = 40.0; + let st = d.story_mut(sid).unwrap(); + st.insert_note(5, "Synthetic spanning footnote.", ParaFormat::default()); + let mut table = designcraft_doc::Table::new(77, 2, 1, 0, 0, 100.0); + for row in &mut table.rows { + row.mode = designcraft_doc::RowHeightMode::Exactly; + row.height = 90.0; + } + table.cells[0].row_span = 2; + let anchor = st.insert_table(st.len(), table); + + let cs = compose_story(&d, sid, &ComposeOptions::default()); + + assert!(cs.is_overset()); + assert_eq!(cs.overset_at, Some(anchor)); + let ft = cs.frame(fid).unwrap(); + assert_eq!(ft.notes.len(), 1); + assert!(ft.notes[0].rect.y0 - d.footnote_options.space_before < 180.0); + assert!(cs.frames.iter().all(|f| f.tables.is_empty()), "the unplaced row group must remain overset"); +} + +#[test] +fn table_cell_footnotes_fit_inside_the_row() { + let (mut d, sid, _) = doc_with("", Rect::new(0.0, 0.0, 200.0, 200.0), ParaAttrs::default()); + let mut table = designcraft_doc::Table::new(77, 1, 1, 0, 0, 180.0); + let cell = &mut table.cells[0]; + cell.text.insert(0, "Cell reference."); + cell.text.insert_note(5, "Synthetic cell footnote.", ParaFormat::default()); + d.story_mut(sid).unwrap().insert_table(0, table); + + let cs = compose_story(&d, sid, &ComposeOptions::default()); + + let cell = &cs.frames[0].tables[0].cells[0]; + assert!(!cell.overset); + let frame = &cell.text.frames[0]; + assert_eq!(frame.notes.len(), 1); + let note = &frame.notes[0]; + assert!(cell.origin.y + note.rect.y1 <= cell.clip.y1 + 0.01, "cell footnote must remain within the row"); + assert!(frame.lines.iter().all(|l| l.baseline + l.descent <= note.rect.y0 - d.footnote_options.space_before + 0.01)); +} + #[test] fn footnotes_stack_baseline_to_baseline() { // Single-line footnotes read as one text: consecutive baselines sit one leading (plus @@ -2836,11 +4375,18 @@ fn only_english_text_gets_english_hyphenation() { let hyphenated = |d: &Document, sid| all_lines(&compose_story(d, sid, &ComposeOptions::default())).iter().filter(|l| l.hyphenated).count(); let (d, sid, _) = doc_with(text, narrow, ParaAttrs::default()); assert!(hyphenated(&d, sid) > 0, "English hyphenates"); - let mut d2 = d.clone(); - let st = d2.story_mut(sid).unwrap(); - let n = st.len(); - st.format_chars(0..n, |f| f.over.language = Some("French".into())); - assert_eq!(hyphenated(&d2, sid), 0, "French isn't hyphenated with English rules"); + // A language without bundled patterns isn't hyphenated with English rules. + let in_language = |lang: &str| { + let mut d2 = d.clone(); + let st = d2.story_mut(sid).unwrap(); + let n = st.len(); + st.format_chars(0..n, |f| f.over.language = Some(lang.into())); + hyphenated(&d2, sid) + }; + assert_eq!(in_language("Swedish"), 0, "Swedish isn't hyphenated with English rules"); + // French and Italian hyphenate with their own patterns. + assert!(in_language("French") > 0, "French hyphenates (hyph-fr)"); + assert!(in_language("Italian") > 0, "Italian hyphenates (hyph-it)"); } // A text frame's bottom inset constrains its last baseline. The full font descent @@ -3492,6 +5038,21 @@ fn text_x(l: &Line, from: usize) -> f64 { l.glyphs.iter().find(|g| g.len > 0 && g.byte >= from).map(|g| g.x).unwrap() } +/// Vertical justification moves the drop cap's box with its line. +#[test] +fn drop_cap_box_follows_vertical_justification() { + let (mut d, sid, fid) = drop_doc_in(&[LOREM; 2].join(" "), Rect::new(0.0, 0.0, 300.0, 400.0), drop_cap(3, 1)); + let top = compose_story(&d, sid, &ComposeOptions::default()); + d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.vertical_justification = designcraft_doc::VerticalJustification::Bottom; + let bottom = compose_story(&d, sid, &ComposeOptions::default()); + let (a, b) = (&top.frame(fid).unwrap().lines[0], &bottom.frame(fid).unwrap().lines[0]); + let dy = b.baseline - a.baseline; + assert!(dy > 1.0); + let (da, db) = (a.drop_cap.unwrap(), b.drop_cap.unwrap()); + assert!((db.baseline - da.baseline - dy).abs() < 1e-6); + assert!((db.rect.y0 - da.rect.y0 - dy).abs() < 1e-6 && (db.rect.y1 - da.rect.y1 - dy).abs() < 1e-6); +} + #[test] fn drop_cap_spans_lines_and_indents_them() { let text = [LOREM; 2].join(" "); @@ -3778,6 +5339,22 @@ fn drop_cap_on_a_baseline_grid_reaches_down_by_grid_steps() { assert!((lines[2].baseline - cap_of(dc) - (lines[0].baseline - cap_of(body))).abs() < 0.01); } +/// A grid the lines can't count in steps (its first line too far off for a 0.7 pt step) is no grid +/// for the drop cap either: it reaches down to line 3 at the 12 pt leading the lines are set at. +#[test] +fn drop_cap_skips_a_grid_the_lines_skip() { + let (d, sid, _) = drop_doc(LOREM, ParaAttrs { grid_align: Some(designcraft_doc::GridAlign::AllLines), ..drop_cap(3, 1) }); + let mut specs = frame_specs(&d, sid); + specs[0].grid = Some((-1.7e308, 0.7)); + let cs = compose(&d, d.story(sid).unwrap(), &specs, &ComposeOptions::default()); + let lines = all_lines(&cs); + assert!((lines[2].baseline - lines[0].baseline - 24.0).abs() < 1e-6, "{} {}", lines[0].baseline, lines[2].baseline); + let dc = &lines[0].glyphs[0]; + assert!((lines[0].baseline + dc.y - lines[2].baseline).abs() < 1e-6, "drop cap baseline {} below line 1", dc.y); + let b = lines[0].drop_cap.unwrap(); + assert!((b.baseline - lines[2].baseline).abs() < 1e-6, "{}", b.baseline); +} + /// A line with a larger auto leading doesn't move the drop cap: it reaches down `lines − 1` /// leadings of the text after it, not to where line N is set. #[test] @@ -3889,6 +5466,56 @@ fn drop_cap_scales_with_its_point_size() { assert!(b2 - fitted * 1.5 < b0 - base[0].ascent, "a 15 pt cap rises above the first line"); } +/// Paragraph Rules › Type: a wavy, dashed or dotted rule is drawn as its shape (filled paths in +/// the rule's box), a striped one as its bands; Gap Color goes under it. Keep In Frame keeps a rule +/// above the first line inside the frame. +#[test] +fn paragraph_rules_have_a_type_a_gap_colour_and_keep_in_frame() { + use designcraft_doc::{Rule, StrokeType}; + let rule = |kind: StrokeType| Rule { on: true, weight: 4.0, kind, ..Default::default() }; + let decos = |r: Rule| { + let para = ParaAttrs { rule_below: Some(r), ..Default::default() }; + let (d, sid, fid) = doc_with("Recipe Categories", Rect::new(0.0, 0.0, 300.0, 200.0), para); + compose_story(&d, sid, &ComposeOptions::default()).frame(fid).unwrap().decos.clone() + }; + let solid = decos(rule(StrokeType::Solid)); + assert!(solid.len() == 1 && solid[0].path.is_none()); + let wavy = decos(rule(StrokeType::Wavy)); + let p = wavy[0].path.as_ref().expect("a wavy rule is a shape"); + assert!(designcraft_geom::Shape::area(p).abs() > 0.0 && (wavy[0].rect.height() - 4.0).abs() < 1e-9); + let subpaths = |p: &designcraft_geom::BezPath| p.elements().iter().filter(|e| matches!(e, designcraft_geom::PathEl::MoveTo(_))).count(); + let dashed = decos(rule(StrokeType::Dashed { pattern: vec![12.0, 4.0] })); + assert!(subpaths(dashed[0].path.as_ref().unwrap()) > 5, "one box per dash"); + let dotted = decos(rule(StrokeType::Dotted)); + assert!(subpaths(dotted[0].path.as_ref().unwrap()) > 10, "one dot per 2 weights"); + let gap = decos(Rule { gap_color: "[Black]".into(), gap_tint: 0.3, ..rule(StrokeType::Dotted) }); + assert_eq!((gap.len(), gap[0].color.as_str(), gap[0].tint, gap[0].path.is_none()), (2, "[Black]", 0.3, true), "the gap colour under the dots"); + assert_eq!(decos(Rule { gap_color: "[Black]".into(), ..rule(StrokeType::Solid) }).len(), 1, "a solid rule has no gaps"); + // A gap in Text Color takes the text's colour, whatever swatch the rule itself has. + let gap = decos(Rule { color: "[Paper]".into(), gap_color: designcraft_doc::TEXT_COLOR.into(), ..rule(StrokeType::Dotted) }); + assert_eq!((gap[0].color.as_str(), gap[1].color.as_str()), ("[Black]", "[Paper]")); + // Keep In Frame: a rule above raised out of the frame comes back to its top. + let above = |keep: bool| { + let r = Rule { on: true, weight: 2.0, offset: 30.0, keep_in_frame: keep, ..Default::default() }; + let para = ParaAttrs { rule_above: Some(r), ..Default::default() }; + let (d, sid, fid) = doc_with("Title", Rect::new(0.0, 50.0, 300.0, 200.0), para); + compose_story(&d, sid, &ComposeOptions::default()).frame(fid).unwrap().decos[0].rect + }; + assert!(above(false).y0 < 50.0, "{:?}", above(false)); + assert!((above(true).y0 - 50.0).abs() < 1e-6, "{:?}", above(true)); + // With a top inset the rule may still rise into it: raised out of the frame, it comes back + // to the frame's edge, not to the text area's below the inset. + let r = Rule { on: true, weight: 2.0, offset: 60.0, keep_in_frame: true, ..Default::default() }; + let para = ParaAttrs { rule_above: Some(r), ..Default::default() }; + let (mut d, sid, fid) = doc_with("Title", Rect::new(0.0, 50.0, 300.0, 200.0), para); + if let Some(tf) = d.item_mut(fid).and_then(|it| it.text_frame_mut()) { + tf.options.inset = [20.0, 0.0, 0.0, 0.0]; + } + let cs = compose_story(&d, sid, &ComposeOptions::default()); + let rule = cs.frame(fid).unwrap().decos[0].rect; + assert!((rule.y0 - 50.0).abs() < 1e-6, "kept at the frame's top, in the inset: {rule:?}"); +} + /// A rule in Text Color takes the colour of the paragraph's text: the first character's for the /// rule above, the last character's for the rule below. A swatch colour is used as is. #[test] @@ -4076,6 +5703,36 @@ fn empty_paragraph_uses_its_own_mark_not_the_previous_one() { assert!((lines[1].baseline - lines[0].baseline - 8.0).abs() < 1e-6, "{} {}", lines[0].baseline, lines[1].baseline); } +#[test] +fn german_2006_text_gets_german_hyphenation() { + let text = "Silbentrennung Fußgänger Bäcker Fenster Donaudampfschifffahrt Silbentrennung"; + let de = hyphen::Lang::for_language("German: 2006 Reform").unwrap(); + for composer in [Composer::Paragraph, Composer::SingleLine] { + for language in ["German: 2006 Reform", "de_DE_2006"] { + let para = ParaAttrs { composer: Some(composer), ..Default::default() }; + let (mut d, sid, _) = doc_with(text, Rect::new(36.0, 36.0, 96.0, 700.0), para); + d.story_mut(sid).unwrap().format_chars(0..text.len(), |f| f.over.language = Some(language.into())); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + assert!(!cs.is_overset(), "{composer:?}, {language}"); + let lines = all_lines(&cs); + assert!(lines.iter().any(|l| l.hyphenated), "{composer:?}, {language}: German text hyphenates"); + for line in lines.iter().filter(|l| l.hyphenated) { + // Check the actual character offset in the original word, including when the + // word spans more than two lines; UTF-8 byte offsets must not become char counts. + let end = line.range.end; + let start = text[..end].rfind(' ').map_or(0, |at| at + 1); + let word = text[start..].split_whitespace().next().unwrap(); + let point = text[start..end].chars().count(); + assert!(hyphen::hyphen_points_in(word, &hyphen::Limits::default(), de).contains(&point), "{word} at {point}"); + } + // The existing paragraph switch must still disable automatic German hyphenation. + d.story_mut(sid).unwrap().format_paras(0..text.len(), |f| f.para.hyphenate = Some(false)); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + assert!(all_lines(&cs).iter().all(|l| !l.hyphenated)); + } + } +} + #[test] fn spanish_text_gets_spanish_hyphenation() { let text = "La transición democrática fue una construcción colectiva extraordinariamente compleja y desesperadamente necesaria."; @@ -5211,6 +6868,43 @@ fn inline_object_only_line_does_not_reserve_phantom_font_descent() { assert!(compose_story(&d, sid, &ComposeOptions::default()).is_overset()); } +/// A story threaded over frames on pages 1 and 2, with a text frame anchored in the text that +/// flows into the second frame: the anchored frame is on page 2, where it is placed, and its page +/// number reads 2 (not the page of the host story's first frame). +#[test] +fn an_anchored_text_frame_in_a_later_frame_is_on_that_frames_page() { + use designcraft_doc::{AnchorPosition, AnchoredObject, story::FRAME_BREAK}; + let mut d = Document::new(&NewDocument { pages: 2, facing_pages: false, ..Default::default() }); + let lid = d.default_layer(); + let text = format!("One{FRAME_BREAK}Two "); + let (first, host) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(36.0, 36.0, 336.0, 436.0), lid, &text, ParaFormat::default()).unwrap(); + let (second, _) = d.add_text_frame(SpreadRef::Doc(1), Rect::new(36.0, 36.0, 336.0, 436.0), lid, "", ParaFormat::default()).unwrap(); + d.thread(first, second).unwrap(); + assert_eq!(d.story(host).unwrap().frames, vec![first, second]); + // A text frame showing a page number, anchored at the end of the host's text (in its second frame). + let (fid, sid) = d + .add_text_frame( + SpreadRef::Doc(0), + Rect::new(0.0, 0.0, 150.0, 40.0), + lid, + &designcraft_doc::story::PAGE_NUMBER.to_string(), + ParaFormat::default(), + ) + .unwrap(); + let item = d.item(fid).unwrap().clone(); + d.spread_mut(SpreadRef::Doc(0)).unwrap().items.retain(|i| i.id != fid); + let st = d.story_mut(host).unwrap(); + let n = st.len(); + st.insert_object(n, AnchoredObject::new(item, AnchorPosition::Inline { y_offset: 0.0 })); + d.check().unwrap(); + let placed = placed::placements(&d, sid, &mut |h| Arc::new(compose_story(&d, h, &ComposeOptions::default()))); + let spec = &frame_specs_placed(&d, sid, &placed)[0]; + assert_eq!((spec.page_name.as_deref(), spec.page), (Some("2"), Some(1))); + let cs = Cache::new().get(&d, sid, None); + let g = cs.frames[0].lines[0].glyphs.iter().find(|g| g.visible).unwrap(); + assert_eq!(g.gid, g.face.get().glyph_for('2'), "the page number of page 2"); +} + #[test] fn composite_metrics_and_character_mappings_apply_inside_footnotes() { use designcraft_doc::cjk::{CompositeFont, CompositeFontEntry}; @@ -5442,6 +7136,224 @@ fn mojikumi_kinsoku_push_in_and_push_out_select_different_legal_breaks() { } } +/// A paragraph that can compress: the Mojikumi table gives its ideographs shrinkable space, so +/// a line ending before a 禁則 boundary can be pulled in (追い込み) or pushed out (追い出し). +fn kinsoku_push_pull_doc(kind: Option<&str>) -> (Document, StoryId) { + kinsoku_push_pull_doc_text("甲乙丙丁戊己庚辛", kind) +} + +/// Same paragraph with a different body: used for the supplementary-plane ideographs, whose +/// CJK classification must match the breaker's Han set. +fn kinsoku_push_pull_doc_text(text: &str, kind: Option<&str>) -> (Document, StoryId) { + use designcraft_doc::cjk::{MojikumiAki, MojikumiTable}; + let (mut d, sid, _) = doc_with( + text, + Rect::new(0.0, 0.0, 45.0, 300.0), + ParaAttrs { + composer: Some(Composer::SingleLine), + mojikumi: Some("MojikumiTable/Compress".into()), + kinsoku_type: kind.map(str::to_string), + ..Default::default() + }, + ); + Arc::make_mut(&mut d.styles).mojikumi_tables.push(MojikumiTable { + name: "Compress".into(), + based_on: "SimpChineseDefault".into(), + overrides: vec![MojikumiAki { + target_class: 12, + side_class: 12, + after: true, + minimum: 0.0, + desired: 1.0, + maximum: 2.0, + priority: 1, + ..Default::default() + }], + }); + (d, sid) +} + +fn first_line_end(cs: &ComposedStory) -> (usize, f64) { + let line = all_lines(cs)[0]; + (line.range.end, line.end_x) +} + +#[test] +fn default_kinsoku_type_composes_as_push_in_first() { + // The empty value is InDesign's default (and what the UI's "Push In First" stores): it must + // behave as push-in-first, not as the minimum-adjustment mode. + let (d, sid) = kinsoku_push_pull_doc(None); + let default = compose_story(&d, sid, &ComposeOptions::default()); + let (d, sid) = kinsoku_push_pull_doc(Some("KinsokuPushInFirst")); + let push_in = compose_story(&d, sid, &ComposeOptions::default()); + let (d, sid) = kinsoku_push_pull_doc(Some("KinsokuPushOutFirst")); + let push_out = compose_story(&d, sid, &ComposeOptions::default()); + assert_eq!(first_line_end(&default).0, first_line_end(&push_in).0); + assert!(first_line_end(&default).0 > first_line_end(&push_out).0, "{:?} vs {:?}", first_line_end(&default), first_line_end(&push_out)); +} + +#[test] +fn push_out_only_leaves_the_line_end_uncompressed() { + // Push-out-only turns the 追い込み compression off: the line cannot be squeezed to reach a + // break, so it ends earlier (and never past the measure). + let (d, sid) = kinsoku_push_pull_doc(None); + let push_in = compose_story(&d, sid, &ComposeOptions::default()); + let (d, sid) = kinsoku_push_pull_doc(Some("KinsokuPushOutOnly")); + let push_out_only = compose_story(&d, sid, &ComposeOptions::default()); + assert!(first_line_end(&push_out_only).0 <= first_line_end(&push_in).0); + for cs in [&push_in, &push_out_only] { + for line in all_lines(cs) { + assert!(line.end_x <= line.x1 + 0.01, "line end {} past the measure {}", line.end_x, line.x1); + } + } + // Push-out-only's first line is not compressed to the measure: it ends short of it. + let (_, short) = first_line_end(&push_out_only); + let line = all_lines(&push_out_only)[0]; + assert!(line.x1 - short > 0.5, "no compression: end {short} vs measure {}", line.x1); +} + +#[test] +fn supplementary_ideograph_paragraph_keeps_the_kinsoku_gate() { + // Extension B 以降の漢字 (U+20000..) は breaker では Han として扱われる。段落全体の CJK 判定 + // (is_cjk_char) がそこを落とすと、補助面だけの段落で禁則の指定が効かなくなる。 + // 補助面だけの本文でも、追い込みと追い出しで行末が変わる (指定が効いている) こと。 + let first_end = |text: &str, kind: Option<&str>| { + let (d, sid) = kinsoku_push_pull_doc_text(text, kind); + first_line_end(&compose_story(&d, sid, &ComposeOptions::default())).0 + }; + let bmp = "甲乙丙丁戊己庚辛"; + let sup = "\u{20000}\u{20001}\u{20002}\u{20003}\u{20004}\u{20005}\u{20006}\u{20007}"; + // 対照: BMP の漢字だけの段落では、追い込みと追い出しで行末が変わる + assert_ne!(first_end(bmp, None), first_end(bmp, Some("KinsokuPushOutOnly")), "BMP の対照で禁則の指定が効いていない"); + // 補助面だけの段落でも同じように効く (判定から漏れると、どちらも同じ行末になる) + assert_ne!(first_end(sup, None), first_end(sup, Some("KinsokuPushOutOnly")), "補助面だけの段落で禁則の指定が効いていない"); + // 判定そのもの (Extension B の最初と最後、Ext G の終わり) + assert!(is_cjk_char('\u{20000}')); + assert!(is_cjk_char('\u{2A6DF}')); + assert!(is_cjk_char('\u{3FFFF}')); + assert!(!is_cjk_char('A')); +} + +#[test] +fn hangul_jamo_extended_blocks_count_as_cjk() { + // `is_cjk_char` takes Hangul from the breaker's classification, so the syllables and the + // Jamo Extended-A/B blocks count as well: a Hangul-only paragraph keeps its 禁則 priority. + for c in ['\u{A960}', '\u{A97F}', '\u{D7B0}', '\u{D7FF}'] { + assert!(is_cjk_char(c), "U+{:04X} is Hangul", c as u32); + } + assert!(is_cjk_char('\u{3105}'), "bopomofo is still CJK"); +} + +/// Shape `text` as a one-paragraph story with the default font and styles: the glyph list the +/// composition classifies before `split_drop_cap` and `prepend_label`. +fn shape_for_script_test(text: &str) -> Vec { + shape_for_script_test_with(text, &SubstCtx::default()) +} + +/// Same, with text variables resolved through `sub`. +fn shape_for_script_test_with(text: &str, sub: &SubstCtx) -> Vec { + let db = designcraft_fonts::FontDb::global().scoped(0); + let mut styles = Vec::new(); + let mut missing = std::collections::HashMap::new(); + let mut table = shape::StyleTable { styles: &mut styles, missing: &mut missing }; + let mut story = Story::new(StoryId(0)); + story.insert(0, text); + let doc_styles = designcraft_doc::Styles::default(); + shape::shape_para( + shape::ShapeInput { + db: &db, + styles: &doc_styles, + story: &story, + range: 0..text.len(), + para_chars: &designcraft_doc::CharProps::default(), + auto_leading: shape::TypeEnv { auto_leading: 1.2, adv: Default::default(), glyph_fallback: true }, + sub, + nested: &[], + grep: &[], + lines: &[], + drop_cap: (0, ""), + }, + &mut table, + ) + .glyphs +} + +#[test] +fn paragraph_script_counts_a_drop_cap_but_not_a_generated_label() { + // The 禁則 gate reads the paragraph's own shaped glyphs. The drop cap has not been split off + // yet, so a CJK one still makes the paragraph CJK. + assert!(paragraph_is_cjk(&shape_for_script_test("漢abc"))); + // A generated list label is prepended after the gate, so it is not part of the paragraph. + let mut glyphs = shape_for_script_test("abc"); + assert!(!paragraph_is_cjk(&glyphs)); + let db = designcraft_fonts::FontDb::global().scoped(0); + let mut styles = Vec::new(); + let mut missing = std::collections::HashMap::new(); + let mut table = shape::StyleTable { styles: &mut styles, missing: &mut missing }; + let n = prepend_label( + &db, + &mut glyphs, + "第1章", + 0, + &designcraft_doc::CharProps::default(), + shape::TypeEnv { auto_leading: 1.2, adv: Default::default(), glyph_fallback: true }, + &mut table, + ); + assert!(n > 0); + // The label's glyphs are CJK, so a gate computed after prepend_label would flip the answer. + assert!(glyphs.iter().take(n).any(|g| is_cjk_char(g.ch))); +} + +#[test] +fn paragraph_script_reads_a_text_variable_replacement() { + // A text variable's glyphs keep the source marker in `ch`; the paragraph shows the replacement, + // so a CJK replacement makes it CJK text even though no source character is. + let marker = designcraft_doc::vars::var_char(0).expect("variable 0"); + let text = format!("{marker}abc"); + let sub = SubstCtx { vars: Arc::new(vec!["漢字".into()]), ..Default::default() }; + let glyphs = shape_for_script_test_with(&text, &sub); + assert!(!glyphs.iter().any(|g| is_cjk_char(g.ch)), "the source is only the marker and Latin text"); + assert!(glyphs.iter().any(|g| g.generated_text.as_deref().is_some_and(|t| t.chars().any(is_cjk_char)))); + assert!(paragraph_is_cjk(&glyphs), "the CJK replacement is the paragraph's text"); +} + +#[test] +fn kinsoku_priority_modes_map_to_breaker_policies() { + let mut pp = ParaProps::default(); + let story = designcraft_doc::Story::new(designcraft_doc::StoryId::default()); + for (kind, priority) in [ + ("", 1u8), + ("KinsokuPushInFirst", 1), + ("KinsokuPushOutFirst", 2), + ("KinsokuPushOutOnly", 3), + ("KinsokuPrioritizeAdjustmentAmount", 0), + ("KinsokuSomethingElse", 0), + ] { + pp.kinsoku_type = kind.to_string(); + let sp = spacing_for(&pp, 12.0, &story, true); + assert_eq!(sp.kinsoku_priority, priority, "{kind}"); + assert!(sp.kinsoku_cjk, "{kind}"); + assert!(!spacing_for(&pp, 12.0, &story, false).kinsoku_cjk, "{kind}: Latin text is not biased"); + } +} + +#[test] +fn latin_paragraphs_are_not_biased_by_the_kinsoku_priority() { + // A justified Latin paragraph composes the same with push-in-first, push-out-first and + // minimum adjustment: the policy is about CJK 禁則, and a Latin paragraph has none. + let compose_with = |kind: &str| { + let (mut d, sid, _) = + doc_with(LOREM, Rect::new(0.0, 0.0, 200.0, 500.0), ParaAttrs { align: Some(Align::FullyJustified), ..Default::default() }); + d.story_mut(sid).unwrap().paras[0].para.kinsoku_type = Some(kind.to_string()); + compose_story(&d, sid, &ComposeOptions::default()) + }; + let ends = |cs: &ComposedStory| all_lines(cs).iter().map(|l| l.range.end).collect::>(); + let push_in = ends(&compose_with("")); + assert_eq!(ends(&compose_with("KinsokuPushInFirst")), push_in); + assert_eq!(ends(&compose_with("KinsokuPushOutFirst")), push_in); + assert_eq!(ends(&compose_with("KinsokuPrioritizeAdjustmentAmount")), push_in); +} + #[test] fn mojikumi_priority_and_elastic_line_start_are_used_in_placement() { use designcraft_doc::cjk::{MojikumiAki, MojikumiTable}; @@ -5686,6 +7598,31 @@ fn mojikumi_one_em_line_end_set_sets_closing_punctuation_full_width_at_line_end( assert!((open - one.0 - em * 0.5).abs() < 0.01 && (stop - one.1).abs() < 0.01, "one-em set: {one:?} of {open}/{stop}"); } +/// Consecutive punctuation touches (JLREQ 3.1.4): in 漢」。漢(「漢 the closing bracket and +/// the full stop, and the two opening brackets, close up by half an em each, under both +/// Japanese base sets (the full stop isn't at the line end, so the line-end rule doesn't apply). +#[test] +fn mojikumi_closes_up_consecutive_punctuation() { + let family = "Mojikumi Consecutive"; + let font = designcraft_fonts::testing::font_mapping(family, &[('漢', '‰'), ('」', '‰'), ('。', '‰'), ('(', '‰'), ('「', '‰')]).unwrap(); + designcraft_fonts::FontDb::global().add_font(font); + let text = "漢」。漢(「漢"; + let (mut d, sid, _) = doc_with(text, Rect::new(0.0, 0.0, 300.0, 100.0), ParaAttrs::default()); + d.story_mut(sid).unwrap().format_chars(0..text.len(), |f| f.over.font_family = Some(family.into())); + let mut width = |set: &str| { + d.story_mut(sid).unwrap().paras[0].para.mojikumi = Some(set.into()); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + let line = all_lines(&cs)[0]; + let g = &line.glyphs[0]; + (line.end_x - line.x0, g.face.units_per_em() * g.sx) + }; + let (natural, em) = width("Nothing"); + for name in ["LineEndAllOneHalfEmEnum", "LineEndAllOneEmEnum"] { + let (set, _) = width(name); + assert!((natural - set - em).abs() < 0.01, "{name}: {natural} - {set} should be one em ({em})"); + } +} + fn ruled(text: &str, rect: Rect, columns: u32, edit: impl FnOnce(&mut Document, StoryId)) -> (Document, ItemId, Vec) { let (mut d, sid, fid) = doc_with(text, rect, ParaAttrs::default()); { @@ -7024,6 +8961,38 @@ fn anchored_object_wraps_another_storys_text() { assert!(lines_in_band(&moved, 200.0, 260.0).iter().all(|l| l.x0 >= left + 100.0 - 1e-6)); } +/// An anchored frame whose wrap is set only on its placed graphic (Direct Selection) wraps +/// another story's text as a wrap set on the frame does. +#[test] +fn anchored_graphic_wrap_wraps_another_storys_text() { + let long = [LOREM; 3].join(" "); + let (mut d, a, fa) = doc_with("Anchor here.", Rect::new(0.0, 0.0, 300.0, 400.0), ParaAttrs::default()); + let lid = d.default_layer(); + let (_, b) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(320.0, 0.0, 620.0, 400.0), lid, &long, ParaFormat::default()).unwrap(); + let left = all_lines(&compose_story(&d, b, &ComposeOptions::default()))[0].x0; + let area = d.item(fa).unwrap().text_area(); + anchor_box(&mut d, a, 0, left - area.x0, 100.0 - area.y0, false, WrapMode::None); + let wrap = designcraft_doc::TextWrap { mode: WrapMode::BoundingBox, ..Default::default() }; + let obj = std::sync::Arc::make_mut(&mut d.story_mut(a).unwrap().objects[0]); + obj.item.content = designcraft_doc::Content::Graphic(designcraft_doc::Graphic { + layer_options: None, + asset: designcraft_doc::AssetId(1), + size: (100.0, 60.0), + xf: designcraft_geom::Affine::IDENTITY, + clip: None, + auto_fit: designcraft_doc::Fitting::None, + fit_align: 0, + crop: [0.0; 4], + wrap, + fill: Default::default(), + }); + let cs = compose_story(&d, b, &ComposeOptions::default()); + let band = lines_in_band(&cs, 100.0, 160.0); + assert!(!band.is_empty()); + assert!(band.iter().all(|l| l.x0 >= left + 100.0 - 1e-6), "{:?}", band.iter().map(|l| l.x0).collect::>()); + assert!(lines_in_band(&cs, 0.0, 80.0).iter().all(|l| (l.x0 - left).abs() < 1e-6)); +} + /// An anchored object's wrap is built as a page item's: a contour on both sides of an oval sets /// text left and right of it, closer in where the oval narrows. #[test] @@ -7131,6 +9100,73 @@ fn spine_relative_anchored_notes_stay_in_the_outside_margin_on_both_pages() { const OBJECT_LEN: usize = designcraft_doc::OBJECT_MARK.len_utf8(); +/// A story of `paras` paragraphs, each with an inline anchored object at its start, an endnote +/// reference after it and a cross-reference that shows `Ref.` for paragraph `k`. +fn story_with_marks(paras: usize) -> (Document, StoryId) { + let text = vec!["Some words, a note and an object."; paras].join("\n"); + let (mut d, sid, _) = doc_with(&text, Rect::new(0.0, 0.0, 400.0, 20_000.0), ParaAttrs::default()); + let starts: Vec = d.story(sid).unwrap().para_ranges().iter().map(|r| r.start).collect(); + let lid = d.default_layer(); + for (k, &s) in starts.iter().enumerate().rev() { + let it = designcraft_doc::Item::new( + ItemId(d.alloc()), + lid, + designcraft_doc::Shape::Rectangle, + designcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 6.0, 6.0)), + ); + let story = d.story_mut(sid).unwrap(); + story.insert_xref(s + 19, designcraft_doc::CrossRef { text: Some(format!("Ref{k}.")), ..Default::default() }); + story.insert_endnote(s + 10, "An endnote.", ParaFormat::default()); + story.insert_object(s, designcraft_doc::AnchoredObject::new(it, designcraft_doc::AnchorPosition::Inline { y_offset: 0.0 })); + } + (d, sid) +} + +/// The marks before each paragraph match a count from the story start, for every kind of mark. +#[test] +fn mark_counts_before_each_paragraph_match_a_count_from_the_start() { + let (d, sid) = story_with_marks(5); + let story = d.story(sid).unwrap(); + let ranges = story.para_ranges(); + let counts = MarkCounts::before_paragraphs(story, &ranges); + assert_eq!(counts.len(), ranges.len()); + for (k, (r, m)) in ranges.iter().zip(&counts).enumerate() { + let head = &story.text[..r.start]; + assert_eq!(m.endnotes, head.matches(designcraft_doc::ENDNOTE_REF).count(), "paragraph {k}"); + assert_eq!(m.objects, head.matches(designcraft_doc::OBJECT_MARK).count(), "paragraph {k}"); + assert_eq!(m.xrefs, head.matches(designcraft_doc::XREF_MARK).count(), "paragraph {k}"); + assert_eq!(*m, MarkCounts { endnotes: k, objects: k, xrefs: k }, "paragraph {k}"); + } + // Each paragraph shows its own cross-reference's text, so the composer numbers the + // cross-references from the marks before the paragraph. + let cs = compose_story(&d, sid, &ComposeOptions::default()); + let shown: String = cs.frames[0].lines.iter().flat_map(|l| l.glyphs.iter().filter(|g| g.visible).map(|g| g.rendered_char)).collect(); + let refs: Vec<&str> = shown.match_indices("Ref").map(|(i, _)| &shown[i..i + 5]).collect(); + assert_eq!(refs, ["Ref0.", "Ref1.", "Ref2.", "Ref3.", "Ref4."], "{shown:?}"); + // A story without endnotes, anchored objects or cross-references reads nothing. + let (plain, psid, _) = doc_with("One\nTwo", Rect::new(0.0, 0.0, 300.0, 300.0), ParaAttrs::default()); + let p = plain.story(psid).unwrap(); + assert!(MarkCounts::before_paragraphs(p, &p.para_ranges()).is_empty()); +} + +/// Composing a story with endnotes, anchored objects and cross-references reads its text for their numbers in one +/// pass, so four times the paragraphs read about four times the bytes, not sixteen times. +#[test] +fn composing_reads_marks_once_per_story() { + let scanned = |paras: usize| { + let (d, sid) = story_with_marks(paras); + MARK_BYTES_SCANNED.with(|n| n.set(0)); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + assert!(!cs.is_overset()); + assert_eq!(cs.frames[0].objects.len(), paras); + (MARK_BYTES_SCANNED.with(std::cell::Cell::get), d.story(sid).unwrap().text.len()) + }; + let (small, small_len) = scanned(40); + let (big, big_len) = scanned(160); + assert!(small > 0); + assert!(big * small_len <= 2 * small * big_len, "40 paragraphs read {small} of {small_len} bytes, 160 read {big} of {big_len}"); +} + #[test] fn anchored_object_wraps_its_own_storys_later_lines() { let text = [LOREM; 4].join(" "); @@ -7155,6 +9191,98 @@ fn anchored_object_wraps_its_own_storys_later_lines() { assert!((o.origin.y - top).abs() < 1e-6); } +/// Vertical Justification › Justify with a Paragraph Spacing Limit: the space goes between the +/// paragraphs (up to the limit each), the lines of a paragraph keep their leading; past the limit +/// the rest spreads over every line. Without a limit it spreads over every line. +#[test] +fn justify_paragraph_spacing_limit() { + let text = "One line. +Two +Three"; + let baselines = |limit: f64| { + let (mut d, sid, fid) = doc_with(text, Rect::new(0.0, 0.0, 300.0, 400.0), ParaAttrs::default()); + let o = &mut d.item_mut(fid).unwrap().text_frame_mut().unwrap().options; + o.vertical_justification = designcraft_doc::VerticalJustification::Justify; + o.vj_paragraph_spacing_limit = limit; + let cs = compose_story(&d, sid, &ComposeOptions::default()); + all_lines(&cs).iter().map(|l| l.baseline).collect::>() + }; + let (none, big, small) = (baselines(0.0), baselines(1000.0), baselines(20.0)); + assert_eq!(none.len(), 3); + let gaps = |b: &[f64]| (b[1] - b[0], b[2] - b[1]); + // No limit: equal steps. A big limit: all of it between paragraphs (here every line is one). + assert!((gaps(&none).0 - gaps(&none).1).abs() < 1e-6, "{none:?}"); + assert!((gaps(&big).0 - gaps(&big).1).abs() < 1e-6, "{big:?}"); + // A small limit: every paragraph gap takes the whole 20 pt, and the rest spreads over lines, + // so each gap is wider than the top-aligned one by at least 20 pt and narrower than with a big limit. + let top = { + let (d, sid, _) = doc_with(text, Rect::new(0.0, 0.0, 300.0, 400.0), ParaAttrs::default()); + all_lines(&compose_story(&d, sid, &ComposeOptions::default())).iter().map(|l| l.baseline).collect::>() + }; + let (natural, small_gaps, big_gaps) = (gaps(&top), gaps(&small), gaps(&big)); + assert!(small_gaps.0 >= natural.0 + 20.0 - 1e-6 && small_gaps.1 >= natural.1 + 20.0 - 1e-6, "{top:?} {small:?}"); + assert!(small_gaps.0 <= big_gaps.0 + 1e-6, "{small:?} {big:?}"); + assert!((none[2] - big[2]).abs() < 1e-6 && (none[2] - small[2]).abs() < 1e-6, "the last line stays at the bottom"); + // A paragraph of two lines keeps its leading when the limit absorbs the space. + let (mut d, sid, fid) = doc_with( + &[LOREM, "End."].join( + " +", + ), + Rect::new(0.0, 0.0, 300.0, 600.0), + ParaAttrs::default(), + ); + let o = &mut d.item_mut(fid).unwrap().text_frame_mut().unwrap().options; + o.vertical_justification = designcraft_doc::VerticalJustification::Justify; + o.vj_paragraph_spacing_limit = 10_000.0; + let cs = compose_story(&d, sid, &ComposeOptions::default()); + let lines = all_lines(&cs); + let first: Vec = lines.iter().filter(|l| l.para == 0).map(|l| l.baseline).collect(); + assert!(first.len() > 2, "LOREM runs over several lines"); + let lead = first[1] - first[0]; + assert!(first.windows(2).all(|w| (w[1] - w[0] - lead).abs() < 1e-6), "the paragraph's lines keep their leading: {first:?}"); + let last = lines.iter().find(|l| l.para == 1).unwrap().baseline; + assert!(last - first[first.len() - 1] > lead + 50.0, "the space went between the paragraphs"); +} + +/// Each object's wrap pushes the anchors after it down, so where each object lands depends on the +/// wraps of all those before it; every object still ends up wrapping the lines it hangs over. +#[test] +fn chained_anchored_objects_all_wrap_their_own_storys_lines() { + const OBJECTS: usize = 8; + let text = [LOREM; 12].join(" "); + let (mut d, sid, _) = doc_with(&text, Rect::new(0.0, 0.0, 300.0, 3000.0), ParaAttrs::default()); + let plain = compose_story(&d, sid, &ComposeOptions::default()); + let lines = all_lines(&plain); + assert!(lines.len() > 2 + 6 * OBJECTS); + let left = lines[0].x0; + // One object every six lines, each hanging from its anchor's baseline over the lines below; + // inserted last first so the earlier offsets still hold. + let ats: Vec = (0..OBJECTS).map(|k| lines[2 + 6 * k].range.start + 3).collect(); + for &at in ats.iter().rev() { + anchor_box(&mut d, sid, at, 0.0, 0.0, true, WrapMode::BoundingBox); + } + let cs = compose_story(&d, sid, &ComposeOptions::default()); + assert!(!cs.is_overset()); + let lines = all_lines(&cs); + let anchors: Vec = d.story(sid).unwrap().text.match_indices(designcraft_doc::OBJECT_MARK).map(|(i, _)| i).collect(); + let objects = &cs.frames[0].objects; + assert_eq!(objects.len(), OBJECTS); + for o in objects { + let anchor_line = lines.iter().find(|l| l.range.contains(&anchors[o.index])).unwrap(); + assert!((o.origin.y - anchor_line.baseline).abs() < 1e-6, "object {} at {}, anchor line at {}", o.index, o.origin.y, anchor_line.baseline); + let under = lines_in_band(&cs, o.origin.y, o.origin.y + 60.0); + assert!(under.len() >= 2); + assert!( + under.iter().all(|l| l.x0 >= left + 100.0 - 1e-6), + "object {} at {}: {:?}", + o.index, + o.origin.y, + under.iter().map(|l| (l.baseline, l.x0)).collect::>() + ); + } +} + #[test] fn anchored_object_without_wrap_leaves_layout_unchanged() { let long = [LOREM; 3].join(" "); @@ -7507,6 +9635,51 @@ fn cache_recomposes_when_the_baseline_grid_changes() { assert!((la.baseline - lb.baseline).abs() > 1.0, "{} {}", la.baseline, lb.baseline); } +/// A cache over another uses its compositions of the same state, and composes an older state +/// without replacing the other cache's composition of the current one. +#[test] +fn a_cache_over_another_reads_it_without_writing_to_it() { + let (old, sid, _) = doc_with(LOREM, Rect::new(0.0, 0.0, 200.0, 600.0), ParaAttrs::default()); + let mut new = old.clone(); + new.story_mut(sid).unwrap().rev += 1; + let base = Arc::new(Cache::new()); + let current = base.get(&new, sid, None); + let reader = Cache::over(Arc::clone(&base)); + assert!(reader.base().is_some_and(|b| Arc::ptr_eq(b, &base))); + assert!(Arc::ptr_eq(&reader.get(&new, sid, None), ¤t), "the base's composition is used"); + let earlier = reader.get(&old, sid, None); + assert!(!Arc::ptr_eq(&earlier, ¤t)); + assert!(Arc::ptr_eq(&reader.get(&old, sid, None), &earlier), "kept in the reader"); + assert!(Arc::ptr_eq(&base.get(&new, sid, None), ¤t), "the base keeps the current state's composition"); + assert!(base.composed_for(&old, sid).is_none(), "the base holds nothing of the older state"); +} + +/// The cross-reference and running-header indexes are built from compositions that depend on the +/// baseline grid and the font scope, so a change to either builds them again, in a cache and in a +/// cache over it. +#[test] +fn the_document_indexes_are_rebuilt_when_the_grid_or_font_scope_changes() { + let para = ParaAttrs { grid_align: Some(GridAlign::AllLines), ..Default::default() }; + let (d, _, _) = doc_with(LOREM, Rect::new(0.0, 0.0, 200.0, 600.0), para); + let base = Arc::new(Cache::new()); + let (xrefs, running) = (base.xref_index(&d), base.running_index(&d)); + let mut grid = d.clone(); + grid.settings.baseline_grid.increment = 30.0; + let mut scope = d.clone(); + scope.font_scope += 1; + for (changed, what) in [(&grid, "grid"), (&scope, "font scope")] { + let reader = Cache::over(Arc::clone(&base)); + assert!(!Arc::ptr_eq(&reader.xref_index(changed), &xrefs), "{what}: the base's cross-reference index is not used"); + assert!(!Arc::ptr_eq(&reader.running_index(changed), &running), "{what}: the base's running-header index is not used"); + let own = Cache::new(); + let (x, r) = (own.xref_index(&d), own.running_index(&d)); + assert!(!Arc::ptr_eq(&own.xref_index(changed), &x), "{what}: cross-reference index rebuilt"); + assert!(!Arc::ptr_eq(&own.running_index(changed), &r), "{what}: running-header index rebuilt"); + } + let reader = Cache::over(Arc::clone(&base)); + assert!(Arc::ptr_eq(&reader.xref_index(&d), &xrefs), "the same state uses the base's index"); +} + /// Two single pages 618 pt tall, top margins 36 and 48, each with an overset 11/13 story aligned /// to a baseline grid (start 0, increment 13) and a frame filling its margin box (bottom 582). fn grid_margin_doc(relative_to: designcraft_doc::GridRelative) -> (Document, [StoryId; 2]) { @@ -7751,6 +9924,160 @@ fn greek_text_gets_greek_hyphenation() { assert_eq!(hyphen::hyphen_points_in("ανθρωπος", &hyphen::Limits::default(), el), vec![2, 5]); } +/// An object's wrap pushes the text so that a later object's anchor goes on into the next frame +/// (Learn Skills Daily's long-document exercise: pictures anchored in headings through a 79-page +/// story). Each object is placed when its anchor line is set and wraps only the lines after it, +/// in the frame its anchor lands in: the layout doesn't depend on where an earlier composition put +/// the objects, and composing again gives the same lines. +#[test] +fn an_object_wraps_the_frame_its_anchor_lands_in_after_an_earlier_object_pushed_it_on() { + let text = [LOREM; 6].join(" "); + let mut d = Document::new(&NewDocument::default()); + let lid = d.default_layer(); + let (a, sid) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(0.0, 0.0, 300.0, 300.0), lid, &text, ParaFormat::default()).unwrap(); + let (b, _) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(320.0, 0.0, 620.0, 300.0), lid, "", ParaFormat::default()).unwrap(); + d.thread(a, b).unwrap(); + let plain = compose_story(&d, sid, &ComposeOptions::default()); + // The second object's anchor sits near the end of the first frame without wrap. + let late = plain.frames[0].lines.iter().rev().nth(2).unwrap().range.start + 2; + anchor_box(&mut d, sid, late, 0.0, 0.0, true, WrapMode::BoundingBox); + // The first, early in the first frame: 60 pt over its whole width pushes the later anchor on. + let early = plain.frames[0].lines[1].range.start + 2; + anchor_box(&mut d, sid, early, 0.0, 0.0, true, WrapMode::JumpObject); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + let late = late + OBJECT_LEN; + let anchor_frame = cs.frames.iter().position(|f| f.range.contains(&late) || f.range.end == late).unwrap(); + assert_eq!(anchor_frame, 1, "the later anchor went on into the second frame"); + // The first frame's lines under the first object's band keep the full measure (the second + // object is in the other frame); in the second frame, the lines under its object move right. + let left = cs.frames[0].lines[0].x0; + assert!(cs.frames[0].lines.iter().all(|l| (l.x0 - left).abs() < 1e-6)); + let f1 = &cs.frames[1]; + let (li, line) = f1.lines.iter().enumerate().find(|(_, l)| l.range.contains(&late)).unwrap(); + let under: Vec<_> = f1.lines[li + 1..].iter().filter(|l| l.baseline - l.ascent < line.baseline + 60.0).collect(); + assert!(!under.is_empty() && under.iter().all(|l| l.x0 >= f1.lines[0].x0 + 100.0 - 1e-6)); + assert_eq!(f1.objects.len(), 1); + // Deterministic: the same lines again. + assert_eq!(line_layout(&compose_story(&d, sid, &ComposeOptions::default())), line_layout(&cs)); +} + +#[test] +fn contour_intervals_preserve_the_gap_between_legs() { + let mut path = designcraft_geom::BezPath::new(); + path.move_to((0.0, 0.0)); + for p in [(40.0, 0.0), (40.0, 100.0), (30.0, 100.0), (30.0, 20.0), (10.0, 20.0), (10.0, 100.0), (0.0, 100.0)] { + path.line_to(p); + } + path.close_path(); + let c = Contour::of(&path, designcraft_geom::Affine::IDENTITY, 3.0).unwrap(); + assert_eq!(c.band_spans(50.0, 60.0), vec![(-3.0, 13.0), (27.0, 43.0)]); + assert_eq!(c.band_spans(5.0, 15.0), vec![(-3.0, 43.0)]); + let frame = designcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 35.0, 100.0)).to_bezpath(); + assert_eq!(c.within(&frame, designcraft_geom::Affine::IDENTITY).band_spans(50.0, 60.0), vec![(-3.0, 13.0), (27.0, 38.0)]); +} + +#[test] +fn contour_intervals_cover_the_whole_slanted_line_band() { + let mut path = designcraft_geom::BezPath::new(); + path.move_to((0.0, 0.0)); + for p in [(2.0, 0.0), (12.0, 10.0), (10.0, 10.0)] { + path.line_to(p); + } + path.close_path(); + let c = Contour::of(&path, designcraft_geom::Affine::IDENTITY, 0.0).unwrap(); + assert_eq!(c.band_spans(0.0, 10.0), vec![(0.0, 12.0)]); +} + +/// A vertical open path blocks the offset on both sides of it, and splits the line with no +/// offset; clipped to a frame that holds it, it still does. +#[test] +fn a_vertical_open_path_keeps_its_offset() { + let mut path = designcraft_geom::BezPath::new(); + path.move_to((10.0, 0.0)); + path.line_to((10.0, 100.0)); + let c = Contour::of(&path, designcraft_geom::Affine::IDENTITY, 3.0).unwrap(); + assert_eq!(c.band_spans(40.0, 50.0), vec![(7.0, 13.0)]); + let frame = designcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 20.0, 100.0)).to_bezpath(); + assert_eq!(c.within(&frame, designcraft_geom::Affine::IDENTITY).band_spans(40.0, 50.0), vec![(7.0, 13.0)]); + let c = Contour::of(&path, designcraft_geom::Affine::IDENTITY, 0.0).unwrap(); + assert_eq!(c.band_spans(40.0, 50.0), vec![(10.0, 10.0)]); +} + +/// An outline counts only where its frame shows it: a part of it in a notch of the frame blocks +/// nothing, even where the frame covers the same x positions lower in the same line band. +#[test] +fn a_clipped_contour_blocks_only_what_its_frame_shows() { + let poly = |pts: &[(f64, f64)]| { + let mut p = designcraft_geom::BezPath::new(); + p.move_to(pts[0]); + for &q in &pts[1..] { + p.line_to(q); + } + p.close_path(); + p + }; + let id = designcraft_geom::Affine::IDENTITY; + // An L-shaped frame with a notch at x 10..40 above y = 6. + let frame = poly(&[(0.0, 0.0), (10.0, 0.0), (10.0, 6.0), (40.0, 6.0), (40.0, 10.0), (0.0, 10.0)]); + // An outline in the notch only. + let c = Contour::of(&poly(&[(20.0, 0.0), (40.0, 0.0), (40.0, 4.0), (20.0, 4.0)]), id, 0.0).unwrap(); + assert_eq!(c.band_spans(0.0, 10.0), vec![(20.0, 40.0)]); + assert_eq!(c.within(&frame, id).band_spans(0.0, 10.0), Vec::<(f64, f64)>::new(), "the frame shows none of it"); + // Reaching below the notch, where the frame shows it from y = 6 to 8. + let c = Contour::of(&poly(&[(20.0, 0.0), (40.0, 0.0), (40.0, 8.0), (20.0, 8.0)]), id, 0.0).unwrap(); + assert_eq!(c.within(&frame, id).band_spans(0.0, 10.0), vec![(20.0, 40.0)]); + // A band that crosses both shapes whole keeps their common part, widened by the offset. + let c = Contour::of(&poly(&[(5.0, -10.0), (30.0, -10.0), (30.0, 20.0), (5.0, 20.0)]), id, 2.0).unwrap(); + assert_eq!(c.within(&frame, id).band_spans(7.0, 9.0), vec![(3.0, 32.0)]); + // A frame in more than 128 pieces across the band takes the common part of the projections. + let mut fragmented = frame.clone(); + for i in 0..200 { + let x = 1000.0 + 2.0 * f64::from(i); + fragmented.extend(poly(&[(x, 0.0), (x + 1.0, 0.0), (x + 1.0, 10.0), (x, 10.0)]).elements().iter().copied()); + } + let c = Contour::of(&poly(&[(20.0, 0.0), (40.0, 0.0), (40.0, 4.0), (20.0, 4.0)]), id, 0.0).unwrap(); + assert_eq!(c.within(&fragmented, id).band_spans(0.0, 10.0), vec![(20.0, 40.0)]); + // So does a frame and an outline too detailed to compare within a line's budget: here 2,000 + // points on the frame's bottom edge and on the outline's top edge. + let mut detailed = vec![(0.0, 0.0), (10.0, 0.0), (10.0, 6.0), (40.0, 6.0), (40.0, 10.0)]; + detailed.extend((1..2000).map(|i| (40.0 - 0.02 * f64::from(i), 10.0))); + detailed.push((0.0, 10.0)); + let mut notch: Vec<(f64, f64)> = (0..2000).map(|i| (20.0 + 0.01 * f64::from(i), 0.0)).collect(); + notch.extend([(40.0, 0.0), (40.0, 4.0), (20.0, 4.0)]); + let c = Contour::of(&poly(¬ch), id, 0.0).unwrap(); + assert_eq!(c.within(&poly(&detailed), id).band_spans(0.0, 10.0), vec![(20.0, 40.0)]); +} + +/// Edges far above or below a line band cost a clipped contour nothing there: an outline with +/// 7,000 points well below the band still gets the exact spans, not the projections' common part. +#[test] +fn a_clipped_contours_budget_counts_only_edges_in_the_band() { + let poly = |pts: &[(f64, f64)]| { + let mut p = designcraft_geom::BezPath::new(); + p.move_to(pts[0]); + for &q in &pts[1..] { + p.line_to(q); + } + p.close_path(); + p + }; + let id = designcraft_geom::Affine::IDENTITY; + // The L-shaped frame of the test above, with its notch at x 10..40 above y = 6. + let frame = poly(&[(0.0, 0.0), (10.0, 0.0), (10.0, 6.0), (40.0, 6.0), (40.0, 10.0), (0.0, 10.0)]); + // An outline in the notch and to the right of the frame, with 40 teeth along its top in the + // band and a 7,000-point zigzag along its bottom at y = 200. + let mut pts = vec![(20.0, 0.0)]; + for i in 0..40 { + let x = 40.0 + 0.5 * f64::from(i); + pts.extend([(x, 0.0), (x + 0.25, 0.5)]); + } + pts.push((60.0, 0.0)); + pts.extend((0..7000).map(|i| (60.0 - 10.0 * f64::from(i) / 6999.0, if i % 2 == 0 { 200.0 } else { 201.0 }))); + pts.extend([(50.0, 4.0), (20.0, 4.0)]); + let c = Contour::of(&poly(&pts), id, 0.0).unwrap(); + assert_eq!(c.within(&frame, id).band_spans(0.0, 10.0), Vec::<(f64, f64)>::new(), "the frame shows none of it"); +} + /// Rule Above's offset runs from the first line's baseline up to the rule's bottom edge, as in /// InDesign: a rule set clear of the cap height sits between the rows, not across the row above /// (an INDD project list whose rules crossed the previous paragraph's text). @@ -7845,6 +10172,205 @@ fn an_rtl_first_line_indent_is_at_the_right_edge() { assert!((left_edge(lines[1]) - (rect.x0 + 10.0 * MM)).abs() < 1.0, "left to right, wrapped line indented: {}", left_edge(lines[1])); } +/// A story threaded through several frames anchored in one host story asks for the host's +/// composition once, not once per frame. +#[test] +fn anchored_frames_in_one_host_compose_it_once() { + let mut d = Document::new(&NewDocument { pages: 1, ..Default::default() }); + let lid = d.default_layer(); + let body = "One.\nTwo.\nThree.\nFour."; + let (_, sid) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(36.0, 36.0, 400.0, 400.0), lid, body, ParaFormat::default()).unwrap(); + let nsid = StoryId(d.alloc()); + let ids: Vec = (0..3).map(|_| ItemId(d.alloc())).collect(); + let mut story = Story::with_text(nsid, "Note", ParaFormat::default()); + story.frames.extend(&ids); + d.stories.insert(nsid, Arc::new(story)); + for (k, &nid) in ids.iter().enumerate() { + let mut note = designcraft_doc::Item::new( + nid, + lid, + designcraft_doc::Shape::Rectangle, + designcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 60.0, 40.0)), + ); + note.content = Content::Text(designcraft_doc::TextFrame { story: nsid, options: Default::default() }); + let at = body.find(["Two", "Three", "Four"][k]).unwrap(); + d.story_mut(sid).unwrap().insert_object(at, designcraft_doc::AnchoredObject::new(note, Default::default())); + } + let mut asked = 0; + let placed = placed::placements(&d, nsid, &mut |h| { + asked += 1; + Arc::new(compose_story(&d, h, &ComposeOptions::default())) + }); + assert_eq!(asked, 1, "the host is composed once"); + assert_eq!(placed.len(), 3, "{placed:?}"); + // The cache and the uncached path agree on where the frames go. + assert_eq!(Cache::new().get(&d, nsid, None).frames.len(), compose_story(&d, nsid, &ComposeOptions::default()).frames.len()); +} + +/// A text frame anchored in a text frame that is itself anchored in a frame on page 1 is placed +/// through both hosts: on page 1, at the inner object's spot in the outer anchored frame. +#[test] +fn a_frame_anchored_in_an_anchored_frame_is_placed_through_both_hosts() { + let mut d = Document::new(&NewDocument { pages: 1, ..Default::default() }); + let lid = d.default_layer(); + let body = "One.\nTwo.\nThree."; + let (bf, sid) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(36.0, 36.0, 400.0, 400.0), lid, body, ParaFormat::default()).unwrap(); + let frame = |d: &mut Document, text: &str, w: f64, h: f64| { + let (fid, fsid) = (ItemId(d.alloc()), StoryId(d.alloc())); + let mut story = Story::with_text(fsid, text, ParaFormat::default()); + story.frames.push(fid); + d.stories.insert(fsid, Arc::new(story)); + let mut it = + designcraft_doc::Item::new(fid, lid, designcraft_doc::Shape::Rectangle, designcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, w, h))); + it.content = Content::Text(designcraft_doc::TextFrame { story: fsid, options: Default::default() }); + (it, fsid) + }; + let (outer, osid) = frame(&mut d, "Outer text", 200.0, 100.0); + let (inner, isid) = frame(&mut d, "Inner", 80.0, 30.0); + let (outer_id, inner_id) = (outer.id, inner.id); + d.story_mut(osid).unwrap().insert_object("Outer ".len(), designcraft_doc::AnchoredObject::new(inner, Default::default())); + d.story_mut(sid).unwrap().insert_object(body.find("Two").unwrap(), designcraft_doc::AnchoredObject::new(outer, Default::default())); + + let placed = placed::placements(&d, isid, &mut |h| Arc::new(compose_story(&d, h, &ComposeOptions::default()))); + assert_eq!(placed.len(), 1, "{placed:?}"); + let (id, p) = placed[0]; + assert_eq!((id, p.spread), (inner_id, SpreadRef::Doc(0))); + // The body frame's object, then the outer frame's object, each at its composed origin. + let host = compose_story(&d, sid, &ComposeOptions::default()); + let o1 = &host.frame(bf).unwrap().objects[0]; + let mid = compose_story(&d, osid, &ComposeOptions::default()); + let o2 = &mid.frame(outer_id).unwrap().objects[0]; + let want = d.item(bf).unwrap().xf + * Affine::translate(o1.origin.to_vec2()) + * d.anchored_item(outer_id).unwrap().xf + * Affine::translate(o2.origin.to_vec2()); + let (got, want) = (p.xf.as_coeffs(), want.as_coeffs()); + assert!(got.iter().zip(want).all(|(a, b)| (a - b).abs() < 1e-9), "{got:?} != {want:?}"); + assert_eq!(frame_specs_placed(&d, isid, &placed)[0].page, Some(0)); + // The cache places it the same way. + assert_eq!(Cache::new().get(&d, isid, None).frames.len(), 1); +} + +/// An unplaced `w` × `h` text frame showing a new story of `text`, ready to anchor. +fn anchored_text_frame(d: &mut Document, text: &str, w: f64, h: f64) -> (designcraft_doc::Item, StoryId) { + let lid = d.default_layer(); + let (fid, fsid) = (ItemId(d.alloc()), StoryId(d.alloc())); + let mut story = Story::with_text(fsid, text, ParaFormat::default()); + story.frames.push(fid); + d.stories.insert(fsid, Arc::new(story)); + let mut it = + designcraft_doc::Item::new(fid, lid, designcraft_doc::Shape::Rectangle, designcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, w, h))); + it.content = Content::Text(designcraft_doc::TextFrame { story: fsid, options: Default::default() }); + (it, fsid) +} + +/// A one-page document whose body frame holds `outer` anchored before its second line. Returns +/// the body frame and the body story's composition. +fn body_holding(d: &mut Document, outer: designcraft_doc::Item) -> (ItemId, ComposedStory) { + let lid = d.default_layer(); + let body = "One.\nTwo.\nThree."; + let (bf, sid) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(36.0, 36.0, 400.0, 400.0), lid, body, ParaFormat::default()).unwrap(); + d.story_mut(sid).unwrap().insert_object(body.find("Two").unwrap(), designcraft_doc::AnchoredObject::new(outer, Default::default())); + (bf, compose_story(d, sid, &ComposeOptions::default())) +} + +/// `isid`'s one frame, `inner`, is placed on page 1 with parent space `want`, and the cache +/// composes it there. +fn assert_placed_on_page_one(d: &Document, isid: StoryId, inner: ItemId, want: Affine) { + let placed = placed::placements(d, isid, &mut |h| Arc::new(compose_story(d, h, &ComposeOptions::default()))); + assert_eq!(placed.len(), 1, "{placed:?}"); + let (id, p) = placed[0]; + assert_eq!((id, p.spread), (inner, SpreadRef::Doc(0))); + let (got, want) = (p.xf.as_coeffs(), want.as_coeffs()); + assert!(got.iter().zip(want).all(|(a, b)| (a - b).abs() < 1e-9), "{got:?} != {want:?}"); + assert_eq!(frame_specs_placed(d, isid, &placed)[0].page, Some(0)); + assert_eq!(Cache::new().get(d, isid, None).frames.len(), 1); +} + +/// A text frame anchored in an anchored text frame that is a member of an anchored group with a +/// rotation and a scale is placed through the group's transform and the member's own. +#[test] +fn a_frame_anchored_in_a_grouped_anchored_frame_is_placed_through_the_group() { + let mut d = Document::new(&NewDocument { pages: 1, ..Default::default() }); + let (mut outer, osid) = anchored_text_frame(&mut d, "Outer text", 200.0, 100.0); + let (inner, isid) = anchored_text_frame(&mut d, "Inner", 80.0, 30.0); + let (outer_id, inner_id) = (outer.id, inner.id); + outer.xf = Affine::translate((12.0, 7.0)); + d.story_mut(osid).unwrap().insert_object("Outer ".len(), designcraft_doc::AnchoredObject::new(inner, Default::default())); + let mut g = + designcraft_doc::Item::new(ItemId(d.alloc()), d.default_layer(), designcraft_doc::Shape::Group, designcraft_geom::PathData::default()); + g.content = Content::Group { items: vec![Arc::new(outer)] }; + g.xf = Affine::rotate(0.25) * Affine::scale(1.25); + let (gid, gxf) = (g.id, g.xf); + let (bf, host) = body_holding(&mut d, g); + + let o1 = &host.frame(bf).unwrap().objects[0]; + // The composed group keeps its rotation and scale; its offset puts its box at the object's origin. + let gxf_placed = o1.object.item.xf; + assert_eq!((o1.object.item.id, gxf_placed.as_coeffs()[..4].to_vec()), (gid, gxf.as_coeffs()[..4].to_vec())); + let mid = compose_story(&d, osid, &ComposeOptions::default()); + let o2 = &mid.frame(outer_id).unwrap().objects[0]; + let want = d.text_xf(d.item(bf).unwrap()) + * Affine::translate(o1.origin.to_vec2()) + * gxf_placed + * d.text_xf(d.anchored_item(outer_id).unwrap()) + * Affine::translate(o2.origin.to_vec2()); + assert_placed_on_page_one(&d, isid, inner_id, want); +} + +/// A text frame anchored in a footnote of an anchored text frame is placed through the footnote's +/// spot in that frame as well as both hosts. +#[test] +fn a_frame_anchored_in_a_footnote_of_an_anchored_frame_is_placed_through_the_footnote() { + let mut d = Document::new(&NewDocument { pages: 1, ..Default::default() }); + let (outer, osid) = anchored_text_frame(&mut d, "Outer text", 200.0, 120.0); + let (inner, isid) = anchored_text_frame(&mut d, "Inner", 80.0, 30.0); + let (outer_id, inner_id) = (outer.id, inner.id); + let st = d.story_mut(osid).unwrap(); + st.insert_note("Outer".len(), "Note text", ParaFormat::default()); + Arc::make_mut(&mut st.notes[0]).text.insert_object("Note ".len(), designcraft_doc::AnchoredObject::new(inner, Default::default())); + let (bf, host) = body_holding(&mut d, outer); + + let o1 = &host.frame(bf).unwrap().objects[0]; + let mid = compose_story(&d, osid, &ComposeOptions::default()); + let note = &mid.frame(outer_id).unwrap().notes[0]; + let o2 = ¬e.text.frames[0].objects[0]; + let want = d.text_xf(d.item(bf).unwrap()) + * Affine::translate(o1.origin.to_vec2()) + * d.text_xf(d.anchored_item(outer_id).unwrap()) + * Affine::translate(note.origin.to_vec2()) + * Affine::translate(o2.origin.to_vec2()); + assert_placed_on_page_one(&d, isid, inner_id, want); +} + +/// A text frame anchored in a table cell of an anchored text frame is placed through the cell's +/// spot in that frame as well as both hosts. +#[test] +fn a_frame_anchored_in_a_table_cell_of_an_anchored_frame_is_placed_through_the_cell() { + let mut d = Document::new(&NewDocument { pages: 1, ..Default::default() }); + let (outer, osid) = anchored_text_frame(&mut d, "Outer text", 200.0, 150.0); + let (inner, isid) = anchored_text_frame(&mut d, "Inner", 80.0, 30.0); + let (outer_id, inner_id) = (outer.id, inner.id); + let mut table = designcraft_doc::Table::new(77, 1, 1, 0, 0, 180.0); + table.cells[0].text.insert(0, "Cell "); + table.cells[0].text.insert_object("Cell ".len(), designcraft_doc::AnchoredObject::new(inner, Default::default())); + let st = d.story_mut(osid).unwrap(); + let end = st.len(); + st.insert_table(end, table); + let (bf, host) = body_holding(&mut d, outer); + + let o1 = &host.frame(bf).unwrap().objects[0]; + let mid = compose_story(&d, osid, &ComposeOptions::default()); + let cell = &mid.frame(outer_id).unwrap().tables[0].cells[0]; + let o2 = &cell.text.frames[0].objects[0]; + let want = d.text_xf(d.item(bf).unwrap()) + * Affine::translate(o1.origin.to_vec2()) + * d.text_xf(d.anchored_item(outer_id).unwrap()) + * Affine::translate(cell.origin.to_vec2()) + * Affine::translate(o2.origin.to_vec2()); + assert_placed_on_page_one(&d, isid, inner_id, want); +} + /// A marginal note (an anchored text frame, Only Align First Line to Grid, 9/10) hangs 15 pt /// above its anchor's baseline on a right-hand page. It composes against the document grid where /// it is placed: its first line moves down onto the grid line, the second follows 10 pt below, @@ -7932,3 +10458,34 @@ fn anchored_text_frames_compose_against_the_grid_where_they_are_placed() { Arc::make_mut(&mut d.spreads[1]).pages[1].side = designcraft_doc::PageSide::Left; assert!(!Arc::ptr_eq(&before, &cache.get(&d, nsid, None))); } + +/// A cross-reference's text breaks at its spaces like ordinary text (it is real text in +/// InDesign), not inside words; edited text whose destination is gone shows its saved page. +#[test] +fn cross_reference_text_breaks_at_its_spaces() { + let (mut d, sid, _) = doc_with("See X.", Rect::new(36.0, 36.0, 110.0, 400.0), ParaAttrs::default()); + let at = d.story(sid).unwrap().text.find('X').unwrap(); + let st = d.story_mut(sid).unwrap(); + st.delete(at..at + 1); + st.insert_xref( + at, + designcraft_doc::CrossRef { + text: Some("Page : Bove, Vinny. \"Advent Horizon.\" 1996. Volume 6, issue 5.".into()), + page: Some("7".into()), + ..Default::default() + }, + ); + let x = d.story(sid).unwrap().xrefs[0].clone(); + let shown = crate::xref::xref_text(&d, &x, None); + assert_eq!(shown, "Page 7: Bove, Vinny. \"Advent Horizon.\" 1996. Volume 6, issue 5."); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + let lines: Vec = + cs.frames[0].lines.iter().map(|l| l.glyphs.iter().filter(|g| g.visible).map(|g| g.rendered_char).collect::()).collect(); + assert!(lines.len() > 3, "{lines:?}"); + let words: Vec<&str> = format!("See {shown}.").leak().split(' ').collect(); + for l in &lines { + for w in l.split(' ').filter(|w| !w.is_empty()) { + assert!(words.contains(&w), "a line breaks inside a word: {w:?} in {lines:?}"); + } + } +} diff --git a/crates/compose/src/vars.rs b/crates/compose/src/vars.rs index 945d8bd04..bd9e32ccd 100644 --- a/crates/compose/src/vars.rs +++ b/crates/compose/src/vars.rs @@ -53,6 +53,32 @@ pub(crate) fn place(doc: &Document, cs: &ComposedStory, pos: usize) -> Option<(u Some((doc.first_page_of_spread(si) + pi, ((b.y0 + baseline) * 10.0) as i64, ((b.x0 + x) * 10.0) as i64)) } +/// A paragraph or run a running header may show: where it starts ([`place`]), its story and byte +/// there, and its text. +struct Hit { + at: (usize, i64, i64), + story: StoryId, + pos: usize, + text: String, +} + +/// (page, text) in the order running headers read a page: text order within a story (a story's +/// second column comes after its first, however high its entries sit), and stories by where their +/// first entry on the page is (top to bottom, then left to right). +fn in_page_order(hits: Vec) -> Vec<(usize, String)> { + // Each story on a page is placed by its first hit there in text order (not its highest hit, + // which in a later column could put the whole story ahead of another). + let mut first: HashMap<(usize, StoryId), (usize, (i64, i64))> = HashMap::new(); + for h in &hits { + let (page, y, x) = h.at; + first.entry((page, h.story)).and_modify(|f| *f = (*f).min((h.pos, (y, x)))).or_insert((h.pos, (y, x))); + } + let mut hits: Vec<_> = + hits.into_iter().map(|h| (h.at.0, first.get(&(h.at.0, h.story)).map_or((h.at.1, h.at.2), |f| f.1), h.story, h.pos, h.text)).collect(); + hits.sort_by_key(|a| (a.0, a.1, a.2.0, a.3)); + hits.into_iter().map(|(page, _, _, _, text)| (page, text)).collect() +} + impl RunningIndex { /// Index the paragraphs / runs that running-header variables refer to. `get` composes a story /// (normally through the cache); stories that themselves contain running headers are skipped. @@ -65,7 +91,8 @@ impl RunningIndex { _ => None, }) .collect(); - let mut hits: HashMap<(String, bool), Vec<((usize, i64, i64), String)>> = HashMap::new(); + // (place, story, byte) of each paragraph or run, with its text. + let mut hits: HashMap<(String, bool), Vec> = HashMap::new(); if wanted.is_empty() { return RunningIndex::default(); } @@ -90,7 +117,7 @@ impl RunningIndex { continue; } if let Some(at) = place(doc, &cs, r.start) { - hits.entry(key).or_default().push((at, text)); + hits.entry(key).or_default().push(Hit { at, story: *sid, pos: r.start, text }); } } } @@ -105,16 +132,15 @@ impl RunningIndex { continue; } if let Some(at) = place(doc, &cs, r.start) { - hits.entry(key).or_default().push((at, text)); + hits.entry(key).or_default().push(Hit { at, story: *sid, pos: r.start, text }); } } } } let mut map = HashMap::new(); - for (key, mut v) in hits { - v.sort_by_key(|(at, _)| *at); + for (key, v) in hits { let mut pages: BTreeMap = BTreeMap::new(); - for ((page, ..), text) in v { + for (page, text) in in_page_order(v) { pages.entry(page).and_modify(|e| e.1 = text.clone()).or_insert((text.clone(), text)); } map.insert(key, pages); @@ -134,10 +160,18 @@ impl RunningIndex { /// Values of every variable on `page`. pub fn values(doc: &Document, page: Option, running: Option<&RunningIndex>) -> Vec { + values_shown(doc, page, false, running) +} + +/// [`values`] as text shows them: on a parent page itself (`parent`, with no `page`), a running +/// header has no entries of its own and shows which variable sits there, ``, as InDesign +/// does. Elsewhere without a page (the pasteboard), it is its text before and after. +pub fn values_shown(doc: &Document, page: Option, parent: bool, running: Option<&RunningIndex>) -> Vec { doc.text_variables .iter() .enumerate() .map(|(i, v)| match &v.kind { + VarKind::RunningHeader { .. } if parent && page.is_none() => format!("<{}>", v.name), VarKind::RunningHeader { style, use_, character } => { let body = match (running, page) { (Some(r), Some(p)) => r.value(style, *character, *use_, p), diff --git a/crates/compose/src/warichu.rs b/crates/compose/src/warichu.rs index 8418faac4..f0bedf183 100644 --- a/crates/compose/src/warichu.rs +++ b/crates/compose/src/warichu.rs @@ -108,6 +108,11 @@ fn trace_counts(take: &[Vec], n: usize, m: usize) -> Option> { (s == m).then_some(counts) } +/// Longest warichu run split exactly. The exact split tries every length for every line start, so +/// its work grows with the square of the run's length; a longer run (from a document) is split by +/// [`split_proportional`] in one pass instead. +const MAX_EXACT_SPLIT_GLYPHS: usize = 512; + /// Glyph counts for `n` lines. Minimises the widest line, and the first and last lines keep their /// break minimums. One line when no split satisfies them. fn split_even(advs: &[f64], n: usize, before: usize, after: usize) -> Vec { @@ -121,6 +126,9 @@ fn split_even(advs: &[f64], n: usize, before: usize, after: usize) -> Vec for (i, a) in advs.iter().enumerate() { pref[i + 1] = pref[i] + *a; } + if m > MAX_EXACT_SPLIT_GLYPHS { + return split_proportional(&pref, n, before, after); + } let mut best = vec![vec![f64::INFINITY; m + 1]; n + 1]; let mut take = vec![vec![0_usize; m + 1]; n + 1]; for s in 0..m { @@ -160,6 +168,34 @@ fn split_even(advs: &[f64], n: usize, before: usize, after: usize) -> Vec trace_counts(&take, n, m).unwrap_or_else(|| vec![m]) } +/// [`split_even`] for a long run: each line ends where the run's advance reaches its share of the +/// total, moved where needed so every line keeps a glyph and the first and last lines their break +/// minimums. `pref` holds the running advance (`pref[i]`: the first `i` glyphs). One line when the +/// minimums can't all be kept. +fn split_proportional(pref: &[f64], n: usize, before: usize, after: usize) -> Vec { + let m = pref.len() - 1; + if before.saturating_add(after).saturating_add(n - 2) > m { + return vec![m]; + } + let total = pref[m]; + let mut counts = Vec::with_capacity(n); + let mut prev = 0; + for k in 1..n { + let target = total * k as f64 / n as f64; + let at = pref.partition_point(|p| *p < target); + let lo = prev + if k == 1 { before } else { 1 }; + // The lines after this one: one glyph each, the last its minimum. + let hi = m - after - (n - 1 - k); + // A wide glyph can straddle the target: take whichever valid break is closer to it. + let (above, below) = (at.clamp(lo, hi), at.saturating_sub(1).clamp(lo, hi)); + let at = if (target - pref[below]).abs() < (pref[above] - target).abs() { below } else { above }; + counts.push(at - prev); + prev = at; + } + counts.push(m - prev); + counts +} + fn restore(line: &mut [PlacedGlyph], members: &[usize], saved: &[(f64, f64, f64, f64)]) { for (i, &k) in members.iter().enumerate() { let Some((y, adv, sx, sy)) = saved.get(i).copied() else { continue }; @@ -283,7 +319,7 @@ fn shift_non_member_glyphs(line: &mut [PlacedGlyph], members: &[usize], old_xs: if g.x >= old_right - 1e-6 { g.x += delta; } else if g.x >= old_x0 - 1e-6 - && let Some(anchor) = placed.iter().rev().find(|p| p.0 <= g.x + 1e-6) + && let Some(anchor) = placed.partition_point(|p| p.0 <= g.x + 1e-6).checked_sub(1).map(|i| placed[i]) { // A mark drawn with the run (a tab leader is not: it sits before old_x0) keeps its // offset from the glyph it was attached to, in the scaled line. @@ -302,4 +338,46 @@ mod tests { assert_eq!(line_count(10, 3, 1, usize::MAX), 1); assert_eq!(line_count(10, 2, 3, 3), 2); } + + /// A run longer than the exact split's limit is split in one pass: the lines cover the run, + /// keep their minimums and come out about even. + #[test] + fn a_long_run_is_split_in_one_pass() { + let m = 200_000; + let advs = vec![1.0; m]; + let t = std::time::Instant::now(); + let counts = split_even(&advs, 16, 3, 5); + assert!(t.elapsed().as_secs() < 5, "{:?}", t.elapsed()); + assert_eq!(counts.len(), 16); + assert_eq!(counts.iter().sum::(), m); + assert!(counts.iter().all(|c| c.abs_diff(m / 16) <= 1), "{counts:?}"); + + // Minimums that the even shares don't meet move the breaks. + let mut advs = vec![0.0; MAX_EXACT_SPLIT_GLYPHS + 10]; + advs[0] = 1000.0; + let counts = split_even(&advs, 3, 4, 7); + assert_eq!(counts.iter().sum::(), advs.len()); + assert!(counts[0] >= 4 && counts[2] >= 7 && counts[1] >= 1, "{counts:?}"); + // Minimums that can't all be kept leave one line. + assert_eq!(split_even(&advs, 3, advs.len(), 1), vec![advs.len()]); + } + + /// Short runs keep the exact split that minimises the widest line. + #[test] + fn a_long_run_breaks_at_the_closer_side_of_a_wide_glyph() { + let mut advs = vec![1.0; 250]; + advs.push(1000.0); + advs.extend([1.0; 262]); + let mut pref = vec![0.0]; + for a in &advs { + pref.push(pref.last().unwrap() + a); + } + assert_eq!(split_proportional(&pref, 3, 1, 1), vec![250, 1, 262]); + } + + #[test] + fn a_short_run_is_split_exactly() { + assert_eq!(split_even(&[1.0, 1.0, 1.0, 1.0, 4.0], 2, 1, 1), vec![4, 1]); + assert_eq!(split_even(&[1.0; 6], 3, 1, 1), vec![2, 2, 2]); + } } diff --git a/crates/compose/src/wrap.rs b/crates/compose/src/wrap.rs index e1cdc5fa7..1424d9dd5 100644 --- a/crates/compose/src/wrap.rs +++ b/crates/compose/src/wrap.rs @@ -12,16 +12,28 @@ //! that come after the line holding its anchor; that line and the lines before it are never //! wrapped by it (an inline object sits in its line and wraps none of its own story). The story //! is composed again with the objects where the previous pass placed them until they stop -//! moving, at most [`MAX_PASSES`] more times. +//! moving. An object's wrap can push the anchors of the objects after it, so a chain of n such +//! objects needs n + 1 more compositions: the k-th pass places the (k + 1)-th object where the +//! wraps before it leave its anchor, and the last pass wraps around the last object. The story +//! is composed at most that many more times (at least [`MIN_PASSES`]), and never more than +//! [`MAX_PASSES`]. -use designcraft_doc::{AnchorPosition, AnchoredObject, Document, Item, OBJECT_MARK, PageSide, SpreadRef, Story, StoryId, WrapMode}; +use designcraft_doc::{AnchorPosition, AnchoredObject, Document, Item, OBJECT_MARK, PageSide, SpreadRef, Story, StoryId}; use designcraft_geom::Affine; +use crate::reuse::{Reuse, Trace}; use crate::{ComposeOptions, ComposedStory, Exclusion, FrameSpec}; -/// Extra compositions of a story with its own anchored objects' wrap; a layout that keeps moving -/// its objects (keep options, vertical justification) stops here. -pub(crate) const MAX_PASSES: usize = 4; +/// Most extra compositions of a story with its own anchored objects' wrap, however many objects +/// it has; a layout that keeps moving its objects (keep options, vertical justification) stops +/// sooner, after one per object and one more (but never fewer than [`MIN_PASSES`]). +pub(crate) const MAX_PASSES: usize = 64; + +/// Fewest extra compositions allowed before giving up on a layout that keeps moving: a single +/// object that keep options or vertical justification move still gets the room it had before. +const MIN_PASSES: usize = 4; +// `clamp` needs min <= max. +const _: () = assert!(MIN_PASSES <= MAX_PASSES); /// How far an obstacle may move between passes and still count as settled (points). const SETTLED: f64 = 0.01; @@ -35,10 +47,13 @@ pub(crate) struct Obstacle<'a> { xf: Affine, /// Story byte of the anchor, for obstacles in their own story. anchor: Option, + /// Baseline of the line holding the anchor, for obstacles in their own story. + anchor_baseline: Option, } +/// The wrap may be set on the frame or on its placed graphic (Direct Selection). fn wraps(o: &AnchoredObject) -> bool { - o.item.wrap.mode != WrapMode::None && !o.item.hidden + o.item.has_wrap() && !o.item.hidden } /// Does `story` have an anchored object whose wrap can push text? @@ -115,7 +130,8 @@ pub(crate) fn obstacles<'a>(doc: &Document, story: &'a Story, cs: &ComposedStory } else { None }; - out.push(Obstacle { spread: loc.spread, item: &obj.item, xf, anchor }); + let anchor_baseline = anchor.and_then(|_| ft.lines.get(o.line)).map(|l| l.baseline); + out.push(Obstacle { spread: loc.spread, item: &obj.item, xf, anchor, anchor_baseline }); } } out @@ -141,11 +157,12 @@ pub(crate) fn exclusions(doc: &Document, specs: &[FrameSpec], obs: &[Obstacle]) let a = spec.area; for ob in obs.iter().filter(|o| o.spread == loc.spread) { let mut found = Vec::new(); - crate::wrap_obstacles(ob.item, ob.xf, inv, spec.id, &left, 0, &mut found); + crate::wrap_obstacles(doc, ob.item, ob.xf, inv, spec.id, &left, 0, &mut found); for mut e in found { let r = e.rect; if r.is_finite() && r.x0 < a.x1 && r.x1 > a.x0 && r.y0 < a.y1 && r.y1 > a.y0 { e.after = ob.anchor; + e.anchor_baseline = ob.anchor_baseline; ex.push(e); } } @@ -181,7 +198,22 @@ fn settled(a: &[Vec], b: &[Vec]) -> bool { /// Compose story `sid` with the wrapping anchored objects of `others` (compositions of its /// [`neighbours`]) and of its own. pub(crate) fn compose_among(doc: &Document, sid: StoryId, opts: &ComposeOptions, others: &[&ComposedStory]) -> ComposedStory { - let Some(st) = doc.story(sid) else { return ComposedStory { story: sid, ..Default::default() } }; + compose_among_traced(doc, sid, opts, others, None).0 +} + +/// [`compose_among`], also giving the trace for composing the story again after an edit, when +/// the composition leaves one ([`crate::reuse`]). `before` is the story before an edit with its +/// composition among the same `others` and that composition's trace: the paragraphs the edit +/// cannot change are taken from it. A story with wrapping anchored objects of its own is +/// composed whole and leaves no trace. +pub(crate) fn compose_among_traced( + doc: &Document, + sid: StoryId, + opts: &ComposeOptions, + others: &[&ComposedStory], + before: Option>, +) -> (ComposedStory, Option) { + let Some(st) = doc.story(sid) else { return (ComposedStory { story: sid, ..Default::default() }, None) }; let mut specs = crate::frame_specs_placed(doc, sid, &opts.placed); if !others.is_empty() { let mut obs = Vec::new(); @@ -195,12 +227,13 @@ pub(crate) fn compose_among(doc: &Document, sid: StoryId, opts: &ComposeOptions, specs = with_exclusions(&specs, &added); } } - let mut out = crate::compose(doc, st, &specs, opts); if !has_wrapping_objects(st) { - return out; + return crate::compose_traced(doc, st, &specs, opts, before); } + let mut out = crate::compose(doc, st, &specs, opts); + let own = st.objects.iter().filter(|o| wraps(o) && !matches!(o.position, AnchorPosition::Inline { .. })).count(); let mut prev = vec![Vec::new(); specs.len()]; - for _ in 0..MAX_PASSES { + for _ in 0..(own + 1).clamp(MIN_PASSES, MAX_PASSES) { let added = exclusions(doc, &specs, &obstacles(doc, st, &out, true)); if settled(&added, &prev) { break; @@ -208,5 +241,5 @@ pub(crate) fn compose_among(doc: &Document, sid: StoryId, opts: &ComposeOptions, out = crate::compose(doc, st, &with_exclusions(&specs, &added), opts); prev = added; } - out + (out, None) } diff --git a/crates/compose/src/xref.rs b/crates/compose/src/xref.rs index b33714203..d658eb3d9 100644 --- a/crates/compose/src/xref.rs +++ b/crates/compose/src/xref.rs @@ -52,8 +52,14 @@ impl XrefIndex { } /// The text a cross-reference shows ("??" when its destination is gone, like an unresolved -/// reference in typesetting). +/// reference in typesetting, unless the text was edited). pub fn xref_text(doc: &Document, x: &xref::CrossRef, index: Option<&XrefIndex>) -> String { + // Edited text stays as typed; its page numbers still follow the destination, or show the + // page last shown when the destination is gone (as in InDesign). + if let Some(t) = &x.text { + let live = index.filter(|_| doc.xref_values(x.target).is_some()).and_then(|i| i.page(x.target)); + return xref::expand_edited(t, live.or(x.page.as_deref()).unwrap_or("?")); + } let Some(mut v) = doc.xref_values(x.target) else { return "??".into() }; v.page = index.and_then(|i| i.page(x.target)).unwrap_or("?").to_string(); let def = doc.xref_format(&x.format).map_or("", |f| f.definition.as_str()); @@ -62,11 +68,26 @@ pub fn xref_text(doc: &Document, x: &xref::CrossRef, index: Option<&XrefIndex>) /// Generated text of the cross-references in `range` of `story`, by byte of their mark. pub fn texts_in(doc: &Document, story: &Story, range: std::ops::Range, index: Option<&XrefIndex>) -> HashMap { + if story.xrefs.is_empty() { + return HashMap::new(); + } + let before = story.text[..range.start].matches(XREF_MARK).count(); + texts_after(doc, story, range, before, index) +} + +/// [`texts_in`] for a caller that already knows `before`, the number of cross-reference marks in +/// `story` before `range`. +pub(crate) fn texts_after( + doc: &Document, + story: &Story, + range: std::ops::Range, + before: usize, + index: Option<&XrefIndex>, +) -> HashMap { let mut out = HashMap::new(); if story.xrefs.is_empty() { return out; } - let before = story.text[..range.start].matches(XREF_MARK).count(); for (k, (i, _)) in story.text[range.clone()].match_indices(XREF_MARK).enumerate() { if let Some(x) = story.xrefs.get(before + k) { out.insert(range.start + i, xref_text(doc, x, index)); diff --git a/crates/doc/src/anchored.rs b/crates/doc/src/anchored.rs index 74fc8818f..f5c4b856c 100644 --- a/crates/doc/src/anchored.rs +++ b/crates/doc/src/anchored.rs @@ -4,14 +4,26 @@ //! [`AnchoredObject`] per mark in text order (like footnotes). The item's geometry is kept with //! its top-left at the origin; composition places it on the line (inline) or on a line of its //! own above the line it is anchored in (above line). +//! +//! An anchored text frame (also one in an anchored group, a footnote or a table cell) is in its +//! story's thread like a frame on a page: [`Document::fix_anchored_text_frames`] keeps it so +//! after edits that copy or delete text and frames, and [`Document::adopt_anchored`] gives +//! copies brought into a document stories of their own. +use std::collections::{BTreeMap, HashMap, HashSet}; use std::sync::Arc; use serde::{Deserialize, Serialize}; +use crate::Document; +use crate::ids::{AssetId, ItemId, StoryId}; use crate::item::Item; use crate::story::Story; +/// How deep anchored text frames (and footnotes and cells) are followed into each other: the +/// nesting [`Document::check`] accepts. +const NESTING: usize = 64; + /// An anchored object's position in the text. pub const OBJECT_MARK: char = '\u{E00E}'; @@ -137,3 +149,673 @@ impl Story { self.objects.get(self.text[..pos].matches(OBJECT_MARK).count()).map(|o| &**o) } } + +/// Visit the items anchored in `st`, its footnotes, endnotes and table cells (and theirs, so +/// deep), in order: a story's objects (a group before its items), then its notes and its cells. +fn items(st: &Story, depth: usize, f: &mut dyn FnMut(&Item)) { + for o in &st.objects { + o.item.walk(&mut |i| f(i)); + } + if depth >= NESTING { + return; + } + for n in st.notes.iter().chain(&st.endnotes) { + items(&n.text, depth + 1, f); + } + for t in st.tables.values() { + for c in &t.cells { + items(&c.text, depth + 1, f); + } + } +} + +/// [`items`], mutably (copy-on-write only where items are). +fn items_mut(st: &mut Story, depth: usize, f: &mut dyn FnMut(&mut Item)) { + for o in &mut st.objects { + walk_mut(&mut Arc::make_mut(o).item, f); + } + if depth >= NESTING { + return; + } + for n in st.notes.iter_mut().chain(st.endnotes.iter_mut()) { + if has_items(&n.text) { + items_mut(&mut Arc::make_mut(n).text, depth + 1, f); + } + } + for t in st.tables.values_mut() { + if t.cells.iter().any(|c| has_items(&c.text)) { + for c in &mut Arc::make_mut(t).cells { + items_mut(&mut c.text, depth + 1, f); + } + } + } +} + +fn walk_mut(it: &mut Item, f: &mut dyn FnMut(&mut Item)) { + f(it); + if let Some(children) = it.children_mut() { + for c in children { + walk_mut(Arc::make_mut(c), f); + } + } +} + +/// Does `st` (or a footnote or cell in it) hold anchored objects? +fn has_items(st: &Story) -> bool { + let mut todo = vec![st]; + while let Some(s) = todo.pop() { + if !s.objects.is_empty() { + return true; + } + todo.extend(s.notes.iter().chain(&s.endnotes).map(|n| &n.text)); + todo.extend(s.tables.values().flat_map(|t| t.cells.iter().map(|c| &c.text))); + } + false +} + +impl Document { + /// Does any story (its footnotes and table cells included) hold anchored objects? + pub fn has_anchored_items(&self) -> bool { + self.stories.values().any(|s| has_items(s)) + } + + /// The stories the anchored text frames in `st` show, and the stories shown by the frames + /// anchored in those: what copied text takes along. + pub fn anchored_stories(&self, st: &Story) -> BTreeMap> { + let mut out = BTreeMap::new(); + let mut todo = Vec::new(); + items(st, 0, &mut |i| todo.extend(i.text_frame().map(|t| (t.story, 1)))); + while let Some((sid, depth)) = todo.pop() { + if depth > NESTING || out.contains_key(&sid) { + continue; + } + let Some(s) = self.stories.get(&sid) else { continue }; + out.insert(sid, s.clone()); + items(s, 0, &mut |i| todo.extend(i.text_frame().map(|t| (t.story, depth + 1)))); + } + out + } + + /// Text copied into this document (from it or another one): give the items anchored in `st` + /// fresh ids, and each anchored text frame among them a copy of its story from `src` (an + /// empty story when `src` hasn't it) threaded to the copied frames that show it, copying the + /// frames anchored in those stories the same way. + pub fn adopt_anchored(&mut self, st: &mut Story, src: &dyn Fn(StoryId) -> Option>) { + self.adopt(&mut |f| items_mut(st, 0, f), src, None, &mut Vec::new(), &mut HashMap::new()); + } + + /// [`Document::adopt_anchored`] for text copied from document `src`: the copies of the + /// stories its anchored text frames show also take the assets they place along from `src` + /// (or reuse the same file here), since `src`'s asset ids may name other files here. + pub fn adopt_anchored_from(&mut self, st: &mut Story, src: &Document) { + self.adopt(&mut |f| items_mut(st, 0, f), &|id| src.stories.get(&id).cloned(), Some(src), &mut Vec::new(), &mut HashMap::new()); + } + + /// `visit` runs a function on every copied item. `path`: the stories being copied (a frame + /// showing one of them again gets an empty story, so copies never nest without end). + /// `assets`: the document the copied stories' assets are in, when it isn't this one. + /// `copies`: the copy made of each source story in this operation. A story shown by frames in + /// several copied stories is copied once and threads all their copies, as the original does, + /// so a graph of shared stories doesn't multiply into exponentially many copies. + fn adopt( + &mut self, + visit: &mut dyn FnMut(&mut dyn FnMut(&mut Item)), + src: &dyn Fn(StoryId) -> Option>, + assets: Option<&Document>, + path: &mut Vec, + copies: &mut HashMap, + ) { + let mut next = self.next_id; + let mut frames = Vec::new(); + visit(&mut |i| { + next = next.saturating_add(1); + i.id = ItemId(next); + frames.extend(i.text_frame().map(|t| (i.id, t.story))); + }); + self.next_id = next; + // The story each copied frame shows: the operation's copy of its story, or an empty one + // where copying would loop or nest too deep. + let mut shows: HashMap = HashMap::new(); + let mut empty: HashMap = HashMap::new(); + for &(fid, old) in &frames { + let looped = path.contains(&old) || path.len() >= NESTING; + if let Some(&id) = if looped { empty.get(&old) } else { copies.get(&old) } { + shows.insert(fid, id); + continue; + } + let id = StoryId(self.alloc()); + shows.insert(fid, id); + let copy = match src(old) { + Some(s) if !looped => { + copies.insert(old, id); + let mut copy = (*s).clone(); + copy.id = id; + copy.frames.clear(); + if let Some(from) = assets { + // The graphics it places, under this document's ids. + let mut map = HashMap::new(); + for a in crate::story_asset_refs(©) { + let here = self.adopt_asset(from, a).unwrap_or_else(|| AssetId(self.alloc())); + if here != a { + map.insert(a, here); + } + } + crate::remap_story_assets(&mut copy, &map); + } + path.push(old); + self.adopt(&mut |f| items_mut(&mut copy, 0, f), src, assets, path, copies); + path.pop(); + copy + } + _ => { + if looped { + empty.insert(old, id); + } else { + copies.insert(old, id); + } + Story::new(id) + } + }; + self.stories.insert(id, Arc::new(copy)); + } + visit(&mut |i| { + if let Some(id) = shows.get(&i.id) + && let Some(t) = i.text_frame_mut() + { + t.story = *id; + } + }); + for (fid, _) in frames { + if let Some(st) = shows.get(&fid).and_then(|id| self.stories.get_mut(id)) { + Arc::make_mut(st).frames.push(fid); + } + } + } + + /// Could the edit from `old` to this document have left anchored items for + /// [`Document::fix_anchored_text_frames`] to repair? Only a story that was added, removed or + /// changed can: one that holds anchored items whose ids or stories changed, or whose thread + /// changed (a frame deleted or copied). Typing, formatting and moving frames don't, so the + /// repair, which walks every story, doesn't run for them. Story by story: unchanged stories + /// share their allocation. + pub fn anchored_items_changed_since(&self, old: &Document) -> bool { + // The anchored items of `st` that the repair looks at: their ids and the stories they show. + let anchored = |st: &Story| { + let mut out = Vec::new(); + items(st, 0, &mut |i| out.push((i.id, i.text_frame().map(|t| t.story)))); + out + }; + for (id, st) in &self.stories { + match old.stories.get(id) { + Some(before) if Arc::ptr_eq(before, st) => {} + Some(before) => { + if before.frames != st.frames || anchored(before) != anchored(st) { + return true; + } + } + None => { + if has_items(st) { + return true; + } + } + } + } + // A removed story: its anchored items went with it, or an anchored frame may show it. + let removed = old.stories.iter().filter(|(id, _)| !self.stories.contains_key(id)); + removed.into_iter().any(|(_, st)| has_items(st) || self.has_anchored_items()) + } + + /// Ids of the items on spreads and parents, and of the items anchored in stories. + fn live_items(&self) -> HashSet { + let mut live = HashSet::new(); + for sp in self.spreads.iter().chain(&self.parents) { + for it in &sp.items { + it.walk(&mut |i| { + live.insert(i.id); + }); + } + } + for st in self.stories.values() { + items(st, 0, &mut |i| { + live.insert(i.id); + }); + } + live + } + + /// Keep anchored items valid ([`Document::check`]) after edits that copy or delete text and + /// frames: an anchored item whose id is taken (text copied in the document) gets a fresh one; + /// threads lose frames that are gone, and a story whose last frame went goes too (unless a + /// frame still shows it); an anchored text frame its story doesn't thread is added to the + /// story when that has no frames left, else gets a copy of it (an empty story when it is + /// missing). Returns how many items, threads and stories changed. + pub fn fix_anchored_text_frames(&mut self) -> usize { + let mut changed = 0; + // Fresh ids for copies: items on spreads keep theirs, then the first in story order. + let mut seen = HashSet::new(); + for sp in self.spreads.iter().chain(&self.parents) { + for it in &sp.items { + it.walk(&mut |i| { + seen.insert(i.id); + }); + } + } + let sids: Vec = self.stories.keys().copied().collect(); + for sid in &sids { + let Some(st) = self.stories.get(sid) else { continue }; + let mut ids = Vec::new(); + items(st, 0, &mut |i| ids.push(i.id)); + let mut own = HashSet::new(); + if !ids.iter().any(|id| seen.contains(id) || !own.insert(*id)) { + seen.extend(ids); + continue; + } + let mut next = self.next_id; + let Some(st) = self.stories.get_mut(sid) else { continue }; + let st = Arc::make_mut(st); + items_mut(st, 0, &mut |i| { + if !seen.insert(i.id) { + next = next.saturating_add(1); + i.id = ItemId(next); + seen.insert(i.id); + changed += 1; + } + }); + st.rev = st.rev.wrapping_add(1); + self.next_id = next; + } + // Frames that are gone (deleted with their text or their host's frame) leave their + // threads; a story left without frames goes with them, and so on into the stories its + // anchored frames showed. + let mut live = seen; + for round in 0..=self.stories.len() { + if round > 0 { + live = self.live_items(); + } + let dangling: Vec = + self.stories.iter().filter(|(_, st)| st.frames.iter().any(|f| !live.contains(f))).map(|(id, _)| *id).collect(); + if dangling.is_empty() { + break; + } + let mut shown = HashSet::new(); + for sp in self.spreads.iter().chain(&self.parents) { + for it in &sp.items { + it.walk(&mut |i| shown.extend(i.text_frame().map(|t| t.story))); + } + } + for st in self.stories.values() { + items(st, 0, &mut |i| shown.extend(i.text_frame().map(|t| t.story))); + } + for sid in dangling { + let Some(st) = self.stories.get_mut(&sid) else { continue }; + let st = Arc::make_mut(st); + st.frames.retain(|f| live.contains(f)); + changed += 1; + if st.frames.is_empty() && !shown.contains(&sid) { + self.stories.remove(&sid); + } + } + } + // Anchored text frames their stories don't thread: copies, or frames whose story went. + let mut frames = Vec::new(); + for (owner, st) in &self.stories { + items(st, 0, &mut |i| frames.extend(i.text_frame().map(|t| (*owner, i.id, t.story)))); + } + for (owner, fid, sid) in frames { + let story = match self.stories.get_mut(&sid) { + Some(st) if st.frames.contains(&fid) => continue, + Some(st) if st.frames.is_empty() => { + Arc::make_mut(st).frames.push(fid); + changed += 1; + continue; + } + Some(st) => { + let mut copy = (**st).clone(); + let id = StoryId(self.alloc()); + copy.id = id; + // Only the stories the copy reaches, as they are now (copies made for earlier + // frames included). + let reachable = self.anchored_stories(©); + self.adopt(&mut |f| items_mut(&mut copy, 0, f), &|s| reachable.get(&s).cloned(), None, &mut vec![sid], &mut HashMap::new()); + copy.frames = vec![fid]; + self.stories.insert(id, Arc::new(copy)); + id + } + None => { + let id = StoryId(self.alloc()); + let mut st = Story::new(id); + st.frames = vec![fid]; + self.stories.insert(id, Arc::new(st)); + id + } + }; + if let Some(st) = self.stories.get_mut(&owner) { + let st = Arc::make_mut(st); + items_mut(st, 0, &mut |i| { + if i.id == fid + && let Some(t) = i.text_frame_mut() + { + t.story = story; + } + }); + st.rev = st.rev.wrapping_add(1); + } + changed += 1; + } + changed + } +} + +#[cfg(test)] +mod tests { + use designcraft_geom::Rect; + + use super::*; + use crate::build::NewDocument; + use crate::{ParaFormat, SpreadRef}; + + /// A document with a text frame (story returned) on its first page. + fn doc() -> (Document, StoryId) { + let mut d = Document::new(&NewDocument { pages: 1, ..Default::default() }); + let lid = d.default_layer(); + let (_, sid) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(36.0, 36.0, 300.0, 300.0), lid, "Host ", ParaFormat::default()).unwrap(); + (d, sid) + } + + /// Anchor, at the end of `host`, a text frame showing a new story with `text`. + fn anchor(d: &mut Document, host: StoryId, text: &str) -> (StoryId, ItemId) { + let lid = d.default_layer(); + let (fid, sid) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(0.0, 0.0, 100.0, 40.0), lid, text, ParaFormat::default()).unwrap(); + let it = d.item(fid).unwrap().clone(); + d.spread_mut(SpreadRef::Doc(0)).unwrap().items.retain(|i| i.id != fid); + let h = d.story_mut(host).unwrap(); + let n = h.len(); + h.insert_object(n, AnchoredObject::new(it, AnchorPosition::default())); + (sid, fid) + } + + /// The stories the anchored text frames show, with their texts. + fn shown(d: &Document) -> Vec<(StoryId, String)> { + d.anchored_items().iter().filter_map(|(_, i)| i.text_frame()).map(|t| (t.story, d.story(t.story).unwrap().text.clone())).collect() + } + + /// Stories shared between layers (two per layer, each anchoring a frame showing each story of + /// the next layer) are copied once each when their text is copied, and each copy threads the + /// copied frames that show it, as the original does. Copying them again for every frame that + /// shows them doubled the work with every layer. + #[test] + fn a_graph_of_shared_stories_is_copied_once_per_story() { + const LAYERS: usize = 12; + let (mut d, host) = doc(); + let lid = d.default_layer(); + let layers: Vec<[StoryId; 2]> = (0..LAYERS) + .map(|_| { + [0, 1].map(|_| { + let id = StoryId(d.alloc()); + d.stories.insert(id, Arc::new(Story::new(id))); + id + }) + }) + .collect(); + // Anchor at the end of `host` a text frame showing `shows`, threaded to it. + let anchor_showing = |d: &mut Document, host: StoryId, shows: StoryId| { + let (fid, own) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(0.0, 0.0, 100.0, 40.0), lid, "", ParaFormat::default()).unwrap(); + let mut it = d.item(fid).unwrap().clone(); + d.spread_mut(SpreadRef::Doc(0)).unwrap().items.retain(|i| i.id != fid); + d.stories.remove(&own); + it.text_frame_mut().unwrap().story = shows; + Arc::make_mut(d.stories.get_mut(&shows).unwrap()).frames.push(fid); + let h = d.story_mut(host).unwrap(); + let n = h.len(); + h.insert_object(n, AnchoredObject::new(it, AnchorPosition::default())); + }; + for &top in &layers[0] { + anchor_showing(&mut d, host, top); + } + for k in 0..LAYERS - 1 { + for s in layers[k] { + for t in layers[k + 1] { + anchor_showing(&mut d, s, t); + } + } + } + let mut copy = d.story(host).unwrap().extract(0..d.story(host).unwrap().len()); + let stories = d.anchored_stories(©); + assert_eq!(stories.len(), 2 * LAYERS); + let before: HashSet = d.stories.keys().copied().collect(); + d.adopt_anchored(&mut copy, &|id| stories.get(&id).cloned()); + let added: Vec = d.stories.keys().copied().filter(|id| !before.contains(id)).collect(); + assert_eq!(added.len(), 2 * LAYERS, "one copy per story"); + // Below the top layer each copy threads the two copied frames that show it. + let threads: Vec = added.iter().map(|id| d.story(*id).unwrap().frames.len()).collect(); + assert_eq!(threads.iter().filter(|&&n| n == 2).count(), 2 * (LAYERS - 1), "{threads:?}"); + assert_eq!(threads.iter().filter(|&&n| n == 1).count(), 2, "{threads:?}"); + } + + /// The repair's trigger: typing in a story with anchored frames (or in theirs) and moving + /// frames leave nothing to repair; copying text with anchored frames, deleting them with + /// their text or their host frame, and removing a story they show do. + #[test] + fn only_edits_that_copy_or_remove_anchored_items_trigger_the_repair() { + let (mut d, host) = doc(); + let (inner, _) = anchor(&mut d, host, "Inner "); + let old = d.clone(); + assert!(!d.anchored_items_changed_since(&old), "nothing changed"); + // Typing in the host and in the anchored frame's story; moving the host frame. + d.story_mut(host).unwrap().insert(0, "Typed "); + d.story_mut(inner).unwrap().insert(0, "Typed "); + let frame = d.story(host).unwrap().frames[0]; + d.item_mut(frame).unwrap().xf = designcraft_geom::Affine::translate((10.0, 0.0)); + assert!(!d.anchored_items_changed_since(&old), "typing and moving"); + d.check().unwrap(); + // Text with the anchored frame copied in the document. + let mut copied = d.clone(); + let st = copied.story(host).unwrap(); + let slice = st.extract(0..st.len()); + let h = copied.story_mut(host).unwrap(); + let n = h.len(); + h.insert_story(n, &slice); + assert!(copied.anchored_items_changed_since(&d), "copied"); + // Deleted with its text, or with the story it is anchored in. + let mut deleted = d.clone(); + let h = deleted.story_mut(host).unwrap(); + let n = h.len(); + h.delete(0..n); + assert!(deleted.anchored_items_changed_since(&d), "deleted with its text"); + let mut gone = d.clone(); + gone.stories.remove(&host); + assert!(gone.anchored_items_changed_since(&d), "deleted with its host's story"); + // The story it shows removed: the frame needs one. + let mut lost = d.clone(); + lost.stories.remove(&inner); + assert!(lost.anchored_items_changed_since(&d), "its story removed"); + // An ordinary text frame added, or text typed in a document without anchored items. + let (mut plain, sid) = doc(); + let before = plain.clone(); + plain.story_mut(sid).unwrap().insert(0, "Typed "); + let lid = plain.default_layer(); + plain.add_text_frame(SpreadRef::Doc(0), Rect::new(0.0, 0.0, 100.0, 40.0), lid, "New", ParaFormat::default()).unwrap(); + assert!(!plain.anchored_items_changed_since(&before)); + } + + #[test] + fn copied_anchored_text_frames_get_stories_of_their_own() { + let (mut d, host) = doc(); + let (inner, _) = anchor(&mut d, host, "Inner "); + anchor(&mut d, inner, "Deeper"); + d.check().unwrap(); + assert_eq!(d.fix_anchored_text_frames(), 0); + // Text copied in the document: the same anchored frames twice. + let copy = d.story(host).unwrap().extract(0..d.story(host).unwrap().len()); + let h = d.story_mut(host).unwrap(); + let n = h.len(); + h.insert_story(n, ©); + assert!(d.check().is_err()); + assert!(d.fix_anchored_text_frames() > 0); + d.check().unwrap(); + let shown = shown(&d); + assert_eq!(shown.len(), 4, "{shown:?}"); + assert_eq!(shown.iter().map(|(s, _)| *s).collect::>().len(), 4, "a story of its own each"); + assert_eq!(shown.iter().filter(|(_, t)| t == "Deeper").count(), 2, "{shown:?}"); + assert_eq!(shown.iter().filter(|(_, t)| t.starts_with("Inner ")).count(), 2, "{shown:?}"); + } + + /// The repair bumps the revisions of the stories it changes; a revision at its maximum wraps + /// around instead of overflowing. + #[test] + fn the_repair_wraps_story_revisions_at_their_maximum() { + let (mut d, host) = doc(); + anchor(&mut d, host, "Inner "); + let copy = d.story(host).unwrap().extract(0..d.story(host).unwrap().len()); + let h = d.story_mut(host).unwrap(); + let n = h.len(); + h.insert_story(n, ©); + Arc::make_mut(d.stories.get_mut(&host).unwrap()).rev = u64::MAX; + assert!(d.fix_anchored_text_frames() > 0); + d.check().unwrap(); + assert_ne!(d.story(host).unwrap().rev, u64::MAX); + } + + #[test] + fn deleted_anchored_text_frames_take_their_stories_along() { + // With the text they are anchored in. + let (mut d, host) = doc(); + let (inner, _) = anchor(&mut d, host, "Inner "); + let (deeper, _) = anchor(&mut d, inner, "Deeper"); + let h = d.story_mut(host).unwrap(); + let n = h.len(); + h.delete(0..n); + assert!(d.check().is_err()); + d.fix_anchored_text_frames(); + d.check().unwrap(); + assert!(d.story(inner).is_none() && d.story(deeper).is_none()); + // With the frame they are anchored in. + let (mut d, host) = doc(); + let (inner, _) = anchor(&mut d, host, "Inner "); + let frame = d.story(host).unwrap().frames[0]; + d.remove_item(frame).unwrap(); + assert!(d.check().is_err()); + d.fix_anchored_text_frames(); + d.check().unwrap(); + assert!(d.story(inner).is_none()); + // An unplaced story stays. + let (mut d, _) = doc(); + let sid = StoryId(d.alloc()); + d.stories.insert(sid, Arc::new(Story::new(sid))); + assert_eq!(d.fix_anchored_text_frames(), 0); + assert!(d.story(sid).is_some()); + } + + #[test] + fn anchored_text_frames_without_their_stories_get_one() { + // Missing: an empty story of its own. + let (mut d, host) = doc(); + let (inner, fid) = anchor(&mut d, host, "Inner"); + d.stories.remove(&inner); + assert!(d.check().is_err()); + d.fix_anchored_text_frames(); + d.check().unwrap(); + let t = d.anchored_item(fid).unwrap().text_frame().unwrap().story; + assert!(d.story(t).unwrap().text.is_empty()); + // Without frames (its frame was cut and pasted back): threaded to it again. + let (mut d, host) = doc(); + let (inner, fid) = anchor(&mut d, host, "Inner"); + Arc::make_mut(d.stories.get_mut(&inner).unwrap()).frames.clear(); + d.fix_anchored_text_frames(); + d.check().unwrap(); + assert_eq!(d.story(inner).unwrap().frames, vec![fid]); + } + + #[test] + fn an_anchored_text_frame_copied_into_its_own_story_does_not_show_itself() { + let (mut d, host) = doc(); + let (inner, _) = anchor(&mut d, host, "Inner "); + let obj = (*d.story(host).unwrap().objects[0]).clone(); + let st = d.story_mut(inner).unwrap(); + let n = st.len(); + st.insert_object(n, obj); + assert!(d.check().is_err()); + d.fix_anchored_text_frames(); + d.check().unwrap(); + } + + /// Text copied from another document takes along the graphics placed in the stories its + /// anchored text frames show: the graphic keeps its own file (a.pdf), though its asset id + /// names another file (b.pdf) in the target document. + #[test] + fn adopted_stories_take_their_graphics_along_from_another_document() { + use crate::{Asset, Content, Graphic, Shape}; + let pdf = |id: AssetId, name: &str| Asset { + id, + name: name.into(), + mime: "application/pdf".into(), + data: crate::AssetData::embedded(format!("%PDF-1.7 {name}").into_bytes()), + ..Default::default() + }; + let (mut a, host) = doc(); + let (inner, _) = anchor(&mut a, host, "Inner "); + let aid = AssetId(a.alloc()); + a.assets.insert(aid, Arc::new(pdf(aid, "a.pdf"))); + let mut g = + Item::new(ItemId(a.alloc()), a.default_layer(), Shape::Rectangle, designcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 20.0, 20.0))); + g.content = Content::Graphic(Graphic { + layer_options: None, + asset: aid, + size: (20.0, 20.0), + xf: designcraft_geom::Affine::IDENTITY, + clip: None, + auto_fit: Default::default(), + fit_align: 4, + crop: [0.0; 4], + wrap: Default::default(), + fill: Default::default(), + }); + let st = a.story_mut(inner).unwrap(); + let n = st.len(); + st.insert_object(n, AnchoredObject::new(g, AnchorPosition::default())); + a.check().unwrap(); + // The target document has b.pdf under the same id (allocated there too). + let (mut b, target) = doc(); + while b.alloc() < aid.0 {} + b.assets.insert(aid, Arc::new(pdf(aid, "b.pdf"))); + let src = a.story(host).unwrap(); + let mut slice = src.extract(0..src.len()); + b.adopt_anchored_from(&mut slice, &a); + let t = b.story_mut(target).unwrap(); + let n = t.len(); + t.insert_story(n, &slice); + b.check().unwrap(); + let placed: Vec = b + .anchored_items() + .iter() + .filter_map(|(_, i)| i.graphic()) + .map(|g| b.assets.get(&g.asset).map_or_else(|| "missing".to_string(), |a| a.name.clone())) + .collect(); + assert_eq!(placed, ["a.pdf"], "the copied story's graphic places its own file"); + assert_eq!(b.assets.get(&aid).map(|a| a.name.as_str()), Some("b.pdf"), "the target's own asset is left alone"); + } + + #[test] + fn adopted_text_brings_copies_of_its_anchored_stories() { + let (mut a, host) = doc(); + let (inner, _) = anchor(&mut a, host, "Inner "); + anchor(&mut a, inner, "Deeper"); + // Another document, whose ids are the same as the first one's. + let (mut b, target) = doc(); + let (other, _) = anchor(&mut b, target, "Other"); + assert!(b.story(inner).is_some(), "ids collide"); + let src = a.story(host).unwrap(); + let mut slice = src.extract(0..src.len()); + let stories = a.anchored_stories(&slice); + assert_eq!(stories.len(), 2); + b.adopt_anchored(&mut slice, &|id| stories.get(&id).cloned()); + let t = b.story_mut(target).unwrap(); + let n = t.len(); + t.insert_story(n, &slice); + b.check().unwrap(); + let mut texts: Vec = shown(&b).into_iter().map(|(_, t)| t).collect(); + texts.sort(); + assert_eq!(texts, ["Deeper", "Inner \u{E00E}", "Other"]); + assert_eq!(b.story(other).unwrap().text, "Other"); + } +} diff --git a/crates/doc/src/arrow.rs b/crates/doc/src/arrow.rs index e3f3387fe..432cd4b93 100644 --- a/crates/doc/src/arrow.rs +++ b/crates/doc/src/arrow.rs @@ -75,7 +75,12 @@ fn end_of(seg: &PathSeg, at_start: bool) -> (Point, Vec2) { let mut d = match seg { PathSeg::Line(l) => l.p1 - l.p0, PathSeg::Quad(q) => q.deriv().eval(t).to_vec2(), - PathSeg::Cubic(c) => c.deriv().eval(t).to_vec2(), + PathSeg::Cubic(c) => { + // A handle sitting on its anchor has no direction: the tangent then points at the next + // control point of the segment that differs from the end point. + let pts = if at_start { [c.p1 - c.p0, c.p2 - c.p0, c.p3 - c.p0] } else { [c.p3 - c.p2, c.p3 - c.p1, c.p3 - c.p0] }; + pts.into_iter().find(|v| v.hypot() >= 1e-9).unwrap_or(Vec2::ZERO) + } }; if d.hypot() < 1e-9 { d = seg.end() - seg.start(); diff --git a/crates/doc/src/asset_data.rs b/crates/doc/src/asset_data.rs new file mode 100644 index 000000000..a4584c19c --- /dev/null +++ b/crates/doc/src/asset_data.rs @@ -0,0 +1,411 @@ +//! The bytes of a placed file ([`crate::Asset::data`]): held in memory (embedded) or read from +//! the linked file when needed. Caches of decoded images key by the value's [`SourceKey`], +//! which outlives the bytes: a decoded image stays usable after the encoded bytes are dropped. +//! +//! Linked bytes are read by the [`Loader`] the engine installs ([`install_loader`]; this crate +//! does no file I/O) and kept in a process-wide store of at most [`STORE_BUDGET`] bytes, least +//! recently used first out. A file over [`MAX_LINKED_BYTES`] is never read. + +use std::fmt; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Arc, Mutex, PoisonError, Weak}; + +use crate::datamerge::Fingerprint; + +mod store; + +pub use store::{Loaded, Loader, MAX_LINKED_BYTES, STORE_BUDGET, install_loader}; + +/// Names one version of an asset's bytes. Every [`AssetData`] made from new bytes gets a key no +/// other value in this process has had; clones share it. Keys are never reused, so a cache +/// entry under a key can't be mistaken for different bytes allocated later. Counting starts at +/// 1: `SourceKey(0)` names no bytes. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub struct SourceKey(pub u64); + +impl SourceKey { + /// A key no other value has had. + pub fn fresh() -> Self { + static NEXT: AtomicU64 = AtomicU64::new(1); + SourceKey(NEXT.fetch_add(1, Ordering::Relaxed)) + } +} + +/// Why an asset's bytes can't be had. +#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)] +pub enum Unavailable { + #[error("the linked file is missing")] + Missing, + #[error("the linked file has changed")] + Modified, + #[error("the linked file is too large to load")] + TooLarge, + #[error("no loader for linked files")] + NoLoader, +} + +/// Where a linked asset's bytes are, and what they must be: the [`crate::Asset`] link record +/// ([`LinkedSource::of`]) with the document it is resolved against. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct LinkedSource { + /// The file's absolute path ([`crate::Asset::link`]), tried first. + pub path: String, + /// The path relative to the document's folder ([`crate::Asset::link_relative`]), tried when + /// the absolute path doesn't hold the bytes. + pub relative: Option, + /// The document file `relative` is resolved against. + pub document: Option, + /// The size of the bytes. + pub len: u64, + /// Size and modification time of the file when it was known to hold the bytes: a file that + /// still has them is read without hashing. + pub fingerprint: Option, + /// The bytes' content hash ([`crate::Asset::link_hash`], `sha256:` and hex digits), checked + /// when the file's fingerprint differs. + pub hash: Option, +} + +impl LinkedSource { + /// The source `asset`'s link record names, resolved against the document file at + /// `document`. `None` without a link, or without the size its fingerprint records. + pub fn of(asset: &crate::Asset, document: Option<&Path>) -> Option { + let fingerprint = asset.link_fingerprint?; + Some(LinkedSource { + path: asset.link.clone()?, + relative: asset.link_relative.clone(), + document: document.map(Path::to_path_buf), + len: fingerprint.size, + fingerprint: Some(fingerprint), + hash: asset.link_hash.clone(), + }) + } +} + +/// A linked source, with the fingerprint a load last found the file at (hash-checked), so later +/// loads of a file whose time changed but whose bytes didn't skip the hash. +struct Linked { + source: LinkedSource, + trusted: Mutex>, +} + +impl Linked { + fn trusted(&self) -> Option { + *self.trusted.lock().unwrap_or_else(PoisonError::into_inner) + } + + fn trust(&self, fingerprint: Fingerprint) { + *self.trusted.lock().unwrap_or_else(PoisonError::into_inner) = Some(fingerprint); + } +} + +#[derive(Clone)] +enum Repr { + Embedded(Arc>), + Linked(Arc), +} + +/// An asset's bytes: embedded in the document, or linked (read from the file on demand). +/// Cloning is cheap and keeps the [`SourceKey`]. +#[derive(Clone)] +pub struct AssetData { + key: SourceKey, + repr: Repr, +} + +impl AssetData { + /// Embedded bytes, under a new key. + pub fn embedded(bytes: impl Into>>) -> Self { + AssetData { key: SourceKey::fresh(), repr: Repr::Embedded(bytes.into()) } + } + + /// Embedded bytes under `key`, which the caller made ([`SourceKey::fresh`]) for exactly these + /// bytes: bytes derived again from the same input (a layer variant of the same file) keep + /// the key their decodes are cached under. Different bytes under one key would draw stale + /// pixels. + pub fn embedded_under(key: SourceKey, bytes: impl Into>>) -> Self { + AssetData { key, repr: Repr::Embedded(bytes.into()) } + } + + /// The bytes of the linked file `source` names, under a new key. + pub fn linked(source: LinkedSource) -> Self { + AssetData { key: SourceKey::fresh(), repr: Repr::Linked(Arc::new(Linked { source, trusted: Mutex::new(None) })) } + } + + /// The linked file `source` names, under `key`: embedded bytes found identical to the file + /// (hash-checked by the caller) become a link without decoding them again. As with + /// [`AssetData::embedded_under`], other bytes under one key would draw stale pixels. + pub fn linked_under(key: SourceKey, source: LinkedSource) -> Self { + AssetData { key, repr: Repr::Linked(Arc::new(Linked { source, trusted: Mutex::new(None) })) } + } + + /// This value pointing at `source` (the file moved, the document was saved elsewhere, the + /// fingerprint was brought up to date). It keeps the key when both name the same bytes + /// (same size and content hash), so nothing decoded is decoded again. + pub fn with_source(&self, source: LinkedSource) -> Self { + let same = self.linked_source().is_some_and(|old| old.len == source.len && old.hash.is_some() && old.hash == source.hash); + let mut new = AssetData::linked(source); + if same { + new.key = self.key; + } + new + } + + /// The bytes, when they are embedded. + pub fn embedded_bytes(&self) -> Option<&Arc>> { + match &self.repr { + Repr::Embedded(b) => Some(b), + Repr::Linked(_) => None, + } + } + + /// Where linked bytes are read from. + pub fn linked_source(&self) -> Option<&LinkedSource> { + match &self.repr { + Repr::Embedded(_) => None, + Repr::Linked(l) => Some(&l.source), + } + } + + /// The bytes: embedded ones, or the linked file's (read once by the installed [`Loader`], + /// and kept while the store's budget allows). Concurrent loads of one value read it once. + pub fn load(&self) -> Result>, Unavailable> { + match &self.repr { + Repr::Embedded(b) => Ok(Arc::clone(b)), + Repr::Linked(l) => store::global().load(self.key, l, store::installed().as_deref()), + } + } + + /// The bytes for output: [`Self::load`], or for a linked file that has changed the file's + /// current bytes, flagged `true`, which are never cached. Linked bytes already in memory are + /// used only while the file still holds them ([`Loader::holds`]): output goes by the file as + /// it is now. + pub fn load_for_output(&self) -> Result<(Arc>, bool), Unavailable> { + if let Repr::Linked(l) = &self.repr + && let Some(kept) = store::global().resident(self.key) + && let Some(loader) = store::installed() + { + return match loader.holds(&l.source, l.trusted(), &kept) { + Ok(found) => { + if let Some(fingerprint) = found { + l.trust(fingerprint); + } + Ok((kept, false)) + } + Err(Unavailable::Modified) => loader.load_current(&l.source).map(|b| (Arc::new(b), true)), + Err(e) => Err(e), + }; + } + match self.load() { + Ok(b) => Ok((b, false)), + Err(Unavailable::Modified) => { + let (Some(source), Some(loader)) = (self.linked_source(), store::installed()) else { return Err(Unavailable::Modified) }; + loader.load_current(source).map(|b| (Arc::new(b), true)) + } + Err(e) => Err(e), + } + } + + /// The bytes without reading anything: embedded ones, or linked ones the store holds. + pub fn resident(&self) -> Option>> { + match &self.repr { + Repr::Embedded(b) => Some(Arc::clone(b)), + Repr::Linked(_) => store::global().resident(self.key), + } + } + + /// Keep `bytes`, just read from the linked file and checked by the caller to be the ones its + /// source names, in the store, so the first [`AssetData::load`] doesn't read the file again. + /// Embedded values, bytes of another size and bytes over the store's budget are ignored. + pub fn keep_resident(&self, bytes: Arc>) { + if let Repr::Linked(l) = &self.repr + && bytes.len() as u64 == l.source.len + { + store::global().keep(self.key, bytes); + } + } + + /// Drop the store's copy of linked bytes (they are read again when next loaded). + pub fn evict(&self) { + if self.is_linked() { + store::global().evict(self.key); + } + } + + pub fn key(&self) -> SourceKey { + self.key + } + + /// The size of the bytes. + pub fn len(&self) -> u64 { + match &self.repr { + Repr::Embedded(b) => b.len() as u64, + Repr::Linked(l) => l.source.len, + } + } + + pub fn is_empty(&self) -> bool { + self.len() == 0 + } + + pub fn is_linked(&self) -> bool { + matches!(self.repr, Repr::Linked(_)) + } + + /// A handle that doesn't keep embedded bytes alive, and upgrades to this value (same key) + /// while anything else does. + pub fn downgrade(&self) -> WeakAssetData { + let repr = match &self.repr { + Repr::Embedded(b) => WeakRepr::Embedded(Arc::downgrade(b)), + Repr::Linked(l) => WeakRepr::Linked(Arc::clone(l)), + }; + WeakAssetData { key: self.key, repr } + } +} + +/// Advances when linked files may have come back or changed ([`links_changed`]). +static LINK_GENERATION: AtomicU64 = AtomicU64::new(0); + +/// Say that linked files may have changed on disk (a relink, an update, a status check): caches +/// that remembered a linked file as unavailable ask for it again. +pub fn links_changed() { + LINK_GENERATION.fetch_add(1, Ordering::AcqRel); +} + +/// The count [`links_changed`] advances. +pub fn link_generation() -> u64 { + LINK_GENERATION.load(Ordering::Acquire) +} + +#[derive(Clone)] +enum WeakRepr { + Embedded(Weak>), + Linked(Arc), +} + +/// [`AssetData::downgrade`]. +#[derive(Clone)] +pub struct WeakAssetData { + key: SourceKey, + repr: WeakRepr, +} + +impl WeakAssetData { + /// The value, while its embedded bytes are held elsewhere. + pub fn upgrade(&self) -> Option { + let repr = match &self.repr { + WeakRepr::Embedded(w) => Repr::Embedded(w.upgrade()?), + WeakRepr::Linked(l) => Repr::Linked(Arc::clone(l)), + }; + Some(AssetData { key: self.key, repr }) + } + + pub fn key(&self) -> SourceKey { + self.key + } +} + +impl fmt::Debug for WeakAssetData { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("WeakAssetData").field("key", &self.key.0).finish() + } +} + +/// New embedded bytes ([`AssetData::embedded`]). +impl From> for AssetData { + fn from(bytes: Vec) -> Self { + AssetData::embedded(bytes) + } +} + +impl Default for AssetData { + fn default() -> Self { + AssetData::embedded(Vec::new()) + } +} + +/// Embedded bytes compare by content; linked ones are equal only as the same version. +impl PartialEq for AssetData { + fn eq(&self, other: &Self) -> bool { + match (&self.repr, &other.repr) { + (Repr::Embedded(a), Repr::Embedded(b)) => a == b, + (Repr::Linked(a), Repr::Linked(b)) => self.key == other.key && a.source.len == b.source.len, + _ => false, + } + } +} + +impl fmt::Debug for AssetData { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let kind = if self.is_linked() { "Linked" } else { "Embedded" }; + f.debug_struct(kind).field("key", &self.key.0).field("len", &self.len()).finish() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + pub(super) fn source(path: &str, len: u64) -> LinkedSource { + LinkedSource { path: path.into(), relative: None, document: None, len, fingerprint: None, hash: None } + } + + #[test] + fn clones_keep_the_key_and_new_bytes_get_a_new_one() { + let a = AssetData::embedded(vec![1, 2, 3]); + let b = a.clone(); + assert_eq!(a.key(), b.key()); + let c = AssetData::embedded(vec![1, 2, 3]); + assert_ne!(a.key(), c.key()); + assert_eq!(a, c, "embedded bytes compare by content"); + let shared = AssetData::embedded(Arc::clone(a.embedded_bytes().unwrap())); + assert_ne!(a.key(), shared.key(), "wrapping bytes again names a new version"); + assert_eq!(a.load().unwrap().as_slice(), [1, 2, 3]); + assert_eq!(a.len(), 3); + let weak = a.downgrade(); + assert_eq!(weak.upgrade().map(|d| d.key()), Some(a.key())); + drop((a, b)); + assert!(weak.upgrade().is_some(), "`shared` still holds the bytes"); + drop(shared); + assert!(weak.upgrade().is_none()); + } + + #[test] + fn linked_assets_keep_their_key_only_for_the_same_bytes() { + let mut s = source("/nowhere/no-loader.png", 10); + let l = AssetData::linked(s.clone()); + assert!(l.is_linked()); + assert_eq!(l.len(), 10); + assert!(l.embedded_bytes().is_none() && l.resident().is_none()); + assert!(AssetData::default().is_empty()); + assert_ne!(l.with_source(s.clone()).key(), l.key(), "no hash: nothing says the bytes are the same"); + s.hash = Some("sha256:00".into()); + let hashed = AssetData::linked(s.clone()); + s.path = "/elsewhere/no-loader.png".into(); + let moved = hashed.with_source(s.clone()); + assert_eq!((moved.key(), moved.linked_source().map(|s| s.path.as_str())), (hashed.key(), Some("/elsewhere/no-loader.png"))); + s.hash = Some("sha256:01".into()); + assert_ne!(hashed.with_source(s).key(), hashed.key(), "other bytes, another key"); + let weak = hashed.downgrade(); + drop(hashed); + assert!(weak.upgrade().is_some(), "a linked value holds no bytes to let go of"); + } + + #[test] + fn a_link_record_names_its_source() { + let fingerprint = Fingerprint { size: 7, mtime: 9 }; + let asset = crate::Asset { + link: Some("/a/b.png".into()), + link_relative: Some("b.png".into()), + link_fingerprint: Some(fingerprint), + link_hash: Some("sha256:ab".into()), + ..Default::default() + }; + let s = LinkedSource::of(&asset, Some(Path::new("/a/doc.dcx"))).unwrap(); + assert_eq!( + (s.len, s.fingerprint, s.relative.as_deref(), s.document.as_deref()), + (7, Some(fingerprint), Some("b.png"), Some(Path::new("/a/doc.dcx"))) + ); + assert!(LinkedSource::of(&crate::Asset { link_fingerprint: None, ..asset }, None).is_none(), "the size comes from the fingerprint"); + } +} diff --git a/crates/doc/src/asset_data/store.rs b/crates/doc/src/asset_data/store.rs new file mode 100644 index 000000000..787289a38 --- /dev/null +++ b/crates/doc/src/asset_data/store.rs @@ -0,0 +1,370 @@ +//! The process-wide store of linked files' bytes ([`super::AssetData::load`]). + +use std::collections::HashMap; +use std::sync::{Arc, Condvar, LazyLock, Mutex, MutexGuard, PoisonError, RwLock}; + +use super::{Linked, LinkedSource, SourceKey, Unavailable}; +use crate::datamerge::Fingerprint; + +/// Linked bytes kept in memory at most, over all files. A file larger than this is read for the +/// one load that asks for it and not kept. +pub const STORE_BUDGET: u64 = 512 << 20; + +/// The largest linked file read: a larger one is [`Unavailable::TooLarge`]. +pub const MAX_LINKED_BYTES: u64 = 1 << 30; + +/// A linked file's bytes as a [`Loader`] read them. +pub struct Loaded { + pub bytes: Vec, + /// The fingerprint the file had, when its bytes were found to be the expected ones by their + /// hash: later loads trust that fingerprint as they trust [`LinkedSource::fingerprint`]. + pub fingerprint: Option, +} + +/// Reads linked files (the engine's, [`install_loader`]). +pub trait Loader: Send + Sync { + /// The bytes of the file `source` names, if it holds the expected ones: its size is + /// `source.len`, and its fingerprint is `source.fingerprint` or `trusted`, or its content + /// hash is `source.hash`. Other bytes are [`Unavailable::Modified`]; no file is + /// [`Unavailable::Missing`]; one over [`MAX_LINKED_BYTES`] is [`Unavailable::TooLarge`]. + fn load(&self, source: &LinkedSource, trusted: Option) -> Result; + + /// The bytes the file `source` names has now, whatever they are (for output that uses the + /// current file of a modified link). Never cached. + fn load_current(&self, _source: &LinkedSource) -> Result, Unavailable> { + Err(Unavailable::NoLoader) + } + + /// Whether the file `source` names still holds `kept`, the bytes read from it earlier: by its + /// fingerprint as [`Self::load`] goes by it, else by its content hash, or for a source without + /// a hash by its bytes. → the file's fingerprint when it was read to tell, else `None`; + /// [`Unavailable::Modified`] when the files there hold other bytes. A loader that can't look + /// takes the kept bytes as the file's. + fn holds(&self, _source: &LinkedSource, _trusted: Option, _kept: &[u8]) -> Result, Unavailable> { + Ok(None) + } +} + +static LOADER: RwLock>> = RwLock::new(None); + +/// Read linked files with `loader` from now on (in the whole process). +pub fn install_loader(loader: Arc) { + *LOADER.write().unwrap_or_else(PoisonError::into_inner) = Some(loader); +} + +pub(super) fn installed() -> Option> { + LOADER.read().unwrap_or_else(PoisonError::into_inner).clone() +} + +pub(super) fn global() -> &'static Store { + static STORE: LazyLock = LazyLock::new(|| Store::new(STORE_BUDGET, MAX_LINKED_BYTES)); + &STORE +} + +type Outcome = Result>, Unavailable>; + +/// One load in progress, which the other loads of the same bytes wait for. +#[derive(Default)] +struct Flight { + outcome: Mutex>, + landed: Condvar, +} + +impl Flight { + fn wait(&self) -> Outcome { + let mut g = self.outcome.lock().unwrap_or_else(PoisonError::into_inner); + loop { + if let Some(outcome) = g.as_ref() { + return outcome.clone(); + } + g = self.landed.wait(g).unwrap_or_else(PoisonError::into_inner); + } + } +} + +struct Kept { + bytes: Arc>, + stamp: u64, +} + +#[derive(Default)] +struct Inner { + kept: HashMap, + flights: HashMap>, + bytes: u64, + clock: u64, +} + +impl Inner { + /// The bytes kept under `key`, marked used. + fn touch(&mut self, key: SourceKey) -> Option>> { + self.clock += 1; + let clock = self.clock; + self.kept.get_mut(&key).map(|k| { + k.stamp = clock; + Arc::clone(&k.bytes) + }) + } + + /// Keep `bytes` under `key`, dropping the least recently used others beyond `budget`. + fn keep(&mut self, key: SourceKey, bytes: Arc>, budget: u64) { + self.clock += 1; + let n = bytes.len() as u64; + if let Some(old) = self.kept.insert(key, Kept { bytes, stamp: self.clock }) { + self.bytes = self.bytes.saturating_sub(old.bytes.len() as u64); + } + self.bytes = self.bytes.saturating_add(n); + while self.bytes > budget { + let Some(oldest) = self.kept.iter().filter(|(k, _)| **k != key).min_by_key(|(_, k)| k.stamp).map(|(k, _)| *k) else { break }; + if let Some(old) = self.kept.remove(&oldest) { + self.bytes = self.bytes.saturating_sub(old.bytes.len() as u64); + } + } + } +} + +/// A single-flight, least-recently-used store of loaded bytes by [`SourceKey`]. +pub(super) struct Store { + inner: Mutex, + budget: u64, + cap: u64, +} + +/// Lands a flight when dropped: with its outcome, or as missing when the loader panicked, so +/// the loads waiting for it don't wait forever. +struct Landing<'a> { + store: &'a Store, + key: SourceKey, + flight: Arc, + outcome: Option, +} + +impl Drop for Landing<'_> { + fn drop(&mut self) { + let outcome = self.outcome.take().unwrap_or(Err(Unavailable::Missing)); + { + let mut g = self.store.lock(); + g.flights.remove(&self.key); + if let Ok(bytes) = &outcome + && bytes.len() as u64 <= self.store.budget + { + g.keep(self.key, Arc::clone(bytes), self.store.budget); + } + } + *self.flight.outcome.lock().unwrap_or_else(PoisonError::into_inner) = Some(outcome); + self.flight.landed.notify_all(); + } +} + +impl Store { + pub(super) fn new(budget: u64, cap: u64) -> Self { + Store { inner: Mutex::new(Inner::default()), budget, cap } + } + + fn lock(&self) -> MutexGuard<'_, Inner> { + self.inner.lock().unwrap_or_else(PoisonError::into_inner) + } + + /// The bytes of `linked`, kept under `key`: from the store, from a load of them in progress, + /// or read by `loader`. + pub(super) fn load(&self, key: SourceKey, linked: &Linked, loader: Option<&dyn Loader>) -> Outcome { + if linked.source.len > self.cap { + return Err(Unavailable::TooLarge); + } + let flight = { + let mut g = self.lock(); + if let Some(bytes) = g.touch(key) { + return Ok(bytes); + } + if let Some(f) = g.flights.get(&key).cloned() { + drop(g); + return f.wait(); + } + let Some(loader) = loader else { return Err(Unavailable::NoLoader) }; + let f = Arc::new(Flight::default()); + g.flights.insert(key, Arc::clone(&f)); + (f, loader) + }; + let (flight, loader) = flight; + let mut landing = Landing { store: self, key, flight, outcome: None }; + // Read outside the lock: other bytes load and are found meanwhile. + let outcome = match loader.load(&linked.source, linked.trusted()) { + Ok(l) if l.bytes.len() as u64 > self.cap => Err(Unavailable::TooLarge), + Ok(l) => { + if let Some(fingerprint) = l.fingerprint { + linked.trust(fingerprint); + } + Ok(Arc::new(l.bytes)) + } + Err(e) => Err(e), + }; + landing.outcome = Some(outcome.clone()); + drop(landing); + outcome + } + + /// The bytes kept under `key`, without loading them. + pub(super) fn resident(&self, key: SourceKey) -> Option>> { + self.lock().touch(key) + } + + /// Keep `bytes` under `key` as if a load had read them (not when over the budget). + pub(super) fn keep(&self, key: SourceKey, bytes: Arc>) { + if bytes.len() as u64 <= self.budget { + self.lock().keep(key, bytes, self.budget); + } + } + + pub(super) fn evict(&self, key: SourceKey) { + let mut g = self.lock(); + if let Some(old) = g.kept.remove(&key) { + g.bytes = g.bytes.saturating_sub(old.bytes.len() as u64); + } + } + + #[cfg(test)] + fn kept_bytes(&self) -> u64 { + self.lock().bytes + } +} + +#[cfg(test)] +mod tests { + use super::super::tests::source; + use super::super::{AssetData, Repr}; + use super::*; + use std::sync::atomic::{AtomicUsize, Ordering}; + + /// Serves `len` bytes of `fill` for every path, counting its reads; slow, so loads overlap. + #[derive(Default)] + struct Counting { + reads: AtomicUsize, + delay_ms: u64, + fail: Option, + trusted: Mutex>>, + } + + impl Loader for Counting { + fn load(&self, source: &LinkedSource, trusted: Option) -> Result { + self.reads.fetch_add(1, Ordering::SeqCst); + self.trusted.lock().unwrap().push(trusted); + std::thread::sleep(std::time::Duration::from_millis(self.delay_ms)); + if let Some(e) = self.fail { + return Err(e); + } + let fill = source.path.bytes().last().unwrap_or(0); + Ok(Loaded { bytes: vec![fill; source.len as usize], fingerprint: Some(Fingerprint { size: source.len, mtime: 5 }) }) + } + } + + fn linked(data: &AssetData) -> &Linked { + match &data.repr { + Repr::Linked(l) => l, + Repr::Embedded(_) => panic!("not linked"), + } + } + + fn load(store: &Store, data: &AssetData, loader: &dyn Loader) -> Outcome { + store.load(data.key(), linked(data), Some(loader)) + } + + #[test] + fn linked_bytes_are_read_once_and_kept() { + let store = Store::new(100, 1000); + let loader = Counting::default(); + let a = AssetData::linked(source("a", 10)); + assert_eq!(load(&store, &a, &loader).unwrap().as_slice(), [b'a'; 10]); + assert_eq!(load(&store, &a.clone(), &loader).unwrap().len(), 10); + assert_eq!(loader.reads.load(Ordering::SeqCst), 1); + assert_eq!(store.resident(a.key()).map(|b| b.len()), Some(10)); + assert_eq!(*loader.trusted.lock().unwrap(), [None]); + store.evict(a.key()); + load(&store, &a, &loader).unwrap(); + assert_eq!(loader.reads.load(Ordering::SeqCst), 2, "evicted bytes are read again"); + assert_eq!( + loader.trusted.lock().unwrap().last(), + Some(&Some(Fingerprint { size: 10, mtime: 5 })), + "a hash-checked fingerprint is trusted next time" + ); + assert_eq!(AssetData::linked(source("x", 1)).load(), Err(Unavailable::NoLoader), "no loader installed in these tests"); + } + + #[test] + fn the_least_recently_used_bytes_go_past_the_budget() { + let store = Store::new(100, 1000); + let loader = Counting::default(); + let [a, b, c] = ["a", "b", "c"].map(|p| AssetData::linked(source(p, 40))); + load(&store, &a, &loader).unwrap(); + load(&store, &b, &loader).unwrap(); + load(&store, &a, &loader).unwrap(); + load(&store, &c, &loader).unwrap(); + assert!(store.resident(b.key()).is_none(), "b was used least recently"); + assert!(store.resident(a.key()).is_some() && store.resident(c.key()).is_some()); + assert_eq!(store.kept_bytes(), 80); + } + + #[test] + fn a_file_over_the_budget_is_returned_but_not_kept_and_one_over_the_cap_is_not_read() { + let store = Store::new(100, 1000); + let loader = Counting::default(); + let small = AssetData::linked(source("s", 50)); + load(&store, &small, &loader).unwrap(); + let big = AssetData::linked(source("b", 200)); + assert_eq!(load(&store, &big, &loader).unwrap().len(), 200); + assert!(store.resident(big.key()).is_none()); + assert!(store.resident(small.key()).is_some(), "an unkept file evicts nothing"); + let huge = AssetData::linked(source("h", 1001)); + assert_eq!(load(&store, &huge, &loader), Err(Unavailable::TooLarge)); + assert_eq!(loader.reads.load(Ordering::SeqCst), 2); + } + + #[test] + fn concurrent_loads_of_the_same_bytes_read_once() { + let store = Store::new(1000, 1000); + let loader = Counting { delay_ms: 50, ..Default::default() }; + let a = AssetData::linked(source("a", 10)); + let got: Vec = std::thread::scope(|s| { + let handles: Vec<_> = (0..8).map(|_| s.spawn(|| load(&store, &a, &loader))).collect(); + handles.into_iter().map(|h| h.join().unwrap()).collect() + }); + assert!(got.iter().all(|g| g.as_ref().is_ok_and(|b| b.len() == 10))); + assert_eq!(loader.reads.load(Ordering::SeqCst), 1); + } + + #[test] + fn a_failed_load_is_shared_and_tried_again_later() { + let store = Store::new(1000, 1000); + let loader = Counting { delay_ms: 30, fail: Some(Unavailable::Modified), ..Default::default() }; + let a = AssetData::linked(source("a", 10)); + let got: Vec = std::thread::scope(|s| { + let handles: Vec<_> = (0..4).map(|_| s.spawn(|| load(&store, &a, &loader))).collect(); + handles.into_iter().map(|h| h.join().unwrap()).collect() + }); + assert!(got.iter().all(|g| *g == Err(Unavailable::Modified))); + assert!(store.resident(a.key()).is_none(), "nothing adopted"); + let reads = loader.reads.load(Ordering::SeqCst); + load(&store, &a, &loader).unwrap_err(); + assert_eq!(loader.reads.load(Ordering::SeqCst), reads + 1, "failures aren't remembered here"); + } + + /// A loader that panics lands its flight: the loads waiting for it return. + #[test] + fn a_panicking_loader_does_not_hang_the_waiters() { + struct Panics; + impl Loader for Panics { + fn load(&self, _: &LinkedSource, _: Option) -> Result { + std::thread::sleep(std::time::Duration::from_millis(30)); + panic!("loader fault"); + } + } + let store = Store::new(1000, 1000); + let a = AssetData::linked(source("a", 10)); + std::thread::scope(|s| { + let first = s.spawn(|| load(&store, &a, &Panics)); + std::thread::sleep(std::time::Duration::from_millis(5)); + let waiter = s.spawn(|| load(&store, &a, &Panics)); + assert!(first.join().is_err()); + assert!(waiter.join().is_ok_and(|r| r.is_err())); + }); + } +} diff --git a/crates/doc/src/assets.rs b/crates/doc/src/assets.rs index 1533b8b4b..18f07326f 100644 --- a/crates/doc/src/assets.rs +++ b/crates/doc/src/assets.rs @@ -9,7 +9,7 @@ use std::hash::BuildHasher; use std::sync::Arc; use crate::story::Story; -use crate::{Asset, AssetId, Content, Document, Item}; +use crate::{Asset, AssetId, Content, Document, Fingerprint, Item}; /// Nesting limit for groups, anchored objects, table cells and notes. A document nested deeper /// is treated as using every asset, so nothing it references is merged away or pruned. @@ -82,6 +82,14 @@ impl Document { } impl Asset { + /// Link the asset to another file, or to none (embedded). The size and time kept with a link + /// ([`Asset::link_fingerprint`]) never outlive it: `loaded` is the new file's when `data` was + /// read from it, and `None` when it wasn't (a copy of the bytes, a file found again by name). + pub fn set_link(&mut self, link: Option, loaded: Option) { + self.link_fingerprint = loaded.filter(|_| link.is_some()); + self.link = link; + } + /// Whether `other` holds the same file: the same type, PDF page and crop, link and bytes. Files at /// different paths stay apart even with identical bytes, since each can be updated or /// relinked on its own. Assets without bytes (a link that couldn't be read) are the same only @@ -100,8 +108,23 @@ impl Asset { } } + /// The same bytes: the same version, or equal embedded bytes. Linked bytes aren't read here. fn same_bytes(&self, other: &Asset) -> bool { - Arc::ptr_eq(&self.data, &other.data) || (self.data.len() == other.data.len() && *self.data == *other.data) + if self.data.key() == other.data.key() { + return true; + } + match (self.data.embedded_bytes(), other.data.embedded_bytes()) { + (Some(a), Some(b)) => Arc::ptr_eq(a, b) || (a.len() == b.len() && **a == **b), + _ => false, + } + } + + /// A hash that is equal for assets with [`Asset::same_bytes`]. + fn bytes_hash(&self, state: &std::collections::hash_map::RandomState) -> u64 { + match self.data.embedded_bytes() { + Some(b) => state.hash_one(b.as_slice()), + None => state.hash_one(self.data.key()), + } } } @@ -112,20 +135,70 @@ pub fn find_same_asset(assets: &BTreeMap>, asset: &Asset) -> /// Add `asset` to `assets` unless they already hold the same file; returns the id placements /// should reference. A new asset with the bytes of an existing one shares its buffer. +/// +/// This scans `assets`; an importer adding many files uses an [`AssetIndex`] instead. pub fn insert_asset(assets: &mut BTreeMap>, mut asset: Asset) -> AssetId { - if let Some(id) = find_same_asset(assets, &asset) { + // An empty, unlinked asset never holds the same file as another: nothing to search for. + if (!asset.data.is_empty() || asset.link.is_some()) + && let Some(id) = find_same_asset(assets, &asset) + { return id; } if !asset.data.is_empty() && let Some(a) = assets.values().find(|a| a.same_bytes(&asset)) { - asset.data = Arc::clone(&a.data); + asset.data = a.data.clone(); } let id = asset.id; assets.insert(id, Arc::new(asset)); id } +/// A lookup of the assets added through it, by content, so that adding many files (an import) +/// costs time in proportion to their number rather than its square. It only knows the assets +/// it inserted: use one index per asset map, and add every asset through it. +#[derive(Debug, Default)] +pub struct AssetIndex { + fingerprint: std::collections::hash_map::RandomState, + /// Candidates for [`Asset::same_file`]: (bytes fingerprint, type, page, link). + files: HashMap<(u64, String, u32, Option), Vec>, + /// One asset per distinct non-empty byte content, for buffer sharing. + bytes: HashMap>, +} + +impl AssetIndex { + pub fn new() -> Self { + Self::default() + } + + /// [`insert_asset`], looking up candidates by fingerprint instead of scanning `assets`. + /// A fingerprint only selects candidates; equality still compares the actual files. + pub fn insert_asset(&mut self, assets: &mut BTreeMap>, mut asset: Asset) -> AssetId { + // Empty, unlinked assets never compare equal: don't search for or index them. + if asset.data.is_empty() && asset.link.is_none() { + let id = asset.id; + assets.insert(id, Arc::new(asset)); + return id; + } + let hash = asset.bytes_hash(&self.fingerprint); + let key = (hash, asset.mime.clone(), asset.page, asset.link.clone()); + if let Some(id) = self.files.get(&key).and_then(|ids| ids.iter().copied().find(|id| assets.get(id).is_some_and(|a| a.same_file(&asset)))) { + return id; + } + if !asset.data.is_empty() { + let bucket = self.bytes.entry(hash).or_default(); + match bucket.iter().find_map(|id| assets.get(id).filter(|a| a.same_bytes(&asset))) { + Some(a) => asset.data = a.data.clone(), + None => bucket.push(asset.id), + } + } + let id = asset.id; + self.files.entry(key).or_default().push(id); + assets.insert(id, Arc::new(asset)); + id + } +} + /// Calls `f` with every asset reference in `it` and its children; false when nesting exceeded /// [`MAX_DEPTH`] (some references weren't visited). fn item_refs(it: &Item, f: &mut impl FnMut(AssetId), depth: usize) -> bool { @@ -323,7 +396,7 @@ impl Document { if a.data.is_empty() && a.link.is_none() { continue; } - let hash = *hashes.entry(Arc::as_ptr(&a.data)).or_insert_with(|| fingerprint.hash_one(a.data.as_slice())); + let hash = *hashes.entry(a.data.key()).or_insert_with(|| a.bytes_hash(&fingerprint)); let bucket = reps.entry((hash, a.mime.as_str(), a.page, a.link.as_deref())).or_default(); // A fingerprint only selects candidates; equality still checks the actual file. match bucket.iter().find(|r| r.same_file(a)) { @@ -353,7 +426,13 @@ mod tests { use designcraft_geom::{Affine, Rect, shapes}; fn asset(id: u64, data: &[u8]) -> Asset { - Asset { id: AssetId(id), name: "p.png".into(), mime: "image/png".into(), data: Arc::new(data.to_vec()), ..Default::default() } + Asset { + id: AssetId(id), + name: "p.png".into(), + mime: "image/png".into(), + data: crate::AssetData::embedded(data.to_vec()), + ..Default::default() + } } #[test] @@ -368,7 +447,7 @@ mod tests { assert_eq!(d.merge_duplicate_assets(), 256); assert_eq!(d.assets.len(), 256); for id in 1..=256u64 { - assert_eq!(d.assets[&AssetId(id)].data[1016..], id.to_le_bytes()); + assert_eq!(d.assets[&AssetId(id)].data.embedded_bytes().unwrap()[1016..], id.to_le_bytes()); } } @@ -463,6 +542,57 @@ mod tests { assert_ne!(m3, m4); } + /// The index dedupes exactly as the scan does, and skips empty unlinked assets. + #[test] + fn indexed_insert_matches_scanning_insert() { + let linked = |id, path: &str, data: &[u8]| Asset { link: Some(path.into()), ..asset(id, data) }; + let cases = vec![ + asset(1, b"same"), + asset(2, b"same"), + asset(3, b"diff"), + Asset { page: 1, ..asset(4, b"same") }, + linked(5, "/p/a.png", b"same"), + linked(6, "/q/b.png", b"same"), + linked(7, "/p/a.png", b"same"), + linked(8, "/m/1.png", b""), + linked(9, "/m/1.png", b""), + asset(10, b""), + asset(11, b""), + ]; + let mut scanned = BTreeMap::new(); + let mut indexed = BTreeMap::new(); + let mut index = AssetIndex::new(); + for a in cases { + let s = insert_asset(&mut scanned, a.clone()); + let i = index.insert_asset(&mut indexed, a); + assert_eq!(s, i); + } + assert_eq!(scanned.keys().collect::>(), indexed.keys().collect::>()); + assert!( + Arc::ptr_eq(indexed[&AssetId(5)].data.embedded_bytes().unwrap(), indexed[&AssetId(6)].data.embedded_bytes().unwrap()), + "identical bytes share one buffer" + ); + } + + /// Many empty unlinked placements (graphics with neither bytes nor a link) insert without + /// comparing against each other. + #[test] + fn many_empty_unlinked_assets_insert_quickly() { + let mut assets = BTreeMap::new(); + let mut index = AssetIndex::new(); + for id in 1..=200_000u64 { + assert_eq!(insert_asset(&mut assets, asset(id, b"")), AssetId(id)); + } + assert_eq!(assets.len(), 200_000); + let mut indexed = BTreeMap::new(); + for id in 1..=20_000u64 { + let mut bytes = vec![7; 64]; + bytes[56..].copy_from_slice(&id.to_le_bytes()); + assert_eq!(index.insert_asset(&mut indexed, asset(id, &bytes)), AssetId(id)); + } + assert_eq!(indexed.len(), 20_000); + } + #[test] fn files_at_different_paths_stay_separate_assets() { let mut d = Document::new(&Default::default()); @@ -475,7 +605,10 @@ mod tests { assert!(embedded != a && a != b && embedded != b); assert_eq!(d.assets[&embedded].link, None); assert_eq!(d.assets[&b].link.as_deref(), Some("/q/b.png")); - assert!(Arc::ptr_eq(&d.assets[&a].data, &d.assets[&b].data), "identical bytes share one buffer"); + assert!( + Arc::ptr_eq(d.assets[&a].data.embedded_bytes().unwrap(), d.assets[&b].data.embedded_bytes().unwrap()), + "identical bytes share one buffer" + ); } #[test] diff --git a/crates/doc/src/attrs/char_attrs.rs b/crates/doc/src/attrs/char_attrs.rs index 4f4cb9d52..154dbf741 100644 --- a/crates/doc/src/attrs/char_attrs.rs +++ b/crates/doc/src/attrs/char_attrs.rs @@ -86,7 +86,7 @@ attr_set! { kenten_font: String = String::new(), kenten_font_style: String = String::new(), /// Mark size in points; `None` is half the text size. - kenten_size: Option = None, + kenten_size: Option = None => "deserialize_explicit_value", /// Horizontal / vertical scale of the mark, 1.0 = 100%. kenten_x_scale: f64 = 1.0, kenten_y_scale: f64 = 1.0, @@ -99,10 +99,10 @@ attr_set! { /// Mark fill and stroke swatches (empty = the text's), tints and stroke weight (`None` = /// the text's). kenten_fill: String = String::new(), - kenten_fill_tint: Option = None, + kenten_fill_tint: Option = None => "deserialize_explicit_value", kenten_stroke: String = String::new(), - kenten_stroke_tint: Option = None, - kenten_stroke_weight: Option = None, + kenten_stroke_tint: Option = None => "deserialize_explicit_value", + kenten_stroke_weight: Option = None => "deserialize_explicit_value", kenten_overprint_fill: crate::cjk_settings::AdornmentOverprint = crate::cjk_settings::AdornmentOverprint::Auto, kenten_overprint_stroke: crate::cjk_settings::AdornmentOverprint = crate::cjk_settings::AdornmentOverprint::Auto, // Shatai (斜体): the character is compressed across the direction at `shatai_angle`. @@ -126,7 +126,7 @@ attr_set! { ruby_font: String = String::new(), ruby_font_style: String = String::new(), /// Points; `None` is half the parent size. - ruby_font_size: Option = None, + ruby_font_size: Option = None => "deserialize_explicit_value", /// 1.0 = 100%. ruby_x_scale: f64 = 1.0, ruby_y_scale: f64 = 1.0, @@ -147,10 +147,10 @@ attr_set! { ruby_scaling_min: f64 = 0.66, /// Ruby colour: empty is the text's colour; `None` tint and weight follow the text. ruby_fill: String = String::new(), - ruby_fill_tint: Option = None, + ruby_fill_tint: Option = None => "deserialize_explicit_value", ruby_stroke: String = String::new(), - ruby_stroke_tint: Option = None, - ruby_stroke_weight: Option = None, + ruby_stroke_tint: Option = None => "deserialize_explicit_value", + ruby_stroke_weight: Option = None => "deserialize_explicit_value", ruby_overprint_fill: crate::cjk_settings::AdornmentOverprint = crate::cjk_settings::AdornmentOverprint::Auto, ruby_overprint_stroke: crate::cjk_settings::AdornmentOverprint = crate::cjk_settings::AdornmentOverprint::Auto, /// Digits (World-Ready): how 0–9 are drawn. diff --git a/crates/doc/src/attrs/language.rs b/crates/doc/src/attrs/language.rs index 35ac044a1..a116bf754 100644 --- a/crates/doc/src/attrs/language.rs +++ b/crates/doc/src/attrs/language.rs @@ -88,6 +88,7 @@ pub fn language_tag(language: &str) -> Option<&'static str> { "urdu" => "ur", "hebrew" => "he", "georgian" => "ka", + "esperanto" => "eo", _ => return None, }) } diff --git a/crates/doc/src/attrs/para_attrs.rs b/crates/doc/src/attrs/para_attrs.rs index 17edc8cc1..b4f356b10 100644 --- a/crates/doc/src/attrs/para_attrs.rs +++ b/crates/doc/src/attrs/para_attrs.rs @@ -113,7 +113,10 @@ attr_set! { kinsoku: Option = None => "deserialize_explicit_value", /// Preserved spacing-table reference; compatibility audit reports unsupported composition. mojikumi: String = String::new(), - /// Preserved priority policy; the current breaker does not implement these priorities. + /// JIS X 4051 禁則処理 type, applied by both composers to CJK text: empty (the default) + /// and `KinsokuPushInFirst` compose as push-in-first, `KinsokuPushOutFirst`, + /// `KinsokuPushOutOnly` and `KinsokuPrioritizeAdjustmentAmount` (minimum adjustment) as + /// their names say. kinsoku_type: String = String::new(), kinsoku_hang: crate::cjk::KinsokuHang = crate::cjk::KinsokuHang::None, bunri_kinshi: bool = false, @@ -141,6 +144,9 @@ attr_set! { shading_on: bool = false, shading_color: String = "[Black]".into(), shading_tint: f32 = 0.2, + /// Overprint (InDesign's Paragraph Shading › Overprint): stored and kept through IDML; + /// PDF export doesn't overprint yet. + shading_overprint: bool = false, shading_offsets: [f64; 4] = [0.0; 4], /// Paragraph border: stroke weights (top, left, bottom, right), colour, and offsets past the /// text (top, left, bottom, right). @@ -148,6 +154,8 @@ attr_set! { border_weights: [f64; 4] = [1.0; 4], border_color: String = "[Black]".into(), border_tint: f32 = 1.0, + /// Overprint the border's stroke (stored and kept through IDML, as `ParagraphBorderOverprint`). + border_overprint: bool = false, border_offsets: [f64; 4] = [0.0; 4], /// The border's stroke type (a document stroke style by name, or a built-in type), cap and /// join. @@ -167,6 +175,8 @@ attr_set! { /// The colour between the dashes, dots or stripes of a border that isn't solid. border_gap_color: String = "[None]".into(), border_gap_tint: f32 = 1.0, + /// Overprint the border's gap colour (stored and kept through IDML). + border_gap_overprint: bool = false, /// Shading corners: top left, top right, bottom right, bottom left. shading_corners: [designcraft_geom::corners::Corner; 4] = [designcraft_geom::corners::Corner::default(); 4], shading_width: BoxWidth = BoxWidth::Column, @@ -188,7 +198,7 @@ attr_set! { bullet_align: ListAlign = ListAlign::Left, number_align: ListAlign = ListAlign::Left, /// A tab stop for the text after the bullet or number, from the column's left edge. - list_tab: Option = None, + list_tab: Option = None => "deserialize_explicit_value", /// Restart Numbers at This Level After: a paragraph at a higher level (0 = any; otherwise /// that level) starts this level's numbering again. restart_numbers: bool = true, @@ -222,8 +232,11 @@ impl ParaAttrs { let serde_json::Value::Object(patch) = value else { return self.set_json(key, value) }; let mut merged = serde_json::to_value(rule).map_err(|e| format!("{key}: {e}"))?; let serde_json::Value::Object(fields) = &mut merged else { return Err(format!("{key}: not an object")) }; + // Every field, those at their defaults (left out of the JSON) included. + const RULE_FIELDS: [&str; 12] = + ["on", "weight", "color", "tint", "columnWidth", "offset", "leftIndent", "rightIndent", "type", "gapColor", "gapTint", "keepInFrame"]; for (k, v) in patch { - if !fields.contains_key(k) { + if !RULE_FIELDS.contains(&k.as_str()) { return Err(format!("{key}: unknown rule field `{k}`")); } fields.insert(k.clone(), v.clone()); diff --git a/crates/doc/src/attrs/rules_lists.rs b/crates/doc/src/attrs/rules_lists.rs index f4ef952e4..4b36c3baf 100644 --- a/crates/doc/src/attrs/rules_lists.rs +++ b/crates/doc/src/attrs/rules_lists.rs @@ -17,11 +17,46 @@ pub struct Rule { pub offset: f64, pub left_indent: f64, pub right_indent: f64, + /// Type: the rule's stroke type (solid, dashed, wavy…, or a stroke style of the document). + #[serde(rename = "type", skip_serializing_if = "rule_solid")] + pub kind: crate::item::StrokeType, + /// Gap Color (a swatch; [None]: none) and Gap Tint: under the gaps of a type that has them. + #[serde(skip_serializing_if = "rule_no_gap")] + pub gap_color: String, + #[serde(skip_serializing_if = "rule_full_tint")] + pub gap_tint: f32, + /// Keep In Frame: a rule above the first line of a frame stays inside the frame. + #[serde(skip_serializing_if = "std::ops::Not::not")] + pub keep_in_frame: bool, +} + +// A rule's settings at their defaults are left out of the document (and of the attributes). +fn rule_solid(k: &crate::item::StrokeType) -> bool { + *k == crate::item::StrokeType::Solid +} +fn rule_no_gap(c: &str) -> bool { + c == designcraft_color::swatch::NONE +} +fn rule_full_tint(t: &f32) -> bool { + *t == 1.0 } impl Default for Rule { fn default() -> Self { - Rule { on: false, weight: 1.0, color: TEXT_COLOR.into(), tint: 1.0, column_width: true, offset: 0.0, left_indent: 0.0, right_indent: 0.0 } + Rule { + on: false, + weight: 1.0, + color: TEXT_COLOR.into(), + tint: 1.0, + column_width: true, + offset: 0.0, + left_indent: 0.0, + right_indent: 0.0, + kind: crate::item::StrokeType::Solid, + gap_color: designcraft_color::swatch::NONE.into(), + gap_tint: 1.0, + keep_in_frame: false, + } } } diff --git a/crates/doc/src/attrs/tests.rs b/crates/doc/src/attrs/tests.rs index 068fbaee8..78c62b77b 100644 --- a/crates/doc/src/attrs/tests.rs +++ b/crates/doc/src/attrs/tests.rs @@ -87,6 +87,8 @@ fn language_names_map_to_bcp47_tags() { assert_eq!(language_tag("Farsi"), Some("fa")); assert_eq!(language_tag("Urdu"), Some("ur")); assert_eq!(language_tag("Hebrew"), Some("he")); + assert_eq!(language_tag("Esperanto"), Some("eo")); + assert_eq!(language_tag("$ID/Esperanto"), Some("eo")); assert_eq!(language_tag("[No Language]"), None); assert_eq!(language_tag("Klingon"), None); assert_eq!(language_tag(""), None); diff --git a/crates/doc/src/build.rs b/crates/doc/src/build.rs index c7259f317..1ee4ea1c4 100644 --- a/crates/doc/src/build.rs +++ b/crates/doc/src/build.rs @@ -148,6 +148,7 @@ impl Document { prefix: String::new(), marker: String::new(), include_prefix: false, + layout: None, }], assets: BTreeMap::new(), hyperlinks: vec![], @@ -164,6 +165,7 @@ impl Document { modified: 0, next_id: 0, font_scope: 0, + alpha_outlines: Vec::new(), }; let lid = LayerId(d.alloc()); d.layers.push(Layer { @@ -174,6 +176,7 @@ impl Document { locked: false, printable: true, show_guides: true, + lock_guides: false, suppress_wrap_when_hidden: false, }); // A-Parent. @@ -259,6 +262,31 @@ impl Document { id } + /// Add an empty copy of parent `id` after the last parent: the same pages (size, margins, columns, + /// guides) and base parent, fresh ids, prefix `prefix`. Returns the copy's id and index; the + /// caller copies the items. + pub fn duplicate_parent_shell(&mut self, id: SpreadId, prefix: &str) -> Result<(SpreadId, usize)> { + let src = self.parent_index(id).and_then(|i| self.parents.get(i)).ok_or_else(|| DocError::Invalid(format!("no parent {id}")))?; + let mut sp = Spread::clone(src); + sp.items.clear(); + for pg in &mut sp.pages { + pg.overridden.clear(); + } + sp.id = SpreadId(self.alloc()); + for k in 0..sp.pages.len() { + let pid = PageId(self.alloc()); + if let Some(pg) = sp.pages.get_mut(k) { + pg.id = pid; + } + } + if let Some(info) = sp.parent.as_mut() { + info.prefix = prefix.into(); + } + let new = sp.id; + self.parents.push(Arc::new(sp)); + Ok((new, self.parents.len().saturating_sub(1))) + } + /// Delete a parent spread and unapply it wherever it is used. Local overrides survive as /// ordinary items; the deleted parent's own items leave their text threads normally. pub fn delete_parent(&mut self, id: SpreadId) -> Result<()> { @@ -339,7 +367,10 @@ impl Document { /// number is a right page (a left page bound right to left), so a section that starts at 1 on /// a left page moves it to the right and the pages after it follow. pub fn repaginate(&mut self) { - let odd: Vec = (0..self.page_count()).map(|i| self.page_number(i) % 2 == 1).collect(); + let odd: Vec = self.page_numbers(self.page_count()).into_iter().map(|n| n % 2 == 1).collect(); + // A layout starts a spread of its own. + let layout_starts: HashSet = self.sections.iter().filter(|s| s.layout.is_some() && s.start > 0).map(|s| s.start).collect(); + let mut breaks: Vec = Vec::new(); // Collect pages with their items (items in page-relative coordinates) and their numbers' parity. let mut pages: Vec<(Page, Vec>)> = Vec::new(); let mut parity: Vec = Vec::new(); @@ -355,6 +386,7 @@ impl Document { } for p in &sp.pages { parity.push(odd.get(abs).copied().unwrap_or(abs % 2 == 0)); + breaks.push(layout_starts.contains(&abs)); was_left.insert(p.id, p.side == PageSide::Left); abs += 1; } @@ -419,7 +451,8 @@ impl Document { // A right page closes its spread, so two right pages in a row (a section restart // at an even position) never share one. let after_ending = cur.last().is_some_and(|(q, _)| q.side != starts); - if (p.side == starts || after_ending) && !cur.is_empty() { + let new_layout = breaks.get(i).copied().unwrap_or(false); + if (p.side == starts || after_ending || new_layout) && !cur.is_empty() { let id = SpreadId(self.alloc()); flush(&mut cur, &mut spreads, id); } @@ -473,6 +506,13 @@ impl Document { } let n = self.page_count(); let at = after.map_or(0, |a| a.saturating_add(1).min(n)); + // Sections (and the layouts they start) stay with their first page: the ones after the + // insertion point move along. Pages inserted after a layout's last page join that layout. + for sec in &mut self.sections { + if sec.start >= at && sec.start > 0 { + sec.start = sec.start.saturating_add(count); + } + } let template = self.page(at.saturating_sub(1).min(n.saturating_sub(1))).cloned(); let (cols, gutter, margins) = template.as_ref().map(|t| (t.columns.count, t.columns.gutter, t.margins)).unwrap_or((1, 12.0, Margins::uniform(36.0))); @@ -543,12 +583,14 @@ impl Document { /// Delete absolute pages (items whose centre is on a deleted page are deleted too). pub fn delete_pages(&mut self, pages: &[usize]) -> Result<()> { - if pages.len() >= self.page_count() { - return Err(DocError::Invalid("a document needs at least one page".into())); - } let mut doomed: Vec<(usize, usize)> = pages.iter().filter_map(|p| self.page_loc(*p)).collect(); doomed.sort(); doomed.dedup(); + // The pages it will remove, not the indices it was given: asking for [0, 0, 1, 2] of four + // pages removes three of them and leaves one, which is allowed. + if doomed.len() >= self.page_count() { + return Err(DocError::Invalid("a document needs at least one page".into())); + } let mut remove_items: Vec = Vec::new(); for &(si, pi) in &doomed { let sp = &self.spreads[si]; @@ -575,6 +617,18 @@ impl Document { sp.relayout(); } self.spreads.retain(|s| !s.pages.is_empty()); + // Sections follow their pages: a section whose first page is deleted starts at the next + // page left, unless another section already starts there (or no page is left). + let mut gone: Vec = pages.to_vec(); + gone.sort_unstable(); + gone.dedup(); + let left = self.page_count(); + let mut sections = std::mem::take(&mut self.sections); + for sec in &mut sections { + let before = gone.partition_point(|g| *g < sec.start); + sec.start = sec.start.saturating_sub(before); + } + self.sections = settle_sections(sections, left); self.repaginate(); Ok(()) } @@ -594,6 +648,23 @@ impl Document { self.repaginate(); let sp = self.spreads.remove(from); self.spreads.insert(to, sp); + // Sections (and the layouts they start) keep their first page wherever it moved; one whose + // first page moves away starts at its next page, as when that page is deleted. + let moved = |i: usize| { + if from < to && i > from && i <= to { + i.saturating_sub(1) + } else if to < from && i >= to && i < from { + i.saturating_add(1) + } else { + i + } + }; + let mut sections = std::mem::take(&mut self.sections); + for sec in sections.iter_mut().filter(|s| s.start > 0) { + sec.start = if sec.start == from { moved(from.saturating_add(1)) } else { moved(sec.start) }; + } + sections.sort_by_key(|s| s.start); + self.sections = settle_sections(sections, n); self.settings.facing_pages = facing; self.repaginate(); Ok(()) @@ -661,11 +732,18 @@ impl Document { } /// Parent page (spread index, page index) applied to `page`: the page on its side of its - /// parent spread. + /// parent spread, or in its place for single-sided pages ([`Spread::parent_page_at`]). pub fn parent_page_of(&self, page: &Page) -> Option<(usize, usize)> { let pi = self.parent_index(page.parent?)?; // A parent spread can come without pages from a file. - Some((pi, self.parents.get(pi)?.parent_page_for_side(page.side)?)) + let parent = self.parents.get(pi)?; + // Only a single-sided page's position matters: look for it only then. + let index = if page.side == PageSide::Single && parent.pages.len() >= 2 { + self.spreads.iter().find_map(|s| s.pages.iter().position(|p| p.id == page.id)).unwrap_or(0) + } else { + 0 + }; + Some((pi, parent.parent_page_at(page.side, index)?)) } /// The parent page applied to `page`. @@ -777,7 +855,21 @@ impl Document { c } }; - chain.into_iter().filter_map(|i| Some((i, self.parents.get(i)?.parent_page_for_side(pg.side)?))).collect() + chain.into_iter().filter_map(|i| Some((i, self.parents.get(i)?.parent_page_at(pg.side, page)?))).collect() + } + + /// The parent items page `page` of spread `sr` leaves out because they are overridden: the + /// page's own overrides and those of every parent page in [`Self::shown_parent_pages`]. A + /// parent page that overrode an item of its base and then deleted the override removed that + /// item from itself and from every page based on it (#1469). An override always names an item + /// of a parent further back, so one set covers the chain. + /// + /// Everything that works out which parent items a page shows -- drawing, PDF and PPTX export, + /// hit-testing, snapping, frame edges -- asks this, so they all hide the same items. + pub fn overridden_parent_items(&self, sr: SpreadRef, page: usize) -> HashSet { + let Some(pg) = self.spread(sr).and_then(|sp| sp.pages.get(page)) else { return HashSet::new() }; + let behind = self.shown_parent_pages(sr, page).into_iter().filter_map(|(ppi, ppage)| self.parents.get(ppi)?.pages.get(ppage)); + pg.overridden.iter().copied().chain(behind.flat_map(|p| p.overridden.iter().copied())).collect() } /// Whether basing parent `pi` on `base` would make a `based_on` cycle (or names no parent). @@ -801,18 +893,51 @@ impl Document { /// Clear `based_on` links that name a missing parent or close a cycle (hand-edited or damaged /// files). Returns one warning per link cleared. pub fn fix_parent_bases(&mut self) -> Vec { + // One id index and one walk over the `based_on` graph (each parent has at most one base), + // not an ancestor walk per parent. `parent_index` takes the first of duplicate ids; so does this. + let mut index = std::collections::HashMap::new(); + for (i, p) in self.parents.iter().enumerate() { + index.entry(p.id).or_insert(i); + } + let n = self.parents.len(); + let base = |i: usize| self.parents.get(i).and_then(|ps| ps.parent.as_ref()).and_then(|info| info.based_on); + // `clear[pi]`: why the link is cleared. 0 = unvisited, 1 = on the current walk, 2 = done. + let mut state = vec![0u8; n]; + let mut clear: Vec> = vec![None; n]; + for start in 0..n { + let mut path = Vec::new(); + let mut cur = start; + loop { + if state[cur] == 2 { + break; + } + if state[cur] == 1 { + // A cycle: breaking its lowest-numbered link is what clearing in order does. + let at = path.iter().position(|&x| x == cur).unwrap_or(0); + if let Some(&low) = path[at..].iter().min() { + clear[low] = Some("makes a cycle"); + } + break; + } + state[cur] = 1; + path.push(cur); + let Some(b) = base(cur) else { break }; + match index.get(&b) { + Some(&next) => cur = next, + None => { + clear[cur] = Some("names a missing parent"); + break; + } + } + } + for x in path { + state[x] = 2; + } + } let mut warnings = Vec::new(); - for pi in 0..self.parents.len() { - let Some(ps) = self.parents.get(pi) else { continue }; - let Some(base) = ps.parent.as_ref().and_then(|info| info.based_on) else { continue }; - let label = ps.parent.as_ref().map(ParentInfo::label).unwrap_or_default(); - let why = if self.parent_index(base).is_none() { - "names a missing parent" - } else if self.parent_base_cycles(pi, base) { - "makes a cycle" - } else { - continue; - }; + for (pi, why) in clear.into_iter().enumerate() { + let Some(why) = why else { continue }; + let label = self.parents.get(pi).and_then(|ps| ps.parent.as_ref()).map(ParentInfo::label).unwrap_or_default(); if let Some(info) = self.parents.get_mut(pi).map(Arc::make_mut).and_then(|ps| ps.parent.as_mut()) { info.based_on = None; } @@ -825,6 +950,33 @@ impl Document { /// Deepest `based_on` chain followed. pub const MAX_PARENT_DEPTH: usize = 64; +/// Sections after their starts moved (pages deleted or moved), in page order: of sections that now +/// share a start the last is kept, those past the last of `left` pages go, and when the first +/// layout lost its pages the next one begins the document. +fn settle_sections(sections: Vec
, left: usize) -> Vec
{ + let mut kept: Vec
= Vec::with_capacity(sections.len()); + for sec in sections.into_iter().filter(|s| s.start < left) { + if let Some(last) = kept.last_mut().filter(|l| l.start == sec.start) { + // A layout's name outlives its first page: it moves onto the section kept. + let layout = last.layout.take(); + *last = sec; + if last.layout.is_none() { + last.layout = layout; + } + } else { + kept.push(sec); + } + } + if let Some(first) = kept.first_mut() + && first.start != 0 + && first.layout.is_some() + { + // The first layout lost its pages: the next one begins the document. + first.start = 0; + } + kept +} + #[cfg(test)] mod tests { use super::*; @@ -1053,4 +1205,21 @@ mod tests { assert_eq!(d.parents[0].parent.as_ref().unwrap().based_on, None); assert!((0..65).all(|i| d.parent_base_cycles(i, ids[(i + 1) % 65]) == (i == 0)), "only the cleared link would close it again"); } + + /// A long acyclic chain is left alone (this was cubic work before); closing it clears one link. + #[test] + fn fix_parent_bases_long_chain() { + let mut d = Document::new(&NewDocument { pages: 1, facing_pages: false, ..Default::default() }); + for i in 1..2000 { + d.add_parent(&format!("P{i}"), "Parent", 1, 12.0, Margins::uniform(36.0)); + } + let ids: Vec = d.parents.iter().map(|p| p.id).collect(); + for i in 1..ids.len() { + base(&mut d, i, Some(ids[i - 1])); + } + assert!(d.fix_parent_bases().is_empty()); + base(&mut d, 0, Some(ids[ids.len() - 1])); + assert_eq!(d.fix_parent_bases().len(), 1); + assert_eq!(d.parents[0].parent.as_ref().unwrap().based_on, None); + } } diff --git a/crates/doc/src/edit.rs b/crates/doc/src/edit.rs index 1bdd088fb..628fc8ee6 100644 --- a/crates/doc/src/edit.rs +++ b/crates/doc/src/edit.rs @@ -28,6 +28,22 @@ pub struct ItemLoc { pub path: ItemPath, } +/// A gap between adjacent items (or between an item and the page edge) on a spread. +#[derive(Clone, Debug, PartialEq)] +pub struct Gap { + /// True for a vertical gap (between left and right neighbours, moving along X); + /// false for a horizontal gap (between top and bottom neighbours, moving along Y). + pub vertical: bool, + /// Leading edge of the gap along its movement axis. + pub a: f64, + /// Trailing edge of the gap along its movement axis. + pub z: f64, + /// Items ending at `a` that resize when the gap moves. + pub before: Vec, + /// Items starting at `z` that resize when the gap moves. + pub after: Vec, +} + impl ItemLoc { /// Top-level index in the spread. pub fn top(&self) -> usize { @@ -632,6 +648,54 @@ impl Document { None } + /// Hit test on a parent spread (master page): like [`Self::hit_item`], but also skips locked + /// items. Items on hidden or locked layers can't be picked there either. + pub fn hit_parent_item(&self, sr: SpreadRef, p: Point, tol: f64) -> Option { + let sp = self.spread(sr)?; + let mut items: Vec<&Arc> = sp.items.iter().collect(); + items.sort_by_key(|i| self.layer_rank(i.layer)); + items + .into_iter() + .rev() + .find(|it| { + let layer = self.layer(it.layer); + !it.locked && !it.hidden && !layer.is_some_and(|l| !l.visible || l.locked) && item_hit(it, p, tol) + }) + .map(|it| it.id) + } + + /// The gap at `p` (spread space) on spread `sr`: between left and right neighbours (vertical + /// gap moving along X), or above and below (horizontal gap moving along Y). + pub fn find_gap(&self, sr: SpreadRef, p: Point) -> Option { + let sp = self.spread(sr)?; + let page = sp.page_at_x(p.x).and_then(|i| sp.pages.get(i)).map(|pg| pg.bounds())?; + let items: Vec<(ItemId, Rect)> = sp + .items + .iter() + .filter(|it| !it.hidden && !it.locked && self.layer(it.layer).is_none_or(|l| !l.locked && l.visible)) + .map(|it| (it.id, it.bounds())) + .collect(); + if items.iter().any(|(_, b)| b.contains(p)) { + return None; + } + // Between left and right neighbours (a vertical gap), or above and below (horizontal). + let side = |vertical: bool| { + let (pos, lo, hi) = if vertical { (p.x, page.x0, page.x1) } else { (p.y, page.y0, page.y1) }; + let across = |b: &Rect| if vertical { b.y0 <= p.y && p.y <= b.y1 } else { b.x0 <= p.x && p.x <= b.x1 }; + let end = |b: &Rect| if vertical { b.x1 } else { b.y1 }; + let start = |b: &Rect| if vertical { b.x0 } else { b.y0 }; + let a = items.iter().filter(|(_, b)| across(b) && end(b) <= pos).map(|(_, b)| end(b)).fold(lo, f64::max); + let z = items.iter().filter(|(_, b)| across(b) && start(b) >= pos).map(|(_, b)| start(b)).fold(hi, f64::min); + let before: Vec = items.iter().filter(|(_, b)| across(b) && (end(b) - a).abs() < 0.5).map(|(i, _)| *i).collect(); + let after: Vec = items.iter().filter(|(_, b)| across(b) && (start(b) - z).abs() < 0.5).map(|(i, _)| *i).collect(); + (!before.is_empty() || !after.is_empty()).then_some(Gap { vertical, a, z, before, after }) + }; + match (side(true), side(false)) { + (Some(v), Some(h)) => Some(if v.z - v.a <= h.z - h.a { v } else { h }), + (v, h) => v.or(h), + } + } + /// The first item on a document or parent spread whose geometry isn't finite /// ([`Item::geometry_is_finite`]). pub fn non_finite_item(&self) -> Option { @@ -777,8 +841,120 @@ impl Document { st.editorial.clear(); st.fix_marks(); st.rev = st.rev.wrapping_add(1); + self.prune_story_text_ranges(sid); Ok(()) } + + /// Prune text-anchored hyperlinks and placeholders for `story` (e.g. after wholesale story replacement). + pub fn prune_story_text_ranges(&mut self, story: StoryId) { + self.hyperlinks.retain(|h| match &h.source { + crate::HyperlinkSource::Text { story: sid, .. } => *sid != story, + _ => true, + }); + self.data_merge.placeholders.retain(|ph| match &ph.anchor { + crate::PlaceholderAnchor::Text { story: sid, .. } => *sid != story, + _ => true, + }); + } + + /// Remaps text range `s..e` when `del_range` is replaced by `ins_len` bytes. + /// Returns `None` if the range is inverted (`s > e`) or emptied by the edit (`s < e && s_new >= e_new`). + pub fn remap_range(del_range: std::ops::Range, ins_len: usize, s: usize, e: usize) -> Option<(usize, usize)> { + if s > e { + return None; + } + let (da, db) = (del_range.start, del_range.end); + let del_before = db.min(s).saturating_sub(da); + let del_inside = db.min(e).saturating_sub(da.max(s)); + let mut s_new = s.saturating_sub(del_before); + let mut e_new = e.saturating_sub(del_before).saturating_sub(del_inside); + if da < s || (da == s && db == s) { + s_new = s_new.saturating_add(ins_len); + e_new = e_new.saturating_add(ins_len); + } else if da < e { + e_new = e_new.saturating_add(ins_len); + } + if s < e && s_new >= e_new { None } else { Some((s_new, e_new)) } + } + + /// Adjust story-external text references (hyperlinks and data-merge placeholders) after text + /// in `story` has `del_range` replaced by `ins_len` bytes. + pub fn adjust_text_ranges(&mut self, story: StoryId, del_range: std::ops::Range, ins_len: usize) { + self.hyperlinks.retain_mut(|h| { + if let crate::HyperlinkSource::Text { story: sid, start, end } = &mut h.source + && *sid == story + { + if let Some((ns, ne)) = Self::remap_range(del_range.clone(), ins_len, *start, *end) { + *start = ns; + *end = ne; + return true; + } + return false; + } + true + }); + + self.data_merge.placeholders.retain_mut(|ph| { + if let crate::PlaceholderAnchor::Text { story: sid, start, end } = &mut ph.anchor + && *sid == story + { + if let Some((ns, ne)) = Self::remap_range(del_range.clone(), ins_len, *start, *end) { + *start = ns; + *end = ne; + return true; + } + return false; + } + true + }); + } + + /// Shifts text ranges when a block of text in `story` is moved from `from` to `to` (the insertion offset after deletion). + /// Preserves the existing order of items in `hyperlinks` and `placeholders`. + pub fn move_text_ranges(&mut self, story: StoryId, from: std::ops::Range, to: usize) { + if from.is_empty() { + return; + } + let (da, db) = (from.start, from.end); + let len = db - da; + + let remap_moved = |s: usize, e: usize| -> Option<(usize, usize)> { + if s >= da && e <= db { + Some((to + (s - da), to + (e - da))) + } else { + let (s1, e1) = Self::remap_range(da..db, 0, s, e)?; + Self::remap_range(to..to, len, s1, e1) + } + }; + + self.hyperlinks.retain_mut(|h| { + if let crate::HyperlinkSource::Text { story: sid, start, end } = &mut h.source + && *sid == story + { + if let Some((ns, ne)) = remap_moved(*start, *end) { + *start = ns; + *end = ne; + return true; + } + return false; + } + true + }); + + self.data_merge.placeholders.retain_mut(|ph| { + if let crate::PlaceholderAnchor::Text { story: sid, start, end } = &mut ph.anchor + && *sid == story + { + if let Some((ns, ne)) = remap_moved(*start, *end) { + *start = ns; + *end = ne; + return true; + } + return false; + } + true + }); + } } /// How deep nested stories (a cell's text, a footnote's text, an endnote's text) are followed @@ -868,13 +1044,20 @@ fn story_has_hit(st: &Story, depth: usize, hit: &impl Fn(&Item) -> bool) -> bool /// Does `p` (in the item's parent space) hit `it`? pub fn item_hit(it: &Item, p: Point, tol: f64) -> bool { - if let Content::Group { items } = &it.content { + // A group is hit through its children. A frame with items pasted into it shows them clipped + // to its path, so it is hit by its own area: not where a nested image runs past the frame. + if let Content::Group { items } = &it.content + && !it.has_nested_items() + { let inner = it.xf.inverse() * p; return items.iter().any(|c| item_hit(c, inner, tol)); } let inner = it.xf.inverse() * p; let bp = it.path.to_bezpath(); - let area = !it.fill.is_none() || matches!(it.content, Content::Text(_) | Content::Graphic(_)) || it.path.is_closed() && it.shape != Shape::Path; + let area = !it.fill.is_none() + || matches!(it.content, Content::Text(_) | Content::Graphic(_)) + || it.has_nested_items() + || it.path.is_closed() && it.shape != Shape::Path; if area && it.path.is_closed() && designcraft_geom::hit::fill_contains(&bp, designcraft_geom::FillRule::NonZero, inner) { return true; } @@ -914,6 +1097,62 @@ const PATH_TYPE_REACH: f64 = 12.0; mod placed_item_tests { use super::*; + /// A frame at (100, 100)–(200, 200) holding an image pasted into it that runs 150 pt past it on + /// every side, as a document from InDesign keeps a cropped photo. + fn frame_with_nested_image() -> Item { + let layer = LayerId(1); + let mut image = Item::new(ItemId(2), layer, Shape::Rectangle, shapes::rectangle(Rect::new(0.0, 0.0, 400.0, 400.0))); + image.xf = Affine::translate((-150.0, -150.0)); + image.content = Content::Graphic(crate::Graphic { + layer_options: None, + asset: crate::AssetId(1), + size: (400.0, 400.0), + xf: Affine::IDENTITY, + clip: None, + auto_fit: Default::default(), + fit_align: 4, + crop: [0.0; 4], + wrap: Default::default(), + fill: Default::default(), + }); + let mut frame = Item::new(ItemId(1), layer, Shape::Rectangle, shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0))); + frame.xf = Affine::translate((100.0, 100.0)); + frame.content = Content::Group { items: vec![Arc::new(image)] }; + frame + } + + /// The frame shows its nested image clipped, so a click where the image runs past the frame + /// hits nothing: clicking the empty page beside such a photo used to select it, so it could + /// not be deselected. + #[test] + fn a_frame_with_a_nested_image_is_hit_only_inside_the_frame() { + let frame = frame_with_nested_image(); + assert!(frame.has_nested_items()); + assert!(item_hit(&frame, Point::new(150.0, 150.0), 1.0), "inside the frame"); + assert!(item_hit(&frame, Point::new(100.0, 150.0), 1.0), "on its edge"); + for p in [Point::new(60.0, 60.0), Point::new(300.0, 150.0), Point::new(150.0, 330.0)] { + assert!(!item_hit(&frame, p, 1.0), "{p:?} is outside the frame, over the cropped image"); + } + // A group is still hit through its children. + let mut group = frame.clone(); + group.shape = Shape::Group; + assert!(item_hit(&group, Point::new(60.0, 60.0), 1.0)); + } + + /// Placing or dropping a graphic fills a frame holding only nested graphics, not one holding + /// other objects. + #[test] + fn a_frame_with_only_nested_graphics_takes_a_graphic() { + let frame = frame_with_nested_image(); + assert!(frame.takes_graphic()); + let mut other = frame.clone(); + other.content = Content::Group { items: vec![Arc::new(Item::new(ItemId(3), LayerId(1), Shape::Rectangle, Default::default()))] }; + assert!(!other.takes_graphic()); + let mut group = frame; + group.shape = Shape::Group; + assert!(!group.takes_graphic(), "a group of images is not a frame"); + } + #[test] fn exhaustive_placements_keep_unselected_branches_shared() { let mut d = Document::new(&Default::default()); diff --git a/crates/doc/src/endnotes.rs b/crates/doc/src/endnotes.rs index b15bb745c..4c7a60a39 100644 --- a/crates/doc/src/endnotes.rs +++ b/crates/doc/src/endnotes.rs @@ -103,8 +103,12 @@ impl Story { /// Insert empty endnotes for `n` new reference characters before which `k` references sit. pub(crate) fn endnotes_inserted(&mut self, k: usize, n: usize) { + // As for footnotes: the largest id kept as ids are given out, and the free-id search past + // the largest one (`+ 1` overflowed there). + let mut max = self.endnotes.iter().map(|x| x.id).max().unwrap_or(0); for i in 0..n { - let id = self.endnotes.iter().map(|x| x.id).max().unwrap_or(0) + 1; + let id = max.checked_add(1).unwrap_or_else(|| crate::ids::next_local_id(self.endnotes.iter().map(|x| x.id))); + max = max.max(id); let mut text = Story::new(StoryId(0)); text.chars[0].format = CharFormat::default(); self.endnotes.insert((k + i).min(self.endnotes.len()), Arc::new(Footnote { id, text })); diff --git a/crates/doc/src/item.rs b/crates/doc/src/item.rs index 1d2feb6a8..29b97e15d 100644 --- a/crates/doc/src/item.rs +++ b/crates/doc/src/item.rs @@ -29,8 +29,8 @@ pub use paint::{ path_length_bound, }; pub use text_frame::{ - AutoSize, ColumnsKind, ContourType, FirstBaseline, FrameBaselineGrid, FrameGridRelative, PathAlign, PathType, TextFrame, TextFrameOptions, - TextWrap, VerticalJustification, WrapMode, WrapSide, vertical_text_xf, + AutoSize, ColumnsKind, ContourType, DEFAULT_ALPHA_THRESHOLD, FirstBaseline, FrameBaselineGrid, FrameGridRelative, PathAlign, PathType, TextFrame, + TextFrameOptions, TextWrap, VerticalJustification, WrapMode, WrapSide, vertical_text_xf, }; fn is_zero_usize(v: &usize) -> bool { @@ -282,6 +282,16 @@ impl Item { self.shape != Shape::Group && matches!(&self.content, Content::Group { items } if !items.is_empty()) } + /// A frame a placed or dropped graphic fills: an empty one, one holding a graphic, or one + /// holding only graphics pasted into it (as a document from InDesign keeps a frame's image). + pub fn takes_graphic(&self) -> bool { + match &self.content { + Content::Unassigned | Content::Graphic(_) => true, + Content::Group { items } => self.has_nested_items() && items.iter().all(|c| matches!(c.content, Content::Graphic(_))), + _ => false, + } + } + pub fn bounds(&self) -> Rect { self.bounds_under(Affine::IDENTITY).unwrap_or(Rect::ZERO) } @@ -385,6 +395,23 @@ mod tests { use super::*; use designcraft_geom::shapes; + /// Shadows and glows saved before they had a blend mode read Normal, as they were drawn; + /// new ones start as InDesign's: Multiply for shadows, Screen for the outer glow. + #[test] + fn effect_blend_modes_default_as_indesign_and_keep_old_documents() { + let old: DropShadow = + serde_json::from_str(r#"{"on": true, "color": "[Black]", "opacity": 0.75, "angle": 120, "distance": 7, "size": 5, "spread": 0}"#) + .unwrap(); + assert_eq!(old.mode, BlendMode::Normal); + let old: OuterGlow = serde_json::from_str(r#"{"on": true, "color": "[Black]", "opacity": 0.75, "size": 7, "spread": 0}"#).unwrap(); + assert_eq!(old.mode, BlendMode::Normal); + assert_eq!(DropShadow::default().mode, BlendMode::Multiply); + assert_eq!(InnerShadow::default().mode, BlendMode::Multiply); + assert_eq!(OuterGlow::default().mode, BlendMode::Screen); + let saved = serde_json::to_value(DropShadow { mode: BlendMode::Screen, ..Default::default() }).unwrap(); + assert_eq!(serde_json::from_value::(saved).unwrap().mode, BlendMode::Screen, "round trip"); + } + #[test] fn graphics_without_a_clipping_path_load_and_save_as_before() { let g = Graphic { diff --git a/crates/doc/src/item/effects.rs b/crates/doc/src/item/effects.rs index fa416643b..5babfbe40 100644 --- a/crates/doc/src/item/effects.rs +++ b/crates/doc/src/item/effects.rs @@ -13,12 +13,22 @@ pub struct DropShadow { pub distance: f64, pub size: f64, pub spread: f64, + /// How the shadow blends with what's behind it (InDesign: Multiply). A document saved before + /// effects had modes reads Normal, as they were drawn then. + #[serde(default = "normal_blend")] + pub mode: BlendMode, +} + +/// The blend of an effect saved before effects had one. +fn normal_blend() -> BlendMode { + BlendMode::Normal } impl Default for DropShadow { fn default() -> Self { DropShadow { on: false, + mode: BlendMode::Multiply, color: designcraft_color::swatch::BLACK.into(), opacity: 0.75, angle: 120.0, @@ -45,12 +55,16 @@ pub struct InnerShadow { pub size: f64, /// Percentage (0–100) of `size` that hardens the edge instead of blurring it. pub choke: f64, + /// How the shadow blends with the object (InDesign: Multiply; Normal when saved before). + #[serde(default = "normal_blend")] + pub mode: BlendMode, } impl Default for InnerShadow { fn default() -> Self { InnerShadow { on: false, + mode: BlendMode::Multiply, color: designcraft_color::swatch::BLACK.into(), opacity: 0.75, angle: 120.0, @@ -72,11 +86,15 @@ pub struct OuterGlow { pub size: f64, /// Percentage (0–100) of `size` that grows the silhouette instead of blurring it. pub spread: f64, + /// How the glow blends with what's behind it (InDesign: Screen; Normal when saved before). + #[serde(default = "normal_blend")] + pub mode: BlendMode, } impl Default for OuterGlow { fn default() -> Self { - OuterGlow { on: false, color: designcraft_color::swatch::BLACK.into(), opacity: 0.75, size: 7.0, spread: 0.0 } + // InDesign starts a glow screened in white. + OuterGlow { on: false, color: designcraft_color::swatch::PAPER.into(), opacity: 0.75, size: 7.0, spread: 0.0, mode: BlendMode::Screen } } } @@ -290,6 +308,8 @@ impl Effects { ds.size = len("dropShadow.size", ds.size)?; ds.spread = pct("dropShadow.spread", ds.spread)?; self.feather = len("feather", self.feather)?; + // As IDML import reads it, so a round trip keeps it. + self.feather_options.choke = pct("featherOptions.choke", self.feather_options.choke)?; let e = &mut self.inner_shadow; e.opacity = opacity("innerShadow.opacity", e.opacity)?; e.angle = finite("innerShadow.angle", e.angle)?; diff --git a/crates/doc/src/item/text_frame.rs b/crates/doc/src/item/text_frame.rs index d8f7f29e3..3c9452546 100644 --- a/crates/doc/src/item/text_frame.rs +++ b/crates/doc/src/item/text_frame.rs @@ -240,6 +240,65 @@ impl Default for TextFrameOptions { } } +impl TextFrameOptions { + /// The JSON keys of the General options: columns, inset spacing, vertical justification and + /// Ignore Text Wrap. An object style's Text Frame General Options category sets these only. + pub const GENERAL_KEYS: [&str; 9] = [ + "columns", + "columnsKind", + "gutter", + "columnWidth", + "balanceColumns", + "inset", + "verticalJustification", + "vjParagraphSpacingLimit", + "ignoreWrap", + ]; + + /// Whether the General options (see [`Self::GENERAL_KEYS`]) of `self` and `other` are the same. + pub fn general_eq(&self, other: &TextFrameOptions) -> bool { + self.columns == other.columns + && self.columns_kind == other.columns_kind + && self.gutter == other.gutter + && self.column_width == other.column_width + && self.balance_columns == other.balance_columns + && self.inset == other.inset + && self.vertical_justification == other.vertical_justification + && self.vj_paragraph_spacing_limit == other.vj_paragraph_spacing_limit + && self.ignore_wrap == other.ignore_wrap + } + + /// Each General option that is `old`'s here takes `new`'s; the others stay. `true` when one + /// changed. + pub fn follow_general(&mut self, old: &TextFrameOptions, new: &TextFrameOptions) -> bool { + let mut changed = false; + macro_rules! follow { + ($($f:ident),*) => {$( + if self.$f == old.$f && self.$f != new.$f { + self.$f = new.$f; + changed = true; + } + )*}; + } + follow!(columns, columns_kind, gutter, column_width, balance_columns, inset, vertical_justification, vj_paragraph_spacing_limit, ignore_wrap); + changed + } + + /// Copies the General options of `from` (see [`Self::GENERAL_KEYS`]). Baseline, auto-size, + /// column rule and Type on a Path settings stay as they are. + pub fn set_general(&mut self, from: &TextFrameOptions) { + self.columns = from.columns; + self.columns_kind = from.columns_kind; + self.gutter = from.gutter; + self.column_width = from.column_width; + self.balance_columns = from.balance_columns; + self.inset = from.inset; + self.vertical_justification = from.vertical_justification; + self.vj_paragraph_spacing_limit = from.vj_paragraph_spacing_limit; + self.ignore_wrap = from.ignore_wrap; + } +} + #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub enum WrapMode { @@ -272,7 +331,7 @@ pub enum ContourType { BoundingBox, /// Edges detected in the image. Composition follows the frame path. DetectEdges, - /// The image's alpha channel. Composition follows the frame path. + /// The image's alpha channel. Composition follows the outline of the image's visible pixels. AlphaChannel, /// A path saved in the image. Composition follows the frame path. PhotoshopPath, @@ -284,7 +343,7 @@ pub enum ContourType { } /// Text Wrap panel settings. -#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase", default)] pub struct TextWrap { pub mode: WrapMode, @@ -298,6 +357,35 @@ pub struct TextWrap { /// item transforms it with the path; other path edits keep it as it is. #[serde(skip_serializing_if = "Option::is_none")] pub path: Option, + /// Contour Options › Include Inside Edges: an Alpha Channel contour also lets text into the + /// transparent holes it encloses (off: holes are blocked with the shape around them). + #[serde(skip_serializing_if = "std::ops::Not::not")] + pub inside_edges: bool, + /// Alpha Channel contour: pixels more opaque than this (0..254) count as the image. + #[serde(skip_serializing_if = "is_default_alpha_threshold")] + pub alpha_threshold: u8, +} + +/// DesignCraft's default alpha threshold for Alpha Channel contour wraps. +pub const DEFAULT_ALPHA_THRESHOLD: u8 = 25; + +fn is_default_alpha_threshold(t: &u8) -> bool { + *t == DEFAULT_ALPHA_THRESHOLD +} + +impl Default for TextWrap { + fn default() -> Self { + TextWrap { + mode: WrapMode::default(), + offsets: [0.0; 4], + invert: false, + side: WrapSide::default(), + contour: ContourType::default(), + path: None, + inside_edges: false, + alpha_threshold: DEFAULT_ALPHA_THRESHOLD, + } + } } impl TextWrap { diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index bf9998209..338f122f4 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -12,6 +12,7 @@ pub mod anchored; pub mod arabic; pub mod arrow; +pub mod asset_data; pub mod assets; pub mod attrs; pub mod build; @@ -44,7 +45,8 @@ use std::collections::BTreeMap; use std::sync::Arc; pub use anchored::{AnchorPosition, AnchoredObject, OBJECT_MARK}; -pub use assets::{find_same_asset, insert_asset, remap_story_assets, story_asset_refs}; +pub use asset_data::{AssetData, LinkedSource, SourceKey, Unavailable, WeakAssetData}; +pub use assets::{AssetIndex, find_same_asset, insert_asset, remap_story_assets, story_asset_refs}; pub use attrs::*; pub use datamerge::{ DataField, DataFieldKind, DataMerge, DataSource, Delimiter, Fingerprint, MergeOptions, Placeholder, PlaceholderAnchor, PlaceholderRole, @@ -52,7 +54,7 @@ pub use datamerge::{ }; pub use designcraft_color as color; pub use designcraft_geom as geom; -pub use edit::{ItemLoc, ItemPath, SpreadRef, hit_descendant, item_hit as edit_hit}; +pub use edit::{Gap, ItemLoc, ItemPath, SpreadRef, hit_descendant, item_hit as edit_hit}; pub use endnotes::{ENDNOTE_REF, EditorialNote, EndnoteOptions, NOTE_MARK}; pub use file_info::FileInfo; pub use flex::{FlexAlign, FlexDirection, FlexJustify, FlexLayout, FlexSize}; @@ -194,6 +196,14 @@ pub struct Condition { pub visible: bool, } +/// One layout of the document: absolute pages `start..end`. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct LayoutRange { + pub name: String, + pub start: usize, + pub end: usize, +} + impl Document { /// A stroke type with named styles resolved (unknown names draw solid). pub fn stroke_kind(&self, t: &StrokeType) -> StrokeType { @@ -216,17 +226,23 @@ impl Document { .iter() .map(|e| { let mut word = String::new(); + // The word's length in chars, kept as it grows (counting it again at every `~` + // was quadratic in the exception's length). + let mut len = 0; let mut breaks = Vec::new(); for c in e.trim().chars() { if c == '~' { - if breaks.last() != Some(&word.chars().count()) && !word.is_empty() { - breaks.push(word.chars().count()); + if breaks.last() != Some(&len) && len > 0 { + breaks.push(len); } } else { - word.extend(c.to_lowercase()); + for l in c.to_lowercase() { + word.push(l); + len += 1; + } } } - breaks.retain(|b| *b < word.chars().count()); + breaks.retain(|b| *b < len); (word, breaks) }) .collect() @@ -237,6 +253,52 @@ impl Document { pub fn conditions_hide(&self, conds: &[String]) -> bool { !conds.is_empty() && conds.iter().all(|c| self.conditions.iter().any(|x| x.name == *c && !x.visible)) } + + /// Is text with character format `f`, in a paragraph whose base character attributes are + /// `base` (`Styles::resolve_para`), left off the page: hidden by its effective conditions + /// (the paragraph's and character style's included) or marked deleted? Exports leave it out + /// as composition does. + pub fn hides_run(&self, base: &CharProps, f: &CharFormat) -> bool { + let props = self.styles.resolve_char(base, f); + props.change == ChangeMark::Deleted || self.conditions_hide(&props.conditions) + } + + /// The byte ranges of `st` that show, in order: the runs [`Self::hides_run`] hides left out. + /// Paragraphs and runs are walked together, once; take it once per story. + pub fn visible_spans(&self, st: &Story) -> Vec> { + let mut out: Vec> = Vec::new(); + let runs: Vec<(std::ops::Range, &CharFormat)> = st.runs().collect(); + let mut k = 0; + for (pi, pr) in st.para_ranges().iter().enumerate() { + let base = st.paras.get(pi).map(|pf| self.styles.resolve_para(pf).1).unwrap_or_default(); + while runs.get(k).is_some_and(|(rr, _)| rr.end <= pr.start) { + k += 1; + } + for (rr, f) in runs.iter().skip(k).take_while(|(rr, _)| rr.start < pr.end) { + let (a, b) = (rr.start.max(pr.start), rr.end.min(pr.end)); + if a >= b || self.hides_run(&base, f) { + continue; + } + match out.last_mut() { + Some(last) if last.end == a => last.end = b, + _ => out.push(a..b), + } + } + } + out + } + + /// The text of `st` within `range` that lies in `spans` ([`Self::visible_spans`] of `st`). + pub fn visible_text(st: &Story, spans: &[std::ops::Range], range: std::ops::Range) -> String { + let first = spans.partition_point(|s| s.end <= range.start); + let mut out = String::new(); + for s in spans.iter().skip(first).take_while(|s| s.start < range.end) { + if let Some(t) = st.text.get(s.start.max(range.start)..s.end.min(range.end)) { + out.push_str(t); + } + } + out + } } /// Ink Manager settings for output, by swatch name. Output applies them through a @@ -515,6 +577,9 @@ pub struct Layer { pub printable: bool, #[serde(default = "yes")] pub show_guides: bool, + /// Lock Guides: the layer's ruler guides can't be moved or deleted. + #[serde(default)] + pub lock_guides: bool, #[serde(default)] pub suppress_wrap_when_hidden: bool, } @@ -553,8 +618,27 @@ pub struct Asset { /// Original location on disk (Links panel), if linked. #[serde(default, skip_serializing_if = "Option::is_none")] pub link: Option, + /// The size and modification time the linked file had when `data` was read from it, or when + /// it was last found to hold `data`: link status compares these first instead of reading a + /// large file from a network share again. They are the file's only together with `link` and + /// `data`: a new link goes through [`Asset::set_link`], and whoever replaces `data` sets or + /// clears them. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub link_fingerprint: Option, + /// `link` relative to the document's folder, for finding the file after both moved. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub link_relative: Option, + /// The linked file's content hash (`sha256:` and hex digits). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub link_hash: Option, + /// Whether a save writes the bytes into the document or only the link to them. + #[serde(default, skip_serializing_if = "Storage::is_embedded")] + pub storage: Storage, + /// A small preview drawn while the full file can't be read. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub proxy: Option, #[serde(skip)] - pub data: Arc>, + pub data: AssetData, /// Pixel size for raster images. #[serde(default, skip_serializing_if = "Option::is_none")] pub pixels: Option<(u32, u32)>, @@ -572,7 +656,42 @@ pub struct Asset { pub pdf_box: Option<[f64; 4]>, } +/// An asset's bytes for output ([`Asset::output_bytes`]) and what to tell the user about them. +pub struct OutputBytes { + pub bytes: std::sync::Arc>, + /// A warning to report: the file on disk replaced a changed original, or the proxy stands in + /// for a missing one. + pub warning: Option, + /// The bytes are the asset's preview, not the original (a missing or unreadable link). + pub proxied: bool, +} + impl Asset { + /// The bytes an export uses: the original (a changed linked file's current bytes, with a + /// warning), or for a missing or unreadable one its proxy, with a warning. `Err` when + /// there is neither. + pub fn output_bytes(&self) -> std::result::Result { + match self.data.load_for_output() { + Ok((bytes, false)) => Ok(OutputBytes { bytes, warning: None, proxied: false }), + Ok((bytes, true)) => Ok(OutputBytes { + bytes, + warning: Some(format!("the linked file `{}` has changed; the file on disk is used", self.name)), + proxied: false, + }), + Err(e) => { + let proxy = self.proxy.as_ref().and_then(|p| p.data.load().ok()); + match proxy { + Some(bytes) => Ok(OutputBytes { + bytes, + warning: Some(format!("the linked file `{}` is unavailable ({e}); its preview is used", self.name)), + proxied: true, + }), + None => Err(e), + } + } + } + } + /// The part of the page a placed PDF shows, when [`Asset::pdf_box`] holds a usable box. pub fn shown_box(&self) -> Option<[f64; 4]> { self.shown(self.pdf_box?) @@ -593,6 +712,40 @@ impl Asset { } } +/// Where a save keeps an asset's bytes. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum Storage { + /// In the document. + #[default] + Embedded, + /// In the linked file only. + Linked, +} + +impl Storage { + fn is_embedded(&self) -> bool { + *self == Storage::Embedded + } +} + +/// A linked asset's preview image. Its bytes are stored next to the JSON, like asset bytes. +#[derive(Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Proxy { + pub mime: String, + pub pixels: (u32, u32), + /// The preview's encoded bytes, under a key of their own (decoded images are cached by it). + #[serde(skip)] + pub data: AssetData, +} + +impl std::fmt::Debug for Proxy { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Proxy").field("mime", &self.mime).field("pixels", &self.pixels).field("len", &self.data.len()).finish() + } +} + /// Image Import Options › Crop to: which box of a PDF page a placed PDF shows. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] @@ -636,6 +789,49 @@ impl PdfCrop { } } +/// The outline of a raster image's visible pixels (Text Wrap › Contour › Alpha Channel), in the +/// image's pixel space (0..width, 0..height). Derived from the image, so not saved: the engine +/// traces it again when a document opens. +#[derive(Clone, Debug)] +pub struct AlphaOutline { + pub asset: AssetId, + pub threshold: u8, + pub width: u32, + pub height: u32, + /// The outer boundaries of the visible areas. + pub outer: designcraft_geom::PathData, + /// The boundaries of transparent holes those areas enclose (wound the other way). + pub holes: designcraft_geom::PathData, + /// The image data it was traced from: a relink or link update replaces the asset's data + /// under the same id, and the outline is traced again. + pub source: SourceKey, + /// A number no other outline traced in this process has ([`AlphaOutline::next_serial`]): + /// composition caches compare it to tell a new outline from the one they used. + pub serial: u64, +} + +impl AlphaOutline { + /// A serial number for a new outline, unique within the process. + pub fn next_serial() -> u64 { + static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); + NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + } + + /// Traced from `data`, the asset's current image data. + pub fn traced_from(&self, data: &AssetData) -> bool { + self.source == data.key() + } +} + +impl PartialEq for AlphaOutline { + fn eq(&self, other: &Self) -> bool { + (self.asset, self.threshold, self.width, self.height) == (other.asset, other.threshold, other.width, other.height) + && self.outer == other.outer + && self.holes == other.holes + && self.source == other.source + } +} + impl Asset { /// A raster image (PNG, JPEG, GIF, WebP, TIFF, BMP, PSD), as opposed to a PDF, EPS or SVG. pub fn is_raster(&self) -> bool { @@ -692,6 +888,10 @@ pub struct Document { pub sections: Vec
, #[serde(default)] pub assets: BTreeMap>, + /// Alpha Channel contour outlines of placed images (see [`AlphaOutline`]), sorted by asset + /// and then threshold, at most one for each pair. Not saved. + #[serde(skip)] + pub alpha_outlines: Vec>, /// Hyperlinks (Window → Interactive → Hyperlinks). #[serde(default, skip_serializing_if = "Vec::is_empty")] pub hyperlinks: Vec, @@ -752,6 +952,30 @@ pub enum HyperlinkDest { Email(String), /// Absolute page index. Page(usize), + /// A text anchor ([`TextAnchor::id`]), as a cross-reference targets one. The page is + /// whichever page the anchor's text has landed on when the document is exported, so the link + /// follows its destination as the text reflows (#1446). + Anchor(u64), +} + +/// Whether a URL may be used as an external link. Only web and mail schemes are allowed: a +/// `file:`, `javascript:` or UNC link can make a recipient's PDF viewer contact an attacker. +pub fn is_safe_link_url(url: &str) -> bool { + let Some((scheme, rest)) = url.split_once(':') else { return false }; + !rest.is_empty() + && !url.chars().any(|c| c.is_control() || c.is_whitespace()) + && matches!(scheme.to_ascii_lowercase().as_str(), "http" | "https" | "mailto") +} + +impl HyperlinkDest { + /// The name a hyperlink is given when none is supplied. + pub fn label(&self) -> String { + match self { + HyperlinkDest::Url(u) | HyperlinkDest::Email(u) => u.clone(), + HyperlinkDest::Page(p) => format!("Page {}", p + 1), + HyperlinkDest::Anchor(a) => format!("Anchor {a}"), + } + } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] @@ -831,6 +1055,9 @@ pub struct Toc { /// Paragraph style of the title; `None` is the generated "TOC Title" style. #[serde(default, skip_serializing_if = "Option::is_none")] pub title_style: Option, + /// Generate a nested PDF outline from the included paragraphs when the TOC is updated. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub create_bookmarks: bool, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] @@ -841,6 +1068,16 @@ pub struct Bookmark { pub page: usize, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub children: Vec, + /// Owned by the document's generated TOC, so updating it preserves manual bookmarks. + /// + /// Stored only in native files. Bookmarks (and so this flag) are not written to or read + /// from IDML yet, so after an IDML round trip the next TOC update builds the outline fresh. + /// If IDML bookmark import is added, imported bookmarks arrive with this flag false and the + /// next update would keep them as manual and add a second, duplicate outline. That import + /// must set this flag on the bookmarks the TOC generated (for example by matching them to + /// the TOC entries) when the TOC has `create_bookmarks` on. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub generated_by_toc: bool, } impl Document { @@ -881,6 +1118,32 @@ impl Document { self.spreads.iter().enumerate().flat_map(|(si, s)| s.pages.iter().map(move |p| (si, p))).enumerate().map(|(i, (si, p))| (i, si, p)) } + /// The document's layouts (Layout › Create Alternate Layout), in page order: the pages up to + /// the first section that starts a layout are the first layout. Always at least one; a layout + /// whose pages are gone is skipped. + pub fn layouts(&self) -> Vec { + let n = self.page_count(); + let mut starts: Vec<(usize, Option<&str>)> = + self.sections.iter().filter_map(|s| s.layout.as_deref().map(|l| (s.start, Some(l)))).filter(|(st, _)| *st < n).collect(); + starts.sort_by_key(|(st, _)| *st); + starts.dedup_by_key(|(st, _)| *st); + if starts.first().is_none_or(|(st, _)| *st != 0) { + starts.insert(0, (0, None)); + } + let mut out: Vec = Vec::with_capacity(starts.len()); + for (k, (start, name)) in starts.iter().enumerate() { + let end = starts.get(k + 1).map_or(n, |(e, _)| *e); + let name = name.map_or_else(|| format!("Layout {}", k + 1), str::to_string); + out.push(LayoutRange { name, start: *start, end }); + } + out + } + + /// The layout holding absolute page `abs` (an index into [`Document::layouts`]). + pub fn layout_of(&self, abs: usize) -> usize { + self.layouts().iter().rposition(|l| l.start <= abs).unwrap_or(0) + } + /// The section containing absolute page `abs`. pub fn section_of(&self, abs: usize) -> Option<&Section> { self.sections.iter().filter(|s| s.start <= abs).max_by_key(|s| s.start) @@ -908,6 +1171,34 @@ impl Document { } } + /// [`Self::page_number`] of pages `0..count` in one pass (a document of continuing sections + /// would otherwise walk back through every earlier section for every page). + pub fn page_numbers(&self, count: usize) -> Vec { + let mut secs: Vec<&Section> = self.sections.iter().collect(); + secs.sort_by_key(|s| s.start); // stable: of equal starts the last wins, as in `section_of` + let (mut nums, mut next): (Vec, usize) = (Vec::with_capacity(count.min(1 << 20)), 0); + for abs in 0..count { + while secs.get(next).is_some_and(|s| s.start <= abs) { + next += 1; + } + let n = match next.checked_sub(1).and_then(|i| secs.get(i)) { + None => u32::try_from(abs).unwrap_or(u32::MAX).saturating_add(1), + Some(sec) => { + let into = u32::try_from(abs - sec.start).unwrap_or(u32::MAX); + match sec.start_number { + Some(n) => n.saturating_add(into), + None => match sec.start.checked_sub(1).and_then(|p| nums.get(p)) { + Some(prev) => prev.saturating_add(into).saturating_add(1), + None => into.saturating_add(1), + }, + } + } + }; + nums.push(n); + } + nums + } + /// The displayed page name ("1", "iv", "A-3"…) for an absolute page index, per sections. /// The chapter number in its style (`3`, `III`, `c`, `03`). pub fn chapter_label(&self) -> String { @@ -920,6 +1211,12 @@ impl Document { if sec.include_prefix { format!("{}{}", sec.prefix, num) } else { num } } + /// The Alpha Channel outline of `asset` at `threshold`, once the engine has traced it. + pub fn alpha_outline(&self, asset: AssetId, threshold: u8) -> Option<&AlphaOutline> { + let i = self.alpha_outlines.binary_search_by_key(&(asset, threshold), |o| (o.asset, o.threshold)).ok()?; + self.alpha_outlines.get(i).map(|o| &**o) + } + pub fn layer(&self, id: LayerId) -> Option<&Layer> { self.layers.iter().find(|l| l.id == id) } @@ -933,6 +1230,12 @@ impl Document { pub fn default_layer(&self) -> LayerId { self.layers.first().map(|l| l.id).unwrap_or_default() } + /// The layer new objects go to when a document opens: the topmost one shown and unlocked, so + /// a document whose top layer is a hidden, locked dieline doesn't put what is placed or drawn + /// where it can't be seen or selected. The top layer when every layer is hidden or locked. + pub fn working_layer(&self) -> LayerId { + self.layers.iter().find(|l| l.visible && !l.locked).map_or_else(|| self.default_layer(), |l| l.id) + } pub fn story(&self, id: StoryId) -> Option<&Story> { self.stories.get(&id).map(|s| &**s) @@ -955,6 +1258,91 @@ impl Document { designcraft_color::swatch::resolve(&self.swatches, swatch, tint) } + /// Give items that reuse an earlier item's id (spreads, then parents, then items anchored in + /// stories) fresh ids, so a file holding such duplicates opens. The first item keeps the id and + /// what refers to it by id; a renumbered text frame takes its place in its story's thread. + pub fn renumber_duplicate_items(&mut self) { + fn walk_mut(it: &mut Item, f: &mut impl FnMut(&mut Item)) { + f(it); + for c in it.children_mut().into_iter().flatten() { + walk_mut(Arc::make_mut(c), f); + } + } + fn story_items(st: &mut Story, f: &mut impl FnMut(&mut Item)) { + for o in &mut st.objects { + walk_mut(&mut Arc::make_mut(o).item, f); + } + for t in st.tables.values_mut() { + for c in &mut Arc::make_mut(t).cells { + story_items(&mut c.text, f); + } + } + for n in st.notes.iter_mut().chain(st.endnotes.iter_mut()) { + story_items(&mut Arc::make_mut(n).text, f); + } + } + let mut seen = std::collections::HashSet::new(); + let mut dups = std::collections::HashSet::new(); + let mut next = self.next_id; + let mut note = |id: ItemId| { + next = next.max(id.0); + if !seen.insert(id) { + dups.insert(id); + } + }; + for sp in self.spreads.iter().chain(self.parents.iter()) { + for it in &sp.items { + it.walk(&mut |i| note(i.id)); + } + } + for (_, i) in self.anchored_items() { + note(i.id); + } + if dups.is_empty() { + return; + } + let mut seen = std::collections::HashSet::new(); + // (story, id in the file) → the ids its frames carry now, in walk order. + let mut threads: std::collections::HashMap<(StoryId, ItemId), Vec> = std::collections::HashMap::new(); + let mut fix = |it: &mut Item| { + let old = it.id; + if !dups.contains(&old) { + return; + } + if !seen.insert(old) { + // An id at the top of the range has no successor: leave the duplicate for + // `check()` to refuse rather than overflow. + let Some(n) = next.checked_add(1) else { return }; + next = n; + it.id = ItemId(next); + } + if let Some(t) = it.text_frame() { + threads.entry((t.story, old)).or_default().push(it.id); + } + }; + for sp in self.spreads.iter_mut().chain(self.parents.iter_mut()) { + for it in &mut Arc::make_mut(sp).items { + walk_mut(Arc::make_mut(it), &mut fix); + } + } + for st in self.stories.values_mut() { + story_items(Arc::make_mut(st), &mut fix); + } + self.next_id = next; + for ((sid, old), ids) in threads { + let Some(st) = self.stories.get_mut(&sid) else { continue }; + let st = Arc::make_mut(st); + let mut ids = ids.into_iter(); + for f in st.frames.iter_mut().filter(|f| **f == old) { + match ids.next() { + Some(id) => *f = id, + None => break, + } + } + st.frames.extend(ids); + } + } + /// Validate structural invariants (ids unique, threads consistent, stories well-formed). pub fn check(&self) -> Result<()> { for f in &self.styles.composite_fonts { @@ -970,6 +1358,11 @@ impl Document { } } let mut ids = std::collections::HashSet::new(); + // Every item's story (text frames), by id, and every (story, frame) of the threads: built + // once, so checking each reference both ways is a lookup, not a search of the document. + let mut frame_story: std::collections::HashMap> = std::collections::HashMap::new(); + let threads: std::collections::HashSet<(StoryId, ItemId)> = + self.stories.iter().flat_map(|(sid, st)| st.frames.iter().map(move |f| (*sid, *f))).collect(); for sp in self.spreads.iter().chain(self.parents.iter()) { for it in &sp.items { let mut dup = None; @@ -977,20 +1370,30 @@ impl Document { if !ids.insert(i.id.0) { dup = Some(i.id); } + frame_story.insert(i.id, i.text_frame().map(|t| t.story)); }); if let Some(d) = dup { return Err(DocError::Invalid(format!("duplicate item id {d}"))); } } } + let embedded = self.anchored_items(); + // An anchored item's story, by id (the first of an id, as a search would find it). + let mut anchored: std::collections::HashMap> = std::collections::HashMap::new(); + for (_, item) in &embedded { + anchored.entry(item.id).or_insert_with(|| item.text_frame().map(|t| t.story)); + } for (sid, st) in &self.stories { st.check().map_err(DocError::Invalid)?; if st.id != *sid { return Err(DocError::Invalid(format!("story key {sid} != id {}", st.id))); } for f in &st.frames { - let item = self.item(*f).or_else(|| self.anchored_item(*f)).ok_or(DocError::NoItem(*f))?; - match item.text_frame().map(|t| t.story) { + let story = match frame_story.get(f) { + Some(story) => *story, + None => anchored.get(f).copied().ok_or(DocError::NoItem(*f))?, + }; + match story { Some(s) if s == *sid => {} other => return Err(DocError::Invalid(format!("frame {f} in story {sid} points at {other:?}"))), } @@ -1002,7 +1405,7 @@ impl Document { let mut bad = None; it.walk(&mut |i| { if let Some(t) = i.text_frame() - && !self.stories.get(&t.story).is_some_and(|s| s.frames.contains(&i.id)) + && !threads.contains(&(t.story, i.id)) { bad = Some(i.id); } @@ -1012,14 +1415,13 @@ impl Document { } } } - let embedded = self.anchored_items(); let mut edges: std::collections::HashMap> = std::collections::HashMap::new(); for (owner, item) in embedded { if !ids.insert(item.id.0) { return Err(DocError::Invalid(format!("duplicate item id {}", item.id))); } if let Some(tf) = item.text_frame() { - if !self.stories.get(&tf.story).is_some_and(|s| s.frames.contains(&item.id)) { + if !threads.contains(&(tf.story, item.id)) { return Err(DocError::Invalid(format!("embedded text frame {} not in its story's thread", item.id))); } edges.entry(owner).or_default().push(tf.story); diff --git a/crates/doc/src/mojikumi.rs b/crates/doc/src/mojikumi.rs index 415e26bc3..9ef52355b 100644 --- a/crates/doc/src/mojikumi.rs +++ b/crates/doc/src/mojikumi.rs @@ -96,6 +96,10 @@ impl<'a> Rules<'a> { leading(right) - before_right } else if right == 22 { trailing(left) - after_left + } else if self.base != Base::Chinese && closing_bracket(left) && middle_dot(right) { + leading(right) - before_right + } else if self.base != Base::Chinese && middle_dot(left) && opening(right) { + trailing(left) - after_left } else { trailing(left).max(leading(right)) - after_left.max(before_right) } @@ -126,6 +130,20 @@ impl<'a> Rules<'a> { if right == 22 { return Aki::fixed(if self.base == Base::LineEndHalfEm { 0.0 } else { trailing(left) }); } + // Consecutive punctuation in the Japanese sets (JLREQ 3.1.4): opening brackets together, + // and closing brackets, commas and full stops together, touch. A middle dot (・:;) after + // a closing bracket or before an opening one keeps only its own quarter em. Other + // neighbours keep the larger blank, so a closing bracket and an opening one are half an + // em apart. The Chinese sets keep the larger blank throughout. + let closing = |c| matches!(c, 2 | 6 | 21 | 28..=31); + if self.base != Base::Chinese { + if (opening(left) && opening(right)) || (closing(left) && closing(right)) { + return Aki::default(); + } + if (closing_bracket(left) && middle_dot(right)) || (middle_dot(left) && opening(right)) { + return Aki { min: 0.0, desired: 0.25, max: 0.25, priority: 1, discrete: false }; + } + } let punctuation = trailing(left).max(leading(right)); if punctuation > 0.0 { return Aki { min: 0.0, desired: punctuation, max: punctuation, priority: 1, discrete: false }; @@ -142,6 +160,16 @@ impl<'a> Rules<'a> { } } +fn opening(c: i16) -> bool { + matches!(c, 1 | 26 | 27) +} +fn closing_bracket(c: i16) -> bool { + matches!(c, 2 | 28 | 29) +} +fn middle_dot(c: i16) -> bool { + matches!(c, 5 | 32) +} + pub fn valid_class(c: i16) -> bool { matches!(c, 1..=12 | 18 | 21..=33) } @@ -237,6 +265,36 @@ mod tests { assert_ne!(class('「'), class('(')); } + #[test] + fn consecutive_punctuation_touches_except_closing_before_opening() { + let styles = Styles::default(); + for set in ["LineEndAllOneHalfEmEnum", "LineEndAllOneEmEnum"] { + let rules = Rules::resolve(&styles, set).unwrap().unwrap(); + let aki = |a: char, b: char| rules.pair(class(a), class(b)).desired; + for (a, b) in + [('」', '。'), ('」', '、'), ('。', '」'), ('、', '」'), ('」', '』'), (')', '」'), (',', ')'), ('「', '『'), ('(', '「')] + { + assert_eq!(aki(a, b), 0.0, "{set}: {a}{b}"); + } + for (a, b) in [('」', '「'), ('。', '「'), ('、', '('), ('」', '漢'), ('漢', '「')] { + assert_eq!(aki(a, b), 0.5, "{set}: {a}{b}"); + } + // A middle dot keeps its quarter em beside a bracket (JLREQ 3.1.4, Figure 69 ⑦). + for (a, b) in [('」', '・'), (')', ':'), ('』', ';'), ('・', '「'), (';', '('), (':', '〈')] { + assert_eq!(aki(a, b), 0.25, "{set}: {a}{b}"); + } + // After a comma or full stop the larger blank stays. + assert_eq!(aki('、', '・'), 0.5, "{set}: 、・"); + } + // The Chinese sets are unchanged: the larger blank stays between any two marks. + for set in ["SimpChineseDefault", "TradChineseDefault"] { + let rules = Rules::resolve(&styles, set).unwrap().unwrap(); + for (a, b) in [('」', '。'), (',', ')'), ('「', '『'), ('」', '「'), ('」', '・'), ('・', '「')] { + assert_eq!(rules.pair(class(a), class(b)).desired, 0.5, "{set}: {a}{b}"); + } + } + } + #[test] fn one_em_line_end_set_keeps_closing_punctuation_full_at_line_end_only() { let styles = Styles::default(); diff --git a/crates/doc/src/notes.rs b/crates/doc/src/notes.rs index 0811c549c..0e6b0f03b 100644 --- a/crates/doc/src/notes.rs +++ b/crates/doc/src/notes.rs @@ -186,8 +186,12 @@ impl Story { /// Insert empty footnotes for `n` new reference characters before which `k` references sit. pub(crate) fn notes_inserted(&mut self, k: usize, n: usize) { + // The largest id so far, kept as ids are given out (finding it again for every new note + // was quadratic in a batch); past the largest id, the free-id search as before. + let mut max = self.notes.iter().map(|x| x.id).max().unwrap_or(0); for i in 0..n { - let id = self.next_note_id(); + let id = max.checked_add(1).unwrap_or_else(|| self.next_note_id()); + max = max.max(id); let mut text = Story::new(StoryId(0)); text.chars[0].format = CharFormat::default(); self.notes.insert((k + i).min(self.notes.len()), Arc::new(Footnote { id, text })); diff --git a/crates/doc/src/page.rs b/crates/doc/src/page.rs index 7041f7ed8..d6e9b1302 100644 --- a/crates/doc/src/page.rs +++ b/crates/doc/src/page.rs @@ -153,9 +153,9 @@ impl Guide { pub fn visible_in(&self, d: &crate::Document) -> bool { self.layer.is_none_or(|l| d.layer(l).is_none_or(|l| l.visible && l.show_guides)) } - /// Can be dragged: neither it nor its layer is locked. + /// Can be dragged: neither it nor its layer is locked, nor are the layer's guides. pub fn editable_in(&self, d: &crate::Document) -> bool { - !self.locked && self.layer.is_none_or(|l| d.layer(l).is_none_or(|l| !l.locked && l.visible && l.show_guides)) + !self.locked && self.layer.is_none_or(|l| d.layer(l).is_none_or(|l| !l.locked && !l.lock_guides && l.visible && l.show_guides)) } } @@ -433,6 +433,21 @@ impl Spread { None => self.bounds().center().x, } } + /// The edges where two pages of the spread meet, left to right: the x of each shared edge and + /// the vertical span of the two pages together. Pages are taken in position order, so + /// right-to-left binding and any page count work; pages that don't touch (an imported spread + /// can keep gaps between them) share no edge. + pub fn page_seams(&self) -> Vec<(f64, f64, f64)> { + /// Facing edges this close (in points) meet: page positions are sums of widths. + const TOUCH: f64 = 1e-6; + let mut pages: Vec = self.pages.iter().map(Page::bounds).collect(); + pages.sort_by(|a, b| a.x0.total_cmp(&b.x0)); + pages + .windows(2) + .filter(|w| (w[1].x0 - w[0].x1).abs() <= TOUCH * w[0].x1.abs().max(1.0)) + .map(|w| (w[1].x0, w[0].y0.min(w[1].y0), w[0].y1.max(w[1].y1))) + .collect() + } /// Indices of the leftmost and rightmost pages. A right-to-left bound spread lists its right /// page first, so list order says nothing about position. pub fn outer_page_indices(&self) -> Option<(usize, usize)> { @@ -452,6 +467,16 @@ impl Spread { PageSide::Single => Some(0), } } + /// The parent page shown behind page `index` of a document spread, on `side`: by side for + /// facing pages ([`Self::parent_page_for_side`]); by position for single-sided pages in a + /// spread of several, as InDesign does, so the second page of a two-page spread shows the + /// parent's second page (the last one, for spreads longer than the parent). + pub fn parent_page_at(&self, side: PageSide, index: usize) -> Option { + match side { + PageSide::Single if self.pages.len() >= 2 => Some(index.min(self.pages.len() - 1)), + _ => self.parent_page_for_side(side), + } + } /// Index of the page under spread x (nearest page for the pasteboard). pub fn page_at_x(&self, x: f64) -> Option { if self.pages.is_empty() { @@ -502,6 +527,10 @@ pub struct Section { pub marker: String, #[serde(default)] pub include_prefix: bool, + /// The name of the alternate layout this section starts (Pages panel: a column of its own). + /// A layout runs from its section to the next section that starts a layout. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub layout: Option, } #[cfg(test)] @@ -674,6 +703,28 @@ mod tests { assert_eq!(s.page_at_x(5000.0), Some(1)); } + /// Seams are where two pages' facing edges meet, in position order: one per shared edge for + /// any page count or binding, none across a gap, spanning both pages' heights. + #[test] + fn page_seams_are_shared_edges_only() { + let spread = |pages| Spread { id: SpreadId(1), pages, items: vec![], parent: None, allow_shuffle: true }; + let full = (0.0, 792.0); + // A facing pair, listed in either order (right-to-left binding lists the right page first). + for pages in [vec![page(PageSide::Left, 0.0), page(PageSide::Right, 612.0)], vec![page(PageSide::Right, 612.0), page(PageSide::Left, 0.0)]] { + assert_eq!(spread(pages).page_seams(), vec![(612.0, full.0, full.1)]); + } + // Three pages: two seams; a single page: none. + let three = spread(vec![page(PageSide::Left, 0.0), page(PageSide::Right, 612.0), page(PageSide::Right, 1224.0)]); + assert_eq!(three.page_seams(), vec![(612.0, 0.0, 792.0), (1224.0, 0.0, 792.0)]); + assert!(spread(vec![page(PageSide::Single, 0.0)]).page_seams().is_empty()); + // A gap between the pages, as an import can keep: no shared edge. + assert!(spread(vec![page(PageSide::Left, 0.0), page(PageSide::Right, 700.0)]).page_seams().is_empty()); + // Pages of different heights: the seam spans both. + let mut tall = page(PageSide::Right, 612.0); + tall.height = 1000.0; + assert_eq!(spread(vec![page(PageSide::Left, 0.0), tall]).page_seams(), vec![(612.0, 0.0, 1000.0)]); + } + /// The outside bleed goes on the leftmost and rightmost pages, also when right-to-left /// binding lists the right page first. #[test] diff --git a/crates/doc/src/selection.rs b/crates/doc/src/selection.rs index 11c4e2ab1..a2dcf29da 100644 --- a/crates/doc/src/selection.rs +++ b/crates/doc/src/selection.rs @@ -3,7 +3,7 @@ use serde::{Deserialize, Serialize}; use crate::edit::SpreadRef; -use crate::ids::{ItemId, StoryId}; +use crate::ids::{ItemId, SpreadId, StoryId}; use crate::table::CellRange; /// A selected ruler guide: index `index` in the guides of page `page` of spread `spread`. @@ -93,6 +93,9 @@ pub struct Selection { /// The page selected with the Page tool (absolute index). #[serde(default, skip_serializing_if = "Option::is_none")] pub page: Option, + /// Parent selected with the Page tool: stable spread id and page index within it. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub parent_page: Option<(SpreadId, usize)>, /// Selected ruler guides. Never together with items, text or cells: selecting one clears /// the other. #[serde(default, skip_serializing_if = "Vec::is_empty")] diff --git a/crates/doc/src/story.rs b/crates/doc/src/story.rs index 05adcb35f..5628021b9 100644 --- a/crates/doc/src/story.rs +++ b/crates/doc/src/story.rs @@ -39,6 +39,35 @@ pub const FORCED_LINE_BREAK: char = '\u{2028}'; pub const ODD_PAGE_BREAK: char = '\u{E011}'; pub const EVEN_PAGE_BREAK: char = '\u{E012}'; +/// Encode a table-of-contents separator using InDesign's special-character notation. +pub fn toc_separator_notation(text: &str) -> String { + text.replace('^', "^^").replace('\t', "^t").replace(RIGHT_INDENT_TAB, "^y").replace('\u{2003}', "^m").replace('\u{2002}', "^>") +} + +/// Decode TOC notation, preserving unknown codes and an escaped literal caret. +pub fn toc_separator_text(notation: &str) -> String { + let mut text = String::new(); + let mut chars = notation.chars(); + while let Some(ch) = chars.next() { + if ch != '^' { + text.push(ch); + continue; + } + match chars.next() { + Some('t') => text.push('\t'), + Some('y') => text.push(RIGHT_INDENT_TAB), + Some('m') => text.push('\u{2003}'), + Some('>') => text.push('\u{2002}'), + Some('^') | None => text.push('^'), + Some(other) => { + text.push('^'); + text.push(other); + } + } + } + text +} + /// A column, frame or page break character. It ends its paragraph: the story stores it as the /// paragraph's last character, followed by the `\n` separator (also at the end of the story), and /// the next paragraph starts in the next column, frame or page. A break inside a paragraph (from @@ -286,6 +315,24 @@ impl Story { v } + /// The paragraphs `r` touches (at least the one at `r.start`), as (index, byte range without + /// its return), found from `r` itself rather than by listing every paragraph of the story. + pub fn paras_touching(&self, r: std::ops::Range) -> Vec<(usize, std::ops::Range)> { + let start = floor_char_boundary(&self.text, r.start.min(self.text.len())); + let mut pi = self.para_at(start); + let mut a = self.text[..start].rfind('\n').map_or(0, |i| i + 1); + let mut out = Vec::new(); + loop { + let b = self.text[a..].find('\n').map_or(self.text.len(), |i| a + i); + out.push((pi, a..b)); + // The next paragraph starts after this one's return: is it still inside `r`? + if b >= self.text.len() || b + 1 >= r.end { + return out; + } + (a, pi) = (b + 1, pi + 1); + } + } + /// Index of the paragraph containing byte `pos`. pub fn para_at(&self, pos: usize) -> usize { self.text[..floor_char_boundary(&self.text, pos)].bytes().filter(|b| *b == b'\n').count() @@ -294,6 +341,11 @@ impl Story { /// Character format at byte `pos` (the run containing it; at a boundary, the preceding run — /// the format new typing takes). pub fn char_format_at(&self, pos: usize) -> &CharFormat { + if pos == self.text.len() + && let Some(r) = self.chars.iter().rev().find(|r| r.len > 0) + { + return &r.format; + } let mut start = 0; for r in &self.chars { let end = start + r.len; @@ -383,18 +435,26 @@ impl Story { self.marks_inserted(pos, text); } // Paragraph formats: each new '\n' splits the current paragraph; the new paragraphs copy it. - let pi = self.para_at(pos); + // An append (an import building a story piece by piece) is in the last paragraph: no prefix count. + let at_end = pos == self.text.len(); + let pi = if at_end { self.paras.len().saturating_sub(1) } else { self.para_at(pos) }; let newlines = text.bytes().filter(|b| *b == b'\n').count(); - if newlines > 0 { - let f = self.paras[pi].clone(); - for _ in 0..newlines { - self.paras.insert(pi + 1, f.clone()); - } + if newlines > 0 + && let Some(f) = self.paras.get(pi).cloned() + { + // All at once: an insert per return made many returns quadratic (#1588). + self.paras.splice(pi + 1..pi + 1, std::iter::repeat_n(f, newlines)); } self.text.insert_str(pos, text); - // Character runs. - self.splice_runs(pos, 0, text.len(), fmt); - self.normalize(); + // Character runs. Appending extends or pushes at the end: no scan, and the runs stay normalized. + match self.chars.last_mut() { + Some(last) if at_end && last.len > 0 && last.format == fmt => last.len += text.len(), + Some(last) if at_end && last.len > 0 => self.chars.push(CharRun { len: text.len(), format: fmt }), + _ => { + self.splice_runs(pos, 0, text.len(), fmt); + self.normalize(); + } + } self.rev = self.rev.wrapping_add(1); } @@ -639,6 +699,27 @@ mod tests { Story::with_text(StoryId(1), t, ParaFormat::default()) } + /// `paras_touching` gives the paragraphs a range reaches into (returns included), as listing + /// every paragraph would, for every range of a story with empty and multi-byte paragraphs. + #[test] + fn paras_touching_matches_the_full_listing() { + let s = st("ab + +çé +last"); + let all = s.para_ranges(); + for a in 0..=s.len() { + for b in a..=s.len() { + if !s.text.is_char_boundary(a) || !s.text.is_char_boundary(b) { + continue; + } + let want: Vec<(usize, std::ops::Range)> = + all.iter().cloned().enumerate().filter(|(i, p)| *i == s.para_at(a) || (a < b && p.start < b && a <= p.end)).collect(); + assert_eq!(s.paras_touching(a..b), want, "{a}..{b}"); + } + } + } + #[test] fn optical_margin_is_optional_in_saved_stories() { let plain = serde_json::to_value(st("Text")).unwrap(); @@ -669,6 +750,19 @@ mod tests { assert_eq!(s.para_ranges(), vec![0..6]); } + /// Each return inserted its paragraph format on its own, quadratic in the returns (#1588). + #[test] + fn many_returns_split_a_paragraph_at_once() { + let para = ParaFormat { style: "Body".into(), ..ParaFormat::default() }; + let started = std::time::Instant::now(); + let s = Story::with_text(StoryId(1), &"\n".repeat(20_000), para.clone()); + let took = started.elapsed(); + assert!(took < std::time::Duration::from_secs(1), "took {took:?}"); + assert_eq!(s.paras.len(), 20_001); + assert!(s.paras.iter().all(|p| *p == para)); + s.check().unwrap(); + } + #[test] fn char_formats_split_and_merge() { let mut s = st("hello world"); @@ -787,4 +881,22 @@ mod tests { } } } + + /// Appending pieces in alternating formats keeps one run per piece and merges equal neighbours. + #[test] + fn appended_pieces_keep_their_runs() { + let bold = CharFormat { style: "B".into(), ..Default::default() }; + let mut s = Story::new(StoryId(1)); + for i in 0..3000 { + let f = if i % 2 == 0 { CharFormat::default() } else { bold.clone() }; + let at = s.len(); + s.insert_with(at, if i % 7 == 0 { "a\n" } else { "b" }, f); + } + assert_eq!(s.chars.len(), 3000); + assert_eq!(s.chars.iter().map(|r| r.len).sum::(), s.text.len()); + assert_eq!(s.paras.len(), s.text.matches('\n').count() + 1); + let at = s.len(); + s.insert_with(at, "c", bold); + assert_eq!(s.chars.len(), 3000); + } } diff --git a/crates/doc/src/styles.rs b/crates/doc/src/styles.rs index 7605cc447..3a5ea58c3 100644 --- a/crates/doc/src/styles.rs +++ b/crates/doc/src/styles.rs @@ -1,10 +1,11 @@ //! Paragraph, character and object styles with based-on inheritance. +use designcraft_geom::corners::CornerOptions; use serde::{Deserialize, Serialize}; use crate::attrs::{CharAttrs, CharProps, ParaAttrs, ParaProps}; use crate::item::{Effects, Fill, Item, Stroke, TextFrameOptions}; -use crate::story::{BASIC_PARAGRAPH, CharFormat, NO_CHAR_STYLE, ParaFormat}; +use crate::story::{BASIC_PARAGRAPH, CharFormat, NO_CHAR_STYLE, ParaFormat, Story}; pub const NO_PARA_STYLE: &str = "[No Paragraph Style]"; pub const BASIC_GRAPHICS_FRAME: &str = "[Basic Graphics Frame]"; @@ -53,17 +54,30 @@ pub struct ObjectStyle { pub stroke: Option, #[serde(skip_serializing_if = "Option::is_none")] pub paragraph_style: Option, + /// Paragraph Styles › Apply Next Style: the paragraph style goes on a text frame's first + /// paragraph, and each paragraph after it takes the Next Style of the one before. + #[serde(skip_serializing_if = "std::ops::Not::not")] + pub apply_next_style: bool, #[serde(skip_serializing_if = "Option::is_none")] pub text_frame: Option, /// Effects (drop shadow, feather, glows…). An item using the style follows them until its own /// effects differ from the style's (a local override). #[serde(skip_serializing_if = "Option::is_none")] pub effects: Option, + /// Corner Options (Stroke & Corner Options): each corner's shape and size, by name (top left, + /// top right, bottom right, bottom left), as InDesign's; an item takes them at the anchors at + /// those corners ([`CornerOptions::named_to_path`]). + #[serde(skip_serializing_if = "Option::is_none")] + pub corners: Option, } impl ObjectStyle { - /// Gives `it` the fill, stroke, effects and text frame options this style sets. + /// Gives `it` the fill, stroke, corners, effects and text frame General options this style + /// sets. A text frame keeps its baseline, auto-size, column rule and Type on a Path settings. pub fn apply_to(&self, it: &mut Item) { + if let Some(c) = self.corners { + it.corners = c.named_to_path(&it.path); + } if let Some(f) = &self.fill { it.fill = f.clone(); } @@ -74,9 +88,62 @@ impl ObjectStyle { it.effects = e.clone(); } if let (Some(tf), Some(o)) = (it.text_frame_mut(), &self.text_frame) { - tf.options = o.clone(); + tf.options.set_general(o); } } + + /// The paragraph style of each of a text frame's `n` paragraphs under this style: its + /// paragraph style for all of them, or with Apply Next Style that one first and then each + /// one's Next Style. `None` when the style sets no paragraph style. + pub fn paragraph_styles(&self, styles: &Styles, n: usize) -> Option> { + let mut cur = self.paragraph_style.clone()?; + let mut out = Vec::with_capacity(n); + for _ in 0..n { + out.push(cur.clone()); + if self.apply_next_style + && let Some(next) = styles.para(&cur).and_then(|s| s.next_style.clone()) + { + cur = next; + } + } + Some(out) + } + + /// Whether a story's paragraphs are in the paragraph styles this style gives them (they + /// always are when it sets none). + pub fn story_follows(&self, styles: &Styles, st: &Story) -> bool { + self.paragraph_styles(styles, st.paras.len()).is_none_or(|want| st.paras.iter().zip(&want).all(|(f, w)| f.style == *w)) + } + + /// After an edit from `old`: the paragraphs of `st` still in the paragraph style `old` gives + /// them (every paragraph, when `old` set none) with the one this style gives each, where that + /// differs. A paragraph in another style is left out. + pub fn restyle_from(&self, old: &ObjectStyle, styles: &Styles, st: &Story) -> Vec<(usize, String)> { + let n = st.paras.len(); + let Some(want) = self.paragraph_styles(styles, n) else { return Vec::new() }; + let was = old.paragraph_styles(styles, n); + st.paras + .iter() + .zip(want) + .enumerate() + .filter(|(i, (f, w))| was.as_ref().is_none_or(|was| f.style == was[*i]) && f.style != *w) + .map(|(i, (_, w))| (i, w)) + .collect() + } + + /// Put a story's paragraphs in the paragraph styles this style gives them; `false` when it + /// sets none or they already are. + pub fn restyle(&self, styles: &Styles, st: &mut Story) -> bool { + if self.story_follows(styles, st) { + return false; + } + let Some(want) = self.paragraph_styles(styles, st.paras.len()) else { return false }; + for (f, w) in st.paras.iter_mut().zip(want) { + f.style = w; + } + st.rev = st.rev.wrapping_add(1); + true + } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] @@ -775,14 +842,29 @@ impl Styles { /// The paragraph style chain from root to `name` (cycle-safe): resolution starts at its first. pub fn para_chain(&self, name: &str) -> Vec<&ParagraphStyle> { + Self::para_chain_by(name, |n| self.para(n)) + } + + /// The paragraph styles by name, the first of each name (as [`Self::para`] finds it), for + /// callers that look up every style: one map instead of a search per style. + pub fn para_index(&self) -> std::collections::HashMap<&str, &ParagraphStyle> { + let mut index = std::collections::HashMap::new(); + for s in &self.paragraph { + index.entry(s.name.as_str()).or_insert(s); + } + index + } + + /// [`Self::para_chain`] with styles found through `find` (a [`Self::para_index`]). + pub fn para_chain_by<'a>(name: &str, find: impl Fn(&str) -> Option<&'a ParagraphStyle>) -> Vec<&'a ParagraphStyle> { let mut chain = Vec::new(); - let mut cur = self.para(name); + let mut cur = find(name); while let Some(s) = cur { if chain.len() >= MAX_DEPTH || chain.iter().any(|c: &&ParagraphStyle| c.name == s.name) { break; } chain.push(s); - cur = s.based_on.as_deref().and_then(|b| self.para(b)); + cur = s.based_on.as_deref().and_then(&find); } chain.reverse(); chain diff --git a/crates/doc/src/swatch_refs.rs b/crates/doc/src/swatch_refs.rs index 1e79662e9..2c9af65b8 100644 --- a/crates/doc/src/swatch_refs.rs +++ b/crates/doc/src/swatch_refs.rs @@ -144,6 +144,10 @@ impl Names<'_> { if let Some(tf) = it.text_frame_mut() { self.frame(&mut tf.options); } + // The swatch a greyscale or bitmap image is coloured with (#2306). + if let crate::item::Content::Graphic(g) = &mut it.content { + self.fill(&mut g.fill); + } if let Some(kids) = it.children_mut() { for k in kids { self.item(Arc::make_mut(k), depth + 1); @@ -164,9 +168,13 @@ impl Names<'_> { } for c in &mut t.cells { self.s(&mut c.fill); + if let Some(g) = &mut c.graphic { + self.fill(&mut g.fill); + } for s in &mut c.strokes { self.cell_stroke(s); } + self.cell_stroke(&mut c.diagonal.stroke); } } /// One story's own text, objects and tables (cell and note text are visited separately). @@ -230,11 +238,10 @@ impl Document { } /// Point every reference to swatch `from` at `to`: tints based on it, colour groups, inks, - /// styles, page items (fills, strokes, gaps, effects, column rules), text, kenten and ruby - /// colours, rules, shading, borders and border gaps, tables (with stroke gaps), footnotes, - /// gradient stops, - /// endnotes and the footnote rule. The swatch itself is renamed by the - /// caller. + /// styles, page items (fills, strokes, gaps, effects, column rules, the swatch an image is + /// coloured with), text, kenten and ruby colours, rules, shading, borders and border gaps, + /// tables (with stroke gaps, diagonal lines and cell images), footnotes, gradient stops, + /// endnotes and the footnote rule. The swatch itself is renamed by the caller. pub fn rename_swatch_refs(&mut self, from: &str, to: &str) { if from == to { return; diff --git a/crates/doc/src/table.rs b/crates/doc/src/table.rs index d5342b5c9..1926cf1df 100644 --- a/crates/doc/src/table.rs +++ b/crates/doc/src/table.rs @@ -22,9 +22,35 @@ mod grid; mod merge; mod story; -pub use cell::{AltFills, AltStrokes, Cell, CellStroke, Column, Row, RowHeightMode, RowKind, TableOptions}; +pub use cell::{AltFills, AltStrokes, Cell, CellDiagonal, CellStroke, Column, DiagonalLines, Row, RowHeightMode, RowKind, TableOptions}; pub use grid::CellRange; +/// Most rows a table holds, as InDesign allows. +pub const MAX_TABLE_ROWS: usize = 10_000; +/// Most columns a table holds, as InDesign allows. +pub const MAX_TABLE_COLS: usize = 1_000; +/// Most cells a table holds, whatever its shape. +/// +/// A [`Cell`] is about 1.4 KB (it carries a [`Story`]), so this is roughly 340 MB of cells at the +/// limit. The row and column limits alone are not enough: 10,000 × 1,000 would be 13.6 GB, and an +/// IDML story holding one `
` with 5,000 `` and 5,000 `` -- about 1 KB +/// zipped -- asked for 25M cells, some 34 GB. That allocation does not fail politely: it aborts +/// the process through `handle_alloc_error`, which no `catch_unwind` can save, so every open +/// document's unsaved work goes with it (#1583). +pub const MAX_TABLE_CELLS: usize = 250_000; + +/// The rows and columns a table of `rows × cols` is actually given, inside the limits above. +/// +/// Columns are clamped first and rows take what is left of the cell budget, because a table is +/// far more often long than wide: truncating a 5,000-column table to 1,000 columns and then its +/// rows loses less of it than the other way round. Callers that read a file report the +/// difference; the counts are a document's claim, not something to trust. +pub fn clamped_size(rows: usize, cols: usize) -> (usize, usize) { + let cols = cols.clamp(1, MAX_TABLE_COLS); + let rows = rows.clamp(1, MAX_TABLE_ROWS.min(MAX_TABLE_CELLS / cols).max(1)); + (rows, cols) +} + #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct Table { @@ -48,6 +74,48 @@ mod tests { Story::with_text(StoryId(1), t, ParaFormat::default()) } + /// A table's shape comes out of IDML and DOCX files unchecked, and `Cell` is about 1.4 KB, so + /// a file claiming 5,000 x 5,000 asked for 25M cells -- some 34 GB. That allocation aborts the + /// process rather than failing, taking every open document's unsaved work with it (#1583). + #[test] + fn a_table_larger_than_the_limits_is_clamped_not_allocated() { + // The reported shape: 5,000 rows and 5,000 columns. + let t = Table::new(1, 5_000, 5_000, 0, 0, 500.0); + assert_eq!(t.columns.len(), MAX_TABLE_COLS, "columns are clamped to InDesign's limit"); + assert!(t.cells.len() <= MAX_TABLE_CELLS, "{} cells is within the budget", t.cells.len()); + assert_eq!(t.rows.len() * t.columns.len(), t.cells.len(), "the grid stays rectangular"); + // What it would have been: 25,000,000 cells at 1,360 bytes each. + assert!(25_000_000 * std::mem::size_of::() > 30_000_000_000, "the size this test is about"); + // Freed before the next large table, so the peak stays at one of them. + drop(t); + + // A long table keeps its rows while it fits the budget (the budget itself is checked by + // `clamped_size`, which allocates nothing). + let long = Table::new(2, 10_000, 5, 0, 0, 500.0); + assert_eq!((long.rows.len(), long.columns.len()), (10_000, 5), "a long thin table is untouched"); + assert_eq!(clamped_size(10_000, 25), (10_000, 25), "10,000 x 25 is inside the budget"); + drop(long); + + // Past the row limit the rows are clamped too. + let longer = Table::new(3, 50_000, 2, 0, 0, 100.0); + assert_eq!(longer.rows.len(), MAX_TABLE_ROWS, "rows are clamped to InDesign's limit"); + drop(longer); + + // Header, body and footer share the budget, and the table still has a body. + let with_parts = Table::new(4, 5_000, 5_000, 3, 2, 500.0); + assert!(with_parts.rows.len() <= MAX_TABLE_ROWS, "{} rows", with_parts.rows.len()); + assert!(with_parts.cells.len() <= MAX_TABLE_CELLS, "{} cells", with_parts.cells.len()); + assert!(with_parts.rows.iter().any(|r| r.kind == RowKind::Header), "the header survives"); + assert!(with_parts.rows.iter().any(|r| r.kind == RowKind::Footer), "the footer survives"); + assert!(with_parts.rows.iter().any(|r| r.kind == RowKind::Body), "and so does a body row"); + drop(with_parts); + + // A header and footer bigger than the whole budget still leave a body row. + let all_header = Table::new(6, 1, 1, MAX_TABLE_ROWS * 2, MAX_TABLE_ROWS * 2, 100.0); + assert!(all_header.rows.len() <= MAX_TABLE_ROWS, "{} rows", all_header.rows.len()); + assert!(all_header.rows.iter().any(|r| r.kind == RowKind::Body), "a body row survives"); + } + #[test] fn move_row_keeps_header_and_footer_rows_in_place() { let mut t = Table::new(1, 3, 2, 1, 1, 120.0); @@ -88,6 +156,19 @@ mod tests { assert_eq!(right.selected_owners(CellRange::new(1, 0, 1, 1)), vec![(0, 1), (1, 0)], "owner order, not encounter order"); } + /// A short last row's padding cells take the converted text's paragraph and character format, + /// like the cells with text. + #[test] + fn from_strings_formats_the_padding_cells_too() { + let data = vec![vec!["a".to_string(), "b".to_string()], vec!["c".to_string()]]; + let para = ParaFormat { style: "Body".into(), ..Default::default() }; + let fmt = CharFormat { style: "Strong".into(), ..Default::default() }; + let t = Table::from_strings(1, &data, 200.0, ¶, &fmt); + let pad = &t.cell(1, 1).unwrap().text; + assert_eq!((pad.paras[0].style.as_str(), pad.chars[0].format.style.as_str()), ("Body", "Strong")); + assert_eq!(pad.text, ""); + } + #[test] fn insert_table_gets_own_paragraph() { let mut s = story("before after"); @@ -183,6 +264,13 @@ mod tests { t.check().unwrap(); assert_eq!(t.cell(1, 1).unwrap().row_span, 3); assert_eq!(t.nrows(), 5); + // Several rows at once go in together, in order, inside the merged region. + t.insert_rows(2, 3); + t.check().unwrap(); + assert_eq!(t.cell(1, 1).unwrap().row_span, 6); + assert_eq!(t.nrows(), 8); + t.delete_rows(2, 3); + t.check().unwrap(); // Header stays first. t.insert_rows(0, 1); t.check().unwrap(); @@ -278,4 +366,27 @@ mod tests { assert_eq!(back, explicit); assert_eq!(back.blank_like().border_overrides, explicit.border_overrides); } + + #[test] + fn cell_diagonal_lines_roundtrip_and_run_corner_to_corner() { + let plain = serde_json::to_value(Cell::default()).unwrap(); + assert!(plain.get("diagonal").is_none(), "a cell without diagonal lines saves none"); + let diagonal = CellDiagonal { lines: DiagonalLines::Crossed, stroke: CellStroke { weight: 2.0, ..Default::default() }, in_front: false }; + let cell = Cell { diagonal: diagonal.clone(), ..Cell::default() }; + let back: Cell = serde_json::from_str(&serde_json::to_string(&cell).unwrap()).unwrap(); + assert_eq!(back.diagonal, diagonal); + assert_eq!(back.blank_like().diagonal, diagonal, "new cells take the cell's formatting"); + let r = designcraft_geom::Rect::new(10.0, 20.0, 110.0, 70.0); + let p = designcraft_geom::Point::new; + let down = (p(10.0, 20.0), p(110.0, 70.0)); + let up = (p(110.0, 20.0), p(10.0, 70.0)); + for (lines, want) in [ + (DiagonalLines::None, vec![]), + (DiagonalLines::TopLeft, vec![down]), + (DiagonalLines::TopRight, vec![up]), + (DiagonalLines::Crossed, vec![down, up]), + ] { + assert_eq!(CellDiagonal { lines, ..Default::default() }.segments(r), want, "{lines:?}"); + } + } } diff --git a/crates/doc/src/table/cell.rs b/crates/doc/src/table/cell.rs index ac022a7a8..628892af6 100644 --- a/crates/doc/src/table/cell.rs +++ b/crates/doc/src/table/cell.rs @@ -74,6 +74,55 @@ impl Default for CellStroke { } } +/// Cell Options › Diagonal Lines: the diagonals drawn across a cell. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum DiagonalLines { + #[default] + None, + /// From the top left corner to the bottom right corner. + TopLeft, + /// From the top right corner to the bottom left corner. + TopRight, + /// Both diagonals. + Crossed, +} + +/// A cell's diagonal lines, their stroke, and whether they are drawn in front of the cell's +/// contents (Draw › Diagonal In Front) or behind them (Content In Front). +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", default)] +pub struct CellDiagonal { + pub lines: DiagonalLines, + pub stroke: CellStroke, + pub in_front: bool, +} + +impl Default for CellDiagonal { + fn default() -> Self { + CellDiagonal { lines: DiagonalLines::None, stroke: CellStroke::default(), in_front: true } + } +} + +impl CellDiagonal { + pub fn is_default(&self) -> bool { + *self == CellDiagonal::default() + } + + /// The diagonals' ends in the cell rectangle `r`, as (start, end) pairs. + pub fn segments(&self, r: designcraft_geom::Rect) -> Vec<(designcraft_geom::Point, designcraft_geom::Point)> { + use designcraft_geom::Point; + let down = (Point::new(r.x0, r.y0), Point::new(r.x1, r.y1)); + let up = (Point::new(r.x1, r.y0), Point::new(r.x0, r.y1)); + match self.lines { + DiagonalLines::None => vec![], + DiagonalLines::TopLeft => vec![down], + DiagonalLines::TopRight => vec![up], + DiagonalLines::Crossed => vec![down, up], + } + } +} + impl CellStroke { pub fn none() -> Self { CellStroke { weight: 0.0, ..Default::default() } @@ -207,6 +256,9 @@ pub struct Cell { /// content box, origin at the box's top left). #[serde(default, skip_serializing_if = "Option::is_none")] pub graphic: Option, + /// Cell Options › Diagonal Lines. + #[serde(default, skip_serializing_if = "CellDiagonal::is_default")] + pub diagonal: CellDiagonal, } impl Default for Cell { @@ -228,6 +280,7 @@ impl Default for Cell { stroke_defined: [false; 4], style: String::new(), graphic: None, + diagonal: CellDiagonal::default(), } } } diff --git a/crates/doc/src/table/edit.rs b/crates/doc/src/table/edit.rs index 8b140fde1..a4a1c876d 100644 --- a/crates/doc/src/table/edit.rs +++ b/crates/doc/src/table/edit.rs @@ -35,13 +35,11 @@ impl Table { } }) .collect(); - for k in 0..n { - self.rows.insert(at + k, row.clone()); - let i = (at + k) * nc; - for (c, cell) in template.iter().enumerate() { - self.cells.insert(i + c, cell.clone()); - } - } + // All the new rows and cells in one move each (one at a time moved every later cell + // again for each one). + self.rows.splice(at..at, std::iter::repeat_n(row, n)); + let i = at * nc; + self.cells.splice(i..i, (0..n).flat_map(|_| template.iter().cloned())); self.set_regions(®ions); } diff --git a/crates/doc/src/table/grid.rs b/crates/doc/src/table/grid.rs index a64f2cd99..6a11ffcd1 100644 --- a/crates/doc/src/table/grid.rs +++ b/crates/doc/src/table/grid.rs @@ -25,8 +25,16 @@ impl CellRange { impl Table { /// A `rows × cols` table (`header` + body + `footer` rows) whose columns share `width`. + /// + /// The shape is clamped to [`clamped_size`](super::clamped_size): the counts reach this from + /// IDML and DOCX files, where they are whatever the file says (#1583). pub fn new(id: u64, body_rows: usize, cols: usize, header: usize, footer: usize, width: f64) -> Table { - let cols = cols.max(1); + // Header, body and footer rows share one budget: the total is clamped first, then the + // header and footer take what they can of it, and the body keeps at least one row. + let (total, cols) = super::clamped_size(body_rows.max(1).saturating_add(header).saturating_add(footer), cols); + let header = header.min(total.saturating_sub(1)); + let footer = footer.min(total.saturating_sub(header).saturating_sub(1)); + let body_rows = total.saturating_sub(header).saturating_sub(footer).max(1); let mut rows = Vec::new(); rows.extend((0..header).map(|_| Row { kind: RowKind::Header, ..Default::default() })); rows.extend((0..body_rows.max(1)).map(|_| Row::default())); @@ -47,12 +55,15 @@ impl Table { pub fn from_strings(id: u64, data: &[Vec], width: f64, para: &ParaFormat, fmt: &CharFormat) -> Table { let cols = data.iter().map(Vec::len).max().unwrap_or(1).max(1); let mut t = Table::new(id, data.len().max(1), cols, 0, 0, width); - for (r, row) in data.iter().enumerate() { - for (c, s) in row.iter().enumerate() { + // Every cell takes the text's format, the padding of a short row too. + for r in 0..t.nrows() { + for c in 0..t.ncols() { let Some(cell) = t.cell_mut(r, c) else { continue }; cell.text = Story::with_text(StoryId(0), "", ParaFormat { table: None, ..para.clone() }); cell.text.chars[0].format = fmt.clone(); - cell.text.insert(0, s); + if let Some(s) = data.get(r).and_then(|row| row.get(c)) { + cell.text.insert(0, s); + } } } t @@ -172,14 +183,19 @@ impl Table { /// Cell texts, rows separated by `\n`, cells by `\t` (Convert Table to Text, search, agents). pub fn plain_text(&self) -> String { + self.text_with("\t", "\n") + } + + /// The cells' text, columns separated by `col` and rows by `row` (Convert Table to Text). + pub fn text_with(&self, col: &str, row: &str) -> String { let mut out = String::new(); for r in 0..self.nrows() { if r > 0 { - out.push('\n'); + out.push_str(row); } for c in 0..self.ncols() { if c > 0 { - out.push('\t'); + out.push_str(col); } if let Some(cell) = self.cell(r, c) { out.push_str(&cell.text.text.replace('\n', " ")); diff --git a/crates/doc/src/table/merge.rs b/crates/doc/src/table/merge.rs index 7f3faecfe..1ccdebe0a 100644 --- a/crates/doc/src/table/merge.rs +++ b/crates/doc/src/table/merge.rs @@ -5,6 +5,9 @@ use super::grid::CellRange; use super::story::append_story; use super::{Story, Table}; +/// Most merged-cell owners one `split_cells` call splits. +const MAX_SPLIT_OWNERS: usize = 1024; + impl Table { /// The smallest range containing `r` that doesn't cut through a merged region. pub fn expand_range(&self, mut r: CellRange) -> CellRange { @@ -78,6 +81,11 @@ impl Table { selected.insert(*owner); } } + // Each owner is split by a transformation that rebuilds the grid's ownership: quadratic in the + // owners, so a very large selection is refused (a table this size is split in parts). + if selected.len() > MAX_SPLIT_OWNERS { + return Err(format!("too many cells to split at once (at most {MAX_SPLIT_OWNERS})")); + } let mut targets = Vec::new(); for (r, c) in selected { let cell = self.cell(r, c).ok_or("missing split cell")?; @@ -232,6 +240,18 @@ impl Table { mod split_tests { use super::*; + #[test] + fn splitting_a_huge_selection_is_refused() { + let mut t = Table::new(1, 40, 40, 0, 0, 400.0); + let all = CellRange { r0: 0, c0: 0, r1: 39, c1: 39 }; + let before = (t.nrows(), t.ncols()); + assert!(t.split_cells(all, true).unwrap_err().contains("too many cells")); + assert_eq!((t.nrows(), t.ncols()), before, "nothing was split"); + // A selection within the limit still splits. + let some = CellRange { r0: 0, c0: 0, r1: 1, c1: 1 }; + assert!(t.split_cells(some, true).is_ok()); + } + #[test] fn split_single_and_merged_cells() { let mut t = Table::new(1, 2, 2, 0, 0, 100.0); diff --git a/crates/doc/src/tests.rs b/crates/doc/src/tests.rs index 723de21b1..93aeae2b1 100644 --- a/crates/doc/src/tests.rs +++ b/crates/doc/src/tests.rs @@ -235,6 +235,20 @@ fn hit_testing_respects_layers() { assert_eq!(d.hit_item(0, designcraft_geom::Point::new(50.0, 50.0), 2.0), None); } +#[test] +fn parent_hit_testing_respects_layers() { + let mut d = doc(); + let lid = d.default_layer(); + let (a, _) = d.add_text_frame(SpreadRef::Parent(0), Rect::new(10.0, 10.0, 100.0, 100.0), lid, "x", ParaFormat::default()).unwrap(); + let at = designcraft_geom::Point::new(50.0, 50.0); + assert_eq!(d.hit_parent_item(SpreadRef::Parent(0), at, 2.0), Some(a)); + d.layer_mut(lid).unwrap().visible = false; + assert_eq!(d.hit_parent_item(SpreadRef::Parent(0), at, 2.0), None); + d.layer_mut(lid).unwrap().visible = true; + d.layer_mut(lid).unwrap().locked = true; + assert_eq!(d.hit_parent_item(SpreadRef::Parent(0), at, 2.0), None); +} + #[test] fn page_numbers_saturate_at_the_largest_start() { // A start number from a file or an old command: page 2 overflowed (a panic in debug builds). @@ -246,6 +260,7 @@ fn page_numbers_saturate_at_the_largest_start() { prefix: String::new(), marker: String::new(), include_prefix: false, + layout: None, }]; assert_eq!((0..3).map(|i| d.page_number(i)).collect::>(), [u32::MAX; 3]); d.sections.push(crate::Section { start: 2, start_number: None, ..d.sections[0].clone() }); @@ -262,6 +277,7 @@ fn page_names_follow_sections() { style: NumberStyle::LowerRoman, prefix: "A-".into(), marker: String::new(), + layout: None, include_prefix: true, }); assert_eq!(d.page_name(1), "2"); @@ -273,6 +289,7 @@ fn page_names_follow_sections() { start_number: None, style: NumberStyle::Arabic, prefix: String::new(), + layout: None, marker: String::new(), include_prefix: false, }); @@ -288,6 +305,7 @@ fn consecutive_right_pages_get_separate_spreads() { start: 1, start_number: Some(1), style: NumberStyle::Arabic, + layout: None, prefix: String::new(), marker: String::new(), include_prefix: false, @@ -351,3 +369,270 @@ fn placed_pdf_without_a_crop_choice_loads_with_the_crop_box() { // A box with no area shows the whole page. assert_eq!(Asset { pdf_box: Some([0.5, 0.5, 0.5, 0.9]), ..back }.shown_box(), None); } + +/// Checking a document looks each frame up once: 20,000 text frames check in well under a +/// second (each lookup searched every item before). +#[test] +fn check_is_linear_in_the_frames() { + let mut d = Document::new(&NewDocument::default()); + let lid = d.default_layer(); + for i in 0..20_000 { + let y = f64::from(i % 100); + d.add_text_frame(SpreadRef::Doc(0), Rect::new(0.0, y, 10.0, y + 1.0), lid, "x", ParaFormat::default()).unwrap(); + } + let t = std::time::Instant::now(); + d.check().unwrap(); + assert!(t.elapsed() < std::time::Duration::from_secs(10), "{:?}", t.elapsed()); + // A frame its story names but the document doesn't have is still refused. + let sid = *d.stories.keys().next().unwrap(); + Arc::make_mut(d.stories.get_mut(&sid).unwrap()).frames.push(ItemId(u64::MAX)); + assert!(matches!(d.check(), Err(DocError::NoItem(ItemId(u64::MAX))))); +} + +#[test] +fn page_numbers_in_one_pass_match_page_number() { + let mut d = crate::Document::new(&crate::build::NewDocument { pages: 12, facing_pages: false, ..Default::default() }); + let sec = |start, start_number| crate::Section { + start, + start_number, + style: Default::default(), + prefix: String::new(), + marker: String::new(), + include_prefix: false, + layout: None, + }; + // Out of order, a repeated start, continuing sections and one with its own number. + d.sections = vec![sec(7, None), sec(2, Some(10)), sec(4, None), sec(7, Some(3)), sec(9, None), sec(11, Some(u32::MAX)), sec(12, None)]; + assert_eq!(d.page_numbers(14), (0..14).map(|i| d.page_number(i)).collect::>()); + d.sections = vec![sec(3, None)]; + assert_eq!(d.page_numbers(6), (0..6).map(|i| d.page_number(i)).collect::>()); + // Many continuing sections: one pass, not one walk per page. + d.sections = (1..5000).map(|i| sec(i, None)).collect(); + assert_eq!(d.page_numbers(5000)[4999], 5000); +} + +#[test] +fn adjust_text_ranges_tracks_and_prunes_hyperlinks_and_placeholders() { + let mut d = doc(); + let sid = StoryId(1); + d.hyperlinks.push(Hyperlink { + id: 10, + name: "Link".into(), + source: HyperlinkSource::Text { story: sid, start: 10, end: 20 }, + dest: HyperlinkDest::Url("https://example.com".into()), + }); + d.data_merge.placeholders.push(crate::Placeholder { + id: 20, + source_id: 1, + field: "Name".into(), + role: crate::PlaceholderRole::Text, + anchor: crate::PlaceholderAnchor::Text { story: sid, start: 10, end: 20 }, + }); + + // 1. Insert before range (at 5, length 3) -> both move by 3: 13..23 + d.adjust_text_ranges(sid, 5..5, 3); + assert_eq!(d.hyperlinks[0].source, HyperlinkSource::Text { story: sid, start: 13, end: 23 }); + assert_eq!(d.data_merge.placeholders[0].anchor, crate::PlaceholderAnchor::Text { story: sid, start: 13, end: 23 }); + + // 2. Pure insert at start (at 13, length 2) -> shifts forward: 15..25 + d.adjust_text_ranges(sid, 13..13, 2); + assert_eq!(d.hyperlinks[0].source, HyperlinkSource::Text { story: sid, start: 15, end: 25 }); + + // 3. Insert inside range (at 18, length 4) -> end expands: 15..29 + d.adjust_text_ranges(sid, 18..18, 4); + assert_eq!(d.hyperlinks[0].source, HyperlinkSource::Text { story: sid, start: 15, end: 29 }); + + // 4. Typing at the very end of the range (at 29, length 3) -> does not expand range + d.adjust_text_ranges(sid, 29..29, 3); + assert_eq!(d.hyperlinks[0].source, HyperlinkSource::Text { story: sid, start: 15, end: 29 }); + + // 5. Insert after range (at 35, length 5) -> no change + d.adjust_text_ranges(sid, 35..35, 5); + assert_eq!(d.hyperlinks[0].source, HyperlinkSource::Text { story: sid, start: 15, end: 29 }); + + // 6. Delete before range (0..5, length 0) -> shifts back by 5: 10..24 + d.adjust_text_ranges(sid, 0..5, 0); + assert_eq!(d.hyperlinks[0].source, HyperlinkSource::Text { story: sid, start: 10, end: 24 }); + + // 7. Delete inside range (12..16, length 0) -> end shrinks by 4: 10..20 + d.adjust_text_ranges(sid, 12..16, 0); + assert_eq!(d.hyperlinks[0].source, HyperlinkSource::Text { story: sid, start: 10, end: 20 }); + + // 8. Delete across start boundary (8..14, length 0) -> surviving start is 8, end is 14 + d.adjust_text_ranges(sid, 8..14, 0); + assert_eq!(d.hyperlinks[0].source, HyperlinkSource::Text { story: sid, start: 8, end: 14 }); + + // 9. Delete entire range (5..20, length 0) -> pruned + d.adjust_text_ranges(sid, 5..20, 0); + assert!(d.hyperlinks.is_empty()); + assert!(d.data_merge.placeholders.is_empty()); +} + +#[test] +fn adjust_text_ranges_preserves_zero_length_ranges_and_drops_inverted() { + let mut d = doc(); + let sid = StoryId(1); + // Zero-length placeholder (e.g. created at caret) + d.data_merge.placeholders.push(crate::Placeholder { + id: 1, + source_id: 1, + field: "CaretPh".into(), + role: crate::PlaceholderRole::Hyperlink, + anchor: crate::PlaceholderAnchor::Text { story: sid, start: 10, end: 10 }, + }); + // Inverted hyperlink from corrupt input + d.hyperlinks.push(Hyperlink { + id: 2, + name: "Inverted".into(), + source: HyperlinkSource::Text { story: sid, start: 25, end: 15 }, + dest: HyperlinkDest::Url("https://example.com".into()), + }); + + // 1. Inverted range is pruned on edit + d.adjust_text_ranges(sid, 0..0, 2); + assert!(d.hyperlinks.is_empty(), "inverted range must be dropped"); + + // 2. Zero-length placeholder shifts when text is inserted before it (at 0, len 5) -> 15..15 + assert_eq!(d.data_merge.placeholders[0].anchor, crate::PlaceholderAnchor::Text { story: sid, start: 12, end: 12 }); + d.adjust_text_ranges(sid, 0..0, 5); + assert_eq!(d.data_merge.placeholders[0].anchor, crate::PlaceholderAnchor::Text { story: sid, start: 17, end: 17 }); + + // 3. Zero-length placeholder shifts when text is deleted before it (0..7) -> 10..10 + d.adjust_text_ranges(sid, 0..7, 0); + assert_eq!(d.data_merge.placeholders[0].anchor, crate::PlaceholderAnchor::Text { story: sid, start: 10, end: 10 }); + + // 4. Deleting text enclosing the zero-length placeholder collapses it to the deletion start without pruning + d.adjust_text_ranges(sid, 5..15, 0); + assert_eq!(d.data_merge.placeholders[0].anchor, crate::PlaceholderAnchor::Text { story: sid, start: 5, end: 5 }); +} + +#[test] +fn move_text_ranges_tracks_hyperlinks_and_placeholders() { + let mut d = doc(); + let sid = StoryId(1); + d.hyperlinks.push(Hyperlink { + id: 1, + name: "Inside".into(), + source: HyperlinkSource::Text { story: sid, start: 22, end: 28 }, + dest: HyperlinkDest::Url("https://example.com/inside".into()), + }); + d.hyperlinks.push(Hyperlink { + id: 2, + name: "Between".into(), + source: HyperlinkSource::Text { story: sid, start: 5, end: 10 }, + dest: HyperlinkDest::Url("https://example.com/between".into()), + }); + + // Move block 20..30 to position 0 (before both links). + // The moved block (length 10) lands at 0..10. + // The link inside (22..28, relative offset +2..+8) becomes 2..8. + // The link originally at 5..10 shifts forward by 10 to 15..20. + d.move_text_ranges(sid, 20..30, 0); + + let inside = d.hyperlinks.iter().find(|h| h.id == 1).unwrap(); + let between = d.hyperlinks.iter().find(|h| h.id == 2).unwrap(); + assert_eq!(inside.source, HyperlinkSource::Text { story: sid, start: 2, end: 8 }); + assert_eq!(between.source, HyperlinkSource::Text { story: sid, start: 15, end: 20 }); + assert_eq!(d.hyperlinks[0].id, 1, "original list order in doc.hyperlinks must be preserved"); + assert_eq!(d.hyperlinks[1].id, 2); +} + +#[test] +fn set_story_text_prunes_story_hyperlinks_and_placeholders() { + let mut d = doc(); + let lid = d.default_layer(); + let (_, sid1) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(10.0, 10.0, 100.0, 100.0), lid, "initial one", ParaFormat::default()).unwrap(); + let (_, sid2) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(110.0, 10.0, 200.0, 100.0), lid, "initial two", ParaFormat::default()).unwrap(); + + d.hyperlinks.push(Hyperlink { + id: 1, + name: "Link1".into(), + source: HyperlinkSource::Text { story: sid1, start: 0, end: 7 }, + dest: HyperlinkDest::Url("https://example.com/1".into()), + }); + d.hyperlinks.push(Hyperlink { + id: 2, + name: "Link2".into(), + source: HyperlinkSource::Text { story: sid2, start: 0, end: 7 }, + dest: HyperlinkDest::Url("https://example.com/2".into()), + }); + d.data_merge.placeholders.push(crate::Placeholder { + id: 10, + source_id: 1, + field: "Ph1".into(), + role: crate::PlaceholderRole::Text, + anchor: crate::PlaceholderAnchor::Text { story: sid1, start: 0, end: 7 }, + }); + d.data_merge.placeholders.push(crate::Placeholder { + id: 20, + source_id: 1, + field: "Ph2".into(), + role: crate::PlaceholderRole::Text, + anchor: crate::PlaceholderAnchor::Text { story: sid2, start: 0, end: 7 }, + }); + + d.set_story_text(sid1, "Replacement story text").unwrap(); + + // sid1 hyperlinks and placeholders must be pruned + assert!(d.hyperlinks.iter().all(|h| match &h.source { + HyperlinkSource::Text { story, .. } => *story != sid1, + _ => true, + })); + assert!(d.data_merge.placeholders.iter().all(|ph| match &ph.anchor { + crate::PlaceholderAnchor::Text { story, .. } => *story != sid1, + _ => true, + })); + + // sid2 hyperlinks and placeholders must be preserved + assert_eq!(d.hyperlinks.len(), 1); + assert_eq!(d.hyperlinks[0].id, 2); + assert_eq!(d.data_merge.placeholders.len(), 1); + assert_eq!(d.data_merge.placeholders[0].id, 20); +} + +/// Many note references put in at once each get a note with an id of its own, in one pass. +#[test] +fn many_note_references_get_their_notes_at_once() { + let n = 20_000; + let mut st = Story::new(StoryId(1)); + let refs = format!("{}{}", FOOTNOTE_REF.to_string().repeat(n), crate::ENDNOTE_REF.to_string().repeat(n)); + st.insert(0, &refs); + assert_eq!((st.notes.len(), st.endnotes.len()), (n, n)); + let ids: std::collections::HashSet = st.notes.iter().map(|x| x.id).collect(); + assert_eq!(ids.len(), n); + let ids: std::collections::HashSet = st.endnotes.iter().map(|x| x.id).collect(); + assert_eq!(ids.len(), n); +} + +/// An existing note whose id is `u64::MAX` can't be counted past: the next note still gets an id +/// of its own. +#[test] +fn note_ids_survive_a_maximal_existing_id() { + let mut st = Story::new(StoryId(1)); + st.insert(0, &FOOTNOTE_REF.to_string()); + st.insert(0, &crate::ENDNOTE_REF.to_string()); + Arc::make_mut(&mut st.notes[0]).id = u64::MAX; + Arc::make_mut(&mut st.endnotes[0]).id = u64::MAX; + st.insert(0, &FOOTNOTE_REF.to_string()); + st.insert(0, &crate::ENDNOTE_REF.to_string()); + assert_ne!(st.notes[0].id, st.notes[1].id); + assert_ne!(st.endnotes[0].id, st.endnotes[1].id); +} + +/// Exceptions are read in one pass: breaks are char positions of the lowercased word, a break +/// at the start, at the end or twice in a row counts once or not at all, and a long exception +/// full of breaks takes no longer than its length. +#[test] +fn hyphenation_exceptions_are_read_in_one_pass() { + let mut d = Document::new(&NewDocument::default()); + d.hyphenation_exceptions = vec!["~Ty~~po~graph~y~".into(), "İs~tanbul".into()]; + let map = d.hyphenation_exception_map(); + assert_eq!(map["typography"], [2, 4, 9]); + // `İ` lowercases to two chars: positions count the lowercased word. + assert_eq!(map["i\u{307}stanbul"], [3]); + d.hyphenation_exceptions = vec!["a~".repeat(200_000)]; + let t = std::time::Instant::now(); + let map = d.hyphenation_exception_map(); + assert!(t.elapsed() < std::time::Duration::from_secs(2), "{:?}", t.elapsed()); + assert_eq!(map.values().next().map(Vec::len), Some(199_999)); +} diff --git a/crates/doc/src/vars.rs b/crates/doc/src/vars.rs index c53eedb1a..1f5fd7456 100644 --- a/crates/doc/src/vars.rs +++ b/crates/doc/src/vars.rs @@ -175,6 +175,9 @@ pub fn parse_iso_date(s: &str) -> Option { let t = time.get(a..b)?; t.bytes().all(|c| c.is_ascii_digit()).then(|| t.parse().ok()).flatten() }; + if time.get(2..3) != Some(":") { + return None; + } let (h, mi) = (tnum(0, 2)?, tnum(3, 5)?); let mut i = 5; let mut sec = 0; @@ -195,8 +198,16 @@ pub fn parse_iso_date(s: &str) -> Option { None | Some('Z') => Some(secs), Some(sign @ ('+' | '-')) => { let z = zone.get(1..)?; - let zh: i64 = z.get(0..2)?.parse().ok()?; - let zm: i64 = z.get(2..).map(|r| r.trim_start_matches(':')).filter(|r| !r.is_empty()).map_or(Some(0), |r| r.parse().ok())?; + let digits = |t: &str| -> Option { t.bytes().all(|c| c.is_ascii_digit()).then(|| t.parse().ok()).flatten() }; + let zh = digits(z.get(0..2)?)?; + let zm = match z.get(2..)? { + "" => 0, + r if r.len() == 2 => digits(r)?, + r => digits(r.strip_prefix(':').filter(|m| m.len() == 2)?)?, + }; + if zh > 23 || zm > 59 { + return None; + } let off = zh * 3600 + zm * 60; Some(if sign == '+' { secs - off } else { secs + off }) } @@ -290,6 +301,12 @@ impl Document { mod tests { use super::*; + #[test] + fn iso_date_requires_colon_separator() { + assert_eq!(parse_iso_date("2019-12-16T09:48:00Z"), Some(1_576_489_680)); + assert_eq!(parse_iso_date("2019-12-16T09x48:00Z"), None); + } + #[test] fn dates() { // 2026-10-01 14:05 UTC @@ -336,6 +353,22 @@ mod tests { } } + #[test] + fn iso_date_rejects_malformed_zone() { + for bad in [ + "2019-12-16T09:48:02+-5:00", + "2019-12-16T09:48:02+05:+30", + "2019-12-16T09:48:02+24:00", + "2019-12-16T09:48:02+05:60", + "2019-12-16T09:48:02+05::30", + "2019-12-16T09:48:02+05:", + "2019-12-16T09:48:02+053", + "2019-12-16T09:48:02+05:3", + ] { + assert_eq!(parse_iso_date(bad), None, "{bad}"); + } + } + #[test] fn chars() { assert_eq!(var_index(var_char(3).unwrap()), Some(3)); diff --git a/crates/doc/src/xref.rs b/crates/doc/src/xref.rs index 96e584862..cd518c02c 100644 --- a/crates/doc/src/xref.rs +++ b/crates/doc/src/xref.rs @@ -29,13 +29,28 @@ pub struct TextAnchor { pub name: String, } -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct CrossRef { /// The destination anchor (0 = unresolved, e.g. pasted without its destination). pub target: u64, /// Name of the format in [`Document::xref_formats`]. pub format: String, + /// Text typed over the generated text (InDesign keeps a cross-reference's edited text until + /// it is updated): shown as is, except that each `` shows the destination's page. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub text: Option, + /// The page last shown (for edited text whose destination is gone). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub page: Option, +} + +/// The `` building block, as it appears in [`CrossRef::text`]. +pub const PAGE_NUM_BLOCK: &str = ""; + +/// Edited cross-reference text with its page numbers filled in (quotes kept as typed). +pub fn expand_edited(text: &str, page: &str) -> String { + text.replace(PAGE_NUM_BLOCK, page) } /// A cross-reference format: building blocks between literal text. @@ -84,9 +99,10 @@ pub fn expand(definition: &str, v: &XrefValues) -> String { let mut rest = definition; while let Some(i) = rest.find('<') { out.push_str(&rest[..i]); - let Some(j) = rest[i..].find('>') else { + let Some(j) = tag_end(&rest[i..]) else { out.push_str(&rest[i..]); - return out; + rest = ""; + break; }; let tag = rest[i + 1..i + j].trim().trim_end_matches('/').trim(); let name = tag.split_whitespace().next().unwrap_or(""); @@ -120,6 +136,20 @@ pub fn expand(definition: &str, v: &XrefValues) -> String { typographic_quotes(&out) } +/// Byte index of the `>` that ends the tag starting at `s`, skipping quoted attribute values. +/// An unterminated quote falls back to the first `>`, so only that malformed tag is affected. +fn tag_end(s: &str) -> Option { + let mut in_quote = false; + for (k, c) in s.char_indices() { + match c { + '"' => in_quote = !in_quote, + '>' if !in_quote => return Some(k), + _ => {} + } + } + s.find('>') +} + /// Straight double quotes in format text become typographer's quotes. fn typographic_quotes(s: &str) -> String { let mut out = String::with_capacity(s.len()); @@ -198,7 +228,7 @@ impl Story { if n > 0 { let k = self.marks_before(XREF_MARK, pos); for i in 0..n { - self.xrefs.insert(k + i, Arc::new(CrossRef { target: 0, format: String::new() })); + self.xrefs.insert(k + i, Arc::new(CrossRef::default())); } } let n = text.matches(crate::index::INDEX_MARK).count(); @@ -268,7 +298,7 @@ impl Story { let n = self.text.matches(XREF_MARK).count(); self.xrefs.truncate(n); while self.xrefs.len() < n { - self.xrefs.push(Arc::new(CrossRef { target: 0, format: String::new() })); + self.xrefs.push(Arc::new(CrossRef::default())); } let n = self.text.matches(crate::index::INDEX_MARK).count(); self.index_refs.truncate(n); @@ -310,6 +340,35 @@ impl Story { } impl Document { + /// The text a cross-reference to `target` in `format` generates, with each page number as + /// [`PAGE_NUM_BLOCK`] (the form saved text takes); `None` when the destination is gone. + pub fn generated_xref_text(&self, target: u64, format: &str) -> Option { + let mut v = self.xref_values(target)?; + v.page = PAGE_NUM_BLOCK.into(); + Some(expand(self.xref_format(format).map_or("", |f| f.definition.as_str()), &v)) + } + + /// Forget saved cross-reference text that is exactly what its format generates for its + /// destination, so it is generated again (and follows edits to the destination). Any other + /// saved text was typed over the generated text, or its destination is gone: it is kept as + /// shown. + pub fn drop_generated_xref_text(&mut self) { + let generated: Vec<(StoryId, usize)> = self + .stories + .iter() + .flat_map(|(sid, st)| st.xrefs.iter().enumerate().map(move |(k, x)| (*sid, k, x))) + .filter(|(_, _, x)| x.text.as_ref().is_some_and(|t| self.generated_xref_text(x.target, &x.format).as_ref() == Some(t))) + .map(|(sid, k, _)| (sid, k)) + .collect(); + for (sid, k) in generated { + if let Some(x) = self.story_mut(sid).and_then(|st| st.xrefs.get_mut(k)) { + let x = Arc::make_mut(x); + x.text = None; + x.page = None; + } + } + } + /// (story, byte) of anchor `id`. pub fn find_anchor(&self, id: u64) -> Option<(StoryId, usize)> { if id == 0 { @@ -388,6 +447,30 @@ pub fn clean(s: &str) -> String { mod tests { use super::*; + #[test] + fn gt_inside_quoted_attribute_does_not_end_tag() { + let v = XrefValues { para: "Intro > the start".into(), ..Default::default() }; + assert_eq!(expand("\" includeDelim=\"false\" />|", &v), "Intro |"); + } + + #[test] + fn unterminated_lt_still_gets_typographic_quotes() { + let v = XrefValues { para: "Intro".into(), ..Default::default() }; + assert_eq!(expand("\"\" <", &v), "\u{201C}Intro\u{201D} <"); + } + + #[test] + fn unterminated_quote_only_affects_its_own_tag() { + let v = XrefValues { para: "Intro > the start".into(), ..Default::default() }; + let out = expand(" ", &v); + assert!(out.contains("Intro > the start"), "{out}"); + } + + #[test] + fn edited_text_fills_in_its_page_numbers() { + assert_eq!(expand_edited("p. and ", "4"), "p. 4 and 4"); + } + #[test] fn formats_expand() { let v = @@ -407,7 +490,7 @@ mod tests { let mut s = Story::with_text(StoryId(3), "Heading\nBody text.", Default::default()); let a = s.insert_anchor(0, "Heading"); assert_eq!(a >> 24, 3); - s.insert_xref(13, CrossRef { target: a, format: "Page Number".into() }); + s.insert_xref(13, CrossRef { target: a, format: "Page Number".into(), ..Default::default() }); s.check().unwrap(); assert_eq!(s.anchor_pos(a), Some(0)); s.insert(0, "New "); diff --git a/crates/doc/tests/autocraft_regression.rs b/crates/doc/tests/autocraft_regression.rs new file mode 100644 index 000000000..83bfdfa89 --- /dev/null +++ b/crates/doc/tests/autocraft_regression.rs @@ -0,0 +1,18 @@ +use designcraft_doc::Styles; +use designcraft_doc::mojikumi::{Rules, class}; + +#[test] +fn middle_dot_keeps_quarter_em_beside_untrimmed_bracket() { + let styles = Styles::default(); + let rules = Rules::resolve(&styles, "LineEndAllOneHalfEmEnum").unwrap().unwrap(); + let aki = rules.pair_with_bodies(class('”'), class('・'), 0.0, 0.25); + assert_eq!(aki.desired, 0.25, "”・"); + let aki = rules.pair_with_bodies(class('・'), class('“'), 0.25, 0.0); + assert_eq!(aki.desired, 0.25, "・“"); + let aki = rules.pair_with_bodies(class('」'), class(':'), 0.0, 0.25); + assert_eq!(aki.desired, 0.25, "」:"); + let aki = rules.pair_with_bodies(class(';'), class('「'), 0.25, 0.0); + assert_eq!(aki.desired, 0.25, ";「"); + let aki = rules.pair_with_bodies(class('」'), class('・'), 0.5, 0.25); + assert_eq!(aki.desired, 0.25, "」・ trimmed"); +} diff --git a/crates/doc/tests/autocraft_regression_2514.rs b/crates/doc/tests/autocraft_regression_2514.rs new file mode 100644 index 000000000..addd40ef2 --- /dev/null +++ b/crates/doc/tests/autocraft_regression_2514.rs @@ -0,0 +1,28 @@ +use designcraft_doc::arrow::apply; +use designcraft_doc::geom::BezPath; +use designcraft_doc::geom::kurbo::Shape; +use designcraft_doc::{Arrowhead, Stroke}; + +#[test] +fn start_head_follows_tangent_when_start_handle_is_missing() { + let mut bp = BezPath::new(); + bp.move_to((0.0, 0.0)); + bp.curve_to((0.0, 0.0), (100.0, 0.0), (100.0, 100.0)); + let st = Stroke { weight: 1.0, start: Arrowhead::Bar, ..Stroke::default() }; + let (_, heads) = apply(&bp, &st, false).unwrap(); + // The curve leaves heading along +x, so the bar at the start stands upright. + let b = heads[0].path.bounding_box(); + assert!(b.height() > b.width() * 3.0, "{b:?}"); +} + +#[test] +fn end_head_follows_tangent_when_end_handle_is_missing() { + let mut bp = BezPath::new(); + bp.move_to((0.0, 0.0)); + bp.curve_to((100.0, 0.0), (100.0, 100.0), (100.0, 100.0)); + let st = Stroke { weight: 1.0, end: Arrowhead::Bar, ..Stroke::default() }; + let (_, heads) = apply(&bp, &st, false).unwrap(); + // The curve arrives heading along +y, so the bar at the end lies across, horizontally. + let b = heads[0].path.bounding_box(); + assert!(b.width() > b.height() * 3.0, "{b:?}"); +} diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index c1c0f1d33..f3dce660f 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -8,7 +8,12 @@ description = "DesignCraft engine: session, documents, history, selection, comma [lints] workspace = true +[features] +# Recovery-writer handshakes for other crates' tests (`designcraft_engine::recovery::testing`). +testing = [] + [dependencies] +craft-mime = { workspace = true } craft-print = { workspace = true } craft-docpath = { workspace = true } designcraft-images = { workspace = true } @@ -26,14 +31,20 @@ designcraft-pdf = { workspace = true } craft-prepress = { workspace = true } designcraft-tools = { workspace = true } designcraft-idml = { workspace = true } -indd = { workspace = true } +craft-file-formats = { workspace = true } +craft-csv = { workspace = true } +craft-indd = { workspace = true } serde = { workspace = true } serde_json = { workspace = true } thiserror = { workspace = true } log = { workspace = true } -quick-xml = { workspace = true } +craft-xml = { workspace = true } +craft-xml-dtd = { workspace = true } +craft-svg = { workspace = true } caseless = { workspace = true } unicode-segmentation = { workspace = true } +# Content hashes of linked files (`asset_io::content_hash`). +sha2 = "0.10" [target.'cfg(not(target_arch = "wasm32"))'.dependencies] craft-atomic = { workspace = true } diff --git a/crates/engine/src/asset_io.rs b/crates/engine/src/asset_io.rs new file mode 100644 index 000000000..1f3b917e5 --- /dev/null +++ b/crates/engine/src/asset_io.rs @@ -0,0 +1,322 @@ +//! Reading linked files' bytes for the document model ([`designcraft_doc::asset_data`]): the +//! [`Loader`] every [`crate::Session`] installs. Files are read through [`crate::io`] (the +//! automation roots of the loading thread apply) and only ever yield the bytes the link record +//! names: other bytes at the path are [`Unavailable::Modified`] and are never handed out. +//! +//! The web build installs no loader: its linked assets are [`Unavailable::NoLoader`]. + +use std::path::{Path, PathBuf}; + +use designcraft_doc::asset_data::{Loaded, Loader, MAX_LINKED_BYTES}; +use designcraft_doc::{Fingerprint, LinkedSource, Unavailable}; + +/// Read linked files with [`FileLoader`] in this process (on the web: nothing to install). +pub fn install() { + #[cfg(not(target_arch = "wasm32"))] + designcraft_doc::asset_data::install_loader(std::sync::Arc::new(FileLoader)); +} + +/// The engine's [`Loader`]: [`read_linked`]. +pub struct FileLoader; + +impl Loader for FileLoader { + fn load(&self, source: &LinkedSource, trusted: Option) -> Result { + read_linked(source, trusted) + } + + fn load_current(&self, source: &LinkedSource) -> Result, Unavailable> { + read_current(source) + } + + fn holds(&self, source: &LinkedSource, trusted: Option, kept: &[u8]) -> Result, Unavailable> { + still_holds(source, trusted, kept) + } +} + +/// Whether a candidate file ([`candidates`]) still holds `kept`, the bytes read for `source` +/// earlier ([`Loader::holds`]): one of `source.len` bytes with the recorded or `trusted` +/// fingerprint (nothing is read), else one whose content hash is `source.hash`, or without a +/// hash whose bytes are `kept`. → the fingerprint of a file that was read to tell. +pub fn still_holds(source: &LinkedSource, trusted: Option, kept: &[u8]) -> Result, Unavailable> { + let mut seen = false; + for path in candidates(source) { + let Some(meta) = crate::io::file_metadata(&path) else { continue }; + seen = true; + let found = fingerprint_from(&meta); + if found.size != source.len { + continue; + } + if has_time(&found) && (Some(found) == source.fingerprint || Some(found) == trusted) { + return Ok(None); + } + let Ok(bytes) = crate::io::read_capped(&path, source.len) else { continue }; + let same = match &source.hash { + Some(hash) => *hash == content_hash(&bytes), + None => bytes == kept, + }; + if same { + return Ok(has_time(&found).then_some(found)); + } + } + Err(if seen { Unavailable::Modified } else { Unavailable::Missing }) +} + +/// The bytes of the first candidate file that exists, whatever they are (no fingerprint or hash +/// check): what an export uses for a link whose file has changed. +pub fn read_current(source: &LinkedSource) -> Result, Unavailable> { + for path in candidates(source) { + let Some(meta) = crate::io::file_metadata(&path) else { continue }; + if meta.len() > MAX_LINKED_BYTES { + return Err(Unavailable::TooLarge); + } + if let Ok(bytes) = crate::io::read_capped(&path, MAX_LINKED_BYTES) { + return Ok(bytes); + } + } + Err(Unavailable::Missing) +} + +/// `sha256:` and the hex digits of the SHA-256 of `bytes` ([`designcraft_doc::Asset::link_hash`]). +pub fn content_hash(bytes: &[u8]) -> String { + use sha2::Digest; + use std::fmt::Write; + let digest = sha2::Sha256::digest(bytes); + let mut out = String::with_capacity(7 + 64); + out.push_str("sha256:"); + for b in digest { + let _ = write!(out, "{b:02x}"); + } + out +} + +/// Size and modification time (whole seconds) from a file's metadata, as link records store them. +pub fn fingerprint_from(meta: &crate::io::Metadata) -> Fingerprint { + let mtime = meta + .modified() + .ok() + .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok()) + .map(|d| i64::try_from(d.as_secs()).unwrap_or(i64::MAX)) + .unwrap_or(0); + Fingerprint { size: meta.len(), mtime } +} + +/// Whether `f` has a modification time to tell the file by: [`fingerprint_from`] gives 0 where +/// the file system reports none, and two such files of one size would look the same. +pub fn has_time(f: &Fingerprint) -> bool { + f.mtime != 0 +} + +/// The files that may hold `source`'s bytes, in the order they are tried: the absolute path, +/// then the relative one resolved against the document. Paths [`crate::io::document_path`] +/// refuses are left out. +pub fn candidates(source: &LinkedSource) -> Vec { + let document = source.document.as_deref(); + let mut out: Vec = crate::io::document_path(&source.path, document).into_iter().collect(); + if let (Some(relative), Some(document)) = (source.relative.as_deref(), document) + && let Ok(p) = crate::io::document_path(relative, Some(document)) + && !out.contains(&p) + { + out.push(p); + } + out +} + +/// Why one candidate file doesn't serve. +enum Miss { + Absent, + Modified, + TooLarge, +} + +/// The bytes of the first candidate file ([`candidates`]) that holds `source`'s bytes: one of +/// `source.len` bytes whose fingerprint is `source.fingerprint` or `trusted`, or whose content +/// hash is `source.hash`. A source that records neither fingerprint nor hash is taken by its +/// size. The fingerprint of a file accepted by its hash is returned with the bytes. +pub fn read_linked(source: &LinkedSource, trusted: Option) -> Result { + if source.len > MAX_LINKED_BYTES { + return Err(Unavailable::TooLarge); + } + let mut worst = Miss::Absent; + for path in candidates(source) { + match read_candidate(&path, source, trusted) { + Ok(loaded) => return Ok(loaded), + Err(Miss::Absent) => {} + Err(miss @ Miss::TooLarge) => worst = miss, + Err(Miss::Modified) => { + if !matches!(worst, Miss::TooLarge) { + worst = Miss::Modified; + } + } + } + } + Err(match worst { + Miss::Absent => Unavailable::Missing, + Miss::Modified => Unavailable::Modified, + Miss::TooLarge => Unavailable::TooLarge, + }) +} + +fn read_candidate(path: &Path, source: &LinkedSource, trusted: Option) -> Result { + let meta = crate::io::file_metadata(path).ok_or(Miss::Absent)?; + let found = fingerprint_from(&meta); + if found.size > MAX_LINKED_BYTES { + return Err(Miss::TooLarge); + } + if found.size != source.len { + return Err(Miss::Modified); + } + let known = has_time(&found) && (Some(found) == source.fingerprint || Some(found) == trusted); + if !known && source.hash.is_none() && source.fingerprint.is_some() { + // Nothing to tell the bytes by. + return Err(Miss::Modified); + } + // At most one byte past the size: a file that grew since is caught without reading it all. + let bytes = crate::io::read_capped(path, source.len).map_err(|_| Miss::Absent)?; + if bytes.len() as u64 != source.len { + return Err(Miss::Modified); + } + if known { + return Ok(Loaded { bytes, fingerprint: None }); + } + match &source.hash { + Some(hash) if *hash != content_hash(&bytes) => Err(Miss::Modified), + Some(_) => Ok(Loaded { bytes, fingerprint: Some(found) }), + None => Ok(Loaded { bytes, fingerprint: None }), + } +} + +#[cfg(test)] +mod tests { + use super::*; + use designcraft_doc::AssetData; + + struct Dir(PathBuf); + + impl Dir { + fn new(name: &str) -> Self { + let dir = std::env::temp_dir().join(format!("dc-asset-io-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + Dir(dir) + } + } + + impl Drop for Dir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } + } + + /// The link record of the file at `path` as it is now. + fn source_of(path: &Path) -> LinkedSource { + let bytes = std::fs::read(path).unwrap(); + LinkedSource { + path: path.to_string_lossy().into_owned(), + relative: None, + document: None, + len: bytes.len() as u64, + fingerprint: Some(fingerprint_from(&std::fs::metadata(path).unwrap())), + hash: Some(content_hash(&bytes)), + } + } + + /// Set the file's modification time `secs` seconds into the past. + fn age(path: &Path, secs: u64) { + let file = std::fs::OpenOptions::new().write(true).open(path).unwrap(); + file.set_modified(std::time::SystemTime::now() - std::time::Duration::from_secs(secs)).unwrap(); + } + + #[test] + fn content_hashes_are_sha256_hex() { + assert_eq!(content_hash(b"abc"), "sha256:ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"); + } + + #[test] + fn a_linked_file_is_read_when_it_holds_the_recorded_bytes() { + let dir = Dir::new("read"); + let path = dir.0.join("a.png"); + std::fs::write(&path, b"original").unwrap(); + let source = source_of(&path); + assert_eq!(read_linked(&source, None).ok().map(|l| (l.bytes, l.fingerprint)), Some((b"original".to_vec(), None))); + // Same bytes, another time: accepted by the hash, and the new fingerprint returned. + age(&path, 1000); + let now = fingerprint_from(&std::fs::metadata(&path).unwrap()); + let loaded = read_linked(&source, None).ok().unwrap(); + assert_eq!((loaded.bytes.as_slice(), loaded.fingerprint), (b"original".as_slice(), Some(now))); + assert!(read_linked(&source, Some(now)).is_ok_and(|l| l.fingerprint.is_none()), "a trusted fingerprint needs no hash"); + let unverifiable = LinkedSource { hash: None, ..source.clone() }; + assert_eq!(read_linked(&unverifiable, None).err(), Some(Unavailable::Modified), "nothing to tell the bytes by"); + } + + #[test] + fn other_bytes_at_the_path_are_modified_and_a_missing_file_is_missing() { + let dir = Dir::new("modified"); + let path = dir.0.join("a.png"); + std::fs::write(&path, b"original").unwrap(); + let source = source_of(&path); + std::fs::write(&path, b"changed!").unwrap(); + age(&path, 1000); + assert_eq!(read_linked(&source, None).err(), Some(Unavailable::Modified), "same size, other bytes"); + std::fs::write(&path, b"longer than before").unwrap(); + assert_eq!(read_linked(&source, None).err(), Some(Unavailable::Modified), "another size"); + std::fs::remove_file(&path).unwrap(); + assert_eq!(read_linked(&source, None).err(), Some(Unavailable::Missing)); + let too_large = LinkedSource { len: MAX_LINKED_BYTES + 1, ..source }; + assert_eq!(read_linked(&too_large, None).err(), Some(Unavailable::TooLarge)); + } + + #[test] + fn the_relative_path_serves_when_the_absolute_one_does_not() { + let dir = Dir::new("relative"); + std::fs::create_dir_all(dir.0.join("moved/links")).unwrap(); + let away = dir.0.join("moved/links/a.png"); + std::fs::write(&away, b"original").unwrap(); + let mut source = source_of(&away); + source.path = dir.0.join("gone/links/a.png").to_string_lossy().into_owned(); + assert_eq!(read_linked(&source, None).err(), Some(Unavailable::Missing)); + source.relative = Some("links/a.png".into()); + source.document = Some(dir.0.join("moved/doc.dcx")); + assert_eq!(read_linked(&source, None).ok().map(|l| l.bytes), Some(b"original".to_vec())); + // A changed file at the absolute path doesn't hide the one that holds the bytes. + std::fs::create_dir_all(dir.0.join("gone/links")).unwrap(); + std::fs::write(dir.0.join("gone/links/a.png"), b"other!!!").unwrap(); + age(&dir.0.join("gone/links/a.png"), 1000); + assert_eq!(read_linked(&source, None).ok().map(|l| l.bytes), Some(b"original".to_vec())); + } + + /// A time of 0 is what a file system without times gives: it can't tell two files apart. + #[test] + fn a_file_without_a_time_is_told_by_its_hash() { + let dir = Dir::new("no-time"); + let path = dir.0.join("a.png"); + let at_epoch = |p: &Path| std::fs::OpenOptions::new().write(true).open(p).unwrap().set_modified(std::time::UNIX_EPOCH).unwrap(); + std::fs::write(&path, b"original").unwrap(); + at_epoch(&path); + let source = source_of(&path); + assert_eq!(source.fingerprint.map(|f| f.mtime), Some(0)); + std::fs::write(&path, b"changed!").unwrap(); + at_epoch(&path); + assert_eq!(read_linked(&source, None).err(), Some(Unavailable::Modified)); + } + + /// Through the installed loader and the store: a file changed on disk is never adopted. + #[test] + fn asset_data_loads_through_the_installed_loader() { + install(); + let dir = Dir::new("installed"); + let path = dir.0.join("a.png"); + std::fs::write(&path, b"original").unwrap(); + let data = AssetData::linked(source_of(&path)); + let changed = AssetData::linked(source_of(&path)); + assert_eq!(data.load().ok().map(|b| b.to_vec()), Some(b"original".to_vec())); + assert!(data.resident().is_some()); + std::fs::write(&path, b"changed!").unwrap(); + age(&path, 1000); + assert_eq!(data.load().ok().map(|b| b.to_vec()), Some(b"original".to_vec()), "kept bytes are the recorded ones"); + assert_eq!(changed.load().err(), Some(Unavailable::Modified)); + assert!(changed.resident().is_none(), "nothing adopted"); + std::fs::remove_file(&path).unwrap(); + data.evict(); + assert_eq!(data.load().err(), Some(Unavailable::Missing)); + } +} diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 1a75d7ece..803814d7e 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -1,5 +1,6 @@ //! The command registry. Ids follow InDesign's menu structure. +pub(crate) mod alpha_wrap; mod anchored; pub mod anchors; mod articles; @@ -16,6 +17,7 @@ mod editorial; mod endnotes; mod export; pub(crate) use export::print_pdf; +pub mod export_batch; mod file; mod file_info; pub(crate) mod find; @@ -32,6 +34,8 @@ mod layout; pub mod library; mod linked; mod links; +pub mod native_links; +pub use links::{LinkListChecks, list_document_links, preview_document_links, remember_link_files}; mod liquid; mod lists; mod load_styles; @@ -39,9 +43,11 @@ mod mathexpr; mod media; mod notes; mod object; +pub use object::text_frame_options_frames; mod overrides; mod package; pub mod params; +mod paste_image; mod paste_svg; mod path_type; mod paths; @@ -175,7 +181,9 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(file_info::specs()); v.extend(interchange::specs()); v.extend(export::specs()); + v.extend(export_batch::specs()); v.extend(edit::specs()); + v.extend(paste_image::specs()); v.extend(paste_svg::specs()); v.extend(endnotes::specs()); v.extend(editorial::specs()); @@ -194,6 +202,7 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(library::specs()); v.extend(lists::specs()); v.extend(linked::specs()); + v.extend(native_links::specs()); v.extend(mathexpr::specs()); v.extend(media::specs()); v.extend(pdflayers::specs()); @@ -247,6 +256,11 @@ pub fn find_command(id: &str) -> Option<&'static CommandSpec> { pub(crate) fn bad(cmd: &str, msg: impl Into) -> EngineError { EngineError::BadParams { cmd: cmd.into(), msg: msg.into() } } + +/// The bytes of `asset`, or why `cmd` can't have them. +pub(crate) fn asset_bytes(cmd: &str, asset: &designcraft_doc::Asset) -> Result>> { + asset.data.load().map_err(|e| bad(cmd, format!("{}: {e}", asset.name))) +} /// `p` with `key` set to `v`. Parameters come from callers (control channel, MCP, scripts) and /// may not be an object: `p[key] = v` panics on an array or a string, so start from `{}` then. pub(crate) fn with_param(p: &Value, key: &str, v: Value) -> Value { @@ -328,6 +342,28 @@ pub(crate) fn named_targets(spec: &CommandSpec, p: &Value) -> Option id_param(p, "id").map(|i| vec![i]) } +/// The table a call names with `table`, for a command whose params document an optional `table`. +/// `None` when the call names no table. A `table` that is present but not a non-negative integer, +/// `null` included, is an error. [`table_story`] reads the `story` that goes with it. +pub(crate) fn named_table(spec: &CommandSpec, p: &Value, cmd: &str) -> Result> { + if !spec.params.split(|c: char| !c.is_ascii_alphanumeric() && c != '?').any(|w| w == "table?") { + return Ok(None); + } + match p.get("table") { + None => Ok(None), + Some(v) => v.as_u64().map(Some).ok_or_else(|| bad(cmd, "`table` must be a nonnegative integer")), + } +} + +/// The `story` a table command's call names alongside `table`, or `None` when the call has no +/// `story`. A `story` that is present but not a non-negative integer, `null` included, is an error. +pub(crate) fn table_story(p: &Value, cmd: &str) -> Result> { + match p.get("story") { + None => Ok(None), + Some(v) => v.as_u64().map(Some).ok_or_else(|| bad(cmd, "`story` must be a non-negative integer")), + } +} + /// Targets: `ids` / `id` params or the selection. pub(crate) fn targets(s: &Session, p: &Value) -> Result> { if let Some(ids) = ids_param(p, "ids") { @@ -355,5 +391,6 @@ pub use file::{ DOCUMENT_SNIFF_BYTES, RecentPreview, base64_decode, base64_encode, from_bytes, is_document, recent_preview, to_bytes, with_document_extension, }; 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; diff --git a/crates/engine/src/cmd/alpha_wrap.rs b/crates/engine/src/cmd/alpha_wrap.rs new file mode 100644 index 000000000..de092273d --- /dev/null +++ b/crates/engine/src/cmd/alpha_wrap.rs @@ -0,0 +1,598 @@ +//! Text Wrap › Contour › Alpha Channel: the outline of a placed raster's visible pixels. +//! +//! The outline is traced once per image and threshold, in the image's pixel space, and kept on +//! the document ([`designcraft_doc::AlphaOutline`]). Composition maps it through the graphic's +//! current transform, so it follows the image when it is moved, scaled or refitted. +use std::collections::BTreeSet; +use std::sync::Arc; + +use designcraft_doc::{AlphaOutline, AssetData, AssetId, ContourType, Document, Item, WrapMode}; +use designcraft_geom::{BezPath, PathData, Point}; + +/// Images larger than this many pixels aren't traced (their contour follows the frame). +const MAX_PIXELS: u64 = 40_000_000; +/// The finest grid an outline is traced on; coarser grids when the outline would be too long. +const MAX_GRID: u32 = 256; +/// Boundary edges an outline may have. +const MAX_EDGES: usize = 1 << 16; + +/// Trace the outlines new Alpha Channel contours need and drop the ones nothing uses. Cheap when +/// nothing changed: tracing happens only for an image and threshold not seen before. +pub(crate) fn sync(doc: &mut Document) { + let mut wanted: BTreeSet<(AssetId, u8)> = BTreeSet::new(); + // Every frame, in groups and Paste Into containers too, with the wrap set on the frame or on + // its placed graphic (Direct Selection sets the graphic's). + let mut want = |it: &Item| { + let Some(g) = it.graphic() else { return }; + for w in [&it.wrap, &g.wrap] { + if w.mode == WrapMode::Contour && w.contour == ContourType::AlphaChannel { + wanted.insert((g.asset, w.alpha_threshold)); + } + } + }; + for sp in doc.spreads.iter().chain(doc.parents.iter()) { + for top in &sp.items { + top.walk(&mut want); + } + } + // Objects anchored in text wrap the lines after their anchor; anchored_items lists their + // children too. + if doc.has_anchored_items() { + for (_, it) in doc.anchored_items() { + want(it); + } + } + if wanted.is_empty() && doc.alpha_outlines.is_empty() { + return; + } + // An outline traced from data the asset no longer has (relinked or updated) is traced again. + let assets = &doc.assets; + doc.alpha_outlines.retain(|o| wanted.contains(&(o.asset, o.threshold)) && assets.get(&o.asset).is_some_and(|a| o.traced_from(&a.data))); + let traced: BTreeSet<(AssetId, u8)> = doc.alpha_outlines.iter().map(|o| (o.asset, o.threshold)).collect(); + let kept = doc.alpha_outlines.len(); + for (asset, threshold) in wanted { + if traced.contains(&(asset, threshold)) { + continue; + } + let Some(a) = doc.assets.get(&asset).filter(|a| a.is_raster()) else { continue }; + // An image with no outline (unreadable, too large) is remembered as an empty + // one, so later edits don't decode it again; the contour is then the frame's. + // A linked image's original is not read here (a document opens without reading its + // links): its preview is traced, scaled to the original's size; with no preview, the + // image has no outline yet and is traced once its bytes are resident. + let o = if a.data.is_linked() && a.data.resident().is_none() { + let Some(proxy) = a.proxy.as_ref().and_then(|p| Some((p.data.load().ok()?, a.pixels?))) else { continue }; + trace_bytes(&proxy.0, a.data.key(), Some(proxy.1), asset, threshold).unwrap_or_else(|| no_outline(&a.data, asset, threshold)) + } else { + trace(&a.data, asset, threshold).unwrap_or_else(|| no_outline(&a.data, asset, threshold)) + }; + doc.alpha_outlines.push(Arc::new(o)); + } + // `Document::alpha_outline` finds an outline by binary search. + if doc.alpha_outlines.len() > kept { + doc.alpha_outlines.sort_by_key(|o| (o.asset, o.threshold)); + } +} + +/// The empty outline standing for an image `trace` found none in: zero-size, which composition +/// takes as no outline, and dropped like a traced one when the asset's data changes. +fn no_outline(data: &AssetData, asset: AssetId, threshold: u8) -> AlphaOutline { + AlphaOutline { + asset, + threshold, + width: 0, + height: 0, + outer: Default::default(), + holes: Default::default(), + source: data.key(), + serial: AlphaOutline::next_serial(), + } +} + +/// The outline of the pixels of `data` more opaque than `threshold`: an image with no +/// transparency gives its rectangle. None for an image that can't be read or is too large. +pub(crate) fn trace(data: &AssetData, asset: AssetId, threshold: u8) -> Option { + trace_bytes(&data.load().ok()?, data.key(), None, asset, threshold) +} + +/// [`trace`] of encoded `bytes` standing for the data under `source`. With `size`, the outline +/// is scaled to an image of that size (a preview traced for the original it stands for). +fn trace_bytes(bytes: &[u8], source: designcraft_doc::SourceKey, size: Option<(u32, u32)>, asset: AssetId, threshold: u8) -> Option { + let (w, h) = designcraft_images::pixel_size(bytes)?; + if w == 0 || h == 0 || u64::from(w) * u64::from(h) > MAX_PIXELS { + return None; + } + let img = designcraft_images::decode_rgba(bytes)?; + if img.width() != w || img.height() != h { + return None; + } + let mut grid = MAX_GRID; + // The previous grid's mask: a grid half as fine is made from it without reading the pixels again. + let mut finer: Option<(Vec, u32, u32)> = None; + while grid >= 16 { + let (cols, rows) = (w.min(grid), h.min(grid)); + let mask = match finer.as_ref().and_then(|(m, fc, fr)| coarsen(m, *fc, *fr, cols, rows)) { + Some(m) => m, + None => occupancy(img.as_raw(), w, h, cols, rows, threshold), + }; + // Composition follows an outline of at most MAX_CONTOUR_POINTS path elements (holes + // included, for Include Inside Edges): a ring of k points is k + 1 elements with its close. + let fits = |outer: &[Vec<(i32, i32)>], holes: &[Vec<(i32, i32)>]| { + outer.iter().chain(holes).map(|r| r.len() + 1).sum::() <= designcraft_compose::MAX_CONTOUR_POINTS + }; + if let Some((outer, holes)) = rings(&mask, cols as usize, rows as usize).filter(|(o, h)| fits(o, h)) { + let (tw, th) = size.filter(|&(a, b)| a > 0 && b > 0).unwrap_or((w, h)); + let (sx, sy) = (f64::from(tw) / f64::from(cols), f64::from(th) / f64::from(rows)); + let path = |rings: &[Vec<(i32, i32)>]| { + let mut p = BezPath::new(); + for ring in rings { + let mut pts = ring.iter().map(|&(x, y)| Point::new(f64::from(x) * sx, f64::from(y) * sy)); + let Some(first) = pts.next() else { continue }; + p.move_to(first); + for q in pts { + p.line_to(q); + } + p.close_path(); + } + PathData::from_bezpath(&p) + }; + let serial = AlphaOutline::next_serial(); + return Some(AlphaOutline { asset, threshold, width: tw, height: th, outer: path(&outer), holes: path(&holes), source, serial }); + } + finer = Some((mask, cols, rows)); + grid /= 2; + } + None +} + +/// The `cols` × `rows` mask made from a `fc` × `fr` one, when each side has the same number of +/// cells or twice as many (a pixel's coarse cell is then its fine cell, or half of it). None +/// otherwise: the pixels are read again. +fn coarsen(mask: &[bool], fc: u32, fr: u32, cols: u32, rows: u32) -> Option> { + let step = |fine: u32, coarse: u32| match fine { + f if f == coarse => Some(1), + f if u64::from(f) == 2 * u64::from(coarse) => Some(2), + _ => None, + }; + let (sx, sy) = (step(fc, cols)?, step(fr, rows)?); + let (fc, cols) = (fc as usize, cols as usize); + let mut out = vec![false; cols * rows as usize]; + for (i, _) in mask.iter().enumerate().filter(|(_, v)| **v) { + let (x, y) = (i % fc, i / fc); + if let Some(c) = out.get_mut(y / sy * cols + x / sx) { + *c = true; + } + } + Some(out) +} + +/// Which cells of a `cols` × `rows` grid hold a pixel of the `w` × `h` RGBA image `rgba` more +/// opaque than `threshold` (a cell is visible when any of its pixels is). +fn occupancy(rgba: &[u8], w: u32, h: u32, cols: u32, rows: u32, threshold: u8) -> Vec { + let mut mask = vec![false; (cols as usize) * (rows as usize)]; + // A pixel's cell is (x * cols / w, y * rows / h). Along a row the column is counted up as x + // passes each cell's edge (cols <= w, so at most one edge per pixel) instead of divided out. + for (y, row) in rgba.chunks_exact(w as usize * 4).take(h as usize).enumerate() { + let base = (y as u64 * u64::from(rows) / u64::from(h)) as usize * cols as usize; + let (mut gx, mut acc, mut edge) = (0usize, 0u64, u64::from(w)); + for px in row.as_chunks::<4>().0 { + if acc >= edge { + gx += 1; + edge += u64::from(w); + } + acc += u64::from(cols); + if px[3] > threshold + && let Some(c) = mask.get_mut(base + gx) + { + *c = true; + } + } + } + mask +} + +/// The closed boundaries of the visible cells, split into outer boundaries and the boundaries of +/// holes (by winding: each boundary keeps the visible cells on the same side). None when the +/// outline would have more than [`MAX_EDGES`] edges. +#[allow(clippy::type_complexity)] +fn rings(mask: &[bool], cols: usize, rows: usize) -> Option<(Vec>, Vec>)> { + use std::collections::BTreeMap; + let visible = |x: i32, y: i32| { + x >= 0 && y >= 0 && (x as usize) < cols && (y as usize) < rows && mask.get(y as usize * cols + x as usize).copied().unwrap_or(false) + }; + let mut edges: BTreeMap<(i32, i32), Vec<(i32, i32)>> = BTreeMap::new(); + let mut count = 0usize; + for y in 0..rows as i32 { + for x in 0..cols as i32 { + if !visible(x, y) { + continue; + } + for (open, a, b) in [ + (!visible(x, y - 1), (x, y), (x + 1, y)), + (!visible(x + 1, y), (x + 1, y), (x + 1, y + 1)), + (!visible(x, y + 1), (x + 1, y + 1), (x, y + 1)), + (!visible(x - 1, y), (x, y + 1), (x, y)), + ] { + if open { + count += 1; + if count > MAX_EDGES { + return None; + } + edges.entry(a).or_default().push(b); + } + } + } + } + let (mut outer, mut holes) = (Vec::new(), Vec::new()); + while let Some((&start, _)) = edges.first_key_value() { + let mut ring = vec![start]; + let mut at = start; + for _ in 0..=MAX_EDGES { + let next = edges.get_mut(&at).and_then(Vec::pop)?; + if edges.get(&at).is_some_and(Vec::is_empty) { + edges.remove(&at); + } + // Drop the middle of straight runs. + if let [.., a, b] = ring[..] + && (b.0 - a.0) * (next.1 - b.1) == (b.1 - a.1) * (next.0 - b.0) + { + ring.pop(); + } + if next == start { + break; + } + ring.push(next); + at = next; + } + // Shoelace in y-down space: positive for outer boundaries, negative for holes. + let area: i64 = ring + .iter() + .zip(ring.iter().cycle().skip(1)) + .map(|(&(x0, y0), &(x1, y1))| i64::from(x0) * i64::from(y1) - i64::from(x1) * i64::from(y0)) + .sum(); + if ring.len() >= 3 { + if area > 0 { outer.push(ring) } else { holes.push(ring) } + } + } + Some((outer, holes)) +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + use crate::Session; + + /// A 64 × 64 PNG: visible where `on(x, y)`. + fn png(on: impl Fn(usize, usize) -> bool) -> Vec { + png_sized(64, on) + } + + /// A `size` × `size` PNG: visible where `on(x, y)`. + fn png_sized(size: usize, on: impl Fn(usize, usize) -> bool) -> Vec { + let mut pixels = vec![0; size * size * 4]; + for y in 0..size { + for x in 0..size { + let i = (y * size + x) * 4; + pixels[i] = 120; + pixels[i + 3] = if on(x, y) { 255 } else { 0 }; + } + } + designcraft_render::Rendered { width: size as u32, height: size as u32, pixels }.to_png() + } + + /// An outline too detailed for composition (here 4,096 separate dots, 20,480 path elements + /// on the finest grid) is traced on a coarser grid until composition can follow it. + #[test] + fn a_fragmented_outline_is_traced_coarser_until_composition_can_follow_it() { + let dots = png_sized(256, |x, y| x % 4 == 0 && y % 4 == 0); + let o = trace(&AssetData::embedded(dots), AssetId(1), 25).unwrap(); + let elements = o.outer.to_bezpath().elements().len() + o.holes.to_bezpath().elements().len(); + assert!(elements > 0 && elements <= designcraft_compose::MAX_CONTOUR_POINTS, "{elements} path elements"); + } + + /// An image with no pixel more opaque than the threshold leaves the text alone: with the + /// frame's contour the caption over it is overset, with Alpha Channel it is set. + #[test] + fn an_image_with_nothing_visible_wraps_no_text() { + let (mut s, image, story) = page(&png(|_, _| false), [150.0, 150.0, 178.0, 178.0]); + assert!(overset(&s, story), "the frame's contour covers the caption"); + s.execute("object.textWrap", &json!({"ids": [image], "contour": "alphaChannel"})).unwrap(); + assert!(!overset(&s, story), "nothing visible: nothing wraps"); + // The same for the wrap set on the placed graphic. + s.execute("object.textWrap", &json!({"ids": [image], "mode": "none"})).unwrap(); + s.execute("object.textWrap", &json!({"ids": [image], "content": true, "mode": "contour", "contour": "alphaChannel"})).unwrap(); + assert!(!overset(&s, story)); + } + + #[test] + fn traces_outer_boundaries_and_holes_apart() { + // A ring: a square with a square hole. + let data = png(|x, y| (8..56).contains(&x) && (8..56).contains(&y) && !((24..40).contains(&x) && (24..40).contains(&y))); + let o = trace(&AssetData::embedded(data), AssetId(1), 25).unwrap(); + assert_eq!((o.width, o.height), (64, 64)); + assert_eq!((o.outer.subpaths.len(), o.holes.subpaths.len()), (1, 1)); + let (a, b) = (o.outer.bounds().unwrap(), o.holes.bounds().unwrap()); + assert_eq!((a.x0, a.y0, a.x1, a.y1), (8.0, 8.0, 56.0, 56.0)); + assert_eq!((b.x0, b.y0, b.x1, b.y1), (24.0, 24.0, 40.0, 40.0)); + // An opaque image's outline is its rectangle. + let o = trace(&AssetData::embedded(png(|_, _| true)), AssetId(1), 25).unwrap(); + let a = o.outer.bounds().unwrap(); + assert_eq!((a.x0, a.y0, a.x1, a.y1, o.holes.subpaths.len()), (0.0, 0.0, 64.0, 64.0, 0)); + } + + /// The cell masks match a pixel-by-pixel count (cell = x * cols / w, y * rows / h), and a + /// mask half as fine made from the finer one matches the mask read from the pixels. + #[test] + fn cell_masks_match_the_pixels_and_coarser_masks_match_the_finer_ones() { + let (w, h) = (600u32, 300u32); + // An irregular pattern: visible where a small hash says so. + let on = |x: u32, y: u32| (x.wrapping_mul(2_654_435_761) ^ y.wrapping_mul(40_503)).rotate_left(7).is_multiple_of(7); + let mut rgba = vec![0u8; (w * h * 4) as usize]; + for y in 0..h { + for x in 0..w { + rgba[((y * w + x) * 4 + 3) as usize] = if on(x, y) { 255 } else { 0 }; + } + } + for (cols, rows) in [(256, 256), (128, 128), (100, 37), (600, 300)] { + let mut expect = vec![false; (cols * rows) as usize]; + for y in 0..h { + for x in 0..w { + if on(x, y) { + expect[((y * rows / h) * cols + x * cols / w) as usize] = true; + } + } + } + assert_eq!(occupancy(&rgba, w, h, cols, rows, 25), expect, "{cols} x {rows}"); + } + let fine = occupancy(&rgba, w, h, 256, 256, 25); + assert_eq!(coarsen(&fine, 256, 256, 128, 128), Some(occupancy(&rgba, w, h, 128, 128, 25))); + // Same count on one side, twice on the other. + let fine = occupancy(&rgba, w, h, 128, 256, 25); + assert_eq!(coarsen(&fine, 128, 256, 128, 128), Some(occupancy(&rgba, w, h, 128, 128, 25))); + // Any other ratio is read from the pixels. + assert_eq!(coarsen(&fine, 128, 256, 100, 128), None); + } + + #[test] + fn an_alpha_channel_contour_is_traced_when_set_and_kept_out_of_the_saved_file() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let data = png(|x, _| (16..48).contains(&x)); + let id = s + .execute("file.place", &json!({"base64": crate::cmd::file::base64_encode(&data), "name": "cut.png", "x": 100, "y": 100, "width": 128})) + .unwrap()["id"] + .clone(); + assert!(s.doc().unwrap().doc.alpha_outlines.is_empty()); + s.execute("object.textWrap", &json!({"ids": [id], "mode": "contour", "contour": "alphaChannel"})).unwrap(); + let d = &s.doc().unwrap().doc; + assert_eq!(d.alpha_outlines.len(), 1); + // Saved and opened again: traced again on open. + let bytes = crate::cmd::file::to_bytes(d).unwrap(); + let back = crate::cmd::file::from_bytes(&bytes).unwrap(); + assert!(back.alpha_outlines.is_empty(), "not saved"); + let st = crate::DocState::new(back, None); + assert_eq!(st.doc.alpha_outlines.len(), 1, "traced on open"); + // Wrap off: the outline goes. + s.execute("object.textWrap", &json!({"ids": [id], "mode": "none"})).unwrap(); + assert!(s.doc().unwrap().doc.alpha_outlines.is_empty()); + } + + /// An outline is traced once: later edits keep it. + #[test] + fn an_outline_is_not_traced_on_every_edit() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let data = png(|_, _| true); + let id = s + .execute("file.place", &json!({"base64": crate::cmd::file::base64_encode(&data), "name": "solid.png", "x": 100, "y": 100, "width": 128})) + .unwrap()["id"] + .clone(); + s.execute("object.textWrap", &json!({"ids": [id], "mode": "contour", "contour": "alphaChannel"})).unwrap(); + let first = s.doc().unwrap().doc.alpha_outlines.clone(); + assert_eq!(first.len(), 1, "remembered"); + s.execute("frame.create", &json!({"rect": [300, 300, 350, 350]})).unwrap(); + let after = &s.doc().unwrap().doc.alpha_outlines; + assert!(Arc::ptr_eq(&first[0], &after[0]), "kept, not traced again"); + } + + /// An opaque image's Alpha Channel contour is its rectangle, not the frame: moved within its + /// frame, it leaves the empty part of the frame to the text. + #[test] + fn an_opaque_image_wraps_its_rectangle() { + let (mut s, image, story) = page(&png(|_, _| true), [105.0, 150.0, 125.0, 178.0]); + s.execute("object.textWrap", &json!({"ids": [image], "contour": "alphaChannel"})).unwrap(); + assert!(overset(&s, story), "the image covers the caption"); + // The graphic moved 30 pt right within its frame: the frame's left 30 pt are empty. + s.execute("selection.set", &json!({"ids": [image], "content": true})).unwrap(); + s.execute("transform.move", &json!({"dx": 30, "dy": 0})).unwrap(); + assert!(!overset(&s, story), "the empty part of the frame takes the caption"); + } + + /// Outlines are traced for a wrap set on the placed graphic and for frames inside groups, and + /// traced again when the image's data changes under the same asset (relink, link update). + #[test] + fn graphic_wraps_nested_frames_and_relinked_images_get_outlines() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let place = |s: &mut Session, x: u64| { + let data = png(|x, _| (16..48).contains(&x)); + s.execute("file.place", &json!({"base64": crate::cmd::file::base64_encode(&data), "name": "cut.png", "x": x, "y": 100, "width": 128})) + .unwrap()["id"] + .as_u64() + .unwrap() + }; + let image = place(&mut s, 100); + // The wrap on the graphic (Direct Selection), not the frame. + s.execute("object.textWrap", &json!({"ids": [image], "content": true, "mode": "contour", "contour": "alphaChannel"})).unwrap(); + let frame_wrap = s.doc().unwrap().doc.item(designcraft_doc::ItemId(image)).unwrap().wrap.mode; + assert_eq!(frame_wrap, WrapMode::None, "the frame has no wrap of its own"); + assert_eq!(s.doc().unwrap().doc.alpha_outlines.len(), 1, "traced for the graphic's wrap"); + // In a group with another frame: still traced. + let other = s.execute("frame.create", &json!({"rect": [300, 100, 350, 150]})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.group", &json!({"ids": [image, other]})).unwrap(); + let d = &s.doc().unwrap().doc; + assert!(d.find(designcraft_doc::ItemId(image)).unwrap().path.len() > 1, "the frame is nested"); + assert_eq!(d.alpha_outlines.len(), 1, "a nested frame keeps its outline"); + // A frame placed and grouped before its wrap is set: traced too. + let second = place(&mut s, 400); + let other2 = s.execute("frame.create", &json!({"rect": [600, 100, 650, 150]})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.group", &json!({"ids": [second, other2]})).unwrap(); + s.execute("object.textWrap", &json!({"ids": [second], "mode": "contour", "contour": "alphaChannel", "threshold": 200})).unwrap(); + assert_eq!(s.doc().unwrap().doc.alpha_outlines.len(), 2); + // The image data replaced under the same asset, as a relink does: traced again. + let Some(designcraft_doc::Content::Graphic(g)) = s.doc().unwrap().doc.item(designcraft_doc::ItemId(image)).map(|it| it.content.clone()) + else { + panic!("a graphic") + }; + let narrower = AssetData::embedded(png(|x, _| (24..40).contains(&x))); + s.edit(|d, _| { + let a = d.assets.get(&g.asset).unwrap(); + let mut a = (**a).clone(); + a.data = narrower.clone(); + d.assets.insert(g.asset, Arc::new(a)); + Ok(()) + }) + .unwrap(); + let d = &s.doc().unwrap().doc; + let o = d.alpha_outline(g.asset, designcraft_doc::DEFAULT_ALPHA_THRESHOLD).unwrap(); + assert!(o.traced_from(&narrower)); + let b = o.outer.bounds().unwrap(); + assert_eq!((b.x0, b.x1), (24.0, 40.0), "the new image's outline"); + } + + /// An outline traced after others is still found: a threshold lower than a kept outline's + /// is traced later and must not hide either outline from the lookup. + #[test] + fn outlines_traced_later_are_found_by_image_and_threshold() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let data = png(|x, _| (16..48).contains(&x)); + let image = s + .execute("file.place", &json!({"base64": crate::cmd::file::base64_encode(&data), "name": "cut.png", "x": 100, "y": 100, "width": 128})) + .unwrap()["id"] + .as_u64() + .unwrap(); + s.execute("object.textWrap", &json!({"ids": [image], "content": true, "mode": "contour", "contour": "alphaChannel", "threshold": 200})) + .unwrap(); + s.execute("object.textWrap", &json!({"ids": [image], "mode": "contour", "contour": "alphaChannel"})).unwrap(); + let d = &s.doc().unwrap().doc; + assert_eq!(d.alpha_outlines.len(), 2, "one outline for each threshold"); + let Some(g) = d.item(designcraft_doc::ItemId(image)).and_then(|it| it.graphic()) else { panic!("a graphic") }; + for threshold in [designcraft_doc::DEFAULT_ALPHA_THRESHOLD, 200] { + let o = d.alpha_outline(g.asset, threshold); + assert!(o.is_some_and(|o| o.threshold == threshold), "the outline at {threshold} is found"); + } + assert!(d.alpha_outline(g.asset, 100).is_none(), "no outline at a threshold nothing uses"); + } + + /// A wrap with the default threshold saves as it did before thresholds were stored; another + /// threshold is saved. + #[test] + fn the_default_threshold_is_left_out_of_a_saved_wrap() { + let v = serde_json::to_value(designcraft_doc::TextWrap::default()).unwrap(); + assert!(v.get("alphaThreshold").is_none(), "{v}"); + let back: designcraft_doc::TextWrap = serde_json::from_value(v).unwrap(); + assert_eq!(back.alpha_threshold, designcraft_doc::DEFAULT_ALPHA_THRESHOLD); + let w = designcraft_doc::TextWrap { alpha_threshold: 200, ..Default::default() }; + assert_eq!(serde_json::to_value(w).unwrap()["alphaThreshold"], 200); + } + + /// A relink that changes only the image data recomposes the text around the new outline. + #[test] + fn text_is_composed_again_around_a_relinked_images_outline() { + let (mut s, image, story) = page(&png(|x, _| x < 32), [180.0, 150.0, 220.0, 178.0]); + s.execute("object.textWrap", &json!({"ids": [image], "contour": "alphaChannel"})).unwrap(); + assert!(!overset(&s, story), "the left half is visible: the caption on the right is set"); + let Some(designcraft_doc::Content::Graphic(g)) = + s.doc().unwrap().doc.item(designcraft_doc::ItemId(image.as_u64().unwrap())).map(|it| it.content.clone()) + else { + panic!("a graphic") + }; + let right = AssetData::embedded(png(|x, _| x >= 32)); + s.edit(|d, _| { + let mut a = (**d.assets.get(&g.asset).unwrap()).clone(); + a.data = right.clone(); + d.assets.insert(g.asset, Arc::new(a)); + Ok(()) + }) + .unwrap(); + assert!(overset(&s, story), "the right half is visible now: it covers the caption"); + } + + /// An image anchored in text keeps its outline: anchored objects wrap the lines after their + /// anchor, and they are kept in the story, not on the spread. + #[test] + fn an_anchored_image_keeps_its_outline() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let data = png(|x, _| (16..48).contains(&x)); + let image = s + .execute("file.place", &json!({"base64": crate::cmd::file::base64_encode(&data), "name": "cut.png", "x": 100, "y": 100, "width": 128})) + .unwrap()["id"] + .as_u64() + .unwrap(); + s.execute("object.textWrap", &json!({"ids": [image], "mode": "contour", "contour": "alphaChannel"})).unwrap(); + assert_eq!(s.doc().unwrap().doc.alpha_outlines.len(), 1); + let t = s.execute("frame.create", &json!({"rect": [36, 300, 400, 500], "content": "text", "text": "Before after."})).unwrap(); + s.execute("anchored.insert", &json!({"ids": [image], "story": t["story"], "pos": 7})).unwrap(); + let d = &s.doc().unwrap().doc; + assert!(d.anchored_item(designcraft_doc::ItemId(image)).is_some(), "the image is in the text"); + assert_eq!(d.alpha_outlines.len(), 1, "the anchored image keeps its outline"); + } + + /// An image placed 128 pt wide at (100, 100) (2 pt per pixel), its wrap a contour with no + /// offset, and a caption frame at `caption` with 8 pt "Hi". + fn page(data: &[u8], caption: [f64; 4]) -> (Session, Value, u64) { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let image = s + .execute("file.place", &json!({"base64": crate::cmd::file::base64_encode(data), "name": "cut.png", "x": 100, "y": 100, "width": 128})) + .unwrap()["id"] + .clone(); + let c = s.execute("frame.create", &json!({"rect": caption, "content": "text", "text": "Hi"})).unwrap(); + s.execute("selection.set", &json!({"ids": [c["id"]]})).unwrap(); + s.execute("type.char", &json!({"size": 8})).unwrap(); + s.execute("object.textWrap", &json!({"ids": [image], "mode": "contour", "offset": 0})).unwrap(); + (s, image, c["story"].as_u64().unwrap()) + } + + fn overset(s: &Session, story: u64) -> bool { + s.cache.get(&s.doc().unwrap().doc, designcraft_doc::StoryId(story), None).is_overset() + } + + use serde_json::Value; + + /// A caption fits between two legs of a cutout, and the contour follows the image when it's + /// moved within its frame (it isn't a boundary stored where it was traced). + #[test] + fn an_alpha_channel_contour_keeps_gaps_open_and_follows_the_image() { + // Legs at pixels 8..20 and 44..56: 116..140 and 188..212 on the page. + let (mut s, image, story) = page(&png(|x, _| (8..20).contains(&x) || (44..56).contains(&x)), [150.0, 120.0, 178.0, 170.0]); + assert!(overset(&s, story), "the frame's contour covers the gap"); + s.execute("object.textWrap", &json!({"ids": [image], "contour": "alphaChannel"})).unwrap(); + assert!(!overset(&s, story), "the gap between the legs stays open"); + // The graphic moved 30 pt right within its frame: its left leg now covers the caption. + s.execute("selection.set", &json!({"ids": [image], "content": true})).unwrap(); + s.execute("transform.move", &json!({"dx": 30, "dy": 0})).unwrap(); + assert!(overset(&s, story), "the contour moved with the image"); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(!overset(&s, story)); + } + + /// A hole enclosed by the image stays blocked unless Include Inside Edges is on. + #[test] + fn holes_are_blocked_unless_inside_edges_are_included() { + // A ring: outer 116..212, hole 148..180 on the page. + let ring = png(|x, y| (8..56).contains(&x) && (8..56).contains(&y) && !((24..40).contains(&x) && (24..40).contains(&y))); + let (mut s, image, story) = page(&ring, [152.0, 152.0, 176.0, 176.0]); + s.execute("object.textWrap", &json!({"ids": [image], "contour": "alphaChannel"})).unwrap(); + assert!(overset(&s, story), "the hole is blocked with the ring around it"); + s.execute("object.textWrap", &json!({"ids": [image], "insideEdges": true})).unwrap(); + assert!(!overset(&s, story), "Include Inside Edges lets text into the hole"); + for bad in [json!({"ids": [image], "threshold": 255}), json!({"ids": [image], "insideEdges": 1})] { + assert!(s.execute("object.textWrap", &bad).is_err()); + } + } +} diff --git a/crates/engine/src/cmd/anchored.rs b/crates/engine/src/cmd/anchored.rs index 1e00585ca..bc80b2e1c 100644 --- a/crates/engine/src/cmd/anchored.rs +++ b/crates/engine/src/cmd/anchored.rs @@ -125,12 +125,14 @@ pub(crate) fn check_item(it: &Item) -> Result<()> { /// Anchor copies of `items` (in spread coordinates) at `pos` of `sid`; returns the end position. pub(crate) fn anchor_items(d: &mut Document, sid: StoryId, pos: usize, items: Vec, position: &AnchorPosition) -> Result { + let count = items.len(); let st = d.story_mut(sid).ok_or(designcraft_doc::DocError::NoStory(sid))?; let mut at = pos.min(st.len()); for it in items { st.insert_object(at, AnchoredObject::new(it, position.clone())); at += OBJECT_MARK.len_utf8(); } + d.adjust_text_ranges(sid, pos..pos, count * OBJECT_MARK.len_utf8()); Ok(at) } @@ -227,9 +229,18 @@ fn release(s: &mut Session, p: &Value) -> Result { if d.layer(it.layer).is_none() { it.layer = d.default_layer(); } + // A text frame keeps its place in its story's thread under its new id. + if let Some(st) = it.text_frame().and_then(|t| d.story_mut(t.story)) { + match st.frames.iter_mut().find(|f| **f == obj.item.id) { + Some(f) => *f = it.id, + None => st.frames.push(it.id), + } + } let id = d.insert_item(spread, it, None)?; let st = d.story_mut(sid).ok_or(designcraft_doc::DocError::NoStory(sid))?; - st.delete(pos..pos + OBJECT_MARK.len_utf8()); + let len = OBJECT_MARK.len_utf8(); + st.delete(pos..pos + len); + d.adjust_text_ranges(sid, pos..pos + len, 0); *sel = designcraft_doc::Selection::items(vec![id]); Ok(json!({"id": id.0})) }) @@ -333,3 +344,251 @@ mod custom_tests { )); } } + +#[cfg(test)] +mod text_frame_tests { + use designcraft_doc::{ParaFormat, StoryId}; + use designcraft_geom::Rect; + use serde_json::json; + + use super::*; + + /// Anchor, at `pos` of `host`, a 200 × 40 pt text frame showing a new story with `text`. + fn anchor(d: &mut Document, host: StoryId, pos: usize, text: &str) -> designcraft_doc::Result<(StoryId, ItemId)> { + let layer = d.default_layer(); + let (fid, sid) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(0.0, 0.0, 200.0, 40.0), layer, text, ParaFormat::default())?; + let item = d.item(fid).ok_or(designcraft_doc::DocError::NoItem(fid))?.clone(); + d.spread_mut(SpreadRef::Doc(0)).ok_or(designcraft_doc::DocError::NoItem(fid))?.items.retain(|i| i.id != fid); + d.story_mut(host).ok_or(designcraft_doc::DocError::NoStory(host))?.insert_object(pos, AnchoredObject::new(item, AnchorPosition::default())); + Ok((sid, fid)) + } + + /// A new document with a text frame whose story holds, after "Host ", an anchored text frame + /// showing "Anchored words " and, in that, one showing "Deeper". Returns the host story, the + /// anchored story and the anchored frame's id. + fn session() -> (Session, StoryId, StoryId, ItemId) { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let r = s.execute("frame.create", &json!({"rect": [72, 72, 400, 400], "content": "text", "text": "Host end"})).unwrap(); + let host = StoryId(r["story"].as_u64().unwrap()); + let (sid, id) = s + .edit(|d, _| { + let (sid, id) = anchor(d, host, 5, "Anchored words ")?; + anchor(d, sid, 15, "Deeper")?; + Ok((sid, id)) + }) + .unwrap(); + s.doc().unwrap().doc.check().unwrap(); + (s, host, sid, id) + } + + /// The document is valid (and opens again once saved); returns the texts its anchored text + /// frames show, sorted, after checking each has a story of its own. + fn shown(s: &Session) -> Vec { + let d = &s.doc().unwrap().doc; + d.check().unwrap(); + designcraft_format::load(&designcraft_format::save(d).unwrap()).unwrap(); + let stories: Vec = d.anchored_items().iter().filter_map(|(_, i)| i.text_frame()).map(|t| t.story).collect(); + let distinct: std::collections::HashSet<_> = stories.iter().collect(); + assert_eq!(distinct.len(), stories.len(), "a story of its own each"); + let mut texts: Vec = stories.iter().map(|sid| d.story(*sid).unwrap().text.clone()).collect(); + texts.sort(); + texts + } + + const SHOWN: [&str; 2] = ["Anchored words \u{E00E}", "Deeper"]; + + #[test] + fn releasing_an_anchored_text_frame_threads_its_story_to_it() { + let (mut s, host, sid, _) = session(); + s.execute("anchored.release", &json!({"story": host.0, "index": 0})).unwrap(); + let d = s.doc().unwrap().doc.clone(); + d.check().unwrap(); + let id = s.doc().unwrap().selection.items[0]; + assert_eq!(d.story(sid).unwrap().frames, vec![id]); + assert_eq!(d.item(id).unwrap().text_frame().unwrap().story, sid); + assert!(s.cache.get(&d, sid, None).frame(id).is_some_and(|f| !f.lines.is_empty())); + assert_eq!(shown(&s), ["Deeper"]); + } + + #[test] + fn copied_anchored_text_frames_get_stories_of_their_own() { + let (mut s, host, sid, id) = session(); + // Text copied and pasted in the same story. + s.execute("text.select", &json!({"story": host.0, "anchor": 0, "focus": 9})).unwrap(); + s.execute("edit.copy", &json!({})).unwrap(); + let len = s.doc().unwrap().doc.story(host).unwrap().len(); + s.execute("text.select", &json!({"story": host.0, "anchor": len, "focus": len})).unwrap(); + s.execute("edit.paste", &json!({})).unwrap(); + assert_eq!(shown(&s), ["Anchored words \u{E00E}", "Anchored words \u{E00E}", "Deeper", "Deeper"]); + // The original keeps its frame and story. + assert_eq!(s.doc().unwrap().doc.story(sid).unwrap().frames, vec![id]); + // The host frame duplicated. + let frame = s.doc().unwrap().doc.story(host).unwrap().frames[0]; + s.execute("selection.set", &json!({"ids": [frame.0]})).unwrap(); + s.execute("edit.duplicate", &json!({})).unwrap(); + assert_eq!(shown(&s).len(), 8); + // Text dragged with a copy. + s.execute("text.select", &json!({"story": host.0, "anchor": 0, "focus": 9})).unwrap(); + s.edit(|d, _| { + let st = d.story_mut(host).ok_or(designcraft_doc::DocError::NoStory(host))?; + let piece = st.extract(0..9); + st.insert_story(0, &piece); + Ok(()) + }) + .unwrap(); + assert_eq!(shown(&s).len(), 10); + } + + /// The endnote frame lists the endnotes of anchored stories copied or deleted with their + /// text at once: it used to be brought up to date before the copies were made. + #[test] + fn the_endnote_frame_follows_anchored_stories_copied_and_deleted() { + let (mut s, host, sid, _) = session(); + s.execute("text.select", &json!({"story": sid.0, "anchor": 0, "focus": 0})).unwrap(); + s.execute("endnote.insert", &json!({"text": "A note"})).unwrap(); + let notes = |s: &Session| { + let d = &s.doc().unwrap().doc; + d.story(d.endnote_story.unwrap()).unwrap().text.matches("A note").count() + }; + assert_eq!(notes(&s), 1); + s.execute("text.select", &json!({"story": host.0, "anchor": 0, "focus": 9})).unwrap(); + s.execute("edit.copy", &json!({})).unwrap(); + let len = s.doc().unwrap().doc.story(host).unwrap().len(); + s.execute("text.select", &json!({"story": host.0, "anchor": len, "focus": len})).unwrap(); + s.execute("edit.paste", &json!({})).unwrap(); + assert_eq!(notes(&s), 2, "copied"); + s.execute("text.select", &json!({"story": host.0, "anchor": 0, "focus": 9})).unwrap(); + s.execute("edit.cut", &json!({})).unwrap(); + assert_eq!(notes(&s), 1, "deleted"); + } + + /// Text with an anchored text frame pasted into the generated endnote story is replaced when + /// the endnotes are set again; the repair after it leaves no story threaded to the dropped frame. + #[test] + fn anchored_text_frames_pasted_into_the_endnote_story_leave_a_valid_document() { + let (mut s, host, sid, _) = session(); + s.execute("text.select", &json!({"story": sid.0, "anchor": 0, "focus": 0})).unwrap(); + s.execute("endnote.insert", &json!({"text": "A note"})).unwrap(); + s.execute("text.select", &json!({"story": host.0, "anchor": 0, "focus": 9})).unwrap(); + s.execute("edit.copy", &json!({})).unwrap(); + let notes = s.doc().unwrap().doc.endnote_story.unwrap(); + let len = s.doc().unwrap().doc.story(notes).unwrap().len(); + s.execute("text.select", &json!({"story": notes.0, "anchor": len, "focus": len})).unwrap(); + let _ = s.execute("edit.paste", &json!({})); + s.doc().unwrap().doc.check().unwrap(); + } + + #[test] + fn deleted_anchored_text_frames_take_their_stories_along() { + let (mut s, host, sid, _) = session(); + let stories = s.doc().unwrap().doc.stories.len(); + // Cut with the text it is in, and pasted back. + s.execute("text.select", &json!({"story": host.0, "anchor": 0, "focus": 9})).unwrap(); + s.execute("edit.cut", &json!({})).unwrap(); + assert!(shown(&s).is_empty()); + assert!(s.doc().unwrap().doc.story(sid).is_none()); + assert_eq!(s.doc().unwrap().doc.stories.len(), stories - 2); + s.execute("edit.paste", &json!({})).unwrap(); + assert_eq!(shown(&s), SHOWN); + assert_eq!(s.doc().unwrap().doc.stories.len(), stories); + // Deleted with the frame it is anchored in; undo brings it back. + let frame = s.doc().unwrap().doc.story(host).unwrap().frames[0]; + s.execute("selection.set", &json!({"ids": [frame.0]})).unwrap(); + s.execute("edit.clear", &json!({})).unwrap(); + assert!(shown(&s).is_empty()); + assert!(s.doc().unwrap().doc.stories.is_empty()); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(shown(&s), SHOWN); + } + + #[test] + fn anchored_text_frames_paste_into_another_document() { + let (mut s, host, _, _) = session(); + let frame = s.doc().unwrap().doc.story(host).unwrap().frames[0]; + // A second document, whose ids are those of the first one. + s.execute("file.new", &json!({})).unwrap(); + let r = s.execute("frame.create", &json!({"rect": [72, 72, 400, 400], "content": "text", "text": "Other "})).unwrap(); + let other = StoryId(r["story"].as_u64().unwrap()); + s.edit(|d, _| Ok(anchor(d, other, 6, "Elsewhere")?)).unwrap(); + // Copied text. + s.set_active(0); + s.execute("text.select", &json!({"story": host.0, "anchor": 0, "focus": 9})).unwrap(); + s.execute("edit.copy", &json!({})).unwrap(); + s.set_active(1); + let len = s.doc().unwrap().doc.story(other).unwrap().len(); + s.execute("text.select", &json!({"story": other.0, "anchor": len, "focus": len})).unwrap(); + s.execute("edit.paste", &json!({})).unwrap(); + assert_eq!(shown(&s), ["Anchored words \u{E00E}", "Deeper", "Elsewhere"]); + // A copied frame. + s.set_active(0); + s.execute("selection.set", &json!({"ids": [frame.0]})).unwrap(); + s.execute("edit.copy", &json!({})).unwrap(); + s.set_active(1); + s.execute("selection.set", &json!({"ids": []})).unwrap(); + s.execute("edit.paste", &json!({})).unwrap(); + assert_eq!(shown(&s), ["Anchored words \u{E00E}", "Anchored words \u{E00E}", "Deeper", "Deeper", "Elsewhere"]); + } + + /// Place a 4 × 4 pt graphic of grey `v`; returns its frame and its asset. + fn place(s: &mut Session, v: u8) -> (ItemId, designcraft_doc::AssetId) { + let png = designcraft_render::Rendered { width: 4, height: 4, pixels: vec![v; 64] }.to_png(); + let r = + s.execute("file.place", &json!({"base64": crate::cmd::file::base64_encode(&png), "name": format!("{v}.png"), "x": 72, "y": 72})).unwrap(); + (ItemId(r["id"].as_u64().unwrap()), designcraft_doc::AssetId(r["asset"].as_u64().unwrap())) + } + + /// The files the graphics anchored in the active document show (in its anchored text frames' + /// stories too), sorted; `None` for a graphic whose asset is missing. + fn anchored_files(s: &Session) -> Vec>>> { + let d = &s.doc().unwrap().doc; + d.check().unwrap(); + let mut files: Vec<_> = + d.anchored_items().iter().filter_map(|(_, i)| i.graphic()).map(|g| d.assets.get(&g.asset).map(|a| a.data.load().unwrap())).collect(); + files.sort(); + files + } + + /// Copied text pasted into another document takes along the files of the graphics anchored + /// in it and in the stories of its anchored text frames: their asset ids may name other files + /// there, or none. + #[test] + fn pasted_text_takes_its_graphics_into_another_document() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let (inline, a) = place(&mut s, 10); + let (nested, _) = place(&mut s, 20); + let r = s.execute("frame.create", &json!({"rect": [72, 200, 400, 500], "content": "text", "text": "Host end"})).unwrap(); + let host = StoryId(r["story"].as_u64().unwrap()); + let (sid, _) = s.edit(|d, _| Ok(anchor(d, host, 5, "Anchored words ")?)).unwrap(); + // A graphic in the copied text and one in its anchored text frame's story. + s.execute("anchored.insert", &json!({"ids": [inline.0], "story": host.0, "pos": 0})).unwrap(); + s.execute("anchored.insert", &json!({"ids": [nested.0], "story": sid.0, "pos": 0})).unwrap(); + let files = anchored_files(&s); + assert_eq!(files.len(), 2); + assert!(files.iter().all(Option::is_some)); + let len = s.doc().unwrap().doc.story(host).unwrap().len(); + s.execute("text.select", &json!({"story": host.0, "anchor": 0, "focus": len})).unwrap(); + s.execute("edit.copy", &json!({})).unwrap(); + let plain = s.text_clipboard.as_ref().unwrap().1.clone(); + + // Another document whose own graphic has the asset id of the first copied one. + s.execute("file.new", &json!({})).unwrap(); + let (_, b) = place(&mut s, 30); + assert_eq!(a, b, "fresh documents allocate the same first asset id"); + let own = s.doc().unwrap().doc.assets.get(&b).unwrap().data.clone(); + let r = s.execute("frame.create", &json!({"rect": [72, 200, 400, 500], "content": "text", "text": "Other "})).unwrap(); + let other = StoryId(r["story"].as_u64().unwrap()); + // Into text. + s.execute("text.select", &json!({"story": other.0, "anchor": 6, "focus": 6})).unwrap(); + s.execute("edit.paste", &json!({})).unwrap(); + assert_eq!(anchored_files(&s), files); + // Into a new text frame. + s.execute("edit.deselectAll", &json!({})).unwrap(); + s.execute("edit.paste", &json!({"text": plain})).unwrap(); + let twice: Vec<_> = files.iter().flat_map(|f| [f.clone(), f.clone()]).collect(); + assert_eq!(anchored_files(&s), twice); + // The document's own graphic keeps its file. + assert_eq!(s.doc().unwrap().doc.assets.get(&b).unwrap().data, own); + } +} diff --git a/crates/engine/src/cmd/anchors.rs b/crates/engine/src/cmd/anchors.rs index fec81de4b..0968fb588 100644 --- a/crates/engine/src/cmd/anchors.rs +++ b/crates/engine/src/cmd/anchors.rs @@ -66,6 +66,15 @@ pub fn specs() -> Vec { has_selection, join_paths ), + cmd!( + "path.deletePoints", + "Delete Points", + [], + None, + "{points?: [[id, subpath, index]]} — the Direct Selection tool's selected points by default, in one undo step (Properties › Quick Actions › Delete Point(s)); a subpath left with one point goes, and an object with none is removed → {deleted, removed: [id]}", + has_doc, + delete_points + ), cmd!( "path.convertPoints", "Convert Point", @@ -162,6 +171,66 @@ fn join_paths(s: &mut Session, p: &Value) -> Result { }) } +/// Delete Point(s): removes the given points, or the ones selected with Direct Selection. +fn delete_points(s: &mut Session, p: &Value) -> Result { + const ID: &str = "path.deletePoints"; + let points: Vec<(ItemId, usize, usize)> = match p.get("points") { + Some(v) => serde_json::from_value::>(v.clone()) + .map_err(|e| bad(ID, format!("points: [[id, subpath, index], …] ({e})")))? + .into_iter() + .map(|(id, si, ai)| (ItemId(id), si, ai)) + .collect(), + None => s.doc()?.selection.anchors.clone(), + }; + if points.is_empty() { + return Err(bad(ID, "no points selected")); + } + // Each subpath's points, worked from the last subpath and the last point back, so the indices + // still to delete keep their place. + let mut groups: Vec<((ItemId, usize), Vec)> = Vec::new(); + for (id, si, ai) in points { + match groups.iter_mut().find(|(k, _)| *k == (id, si)) { + Some((_, v)) => v.push(ai), + None => groups.push(((id, si), vec![ai])), + } + } + groups.sort_by_key(|((id, si), _)| std::cmp::Reverse((id.0, *si))); + s.edit(|d, sel| { + let (mut deleted, mut removed) = (0usize, Vec::new()); + for ((id, si), mut ais) in groups { + if d.item(id).is_none() { + continue; + } + path_editable(d, id, ID)?; + let Some(it) = d.item_mut(id) else { continue }; + let Some(sp) = it.path.subpaths.get_mut(si) else { continue }; + ais.sort_unstable(); + ais.dedup(); + for ai in ais.into_iter().rev() { + if ai < sp.anchors.len() { + sp.anchors.remove(ai); + deleted += 1; + } + } + // A subpath needs two points (three to stay closed). + let (left, closed) = (sp.anchors.len(), sp.closed); + if left < 2 { + it.path.subpaths.remove(si); + } else if closed && left < 3 { + sp.closed = false; + } + as_path(&mut it.shape); + if it.path.subpaths.is_empty() { + d.remove_item(id)?; + sel.items.retain(|i| *i != id); + removed.push(id.0); + } + } + sel.anchors.clear(); + Ok(json!({"deleted": deleted, "removed": removed})) + }) +} + /// Convert Point: the selected points (or every point of the selected paths) to a point type. fn convert_points(s: &mut Session, p: &Value) -> Result { let kind = super::str_param(p, "kind").unwrap_or("plain").to_string(); @@ -222,33 +291,61 @@ fn convert_points(s: &mut Session, p: &Value) -> Result { }) } +/// Most samples of a drag that Erase / Smooth look at. +const MAX_DRAG_SAMPLES: usize = 4096; + /// Erase / Smooth: the stretch of one subpath touched by the drag. fn erase_or_smooth(s: &mut Session, p: &Value, smooth: bool) -> Result { let cmd = if smooth { "path.smooth" } else { "path.erase" }; let id = super::id_param(p, "id").ok_or_else(|| bad(cmd, "missing id"))?; let tol = p.get("tolerance").and_then(Value::as_f64).unwrap_or(4.0); - let pts: Vec = p + let mut pts: Vec = p .get("points") .and_then(Value::as_array) .map(|a| a.iter().filter_map(|v| Some(Point::new(v.get(0)?.as_f64()?, v.get(1)?.as_f64()?))).collect()) .unwrap_or_default(); - s.edit(|d, _| { + // Each sample is a search of every segment: repeated samples add nothing, and a drag has no use + // for more than MAX_DRAG_SAMPLES (evenly thinned, the first and last kept). Whether the drag + // touched the path is decided on every distinct sample, though: see below. + let mut seen = std::collections::HashSet::new(); + pts.retain(|q| seen.insert((q.x.to_bits(), q.y.to_bits()))); + let thinned: Vec = if pts.len() > MAX_DRAG_SAMPLES { + let (n, last) = (pts.len(), pts.last().copied()); + (0..MAX_DRAG_SAMPLES).filter_map(|i| pts.get((i as u64 * n as u64 / MAX_DRAG_SAMPLES as u64) as usize).copied()).chain(last).collect() + } else { + Vec::new() + }; + s.edit(|d, sel| { path_editable(d, id, cmd)?; let inv = to_inner(d, id).ok_or(designcraft_doc::DocError::NoItem(id))?; let scale = inv.determinant().abs().sqrt().max(1e-9); let it = d.item_mut(id).ok_or(designcraft_doc::DocError::NoItem(id))?; // Where the drag touched the path, per subpath. - let mut hits: Vec<(usize, usize, f64)> = Vec::new(); - for q in &pts { - if let Some((si, seg, t, _, dist)) = it.path.nearest(inv * *q) - && dist <= tol * scale - { - hits.push((si, seg, t)); + let hits_of = |set: &[Point]| -> Vec<(usize, usize, f64)> { + let mut hits = Vec::new(); + for q in set { + if let Some((si, seg, t, _, dist)) = it.path.nearest(inv * *q) + && dist <= tol * scale + { + hits.push((si, seg, t)); + } + } + hits + }; + // A long drag is searched thinned; only when that finds nothing are all its samples, so a + // touch the thinning skipped over still counts and a long drag is never refused for it. + let mut hits = hits_of(if thinned.is_empty() { &pts } else { &thinned }); + if hits.is_empty() && !thinned.is_empty() { + hits = hits_of(&pts); + } + // The subpath with the most hits (the last of equals), counted in one pass. + let mut counts = vec![0usize; it.path.subpaths.len()]; + for h in &hits { + if let Some(n) = counts.get_mut(h.0) { + *n += 1; } } - let Some(si) = - (0..it.path.subpaths.len()).max_by_key(|i| hits.iter().filter(|h| h.0 == *i).count()).filter(|i| hits.iter().any(|h| h.0 == *i)) - else { + let Some((si, _)) = counts.iter().copied().enumerate().filter(|(_, n)| *n > 0).max_by_key(|(_, n)| *n) else { return Err(bad(cmd, "the drag didn't touch the path")); }; let on: Vec<(usize, f64)> = hits.iter().filter(|h| h.0 == si).map(|h| (h.1, h.2)).collect(); @@ -257,6 +354,8 @@ fn erase_or_smooth(s: &mut Session, p: &Value, smooth: bool) -> Result { return Err(bad(cmd, "the drag didn't touch the path")); }; let sp = it.path.subpaths[si].clone(); + // The subpath list changes under the stored point indices: they would name other points. + sel.anchors.retain(|a| a.0 != id); if smooth { it.path.subpaths[si] = designcraft_geom::edit_path::smooth(&sp, a, b, tol * scale); } else { @@ -299,7 +398,7 @@ fn add_anchor(s: &mut Session, p: &Value) -> Result { let id = super::id_param(p, "id").ok_or_else(|| bad("path.addAnchor", "missing id"))?; let at = point_param(p, "at").ok_or_else(|| bad("path.addAnchor", "missing at"))?; let tol = p.get("tolerance").and_then(Value::as_f64).unwrap_or(4.0); - s.edit(|d, _| { + s.edit(|d, sel| { path_editable(d, id, "path.addAnchor")?; let inv = to_inner(d, id).ok_or(designcraft_doc::DocError::NoItem(id))?; let it = d.item_mut(id).ok_or(designcraft_doc::DocError::NoItem(id))?; @@ -313,6 +412,10 @@ fn add_anchor(s: &mut Session, p: &Value) -> Result { let t = t.clamp(1e-4, 1.0 - 1e-4); let ai = it.path.subpaths[si].insert_anchor(seg, t); as_path(&mut it.shape); + // Selected points after the new one move up an index, so they stay the same points. + for a in sel.anchors.iter_mut().filter(|a| a.0 == id && a.1 == si && a.2 >= ai) { + a.2 += 1; + } Ok(json!({"subpath": si, "anchor": ai})) }) } @@ -328,15 +431,27 @@ fn delete_anchor(s: &mut Session, p: &Value) -> Result { } sp.anchors.remove(ai); // A subpath needs two points (three to stay closed). - if sp.anchors.len() < 2 { + let removed_subpath = sp.anchors.len() < 2; + if removed_subpath { it.path.subpaths.remove(si); } else if sp.closed && sp.anchors.len() < 3 { sp.closed = false; } as_path(&mut it.shape); + // The deleted point leaves the selection; the selected points after it (or the subpaths + // after a removed one) move down an index. + sel.anchors.retain(|a| !(a.0 == id && a.1 == si && (a.2 == ai || removed_subpath))); + for a in sel.anchors.iter_mut().filter(|a| a.0 == id) { + if removed_subpath && a.1 > si { + a.1 -= 1; + } else if !removed_subpath && a.1 == si && a.2 > ai { + a.2 -= 1; + } + } if it.path.subpaths.is_empty() { d.remove_item(id)?; sel.items.retain(|i| *i != id); + sel.anchors.retain(|a| a.0 != id); return Ok(json!({"deleted": true})); } Ok(json!({"deleted": false})) @@ -426,6 +541,27 @@ mod tests { } /// Join Path closes one open path, and joins two open paths at their nearest ends. + /// `path.moveAnchors` points may each carry their own movement (Direct Selection sends each + /// point's in its own spread); without one a point takes the shared `dx`, `dy`. + #[test] + fn move_anchors_takes_a_movement_per_point() { + let mut s = crate::Session::new(); + s.execute("file.new", &serde_json::json!({})).unwrap(); + let id = s.execute("frame.create", &serde_json::json!({"rect": [100, 100, 200, 200]})).unwrap()["id"].as_u64().unwrap(); + let at = |s: &crate::Session, i: usize| { + let d = &s.doc().unwrap().doc; + let it = d.item(designcraft_doc::ItemId(id)).unwrap(); + it.xf * it.path.subpaths[0].anchors[i].p + }; + let (a0, a1) = (at(&s, 0), at(&s, 1)); + s.execute("path.moveAnchors", &serde_json::json!({"points": [[id, 0, 0, 5, 0], [id, 0, 1]], "dx": 0, "dy": 7})).unwrap(); + assert_eq!(at(&s, 0) - a0, designcraft_geom::Vec2::new(5.0, 0.0), "its own"); + assert_eq!(at(&s, 1) - a1, designcraft_geom::Vec2::new(0.0, 7.0), "the shared one"); + for bad in [serde_json::json!([[id, 0, 0, "x", 1]]), serde_json::json!([[id, 0, 0, 5]])] { + assert!(s.execute("path.moveAnchors", &serde_json::json!({"points": bad})).is_err(), "{bad}"); + } + } + #[test] fn join_path_closes_one_path_and_joins_two() { let mut s = Session::new(); @@ -454,6 +590,63 @@ mod tests { } /// Convert Point turns the selected points (or a whole path's) plain, corner, smooth or symmetrical. + /// Delete Point(s) removes the selected points of several paths in one step; a triangle left + /// with two points opens, and Undo brings every point back. + #[test] + fn delete_points_removes_the_selected_points_of_several_paths() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let a = s.execute("frame.create", &json!({"rect": [72, 72, 172, 172]})).unwrap()["id"].as_u64().unwrap(); + let b = s.execute("frame.create", &json!({"rect": [200, 72, 300, 172], "shape": "polygon", "sides": 3})).unwrap()["id"].as_u64().unwrap(); + s.execute("selection.set", &json!({"anchors": [[a, 0, 0], [a, 0, 2], [b, 0, 1]]})).unwrap(); + let r = s.execute("path.deletePoints", &json!({})).unwrap(); + assert_eq!(r["deleted"], 3); + let d = &s.doc().unwrap().doc; + let pa = &d.item(ItemId(a)).unwrap().path.subpaths[0]; + assert_eq!(pa.anchors.len(), 2, "two of the square's four points are left"); + assert!(!pa.closed, "two points can't stay closed"); + assert_eq!(d.item(ItemId(b)).unwrap().path.subpaths[0].anchors.len(), 2); + assert!(s.doc().unwrap().selection.anchors.is_empty()); + s.execute("edit.undo", &json!({})).unwrap(); + let d = &s.doc().unwrap().doc; + assert_eq!(d.item(ItemId(a)).unwrap().path.subpaths[0].anchors.len(), 4, "one undo step"); + assert_eq!(d.item(ItemId(b)).unwrap().path.subpaths[0].anchors.len(), 3); + // A line's two points: the line goes. + let l = s.execute("path.create", &json!({"anchors": [{"p": [72, 300]}, {"p": [172, 300]}]})).unwrap()["id"].as_u64().unwrap(); + let r = s.execute("path.deletePoints", &json!({"points": [[l, 0, 0]]})).unwrap(); + assert_eq!(r["removed"], json!([l])); + assert!(s.doc().unwrap().doc.item(ItemId(l)).is_none()); + assert!(s.execute("path.deletePoints", &json!({"points": []})).is_err()); + // Named points need no selected object. + s.execute("selection.set", &json!({"ids": []})).unwrap(); + assert!(s.doc().unwrap().selection.items.is_empty()); + let r = s.execute("path.deletePoints", &json!({"points": [[b, 0, 0]]})).unwrap(); + assert_eq!(r["deleted"], 1); + // Edit › Clear with points selected deletes the points, not their paths. + s.execute("selection.set", &json!({"anchors": [[a, 0, 0]]})).unwrap(); + s.execute("edit.clear", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc.item(ItemId(a)).unwrap().path.subpaths[0].anchors.len(), 3, "one point gone, the frame stays"); + // Cut copies whole objects, so it removes whole objects. + s.execute("selection.set", &json!({"anchors": [[a, 0, 0]]})).unwrap(); + s.execute("edit.cut", &json!({})).unwrap(); + assert!(s.doc().unwrap().doc.item(ItemId(a)).is_none(), "the cut object is gone"); + } + + /// Shift-adding an object to a point selection drops the points, so Clear deletes the objects. + #[test] + fn clear_after_adding_an_object_to_a_point_selection_deletes_objects() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let a = s.execute("frame.create", &json!({"rect": [72, 72, 172, 172]})).unwrap()["id"].as_u64().unwrap(); + let b = s.execute("frame.create", &json!({"rect": [200, 72, 300, 172]})).unwrap()["id"].as_u64().unwrap(); + s.execute("selection.set", &json!({"anchors": [[a, 0, 0]]})).unwrap(); + s.execute("selection.set", &json!({"ids": [b], "add": true})).unwrap(); + assert!(s.doc().unwrap().selection.anchors.is_empty()); + s.execute("edit.clear", &json!({})).unwrap(); + assert!(s.doc().unwrap().doc.item(ItemId(a)).is_none()); + assert!(s.doc().unwrap().doc.item(ItemId(b)).is_none()); + } + #[test] fn convert_point_kinds() { let mut s = Session::new(); @@ -486,16 +679,70 @@ mod tests { let pts: Vec = (0..=20).map(|i| json!({"p": [100.0 + i as f64 * 20.0, if i % 2 == 0 { 300.0 } else { 306.0 }]})).collect(); let id = s.execute("path.create", &json!({"anchors": pts})).unwrap()["id"].as_u64().unwrap(); let n = s.doc().unwrap().doc.item(ItemId(id)).unwrap().path.anchor_count(); + s.execute("selection.set", &json!({"anchors": [[id, 0, 20]]})).unwrap(); let drag: Vec = (0..=12).map(|i| json!([150.0 + i as f64 * 20.0, 303.0])).collect(); s.execute("path.smooth", &json!({"id": id, "points": drag})).unwrap(); let after = s.doc().unwrap().doc.item(ItemId(id)).unwrap().path.anchor_count(); assert!(after < n, "{after} < {n}"); + assert!(s.doc().unwrap().selection.anchors.is_empty(), "stored point indices are stale after the path is rebuilt"); let drag: Vec = (0..=5).map(|i| json!([200.0 + i as f64 * 20.0, 303.0])).collect(); let r = s.execute("path.erase", &json!({"id": id, "points": drag})).unwrap(); assert_eq!(r["subpaths"], 2, "a gap in the middle"); assert!(s.execute("path.erase", &json!({"id": id, "points": [[100, 600]]})).is_err()); } + /// A touch only thinning would skip still counts: a long drag is not refused as missing the path. + #[test] + fn a_touch_the_thinning_skips_still_counts() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let pts: Vec = (0..=20).map(|i| json!({"p": [100.0 + i as f64 * 20.0, 300.0]})).collect(); + let id = s.execute("path.create", &json!({"anchors": pts})).unwrap()["id"].as_u64().unwrap(); + // 6,000 distinct samples far from the path but one, at an index thinning to 4,096 drops. + let drag: Vec = (0..6_000).map(|i| if i == 3 { json!([200.0, 300.0]) } else { json!([200.0 + f64::from(i) * 0.01, 900.0]) }).collect(); + assert!(s.execute("path.erase", &json!({"id": id, "points": drag})).is_ok()); + } + + /// A drag of many repeated and many distinct samples is thinned and still erases where it went. + #[test] + fn a_drag_with_many_samples_still_erases() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let pts: Vec = (0..=20).map(|i| json!({"p": [100.0 + i as f64 * 20.0, if i % 2 == 0 { 300.0 } else { 306.0 }]})).collect(); + let id = s.execute("path.create", &json!({"anchors": pts})).unwrap()["id"].as_u64().unwrap(); + // 60,000 samples along the middle of the path, each point repeated. + let drag: Vec = (0..60_000).map(|i| json!([200.0 + f64::from(i % 6000) * 0.025, 303.0])).collect(); + let r = s.execute("path.erase", &json!({"id": id, "points": drag})).unwrap(); + assert_eq!(r["subpaths"], 2, "a gap in the middle"); + } + + /// The Direct Selection's selected points stay the same points when the path changes under + /// them: a point added before them, one of them deleted, the path reversed. + #[test] + fn selected_anchors_follow_added_deleted_and_reversed_points() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let id = s.execute("frame.create", &json!({"rect": [100, 100, 200, 200], "content": "unassigned"})).unwrap()["id"].as_u64().unwrap(); + let point = |s: &Session, a: (usize, usize)| s.doc().unwrap().doc.item(ItemId(id)).unwrap().path.subpaths[a.0].anchors[a.1].p; + s.execute("selection.set", &json!({"anchors": [[id, 0, 2], [id, 0, 3]]})).unwrap(); + let picked = |s: &Session| s.doc().unwrap().selection.anchors.iter().map(|a| (a.1, a.2)).collect::>(); + let before: Vec<_> = picked(&s).into_iter().map(|a| point(&s, a)).collect(); + // A point added on the first side, before both. + let first = point(&s, (0, 0)); + let second = point(&s, (0, 1)); + let mid = [(first.x + second.x) / 2.0, (first.y + second.y) / 2.0]; + s.execute("path.addAnchor", &json!({"id": id, "at": mid})).unwrap(); + assert_eq!(picked(&s).into_iter().map(|a| point(&s, a)).collect::>(), before, "after an added point"); + // One of them deleted: the other stays selected, the same point. + let (si, ai) = picked(&s)[0]; + s.execute("path.deleteAnchor", &json!({"id": id, "subpath": si, "anchor": ai})).unwrap(); + assert_eq!(picked(&s).len(), 1); + assert_eq!(point(&s, picked(&s)[0]), before[1], "after a deleted point"); + // Reversed: still the same point. + s.execute("path.reverse", &json!({"ids": [id]})).unwrap(); + assert_eq!(point(&s, picked(&s)[0]), before[1], "after reversing"); + } + #[test] fn add_convert_delete_anchor_points() { let mut s = Session::new(); diff --git a/crates/engine/src/cmd/book.rs b/crates/engine/src/cmd/book.rs index 18f554d57..c24aeae1c 100644 --- a/crates/engine/src/cmd/book.rs +++ b/crates/engine/src/cmd/book.rs @@ -1,6 +1,8 @@ //! Books (File › New / Open Book): an ordered list of documents with continuous page numbers, //! styles synchronised from a style source, and one PDF for the whole book. Saved as `.dcbook`. +use std::collections::{HashMap, HashSet}; + use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; @@ -57,7 +59,7 @@ fn load(path: &str) -> Result { let _ = path; vec![] }; - if path.to_lowercase().ends_with(".idml") { + if craft_file_formats::detect(path, &bytes) == Some(craft_file_formats::Format::Idml) { return super::interchange::import_idml_confined(&bytes, Some(std::path::Path::new(path))) .map_err(|e| EngineError::Other(format!("{path}: {e}"))); } @@ -130,7 +132,11 @@ impl ChapterBatch { fn writable_chapter(s: &Session, path: &str, command: &'static str) -> Result<()> { use std::path::Path; - if Path::new(path).extension().and_then(std::ffi::OsStr::to_str).is_some_and(|ext| ext.eq_ignore_ascii_case("idml")) { + if Path::new(path) + .extension() + .and_then(std::ffi::OsStr::to_str) + .is_some_and(|ext| craft_file_formats::from_extension(ext) == Some(craft_file_formats::Format::Idml)) + { return Err(bad(command, format!("cannot change imported IDML chapter {path}; convert it to a native DesignCraft document first"))); } let target = crate::io::canonicalize(path).map_err(|e| EngineError::Other(format!("{path}: {e}")))?; @@ -177,6 +183,15 @@ fn paginate(s: &Session) -> Result { Ok(json!({"pages": next - 1, "chapters": chapters})) } +/// `list` with only the last entry of each name, in the order of those last entries. +#[cfg(not(target_arch = "wasm32"))] +fn keep_last(list: &[T], name: impl Fn(&T) -> &str) -> Vec<&T> { + let mut seen = HashSet::new(); + let mut out: Vec<&T> = list.iter().rev().filter(|x| seen.insert(name(x))).collect(); + out.reverse(); + out +} + #[cfg(not(target_arch = "wasm32"))] fn sync_styles(s: &Session) -> Result { let b = s.book.as_ref().ok_or_else(no_book)?; @@ -187,6 +202,11 @@ fn sync_styles(s: &Session) -> Result { let styles = src.styles.clone(); let swatches = src.swatches.clone(); drop(src); + // A name the source defines twice keeps its last definition, at its last position. + let paragraph = keep_last(&styles.paragraph, |x| x.name.as_str()); + let character = keep_last(&styles.character, |x| x.name.as_str()); + let (paragraph_names, character_names): (HashSet<&str>, HashSet<&str>) = + (paragraph.iter().map(|x| x.name.as_str()).collect(), character.iter().map(|x| x.name.as_str()).collect()); let mut n = 0; for (i, path) in paths.iter().enumerate() { if i == b.style_source { @@ -195,21 +215,27 @@ fn sync_styles(s: &Session) -> Result { writable_chapter(s, path, "book.syncStyles")?; let mut d = load(path)?; { + // The source's styles replace the chapter's of the same names and go last, in the + // source's order (one pass over each list, not one per style). let st = d.styles_mut(); - for ps in &styles.paragraph { - st.paragraph.retain(|x| x.name != ps.name); - st.paragraph.push(ps.clone()); - } - for cs in &styles.character { - st.character.retain(|x| x.name != cs.name); - st.character.push(cs.clone()); - } + st.paragraph.retain(|x| !paragraph_names.contains(x.name.as_str())); + st.paragraph.extend(paragraph.iter().map(|x| (*x).clone())); + st.character.retain(|x| !character_names.contains(x.name.as_str())); + st.character.extend(character.iter().map(|x| (*x).clone())); + } + // First index per name, as Document::swatch resolves colours. + let mut at: HashMap = HashMap::new(); + for (i, w) in d.swatches.iter().enumerate() { + at.entry(w.name.clone()).or_insert(i); } for sw in &swatches { - match d.swatches.iter_mut().find(|w| w.name == sw.name) { + match at.get(&sw.name).and_then(|i| d.swatches.get_mut(*i)) { Some(w) if !w.locked => *w = sw.clone(), Some(_) => {} - None => d.swatches.push(sw.clone()), + None => { + at.insert(sw.name.clone(), d.swatches.len()); + d.swatches.push(sw.clone()); + } } } batch.stage(path, &d)?; @@ -246,6 +272,7 @@ fn start_at(d: &mut designcraft_doc::Document, n: u32) { prefix: String::new(), marker: String::new(), include_prefix: false, + layout: None, }, ); } @@ -284,7 +311,12 @@ pub fn specs() -> Vec { load(&path)?; let mut b = s.book.as_ref().ok_or_else(no_book)?.clone(); let at = p.get("at").and_then(Value::as_u64).map_or(b.documents.len(), |i| (i as usize).min(b.documents.len())); + // Keep a valid existing source attached to its chapter when inserting before it. + let shift_source = b.style_source < b.documents.len() && at <= b.style_source; b.documents.insert(at, path); + if shift_source { + b.style_source += 1; + } save(&b)?; s.book = Some(b); ok() @@ -296,6 +328,9 @@ pub fn specs() -> Vec { return Err(bad("book.remove", format!("no document {i}"))); } b.documents.remove(i); + if i < b.style_source { + b.style_source -= 1; + } if b.style_source >= b.documents.len() { b.style_source = 0; } @@ -340,8 +375,9 @@ pub fn specs() -> Vec { let _fonts = super::file::load_document_fonts(&mut d, path).0; let cache = designcraft_compose::Cache::new(); let r = designcraft_pdf::export_pdf_with_report(&super::interchange::with_pdf_boxes(&d), &cache, &designcraft_pdf::PdfOptions::default()).map_err(|e| EngineError::Other(e.to_string()))?; - let n = designcraft_render::pdf_page_count(&r.bytes).unwrap_or(0); - let sizes: Vec<(f32, f32)> = (0..n).filter_map(|i| designcraft_render::pdf_page_size(&r.bytes, i)).map(|(w, h)| (w as f32, h as f32)).collect(); + // Every page's size from one opening of the chapter's PDF (not one per page). + let sizes: Vec<(f32, f32)> = + designcraft_render::pdf_page_sizes(&r.bytes).unwrap_or_default().into_iter().map(|(w, h)| (w as f32, h as f32)).collect(); parts.push((r.bytes, sizes)); } let pages: usize = parts.iter().map(|p| p.1.len()).sum(); @@ -429,4 +465,84 @@ mod tests { assert_eq!(t.execute("book.open", &json!({"path": p("book.dcbook")})).unwrap()["documents"], 2); std::fs::remove_dir_all(&dir).ok(); } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn a_source_style_defined_twice_keeps_its_last_definition() { + let list = [("a", 1), ("b", 2), ("a", 3), ("c", 4)]; + let kept: Vec<_> = super::keep_last(&list, |x| x.0).into_iter().copied().collect(); + // As the one-style-at-a-time loop left them: each name once, at its last position. + assert_eq!(kept, [("b", 2), ("a", 3), ("c", 4)]); + } + + #[cfg(not(target_arch = "wasm32"))] + fn open_book_fixture(path: &std::path::Path, documents: &[&str], style_source: usize) -> Session { + let book = super::Book { + path: path.to_str().unwrap().to_string(), + documents: documents.iter().map(|path| path.to_string()).collect(), + style_source, + }; + super::save(&book).unwrap(); + let mut s = Session::new(); + s.execute("book.open", &json!({"path": book.path})).unwrap(); + s + } + + #[cfg(not(target_arch = "wasm32"))] + fn assert_book_style_source(s: &Session, path: &std::path::Path, index: usize, source: Option<&str>) { + let mut reopened = Session::new(); + reopened.execute("book.open", &json!({"path": path.to_str().unwrap()})).unwrap(); + for book in [s.book.as_ref().unwrap(), reopened.book.as_ref().unwrap()] { + assert_eq!(book.style_source, index, "{book:?}"); + assert_eq!(book.documents.get(index).map(String::as_str), source, "{book:?}"); + } + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn adding_a_chapter_keeps_the_existing_style_source() { + let dir = tempfile::TempDir::new().unwrap(); + let path = dir.path().join("book.dcbook"); + let inserted = dir.path().join("inserted.designcraft"); + let inserted = inserted.to_str().unwrap(); + let doc = designcraft_doc::Document::new(&Default::default()); + std::fs::write(inserted, designcraft_format::save(&doc).unwrap()).unwrap(); + let chapters = ["a.designcraft", "b.designcraft", "c.designcraft"]; + for (documents, source, at, expected_index, expected_source) in [ + (&chapters[..], 1, 0, 2, Some("b.designcraft")), + (&chapters[..], 1, 1, 2, Some("b.designcraft")), + (&chapters[..], 1, 2, 1, Some("b.designcraft")), + (&chapters[..], 1, 3, 1, Some("b.designcraft")), + (&[][..], 0, 0, 0, Some(inserted)), + (&chapters[..], 3, 0, 3, Some("c.designcraft")), + (&chapters[..], usize::MAX, 0, usize::MAX, None), + ] { + let mut s = open_book_fixture(&path, documents, source); + s.execute("book.add", &json!({"path": inserted, "at": at})).unwrap(); + assert_book_style_source(&s, &path, expected_index, expected_source); + } + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn removing_a_chapter_keeps_a_surviving_style_source() { + let dir = tempfile::TempDir::new().unwrap(); + let path = dir.path().join("book.dcbook"); + let chapters = ["a.designcraft", "b.designcraft", "c.designcraft"]; + for (documents, source, removed, expected_index, expected_source) in [ + (&chapters[..], 1, 0, 0, Some("b.designcraft")), + (&chapters[..], 2, 0, 1, Some("c.designcraft")), + (&chapters[..], 1, 2, 1, Some("b.designcraft")), + (&chapters[..], 0, 2, 0, Some("a.designcraft")), + (&chapters[..], 1, 1, 1, Some("c.designcraft")), + (&chapters[..], 2, 2, 0, Some("a.designcraft")), + (&chapters[..1], 0, 0, 0, None), + (&chapters[..], 3, 0, 0, Some("b.designcraft")), + (&chapters[..], usize::MAX, 0, 0, Some("b.designcraft")), + ] { + let mut s = open_book_fixture(&path, documents, source); + s.execute("book.remove", &json!({"index": removed})).unwrap(); + assert_book_style_source(&s, &path, expected_index, expected_source); + } + } } diff --git a/crates/engine/src/cmd/buttons.rs b/crates/engine/src/cmd/buttons.rs index 5a644503d..9c5174440 100644 --- a/crates/engine/src/cmd/buttons.rs +++ b/crates/engine/src/cmd/buttons.rs @@ -18,7 +18,13 @@ fn parse(p: &Value) -> Result> { "lastPage" => ButtonAction::GoToLastPage, "nextPage" => ButtonAction::GoToNextPage, "previousPage" => ButtonAction::GoToPreviousPage, - "url" => ButtonAction::GoToUrl { url: p.get("url").and_then(Value::as_str).ok_or_else(|| bad("button.set", "`url` required"))?.to_string() }, + "url" => { + let url = p.get("url").and_then(Value::as_str).ok_or_else(|| bad("button.set", "`url` required"))?; + if !designcraft_doc::is_safe_link_url(url) { + return Err(bad("button.set", "`url` must start with http://, https:// or mailto:")); + } + ButtonAction::GoToUrl { url: url.to_string() } + } o => return Err(bad("button.set", format!("unknown action `{o}`"))), })) } @@ -179,4 +185,16 @@ mod tests { assert_eq!(designcraft_render::pdf_page_count(&bytes), Some(3), "the update still reads"); assert!(s.execute("button.list", &json!({})).unwrap().as_array().unwrap().is_empty()); } + + #[test] + fn buttons_refuse_non_web_schemes() { + let mut s = Session::new(); + s.execute("file.new", &json!({"pages": 1})).unwrap(); + let id = s.execute("frame.create", &json!({"rect": [72, 72, 200, 120]})).unwrap()["id"].clone(); + for bad in ["javascript:alert(1)", "file:///etc/passwd", "\\\\attacker\\share"] { + let e = s.execute("button.set", &json!({"ids": [id.clone()], "action": "url", "url": bad})).expect_err("refused").to_string(); + assert!(e.contains("http://"), "{bad}: {e}"); + } + s.execute("button.set", &json!({"ids": [id], "action": "url", "url": "https://example.com"})).unwrap(); + } } diff --git a/crates/engine/src/cmd/captions.rs b/crates/engine/src/cmd/captions.rs index d35dc3e60..b00dac1be 100644 --- a/crates/engine/src/cmd/captions.rs +++ b/crates/engine/src/cmd/captions.rs @@ -112,6 +112,19 @@ fn caption(s: &mut Session, p: &Value) -> Result { }) } +/// Whether any item on the document spreads, inside groups included, is a live caption: the +/// items [`refresh_live`] visits. +pub(crate) fn has_live(d: &Document) -> bool { + let mut found = false; + for it in d.spreads.iter().flat_map(|sp| &sp.items) { + it.walk(&mut |i| found |= i.live_caption.is_some()); + if found { + return true; + } + } + false +} + /// Bring live captions up to date with their source objects (the text frame's story is /// replaced when its text changed; a caption whose source is gone keeps its last text). pub(crate) fn refresh_live(d: &mut Document) -> bool { @@ -131,10 +144,22 @@ pub(crate) fn refresh_live(d: &mut Document) -> bool { let len = st.len(); st.replace(0..len, &text); } + d.prune_story_text_ranges(sid); } changed } +/// Keep a text selection inside its story after `refresh_live` replaced the story's text. +pub(crate) fn clamp_text_selection(d: &Document, sel: &mut Selection) { + if let Some(ts) = sel.text.as_mut() + && ts.cell.is_none() + && let Some(st) = d.story(ts.story) + { + ts.anchor = designcraft_doc::floor_char_boundary(&st.text, ts.anchor); + ts.focus = designcraft_doc::floor_char_boundary(&st.text, ts.focus); + } +} + #[cfg(test)] mod tests { use serde_json::json; @@ -177,4 +202,107 @@ mod tests { s.execute("edit.undo", &json!({})).unwrap(); assert_eq!(text(&s), "Photo: First", "one undo step for both"); } + + #[test] + fn live_caption_follows_a_committed_gesture() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let a = s.execute("frame.create", &json!({"rect": [72, 72, 272, 172]})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.altText", &json!({"text": "First", "ids": [a]})).unwrap(); + let r = s.execute("object.caption", &json!({"ids": [a], "text": "Photo: {altText}", "live": true})).unwrap(); + let cid = designcraft_doc::ItemId(r["ids"][0].as_u64().unwrap()); + let text = |s: &Session| { + let d = &s.doc().unwrap().doc; + d.stories[&d.item(cid).unwrap().text_frame().unwrap().story].text.clone() + }; + s.begin_interaction("Alt Text").unwrap(); + s.preview("object.altText", json!({"text": "Second", "ids": [a]})).unwrap(); + let revision = s.doc().unwrap().revision; + s.commit_interaction().unwrap(); + assert_eq!(text(&s), "Photo: Second", "updated when the gesture commits"); + assert_ne!(s.doc().unwrap().revision, revision, "caches keyed by the revision draw the new caption"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(text(&s), "Photo: First", "one undo step for both"); + } + + #[test] + fn auto_sized_live_caption_fits_a_committed_gesture() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let a = s.execute("frame.create", &json!({"rect": [72, 72, 272, 172]})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.altText", &json!({"text": "First", "ids": [a]})).unwrap(); + let r = s.execute("object.caption", &json!({"ids": [a], "text": "Photo: {altText}", "live": true})).unwrap(); + let cid = r["ids"][0].as_u64().unwrap(); + s.execute("object.textFrameOptions", &json!({"ids": [cid], "autoSize": "heightOnly"})).unwrap(); + let height = |s: &Session| s.doc().unwrap().doc.item(designcraft_doc::ItemId(cid)).unwrap().bounds().height(); + let short = height(&s); + let long = "A harbour at dawn, with the fishing boats coming in one after another past the lighthouse and the long stone pier"; + s.begin_interaction("Alt Text").unwrap(); + s.preview("object.altText", json!({"text": long, "ids": [a]})).unwrap(); + s.commit_interaction().unwrap(); + assert!(height(&s) > short + 5.0, "the caption frame grows with its text: {short} -> {}", height(&s)); + } + + #[test] + fn grouped_live_caption_follows_its_source() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let a = s.execute("frame.create", &json!({"rect": [72, 72, 272, 172]})).unwrap()["id"].as_u64().unwrap(); + let b = s.execute("frame.create", &json!({"rect": [300, 72, 400, 172]})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.altText", &json!({"text": "First", "ids": [a]})).unwrap(); + let r = s.execute("object.caption", &json!({"ids": [a], "text": "Photo: {altText}", "live": true})).unwrap(); + let cid = designcraft_doc::ItemId(r["ids"][0].as_u64().unwrap()); + // The only live caption sits inside a group, not at the top of the spread. + s.execute("object.group", &json!({"ids": [cid.0, b]})).unwrap(); + let text = |s: &Session| { + let d = &s.doc().unwrap().doc; + d.stories[&d.item(cid).unwrap().text_frame().unwrap().story].text.clone() + }; + s.execute("object.altText", &json!({"text": "Second", "ids": [a]})).unwrap(); + assert_eq!(text(&s), "Photo: Second", "updated by a command"); + s.begin_interaction("Alt Text").unwrap(); + s.preview("object.altText", json!({"text": "Third", "ids": [a]})).unwrap(); + s.commit_interaction().unwrap(); + assert_eq!(text(&s), "Photo: Third", "updated when the gesture commits"); + } + + /// A session with a live caption reading "Photo: First" and the caret at its end. + fn caret_at_end_of_live_caption() -> (Session, designcraft_doc::StoryId) { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let a = s.execute("frame.create", &json!({"rect": [72, 72, 272, 172]})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.altText", &json!({"text": "First", "ids": [a]})).unwrap(); + let r = s.execute("object.caption", &json!({"ids": [a], "text": "Photo: {altText}", "live": true})).unwrap(); + let cid = designcraft_doc::ItemId(r["ids"][0].as_u64().unwrap()); + let sid = s.doc().unwrap().doc.item(cid).unwrap().text_frame().unwrap().story; + let len = "Photo: First".len(); + s.execute("text.select", &json!({"story": sid.0, "anchor": len, "focus": len})).unwrap(); + (s, sid) + } + + fn assert_caret_inside(s: &Session, sid: designcraft_doc::StoryId) { + let st = s.doc().unwrap(); + let len = st.doc.stories[&sid].text.len(); + let ts = st.selection.text.unwrap(); + assert!(ts.anchor <= len && ts.focus <= len, "caret {}..{} past the end of {len} bytes", ts.anchor, ts.focus); + assert!(s.ime_text_context().is_some(), "the caret still describes its text"); + } + + #[test] + fn caret_stays_inside_a_live_caption_that_discards_typing() { + let (mut s, sid) = caret_at_end_of_live_caption(); + s.execute("text.insert", &json!({"text": " and more"})).unwrap(); + assert_eq!(s.doc().unwrap().doc.stories[&sid].text, "Photo: First"); + assert_caret_inside(&s, sid); + } + + #[test] + fn caret_stays_inside_a_live_caption_after_a_committed_gesture() { + let (mut s, sid) = caret_at_end_of_live_caption(); + s.begin_interaction("Typing").unwrap(); + s.preview("text.insert", json!({"text": " and more"})).unwrap(); + s.commit_interaction().unwrap(); + assert_eq!(s.doc().unwrap().doc.stories[&sid].text, "Photo: First"); + assert_caret_inside(&s, sid); + } } diff --git a/crates/engine/src/cmd/changes.rs b/crates/engine/src/cmd/changes.rs index e471c4b6e..1ed5b8716 100644 --- a/crates/engine/src/cmd/changes.rs +++ b/crates/engine/src/cmd/changes.rs @@ -1,16 +1,16 @@ //! Type › Track Changes: record edits as inserted / deleted text; accept or reject them. -use designcraft_doc::{ChangeMark, Story, StoryId}; +use designcraft_doc::{ChangeMark, Document, Selection, Story, StoryId}; use serde_json::{Value, json}; use super::{CommandSpec, cmd, has_doc}; use crate::{Result, Session}; -/// Mark `r` deleted (text this session inserted while tracking is simply removed). Returns where -/// the text after the range now starts. -pub(crate) fn mark_deleted(st: &mut Story, r: std::ops::Range) -> usize { +/// Returns the new start of text after `r` and the list of physically removed byte ranges (in original offsets, last first) +/// so callers can reconcile document-level text ranges. +pub(crate) fn mark_deleted_reporting(st: &mut Story, r: std::ops::Range) -> (usize, Vec>) { if r.is_empty() { - return r.start; + return (r.start, Vec::new()); } // Inserted pieces inside the range go away; the rest is marked deleted. let mut ins: Vec> = st @@ -20,6 +20,7 @@ pub(crate) fn mark_deleted(st: &mut Story, r: std::ops::Range) -> usize { .collect(); let mut end = r.end; ins.sort_by_key(|x| std::cmp::Reverse(x.start)); + let removed = ins.clone(); for x in ins { st.delete(x.clone()); end -= x.len(); @@ -27,7 +28,14 @@ pub(crate) fn mark_deleted(st: &mut Story, r: std::ops::Range) -> usize { if end > r.start { st.format_chars(r.start..end, |f| f.over.change = Some(ChangeMark::Deleted)); } - end + (end, removed) +} + +/// Mark `r` deleted (text this session inserted while tracking is simply removed). Returns where +/// the text after the range now starts. +#[cfg(test)] +pub(crate) fn mark_deleted(st: &mut Story, r: std::ops::Range) -> usize { + mark_deleted_reporting(st, r).0 } /// Ranges of `mark` in `st`, last first. @@ -37,20 +45,32 @@ fn ranges(st: &Story, mark: ChangeMark) -> Vec> { v } -/// Accept (or reject) every change in `st`. -fn resolve(st: &mut Story, accept: bool) -> usize { +/// Accept (or reject) every change in `sid`. +fn resolve(d: &mut Document, sel: &mut Selection, sid: StoryId, accept: bool) -> usize { let (remove, keep) = if accept { (ChangeMark::Deleted, ChangeMark::Inserted) } else { (ChangeMark::Inserted, ChangeMark::Deleted) }; - let removed = ranges(st, remove); - let n = removed.len() + ranges(st, keep).len(); - for r in removed { - st.delete(r); - } - let len = st.len(); - st.format_chars(0..len, |f| { - if f.over.change.is_some() { - f.over.change = None; + let (removed, keep_count) = { + let st = match d.story(sid) { + Some(st) => st, + None => return 0, + }; + (ranges(st, remove), ranges(st, keep).len()) + }; + let n = removed.len() + keep_count; + if let Some(st) = d.story_mut(sid) { + for r in &removed { + st.delete(r.clone()); } - }); + let len = st.len(); + st.format_chars(0..len, |f| { + if f.over.change.is_some() { + f.over.change = None; + } + }); + } + for r in removed { + super::notes::follow_delete(sel, sid, r.clone()); + d.adjust_text_ranges(sid, r, 0); + } n } @@ -60,20 +80,29 @@ fn one(s: &mut Session, p: &Value, accept: bool) -> Result { let sid = p.get("story").and_then(Value::as_u64).map(StoryId).ok_or_else(|| super::bad(id, "`story` required"))?; let start = p.get("start").and_then(Value::as_u64).ok_or_else(|| super::bad(id, "`start` required"))? as usize; s.edit(|d, sel| { - let st = d.story_mut(sid).ok_or_else(|| super::bad(id, "no such story"))?; - let (r, mark) = st - .runs() - .find(|(r, f)| matches!(f.over.change, Some(ChangeMark::Inserted | ChangeMark::Deleted)) && r.start <= start && start < r.end) - .map(|(r, f)| (r, f.over.change.unwrap_or_default())) - .ok_or_else(|| super::bad(id, "no change there"))?; + let (r, mark) = { + let st = d.story(sid).ok_or_else(|| super::bad(id, "no such story"))?; + st.runs() + .find(|(r, f)| matches!(f.over.change, Some(ChangeMark::Inserted | ChangeMark::Deleted)) && r.start <= start && start < r.end) + .map(|(r, f)| (r, f.over.change.unwrap_or_default())) + .ok_or_else(|| super::bad(id, "no change there"))? + }; // Accepting a deletion or rejecting an insertion removes the text; otherwise it stays, unmarked. - if (mark == ChangeMark::Deleted) == accept { - st.delete(r.clone()); - } else { - st.format_chars(r.clone(), |f| f.over.change = None); + let delete = (mark == ChangeMark::Deleted) == accept; + if let Some(st) = d.story_mut(sid) { + if delete { + st.delete(r.clone()); + } else { + st.format_chars(r.clone(), |f| f.over.change = None); + } + } + if delete { + super::notes::follow_delete(sel, sid, r.clone()); + d.adjust_text_ranges(sid, r.clone(), 0); } if let Some(t) = &mut sel.text && t.story == sid + && t.cell.is_none() { let len = d.story(sid).map_or(0, |x| x.len()); t.anchor = t.anchor.min(len); @@ -137,12 +166,11 @@ fn all(s: &mut Session, p: &Value, accept: bool) -> Result { let ids: Vec = d.stories.keys().copied().filter(|id| only.is_none_or(|o| o == *id)).collect(); let mut n = 0; for id in ids { - if let Some(st) = d.story_mut(id) { - n += resolve(st, accept); - } + n += resolve(d, sel, id, accept); } - // The caret may now be past the end. + // A body-text edit must not clamp a cell or note caret against the body length. if let Some(t) = &mut sel.text + && t.cell.is_none() && let Some(st) = d.story(t.story) { t.anchor = t.anchor.min(st.len()); @@ -196,4 +224,91 @@ mod tests { assert_eq!(text(&s), "The dog sat"); assert!(s.execute("changes.list", &json!({})).unwrap().as_array().unwrap().is_empty()); } + + /// Removing a tracked run follows the selected text by UTF-8 byte offsets, including undo. + #[test] + fn resolving_a_removed_change_follows_the_text_selection() { + use designcraft_doc::ChangeMark; + + for (command, mark) in [ + ("changes.accept", ChangeMark::Deleted), + ("changes.reject", ChangeMark::Inserted), + ("changes.acceptAll", ChangeMark::Deleted), + ("changes.rejectAll", ChangeMark::Inserted), + ] { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let sid = s.execute("frame.create", &json!({"rect": [72, 72, 400, 200], "content": "text", "text": "ab猫cdéfg"})).unwrap()["story"] + .as_u64() + .unwrap(); + s.edit(|d, _| { + d.story_mut(designcraft_doc::StoryId(sid)).unwrap().format_chars(2..5, |f| f.over.change = Some(mark)); + Ok(()) + }) + .unwrap(); + s.execute("text.select", &json!({"story": sid, "anchor": 9, "focus": 5})).unwrap(); + let params = if command.ends_with("All") { json!({"story": sid}) } else { json!({"story": sid, "start": 2}) }; + s.execute(command, ¶ms).unwrap(); + assert_eq!(s.doc().unwrap().doc.story(designcraft_doc::StoryId(sid)).unwrap().text, "abcdéfg", "{command}"); + let selected = s.doc().unwrap().selection.text.unwrap(); + assert_eq!((selected.anchor, selected.focus), (6, 2), "{command}"); + s.execute("edit.undo", &json!({})).unwrap(); + let selected = s.doc().unwrap().selection.text.unwrap(); + assert_eq!((selected.anchor, selected.focus), (9, 5), "undo {command}"); + s.execute("edit.redo", &json!({})).unwrap(); + let selected = s.doc().unwrap().selection.text.unwrap(); + assert_eq!((selected.anchor, selected.focus), (6, 2), "redo {command}"); + } + } + + /// All-change resolution removes disjoint runs from the end and maps each one once. + #[test] + fn resolving_all_changes_follows_multiple_removed_runs() { + use designcraft_doc::ChangeMark; + + for (command, mark) in [("changes.acceptAll", ChangeMark::Deleted), ("changes.rejectAll", ChangeMark::Inserted)] { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let sid = s.execute("frame.create", &json!({"rect": [72, 72, 400, 200], "content": "text", "text": "a猫bécδd"})).unwrap()["story"] + .as_u64() + .unwrap(); + s.edit(|d, _| { + let story = d.story_mut(designcraft_doc::StoryId(sid)).unwrap(); + story.format_chars(1..4, |f| f.over.change = Some(mark)); + story.format_chars(5..7, |f| f.over.change = Some(mark)); + Ok(()) + }) + .unwrap(); + s.execute("text.select", &json!({"story": sid, "anchor": 10, "focus": 4})).unwrap(); + s.execute(command, &json!({"story": sid})).unwrap(); + assert_eq!(s.doc().unwrap().doc.story(designcraft_doc::StoryId(sid)).unwrap().text, "abcδd", "{command}"); + let selected = s.doc().unwrap().selection.text.unwrap(); + assert_eq!((selected.anchor, selected.focus), (5, 1), "{command}"); + } + } + + /// A body-story change leaves the independent footnote insertion point alone. + #[test] + fn resolving_body_changes_keeps_a_footnote_caret() { + for command in ["changes.accept", "changes.acceptAll"] { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let sid = s.execute("frame.create", &json!({"rect": [72, 72, 400, 200], "content": "text", "text": "abcd"})).unwrap()["story"] + .as_u64() + .unwrap(); + s.execute("text.select", &json!({"story": sid, "anchor": 4, "focus": 4})).unwrap(); + s.execute("footnote.insert", &json!({"text": "Footnote text beyond body"})).unwrap(); + let before = s.doc().unwrap().selection.text.unwrap(); + s.edit(|d, _| { + d.story_mut(designcraft_doc::StoryId(sid)) + .unwrap() + .format_chars(0..1, |f| f.over.change = Some(designcraft_doc::ChangeMark::Deleted)); + Ok(()) + }) + .unwrap(); + let params = if command.ends_with("All") { json!({"story": sid}) } else { json!({"story": sid, "start": 0}) }; + s.execute(command, ¶ms).unwrap(); + assert_eq!(s.doc().unwrap().selection.text.unwrap(), before, "{command}"); + } + } } diff --git a/crates/engine/src/cmd/color_theme.rs b/crates/engine/src/cmd/color_theme.rs index c406c72da..eb84bbae1 100644 --- a/crates/engine/src/cmd/color_theme.rs +++ b/crates/engine/src/cmd/color_theme.rs @@ -37,11 +37,12 @@ fn extract(s: &mut Session, p: &Value) -> Result { }; let graphic = st.doc.item(id).and_then(|it| it.graphic()).ok_or_else(|| bad(ID, "select one placed raster image"))?; let asset = st.doc.assets.get(&graphic.asset).filter(|a| a.is_raster()).ok_or_else(|| bad(ID, "a raster image is required"))?; - let (width, height) = designcraft_images::pixel_size(&asset.data).ok_or_else(|| bad(ID, "cannot read image dimensions"))?; + let bytes = crate::cmd::asset_bytes(ID, asset)?; + let (width, height) = designcraft_images::pixel_size(&bytes).ok_or_else(|| bad(ID, "cannot read image dimensions"))?; if width == 0 || height == 0 || u64::from(width) * u64::from(height) > 16_000_000 { return Err(bad(ID, "the image must contain between 1 and 16 million pixels")); } - let img = designcraft_images::decode_rgba(&asset.data).ok_or_else(|| bad(ID, "cannot decode this image"))?; + let img = designcraft_images::decode_rgba(&bytes).ok_or_else(|| bad(ID, "cannot decode this image"))?; // A regular 128 × 128 grid bounds work and includes both axes even for very thin images. let (nx, ny) = (width.min(128), height.min(128)); let mut samples = Vec::with_capacity((nx * ny) as usize); diff --git a/crates/engine/src/cmd/datamerge.rs b/crates/engine/src/cmd/datamerge.rs index e96feb9fb..fe565d679 100644 --- a/crates/engine/src/cmd/datamerge.rs +++ b/crates/engine/src/cmd/datamerge.rs @@ -10,22 +10,21 @@ use std::path::{Path, PathBuf}; use std::sync::Arc; use designcraft_doc::{ - DataField, DataFieldKind, DataSource, Delimiter, Document, HyperlinkSource, ItemId, MergeOptions, Page, Placeholder, PlaceholderAnchor, - PlaceholderRole, Selection, SourceStatus, SpreadRef, StoryId, + DataField, DataFieldKind, DataSource, Delimiter, Document, ItemId, MergeOptions, Page, Placeholder, PlaceholderAnchor, PlaceholderRole, + Selection, SourceStatus, SpreadRef, StoryId, }; use designcraft_geom::{Rect, Vec2}; use serde_json::{Value, json}; use super::{CommandSpec, bad, cmd, has_doc, id_param, ok, str_param}; use crate::{DocState, Result, Session}; -use fill::{FillReport, Maps, MissingImage, Sources, copy_item, fill_row, identity_map}; -use parse::{ - Table, TileInput, extension, fingerprint_of, relative_between, select_records, status_of, table_from_bytes, table_from_grid, table_from_objects, - tile, -}; +use fill::{FillReport, ImageCache, Maps, MissingImage, Sources, copy_item, fill_row, identity_map}; +pub(crate) use parse::relative_between; +use parse::{Table, TileInput, select_records, status_of, table_from_bytes, table_from_grid, table_from_objects, tile}; #[cfg(not(target_arch = "wasm32"))] pub(crate) use parse::fingerprint_from; +pub(crate) use parse::fingerprint_of; pub(crate) fn fingerprint_from_path(path: &str) -> Option { fingerprint_of(Path::new(path)) @@ -60,7 +59,7 @@ pub fn specs() -> Vec { "Insert Field", [], None, - "{field, role?: text|image|qr|hyperlink, story?, at?, end?, item?} → {id}", + "{field, role?: text|image|qr|hyperlink, story?, at?, end?, item?} → {id}; an image field at a text insertion point merges as an inline image; with the insertion point in a table cell or a note → {cell: true, marker} (a typed marker, not an anchored placeholder; an image field there is an error unless role is text)", has_doc, placeholder_add ), @@ -148,8 +147,27 @@ fn fields_cmd(s: &mut Session, p: &Value) -> Result { let Some(src) = st.doc.data_merge.sources.first() else { return Ok(json!([])); }; - let placeholders = st.doc.data_merge.placeholders.clone(); - Ok(fields_json(&src.fields, |name| placeholders.iter().filter(|ph| ph.field == name).count())) + let doc = st.preview_stash.as_deref().unwrap_or(st.doc.as_ref()); + let placeholders = &doc.data_merge.placeholders; + let mut marker_counts = std::collections::HashMap::::new(); + for (story_id, story) in &doc.stories { + // The generated endnote frame repeats note text already counted in its owning story. + if Some(*story_id) == doc.endnote_story { + continue; + } + for (start, end, name) in fill::find_markers(&story.text) { + // A bound placeholder already accounts for its marker in the usage count. + let covered = placeholders.iter().any(|ph| { + matches!((&ph.role, &ph.anchor), (PlaceholderRole::Text | PlaceholderRole::Image, PlaceholderAnchor::Text { story, start: a, end: b }) + if story == story_id && start < *b && end > *a) + }); + if !covered { + *marker_counts.entry(name).or_default() += 1; + } + } + fill::count_nested_markers(story, &mut marker_counts, 0); + } + Ok(fields_json(&src.fields, |name| placeholders.iter().filter(|ph| ph.field == name).count() + marker_counts.get(name).copied().unwrap_or(0))) } fn placeholder_add(s: &mut Session, p: &Value) -> Result { @@ -172,8 +190,7 @@ fn placeholder_remove(s: &mut Session, p: &Value) -> Result { let start = start.min(end); st.replace(start..end, ""); } - let removed = end.saturating_sub(start); - shift_after(d, story, end, -(removed as isize)); + d.adjust_text_ranges(story, start..end, 0); } } d.data_merge.placeholders.retain(|ph| ph.id != id); @@ -210,8 +227,11 @@ fn preview_cmd(s: &mut Session, p: &Value) -> Result { let row = source.rows.get((record as usize).saturating_sub(1)).cloned().unwrap_or_default(); let data_dir = source_file(&source, st.path.as_deref().map(Path::new)).as_deref().and_then(Path::parent).map(Path::to_path_buf); let doc_dir = st.path.as_deref().and_then(parent_dir); - let sources = Sources { options: &options, data_dir: data_dir.as_deref(), doc_dir: doc_dir.as_deref() }; + let images = ImageCache::default(); + let sources = Sources { options: &options, data_dir: data_dir.as_deref(), doc_dir: doc_dir.as_deref(), images: &images }; fill_row(&mut doc, &source.fields, &row, record as u32, &maps, &sources); + // An image the record placed gets its Alpha Channel outline, as an edit's would. + crate::cmd::alpha_wrap::sync(&mut doc); st.doc = Arc::new(doc); st.preview_record = Some(record as u32); st.bump_revision(); @@ -246,7 +266,8 @@ fn merge_cmd(s: &mut Session, p: &Value) -> Result { warnings.extend(table.warnings.iter().cloned()); let mut merged = src.clone(); let mut missing = Vec::new(); - let sources = Sources { options: &options, data_dir: data_dir.as_deref(), doc_dir: doc_dir.as_deref() }; + let images = ImageCache::default(); + let sources = Sources { options: &options, data_dir: data_dir.as_deref(), doc_dir: doc_dir.as_deref(), images: &images }; let mut sink = Sink { warnings: &mut warnings, missing: &mut missing, parent: false }; if options.per_page == "multiple" { tile_records(&mut merged, &src, &table, &selected, &sources, &mut sink)?; @@ -262,6 +283,8 @@ fn merge_cmd(s: &mut Session, p: &Value) -> Result { merged.data_merge.placeholders.clear(); merged.title = format!("{} merged", src.title); let pages = merged.page_count(); + // The merged images' Alpha Channel outlines first: the overset count composes with them. + crate::cmd::alpha_wrap::sync(&mut merged); let overset = overset_count(&merged); let records = selected.len(); let missing_json: Vec = missing.iter().map(|m| json!({"record": m.record, "field": m.field, "path": m.path})).collect(); @@ -275,37 +298,74 @@ fn merge_cmd(s: &mut Session, p: &Value) -> Result { })) } +/// Pages a merge may make in all, checked before any is built. +const MAX_MERGED_PAGES: usize = 1_000_000; + fn copy_records(dst: &mut Document, src: &Document, table: &Table, selected: &[usize], sources: &Sources, sink: &mut Sink) -> Result<()> { if let Some(&idx) = selected.first() { let maps = identity_map(dst); fill_at(dst, table, idx, sources, &maps, sink); } - for &idx in selected.iter().skip(1) { - let maps = append_copy(dst, src)?; + let rest = selected.len().saturating_sub(1); + if rest == 0 { + return Ok(()); + } + // The pages of every further record in one insertion (one repagination, not one per record), + // then each copy goes onto its own. + let n = src.page_count().max(1); + let first_new = dst.page_count(); + let total = n + .checked_mul(rest) + .filter(|t| t.saturating_add(first_new) <= MAX_MERGED_PAGES) + .ok_or_else(|| bad("data.merge", format!("the merge would make more than {MAX_MERGED_PAGES} pages")))?; + let parent = src.page(0).and_then(|p| p.parent); + dst.insert_pages(Some(first_new.saturating_sub(1)), total, parent)?; + let dst_starts = spread_starts(dst); + let src_starts = spread_starts(src); + for (k, &idx) in selected.iter().skip(1).enumerate() { + let maps = append_copy(dst, src, first_new + k * n, &dst_starts, &src_starts)?; fill_at(dst, table, idx, sources, &maps, sink); } Ok(()) } -fn append_copy(dst: &mut Document, src: &Document) -> Result { - let start = dst.page_count(); +/// Absolute index of each spread's first page: page lookups by search rather than by walking the spreads. +fn spread_starts(d: &Document) -> Vec { + let mut n = 0; + d.spreads + .iter() + .map(|s| { + let at = n; + n += s.pages.len(); + at + }) + .collect() +} + +/// (spread, page in spread) of absolute page `abs`, as [`Document::page_loc`] says, given `starts`. +fn loc_of(d: &Document, starts: &[usize], abs: usize) -> Option<(usize, usize)> { + let si = starts.partition_point(|&s| s <= abs).checked_sub(1)?; + let pi = abs - starts.get(si)?; + (pi < d.spreads.get(si)?.pages.len()).then_some((si, pi)) +} + +/// Copy `src`'s pages and items onto the pages of `dst` from absolute page `start`. +fn append_copy(dst: &mut Document, src: &Document, start: usize, dst_starts: &[usize], src_starts: &[usize]) -> Result { let n = src.page_count().max(1); - let parent = src.page(0).and_then(|p| p.parent); - dst.insert_pages(Some(start.saturating_sub(1)), n, parent)?; for i in 0..n { if let Some(pg) = src.page(i).cloned() { - assign_page(dst, start.saturating_add(i), &pg); + assign_page(dst, loc_of(dst, dst_starts, start.saturating_add(i)), &pg); } } let mut maps = Maps::default(); for (spi, sp) in src.spreads.iter().enumerate() { for it in &sp.items { let pi = sp.page_at_x(it.bounds().center().x).unwrap_or(0); - let abs = src.first_page_of_spread(spi).saturating_add(pi); + let abs = src_starts.get(spi).copied().unwrap_or(0).saturating_add(pi); let dest_abs = start.saturating_add(abs); - let Some((dsi, _)) = dst.page_loc(dest_abs) else { continue }; + let Some((dsi, dpi)) = loc_of(dst, dst_starts, dest_abs) else { continue }; let src_x = src.page(abs).map(|p| p.x).unwrap_or(0.0); - let dst_x = dst.page(dest_abs).map(|p| p.x).unwrap_or(0.0); + let dst_x = dst.spreads.get(dsi).and_then(|s| s.pages.get(dpi)).map(|p| p.x).unwrap_or(0.0); copy_item(dst, src, it, SpreadRef::Doc(dsi), Vec2::new(dst_x - src_x, 0.0), &mut maps)?; } } @@ -334,11 +394,13 @@ fn tile_records(dst: &mut Document, src: &Document, table: &Table, selected: &[u let template = src.page(0).cloned(); dst.insert_pages(Some(0), plan.pages.saturating_sub(1), parent)?; if let Some(pg) = template { + let starts = spread_starts(dst); for i in 1..plan.pages { - assign_page(dst, i, &pg); + assign_page(dst, loc_of(dst, &starts, i), &pg); } } } + let starts = spread_starts(dst); for hit in plan.hits { let Some(&idx) = selected.get(hit.index) else { continue }; if hit.index == 0 && hit.page == 0 && hit.col == 0 && hit.row == 0 { @@ -346,7 +408,7 @@ fn tile_records(dst: &mut Document, src: &Document, table: &Table, selected: &[u fill_at(dst, table, idx, sources, &maps, sink); continue; } - let Some((dsi, _)) = dst.page_loc(hit.page) else { continue }; + let Some((dsi, _)) = loc_of(dst, &starts, hit.page) else { continue }; let mut maps = Maps::default(); for id in &ids { let Some(it) = src.item(*id) else { continue }; @@ -407,8 +469,8 @@ fn block_of(doc: &Document) -> (Rect, Vec) { (block.unwrap_or(Rect::ZERO), ids) } -fn assign_page(dst: &mut Document, abs: usize, from: &Page) { - let Some((si, pi)) = dst.page_loc(abs) else { return }; +fn assign_page(dst: &mut Document, loc: Option<(usize, usize)>, from: &Page) { + let Some((si, pi)) = loc else { return }; let Some(sp) = dst.spreads.get_mut(si) else { return }; let sp = Arc::make_mut(sp); let Some(p) = sp.pages.get_mut(pi) else { return }; @@ -432,7 +494,7 @@ fn overset_count(doc: &Document) -> usize { .count() } -fn add_placeholder(d: &mut Document, sel: &Selection, p: &Value, name: &str) -> Result { +fn add_placeholder(d: &mut Document, sel: &mut Selection, p: &Value, name: &str) -> Result { let (source_id, field) = { let source = d.data_merge.sources.first().ok_or_else(|| bad("data.placeholder.add", "select a data source"))?; let field = @@ -446,8 +508,13 @@ fn add_placeholder(d: &mut Document, sel: &Selection, p: &Value, name: &str) -> true } else if explicit_story || role_param == Some("text") { false - } else if matches!(role_param, Some("image" | "qr")) { - true + } else if role_param == Some("qr") { + // A QR role with the insertion point in text is refused below rather than bound to a + // selected frame the caret is not in. + sel.text.is_none() + } else if role_param == Some("image") { + // An image role with the insertion point in text places an inline image there. + sel.text.is_none() } else { sel.text.is_none() && !sel.items.is_empty() }; @@ -459,6 +526,12 @@ fn add_placeholder(d: &mut Document, sel: &Selection, p: &Value, name: &str) -> DataFieldKind::Qr => PlaceholderRole::Qr, DataFieldKind::Text => return Err(bad("data.placeholder.add", "say which role to use on this frame")), } + } else if field.kind == DataFieldKind::Image { + // An image field at the insertion point places the image inline in the text. + PlaceholderRole::Image + } else if field.kind == DataFieldKind::Qr { + // A QR field at the insertion point is refused below: QR codes bind to a frame. + PlaceholderRole::Qr } else { PlaceholderRole::Text }; @@ -477,14 +550,58 @@ fn add_placeholder(d: &mut Document, sel: &Selection, p: &Value, name: &str) -> } PlaceholderAnchor::Item { id: item } } else { - if matches!(role, PlaceholderRole::Image | PlaceholderRole::Qr) { - return Err(bad("data.placeholder.add", "image and qr placeholders bind to a frame")); + if role == PlaceholderRole::Qr { + return Err(bad("data.placeholder.add", "qr placeholders bind to a frame")); + } + // The insertion point is in a table cell or a footnote: the field goes into that text as + // its marker, which the merge fills as it fills a typed one. Such a text is a story of its + // own that a placeholder can't name, and the selection's offsets are its own, so they used + // to put the marker in the table's story instead (#2315). + if !explicit_story + && let Some(t) = sel.text + && let Some(pressed) = t.cell + { + // The merge fills such a text with the record's value as text, so an image there + // would merge as its path. + if role == PlaceholderRole::Image { + return Err(bad( + "data.placeholder.add", + "an image field can't go in a table cell or a note; bind it to a frame, or insert it with role text to merge its path", + )); + } + if role != PlaceholderRole::Text { + return Err(bad("data.placeholder.add", "a hyperlink field can't go in a table cell or a note; insert it as text")); + } + // The merge finds a marker by its name, so a name that can't be read back out of one + // would stay a marker: say so rather than insert it. + if name.is_empty() || name.contains(['<', '>', '\n']) { + return Err(bad( + "data.placeholder.add", + format!("the field \"{name}\" can't be inserted in a table cell or a note: its name holds < > or a line break"), + )); + } + // A position a merged cell covers is the merged cell's: the field goes where it shows. + let cell = d.story(t.story).and_then(|st| st.tables.get(&pressed.table)).map_or(pressed, |tab| { + let (row, col) = tab.owner(pressed.row, pressed.col); + designcraft_doc::CellAddr { row, col, ..pressed } + }); + let marker = format!("<<{name}>>"); + let st = d.text_story_mut(t.story, Some(cell)).ok_or_else(|| bad("data.placeholder.add", "no table cell there"))?; + let at = if cell == pressed { t.range().start.min(st.text.len()) } else { st.text.len() }; + let at = designcraft_doc::floor_char_boundary(&st.text, at); + st.replace(at..at, &marker); + // The caret goes after the field, in that text, as after typing; a cell selection + // would have the next keystroke replace the whole cell, field and all. + let end = at + marker.len(); + sel.cells = None; + sel.text = Some(designcraft_doc::TextSel { anchor: end, focus: end, cell: Some(cell), ..t }); + return Ok(json!({"cell": true, "marker": marker})); } let (story, at, end) = text_target(p, sel).ok_or_else(|| bad("data.placeholder.add", "select text or a frame"))?; if d.story(story).is_none() { return Err(bad("data.placeholder.add", "no story")); } - if role == PlaceholderRole::Text { + if matches!(role, PlaceholderRole::Text | PlaceholderRole::Image) { let marker = format!("<<{name}>>"); let at = { let text = d.story(story).map(|st| st.text.clone()).unwrap_or_default(); @@ -493,7 +610,12 @@ fn add_placeholder(d: &mut Document, sel: &Selection, p: &Value, name: &str) -> if let Some(st) = d.story_mut(story) { st.replace(at..at, &marker); } - shift_after(d, story, at, marker.len() as isize); + d.adjust_text_ranges(story, at..at, marker.len()); + // The caret moves past the field, as after typing, so the next field goes after it. + if let Some(t) = sel.text.as_mut().filter(|t| t.story == story && t.cell.is_none()) { + let shift = |pos: usize| if pos >= at { pos + marker.len() } else { pos }; + (t.anchor, t.focus) = (shift(t.anchor), shift(t.focus)); + } PlaceholderAnchor::Text { story, start: at, end: at.saturating_add(marker.len()) } } else { let text = d.story(story).map(|st| st.text.clone()).unwrap_or_default(); @@ -519,30 +641,6 @@ fn text_target(p: &Value, sel: &Selection) -> Option<(StoryId, usize, usize)> { }) } -fn shift_after(doc: &mut Document, story: StoryId, at: usize, delta: isize) { - if delta == 0 { - return; - } - for ph in &mut doc.data_merge.placeholders { - if let PlaceholderAnchor::Text { story: s, start, end } = &mut ph.anchor - && *s == story - && *start >= at - { - *start = fill::add_delta(*start, delta); - *end = fill::add_delta(*end, delta); - } - } - for link in &mut doc.hyperlinks { - if let HyperlinkSource::Text { story: s, start, end } = &mut link.source - && *s == story - && *start >= at - { - *start = fill::add_delta(*start, delta); - *end = fill::add_delta(*end, delta); - } - } -} - /// After an edit, drop a text placeholder whose marker is gone unless the story still has exactly /// one copy of it, and drop an item placeholder whose frame is gone. pub(crate) fn sync_placeholders(doc: &mut Document) { @@ -560,7 +658,7 @@ pub(crate) fn sync_placeholders(doc: &mut Document) { } PlaceholderAnchor::Text { story, start, end } => { let text = doc.story(story).map(|st| st.text.clone()).unwrap_or_default(); - if ph.role != PlaceholderRole::Text { + if !matches!(ph.role, PlaceholderRole::Text | PlaceholderRole::Image) { if start <= end && end <= text.len() { keep.push(ph); } @@ -749,11 +847,10 @@ fn take_file(p: &Value) -> std::result::Result<(Vec, String, Option) } fn parse_file(bytes: &[u8], name: &str, delimiter: Option, sheet: Option<&str>) -> std::result::Result { - let ext = extension(name); - if ext == "xls" || ext == "xlsm" { - return Err(format!("{ext} workbooks are not supported")); + if craft_file_formats::detect(name, &[]) == Some(craft_file_formats::Format::LegacyExcel) { + return Err("legacy Excel .xls/.xlsm workbooks are not supported".into()); } - if ext == "xlsx" { + if craft_file_formats::detect(name, bytes) == Some(craft_file_formats::Format::Xlsx) { let grid = designcraft_textimport::xlsx_records(bytes, sheet).map_err(|e| e.to_string())?; return table_from_grid(grid, Delimiter::Comma); } diff --git a/crates/engine/src/cmd/datamerge/fill.rs b/crates/engine/src/cmd/datamerge/fill.rs index 629258d6d..b7d465320 100644 --- a/crates/engine/src/cmd/datamerge/fill.rs +++ b/crates/engine/src/cmd/datamerge/fill.rs @@ -4,14 +4,14 @@ //! unfilled template. A placeholder whose frame or story is not in the map is left as it is. use std::collections::HashMap; -use std::path::Path; +use std::path::{Path, PathBuf}; use std::sync::Arc; use designcraft_doc::{ - Asset, AssetId, Content, DataField, Fill, Fitting, Graphic, Hyperlink, HyperlinkDest, HyperlinkSource, Item, ItemId, MergeOptions, - PlaceholderAnchor, PlaceholderRole, Shape, SpreadRef, Story, StoryId, + AnchorPosition, AnchoredObject, Asset, AssetId, Content, DataField, DataFieldKind, Fill, Fitting, Graphic, Hyperlink, HyperlinkDest, + HyperlinkSource, Item, ItemId, MergeOptions, OBJECT_MARK, PlaceholderAnchor, PlaceholderRole, Shape, SpreadRef, Story, StoryId, }; -use designcraft_geom::{Affine, Rect, Vec2}; +use designcraft_geom::{Affine, Rect, Vec2, shapes}; use super::parse::image_candidates; use crate::EngineError; @@ -71,11 +71,17 @@ pub fn copy_item( } fn renumber(dst: &mut designcraft_doc::Document, src: &designcraft_doc::Document, it: &mut Item, maps: &mut Maps) { + renumber_in(dst, src, it, maps, true); +} + +/// `adopt` is false inside a story copy, whose asset references the copy has already adopted. +fn renumber_in(dst: &mut designcraft_doc::Document, src: &designcraft_doc::Document, it: &mut Item, maps: &mut Maps, adopt: bool) { let old = it.id; let new_id = ItemId(dst.alloc()); maps.items.insert(old, new_id); it.id = new_id; - if let Some(m) = it.media.as_mut() + if adopt + && let Some(m) = it.media.as_mut() && let Some(p) = m.poster { m.poster = dst.adopt_asset(src, p).or(Some(p)); @@ -98,8 +104,10 @@ fn renumber(dst: &mut designcraft_doc::Document, src: &designcraft_doc::Document } designcraft_doc::remap_story_assets(&mut st, &assets); st.frames.clear(); - dst.stories.insert(n, Arc::new(st)); + // Mapped first: the map is the seen-set that stops story recursion. maps.stories.insert(tf.story, n); + renumber_anchored(dst, src, &mut st, maps); + dst.stories.insert(n, Arc::new(st)); n }; tf.story = new_sid; @@ -108,24 +116,47 @@ fn renumber(dst: &mut designcraft_doc::Document, src: &designcraft_doc::Document } } Content::Graphic(g) => { - if let Some(a) = dst.adopt_asset(src, g.asset) { + if adopt && let Some(a) = dst.adopt_asset(src, g.asset) { g.asset = a; } } Content::Group { items } => { for child in items.iter_mut() { - renumber(dst, src, Arc::make_mut(child), maps); + renumber_in(dst, src, Arc::make_mut(child), maps, adopt); } } Content::Unassigned => {} } } +/// Fresh ids for the objects anchored in story copy `st`, its table cells, footnotes and endnotes (#1522). +fn renumber_anchored(dst: &mut designcraft_doc::Document, src: &designcraft_doc::Document, st: &mut Story, maps: &mut Maps) { + let mut fresh = |t: &mut Story| { + for o in &mut t.objects { + renumber_in(dst, src, &mut Arc::make_mut(o).item, maps, false); + } + }; + st.for_each_text_mut(&mut fresh); + for n in &mut st.endnotes { + Arc::make_mut(n).text.for_each_text_mut(&mut fresh); + } +} + struct Rep { story: StoryId, start: usize, end: usize, text: String, + /// An inline image that takes the range's place; `text` is then its object mark. + object: Option, +} + +/// An image field at a text range: the placed image goes into the text in the marker's place. +struct InlineImage { + story: StoryId, + start: usize, + end: usize, + field: String, } /// Where `fill_row` looks for linked images: the merge options and the two search folders. @@ -134,12 +165,53 @@ pub struct Sources<'a> { pub options: &'a MergeOptions, pub data_dir: Option<&'a Path>, pub doc_dir: Option<&'a Path>, + /// Images this merge has already read, by the path they resolved to. + /// + /// Every record used to stat and read its image again, so a 100,000-row sheet naming the same + /// file read it 100,000 times -- up to 256 MiB each, around 25 TB of I/O for one merge + /// (#1595). Shared by `&`, so the cache is behind a `RefCell`. + pub images: &'a ImageCache, +} + +/// Image files read during one merge: the bytes by path, and the total read so far. +#[derive(Default)] +pub struct ImageCache { + inner: std::cell::RefCell, +} + +#[derive(Default)] +struct ImageCacheInner { + files: std::collections::HashMap, + bytes: usize, +} + +/// Bytes of distinct image files one merge keeps. Past this the cache stops growing and files are +/// read as before, so a merge over many large images is slow rather than out of memory. +const MAX_CACHED_IMAGE_BYTES: usize = 256 << 20; + +impl ImageCache { + /// The bytes of `path`, reading it once per merge. `read` is called only on a miss. + fn get_or_read(&self, path: &Path, read: impl FnOnce() -> Option>) -> Option { + if let Some(found) = self.inner.borrow().files.get(path) { + return Some(found.clone()); + } + let bytes = read()?; + let len = bytes.len(); + let bytes = designcraft_doc::AssetData::embedded(bytes); + let mut inner = self.inner.borrow_mut(); + if inner.bytes.saturating_add(len) <= MAX_CACHED_IMAGE_BYTES { + inner.bytes = inner.bytes.saturating_add(len); + inner.files.insert(path.to_path_buf(), bytes.clone()); + } + Some(bytes) + } } /// Replacements and hyperlinks collected while walking the placeholders of one record. #[derive(Default)] struct Pending { reps: Vec, + images: Vec, links: Vec<(PlaceholderAnchor, HyperlinkDest, String)>, parent: bool, report: FillReport, @@ -166,9 +238,16 @@ pub fn fill_row( PlaceholderAnchor::Item { .. } => plan_item(doc, maps, ph, &cell, record, sources, &mut pending), } } - let Pending { mut reps, links, parent, mut report } = pending; - typed_reps(doc, fields, row, maps, &placeholders, &mut reps); + let Pending { mut reps, mut images, links, parent, mut report } = pending; + typed_reps(doc, fields, row, maps, &placeholders, &mut reps, &mut images); + for InlineImage { story, start, end, field } in images { + let cell = cell_of(fields, row, &field); + let object = inline_image(doc, story, &field, cell, record, sources, &mut report); + let text = if object.is_some() { OBJECT_MARK.to_string() } else { String::new() }; + reps.push(Rep { story, start, end, text, object }); + } apply_reps(doc, &reps); + fill_nested_markers(doc, fields, row, maps); for (anchor, dest, field) in links { let anchor = match anchor { PlaceholderAnchor::Text { story, start, end } => { @@ -202,13 +281,14 @@ fn plan_text( return; }; match ph.role { - PlaceholderRole::Text => pending.reps.push(Rep { story: mapped, start, end, text: cell }), + PlaceholderRole::Text => pending.reps.push(Rep { story: mapped, start, end, text: cell, object: None }), + PlaceholderRole::Image => pending.images.push(InlineImage { story: mapped, start, end, field: ph.field.clone() }), PlaceholderRole::Hyperlink => { if let Some(dest) = classify_link(&cell) { pending.links.push((PlaceholderAnchor::Text { story: mapped, start, end }, dest, ph.field.clone())); } } - PlaceholderRole::Image | PlaceholderRole::Qr => {} + PlaceholderRole::Qr => {} } } @@ -247,6 +327,7 @@ fn typed_reps( maps: &Maps, placeholders: &[designcraft_doc::Placeholder], reps: &mut Vec, + images: &mut Vec, ) { let mut stories: Vec<(StoryId, StoryId)> = maps.stories.iter().map(|(a, b)| (*a, *b)).collect(); stories.sort_by_key(|(a, _)| a.0); @@ -256,7 +337,9 @@ fn typed_reps( let covers: Vec<(usize, usize)> = placeholders .iter() .filter_map(|ph| match (&ph.role, &ph.anchor) { - (PlaceholderRole::Text, PlaceholderAnchor::Text { story, start, end }) if *story == original => Some((*start, *end)), + (PlaceholderRole::Text | PlaceholderRole::Image, PlaceholderAnchor::Text { story, start, end }) if *story == original => { + Some((*start, *end)) + } _ => None, }) .collect(); @@ -264,24 +347,120 @@ fn typed_reps( if covers.iter().any(|(a, b)| start < *b && end > *a) { continue; } - if !fields.iter().any(|f| f.name == name) { + let Some(field) = fields.iter().find(|f| f.name == name) else { continue }; + if field.kind == DataFieldKind::Image { + images.push(InlineImage { story: mapped, start, end, field: name }); continue; } - reps.push(Rep { story: mapped, start, end, text: cell_of(fields, row, &name).to_string() }); + reps.push(Rep { story: mapped, start, end, text: cell_of(fields, row, &name).to_string(), object: None }); } } } -fn find_markers(text: &str) -> Vec<(usize, usize, String)> { +/// How deep the merge follows texts inside texts (a table in a cell of a table, a note in a cell). +/// Documents don't come anywhere near it; a file that goes deeper is filled down to here instead of +/// exhausting the stack. +pub(super) const MAX_NESTED_DEPTH: usize = 32; + +/// The `<>` markers in the table cells, footnotes and endnotes of the stories being filled. +/// Those texts are stories inside their story, which no placeholder can name and `typed_reps` +/// doesn't read, so a field in a table was left as its marker (#2315). A story, table or note is +/// copied only when something inside it holds a marker of a known field. +fn fill_nested_markers(doc: &mut designcraft_doc::Document, fields: &[DataField], row: &[String], maps: &Maps) { + let mut mapped: Vec = maps.stories.values().copied().collect(); + mapped.sort(); + mapped.dedup(); + for sid in mapped { + if !doc.story(sid).is_some_and(|st| inner_has(st, fields, 0)) { + continue; + } + let Some(st) = doc.story_mut(sid) else { continue }; + fill_inner(st, fields, row, 0); + } +} + +/// Whether `st`'s own text holds a marker of a known field. +fn own_has(st: &Story, fields: &[DataField]) -> bool { + find_markers(&st.text).iter().any(|(_, _, name)| fields.iter().any(|f| f.name == *name)) +} + +/// Whether a text inside `st` (a table cell, footnote or endnote, or one inside those), not `st`'s +/// own text, holds a marker of a known field. +fn inner_has(st: &Story, fields: &[DataField], depth: usize) -> bool { + if depth >= MAX_NESTED_DEPTH { + return false; + } + let holds = |t: &Story| own_has(t, fields) || inner_has(t, fields, depth + 1); + st.tables.values().any(|t| t.cells.iter().any(|c| holds(&c.text))) || st.notes.iter().chain(&st.endnotes).any(|n| holds(&n.text)) +} + +/// Fill the known fields' markers in the texts inside `st`, not in its own text. +fn fill_inner(st: &mut Story, fields: &[DataField], row: &[String], depth: usize) { + if depth >= MAX_NESTED_DEPTH { + return; + } + let holds = |t: &Story| own_has(t, fields) || inner_has(t, fields, depth + 1); + for t in st.tables.values_mut() { + if t.cells.iter().any(|c| holds(&c.text)) { + for c in &mut Arc::make_mut(t).cells { + fill_own(&mut c.text, fields, row); + fill_inner(&mut c.text, fields, row, depth + 1); + } + } + } + for n in st.notes.iter_mut().chain(st.endnotes.iter_mut()) { + if holds(&n.text) { + let n = Arc::make_mut(n); + fill_own(&mut n.text, fields, row); + fill_inner(&mut n.text, fields, row, depth + 1); + } + } +} + +/// Count markers in nested text to match the merge's depth limit. +pub(super) fn count_nested_markers(st: &Story, counts: &mut HashMap, depth: usize) { + if depth >= MAX_NESTED_DEPTH { + return; + } + let mut count = |inner: &Story| { + for (_, _, name) in find_markers(&inner.text) { + *counts.entry(name).or_default() += 1; + } + count_nested_markers(inner, counts, depth + 1); + }; + for table in st.tables.values() { + for cell in &table.cells { + count(&cell.text); + } + } + for note in st.notes.iter().chain(st.endnotes.iter()) { + count(¬e.text); + } +} +/// Replace the markers of known fields in `st`'s own text with the record's values. +fn fill_own(st: &mut Story, fields: &[DataField], row: &[String]) { + let found: Vec<(usize, usize, String)> = + find_markers(&st.text).into_iter().filter(|(_, _, name)| fields.iter().any(|f| f.name == *name)).collect(); + for (start, end, name) in found.into_iter().rev() { + st.replace(start..end, cell_of(fields, row, &name)); + } +} + +pub(super) fn find_markers(text: &str) -> Vec<(usize, usize, String)> { let mut out = Vec::new(); let mut i = 0; + // The next `>>` at or after the `<<` being looked at: found once, kept until passed, so the + // text is scanned once however many `<<` it holds (not again from every one of them). + let mut close: Option = Some(0); while i < text.len() { - if text[i..].starts_with("<<") - && let Some(rel) = text[i + 2..].find(">>") - { - let name = &text[i + 2..i + 2 + rel]; + if text[i..].starts_with("<<") { + if close.is_some_and(|c| c < i + 2) { + close = text[i + 2..].find(">>").map(|rel| i + 2 + rel); + } + let Some(c) = close else { break }; + let name = &text[i + 2..c]; if !name.is_empty() && !name.contains(['<', '>', '\n']) { - let end = i + 2 + rel + 2; + let end = c + 2; out.push((i, end, name.to_string())); i = end; continue; @@ -303,6 +482,15 @@ fn apply_reps(doc: &mut designcraft_doc::Document, reps: &[Rep]) { for r in mine { if r.start <= r.end && r.end <= st.text.len() { st.replace(r.start..r.end, &r.text); + // The replacement made a blank object for its mark; the image takes that slot. + if let Some(obj) = &r.object + && st.text.get(r.start..).is_some_and(|t| t.starts_with(OBJECT_MARK)) + { + let k = st.text[..r.start].matches(OBJECT_MARK).count(); + if let Some(slot) = st.objects.get_mut(k) { + *slot = Arc::new(obj.clone()); + } + } } } } @@ -351,41 +539,129 @@ fn create_link(doc: &mut designcraft_doc::Document, anchor: PlaceholderAnchor, d } }; let id = doc.alloc(); - let name = match &dest { - HyperlinkDest::Url(u) | HyperlinkDest::Email(u) => u.clone(), - HyperlinkDest::Page(p) => format!("Page {}", p + 1), - }; + let name = dest.label(); doc.hyperlinks.push(Hyperlink { id, name, source, dest }); true } -fn place_image(doc: &mut designcraft_doc::Document, item: ItemId, field: &str, cell: &str, record: u32, sources: &Sources, report: &mut FillReport) { - let Sources { options, data_dir, doc_dir } = *sources; +/// An image file named by a cell: where it was found, its bytes, its pixel size and its natural size. +struct LoadedImage { + path: PathBuf, + bytes: designcraft_doc::AssetData, + pixels: (u32, u32), + natural: (f64, f64), +} + +/// The first candidate for `cell` that reads and decodes; `None` when none does. +fn load_image(cell: &str, sources: &Sources) -> Option { + let Sources { data_dir, doc_dir, images, .. } = *sources; let cands = image_candidates(cell, data_dir, doc_dir); - let found = cands.iter().find_map(|p| { - // Refuse huge files before reading them; a too-large image counts as missing. - let len = crate::io::metadata(p).ok()?.len(); - if len == 0 || len > super::MAX_IMAGE_FILE_BYTES { - return None; - } - crate::io::read_file(p).ok().filter(|b| !b.is_empty()).map(|b| (p.clone(), b)) + cands.iter().find_map(|p| { + // Read once per merge: many records naming one file is the normal case, and reading it + // per record is the amplification (#1595). + let bytes = images.get_or_read(p, || { + // Refuse huge files before reading them; a too-large image counts as missing. + let len = crate::io::metadata(p).ok()?.len(); + if len == 0 || len > super::MAX_IMAGE_FILE_BYTES { + return None; + } + crate::io::read_file(p).ok().filter(|b| !b.is_empty()) + })?; + // A file that does not decode leaves the search going, so a valid image at a later + // candidate is still found. + let raw = bytes.embedded_bytes()?; + let (pixels, natural) = designcraft_render::image_size(raw).zip(designcraft_render::natural_size(raw, 0))?; + Some(LoadedImage { path: p.clone(), bytes, pixels, natural }) + }) +} + +fn report_missing(report: &mut FillReport, record: u32, field: &str, cell: &str) { + report.missing.push(MissingImage { record, field: field.to_string(), path: cell.to_string() }); + report.warnings.push(format!("Record {record}, field {field}: missing image {cell}.")); +} + +/// Add `image` to the document as a new asset, linked to its file when the options say so. +fn add_image_asset(doc: &mut designcraft_doc::Document, image: LoadedImage, field: &str, options: &MergeOptions) -> AssetId { + let fresh = AssetId(doc.alloc()); + let name = image.path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| field.to_string()); + let link = options.link_images.then(|| image.path.to_string_lossy().into_owned()); + doc.add_asset(Asset { + id: fresh, + name, + mime: designcraft_render::image_mime(image.bytes.embedded_bytes().map_or(&[][..], |b| b.as_slice())).to_string(), + link, + // The cached buffer is shared with every other record naming this file, rather than + // copied per record (#1595). + data: image.bytes, + pixels: Some(image.pixels), + ..Default::default() + }) +} + +/// The image `cell` names, as an inline object for the text of `story`. It comes in at its +/// natural size, scaled down to fit the smallest text column of the story's frames (never scaled up). +fn inline_image( + doc: &mut designcraft_doc::Document, + story: StoryId, + field: &str, + cell: &str, + record: u32, + sources: &Sources, + report: &mut FillReport, +) -> Option { + let Some(image) = load_image(cell, sources) else { + report_missing(report, record, field, cell); + return None; + }; + let (nw, nh) = image.natural; + let frame = doc.story(story).and_then(|st| st.frames.first().copied()).and_then(|id| doc.item(id)); + let layer = frame.map_or_else(|| doc.default_layer(), |it| it.layer); + // The marker may flow into any of the story's frames: fit the smallest column among them. + let fit = designcraft_compose::frame_specs(doc, story) + .iter() + .flat_map(|f| f.columns()) + .map(|b| (b.width() / nw).min(b.height() / nh)) + .reduce(f64::min) + .unwrap_or(1.0); + let k = if fit.is_finite() && fit > 0.0 { fit.min(1.0) } else { 1.0 }; + let rect = Rect::new(0.0, 0.0, nw * k, nh * k); + let xf = Affine::scale(k); + if super::super::file::validate_placement((nw, nh), rect, xf, "data.merge").is_err() { + report.missing.push(MissingImage { record, field: field.to_string(), path: cell.to_string() }); + report.warnings.push(format!("Record {record}, field {field}: image {cell} exceeds finite geometry limits.")); + return None; + } + let asset = add_image_asset(doc, image, field, sources.options); + let mut it = Item::new(ItemId(doc.alloc()), layer, Shape::Rectangle, shapes::rectangle(rect)); + it.object_style = doc.styles.default_graphic_frame.clone(); + if let Some(e) = doc.styles.object_effects(&it.object_style) { + it.effects = e.clone(); + } + it.content = Content::Graphic(Graphic { + layer_options: None, + asset, + size: (nw, nh), + xf, + auto_fit: Fitting::None, + fit_align: 0, + crop: [0.0; 4], + wrap: Default::default(), + clip: None, + fill: Default::default(), }); - let Some((path, bytes)) = found else { + Some(AnchoredObject::new(it, AnchorPosition::default())) +} + +fn place_image(doc: &mut designcraft_doc::Document, item: ItemId, field: &str, cell: &str, record: u32, sources: &Sources, report: &mut FillReport) { + let options = sources.options; + let Some(image) = load_image(cell, sources) else { if let Some(it) = doc.item_mut(item) { it.content = Content::Unassigned; } - report.missing.push(MissingImage { record, field: field.to_string(), path: cell.to_string() }); - report.warnings.push(format!("Record {record}, field {field}: missing image {cell}.")); - return; - }; - let Some(((pw, ph), (nw, nh))) = designcraft_render::image_size(&bytes).zip(designcraft_render::natural_size(&bytes, 0)) else { - if let Some(it) = doc.item_mut(item) { - it.content = Content::Unassigned; - } - report.missing.push(MissingImage { record, field: field.to_string(), path: cell.to_string() }); - report.warnings.push(format!("Record {record}, field {field}: missing image {cell}.")); + report_missing(report, record, field, cell); return; }; + let (nw, nh) = image.natural; let Some(inner) = doc.item(item).map(|it| it.inner_bounds()) else { report.warnings.push(format!("Record {record}, field {field}: missing image {cell}.")); report.missing.push(MissingImage { record, field: field.to_string(), path: cell.to_string() }); @@ -422,18 +698,7 @@ fn place_image(doc: &mut designcraft_doc::Document, item: ItemId, field: &str, c report.warnings.push(format!("Record {record}, field {field}: image {cell} exceeds finite geometry limits.")); return; } - let fresh = AssetId(doc.alloc()); - let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| field.to_string()); - let link = options.link_images.then(|| path.to_string_lossy().into_owned()); - g.asset = doc.add_asset(Asset { - id: fresh, - name, - mime: designcraft_render::image_mime(&bytes).to_string(), - link, - data: Arc::new(bytes), - pixels: Some((pw, ph)), - ..Default::default() - }); + g.asset = add_image_asset(doc, image, field, options); if let Some(it) = doc.item_mut(item) { it.content = Content::Graphic(g); } @@ -507,6 +772,25 @@ fn cell_of<'a>(fields: &[DataField], row: &'a [String], name: &str) -> &'a str { fields.iter().position(|f| f.name == name).and_then(|i| row.get(i)).map(String::as_str).unwrap_or("") } +#[cfg(test)] +mod marker_tests { + use super::find_markers; + + #[test] + fn markers_are_found_in_one_pass() { + let found = find_markers; + assert_eq!(found("a <> b <>"), [(2, 10, "Name".to_string()), (13, 18, "x".to_string())]); + assert_eq!(found("<<>> <> <>"), [(13, 19, "ok".to_string())]); + assert_eq!(found("<<<>"), [(2, 7, "a".to_string())]); + // Many `<<` with no `>>` to close them: linear, not a search from each of them. + let open = "<<".repeat(200_000); + let t = std::time::Instant::now(); + assert!(found(&open).is_empty()); + assert!(found(&format!("{open}>>")).is_empty(), "a name made of `<` isn't one"); + assert!(t.elapsed() < std::time::Duration::from_secs(5), "{:?}", t.elapsed()); + } +} + #[cfg(test)] mod link_tests { use super::*; @@ -523,20 +807,67 @@ mod link_tests { } } -#[cfg(all(test, unix))] +#[cfg(test)] mod image_path_tests { use std::path::Path; use super::image_candidates; + /// A merge image field names a file, and a field that names **another computer** must resolve + /// to nothing: a UNC path is how a hostile data file turns a merge into an outbound SMB + /// connection, and on Windows that means handing over NTLM credentials. This ran only on + /// unix, so the refusal was unverified on the one platform where UNC means anything (#1601). #[test] - fn image_cells_resolve_beside_the_data_and_never_to_other_computers() { + fn an_image_cell_never_resolves_to_another_computer() { let (data, doc) = (Path::new("/work/data"), Path::new("/work/doc")); for cell in [r"\\192.0.2.1\share\x.png", "file://192.0.2.1/s/x.png", "//192.0.2.1/s/x.png", "https://example.com/x.png"] { assert!(image_candidates(cell, Some(data), Some(doc)).is_empty(), "{cell}"); } - let found = image_candidates("img/x.png", Some(data), Some(doc)); - assert_eq!(found, [data.join("img").join("x.png"), doc.join("img").join("x.png")]); + // A field naming nothing resolves to nothing, whatever the platform. + assert!(image_candidates("", Some(data), Some(doc)).is_empty(), "an empty cell"); assert!(image_candidates("img/x.png", None, None).is_empty(), "not beside the working directory"); } + + /// The Windows shapes `craft-docpath` refuses, asserted where they have meaning: the extended + /// UNC prefix, a device namespace path, and a legacy device name (with an extension, since a + /// reserved name is reserved whatever follows it). + #[cfg(windows)] + #[test] + fn windows_device_and_network_paths_are_refused() { + let (data, doc) = (Path::new(r"C:\work\data"), Path::new(r"C:\work\doc")); + for cell in [r"\\?\UNC\192.0.2.1\share\x.png", r"\\.\pipe\x", r"\\?\GLOBALROOT\Device\HarddiskVolume1\x", "CON", "NUL.png"] { + assert!(image_candidates(cell, Some(data), Some(doc)).is_empty(), "{cell}"); + } + } + + /// An extended-length path is not one of them: `\\?\C:\x` names a local file, the same one + /// `C:\x` names, and `craft-docpath`'s own suite classifies it `PathKind::Local`. A data file + /// could already give the plain spelling, so refusing this one would shut out long paths + /// without shutting anything out (noted in review). + #[cfg(windows)] + #[test] + fn an_extended_length_drive_path_is_a_local_file() { + let (data, doc) = (Path::new(r"C:\work\data"), Path::new(r"C:\work\doc")); + assert!(!image_candidates(r"\\?\C:\secret\x.png", Some(data), Some(doc)).is_empty()); + } + + /// Resolution beside the data and the document, with absolute paths this platform means. + #[cfg(unix)] + #[test] + fn an_image_cell_resolves_beside_the_data_then_the_document() { + let (data, doc) = (Path::new("/work/data"), Path::new("/work/doc")); + let found = image_candidates("img/x.png", Some(data), Some(doc)); + assert_eq!(found, [data.join("img").join("x.png"), doc.join("img").join("x.png")]); + } + + /// A path that starts with one separator is tried as it is, then beside the data file and the + /// document without the separator. Two separators still name another computer. + #[cfg(unix)] + #[test] + fn a_rooted_image_cell_is_also_tried_beside_the_data_and_the_document() { + let (data, doc) = (Path::new("/work/data"), Path::new("/work/doc")); + let found = image_candidates("/img/x.png", Some(data), Some(doc)); + assert_eq!(found, [Path::new("/img/x.png").to_path_buf(), data.join("img").join("x.png"), doc.join("img").join("x.png")]); + assert!(image_candidates("//192.0.2.1/img/x.png", Some(data), Some(doc)).is_empty()); + } } diff --git a/crates/engine/src/cmd/datamerge/parse.rs b/crates/engine/src/cmd/datamerge/parse.rs index 6cc838c3c..435188f99 100644 --- a/crates/engine/src/cmd/datamerge/parse.rs +++ b/crates/engine/src/cmd/datamerge/parse.rs @@ -159,7 +159,11 @@ pub fn select_records(count: usize, records: &str, one: u32, range: &str, limit: let i = record_index(one, count)?; idx.push(i); } - "range" => select_range(range, count, &mut idx, &mut seen)?, + "range" => { + // Past this many records nothing more can be kept, so later ranges are only validated. + let keep = limit.filter(|l| *l > 0).map_or(count, |l| count.min(l as usize)); + select_range(range, count, keep, &mut idx, &mut seen)? + } other => return Err(format!("unknown records value \"{other}\"")), } if let Some(limit) = limit { @@ -175,7 +179,9 @@ pub fn select_records(count: usize, records: &str, one: u32, range: &str, limit: } /// Expand a comma-separated list of record numbers and `a-b` ranges into `idx`, skipping repeats. -fn select_range(range: &str, count: usize, idx: &mut Vec, seen: &mut std::collections::HashSet) -> Result<(), String> { +/// Every token is still checked, but once `idx` holds `keep` records no more are expanded, so +/// repeated or overlapping ranges cost nothing past that point. +fn select_range(range: &str, count: usize, keep: usize, idx: &mut Vec, seen: &mut std::collections::HashSet) -> Result<(), String> { if range.trim().is_empty() { return Err("no records".into()); } @@ -194,8 +200,11 @@ fn select_range(range: &str, count: usize, idx: &mut Vec, seen: &mut std: if a > b { return Err(format!("range {a}-{b} is reversed")); } + // Both ends in range means every record between them is. + record_index(a, count)?; + record_index(b, count)?; let mut n = a; - while n <= b { + while n <= b && idx.len() < keep { let i = record_index(n, count)?; if seen.insert(i) { idx.push(i); @@ -210,6 +219,10 @@ fn select_range(range: &str, count: usize, idx: &mut Vec, seen: &mut std: } fn parse_record_no(s: &str) -> Result { + // `parse` alone would accept a leading '+'. + if !s.bytes().all(|b| b.is_ascii_digit()) { + return Err(format!("bad record \"{s}\"")); + } s.parse::().map_err(|_| format!("bad record \"{s}\"")) } @@ -284,15 +297,18 @@ fn next_slot(col: i32, row: i32, rows_first: bool, fits_col: &impl Fn(i32) -> bo /// Files to try for an image cell: an absolute path as it is, a relative one beside the data /// file, then beside the document. Relative paths are not resolved against the process working /// directory, and paths that may not be followed ([`crate::io::document_path`]: URLs, other -/// computers, devices) are not candidates. +/// computers, devices) are not candidates. A path that starts with one separator (`\Photos\x.jpg`) +/// is tried as it is first, then beside the data file and the document with that separator dropped. pub fn image_candidates(cell: &str, data_dir: Option<&Path>, doc_dir: Option<&Path>) -> Vec { let cell = cell.trim(); if cell.is_empty() { return Vec::new(); } + let below = cell.strip_prefix(['\\', '/']).filter(|rest| !rest.is_empty() && !rest.starts_with(['\\', '/'])); let found = std::iter::once(crate::io::document_path(cell, None)) .chain(data_dir.map(|dir| crate::io::folder_path(cell, dir))) - .chain(doc_dir.map(|dir| crate::io::folder_path(cell, dir))); + .chain(doc_dir.map(|dir| crate::io::folder_path(cell, dir))) + .chain(below.into_iter().flat_map(|rest| [data_dir, doc_dir].into_iter().flatten().map(move |dir| crate::io::folder_path(rest, dir)))); let mut out: Vec = Vec::new(); for p in found.flatten() { if !out.contains(&p) { @@ -350,102 +366,20 @@ pub fn status_of(path: &Path, previous: Option) -> SourceStatus { } fn decode_utf8(bytes: &[u8], name: &str) -> Result { - let bytes = bytes.strip_prefix(&[0xEF, 0xBB, 0xBF]).unwrap_or(bytes); - let mut text = String::from_utf8(bytes.to_vec()).map_err(|_| format!("{name} is not UTF-8"))?; - if text.starts_with('\u{FEFF}') { - text.replace_range(..'\u{FEFF}'.len_utf8(), ""); - } - Ok(text) + craft_csv::decode_utf8(bytes).map_err(|_| format!("{name} is not UTF-8")) } fn sniff(name: &str, text: &str) -> Delimiter { - let ext = extension(name); - if ext == "tsv" || ext == "tab" { - return Delimiter::Tab; + match craft_file_formats::detect(name, &[]) { + Some(craft_file_formats::Format::Tsv) => return Delimiter::Tab, + Some(craft_file_formats::Format::Csv) => return Delimiter::Comma, + _ => {} } - if ext == "csv" { - return Delimiter::Comma; + match craft_csv::sniff_delimiter(text, '"') { + b'\t' => Delimiter::Tab, + b';' => Delimiter::Semicolon, + _ => Delimiter::Comma, } - let tab = header_delimiter_candidate(text, '\t'); - let semicolon = header_delimiter_candidate(text, ';'); - let comma = header_delimiter_candidate(text, ','); - // Prefer formats with coherent quoted-field boundaries. If none separates fields, - // retain the legacy permissive choice; this is detection, not record validation. - let prefer_coherent = [&tab, &semicolon, &comma].iter().any(|c| c.found && c.coherent); - let eligible = |c: &HeaderDelimiterCandidate| c.found && (!prefer_coherent || c.coherent); - if eligible(&tab) { - Delimiter::Tab - } else if eligible(&semicolon) && !eligible(&comma) { - Delimiter::Semicolon - } else { - Delimiter::Comma - } -} - -pub fn extension(name: &str) -> String { - Path::new(name).extension().and_then(std::ffi::OsStr::to_str).unwrap_or("").to_ascii_lowercase() -} - -struct HeaderDelimiterCandidate { - found: bool, - coherent: bool, -} - -/// A candidate separator outside quotes in its first nonempty logical record. -/// Only that candidate starts a new field. Quotes in an unquoted field stay literal; -/// Non-whitespace text after a quoted field closes lowers coherence, not validity. -fn header_delimiter_candidate(text: &str, delimiter: char) -> HeaderDelimiterCandidate { - let mut found = false; - let mut coherent = true; - let mut quoted = false; - let mut after_quote = false; - let mut field_start = true; - let mut nonempty = false; - let mut chars = text.chars().peekable(); - while let Some(c) = chars.next() { - if quoted { - if c == '"' { - if chars.peek() == Some(&'"') { - chars.next(); - nonempty = true; - } else { - quoted = false; - after_quote = true; - } - } else if !c.is_whitespace() { - nonempty = true; - } - continue; - } - match c { - '"' if field_start => { - quoted = true; - field_start = false; - } - separator if separator == delimiter => { - found = true; - field_start = true; - after_quote = false; - } - '\r' | '\n' => { - if nonempty { - break; - } - found = false; - coherent = true; - field_start = true; - after_quote = false; - } - _ => { - // Whitespace may follow a closing quote, but does not start a new field - // or allow a later non-whitespace suffix to regain coherence. - coherent &= !after_quote || c.is_whitespace(); - nonempty |= !c.is_whitespace(); - field_start = false; - } - } - } - HeaderDelimiterCandidate { found, coherent: coherent && !quoted } } /// Header cell: trim, drop one leading apostrophe, then `@` is image and `#` is qr. @@ -507,121 +441,59 @@ fn table_from_raw(raw: &[RawRow]) -> Result { Ok(Table { fields, rows, warnings, delimiter: Delimiter::Comma }) } -/// Split `s` on `delim`. Quoted fields keep commas, doubled quotes, and newlines. -/// More than 200 header columns, or the 100,001st non-empty data row, is an error and -/// the oversized row is not kept. +/// Parse delimited text with the shared CSV grammar, then apply DesignCraft's table limits and row policy. fn parse_delimited(s: &str, delim: char) -> Result, String> { - let mut rows: Vec = Vec::new(); - let mut row: Vec = Vec::new(); - let mut field = String::new(); - let mut quoted = false; - let mut field_start = true; + let mut rows = Vec::new(); let mut line = 1usize; - let mut row_line = 1usize; - let mut data_rows = 0usize; - let mut header_width: Option = None; - let mut discarding = false; - let mut chars = s.chars().peekable(); - - let finish = |row: &mut Vec, - field: &mut String, - rows: &mut Vec, - data_rows: &mut usize, - header_width: &mut Option, - row_line: usize, - discarding: &mut bool| - -> Result<(), String> { - if !*discarding { - row.push(std::mem::take(field)); - } else { - field.clear(); - } - *discarding = false; - let empty = row.iter().all(|c| c.trim().is_empty()); - if empty { - row.clear(); - return Ok(()); - } - match *header_width { - None => { - if row.len() > DATA_MERGE_MAX_COLS { - return Err(format!("the file has {} columns; the limit is {DATA_MERGE_MAX_COLS}", row.len())); - } - *header_width = Some(row.len()); - rows.push(RawRow { line: row_line, cells: std::mem::take(row) }); - } - Some(width) => { - *data_rows = data_rows.saturating_add(1); - if *data_rows > DATA_MERGE_MAX_ROWS { - return Err(format!("the file has more than {DATA_MERGE_MAX_ROWS} data rows")); - } - if row.len() > width.saturating_add(1) { - row.truncate(width.saturating_add(1)); - } - rows.push(RawRow { line: row_line, cells: std::mem::take(row) }); - } - } - Ok(()) - }; - - while let Some(c) = chars.next() { - if c == '\n' || (c == '\r' && chars.peek() != Some(&'\n')) { - line = line.saturating_add(1); - } - if quoted { - match c { - '"' if chars.peek() == Some(&'"') => { - if !discarding { - field.push('"'); + let mut error = None; + craft_csv::parse_records(s, delim, '"', DATA_MERGE_MAX_COLS.saturating_add(1), |cells| { + let row_line = line; + let inside_newlines = cells + .iter() + .map(|cell| { + let mut count = 0usize; + let mut previous_cr = false; + for c in cell.chars() { + if c == '\r' { + count = count.saturating_add(1); + previous_cr = true; + } else if c == '\n' { + if !previous_cr { + count = count.saturating_add(1); + } + previous_cr = false; + } else { + previous_cr = false; } - chars.next(); } - '"' => quoted = false, - _ if !discarding => field.push(c), - _ => {} - } - continue; + count + }) + .sum::(); + line = line.saturating_add(inside_newlines).saturating_add(1); + if cells.iter().all(|cell| cell.trim().is_empty()) { + return true; } - if c == delim { - field_start = true; - if discarding { - field.clear(); - continue; - } - row.push(std::mem::take(&mut field)); - if header_width.is_none() && row.len() > DATA_MERGE_MAX_COLS { - return Err(format!("the file has {} columns; the limit is {DATA_MERGE_MAX_COLS}", row.len())); - } - if header_width.is_some_and(|w| row.len() > w.saturating_add(1)) { - row.pop(); - discarding = true; - } - continue; + if rows.is_empty() && cells.len() > DATA_MERGE_MAX_COLS { + error = Some(format!("the file has {} columns; the limit is {DATA_MERGE_MAX_COLS}", cells.len())); + return false; } - match c { - '"' if field_start => { - quoted = true; - field_start = false; - } - '\r' | '\n' => { - if c == '\r' && chars.peek() == Some(&'\n') { - chars.next(); - line = line.saturating_add(1); - } - finish(&mut row, &mut field, &mut rows, &mut data_rows, &mut header_width, row_line, &mut discarding)?; - row_line = line; - field_start = true; - } - _ => { - field_start = false; - if !discarding { - field.push(c); - } - } + if !rows.is_empty() && rows.len() > DATA_MERGE_MAX_ROWS { + error = Some(format!("the file has more than {DATA_MERGE_MAX_ROWS} data rows")); + return false; } + rows.push(RawRow { line: row_line, cells }); + true + }); + if let Some(error) = error { + return Err(error); } - if !field.is_empty() || !row.is_empty() || discarding { - finish(&mut row, &mut field, &mut rows, &mut data_rows, &mut header_width, row_line, &mut discarding)?; + let Some(width) = rows.first().map(|row| row.cells.len()) else { + return Ok(rows); + }; + for row in rows.iter_mut().skip(1) { + if row.cells.len() > width.saturating_add(1) { + row.cells.truncate(width.saturating_add(1)); + } } Ok(rows) } diff --git a/crates/engine/src/cmd/datamerge/tests.rs b/crates/engine/src/cmd/datamerge/tests.rs index 79e16027e..3515d665e 100644 --- a/crates/engine/src/cmd/datamerge/tests.rs +++ b/crates/engine/src/cmd/datamerge/tests.rs @@ -519,6 +519,69 @@ fn typed_fields_keep_style_and_unknown_markers() { assert_eq!(story.format_after(at).over.size, Some(21.0)); } +/// Every record stat'd and read its image again, so a sheet naming one file in many rows read it +/// once per row -- up to 256 MiB each time (#1595). A merge reads a file once and the records +/// share the bytes. +#[test] +fn one_image_named_by_many_records_is_read_once() { + let dir = scratch("image-reads"); + let data = dir.join("data"); + std::fs::create_dir_all(&data).unwrap(); + let shared = dir.join("shared.png"); + write_png(&shared); + // 25 records, all naming the same file. + let rows: String = (0..25).map(|_| format!("{}\n", shared.display())).collect(); + write(&data.join("many.csv"), &format!("@Photo\n{rows}")); + + let mut s = Session::new(); + new_doc(&mut s, 1); + exec(&mut s, "data.source.select", json!({"path": data.join("many.csv")})); + let frame = exec(&mut s, "frame.create", json!({"rect": [36.0, 36.0, 80.0, 80.0], "content": "graphic"})); + exec(&mut s, "data.placeholder.add", json!({"field": "Photo", "item": frame["id"]})); + let r = exec(&mut s, "data.merge", json!({})); + assert_eq!(r["records"], 25); + assert_eq!(r["missingImages"].as_array().map(Vec::len).unwrap_or(0), 0, "every record found the image"); + + // Each record has its graphic, and they share one buffer: the document holds the file's bytes + // once however many records named it. + let doc = &s.documents()[s.active_index().unwrap()].doc; + let graphics: Vec<_> = doc + .spreads + .iter() + .flat_map(|sp| &sp.items) + .filter_map(|it| match &it.content { + Content::Graphic(g) => Some(g.asset), + _ => None, + }) + .collect(); + assert_eq!(graphics.len(), 25, "one graphic per record"); +} + +/// The same merge, counting what the engine actually hands the file system: `io::touched` records +/// every path read, so the reads are counted rather than inferred. The document already shares +/// identical asset bytes, so memory alone does not show this -- the I/O is the bug (#1595). +#[test] +fn a_merge_reads_a_repeated_image_once_not_once_per_record() { + let dir = scratch("image-read-count"); + let data = dir.join("data"); + std::fs::create_dir_all(&data).unwrap(); + let shared = dir.join("shared.png"); + write_png(&shared); + let rows: String = (0..25).map(|_| format!("{}\n", shared.display())).collect(); + write(&data.join("many.csv"), &format!("@Photo\n{rows}")); + + let mut s = Session::new(); + new_doc(&mut s, 1); + exec(&mut s, "data.source.select", json!({"path": data.join("many.csv")})); + let frame = exec(&mut s, "frame.create", json!({"rect": [36.0, 36.0, 80.0, 80.0], "content": "graphic"})); + exec(&mut s, "data.placeholder.add", json!({"field": "Photo", "item": frame["id"]})); + + let (r, seen) = crate::io::touched(|| exec(&mut s, "data.merge", json!({}))); + assert_eq!(r["records"], 25); + let reads = seen.iter().filter(|p| p.ends_with("shared.png")).count(); + assert!(reads <= 2, "the image is read once for the merge, not once per record: {reads} reads for 25 records"); +} + #[test] fn images_resolve_in_order_and_roles_win() { let dir = scratch("images"); @@ -679,12 +742,238 @@ fn role_overrides_column_kind_qr_and_hyperlink() { HyperlinkDest::Email(v) => format!("email:{v}"), HyperlinkDest::Url(v) => format!("url:{v}"), HyperlinkDest::Page(n) => format!("page:{n}"), + HyperlinkDest::Anchor(a) => format!("anchor:{a}"), }); } kinds.sort(); assert_eq!(kinds, vec!["email:a@b.c".to_string(), "url:https://example.com".to_string()]); } +fn write_png_sized(path: &Path, width: u32, height: u32) { + let pixels = vec![255; width as usize * height as usize * 4]; + let bytes = designcraft_render::Rendered { width, height, pixels }.to_png(); + assert_eq!(designcraft_render::image_size(&bytes), Some((width, height)), "the fixture png must decode"); + if let Some(dir) = path.parent() { + std::fs::create_dir_all(dir).unwrap(); + } + std::fs::write(path, bytes).unwrap(); +} + +/// The images anchored in the stories of document `index`, as (file name, width, height), by name. +fn inline_images(s: &Session, index: usize) -> Vec<(String, f64, f64)> { + let doc = &s.documents()[index].doc; + let mut out = Vec::new(); + for st in doc.stories.values() { + for o in &st.objects { + if let Content::Graphic(g) = &o.item.content { + let name = doc.assets.get(&g.asset).map(|a| a.name.clone()).unwrap_or_default(); + let (w, h) = o.size(); + out.push((name, w, h)); + } + } + } + out.sort_by(|a, b| a.0.cmp(&b.0)); + out +} + +/// An image field inserted at a text insertion point placed the path as text. It places the +/// image in the text: at its natural size, scaled down to fit the frame, with a missing file +/// reported and its marker removed. +#[test] +fn an_image_field_at_the_insertion_point_merges_as_an_inline_image() { + let dir = scratch("inline-image"); + let data = dir.join("data"); + write_png_sized(&data.join("pics").join("small.png"), 40, 20); + write_png_sized(&data.join("pics").join("wide.png"), 800, 100); + write(&data.join("cards.csv"), "Name,@Photo\nAda,pics/small.png\nGrace,pics/wide.png\nKai,pics/none.png\n"); + + let mut s = Session::new(); + new_doc(&mut s, 1); + exec(&mut s, "data.source.select", json!({"path": data.join("cards.csv")})); + let made = text_frame(&mut s, [36.0, 36.0, 236.0, 236.0], "Photo: ", None); + exec(&mut s, "text.select", json!({"story": made["story"], "anchor": 7, "focus": 7})); + exec(&mut s, "data.placeholder.add", json!({"field": "Photo"})); + let template = &s.documents()[0].doc; + assert_eq!(template.stories.values().next().unwrap().text, "Photo: <>"); + let width = template.item(designcraft_doc::ItemId(made["id"].as_u64().unwrap())).unwrap().inner_bounds().width(); + + exec(&mut s, "data.preview", json!({"record": 1})); + assert_eq!(inline_images(&s, 0).len(), 1, "the preview shows the image"); + exec(&mut s, "data.preview.stop", json!({})); + + let r = exec(&mut s, "data.merge", json!({})); + assert_eq!(r["records"], 3); + let missing = r["missingImages"].as_array().unwrap(); + assert_eq!(missing.len(), 1, "{missing:?}"); + assert_eq!((missing[0]["record"].as_u64(), missing[0]["path"].as_str()), (Some(3), Some("pics/none.png"))); + let mark = designcraft_doc::OBJECT_MARK; + assert_eq!(texts(&s), vec!["Photo: ".to_string(), format!("Photo: {mark}"), format!("Photo: {mark}")]); + let placed = inline_images(&s, s.active_index().unwrap()); + assert_eq!(placed.len(), 2, "{placed:?}"); + let (small, wide) = (&placed[0], &placed[1]); + assert_eq!(small.0, "small.png"); + assert!((small.1 - 40.0).abs() < 0.01 && (small.2 - 20.0).abs() < 0.01, "a small image keeps its natural size: {small:?}"); + assert_eq!(wide.0, "wide.png"); + assert!((wide.1 - width).abs() < 0.01 && (wide.2 - width / 8.0).abs() < 0.01, "a wide image is scaled down to the frame: {wide:?}"); +} + +/// A QR field at a text insertion point is refused instead of merging its payload as text. +#[test] +fn a_qr_field_at_the_insertion_point_is_refused() { + let mut s = Session::new(); + new_doc(&mut s, 1); + select_csv(&mut s, "@Photo,#Code\n/x.png,hello\n"); + let made = text_frame(&mut s, [36.0, 36.0, 300.0, 300.0], "Hi ", None); + exec(&mut s, "text.select", json!({"story": made["story"], "anchor": 3, "focus": 3})); + let msg = err(&mut s, "data.placeholder.add", json!({"field": "Code"})); + assert!(msg.contains("bind to a frame"), "{msg}"); + assert_eq!(texts(&s), vec!["Hi ".to_string()]); + assert!(s.documents()[0].doc.data_merge.placeholders.is_empty()); +} + +/// An explicit QR role at a text insertion point is refused too, rather than binding the QR code +/// to a selected frame the caret is not in. +#[test] +fn an_explicit_qr_role_at_the_insertion_point_is_refused() { + let mut s = Session::new(); + new_doc(&mut s, 1); + select_csv(&mut s, "Name,#Code\nAda,hello\n"); + let made = text_frame(&mut s, [36.0, 36.0, 300.0, 300.0], "Hi ", None); + let other = text_frame(&mut s, [36.0, 400.0, 300.0, 600.0], "", None); + let other_id = designcraft_doc::ItemId(other["id"].as_u64().unwrap()); + let sid = StoryId(made["story"].as_u64().unwrap()); + let doc = s.doc_mut().unwrap(); + doc.selection = Selection::text(TextSel { story: sid, anchor: 3, focus: 3, frame: None, cell: None }); + doc.selection.items = vec![other_id]; + let msg = err(&mut s, "data.placeholder.add", json!({"field": "Code", "role": "qr"})); + assert!(msg.contains("bind to a frame"), "{msg}"); + let doc = &s.documents()[0].doc; + assert!(doc.data_merge.placeholders.is_empty()); + assert_eq!(doc.item(other_id).unwrap().label, "", "the other frame is not bound"); +} + +/// Fields inserted one after another at the insertion point keep their order: the caret moves +/// past each marker, as after typing. +#[test] +fn fields_inserted_at_the_insertion_point_keep_their_order() { + let mut s = Session::new(); + new_doc(&mut s, 1); + select_csv(&mut s, "Name,City,@Photo\nAda,Paris,/x.png\n"); + let made = text_frame(&mut s, [36.0, 36.0, 300.0, 300.0], "Hi ", None); + exec(&mut s, "text.select", json!({"story": made["story"], "anchor": 3, "focus": 3})); + exec(&mut s, "data.placeholder.add", json!({"field": "Name", "role": "text"})); + exec(&mut s, "data.placeholder.add", json!({"field": "City", "role": "text"})); + exec(&mut s, "data.placeholder.add", json!({"field": "Photo"})); + assert_eq!(texts(&s), vec!["Hi <><><>".to_string()]); + let t = s.documents()[0].selection.text.unwrap(); + assert_eq!((t.anchor, t.focus), (28, 28)); +} + +/// A typed `<>` marker for an image column places the image too, from an absolute path; +/// an explicit text role still writes the path as text. +#[test] +fn a_typed_image_marker_places_the_image_and_a_text_role_keeps_the_path() { + let dir = scratch("typed-image"); + let pic = dir.join("pic.png"); + write_png_sized(&pic, 10, 30); + let mut s = Session::new(); + new_doc(&mut s, 1); + select_csv(&mut s, &format!("@Photo\n{}\n", pic.display())); + text_frame(&mut s, [36.0, 36.0, 300.0, 300.0], "A <> B", None); + let r = exec(&mut s, "data.merge", json!({})); + assert_eq!(r["missingImages"].as_array().map(Vec::len), Some(0)); + assert_eq!(texts(&s), vec![format!("A {} B", designcraft_doc::OBJECT_MARK)]); + let placed = inline_images(&s, s.active_index().unwrap()); + assert_eq!(placed.len(), 1); + assert!((placed[0].1 - 10.0).abs() < 0.01 && (placed[0].2 - 30.0).abs() < 0.01, "{placed:?}"); + + let mut s = Session::new(); + new_doc(&mut s, 1); + select_csv(&mut s, &format!("@Photo\n{}\n", pic.display())); + let made = text_frame(&mut s, [36.0, 36.0, 300.0, 300.0], "", None); + exec(&mut s, "text.select", json!({"story": made["story"], "anchor": 0, "focus": 0})); + exec(&mut s, "data.placeholder.add", json!({"field": "Photo", "role": "text"})); + exec(&mut s, "data.merge", json!({})); + assert_eq!(texts(&s), vec![pic.display().to_string()]); + assert!(inline_images(&s, s.active_index().unwrap()).is_empty()); +} + +/// An explicit image role at a text insertion point places an inline image too, and in a frame +/// with two columns the image is scaled down to one column's width. +#[test] +fn an_inline_image_role_at_text_fits_one_column() { + let dir = scratch("inline-columns"); + let pic = dir.join("wide.png"); + write_png_sized(&pic, 800, 100); + let mut s = Session::new(); + new_doc(&mut s, 1); + select_csv(&mut s, &format!("@Photo\n{}\n", pic.display())); + let made = text_frame(&mut s, [36.0, 36.0, 456.0, 336.0], "", None); + exec(&mut s, "object.textFrameOptions", json!({"ids": [made["id"]], "columns": 2, "gutter": 20})); + exec(&mut s, "text.select", json!({"story": made["story"], "anchor": 0, "focus": 0})); + exec(&mut s, "data.placeholder.add", json!({"field": "Photo", "role": "image"})); + let r = exec(&mut s, "data.merge", json!({})); + assert_eq!(r["missingImages"].as_array().map(Vec::len), Some(0), "{r}"); + let placed = inline_images(&s, s.active_index().unwrap()); + assert_eq!(placed.len(), 1, "{placed:?}"); + // 420 pt wide, less the 20 pt gutter, gives two 200 pt columns. + assert!((placed[0].1 - 200.0).abs() < 0.01 && (placed[0].2 - 25.0).abs() < 0.01, "{placed:?}"); + + // The story threads on into a 100 pt frame: the image fits that one, wherever the marker lands. + let mut s = Session::new(); + new_doc(&mut s, 1); + select_csv(&mut s, &format!("@Photo\n{}\n", pic.display())); + let made = text_frame(&mut s, [36.0, 36.0, 456.0, 336.0], "", None); + let small = exec(&mut s, "frame.create", json!({"rect": [36.0, 400.0, 136.0, 500.0], "content": "unassigned"})); + exec(&mut s, "text.thread", json!({"from": made["id"], "to": small["id"]})); + exec(&mut s, "text.select", json!({"story": made["story"], "anchor": 0, "focus": 0})); + exec(&mut s, "data.placeholder.add", json!({"field": "Photo"})); + exec(&mut s, "data.merge", json!({})); + let placed = inline_images(&s, s.active_index().unwrap()); + assert_eq!(placed.len(), 1, "{placed:?}"); + assert!(placed[0].1 <= 100.0 + 0.01, "{placed:?}"); +} + +/// A cell that starts with one separator (`\pics\a.png`) and names no file from the drive's root +/// is found beside the data file. +#[test] +fn an_image_path_with_a_leading_separator_is_found_beside_the_data_file() { + let dir = scratch("rooted-image"); + let data = dir.join("data"); + write_png_sized(&data.join("dc-merge-rooted-pics").join("a.png"), 12, 12); + write(&data.join("cards.csv"), "@Photo\n\\dc-merge-rooted-pics\\a.png\n/dc-merge-rooted-pics/a.png\n"); + let mut s = Session::new(); + new_doc(&mut s, 1); + exec(&mut s, "data.source.select", json!({"path": data.join("cards.csv")})); + let frame = exec(&mut s, "frame.create", json!({"rect": [36.0, 36.0, 80.0, 80.0], "content": "graphic"})); + exec(&mut s, "data.placeholder.add", json!({"field": "Photo", "item": frame["id"]})); + let r = exec(&mut s, "data.merge", json!({})); + assert_eq!(r["records"], 2); + assert_eq!(r["missingImages"].as_array().map(Vec::len), Some(0), "{r}"); +} + +/// A file at an earlier candidate that is not an image does not hide a valid image at a later +/// one: the search goes on past it. +#[test] +fn a_non_image_file_beside_the_data_does_not_hide_the_image_beside_the_document() { + let dir = scratch("undecodable-image"); + let (data, docs) = (dir.join("data"), dir.join("docs")); + write(&data.join("pics").join("a.png"), "not an image"); + write_png_sized(&docs.join("pics").join("a.png"), 12, 12); + write(&data.join("cards.csv"), "@Photo\npics/a.png\n"); + let mut s = Session::new(); + new_doc(&mut s, 1); + exec(&mut s, "data.source.select", json!({"path": data.join("cards.csv")})); + exec(&mut s, "file.save", json!({"path": docs.join("layout.designcraft")})); + let frame = exec(&mut s, "frame.create", json!({"rect": [36.0, 36.0, 80.0, 80.0], "content": "graphic"})); + exec(&mut s, "data.placeholder.add", json!({"field": "Photo", "item": frame["id"]})); + exec(&mut s, "data.options", json!({"linkImages": true})); + let r = exec(&mut s, "data.merge", json!({})); + assert_eq!(r["missingImages"].as_array().map(Vec::len), Some(0), "{r}"); + let link = graphic_link(&s).unwrap_or_default(); + assert!(link.contains("docs"), "{link}"); +} + #[test] fn single_record_merge_copies_pages_and_leaves_the_template() { let mut s = Session::new(); @@ -790,6 +1079,30 @@ fn tiling_rows_first_bottom_inset_and_refusals() { assert_eq!(s.documents().len(), before); } +/// A two-page template merged for three records: six pages made in one insertion, each record's +/// frame on its own pages, in record order. +#[test] +fn a_two_page_template_merges_onto_consecutive_pages() { + let mut s = Session::new(); + new_doc(&mut s, 2); + text_frame(&mut s, [72.0, 72.0, 172.0, 172.0], "<>", None); + select_csv(&mut s, "Name\nA\nB\nC\n"); + let r = exec(&mut s, "data.merge", json!({})); + assert_eq!(r["pages"], 6); + let d = &s.documents()[s.active_index().unwrap()].doc; + assert_eq!(d.page_count(), 6); + let mut at: Vec<(usize, String)> = Vec::new(); + for st in d.stories.values() { + let f = d.item(*st.frames.first().unwrap()).unwrap(); + let sp = d.spreads.iter().position(|sp| sp.items.iter().any(|i| i.id == f.id)).unwrap(); + let page = d.first_page_of_spread(sp) + d.spreads[sp].page_at_x(f.bounds().center().x).unwrap_or(0); + at.push((page, st.text.clone())); + } + at.sort(); + assert_eq!(at, vec![(0, "A".to_string()), (2, "B".to_string()), (4, "C".to_string())]); + d.check().unwrap(); +} + /// An IME delete-surrounding while a record is previewed edits the template, not the filled /// record, and its undo step restores the template. #[test] @@ -1116,6 +1429,14 @@ fn select_records_dedupes_large_ranges_in_first_seen_order() { assert_eq!(&idx[..3], &[4, 0, 1]); } +#[test] +fn select_records_rejects_signed_record_numbers() { + for (tok, bad) in [("+2", "+2"), ("1-+3", "+3"), ("+1,+4", "+1")] { + let err = parse::select_records(5, "range", 1, tok, None).unwrap_err(); + assert!(err.contains(&format!("bad record \"{bad}\"")), "{tok}: {err}"); + } +} + #[test] fn oversized_data_file_is_refused_before_reading() { let dir = scratch("oversized"); @@ -1198,3 +1519,333 @@ fn facing_pages_merge_tiles_short_blocks_without_stacking() { let unique: std::collections::BTreeSet<_> = origins.iter().collect(); assert_eq!(unique.len(), 3, "no two records may share a page and coordinates: {origins:?}"); } + +// #1522: each record's copy of an anchored object needs its own id, or the merged file won't reopen. +#[test] +fn merged_records_give_anchored_objects_their_own_ids() { + let mut s = Session::new(); + new_doc(&mut s, 1); + select_csv(&mut s, "Name\nAda\nGrace\n"); + let made = text_frame(&mut s, [36.0, 36.0, 400.0, 80.0], "<> here", None); + let b = exec(&mut s, "frame.create", json!({"rect": [450, 450, 474, 490]})); + exec(&mut s, "anchored.insert", json!({"ids": [b["id"]], "story": made["story"], "pos": 2})); + assert_eq!(exec(&mut s, "data.merge", json!({}))["records"], 2); + let doc = &s.documents()[s.active_index().unwrap()].doc; + assert_eq!(doc.anchored_items().len(), 2); + doc.check().unwrap(); + designcraft_format::load(&designcraft_format::save(doc).unwrap()).unwrap(); +} + +/// A record previewed into an image placeholder whose frame wraps with an Alpha Channel contour +/// gets the image's outline, as an edit would. +#[test] +fn a_previewed_image_gets_its_alpha_channel_outline() { + let dir = scratch("alpha-preview"); + let mut pixels = vec![0u8; 64 * 64 * 4]; + for y in 0..64 { + for x in 16..48 { + pixels[(y * 64 + x) * 4 + 3] = 255; + } + } + std::fs::write(dir.join("cut.png"), designcraft_render::Rendered { width: 64, height: 64, pixels }.to_png()).unwrap(); + write(&dir.join("pics.csv"), "Photo\ncut.png\n"); + let mut s = Session::new(); + new_doc(&mut s, 1); + exec(&mut s, "data.source.select", json!({"path": dir.join("pics.csv")})); + let frame = exec(&mut s, "frame.create", json!({"rect": [0.0, 0.0, 200.0, 100.0], "content": "graphic"})); + exec(&mut s, "data.placeholder.add", json!({"field": "Photo", "role": "image", "item": frame["id"]})); + exec(&mut s, "object.textWrap", json!({"ids": [frame["id"]], "mode": "contour", "contour": "alphaChannel"})); + assert!(s.doc().unwrap().doc.alpha_outlines.is_empty(), "no image placed yet"); + exec(&mut s, "data.preview", json!({"record": 1})); + let d = &s.doc().unwrap().doc; + assert_eq!(d.alpha_outlines.len(), 1, "the previewed image is traced"); + assert!(d.alpha_outlines[0].width > 0 && !d.alpha_outlines[0].outer.subpaths.is_empty()); + let _ = std::fs::remove_dir_all(&dir); +} + +/// The overset count data merge reports is composed with the merged images' Alpha Channel +/// outlines: a caption over the image's transparent part is set, not counted as overset. With a +/// bounding box wrap the same caption is overset, so the count depends on the outline. +#[test] +fn a_merge_counts_overset_text_with_the_merged_images_outlines() { + let (r, outlines) = merge_with_wrap("alpha-merge", json!({"mode": "contour", "contour": "alphaChannel", "offset": 0})); + assert_eq!(r["oversetStories"], 0, "the caption sits beside the image's visible pixels: {r}"); + assert_eq!(outlines, 1, "the merged document has the image's outline"); + let (r, _) = merge_with_wrap("alpha-merge-box", json!({"mode": "boundingBox", "offset": 0})); + assert_eq!(r["oversetStories"], 1, "the image's frame covers the caption: {r}"); +} + +/// Merges one record whose image is visible only in its left quarter into a graphic placeholder +/// with the text wrap `wrap`, beside a caption over the image's transparent part. Returns the +/// merge's answer and the number of nonempty Alpha Channel outlines in the merged document. +fn merge_with_wrap(name: &str, wrap: Value) -> (Value, usize) { + let dir = scratch(name); + // Visible only in the left quarter. + let mut pixels = vec![0u8; 64 * 64 * 4]; + for y in 0..64 { + for x in 0..16 { + pixels[(y * 64 + x) * 4 + 3] = 255; + } + } + std::fs::write(dir.join("cut.png"), designcraft_render::Rendered { width: 64, height: 64, pixels }.to_png()).unwrap(); + write(&dir.join("pics.csv"), "Photo\ncut.png\n"); + let mut s = Session::new(); + new_doc(&mut s, 1); + exec(&mut s, "data.source.select", json!({"path": dir.join("pics.csv")})); + let frame = exec(&mut s, "frame.create", json!({"rect": [100.0, 100.0, 300.0, 300.0], "content": "graphic"})); + exec(&mut s, "data.placeholder.add", json!({"field": "Photo", "role": "image", "item": frame["id"]})); + exec(&mut s, "data.options", json!({"fitting": "fitContentToFrame"})); + let mut params = wrap; + params["ids"] = json!([frame["id"]]); + exec(&mut s, "object.textWrap", params); + text_frame(&mut s, [220.0, 180.0, 290.0, 220.0], "Hi", None); + let r = exec(&mut s, "data.merge", json!({})); + let doc = &s.documents()[s.active_index().unwrap()].doc; + let outlines = doc.alpha_outlines.iter().filter(|o| o.width > 0 && !o.outer.subpaths.is_empty()).count(); + let _ = std::fs::remove_dir_all(&dir); + (r, outlines) +} + +/// The cell texts of the first table in the active document's first story that has one. +fn cell_texts(s: &Session) -> Vec { + let doc = &s.documents()[s.active_index().unwrap()].doc; + let t = doc.stories.values().find_map(|st| st.tables.values().next().cloned()).expect("a table"); + t.cells.iter().map(|c| c.text.text.clone()).collect() +} + +/// A field inserted with the insertion point in a table cell goes into that cell, and the +/// preview and the merge fill it. The cell's offsets used to put the marker in the table's own +/// story, outside the table, and the merge never read a cell's text (#2315). +#[test] +fn a_field_inserted_in_a_table_cell_goes_there_and_is_filled() { + let mut s = Session::new(); + new_doc(&mut s, 1); + select_csv(&mut s, "Name,City\nAda,London\nGrace,Arlington\n"); + let made = text_frame(&mut s, [36.0, 36.0, 400.0, 200.0], "Who\tWhere", None); + exec(&mut s, "text.select", json!({"story": made["story"], "anchor": 0, "focus": 9})); + exec(&mut s, "table.convertFromText", json!({"columnSeparator": "tab"})); + let story_text = |s: &Session| s.documents()[s.active_index().unwrap()].doc.stories.values().next().unwrap().text.clone(); + let before = story_text(&s); + exec(&mut s, "table.select", json!({"story": made["story"], "rows": [0, 0], "cols": [1, 1]})); + let r = exec(&mut s, "data.placeholder.add", json!({"field": "City"})); + assert_eq!(r["marker"], "<>", "{r}"); + assert_eq!(cell_texts(&s), ["Who", "<>Where"], "the marker is in the cell with the caret"); + assert_eq!(story_text(&s), before, "and not in the table's story"); + + exec(&mut s, "data.preview", json!({"record": 2})); + assert_eq!(cell_texts(&s), ["Who", "ArlingtonWhere"], "the preview fills the cell"); + exec(&mut s, "data.preview.stop", json!({})); + assert_eq!(cell_texts(&s), ["Who", "<>Where"], "stopping it puts the marker back"); + exec(&mut s, "data.merge", json!({})); + let merged = &s.documents()[s.active_index().unwrap()].doc; + let mut cities: Vec = + merged.stories.values().flat_map(|st| st.tables.values().map(|t| t.cells[1].text.text.clone()).collect::>()).collect(); + cities.sort(); + assert_eq!(cities, ["ArlingtonWhere", "LondonWhere"], "one table per record, filled"); +} + +/// A field typed (or inserted) in text that is then converted to a table is filled in its cell. +#[test] +fn a_field_converted_into_a_table_is_filled_in_its_cell() { + let mut s = Session::new(); + new_doc(&mut s, 1); + select_csv(&mut s, "Name,City\nAda,London\n"); + let made = text_frame(&mut s, [36.0, 36.0, 400.0, 200.0], "Name\t<>", None); + exec(&mut s, "text.select", json!({"story": made["story"], "anchor": 0, "focus": 13})); + exec(&mut s, "table.convertFromText", json!({"columnSeparator": "tab"})); + assert_eq!(cell_texts(&s), ["Name", "<>"]); + assert_eq!(exec(&mut s, "data.fields", json!({}))[0]["uses"], 1); + exec(&mut s, "data.preview", json!({"record": 1})); + assert_eq!(cell_texts(&s), ["Name", "Ada"], "the field is filled in its cell"); + assert_eq!(exec(&mut s, "data.fields", json!({}))[0]["uses"], 1, "the count reads the unfilled template while previewing"); +} + +/// A table `Who⇥Where` with the caret in its second cell, and a source with `Name` and `City`. +fn table_with_caret_in_cell(s: &mut Session, csv: &str) -> Value { + new_doc(s, 1); + select_csv(s, csv); + let made = text_frame(s, [36.0, 36.0, 400.0, 200.0], "Who\tWhere", None); + exec(s, "text.select", json!({"story": made["story"], "anchor": 0, "focus": 9})); + exec(s, "table.convertFromText", json!({"columnSeparator": "tab"})); + exec(s, "table.select", json!({"story": made["story"], "rows": [0, 0], "cols": [1, 1]})); + made +} + +/// After a field goes into a cell the caret is after it, in that cell, and the cell selection is +/// gone: typing goes on after the field instead of replacing the cell, field and all. +#[test] +fn typing_after_a_field_inserted_in_a_cell_goes_on_after_it() { + let mut s = Session::new(); + table_with_caret_in_cell(&mut s, "Name,City\nAda,London\n"); + exec(&mut s, "data.placeholder.add", json!({"field": "City"})); + let sel = &s.documents()[s.active_index().unwrap()].selection; + assert!(sel.cells.is_none(), "no cell selection left"); + exec(&mut s, "text.insert", json!({"text": ", "})); + assert_eq!(cell_texts(&s), ["Who", "<>, Where"]); +} + +/// A position that a merged cell covers is the merged cell's: the field goes into the merged cell, +/// where it shows, not into the hidden one under it. +#[test] +fn a_field_inserted_in_a_merged_cell_goes_where_it_shows() { + let mut s = Session::new(); + let made = table_with_caret_in_cell(&mut s, "Name,City\nAda,London\n"); + exec(&mut s, "table.merge", json!({"story": made["story"], "rows": [0, 0], "cols": [0, 1]})); + exec(&mut s, "table.select", json!({"story": made["story"], "rows": [0, 0], "cols": [1, 1]})); + exec(&mut s, "data.placeholder.add", json!({"field": "City"})); + let cells = cell_texts(&s); + assert!(cells[0].contains("<>"), "in the merged cell: {cells:?}"); + assert!(!cells[1].contains("<>"), "not in the covered one: {cells:?}"); + exec(&mut s, "data.preview", json!({"record": 1})); + assert!(cell_texts(&s)[0].contains("London"), "and filled: {:?}", cell_texts(&s)); +} + +/// A field whose name a marker can't hold (it has `<` or `>`) can't be filled from a cell, so it +/// isn't inserted there; in body text it still becomes an anchored placeholder. +#[test] +fn a_field_named_with_angle_brackets_is_refused_in_a_cell() { + let mut s = Session::new(); + let made = table_with_caret_in_cell(&mut s, "Customer ,City\n7,London\n"); + let e = s.execute("data.placeholder.add", &json!({"field": "Customer "})).expect_err("refused").to_string(); + assert!(e.contains("can't be inserted in a table cell"), "{e}"); + assert_eq!(cell_texts(&s), ["Who", "Where"], "nothing inserted"); + let other = text_frame(&mut s, [36.0, 300.0, 400.0, 400.0], "No. ", None); + exec(&mut s, "text.select", json!({"story": other["story"], "anchor": 4, "focus": 4})); + assert!(exec(&mut s, "data.placeholder.add", json!({"field": "Customer "}))["id"].is_u64(), "body text still takes it"); + let _ = made; +} + +/// An image field with the insertion point in a table cell is refused with a message about image +/// fields, and nothing is inserted; with role text its marker goes into the cell. +#[test] +fn an_image_field_in_a_cell_is_refused_unless_its_role_is_text() { + let mut s = Session::new(); + table_with_caret_in_cell(&mut s, "Name,@Photo\nAda,pics/a.png\n"); + for params in [json!({"field": "Photo"}), json!({"field": "Photo", "role": "image"})] { + let e = s.execute("data.placeholder.add", ¶ms).expect_err("refused").to_string(); + assert!(e.contains("an image field can't go in a table cell or a note"), "{e}"); + assert!(!e.contains("hyperlink"), "{e}"); + assert_eq!(cell_texts(&s), ["Who", "Where"], "nothing inserted"); + } + let r = exec(&mut s, "data.placeholder.add", json!({"field": "Photo", "role": "text"})); + assert_eq!(r["marker"], "<>", "{r}"); + assert_eq!(cell_texts(&s), ["Who", "<>Where"]); + exec(&mut s, "data.preview", json!({"record": 1})); + assert_eq!(cell_texts(&s), ["Who", "pics/a.pngWhere"], "the text role merges the path"); +} + +/// Endnote text is filled too: it is a text inside its story, like a footnote's. +#[test] +fn a_field_in_an_endnote_is_filled() { + let mut s = Session::new(); + new_doc(&mut s, 1); + select_csv(&mut s, "Name,City\nAda,London\n"); + let made = text_frame(&mut s, [36.0, 36.0, 400.0, 200.0], "See the note", None); + exec(&mut s, "text.select", json!({"story": made["story"], "anchor": 12, "focus": 12})); + exec(&mut s, "endnote.insert", json!({"text": "From <>"})); + let endnotes = |s: &Session| -> Vec { + s.documents()[s.active_index().unwrap()].doc.stories.values().flat_map(|st| st.endnotes.iter().map(|e| e.text.text.clone())).collect() + }; + assert_eq!(endnotes(&s), ["From <>"]); + assert_eq!(exec(&mut s, "data.fields", json!({}))[1]["uses"], 1); + exec(&mut s, "data.preview", json!({"record": 1})); + assert_eq!(endnotes(&s), ["From London"]); +} + +/// Tables nested in cells far deeper than any document goes are filled down to the merge's depth +/// limit, and the preview returns instead of exhausting the stack. +#[test] +fn deeply_nested_tables_are_filled_down_to_the_limit_without_overflowing() { + use designcraft_doc::{Cell, ParaFormat, Table}; + let mut s = Session::new(); + new_doc(&mut s, 1); + select_csv(&mut s, "Name,City\nAda,London\n"); + let made = text_frame(&mut s, [36.0, 36.0, 400.0, 200.0], "x", None); + let sid = StoryId(made["story"].as_u64().unwrap()); + // `depth` tables, each in the one cell of the next, each cell's own text `<>`. + let nest = |depth: usize| { + let mut inner: Option
= None; + for i in 0..depth { + let mut t = Table::new(1000 + i as u64, 1, 1, 0, 0, 100.0); + t.cells[0] = Cell::with_text("<>", ParaFormat::default()); + if let Some(child) = inner.take() { + t.cells[0].text.insert_table(0, child); + } + inner = Some(t); + } + inner.unwrap() + }; + s.edit(|d, _| { + d.story_mut(sid).unwrap().insert_table(0, nest(500)); + Ok(()) + }) + .unwrap(); + exec(&mut s, "data.preview", json!({"record": 1})); + let doc = &s.documents()[s.active_index().unwrap()].doc; + let mut t = doc.story(sid).unwrap().tables.values().next().unwrap().clone(); + let mut filled = Vec::new(); + for _ in 0..40 { + filled.push(t.cells[0].text.text.contains("Ada")); + let Some(next) = t.cells[0].text.tables.values().next().cloned() else { break }; + t = next; + } + assert!(filled[..super::fill::MAX_NESTED_DEPTH].iter().all(|f| *f), "filled down to the limit: {filled:?}"); + assert!(!filled[super::fill::MAX_NESTED_DEPTH], "and not past it"); +} + +#[test] +fn select_records_stops_expanding_once_the_limit_is_met_but_still_checks_every_range() { + // 4 billion records in a range would not finish if it were expanded; the limit stops it. + let idx = parse::select_records(u32::MAX as usize, "range", 1, "1-3,1-4294967295,2-4294967295", Some(5)).unwrap(); + assert_eq!(idx, vec![0, 1, 2, 3, 4]); + // A later token that is out of range is still an error. + assert!(parse::select_records(10, "range", 1, "1-10,5-11", Some(2)).is_err()); + assert!(parse::select_records(10, "range", 1, "1-2,0", Some(2)).is_err()); +} + +#[test] +fn idml_reopen_relink_counts_existing_text_field() { + let dir = scratch("idml-field-count"); + let csv = dir.join("people.csv"); + let idml = dir.join("template.idml"); + write(&csv, "Name\nAda\n"); + let mut s = Session::new(); + new_doc(&mut s, 1); + text_frame(&mut s, [36.0, 36.0, 240.0, 80.0], "", None); + exec(&mut s, "data.source.select", json!({"path": csv})); + exec(&mut s, "data.placeholder.add", json!({"field": "Name"})); + assert_eq!(exec(&mut s, "data.fields", json!({}))[0]["uses"], 1); + exec(&mut s, "file.exportIdml", json!({"path": idml})); + let mut reopened = Session::new(); + exec(&mut reopened, "file.openIdml", json!({"path": idml})); + exec(&mut reopened, "data.source.select", json!({"path": csv})); + let uses = exec(&mut reopened, "data.fields", json!({}))[0]["uses"].clone(); + exec(&mut reopened, "data.merge", json!({})); + assert!(texts(&reopened).contains(&"Ada".to_string())); + assert_eq!(uses, 1); +} + +#[test] +fn fields_count_unbound_markers_without_double_counting_bound_placeholders() { + let mut s = Session::new(); + new_doc(&mut s, 1); + select_csv(&mut s, "Name\nAda\n"); + text_frame(&mut s, [36.0, 36.0, 240.0, 80.0], "<> <>", None); + text_frame(&mut s, [36.0, 100.0, 240.0, 150.0], "", None); + exec(&mut s, "data.placeholder.add", json!({"field": "Name"})); + assert_eq!(exec(&mut s, "data.fields", json!({}))[0]["uses"], 3); + assert_eq!(exec(&mut s, "data.fields", json!({"csv": "Name\nAda\n"}))[0]["uses"], 0); +} + +#[test] +fn hyperlink_over_marker_does_not_hide_its_field_usage() { + let mut s = Session::new(); + new_doc(&mut s, 1); + select_csv(&mut s, "Name,Link\nAda,https://example.com\n"); + let made = text_frame(&mut s, [36.0, 36.0, 240.0, 80.0], "<>", None); + exec(&mut s, "text.select", json!({"story": made["story"], "anchor": 0, "focus": 8})); + exec(&mut s, "data.placeholder.add", json!({"field": "Link", "role": "hyperlink"})); + let fields = exec(&mut s, "data.fields", json!({})); + assert_eq!(fields[0]["uses"], 1); + assert_eq!(fields[1]["uses"], 1); +} diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 890974f32..9b2ac1a1c 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -8,6 +8,21 @@ use serde_json::{Value, json}; use super::{CommandSpec, bool_or, cmd, has_doc, has_selection, ids_param, ok}; use crate::{HistoryEntry, Result, Session}; +/// `anchors` of `selection.set`: the points that exist, once each. +fn anchors_param(doc: &designcraft_doc::Document, p: &Value) -> Vec<(ItemId, usize, usize)> { + let mut out: Vec<(ItemId, usize, usize)> = Vec::new(); + for v in p.get("anchors").and_then(Value::as_array).into_iter().flatten() { + let n = |i: usize| v.get(i).and_then(Value::as_u64); + let (Some(id), Some(si), Some(ai)) = (n(0), n(1), n(2)) else { continue }; + let (Ok(si), Ok(ai)) = (usize::try_from(si), usize::try_from(ai)) else { continue }; + let a = (ItemId(id), si, ai); + if doc.item(a.0).is_some_and(|it| it.path.subpaths.get(si).is_some_and(|sp| ai < sp.anchors.len())) && !out.contains(&a) { + out.push(a); + } + } + out +} + fn can_undo(s: &Session) -> std::result::Result<(), String> { s.active().filter(|d| !d.history.undo.is_empty()).map(|_| ()).ok_or_else(|| "nothing to undo".into()) } @@ -39,10 +54,44 @@ fn copy_text(s: &mut Session) -> Result> { let Some(story) = st.doc.text_story(t.story, t.cell) else { return Ok(None) }; let slice = story.extract(t.range()); let text = plain(&slice); - s.text_clipboard = Some((Arc::new(slice), text.clone())); + // Anchored text frames take their stories along, and graphics their files. + let source = text_source(&st.doc, &slice); + s.text_clipboard = Some((Arc::new(slice), text.clone(), Arc::new(source))); Ok(Some(text)) } +/// What pasting `slice` (text copied from `doc`) needs from `doc`, also in another document: the +/// stories its anchored text frames show (and theirs) and the graphics it and those stories +/// place. Nothing on spreads. +fn text_source(doc: &designcraft_doc::Document, slice: &designcraft_doc::Story) -> designcraft_doc::Document { + let mut d = doc.clone(); + d.stories = doc.anchored_stories(slice); + let used: std::collections::HashSet = + std::iter::once(slice).chain(d.stories.values().map(|st| &**st)).flat_map(designcraft_doc::story_asset_refs).collect(); + d.assets.retain(|id, _| used.contains(id)); + for sp in d.spreads.iter_mut().chain(d.parents.iter_mut()) { + Arc::make_mut(sp).items.clear(); + } + d +} + +/// Copied text `slice` pasted into `d`: the graphics it places (from `src`, its +/// [`text_source`]) under `d`'s ids, since `src`'s may name other files in another document; +/// fresh ids for its anchored items and copies of the stories its anchored text frames show. +fn adopt_text(d: &mut designcraft_doc::Document, slice: &mut designcraft_doc::Story, src: &designcraft_doc::Document) { + let refs: std::collections::BTreeSet = designcraft_doc::story_asset_refs(slice).into_iter().collect(); + let mut map = std::collections::HashMap::new(); + for a in refs { + // A graphic missing there stays missing: a fresh id, not one that may name a file here. + let here = d.adopt_asset(src, a).unwrap_or_else(|| designcraft_doc::AssetId(d.alloc())); + if here != a { + map.insert(a, here); + } + } + designcraft_doc::remap_story_assets(slice, &map); + d.adopt_anchored_from(slice, src); +} + /// Plain text for the system clipboard after copying objects: the copied text frames' stories, /// or U+FFFC (object replacement character) when none has text. Paste reads it back as "the /// copied objects", not as text. @@ -86,43 +135,56 @@ fn paste_text(s: &mut Session, text: Option, formatted: bool) -> Result< return s.edit(|d, sel| { let st = d.story_mut(t.story).ok_or(designcraft_doc::DocError::NoStory(t.story))?; let r = t.range(); - st.delete(r.start.min(st.len())..r.end.min(st.len())); + let del = r.start.min(st.len())..r.end.min(st.len()); + st.delete(del.clone()); + d.adjust_text_ranges(t.story, del, 0); // Fresh ids, story and asset copies for every paste, as on the page. let mut stories = std::collections::HashMap::new(); let fresh: Vec = list .iter() - .map(|i| { - let mut i = i.clone(); - super::object::renumber(d, &items, &mut i, &mut stories); + .map(|orig| { + let mut i = orig.clone(); + if !super::object::renumber(d, &items, &mut i, &mut stories) { + return Err(designcraft_doc::DocError::Invalid(format!("{} nests groups or tables too deeply to copy", orig.id))); + } if d.layer(i.layer).is_none() { i.layer = d.default_layer(); } - i + Ok(i) }) - .collect(); + .collect::>()?; + super::object::retarget_copied_xrefs(d, &items, &stories); let end = super::anchored::anchor_items(d, t.story, r.start, fresh, &Default::default())?; sel.text = Some(designcraft_doc::TextSel { anchor: end, focus: end, ..t }); Ok(json!({"pos": end, "anchored": list.len()})) }); } } - let use_clip = formatted && clip.as_ref().is_some_and(|(_, p)| text.as_ref().is_none_or(|x| x.replace("\r\n", "\n") == *p)); + let use_clip = formatted && clip.as_ref().is_some_and(|(_, p, _)| text.as_ref().is_none_or(|x| x.replace("\r\n", "\n") == *p)); // Footnotes, endnotes, editorial notes, cross-references and tables cannot be pasted into cells or footnotes. - if use_clip && let Some((slice, _)) = clip { - let slice = if t.cell.is_some() { strip_objects(&slice) } else { (*slice).clone() }; + if use_clip && let Some((slice, _, source)) = clip { + let mut slice = if t.cell.is_some() { strip_objects(&slice) } else { (*slice).clone() }; return s.edit(|d, sel| { - let st = d.text_story_mut(t.story, t.cell).ok_or(designcraft_doc::DocError::NoStory(t.story))?; - let r = t.range(); - let r = r.start.min(st.len())..r.end.min(st.len()); - st.delete(r.clone()); - let end = st.insert_story(r.start, &slice); + adopt_text(d, &mut slice, &source); + let slice_len = slice.text.len(); + let (end, r) = { + let st = d.text_story_mut(t.story, t.cell).ok_or(designcraft_doc::DocError::NoStory(t.story))?; + let r = t.range(); + let r = r.start.min(st.len())..r.end.min(st.len()); + st.delete(r.clone()); + let end = st.insert_story(r.start, &slice); + (end, r) + }; + if t.cell.is_none() { + d.adjust_text_ranges(t.story, r, slice_len); + } sel.text = Some(designcraft_doc::TextSel { anchor: end, focus: end, ..t }); Ok(json!({"pos": end, "formatted": true})) }); } // U+FFFC stands for objects with no text. let text = if own { Some(copied_objects_text(s)).filter(|m| m != "\u{FFFC}") } else { text }; - let text = text.or_else(|| clip.map(|(_, p)| p)).ok_or_else(|| super::bad("edit.paste", "clipboard is empty"))?; + let text = text.or_else(|| clip.map(|(_, p, _)| p)).ok_or_else(|| super::bad("edit.paste", "clipboard is empty"))?; let text = outside_text(&text)?; s.execute("text.insert", &json!({"text": text, "raw": true})) } @@ -138,8 +200,9 @@ fn outside_text(text: &str) -> Result { /// Pasted text with no insertion point: a new text frame holding it, as wide as the first column /// of the page's margin area and as tall as the text (at most the margin area's height), centred /// on `at` (spread coordinates) or else on the margin area. The frame ends up selected. With -/// `slice` (the text copied here), the frame's story is that formatted copy. -fn paste_text_frame(s: &mut Session, p: &Value, text: &str, slice: Option<&designcraft_doc::Story>) -> Result { +/// `slice` (the text copied here, with its [`text_source`]), the frame's story is that formatted +/// copy. +fn paste_text_frame(s: &mut Session, p: &Value, text: &str, slice: Option<(&designcraft_doc::Story, &designcraft_doc::Document)>) -> Result { use designcraft_geom::{Point, Rect, shapes}; const LIMIT: f64 = 1.0e5; let sr = super::spread_param(p, "edit.paste")?; @@ -159,13 +222,15 @@ fn paste_text_frame(s: &mut Session, p: &Value, text: &str, slice: Option<&desig let max_h = margins.height().max(12.0); let c = at.unwrap_or(Point::new(column.center().x, margins.center().y)); let rect = |h: f64| Rect::new(c.x - w / 2.0, c.y - h / 2.0, c.x + w / 2.0, c.y + h / 2.0); - let para = match slice.and_then(|sl| sl.paras.first()) { + let para = match slice.and_then(|(sl, _)| sl.paras.first()) { Some(pf) => designcraft_doc::ParaFormat { table: None, ..pf.clone() }, None => designcraft_doc::ParaFormat { style: d.styles.default_paragraph.clone(), ..Default::default() }, }; let (id, sid) = d.add_text_frame(sr, rect(max_h), lid, &text, para)?; - if let Some(sl) = slice { - d.story_mut(sid).ok_or(designcraft_doc::DocError::NoStory(sid))?.insert_story(0, sl); + if let Some((sl, source)) = slice { + let mut sl = sl.clone(); + adopt_text(d, &mut sl, source); + d.story_mut(sid).ok_or(designcraft_doc::DocError::NoStory(sid))?.insert_story(0, &sl); } // Shrink to the composed text unless it already fills the frame. let composed = cache.get(d, sid, None); @@ -235,20 +300,36 @@ pub fn specs() -> Vec { s.typing_format = None; Ok(json!({"redone": e.label})) }), - cmd!(noundo "selection.set", "Select", [], None, "{ids: [id], add?: bool, content?: bool}", has_doc, |s, p| { - let ids = ids_param(p, "ids").unwrap_or_default(); + cmd!(noundo "selection.set", "Select", [], None, "{ids: [id], add?: bool, content?: bool, anchors?: [[id, subpath, index]] (Direct Selection: the selected anchor points; their paths are selected too)}", has_doc, |s, p| { + let mut ids = ids_param(p, "ids").unwrap_or_default(); let add = bool_or(p, "add", false); let content = bool_or(p, "content", false); let st = s.doc_mut()?; + let anchors = anchors_param(&st.doc, p); + for (id, _, _) in &anchors { + if !ids.contains(id) { + ids.push(*id); + } + } let ids: Vec = ids.into_iter().filter(|i| st.doc.item(*i).is_some()).collect(); if add { + // Adding objects (no points) leaves no live points: Delete would otherwise remove + // the stale points instead of the objects. + if anchors.is_empty() { + st.selection.anchors.clear(); + } for i in ids { if !st.selection.items.contains(&i) { st.selection.items.push(i); } } + for a in anchors { + if !st.selection.anchors.contains(&a) { + st.selection.anchors.push(a); + } + } } else { - st.selection = Selection { items: ids, content, ..Default::default() }; + st.selection = Selection { items: ids, content, anchors, ..Default::default() }; } st.selection.text = None; st.selection.cells = None; @@ -262,12 +343,15 @@ pub fn specs() -> Vec { st.selection.cells = None; if let Some(i) = st.selection.items.iter().position(|x| *x == id) { st.selection.items.remove(i); + // Its points go with it: arrow keys and Delete act on the selected points. + st.selection.anchors.retain(|a| a.0 != id); // A key object needs another object to align to it. if st.selection.key == Some(id) || st.selection.items.len() < 2 { st.selection.key = None; } } else { st.selection.items.push(id); + st.selection.anchors.clear(); } st.bump_revision(); ok() @@ -320,7 +404,7 @@ pub fn specs() -> Vec { "Clear", ["Edit"], Some("Delete"), - "{ids?} — delete selected items (or the selected text or ruler guides)", + "{ids?} — delete selected items (or the selected text, points or ruler guides)", has_doc, |s, p| { if s.doc()?.selection.text.is_some() && p.get("ids").is_none() { @@ -329,6 +413,10 @@ pub fn specs() -> Vec { if p.get("ids").is_none() && s.doc()?.selection.items.is_empty() && !s.doc()?.selection.guides.is_empty() { return s.execute("guide.delete", &json!({})); } + // Points selected with Direct Selection: they go, not their paths (as InDesign). + if p.get("ids").is_none() && !s.doc()?.selection.anchors.is_empty() { + return s.execute("path.deletePoints", &json!({})); + } let ids = super::targets(s, p)?; // With a placed graphic itself selected (Direct Selection), only the graphic goes: its // frame stays, empty and selected (as in InDesign). Other items are deleted. @@ -362,6 +450,11 @@ pub fn specs() -> Vec { return Ok(json!({"text": text})); } 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 ids: Vec = s.doc()?.selection.items.iter().map(|i| i.0).collect(); + return s.execute("edit.clear", &json!({"ids": ids})); + } s.execute("edit.clear", p) }), cmd!( @@ -389,8 +482,8 @@ pub fn specs() -> Vec { // The placeholder of an object copy pastes the copied objects. if let Some(text) = text.filter(|t| !is_objects_placeholder(s, t)) { // What our own text copy put on the clipboard keeps its formatting. - let slice = s.text_clipboard.clone().filter(|(_, plain)| text.replace("\r\n", "\n") == *plain).map(|(slice, _)| slice); - return paste_text_frame(s, p, text, slice.as_deref()); + let clip = s.text_clipboard.clone().filter(|(_, plain, _)| text.replace("\r\n", "\n") == *plain); + return paste_text_frame(s, p, text, clip.as_ref().map(|(slice, _, source)| (&**slice, &**source))); } let Some(clip) = s.clipboard.clone() else { return Err(super::bad("edit.paste", "clipboard is empty")); @@ -517,6 +610,33 @@ pub(crate) fn clip_doc(s: &Session) -> Result { if let Some(sp) = d.spreads.first_mut() { Arc::make_mut(sp).items = items; } + // A text frame anchored in a copied frame's text (as IDML import makes them) is in its host's + // story, not among the items: keep it, and the ones anchored in its text in turn, or the copy + // pointed at a story the clipping didn't have and pasted the anchored frame empty. + let mut kept: std::collections::HashSet = + d.stories.iter().filter(|(_, st)| st.frames.iter().any(|f| frames.contains(f))).map(|(id, _)| *id).collect(); + // Nothing to scan when no story is kept (a copied graphic). + while !kept.is_empty() { + let mut found = Vec::new(); + // Every anchored item once, group members included: `anchored_items` lists them. + for (owner, it) in d.anchored_items() { + if !kept.contains(&owner) { + continue; + } + if let designcraft_doc::Content::Text(tf) = &it.content { + found.push((it.id, tf.story)); + } + } + let before = kept.len(); + for (frame, story) in found { + frames.insert(frame); + kept.insert(story); + } + // Each pass keeps at least one more story or stops: there are finitely many. + if kept.len() == before { + break; + } + } // Parent spreads aren't part of a clipping; stories keep only the copied frames. for p in d.parents.iter_mut() { Arc::make_mut(p).items.clear(); @@ -736,6 +856,141 @@ mod paste_tests { assert_eq!(pasted(&mut s, "edit.pasteInPlace", json!({"spread": 1})), (SpreadRef::Doc(1), Rect::new(w + 36.0, 36.0, w + 136.0, 136.0))); } + /// A frame with `Host` text and, anchored at its start, a text frame with `Inner`; anchored + /// in that one's text, if `nested`, another with `Deepest`, as IDML import makes them (the + /// commands don't anchor text frames). Returns the host frame. + fn host_with_anchored_text_frames(s: &mut Session, nested: bool) -> ItemId { + use designcraft_doc::{AnchoredObject, ParaFormat, SpreadRef}; + s.execute("file.new", &json!({})).unwrap(); + let host = + s.execute("frame.create", &json!({"rect": [36, 36, 400, 400], "content": "text", "text": "Host"})).unwrap()["id"].as_u64().unwrap(); + s.edit(|d, _| { + let layer = d.default_layer(); + let host_sid = d.item(ItemId(host)).and_then(|i| i.text_frame()).map(|t| t.story).unwrap(); + // Anchor a new text frame holding `text` in story `into`, and give back its story. + let anchor_frame = |d: &mut designcraft_doc::Document, into: designcraft_doc::StoryId, text: &str| { + let (id, sid) = d + .add_text_frame(SpreadRef::Doc(0), designcraft_geom::Rect::new(0.0, 0.0, 80.0, 40.0), layer, text, ParaFormat::default()) + .unwrap(); + let item = d.item(id).unwrap().clone(); + let story = d.stories.get(&sid).unwrap().clone(); + d.remove_item(id).unwrap(); + d.stories.insert(sid, story); + d.story_mut(into).unwrap().insert_object(0, AnchoredObject { item, position: Default::default() }); + sid + }; + let inner = anchor_frame(d, host_sid, "Inner"); + if nested { + anchor_frame(d, inner, "Deepest"); + } + d.check().unwrap(); + Ok(()) + }) + .unwrap(); + ItemId(host) + } + + /// The text of every text frame anchored in the story of frame `host` of the active document, + /// and in theirs, depth first. + fn anchored_texts(s: &Session, host: ItemId) -> Vec { + let d = &s.doc().unwrap().doc; + // Without the marks the text holds for what is anchored in it. + let text = |x: &designcraft_doc::Story| -> String { x.text.chars().filter(|c| !('\u{E000}'..='\u{E1FF}').contains(c)).collect() }; + let mut out = Vec::new(); + let mut todo = vec![d.item(host).unwrap().text_frame().unwrap().story]; + while let Some(sid) = todo.pop() { + let Some(st) = d.story(sid) else { + out.push("".into()); + continue; + }; + for o in &st.objects { + if let Some(tf) = o.item.text_frame() { + out.push(d.story(tf.story).map_or("".into(), text)); + todo.push(tf.story); + } + } + } + out + } + + /// A text frame anchored in a copied frame's text keeps its text through copy and paste, into + /// another document or the same one, and so does one anchored in that. The clipboard used to + /// keep only the stories of the frames among the copied items, so an anchored frame pasted + /// empty: its story wasn't on the clipboard and the paste made it an empty one. + #[test] + fn a_text_frame_anchored_in_a_copied_frame_keeps_its_text() { + for nested in [false, true] { + let mut s = Session::new(); + let host = host_with_anchored_text_frames(&mut s, nested); + let expected: Vec = if nested { vec!["Inner".into(), "Deepest".into()] } else { vec!["Inner".into()] }; + assert_eq!(anchored_texts(&s, host), expected, "the original"); + s.execute("selection.set", &json!({"ids": [host.0]})).unwrap(); + s.execute("edit.copy", &json!({})).unwrap(); + for other in [true, false] { + if other { + s.execute("file.new", &json!({})).unwrap(); + } + let pasted = ItemId(s.execute("edit.paste", &json!({})).unwrap()["ids"][0].as_u64().unwrap()); + assert_eq!(anchored_texts(&s, pasted), expected, "nested {nested}, into another document {other}"); + s.doc().unwrap().doc.check().unwrap(); + if other { + s.execute("file.close", &json!({})).unwrap(); + } + } + } + } + + /// The same for a text frame inside a group anchored in the copied frame's text, as IDML + /// import anchors an InDesign group: the group's members are anchored items too. + #[test] + fn a_text_frame_in_an_anchored_group_keeps_its_text() { + use designcraft_doc::{AnchoredObject, Content, Item, ParaFormat, Shape, SpreadRef}; + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let host = ItemId( + s.execute("frame.create", &json!({"rect": [36, 36, 400, 400], "content": "text", "text": "Host"})).unwrap()["id"].as_u64().unwrap(), + ); + s.edit(|d, _| { + let layer = d.default_layer(); + let host_sid = d.item(host).and_then(|i| i.text_frame()).map(|t| t.story).unwrap(); + let (id, sid) = d + .add_text_frame(SpreadRef::Doc(0), designcraft_geom::Rect::new(0.0, 0.0, 80.0, 40.0), layer, "Grouped", ParaFormat::default()) + .unwrap(); + let child = d.item(id).unwrap().clone(); + let story = d.stories.get(&sid).unwrap().clone(); + d.remove_item(id).unwrap(); + d.stories.insert(sid, story); + let mut group = Item::new(ItemId(d.alloc()), layer, Shape::Group, Default::default()); + group.content = Content::Group { items: vec![Arc::new(child)] }; + d.story_mut(host_sid).unwrap().insert_object(0, AnchoredObject { item: group, position: Default::default() }); + d.check().unwrap(); + Ok(()) + }) + .unwrap(); + // The texts of the text frames in the groups anchored in frame `f`'s story. + let grouped = |s: &Session, f: ItemId| -> Vec { + let d = &s.doc().unwrap().doc; + let st = d.story(d.item(f).unwrap().text_frame().unwrap().story).unwrap(); + st.objects + .iter() + .flat_map(|o| { + o.item + .children() + .iter() + .filter_map(|c| c.text_frame()) + .map(|tf| d.story(tf.story).map_or("".into(), |x| x.text.clone())) + }) + .collect() + }; + assert_eq!(grouped(&s, host), ["Grouped"]); + s.execute("selection.set", &json!({"ids": [host.0]})).unwrap(); + s.execute("edit.copy", &json!({})).unwrap(); + s.execute("file.new", &json!({})).unwrap(); + let pasted = ItemId(s.execute("edit.paste", &json!({})).unwrap()["ids"][0].as_u64().unwrap()); + assert_eq!(grouped(&s, pasted), ["Grouped"]); + s.doc().unwrap().doc.check().unwrap(); + } + /// A copied text frame's clipping holds the files its anchored graphics show. #[test] fn copied_text_frames_keep_the_graphics_anchored_in_their_text() { diff --git a/crates/engine/src/cmd/editorial.rs b/crates/engine/src/cmd/editorial.rs index 5b09cbcb6..7392d2da8 100644 --- a/crates/engine/src/cmd/editorial.rs +++ b/crates/engine/src/cmd/editorial.rs @@ -20,16 +20,19 @@ pub fn specs() -> Vec { let author = str_param(p, "author").unwrap_or("").to_string(); let at = ts.anchor.max(ts.focus); s.edit(|d, sel| { - let story = d.story_mut(ts.story).ok_or_else(|| bad("note.new", "no such story"))?; - let fmt = story.char_format_at(at).clone(); - story.insert_with(at, &NOTE_MARK.to_string(), fmt); - // A file may hold fewer notes than anchors; give every anchor one. - story.fix_marks(); - let k = story.text[..at].matches(NOTE_MARK).count(); - let n = story.editorial.get_mut(k).ok_or_else(|| bad("note.new", "the story's notes don't match their anchors"))?; - let n = Arc::make_mut(n); - (n.text, n.author) = (text, author); - let id = n.id; + let id = { + let story = d.story_mut(ts.story).ok_or_else(|| bad("note.new", "no such story"))?; + let fmt = story.char_format_at(at).clone(); + story.insert_with(at, &NOTE_MARK.to_string(), fmt); + // A file may hold fewer notes than anchors; give every anchor one. + story.fix_marks(); + let k = story.text[..at].matches(NOTE_MARK).count(); + let n = story.editorial.get_mut(k).ok_or_else(|| bad("note.new", "the story's notes don't match their anchors"))?; + let n = Arc::make_mut(n); + (n.text, n.author) = (text, author); + n.id + }; + d.adjust_text_ranges(ts.story, at..at, NOTE_MARK.len_utf8()); if let Some(t) = &mut sel.text { let c = at + NOTE_MARK.len_utf8(); (t.anchor, t.focus) = (c, c); @@ -68,8 +71,10 @@ pub fn specs() -> Vec { s.edit(|d, sel| { let st = d.story_mut(sid).ok_or_else(|| bad("note.delete", "no such story"))?; let at = anchor(st, id).ok_or_else(|| bad("note.delete", format!("no note {id}")))?; - follow_replace(sel, sid, at..at + NOTE_MARK.len_utf8(), 0); - st.delete(at..at + NOTE_MARK.len_utf8()); + let len = NOTE_MARK.len_utf8(); + follow_replace(sel, sid, at..at + len, 0); + st.delete(at..at + len); + d.adjust_text_ranges(sid, at..at + len, 0); ok() }) }), @@ -86,8 +91,10 @@ pub fn specs() -> Vec { let st = d.story_mut(sid).ok_or_else(|| bad("note.convertToText", "no such story"))?; let at = anchor(st, id).ok_or_else(|| bad("note.convertToText", format!("no note {id}")))?; let text = st.editorial.iter().find(|n| n.id == id).map(|n| n.text.clone()).unwrap_or_default(); - follow_replace(sel, sid, at..at + NOTE_MARK.len_utf8(), text.len()); - st.replace(at..at + NOTE_MARK.len_utf8(), &text); + let len = NOTE_MARK.len_utf8(); + follow_replace(sel, sid, at..at + len, text.len()); + st.replace(at..at + len, &text); + d.adjust_text_ranges(sid, at..at + len, text.len()); ok() }) } @@ -161,20 +168,23 @@ fn convert_from_text(s: &mut Session, p: &Value) -> Result { } let author = str_param(p, "author").unwrap_or("").to_string(); s.edit(|d, sel| { - let story = d.story_mut(ts.story).ok_or_else(|| bad(ID, "no such story"))?; - let text = story.text.get(r.clone()).ok_or_else(|| bad(ID, "the selection is outside the story"))?.to_string(); - if text.contains(MARKS) { - return Err(bad(ID, "the selection holds a table, an anchored object, a note, a footnote, an endnote or a marker")); - } - let fmt = story.format_after(r.start).clone(); - story.delete(r.clone()); - story.insert_with(r.start, &NOTE_MARK.to_string(), fmt); - story.fix_marks(); - let k = story.text[..r.start].matches(NOTE_MARK).count(); - let n = story.editorial.get_mut(k).ok_or_else(|| bad(ID, "the story's notes don't match their anchors"))?; - let n = Arc::make_mut(n); - (n.text, n.author) = (text, author); - let id = n.id; + let id = { + let story = d.story_mut(ts.story).ok_or_else(|| bad(ID, "no such story"))?; + let text = story.text.get(r.clone()).ok_or_else(|| bad(ID, "the selection is outside the story"))?.to_string(); + if text.contains(MARKS) { + return Err(bad(ID, "the selection holds a table, an anchored object, a note, a footnote, an endnote or a marker")); + } + let fmt = story.format_after(r.start).clone(); + story.delete(r.clone()); + story.insert_with(r.start, &NOTE_MARK.to_string(), fmt); + story.fix_marks(); + let k = story.text[..r.start].matches(NOTE_MARK).count(); + let n = story.editorial.get_mut(k).ok_or_else(|| bad(ID, "the story's notes don't match their anchors"))?; + let n = Arc::make_mut(n); + (n.text, n.author) = (text, author); + n.id + }; + d.adjust_text_ranges(ts.story, r.clone(), NOTE_MARK.len_utf8()); if let Some(t) = &mut sel.text { let c = r.start + NOTE_MARK.len_utf8(); (t.anchor, t.focus) = (c, c); diff --git a/crates/engine/src/cmd/endnotes.rs b/crates/engine/src/cmd/endnotes.rs index 9b02d2c87..decd6b097 100644 --- a/crates/engine/src/cmd/endnotes.rs +++ b/crates/engine/src/cmd/endnotes.rs @@ -40,8 +40,10 @@ pub fn specs() -> Vec { .nth(k) .map(|(i, _)| i) .ok_or_else(|| bad("endnote.delete", format!("endnote {id} has no reference in the text")))?; - super::notes::follow_delete(sel, sid, at..at + designcraft_doc::ENDNOTE_REF.len_utf8()); - st.delete(at..at + designcraft_doc::ENDNOTE_REF.len_utf8()); + let len = designcraft_doc::ENDNOTE_REF.len_utf8(); + super::notes::follow_delete(sel, sid, at..at + len); + st.delete(at..at + len); + d.adjust_text_ranges(sid, at..at + len, 0); ok() }) }), @@ -125,6 +127,7 @@ fn insert(s: &mut Session, p: &Value) -> Result { let id = story .insert_endnote(at, &text, ParaFormat { style, ..Default::default() }) .ok_or_else(|| bad(ID, "the story's endnotes don't match its references"))?; + d.adjust_text_ranges(ts.story, at..at, designcraft_doc::ENDNOTE_REF.len_utf8()); let caret = at + designcraft_doc::ENDNOTE_REF.len_utf8(); if let Some(t) = &mut sel.text { (t.anchor, t.focus) = (caret, caret); diff --git a/crates/engine/src/cmd/export.rs b/crates/engine/src/cmd/export.rs index a4ee73ce4..d65af9272 100644 --- a/crates/engine/src/cmd/export.rs +++ b/crates/engine/src/cmd/export.rs @@ -16,8 +16,12 @@ mod registry; use flatten::{rasterize_effects, shadow_coverage}; #[cfg(not(target_arch = "wasm32"))] pub(crate) use pdf::pdf_export; +pub(crate) use pdf::{check_pdf_options, pdf_report}; pub(crate) use pdf::{flatten_ppi, options, print_pdf}; pub use registry::specs; #[cfg(test)] mod text_tests; + +#[cfg(test)] +mod linked_tests; diff --git a/crates/engine/src/cmd/export/flatten.rs b/crates/engine/src/cmd/export/flatten.rs index b32d54383..730f28b4a 100644 --- a/crates/engine/src/cmd/export/flatten.rs +++ b/crates/engine/src/cmd/export/flatten.rs @@ -31,7 +31,7 @@ pub(super) fn flatten(d: &designcraft_doc::Document, cache: &designcraft_compose id: aid, name: format!("flattened-{}.png", aid.0), mime: "image/png".into(), - data: std::sync::Arc::new(img.to_png()), + data: designcraft_doc::AssetData::embedded(img.to_png()), pixels: Some((w, h)), ..Default::default() }), @@ -147,7 +147,7 @@ pub(super) fn rasterize_effects( cache: &designcraft_compose::Cache, skip: &std::collections::HashMap, ) -> (Option, usize) { - rasterize_where(d, cache, 300.0, true, |it| raster_effects(it) && !threaded(d, it) && !skip.contains_key(&it.id)) + rasterize_where_with_links(d, cache, 300.0, true, true, |it| raster_effects(it) && !threaded(d, it) && !skip.contains_key(&it.id)) } /// A drop shadow is the object's only soft effect, and the PDF writer draws its shadow itself @@ -253,6 +253,17 @@ pub(super) fn rasterize_where( ppi: f64, keep_wrap: bool, pred: impl Fn(&designcraft_doc::Item) -> bool, +) -> (Option, usize) { + rasterize_where_with_links(d, cache, ppi, keep_wrap, false, pred) +} + +fn rasterize_where_with_links( + d: &designcraft_doc::Document, + cache: &designcraft_compose::Cache, + ppi: f64, + keep_wrap: bool, + keep_links: bool, + pred: impl Fn(&designcraft_doc::Item) -> bool, ) -> (Option, usize) { use designcraft_doc::{Asset, AssetId, Content, Graphic, Item, ItemId, Shape, SpreadRef}; let todo: Vec<(usize, ItemId)> = @@ -299,7 +310,7 @@ pub(super) fn rasterize_where( id: aid, name: format!("effects-{}.png", id.0), mime: "image/png".into(), - data: std::sync::Arc::new(img.to_png()), + data: designcraft_doc::AssetData::embedded(img.to_png()), pixels: Some((w, h)), ..Default::default() }), @@ -320,11 +331,24 @@ pub(super) fn rasterize_where( img_item.stroke.weight = 0.0; img_item.alt_text = it.alt_text.clone(); img_item.export_options = it.export_options.clone(); + let linked = keep_links + && d.hyperlinks.iter().any(|link| match &link.source { + designcraft_doc::HyperlinkSource::Item { id: source } => d.top_level_of(*source) == Some(id), + designcraft_doc::HyperlinkSource::Text { story, .. } => { + d.story(*story).is_some_and(|st| st.frames.iter().any(|frame| d.top_level_of(*frame) == Some(id))) + } + }); // Same place in the stacking order. let osp = std::sync::Arc::make_mut(&mut out.spreads[si]); if let Some(pos) = osp.items.iter().position(|x| x.id == id) { osp.items[pos] = std::sync::Arc::new(img_item); - if keep_wrap && has_wrap(it, 0) { + if linked { + // Annotation bounds and text composition still need the original frame, not + // the image's larger effect bounds. This copy also keeps any text wrap. It keeps + // the frame's ItemId, which hyperlink sources and the story's frame list name, + // while the image takes a fresh id. + osp.items.insert(pos, std::sync::Arc::new(link_stand_in(it, 0))); + } else if keep_wrap && has_wrap(it, 0) { osp.items.insert(pos, std::sync::Arc::new(wrap_stand_in(it, 0))); } n += 1; @@ -347,9 +371,29 @@ fn has_wrap(it: &designcraft_doc::Item, depth: usize) -> bool { } } -/// Nesting depth past which groups inside a rasterised object keep no wrap stand-ins. +/// Nesting depth past which groups inside a rasterised object keep no stand-in children. const MAX_STAND_IN_DEPTH: usize = 64; +/// Nonprinting link geometry, retaining text stories and wrap but no interactive annotations. +fn link_stand_in(it: &designcraft_doc::Item, depth: usize) -> designcraft_doc::Item { + use designcraft_doc::Content; + let mut c = it.clone(); + c.nonprinting = true; + c.form_field = None; + c.button = None; + c.media = None; + if let Content::Group { items } = &it.content { + c.content = Content::Group { + items: if depth < MAX_STAND_IN_DEPTH { + items.iter().map(|i| std::sync::Arc::new(link_stand_in(i, depth + 1))).collect() + } else { + Vec::new() + }, + }; + } + c +} + /// A nonprinting copy of `it` that keeps its text wrap (and its graphic's and its items') and /// nothing else that reaches the PDF: no text, form field, button or media. The image of the /// object stands in for all of that, as it does without the copy. @@ -382,7 +426,7 @@ pub(super) fn rasterize_layered(d: &designcraft_doc::Document) -> Result<(Option .filter(|it| it.has_pdf_layer_override()) .filter_map(|it| { let g = it.graphic()?; - let a = d.assets.get(&g.asset).filter(|a| designcraft_render::is_pdf(&a.data))?; + let a = d.assets.get(&g.asset).filter(|a| a.output_bytes().is_ok_and(|o| designcraft_render::is_pdf(&o.bytes)))?; Some((it.id, g.clone(), a.clone(), it.pdf_hidden_layers.clone())) }) .collect(); @@ -398,7 +442,8 @@ pub(super) fn rasterize_layered(d: &designcraft_doc::Document) -> Result<(Option let [l, t, r, b] = shown.unwrap_or([0.0, 0.0, 1.0, 1.0]); let page_side = (g.size.0 / (r - l)).max(g.size.1 / (b - t)); let side = (page_side * 300.0 / 72.0).clamp(64.0, 8000.0) as u32; - let png = designcraft_render::pdf_page_png_options_checked(&a.data, a.page as usize, side, Some(&hidden), shown) + let bytes = a.output_bytes().map_err(|e| EngineError::Other(format!("{}: {e}", a.name)))?.bytes; + let png = designcraft_render::pdf_page_png_options_checked(&bytes, a.page as usize, side, Some(&hidden), shown) .map_err(|e| EngineError::Other(format!("{}: {e}", a.name)))?; let px = designcraft_render::image_size(&png); let aid = designcraft_doc::AssetId(out.alloc()); @@ -408,7 +453,7 @@ pub(super) fn rasterize_layered(d: &designcraft_doc::Document) -> Result<(Option id: aid, name: format!("{}.png", a.name), mime: "image/png".into(), - data: std::sync::Arc::new(png), + data: designcraft_doc::AssetData::embedded(png), pixels: px, ..Default::default() }), @@ -496,7 +541,7 @@ mod placed_layer_tests { let aid = d.item(id).unwrap().graphic().unwrap().asset; let asset = Arc::make_mut(d.assets.get_mut(&aid).unwrap()); asset.mime = "image/png".into(); - asset.data = Arc::new(designcraft_render::Rendered { width: 1, height: 1, pixels: vec![0, 0, 0, 0] }.to_png()); + asset.data = designcraft_doc::AssetData::embedded(designcraft_render::Rendered { width: 1, height: 1, pixels: vec![0, 0, 0, 0] }.to_png()); let (copy, count) = super::rasterize_layered(d).unwrap(); assert_eq!(count, 0); assert!(copy.is_none()); diff --git a/crates/engine/src/cmd/export/formats.rs b/crates/engine/src/cmd/export/formats.rs index 31885bee2..2f9d9f88e 100644 --- a/crates/engine/src/cmd/export/formats.rs +++ b/crates/engine/src/cmd/export/formats.rs @@ -25,7 +25,8 @@ pub(super) fn print_booklet(s: &mut Session, p: &Value) -> Result { } } -/// HTML and reflowable EPUB embed the EPS preview; keep the session's source bytes intact. +/// HTML and reflowable EPUB read embedded bytes only: every used linked asset gets its output +/// bytes embedded, and EPS its preview. The session's own assets stay as they are. fn eps_previews(d: &designcraft_doc::Document) -> (Cow<'_, designcraft_doc::Document>, Vec) { // Match the exporter's reading order (including Article exclusions), not every asset // in the document: unused or hidden graphics must not prevent an export. @@ -48,17 +49,40 @@ fn eps_previews(d: &designcraft_doc::Document) -> (Cow<'_, designcraft_doc::Docu let mut out = Cow::Borrowed(d); let mut warnings = Vec::new(); for id in used { - let Some(a) = d.assets.get(&id).filter(|a| designcraft_images::is_eps(&a.data)) else { - continue; + let Some(a) = d.assets.get(&id) else { continue }; + let linked = a.data.is_linked(); + let got = match a.output_bytes() { + Ok(got) => got, + Err(e) => { + if linked { + warnings.push(format!("{}: the linked file is unavailable ({e}); graphic omitted", a.name)); + } + continue; + } }; - let png = designcraft_images::eps_png(&a.data); - if png.is_none() { - warnings.push(format!("{}: unusable EPS preview; graphic omitted", a.name)); + let bytes = got.bytes; + let eps = designcraft_images::is_eps(&bytes); + // Embedded bytes the writers read as they are; a linked asset's bytes are read here + // (the writers only see embedded data), and EPS is replaced by its preview. + if !eps && !linked { + continue; } + warnings.extend(got.warning); + let data = if eps { + let png = designcraft_images::eps_png(&bytes); + if png.is_none() { + warnings.push(format!("{}: unusable EPS preview; graphic omitted", a.name)); + } + png.unwrap_or_default() + } else { + bytes.as_ref().clone() + }; if let Some(a) = out.to_mut().assets.get_mut(&id) { let a = Arc::make_mut(a); - a.mime = "image/png".into(); - a.data = Arc::new(png.unwrap_or_default()); + if eps { + a.mime = "image/png".into(); + } + a.data = designcraft_doc::AssetData::embedded(data); } } (out, warnings) @@ -110,6 +134,8 @@ pub(super) fn export_pptx(s: &mut Session, p: &Value) -> Result { if rasterized > 0 { r.warnings.push(format!("{rasterized} object(s) went in as images")); } + // A slide has no room for the overset text either (#1465). + r.warnings.extend(crate::cmd::preflight::overset_warnings(s, opts.pages.as_deref())); match str_param(p, "path") { Some(path) => { #[cfg(not(target_arch = "wasm32"))] @@ -134,13 +160,13 @@ pub(super) fn export_text(s: &mut Session, p: &Value) -> Result { Some(f @ ("rtf" | "tagged")) => f, Some("txt") | Some("text") => "txt", Some(f) => return Err(bad(ID, format!("unknown format `{f}` (txt, rtf, tagged)"))), - None if path.is_some_and(|x| x.to_ascii_lowercase().ends_with(".rtf")) => "rtf", + None if path.is_some_and(|x| craft_file_formats::detect(x, &[]) == Some(craft_file_formats::Format::Rtf)) => "rtf", None => "txt", }; let text = match format { "rtf" => designcraft_textimport::export::rtf(doc, story), "tagged" => designcraft_textimport::tagged::tagged_text(doc, story), - _ => designcraft_textimport::export::plain_text(story), + _ => designcraft_textimport::export::plain_text(doc, story), }; match path { Some(path) => { @@ -157,13 +183,30 @@ fn page_text(d: &designcraft_doc::Document, cache: &designcraft_compose::Cache, let mut out = String::new(); for st in d.stories.values() { let cs = cache.get(d, st.id, None); + let spans = d.visible_spans(st); for ft in &cs.frames { if d.page_of_item(ft.frame) != Some(abs) { continue; } + // Pages render printing-only: a hidden or nonprinting frame or group around it, or a top-level item on a hidden or non-printable layer (members draw on its layer), isn't on the rendered page. + // Inside a multi-state object only the active state is drawn. + if d.find(ft.frame).is_some_and(|loc| { + (1..=loc.path.len()).any(|n| { + d.item_at(&designcraft_doc::ItemLoc { spread: loc.spread, path: loc.path[..n].to_vec() }).is_some_and(|it| { + it.hidden + || it.nonprinting + || n == 1 && d.layers.iter().any(|l| (!l.visible || !l.printable) && l.id == it.layer) + || n < loc.path.len() && !it.states.is_empty() && loc.path[n] != it.active_state + }) + }) + }) { + continue; + } for l in &ft.lines { let r = l.range.start.min(st.text.len())..l.range.end.min(st.text.len()); - let t: String = st.text[r].chars().filter(|c| !('\u{E000}'..='\u{F8FF}').contains(c)).collect(); + // The line's text as it shows: hidden conditional text and deletions left out. + let t: String = + designcraft_doc::Document::visible_text(st, &spans, r).chars().filter(|c| !('\u{E000}'..='\u{F8FF}').contains(c)).collect(); if !t.trim().is_empty() { out.push_str(t.trim_end_matches('\n')); out.push('\n'); @@ -395,6 +438,36 @@ mod pptx_tests { assert!(s.execute("file.exportPptx", &json!({"pages": [9]})).is_err()); } + #[test] + fn cell_diagonal_lines_export_as_cell_diagonal_borders() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let r = s.execute("frame.create", &json!({"rect": [72, 72, 500, 400], "content": "text", "text": ""})).unwrap(); + s.execute("text.select", &json!({"story": r["story"], "anchor": 0, "focus": 0})).unwrap(); + s.execute("table.insert", &json!({"rows": 2, "cols": 2})).unwrap(); + for (row, col, lines) in [(0, 0, "topLeft"), (0, 1, "topRight"), (1, 0, "crossed")] { + s.execute("table.setCell", &json!({"row": row, "col": col, "diagonal": {"lines": lines, "weight": 3}})).unwrap(); + } + let r = s.execute("file.exportPptx", &json!({})).unwrap(); + let x = read(&mut unzip(r["base64"].as_str().unwrap()), "ppt/slides/slide1.xml"); + let cells: Vec<&str> = x.split("").filter(|c| c.contains(" = cells.iter().map(|c| has(c)).collect(); + assert_eq!(got, [(true, false), (false, true), (true, true), (false, false)], "{x}"); + // The diagonals follow the four edges and come before the cell's fill, in the schema's order. + let c = cells[2]; + let at = |tag: &str| c.find(tag).unwrap_or(usize::MAX); + assert!(at(" at(" Self { + let dir = std::env::temp_dir().join(format!("dc-linked-output-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + Dir(dir) + } +} + +impl Drop for Dir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +/// A `w` × `h` PNG; transparent in its left half when `cut`. +fn png(w: usize, h: usize, cut: bool) -> Vec { + let mut pixels = Vec::new(); + for _ in 0..h { + for x in 0..w { + pixels.extend([200, 40, 40, if cut && x < w / 2 { 0 } else { 255 }]); + } + } + designcraft_render::Rendered { width: w as u32, height: h as u32, pixels }.to_png() +} + +/// A session with `bytes` placed, then made a linked asset to `file` (holding `bytes`) with a +/// proxy of them → the asset. +fn linked_session(file: &Path, bytes: &[u8]) -> (Session, AssetId) { + std::fs::write(file, bytes).unwrap(); + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + s.execute("file.place", &json!({"base64": crate::cmd::base64_encode(bytes), "name": "art.png", "x": 10, "y": 10, "width": 100})).unwrap(); + let id = *s.doc().unwrap().doc.assets.keys().next().unwrap(); + let proxy = designcraft_render::proxy::make_proxy(bytes, 0).unwrap(); + let st = s.doc_mut().unwrap(); + let a = Arc::make_mut(Arc::make_mut(&mut st.doc).assets.get_mut(&id).unwrap()); + a.link = Some(file.to_string_lossy().into_owned()); + a.link_fingerprint = Some(fingerprint_from(&std::fs::metadata(file).unwrap())); + a.link_hash = Some(content_hash(bytes)); + a.storage = Storage::Linked; + a.data = AssetData::linked(LinkedSource::of(a, None).unwrap()); + a.proxy = Some(Proxy { mime: proxy.mime.into(), pixels: proxy.pixels, data: AssetData::embedded(proxy.data) }); + (s, id) +} + +fn warnings(r: &Value) -> String { + r["warnings"].to_string() +} + +fn pdf_text(r: &Value) -> String { + String::from_utf8_lossy(&crate::cmd::base64_decode(r["base64"].as_str().unwrap())).into_owned() +} + +#[test] +fn a_missing_link_is_a_preflight_error_and_exports_its_proxy() { + let dir = Dir::new("missing"); + let file = dir.0.join("art.png"); + let (mut s, _) = linked_session(&file, &png(40, 20, false)); + std::fs::remove_file(&file).unwrap(); + let issues = s.execute("preflight.run", &json!({})).unwrap(); + assert!(issues.to_string().contains("missingLink"), "{issues}"); + let r = s.execute("file.exportPdf", &json!({})).unwrap(); + assert!(warnings(&r).contains("art.png") && warnings(&r).contains("preview"), "{}", warnings(&r)); + assert!(pdf_text(&r).contains("/Subtype /Image") || pdf_text(&r).contains("/Subtype/Image"), "the proxy is in the PDF"); +} + +#[test] +fn a_modified_link_is_a_preflight_warning_and_exports_the_file_on_disk() { + let dir = Dir::new("modified"); + let file = dir.0.join("art.png"); + let (mut s, _) = linked_session(&file, &png(40, 20, false)); + std::fs::write(&file, png(77, 33, false)).unwrap(); + let issues = s.execute("preflight.run", &json!({})).unwrap(); + assert!(issues.to_string().contains("modifiedLink"), "{issues}"); + let r = s.execute("file.exportPdf", &json!({})).unwrap(); + assert!(warnings(&r).contains("file on disk"), "{}", warnings(&r)); + let text = pdf_text(&r); + assert!(text.contains("/Width 77") || text.contains("/Width%2077") || text.contains("/Width\n77"), "the new file's pixels are in the PDF"); +} + +#[test] +fn a_package_copies_a_linked_file_from_disk_and_links_to_the_copy() { + let dir = Dir::new("package"); + let file = dir.0.join("art.png"); + let bytes = png(40, 20, false); + let (mut s, id) = linked_session(&file, &bytes); + let out = dir.0.join("out"); + s.execute("file.package", &json!({"dir": out.to_string_lossy(), "pdf": false, "idml": false})).unwrap(); + let copy = out.join("Links/art.png"); + assert_eq!(std::fs::read(©).unwrap(), bytes); + let doc = std::fs::read_dir(&out) + .unwrap() + .filter_map(Result::ok) + .map(|e| e.path()) + .find(|p| p.extension().is_some_and(|e| e == "designcraft")) + .unwrap(); + std::fs::remove_file(&file).unwrap(); + let mut t = Session::new(); + t.execute("file.open", &json!({"path": doc.to_string_lossy()})).unwrap(); + let a = &t.doc().unwrap().doc.assets[&id]; + assert_eq!((a.storage, a.link_relative.as_deref()), (Storage::Linked, Some("Links/art.png"))); + assert_eq!(a.data.load().unwrap().as_slice(), bytes.as_slice()); +} + +#[test] +fn opening_a_document_with_a_linked_alpha_wrap_image_reads_no_original() { + let dir = Dir::new("alpha"); + let file = dir.0.join("art.png"); + let (mut s, _) = linked_session(&file, &png(64, 64, true)); + let image = s.doc().unwrap().doc.spreads[0].items[0].id.0; + s.execute("object.textWrap", &json!({"ids": [image], "mode": "contour", "contour": "alphaChannel"})).unwrap(); + let path = dir.0.join("doc.designcraft"); + s.execute("file.save", &json!({"path": path.to_string_lossy()})).unwrap(); + let mut t = Session::new(); + t.execute("file.open", &json!({"path": path.to_string_lossy()})).unwrap(); + let d = &t.doc().unwrap().doc; + let a = d.assets.values().next().unwrap(); + assert!(a.data.is_linked() && a.data.resident().is_none(), "no original was read"); + let o = d.alpha_outlines.first().expect("the outline is traced from the proxy"); + assert_eq!((o.width, o.height), (64, 64), "scaled to the original's size"); +} + +#[test] +fn epub_and_html_carry_a_linked_graphic_and_a_modified_one_from_disk() { + let dir = Dir::new("epub"); + let file = dir.0.join("art.png"); + let (mut s, _) = linked_session(&file, &png(40, 20, false)); + let html = s.execute("file.exportHtml", &json!({})).unwrap(); + assert!(html["text"].as_str().unwrap().contains(" = z.file_names().map(str::to_string).collect(); + let image = names.iter().find(|n| n.starts_with("OEBPS/images/")).unwrap_or_else(|| panic!("no image in {names:?}")).clone(); + // A modified link exports the file on disk, with a warning. + std::fs::write(&file, png(77, 33, false)).unwrap(); + let r = s.execute("file.exportEpub", &json!({})).unwrap(); + assert!(warnings(&r).contains("file on disk"), "{}", warnings(&r)); + let mut z = zip::ZipArchive::new(std::io::Cursor::new(crate::cmd::base64_decode(r["base64"].as_str().unwrap()))).unwrap(); + let mut bytes = Vec::new(); + std::io::Read::read_to_end(&mut z.by_name(&image).unwrap(), &mut bytes).unwrap(); + assert_eq!(bytes, std::fs::read(&file).unwrap()); +} + +#[test] +fn a_package_copies_a_modified_link_from_disk_with_a_warning() { + let dir = Dir::new("package-modified"); + let file = dir.0.join("art.png"); + let (mut s, _) = linked_session(&file, &png(40, 20, false)); + let changed = png(77, 33, false); + std::fs::write(&file, &changed).unwrap(); + let out = dir.0.join("out"); + let r = s.execute("file.package", &json!({"dir": out.to_string_lossy(), "pdf": false, "idml": false})).unwrap(); + assert_eq!(std::fs::read(out.join("Links/art.png")).unwrap(), changed); + assert!(r.to_string().contains("file on disk"), "{r}"); +} diff --git a/crates/engine/src/cmd/export/pdf.rs b/crates/engine/src/cmd/export/pdf.rs index 903639ff9..09a9b9a1e 100644 --- a/crates/engine/src/cmd/export/pdf.rs +++ b/crates/engine/src/cmd/export/pdf.rs @@ -87,8 +87,27 @@ fn first_page_ref(pdf: &[u8]) -> Option { s[i..].split_whitespace().next()?.parse().ok() } +/// Every page sharing a spread with one of `pages` (0-based), for an export that puts whole +/// spreads on a sheet. The pages come back in document order. +fn with_their_spreads(s: &Session, pages: &[usize]) -> Vec { + let Some(st) = s.active() else { return pages.to_vec() }; + let d = &st.doc; + let spreads: std::collections::BTreeSet = pages.iter().filter_map(|p| d.page_loc(*p)).map(|(si, _)| si).collect(); + if spreads.is_empty() { + return pages.to_vec(); + } + (0..d.page_count()).filter(|p| d.page_loc(*p).is_some_and(|(si, _)| spreads.contains(&si))).collect() +} + pub(super) fn export_pdf(s: &mut Session, p: &Value) -> Result { - let r = pdf_export(s, p)?; + let mut r = pdf_export(s, p)?; + // Text the pages have no room for is not in the file: say so, as preflight does (#1465). + // A spread export puts the whole spread on the sheet, so choosing page 2 exports page 3 as + // well and page 3's overset is as absent from the file as page 2's would be. The selection + // is widened to the spreads it touches before the warnings are collected (noted in review). + let opts = options(p, s.doc()?.doc.page_count())?; + let warn_pages = opts.pages.as_deref().map(|pages| if opts.spreads { with_their_spreads(s, pages) } else { pages.to_vec() }); + r.warnings.extend(crate::cmd::preflight::overset_warnings(s, warn_pages.as_deref())); match str_param(p, "path") { Some(path) => { write_file(path, &r.bytes)?; @@ -169,41 +188,21 @@ pub(crate) fn print_pdf( /// The PDF that File › Export PDF writes for `p`, with its warnings: the print PDF /// ([`print_pdf`]) with its view options, timings and transitions. File › Print prints it. pub(crate) fn pdf_export(s: &Session, p: &Value) -> Result { - let st = s.doc()?; - let opts = options(p, st.doc.page_count())?; + pdf_report(&s.doc()?.doc, &s.cache, p) +} + +/// [`pdf_export`] of `doc`: `file.package` writes its PDF of the packaged copy with it. +pub(crate) fn pdf_report(doc: &designcraft_doc::Document, cache: &designcraft_compose::Cache, p: &Value) -> Result { + let opts = options(p, doc.page_count())?; let ppi = flatten_ppi("file.exportPdf", p)?; - let mut r = print_pdf(&st.doc, &s.cache, &opts, ppi)?; - let doc: &designcraft_doc::Document = &st.doc; + let (cat, dest) = view_options(p)?; + let mut r = print_pdf(doc, cache, &opts, ppi)?; let spreads = designcraft_pdf::sheet_spreads(doc, &opts); - // Interactive PDF view options. - let mut cat = String::new(); - if p.get("fullScreen").and_then(Value::as_bool) == Some(true) { - cat.push_str("/PageMode/FullScreen"); - } else if p.get("bookmarksPanel").and_then(Value::as_bool) == Some(true) { - cat.push_str("/PageMode/UseOutlines"); - } - match str_param(p, "pageLayout") { - Some("single") => cat.push_str("/PageLayout/SinglePage"), - Some("continuous") => cat.push_str("/PageLayout/OneColumn"), - Some("twoUp") => cat.push_str("/PageLayout/TwoPageLeft"), - Some("twoUpCover") => cat.push_str("/PageLayout/TwoPageRight"), - Some("twoUpContinuous") => cat.push_str("/PageLayout/TwoColumnRight"), - Some(o) => return Err(bad("file.exportPdf", format!("unknown pageLayout `{o}`"))), - None => {} - } - if let Some(v) = str_param(p, "view") { - // The first page opens with this view (pages are objects in order, so refer by index 0). - let dest = match v { - "fitPage" => "/Fit", - "fitWidth" => "/FitH null", - "actual" => "/XYZ null null 1", - o => { - return Err(bad("file.exportPdf", format!("unknown view `{o}` (fitPage, fitWidth, actual)"))); - } - }; - if let Some(first) = first_page_ref(&r.bytes) { - cat.push_str(&format!("/OpenAction[{first} 0 R{dest}]")); - } + let mut cat = cat; + if let Some(dest) = dest + && let Some(first) = first_page_ref(&r.bytes) + { + cat.push_str(&format!("/OpenAction[{first} 0 R{dest}]")); } if !cat.is_empty() { match designcraft_pdf::add_catalog_entries(&r.bytes, &cat) { @@ -213,8 +212,7 @@ pub(crate) fn pdf_export(s: &Session, p: &Value) -> Result 0.0) { - let n = designcraft_pdf::sheet_spreads(doc, &opts).len(); - let dur: Vec> = (0..n).map(|_| Some(format!("/Dur {secs:.2}"))).collect(); + let dur: Vec> = (0..spreads.len()).map(|_| Some(format!("/Dur {secs:.2}"))).collect(); match designcraft_pdf::add_page_entries(&r.bytes, &dur) { Some(b) => r.bytes = b, None => r.warnings.push("page timings couldn't be set".into()), @@ -232,6 +230,44 @@ pub(crate) fn pdf_export(s: &Session, p: &Value) -> Result Result<(String, Option<&'static str>)> { + let mut cat = String::new(); + if p.get("fullScreen").and_then(Value::as_bool) == Some(true) { + cat.push_str("/PageMode/FullScreen"); + } else if p.get("bookmarksPanel").and_then(Value::as_bool) == Some(true) { + cat.push_str("/PageMode/UseOutlines"); + } + match str_param(p, "pageLayout") { + Some("single") => cat.push_str("/PageLayout/SinglePage"), + Some("continuous") => cat.push_str("/PageLayout/OneColumn"), + Some("twoUp") => cat.push_str("/PageLayout/TwoPageLeft"), + Some("twoUpCover") => cat.push_str("/PageLayout/TwoPageRight"), + Some("twoUpContinuous") => cat.push_str("/PageLayout/TwoColumnRight"), + Some(o) => return Err(bad("file.exportPdf", format!("unknown pageLayout `{o}`"))), + None => {} + } + // The first page opens with this view (pages are objects in order, so refer by index 0). + let dest = match str_param(p, "view") { + None => None, + Some("fitPage") => Some("/Fit"), + Some("fitWidth") => Some("/FitH null"), + Some("actual") => Some("/XYZ null null 1"), + Some(o) => return Err(bad("file.exportPdf", format!("unknown view `{o}` (fitPage, fitWidth, actual)"))), + }; + Ok((cat, dest)) +} + +/// Refuses PDF options `p` that [`pdf_report`] would refuse for a document of `pages` pages, +/// without exporting: `file.package` checks them before it writes anything. +pub(crate) fn check_pdf_options(p: &Value, pages: usize) -> Result<()> { + options(p, pages)?; + flatten_ppi("file.exportPdf", p)?; + view_options(p)?; + Ok(()) +} + #[cfg(test)] mod tagged_tests { use serde_json::json; @@ -461,3 +497,252 @@ mod page_list_tests { assert!(s.execute("file.exportPdf", &json!({"pages": []})).is_err()); } } + +#[cfg(test)] +mod overset_tests { + use serde_json::json; + + use crate::Session; + + /// A page-based export leaves out the text its frames have no room for, and said nothing + /// about it: an imported 58-page form lost whole sentences — a data-consent clause, a + /// statutory rule, the last row of two tables — with `warnings` empty while preflight + /// reported 19 overset stories (#1465). + #[test] + fn an_export_warns_about_the_text_the_pages_had_no_room_for() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 300, "height": 200, "pages": 2, "facingPages": false, "margins": 0})).unwrap(); + let text = "First line is visible.\nSecond paragraph does not fit: this sentence carries the legal notice and must not vanish from the PDF without a warning."; + let frame = s.execute("frame.create", &json!({"rect": [20, 20, 280, 60], "content": "text", "text": text})).unwrap(); + let (id, sid) = (frame["id"].as_u64().unwrap(), frame["story"].clone()); + + // What preflight says about the same frame, for the warning to agree with. + let issues = s.execute("preflight.run", &json!({})).unwrap(); + let overset = issues["issues"].as_array().unwrap().iter().find(|i| i["kind"] == "overset").expect("preflight reports it").clone(); + assert_eq!(overset["message"], "Overset text: 76 characters"); + + for command in ["file.exportPdf", "file.exportPptx"] { + let r = s.execute(command, &json!({})).unwrap(); + let warnings = r["warnings"].as_array().expect("warnings").clone(); + let about: Vec<&str> = warnings.iter().filter_map(|w| w.as_str()).filter(|w| w.contains("not in the export")).collect(); + assert_eq!(about.len(), 1, "{command}: {warnings:?}"); + let w = about[0]; + assert!(w.contains("page 1"), "{command}: the page it is on: {w}"); + assert!(w.contains("76 character"), "{command}: the count preflight gives: {w}"); + assert!(w.contains(&format!("frame {id}")), "{command}: the frame: {w}"); + } + + // The pages being exported are the ones reported on: page 2 has no overset frame. + let r = s.execute("file.exportPdf", &json!({"pages": [2]})).unwrap(); + assert_eq!(r["warnings"], json!([]), "{r}"); + + // A reflowable export carries the whole story, so it has nothing to report. + let r = s.execute("file.exportHtml", &json!({})).unwrap(); + assert_eq!(r["warnings"], json!([]), "{r}"); + assert!(r["text"].as_str().unwrap().contains("must not vanish"), "the HTML has the text the PDF left out"); + + // `overset` is the index where the text stops fitting; `oversetChars` is how much is left, + // which is the number preflight reports. The two were read as the same thing. + let story = s.execute("story.get", &json!({"story": sid})).unwrap(); + assert_eq!(story["overset"], json!(68), "{story}"); + assert_eq!(story["oversetChars"], json!(76), "{story}"); + + // A frame the text fits: nothing is reported anywhere. + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 300, "height": 200, "pages": 1, "facingPages": false, "margins": 0})).unwrap(); + let frame = s.execute("frame.create", &json!({"rect": [20, 20, 280, 180], "content": "text", "text": "Short."})).unwrap(); + for command in ["file.exportPdf", "file.exportPptx"] { + assert_eq!(s.execute(command, &json!({})).unwrap()["warnings"], json!([]), "{command}"); + } + let story = s.execute("story.get", &json!({"story": frame["story"].clone()})).unwrap(); + assert!(story["overset"].is_null() && story["oversetChars"].is_null(), "{story}"); + } + + /// A sheet draws its spread's items without asking which page each one sits on, so a frame + /// straddling two pages is drawn, in part, on both. Choosing the page by the frame's centre + /// alone meant a frame centred on a page the export leaves out had its warning dropped while + /// the part on an exported page went into the file (#1493 review). + #[test] + fn an_export_warns_about_a_frame_that_only_crosses_into_one_of_its_pages() { + let mut s = Session::new(); + // Facing pages, so pages 2 and 3 are one spread and a frame can straddle their boundary. + s.execute("file.new", &json!({"width": 300, "height": 200, "pages": 4, "facingPages": true, "margins": 0})).unwrap(); + let text = "First line is visible.\nSecond paragraph does not fit: this sentence carries the legal notice and must not vanish from the PDF without a warning."; + // Spread 1 is pages 2-3; its page 2 runs x 0..300 and page 3 runs x 300..600. The frame + // is centred on page 3 and reaches back over the boundary into page 2. + let frame = json!({"spread": 1, "rect": [260, 20, 420, 60], "content": "text", "text": text}); + let id = s.execute("frame.create", &frame).unwrap()["id"].as_u64().unwrap(); + + let about = |s: &mut Session, pages: serde_json::Value| { + let params = if pages.is_null() { json!({}) } else { json!({"pages": pages}) }; + let r = s.execute("file.exportPdf", ¶ms).unwrap(); + let ws = r["warnings"].as_array().cloned().unwrap_or_default(); + ws.iter().filter_map(|w| w.as_str()).filter(|w| w.contains("not in the export")).map(str::to_owned).collect::>() + }; + + // The whole document: reported once, at the page the frame is centred on. + let all = about(&mut s, serde_json::Value::Null); + assert_eq!(all.len(), 1, "{all:?}"); + assert!(all[0].contains("page 3") && all[0].contains(&format!("frame {id}")), "{}", all[0]); + + // Exporting page 3 alone: the centre page, reported as before. + let three = about(&mut s, json!([3])); + assert_eq!(three.len(), 1, "{three:?}"); + assert!(three[0].contains("page 3"), "{}", three[0]); + + // Exporting page 2 alone: the frame's centre is on page 3, which is not in the export -- + // but part of the frame is drawn on page 2, so it is still reported, and the page named is + // one the export has. + let two = about(&mut s, json!([2])); + assert_eq!(two.len(), 1, "a frame crossing into page 2 is reported: {two:?}"); + assert!(two[0].contains("page 2"), "and the page it names is an exported one: {}", two[0]); + assert!(two[0].contains(&format!("frame {id}")), "{}", two[0]); + + // A page the frame does not reach at all: nothing to say. + assert_eq!(about(&mut s, json!([4])), Vec::::new()); + } + + /// `overset` indexes `text` in UTF-8 bytes, not characters: a client that slices a JavaScript + /// string at it cuts the wrong place once the text is not ASCII (noted in review). + #[test] + fn overset_is_a_byte_offset_into_the_text() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 300, "height": 200, "pages": 1, "facingPages": false, "margins": 0})).unwrap(); + // Accented letters are two bytes each, so the byte offset runs ahead of the character index. + let text = "Réservé à l'évaluation détaillée des éléments.\nCette phrase dépasse le cadre et n'est pas dans le PDF exporté du tout."; + let frame = s.execute("frame.create", &json!({"rect": [20, 20, 280, 40], "content": "text", "text": text})).unwrap(); + let story = s.execute("story.get", &json!({"story": frame["story"].clone()})).unwrap(); + let at = story["overset"].as_u64().expect("it oversets") as usize; + assert!(text.is_char_boundary(at), "a byte offset that splits no character: {at}"); + assert!(at > text[..at].chars().count(), "ahead of the character index: {at} bytes, {} characters", text[..at].chars().count()); + // And `oversetChars` counts characters, which is why the two numbers differ. + assert_eq!(story["oversetChars"], json!(text[at..].chars().count()), "{story}"); + } + + /// A parent page's frame is composed once per page that shows it: its page number marker is + /// that page's, so the same frame fits on page 1 and oversets on page 10 -- and a parent page + /// no exported page uses puts nothing in the file to be missing. Composing it once with no + /// page reported neither: every selection got the same unpaged warning (noted in review). + #[test] + fn a_parent_frame_is_checked_on_the_pages_that_show_it() { + let about = |r: &serde_json::Value| -> Vec { + r["warnings"] + .as_array() + .map(|w| w.iter().filter_map(|w| w.as_str()).filter(|w| w.contains("not in the export")).map(str::to_string).collect()) + .unwrap_or_default() + }; + + // A parent page that only page 1 uses. + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 300, "height": 200, "pages": 2, "facingPages": false, "margins": 0})).unwrap(); + s.execute("layout.pages.applyParent", &json!({"pages": [1], "parent": null})).unwrap(); + let text = "First line is visible.\nSecond paragraph does not fit: this sentence carries the legal notice and must not vanish from the PDF without a warning."; + let frame = s + .execute("frame.create", &json!({"spread": {"kind": "parent", "index": 0}, "rect": [20, 20, 280, 60], "content": "text", "text": text})) + .unwrap(); + let id = frame["id"].as_u64().unwrap(); + + let w = about(&s.execute("file.exportPdf", &json!({"pages": [1]})).unwrap()); + assert_eq!(w.len(), 1, "page 1 shows the parent: {w:?}"); + assert!(w[0].contains("page 1") && w[0].contains(&format!("frame {id}")) && w[0].contains("76 character"), "{}", w[0]); + + // Page 2 has no parent, so nothing of that frame is in its export to be missing. + let r = s.execute("file.exportPdf", &json!({"pages": [2]})).unwrap(); + assert!(about(&r).is_empty(), "page 2 does not use the parent: {r}"); + + // Page-dependent text: the marker is one digit up to page 9 and two from page 10, and the + // wider line no longer fits. 112 pt is the width where that is the only difference. + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 300, "height": 200, "pages": 12, "facingPages": false, "margins": 0})).unwrap(); + let text = format!("Continued on page {}", designcraft_doc::story::PAGE_NUMBER); + s.execute("frame.create", &json!({"spread": {"kind": "parent", "index": 0}, "rect": [20, 20, 132, 36], "content": "text", "text": text})) + .unwrap(); + + for page in [1, 9] { + let r = s.execute("file.exportPdf", &json!({"pages": [page]})).unwrap(); + assert!(about(&r).is_empty(), "page {page} fits one digit: {r}"); + } + let w = about(&s.execute("file.exportPdf", &json!({"pages": [10]})).unwrap()); + assert_eq!(w.len(), 1, "two digits do not fit: {w:?}"); + assert!(w[0].contains("page 10"), "{}", w[0]); + + // The whole document: one line naming every page it happens on, not one line per page. + let w = about(&s.execute("file.exportPdf", &json!({})).unwrap()); + assert_eq!(w.len(), 1, "one line for the story: {w:?}"); + assert!(w[0].starts_with("pages 10, 11, 12:"), "{}", w[0]); + } + + /// A spread export puts the whole spread on the sheet, so choosing one page of it exports its + /// partner too -- and that partner's overset is just as absent from the file. Reporting only + /// the pages that were named left it unmentioned (noted in review of #1465). + #[test] + fn a_spread_export_warns_about_the_pages_it_takes_with_it() { + let mut s = Session::new(); + // Facing pages: 2 and 3 share a spread, 1 is the cover on its own. + s.execute("file.new", &json!({"width": 200, "height": 200, "pages": 4, "facingPages": true, "margins": 0})).unwrap(); + let text = "First line is visible.\nSecond paragraph does not fit: this sentence carries the legal notice and must not vanish from the PDF without a warning."; + // A frame on page 3, whose text does not fit it. `frame.create` takes a spread and + // spread coordinates, so page 3's own bounds say where to put it. + let (si, b) = { + let d = &s.active().expect("a document").doc; + let (si, pi) = d.page_loc(2).expect("page 3 is there"); + (si, d.spreads[si].pages[pi].bounds()) + }; + let rect = json!([b.x0 + 20.0, b.y0 + 20.0, b.x0 + 180.0, b.y0 + 60.0]); + let frame = s.execute("frame.create", &json!({"spread": si, "rect": rect, "content": "text", "text": text})).unwrap(); + let id = frame["id"].as_u64().unwrap(); + let about = |r: &serde_json::Value| -> Vec { + r["warnings"] + .as_array() + .map(|w| w.iter().filter_map(|w| w.as_str()).filter(|w| w.contains("not in the export")).map(str::to_string).collect()) + .unwrap_or_default() + }; + + // Page by page, choosing page 2 reports nothing: page 2 holds no overset frame. + let r = s.execute("file.exportPdf", &json!({"pages": [2]})).unwrap(); + assert!(about(&r).is_empty(), "page 2 alone has nothing to report: {r}"); + + // As spreads, choosing page 2 exports page 3 with it, so page 3's overset is reported. + let r = s.execute("file.exportPdf", &json!({"pages": [2], "spreads": true})).unwrap(); + let w = about(&r); + assert_eq!(w.len(), 1, "the page that came along is reported too: {r}"); + assert!(w[0].contains("page 3") && w[0].contains(&format!("frame {id}")), "{}", w[0]); + + // And a page on another spread entirely is still not reported. + let r = s.execute("file.exportPdf", &json!({"pages": [1], "spreads": true})).unwrap(); + assert!(about(&r).is_empty(), "the cover's spread holds no overset frame: {r}"); + } + + /// Plain print exports attach `/DefaultCMYK` without `/OutputIntents`, PDF/X-4 keeps both + /// cleanly, and PDF/X-1a omits `/DefaultCMYK`. + #[test] + fn export_pdf_command_attaches_default_cmyk_according_to_standard() { + let mut s = Session::new(); + s.execute("file.new", &json!({"intent": "print"})).unwrap(); + s.execute("frame.create", &json!({"rect": [36, 36, 200, 200]})).unwrap(); + s.execute("swatch.create", &json!({"name": "Slate", "color": {"c": 42.5, "m": 17.5, "y": 16.0, "k": 7.1}})).unwrap(); + s.execute("object.fill", &json!({"swatch": "Slate"})).unwrap(); + + let export = |s: &mut Session, extra: serde_json::Value| { + let res = s.execute("file.exportPdf", &extra).unwrap(); + let raw = crate::cmd::base64_decode(res["base64"].as_str().unwrap()); + (raw, res["warnings"].clone()) + }; + + let (plain, plain_w) = export(&mut s, json!({"tagged": true})); + assert_eq!(plain_w, json!([]), "plain export warnings: {plain_w}"); + let plain_text = String::from_utf8_lossy(&plain); + assert!(plain_text.contains("/DefaultCMYK ["), "plain export must carry /DefaultCMYK"); + assert!(!plain_text.contains("/OutputIntents"), "plain export must not carry /OutputIntents"); + + let (x4, x4_w) = export(&mut s, json!({"standard": "x4"})); + assert_eq!(x4_w, json!([]), "PDF/X-4 warnings: {x4_w}"); + let x4_text = String::from_utf8_lossy(&x4); + assert!(x4_text.contains("/DefaultCMYK ["), "PDF/X-4 export must carry /DefaultCMYK"); + assert!(x4_text.contains("/OutputIntents"), "PDF/X-4 export must keep /OutputIntents"); + + let (x1a, _) = export(&mut s, json!({"standard": "x1a"})); + let x1a_text = String::from_utf8_lossy(&x1a); + assert!(!x1a_text.contains("/DefaultCMYK"), "PDF/X-1a must not carry ICCBased DefaultCMYK"); + } +} diff --git a/crates/engine/src/cmd/export/registry.rs b/crates/engine/src/cmd/export/registry.rs index 5f7f1d013..312628822 100644 --- a/crates/engine/src/cmd/export/registry.rs +++ b/crates/engine/src/cmd/export/registry.rs @@ -5,7 +5,7 @@ use super::{CommandSpec, Value, cmd, has_doc, json}; pub fn specs() -> Vec { vec![ cmd!(noundo "file.exportPdf", "Export PDF…", ["File"], None, - "{path?, pages?: \"1-3,5\" | [1,3] (1-based positions; default all), flatten?: high|medium|low|ppi (Transparency Flattener: spreads with transparency are rasterised; with standard x1a, the resolution complex transparent regions are rasterized at: high 300, medium 150, low 72, default 300), spreads?: bool, fullScreen?: bool, bookmarksPanel?: bool, pageLayout?: single|continuous|twoUp|twoUpCover|twoUpContinuous, view?: fitPage|fitWidth|actual, advanceSeconds?: number (interactive PDF), bleed?: bool (document bleed), marks?: bool | {crop?, bleed?, pageInfo?, weight?, offset?}, standard?: \"none\"|\"x4\"|\"x1a\"|\"a2b\" (x1a: PDF/X-1a:2003, the PDF/X-4 file flattened in its inks by craft-prepress: no transparency, only CMYK, gray and spot color), compressImages?: bool, tagged?: bool (structure tree: stories as paragraphs, figures with alt text), media?: bool (interactive: embed placed video and sound), title?, author?, created?: int (creation date in Unix seconds; default now, for reproducible files)} → {path, bytes, pages, warnings} (no path: {base64, …})", + "{path?, pages?: \"1-3,5\" | [1,3] (1-based positions: \"1\" is the first page, which ui.render and app.export take as page 0; default all), flatten?: high|medium|low|ppi (Transparency Flattener: spreads with transparency are rasterised; with standard x1a, the resolution complex transparent regions are rasterized at: high 300, medium 150, low 72, default 300), spreads?: bool, fullScreen?: bool, bookmarksPanel?: bool, pageLayout?: single|continuous|twoUp|twoUpCover|twoUpContinuous, view?: fitPage|fitWidth|actual, advanceSeconds?: number (interactive PDF), bleed?: bool (document bleed), marks?: bool | {crop?, bleed?, pageInfo?, weight?, offset?}, standard?: \"none\"|\"x4\"|\"x1a\"|\"a2b\" (x1a: PDF/X-1a:2003, the PDF/X-4 file flattened in its inks by craft-prepress: no transparency, only CMYK, gray and spot color), compressImages?: bool, tagged?: bool (structure tree: stories as paragraphs, figures with alt text), media?: bool (interactive: embed placed video and sound), title?, author?, created?: int (creation date in Unix seconds; default now, for reproducible files)} → {path, bytes, pages, warnings} (no path: {base64, …})", has_doc, export_pdf), cmd!(noundo "file.exportEpub", "Export EPUB (Reflowable)…", ["File"], None, "{path?, title?, author?, language?: \"en\", identifier?: str (dc:identifier; a stable urn:uuid by default), coverImage?: path (a PNG or JPEG as the cover), tocTitle?: str (the table of contents' title; from the language by default), cover?: bool (the first page as the cover image), embedFonts?: bool (package the stylesheet's fonts whose licence allows it, whole files), split?: \"off\"|\"exportTags\"|{style: name} (Split Document for this export, not stored; the document's `document.epubSplit` by default), fixedLayout?: bool (pre-paginated: each page as an image with its text)} → {path, bytes, warnings} (no path: {base64, bytes, warnings}); warnings name images without alt text, exported as decorative, and fonts that could not be embedded", diff --git a/crates/engine/src/cmd/export/text_tests.rs b/crates/engine/src/cmd/export/text_tests.rs index e533320f8..48e255ef7 100644 --- a/crates/engine/src/cmd/export/text_tests.rs +++ b/crates/engine/src/cmd/export/text_tests.rs @@ -92,6 +92,25 @@ fn epub_cover_and_fixed_layout() { assert!(p1.contains("width=612, height=792") && p1.contains("Page one words"), "{p1}"); } +/// Fixed-layout page text leaves out frames in a multi-state object's inactive states. +#[test] +fn fixed_epub_text_skips_inactive_states() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let a = s.execute("frame.create", &json!({"rect": [72, 72, 200, 100], "content": "text", "text": "Active words", "caret": false})).unwrap()["id"] + .as_u64() + .unwrap(); + let b = + s.execute("frame.create", &json!({"rect": [72, 300, 200, 100], "content": "text", "text": "Inactive words", "caret": false})).unwrap()["id"] + .as_u64() + .unwrap(); + s.execute("states.create", &json!({"ids": [a, b]})).unwrap(); + let r = s.execute("file.exportFixedEpub", &json!({})).unwrap(); + let mut z = unzip(r["base64"].as_str().unwrap()); + let p1 = read(&mut z, "OEBPS/page1.xhtml"); + assert!(p1.contains("Active words") && !p1.contains("Inactive words"), "{p1}"); +} + /// #775: the fallback follows the font's class, and embedFonts packages the stylesheet's fonts /// (and reports those it can't). #[test] @@ -204,12 +223,12 @@ fn black_and_gold(pdf: &[u8]) -> Vec<(u8, u8)> { let mut out = Vec::new(); for st in file.objects().into_iter().filter_map(|o| o.into_stream()) { let d = st.dict(); - if !d.get::>(b"Subtype").is_some_and(|n| n.as_ref() == b"Image") || d.get::(b"BitsPerComponent") != Some(8) { + if d.get::>(b"Subtype").is_none_or(|n| n.as_ref() != b"Image") || d.get::(b"BitsPerComponent") != Some(8) { continue; } let Some(cs) = d.get::>(b"ColorSpace") else { continue }; let mut it = cs.iter::>(); - if !it.next().and_then(|o| o.into_name()).is_some_and(|n| n.as_ref() == b"DeviceN") { + if it.next().and_then(|o| o.into_name()).is_none_or(|n| n.as_ref() != b"DeviceN") { continue; } let Some(Object::Array(names)) = it.next() else { continue }; @@ -376,3 +395,121 @@ fn export_story_as_text_and_rtf() { assert!(std::fs::read_to_string(&path).unwrap().starts_with("{\\rtf1")); std::fs::remove_dir_all(&dir).ok(); } + +fn linked_effect_frame() -> (Session, designcraft_doc::ItemId) { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 72, "height": 72})).unwrap(); + let frame = s.execute("frame.create", &json!({"rect": [10, 10, 30, 30], "content": "text", "text": "Link", "caret": false})).unwrap(); + let id = designcraft_doc::ItemId(frame["id"].as_u64().unwrap()); + s.execute("hyperlink.create", &json!({"url": "https://example.com", "ids": [id.0]})).unwrap(); + s.execute("object.feather", &json!({"ids": [id.0], "width": 2})).unwrap(); + (s, id) +} + +#[test] +fn rasterized_links_leave_no_stand_in_for_other_formats() { + let (s, _) = linked_effect_frame(); + let d = &s.doc().unwrap().doc; + let mut unlinked = (**d).clone(); + unlinked.hyperlinks.clear(); + for keep_wrap in [false, true] { + let (linked, n) = super::flatten::rasterize_where(d, &s.cache, 144.0, keep_wrap, |_| true); + let (plain, plain_n) = super::flatten::rasterize_where(&unlinked, &s.cache, 144.0, keep_wrap, |_| true); + assert_eq!(n, 1); + assert_eq!(plain_n, 1); + assert_eq!(linked.unwrap().spreads[0].items.len(), plain.unwrap().spreads[0].items.len(), "keep_wrap={keep_wrap}"); + } +} + +fn assert_link_stand_in_is_inert(item: &designcraft_doc::Item) { + assert!(item.nonprinting, "every stand-in item is nonprinting"); + assert!(item.form_field.is_none(), "stand-ins must not emit form fields"); + assert!(item.button.is_none(), "stand-ins must not emit buttons"); + assert!(item.media.is_none(), "stand-ins must not emit media"); + for child in item.children() { + assert_link_stand_in_is_inert(child); + } +} + +#[test] +fn rasterized_links_clear_interactivity_on_frames() { + let (mut s, id) = linked_effect_frame(); + let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let item = d.item_mut(id).unwrap(); + item.button = Some(designcraft_doc::ButtonAction::GoToFirstPage); + item.media = Some(Default::default()); + let story = item.text_frame().unwrap().story; + let (copy, n) = super::rasterize_effects(&s.doc().unwrap().doc, &s.cache, &Default::default()); + assert_eq!(n, 1); + let copy = copy.unwrap(); + let stand_in = copy.item(id).unwrap(); + assert_link_stand_in_is_inert(stand_in); + assert_eq!(stand_in.text_frame().unwrap().story, story); +} + +#[test] +fn rasterized_links_clear_interactivity_in_nested_groups() { + let (mut s, id) = linked_effect_frame(); + let other = s.execute("frame.create", &json!({"rect": [35, 10, 45, 20]})).unwrap()["id"].clone(); + let inner = s.execute("object.group", &json!({"ids": [id.0, other]})).unwrap()["id"].clone(); + let other = s.execute("frame.create", &json!({"rect": [35, 25, 45, 35]})).unwrap()["id"].clone(); + let group = s.execute("object.group", &json!({"ids": [inner, other]})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.feather", &json!({"ids": [group], "width": 2})).unwrap(); + let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let child = d.item_mut(id).unwrap(); + child.form_field = Some(designcraft_doc::FormField { + kind: designcraft_doc::FieldKind::TextField, + name: "Field".into(), + value: String::new(), + options: Vec::new(), + multiline: false, + required: false, + font_size: 0.0, + }); + child.button = Some(designcraft_doc::ButtonAction::GoToFirstPage); + child.media = Some(Default::default()); + let story = child.text_frame().unwrap().story; + let (copy, n) = super::rasterize_effects(&s.doc().unwrap().doc, &s.cache, &Default::default()); + assert_eq!(n, 1); + let copy = copy.unwrap(); + assert_link_stand_in_is_inert(copy.item(designcraft_doc::ItemId(group)).unwrap()); + assert_eq!(copy.item(id).unwrap().text_frame().unwrap().story, story); +} + +/// The stand-in keeps the frame's story, alt text and effects for link bounds, but being +/// nonprinting none of it reaches a tagged PDF: only the link annotation is added. +#[test] +fn rasterized_link_stand_ins_add_only_the_link_to_tagged_pdf() { + let tagged = |keep_link: bool| { + let (mut s, id) = linked_effect_frame(); + s.execute("object.exportOptions", &json!({"ids": [id.0], "altText": "A link"})).unwrap(); + if !keep_link { + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).hyperlinks.clear(); + } + let r = s.execute("file.exportPdf", &json!({"tagged": true})).unwrap(); + String::from_utf8_lossy(&super::super::file::base64_decode(r["base64"].as_str().unwrap())).into_owned() + }; + // Whole names only: `/Tabs/S/Parent` on a page with annotations is not a `/S/P` element. + let count = + |pdf: &str, tag: &str| pdf.match_indices(tag).filter(|(i, _)| !pdf[i + tag.len()..].starts_with(|c: char| c.is_ascii_alphabetic())).count(); + let (linked, plain) = (tagged(true), tagged(false)); + assert_eq!(count(&linked, "/S/Figure"), 1); + for tag in ["/S/Figure", "/S/P", "/Alt", "(A link)"] { + assert_eq!(count(&linked, tag), count(&plain, tag), "{tag}"); + } + assert!(linked.contains("/Subtype/Link") && !plain.contains("/Subtype/Link")); +} + +#[test] +fn rasterized_links_keep_exactly_one_wrapping_stand_in() { + let (mut s, id) = linked_effect_frame(); + s.execute("object.textWrap", &json!({"ids": [id.0], "mode": "boundingBox", "offset": 3})).unwrap(); + let before = s.doc().unwrap().doc.item(id).unwrap().wrap.clone(); + let (copy, n) = super::rasterize_effects(&s.doc().unwrap().doc, &s.cache, &Default::default()); + assert_eq!(n, 1); + let copy = copy.unwrap(); + assert_eq!(copy.spreads[0].items.len(), 2); + assert_eq!(copy.spreads[0].items.iter().filter(|it| it.nonprinting).count(), 1); + assert_eq!(copy.item(id).unwrap().wrap, before); + assert_ne!(before.mode, designcraft_doc::WrapMode::None); +} diff --git a/crates/engine/src/cmd/export_batch.rs b/crates/engine/src/cmd/export_batch.rs new file mode 100644 index 000000000..3b24f60c9 --- /dev/null +++ b/crates/engine/src/cmd/export_batch.rs @@ -0,0 +1,624 @@ +//! File › Export Layouts and Versions: the document's alternate layouts, one file per layout or +//! all in one, in several versions at once (a press PDF with marks and bleed, a screen PDF, PNG or +//! JPEG images…), each version in a folder of its own, named from a template. A job can be saved +//! as a preset and run again. + +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; + +use super::{CommandSpec, bad, cmd, has_doc, ok, str_param}; +use crate::{EngineError, Result, Session}; + +const ID: &str = "file.exportBatch"; +/// The most files one export writes. +const MAX_FILES: usize = 5_000; +/// The most versions in a job. +const MAX_VERSIONS: usize = 24; +/// The most pixels in one exported image (the limit EPUB page images have: an RGBA buffer of +/// about 320 MB before encoding). +const MAX_PIXELS: f64 = 8.0e7; +/// The most characters in a file or folder name. +const MAX_NAME: usize = 120; +/// The most bytes an export returns in its reply (no `dir`): past it, export to a folder. +const MAX_INLINE_BYTES: usize = 512 << 20; +/// The most saved export presets, and the longest preset name. +const MAX_PRESETS: usize = 100; +const MAX_PRESET_NAME: usize = 80; + +/// What a version is exported as. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum ExportFormat { + #[default] + Pdf, + Png, + Jpeg, +} + +impl ExportFormat { + pub fn ext(self) -> &'static str { + match self { + ExportFormat::Pdf => "pdf", + ExportFormat::Png => "png", + ExportFormat::Jpeg => "jpg", + } + } +} + +/// Printer's marks of a PDF version. +#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(default, rename_all = "camelCase")] +pub struct VersionMarks { + pub crop: bool, + pub bleed: bool, + pub page_info: bool, +} + +/// One output of a job: a format and its settings. Its name is its folder. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default, rename_all = "camelCase")] +pub struct ExportVersion { + pub name: String, + pub format: ExportFormat, + /// PDF: the document's bleed. + pub bleed: bool, + /// PDF: printer's marks. + pub marks: VersionMarks, + /// PDF: none | x4 | a2b. + pub standard: String, + /// PDF: spreads rather than pages. + pub spreads: bool, + /// PDF: downsample and compress images. + pub compress_images: bool, + /// PNG / JPEG: pixels per inch. + pub ppi: f64, + /// JPEG: quality, 1–100. + pub quality: u8, +} + +impl Default for ExportVersion { + fn default() -> Self { + ExportVersion { + name: "PDF".into(), + format: ExportFormat::Pdf, + bleed: false, + marks: VersionMarks::default(), + standard: "none".into(), + spreads: false, + compress_images: false, + ppi: 150.0, + quality: 85, + } + } +} + +/// An export job (and what a preset keeps). +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default, rename_all = "camelCase")] +pub struct ExportJob { + /// The layouts to export, by name (empty: all of them). + pub layouts: Vec, + /// PDF versions: all the chosen layouts in one file rather than a file per layout. + pub combine: bool, + /// File name template: {document}, {layout}, {version}, {date}. + pub file_name: String, + pub versions: Vec, + /// Each version in a folder of its own (named after it). + pub folders: bool, +} + +impl Default for ExportJob { + fn default() -> Self { + ExportJob { layouts: Vec::new(), combine: false, file_name: "{document} - {layout}".into(), versions: vec![], folders: true } + } +} + +/// A saved export preset. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(default, rename_all = "camelCase")] +pub struct ExportPreset { + pub name: String, + pub job: ExportJob, +} + +/// The ready-made versions: a press PDF (crop and bleed marks, bleed), a PDF with bleed and no +/// marks, a screen PDF, and PNG and JPEG images. +pub fn version_templates() -> Vec { + let pdf = ExportVersion::default(); + vec![ + ExportVersion { + name: "PDF Print (marks + bleed)".into(), + bleed: true, + marks: VersionMarks { crop: true, bleed: true, page_info: true }, + ..pdf.clone() + }, + ExportVersion { name: "PDF Bleed (no marks)".into(), bleed: true, ..pdf.clone() }, + ExportVersion { name: "PDF Screen".into(), compress_images: true, ..pdf.clone() }, + ExportVersion { name: "PNG".into(), format: ExportFormat::Png, ..pdf.clone() }, + ExportVersion { name: "JPEG".into(), format: ExportFormat::Jpeg, ..pdf }, + ] +} + +/// The built-in presets, listed before the saved ones; they can't be replaced or deleted. +pub fn builtin_presets() -> Vec { + let t = version_templates(); + let pick = |names: &[&str]| -> Vec { t.iter().filter(|v| names.contains(&v.name.as_str())).cloned().collect() }; + vec![ + ExportPreset { + name: "Print + Screen".into(), + job: ExportJob { versions: pick(&["PDF Print (marks + bleed)", "PDF Screen", "PNG"]), ..ExportJob::default() }, + }, + ExportPreset { + name: "Press PDF per Layout".into(), + job: ExportJob { versions: pick(&["PDF Print (marks + bleed)", "PDF Bleed (no marks)"]), ..ExportJob::default() }, + }, + ExportPreset { name: "Images per Layout".into(), job: ExportJob { versions: pick(&["PNG", "JPEG"]), ..ExportJob::default() } }, + ExportPreset { + name: "All Layouts in One PDF".into(), + job: ExportJob { + combine: true, + folders: false, + file_name: "{document}".into(), + versions: pick(&["PDF Bleed (no marks)"]), + ..ExportJob::default() + }, + }, + ] +} + +pub fn specs() -> Vec { + vec![ + cmd!(noundo "file.exportBatch", "Export Layouts and Versions…", ["File"], None, + "{job?: {layouts?: [layout names] (default all), combine?: bool (PDF: all the layouts in one file), fileName?: \"{document} - {layout}\" (also {version}, {date}), versions: [{name, format: pdf|png|jpeg, bleed?, marks?: {crop?, bleed?, pageInfo?}, standard?: none|x4|a2b, spreads?, compressImages?, ppi?: 150, quality?: 85}], folders?: bool (default true: a folder per version)}, preset?: name (instead of or under `job`), dir?: folder to write into, dryRun?: bool (list the files only), date?: \"YYYY-MM-DD\" (for {date})} → {files: [{path, version, layout, pages, bytes, base64? (no dir)}], warnings}", + has_doc, export_batch), + cmd!(query "file.exportPresets", "Export Presets", [], None, + "{} → {presets: [{name, job, builtIn}], versions: [the ready-made versions]}", super::always, |s, _| { + let mut presets: Vec = builtin_presets().into_iter().map(|p| json!({"name": p.name, "job": p.job, "builtIn": true})).collect(); + presets.extend(s.prefs.export_presets.iter().map(|p| json!({"name": p.name, "job": p.job, "builtIn": false}))); + Ok(json!({"presets": presets, "versions": version_templates()})) + }), + cmd!(noundo "file.saveExportPreset", "Save Export Preset", [], None, + "{name, job} — kept with the preferences; a saved preset of that name is replaced, built-in names are refused", super::always, save_preset), + cmd!(noundo "file.deleteExportPreset", "Delete Export Preset", [], None, "{name} — a saved export preset", super::always, |s, p| { + let name = str_param(p, "name").unwrap_or_default().trim().to_string(); + let before = s.prefs.export_presets.len(); + s.prefs.export_presets.retain(|x| !x.name.eq_ignore_ascii_case(&name)); + if s.prefs.export_presets.len() == before { + return Err(bad("file.deleteExportPreset", format!("no saved export preset `{name}`"))); + } + ok() + }), + ] +} + +fn save_preset(s: &mut Session, p: &Value) -> Result { + const CMD: &str = "file.saveExportPreset"; + let name = str_param(p, "name").map(str::trim).filter(|n| !n.is_empty()).ok_or_else(|| bad(CMD, "missing `name`"))?.to_string(); + if name.chars().count() > MAX_PRESET_NAME { + return Err(bad(CMD, format!("a preset name has at most {MAX_PRESET_NAME} characters"))); + } + if builtin_presets().iter().any(|b| b.name.eq_ignore_ascii_case(&name)) { + return Err(bad(CMD, format!("`{name}` is a built-in preset"))); + } + let job = job_param(CMD, p.get("job").ok_or_else(|| bad(CMD, "missing `job`"))?)?; + let presets = &mut s.prefs.export_presets; + presets.retain(|x| !x.name.eq_ignore_ascii_case(&name)); + if presets.len() >= MAX_PRESETS { + return Err(bad(CMD, format!("at most {MAX_PRESETS} saved export presets"))); + } + presets.push(ExportPreset { name: name.clone(), job }); + Ok(json!({"name": name})) +} + +/// A job from JSON, checked: versions present and sane, numbers in range. +fn job_param(cmd: &str, v: &Value) -> Result { + let mut job: ExportJob = serde_json::from_value(v.clone()).map_err(|e| bad(cmd, format!("bad `job`: {e}")))?; + if job.versions.is_empty() { + return Err(bad(cmd, "a job needs at least one version")); + } + if job.versions.len() > MAX_VERSIONS { + return Err(bad(cmd, format!("at most {MAX_VERSIONS} versions"))); + } + if job.file_name.chars().count() > 400 { + return Err(bad(cmd, "the file name template is too long")); + } + for v in &mut job.versions { + if !v.ppi.is_finite() { + return Err(bad(cmd, format!("version `{}`: `ppi` is a number", v.name))); + } + v.ppi = v.ppi.clamp(36.0, 1200.0); + v.quality = v.quality.clamp(1, 100); + if designcraft_pdf::Standard::parse(&v.standard).is_none() { + return Err(bad(cmd, format!("version `{}`: unknown standard `{}` (none, x4, a2b)", v.name, v.standard))); + } + } + Ok(job) +} + +/// The pages (absolute, 0-based) of each chosen layout, by name; `names` empty: every layout. +pub(crate) fn layout_pages(cmd: &str, d: &designcraft_doc::Document, names: &[String]) -> Result)>> { + let layouts = d.layouts(); + if names.is_empty() { + return Ok(layouts.into_iter().map(|l| (l.name, (l.start..l.end).collect())).collect()); + } + for n in names { + if !layouts.iter().any(|l| l.name == *n) { + return Err(bad(cmd, format!("no layout `{n}`"))); + } + } + // In document order, whatever order they were named in. + Ok(layouts.into_iter().filter(|l| names.contains(&l.name)).map(|l| (l.name, (l.start..l.end).collect())).collect()) +} + +/// `s` as a file or folder name: no path separators, reserved or control characters, no leading +/// dots, no Windows device name (`CON`, `NUL`… get a leading `_`), at most [`MAX_NAME`] +/// characters; "Untitled" when nothing is left. +pub fn safe_name(s: &str) -> String { + let cleaned: String = s.chars().map(|c| if c.is_control() || r#"/\:*?"<>|"#.contains(c) { ' ' } else { c }).collect(); + let words: Vec<&str> = cleaned.split_whitespace().collect(); + let joined = words.join(" "); + let trimmed = joined.trim_start_matches('.').trim(); + let capped: String = trimmed.chars().take(MAX_NAME).collect(); + let capped = capped.trim_end_matches(['.', ' ']).to_string(); + if capped.is_empty() { + "Untitled".into() + } else if crate::file_access::is_device_name(&capped) { + format!("_{capped}") + } else { + capped + } +} + +/// `name.ext`, or `name 2.ext`, `name 3.ext`… when `taken` has it (case-insensitively). +fn unique(taken: &mut Vec, name: &str, ext: &str) -> String { + let mut k = 1usize; + loop { + let candidate = if k == 1 { format!("{name}.{ext}") } else { format!("{name} {k}.{ext}") }; + if !taken.iter().any(|t| t.eq_ignore_ascii_case(&candidate)) { + taken.push(candidate.clone()); + return candidate; + } + k = k.saturating_add(1); + } +} + +/// Today as YYYY-MM-DD (UTC), where there is a clock (chrono, through `designcraft_doc::time`). +fn today() -> String { + #[cfg(not(target_arch = "wasm32"))] + { + let (y, date) = designcraft_doc::time::date_parts(designcraft_doc::vars::now().div_euclid(86_400)); + format!("{y:04}-{}", date.format("%m-%d")) + } + #[cfg(target_arch = "wasm32")] + String::new() +} + +/// One file a job writes. +struct Planned { + /// Relative to the export folder: `version folder/name.ext`. + path: String, + version: usize, + layout: String, + /// Absolute, 0-based. + pages: Vec, +} + +/// The files `job` writes, in order: for each version, a PDF per layout (or one for all), or an +/// image per page. +fn plan(s: &Session, job: &ExportJob, date: &str) -> Result> { + let d = &s.doc()?.doc; + let groups = layout_pages(ID, d, &job.layouts)?; + if groups.iter().all(|(_, p)| p.is_empty()) { + return Err(bad(ID, "the chosen layouts have no pages")); + } + let document = if d.title.trim().is_empty() { "Untitled" } else { d.title.as_str() }; + let mut out = Vec::new(); + let mut folders: Vec = Vec::new(); + for (vi, v) in job.versions.iter().enumerate() { + let folder = if job.folders { + let f = safe_name(&v.name); + // Two versions with one name share no folder. + let f = unique(&mut folders, &f, "").trim_end_matches('.').to_string(); + format!("{f}/") + } else { + String::new() + }; + let mut taken: Vec = out.iter().filter_map(|p: &Planned| p.path.strip_prefix(folder.as_str()).map(str::to_string)).collect(); + let name = |layout: &str| { + safe_name( + &job.file_name.replace("{document}", document).replace("{layout}", layout).replace("{version}", &v.name).replace("{date}", date), + ) + }; + match v.format { + ExportFormat::Pdf if job.combine => { + let pages: Vec = groups.iter().flat_map(|(_, p)| p.iter().copied()).collect(); + let file = unique(&mut taken, &name("All Layouts"), "pdf"); + out.push(Planned { path: format!("{folder}{file}"), version: vi, layout: "All Layouts".into(), pages }); + } + ExportFormat::Pdf => { + for (layout, pages) in groups.iter().filter(|(_, p)| !p.is_empty()) { + let file = unique(&mut taken, &name(layout), "pdf"); + out.push(Planned { path: format!("{folder}{file}"), version: vi, layout: layout.clone(), pages: pages.clone() }); + } + } + ExportFormat::Png | ExportFormat::Jpeg => { + for (layout, pages) in &groups { + let base = name(layout); + for &abs in pages { + let stem = safe_name(&format!("{base} - {}", s.page_label(abs))); + let file = unique(&mut taken, &stem, v.format.ext()); + out.push(Planned { path: format!("{folder}{file}"), version: vi, layout: layout.clone(), pages: vec![abs] }); + } + } + } + } + if out.len() > MAX_FILES { + return Err(bad(ID, format!("the export would write more than {MAX_FILES} files"))); + } + } + Ok(out) +} + +/// The `file.exportPdf` parameters of a PDF version for `pages` (absolute, 0-based). +fn pdf_params(v: &ExportVersion, pages: &[usize], title: &str) -> Value { + json!({ + "pages": pages.iter().map(|p| p.saturating_add(1)).collect::>(), + "bleed": v.bleed, + "marks": {"crop": v.marks.crop, "bleed": v.marks.bleed, "pageInfo": v.marks.page_info}, + "standard": v.standard, + "spreads": v.spreads, + "compressImages": v.compress_images, + "tagged": true, + "title": title, + }) +} + +/// The bytes of one planned file. +fn render(s: &Session, v: &ExportVersion, f: &Planned) -> Result<(Vec, Vec)> { + let d = &s.doc()?.doc; + match v.format { + ExportFormat::Pdf => { + let r = super::export::pdf_report(d, &s.cache, &pdf_params(v, &f.pages, &d.title))?; + Ok((r.bytes, r.warnings)) + } + ExportFormat::Png | ExportFormat::Jpeg => { + let abs = f.pages.first().copied().ok_or_else(|| bad(ID, "no page"))?; + let page = d.page(abs).ok_or_else(|| bad(ID, format!("no page {}", abs.saturating_add(1))))?; + let scale = v.ppi / 72.0; + if page.width * scale * page.height * scale > MAX_PIXELS { + return Err(bad(ID, format!("page {} at {} ppi is too large for an image; lower the resolution", s.page_label(abs), v.ppi))); + } + let mut r = designcraft_render::Renderer::new(); + let opts = designcraft_render::RenderOptions { printing_only: true, rich_black: s.prefs.rich_black_output, ..Default::default() }; + let img = r.render_page(d, &s.cache, abs, scale, false, &opts).ok_or_else(|| bad(ID, "the page couldn't be rendered"))?; + Ok((if v.format == ExportFormat::Png { img.to_png() } else { img.to_jpeg(v.quality) }, vec![])) + } + } +} + +/// `e` for the file at `path`, saying how many files were written to disk before it (they stay). +fn partly(e: EngineError, path: &str, written: usize, to_disk: bool) -> EngineError { + if to_disk && written > 0 { bad(ID, format!("{path}: {e}; the {written} file(s) before it were written")) } else { e } +} + +/// Write `bytes` at `rel` inside `dir`, making the version's folder. +#[cfg(not(target_arch = "wasm32"))] +fn write_into(dir: &str, rel: &str, bytes: &[u8]) -> Result { + let path = std::path::Path::new(dir).join(rel); + if let Some(parent) = path.parent() { + crate::io::create_dir_all(parent).map_err(EngineError::Other)?; + } + let s = path.to_string_lossy().into_owned(); + crate::io::write_file(&s, bytes).map_err(EngineError::Other)?; + Ok(s) +} +#[cfg(target_arch = "wasm32")] +fn write_into(_dir: &str, _rel: &str, _bytes: &[u8]) -> Result { + Err(EngineError::Other("no file system on the web; omit `dir` to get the files".into())) +} + +fn export_batch(s: &mut Session, p: &Value) -> Result { + let job = match (p.get("job"), str_param(p, "preset")) { + (Some(j), _) => job_param(ID, j)?, + (None, Some(name)) => { + let preset = builtin_presets() + .into_iter() + .chain(s.prefs.export_presets.iter().cloned()) + .find(|x| x.name.eq_ignore_ascii_case(name.trim())) + .ok_or_else(|| bad(ID, format!("no export preset `{name}`")))?; + job_param(ID, &serde_json::to_value(&preset.job).map_err(|e| bad(ID, e.to_string()))?)? + } + (None, None) => return Err(bad(ID, "give a `job` or a `preset`")), + }; + let date = match str_param(p, "date") { + Some(d) => safe_name(d), + None => today(), + }; + let dir = str_param(p, "dir").map(str::to_string); + let planned = plan(s, &job, &date)?; + let dry = p.get("dryRun").and_then(Value::as_bool).unwrap_or(false); + let mut files = Vec::with_capacity(planned.len()); + let mut warnings: Vec = Vec::new(); + let mut inline = 0usize; + for f in &planned { + let v = job.versions.get(f.version).ok_or_else(|| bad(ID, "no such version"))?; + let mut entry = json!({ + "path": f.path, + "version": v.name, + "layout": f.layout, + "pages": f.pages.iter().map(|p| p.saturating_add(1)).collect::>(), + }); + if !dry { + let (bytes, w) = render(s, v, f).map_err(|e| partly(e, &f.path, files.len(), dir.is_some()))?; + for w in w { + let w = format!("{}: {w}", f.path); + if !warnings.contains(&w) { + warnings.push(w); + } + } + entry["bytes"] = json!(bytes.len()); + match &dir { + Some(dir) => entry["path"] = json!(write_into(dir, &f.path, &bytes).map_err(|e| partly(e, &f.path, files.len(), true))?), + None => { + inline = inline.saturating_add(bytes.len()); + if inline > MAX_INLINE_BYTES { + return Err(bad(ID, format!("the files come to more than {} MB: give a `dir` to export to", MAX_INLINE_BYTES >> 20))); + } + entry["base64"] = json!(super::base64_encode(&bytes)); + } + } + } + files.push(entry); + } + Ok(json!({"files": files, "warnings": warnings})) +} + +#[cfg(test)] +mod tests { + use serde_json::json; + + use super::*; + + fn two_layouts() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"pages": 2, "facingPages": false, "width": 300, "height": 400, "bleed": 9, "title": "Mag"})).unwrap(); + s.execute("frame.create", &json!({"rect": [20, 20, 200, 200]})).unwrap(); + s.execute("layout.createAlternate", &json!({"name": "Tablet H", "width": 400, "height": 300, "fromName": "Print"})).unwrap(); + s + } + + fn job(versions: &[&str]) -> Value { + let t = version_templates(); + let v: Vec<_> = versions.iter().map(|n| t.iter().find(|x| x.name == *n).unwrap().clone()).collect(); + json!({"versions": v}) + } + + fn paths(r: &Value) -> Vec { + r["files"].as_array().unwrap().iter().map(|f| f["path"].as_str().unwrap().to_string()).collect() + } + + #[test] + fn a_file_per_layout_and_version_in_folders() { + let mut s = two_layouts(); + let r = s.execute(ID, &json!({"job": job(&["PDF Print (marks + bleed)", "PNG"]), "dryRun": true})).unwrap(); + assert_eq!( + paths(&r), + [ + "PDF Print (marks + bleed)/Mag - Print.pdf", + "PDF Print (marks + bleed)/Mag - Tablet H.pdf", + "PNG/Mag - Print - 1.png", + "PNG/Mag - Print - 2.png", + "PNG/Mag - Tablet H - 1.png", + "PNG/Mag - Tablet H - 2.png", + ] + ); + assert_eq!(r["files"][1]["pages"], json!([3, 4])); + // One layout on its own, all layouts in one PDF, no folders, another name. + let mut one = job(&["PDF Screen"]); + one["layouts"] = json!(["Tablet H"]); + assert_eq!(paths(&s.execute(ID, &json!({"job": one, "dryRun": true})).unwrap()), ["PDF Screen/Mag - Tablet H.pdf"]); + let mut all = job(&["PDF Screen"]); + all["combine"] = json!(true); + all["folders"] = json!(false); + all["fileName"] = json!("{document} {version} {date}"); + let r = s.execute(ID, &json!({"job": all, "dryRun": true, "date": "2026-10-20"})).unwrap(); + assert_eq!(paths(&r), ["Mag PDF Screen 2026-10-20.pdf"]); + assert_eq!(r["files"][0]["pages"], json!([1, 2, 3, 4])); + } + + #[test] + fn the_export_renders_each_file() { + let mut s = two_layouts(); + let r = s.execute(ID, &json!({"job": job(&["PDF Print (marks + bleed)", "PDF Bleed (no marks)", "JPEG"])})).unwrap(); + let files = r["files"].as_array().unwrap(); + assert_eq!(files.len(), 2 + 2 + 4); + let bytes = |i: usize| super::super::file::base64_decode(files[i]["base64"].as_str().unwrap()); + for (i, f) in files.iter().enumerate().take(4) { + assert!(bytes(i).starts_with(b"%PDF-"), "{}", f["path"]); + } + assert!(bytes(4).starts_with(&[0xFF, 0xD8]), "a JPEG"); + // Marks need room around the bleed: the marked PDF's page is larger. + let size = |b: &[u8]| designcraft_render::pdf_page_size(b, 0).unwrap(); + let (marked, bled) = (size(&bytes(0)), size(&bytes(2))); + assert!(marked.0 > bled.0 && marked.1 > bled.1, "{marked:?} {bled:?}"); + assert_eq!(designcraft_render::pdf_page_count(&bytes(1)), Some(2)); + } + + #[test] + fn files_go_into_a_folder_per_version() { + let dir = tempfile::tempdir().unwrap(); + let mut s = two_layouts(); + let r = s.execute(ID, &json!({"preset": "Print + Screen", "dir": dir.path().to_str().unwrap()})).unwrap(); + assert_eq!(r["files"].as_array().unwrap().len(), 2 + 2 + 4); + for f in ["PDF Print (marks + bleed)/Mag - Print.pdf", "PDF Screen/Mag - Tablet H.pdf", "PNG/Mag - Tablet H - 2.png"] { + assert!(dir.path().join(f).is_file(), "{f}"); + } + let pdf = std::fs::read(dir.path().join("PDF Screen/Mag - Print.pdf")).unwrap(); + assert!(pdf.starts_with(b"%PDF-")); + } + + /// An export name drops reserved characters, and a Windows device name (`CON`, `COM¹`, `LPT³`) + /// is written with a leading `_`. Two files built from one name stay distinct. + #[test] + fn names_are_made_safe_and_unique() { + assert_eq!(safe_name("../a/b:c*?"), "a b c"); + assert_eq!(safe_name(" ... "), "Untitled"); + assert_eq!(safe_name(&"x".repeat(500)).chars().count(), MAX_NAME); + // Windows device names name no file. + for (name, safe) in + [("CON", "_CON"), ("nul", "_nul"), ("com1.x", "_com1.x"), ("COM¹", "_COM¹"), ("lpt³.x", "_lpt³.x"), ("Console", "Console")] + { + assert_eq!(safe_name(name), safe); + } + let mut s = two_layouts(); + let mut j = job(&["PNG", "PNG"]); + j["fileName"] = json!("../{document}"); + let r = s.execute(ID, &json!({"job": j, "dryRun": true})).unwrap(); + let p = paths(&r); + assert!(p.iter().all(|x| !x.contains("..")), "{p:?}"); + assert!(p.contains(&"PNG/Mag - 1.png".to_string()) && p.contains(&"PNG/Mag - 1 2.png".to_string()), "{p:?}"); + assert!(p.iter().any(|x| x.starts_with("PNG 2/")), "two versions, two folders: {p:?}"); + } + + #[test] + fn bad_jobs_are_refused() { + let mut s = two_layouts(); + for p in [ + json!({}), + json!({"job": {"versions": []}}), + json!({"job": {"versions": [{"format": "tiff"}]}}), + json!({"job": {"versions": [{"standard": "x9"}]}}), + json!({"job": {"versions": [{"format": "png"}], "layouts": ["Nope"]}}), + json!({"job": "pdf"}), + json!({"preset": "Nope"}), + ] { + assert!(s.execute(ID, &p).is_err(), "{p}"); + } + // A huge resolution is capped, not a crash; past 80 million pixels an image is refused. + let mut tall = Session::new(); + tall.execute("file.new", &json!({"pages": 1, "width": 3000, "height": 3000})).unwrap(); + assert!(tall.execute(ID, &json!({"job": {"versions": [{"format": "png", "ppi": 300}]}})).is_err(), "12500² pixels"); + let r = s.execute(ID, &json!({"job": {"versions": [{"format": "png", "ppi": 1e12}], "layouts": ["Print"]}, "dryRun": true})).unwrap(); + assert_eq!(r["files"].as_array().unwrap().len(), 2); + let mut big = Session::new(); + big.execute("file.new", &json!({"pages": 1, "width": 10000, "height": 10000})).unwrap(); + assert!(big.execute(ID, &json!({"job": {"versions": [{"format": "png", "ppi": 1200}]}})).is_err(), "too many pixels"); + } + + #[test] + fn presets_are_saved_listed_and_deleted() { + let mut s = two_layouts(); + let builtin = s.execute("file.exportPresets", &json!({})).unwrap()["presets"].as_array().unwrap().len(); + s.execute("file.saveExportPreset", &json!({"name": "Client", "job": job(&["PNG"])})).unwrap(); + s.execute("file.saveExportPreset", &json!({"name": "client", "job": job(&["JPEG"])})).unwrap(); + let list = s.execute("file.exportPresets", &json!({})).unwrap(); + assert_eq!(list["presets"].as_array().unwrap().len(), builtin + 1, "same name replaces"); + let r = s.execute(ID, &json!({"preset": "CLIENT", "dryRun": true})).unwrap(); + assert!(paths(&r)[0].ends_with(".jpg")); + assert!(s.execute("file.saveExportPreset", &json!({"name": "Print + Screen", "job": job(&["PNG"])})).is_err()); + assert!(s.execute("file.saveExportPreset", &json!({"name": "X", "job": {"versions": []}})).is_err()); + assert!(s.execute("file.deleteExportPreset", &json!({"name": "Print + Screen"})).is_err()); + s.execute("file.deleteExportPreset", &json!({"name": "Client"})).unwrap(); + assert!(s.execute(ID, &json!({"preset": "Client", "dryRun": true})).is_err()); + } +} diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index 44aaa85b7..b8429f860 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -21,7 +21,7 @@ mod snippets; pub use bytes::{DOCUMENT_SNIFF_BYTES, base64_decode, base64_encode, from_bytes, is_document, to_bytes, with_document_extension}; pub(crate) use open::load_document_fonts; pub use open::{RecentPreview, recent_preview}; -pub(crate) use place::{crop_pdf, read_source, validate_placement}; +pub(crate) use place::{crop_pdf, crop_pdf_from, document_of, prepare_placed, read_source, validate_placement}; pub use registry::specs; pub(crate) use snippets::{snippet_bytes, snippet_place}; diff --git a/crates/engine/src/cmd/file/bytes.rs b/crates/engine/src/cmd/file/bytes.rs index 0946205a8..028937364 100644 --- a/crates/engine/src/cmd/file/bytes.rs +++ b/crates/engine/src/cmd/file/bytes.rs @@ -21,17 +21,30 @@ fn save_bytes(d: &Document, preview: Option<&[u8]>) -> Result> { pub fn with_document_extension(path: &str) -> String { let p = std::path::Path::new(path); let ext = p.extension().and_then(std::ffi::OsStr::to_str); - if p.file_name().is_none() || ext.is_some_and(|e| e.eq_ignore_ascii_case(designcraft_format::EXTENSION)) { + if p.file_name().is_none() || ext.is_some_and(|e| craft_file_formats::from_extension(e) == Some(craft_file_formats::Format::DesignCraft)) { return path.to_string(); } format!("{path}.{}", designcraft_format::EXTENSION) } +/// `name` without a trailing `.designcraft` (any case): the title of a document opened from bytes +/// under its file name. Save, Save As and the File Name variable add the extension back, so a title +/// that kept it would name the file `Brochure.designcraft.designcraft`. A bare `.designcraft` stays. +pub(super) fn without_native_extension(name: &str) -> &str { + match name.rsplit_once('.') { + Some((stem, ext)) if !stem.is_empty() && craft_file_formats::from_extension(ext) == Some(craft_file_formats::Format::DesignCraft) => stem, + _ => name, + } +} + /// Whether `bytes` are a document `file.open` reads: a DesignCraft package or an IDML package. /// The first [`DOCUMENT_SNIFF_BYTES`] of a file are enough for packages that start with their /// `mimetype` entry, as both formats write them. pub fn is_document(bytes: &[u8]) -> bool { - designcraft_idml::is_idml(bytes) || designcraft_format::starts_designcraft(bytes) || designcraft_format::is_designcraft(bytes) + matches!( + craft_file_formats::detect("", bytes), + Some(craft_file_formats::Format::DesignCraft | craft_file_formats::Format::DesignCraftJson | craft_file_formats::Format::Idml) + ) } /// How much of a file [`is_document`] needs to recognise a package by its `mimetype` entry. @@ -50,7 +63,12 @@ pub(super) fn to_bytes_with_preview(d: &Document, cache: &crate::Cache) -> Resul }); let png = preview.and_then(|scale| designcraft_render::Renderer::new().render_page(d, cache, 0, scale, false, &Default::default())).map(|r| r.to_png()); - save_bytes(d, png.as_deref()) + let bytes = save_bytes(d, png.as_deref())?; + // `file.open` and `file.revert` refuse a longer file, so don't write one the app can't read back. + if bytes.len() as u64 > crate::io::MAX_FILE_BYTES { + return Err(EngineError::Other(format!("could not write the document: encoded file is longer than {} bytes", crate::io::MAX_FILE_BYTES))); + } + Ok(bytes) } pub fn from_bytes(b: &[u8]) -> Result { @@ -65,19 +83,7 @@ pub(super) fn load_bytes(b: &[u8]) -> Result<(Document, Vec)> { Ok((d, warnings)) } -const B64: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; - -pub fn base64_encode(data: &[u8]) -> String { - let mut out = String::with_capacity(data.len().div_ceil(3) * 4); - for c in data.chunks(3) { - let n = (c[0] as u32) << 16 | (*c.get(1).unwrap_or(&0) as u32) << 8 | *c.get(2).unwrap_or(&0) as u32; - out.push(B64[(n >> 18) as usize & 63] as char); - out.push(B64[(n >> 12) as usize & 63] as char); - out.push(if c.len() > 1 { B64[(n >> 6) as usize & 63] as char } else { '=' }); - out.push(if c.len() > 2 { B64[n as usize & 63] as char } else { '=' }); - } - out -} +pub use craft_mime::transfer::base64 as base64_encode; pub fn base64_decode(s: &str) -> Vec { let mut out = Vec::with_capacity(s.len() * 3 / 4); @@ -163,3 +169,20 @@ mod extension_tests { let _ = std::fs::remove_dir_all(&dir); } } + +#[cfg(test)] +mod shared_base64_tests { + use super::{base64_decode, base64_encode}; + + #[test] + fn serialization_encoding_preserves_all_bytes_and_padding() { + let bytes: Vec = (0..=255).collect(); + for n in 0..=bytes.len() { + let encoded = base64_encode(&bytes[..n]); + assert_eq!(encoded.len(), n.div_ceil(3) * 4); + assert!(!encoded.contains(['\r', '\n'])); + assert_eq!(base64_decode(&encoded), bytes[..n]); + } + assert_eq!(base64_encode(&[0xfb, 0xff, 0xff]), "+///"); + } +} diff --git a/crates/engine/src/cmd/file/eps_place_tests.rs b/crates/engine/src/cmd/file/eps_place_tests.rs index 2501a31d3..8a78422a3 100644 --- a/crates/engine/src/cmd/file/eps_place_tests.rs +++ b/crates/engine/src/cmd/file/eps_place_tests.rs @@ -167,8 +167,8 @@ fn eps_idml_roundtrip_preserves_source_and_resource_type() { let restored = designcraft_idml::import_idml(&idml).unwrap(); let a = restored.assets.values().next().unwrap(); assert_eq!(a.mime, "application/postscript"); - assert_eq!(a.data.as_slice(), bytes); - assert!(designcraft_render::decode_pixmap(&a.data).is_some()); + assert_eq!(a.data.load().unwrap().as_slice(), bytes); + assert!(designcraft_render::decode_pixmap(&a.data.load().unwrap()).is_some()); // A linked-only EPS keeps its type even when the external file is unavailable; // when the resolver supplies it, sniff the raw source rather than PNG metadata. let mut linked = (*source).clone(); @@ -186,7 +186,7 @@ fn eps_idml_roundtrip_preserves_source_and_resource_type() { .unwrap(); let a = resolved.assets.values().next().unwrap(); assert_eq!(a.mime, "application/postscript"); - assert_eq!(a.data.as_slice(), bytes); + assert_eq!(a.data.load().unwrap().as_slice(), bytes); } } @@ -197,7 +197,7 @@ fn eps_place_cursor_retains_source_and_uses_bounding_box_size() { s.execute("file.new", &json!({})).unwrap(); let result = s.execute("place.load", &json!({"base64": base64_encode(source), "name": "logo.eps"})).unwrap(); let aid = AssetId(result["asset"].as_u64().unwrap()); - assert_eq!(s.doc().unwrap().doc.assets[&aid].data.as_slice(), source); + assert_eq!(s.doc().unwrap().doc.assets[&aid].data.load().unwrap().as_slice(), source); assert_eq!(s.doc().unwrap().doc.assets[&aid].mime, "application/postscript"); assert_eq!(s.doc().unwrap().doc.assets[&aid].pixels, Some((201, 101))); let result = s.execute("place.drop", &json!({"x": 72, "y": 72})).unwrap(); diff --git a/crates/engine/src/cmd/file/new.rs b/crates/engine/src/cmd/file/new.rs index 6614a2323..62f596d00 100644 --- a/crates/engine/src/cmd/file/new.rs +++ b/crates/engine/src/cmd/file/new.rs @@ -13,10 +13,11 @@ fn find_preset(s: &Session, name: &str) -> Option { } /// The settings `file.new` makes a document with for `p`: its preset, then the settings over it. +/// Without a preset or `units`, it is in the default units (Preferences with no document). fn new_document_settings(s: &Session, p: &Value) -> Result { let mut nd = match str_param(p, "preset") { Some(name) => find_preset(s, name).ok_or_else(|| bad("file.new", format!("unknown preset `{name}`")))?, - None => NewDocument::default(), + None => s.default_new_document(), }; apply_settings(&mut nd, p); check_size("file.new", &nd)?; @@ -40,12 +41,19 @@ pub(super) fn file_new(s: &mut Session, p: &Value) -> Result { let mut nd = new_document_settings(s, p)?; s.untitled += 1; nd.title = str_param(p, "title").map(str::to_string).unwrap_or_else(|| format!("Untitled-{}", s.untitled)); - let d = new_document(&nd); + let mut d = new_document(&nd); + s.prefs.default_units.apply(&mut d.settings, p.get("preset").is_some_and(|v| !v.is_null())); let i = s.add_document(DocState::new(d, None)); Ok(json!({"index": i})) } impl Session { + /// What New Document starts with: the factory settings, in the default units (Preferences + /// with no document open). + pub fn default_new_document(&self) -> NewDocument { + NewDocument { units: self.prefs.default_units.horizontal_units, ..NewDocument::default() } + } + /// New Document's Preview: a document made as `file.new` would make it with `p`, shown while /// the New Document window is open. It replaces the previous preview document in its tab and /// takes no Untitled number, no undo step and no recovery entry. Settings `file.new` refuses @@ -64,7 +72,9 @@ impl Session { self.untitled += 1; } nd.title = str_param(p, "title").map(str::to_string).unwrap_or_else(|| self.next_untitled_title()); - let st = DocState::new(new_document(&nd), None); + let mut d = new_document(&nd); + self.prefs.default_units.apply(&mut d.settings, p.get("preset").is_some_and(|v| !v.is_null())); + let st = DocState::new(d, None); let uid = st.uid; match replace.and_then(|i| self.docs.get_mut(i).map(|d| (i, d))) { Some((i, d)) => { @@ -166,7 +176,7 @@ fn apply_settings(nd: &mut NewDocument, p: &Value) { nd.start_page = p.get("startPage").and_then(Value::as_u64).map(|v| v.clamp(1, 99_999) as u32).unwrap_or(nd.start_page); nd.facing_pages = p.get("facingPages").and_then(Value::as_bool).unwrap_or(nd.facing_pages); nd.columns = p.get("columns").and_then(Value::as_u64).map(|v| v.clamp(1, 216) as u32).unwrap_or(nd.columns); - nd.gutter = f64_or(p, "gutter", nd.gutter); + nd.gutter = p.get("gutter").and_then(Value::as_f64).filter(|g| g.is_finite()).unwrap_or(nd.gutter).max(0.0); nd.primary_text_frame = p.get("primaryTextFrame").and_then(Value::as_bool).unwrap_or(nd.primary_text_frame); match p.get("margins") { Some(Value::Number(n)) => nd.margins = designcraft_doc::Margins::uniform(n.as_f64().unwrap_or(36.0)), @@ -244,6 +254,16 @@ mod new_document_tests { assert!(s.execute("file.new", &json!({"preset": "Newsletter"})).is_err()); } + #[test] + fn negative_gutter_is_clamped_to_zero() { + let mut s = Session::new(); + s.execute("file.new", &json!({"gutter": -50, "columns": 2})).unwrap(); + let d = &s.doc().unwrap().doc; + assert_eq!(d.page(0).unwrap().columns.gutter, 0.0); + s.execute("file.savePreset", &json!({"name": "Tight", "gutter": -50, "columns": 2})).unwrap(); + assert_eq!(s.prefs.document_presets[0].gutter, 0.0); + } + #[test] fn new_document_takes_intent_units_start_page_bleed_and_slug() { let mut s = Session::new(); diff --git a/crates/engine/src/cmd/file/open.rs b/crates/engine/src/cmd/file/open.rs index 75a7ce627..a2f5c709c 100644 --- a/crates/engine/src/cmd/file/open.rs +++ b/crates/engine/src/cmd/file/open.rs @@ -1,6 +1,6 @@ #[cfg(test)] use super::bytes::{PREVIEW_PX, to_bytes}; -use super::bytes::{base64_decode, load_bytes}; +use super::bytes::{base64_decode, load_bytes, without_native_extension}; use super::{Arc, DocState, Document, EngineError, Result, Session, Value, bad, json, str_param}; pub(super) fn has_recent(s: &Session) -> std::result::Result<(), String> { @@ -14,6 +14,10 @@ pub struct RecentPreview { pub rgba: Vec, } +/// The most pixels a recent file's preview may have to be shown (its PNG is bounded by +/// `designcraft_format::MAX_PREVIEW_BYTES`, but a small PNG can claim a huge picture). +const MAX_PREVIEW_PIXELS: u64 = 1 << 24; + /// The picture a `.designcraft` file saved of its first page; None when the file is gone, isn't /// ours, or was saved before files had one (it gets one when saved again). pub fn recent_preview(path: &str) -> Option { @@ -21,6 +25,12 @@ pub fn recent_preview(path: &str) -> Option { { // Only the zip directory and the preview entry are read, not the whole document. let png = designcraft_format::read_preview(std::io::BufReader::new(crate::io::open(path).ok()?))?; + // A preview is a small picture: one whose header claims more pixels than that isn't + // decoded (a decode is bounded, but not at thumbnail size). + let (w, h) = designcraft_images::pixel_size(&png)?; + if u64::from(w).saturating_mul(u64::from(h)) > MAX_PREVIEW_PIXELS { + return None; + } let img = designcraft_images::decode_rgba(&png)?; let (width, height) = img.dimensions(); Some(RecentPreview { width, height, rgba: img.into_raw() }) @@ -74,24 +84,33 @@ fn open_path(s: &mut Session, p: &Value) -> Result { let bytes = crate::io::read_file(path).map_err(EngineError::Other)?; // The content decides first: a file's extension may be missing or wrong. The extension // then routes files whose content isn't recognised to the reader that explains why. - let ext = std::path::Path::new(path).extension().and_then(std::ffi::OsStr::to_str).unwrap_or_default().to_ascii_lowercase(); - let native = designcraft_format::is_designcraft(&bytes) || bytes.trim_ascii_start().starts_with(b"{"); - if designcraft_idml::is_idml(&bytes) || (!native && (crate::cmd::interchange::is_indd(path, &bytes) || ext == "idml")) { + let format = craft_file_formats::detect(path, &bytes); + let native = matches!( + craft_file_formats::detect("", &bytes), + Some(craft_file_formats::Format::DesignCraft | craft_file_formats::Format::DesignCraftJson) + ); + let legacy = (format == Some(craft_file_formats::Format::Indd) && !native).then(|| load_bytes(&bytes).ok()).flatten(); + if format == Some(craft_file_formats::Format::Idml) || (!native && format == Some(craft_file_formats::Format::Indd) && legacy.is_none()) { return crate::cmd::interchange::open_idml(s, p); } - if !native && ext != designcraft_format::EXTENSION { + if !native && legacy.is_none() { return Err(bad("file.open", format!("{path}: not a DesignCraft or IDML file"))); } - let (mut d, mut warnings) = load_bytes(&bytes)?; + let (mut d, mut warnings) = match legacy { + Some(loaded) => loaded, + None => load_bytes(&bytes)?, + }; crate::cmd::interchange::resolve_packaged_links(&mut d, Some(std::path::Path::new(path))); crate::cmd::datamerge::resolve_sources_on_open(&mut d, Some(std::path::Path::new(path))); + let links = crate::cmd::native_links::resolve(&mut d, Some(std::path::Path::new(path)), true); let (fonts, faces, font_warnings) = load_document_fonts(&mut d, path); warnings.extend(font_warnings); warnings.extend(crate::cmd::style::grep_style_warnings(&d)); let mut st = DocState::new(d, Some(path.to_string())); st.fonts = fonts; + let checks = crate::cmd::native_links::start(&mut st, links); let i = s.add_document(st); - Ok(json!({"index": i, "documentFonts": faces, "warnings": warnings})) + Ok(json!({"index": i, "documentFonts": faces, "warnings": warnings, "linkChecks": checks})) } #[cfg(target_arch = "wasm32")] { @@ -128,6 +147,8 @@ pub(crate) fn load_document_fonts(d: &mut Document, path: &str) -> (Option std::path::PathBuf { use designcraft_fonts::DOCUMENT_FONTS_FOLDER; + // A bare file name has an empty parent; directory traversal needs an explicit `.`. + let dir = if dir.as_os_str().is_empty() { std::path::Path::new(".") } else { dir }; let exact = dir.join(DOCUMENT_FONTS_FOLDER); if crate::io::is_dir(&exact) { return exact; @@ -144,16 +165,29 @@ pub(super) fn file_open_bytes(s: &mut Session, p: &Value) -> Result { let b = base64_decode(str_param(p, "base64").unwrap_or("")); // IDML packages are recognised by their stored `mimetype` first entry, INDD files by their // signature (or their name). - if designcraft_idml::is_idml(&b) || crate::cmd::interchange::is_indd(str_param(p, "name").unwrap_or_default(), &b) { + let name = str_param(p, "name").unwrap_or_default(); + let format = craft_file_formats::detect(name, &b); + let native = + matches!(craft_file_formats::detect("", &b), Some(craft_file_formats::Format::DesignCraft | craft_file_formats::Format::DesignCraftJson)); + let legacy = (format == Some(craft_file_formats::Format::Indd) && !native).then(|| load_bytes(&b).ok()).flatten(); + if format == Some(craft_file_formats::Format::Idml) || (!native && format == Some(craft_file_formats::Format::Indd) && legacy.is_none()) { return crate::cmd::interchange::open_idml(s, p); } - let (mut d, warnings) = load_bytes(&b)?; + let (mut d, warnings) = match legacy { + Some(loaded) => loaded, + None => load_bytes(&b)?, + }; crate::cmd::datamerge::resolve_sources_on_open(&mut d, None); + // No file to resolve relative links against, and nothing moved to links. + let links = crate::cmd::native_links::resolve(&mut d, None, false); if let Some(n) = str_param(p, "name") { - d.title = n.to_string(); + // Titled as an IDML file opened from bytes is: without its extension. + d.title = without_native_extension(n).to_string(); } - let i = s.add_document(DocState::new(d, None)); - Ok(json!({"index": i, "warnings": warnings})) + let mut st = DocState::new(d, None); + let checks = crate::cmd::native_links::start(&mut st, links); + let i = s.add_document(st); + Ok(json!({"index": i, "warnings": warnings, "linkChecks": checks})) } #[cfg(test)] @@ -286,6 +320,75 @@ mod document_fonts_tests { let _ = std::fs::remove_dir_all(&dir); } + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn document_fonts_are_found_for_bare_and_explicit_paths() { + // Only the child changes its working directory; parallel tests keep theirs. + let dir = tempfile::tempdir().unwrap(); + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "cmd::file::open::document_fonts_tests::document_font_paths_child", "--ignored", "--nocapture"]) + .env("DESIGNCRAFT_TEST_DOCUMENT_FONT_PATHS", "1") + .current_dir(dir.path()) + .output() + .unwrap(); + assert!(output.status.success(), "child failed: {}{}", String::from_utf8_lossy(&output.stdout), String::from_utf8_lossy(&output.stderr)); + let stdout = String::from_utf8_lossy(&output.stdout); + assert!(stdout.contains("test result: ok. 1 passed; 0 failed;"), "the subprocess helper must run exactly once: {stdout}"); + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + #[ignore = "subprocess helper, executed by document_fonts_are_found_for_bare_and_explicit_paths"] + fn document_font_paths_child() { + const FAMILY: &str = "DocFont Bare Path Test"; + assert!(std::env::var_os("DESIGNCRAFT_TEST_DOCUMENT_FONT_PATHS").is_some(), "run through the parent test"); + let cwd = std::env::current_dir().unwrap(); + std::fs::create_dir("nested").unwrap(); + std::fs::create_dir("other").unwrap(); + for extension in ["idml", "designcraft"] { + let path = PathBuf::from(format!("t.{extension}")); + write_document(&cwd.join(&path), FAMILY); + write_document(&cwd.join("other").join(&path), FAMILY); + assert_eq!(open(&mut Session::new(), &path)["documentFonts"], 0, "no font folder: {path:?}"); + } + + let roots = crate::file_access::AutomationRoots::new(&[cwd.as_path()], &[]).unwrap(); + for folder in ["Document fonts", DOCUMENT_FONTS_FOLDER] { + std::fs::create_dir_all(folder).unwrap(); + std::fs::write(Path::new(folder).join("case.ttf"), font_with(FAMILY, &['H', 'e', 'l', 'o']).unwrap()).unwrap(); + if folder == DOCUMENT_FONTS_FOLDER { + // Both spellings exist on case-sensitive file systems; the exact name still wins. + assert_eq!(super::document_fonts_folder(Path::new("")), Path::new(".").join(DOCUMENT_FONTS_FOLDER)); + } + for extension in ["idml", "designcraft"] { + let name = format!("t.{extension}"); + for path in [PathBuf::from(&name), Path::new(".").join(&name), Path::new("nested/..").join(&name), cwd.join(&name)] { + let mut s = Session::new(); + let r = crate::file_access::confine(roots.as_ref(), || open(&mut s, &path)); + assert_eq!(r["documentFonts"], 1, "{folder}, {path:?}: {r}"); + let f = font_entry(&mut s, FAMILY); + assert_eq!((f["missing"].clone(), f["source"].clone()), (json!(false), json!("document")), "{path:?}: {f}"); + } + } + } + + // Opening a second document without the folder must not inherit the first one's font. + let mut s = Session::new(); + assert_eq!(open(&mut s, Path::new("t.idml"))["documentFonts"], 1); + assert_eq!(open(&mut s, Path::new("other/t.designcraft"))["documentFonts"], 0); + assert_eq!(font_entry(&mut s, FAMILY)["missing"], true); + s.execute("file.activate", &json!({"index": 0})).unwrap(); + assert_eq!(font_entry(&mut s, FAMILY)["source"], "document"); + + // Normalising the directory must not grant access outside the automation read root. + let restricted = crate::file_access::AutomationRoots::new(&[Path::new("other")], &[]).unwrap(); + let mut doc = s.doc().unwrap().doc.as_ref().clone(); + let (scope, faces, _) = crate::file_access::confine(restricted.as_ref(), || super::load_document_fonts(&mut doc, "t.idml")); + assert!(scope.is_none()); + assert_eq!(faces, 0); + assert_eq!(doc.font_scope, 0); + } + #[test] fn a_document_without_the_folder_opens_as_before() { let dir = std::env::temp_dir().join(format!("dc-open-docfonts-none-{}", std::process::id())); @@ -413,6 +516,76 @@ mod document_fonts_tests { } } +#[cfg(test)] +mod open_bytes_tests { + use serde_json::json; + + use crate::Session; + + #[test] + fn legacy_and_idml_bytes_named_as_indesign_files_open_without_conversion() { + let mut maker = Session::new(); + maker.execute("file.new", &json!({})).unwrap(); + let idml = designcraft_idml::export_idml(&maker.doc().unwrap().doc); + let base64 = super::super::bytes::base64_encode(&idml); + let legacy_bytes = serde_json::to_vec(&maker.doc().unwrap().doc).unwrap(); + let legacy = super::super::bytes::base64_encode(&legacy_bytes); + #[cfg(not(target_arch = "wasm32"))] + { + let legacy_path = std::env::temp_dir().join(format!("dc-legacy-indd-{}.indd", std::process::id())); + std::fs::write(&legacy_path, &legacy_bytes).unwrap(); + let mut by_path = Session::new(); + by_path.execute("file.open", &json!({"path": legacy_path})).unwrap(); + assert_eq!(by_path.documents().len(), 1, "legacy JSON must win over an InDesign extension"); + let _ = std::fs::remove_file(&legacy_path); + } + for name in ["Brochure.indd", "Brochure.INDT"] { + let mut s = Session::new(); + s.execute("file.openBytes", &json!({"name": name, "base64": legacy})).unwrap(); + assert_eq!(s.documents().len(), 1, "legacy: {name}"); + assert_eq!(s.doc().unwrap().doc.title, name, "legacy: {name}"); + } + for command in ["file.openBytes", "file.openIdml"] { + for name in ["Brochure.indd", "Brochure.INDT"] { + let mut s = Session::new(); + s.execute(command, &json!({"name": name, "base64": base64})).unwrap(); + assert_eq!(s.documents().len(), 1, "{command}: {name}"); + assert_eq!(s.doc().unwrap().doc.title, "Brochure", "{command}: {name}"); + } + } + } + + /// A `.designcraft` file opened from bytes under its file name (a browser or host passes the + /// name it has) is titled without the extension, as an IDML file is, so saving it gives + /// `Brochure.designcraft` and not `Brochure.designcraft.designcraft`. + #[test] + fn open_bytes_titles_a_native_document_without_its_extension() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let native = s.execute("file.serialize", &json!({})).unwrap(); + for (name, title) in [ + ("Brochure.designcraft", "Brochure"), + ("Brochure.DesignCraft", "Brochure"), + ("Brochure", "Brochure"), + ("Brochure.v2", "Brochure.v2"), + ("Brochure.indd", "Brochure.indd"), + ("Brochure.INDT", "Brochure.INDT"), + ("Brochure.designcraft.designcraft", "Brochure.designcraft"), + (".designcraft", ".designcraft"), + // Names that aren't ASCII: cutting the extension's length off the end of the last one + // would land inside its `é`. + ("Präsentation.designcraft", "Präsentation"), + ("日本.DESIGNCRAFT", "日本"), + ("é", "é"), + ("édesigncraft", "édesigncraft"), + ] { + let r = s.execute("file.openBytes", &json!({"name": name, "base64": native["base64"]})).unwrap(); + let st = &s.documents()[r["index"].as_u64().unwrap() as usize]; + assert_eq!((st.doc.title.as_str(), st.title()), (title, title.to_string()), "{name}"); + } + } +} + #[cfg(test)] mod recent_tests { use serde_json::json; diff --git a/crates/engine/src/cmd/file/place.rs b/crates/engine/src/cmd/file/place.rs index 44f993a64..7a8a37b95 100644 --- a/crates/engine/src/cmd/file/place.rs +++ b/crates/engine/src/cmd/file/place.rs @@ -4,9 +4,10 @@ use super::EngineError; use super::bytes::base64_encode; use super::bytes::{base64_decode, from_bytes}; use super::{ - Affine, Arc, Asset, AssetId, Content, Graphic, Item, ItemId, PdfCrop, Rect, Result, Selection, Session, Shape, Value, bad, json, ok, shapes, - str_param, + Affine, Asset, AssetId, Content, Graphic, Item, ItemId, PdfCrop, Rect, Result, Selection, Session, Shape, Value, bad, json, ok, shapes, str_param, }; +use crate::cmd::links::{FileLink, give_placed}; +use crate::cmd::native_links::Pending; pub(super) fn file_place(s: &mut Session, p: &Value) -> Result { // The file's size and time before it is read (a linked text file remembers them). @@ -25,16 +26,30 @@ pub(super) fn file_place(s: &mut Session, p: &Value) -> Result { s.ui_requests.push(crate::UiRequest::Pick { purpose: "place".into(), params: json!({}) }); return ok(); }; + // A frame named outright is not replaced while it is locked (the selected frame is the user's own choice). + if let Some(fid) = crate::cmd::id_param(p, "frame") + && s.doc()?.doc.item(fid).is_some_and(|it| it.locked) + { + return Err(bad("file.place", "the frame is locked")); + } // A page of another layout (IDML or DesignCraft): its objects, as one group. - let lname = name.to_lowercase(); - if lname.ends_with(".idml") || lname.ends_with(".designcraft") { - return place_layout_page(s, p, &name, &bytes); + let format = craft_file_formats::detect(&name, &bytes); + if matches!(format, Some(craft_file_formats::Format::Idml | craft_file_formats::Format::DesignCraft)) { + return place_layout_page(s, p, &bytes, format); } // Keep the EPS source for link comparison; rendering uses its preview at the bounding box size. let eps_size = eps_size(&bytes, "file.place")?; + // A file placed from a path links to it unless `embed`. + let embed = p.get("embed").and_then(Value::as_bool) == Some(true); + let document = document_of(s); // Video and sound: a media frame (Window › Interactive › Media). if let Some(mime) = designcraft_doc::media_mime(&name) { - return crate::cmd::media::place_media(s, p, name, mime, bytes, link); + let file = link.as_deref().map(|l| FileLink::of(std::path::Path::new(l), before)); + let mut asset = Asset { name, mime: mime.to_string(), ..Default::default() }; + let pending = give_placed(&mut asset, bytes, file, embed, document.as_deref()); + let r = crate::cmd::media::place_media(s, p, asset)?; + prepare_placed(s, pending); + return Ok(r); } // Text files (plain, Word, RTF) flow into frames. if designcraft_textimport::is_text_file(&name) { @@ -51,11 +66,11 @@ pub(super) fn file_place(s: &mut Session, p: &Value) -> Result { }) .transpose()?; // Image Import Options: which page of a PDF (1-based). - if designcraft_render::is_pdf(&bytes) { + if format == Some(craft_file_formats::Format::Pdf) { designcraft_render::check_pdf_input_size(bytes.len()).map_err(|e| bad("file.place", e.to_string()))?; } let pdf_page = match p.get("pdfPage").and_then(Value::as_u64) { - Some(n) if designcraft_render::is_pdf(&bytes) => { + Some(n) if format == Some(craft_file_formats::Format::Pdf) => { let count = designcraft_render::pdf_page_count(&bytes).unwrap_or(1); let invalid_page = || bad("file.place", format!("the PDF has {count} page(s)")); let one_based = usize::try_from(n).map_err(|_| invalid_page())?; @@ -77,29 +92,35 @@ pub(super) fn file_place(s: &mut Session, p: &Value) -> Result { // and SVGs keep their exact size: rounding it to whole points would stretch them unevenly. let (nw, nh) = eps_size.or_else(|| designcraft_render::natural_size(&bytes, pdf_page as usize)).unwrap_or((pw as f64, ph as f64)); // Image Import Options › Crop to: the graphic spans that box of the PDF page. - let is_pdf = designcraft_render::is_pdf(&bytes); + let is_pdf = format == Some(craft_file_formats::Format::Pdf); let pdf_crop = match str_param(p, "pdfCrop") { Some(k) if is_pdf => PdfCrop::from_name(k) .ok_or_else(|| bad("file.place", format!("unknown pdfCrop `{k}` (crop, art, trim, bleed, media, contentVisible, contentAll)")))?, _ => PdfCrop::Crop, }; let mime = designcraft_render::image_mime(&bytes).to_string(); - let mut asset = Asset { page: pdf_page, name, mime, link, data: Arc::new(bytes), pixels: Some((pw, ph)), pdf_crop, ..Default::default() }; + let file = link.as_deref().map(|l| FileLink::of(std::path::Path::new(l), before)); + let mut asset = Asset { page: pdf_page, name, mime, pixels: Some((pw, ph)), pdf_crop, ..Default::default() }; // The graphic's natural size: the box in points (the whole page when the box can't be found, // and then the document says so). - let (bw, bh) = match crop_pdf(&mut asset) { + let cropped = crop_pdf_from(&mut asset, &bytes); + let pending = give_placed(&mut asset, bytes, file, embed, document.as_deref()); + let (bw, bh) = match cropped { Some(size) => size, None => { asset.pdf_crop = PdfCrop::Crop; (nw, nh) } }; + // A file joining the place cursor's queue goes after the ones already there, whatever is selected. + let load_cursor_param = p.get("loadCursor").and_then(Value::as_bool) == Some(true); + let append = p.get("append").and_then(Value::as_bool) == Some(true); let target_frame = crate::cmd::id_param(p, "frame").or_else(|| { - if ["x", "y", "spread", "width"].iter().any(|key| p.get(*key).is_some_and(|value| !value.is_null())) { + if (load_cursor_param && append) || ["x", "y", "spread", "width"].iter().any(|key| p.get(*key).is_some_and(|value| !value.is_null())) { return None; } let st = s.active()?; - st.selection.items.iter().copied().find(|i| st.doc.item(*i).is_some_and(|it| matches!(it.content, Content::Unassigned | Content::Graphic(_)))) + st.selection.items.iter().copied().find(|i| st.doc.item(*i).is_some_and(|it| it.path.encloses_area() && it.takes_graphic())) }); // `"spread": null` counts as omitted, like the other placement parameters. let spread = match p.get("spread") { @@ -109,10 +130,12 @@ pub(super) fn file_place(s: &mut Session, p: &Value) -> Result { let lid = s.doc()?.active_layer; let px = p.get("x").and_then(Value::as_f64); let py = p.get("y").and_then(Value::as_f64); - if target_frame.is_none() && px.is_none() && py.is_none() && p.get("loadCursor").and_then(Value::as_bool) == Some(true) { - return load_cursor(s, asset, (bw, bh)); + if target_frame.is_none() && px.is_none() && py.is_none() && load_cursor_param { + let r = load_cursor(s, asset, (bw, bh), append)?; + prepare_placed(s, pending); + return Ok(r); } - s.edit(|d, sel| { + let r = s.edit(|d, sel| { let fresh = AssetId(d.alloc()); let aid = d.add_asset(Asset { id: fresh, ..asset }); // The width the whole page (or image) gets; the height follows the proportions. @@ -175,33 +198,87 @@ pub(super) fn file_place(s: &mut Session, p: &Value) -> Result { }; *sel = Selection::items(vec![id]); Ok(json!({"id": id.0, "asset": aid.0})) - }) + })?; + prepare_placed(s, pending); + Ok(r) +} + +/// Have the hash and proxy of graphics just placed into the active document made in the +/// background ([`crate::cmd::native_links::prepare`]). +pub(crate) fn prepare_placed(s: &mut Session, pending: impl IntoIterator) { + if let Ok(st) = s.doc_mut() { + crate::cmd::native_links::prepare(st, pending.into_iter().collect()); + } } /// Sets `a.pdf_box` to where its `pdf_crop` box sits on its page and returns the box's size in /// points. The crop box is the whole page and has none; nor has a page that can't be read, which -/// keeps its crop choice (a missing link relinked later gets its box then). +/// keeps its crop choice (a missing link relinked later gets its box then). Only a PDF with +/// another box chosen is read. pub(crate) fn crop_pdf(a: &mut Asset) -> Option<(f64, f64)> { a.pdf_box = None; - if a.pdf_crop == PdfCrop::Crop || !designcraft_render::is_pdf(&a.data) { + if !crops_pdf(a) { return None; } - let (frac, size) = designcraft_render::pdf_crop_box(&a.data, a.page as usize, a.pdf_crop)?; + let bytes = a.data.load().ok()?; + crop_pdf_from(a, &bytes) +} + +/// [`crop_pdf`] with `a`'s bytes, `bytes`, in hand. +pub(crate) fn crop_pdf_from(a: &mut Asset, bytes: &[u8]) -> Option<(f64, f64)> { + a.pdf_box = None; + if !crops_pdf(a) || !designcraft_render::is_pdf(bytes) { + return None; + } + let (frac, size) = designcraft_render::pdf_crop_box(bytes, a.page as usize, a.pdf_crop)?; a.pdf_box = Some(frac); Some(size) } -pub(crate) fn read_source(p: &Value) -> Result<(Vec, String, Option)> { +/// Whether `a` is a PDF placed with a box other than its crop box, which only its bytes locate. +fn crops_pdf(a: &Asset) -> bool { + a.pdf_crop != PdfCrop::Crop && a.mime == "application/pdf" +} + +/// A file to place: its bytes and name, and its link record when it was read from a path. +pub(crate) struct Source { + pub bytes: Vec, + pub name: String, + file: Option, + /// `embed: true`: the bytes are kept in the document instead of linking the file. + embed: bool, +} + +impl Source { + /// Give `a` these bytes: linked to the file they were read from once the returned work is + /// done, else embedded ([`give_placed`]). `a`'s `mime` and `page` are set. + pub(crate) fn give(self, a: &mut Asset, document: Option<&std::path::Path>) -> Option { + give_placed(a, self.bytes, self.file, self.embed, document) + } +} + +/// The file of the document open in `s`, which relative links are recorded against. +pub(crate) fn document_of(s: &Session) -> Option { + s.doc().ok()?.path.as_deref().map(std::path::PathBuf::from) +} + +/// The file `p` names: `{path, embed?}` or `{base64, name?}`. Its size and time are taken before +/// it is read, so a later version that replaces it while a network or syncing source is being +/// loaded isn't vouched for ([`crate::cmd::links::loaded_fingerprint`]). +pub(crate) fn read_source(p: &Value) -> Result { + let embed = p.get("embed").and_then(Value::as_bool) == Some(true); if let Some(b) = str_param(p, "base64") { - return Ok((base64_decode(b), str_param(p, "name").unwrap_or("image").to_string(), None)); + return Ok(Source { bytes: base64_decode(b), name: str_param(p, "name").unwrap_or("image").to_string(), file: None, embed }); } let path = str_param(p, "path").ok_or_else(|| bad("place", "missing `path` or `base64`"))?; + let before = crate::cmd::datamerge::fingerprint_from_path(path); #[cfg(not(target_arch = "wasm32"))] let b = crate::io::read_file(path).map_err(EngineError::Other)?; #[cfg(target_arch = "wasm32")] let b: Vec = vec![]; let name = std::path::Path::new(path).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| path.into()); - Ok((b, name, Some(path.to_string()))) + let file = Some(FileLink::of(std::path::Path::new(path), before)); + Ok(Source { bytes: b, name, file, embed }) } fn eps_size(bytes: &[u8], command: &str) -> Result> { @@ -229,35 +306,126 @@ pub(crate) fn validate_placement(size: (f64, f64), frame: Rect, xf: Affine, comm Ok(()) } +/// Decode and validate the complete batch before replacing the placement cursor. pub(super) fn place_load(s: &mut Session, p: &Value) -> Result { - let (bytes, name, link) = read_source(p)?; - let (pw, ph) = designcraft_render::image_size(&bytes).ok_or_else(|| bad("place.load", "unsupported or corrupt image"))?; - let natural = eps_size(&bytes, "place.load")?.or_else(|| designcraft_render::natural_size(&bytes, 0)).unwrap_or((pw as f64, ph as f64)); - let mime = designcraft_render::image_mime(&bytes).to_string(); - let asset = Asset { name, mime, link, data: Arc::new(bytes), pixels: Some((pw, ph)), ..Default::default() }; - load_cursor(s, asset, natural) + let append = p.get("append").and_then(Value::as_bool) == Some(true); + let embed = p.get("embed").and_then(Value::as_bool) == Some(true); + let document = document_of(s); + if p.get("files").is_none() { + let source = read_source(p)?; + let bytes = &source.bytes; + let (pw, ph) = designcraft_render::image_size(bytes).ok_or_else(|| bad("place.load", "unsupported or corrupt image"))?; + let natural = eps_size(bytes, "place.load")?.or_else(|| designcraft_render::natural_size(bytes, 0)).unwrap_or((pw as f64, ph as f64)); + let mut asset = Asset { + name: source.name.clone(), + mime: designcraft_render::image_mime(bytes).to_string(), + pixels: Some((pw, ph)), + ..Default::default() + }; + let pending = source.give(&mut asset, document.as_deref()); + let r = load_cursor(s, asset, natural, append)?; + prepare_placed(s, pending); + return Ok(r); + } + let sources = p.get("files").and_then(Value::as_array).ok_or_else(|| bad("place.load", "files must be an array"))?; + if sources.is_empty() || sources.len() > MAX_LOADED_IMAGES { + return Err(bad("place.load", format!("select between 1 and {MAX_LOADED_IMAGES} images"))); + } + check_cursor_room(s, sources.len(), append, "place.load")?; + let mut images = Vec::with_capacity(sources.len()); + let mut pending = Vec::new(); + for source in sources { + let mut source = read_source(source)?; + source.embed |= embed; + let bytes = &source.bytes; + let (pw, ph) = + designcraft_render::image_size(bytes).ok_or_else(|| bad("place.load", format!("unsupported or corrupt image: {}", source.name)))?; + let size = eps_size(bytes, "place.load")?.or_else(|| designcraft_render::natural_size(bytes, 0)).unwrap_or((pw as f64, ph as f64)); + validate_placement(size, Rect::new(0.0, 0.0, size.0, size.1), Affine::IDENTITY, "place.load")?; + let mut asset = Asset { + name: source.name.clone(), + mime: designcraft_render::image_mime(bytes).to_string(), + pixels: Some((pw, ph)), + ..Default::default() + }; + pending.extend(source.give(&mut asset, document.as_deref())); + images.push((asset, size)); + } + let queue = s.edit(|d, _| { + let mut queue = std::collections::VecDeque::with_capacity(images.len()); + for (mut asset, size) in images { + asset.id = AssetId(d.alloc()); + queue.push_back(crate::LoadedGraphic { asset: d.add_asset(asset), size }); + } + Ok(queue) + })?; + prepare_placed(s, pending); + if append && s.loaded.is_some() { + s.loaded_queue.extend(queue); + } else { + s.loaded_queue = queue; + s.loaded = s.loaded_queue.pop_front(); + } + s.set_tool("placeGun"); + Ok(json!({"remaining": loaded_count(s), "loaded": true})) } -/// Adds `asset` to the document (with a fresh id) and loads it into the place cursor. -fn load_cursor(s: &mut Session, mut asset: Asset, size: (f64, f64)) -> Result { +/// Most images the place cursor holds, and so most one `place.load` takes. +const MAX_LOADED_IMAGES: usize = 1000; + +/// Whether `incoming` images fit in the place cursor: appended, they go after the ones it holds. +fn check_cursor_room(s: &Session, incoming: usize, append: bool, command: &str) -> Result<()> { + let held = if append { loaded_count(s) } else { 0 }; + if held.saturating_add(incoming) > MAX_LOADED_IMAGES { + return Err(bad(command, format!("the place cursor holds at most {MAX_LOADED_IMAGES} images, and it has {held}"))); + } + Ok(()) +} + +/// How many images the place cursor holds: the current one and those queued after it. +fn loaded_count(s: &Session) -> usize { + s.loaded_queue.len().saturating_add(usize::from(s.loaded.is_some())) +} + +/// Add a decoded asset with a fresh id, replacing the previous placement queue (or, with +/// `append` and an image already loaded, queued after it). +fn load_cursor(s: &mut Session, mut asset: Asset, size: (f64, f64), append: bool) -> Result { + check_cursor_room(s, 1, append, "place.load")?; let name = asset.name.clone(); let (pw, ph) = asset.pixels.unwrap_or_default(); let aid = s.edit(|d, _| { asset.id = AssetId(d.alloc()); Ok(d.add_asset(asset)) })?; - s.loaded = Some(crate::LoadedGraphic { asset: aid, size }); + let image = crate::LoadedGraphic { asset: aid, size }; + if append && s.loaded.is_some() { + s.loaded_queue.push_back(image); + } else { + s.loaded_queue.clear(); + s.loaded = Some(image); + } s.set_tool("placeGun"); Ok(json!({"asset": aid.0, "name": name, "width": pw, "height": ph, "loaded": true})) } -pub(super) fn place_drop(s: &mut Session, p: &Value) -> Result { - let crate::LoadedGraphic { asset: aid, size: (nw, nh) } = s.loaded.ok_or_else(|| bad("place.drop", "nothing loaded in the place cursor"))?; - // Undo can remove the loaded graphic's asset. - if !s.doc()?.doc.assets.contains_key(&aid) { - s.loaded = None; - return Err(bad("place.drop", "the loaded graphic is no longer in the document")); +/// Cancel every pending image if Undo removed an asset used by the cursor. +fn validate_place_cursor(s: &mut Session, command: &str) -> Result<()> { + // An empty cursor is its own error, and leaves the tool as it is. + if s.loaded.is_none() { + return Err(bad(command, "nothing loaded in the place cursor")); } + let valid = s.loaded.iter().chain(s.loaded_queue.iter()).all(|image| s.doc().is_ok_and(|d| d.doc.assets.contains_key(&image.asset))); + if !valid { + s.unload_place_cursor(); + return Err(bad(command, "the loaded graphic is no longer in the document")); + } + Ok(()) +} + +/// Place the current image and advance the cursor only after success. +pub(super) fn place_drop(s: &mut Session, p: &Value) -> Result { + validate_place_cursor(s, "place.drop")?; + let crate::LoadedGraphic { asset: aid, size: (nw, nh) } = s.loaded.ok_or_else(|| bad("place.drop", "nothing loaded in the place cursor"))?; let sr = crate::cmd::spread_param(p, "place.drop")?; let lid = s.doc()?.active_layer; let frame = crate::cmd::id_param(p, "frame"); @@ -276,7 +444,7 @@ pub(super) fn place_drop(s: &mut Session, p: &Value) -> Result { } // Drag: fit proportionally; click: actual size at the point. let (r, k) = match rect { - Some(r) if r.width() > 2.0 && r.height() > 2.0 => { + Some(r) if r.width() > designcraft_tools::PLACE_DRAG_MIN && r.height() > designcraft_tools::PLACE_DRAG_MIN => { let k = (r.width() / nw).min(r.height() / nh); (Rect::new(r.x0, r.y0, r.x0 + nw * k, r.y0 + nh * k), k) } @@ -315,16 +483,189 @@ pub(super) fn place_drop(s: &mut Session, p: &Value) -> Result { *sel = Selection::items(vec![id]); Ok(json!({"id": id.0})) })?; - s.loaded = None; - s.set_tool("selection"); + advance_place_cursor(s); Ok(r) } +/// Advance in file order, returning to selection when the queue is exhausted. +fn advance_place_cursor(s: &mut Session) { + s.loaded = s.loaded_queue.pop_front(); + if s.loaded.is_none() { + s.set_tool("selection"); + } +} + +/// Drop the current loaded image without placing it and move to the next; the last one ends placing. +pub(super) fn place_skip(s: &mut Session, _p: &Value) -> Result { + validate_place_cursor(s, "place.skip")?; + advance_place_cursor(s); + Ok(json!({"remaining": loaded_count(s)})) +} + +/// Rotate the loaded images: `dir` 1 makes the next one current (the current one goes to the back), +/// -1 the previous one (the last goes to the front). +pub(super) fn place_cycle(s: &mut Session, p: &Value) -> Result { + const ID: &str = "place.cycle"; + let dir = p.get("dir").and_then(Value::as_i64).filter(|d| matches!(d, 1 | -1)).ok_or_else(|| bad(ID, "dir must be 1 or -1"))?; + validate_place_cursor(s, ID)?; + if let Some(current) = s.loaded { + if dir == 1 { + s.loaded_queue.push_back(current); + s.loaded = s.loaded_queue.pop_front(); + } else if let Some(last) = s.loaded_queue.pop_back() { + s.loaded_queue.push_front(current); + s.loaded = Some(last); + } + } + Ok(json!({"remaining": loaded_count(s)})) +} + +/// Validate bounded grid dimensions and a finite nonnegative gutter. +fn grid_dimensions(p: &Value, command: &str, default_columns: usize, default_rows: usize) -> Result<(usize, usize, f64)> { + let dimension = |key, default| -> Result { + match p.get(key) { + None => Ok(default), + Some(v) => v + .as_u64() + .filter(|n| (1..=100).contains(n)) + .and_then(|n| usize::try_from(n).ok()) + .ok_or_else(|| bad(command, "rows and columns must be integers between 1 and 100")), + } + }; + let gutter = crate::cmd::f64_or(p, "gutter", 6.0); + if !gutter.is_finite() || gutter < 0.0 { + return Err(bad(command, "gutter must be finite and nonnegative")); + } + Ok((dimension("columns", default_columns)?, dimension("rows", default_rows)?, gutter)) +} + +/// Calculate row-major cells, rejecting gutters that leave no usable space. +fn grid_cells(rect: Rect, columns: usize, rows: usize, gutter: f64, command: &str) -> Result> { + let (columns, rows) = (columns.max(1), rows.max(1)); + let w = (rect.width() - gutter * columns.saturating_sub(1) as f64) / columns as f64; + let h = (rect.height() - gutter * rows.saturating_sub(1) as f64) / rows as f64; + if ![rect.x0, rect.y0, rect.x1, rect.y1, w, h].iter().all(|v| v.is_finite()) || w <= 0.0 || h <= 0.0 { + return Err(bad(command, "the grid area is too small for its rows, columns and gutter")); + } + Ok((0..rows) + .flat_map(|row| { + (0..columns).map(move |column| { + let x = rect.x0 + column as f64 * (w + gutter); + let y = rect.y0 + row as f64 * (h + gutter); + Rect::new(x, y, x + w, y + h) + }) + }) + .collect()) +} + +/// Insert a proportionally fitted image into one grid cell. +fn insert_grid_image( + d: &mut designcraft_doc::Document, + spread: designcraft_doc::SpreadRef, + layer: designcraft_doc::LayerId, + image: crate::LoadedGraphic, + rect: Rect, + command: &str, +) -> Result { + let crate::LoadedGraphic { asset, size: (nw, nh) } = image; + if !d.assets.contains_key(&asset) { + return Err(bad(command, "a loaded image is no longer in the document")); + } + let k = (rect.width() / nw).min(rect.height() / nh); + let xf = Affine::translate((rect.x0 + (rect.width() - nw * k) / 2.0, rect.y0 + (rect.height() - nh * k) / 2.0)) * Affine::scale(k); + validate_placement((nw, nh), rect, xf, command)?; + let id = ItemId(d.alloc()); + let mut item = Item::new(id, layer, Shape::Rectangle, shapes::rectangle(rect)); + item.object_style = d.styles.default_graphic_frame.clone(); + if let Some(effects) = d.styles.object_effects(&item.object_style) { + item.effects = effects.clone(); + } + item.content = Content::Graphic(Graphic { + layer_options: None, + asset, + size: (nw, nh), + xf, + auto_fit: designcraft_doc::Fitting::FitProportionally, + fit_align: 4, + crop: [0.0; 4], + clip: None, + wrap: Default::default(), + fill: Default::default(), + }); + d.insert_item(spread, item, None)?; + Ok(id) +} + +/// Place a row-major grid as one undoable edit. +pub(super) fn place_grid(s: &mut Session, p: &Value) -> Result { + const ID: &str = "place.grid"; + validate_place_cursor(s, ID)?; + let (columns, rows, gutter) = grid_dimensions(p, ID, 1, 1)?; + let rect = crate::cmd::rect_param(p, "rect").ok_or_else(|| bad(ID, "missing rect"))?; + let cells = grid_cells(rect, columns, rows, gutter, ID)?; + let images: Vec<_> = s.loaded.iter().chain(s.loaded_queue.iter()).copied().take(cells.len()).collect(); + if images.is_empty() { + return Err(bad(ID, "nothing loaded in the place cursor")); + } + let layer = s.doc()?.active_layer; + let spread = crate::cmd::spread_param(p, ID)?; + let ids = s.edit(|d, sel| { + let mut ids = Vec::with_capacity(images.len()); + for (image, rect) in images.iter().zip(cells) { + ids.push(insert_grid_image(d, spread, layer, *image, rect, ID)?); + } + *sel = Selection::items(ids.clone()); + Ok(ids) + })?; + for _ in &ids { + advance_place_cursor(s); + } + Ok(json!({"ids": ids.iter().map(|id| id.0).collect::>(), "remaining": loaded_count(s)})) +} + +/// Place all queued images on new pages as one undoable edit. +pub(super) fn place_contact_sheet(s: &mut Session, p: &Value) -> Result { + const ID: &str = "place.contactSheet"; + validate_place_cursor(s, ID)?; + let (columns, rows, gutter) = grid_dimensions(p, ID, 3, 4)?; + let margin = crate::cmd::f64_or(p, "margin", 36.0); + if !margin.is_finite() || margin < 0.0 { + return Err(bad(ID, "invalid margin")); + } + let images: Vec<_> = s.loaded.iter().chain(s.loaded_queue.iter()).copied().collect(); + if images.is_empty() { + return Err(bad(ID, "load images first using File > Place")); + } + let layer = s.doc()?.active_layer; + let per_page = columns.saturating_mul(rows).max(1); + let count = images.len().div_ceil(per_page); + let ids = s.edit(|d, sel| { + let after = d.page_count().saturating_sub(1); + d.insert_pages(Some(after), count, None)?; + let mut ids = Vec::with_capacity(images.len()); + for (page_offset, chunk) in images.chunks(per_page).enumerate() { + let index = after.saturating_add(1).saturating_add(page_offset); + let (si, pi) = d.page_loc(index).ok_or_else(|| bad(ID, "missing page"))?; + let b = d.spreads.get(si).and_then(|sp| sp.pages.get(pi)).ok_or_else(|| bad(ID, "missing page"))?.bounds(); + let cells = grid_cells(Rect::new(b.x0 + margin, b.y0 + margin, b.x1 - margin, b.y1 - margin), columns, rows, gutter, ID)?; + for (image, rect) in chunk.iter().zip(cells) { + ids.push(insert_grid_image(d, designcraft_doc::SpreadRef::Doc(si), layer, *image, rect, ID)?); + } + } + *sel = Selection::items(ids.clone()); + Ok(ids) + })?; + for _ in &ids { + advance_place_cursor(s); + } + Ok(json!({"pages": count, "images": ids.len()})) +} + /// File › Place of an IDML or DesignCraft document: the objects of one page (`layoutPage`, /// 1-based) grouped, top-left at x/y (default: the source position on the first page). -fn place_layout_page(s: &mut Session, p: &Value, name: &str, bytes: &[u8]) -> Result { +fn place_layout_page(s: &mut Session, p: &Value, bytes: &[u8], format: Option) -> Result { const ID: &str = "file.place"; - let src = if name.to_lowercase().ends_with(".idml") { + let src = if format == Some(craft_file_formats::Format::Idml) { crate::cmd::interchange::import_idml_confined(bytes, str_param(p, "path").map(std::path::Path::new)).map_err(|e| bad(ID, e.to_string()))? } else { from_bytes(bytes)? @@ -372,7 +713,7 @@ fn place_layout_page(s: &mut Session, p: &Value, name: &str, bytes: &[u8]) -> Re #[cfg(all(test, not(target_arch = "wasm32")))] pub(super) mod image_place_tests { - use designcraft_doc::{Content, ItemId}; + use designcraft_doc::{AssetId, Content, ItemId}; use designcraft_geom::Rect; use serde_json::{Value, json}; @@ -389,6 +730,64 @@ pub(super) mod image_place_tests { Ok(file) } + /// With nothing in the place cursor, placing says so and leaves the tool as it is (the + /// cursor's graphic gone from the document is another error). + #[test] + fn an_empty_place_cursor_says_so_and_keeps_the_tool() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + s.set_tool("rectangleFrame"); + for (cmd, p) in + [("place.drop", json!({"x": 10, "y": 10})), ("place.grid", json!({"rect": [0, 0, 100, 100]})), ("place.contactSheet", json!({}))] + { + let e = s.execute(cmd, &p).unwrap_err().to_string(); + assert!(e.contains("nothing loaded"), "{cmd}: {e}"); + assert_eq!(s.tool_id(), "rectangleFrame", "{cmd}"); + } + } + + fn test_png(shade: u8) -> String { + let png = designcraft_render::Rendered { width: 4, height: 4, pixels: vec![shade; 4 * 4 * 4] }.to_png(); + crate::cmd::base64_encode(&png) + } + + fn loaded_names(s: &Session) -> Vec { + let Ok(st) = s.doc() else { return Vec::new() }; + let d = &st.doc; + s.loaded.iter().chain(s.loaded_queue.iter()).map(|g| d.assets[&g.asset].name.clone()).collect() + } + + #[test] + fn skip_drops_the_current_image_and_the_last_one_ends_placing() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let files: Vec<_> = (0..3).map(|i| json!({"base64": test_png(i as u8), "name": format!("{i}.png")})).collect(); + s.execute("place.load", &json!({"files": files})).unwrap(); + assert_eq!(s.execute("place.skip", &json!({})).unwrap()["remaining"], 2); + assert_eq!(loaded_names(&s), ["1.png", "2.png"]); + s.execute("place.skip", &json!({})).unwrap(); + assert_eq!(s.tool_id(), "placeGun"); + s.execute("place.skip", &json!({})).unwrap(); + assert!(s.loaded.is_none()); + assert_eq!(s.tool_id(), "selection"); + assert!(s.execute("place.skip", &json!({})).is_err()); + } + + #[test] + fn cycle_rotates_the_loaded_images_both_ways() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let files: Vec<_> = (0..3).map(|i| json!({"base64": test_png(i as u8), "name": format!("{i}.png")})).collect(); + s.execute("place.load", &json!({"files": files})).unwrap(); + s.execute("place.cycle", &json!({"dir": 1})).unwrap(); + assert_eq!(loaded_names(&s), ["1.png", "2.png", "0.png"]); + s.execute("place.cycle", &json!({"dir": -1})).unwrap(); + s.execute("place.cycle", &json!({"dir": -1})).unwrap(); + assert_eq!(loaded_names(&s), ["2.png", "0.png", "1.png"]); + assert!(s.execute("place.cycle", &json!({"dir": 2})).is_err()); + assert!(s.execute("place.cycle", &json!({})).is_err()); + } + #[test] fn consecutive_path_placements_create_distinct_graphics() { let images = [image_file_with_color(30).unwrap(), image_file_with_color(31).unwrap(), image_file_with_color(32).unwrap()]; @@ -428,6 +827,44 @@ pub(super) mod image_place_tests { } } + #[test] + fn a_locked_frame_named_outright_is_not_replaced() { + let image = image_file_with_color(30).unwrap(); + let mut session = Session::new(); + session.execute("file.new", &json!({})).unwrap(); + let frame = session.execute("frame.create", &json!({"rect": [36, 36, 136, 136]})).unwrap()["id"].as_u64().unwrap(); + session.execute("object.lock", &json!({"ids": [frame]})).unwrap(); + assert!(session.execute("file.place", &json!({"path": image.path(), "frame": frame})).is_err()); + let document = &session.doc().unwrap().doc; + assert!(matches!(document.item(ItemId(frame)).unwrap().content, Content::Unassigned), "the locked frame stays empty"); + session.execute("object.unlockAll", &json!({})).unwrap(); + session.execute("file.place", &json!({"path": image.path(), "frame": frame})).unwrap(); + assert!(matches!(session.doc().unwrap().doc.item(ItemId(frame)).unwrap().content, Content::Graphic(_))); + } + + #[test] + fn place_load_remembers_the_fingerprint_captured_for_its_link() { + let image = image_file().unwrap(); + let mut session = Session::new(); + session.execute("file.new", &json!({})).unwrap(); + let load = |session: &mut Session| { + let loaded = session.execute("place.load", &json!({"path": image.path()})).unwrap(); + session.doc().unwrap().doc.assets[&AssetId(loaded["asset"].as_u64().unwrap())].clone() + }; + + // Written just now: another write in the same second would keep its time, so the time + // can't vouch for the bytes later: only the size is kept, with a time no file has. + let asset = load(&mut session); + assert_eq!(asset.link_fingerprint.map(|f| f.mtime), Some(crate::cmd::links::UNVERIFIED_MTIME)); + assert_eq!(asset.link.as_deref(), image.path().to_str()); + + // A file that has been as it is for a while is remembered by its size and time. + image.as_file().set_modified(std::time::SystemTime::now() - std::time::Duration::from_secs(60)).unwrap(); + let expected = crate::cmd::datamerge::fingerprint_from(&std::fs::metadata(image.path()).unwrap()); + session.execute("file.new", &json!({})).unwrap(); + assert_eq!(load(&mut session).link_fingerprint, Some(expected)); + } + #[test] fn individual_placement_parameters_bypass_selected_frames() { let image = image_file().unwrap(); @@ -469,6 +906,153 @@ pub(super) mod image_place_tests { } } + fn assert_implicit_placement_preserves_geometry(command: &str, params: Value) -> std::result::Result<(), Box> { + let image = image_file()?; + let mut session = Session::new(); + session.execute("file.new", &json!({}))?; + let selected = session.execute(command, ¶ms)?; + session.execute("object.stroke", &json!({"weight": 6}))?; + let id = ItemId(selected["id"].as_u64().ok_or("missing selected item id")?); + let original = serde_json::to_value(session.doc()?.doc.item(id).ok_or(designcraft_doc::DocError::NoItem(id))?)?; + + let placed = session.execute("file.place", &json!({"path": image.path()}))?; + + assert_ne!(placed["id"], selected["id"], "{command}"); + let document = &session.doc()?.doc; + assert_eq!(serde_json::to_value(document.item(id).ok_or(designcraft_doc::DocError::NoItem(id))?)?, original, "{command}"); + let placed_id = ItemId(placed["id"].as_u64().ok_or("missing placed item id")?); + let item = document.item(placed_id).ok_or(designcraft_doc::DocError::NoItem(placed_id))?; + assert_eq!(item.bounds(), Rect::new(36.0, 36.0, 76.0, 56.0)); + assert!(matches!(item.content, Content::Graphic(_))); + assert_eq!(document.spreads[0].items.len(), 2); + Ok(()) + } + + #[test] + fn implicit_placement_preserves_selected_line() { + assert_implicit_placement_preserves_geometry("line.create", json!({"a": [18, 600], "b": [594, 600]})).unwrap(); + } + + #[test] + fn implicit_placement_preserves_selected_straight_open_path() { + assert_implicit_placement_preserves_geometry( + "path.create", + json!({"anchors": [{"p": [20, 30]}, {"p": [80, 90]}, {"p": [140, 150]}], "closed": false}), + ) + .unwrap(); + } + + /// Paths with an area take the image: a closed empty frame, and an open V as before. + #[test] + fn implicit_placement_fills_selected_frames_and_open_paths_with_an_area() { + let image = image_file().unwrap(); + for (command, params) in [ + ("frame.create", json!({"rect": [100, 120, 200, 220]})), + ("path.create", json!({"anchors": [{"p": [20, 30]}, {"p": [80, 90]}, {"p": [140, 30]}], "closed": false})), + ] { + let mut session = Session::new(); + session.execute("file.new", &json!({})).unwrap(); + let selected = session.execute(command, ¶ms).unwrap(); + + let placed = session.execute("file.place", &json!({"path": image.path()})).unwrap(); + + assert_eq!(placed["id"], selected["id"], "{command}"); + let document = &session.doc().unwrap().doc; + assert!(matches!(document.item(ItemId(selected["id"].as_u64().unwrap())).unwrap().content, Content::Graphic(_)), "{command}"); + assert_eq!(document.spreads[0].items.len(), 1, "{command}"); + } + } + + /// A `width` x `height` PNG with a pHYs chunk of `ppm` pixels per meter on both axes, or none. + fn png_with_density(width: u32, height: u32, ppm: Option) -> std::io::Result { + fn crc32(data: &[u8]) -> u32 { + let mut crc = 0xFFFF_FFFFu32; + for &b in data { + crc ^= b as u32; + for _ in 0..8 { + crc = if crc & 1 == 1 { (crc >> 1) ^ 0xEDB8_8320 } else { crc >> 1 }; + } + } + !crc + } + let pixels = [30, 90, 180, 255].repeat((width * height) as usize); + let png = designcraft_render::Rendered { width, height, pixels }.to_png(); + assert_eq!(&png[12..16], b"IHDR"); + let mut bytes = png[..33].to_vec(); + if let Some(ppm) = ppm { + let mut phys = Vec::new(); + phys.extend_from_slice(&ppm.to_be_bytes()); + phys.extend_from_slice(&ppm.to_be_bytes()); + phys.push(1); + bytes.extend_from_slice(&(phys.len() as u32).to_be_bytes()); + bytes.extend_from_slice(b"pHYs"); + bytes.extend_from_slice(&phys); + let mut c = b"pHYs".to_vec(); + c.extend_from_slice(&phys); + bytes.extend_from_slice(&crc32(&c).to_be_bytes()); + } + bytes.extend_from_slice(&png[33..]); + let file = tempfile::Builder::new().suffix(".png").tempfile()?; + std::fs::write(file.path(), bytes)?; + Ok(file) + } + + #[test] + fn placed_photo_honors_its_embedded_resolution() { + // #1991: a placed graphic's embedded density sets its size (600 dpi: 40 px place + // 4.8 pt wide), instead of a pixel always becoming a point. + let file = png_with_density(40, 20, Some(23622)).unwrap(); + let mut session = Session::new(); + session.execute("file.new", &json!({})).unwrap(); + let placed = session.execute("file.place", &json!({"path": file.path(), "x": 10.0, "y": 20.0})).unwrap(); + let document = &session.doc().unwrap().doc; + let item = document.item(ItemId(placed["id"].as_u64().unwrap())).unwrap(); + let b = item.bounds(); + assert!((b.x0 - 10.0).abs() < 1e-9 && (b.y0 - 20.0).abs() < 1e-9, "{b:?}"); + assert!((b.width() - 4.8).abs() < 0.01 && (b.height() - 2.4).abs() < 0.01, "{b:?}"); + } + + /// File › Place, then a click: an 11 x 17 in image (330 x 510 px at 30 ppi) comes in at + /// 792 x 1224 pt, keeps that size through a save and reopen, and an image with no stored + /// resolution comes in at 72 ppi (330 x 510 pt). + #[test] + fn a_clicked_image_keeps_its_print_size_through_save_and_reopen() { + // 1181 pixels per meter is 29.9974 ppi. + let (w, h) = (330.0 * 72.0 / (1181.0 * 0.0254), 510.0 * 72.0 / (1181.0 * 0.0254)); + for (ppm, (ew, eh)) in [(Some(1181), (w, h)), (None, (330.0, 510.0))] { + let image = png_with_density(330, 510, ppm).unwrap(); + let mut session = Session::new(); + session.execute("file.new", &json!({})).unwrap(); + session.execute("file.place", &json!({"path": image.path(), "loadCursor": true})).unwrap(); + session.execute("place.drop", &json!({"x": 0, "y": 0})).unwrap(); + // The bounds and natural size of the document's one placed graphic. + let shown = |session: &Session| { + let doc = &session.doc().unwrap().doc; + let graphics: Vec<_> = doc + .all_items() + .into_iter() + .filter_map(|id| doc.item(id)) + .filter_map(|item| match &item.content { + Content::Graphic(g) => Some((item.bounds(), g.size)), + _ => None, + }) + .collect(); + assert_eq!(graphics.len(), 1, "{graphics:?}"); + graphics[0] + }; + let (b, size) = shown(&session); + assert!((b.width() - ew).abs() < 1e-6 && (b.height() - eh).abs() < 1e-6, "{ppm:?}: {b:?}"); + assert!((size.0 - ew).abs() < 1e-6 && (size.1 - eh).abs() < 1e-6, "{ppm:?}: {size:?}"); + + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("placed.designcraft"); + session.execute("file.save", &json!({"path": path.to_string_lossy()})).unwrap(); + let mut reopened = Session::new(); + reopened.execute("file.open", &json!({"path": path.to_string_lossy()})).unwrap(); + assert_eq!(shown(&reopened), (b, size), "{ppm:?}"); + } + } + #[test] fn explicit_frame_wins_over_placement_and_selection() { let image = image_file().unwrap(); @@ -756,3 +1340,127 @@ mod layout_place_tests { assert!(b.execute("file.place", &json!({"base64": b64, "name": "src.idml", "layoutPage": 2})).is_err(), "page 2 is empty"); } } + +#[cfg(test)] +mod nested_frame_tests { + use std::sync::Arc; + + use designcraft_doc::{Content, Item, ItemId, Shape, SpreadRef}; + use designcraft_geom::{Affine, Rect, shapes}; + use serde_json::json; + + use crate::Session; + + fn png(red: u8) -> String { + let png = designcraft_render::Rendered { width: 40, height: 20, pixels: [red, 90, 30, 255].repeat(800) }.to_png(); + super::super::base64_encode(&png) + } + + /// A graphic placed into a frame holding an image pasted into it (how a document from InDesign + /// keeps a photo) replaces the image and fills the frame, which keeps its size. + #[test] + fn placing_into_a_frame_with_a_nested_image_replaces_it() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let first = s.execute("file.place", &json!({"base64": png(200), "name": "old.png", "x": 0, "y": 0})).unwrap(); + let old = ItemId(first["id"].as_u64().unwrap()); + let frame = s + .edit(|d, _| { + let mut image = (*d.item(old).unwrap()).clone(); + d.remove_item(old)?; + image.xf = Affine::translate((-20.0, -20.0)); + let id = ItemId(d.alloc()); + let mut frame = Item::new(id, image.layer, Shape::Rectangle, shapes::rectangle(Rect::new(0.0, 0.0, 60.0, 90.0))); + frame.xf = Affine::translate((100.0, 100.0)); + frame.content = Content::Group { items: vec![Arc::new(image)] }; + d.insert_item(SpreadRef::Doc(0), frame, None)?; + Ok(id) + }) + .unwrap(); + s.execute("selection.set", &json!({"ids": [frame.0]})).unwrap(); + s.execute("file.place", &json!({"base64": png(20), "name": "new.png"})).unwrap(); + let d = &s.doc().unwrap().doc; + let it = d.item(frame).unwrap(); + let Content::Graphic(g) = &it.content else { panic!("the frame holds the new graphic: {:?}", it.content) }; + assert_eq!(d.assets[&g.asset].name, "new.png"); + assert_eq!(it.inner_bounds(), Rect::new(0.0, 0.0, 60.0, 90.0), "the frame keeps its size"); + assert_eq!(d.spreads[0].items.len(), 1, "no new object"); + } +} + +#[cfg(test)] +mod cursor_cap_tests { + use serde_json::{Value, json}; + + use super::MAX_LOADED_IMAGES; + use crate::Session; + + fn png() -> String { + let png = designcraft_render::Rendered { width: 4, height: 4, pixels: [200, 90, 30, 255].repeat(16) }.to_png(); + super::super::base64_encode(&png) + } + + /// A session whose place cursor holds `held` images, loaded without decoding each of them. + fn holding(held: usize) -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + s.execute("place.load", &json!({"base64": png(), "name": "first.png"})).unwrap(); + let first = s.loaded.unwrap(); + s.loaded_queue = std::iter::repeat_n(first, held - 1).collect(); + s + } + + fn count(s: &Session) -> usize { + super::loaded_count(s) + } + + /// Every way of adding to the cursor stops at the cap, and a refused add changes nothing. + #[test] + fn appending_stops_at_the_cap_on_the_whole_cursor() { + let image = png(); + let single = json!({"base64": image, "name": "a.png", "append": true}); + let placed = json!({"base64": image, "name": "a.png", "append": true, "loadCursor": true}); + let two = json!({"files": [{"base64": image, "name": "a.png"}, {"base64": image, "name": "b.png"}], "append": true}); + for (command, params) in [("place.load", &single), ("file.place", &placed), ("place.load", &two)] { + let mut s = holding(MAX_LOADED_IMAGES); + let assets = s.doc().unwrap().doc.assets.len(); + assert!(s.execute(command, params).is_err(), "{command} {params}"); + assert_eq!(count(&s), MAX_LOADED_IMAGES, "{command} {params}"); + assert_eq!(s.doc().unwrap().doc.assets.len(), assets, "{command} {params}"); + } + // One over, as a batch. + let mut s = holding(MAX_LOADED_IMAGES - 1); + assert!(s.execute("place.load", &two).is_err()); + assert_eq!(count(&s), MAX_LOADED_IMAGES - 1); + } + + /// The last places up to the cap load, and an unreadable batch reports the cap before decoding. + #[test] + fn appending_up_to_the_cap_still_loads() { + let image = png(); + for params in + [json!({"base64": image, "name": "a.png", "append": true}), json!({"files": [{"base64": image, "name": "a.png"}], "append": true})] + { + let mut s = holding(MAX_LOADED_IMAGES - 1); + s.execute("place.load", ¶ms).unwrap(); + assert_eq!(count(&s), MAX_LOADED_IMAGES, "{params}"); + } + let mut s = holding(MAX_LOADED_IMAGES); + let error = + s.execute("place.load", &json!({"files": [{"base64": "not an image", "name": "a.png"}], "append": true})).unwrap_err().to_string(); + assert!(error.contains(&MAX_LOADED_IMAGES.to_string()), "{error}"); + } + + /// Without `append` the new images replace the cursor, so what it holds doesn't count. + #[test] + fn replacing_a_full_cursor_is_not_capped() { + let image = png(); + let mut s = holding(MAX_LOADED_IMAGES); + let result: Value = s.execute("place.load", &json!({"base64": image, "name": "a.png"})).unwrap(); + assert_eq!(result["loaded"], true); + assert_eq!(count(&s), 1); + let mut s = holding(MAX_LOADED_IMAGES); + s.execute("place.load", &json!({"files": [{"base64": image, "name": "a.png"}]})).unwrap(); + assert_eq!(count(&s), 1); + } +} diff --git a/crates/engine/src/cmd/file/registry.rs b/crates/engine/src/cmd/file/registry.rs index 216f12bdb..f59144fe6 100644 --- a/crates/engine/src/cmd/file/registry.rs +++ b/crates/engine/src/cmd/file/registry.rs @@ -1,10 +1,8 @@ -#[cfg(not(target_arch = "wasm32"))] -use super::EngineError; -use super::bytes::{base64_encode, to_bytes, to_bytes_with_preview, with_document_extension}; +use super::bytes::{base64_encode, to_bytes}; use super::new::{file_new, file_sample, save_preset}; use super::open::{file_open, file_open_bytes, file_open_recent, has_recent, recent_entry}; -use super::place::{file_place, place_drop, place_load, read_source}; -use super::save::{FolderAccess, can_revert, file_revert, file_save, recovery_dir}; +use super::place::{file_place, place_contact_sheet, place_cycle, place_drop, place_grid, place_load, place_skip, read_source}; +use super::save::{FolderAccess, can_revert, file_revert, file_save, file_save_a_copy, recovery_dir}; use super::snippets::{snippet_export, snippet_place}; use super::{CommandSpec, PRESETS, Value, always, bad, cmd, has_doc, json, ok, str_param}; @@ -37,7 +35,7 @@ pub fn specs() -> Vec { ok() }), cmd!(noundo "file.open", "Open…", ["File"], Some("Cmd+O"), - "{path} — a DesignCraft or IDML file (recognised by its content, so the extension may be missing), or an InDesign .indd/.indt (recognised by its signature or extension, converted to IDML; its conversion warnings join `warnings`); the fonts in a `Document Fonts` folder beside it load first → {index, documentFonts: faces loaded, warnings: font files skipped, GREP styles whose pattern can't compile, Based on Parent links cleared and, for IDML and InDesign files, package parts missing}", + "{path} — a DesignCraft or IDML file (recognised by its content, so the extension may be missing), or an InDesign .indd/.indt (recognised by its signature or extension, converted to IDML; its conversion warnings join `warnings`); the fonts in a `Document Fonts` folder beside it load first → {index, documentFonts: faces loaded, warnings: font files skipped, GREP styles whose pattern can't compile, Based on Parent links cleared and, for IDML and InDesign files, package parts missing; warningItems (IDML and InDesign files): per warning, the id of the frame it is about, or null}", always, file_open), cmd!(noundo "file.openBytes", "Open Bytes", [], None, "{name, base64} — DesignCraft JSON, an IDML package or an InDesign .indd/.indt → {index, warnings}", always, file_open_bytes), cmd!(noundo "file.openRecent", "Open Recent File", [], None, @@ -52,36 +50,44 @@ pub fn specs() -> Vec { }), 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} — 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}", has_doc, |s, p| { - let path = str_param(p, "path").ok_or_else(|| bad("file.saveACopy", "missing `path`"))?; - let path = with_document_extension(path); - let mut copy = (*s.doc()?.doc).clone(); - crate::cmd::datamerge::refresh_relative_paths(&mut copy, std::path::Path::new(&path)); - let bytes = to_bytes_with_preview(©, &s.cache)?; - #[cfg(not(target_arch = "wasm32"))] - crate::io::write_file(&path, &bytes).map_err(EngineError::Other)?; - Ok(json!({"path": path, "bytes": bytes.len()})) - }), + 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.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)?; Ok(Value::Array(crate::recovery::list(&dir).into_iter().map(|(uid, mut m)| { m["uid"] = json!(uid); m }).collect())) }), - cmd!(noundo "file.recovery.save", "Save Recovery Data", [], None, "{dir?} — write every unsaved document to the recovery folder (the app does this on a timer)", always, |s, p| { + cmd!(noundo "file.recovery.save", "Save Recovery Data", [], None, + "{dir?, background?} — write every unsaved document to the recovery folder (the app does this on a timer; `background` queues the writes and returns at once) → {saved} or {queued}", + always, |s, p| { + let background = match p.get("background") { + None | Some(Value::Null) => false, + Some(v) => v.as_bool().ok_or_else(|| bad("file.recovery.save", "`background` must be true or false"))?, + }; let dir = recovery_dir(s, p, FolderAccess::Write)?; + if background { + return Ok(json!({"queued": crate::recovery::start_tracked(s, &dir)?})); + } Ok(json!({"saved": crate::recovery::save_tracked(s, &dir)?})) }), + cmd!(query "file.recovery.progress", "Recovery Progress", [], None, + "{} → {written, busy, errors} recovery data queued in the background has been written", always, |s, _| { + let done = crate::recovery::finished(s); + Ok(json!({"written": done.written, "busy": done.busy, "errors": done.errors})) + }), cmd!(noundo "file.recovery.open", "Recover Documents", [], None, "{dir?} — reopen documents left in the recovery folder (unsaved)", always, |s, p| { // Reopening removes the entries it read. let dir = recovery_dir(s, p, FolderAccess::ReadWrite)?; Ok(json!({"opened": crate::recovery::open(s, &dir)?})) }), - cmd!(query "file.serialize", "Serialize", [], None, "{} → {base64, bytes} the .designcraft file", has_doc, |s, _| { + cmd!(query "file.serialize", "Serialize", [], None, "{} → {base64, bytes, warnings} the .designcraft file (on the web, linked files stay links, with a warning)", has_doc, |s, _| { let st = s.doc()?; // Preview fill is session state. Serialize the unfilled template. let doc = st.preview_stash.as_deref().unwrap_or(st.doc.as_ref()); + let proxied = crate::cmd::native_links::with_proxies(doc, || false); + let doc = proxied.as_ref().unwrap_or(doc); let bytes = to_bytes(doc)?; - Ok(json!({"base64": base64_encode(&bytes), "bytes": bytes.len()})) + let warnings = crate::cmd::native_links::web_save_warnings(doc); + Ok(json!({"base64": base64_encode(&bytes), "bytes": bytes.len(), "warnings": warnings})) }), cmd!(noundo "file.close", "Close", ["File"], Some("Cmd+W"), "{index?}", has_doc, |s, p| { let i = p.get("index").and_then(Value::as_u64).map(|v| v as usize).or(s.active_index()).unwrap_or(0); @@ -97,8 +103,8 @@ pub fn specs() -> Vec { cmd!(query "place.styles", "Import Options: Styles", [], None, "{path | base64, name} → {paragraph: [name], character: [name], conflicts: [name]} — the styles a Word/RTF file brings (for styleMap / styleConflicts)", has_doc, |s, p| { - let (bytes, name, _) = read_source(p)?; - let imp = designcraft_textimport::import(&name, &bytes).map_err(|e| bad("place.styles", e.to_string()))?; + let source = read_source(p)?; + let imp = designcraft_textimport::import(&source.name, &source.bytes).map_err(|e| bad("place.styles", e.to_string()))?; let st = &s.doc()?.doc.styles; let conflicts: Vec<&str> = imp .para_styles @@ -123,17 +129,43 @@ pub fn specs() -> Vec { "Load Place Cursor", [], None, - "{path | base64, name?} — load a graphic into the place cursor (then click/drag with the placeGun tool)", + "{path | base64, name?, files?: [{path | base64, name?, embed?}], append? (keep the images already loaded and queue these after them), embed? (keep every image's bytes in the document; default: images read from a path link to their files)} — load up to 1000 images into the place cursor, in order (then click/drag with the placeGun tool)", has_doc, place_load ), cmd!("place.drop", "Place Loaded Graphic", [], None, "{spread?, x, y, rect?: [x0,y0,x1,y1], frame?: id}", has_doc, place_drop), + cmd!( + "place.grid", + "Place Image Grid", + [], + None, + "{spread?, rect: [x0,y0,x1,y1], columns?: 1, rows?: 1, gutter?: 6} — place queued images in row order", + has_doc, + place_grid + ), + cmd!( + "place.contactSheet", + "Place Contact Sheet", + ["File"], + None, + "{columns?: 3, rows?: 4, gutter?: 6, margin?: 36} — place all loaded images on new pages", + has_doc, + place_contact_sheet + ), + cmd!(noundo "place.skip", "Skip Loaded Image", [], None, "{} — drops the current loaded image without placing it and loads the next; the last one ends placing", has_doc, place_skip), + cmd!(noundo "place.cycle", "Cycle Loaded Images", [], None, "{dir: 1|-1} — makes the next (1) or previous (-1) loaded image the current one", has_doc, place_cycle), + cmd!(noundo "place.cancel", "Cancel Image Placement", [], None, "{} — clears every loaded image", has_doc, |s, _| { + s.loaded = None; + s.loaded_queue.clear(); + s.set_tool("selection"); + ok() + }), cmd!( "file.place", "Place…", ["File"], Some("Cmd+D"), - "{path?|base64?, name?, frame?: id (place into), spread?, x?, y?, width?: finite number > 0 (null: absent), height? (video/audio), pdfPage?: n (1-based, Image Import Options), pdfCrop?: crop|art|trim|bleed|media|contentVisible|contentAll (the box the graphic shows; `width` is the whole page's), loadCursor? (with no frame to fill and no x/y, an image loads into the place cursor, as File › Place), layoutPage?: n (IDML / .designcraft: that page's objects as a group), page?, rect?: [x0,y0,x1,y1] (text: a new frame there), autoflow? (threads one frame per page column from the first frame on, adding pages until the text fits), removeStyles?, styleMap?: {imported name: document style}, styleConflicts?: useExisting|redefine|autoRename, link? (keep the file linked in the Links panel; default: the linkTextFiles preference)} — places an image into `frame` when given; otherwise any explicit x/y/spread/width creates a new frame; otherwise uses the selected empty or graphic frame, or creates a new frame; text files (.txt, .docx, .rtf, .md) and Excel workbooks (.xlsx, as a table) go into the insertion point, the selected frame or a new frame on `page`/`rect`", + "{path?|base64?, name?, embed? (keep the file's bytes in the document; default: a graphic placed from a path links to its file, base64 bytes and the web always embed), frame?: id (place into), spread?, x?, y?, width?: finite number > 0 (null: absent), height? (video/audio), pdfPage?: n (1-based, Image Import Options), pdfCrop?: crop|art|trim|bleed|media|contentVisible|contentAll (the box the graphic shows; `width` is the whole page's), loadCursor? (with no frame to fill and no x/y, an image loads into the place cursor, as File › Place), append? (with loadCursor: queue the image after those already loaded instead of replacing them), layoutPage?: n (IDML / .designcraft: that page's objects as a group), page?, rect?: [x0,y0,x1,y1] (text: a new frame there), autoflow? (threads one frame per page column from the first frame on, adding pages until the text fits), removeStyles?, styleMap?: {imported name: document style}, styleConflicts?: useExisting|redefine|autoRename, link? (keep the file linked in the Links panel; default: the linkTextFiles preference)} — places an image into `frame` when given; otherwise any explicit x/y/spread/width creates a new frame; otherwise uses the selected empty or graphic frame, or creates a new frame; text files (.txt, .docx, .rtf, .md) and Excel workbooks (.xlsx, as a table) go into the insertion point, the selected frame or a new frame on `page`/`rect`", has_doc, file_place ), diff --git a/crates/engine/src/cmd/file/save.rs b/crates/engine/src/cmd/file/save.rs index d94a02ab9..7d5b1ba19 100644 --- a/crates/engine/src/cmd/file/save.rs +++ b/crates/engine/src/cmd/file/save.rs @@ -19,16 +19,28 @@ pub(super) fn file_save(s: &mut Session, p: &Value) -> Result { // Before anything about the document changes: a refused save leaves it as it was. crate::file_access::check_write(&path).map_err(EngineError::Other)?; // Prepare paths for the destination without changing the live document until persistence succeeds. - let mut saved = (*st.doc).clone(); - crate::cmd::datamerge::refresh_relative_paths(&mut saved, std::path::Path::new(&path)); - let paths_changed = saved.data_merge != st.doc.data_merge; - let saved = if paths_changed { Arc::new(saved) } else { st.doc.clone() }; + let destination = std::path::Path::new(&path); + let from = st.path.as_deref().map(std::path::Path::new); + let linked = crate::cmd::native_links::for_destination(&st.doc, from, destination); + let links_changed = linked.is_some(); + let mut saved = linked.unwrap_or_else(|| (*st.doc).clone()); + crate::cmd::datamerge::refresh_relative_paths(&mut saved, destination); + // Proxies the background job hasn't made yet are made here, on this thread: the save is + // synchronous. The document keeps them. + let proxied = crate::cmd::native_links::with_proxies(&saved, || false); + let proxies_made = proxied.is_some(); + 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)?; #[cfg(not(target_arch = "wasm32"))] crate::io::write_file(&path, &bytes).map_err(EngineError::Other)?; let st = s.doc_mut()?; - if paths_changed { - st.doc = saved; + // Images saved as links let go of their bytes; linked files resolve against the new file. + let doc = crate::cmd::native_links::after_save(&saved, destination).map_or(saved, Arc::new); + if !Arc::ptr_eq(&doc, &st.doc) { + st.doc = doc; st.bump_revision(); } st.path = Some(path.clone()); @@ -41,7 +53,35 @@ pub(super) fn file_save(s: &mut Session, p: &Value) -> Result { crate::recovery::discard_document(s, index, recovery_dir.as_deref()); s.prefs.note_recent_file(&path); } - Ok(json!({"path": path, "bytes": bytes.len()})) + Ok(json!({"path": path, "bytes": bytes.len(), "warnings": warnings})) +} + +/// `file.saveACopy`: the document written to `path` without changing which file it is or its +/// unsaved state. With `embedLinks`, every linked file is copied in: a document that opens +/// anywhere. +pub(super) fn file_save_a_copy(s: &mut Session, p: &Value) -> Result { + let path = str_param(p, "path").ok_or_else(|| bad("file.saveACopy", "missing `path`"))?; + let path = with_document_extension(path); + let 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"))?, + }; + let st = s.doc()?; + let destination = std::path::Path::new(&path); + let from = st.path.as_deref().map(std::path::Path::new); + let mut copy = crate::cmd::native_links::for_destination(&st.doc, from, destination).unwrap_or_else(|| (*st.doc).clone()); + crate::cmd::datamerge::refresh_relative_paths(&mut copy, destination); + if embed { + crate::cmd::native_links::embed_linked(&mut copy, "file.saveACopy")?; + } + 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)?; + #[cfg(not(target_arch = "wasm32"))] + crate::io::write_file(&path, &bytes).map_err(EngineError::Other)?; + Ok(json!({"path": path, "bytes": bytes.len(), "warnings": warnings})) } /// Which access a recovery command needs to the folder it is given. @@ -89,20 +129,23 @@ pub(super) fn file_revert(s: &mut Session, _: &Value) -> Result { let path = s.doc()?.path.clone().ok_or_else(|| bad("file.revert", "the document has never been saved"))?; #[cfg(not(target_arch = "wasm32"))] { - let mut d = if path.to_ascii_lowercase().ends_with(".idml") { - let bytes = crate::io::read_file(&path).map_err(EngineError::Other)?; + let bytes = crate::io::read_file(&path).map_err(EngineError::Other)?; + let mut d = if craft_file_formats::detect(&path, &bytes) == Some(craft_file_formats::Format::Idml) { crate::cmd::interchange::import_idml_confined(&bytes, Some(std::path::Path::new(&path))).map_err(|e| EngineError::Other(e.to_string()))? } else { - from_bytes(&crate::io::read_file(&path).map_err(EngineError::Other)?)? + from_bytes(&bytes)? }; - // As opened again: the fonts beside it now (unchanged files are shared, not read again). + // As opened again: the fonts beside it now (unchanged files are shared, not read again), + // its linked files found again. let (fonts, _, _) = load_document_fonts(&mut d, &path); + let links = crate::cmd::native_links::resolve(&mut d, Some(std::path::Path::new(&path)), true); let uid = s.doc()?.uid; let recovery_dir = s.recovery_dir.clone(); let index = s.active_index().ok_or(EngineError::NoDocument)?; let mut fresh = DocState::new(d, Some(path.clone())); fresh.fonts = fonts; fresh.uid = uid; + crate::cmd::native_links::start(&mut fresh, links); // A new state has a revision no state had before, so caches don't show the old document. crate::recovery::discard_document(s, index, recovery_dir.as_deref()); *s.doc_mut()? = fresh; diff --git a/crates/engine/src/cmd/file/snippets.rs b/crates/engine/src/cmd/file/snippets.rs index 5ff1f3795..21d986dce 100644 --- a/crates/engine/src/cmd/file/snippets.rs +++ b/crates/engine/src/cmd/file/snippets.rs @@ -23,8 +23,7 @@ pub(super) fn snippet_export(s: &mut Session, p: &Value) -> Result { } pub(crate) fn snippet_place(s: &mut Session, p: &Value) -> Result { - let (bytes, _, _) = read_source(p)?; - let src = from_bytes(&bytes)?; + let src = from_bytes(&read_source(p)?.bytes)?; let ids: Vec = src.spreads.first().map(|sp| sp.items.iter().map(|i| i.id).collect()).unwrap_or_default(); if ids.is_empty() { return Err(bad("snippet.place", "the snippet is empty")); diff --git a/crates/engine/src/cmd/find.rs b/crates/engine/src/cmd/find.rs index 8d7c68632..63a1debb9 100644 --- a/crates/engine/src/cmd/find.rs +++ b/crates/engine/src/cmd/find.rs @@ -1,12 +1,12 @@ //! Edit → Find/Change: plain text and GREP (regular expressions) with InDesign's metacharacters, -//! optional formatting in the change, scoped to the document, a story or the selection. +//! a Find Format and a Change Format, scoped to the document, a story or the selection. use std::ops::Range; use std::sync::{Arc, Weak}; use designcraft_compose::grep::{Grep, GrepOptions, translate_replacement}; use designcraft_doc::story::floor_char_boundary; -use designcraft_doc::{CellAddr, Document, Selection, StoryId, TextSel}; +use designcraft_doc::{CellAddr, Document, Selection, Story, StoryId, Styles, TextSel}; use serde_json::{Value, json}; use super::{CommandSpec, bad, bool_or, cmd, has_doc, str_param}; @@ -61,18 +61,18 @@ pub fn specs() -> Vec { } ), cmd!(query "find.find", "Find", ["Edit", "Find/Change"], None, - "{find, grep?: bool, caseSensitive?: bool, wholeWord?: bool, scope?: document|story|selection, story?, change?|first?|attrs?: ignored (find.change takes them; one request serves all three Find/Change commands)} → matches [{story, start, end, text, cell?: {table, row, col}}] (document scope also searches table cells; start/end then index the cell's text)", + "{find, grep?: bool, caseSensitive?: bool, wholeWord?: bool, scope?: document|story|selection, story?, findFormat?: {charStyle?, paraStyle?, chars?: resolved character attributes} (Find Format: only text with it all through; with an empty find, each stretch of text with it), change?|first?|found?|attrs?|charStyle?|paraStyle?: ignored (find.change takes them; one request serves all three Find/Change commands)} → matches [{story, start, end, text, cell?: {table, row, col}}] (document scope also searches table cells; start/end then index the cell's text)", has_doc, find), cmd!( "find.change", "Change All", ["Edit", "Find/Change"], None, - "{find, change, grep?, caseSensitive?, wholeWord?, scope?, story?, first?: bool (change only the first match), attrs?: {character attributes applied to changed text}} → {count}", + "{find, change, grep?, caseSensitive?, wholeWord?, scope?, story?, findFormat?: {charStyle?, paraStyle?, chars?: resolved character attributes} (Find Format: only text with it all through; with an empty find, each stretch of text with it), first?: bool (change only the first match), found?: bool (Change: only the text Find Next found, while it is selected and still a match; it stays selected, and Find Next goes on after it in the same domain), attrs?: {character attributes applied to changed text}, charStyle?: a character style applied to it, paraStyle?: a paragraph style applied to its paragraphs} → {count} — attrs, charStyle and paraStyle are the Change Format: with one and an empty change, the found text stays and is only formatted; with no find, change is literal text", has_doc, change ), - cmd!(noundo "find.next", "Find Next", ["Edit"], Some("Cmd+Alt+F"), "{find, grep?, caseSensitive?, wholeWord?, scope?: document|story|selection, story?, change?|first?|attrs?: ignored (find.change takes them; one request serves all three Find/Change commands)} — Selection starts at its original beginning; later calls advance within the scope", has_doc, find_next), + cmd!(noundo "find.next", "Find Next", ["Edit"], Some("Cmd+Alt+F"), "{find, grep?, caseSensitive?, wholeWord?, scope?: document|story|selection, story?, findFormat?: {charStyle?, paraStyle?, chars?: resolved character attributes} (Find Format: only text with it all through; with an empty find, each stretch of text with it), change?|first?|found?|attrs?|charStyle?|paraStyle?: ignored (find.change takes them; one request serves all three Find/Change commands)} — Selection starts at its original beginning; later calls advance within the scope", has_doc, find_next), ] } @@ -108,6 +108,235 @@ fn build(p: &Value) -> Result { re.map_err(|e| bad("find", e)) } +/// Find/Change's Find Format: the text a search finds must have it all through. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +struct FindFormat { + char_style: Option, + para_style: Option, + /// Resolved character attributes, as `type.selectionAttrs` reports them. + chars: serde_json::Map, +} + +impl FindFormat { + fn from_params(p: &Value) -> Result> { + let Some(f) = p.get("findFormat").filter(|f| !f.is_null()) else { return Ok(None) }; + let o = f.as_object().ok_or_else(|| bad("find", "`findFormat` is an object"))?; + // A style is named; a null asks for none. Any other value is refused rather than + // searched without. + let name = |k: &str| match o.get(k) { + None | Some(Value::Null) => Ok(None), + Some(Value::String(n)) => Ok(Some(n.clone())), + Some(v) => Err(bad("find", format!("findFormat: `{k}` is a style name, not {v}"))), + }; + let chars = match o.get("chars") { + None | Some(Value::Null) => None, + Some(Value::Object(m)) => Some(m), + Some(v) => return Err(bad("find", format!("findFormat: `chars` is an object of character attributes, not {v}"))), + }; + // Only attributes text has, kept as the document writes them: `font_style` and + // `fontStyle`, or 12 and 12.0, then find the same text. A null asks for nothing. + let mut known = designcraft_doc::CharAttrs::default(); + for (k, v) in chars.into_iter().flatten() { + known.set_json(k, v).map_err(|e| bad("find", format!("findFormat: {e}")))?; + } + let chars = match serde_json::to_value(&known) { + Ok(Value::Object(m)) => m, + _ => serde_json::Map::new(), + }; + let f = Self { char_style: name("charStyle")?, para_style: name("paraStyle")?, chars }; + Ok((f != Self::default()).then_some(f)) + } + + /// Styles the document doesn't have are refused, as `find.change` refuses them. + fn check(&self, styles: &Styles) -> Result<()> { + if let Some(n) = self.char_style.as_ref().filter(|n| styles.char_style(n).is_none()) { + return Err(bad("find", format!("no character style `{n}`"))); + } + if let Some(n) = self.para_style.as_ref().filter(|n| styles.para(n).is_none()) { + return Err(bad("find", format!("no paragraph style `{n}`"))); + } + Ok(()) + } + + /// The text in `r` of `story` that has the format, relative to `r.start`: the longest + /// stretches, each paragraph's apart (a paragraph's `\n` isn't in one). + fn spans(&self, styles: &Styles, story: &Story, r: &Range) -> Vec> { + let mut out: Vec> = Vec::new(); + // Paragraphs and runs both go in text order: the runs before a paragraph are passed once. + let runs: Vec<_> = story.runs().collect(); + let mut first = 0; + for (pi, pr) in story.para_ranges().into_iter().enumerate() { + let (a, b) = (pr.start.max(r.start), pr.end.min(r.end)); + let Some(pf) = story.paras.get(pi) else { continue }; + if a >= b || self.para_style.as_ref().is_some_and(|n| *n != pf.style) { + continue; + } + while runs.get(first).is_some_and(|(run, _)| run.end <= a) { + first += 1; + } + let base = (!self.chars.is_empty()).then(|| styles.resolve_para(pf).1); + for (run, cf) in runs[first..].iter().take_while(|(run, _)| run.start < b) { + let (x, y) = (run.start.max(a), run.end.min(b)); + if x >= y || self.char_style.as_ref().is_some_and(|n| *n != cf.style) { + continue; + } + if let Some(base) = &base { + let cp = serde_json::to_value(styles.resolve_char(base, cf)).unwrap_or_default(); + if !self.chars.iter().all(|(k, v)| cp.get(k).is_some_and(|c| same_value(c, v))) { + continue; + } + } + match out.last_mut() { + Some(last) if last.end == x - r.start => last.end = y - r.start, + _ => out.push(x - r.start..y - r.start), + } + } + } + out + } +} + +/// Attribute values alike: numbers to within rounding (inside objects and lists too), the rest +/// exactly. +fn same_value(a: &Value, b: &Value) -> bool { + match (a, b) { + (Value::Number(_), Value::Number(_)) => match (a.as_f64(), b.as_f64()) { + (Some(x), Some(y)) => (x - y).abs() < 1e-6, + _ => a == b, + }, + (Value::Array(x), Value::Array(y)) => x.len() == y.len() && x.iter().zip(y).all(|(a, b)| same_value(a, b)), + (Value::Object(x), Value::Object(y)) => x.len() == y.len() && x.iter().all(|(k, v)| y.get(k).is_some_and(|w| same_value(v, w))), + _ => a == b, + } +} + +/// Whether match `m` lies in one of `spans`. +fn within(spans: &[Range], m: &Range) -> bool { + spans.iter().any(|s| s.start <= m.start && m.end <= s.end) +} + +/// What a search finds: the pattern's matches (with a Find Format, those whose text has it all +/// through), or, with no pattern, the stretches of text with the Find Format. +struct Search { + re: Option, + format: Option, +} + +/// The search of a Find/Change request: an empty `find` needs a Find Format. +fn search(p: &Value) -> Result { + let format = FindFormat::from_params(p)?; + if format.is_some() && str_param(p, "find") == Some("") { + return Ok(Search { re: None, format }); + } + Ok(Search { re: Some(build(p)?), format }) +} + +impl Search { + fn check(&self, styles: &Styles) -> Result<()> { + self.format.as_ref().map_or(Ok(()), |f| f.check(styles)) + } + + /// Where the Find Format holds in target `r` of story `sid` (of its table cell `cell`, if any; + /// `None`: no Find Format). + fn spans(&self, d: &Document, sid: StoryId, cell: Option, r: &Range) -> Option>> { + let f = self.format.as_ref()?; + Some(d.text_story(sid, cell).map(|story| f.spans(&d.styles, story, r)).unwrap_or_default()) + } + + /// Up to `limit` matches in `text`, target `r` of story `sid` (offsets in `text`). + fn find_all(&self, d: &Document, sid: StoryId, cell: Option, r: &Range, text: &str, limit: usize) -> Result>> { + let spans = self.spans(d, sid, cell, r); + let Some(re) = &self.re else { return Ok(spans.unwrap_or_default().into_iter().take(limit).collect()) }; + let Some(spans) = spans else { return re.find_all(text, limit).map_err(|e| bad("find", e)) }; + Ok(re.find_all(text, usize::MAX).map_err(|e| bad("find", e))?.into_iter().filter(|m| within(&spans, m)).take(limit).collect()) + } + + /// The first match in `text` (target `r` of story `sid`) at or after byte `from`. + fn find_at(&self, d: &Document, sid: StoryId, cell: Option, r: &Range, text: &str, from: usize) -> Result>> { + let spans = self.spans(d, sid, cell, r); + let Some(re) = &self.re else { + // From inside a stretch, the rest of it. + return Ok(spans.unwrap_or_default().into_iter().find(|s| s.end > from).map(|s| s.start.max(from)..s.end)); + }; + let mut at = from; + loop { + let Some(m) = re.find_at(text, at).map_err(|e| bad("find.next", e))? else { return Ok(None) }; + if spans.as_ref().is_none_or(|s| within(s, &m)) { + return Ok(Some(m)); + } + // On past it: its end, or a character on from an empty match. + at = if m.is_empty() { text.get(m.end..).and_then(|t| t.chars().next()).map_or(text.len() + 1, |c| m.end + c.len_utf8()) } else { m.end }; + if at > text.len() { + return Ok(None); + } + } + } + + /// The edit Change makes when the selection `range` (offsets in `text`, target `r` of story + /// `sid`) is what Find Next found there, so the two commands agree on what a match is. With + /// no pattern: a selection inside one stretch with the Find Format (Find Next selects the rest + /// of a stretch from inside it). With a pattern: the match it makes from the selection's start + /// must be the selection, overlapping matches Find Next can select included. + #[allow(clippy::too_many_arguments)] + fn found_edit( + &self, + d: &Document, + sid: StoryId, + cell: Option, + r: &Range, + text: &str, + range: &Range, + rep: &str, + grep: bool, + ) -> Result, String)>> { + let spans = self.spans(d, sid, cell, r); + let Some(re) = &self.re else { + let inside = !range.is_empty() && spans.unwrap_or_default().iter().any(|s| s.start <= range.start && range.end <= s.end); + return Ok(inside.then(|| (range.clone(), rep.to_string()))); + }; + let found = + if grep { re.replacement_at(text, range.start, rep) } else { re.find_at(text, range.start).map(|m| m.map(|m| (m, rep.to_string()))) }; + let found = found.map_err(|e| bad("find.change", e))?; + Ok(found.filter(|(m, _)| m == range && spans.as_ref().is_none_or(|s| within(s, m)))) + } + + /// The edits Change All makes in `text` (target `r` of story `sid`): `rep` expanded for each + /// GREP match, else `rep` itself. + #[allow(clippy::too_many_arguments)] + fn replacements( + &self, + d: &Document, + sid: StoryId, + cell: Option, + r: &Range, + text: &str, + rep: &str, + grep: bool, + first_only: bool, + ) -> Result, String)>> { + let limit = if first_only { 1 } else { usize::MAX }; + match (&self.re, self.spans(d, sid, cell, r)) { + (Some(re), spans) if grep => re + .replacements(text, rep, first_only, MAX_CHANGE_BYTES, |m| spans.as_ref().is_none_or(|s| within(s, m))) + .map_err(|e| bad("find.change", e)), + _ => { + let found = self.find_all(d, sid, cell, r, text, limit)?; + // Every match gets its own copy of the change: bounded before any is made. + if found.len().saturating_mul(rep.len()) > MAX_CHANGE_BYTES { + return Err(bad( + "find.change", + format!("changing {} matches to {} bytes each would put more than {MAX_CHANGE_BYTES} bytes in", found.len(), rep.len()), + )); + } + Ok(found.into_iter().map(|m| (m, rep.to_string())).collect()) + } + } + } +} + +/// The most text one Change All may put into a story: the matches times the change's length. +const MAX_CHANGE_BYTES: usize = 64 << 20; + #[derive(Clone, Debug, PartialEq, Eq)] enum Domain { Document, @@ -140,6 +369,7 @@ struct Matcher { grep: bool, case_sensitive: bool, whole_word: bool, + format: Option, } impl Matcher { @@ -149,6 +379,7 @@ impl Matcher { grep: bool_or(p, "grep", false), case_sensitive: bool_or(p, "caseSensitive", false), whole_word: bool_or(p, "wholeWord", false), + format: FindFormat::from_params(p).ok().flatten(), } } } @@ -183,6 +414,29 @@ impl FindContext { self.selection = st.selection.clone(); } + /// After Change put `new_len` bytes in place of `old` in story `sid`: the domain keeps the + /// changed text and the search goes on after it. + fn after_change(&mut self, st: &DocState, sid: StoryId, cell: Option, old: &Range, new_len: usize) { + let moved = |x: usize| if x >= old.end { x - old.len() + new_len } else { x }; + for (tid, tcell, r) in &mut self.targets { + if *tid == sid && *tcell == cell { + *r = moved(r.start)..moved(r.end); + } + } + self.offset = old.start + new_len; + self.last_match_end = Some(self.offset); + let at = self.offset; + if let Some(i) = self + .order + .iter() + .position(|i| self.targets.get(*i).is_some_and(|(tid, tcell, r)| *tid == sid && *tcell == cell && r.start <= at && at <= r.end)) + { + self.target = i; + } + self.document = Arc::downgrade(&st.doc); + self.acknowledge(st); + } + fn restart(&mut self, st: &DocState) -> Result<()> { self.target = 0; self.last_match_end = None; @@ -299,13 +553,14 @@ fn scope(s: &Session, p: &Value) -> Result { const MAX_MATCHES: usize = 10_000; fn find(s: &mut Session, p: &Value) -> Result { - let re = build(p)?; + let re = search(p)?; + re.check(&s.doc()?.doc.styles)?; let context = scope(s, p)?; let st = s.doc()?; let mut out = Vec::new(); for (sid, cell, r) in &context.targets { let text = target_text(&st.doc, *sid, *cell, r)?; - for m in re.find_all(text, MAX_MATCHES.saturating_sub(out.len())).map_err(|e| bad("find", e))? { + for m in re.find_all(&st.doc, *sid, *cell, r, text, MAX_MATCHES.saturating_sub(out.len()))? { let mut hit = json!({"story": sid.0, "start": r.start + m.start, "end": r.start + m.end, "text": text.get(m)}); if let Some(c) = cell { hit["cell"] = json!({"table": c.table, "row": c.row, "col": c.col}); @@ -349,51 +604,149 @@ fn char_overrides(attrs: Option<&Value>) -> Result { } fn change(s: &mut Session, p: &Value) -> Result { - let re = build(p)?; - let grep = bool_or(p, "grep", false); - let rep = replacement(p); + let re = search(p)?; + re.check(&s.doc()?.doc.styles)?; + // With no pattern (a Find Format alone), the change is literal text. + let grep = bool_or(p, "grep", false) && re.re.is_some(); + let rep = if re.re.is_some() { replacement(p) } else { metachars(str_param(p, "change").unwrap_or("")) }; let first_only = bool_or(p, "first", false); let attrs = p.get("attrs").cloned(); let over = char_overrides(attrs.as_ref())?; + // A null attribute clears that override on the found text. + let cleared: Vec = attrs + .as_ref() + .and_then(Value::as_object) + .map(|o| o.iter().filter(|(_, v)| v.is_null()).map(|(k, _)| k.clone()).collect()) + .unwrap_or_default(); super::text::validate_char_fill(&s.doc()?.doc, &over, "find.change")?; - let targets = scope(s, p)?.targets; - s.edit(|d, sel| { + let char_style = str_param(p, "charStyle").map(str::to_string); + let para_style = str_param(p, "paraStyle").map(str::to_string); + let styles = &s.doc()?.doc.styles; + if let Some(n) = char_style.as_ref().filter(|n| styles.char_style(n).is_none()) { + return Err(bad("find.change", format!("no character style `{n}`"))); + } + if let Some(n) = para_style.as_ref().filter(|n| styles.para(n).is_none()) { + return Err(bad("find.change", format!("no paragraph style `{n}`"))); + } + // InDesign: with a Change Format and nothing in Change to, the found text is only formatted. + let format_only = + str_param(p, "change").unwrap_or("").is_empty() && (char_style.is_some() || para_style.is_some() || !over.is_empty() || !cleared.is_empty()); + let context = scope(s, p)?; + let targets = context.targets.clone(); + // Change: only the text Find Next found, the selection, while it is still a match (as Find + // Next defines one), with its replacement. + let (found, found_out) = if bool_or(p, "found", false) { + let st = s.doc()?; + let selected = st.selection.text.filter(|t| st.selection.cells.is_none() && !t.is_caret()).map(|t| (t.story, t.cell, t.range())); + let hit = selected.and_then(|(sid, cell, range)| { + targets.iter().find_map(|(tid, tcell, r)| { + if *tid != sid || *tcell != cell || range.start < r.start || r.end < range.end { + return None; + } + let text = target_text(&st.doc, *tid, cell, r).ok()?; + let local = range.start - r.start..range.end - r.start; + let (m, out) = re.found_edit(&st.doc, *tid, cell, r, text, &local, &rep, grep).ok()??; + Some(((sid, cell, r.start + m.start..r.start + m.end), out)) + }) + }); + match hit { + Some((hit, out)) => (Some(hit), Some(out)), + None => return Ok(json!({"count": 0})), + } + } else { + (None, None) + }; + let (count, changed) = s.edit(|d, sel| { + let styles = d.styles.clone(); let mut count = 0usize; + let mut changed = None; for (sid, cell, r) in targets { + if found.as_ref().is_some_and(|(at, in_cell, _)| *at != sid || *in_cell != cell) { + continue; + } let Some(story) = d.text_story(sid, cell) else { continue }; // Collect matches first (positions refer to the original text), apply back to front. let text = story.text.get(r.clone()).ok_or_else(|| bad("find", "invalid selection bounds or UTF-8 boundary"))?; - let edits: Vec<(std::ops::Range, String)> = if grep { - re.replacements(text, &rep, first_only) - } else { - re.find_all(text, if first_only { 1 } else { usize::MAX }).map(|ms| ms.into_iter().map(|m| (m, rep.clone())).collect()) - } - .map_err(|e| bad("find.change", e))? - .into_iter() - .map(|(m, out)| (r.start + m.start..r.start + m.end, out)) - .collect(); + let mut edits: Vec<(std::ops::Range, String)> = match (&found, &found_out) { + // Change: the found text alone, in the target it lies in. + (Some((_, _, range)), Some(out)) => { + if r.start <= range.start && range.end <= r.end { + vec![(range.clone(), out.clone())] + } else { + Vec::new() + } + } + _ => re + .replacements(d, sid, cell, &r, text, &rep, grep, first_only)? + .into_iter() + .map(|(m, out)| (r.start + m.start..r.start + m.end, out)) + .collect(), + }; + edits.sort_by_key(|(range, _)| range.start); let Some(st) = d.text_story_mut(sid, cell) else { continue }; for (range, new) in edits.iter().rev() { - st.replace(range.clone(), new); - if !over.is_empty() && !new.is_empty() { - st.format_chars(range.start..range.start + new.len(), |f| f.over.merge(&over)); + let changed = if format_only { + range.clone() + } else { + st.replace(range.clone(), new); + range.start..range.start + new.len() + }; + // A paragraph style goes to the match's paragraphs, an empty match's (`^`) too; + // character formatting needs characters. + if let Some(n) = ¶_style { + super::style::apply_para_style(st, &styles, n, &changed, false); + } + if !changed.is_empty() { + if let Some(n) = &char_style { + super::style::apply_char_style(st, &styles, n, &changed); + } + if !over.is_empty() || !cleared.is_empty() { + st.format_chars(changed, |f| { + f.over.merge(&over); + for k in &cleared { + let _ = f.over.set_json(k, &Value::Null); + } + }); + } } count += 1; } if let Some(t) = sel.text.as_mut().filter(|t| t.story == sid && t.cell == cell) { repair_selection(t, st); } + if cell.is_none() && !format_only { + for (range, new) in edits.iter().rev() { + d.adjust_text_ranges(sid, range.clone(), new.len()); + } + } + // Change leaves the changed text selected. + if let Some((_, _, range)) = &found + && let Some((_, new)) = edits.first() + && let Some(t) = sel.text.as_mut() + { + let len = if format_only { range.len() } else { new.len() }; + (t.anchor, t.focus) = (range.start, range.start + len); + changed = Some(len); + } // `first` is the first match of the whole search, not of each story. if first_only && count > 0 { break; } } - Ok(json!({"count": count})) - }) + Ok((count, changed)) + })?; + // Change: Find Next goes on after the changed text, in the search's domain. + if let (Some((sid, cell, old)), Some(len)) = (&found, changed) { + let mut context = context; + context.after_change(s.doc()?, *sid, *cell, old, len); + s.find_context = Some(context); + } + Ok(json!({"count": count})) } fn find_next(s: &mut Session, p: &Value) -> Result { - let re = build(p)?; + let re = search(p)?; + re.check(&s.doc()?.doc.styles)?; let mut context = scope(s, p)?; let st = s.doc()?; let mut hit = None; @@ -403,7 +756,7 @@ fn find_next(s: &mut Session, p: &Value) -> Result { if text.get(from..).is_none() { return Err(bad("find", "invalid UTF-8 search cursor")); } - if let Some(m) = re.find_at(text, from).map_err(|e| bad("find.next", e))? { + if let Some(m) = re.find_at(&st.doc, sid, cell, &r, text, from)? { let (a, b) = (r.start + m.start, r.start + m.end); // Match find_iter/captures_iter: suppress an empty match adjacent to the // previous match's end, but keep adjacent nonempty matches. @@ -489,6 +842,34 @@ mod object_find_tests { use crate::Session; + /// A GREP match that is empty (`^`, the start of each paragraph) gets the paragraph style: + /// only character formatting needs characters. + #[test] + fn change_format_styles_paragraphs_of_empty_matches() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let r = s + .execute( + "frame.create", + &json!({"rect": [36, 36, 300, 300], "content": "text", "text": "One +Two +Three"}), + ) + .unwrap(); + let sid = designcraft_doc::StoryId(r["story"].as_u64().unwrap()); + s.execute("style.paragraph.create", &json!({"name": "Method"})).unwrap(); + let r = s.execute("find.change", &json!({"find": "^", "change": "", "grep": true, "paraStyle": "Method"})).unwrap(); + assert_eq!(r["count"], 3); + let story = s.doc().unwrap().doc.story(sid).unwrap().clone(); + assert!(story.paras.iter().all(|p| p.style == "Method"), "{:?}", story.paras.iter().map(|p| &p.style).collect::>()); + assert_eq!( + story.text, + "One +Two +Three" + ); + } + #[test] fn find_and_change_objects_by_attributes() { let mut s = Session::new(); diff --git a/crates/engine/src/cmd/find/tests.rs b/crates/engine/src/cmd/find/tests.rs index 5914c2e51..edea872ad 100644 --- a/crates/engine/src/cmd/find/tests.rs +++ b/crates/engine/src/cmd/find/tests.rs @@ -621,6 +621,27 @@ fn document_scope_searches_and_changes_table_cells() { assert_eq!(s.execute("find.find", &json!({"find": "13.00", "scope": "document"})).unwrap().as_array().unwrap().len(), 2); } +/// Change (`found`) on text Find Next found in a table cell changes it there, leaves the +/// same text in the story alone, and Find Next goes on after it. +#[test] +fn change_changes_the_text_find_next_found_in_a_cell() { + let (mut s, sid) = scope_session("red here"); + scope_select(&mut s, sid, 0, 0); + let table = s.execute("table.insert", &json!({"rows": 1, "cols": 2})).unwrap()["table"].as_u64().unwrap(); + s.execute("table.setCell", &json!({"row": 0, "col": 1, "text": "red"})).unwrap(); + let p = json!({"find": "red", "change": "blue", "scope": "document"}); + let hit = s.execute("find.next", &p).unwrap(); + assert_eq!(hit["cell"], json!({"table": table, "row": 0, "col": 1}), "{hit}"); + let mut change = p.clone(); + change["found"] = json!(true); + assert_eq!(s.execute("find.change", &change).unwrap()["count"], 1); + let t = s.execute("table.get", &json!({"table": table})).unwrap(); + assert_eq!(t["cells"][1]["text"], "blue"); + assert!(s.doc().unwrap().doc.story(sid).unwrap().text.contains("red here"), "the story's red stays"); + let next = s.execute("find.next", &p).unwrap(); + assert!(next.get("cell").is_none() && next.get("start").is_some(), "on to the story: {next}"); +} + fn child_scope_session(note: bool, child: &str) -> (Session, designcraft_doc::StoryId, designcraft_doc::TextSel) { let (mut s, sid) = scope_session("red"); scope_select(&mut s, sid, 3, 3); @@ -747,3 +768,212 @@ fn find_scope_revert_releases_context_with_same_document_uid() { assert_eq!(s.doc().unwrap().doc.story(sid).unwrap().text, "red red | red"); assert!(s.execute("find.find", &p).is_err(), "revert's empty selection cannot inherit a previous range"); } + +#[test] +fn change_format_styles_the_found_text_and_keeps_it() { + // The course's chapter 22: every lowercase "eggs" gets the character style "eggs", with + // Change to empty, so the words stay. + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let text = "Poached Eggs\nBreak eggs; cook until eggs are set."; + let r = s.execute("frame.create", &json!({"rect": [36, 36, 300, 300], "content": "text", "text": text})).unwrap(); + let sid = designcraft_doc::StoryId(r["story"].as_u64().unwrap()); + s.execute("style.character.create", &json!({"name": "eggs", "chars": {"fontStyle": "Bold", "fill": "C=15 M=100 Y=100 K=0"}})).unwrap(); + s.execute("style.paragraph.create", &json!({"name": "Method"})).unwrap(); + let undo = s.doc().unwrap().history.undo.len(); + let r = s.execute("find.change", &json!({"find": "eggs", "change": "", "caseSensitive": true, "charStyle": "eggs"})).unwrap(); + assert_eq!(r["count"], 2); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "one undo step"); + let style_at = |s: &Session, at: usize| s.doc().unwrap().doc.story(sid).unwrap().format_after(at).style.clone(); + let story = s.doc().unwrap().doc.story(sid).unwrap().clone(); + assert_eq!(story.text, text, "the words stay"); + for at in [19, 36] { + assert_eq!(&story.text[at..at + 4], "eggs"); + assert_eq!(style_at(&s, at), "eggs"); + } + assert_eq!(style_at(&s, 8), designcraft_doc::NO_CHAR_STYLE, "case sensitive: not \"Eggs\""); + assert_eq!(style_at(&s, 25), designcraft_doc::NO_CHAR_STYLE, "only the found text"); + // A paragraph style goes to the found text's paragraphs, with attributes over the text. + s.execute("find.change", &json!({"find": "cook", "change": "", "paraStyle": "Method", "attrs": {"underline": true}})).unwrap(); + let story = s.doc().unwrap().doc.story(sid).unwrap().clone(); + assert_eq!((story.paras[0].style.as_str(), story.paras[1].style.as_str()), (designcraft_doc::BASIC_PARAGRAPH, "Method")); + assert_eq!(story.format_after(25).over.underline, Some(true)); + assert_eq!(story.format_after(19).style, "eggs", "the other text keeps its character style"); + // Change to and a Change Format: the new text is formatted. + s.execute("find.change", &json!({"find": "set", "change": "firm", "charStyle": "eggs"})).unwrap(); + assert_eq!(style_at(&s, s.doc().unwrap().doc.story(sid).unwrap().text.find("firm").unwrap()), "eggs"); + // No such style: refused, nothing changed. + let before = s.doc().unwrap().doc.clone(); + assert!(s.execute("find.change", &json!({"find": "eggs", "change": "", "charStyle": "Nope"})).is_err()); + assert!(s.execute("find.change", &json!({"find": "eggs", "change": "", "paraStyle": "Nope"})).is_err()); + assert_eq!(s.doc().unwrap().doc, before); + // A null attribute is a Change Format too: the found text stays and loses that override. + let before = s.doc().unwrap().doc.story(sid).unwrap().clone(); + s.execute("find.change", &json!({"find": "cook", "change": "", "attrs": {"underline": null}})).unwrap(); + let story = s.doc().unwrap().doc.story(sid).unwrap().clone(); + assert_eq!(story.text, before.text, "the words stay"); + assert_eq!(story.format_after(25).over.underline, None); + // With no Change Format, an empty Change to still deletes the found text. + s.execute("find.change", &json!({"find": "Break ", "change": ""})).unwrap(); + assert!(!s.doc().unwrap().doc.story(sid).unwrap().text.contains("Break")); +} + +#[test] +fn a_find_format_finds_only_text_with_it() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let r = + s.execute("frame.create", &json!({"rect": [36, 36, 300, 300], "content": "text", "text": "Break eggs; cook eggs.\nEggs and eggs"})).unwrap(); + let sid = r["story"].as_u64().unwrap(); + s.execute("style.character.create", &json!({"name": "eggs", "chars": {"fontStyle": "Bold"}})).unwrap(); + s.execute("style.paragraph.create", &json!({"name": "Method"})).unwrap(); + for (a, b) in [(6, 10), (12, 16)] { + s.execute("text.select", &json!({"story": sid, "anchor": a, "focus": b})).unwrap(); + s.execute("style.character.apply", &json!({"name": "eggs"})).unwrap(); + } + s.execute("text.select", &json!({"story": sid, "anchor": 25, "focus": 25})).unwrap(); + s.execute("style.paragraph.apply", &json!({"name": "Method"})).unwrap(); + let found = |s: &mut Session, p: serde_json::Value| -> Vec<(u64, u64)> { + let m = s.execute("find.find", &p).unwrap(); + m.as_array().unwrap().iter().map(|m| (m["start"].as_u64().unwrap(), m["end"].as_u64().unwrap())).collect() + }; + // "eggs" where it has the character style: the first only. + assert_eq!(found(&mut s, json!({"find": "eggs", "findFormat": {"charStyle": "eggs"}})), [(6, 10)]); + // Nothing in Find what: each stretch of text in the style. + assert_eq!(found(&mut s, json!({"find": "", "findFormat": {"charStyle": "eggs"}})), [(6, 10), (12, 16)]); + // A paragraph style, and resolved attributes. + assert_eq!(found(&mut s, json!({"find": "eggs", "findFormat": {"paraStyle": "Method"}})), [(23, 27), (32, 36)]); + assert_eq!(found(&mut s, json!({"find": "", "findFormat": {"chars": {"fontStyle": "Bold"}}})), [(6, 10), (12, 16)]); + assert_eq!(found(&mut s, json!({"find": "", "findFormat": {"chars": {"size": 12}}})), [(0, 22), (23, 36)], "each paragraph apart"); + // Find Next walks the stretches. + s.execute("text.select", &json!({"story": sid, "anchor": 0, "focus": 0})).unwrap(); + let next = json!({"find": "", "findFormat": {"charStyle": "eggs"}}); + assert_eq!(s.execute("find.next", &next).unwrap()["start"], 6); + assert_eq!(s.execute("find.next", &next).unwrap()["start"], 12); + // Equivalent spellings the attributes accept find the same text: a snake_case key, and a + // nested number written as an integer (14 pt leading on the second paragraph). + s.execute("text.select", &json!({"story": sid, "anchor": 23, "focus": 36})).unwrap(); + s.execute("type.char", &json!({"leading": {"kind": "points", "value": 14.0}})).unwrap(); + for (a, b) in [ + (json!({"fontStyle": "Bold"}), json!({"font_style": "Bold"})), + (json!({"leading": {"kind": "points", "value": 14.0}}), json!({"leading": {"kind": "points", "value": 14}})), + ] { + let (a, b) = (json!({"find": "", "findFormat": {"chars": a}}), json!({"find": "", "findFormat": {"chars": b}})); + let all = found(&mut s, a.clone()); + assert!(!all.is_empty(), "{a}"); + assert_eq!(found(&mut s, b.clone()), all, "{b}"); + for p in [&a, &b] { + s.execute("text.select", &json!({"story": sid, "anchor": 0, "focus": 0})).unwrap(); + assert_eq!(s.execute("find.next", p).unwrap()["start"].as_u64(), Some(all[0].0), "{p}"); + } + } + // A null attribute asks for nothing. + assert_eq!(found(&mut s, json!({"find": "eggs", "findFormat": {"charStyle": "eggs", "chars": {"size": null}}})), [(6, 10)]); + // With a Change Format: the text in the style goes back to [None], underlined. + let r = s + .execute( + "find.change", + &json!({"find": "", "change": "", "findFormat": {"charStyle": "eggs", "chars": {"font_style": "Bold"}}, "charStyle": "[None]", "attrs": {"underline": true}}), + ) + .unwrap(); + assert_eq!(r["count"], 2, "a snake_case attribute changes the same text"); + assert!(found(&mut s, json!({"find": "", "findFormat": {"charStyle": "eggs"}})).is_empty()); + assert_eq!(found(&mut s, json!({"find": "", "findFormat": {"chars": {"underline": true}}})), [(6, 10), (12, 16)]); + // Unknown styles and attributes are refused; an empty search needs a Find Format. + assert!(s.execute("find.find", &json!({"find": "", "findFormat": {"charStyle": "Nope"}})).is_err()); + assert!(s.execute("find.next", &json!({"find": "eggs", "findFormat": {"paraStyle": "Nope"}})).is_err()); + assert!(s.execute("find.find", &json!({"find": "eggs", "findFormat": {"chars": {"bogus": 1}}})).is_err()); + // Malformed fields are refused, not searched without. + for f in [json!({"chars": [1]}), json!({"chars": 12}), json!({"charStyle": 3}), json!({"paraStyle": ["Body"]})] { + assert!(s.execute("find.find", &json!({"find": "eggs", "findFormat": f})).is_err(), "{f}"); + } + assert!(s.execute("find.find", &json!({"find": ""})).is_err()); +} + +/// Change and Change/Find: only the text Find Next found changes; it stays selected and the +/// search goes on after it in its domain (here the original selection). A selection that +/// isn't a match changes nothing and makes no undo step. +#[test] +fn change_changes_the_found_text_and_the_search_goes_on() { + let (mut s, sid) = scope_session("red red | red"); + scope_select(&mut s, sid, 0, 7); + let p = json!({"find": "red", "change": "blue", "scope": "selection"}); + let mut change = p.clone(); + change["found"] = json!(true); + scope_hit(&mut s, &p, sid, 0, 3); + assert_eq!(s.execute("find.change", &change).unwrap()["count"], 1); + let text = |s: &Session| s.doc().unwrap().doc.story(sid).unwrap().text.clone(); + assert_eq!(text(&s), "blue red | red"); + assert_eq!(s.doc().unwrap().selection.text.unwrap().range(), 0..4, "the changed text stays selected"); + scope_hit(&mut s, &p, sid, 5, 8); + s.execute("find.change", &change).unwrap(); + assert_eq!(text(&s), "blue blue | red"); + assert_eq!(s.execute("find.next", &p).unwrap(), serde_json::Value::Null, "the last red is outside the selection searched"); + // Not a match: nothing changes, no undo step. + scope_select(&mut s, sid, 0, 4); + let history = s.doc().unwrap().history.undo.len(); + assert_eq!(s.execute("find.change", &json!({"find": "red", "change": "blue", "found": true})).unwrap()["count"], 0); + assert_eq!(s.doc().unwrap().history.undo.len(), history); + // A Change Format with nothing in Change to formats the found text only. + scope_select(&mut s, sid, 0, 0); + let fmt = json!({"find": "red", "change": "", "attrs": {"underline": true}}); + let hit = s.execute("find.next", &fmt).unwrap(); + assert_eq!(hit["start"], 12); + let mut found = fmt.clone(); + found["found"] = json!(true); + s.execute("find.change", &found).unwrap(); + assert_eq!(text(&s), "blue blue | red"); + assert_eq!(s.doc().unwrap().doc.story(sid).unwrap().format_after(12).over.underline, Some(true)); + assert_eq!(s.doc().unwrap().selection.text.unwrap().range(), 12..15); +} + +/// Change accepts what Find Next selected even when Change All wouldn't match there: the +/// rest of a Find Format stretch from a caret inside it, and an overlapping match. +#[test] +fn change_takes_any_selection_find_next_made() { + // A caret inside a bold stretch: Find Next with only a Find Format selects the rest of it. + let (mut s, sid) = scope_session("plain bold text"); + s.execute("style.character.create", &json!({"name": "Strong", "chars": {"fontStyle": "Bold"}})).unwrap(); + scope_select(&mut s, sid, 6, 10); + s.execute("style.character.apply", &json!({"name": "Strong"})).unwrap(); + scope_select(&mut s, sid, 8, 8); + let p = json!({"find": "", "change": "", "findFormat": {"charStyle": "Strong"}, "attrs": {"underline": true}, "scope": "story"}); + let hit = s.execute("find.next", &p).unwrap(); + assert_eq!((hit["start"].as_u64(), hit["end"].as_u64()), (Some(8), Some(10))); + let mut change = p.clone(); + change["found"] = json!(true); + assert_eq!(s.execute("find.change", &change).unwrap()["count"], 1); + let st = s.doc().unwrap().doc.story(sid).unwrap().clone(); + assert_eq!((st.format_after(7).over.underline, st.format_after(8).over.underline), (None, Some(true)), "only the selected rest"); + // "aa" in "aaa" from the second a: Find Next selects 1..3, which Change All never finds. + for grep in [false, true] { + let (mut s, sid) = scope_session("aaa"); + scope_select(&mut s, sid, 1, 1); + let (find, change) = if grep { ("(a)a", "<$1>") } else { ("aa", "b") }; + let p = json!({"find": find, "change": change, "grep": grep, "scope": "story"}); + let hit = s.execute("find.next", &p).unwrap(); + assert_eq!((hit["start"].as_u64(), hit["end"].as_u64()), (Some(1), Some(3))); + let mut found = p.clone(); + found["found"] = json!(true); + assert_eq!(s.execute("find.change", &found).unwrap()["count"], 1, "grep: {grep}"); + assert_eq!(s.doc().unwrap().doc.story(sid).unwrap().text, if grep { "a" } else { "ab" }); + } +} + +/// Change All with a long change and many matches is refused before any copy of the change is +/// made, not after the memory for all of them has gone. +#[test] +fn change_all_is_bounded_by_what_it_would_put_in() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let text = "x ".repeat(2048); + s.execute("frame.create", &json!({"rect": [36, 36, 300, 300], "content": "text", "text": text})).unwrap(); + let huge = "y".repeat(40_000); + let e = s.execute("find.change", &json!({"find": "x", "change": huge})).unwrap_err().to_string(); + assert!(e.contains("would put more than"), "{e}"); + // GREP replacements are held to the same total while they are made. + let e = s.execute("find.change", &json!({"find": "x", "change": huge, "grep": true})).unwrap_err().to_string(); + assert!(e.contains("would put more than"), "{e}"); + let r = s.execute("find.change", &json!({"find": "x", "change": "yy"})).unwrap(); + assert_eq!(r["count"], 2048); +} diff --git a/crates/engine/src/cmd/fonts.rs b/crates/engine/src/cmd/fonts.rs index ee80eb914..8d78e4b4a 100644 --- a/crates/engine/src/cmd/fonts.rs +++ b/crates/engine/src/cmd/fonts.rs @@ -14,7 +14,7 @@ use crate::{Result, Session}; pub fn specs() -> Vec { vec![ - cmd!(query "font.list", "Fonts in Document", [], None, "{} → [{family, style, characters, missing, styleMissing, source: bundled|installed|document|added (null when missing), matchStatus: exact|styleSubstitute|missing, resolvedFamily, resolvedStyle, replacementFamily, replacementStyle}] (missing first)", has_doc, |s, _| { + cmd!(query "font.list", "Fonts in Document", [], None, "{} → [{family, style, characters, missing, styleMissing, source: bundled|installed|document|added (null when missing), matchStatus: exact|styleSubstitute|missing, resolvedFamily, resolvedStyle, replacementFamily, replacementStyle, fsType, restrictedLicence, bitmapOnly, noSubsetting, editable, previewPrint (the OS/2 fsType embedding bits of the face that sets the text and what they mean; null when missing or the face has no OS/2 table)}] (missing first)", has_doc, |s, _| { Ok(Value::Array(list(&s.doc()?.doc))) }), cmd!( @@ -75,27 +75,49 @@ pub(super) struct UsedFont { pub resolved_style: String, pub replacement_family: String, pub replacement_style: String, + /// The OS/2 `fsType` of the face that sets the text (`resolved_*`); None when missing or the + /// face has no OS/2 table (as are the bits below). + pub fs_type: Option, + /// Restricted License embedding (bit 1 without bits 2–3). + pub restricted_licence: Option, + /// Bitmap embedding only (bit 9). + pub bitmap_only: Option, + /// No subsetting (bit 8): the font may only be embedded whole. + pub no_subsetting: Option, + /// Editable embedding (bit 3). + pub editable: Option, + /// Preview & Print embedding (bit 2). + pub preview_print: Option, } fn list(d: &Document) -> Vec { used_fonts(d).into_iter().map(|font| json!(font)).collect() } -type FontTally = BTreeMap<(String, String), (usize, std::collections::BTreeSet)>; +pub(super) type FontTally = BTreeMap<(String, String), (usize, std::collections::BTreeSet)>; /// Count the characters of every run of one story against the font each resolves to. fn tally_story(d: &Document, st: &Story, used: &mut FontTally) { - let ranges = st.para_ranges(); - for (pi, r) in ranges.iter().enumerate() { - let (_, base) = d.styles.resolve_para(&st.paras[pi]); + tally_range(d, st, 0..st.text.len(), used); +} + +/// Count the characters in the byte range `within` of a story against the font each resolves to; +/// a composite font counts each character under the font of its entry. An empty paragraph counts +/// the font of its mark, which still sets its line. +pub(super) fn tally_range(d: &Document, st: &Story, within: std::ops::Range, used: &mut FontTally) { + let to_end = within.end >= st.text.len(); + for (pi, r) in st.para_ranges().iter().enumerate() { + let Some(para) = st.paras.get(pi) else { continue }; + let (_, base) = d.styles.resolve_para(para); + let mark = r.is_empty() && within.start <= r.start && (r.start < within.end || to_end); for (rr, fmt) in st.runs() { - let n = st.text[rr.start.max(r.start)..rr.end.min(r.end).max(rr.start.max(r.start))].chars().count(); - if n == 0 && !(r.is_empty() && rr.contains(&r.start)) { + let start = rr.start.max(r.start).max(within.start); + let text = st.text.get(start..rr.end.min(r.end).min(within.end).max(start)).unwrap_or(""); + if text.is_empty() && !(mark && rr.contains(&r.start)) { continue; } let p = d.styles.resolve_char(&base, fmt); if let Some(f) = d.styles.composite_font(&p.font_family) { - let text = st.text.get(rr.start.max(r.start)..rr.end.min(r.end).max(rr.start.max(r.start))).unwrap_or(""); for c in text.chars() { if let Some(e) = f.entry(c) { let entry = used.entry((e.family.clone(), e.style.clone())).or_default(); @@ -105,17 +127,23 @@ fn tally_story(d: &Document, st: &Story, used: &mut FontTally) { } } else { let entry = used.entry((p.font_family, p.font_style)).or_default(); - entry.0 += n; - entry.1.extend(st.text.get(rr.start.max(r.start)..rr.end.min(r.end).max(rr.start.max(r.start))).unwrap_or("").chars()); + entry.0 += text.chars().count(); + entry.1.extend(text.chars()); } } } } pub(super) fn used_fonts(d: &Document) -> Vec { - let db = designcraft_fonts::FontDb::global().scoped(d.font_scope); let mut used = FontTally::new(); for_each_story(d, &mut |st| tally_story(d, st, &mut used)); + describe_fonts(d, used) +} + +/// The tallied fonts as this document's fonts resolve them: missing, a substitute style, or the +/// face itself (missing ones first). +pub(super) fn describe_fonts(d: &Document, used: FontTally) -> Vec { + let db = designcraft_fonts::FontDb::global().scoped(d.font_scope); let mut out: Vec = used .into_iter() .map(|((family, style), (n, characters))| { @@ -124,6 +152,8 @@ pub(super) fn used_fonts(d: &Document) -> Vec { let resolved = db.face(&family, &style); let characters: Vec = characters.into_iter().filter(|c| !('\u{E000}'..='\u{E1FF}').contains(c)).collect(); let replacement = db.replacement_face(&family, &style, &characters); + let fs_type = (!missing).then(|| resolved.fs_type()).flatten(); + let bit = |mask: u16| fs_type.map(|t| t & mask != 0); let source = (!missing).then(|| match db.face(&family, &style).source { FontSource::Bundled => "bundled", FontSource::Installed(_) => "installed", @@ -148,6 +178,12 @@ pub(super) fn used_fonts(d: &Document) -> Vec { resolved_style: resolved.style.clone(), replacement_family: replacement.family.clone(), replacement_style: replacement.style.clone(), + fs_type, + restricted_licence: fs_type.map(|_| resolved.restricted_licence()), + bitmap_only: bit(0x0200), + no_subsetting: bit(0x0100), + editable: bit(0x0008), + preview_print: bit(0x0004), } }) .collect(); @@ -297,6 +333,55 @@ mod tests { assert_eq!(before, s.execute("font.list", &json!({})).unwrap()); } + /// `font.list` reports each face's OS/2 fsType and what its bits allow, so a caller can + /// refuse a face whose licence doesn't allow the export it is about to make. + #[test] + fn font_list_reports_the_embedding_licence_bits() { + use designcraft_fonts::testing::{font_with, with_fs_type, with_table_len}; + const FAMILY: &str = "DocFont List FsType"; + const FS_TYPES: [u16; 3] = [0x0002, 0x0108, 0x0204]; + for fs_type in FS_TYPES { + designcraft_fonts::FontDb::global() + .add_font(with_fs_type(font_with(&format!("{FAMILY} {fs_type:04x}"), &['W']).unwrap(), fs_type).unwrap()); + } + // An OS/2 table cut to nothing can't be read: as if the font had none. + designcraft_fonts::FontDb::global().add_font(with_table_len(font_with(&format!("{FAMILY} no OS/2"), &['W']).unwrap(), b"OS/2", 0).unwrap()); + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + // "W W W W Plain Gone": each W in one of the fonts above, Plain in the default (bundled) + // font, Gone in a family that isn't available. + let r = s.execute("frame.create", &json!({"rect": [72, 72, 400, 300], "content": "text", "text": "W W W W Plain Gone"})).unwrap(); + let sid = s.doc().unwrap().doc.item(designcraft_doc::ItemId(r["id"].as_u64().unwrap())).unwrap().text_frame().unwrap().story; + let set = |s: &mut Session, at: usize, end: usize, family: &str| { + s.execute("text.select", &json!({"story": sid.0, "anchor": at, "focus": end})).unwrap(); + s.execute("type.char", &json!({"fontFamily": family, "fontStyle": "Regular"})).unwrap(); + }; + for (i, fs_type) in FS_TYPES.into_iter().enumerate() { + set(&mut s, i * 2, i * 2 + 1, &format!("{FAMILY} {fs_type:04x}")); + } + set(&mut s, 6, 7, &format!("{FAMILY} no OS/2")); + set(&mut s, 14, 18, "Nonexistent Sans"); + let l = s.execute("font.list", &json!({})).unwrap(); + let rows = l.as_array().unwrap(); + let entry = |family: &str| rows.iter().find(|f| f["family"] == family).unwrap_or_else(|| panic!("{family}: {l}")); + let bits = |e: &Value| ["fsType", "restrictedLicence", "bitmapOnly", "noSubsetting", "editable", "previewPrint"].map(|k| e[k].clone()); + let (t, f) = (json!(true), json!(false)); + assert_eq!(entry(&format!("{FAMILY} 0002"))["source"], "added", "{l}"); + assert_eq!(bits(entry(&format!("{FAMILY} 0002"))), [json!(0x0002), t.clone(), f.clone(), f.clone(), f.clone(), f.clone()], "{l}"); + assert_eq!(bits(entry(&format!("{FAMILY} 0108"))), [json!(0x0108), f.clone(), f.clone(), t.clone(), t.clone(), f.clone()], "{l}"); + assert_eq!(bits(entry(&format!("{FAMILY} 0204"))), [json!(0x0204), f.clone(), t.clone(), f.clone(), f.clone(), t.clone()], "{l}"); + // The bundled fonts are OFL: installable embedding, every bit clear. + let bundled = rows.iter().find(|r| r["source"] == "bundled").unwrap_or_else(|| panic!("no bundled face: {l}")); + assert_eq!(bits(bundled), [json!(0), f.clone(), f.clone(), f.clone(), f.clone(), f], "{l}"); + // A face without an OS/2 table doesn't say what its licence allows. + assert_eq!(entry(&format!("{FAMILY} no OS/2"))["missing"], false, "{l}"); + assert_eq!(bits(entry(&format!("{FAMILY} no OS/2"))), [(); 6].map(|()| Value::Null), "{l}"); + // A missing face has no file to read. + let missing = entry("Nonexistent Sans"); + assert_eq!(missing["missing"], true, "{l}"); + assert_eq!(bits(missing), [(); 6].map(|()| Value::Null), "{l}"); + } + #[test] fn find_and_replace_font() { let mut s = Session::new(); diff --git a/crates/engine/src/cmd/guides.rs b/crates/engine/src/cmd/guides.rs index 18826fb18..24ccf1696 100644 --- a/crates/engine/src/cmd/guides.rs +++ b/crates/engine/src/cmd/guides.rs @@ -54,19 +54,25 @@ pub fn specs() -> Vec { has_doc, delete ), - cmd!("guide.deleteAll", "Delete All Guides on Spread", ["View", "Grids & Guides"], None, "{spread?}", has_doc, |s, p| { - let r = super::spread_param(p, "guide.deleteAll")?; - s.edit(|d, sel| { - let sp = d.spread_mut(r).ok_or_else(|| bad("guide.deleteAll", "no such spread"))?; - let mut n = 0; - for pg in &mut sp.pages { - n += pg.guides.len(); - pg.guides.clear(); - } - sel.guides.retain(|g| g.spread != r); - Ok(json!({"deleted": n})) - }) - }), + cmd!( + "guide.deleteAll", + "Delete All Guides on Spread", + ["View", "Grids & Guides"], + None, + "{spread?} — a locked guide, and the guides of a layer that is locked, hidden or locks its guides, stay → {deleted}", + has_doc, + |s, p| { + let r = super::spread_param(p, "guide.deleteAll")?; + s.edit(|d, sel| { + let keep = kept_guides(d, r).ok_or_else(|| bad("guide.deleteAll", "no such spread"))?; + let sp = d.spread_mut(r).ok_or_else(|| bad("guide.deleteAll", "no such spread"))?; + let n: usize = sp.pages.iter_mut().zip(&keep).map(|(pg, keep)| drop_editable(&mut pg.guides, keep)).sum(); + // The guides kept can't be selected: the spread's selected guides are gone. + sel.guides.retain(|g| g.spread != r); + Ok(json!({"deleted": n})) + }) + } + ), cmd!( "view.lockColumnGuides", "Lock Column Guides", @@ -112,7 +118,7 @@ pub fn specs() -> Vec { "Select All Guides", ["Edit"], Some("Cmd+Alt+G"), - "{spread?} — every guide on the spread that is not locked or on a locked or hidden layer → {selected: n}", + "{spread?} — every guide on the spread that is not locked or on a layer that is locked, hidden or locks its guides → {selected: n}", has_doc, select_all ), @@ -566,6 +572,7 @@ fn create_guides(s: &mut Session, p: &Value) -> Result { .ok_or_else(|| bad("layout.createGuides", format!("a single command may create at most {MAX_GUIDES_CREATED} guides")))?; let layer = s.doc()?.active_layer; s.edit(|d, sel| { + let keep = kept_guides(d, r).ok_or_else(|| bad("layout.createGuides", "no such spread"))?; if remove { // The cleared pages' guide addresses name the new guides now. sel.guides.retain(|g| g.spread != r || only.is_some_and(|o| o != g.page)); @@ -577,7 +584,7 @@ fn create_guides(s: &mut Session, p: &Value) -> Result { continue; } if remove { - pg.guides.clear(); + drop_editable(&mut pg.guides, keep.get(pi).map_or(&[][..], Vec::as_slice)); } let area: Rect = if to_page { pg.bounds() } else { pg.margin_rect() }; for y in grid_positions(area.y0, area.y1, rows, rg)? { @@ -607,6 +614,20 @@ fn create_guides(s: &mut Session, p: &Value) -> Result { }) } +/// Per page of spread `r`, the guides that can't be edited (locked, or on a layer that is locked, +/// hidden or locks its guides): what removing guides leaves. `None` without the spread. +fn kept_guides(d: &designcraft_doc::Document, r: designcraft_doc::SpreadRef) -> Option>> { + Some(d.spread(r)?.pages.iter().map(|pg| pg.guides.iter().map(|g| !g.editable_in(d)).collect()).collect()) +} + +/// Remove the guides `keep` doesn't mark (the editable ones); returns how many went. +fn drop_editable(guides: &mut Vec, keep: &[bool]) -> usize { + let before = guides.len(); + let mut keep = keep.iter(); + guides.retain(|_| keep.next().copied().unwrap_or(false)); + before - guides.len() +} + #[cfg(test)] mod tests { use super::*; @@ -953,6 +974,53 @@ mod layer_tests { assert_eq!(s.execute("guide.list", &json!({})).unwrap()[0]["position"], 200.0); } + /// Layer Options › Lock Guides: the layer's guides stay where they are (moving and deleting + /// them is refused) while its objects stay editable. + #[test] + fn lock_guides_locks_only_the_layers_guides() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let layer = s.execute("layer.new", &json!({"name": "Grid"})).unwrap()["id"].as_u64().unwrap(); + s.execute("layer.activate", &json!({"id": layer})).unwrap(); + s.execute("guide.add", &json!({"orientation": "vertical", "position": 100})).unwrap(); + let frame = s.execute("frame.create", &json!({"rect": [36, 36, 200, 200]})).unwrap()["id"].as_u64().unwrap(); + s.execute("layer.set", &json!({"id": layer, "lockGuides": true})).unwrap(); + let d = s.doc().unwrap().doc.clone(); + let g = d.spreads[0].pages[0].guides[0].clone(); + assert!(g.visible_in(&d) && !g.editable_in(&d)); + for command in ["guide.move", "guide.delete"] { + assert!(s.execute(command, &json!({"page": 0, "index": 0, "position": 200})).is_err(), "{command} moved a locked guide"); + } + assert_eq!(s.execute("guide.list", &json!({})).unwrap()[0]["position"], 100.0); + // The layer's objects aren't locked. + s.execute("transform.move", &json!({"ids": [frame], "dx": 10, "dy": 0})).unwrap(); + s.execute("layer.set", &json!({"id": layer, "lockGuides": false})).unwrap(); + s.execute("guide.move", &json!({"page": 0, "index": 0, "position": 200})).unwrap(); + assert_eq!(s.execute("guide.list", &json!({})).unwrap()[0]["position"], 200.0); + } + + #[test] + fn delete_all_and_remove_existing_keep_locked_guides() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let grid = s.execute("layer.new", &json!({"name": "Grid"})).unwrap()["id"].as_u64().unwrap(); + s.execute("layer.activate", &json!({"id": grid})).unwrap(); + s.execute("guide.add", &json!({"orientation": "vertical", "position": 100})).unwrap(); + let free = s.execute("layer.new", &json!({"name": "Free"})).unwrap()["id"].as_u64().unwrap(); + s.execute("layer.activate", &json!({"id": free})).unwrap(); + s.execute("guide.add", &json!({"orientation": "vertical", "position": 200})).unwrap(); + s.execute("layer.set", &json!({"id": grid, "lockGuides": true})).unwrap(); + let positions = |s: &mut Session| { + s.execute("guide.list", &json!({})).unwrap().as_array().unwrap().iter().map(|g| g["position"].as_f64().unwrap()).collect::>() + }; + assert_eq!(s.execute("guide.deleteAll", &json!({})).unwrap()["deleted"], 1); + assert_eq!(positions(&mut s), [100.0], "the locked layer's guide stays"); + s.execute("guide.add", &json!({"orientation": "vertical", "position": 200})).unwrap(); + s.execute("layout.createGuides", &json!({"columns": 2, "removeExisting": true, "page": 0})).unwrap(); + let after = positions(&mut s); + assert!(after.contains(&100.0) && !after.contains(&200.0), "{after:?}"); + } + #[test] fn guides_follow_their_layer() { let mut s = Session::new(); diff --git a/crates/engine/src/cmd/index.rs b/crates/engine/src/cmd/index.rs index 38a6bc49d..fa43d4d1b 100644 --- a/crates/engine/src/cmd/index.rs +++ b/crates/engine/src/cmd/index.rs @@ -88,6 +88,9 @@ fn add_reference(s: &mut Session, p: &Value) -> Result { let at = t.range().start.min(st.len()); st.insert_index_ref(at, r.clone()); let shift = INDEX_MARK.len_utf8(); + if t.cell.is_none() { + d.adjust_text_ranges(t.story, at..at, shift); + } sel.text = Some(TextSel { anchor: t.anchor + shift, focus: t.focus + shift, ..t }); Ok(json!({"pos": at})) }) @@ -184,14 +187,17 @@ fn fill_index(s: &mut Session, spec: IndexSpec, new_frame: Option<(usize, Option } }; let text = paras.iter().map(|(_, t)| t.as_str()).collect::>().join("\n"); - let st = d.story_mut(story).ok_or(designcraft_doc::DocError::NoStory(story))?; - let len = st.len(); - st.replace(0..len, &text); - for (pi, r) in st.para_ranges().into_iter().enumerate() { - if let Some((name, _)) = paras.get(pi) { - st.format_paras(r.start..r.start, |f| *f = ParaFormat { style: name.clone(), ..Default::default() }); + { + let st = d.story_mut(story).ok_or(designcraft_doc::DocError::NoStory(story))?; + let len = st.len(); + st.replace(0..len, &text); + for (pi, r) in st.para_ranges().into_iter().enumerate() { + if let Some((name, _)) = paras.get(pi) { + st.format_paras(r.start..r.start, |f| *f = ParaFormat { style: name.clone(), ..Default::default() }); + } } } + d.prune_story_text_ranges(story); d.index = Some(IndexSpec { story, ..spec.clone() }); Ok(json!({"story": story.0, "entries": paras.iter().filter(|(s, _)| s.starts_with("Index Level")).count()})) }) diff --git a/crates/engine/src/cmd/interactive.rs b/crates/engine/src/cmd/interactive.rs index 32562737c..75347b549 100644 --- a/crates/engine/src/cmd/interactive.rs +++ b/crates/engine/src/cmd/interactive.rs @@ -6,6 +6,7 @@ use serde_json::{Value, json}; use super::{CommandSpec, bad, cmd, has_doc, str_param}; use crate::{Result, Session}; +/// Register commands for editing hyperlinks and manual bookmarks. pub fn specs() -> Vec { vec![ cmd!( @@ -13,7 +14,7 @@ pub fn specs() -> Vec { "New Hyperlink…", ["Type", "Hyperlinks & Cross-References"], None, - "{url? | email? | page? (1-based), name?, ids?} — from the selected text, or the selected frames", + "{url? | email? | page? (1-based) | anchor? (a text anchor's id or name; the link follows it as the text reflows), name?, ids?} — from the selected text, or the selected frames", has_doc, create ), @@ -25,9 +26,9 @@ pub fn specs() -> Vec { }) }), cmd!(query "hyperlink.list", "Hyperlinks", [], None, "{}", has_doc, |s, _| Ok(serde_json::to_value(&s.doc()?.doc.hyperlinks).unwrap_or_default())), - cmd!("hyperlink.edit", "Hyperlink Options…", [], None, "{id, name?, url? | email? | page? (1-based)}", has_doc, |s, p| { + cmd!("hyperlink.edit", "Hyperlink Options…", [], None, "{id, name?, url? | email? | page? (1-based) | anchor?}", has_doc, |s, p| { let id = p.get("id").and_then(Value::as_u64).ok_or_else(|| bad("hyperlink.edit", "missing id"))?; - let dest = dest_param(p); + let dest = dest_param("hyperlink.edit", &s.doc()?.doc, p)?; let name = str_param(p, "name").map(str::to_string); s.edit(|d, _| { let h = d.hyperlinks.iter_mut().find(|h| h.id == id).ok_or_else(|| bad("hyperlink.edit", format!("no hyperlink {id}")))?; @@ -73,7 +74,7 @@ pub fn specs() -> Vec { let name = str_param(p, "name").map(str::to_string); s.edit(|d, _| { let name = name.clone().unwrap_or_else(|| format!("Bookmark {}", d.bookmarks.len() + 1)); - d.bookmarks.push(Bookmark { name, page, children: vec![] }); + d.bookmarks.push(Bookmark { name, page, children: vec![], generated_by_toc: false }); Ok(json!({"index": d.bookmarks.len() - 1})) }) }), @@ -90,19 +91,65 @@ pub fn specs() -> Vec { ] } -fn dest_param(p: &Value) -> Option { +/// `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). +fn dest_param(id: &str, d: &designcraft_doc::Document, p: &Value) -> Result> { if let Some(u) = str_param(p, "url") { - Some(HyperlinkDest::Url(u.to_string())) - } else if let Some(e) = str_param(p, "email") { - Some(HyperlinkDest::Email(e.to_string())) - } else { - p.get("page").and_then(Value::as_u64).map(|pg| HyperlinkDest::Page((pg as usize).saturating_sub(1))) + if !designcraft_doc::is_safe_link_url(u) { + return Err(bad(id, "`url` must start with http://, https:// or mailto:")); + } + return Ok(Some(HyperlinkDest::Url(u.to_string()))); } + if let Some(e) = str_param(p, "email") { + return Ok(Some(HyperlinkDest::Email(e.to_string()))); + } + if let Some(a) = p.get("anchor").filter(|a| !a.is_null()) { + let anchors = || d.stories.values().flat_map(|st| st.anchors.iter()); + // An id names one anchor or none. + if let Some(n) = a.as_u64() { + return match anchors().any(|x| x.id == n) { + true => Ok(Some(HyperlinkDest::Anchor(n))), + false => Err(bad(id, format!("no text anchor {a} (anchor.list names them)"))), + }; + } + // A name need not. `anchor.create` refuses a name in use, but an IDML import can bring a + // document that already has two of the same, so taking the first match stored whichever + // anchor happened to come first, and a link on a name shared by anchors on two pages went + // to the wrong page with nothing to say so (noted in review). The id still reaches either + // of them. + let Some(name) = a.as_str() else { return Err(bad(id, format!("no text anchor {a} (anchor.list names them)"))) }; + let mut named = anchors().filter(|x| x.name == name); + return match (named.next(), named.next()) { + (Some(x), None) => Ok(Some(HyperlinkDest::Anchor(x.id))), + (Some(_), Some(_)) => { + let ids: Vec = anchors().filter(|x| x.name == name).map(|x| x.id.to_string()).collect(); + Err(bad(id, format!("more than one text anchor is named {name:?} ({}); give the id instead", ids.join(", ")))) + } + (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)))) +} + +/// The anchor's own name, for a link to one that was not given a name. +fn dest_label(d: &designcraft_doc::Document, dest: &HyperlinkDest) -> String { + if let HyperlinkDest::Anchor(a) = dest + && let Some(x) = d.stories.values().flat_map(|st| st.anchors.iter()).find(|x| x.id == *a) + { + return x.name.clone(); + } + dest.label() } fn create(s: &mut Session, p: &Value) -> Result { - let dest = dest_param(p).ok_or_else(|| bad("hyperlink.create", "give `url`, `email` or `page`"))?; let st = s.doc()?; + let dest = dest_param("hyperlink.create", &st.doc, p)?.ok_or_else(|| bad("hyperlink.create", "give `url`, `email`, `page` or `anchor`"))?; let sources: Vec = if let Some(ids) = super::ids_param(p, "ids") { ids.into_iter().map(|id| HyperlinkSource::Item { id }).collect() } else if let Some(t) = st.selection.text.filter(|t| !t.is_caret()) { @@ -118,11 +165,7 @@ fn create(s: &mut Session, p: &Value) -> Result { let mut ids = vec![]; for src in sources { let id = d.alloc(); - let name = name.clone().unwrap_or_else(|| match &dest { - HyperlinkDest::Url(u) => u.clone(), - HyperlinkDest::Email(e) => e.clone(), - HyperlinkDest::Page(p) => format!("Page {}", p + 1), - }); + let name = name.clone().unwrap_or_else(|| dest_label(d, &dest)); d.hyperlinks.push(Hyperlink { id, name, source: src, dest: dest.clone() }); ids.push(id); } @@ -155,4 +198,176 @@ mod panel_tests { s.execute("bookmark.rename", &json!({"index": 0, "name": "Back"})).unwrap(); assert_eq!(s.execute("bookmark.list", &json!({})).unwrap()[0]["name"], "Back"); } + + #[test] + fn hyperlinks_refuse_non_web_schemes() { + let mut s = Session::new(); + s.execute("file.new", &json!({"pages": 1})).unwrap(); + let id = s.execute("frame.create", &json!({"rect": [72, 72, 200, 120]})).unwrap()["id"].clone(); + for bad in ["javascript:alert(1)", "file:///etc/passwd", "data:text/html,hi", "\\\\attacker\\share"] { + let e = s.execute("hyperlink.create", &json!({"ids": [id.clone()], "url": bad})).expect_err("refused").to_string(); + assert!(e.contains("http://"), "{bad}: {e}"); + } + s.execute("hyperlink.create", &json!({"ids": [id.clone()], "url": "mailto:info@example.com"})).unwrap(); + s.execute("hyperlink.create", &json!({"ids": [id], "url": "https://example.com"})).unwrap(); + } +} + +#[cfg(test)] +mod anchor_dest_tests { + use serde_json::json; + + use crate::Session; + + /// The page object numbers of a PDF, in order, and the page each link annotation points at + /// (as an index into that list). + fn link_pages(s: &mut Session) -> Vec { + let r = s.execute("file.exportPdf", &json!({})).unwrap(); + let bytes = super::super::file::base64_decode(r["base64"].as_str().unwrap()); + let pdf = String::from_utf8_lossy(&bytes).into_owned(); + let kids: Vec<&str> = pdf + .split("/Kids[") + .nth(1) + .and_then(|k| k.split(']').next()) + .map(|k| k.split(" 0 R").map(str::trim).filter(|s| !s.is_empty()).collect()) + .unwrap_or_default(); + let object = + |n: &str| -> String { pdf.split(&format!("\n{n} 0 obj\n")).nth(1).and_then(|o| o.split("\nendobj").next()).unwrap_or("").to_string() }; + let mut out = Vec::new(); + for part in pdf.split("/Subtype/Link").skip(1) { + let Some(dest) = part.split("/Dest ").nth(1).and_then(|d| d.split(" 0 R").next()) else { continue }; + // `[ 0 R/XYZ …]` + let page = object(dest.trim()); + let Some(page) = page.trim_start_matches('[').split(" 0 R").next() else { continue }; + if let Some(i) = kids.iter().position(|k| *k == page.trim()) { + out.push(i); + } + } + out + } + + /// `anchor.create` does not require a name to be unique -- and an IDML import can bring a + /// document that already has two of the same -- so the lookup taking the first match meant a + /// link made on a shared name went to whichever anchor came first, a different page, with + /// nothing to say so (noted in review). The id still reaches either of them. + #[test] + fn a_name_two_anchors_share_cannot_pick_one_of_them() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 300, "height": 300, "pages": 3, "facingPages": false, "margins": 0})).unwrap(); + + // Two anchors with one name, in text on different pages. `anchor.create` refuses a name + // in use, but a document opened from a file can still hold two, so the second is renamed + // in the document directly. + let mut made = Vec::new(); + for (page, name) in [(1usize, "Photo 1"), (2, "Photo 1 (second)")] { + let sp = s.doc().unwrap().doc.page_loc(page).unwrap().0; + let f = s + .execute("frame.create", &json!({"spread": sp, "rect": [20, 20, 280, 100], "content": "text", "text": "Photo 1 full size"})) + .unwrap(); + s.execute("text.select", &json!({"story": f["story"].clone(), "anchor": 0, "focus": 7})).unwrap(); + made.push(s.execute("anchor.create", &json!({"name": name})).unwrap()); + } + s.edit(|d, _| { + for sid in d.stories.keys().copied().collect::>() { + for a in &mut d.story_mut(sid).unwrap().anchors { + if a.name == "Photo 1 (second)" { + std::sync::Arc::make_mut(a).name = "Photo 1".into(); + } + } + } + Ok(()) + }) + .unwrap(); + assert_ne!(made[0]["id"], made[1]["id"], "two anchors, one name"); + let thumb = s.execute("frame.create", &json!({"rect": [20, 20, 120, 80], "content": "unassigned"})).unwrap(); + + // Creating on the shared name is refused, and says what to do instead. + let e = s.execute("hyperlink.create", &json!({"anchor": "Photo 1", "ids": [thumb["id"].clone()]})).expect_err("ambiguous").to_string(); + assert!(e.contains("more than one text anchor"), "{e}"); + assert!(e.contains("give the id instead"), "it says what to do instead: {e}"); + assert!(s.execute("hyperlink.list", &json!({})).unwrap().as_array().is_some_and(|l| l.is_empty()), "and no link was made"); + + // By id it works, and the id picks the one that was asked for. + s.execute("hyperlink.create", &json!({"anchor": made[1]["id"].clone(), "ids": [thumb["id"].clone()]})).unwrap(); + let live = s.execute("hyperlink.list", &json!({})).unwrap()[0]["id"].clone(); + let dest = |s: &mut Session| s.execute("hyperlink.list", &json!({})).unwrap()[0]["dest"].clone(); + assert_eq!(dest(&mut s), json!({"kind": "anchor", "value": made[1]["id"].clone()})); + + // An edit on the shared name is refused and leaves the destination as it was. + let e = s.execute("hyperlink.edit", &json!({"id": live.clone(), "anchor": "Photo 1"})).expect_err("ambiguous").to_string(); + assert!(e.contains("more than one text anchor"), "{e}"); + assert_eq!(dest(&mut s), json!({"kind": "anchor", "value": made[1]["id"].clone()}), "the refused edit changed nothing"); + + // And the other anchor is still reachable by its id. + s.execute("hyperlink.edit", &json!({"id": live, "anchor": made[0]["id"].clone()})).unwrap(); + assert_eq!(dest(&mut s), json!({"kind": "anchor", "value": made[0]["id"].clone()})); + } + + /// A frame can link to a text anchor, as a cross-reference refers to one, and the link lands + /// on whichever page the anchor's text is on when the PDF is written — IDML files link photo + /// thumbnails to their full-size pictures that way (#1446). + #[test] + fn a_frame_can_link_to_a_text_anchor_and_follows_it() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 300, "height": 300, "pages": 3, "facingPages": false, "margins": 0})).unwrap(); + // The destination: an anchor in text on page 3. + let sp = s.doc().unwrap().doc.page_loc(2).unwrap().0; + let dest = + s.execute("frame.create", &json!({"spread": sp, "rect": [20, 20, 280, 100], "content": "text", "text": "Photo 1 full size"})).unwrap(); + s.execute("text.select", &json!({"story": dest["story"].clone(), "anchor": 0, "focus": 7})).unwrap(); + let anchor = s.execute("anchor.create", &json!({"name": "Photo 1"})).unwrap(); + // The source: a thumbnail frame on page 1, linked by the anchor's name. + let thumb = s.execute("frame.create", &json!({"rect": [20, 20, 120, 80], "content": "unassigned"})).unwrap(); + s.execute("hyperlink.create", &json!({"anchor": "Photo 1", "ids": [thumb["id"].clone()]})).unwrap(); + let links = s.execute("hyperlink.list", &json!({})).unwrap(); + assert_eq!(links[0]["dest"], json!({"kind": "anchor", "value": anchor["id"].clone()}), "{links}"); + // Named after the anchor, since no name was given. + assert_eq!(links[0]["name"], "Photo 1"); + assert_eq!(link_pages(&mut s), vec![2], "the link lands on the anchor's page (the third)"); + + // A page inserted in front moves the anchor's text to page 4, and the link follows it + // without being edited. + s.execute("layout.pages.insert", &json!({"count": 1, "after": 0})).unwrap(); + assert_eq!(s.execute("anchor.list", &json!({})).unwrap()[0]["page"], "4"); + assert_eq!(link_pages(&mut s), vec![3], "the link follows the text"); + + // 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(); + assert_eq!(s.execute("hyperlink.list", &json!({})).unwrap()[0]["name"], "Thumbnail"); + assert_eq!(link_pages(&mut s), vec![3]); + let e = s.execute("hyperlink.create", &json!({"anchor": "No Such Anchor", "ids": [thumb["id"].clone()]})).expect_err("refused").to_string(); + assert!(e.contains("no text anchor"), "and it says why, rather than that no destination was given: {e}"); + + // An unknown anchor *id* is refused as well. `as_u64` answered for any number, so a link + // was stored to an anchor nobody has and the export quietly left it out (noted in review). + let live = s.execute("hyperlink.list", &json!({})).unwrap()[0]["id"].clone(); + let missing = anchor["id"].as_u64().expect("the anchor's id") + 9_999; + let e = s.execute("hyperlink.create", &json!({"anchor": missing, "ids": [thumb["id"].clone()]})).expect_err("refused").to_string(); + assert!(e.contains("no text anchor"), "an unknown id is refused: {e}"); + + // And `hyperlink.edit` reports it rather than reading it as "no destination given", which + // made the command succeed and keep the old destination (noted in review). + for unknown in [json!(missing), json!("No Such Anchor")] { + let e = s.execute("hyperlink.edit", &json!({"id": live.clone(), "anchor": unknown.clone()})).expect_err("refused").to_string(); + assert!(e.contains("no text anchor"), "{unknown}: {e}"); + } + let after = s.execute("hyperlink.list", &json!({})).unwrap(); + assert_eq!(after[0]["dest"], json!({"kind": "anchor", "value": anchor["id"].clone()}), "the destination is unchanged: {after}"); + assert_eq!(after[0]["name"], "Thumbnail", "and so is the name"); + assert_eq!(link_pages(&mut s), vec![3], "and the export still lands on the anchor's page"); + + // A rename that names no destination still works: that is what `None` is for, and it must + // not have become an error on the way. + s.execute("hyperlink.edit", &json!({"id": live.clone(), "name": "Thumb"})).unwrap(); + let renamed = s.execute("hyperlink.list", &json!({})).unwrap(); + assert_eq!(renamed[0]["name"], "Thumb"); + assert_eq!(renamed[0]["dest"], json!({"kind": "anchor", "value": anchor["id"].clone()}), "the destination survives a rename"); + + // A link to a deleted anchor is not exported, rather than pointing at the wrong page. + s.execute("text.select", &json!({"story": dest["story"].clone(), "anchor": 0, "focus": 8})).unwrap(); + s.execute("text.delete", &json!({})).unwrap(); + assert!(s.execute("anchor.list", &json!({})).unwrap().as_array().unwrap().is_empty()); + assert_eq!(link_pages(&mut s), Vec::::new(), "no link rather than a wrong one"); + } } diff --git a/crates/engine/src/cmd/interchange.rs b/crates/engine/src/cmd/interchange.rs index 0ddb6a1aa..940404aa9 100644 --- a/crates/engine/src/cmd/interchange.rs +++ b/crates/engine/src/cmd/interchange.rs @@ -17,7 +17,7 @@ use crate::{DocState, EngineError, Result, Session}; pub fn specs() -> Vec { vec![ cmd!(query "file.exportIdml", "Export IDML…", [], None, - "{path?, embedImages?: true} — writes an IDML package to `path`, or returns {base64} without a path", + "{path?, embedImages?: true} — writes an IDML package to `path`, or returns {base64} without a path; `warnings` names each image written as a link because the embedded-image limit was reached", has_doc, export_idml), cmd!(noundo "file.openIdml", "Open IDML", [], None, "{path | base64, name?} — opens an IDML package, or an InDesign document or template (.indd, .indt: converted to IDML first; its conversion warnings join `warnings`), as a new document (linked images are read next to the file or from its Links/ folder; the fonts in a `Document Fonts` folder beside it load first) → {index, documentFonts, warnings: conversion warnings, package parts missing, font files skipped, GREP styles whose pattern can't compile}", @@ -29,15 +29,19 @@ fn export_idml(s: &mut Session, p: &Value) -> Result { let st = s.doc()?; let opts = designcraft_idml::ExportOptions { embed_images: p.get("embedImages").and_then(Value::as_bool).unwrap_or(true) }; let layer_doc = with_pdf_layer_variants(&st.doc, opts.embed_images)?; - let bytes = designcraft_idml::export_idml_with(layer_doc.as_ref().unwrap_or(&st.doc), &opts); - match str_param(p, "path") { + let (bytes, warnings) = designcraft_idml::export_idml_report(layer_doc.as_ref().unwrap_or(&st.doc), &opts); + let mut out = match str_param(p, "path") { Some(path) => { #[cfg(not(target_arch = "wasm32"))] crate::io::write_file(path, &bytes).map_err(EngineError::Other)?; - Ok(json!({"path": path, "bytes": bytes.len()})) + json!({"path": path, "bytes": bytes.len()}) } - None => Ok(json!({"base64": base64_encode(&bytes), "bytes": bytes.len()})), + None => json!({"base64": base64_encode(&bytes), "bytes": bytes.len()}), + }; + if !warnings.is_empty() { + out["warnings"] = json!(warnings); } + Ok(out) } /// Whether a placement holds an Object Layer Options choice an export can still apply: a graphic @@ -45,7 +49,8 @@ fn export_idml(s: &mut Session, p: &Value) -> Result { /// replaced with another format) is not one, so the package report does not name it. pub(crate) fn has_applicable_pdf_layer_overrides(doc: &Document) -> bool { doc.placed_items().into_iter().any(|it| { - it.has_pdf_layer_override() && it.graphic().and_then(|g| doc.assets.get(&g.asset)).is_some_and(|a| designcraft_render::is_pdf(&a.data)) + it.has_pdf_layer_override() + && it.graphic().and_then(|g| doc.assets.get(&g.asset)).is_some_and(|a| a.data.load().is_ok_and(|b| designcraft_render::is_pdf(&b))) }) } @@ -62,7 +67,8 @@ fn with_pdf_layer_variants(doc: &Document, embed: bool) -> Result Result Result Option> { #[cfg(not(target_arch = "wasm32"))] { - read_packaged_link(link, package).map(|(_, data)| data) + read_packaged_link(link, package).map(|(_, data, _)| data) } #[cfg(target_arch = "wasm32")] { @@ -160,7 +167,7 @@ pub fn import(bytes: &[u8], package: Option<&std::path::Path>) -> Result) -> Result<(Document, Vec)> { - import_report_with_previews(bytes, package, &std::collections::HashMap::new()) + import_report_with_previews(bytes, package, &std::collections::HashMap::new()).map(|(document, warnings, _)| (document, warnings)) } /// [`import_report`], showing `previews` (graphic `Self` → image) for linked files that can't be read. @@ -168,14 +175,14 @@ fn import_report_with_previews( bytes: &[u8], package: Option<&std::path::Path>, previews: &std::collections::HashMap>>, -) -> Result<(Document, Vec)> { +) -> Result<(Document, Vec, std::collections::HashMap)> { #[cfg(not(target_arch = "wasm32"))] let resolved = std::cell::RefCell::new(std::collections::HashMap::new()); let read = |link: &str| -> Option> { #[cfg(not(target_arch = "wasm32"))] { - let (path, data) = read_packaged_link(link, package)?; - resolved.borrow_mut().insert(link.to_string(), path); + let (path, data, fingerprint) = read_packaged_link(link, package)?; + resolved.borrow_mut().insert(link.to_string(), (path, fingerprint, data.len() as u64)); Some(data) } #[cfg(target_arch = "wasm32")] @@ -184,22 +191,88 @@ fn import_report_with_previews( None } }; - let designcraft_idml::Imported { mut document, warnings } = + let designcraft_idml::Imported { mut document, warnings, story_ids } = designcraft_idml::import_idml_report_with_previews(bytes, &read, previews).map_err(|e| EngineError::Other(e.to_string()))?; resolve_pdf_crops(&mut document); #[cfg(not(target_arch = "wasm32"))] let document = { let mut document = document; for asset in document.assets.values_mut() { - if let Some(path) = asset.link.as_ref().and_then(|link| resolved.borrow().get(link).cloned()) { + if let Some((path, fingerprint, len)) = asset.link.as_ref().and_then(|link| resolved.borrow().get(link).cloned()) { // Relocated packages must also use the new path for preflight and link updates. - std::sync::Arc::make_mut(asset).link = Some(path); + std::sync::Arc::make_mut(asset).set_link(Some(path), fingerprint); + // Bytes read from the file stay a link to it; graphics embedded in the IDML (whose + // size differs from the file's, or that share no read) stay embedded. + if asset.data.embedded_bytes().is_some_and(|b| b.len() as u64 == len) { + link_read_file(std::sync::Arc::make_mut(asset), package); + } else if asset.proxy.is_some() { + // An embedded graphic draws its own bytes. + std::sync::Arc::make_mut(asset).proxy = None; + } } } resolve_packaged_links(&mut document, package); document }; - Ok((document, warnings)) + Ok((document, warnings, story_ids)) +} + +/// `asset`, whose embedded bytes were just read from the file its link names, as a linked asset +/// ([`super::links::link_to_file`]), drawn while the file can't be read with a proxy: the +/// document's preview of it when that shows the whole image ([`preview_proxy`], +/// [`shows_whole`]), else one made from the file, else the preview. +#[cfg(not(target_arch = "wasm32"))] +fn link_read_file(asset: &mut designcraft_doc::Asset, package: Option<&std::path::Path>) { + let Some(bytes) = asset.data.embedded_bytes().cloned() else { return }; + let Some(path) = asset.link.clone() else { return }; + let preview = asset.proxy.take().and_then(|p| preview_proxy(&p)); + let (whole, fallback) = match preview { + Some(p) if shows_whole(asset, &bytes, &p) => (Some(p), None), + p => (None, p), + }; + // The fingerprint kept by the read (none for a file just written: its hash tells its bytes). + let file = super::links::FileLink::of(std::path::Path::new(&path), asset.link_fingerprint); + super::links::link_to_file(asset, bytes, file, package, whole); + if asset.storage == designcraft_doc::Storage::Linked && asset.proxy.is_none() { + asset.proxy = fallback; + } +} + +/// A document's stored preview of a linked graphic as a proxy: checked to decode, and made again +/// within the proxy limits ([`designcraft_render::proxy`]) when it is bigger or in another +/// format (a larger one wouldn't be kept by the saved document). `None` when it doesn't decode. +#[cfg(not(target_arch = "wasm32"))] +fn preview_proxy(preview: &designcraft_doc::Proxy) -> Option { + use designcraft_render::proxy::{MAX_BYTES, MAX_SIDE_PX, make_proxy}; + let bytes = preview.data.embedded_bytes()?; + let mime = designcraft_render::image_mime(bytes); + let fits = bytes.len() <= MAX_BYTES + && matches!(mime, "image/jpeg" | "image/png") + && designcraft_render::image_size(bytes).is_some_and(|(w, h)| w.max(h) <= MAX_SIDE_PX); + if fits && let Some(pm) = designcraft_render::decode_pixmap(bytes) { + let pixels = (u32::from(pm.width()), u32::from(pm.height())); + return Some(designcraft_doc::Proxy { mime: mime.into(), pixels, data: preview.data.clone() }); + } + let p = make_proxy(bytes, 0)?; + Some(designcraft_doc::Proxy { mime: p.mime.into(), pixels: p.pixels, data: designcraft_doc::AssetData::embedded(p.data) }) +} + +/// Whether `preview` shows the whole of `asset`'s image (`bytes`, its file's), as a proxy must: +/// a raster whose preview has the image's proportions. A PDF's preview shows its crop, which may +/// not be the page the proxy stands for, and other files' proportions aren't known here. +#[cfg(not(target_arch = "wasm32"))] +fn shows_whole(asset: &designcraft_doc::Asset, bytes: &[u8], preview: &designcraft_doc::Proxy) -> bool { + if designcraft_render::is_pdf(bytes) || asset.mime == "application/pdf" { + return false; + } + let Some((w, h)) = designcraft_render::image_size(bytes) else { return false }; + let (pw, ph) = preview.pixels; + if w == 0 || h == 0 || pw == 0 || ph == 0 { + return false; + } + // Proportions equal but for the preview's rounding to whole pixels. + let (ratio, preview_ratio) = (f64::from(w) / f64::from(h), f64::from(pw) / f64::from(ph)); + (preview_ratio / ratio - 1.0).abs() <= 1.0 / f64::from(pw) + 1.0 / f64::from(ph) + 0.01 } /// Placed PDFs read from IDML name their crop (`PDFCrop`): find where each box sits on its page, @@ -347,6 +420,10 @@ fn is_graphic(bytes: &[u8]) -> bool { pub(crate) fn resolve_packaged_links(document: &mut Document, package: Option<&std::path::Path>) { let Some(package) = package else { return }; for asset in document.assets.values_mut() { + // Linked storage finds its files itself (`native_links::resolve`). + if asset.storage == designcraft_doc::Storage::Linked { + continue; + } let Some(link) = asset.link.as_deref() else { continue }; if link.len() > MAX_LINK_PATH_BYTES { continue; @@ -357,29 +434,41 @@ pub(crate) fn resolve_packaged_links(document: &mut Document, package: Option<&s // A link relative to the document (what File › Package writes, `Links/logo.png`) is // held as the file it names, as every other link is, so preflight and updates find it. if std::path::Path::new(link).is_relative() { - std::sync::Arc::make_mut(asset).link = Some(path.to_string_lossy().into_owned()); + // The same file under its full name: what is kept of it stays. + let loaded = asset.link_fingerprint; + std::sync::Arc::make_mut(asset).set_link(Some(path.to_string_lossy().into_owned()), loaded); } continue; } let Some(path) = packaged_link_candidates(link, Some(package)).into_iter().find(|p| crate::io::is_file(p)) else { continue }; - std::sync::Arc::make_mut(asset).link = Some(path.to_string_lossy().into_owned()); + // Another file than the link named, found again by name: the bytes weren't read from it. + std::sync::Arc::make_mut(asset).set_link(Some(path.to_string_lossy().into_owned()), None); } } /// The first candidate for `link` ([`packaged_link_candidates`]) that is a regular file no larger -/// than [`MAX_LINKED_FILE_BYTES`] holding an image or a graphic, with its path. +/// than [`MAX_LINKED_FILE_BYTES`] holding an image or a graphic, with its path and the size and +/// time to keep with its bytes ([`super::links::loaded_fingerprint`]). #[cfg(not(target_arch = "wasm32"))] -fn read_packaged_link(link: &str, package: Option<&std::path::Path>) -> Option<(String, Vec)> { +fn read_packaged_link(link: &str, package: Option<&std::path::Path>) -> Option<(String, Vec, Option)> { for path in packaged_link_candidates(link, package) { - if !crate::io::is_file(&path) || !crate::io::metadata(&path).is_ok_and(|m| m.len() <= MAX_LINKED_FILE_BYTES) { + if !crate::io::is_file(&path) { continue; } + // The version about to be read: one that replaces it during the read (a syncing or + // network file) has other metadata, and the next Links check compares the bytes. + let Ok(metadata) = crate::io::metadata(&path) else { continue }; + if metadata.len() > MAX_LINKED_FILE_BYTES { + continue; + } + let before = super::datamerge::fingerprint_from(&metadata); // At most one byte over the limit, in case the file grew since. let Ok(bytes) = crate::io::read_capped(&path, MAX_LINKED_FILE_BYTES) else { continue }; if bytes.len() as u64 > MAX_LINKED_FILE_BYTES || !is_graphic(&bytes) { continue; } - return Some((path.to_string_lossy().into_owned(), bytes)); + let loaded = super::links::loaded_fingerprint(Some(before), &bytes); + return Some((path.to_string_lossy().into_owned(), bytes, loaded)); } None } @@ -406,7 +495,7 @@ pub(crate) fn open_idml(s: &mut Session, p: &Value) -> Result { let mut previews = std::collections::HashMap::new(); let bytes = if is_indd(&file, &bytes) { // What the converter can't read still comes over as IDML (#21). - let conversion = indd::convert(&bytes, &file).map_err(|e| { + let conversion = craft_indd::convert(&bytes, &file).map_err(|e| { EngineError::Other(format!( "can't convert the InDesign file: {e}. In InDesign, choose File ▸ Export… ▸ InDesign Markup (IDML) and open the .idml in DesignCraft." )) @@ -422,7 +511,7 @@ pub(crate) fn open_idml(s: &mut Session, p: &Value) -> Result { } else { bytes }; - let (mut d, import_warnings) = import_report_with_previews(&bytes, package.as_deref(), &previews)?; + let (mut d, import_warnings, story_ids) = import_report_with_previews(&bytes, package.as_deref(), &previews)?; warnings.extend(import_warnings); if !title.is_empty() { d.title = title; @@ -433,28 +522,42 @@ pub(crate) fn open_idml(s: &mut Session, p: &Value) -> Result { }; warnings.extend(font_warnings); warnings.extend(super::style::grep_style_warnings(&d)); + let warning_items: Vec = warnings.iter().map(|w| warning_item(&d, &story_ids, w).map_or(Value::Null, |i| json!(i.0))).collect(); // Never save over the .idml or .indd with the native format: the document starts unsaved. let mut st = DocState::new(d, None); st.fonts = fonts; let i = s.add_document(st); - Ok(json!({"index": i, "documentFonts": faces, "warnings": warnings})) + Ok(json!({"index": i, "documentFonts": faces, "warnings": warnings, "warningItems": warning_items})) +} + +/// The frame an import warning is about, so it can be shown: the first frame of the story a +/// "story …: …" warning names, by the converter's INDD id (`story 30892`, which it writes to the +/// IDML as `u78ac`) or by its IDML `Self` (`story u78ac`). +fn warning_item( + d: &Document, + story_ids: &std::collections::HashMap, + warning: &str, +) -> Option { + let name = warning.strip_prefix("story ")?.split([':', ' ']).next()?; + let self_id = name.parse::().map_or_else(|_| name.to_string(), |uid| format!("u{uid:x}")); + d.stories.get(story_ids.get(&self_id)?)?.frames.first().copied() } /// An InDesign document or template (.indd, .indt): known by its signature, or by its name when -/// the bytes are something else (the converter then says why it can't read them). +/// the bytes are neither a recognized DesignCraft document nor IDML. The converter explains +/// unrecognized data with an InDesign extension. pub(crate) fn is_indd(name: &str, bytes: &[u8]) -> bool { - bytes.starts_with(&indd::header::SIGNATURE) || has_indd_extension(name) -} - -pub(crate) fn has_indd_extension(name: &str) -> bool { - let n = name.to_ascii_lowercase(); - n.ends_with(".indd") || n.ends_with(".indt") + craft_file_formats::detect(name, bytes) == Some(craft_file_formats::Format::Indd) && !super::file::is_document(bytes) } /// `name` without a trailing .idml, .indd or .indt (any case). fn without_document_extension(name: &str) -> &str { match name.rsplit_once('.') { - Some((stem, ext)) if ["idml", "indd", "indt"].iter().any(|e| ext.eq_ignore_ascii_case(e)) => stem, + Some((stem, ext)) + if matches!(craft_file_formats::from_extension(ext), Some(craft_file_formats::Format::Idml | craft_file_formats::Format::Indd)) => + { + stem + } _ => name, } } @@ -479,6 +582,24 @@ mod tests { Ok((bytes, png)) } + #[test] + fn story_warnings_point_at_the_story_frame() { + let mut session = Session::new(); + session.execute("file.new", &json!({})).unwrap(); + session.execute("frame.create", &json!({"rect": [36, 36, 300, 200], "content": "text"})).unwrap(); + let idml = designcraft_idml::export_idml_with(&session.doc().unwrap().doc, &designcraft_idml::ExportOptions { embed_images: true }); + let (d, _, story_ids) = import_report_with_previews(&idml, None, &std::collections::HashMap::new()).unwrap(); + let (self_id, sid) = story_ids.iter().find(|(_, sid)| d.stories.get(*sid).is_some_and(|s| !s.frames.is_empty())).unwrap(); + let frame = d.stories[sid].frames[0]; + assert_eq!(warning_item(&d, &story_ids, &format!("story {self_id}: something")), Some(frame)); + // The INDD converter names stories by their number, which it writes as `u` + hex. + if let Some(uid) = self_id.strip_prefix('u').and_then(|h| u32::from_str_radix(h, 16).ok()) { + assert_eq!(warning_item(&d, &story_ids, &format!("story {uid}: text orientation of its frames is not known")), Some(frame)); + } + assert_eq!(warning_item(&d, &story_ids, "story 999999999: unknown"), None); + assert_eq!(warning_item(&d, &story_ids, "a table of 2 rows was read as 1"), None); + } + #[test] fn opens_nested_packaged_links_from_a_different_computer() { let dir = std::env::temp_dir().join(format!("dc-idml-nested-links-{}", std::process::id())); @@ -486,14 +607,19 @@ mod tests { std::fs::create_dir_all(path.parent().unwrap()).unwrap(); let (idml, png) = linked_idml("C:\\original-computer\\project\\Links\\illustrations\\logo.png", false).unwrap(); std::fs::write(&path, &png).unwrap(); + // Not written just now: its size and time can vouch for the imported bytes. + let earlier = std::time::SystemTime::now() - std::time::Duration::from_secs(60); + std::fs::File::options().write(true).open(&path).unwrap().set_modified(earlier).unwrap(); std::fs::write(dir.join("logo.png"), b"a different file with the same basename").unwrap(); let doc = import(&idml, Some(&dir.join("x.idml"))).unwrap(); let asset = doc.assets.values().next().unwrap(); - assert_eq!(*asset.data, png, "the packaged graphic must render even when its author-machine path no longer exists"); + assert_eq!(*asset.data.resident().unwrap(), png, "the packaged graphic must render even when its author-machine path no longer exists"); let resolved = std::path::absolute(&path).unwrap(); assert_eq!(asset.link.as_deref(), resolved.to_str(), "remember the resolved link so update and preflight use the packaged file"); - assert_eq!(super::super::links::status(asset, None), "ok"); + let expected = super::super::datamerge::fingerprint_from(&std::fs::metadata(&path).unwrap()); + assert_eq!(asset.link_fingerprint, Some(expected), "remember the same version of the file whose bytes were imported"); + assert_eq!(super::super::links::status_cached(asset, None, &mut Default::default()), "ok"); std::fs::remove_dir_all(dir).unwrap(); } @@ -508,9 +634,9 @@ mod tests { let doc = import(&idml, Some(&dir.join("x.idml"))).unwrap(); let asset = doc.assets.values().next().unwrap(); - assert_eq!(*asset.data, png); + assert_eq!(*asset.data.resident().unwrap(), png); assert_eq!(asset.link.as_deref(), std::path::absolute(&path).unwrap().to_str()); - assert_eq!(super::super::links::status(asset, None), "ok"); + assert_eq!(super::super::links::status_cached(asset, None, &mut Default::default()), "ok"); std::fs::remove_dir_all(dir).unwrap(); } @@ -524,9 +650,92 @@ mod tests { let doc = import(&idml, Some(&dir.join("x.idml"))).unwrap(); let asset = doc.assets.values().next().unwrap(); - assert_eq!(*asset.data, png); + assert_eq!(*asset.data.resident().unwrap(), png); assert_eq!(asset.link.as_deref(), std::path::absolute(&path).unwrap().to_str()); - assert_eq!(super::super::links::status(asset, None), "ok"); + assert_eq!(super::super::links::status_cached(asset, None, &mut Default::default()), "ok"); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn a_link_that_resolves_imports_as_a_linked_asset() { + let dir = std::env::temp_dir().join(format!("dc-idml-linked-import-{}", std::process::id())); + let path = dir.join("Links").join("logo.png"); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + let (idml, png) = linked_idml("/original-computer/project/logo.png", false).unwrap(); + std::fs::write(&path, &png).unwrap(); + + let doc = import(&idml, Some(&dir.join("x.idml"))).unwrap(); + let asset = doc.assets.values().next().unwrap(); + assert_eq!(asset.storage, designcraft_doc::Storage::Linked); + assert!(asset.data.embedded_bytes().is_none(), "no embedded original"); + assert!(asset.data.is_linked() && asset.data.resident().is_some(), "the bytes read are resident for the first draw"); + assert_eq!(asset.link_hash.as_deref(), Some(crate::asset_io::content_hash(&png).as_str())); + assert_eq!(asset.link_relative.as_deref(), Some("Links/logo.png")); + assert!(asset.proxy.is_some(), "a proxy made from the file"); + assert_eq!(asset.data.load().ok().map(|b| (*b).clone()), Some(png)); + std::fs::remove_dir_all(dir).unwrap(); + } + + /// A document's stored preview stands in for a linked file only when it decodes and shows + /// the whole image, within the proxy limits (made again when bigger); otherwise the proxy is + /// made from the file. + #[test] + fn a_stored_preview_is_the_proxy_only_when_it_decodes_and_shows_the_whole_image() { + use designcraft_render::proxy::{MAX_BYTES, MAX_SIDE_PX}; + let dir = std::env::temp_dir().join(format!("dc-idml-previews-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("photo.png"); + let png = |width: u32, height: u32| designcraft_render::Rendered { width, height, pixels: vec![255; (width * height * 4) as usize] }.to_png(); + let original = png(400, 200); + std::fs::write(&path, &original).unwrap(); + let linked_with = |preview: Vec| { + let mut a = designcraft_doc::Asset { + name: "photo.png".into(), + mime: "image/png".into(), + link: Some(path.to_str().unwrap().into()), + data: designcraft_doc::AssetData::embedded(original.clone()), + pixels: Some((400, 200)), + proxy: Some(designcraft_doc::Proxy { mime: "image/png".into(), pixels: (1, 1), data: designcraft_doc::AssetData::embedded(preview) }), + ..Default::default() + }; + link_read_file(&mut a, None); + assert_eq!(a.storage, designcraft_doc::Storage::Linked); + let proxy = a.proxy.expect("a proxy"); + let bytes = proxy.data.embedded_bytes().expect("embedded").clone(); + let pm = designcraft_render::decode_pixmap(&bytes).expect("the proxy decodes"); + assert_eq!((u32::from(pm.width()), u32::from(pm.height())), proxy.pixels); + assert!(bytes.len() <= MAX_BYTES && proxy.pixels.0.max(proxy.pixels.1) <= MAX_SIDE_PX); + (proxy.pixels, bytes) + }; + let small = png(100, 50); + assert_eq!(linked_with(small.clone()), ((100, 50), Arc::new(small)), "kept as it is"); + assert_eq!(linked_with(png(2048, 1024)).0, (1024, 512), "made again within the limits"); + assert_eq!(linked_with(png(100, 100)).0, (400, 200), "a crop of the image: made from the file"); + assert_eq!(linked_with(b"not an image".to_vec()).0, (400, 200), "undecodable: made from the file"); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn a_link_that_does_not_resolve_keeps_its_path_for_relink() { + let (idml, _) = linked_idml("/original-computer/project/logo.png", false).unwrap(); + let doc = import(&idml, None).unwrap(); + let asset = doc.assets.values().next().unwrap(); + assert_eq!(asset.storage, designcraft_doc::Storage::Embedded); + assert_eq!(asset.link.as_deref(), Some("/original-computer/project/logo.png")); + assert!(asset.data.embedded_bytes().is_some_and(|b| b.is_empty()) && asset.link_hash.is_none()); + } + + #[test] + fn a_graphic_embedded_in_the_idml_stays_embedded_beside_its_file() { + let dir = std::env::temp_dir().join(format!("dc-idml-embedded-stays-{}", std::process::id())); + let path = dir.join("logo.png"); + std::fs::create_dir_all(&dir).unwrap(); + let (idml, png) = linked_idml(path.to_str().unwrap(), true).unwrap(); + std::fs::write(&path, &png).unwrap(); + let doc = import(&idml, Some(&dir.join("x.idml"))).unwrap(); + let asset = doc.assets.values().next().unwrap(); + assert_eq!(asset.storage, designcraft_doc::Storage::Embedded); + assert_eq!(asset.data.embedded_bytes().map(|b| (**b).clone()), Some(png)); std::fs::remove_dir_all(dir).unwrap(); } @@ -545,16 +754,16 @@ mod tests { let doc = import(&idml, Some(&package.join("x.idml"))).unwrap(); let asset = doc.assets.values().next().unwrap(); assert_eq!(std::path::Path::new(asset.link.as_deref().unwrap()), original.as_path(), "an existing original stays authoritative"); - assert_eq!(*asset.data, png); - assert_eq!(super::super::links::status(asset, None), "modified"); + assert_eq!(**asset.data.embedded_bytes().unwrap(), png); + assert_eq!(super::super::links::status_cached(asset, None, &mut Default::default()), "modified"); std::fs::remove_file(&original).unwrap(); std::fs::write(©, b"modified packaged copy").unwrap(); let doc = import(&idml, Some(&package.join("x.idml"))).unwrap(); let asset = doc.assets.values().next().unwrap(); assert_eq!(asset.link.as_deref(), copy.to_str()); - assert_eq!(*asset.data, png, "rebinding must not replace embedded pixels"); - assert_eq!(super::super::links::status(asset, None), "modified"); + assert_eq!(**asset.data.embedded_bytes().unwrap(), png, "rebinding must not replace embedded pixels"); + assert_eq!(super::super::links::status_cached(asset, None, &mut Default::default()), "modified"); std::fs::remove_file(©).unwrap(); let packaged = package.join("x.idml"); @@ -562,8 +771,8 @@ mod tests { let doc = import(&idml, folder).unwrap(); let asset = doc.assets.values().next().unwrap(); assert_eq!(std::path::Path::new(asset.link.as_deref().unwrap()), original.as_path(), "keep a missing link when there is no candidate"); - assert_eq!(*asset.data, png); - assert_eq!(super::super::links::status(asset, None), "missing"); + assert_eq!(**asset.data.embedded_bytes().unwrap(), png); + assert_eq!(super::super::links::status_cached(asset, None, &mut Default::default()), "missing"); } let oversized = "a/".repeat(MAX_LINK_PATH_BYTES); assert!(packaged_link_candidates(&oversized, Some(&packaged)).is_empty()); @@ -572,7 +781,7 @@ mod tests { resolve_packaged_links(&mut doc, Some(&packaged)); let asset = doc.assets.values().next().unwrap(); assert_eq!(asset.link.as_deref(), Some(oversized.as_str())); - assert_eq!(*asset.data, png); + assert_eq!(**asset.data.embedded_bytes().unwrap(), png); std::fs::remove_dir_all(dir).unwrap(); } @@ -611,7 +820,7 @@ mod tests { assert!(seen.iter().all(|p| p.starts_with(&dir) || itself.as_ref() == Some(p)), "{link}: {seen:?}"); let asset = doc.assets.values().next().unwrap(); assert!(asset.data.is_empty(), "{link}"); - assert_eq!(super::super::links::status(asset, None), "missing", "{link}"); + assert_eq!(super::super::links::status_cached(asset, None, &mut Default::default()), "missing", "{link}"); } // An image elsewhere on this computer is read, and so is one beside the package. let away = outside.join("logo.png"); @@ -619,12 +828,12 @@ mod tests { let (idml, _) = linked_idml(away.to_str().unwrap(), false).unwrap(); let doc = import(&idml, Some(&package)).unwrap(); let asset = doc.assets.values().next().unwrap(); - assert_eq!((&*asset.data, asset.link.as_deref()), (&png, away.to_str())); - assert_eq!(super::super::links::status(asset, None), "ok"); + assert_eq!((&*asset.data.resident().unwrap(), asset.link.as_deref()), (&png, away.to_str())); + assert_eq!(super::super::links::status_cached(asset, None, &mut Default::default()), "ok"); std::fs::write(dir.join("Links").join("logo.png"), &png).unwrap(); let (idml, _) = linked_idml("Links/logo.png", false).unwrap(); let doc = import(&idml, Some(&package)).unwrap(); - assert_eq!(*doc.assets.values().next().unwrap().data, png); + assert_eq!(*doc.assets.values().next().unwrap().data.resident().unwrap(), png); std::fs::remove_dir_all(base).unwrap(); } @@ -632,7 +841,7 @@ mod tests { /// name) go to the converter, and what it can't read is an open error that adds no document. #[test] fn indd_files_go_through_the_converter_and_its_errors_are_open_errors() { - let mut signed = indd::header::SIGNATURE.to_vec(); + let mut signed = craft_indd::SIGNATURE.to_vec(); signed.resize(4096, 0); let cases = [(signed, "Brochure"), (vec![0; 4096], "Brochure.indd"), (b"not an InDesign file".to_vec(), "Template.INDT")]; let mut s = Session::new(); @@ -724,14 +933,14 @@ mod nested_layer_tests { for (id, expected) in ids.into_iter().zip([states(false, true), states(true, true)]) { let item = copy.placed_items().into_iter().find(|i| i.id == id).unwrap(); let asset = ©.assets[&item.graphic().unwrap().asset]; - assert_eq!(designcraft_render::pdf_layers(&asset.data), expected, "{location}: placement {id}"); + assert_eq!(designcraft_render::pdf_layers(&asset.data.load().unwrap()), expected, "{location}: placement {id}"); assert_ne!(asset.id, original_asset); assert!(asset.link.is_none()); assert!(!item.pdf_layer_override && item.pdf_hidden_layers.is_empty()); } assert_eq!(copy.item(control).unwrap().graphic().unwrap().asset, original_asset); assert!(Arc::ptr_eq(©.assets[&original_asset], &source.assets[&original_asset])); - assert_eq!(designcraft_render::pdf_layers(&source.assets[&original_asset].data), states(true, false)); + assert_eq!(designcraft_render::pdf_layers(&source.assets[&original_asset].data.load().unwrap()), states(true, false)); assert!(source.placed_items().into_iter().filter(|i| ids.contains(&i.id)).all(|i| i.has_pdf_layer_override())); } @@ -741,8 +950,12 @@ mod nested_layer_tests { let result = session.execute("file.exportIdml", &json!({})).unwrap(); let bytes = base64_decode(result["base64"].as_str().unwrap()); let imported = designcraft_idml::import_idml(&bytes).unwrap(); - let mut roundtrip: Vec<_> = - imported.assets.values().filter(|a| designcraft_render::is_pdf(&a.data)).map(|a| designcraft_render::pdf_layers(&a.data)).collect(); + let mut roundtrip: Vec<_> = imported + .assets + .values() + .filter(|a| designcraft_render::is_pdf(&a.data.load().unwrap())) + .map(|a| designcraft_render::pdf_layers(&a.data.load().unwrap())) + .collect(); let mut expected = vec![states(true, false), states(false, true), states(true, true)]; roundtrip.sort(); expected.sort(); @@ -798,8 +1011,8 @@ mod nested_layer_tests { session.execute("file.exportIdml", &json!({"embedImages": false})).unwrap(); } - // Duplicating a text frame that holds an anchored placed PDF leaves two placements sharing - // one ItemId (renumber gap, tracked separately). Export must still apply the choice to both. + // Duplicating a text frame that holds an anchored placed PDF copies the placement under a + // fresh id (#1522). Export must apply the choice to both. #[test] fn duplicated_frame_keeps_its_anchored_pdf_choice_in_idml() { let pdf = designcraft_render::pdf_hide_layers(&super::super::pdflayers::tests::two_layer_pdf(), &["Red".into()]).unwrap(); @@ -821,18 +1034,23 @@ mod nested_layer_tests { s.execute("transform.move", &json!({"ids": [frame.0], "dx": 10, "dy": 10, "copy": true})).unwrap(); let doc = s.doc().unwrap().doc.clone(); let with_choice: Vec<_> = doc.placed_items().into_iter().filter(|i| i.has_pdf_layer_override()).map(|i| i.id).collect(); - assert_eq!(with_choice, [chosen, chosen], "both placements share one id"); - assert!(doc.check().unwrap_err().to_string().contains(&format!("duplicate item id {chosen}"))); + assert_eq!(with_choice.len(), 2); + assert!(with_choice.contains(&chosen) && with_choice[0] != with_choice[1], "{with_choice:?}"); + doc.check().unwrap(); let result = s.execute("file.exportIdml", &json!({})).unwrap(); let imported = designcraft_idml::import_idml(&base64_decode(result["base64"].as_str().unwrap())).unwrap(); - let mut layers: Vec<_> = - imported.assets.values().filter(|a| designcraft_render::is_pdf(&a.data)).map(|a| designcraft_render::pdf_layers(&a.data)).collect(); + let mut layers: Vec<_> = imported + .assets + .values() + .filter(|a| designcraft_render::is_pdf(&a.data.load().unwrap())) + .map(|a| designcraft_render::pdf_layers(&a.data.load().unwrap())) + .collect(); layers.sort(); assert_eq!(layers, vec![states(false, true), states(true, false)]); } - // Shared anchored ids are a pre-existing duplication gap. Conflicting choices must not - // silently select one variant; this fixture changes only the copied anchor's choice. + // Duplication no longer shares anchored ids (#1522), so this fixture forces the shared id. + // Conflicting choices must not silently select one variant; only the copy's choice changes. #[test] fn shared_id_with_divergent_pdf_choices_is_rejected() { let mut s = Session::new(); @@ -840,23 +1058,25 @@ mod nested_layer_tests { let pdf = designcraft_render::pdf_hide_layers(&super::super::pdflayers::tests::two_layer_pdf(), &["Red".into()]).unwrap(); let placed = s.execute("file.place", &json!({"base64": base64_encode(&pdf), "name": "layers.pdf"})).unwrap(); let control = ItemId(placed["id"].as_u64().unwrap()); - let frame = { + let (frame, anchored) = { let doc = Arc::make_mut(&mut s.doc_mut().unwrap().doc); let mut item = doc.item(control).unwrap().clone(); item.id = ItemId(doc.alloc()); item.pdf_hidden_layers = vec!["Blue".into()]; + let anchored = item.id; let layer = doc.default_layer(); let (frame, sid) = doc.add_text_frame(SpreadRef::Doc(0), Rect::new(0.0, 0.0, 200.0, 200.0), layer, "Body", Default::default()).unwrap(); doc.story_mut(sid).unwrap().insert_object(0, AnchoredObject { item, position: Default::default() }); - frame + (frame, anchored) }; s.execute("transform.move", &json!({"ids": [frame.0], "dx": 10, "dy": 10, "copy": true})).unwrap(); - // Change ONLY the copy in the newest story to explicit all-on. + // Give ONLY the copy in the newest story the original's id and explicit all-on. { let doc = Arc::make_mut(&mut s.doc_mut().unwrap().doc); let (_, st) = doc.stories.iter_mut().filter(|(_, st)| !st.objects.is_empty()).last().unwrap(); let o = &mut Arc::make_mut(st).objects[0]; let it = &mut Arc::make_mut(o).item; + it.id = anchored; it.pdf_hidden_layers.clear(); it.pdf_layer_override = true; } @@ -871,8 +1091,8 @@ mod nested_layer_tests { assert!(Arc::ptr_eq(&before, &s.doc().unwrap().doc)); } - // Cross-document paste: the pasted frame's anchored placement keeps its source id, - // which can collide with an unrelated placement in the destination. + // Cross-document paste used to keep the anchored placement's source id (#1522), colliding + // with an unrelated placement in the destination. The fixture forces that collision. #[test] fn shared_id_with_different_pdf_assets_is_rejected() { let mut s = Session::new(); @@ -893,7 +1113,13 @@ mod nested_layer_tests { .as_u64() .unwrap(); s.execute("edit.paste", &json!({})).unwrap(); - assert_eq!(a, b, "fresh documents allocate the same first placement id"); + { + let doc = Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let (_, st) = doc.stories.iter_mut().find(|(_, st)| !st.objects.is_empty()).unwrap(); + let pasted = &mut Arc::make_mut(&mut Arc::make_mut(st).objects[0]).item; + assert_ne!(pasted.id.0, b, "paste gives the anchored placement a fresh id"); + pasted.id = ItemId(b); + } let before = s.doc().unwrap().doc.clone(); let graphics: Vec<_> = before.placed_items().into_iter().filter(|i| i.graphic().is_some()).collect(); assert_eq!(graphics.len(), 2); diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index 5ec6abb4d..8833f3b71 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -20,3 +20,7 @@ pub use sections::chapter_numbering; #[cfg(test)] #[path = "parent_delete_tests.rs"] mod parent_delete_tests; + +#[cfg(test)] +#[path = "parent_resize_tests.rs"] +mod parent_resize_tests; diff --git a/crates/engine/src/cmd/layout/layers.rs b/crates/engine/src/cmd/layout/layers.rs index 80fbc9d28..8e4a92c4b 100644 --- a/crates/engine/src/cmd/layout/layers.rs +++ b/crates/engine/src/cmd/layout/layers.rs @@ -1,4 +1,9 @@ -use super::{LAYER_COLORS, LayerId, Result, Session, Value, bad, ok}; +use std::collections::{HashMap, HashSet}; +use std::sync::Arc; + +use designcraft_doc::{Guide, Hyperlink, HyperlinkSource, Item, ItemId, SpreadRef, Story, StoryId}; + +use super::{LAYER_COLORS, Layer, LayerId, Result, Session, Value, bad, json, ok}; /// Layer Options: every field in one undo step; a bad name or colour changes nothing. pub(super) fn set_layer(s: &mut Session, p: &Value) -> Result { @@ -24,7 +29,7 @@ pub(super) fn set_layer(s: &mut Session, p: &Value) -> Result { Some(v) => v.as_bool().map(Some).ok_or_else(|| bad(ID, format!("`{k}` is true or false"))), }; let (visible, locked, printable) = (flag("visible")?, flag("locked")?, flag("printable")?); - let (guides, wrap) = (flag("showGuides")?, flag("suppressWrapWhenHidden")?); + let (guides, lock_guides, wrap) = (flag("showGuides")?, flag("lockGuides")?, flag("suppressWrapWhenHidden")?); s.edit(|d, _| { if let Some(n) = &name && d.layers.iter().any(|l| l.id != id && l.name == *n) @@ -43,6 +48,7 @@ pub(super) fn set_layer(s: &mut Session, p: &Value) -> Result { (&mut l.locked, locked), (&mut l.printable, printable), (&mut l.show_guides, guides), + (&mut l.lock_guides, lock_guides), (&mut l.suppress_wrap_when_hidden, wrap), ] { if let Some(v) = v { @@ -53,6 +59,325 @@ pub(super) fn set_layer(s: &mut Session, p: &Value) -> Result { }) } +/// Duplicate Layer: a new layer above `id` with its settings and a copy of every object on it, on document and parent +/// spreads, in one undo step. Copied text frames stay threaded to the other copied frames of their story, and each copy +/// of a story holds all of its text. A copied override of a parent item overrides that item's copy, or is detached when +/// the parent item is on another layer. Pages hide a parent item's copy where they hide the parent item. Hyperlinks on +/// copied objects and text get copies that go to the same destinations. +pub(super) fn duplicate_layer(s: &mut Session, p: &Value) -> Result { + const ID: &str = "layer.duplicate"; + let id = LayerId(p.get("id").and_then(Value::as_u64).ok_or_else(|| bad(ID, "missing id"))?); + let r = s.edit(|d, _| { + let i = d.layers.iter().position(|l| l.id == id).ok_or_else(|| bad(ID, "no such layer"))?; + let mut seen = HashMap::new(); + if d.spreads.iter().chain(&d.parents).flat_map(|sp| sp.items.iter()).any(|it| it.layer == id && too_deep(it, d, &mut seen)) { + return Err(bad(ID, "the layer's objects are nested too deeply to copy")); + } + let new_id = LayerId(d.alloc()); + let mut layer = d.layers[i].clone(); + layer.id = new_id; + layer.name = copy_name(&d.layers, &layer.name); + d.layers.insert(i, layer); + let src = d.clone(); + let mut stories = HashMap::new(); + let mut ids = HashMap::new(); + let refs = (0..src.parents.len()).map(SpreadRef::Parent).chain((0..src.spreads.len()).map(SpreadRef::Doc)); + let mut copies = Vec::new(); + for r in refs { + let Some(sp) = src.spread(r) else { continue }; + for it in sp.items.iter().filter(|it| it.layer == id) { + let mut copy = Item::clone(it); + if !super::super::object::renumber(d, &src, &mut copy, &mut stories) { + return Err(bad(ID, "the layer's objects are nested too deeply to copy")); + } + map_ids(it, ©, &mut ids); + copies.push((r, copy)); + } + } + // The story copies hold copies of the original's anchored objects with ids of their own (and copies of the + // stories of anchored text frames): record each copy's id against the original's. + for (old, new) in &stories { + if let (Some(orig), Some(copy)) = (src.story(*old), d.story(*new)) { + map_anchored(orig, copy, &mut ids); + } + } + // Every copy, anchored objects included, has its id before overrides are pointed at the copied parent items and + // live captions at the copied objects. + for (r, mut copy) in copies { + move_copy(&mut copy, new_id, &ids); + d.insert_item(r, copy, None)?; + } + for new in stories.values() { + if let Some(st) = d.story_mut(*new) { + move_anchored(st, new_id, &ids); + } + } + // Each story copy gets its frames in the original order, text anchors of its own, which its cross-references + // and those of the other copies point at, and tables with ids of their own, the tables in its cells and notes + // included, allocated in story order. + let mut anchors = HashMap::new(); + // The copies' own anchors are given ids below, so only the other stories' anchors count as taken. + let copied: HashSet = stories.values().copied().collect(); + let mut used = HashSet::new(); + for st in d.stories.values().filter(|st| !copied.contains(&st.id)) { + anchor_ids(st, &mut used); + } + let mut order: Vec<(StoryId, StoryId)> = stories.iter().map(|(old, new)| (*old, *new)).collect(); + order.sort_unstable_by_key(|(_, new)| *new); + for (old, new) in &order { + let Some(mut st) = d.story(*new).cloned() else { continue }; + if let Some((parent, revision)) = st.link { + st.link = Some((stories.get(&parent).copied().unwrap_or(parent), revision)); + } + st.frames = src.story(*old).map(|o| o.frames.iter().filter_map(|f| ids.get(f).copied()).collect()).unwrap_or_default(); + // The copy's anchors may already have new ids: each is keyed by the id of the original's anchor, which the + // copied cross-references still point at. + let originals: Vec = src.story(*old).map(|o| o.anchors.iter().map(|a| a.id).collect()).unwrap_or_default(); + for ((k, a), orig_id) in (1..).zip(st.anchors.iter_mut()).zip(originals) { + // `story id << 24 | n`, as anchors are made, or a new id when another anchor has that one or the story id + // does not fit. + let made = new.0.checked_mul(1 << 24).and_then(|base| base.checked_add(k)).filter(|id| !used.contains(id)); + let id = match made { + Some(id) => id, + None => loop { + let id = d.alloc(); + if !used.contains(&id) { + break id; + } + }, + }; + anchors.insert(orig_id, id); + used.insert(id); + Arc::make_mut(a).id = id; + } + renumber_tables(d, &mut st); + renumber_nested_anchors(d, &mut st, &mut anchors, &mut used); + d.stories.insert(*new, Arc::new(st)); + } + for new in stories.values() { + if let Some(st) = d.story_mut(*new) { + remap_xrefs(st, &anchors); + } + } + // The hyperlinks of copied objects and copied text get copies with ids of their own and the same destinations. + let links: Vec<_> = src + .hyperlinks + .iter() + .filter_map(|h| { + let source = match &h.source { + HyperlinkSource::Item { id } => HyperlinkSource::Item { id: *ids.get(id)? }, + HyperlinkSource::Text { story, start, end } => HyperlinkSource::Text { story: *stories.get(story)?, start: *start, end: *end }, + }; + Some((h, source)) + }) + .collect(); + for (h, source) in links { + let id = d.alloc(); + d.hyperlinks.push(Hyperlink { id, source, ..h.clone() }); + } + // A page, document or parent, hides a parent item's copy where it hides the parent item, and its ruler guides on + // the layer get copies on the new layer. + let hidden = |pg: &designcraft_doc::Page| -> Vec { pg.overridden.iter().filter_map(|o| ids.get(o).copied()).collect() }; + for sp in d.spreads.iter_mut().chain(d.parents.iter_mut()) { + if sp.pages.iter().all(|pg| hidden(pg).is_empty() && pg.guides.iter().all(|g| g.layer != Some(id))) { + continue; + } + for pg in &mut Arc::make_mut(sp).pages { + let copies = hidden(pg); + pg.overridden.extend(copies); + let guides: Vec<_> = pg.guides.iter().filter(|g| g.layer == Some(id)).map(|g| Guide { layer: Some(new_id), ..g.clone() }).collect(); + pg.guides.extend(guides); + } + } + Ok(new_id) + })?; + s.doc_mut()?.active_layer = r; + Ok(json!({"id": r.0})) +} + +/// The name of a copy of layer `name`: " copy", then " copy 2" and up while a layer has the name. +fn copy_name(layers: &[Layer], name: &str) -> String { + let base = format!("{name} copy"); + let taken = |n: &str| layers.iter().any(|l| l.name == n); + if !taken(&base) { + return base; + } + (2..).map(|k| format!("{base} {k}")).find(|n| !taken(n)).unwrap_or(base) +} + +/// Record each id of `orig` and its descendants against the matching id in `copy`. +fn map_ids(orig: &Item, copy: &Item, ids: &mut HashMap) { + ids.insert(orig.id, copy.id); + for (o, c) in orig.children().iter().zip(copy.children()) { + map_ids(o, c, ids); + } +} + +/// A layer whose groups, anchored objects, table cells and notes nest deeper than this, counted from an object on a +/// spread through the stories its anchored text frames show, is not duplicated. +const MAX_COPY_DEPTH: usize = 64; + +/// Whether `it`, with the stories its text frames reach directly or through anchored text frames, nests groups, +/// anchored objects, table cells and notes deeper than [`MAX_COPY_DEPTH`] in all: a story counts from the depth of the +/// frame that shows it, as copying it recurses on from there. `seen` holds the deepest level each story was checked at; +/// a story reached again no deeper is skipped. +fn too_deep(it: &Item, d: &designcraft_doc::Document, seen: &mut HashMap) -> bool { + fn item(it: &Item, depth: usize, next: &mut Vec<(StoryId, usize)>) -> bool { + if let Some(t) = it.text_frame() { + next.push((t.story, depth)); + } + depth > MAX_COPY_DEPTH || it.children().iter().any(|c| item(c, depth + 1, next)) + } + fn story(st: &Story, depth: usize, next: &mut Vec<(StoryId, usize)>) -> bool { + depth > MAX_COPY_DEPTH + || st.objects.iter().any(|o| item(&o.item, depth + 1, next)) + || st.tables.values().flat_map(|t| &t.cells).any(|c| story(&c.text, depth + 1, next)) + || st.notes.iter().chain(&st.endnotes).any(|n| story(&n.text, depth + 1, next)) + } + let mut next = Vec::new(); + if item(it, 0, &mut next) { + return true; + } + while let Some((sid, depth)) = next.pop() { + if seen.get(&sid).is_some_and(|&checked| checked >= depth) { + continue; + } + seen.insert(sid, depth); + if let Some(st) = d.story(sid) + && story(st, depth, &mut next) + { + return true; + } + } + false +} + +/// Run [`map_ids`] on the items anchored in story `orig` and in its copy `copy`, and in the stories of their table cells +/// and notes. [`too_deep`] bounds the nesting. +fn map_anchored(orig: &Story, copy: &Story, ids: &mut HashMap) { + for (o, c) in orig.objects.iter().zip(©.objects) { + map_ids(&o.item, &c.item, ids); + } + // Copied tables have new ids, given in the order of the old ones, so the two maps list them in the same order. + for (t, ct) in orig.tables.values().zip(copy.tables.values()) { + for (o, c) in t.cells.iter().zip(&ct.cells) { + map_anchored(&o.text, &c.text, ids); + } + } + for (o, c) in orig.notes.iter().chain(&orig.endnotes).zip(copy.notes.iter().chain(©.endnotes)) { + map_anchored(&o.text, &c.text, ids); + } +} + +/// Give the tables of `st`, and the tables in the stories of its table cells and notes, new ids from `d`, and point the +/// paragraphs that hold them at the new ids. [`too_deep`] bounds the nesting. +fn renumber_tables(d: &mut designcraft_doc::Document, st: &mut Story) { + let mut tables = HashMap::new(); + for (t, mut table) in std::mem::take(&mut st.tables) { + let n = d.alloc(); + let table_mut = Arc::make_mut(&mut table); + table_mut.id = n; + for c in &mut table_mut.cells { + renumber_tables(d, &mut c.text); + } + tables.insert(t, n); + st.tables.insert(n, table); + } + for pf in &mut st.paras { + pf.table = pf.table.and_then(|t| tables.get(&t).copied()); + } + for n in st.notes.iter_mut().chain(st.endnotes.iter_mut()) { + renumber_tables(d, &mut Arc::make_mut(n).text); + } +} + +/// Add the ids of the text anchors in `st`, and in the stories of its table cells and notes at any depth, to `used`. +/// The walk keeps its own stack, so a story on another layer that nests deeper than [`too_deep`] allows is read too. +fn anchor_ids(st: &Story, used: &mut HashSet) { + let mut stack = vec![st]; + while let Some(st) = stack.pop() { + used.extend(st.anchors.iter().map(|a| a.id)); + stack.extend(st.tables.values().flat_map(|t| t.cells.iter().map(|c| &c.text))); + stack.extend(st.notes.iter().chain(st.endnotes.iter()).map(|n| &n.text)); + } +} + +/// Give the text anchors in the stories of the table cells and notes of `st` new ids from `d` that are not in `used` +/// (recorded in `anchors` and `used`). [`too_deep`] bounds the nesting. +fn renumber_nested_anchors(d: &mut designcraft_doc::Document, st: &mut Story, anchors: &mut HashMap, used: &mut HashSet) { + fn child(d: &mut designcraft_doc::Document, st: &mut Story, anchors: &mut HashMap, used: &mut HashSet) { + for anchor in &mut st.anchors { + let id = loop { + let id = d.alloc(); + if used.insert(id) { + break id; + } + }; + anchors.insert(anchor.id, id); + Arc::make_mut(anchor).id = id; + } + renumber_nested_anchors(d, st, anchors, used); + } + for table in st.tables.values_mut() { + for cell in &mut Arc::make_mut(table).cells { + child(d, &mut cell.text, anchors, used); + } + } + for note in st.notes.iter_mut().chain(st.endnotes.iter_mut()) { + child(d, &mut Arc::make_mut(note).text, anchors, used); + } +} + +/// Point the cross-references in `st`, and in the stories of its table cells and notes, at the anchors `map` gives for +/// their targets. [`too_deep`] bounds the nesting. +fn remap_xrefs(st: &mut Story, map: &HashMap) { + for x in &mut st.xrefs { + if let Some(n) = map.get(&x.target) { + Arc::make_mut(x).target = *n; + } + } + for t in st.tables.values_mut() { + for c in &mut Arc::make_mut(t).cells { + remap_xrefs(&mut c.text, map); + } + } + for n in st.notes.iter_mut().chain(st.endnotes.iter_mut()) { + remap_xrefs(&mut Arc::make_mut(n).text, map); + } +} + +/// Put `it` and its descendants on layer `to`, and point overrides at the copied parent items and live captions at the +/// copied objects. A copy whose parent item was not copied is detached from it, so the original override stays the only +/// one of that item. +fn move_copy(it: &mut Item, to: LayerId, ids: &HashMap) { + it.layer = to; + it.overrides = it.overrides.and_then(|o| ids.get(&o).copied()); + if let Some(c) = &mut it.live_caption + && let Some(n) = ids.get(&c.source) + { + c.source = *n; + } + for c in it.children_mut().into_iter().flatten() { + move_copy(Arc::make_mut(c), to, ids); + } +} + +/// Run [`move_copy`] on the anchored objects of `st` and of the stories of its table cells and notes. [`too_deep`] bounds +/// the nesting. +fn move_anchored(st: &mut Story, to: LayerId, ids: &HashMap) { + for o in &mut st.objects { + move_copy(&mut Arc::make_mut(o).item, to, ids); + } + for t in st.tables.values_mut() { + for c in &mut Arc::make_mut(t).cells { + move_anchored(&mut c.text, to, ids); + } + } + for n in st.notes.iter_mut().chain(st.endnotes.iter_mut()) { + move_anchored(&mut Arc::make_mut(n).text, to, ids); + } +} + #[cfg(test)] mod layer_tests { use serde_json::json; @@ -96,6 +421,770 @@ mod layer_tests { assert_eq!(d.layers.len(), 1); assert_eq!(d.item(designcraft_doc::ItemId(f)).unwrap().layer.0, l4); } + + fn on_layer(d: &designcraft_doc::Document, layer: u64) -> Vec> { + d.spreads.iter().chain(&d.parents).flat_map(|sp| sp.items.iter().filter(|i| i.layer.0 == layer).cloned()).collect() + } + + #[test] + fn duplicate_layer_copies_settings_and_objects_above_the_original() { + let mut s = crate::Session::new(); + s.execute("file.new", &json!({"pages": 2, "facingPages": false})).unwrap(); + let base = s.doc().unwrap().doc.layers[0].id.0; + let art = s.execute("layer.new", &json!({"name": "Art"})).unwrap()["id"].as_u64().unwrap(); + s.execute("layer.set", &json!({"id": art, "color": "Red", "printable": false, "showGuides": false})).unwrap(); + let rect = s.execute("frame.create", &json!({"rect": [10, 10, 50, 50]})).unwrap()["id"].as_u64().unwrap(); + s.execute("frame.create", &json!({"spread": 1, "rect": [10, 10, 60, 60]})).unwrap(); + s.execute("guide.add", &json!({"orientation": "horizontal", "position": 200, "page": 0, "liquid": true})).unwrap(); + s.execute("layer.activate", &json!({"id": base})).unwrap(); + s.execute("frame.create", &json!({"rect": [100, 100, 150, 150]})).unwrap(); + s.execute("guide.add", &json!({"orientation": "vertical", "position": 300, "page": 0})).unwrap(); + s.execute("layer.set", &json!({"id": art, "locked": true})).unwrap(); + let before = s.doc().unwrap().doc.clone(); + let copy = s.execute("layer.duplicate", &json!({"id": art})).unwrap()["id"].as_u64().unwrap(); + let d = s.doc().unwrap().doc.clone(); + assert_eq!(d.layers.iter().map(|l| l.id.0).collect::>(), [copy, art, base], "the copy sits right above the original"); + let (l, o) = (d.layer(designcraft_doc::LayerId(copy)).unwrap(), d.layer(designcraft_doc::LayerId(art)).unwrap()); + assert_eq!(l.name, "Art copy"); + assert_eq!((l.color, l.visible, l.locked, l.printable, l.show_guides), (o.color, o.visible, o.locked, o.printable, o.show_guides)); + assert_eq!(s.doc().unwrap().active_layer.0, copy); + let (orig, copies) = (on_layer(&d, art), on_layer(&d, copy)); + assert_eq!(copies.len(), 2, "both spreads' objects"); + for (a, b) in orig.iter().zip(&copies) { + assert_ne!(a.id, b.id); + assert_eq!((a.xf, a.path.clone()), (b.xf, b.path.clone())); + assert_eq!(d.find(a.id).unwrap().spread, d.find(b.id).unwrap().spread); + } + assert_eq!(on_layer(&d, base).len(), 1, "other layers' objects stay as they were"); + let guides = &d.spreads[0].pages[0].guides; + assert_eq!(guides.len(), 3, "Art's guide gets a copy; the base layer's does not"); + let (g, c) = (&guides[0], &guides[2]); + assert_eq!((g.layer, c.layer), (Some(designcraft_doc::LayerId(art)), Some(designcraft_doc::LayerId(copy)))); + assert_eq!((g.orientation, g.position, g.liquid), (c.orientation, c.position, c.liquid)); + assert!(d.item(designcraft_doc::ItemId(rect)).is_some()); + // A second copy gets a name of its own; bad ids change nothing. + s.execute("layer.duplicate", &json!({"id": art})).unwrap(); + assert_eq!(s.doc().unwrap().doc.layers[1].name, "Art copy 2"); + s.execute("edit.undo", &json!({})).unwrap(); + for bad in [json!({"id": 999}), json!({})] { + assert!(s.execute("layer.duplicate", &bad).is_err(), "{bad}"); + } + // One undo step. + s.execute("edit.undo", &json!({})).unwrap(); + let d = &s.doc().unwrap().doc; + assert_eq!(d.layers, before.layers); + assert_eq!(d.all_items(), before.all_items()); + } + + #[test] + fn duplicate_layer_keeps_linked_story_parents_with_their_copies() { + for copy_parent in [true, false] { + let mut s = crate::Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let parent = s.execute("frame.create", &json!({"rect": [0, 0, 100, 100], "content": "text", "text": "Original"})).unwrap(); + let layer = if copy_parent { + s.doc().unwrap().active_layer.0 + } else { + s.execute("layer.new", &json!({"name": "Linked"})).unwrap()["id"].as_u64().unwrap() + }; + let child = s.execute("story.placeAndLink", &json!({"story": parent["story"], "rect": [100, 0, 200, 100]})).unwrap(); + let copy = s.execute("layer.duplicate", &json!({"id": layer})).unwrap()["id"].as_u64().unwrap(); + let d = &s.doc().unwrap().doc; + let copies = on_layer(d, copy); + let copied_stories: Vec<_> = copies.iter().map(|item| d.story(item.text_frame().unwrap().story).unwrap()).collect(); + let copied_child = copied_stories.iter().find(|story| story.link.is_some()).unwrap().id; + let expected_parent = if copy_parent { + copied_stories.iter().find(|story| story.link.is_none()).unwrap().id + } else { + designcraft_doc::StoryId(parent["story"].as_u64().unwrap()) + }; + assert_eq!(d.story(copied_child).unwrap().link.unwrap().0, expected_parent); + s.execute("story.setText", &json!({"story": expected_parent.0, "text": "Edited source"})).unwrap(); + s.execute("story.updateLink", &json!({"story": copied_child.0})).unwrap(); + assert_eq!(s.doc().unwrap().doc.story(copied_child).unwrap().text, "Edited source"); + assert_eq!(s.doc().unwrap().doc.story(designcraft_doc::StoryId(child["story"].as_u64().unwrap())).unwrap().text, "Original"); + if copy_parent { + s.execute("story.setText", &json!({"story": parent["story"], "text": "Edited original"})).unwrap(); + s.execute("story.updateLink", &json!({"story": copied_child.0})).unwrap(); + assert_eq!(s.doc().unwrap().doc.story(copied_child).unwrap().text, "Edited source"); + } + } + } + + #[test] + fn duplicate_layer_keeps_threads_on_the_layer_only() { + let mut s = crate::Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let base = s.doc().unwrap().doc.layers[0].id.0; + let text = |s: &mut crate::Session, rect: [f64; 4], t: &str| { + s.execute("frame.create", &json!({"rect": rect, "content": "text", "text": t})).unwrap()["id"].as_u64().unwrap() + }; + // a → b on Base, c on Art at the end of the same thread. + let b = text(&mut s, [10.0, 200.0, 100.0, 240.0], ""); + let a = text(&mut s, [10.0, 10.0, 100.0, 50.0], "One two three four five six seven eight nine ten eleven twelve"); + s.execute("text.thread", &json!({"from": a, "to": b})).unwrap(); + let art = s.execute("layer.new", &json!({"name": "Art"})).unwrap()["id"].as_u64().unwrap(); + let c = text(&mut s, [300.0, 10.0, 400.0, 50.0], ""); + s.execute("text.thread", &json!({"from": b, "to": c})).unwrap(); + let _ = art; + let copy = s.execute("layer.duplicate", &json!({"id": base})).unwrap()["id"].as_u64().unwrap(); + let d = s.doc().unwrap().doc.clone(); + let story = |id: u64| d.item(designcraft_doc::ItemId(id)).and_then(|i| i.text_frame()).map(|t| t.story).unwrap(); + let orig = d.story(story(a)).unwrap(); + assert_eq!(orig.frames.iter().map(|f| f.0).collect::>(), [a, b, c], "the original thread is unchanged"); + let copies = on_layer(&d, copy); + assert_eq!(copies.len(), 2); + let sid = copies[0].text_frame().unwrap().story; + assert_eq!(copies[1].text_frame().unwrap().story, sid, "the copies share one story"); + let st = d.story(sid).unwrap(); + assert_ne!(sid, orig.id); + assert_eq!(st.text, orig.text, "the copy holds the whole text"); + // Thread order as in the original (a's copy first, though b's copy was made first), without c. + let pos = |id: designcraft_doc::ItemId| d.find(id).map(|l| l.path.clone()); + let order: Vec<_> = st.frames.iter().map(|f| d.item(*f).unwrap().path.clone()).collect(); + let want: Vec<_> = [a, b].iter().map(|f| d.item(designcraft_doc::ItemId(*f)).unwrap().path.clone()).collect(); + assert_eq!(order, want); + assert!(st.frames.iter().all(|f| pos(*f).is_some())); + } + + #[test] + fn duplicate_layer_copies_parent_items_and_their_overrides() { + let mut s = crate::Session::new(); + s.execute("file.new", &json!({"pages": 3, "facingPages": false})).unwrap(); + let base = s.doc().unwrap().doc.layers[0].id.0; + let folio = json!({"spread": {"kind": "parent", "index": 0}, "rect": [72, 720, 300, 750], "content": "text", "text": "Folio"}); + let parent = s.execute("frame.create", &folio).unwrap()["id"].as_u64().unwrap(); + let o = s.execute("layout.overrideParentItems", &json!({"page": 1})).unwrap()["ids"][0].as_u64().unwrap(); + // Page 3's override is deleted, which keeps the parent item hidden there. + let gone = s.execute("layout.overrideParentItems", &json!({"page": 2})).unwrap()["ids"][0].as_u64().unwrap(); + s.execute("selection.set", &json!({"ids": [gone]})).unwrap(); + s.execute("edit.clear", &json!({})).unwrap(); + // Parent B, based on A, hides the folio on its page. + s.execute("layout.parents.new", &json!({"prefix": "B"})).unwrap(); + s.edit(|d, _| { + let a = d.parents[0].id; + let bp = std::sync::Arc::make_mut(&mut d.parents[1]); + bp.parent.as_mut().unwrap().based_on = Some(a); + bp.pages[0].parent = Some(a); + bp.pages[0].overridden.push(designcraft_doc::ItemId(parent)); + Ok(()) + }) + .unwrap(); + let copy = s.execute("layer.duplicate", &json!({"id": base})).unwrap()["id"].as_u64().unwrap(); + let d = s.doc().unwrap().doc.clone(); + let copies = on_layer(&d, copy); + assert_eq!(copies.len(), 2, "the parent item and page 2's override"); + let p2 = copies.iter().find(|i| matches!(d.find(i.id).unwrap().spread, designcraft_doc::SpreadRef::Parent(0))).unwrap(); + let o2 = copies.iter().find(|i| i.overrides.is_some()).unwrap(); + assert_ne!((p2.id.0, o2.id.0), (parent, o)); + assert_eq!(o2.overrides, Some(p2.id), "the override's copy overrides the parent item's copy"); + assert_eq!(d.page_of_item(o2.id), Some(1)); + let overridden = |page: usize| { + let (si, pi) = d.page_loc(page).unwrap(); + d.spreads[si].pages[pi].overridden.clone() + }; + assert_eq!(overridden(1), [designcraft_doc::ItemId(parent), p2.id], "page 2 hides both parent items"); + assert_eq!(overridden(2), [designcraft_doc::ItemId(parent), p2.id], "page 3 too, without an override"); + assert!(overridden(0).is_empty(), "page 1 shows both"); + assert_eq!(d.parents[1].pages[0].overridden, [designcraft_doc::ItemId(parent), p2.id], "parent B hides both"); + } + + #[test] + fn duplicate_layer_moves_whole_groups_and_finds_later_parent_items() { + let mut s = crate::Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let base = s.doc().unwrap().doc.layers[0].id.0; + let a = s.execute("frame.create", &json!({"rect": [0, 0, 10, 10]})).unwrap()["id"].as_u64().unwrap(); + s.execute("layer.new", &json!({"name": "Art"})).unwrap(); + let b = s.execute("frame.create", &json!({"rect": [20, 0, 30, 10]})).unwrap()["id"].as_u64().unwrap(); + // The group takes the base layer from its first member; b stays on Art inside it. + let g = s.execute("object.group", &json!({"ids": [a, b]})).unwrap()["id"].as_u64().unwrap(); + s.execute("layer.activate", &json!({"id": base})).unwrap(); + // Parent A's item overrides one on parent B, which comes after it in the document. + s.execute("layout.parents.new", &json!({"prefix": "B"})).unwrap(); + let on_b = + s.execute("frame.create", &json!({"spread": {"kind": "parent", "index": 1}, "rect": [0, 0, 50, 50]})).unwrap()["id"].as_u64().unwrap(); + let on_a = + s.execute("frame.create", &json!({"spread": {"kind": "parent", "index": 0}, "rect": [0, 0, 50, 50]})).unwrap()["id"].as_u64().unwrap(); + s.edit(|d, _| { + d.item_mut(designcraft_doc::ItemId(on_a)).unwrap().overrides = Some(designcraft_doc::ItemId(on_b)); + Ok(()) + }) + .unwrap(); + let d = s.doc().unwrap().doc.clone(); + let layer_of = |id: u64| d.item(designcraft_doc::ItemId(id)).unwrap().layer.0; + assert_eq!((layer_of(g), layer_of(b)), (base, d.layers.iter().find(|l| l.name == "Art").unwrap().id.0)); + let copy = s.execute("layer.duplicate", &json!({"id": base})).unwrap()["id"].as_u64().unwrap(); + let d = s.doc().unwrap().doc.clone(); + let copies = on_layer(&d, copy); + let group = copies.iter().find(|i| !i.children().is_empty()).unwrap(); + assert!(group.children().iter().all(|c| c.layer.0 == copy), "the copied group is on the new layer as a whole"); + let in_parent = + |i: usize| copies.iter().find(|c| matches!(d.find(c.id).unwrap().spread, designcraft_doc::SpreadRef::Parent(p) if p == i)).unwrap(); + assert_eq!(in_parent(0).overrides, Some(in_parent(1).id), "A's copy overrides B's copy"); + } + + #[test] + fn duplicate_layer_gives_anchored_objects_their_own_ids() { + let mut s = crate::Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let base = s.doc().unwrap().doc.layers[0].id.0; + let text = json!({"rect": [72, 72, 400, 400], "content": "text", "text": "Before after."}); + let f = s.execute("frame.create", &text).unwrap()["id"].as_u64().unwrap(); + let sid = s.doc().unwrap().doc.item(designcraft_doc::ItemId(f)).unwrap().text_frame().unwrap().story; + let b = s.execute("frame.create", &json!({"rect": [450, 450, 474, 490]})).unwrap()["id"].as_u64().unwrap(); + s.execute("anchored.insert", &json!({"ids": [b], "story": sid.0, "pos": 7})).unwrap(); + // Two anchored text frames threaded in one story, as IDML import makes them. + let threaded = s + .edit(|d, _| { + use designcraft_doc::{AnchoredObject, ParaFormat}; + let (r, r2) = (designcraft_geom::Rect::new(0.0, 0.0, 60.0, 30.0), designcraft_geom::Rect::new(0.0, 0.0, 80.0, 40.0)); + let (first, story) = d.add_text_frame(designcraft_doc::SpreadRef::Doc(0), r, d.default_layer(), "Symbol", ParaFormat::default())?; + let (second, spare) = d.add_text_frame(designcraft_doc::SpreadRef::Doc(0), r2, d.default_layer(), "", ParaFormat::default())?; + let mut items = Vec::new(); + for f in [first, second] { + let mut it = d.item(f).cloned().ok_or(designcraft_doc::DocError::NoItem(f))?; + if let designcraft_doc::Content::Text(tf) = &mut it.content { + tf.story = story; + } + items.push(it); + } + d.stories.remove(&spare); + d.story_mut(story).ok_or(designcraft_doc::DocError::NoStory(story))?.frames = vec![first, second]; + std::sync::Arc::make_mut(&mut d.spreads[0]).items.retain(|i| i.id != first && i.id != second); + let st = d.story_mut(sid).ok_or(designcraft_doc::DocError::NoStory(sid))?; + for it in items.into_iter().rev() { + st.insert_object(0, AnchoredObject::new(it, Default::default())); + } + Ok(story) + }) + .unwrap(); + s.doc().unwrap().doc.check().unwrap(); + let copy = s.execute("layer.duplicate", &json!({"id": base})).unwrap()["id"].as_u64().unwrap(); + let d = &s.doc().unwrap().doc; + d.check().unwrap(); + let symbols: Vec<_> = d.anchored_items().into_iter().filter_map(|(_, i)| i.text_frame().map(|t| (i.id, t.story))).collect(); + assert_eq!(symbols.len(), 4); + let copied = symbols.iter().map(|s| s.1).find(|s| *s != threaded).unwrap(); + let st = d.story(copied).unwrap(); + assert_eq!(st.text, "Symbol"); + assert_eq!(st.frames.len(), 2, "the copies share one story"); + let order = |story: &designcraft_doc::Story| story.frames.iter().map(|f| d.anchored_item(*f).unwrap().path.clone()).collect::>(); + assert_eq!(order(st), order(d.story(threaded).unwrap()), "in the original thread order"); + let anchored: Vec<_> = d.anchored_items().into_iter().filter(|(_, i)| i.text_frame().is_none()).map(|(_, i)| (i.id, i.layer.0)).collect(); + assert_eq!(anchored.len(), 2); + assert_ne!(anchored[0].0, anchored[1].0, "the copy's anchored object has an id of its own"); + let mut layers: Vec<_> = anchored.iter().map(|a| a.1).collect(); + layers.sort_unstable(); + let mut want = vec![base, copy]; + want.sort_unstable(); + assert_eq!(layers, want, "the copy's anchored object is on the new layer"); + } + + #[test] + fn duplicate_layer_points_copied_live_captions_at_the_copied_objects() { + let mut s = crate::Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let base = s.doc().unwrap().doc.layers[0].id.0; + let a = s.execute("frame.create", &json!({"rect": [72, 72, 272, 172]})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.altText", &json!({"text": "First", "ids": [a]})).unwrap(); + s.execute("object.caption", &json!({"ids": [a], "text": "Photo: {altText}", "live": true})).unwrap(); + let copy = s.execute("layer.duplicate", &json!({"id": base})).unwrap()["id"].as_u64().unwrap(); + let d = &s.doc().unwrap().doc; + let copies = on_layer(d, copy); + let frame = copies.iter().find(|i| i.live_caption.is_none()).unwrap(); + let caption = copies.iter().find_map(|i| i.live_caption.as_ref()).unwrap(); + assert_eq!(caption.source, frame.id, "the caption's copy follows the frame's copy"); + assert_ne!(frame.id.0, a); + } + + #[test] + fn duplicate_layer_points_copied_live_captions_at_copied_anchored_objects() { + let mut s = crate::Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let base = s.doc().unwrap().doc.layers[0].id.0; + let a = s.execute("frame.create", &json!({"rect": [450, 450, 474, 490]})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.caption", &json!({"ids": [a], "text": "{name}", "live": true})).unwrap(); + let text = json!({"rect": [72, 72, 400, 400], "content": "text", "text": "Before after."}); + let f = s.execute("frame.create", &text).unwrap()["id"].as_u64().unwrap(); + let sid = s.doc().unwrap().doc.item(designcraft_doc::ItemId(f)).unwrap().text_frame().unwrap().story; + // The caption's source moves into the story and keeps its id. + s.execute("anchored.insert", &json!({"ids": [a], "story": sid.0, "pos": 7})).unwrap(); + let copy = s.execute("layer.duplicate", &json!({"id": base})).unwrap()["id"].as_u64().unwrap(); + let d = &s.doc().unwrap().doc; + let anchored = d.anchored_items().into_iter().map(|(_, i)| i).find(|i| i.layer.0 == copy).unwrap(); + assert_ne!(anchored.id.0, a); + let copies = on_layer(d, copy); + let caption = copies.iter().find_map(|i| i.live_caption.as_ref()).unwrap(); + assert_eq!(caption.source, anchored.id, "the caption's copy follows the anchored object's copy"); + } + + #[test] + fn duplicate_layer_copies_the_hyperlinks_of_its_objects_and_text() { + use designcraft_doc::{HyperlinkDest, HyperlinkSource}; + let mut s = crate::Session::new(); + s.execute("file.new", &json!({"pages": 2})).unwrap(); + let base = s.doc().unwrap().doc.layers[0].id.0; + let a = s.execute("frame.create", &json!({"rect": [72, 72, 172, 172]})).unwrap()["id"].as_u64().unwrap(); + s.execute("hyperlink.create", &json!({"ids": [a], "url": "https://example.com/a", "name": "Logo"})).unwrap(); + let t = s.execute("frame.create", &json!({"rect": [72, 200, 400, 300], "content": "text", "text": "Read more here"})).unwrap(); + let sid = s.doc().unwrap().doc.item(designcraft_doc::ItemId(t["id"].as_u64().unwrap())).unwrap().text_frame().unwrap().story; + s.execute("text.select", &json!({"story": sid.0, "anchor": 5, "focus": 9})).unwrap(); + s.execute("hyperlink.create", &json!({"page": 2})).unwrap(); + s.execute("layer.new", &json!({"name": "Art"})).unwrap(); + let other = s.execute("frame.create", &json!({"rect": [300, 72, 400, 172]})).unwrap()["id"].as_u64().unwrap(); + s.execute("hyperlink.create", &json!({"ids": [other], "email": "info@example.com"})).unwrap(); + let before = s.doc().unwrap().doc.hyperlinks.clone(); + let copy = s.execute("layer.duplicate", &json!({"id": base})).unwrap()["id"].as_u64().unwrap(); + let d = s.doc().unwrap().doc.clone(); + assert_eq!(d.hyperlinks[..3], before[..], "the original hyperlinks are unchanged"); + let copies = on_layer(&d, copy); + let frame = copies.iter().find(|i| i.text_frame().is_none()).unwrap().id; + let story = copies.iter().find_map(|i| i.text_frame()).unwrap().story; + let added = &d.hyperlinks[3..]; + assert_eq!(added.len(), 2, "the other layer's hyperlink gets no copy"); + assert_eq!((&added[0].name, &added[0].source, &added[0].dest), (&before[0].name, &HyperlinkSource::Item { id: frame }, &before[0].dest)); + assert_eq!(added[1].source, HyperlinkSource::Text { story, start: 5, end: 9 }); + assert_eq!((&added[1].name, &added[1].dest), (&before[1].name, &HyperlinkDest::Page(1))); + let ids: std::collections::HashSet = d.hyperlinks.iter().map(|h| h.id).collect(); + assert_eq!(ids.len(), 5, "each copy has an id of its own"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc.hyperlinks, before, "one undo step removes the copies"); + } + + #[test] + fn duplicate_layer_gives_copied_text_anchors_their_own_ids() { + let mut s = crate::Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let base = s.doc().unwrap().doc.layers[0].id.0; + let text = json!({"rect": [72, 72, 400, 400], "content": "text", "text": "Heading\rSee "}); + let f = s.execute("frame.create", &text).unwrap()["id"].as_u64().unwrap(); + let sid = s.doc().unwrap().doc.item(designcraft_doc::ItemId(f)).unwrap().text_frame().unwrap().story; + let anchor = s + .edit(|d, _| { + let a = d.paragraph_anchor(sid, 0).ok_or(designcraft_doc::DocError::NoStory(sid))?; + let format = d.xref_formats[0].name.clone(); + let st = d.story_mut(sid).ok_or(designcraft_doc::DocError::NoStory(sid))?; + let end = st.len(); + st.insert_xref(end, designcraft_doc::CrossRef { target: a, format, ..Default::default() }); + Ok(a) + }) + .unwrap(); + let copy = s.execute("layer.duplicate", &json!({"id": base})).unwrap()["id"].as_u64().unwrap(); + let d = &s.doc().unwrap().doc; + let copied = on_layer(d, copy)[0].text_frame().unwrap().story; + let (orig, st) = (d.story(sid).unwrap(), d.story(copied).unwrap()); + assert_eq!((orig.anchors[0].id, orig.xrefs[0].target), (anchor, anchor), "the original is unchanged"); + assert_ne!(st.anchors[0].id, anchor, "the copy's anchor has an id of its own"); + assert_eq!(st.anchors[0].name, orig.anchors[0].name); + assert_eq!(st.xrefs[0].target, st.anchors[0].id, "the copied cross-reference points at the copied paragraph"); + assert_eq!(d.find_anchor(st.anchors[0].id).map(|a| a.0), Some(copied)); + } + + #[test] + fn duplicate_layer_gives_copied_text_anchors_ids_no_other_anchor_has() { + use std::sync::Arc; + + let mut s = crate::Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let base = s.doc().unwrap().doc.layers[0].id.0; + let f = s.execute("frame.create", &json!({"rect": [72, 72, 400, 400], "content": "text", "text": "Head"})).unwrap()["id"].as_u64().unwrap(); + let sid = s.doc().unwrap().doc.item(designcraft_doc::ItemId(f)).unwrap().text_frame().unwrap().story; + s.execute("layer.new", &json!({"name": "Art"})).unwrap(); + let g = s.execute("frame.create", &json!({"rect": [72, 450, 400, 600], "content": "text", "text": "Other"})).unwrap()["id"].as_u64().unwrap(); + let other = s.doc().unwrap().doc.item(designcraft_doc::ItemId(g)).unwrap().text_frame().unwrap().story; + let d = Arc::make_mut(&mut s.doc_mut().unwrap().doc); + d.story_mut(sid).unwrap().insert_anchor(0, "Heading"); + // A story on another layer holds the ids the copy's first anchor would take, as anchors loaded from a file can. + let next = d.next_id; + let st = d.story_mut(other).unwrap(); + for k in 1..=64 { + st.insert_anchor(0, "Taken"); + Arc::make_mut(&mut st.anchors[0]).id = ((next + k) << 24) + 1; + } + s.execute("layer.duplicate", &json!({"id": base})).unwrap(); + let d = &s.doc().unwrap().doc; + let all: Vec = d.stories.values().flat_map(|st| st.anchors.iter().map(|a| a.id)).collect(); + assert_eq!(all.len(), 66); + let unique: std::collections::HashSet<_> = all.iter().collect(); + assert_eq!(unique.len(), all.len(), "the copied anchor has an id no other anchor has"); + } + + #[test] + fn duplicate_layer_remaps_anchors_in_cells_and_notes() { + use designcraft_doc::Story; + use std::sync::Arc; + + fn add_anchor(st: &mut Story, id: u64) { + st.insert_anchor(0, "Nested heading"); + Arc::make_mut(&mut st.anchors[0]).id = id; + st.insert_xref(st.len(), designcraft_doc::CrossRef { target: id, ..Default::default() }); + } + fn collect(st: &Story, values: &mut Vec<(u64, u64)>) { + for (a, x) in st.anchors.iter().zip(st.xrefs.iter()) { + values.push((a.id, x.target)); + } + for table in st.tables.values() { + for cell in &table.cells { + collect(&cell.text, values); + } + } + for note in st.notes.iter().chain(st.endnotes.iter()) { + collect(¬e.text, values); + } + } + let mut s = crate::Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let base = s.doc().unwrap().doc.layers[0].id.0; + let f = s.execute("frame.create", &json!({"rect": [72, 72, 400, 400], "content": "text", "text": "Rows"})).unwrap()["id"].as_u64().unwrap(); + let sid = s.doc().unwrap().doc.item(designcraft_doc::ItemId(f)).unwrap().text_frame().unwrap().story; + let d = Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let table_id = d.alloc(); + let nested_id = d.alloc(); + let anchor_ids = [d.alloc(), d.alloc(), d.alloc(), d.alloc()]; + let mut table = designcraft_doc::Table::new(table_id, 1, 1, 0, 0, 40.0); + let cell = &mut table.cells[0].text; + add_anchor(cell, anchor_ids[0]); + let mut nested = designcraft_doc::Table::new(nested_id, 1, 1, 0, 0, 20.0); + add_anchor(&mut nested.cells[0].text, anchor_ids[1]); + cell.insert_table(cell.len(), nested); + cell.insert_note(cell.len(), "Footnote", Default::default()).unwrap(); + add_anchor(&mut Arc::make_mut(&mut cell.notes[0]).text, anchor_ids[2]); + cell.insert_endnote(cell.len(), "Endnote", Default::default()).unwrap(); + add_anchor(&mut Arc::make_mut(&mut cell.endnotes[0]).text, anchor_ids[3]); + d.story_mut(sid).unwrap().insert_table(0, table); + let mut original = Vec::new(); + collect(d.story(sid).unwrap(), &mut original); + assert_eq!(original.len(), 4); + let copy = s.execute("layer.duplicate", &json!({"id": base})).unwrap()["id"].as_u64().unwrap(); + let d = &s.doc().unwrap().doc; + let copied = on_layer(d, copy)[0].text_frame().unwrap().story; + let mut after = Vec::new(); + collect(d.story(copied).unwrap(), &mut after); + assert_eq!(after.len(), original.len()); + let unique: std::collections::HashSet<_> = after.iter().map(|(id, _)| *id).collect(); + assert_eq!(unique.len(), after.len()); + for (id, target) in &after { + assert!(!anchor_ids.contains(id), "copied nested anchor retains original id {id}"); + assert_eq!(id, target, "copied reference points to its copied anchor"); + } + let mut unchanged = Vec::new(); + collect(d.story(sid).unwrap(), &mut unchanged); + assert_eq!(unchanged, original); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.redo", &json!({})).unwrap(); + let mut redone = Vec::new(); + collect(s.doc().unwrap().doc.story(copied).unwrap(), &mut redone); + assert_eq!(redone, after); + } + + #[test] + fn duplicate_layer_gives_objects_anchored_in_endnotes_of_cells_their_own_ids() { + use designcraft_doc::AnchoredObject; + use std::sync::Arc; + + let mut s = crate::Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let base = s.doc().unwrap().doc.layers[0].id.0; + let a = s.execute("frame.create", &json!({"rect": [450, 450, 474, 490]})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.caption", &json!({"ids": [a], "text": "{name}", "live": true})).unwrap(); + let f = s.execute("frame.create", &json!({"rect": [72, 72, 400, 400], "content": "text", "text": "Rows"})).unwrap()["id"].as_u64().unwrap(); + let sid = s.doc().unwrap().doc.item(designcraft_doc::ItemId(f)).unwrap().text_frame().unwrap().story; + let d = Arc::make_mut(&mut s.doc_mut().unwrap().doc); + // The caption's source moves into an endnote of a table cell and keeps its id. + let it = d.item(designcraft_doc::ItemId(a)).cloned().unwrap(); + Arc::make_mut(&mut d.spreads[0]).items.retain(|i| i.id.0 != a); + let mut table = designcraft_doc::Table::new(d.alloc(), 1, 1, 0, 0, 40.0); + let cell = &mut table.cells[0].text; + cell.insert_endnote(cell.len(), "Endnote", Default::default()).unwrap(); + Arc::make_mut(&mut cell.endnotes[0]).text.insert_object(0, AnchoredObject::new(it, Default::default())); + d.story_mut(sid).unwrap().insert_table(0, table); + d.check().unwrap(); + let copy = s.execute("layer.duplicate", &json!({"id": base})).unwrap()["id"].as_u64().unwrap(); + let d = &s.doc().unwrap().doc; + d.check().unwrap(); + let anchored: Vec<_> = d.anchored_items().into_iter().map(|(_, i)| (i.id, i.layer.0)).collect(); + assert_eq!(anchored.len(), 2); + let copied = anchored.iter().find(|i| i.1 == copy).unwrap().0; + assert_ne!(copied.0, a, "the copy has an id of its own"); + let caption = on_layer(d, copy).iter().find_map(|i| i.live_caption.clone()).unwrap(); + assert_eq!(caption.source, copied, "the caption's copy follows the anchored object's copy"); + } + + #[test] + fn duplicate_layer_gives_copied_cell_anchors_ids_no_other_anchor_has() { + use std::sync::Arc; + + fn ids(st: &designcraft_doc::Story, out: &mut Vec) { + out.extend(st.anchors.iter().map(|a| a.id)); + for table in st.tables.values() { + for cell in &table.cells { + ids(&cell.text, out); + } + } + } + let mut s = crate::Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let base = s.doc().unwrap().doc.layers[0].id.0; + let f = s.execute("frame.create", &json!({"rect": [72, 72, 400, 400], "content": "text", "text": "Rows"})).unwrap()["id"].as_u64().unwrap(); + let sid = s.doc().unwrap().doc.item(designcraft_doc::ItemId(f)).unwrap().text_frame().unwrap().story; + let d = Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let table_id = d.alloc(); + // The cell's anchors take the ids the document hands out next, as anchors made in a cell story can. + let start = d.alloc(); + let mut table = designcraft_doc::Table::new(table_id, 1, 1, 0, 0, 40.0); + let cell = &mut table.cells[0].text; + for k in 1..=64 { + cell.insert_anchor(0, "Heading"); + Arc::make_mut(&mut cell.anchors[0]).id = start + k; + } + d.story_mut(sid).unwrap().insert_table(0, table); + let mut original = Vec::new(); + ids(d.story(sid).unwrap(), &mut original); + assert_eq!(original.len(), 64); + let copy = s.execute("layer.duplicate", &json!({"id": base})).unwrap()["id"].as_u64().unwrap(); + let d = &s.doc().unwrap().doc; + let copied = on_layer(d, copy)[0].text_frame().unwrap().story; + let mut after = Vec::new(); + ids(d.story(copied).unwrap(), &mut after); + assert_eq!(after.len(), original.len()); + for id in &after { + assert!(!original.contains(id), "copied cell anchor {id} has the id of an original anchor"); + } + } + + #[test] + fn duplicate_layer_gives_copied_tables_their_own_ids() { + let mut s = crate::Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let base = s.doc().unwrap().doc.layers[0].id.0; + let text = json!({"rect": [72, 72, 400, 400], "content": "text", "text": "Rows"}); + let f = s.execute("frame.create", &text).unwrap()["id"].as_u64().unwrap(); + let sid = s.doc().unwrap().doc.item(designcraft_doc::ItemId(f)).unwrap().text_frame().unwrap().story; + s.execute("text.select", &json!({"story": sid.0, "anchor": 4, "focus": 4})).unwrap(); + let table = s.execute("table.insert", &json!({"rows": 1, "cols": 2})).unwrap()["table"].as_u64().unwrap(); + let copy = s.execute("layer.duplicate", &json!({"id": base})).unwrap()["id"].as_u64().unwrap(); + let d = &s.doc().unwrap().doc; + let copied = on_layer(d, copy)[0].text_frame().unwrap().story; + let st = d.story(copied).unwrap(); + let tables: Vec = st.tables.keys().copied().collect(); + assert_eq!(tables.len(), 1); + let new = tables[0]; + assert_ne!(new, table, "the copy's table has an id of its own"); + assert_eq!(st.tables[&new].id, new); + assert_eq!(st.paras.iter().filter_map(|pf| pf.table).collect::>(), [new], "the copied paragraph holds the copied table"); + d.check().unwrap(); + s.execute("table.insertRow", &json!({"table": new})).unwrap(); + let d = &s.doc().unwrap().doc; + assert_eq!(d.story(sid).unwrap().tables[&table].nrows(), 1, "the original table is unchanged"); + assert_eq!(d.story(copied).unwrap().tables[&new].nrows(), 2, "a command naming the copy's table changes the copy"); + } + + #[test] + fn duplicate_layer_gives_tables_in_copied_cells_their_own_ids() { + let mut s = crate::Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let base = s.doc().unwrap().doc.layers[0].id.0; + let text = json!({"rect": [72, 72, 400, 400], "content": "text", "text": "Rows"}); + let f = s.execute("frame.create", &text).unwrap()["id"].as_u64().unwrap(); + let sid = s.doc().unwrap().doc.item(designcraft_doc::ItemId(f)).unwrap().text_frame().unwrap().story; + s.execute("text.select", &json!({"story": sid.0, "anchor": 4, "focus": 4})).unwrap(); + let table = s.execute("table.insert", &json!({"rows": 1, "cols": 2})).unwrap()["table"].as_u64().unwrap(); + let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let inner = d.alloc(); + let deepest = d.alloc(); + let mut nested = designcraft_doc::Table::new(inner, 1, 1, 0, 0, 40.0); + nested.cells[0].text.insert_table(0, designcraft_doc::Table::new(deepest, 1, 1, 0, 0, 20.0)); + d.story_mut(sid).unwrap().table_mut(table).unwrap().cells[0].text.insert_table(0, nested); + let copy = s.execute("layer.duplicate", &json!({"id": base})).unwrap()["id"].as_u64().unwrap(); + let d = &s.doc().unwrap().doc; + let copied = on_layer(d, copy)[0].text_frame().unwrap().story; + let outer = d.story(copied).unwrap().tables.values().next().unwrap(); + let cell = &outer.cells[0].text; + let new_inner = *cell.tables.keys().next().unwrap(); + assert_ne!(new_inner, inner, "a table in a copied cell has an id of its own"); + assert_eq!(cell.tables[&new_inner].id, new_inner); + assert_eq!(cell.paras.iter().filter_map(|pf| pf.table).collect::>(), [new_inner], "the copied cell holds the copied table"); + let inner_cell = &cell.tables[&new_inner].cells[0].text; + let new_deepest = *inner_cell.tables.keys().next().unwrap(); + assert_ne!(new_deepest, deepest, "a table nested deeper has an id of its own"); + assert_eq!(inner_cell.paras.iter().filter_map(|pf| pf.table).collect::>(), [new_deepest]); + let ids = [outer.id, new_inner, new_deepest, table, inner, deepest]; + assert_eq!(ids.iter().collect::>().len(), ids.len(), "every table id is unique: {ids:?}"); + let orig = d.story(sid).unwrap().tables[&table].cells[0].text.tables.keys().copied().collect::>(); + assert_eq!(orig, [inner], "the original's nested table keeps its id"); + } + + #[test] + fn duplicate_layer_numbers_copied_tables_and_anchored_objects_in_story_order() { + let mut s = crate::Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let base = s.doc().unwrap().doc.layers[0].id.0; + for k in 0..8 { + let y = 72 + 80 * k; + let text = json!({"rect": [72, y, 400, y + 60], "content": "text", "text": "Rows"}); + let f = s.execute("frame.create", &text).unwrap()["id"].as_u64().unwrap(); + let sid = s.doc().unwrap().doc.item(designcraft_doc::ItemId(f)).unwrap().text_frame().unwrap().story; + s.execute("text.select", &json!({"story": sid.0, "anchor": 4, "focus": 4})).unwrap(); + s.execute("table.insert", &json!({"rows": 1, "cols": 2})).unwrap(); + let b = s.execute("frame.create", &json!({"rect": [450, y, 474, y + 40]})).unwrap()["id"].as_u64().unwrap(); + s.execute("anchored.insert", &json!({"ids": [b], "story": sid.0, "pos": 0})).unwrap(); + } + let copy = s.execute("layer.duplicate", &json!({"id": base})).unwrap()["id"].as_u64().unwrap(); + let d = &s.doc().unwrap().doc; + d.check().unwrap(); + let mut stories: Vec<_> = on_layer(d, copy).iter().filter_map(|i| i.text_frame().map(|t| t.story)).collect(); + stories.sort_unstable(); + assert_eq!(stories.len(), 8); + let tables: Vec = stories.iter().map(|sid| *d.story(*sid).unwrap().tables.keys().next().unwrap()).collect(); + let objects: Vec = stories.iter().map(|sid| d.story(*sid).unwrap().objects[0].item.id.0).collect(); + assert!(tables.is_sorted(), "the copied tables take ids in story order: {tables:?}"); + assert!(objects.is_sorted(), "the copied anchored objects take ids in story order: {objects:?}"); + } + + /// 40 stories, each holding two anchored text frames threaded in the next: 2^40 paths, 40 stories. + #[test] + fn duplicate_layer_checks_each_shared_story_once() { + let mut s = crate::Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let base = s.doc().unwrap().doc.layers[0].id.0; + let f = s.execute("frame.create", &json!({"rect": [72, 72, 400, 400], "content": "text", "text": "Top"})).unwrap()["id"].as_u64().unwrap(); + let top = s.doc().unwrap().doc.item(designcraft_doc::ItemId(f)).unwrap().text_frame().unwrap().story; + s.edit(|d, _| { + use designcraft_doc::{AnchoredObject, ParaFormat}; + let r = designcraft_geom::Rect::new(0.0, 0.0, 60.0, 30.0); + let mut outer = top; + for _ in 0..40 { + let (a, inner) = d.add_text_frame(designcraft_doc::SpreadRef::Doc(0), r, d.default_layer(), "Link", ParaFormat::default())?; + let (b, spare) = d.add_text_frame(designcraft_doc::SpreadRef::Doc(0), r, d.default_layer(), "", ParaFormat::default())?; + let mut items = Vec::new(); + for f in [a, b] { + let mut it = d.item(f).cloned().ok_or(designcraft_doc::DocError::NoItem(f))?; + if let designcraft_doc::Content::Text(tf) = &mut it.content { + tf.story = inner; + } + items.push(it); + } + d.stories.remove(&spare); + d.story_mut(inner).ok_or(designcraft_doc::DocError::NoStory(inner))?.frames = vec![a, b]; + std::sync::Arc::make_mut(&mut d.spreads[0]).items.retain(|i| i.id != a && i.id != b); + let st = d.story_mut(outer).ok_or(designcraft_doc::DocError::NoStory(outer))?; + for it in items.into_iter().rev() { + st.insert_object(0, AnchoredObject::new(it, Default::default())); + } + outer = inner; + } + Ok(()) + }) + .unwrap(); + s.doc().unwrap().doc.check().unwrap(); + let before = s.doc().unwrap().doc.stories.len(); + s.execute("layer.duplicate", &json!({"id": base})).unwrap(); + let d = &s.doc().unwrap().doc; + d.check().unwrap(); + assert_eq!(d.stories.len(), 2 * before, "one copy of each story"); + } + + #[test] + fn duplicate_layer_refuses_objects_nested_too_deeply() { + let mut s = crate::Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let base = s.doc().unwrap().doc.layers[0].id.0; + let mut g = s.execute("frame.create", &json!({"rect": [0, 0, 10, 10]})).unwrap()["id"].as_u64().unwrap(); + for _ in 0..super::MAX_COPY_DEPTH + 1 { + let f = s.execute("frame.create", &json!({"rect": [0, 0, 10, 10]})).unwrap()["id"].as_u64().unwrap(); + g = s.execute("object.group", &json!({"ids": [g, f]})).unwrap()["id"].as_u64().unwrap(); + } + let before = s.doc().unwrap().doc.layers.clone(); + assert!(s.execute("layer.duplicate", &json!({"id": base})).is_err()); + assert_eq!(s.doc().unwrap().doc.layers, before, "nothing changes"); + } + + /// Two stories, each anchoring groups nested 40 deep, the innermost group of the first holding a text frame that + /// shows the second: within the limit in each story, past it in all. + #[test] + fn duplicate_layer_refuses_nesting_too_deep_across_stories() { + use designcraft_doc::{AnchoredObject, Content, Item, ItemId}; + use std::sync::Arc; + + fn nest(d: &mut designcraft_doc::Document, mut it: Item, levels: usize) -> Item { + for _ in 0..levels { + let mut group = it.clone(); + group.id = ItemId(d.alloc()); + group.content = Content::Group { items: vec![Arc::new(it)] }; + it = group; + } + it + } + let mut s = crate::Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let base = s.doc().unwrap().doc.layers[0].id.0; + let f = s.execute("frame.create", &json!({"rect": [72, 72, 400, 400], "content": "text", "text": "Top"})).unwrap()["id"].as_u64().unwrap(); + let g = s.execute("frame.create", &json!({"rect": [0, 0, 60, 30], "content": "text", "text": "Inner"})).unwrap()["id"].as_u64().unwrap(); + let h = s.execute("frame.create", &json!({"rect": [0, 0, 10, 10]})).unwrap()["id"].as_u64().unwrap(); + let d = Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let top = d.item(ItemId(f)).unwrap().text_frame().unwrap().story; + let (inner_frame, leaf) = (d.item(ItemId(g)).cloned().unwrap(), d.item(ItemId(h)).cloned().unwrap()); + let inner = inner_frame.text_frame().unwrap().story; + Arc::make_mut(&mut d.spreads[0]).items.retain(|i| i.id.0 != g && i.id.0 != h); + let deep_leaf = nest(d, leaf, 40); + d.story_mut(inner).unwrap().insert_object(0, AnchoredObject::new(deep_leaf, Default::default())); + let deep_frame = nest(d, inner_frame, 40); + d.story_mut(top).unwrap().insert_object(0, AnchoredObject::new(deep_frame, Default::default())); + let before = s.doc().unwrap().doc.layers.clone(); + assert!(s.execute("layer.duplicate", &json!({"id": base})).is_err()); + assert_eq!(s.doc().unwrap().doc.layers, before, "nothing changes"); + } + + /// An empty group inside 64 others: within the layer's depth check, which counts the objects below a group, but + /// past the limit of the copy, which counts the group itself. + #[test] + fn duplicate_layer_refuses_an_empty_group_at_the_copy_limit() { + use designcraft_doc::{Content, ItemId}; + use std::sync::Arc; + + let mut s = crate::Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let base = s.doc().unwrap().doc.layers[0].id.0; + let f = s.execute("frame.create", &json!({"rect": [0, 0, 10, 10]})).unwrap()["id"].as_u64().unwrap(); + let d = Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let mut it = d.item(ItemId(f)).cloned().unwrap(); + it.content = Content::Group { items: Vec::new() }; + for _ in 0..super::MAX_COPY_DEPTH { + let mut group = it.clone(); + group.id = ItemId(d.alloc()); + group.content = Content::Group { items: vec![Arc::new(it)] }; + it = group; + } + let items = &mut Arc::make_mut(&mut d.spreads[0]).items; + items.retain(|i| i.id.0 != f); + items.push(Arc::new(it)); + let before = s.doc().unwrap().doc.clone(); + let e = s.execute("layer.duplicate", &json!({"id": base})).unwrap_err().to_string(); + assert!(e.contains("too deeply to copy"), "{e}"); + assert_eq!(s.doc().unwrap().doc, before, "nothing changes"); + } + + #[test] + fn duplicate_layer_detaches_overrides_of_parent_items_on_other_layers() { + let mut s = crate::Session::new(); + s.execute("file.new", &json!({"pages": 2, "facingPages": false})).unwrap(); + let base = s.doc().unwrap().doc.layers[0].id.0; + s.execute("layer.new", &json!({"name": "Art"})).unwrap(); + let logo = json!({"spread": {"kind": "parent", "index": 0}, "rect": [72, 72, 144, 144]}); + let parent = s.execute("frame.create", &logo).unwrap()["id"].as_u64().unwrap(); + let o = s.execute("layout.overrideParentItems", &json!({"page": 1})).unwrap()["ids"][0].as_u64().unwrap(); + s.execute("selection.set", &json!({"ids": [o]})).unwrap(); + s.execute("object.setLayer", &json!({"layer": base})).unwrap(); + let copy = s.execute("layer.duplicate", &json!({"id": base})).unwrap()["id"].as_u64().unwrap(); + let d = &s.doc().unwrap().doc; + let copies = on_layer(d, copy); + assert_eq!(copies.len(), 1, "the override only: the parent item is on Art"); + assert_eq!(copies[0].overrides, None, "a plain object, so the original override stays the only one"); + assert_eq!(d.item(designcraft_doc::ItemId(o)).unwrap().overrides, Some(designcraft_doc::ItemId(parent))); + let (si, pi) = d.page_loc(1).unwrap(); + assert_eq!(d.spreads[si].pages[pi].overridden, [designcraft_doc::ItemId(parent)]); + } } #[cfg(test)] diff --git a/crates/engine/src/cmd/layout/pages.rs b/crates/engine/src/cmd/layout/pages.rs index 0417f1ff6..4a7092eb2 100644 --- a/crates/engine/src/cmd/layout/pages.rs +++ b/crates/engine/src/cmd/layout/pages.rs @@ -61,84 +61,93 @@ pub(crate) fn resize_pages(d: &mut designcraft_doc::Document, pages: &[usize], w /// [`resize_pages`] keeping reference point `anchor` (0–8, row-major from the top-left) in place: /// the page grows away from it, so objects keep their place relative to it. pub(crate) fn resize_pages_from(d: &mut designcraft_doc::Document, pages: &[usize], w: Option, h: Option, anchor: usize) { + for page in pages { + let Some((si, pi)) = page.checked_sub(1).and_then(|i| d.page_loc(i)) else { continue }; + resize_spread_page(d, designcraft_doc::SpreadRef::Doc(si), pi, w.map(|v| v.max(1.0)), h.map(|v| v.max(1.0)), anchor); + } +} + +pub(super) fn resize_spread_page( + d: &mut designcraft_doc::Document, + sr: designcraft_doc::SpreadRef, + pi: usize, + w: Option, + h: Option, + anchor: usize, +) { let (fx, fy) = ((anchor % 3) as f64 / 2.0, (anchor / 3).min(2) as f64 / 2.0); - { - for page in pages { - let Some((si, pi)) = d.page_loc(page - 1) else { continue }; - let sp = std::sync::Arc::make_mut(&mut d.spreads[si]); - let old: Vec = sp.pages.iter().map(|x| x.x).collect(); - let old_bounds = sp.pages[pi].bounds(); - // The page's own objects (outer pages take the pasteboard beside them). - let last = sp.pages.len() - 1; - let (lo, hi) = (if pi == 0 { f64::NEG_INFINITY } else { old_bounds.x0 }, if pi == last { f64::INFINITY } else { old_bounds.x1 }); - let own: Vec = sp - .items - .iter() - .enumerate() - .filter(|(_, it)| { - let c = it.bounds().center().x; - c >= lo && c < hi - }) - .map(|(i, _)| i) - .collect(); - let pg = &mut sp.pages[pi]; - let dw = w.map_or(0.0, |w| w.max(1.0) - pg.width); - let dh = h.map_or(0.0, |h| h.max(1.0) - pg.height); - if let Some(w) = w { - set_page_width(pg, w.max(1.0)); - } - if let Some(h) = h { - pg.height = h.max(1.0); - } - let left = pg.side == designcraft_doc::PageSide::Left; - sp.relayout(); - // Keep the spine: shift the whole spread back when a left page grows. - if left && dw != 0.0 { - for q in &mut sp.pages { - q.x -= dw; - } - } - let new: Vec = sp.pages.iter().map(|x| x.x).collect(); - // Objects follow their page. - let shifts: Vec<(f64, f64, f64)> = - sp.pages.iter().enumerate().map(|(k, q)| (old[k], old[k] + q.width - if k == pi { dw } else { 0.0 }, new[k] - old[k])).collect(); - for it in &mut sp.items { - let cx = it.bounds().center().x; - if let Some((_, _, dx)) = shifts.iter().find(|(a, b, _)| cx >= *a && cx < *b) - && *dx != 0.0 - { - let it = std::sync::Arc::make_mut(it); - it.xf = designcraft_geom::Affine::translate((*dx, 0.0)) * it.xf; - } - } - // Page guides move with their page. - for (k, q) in sp.pages.iter_mut().enumerate() { - let dx = new[k] - old[k]; - if dx != 0.0 { - for g in q.guides.iter_mut().filter(|g| g.orientation == designcraft_doc::Orientation::Vertical) { - g.position += dx; - } - } - } - // Growing away from the anchor: the page's objects and guides keep their place - // relative to it. - let shift = designcraft_geom::Vec2::new(fx * dw, fy * dh); - if shift != designcraft_geom::Vec2::ZERO { - for i in &own { - if let Some(it) = sp.items.get_mut(*i) { - let it = std::sync::Arc::make_mut(it); - it.xf = designcraft_geom::Affine::translate(shift) * it.xf; - } - } - for g in &mut sp.pages[pi].guides { - g.position += if g.orientation == designcraft_doc::Orientation::Vertical { shift.x } else { shift.y }; - } - } - // Liquid rules: objects were carried along with the page's left edge (and the anchor). - let moved = old_bounds + designcraft_geom::Vec2::new(new[pi] - old[pi], 0.0) + shift; - crate::cmd::liquid::apply(d, designcraft_doc::SpreadRef::Doc(si), pi, moved); + let Some(sp) = d.spread_mut(sr) else { return }; + let origin = sp.bounds().x0; + let old: Vec = sp.pages.iter().map(|x| x.x).collect(); + let old_bounds = sp.pages[pi].bounds(); + // The page's own objects (outer pages take the pasteboard beside them). + let Some((leftmost, rightmost)) = sp.outer_page_indices() else { return }; + let (lo, hi) = (if pi == leftmost { f64::NEG_INFINITY } else { old_bounds.x0 }, if pi == rightmost { f64::INFINITY } else { old_bounds.x1 }); + let own: Vec = sp + .items + .iter() + .enumerate() + .filter(|(_, it)| { + let c = it.bounds().center().x; + c >= lo && c < hi + }) + .map(|(i, _)| i) + .collect(); + let pg = &mut sp.pages[pi]; + let dw = w.map_or(0.0, |w| w - pg.width); + let dh = h.map_or(0.0, |h| h - pg.height); + if let Some(w) = w { + set_page_width(pg, w); + } + if let Some(h) = h { + pg.height = h; + } + let left = pg.side == designcraft_doc::PageSide::Left; + sp.relayout(); + // Relayout resets the origin; retain prior edits and grow left pages away from the spine. + let offset = origin - if left { dw } else { 0.0 }; + for q in &mut sp.pages { + q.x += offset; + } + let new: Vec = sp.pages.iter().map(|x| x.x).collect(); + // Objects follow their page. + let shifts: Vec<(f64, f64, f64)> = + sp.pages.iter().enumerate().map(|(k, q)| (old[k], old[k] + q.width - if k == pi { dw } else { 0.0 }, new[k] - old[k])).collect(); + for it in &mut sp.items { + let cx = it.bounds().center().x; + if let Some((_, _, dx)) = shifts.iter().find(|(a, b, _)| cx >= *a && cx < *b) + && *dx != 0.0 + { + let it = std::sync::Arc::make_mut(it); + it.xf = designcraft_geom::Affine::translate((*dx, 0.0)) * it.xf; } } + // Page guides move with their page. + for (k, q) in sp.pages.iter_mut().enumerate() { + let dx = new[k] - old[k]; + if dx != 0.0 { + for g in q.guides.iter_mut().filter(|g| g.orientation == designcraft_doc::Orientation::Vertical) { + g.position += dx; + } + } + } + // Growing away from the anchor: the page's objects and guides keep their place + // relative to it. + let shift = designcraft_geom::Vec2::new(fx * dw, fy * dh); + if shift != designcraft_geom::Vec2::ZERO { + for i in &own { + if let Some(it) = sp.items.get_mut(*i) { + let it = std::sync::Arc::make_mut(it); + it.xf = designcraft_geom::Affine::translate(shift) * it.xf; + } + } + for g in &mut sp.pages[pi].guides { + g.position += if g.orientation == designcraft_doc::Orientation::Vertical { shift.x } else { shift.y }; + } + } + // Liquid rules: objects were carried along with the page's left edge (and the anchor). + let moved = old_bounds + designcraft_geom::Vec2::new(new[pi] - old[pi], 0.0) + shift; + crate::cmd::liquid::apply(d, sr, pi, moved); } /// File › Document Setup values. @@ -322,6 +331,51 @@ mod setup_tests { mod page_size_tests { use serde_json::json; + #[test] + fn document_page_resize_preserves_shifted_spread_objects_and_guides() { + for binding in ["leftToRight", "rightToLeft"] { + let mut s = crate::Session::new(); + s.execute("file.new", &json!({"pages": 3, "facingPages": true, "width": 400, "height": 400})).unwrap(); + s.execute("layout.documentSetup", &json!({"binding": binding})).unwrap(); + let before = s.doc().unwrap().doc.clone(); + let (si, _) = before.page_loc(1).unwrap(); + let (left, right) = before.spreads[si].outer_page_indices().unwrap(); + let mut items = Vec::new(); + for pi in [left, right] { + let x = before.spreads[si].pages[pi].x; + let id = s.execute("frame.create", &json!({"spread": si, "rect": [x + 80.0, 80, x + 180.0, 180]})).unwrap()["id"].as_u64().unwrap(); + items.push(designcraft_doc::ItemId(id)); + s.execute("guide.add", &json!({"spread": si, "page": pi, "orientation": "vertical", "position": x + 120.0})).unwrap(); + } + let first = before.first_page_of_spread(si) + 1; + s.execute("layout.pageSize", &json!({"pages": [first + left], "width": 300})).unwrap(); + let shifted = s.doc().unwrap().doc.clone(); + let sp = &shifted.spreads[si]; + assert_eq!(sp.bounds().x0, 100.0); + assert_eq!(sp.pages[right].x, 400.0); + assert_eq!(sp.pages[left].guides[0].position, 220.0); + assert_eq!(sp.pages[right].guides[0].position, 520.0); + assert_eq!(shifted.item(items[0]).unwrap().bounds().x0, 180.0); + assert_eq!(shifted.item(items[1]).unwrap().bounds().x0, 480.0); + for width in [500, 450, 520] { + s.execute("layout.pageSize", &json!({"pages": [first + right], "width": width})).unwrap(); + let d = &s.doc().unwrap().doc; + let sp = &d.spreads[si]; + assert_eq!(sp.bounds().x0, 100.0, "{binding}, width {width}"); + assert_eq!(sp.pages[right].x, 400.0); + for pi in [left, right] { + assert_eq!(sp.pages[pi].guides, shifted.spreads[si].pages[pi].guides); + } + for id in &items { + assert_eq!(d.item(*id).unwrap().bounds(), shifted.item(*id).unwrap().bounds()); + } + assert_eq!(d.parents, before.parents); + assert_eq!(d.settings, before.settings); + d.check().unwrap(); + } + } + } + #[test] fn page_size_per_page_keeps_objects_on_their_page() { let mut s = crate::Session::new(); diff --git a/crates/engine/src/cmd/layout/parents.rs b/crates/engine/src/cmd/layout/parents.rs index f53d774f4..4241290b9 100644 --- a/crates/engine/src/cmd/layout/parents.rs +++ b/crates/engine/src/cmd/layout/parents.rs @@ -40,31 +40,117 @@ pub(super) fn parent_ref(cmd: &str, d: &designcraft_doc::Document, v: Option<&Va } } -/// Layout › Pages › Parent Options: Based on Parent. A base that would make a cycle is refused. +/// Whether a parent other than index `except` is labelled `label` (`A-Parent`). Parents may share +/// a prefix, but a label names one parent. +pub(super) fn parent_label_taken(d: &designcraft_doc::Document, label: &str, except: Option) -> bool { + d.parents.iter().enumerate().any(|(i, x)| Some(i) != except && x.parent.as_ref().is_some_and(|o| o.label() == label)) +} + +/// A parent prefix parameter: trimmed, 1–4 characters, no `-` (it separates prefix and name). +pub(super) fn parent_prefix_param(cmd: &str, p: &Value) -> Result> { + let Some(v) = p.get("prefix") else { return Ok(None) }; + let s = v.as_str().ok_or_else(|| bad(cmd, "`prefix` is text"))?.trim(); + if s.is_empty() || s.chars().count() > 4 || s.contains('-') { + return Err(bad(cmd, "a parent prefix has 1 to 4 characters and no `-`")); + } + Ok(Some(s.to_string())) +} + +/// A parent name parameter: trimmed, not empty, at most 100 characters. +pub(super) fn parent_name_param(cmd: &str, p: &Value) -> Result> { + let Some(v) = p.get("name") else { return Ok(None) }; + let s = v.as_str().ok_or_else(|| bad(cmd, "`name` is text"))?.trim(); + if s.is_empty() || s.chars().count() > 100 { + return Err(bad(cmd, "a parent name has 1 to 100 characters")); + } + Ok(Some(s.to_string())) +} + +/// Layout › Pages › Parent Options: prefix, name and Based on Parent. A base that would make a +/// cycle is refused. pub(super) fn parent_options(s: &mut crate::Session, p: &Value) -> Result { const CMD: &str = "layout.parents.options"; + let prefix = parent_prefix_param(CMD, p)?; + let name = parent_name_param(CMD, p)?; let d = &s.doc()?.doc; let Some(Some(id)) = parent_ref(CMD, d, p.get("parent"))? else { return Err(bad(CMD, "`parent` names the parent to change")) }; let pi = d.parent_index(id).ok_or_else(|| bad(CMD, format!("no parent with id {}", id.0)))?; - let base = parent_ref(CMD, d, p.get("basedOn"))?.ok_or_else(|| bad(CMD, "missing `basedOn` (a parent, or null for [None])"))?; + let info = d.parents.get(pi).and_then(|x| x.parent.clone()).ok_or_else(|| bad(CMD, "no such parent"))?; + let base = match parent_ref(CMD, d, p.get("basedOn"))? { + Some(b) => b, + None => info.based_on, + }; + if base == Some(id) { + return Err(bad(CMD, format!("{} cannot be based on itself", info.label()))); + } let label = |d: &designcraft_doc::Document, i: usize| d.parents.get(i).and_then(|x| x.parent.as_ref()).map(|i| i.label()); if let Some(b) = base && d.parent_base_cycles(pi, b) { - let (name, b) = (label(d, pi).unwrap_or_default(), d.parent_index(b).and_then(|i| label(d, i)).unwrap_or_default()); + let (name, b) = (info.label(), d.parent_index(b).and_then(|i| label(d, i)).unwrap_or_default()); return Err(bad(CMD, format!("{name} cannot be based on {b}: that would make a cycle"))); } - let out = json!({"parent": label(d, pi), "basedOn": base.and_then(|b| d.parent_index(b)).and_then(|i| label(d, i))}); - if d.parents.get(pi).and_then(|x| x.parent.as_ref()).and_then(|i| i.based_on) == base { + let new = designcraft_doc::ParentInfo { + prefix: prefix.unwrap_or_else(|| info.prefix.clone()), + name: name.unwrap_or_else(|| info.name.clone()), + based_on: base, + }; + let out = json!({ + "parent": new.label(), + "prefix": new.prefix, + "name": new.name, + "basedOn": base.and_then(|b| d.parent_index(b)).and_then(|i| label(d, i)), + }); + if new == info { return Ok(out); } + if parent_label_taken(d, &new.label(), Some(pi)) { + return Err(bad(CMD, format!("a parent named {} exists", new.label()))); + } s.edit(|d, _| { let info = d.parents.get_mut(pi).map(std::sync::Arc::make_mut).and_then(|x| x.parent.as_mut()).ok_or_else(|| bad(CMD, "no such parent"))?; - info.based_on = base; + *info = new; Ok(out) }) } +pub(super) fn parent_page_target(d: &designcraft_doc::Document, p: &Value, cmd: &str) -> Result<(usize, usize)> { + let parent = p.get("parent").and_then(Value::as_u64).map(SpreadId).ok_or_else(|| bad(cmd, "give a parent spread id"))?; + let si = d.parent_index(parent).ok_or_else(|| bad(cmd, "no such parent"))?; + let pi = p + .get("page") + .and_then(Value::as_u64) + .and_then(|n| usize::try_from(n).ok()) + .filter(|i| *i < d.parents[si].pages.len()) + .ok_or_else(|| bad(cmd, "no such parent page"))?; + Ok((si, pi)) +} + +pub(super) fn parent_page_size(s: &mut crate::Session, p: &Value) -> Result { + const ID: &str = "layout.parentPageSize"; + let (si, pi) = parent_page_target(&s.doc()?.doc, p, ID)?; + let size = |key| { + p.get(key) + .map(|v| { + v.as_f64().filter(|v| v.is_finite() && *v > 0.0 && *v <= 15552.0).ok_or_else(|| bad(ID, "page size out of range (0 < size ≤ 216 in)")) + }) + .transpose() + }; + let (w, h) = (size("width")?, size("height")?); + if w.is_none() && h.is_none() { + return Err(bad(ID, "give width or height")); + } + let anchor = match p.get("anchor") { + None => 0, + Some(v) => v.as_u64().filter(|n| *n <= 8).ok_or_else(|| bad(ID, "anchor: 0–8"))? as usize, + }; + s.edit(|d, _| { + super::pages::resize_spread_page(d, designcraft_doc::SpreadRef::Parent(si), pi, w, h, anchor); + d.sync_parent_margins(); + Ok(json!({"parent": d.parents[si].id.0, "page": pi})) + }) +} + #[cfg(test)] mod parent_margin_tests { use designcraft_doc::{Document, Margins}; @@ -117,6 +203,52 @@ mod parent_margin_tests { assert!(s.execute("layout.marginsAndColumns", &json!({"parent": "Z", "margins": 10})).is_err()); } + /// Insert Pages before a page, or at the start of the document (`before: 0`), as InDesign's + /// dialog offers; `after` and `before` together are refused without an undo step. + #[test] + fn pages_go_in_before_a_page_or_at_the_start() { + let mut s = Session::new(); + // Facing: [1] [2 3]. + s.execute("file.new", &json!({"pages": 3})).unwrap(); + let b = s.execute("layout.parents.new", &json!({"prefix": "B"})).unwrap()["id"].as_u64().unwrap(); + let ids = |s: &Session| -> Vec { + let d = &s.doc().unwrap().doc; + (0..d.page_count()).map(|i| d.page(i).unwrap().id.0).collect() + }; + let parent = |s: &Session, i: usize| s.doc().unwrap().doc.page(i).unwrap().parent.map(|p| p.0); + let old = ids(&s); + s.execute("layout.pages.insert", &json!({"before": 0, "parent": "B"})).unwrap(); + let now = ids(&s); + assert_eq!(now.len(), 4); + assert_eq!(now[1..], old[..], "the old pages follow the new first page"); + assert_eq!(parent(&s, 0), Some(b)); + // Before page 4 (index 3, the old page 3): two pages without a parent. + s.execute("layout.pages.insert", &json!({"before": 3, "count": 2, "parent": null})).unwrap(); + let then = ids(&s); + assert_eq!(then.len(), 6); + assert_eq!(then[..3], now[..3]); + assert_eq!(then[5], old[2]); + assert_eq!((parent(&s, 3), parent(&s, 4)), (None, None)); + // Refused without a change or an undo step: both placements, even one of them null, and a + // placement that isn't a page index. + let undo = s.doc().unwrap().history.undo.len(); + for bad in [ + json!({"after": 0, "before": 1}), + json!({"after": 0, "before": null}), + json!({"after": null, "before": 1}), + json!({"before": -1}), + json!({"before": "0"}), + json!({"before": null}), + json!({"after": 1.5}), + json!({"before": 6}), + json!({"before": 99}), + ] { + assert!(s.execute("layout.pages.insert", &bad).is_err(), "{bad}"); + assert_eq!(s.doc().unwrap().history.undo.len(), undo, "{bad}"); + assert_eq!(ids(&s), then, "{bad}"); + } + } + #[test] fn applying_a_parent_gives_its_margins_and_local_margins_stay_local() { let mut s = Session::new(); @@ -186,6 +318,81 @@ mod parent_tests { assert_eq!(parent_of(&s, 1), None); } + #[test] + fn new_parents_take_the_next_letters_and_options_rename_them() { + let mut s = crate::Session::new(); + s.execute("file.new", &json!({"pages": 2})).unwrap(); + let b = s.execute("layout.parents.new", &json!({})).unwrap(); + assert_eq!(b["prefix"], "B"); + let c = s.execute("layout.parents.new", &json!({"basedOn": "A"})).unwrap(); + assert_eq!(c["prefix"], "C"); + let (b, c) = (b["id"].as_u64().unwrap(), c["id"].as_u64().unwrap()); + let info = |s: &crate::Session, id: u64| { + let d = &s.doc().unwrap().doc; + d.parents.iter().find(|p| p.id.0 == id).and_then(|p| p.parent.clone()).unwrap() + }; + assert!(info(&s, c).based_on.is_some()); + s.execute("layout.pages.applyParent", &json!({"pages": [1], "parent": b})).unwrap(); + let r = s.execute("layout.parents.options", &json!({"parent": "B", "prefix": " Z ", "name": "Cover"})).unwrap(); + assert_eq!(r["parent"], "Z-Cover"); + assert_eq!(info(&s, b).label(), "Z-Cover"); + // The page keeps its parent, now called Z-Cover; Based On is untouched when not given. + assert_eq!(parent_of(&s, 1), Some(b)); + assert!(info(&s, c).based_on.is_some()); + s.execute("layout.parents.options", &json!({"parent": "C", "name": "Back"})).unwrap(); + assert_eq!(info(&s, c).label(), "C-Back"); + assert!(info(&s, c).based_on.is_some(), "a rename keeps the base"); + // Bad prefixes and names change nothing and add no history. + let undo = s.doc().unwrap().history.undo.len(); + for bad in [json!({"prefix": ""}), json!({"prefix": "ABCDE"}), json!({"prefix": "A-B"}), json!({"name": " "}), json!({"prefix": 3})] { + let mut p = bad.clone(); + p["parent"] = json!(b); + assert!(s.execute("layout.parents.options", &p).is_err(), "{bad}"); + assert!(s.execute("layout.parents.new", &bad).is_err(), "{bad}"); + } + assert!(s.execute("layout.parents.options", &json!({"parent": "C", "basedOn": "C-Back"})).is_err()); + // A label names one parent: taking another parent's label is refused, a prefix may be shared. + assert!(s.execute("layout.parents.options", &json!({"parent": "C-Back", "prefix": "Z", "name": "Cover"})).is_err()); + assert!(s.execute("layout.parents.new", &json!({"prefix": "Z", "name": "Cover"})).is_err()); + assert!(s.execute("layout.parents.options", &json!({"parent": "C-Back", "prefix": "Z"})).is_ok()); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().history.undo.len(), undo); + assert_eq!(info(&s, b).label(), "Z-Cover"); + // Four characters, including non-Latin ones, are fine. + s.execute("layout.parents.options", &json!({"parent": b, "prefix": "表紙ページ".chars().take(4).collect::()})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(info(&s, b).label(), "Z-Cover"); + } + + #[test] + fn duplicate_parent_copies_pages_and_items_with_a_new_prefix() { + let mut s = crate::Session::new(); + s.execute("file.new", &json!({"pages": 2})).unwrap(); + let a = json!({"kind": "parent", "index": 0}); + s.execute("frame.create", &json!({"spread": a, "rect": [40, 40, 200, 100], "content": "text"})).unwrap(); + s.execute("frame.create", &json!({"spread": a, "rect": [60, 200, 160, 300]})).unwrap(); + let n = s.doc().unwrap().doc.parents.len(); + let r = s.execute("layout.parents.duplicate", &json!({"parent": "A-Parent"})).unwrap(); + assert_eq!(r["prefix"], "B"); + let d = &s.doc().unwrap().doc; + assert_eq!(d.parents.len(), n + 1); + let (src, copy) = (&d.parents[0], &d.parents[n]); + assert_eq!(copy.id.0, r["id"].as_u64().unwrap()); + assert_eq!(copy.parent.as_ref().unwrap().label(), "B-Parent"); + assert_eq!(copy.pages.len(), src.pages.len()); + assert_eq!(copy.items.len(), 2); + assert!(copy.pages.iter().all(|p| src.pages.iter().all(|q| q.id != p.id))); + assert!(copy.items.iter().all(|i| src.items.iter().all(|j| j.id != i.id))); + // The copied text frame has its own story. + let story = |it: &designcraft_doc::Item| it.text_frame().map(|t| t.story); + let (s0, s1) = (src.items.iter().find_map(|i| story(i)), copy.items.iter().find_map(|i| story(i))); + assert!(s0.is_some() && s1.is_some() && s0 != s1); + assert!(s.execute("layout.parents.duplicate", &json!({"parent": "Nope"})).is_err()); + assert!(s.execute("layout.parents.duplicate", &json!({})).is_err()); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc.parents.len(), n); + } + #[test] fn edit_parents_shows_the_named_parent() { let mut s = crate::Session::new(); @@ -388,7 +595,7 @@ mod parent_base_tests { assert!(paper(page(&s, 1).pixel(50, 100)), "B alone does not show A's items"); let r = s.execute("layout.parents.options", &json!({"parent": "B", "basedOn": "A"})).unwrap(); - assert_eq!(r, json!({"parent": "B-Opening", "basedOn": "A-Parent"})); + assert_eq!(r, json!({"parent": "B-Opening", "prefix": "B", "name": "Opening", "basedOn": "A-Parent"})); let img = page(&s, 1); assert!(black(img.pixel(50, 100)), "A's item: {:?}", img.pixel(50, 100)); assert!(cyan(img.pixel(150, 150)), "B's item over A's: {:?}", img.pixel(150, 150)); diff --git a/crates/engine/src/cmd/layout/registry.rs b/crates/engine/src/cmd/layout/registry.rs index 4826f9273..d79d829b8 100644 --- a/crates/engine/src/cmd/layout/registry.rs +++ b/crates/engine/src/cmd/layout/registry.rs @@ -1,9 +1,11 @@ -use super::layers::set_layer; +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}; -use super::parents::{parent_options, parent_ref, parent_spread_index}; +use super::parents::{ + parent_label_taken, parent_name_param, parent_options, parent_page_size, parent_page_target, parent_prefix_param, parent_ref, parent_spread_index, +}; use super::sections::{ChapterEdit, SectionEdit, chapter_numbering, start_number}; -use super::{CommandSpec, LAYER_COLORS, Layer, LayerId, Margins, SpreadId, Value, bad, cmd, has_doc, json, ok, str_param}; +use super::{CommandSpec, LAYER_COLORS, Layer, LayerId, Margins, Result, SpreadId, Value, bad, cmd, has_doc, json, ok, str_param}; pub fn specs() -> Vec { vec![ @@ -12,7 +14,7 @@ pub fn specs() -> Vec { "Insert Pages…", ["Layout", "Pages"], Some("Cmd+Shift+P"), - "{count?: 1 (1 to 9999), after?: 0-based page index (default: the last page), parent?: id|\"A-Parent\"|\"A\"|null}", + "{count?: 1 (1 to 9999), after?: 0-based page index (default: the last page; past it: at the end), before?: 0-based page index (instead of `after`; 0: at the start), parent?: id|\"A-Parent\"|\"A\"|null (default: the parent of the page they follow, or of the first page)}", has_doc, |s, p| { const ID: &str = "layout.pages.insert"; @@ -27,12 +29,36 @@ pub fn specs() -> Vec { }; let st = s.doc()?; let n = st.doc.page_count(); - // An `after` past the last page appends, which `insert_after_u64_max_appends_at_the_end` - // pins deliberately. - let after = p.get("after").and_then(Value::as_u64).map(|v| usize::try_from(v).unwrap_or(usize::MAX)).unwrap_or(n.saturating_sub(1)); - let parent = parent_ref(ID, &st.doc, p.get("parent"))?.unwrap_or_else(|| st.doc.parents.first().map(|x| x.id)); + // A placement given (null included) must be a page index; only when neither is + // given do the pages go after the last. + if p.get("after").is_some() && p.get("before").is_some() { + return Err(bad("layout.pages.insert", "give `after` or `before`, not both")); + } + // `before` names a page of the document; an `after` past the last page appends + // (`insert_pages_bounds.rs` pins that). + let index = |k: &str| match p.get(k) { + None => Ok(None), + Some(v) => v + .as_u64() + .map(|v| usize::try_from(v).unwrap_or(usize::MAX)) + .filter(|&i| k == "after" || i < n) + .map(|i| Some(i.min(n.saturating_sub(1)))) + .ok_or_else(|| bad(ID, format!("`{k}` must be the index of one of the {n} pages, not {v}"))), + }; + // The page the new ones follow; none: they go first. + let after = match (index("after")?, index("before")?) { + (_, Some(b)) => b.checked_sub(1), + (a, None) => Some(a.unwrap_or(n.saturating_sub(1))), + }; + // No parent given: the new pages continue the page they follow (the first page when + // they go at the start), [None] included (#2788); in a document without pages, the + // first parent. + let parent = parent_ref(ID, &st.doc, p.get("parent"))?.unwrap_or_else(|| match st.doc.page(after.unwrap_or(0)) { + Some(pg) => pg.parent, + None => st.doc.parents.first().map(|x| x.id), + }); s.edit(|d, _| { - let ids = d.insert_pages(Some(after), count, parent)?; + let ids = d.insert_pages(after, count, parent)?; Ok(json!({"pages": ids.len(), "total": d.page_count()})) }) } @@ -61,19 +87,25 @@ pub fn specs() -> Vec { }) } ), - cmd!("layout.pages.delete", "Delete Pages", ["Layout", "Pages"], None, "{pages: [index]}", has_doc, |s, p| { - let pages: Vec = p - .get("pages") - .and_then(Value::as_array) - .map(|a| a.iter().filter_map(Value::as_u64).map(|v| v as usize).collect()) - .unwrap_or_default(); - s.edit(|d, sel| { - d.delete_pages(&pages)?; - sel.items.retain(|i| d.item(*i).is_some()); - sel.text = sel.text.filter(|t| d.story(t.story).is_some()); - ok() - }) - }), + cmd!( + "layout.pages.delete", + "Delete Pages", + ["Layout", "Pages"], + None, + "{pages: [0-based page indices]} → {deleted: how many pages were removed}", + has_doc, + |s, p| { + const ID: &str = "layout.pages.delete"; + let pages = page_indices(ID, s.doc()?.doc.page_count(), p)?; + let deleted = distinct_pages(&pages); + s.edit(|d, sel| { + d.delete_pages(&pages)?; + sel.items.retain(|i| d.item(*i).is_some()); + sel.text = sel.text.filter(|t| d.story(t.story).is_some()); + Ok(json!({"deleted": deleted})) + }) + } + ), cmd!("layout.pages.move", "Move Pages…", ["Layout", "Pages"], None, "{from, to}", has_doc, |s, p| { let from = p.get("from").and_then(Value::as_u64).ok_or_else(|| bad("layout.pages.move", "missing from"))? as usize; let to = p.get("to").and_then(Value::as_u64).ok_or_else(|| bad("layout.pages.move", "missing to"))? as usize; @@ -145,42 +177,82 @@ pub fn specs() -> Vec { "Apply Parent to Pages…", ["Layout", "Pages"], None, - "{pages: [index], parent: id|\"A-Parent\"|\"A\"|null (null or \"[None]\" clears)}", + "{pages: [0-based page indices], parent: id|\"A-Parent\"|\"A\"|null (null or \"[None]\" clears)} → {applied: how many pages took the parent}", has_doc, |s, p| { - let pages: Vec = p - .get("pages") - .and_then(Value::as_array) - .map(|a| a.iter().filter_map(Value::as_u64).map(|v| v as usize).collect()) - .unwrap_or_default(); - let parent = parent_ref("layout.pages.applyParent", &s.doc()?.doc, p.get("parent"))?.unwrap_or(None); + const ID: &str = "layout.pages.applyParent"; + let pages = page_indices(ID, s.doc()?.doc.page_count(), p)?; + let applied = distinct_pages(&pages); + let parent = parent_ref(ID, &s.doc()?.doc, p.get("parent"))?.unwrap_or(None); s.edit(|d, _| { d.apply_parent(&pages, parent)?; - ok() + Ok(json!({"applied": applied})) }) } ), - cmd!("layout.parents.new", "New Parent…", ["Layout", "Pages"], None, "{prefix?, name?: \"Parent\"}", has_doc, |s, p| { - let name = str_param(p, "name").unwrap_or("Parent").to_string(); - s.edit(|d, _| { - let prefix = str_param(p, "prefix").map(str::to_string).unwrap_or_else(|| d.next_parent_prefix()); - let src = d.page(0).cloned(); - let (columns, margins) = - src.as_ref().map_or_else(|| (designcraft_doc::Columns::default(), Margins::uniform(36.0)), |p| (p.columns.clone(), p.margins)); - let id = d.add_parent(&prefix, &name, columns.count, columns.gutter, margins); - // Dragged column guides carry over to the parent pages they still fit, mirrored - // on the parent page across the spine from the first page. - if let (Some(src), Some(sp)) = (&src, d.parents.iter_mut().find(|x| x.id == id)) { - for pg in &mut std::sync::Arc::make_mut(sp).pages { - let columns = pg.columns_from(src); - if columns.valid_positions(pg.margin_rect().width()).is_some() { - pg.columns.positions = columns.positions; + cmd!( + "layout.parents.new", + "New Parent…", + ["Layout", "Pages"], + None, + "{prefix?: 1–4 characters without `-` (default: the next free letter), name?: \"Parent\", basedOn?: id|\"A-Parent\"|\"A\"|null} → {id, prefix}", + has_doc, + |s, p| { + const ID: &str = "layout.parents.new"; + let name = parent_name_param(ID, p)?.unwrap_or_else(|| "Parent".into()); + let prefix = parent_prefix_param(ID, p)?; + let base = parent_ref(ID, &s.doc()?.doc, p.get("basedOn"))?.flatten(); + s.edit(|d, _| { + let prefix = prefix.unwrap_or_else(|| d.next_parent_prefix()); + let label = designcraft_doc::ParentInfo { prefix: prefix.clone(), name: name.clone(), based_on: None }.label(); + if parent_label_taken(d, &label, None) { + return Err(bad(ID, format!("a parent named {label} exists"))); + } + let src = d.page(0).cloned(); + let (columns, margins) = src + .as_ref() + .map_or_else(|| (designcraft_doc::Columns::default(), Margins::uniform(36.0)), |p| (p.columns.clone(), p.margins)); + let id = d.add_parent(&prefix, &name, columns.count, columns.gutter, margins); + // Dragged column guides carry over to the parent pages they still fit, mirrored + // on the parent page across the spine from the first page. + if let (Some(src), Some(sp)) = (&src, d.parents.iter_mut().find(|x| x.id == id)) { + for pg in &mut std::sync::Arc::make_mut(sp).pages { + let columns = pg.columns_from(src); + if columns.valid_positions(pg.margin_rect().width()).is_some() { + pg.columns.positions = columns.positions; + } } } - } - Ok(json!({"id": id.0, "prefix": prefix})) - }) - }), + if let Some(info) = d.parents.iter_mut().find(|x| x.id == id).map(std::sync::Arc::make_mut).and_then(|x| x.parent.as_mut()) { + info.based_on = base; + } + Ok(json!({"id": id.0, "prefix": prefix})) + }) + } + ), + cmd!( + "layout.parents.duplicate", + "Duplicate Parent Spread", + ["Layout", "Pages"], + None, + "{parent: id|\"A-Parent\"|\"A\"} — a copy with the next free prefix, its pages and items → {id, prefix}", + has_doc, + |s, p| { + const ID: &str = "layout.parents.duplicate"; + let Some(Some(id)) = parent_ref(ID, &s.doc()?.doc, p.get("parent"))? else { + return Err(bad(ID, "`parent` names the parent to duplicate")); + }; + s.edit(|d, _| { + let prefix = d.next_parent_prefix(); + let src = d.clone(); + let ids: Vec<_> = + src.parent_index(id).and_then(|i| src.parents.get(i)).map(|sp| sp.items.iter().map(|i| i.id).collect()).unwrap_or_default(); + let (new, at) = d.duplicate_parent_shell(id, &prefix)?; + crate::cmd::object::duplicate_from(d, &src, &ids, designcraft_doc::SpreadRef::Parent(at), designcraft_geom::Vec2::ZERO)?; + Ok(json!({"id": new.0, "prefix": prefix})) + }) + } + ), cmd!( "layout.parents.delete", "Delete Parent", @@ -243,7 +315,7 @@ pub fn specs() -> Vec { "Parent Options…", [], None, - "{parent: id|\"B-Parent\"|\"B\", basedOn: id|\"A-Parent\"|\"A\"|null (= [None])} — the parent shows its base's items under its own, and so do the pages that use it → {parent, basedOn}", + "{parent: id|\"B-Parent\"|\"B\", prefix?: 1–4 characters without `-`, name?, basedOn?: id|\"A-Parent\"|\"A\"|null (= [None])} — rename the parent; with a base it shows the base's items under its own, and so do the pages that use it → {parent, prefix, name, basedOn}", has_doc, parent_options ), @@ -373,6 +445,7 @@ pub fn specs() -> Vec { prefix: String::new(), marker: String::new(), include_prefix: false, + layout: None, }, ); } @@ -484,6 +557,30 @@ pub fn specs() -> Vec { has_doc, page_size ), + cmd!( + "layout.parentPageSize", + "Parent Page Size", + [], + None, + "{parent: spread id, page: 0-based parent page index, width?, height?, anchor?: 0–8} — resize only this parent page, keeping document page sizes independent", + has_doc, + parent_page_size + ), + cmd!( + noundo "layout.selectParentPage", "Select Parent Page", [], None, + "{parent: spread id|null, page?: 0-based parent page index} — select a parent page with the Page tool; null clears the selection", + has_doc, |s, p| { + let target = match p.get("parent") { + Some(Value::Null) => None, + _ => Some(parent_page_target(&s.doc()?.doc, p, "layout.selectParentPage")?), + }; + let st = s.doc_mut()?; + st.selection = Default::default(); + st.selection.parent_page = target.map(|(si, pi)| (st.doc.parents[si].id, pi)); + st.bump_revision(); + ok() + } + ), cmd!( "layout.pageOptions", "Page Options", @@ -518,6 +615,7 @@ pub fn specs() -> Vec { st.selection = designcraft_doc::Selection::items(ids); } st.selection.page = page; + st.selection.parent_page = None; st.bump_revision(); Ok(json!({"page": page.map(|p| p + 1)})) } @@ -613,6 +711,7 @@ pub fn specs() -> Vec { locked: false, printable: true, show_guides: true, + lock_guides: false, suppress_wrap_when_hidden: false, }, ); @@ -621,12 +720,21 @@ pub fn specs() -> Vec { s.doc_mut()?.active_layer = r; Ok(json!({"id": r.0})) }), + cmd!( + "layer.duplicate", + "Duplicate Layer", + [], + None, + "{id} → {id}. Adds a copy of the layer's settings and objects (document and parent spreads) above it, named \" copy\"", + has_doc, + duplicate_layer + ), cmd!( "layer.set", "Layer Options…", [], None, - "{id, name?, color?: [r,g,b] | layer colour name (\"Light Blue\", \"Red\", …), visible?, locked?, printable?, showGuides?, suppressWrapWhenHidden?} — names are unique and not empty", + "{id, name?, color?: [r,g,b] | layer colour name (\"Light Blue\", \"Red\", …), visible?, locked?, printable?, showGuides?, lockGuides?, suppressWrapWhenHidden?} — names are unique and not empty", has_doc, set_layer ), @@ -740,3 +848,129 @@ pub fn specs() -> Vec { }), ] } + +/// The page indices a `layout.pages.*` command was given, in the order it passed them. +/// +/// Both commands count pages from 0. An index past the last page used to be dropped in +/// silence, so a caller that was off by one deleted a different range and still read +/// `ok`; the sentence is the one the MCP export commands have used since #70. +fn page_indices(id: &str, count: usize, p: &Value) -> Result> { + // A list that is missing, is not a list, or holds something that is not a whole number is + // refused rather than filtered: dropping an entry silently is the same mistake this fixes, + // one level up — the caller would be told a page was handled when it never was. + let raw = p.get("pages").and_then(Value::as_array).ok_or_else(|| bad(id, "pages takes a list of page indices"))?; + let mut out = Vec::with_capacity(raw.len()); + for v in raw { + let n = v.as_u64().ok_or_else(|| bad(id, format!("pages takes whole numbers, and {v} is not one")))?; + let i = usize::try_from(n).unwrap_or(usize::MAX); + if i >= count { + return Err(bad(id, format!("no page {i} (the document has {count} pages, indices are 0-based)"))); + } + out.push(i); + } + Ok(out) +} + +/// How many pages a list of indices names, counting a repeated index once. +fn distinct_pages(pages: &[usize]) -> usize { + let mut v = pages.to_vec(); + v.sort_unstable(); + v.dedup(); + v.len() +} + +#[cfg(test)] +mod page_index_tests { + use serde_json::json; + + fn four_pages() -> crate::Session { + let mut s = crate::Session::new(); + s.execute("file.new", &json!({"pages": 4})).unwrap(); + s + } + + fn pages_left(s: &crate::Session) -> usize { + s.doc().unwrap().doc.page_count() + } + + /// An index past the last page is an error that names it, and nothing is removed. + #[test] + fn a_page_index_past_the_end_is_refused_and_nothing_is_deleted() { + let mut s = four_pages(); + let err = s.execute("layout.pages.delete", &json!({"pages": [4]})).unwrap_err().to_string(); + assert!(err.contains("no page 4"), "the message names the index: {err}"); + assert!(err.contains("indices are 0-based"), "and the base: {err}"); + assert_eq!(pages_left(&s), 4, "nothing went"); + } + + /// The reply says how many pages went, and a page named twice is one page. + #[test] + fn deleting_says_how_many_pages_went() { + let mut s = four_pages(); + let r = s.execute("layout.pages.delete", &json!({"pages": [0, 1]})).unwrap(); + assert_eq!(r["deleted"], 2); + assert_eq!(pages_left(&s), 2); + // A page named twice is one page, not two. + let mut s = four_pages(); + let r = s.execute("layout.pages.delete", &json!({"pages": [1, 1]})).unwrap(); + assert_eq!(r["deleted"], 1); + assert_eq!(pages_left(&s), 3); + } + + /// Three pages named of four leave one, which is allowed even with a repeat. + #[test] + fn a_page_named_twice_does_not_count_as_two_against_the_last_one_left() { + // Four pages, three named (one of them twice): that leaves one and is allowed. + let mut s = four_pages(); + let r = s.execute("layout.pages.delete", &json!({"pages": [0, 0, 1, 2]})).unwrap(); + assert_eq!(r["deleted"], 3); + assert_eq!(pages_left(&s), 1); + } + + /// Applying a parent reports how many pages took it, and the pages really do. + #[test] + fn applying_a_parent_says_how_many_pages_took_it() { + let mut s = four_pages(); + s.execute("layout.parents.new", &json!({"prefix": "B"})).unwrap(); + let r = s.execute("layout.pages.applyParent", &json!({"pages": [1, 2], "parent": "B"})).unwrap(); + assert_eq!(r["applied"], 2); + let doc = s.doc().unwrap(); + for page in [1usize, 2] { + assert!(doc.doc.page(page).unwrap().parent.is_some(), "page {page} took the parent"); + } + } + + /// Refused before the edit starts, so no page changes parent. + #[test] + fn a_page_index_past_the_end_is_refused_by_a_parent() { + let mut s = four_pages(); + // Pages are born on the default parent A, so what must not change is which parent they have. + let b = s.execute("layout.parents.new", &json!({"prefix": "B"})).unwrap()["id"].as_u64().unwrap(); + let before: Vec<_> = (0..4).map(|i| s.doc().unwrap().doc.page(i).unwrap().parent.map(|p| p.0)).collect(); + let err = s.execute("layout.pages.applyParent", &json!({"pages": [4], "parent": "B"})).unwrap_err().to_string(); + assert!(err.contains("no page 4"), "{err}"); + let after: Vec<_> = (0..4).map(|i| s.doc().unwrap().doc.page(i).unwrap().parent.map(|p| p.0)).collect(); + assert_eq!(before, after, "no page changed parent"); + assert!(!after.contains(&Some(b)), "and none took B"); + } + + /// A malformed list is refused instead of quietly dropping the entries it cannot read. + #[test] + fn a_malformed_page_list_is_refused_instead_of_ignored() { + let mut s = four_pages(); + for list in [json!({"pages": "4"}), json!({"pages": [1, "2"]}), json!({})] { + let err = s.execute("layout.pages.delete", &list).unwrap_err().to_string(); + assert!(err.contains("pages takes"), "refused: {list} → {err}"); + } + assert_eq!(pages_left(&s), 4, "and nothing went"); + } + + /// Both commands' `params` doc states that the indices count from 0. + #[test] + fn both_commands_state_the_base_in_their_params() { + for id in ["layout.pages.delete", "layout.pages.applyParent"] { + let spec = crate::cmd::command_specs().iter().find(|s| s.id == id).unwrap(); + assert!(spec.params.contains("0-based"), "{id} says its base: {}", spec.params); + } + } +} diff --git a/crates/engine/src/cmd/layout/sections.rs b/crates/engine/src/cmd/layout/sections.rs index 3a388743d..cbca71f35 100644 --- a/crates/engine/src/cmd/layout/sections.rs +++ b/crates/engine/src/cmd/layout/sections.rs @@ -63,7 +63,13 @@ impl SectionEdit { let start = self.start; // Page 1 always starts a section. if self.remove && start != 0 { - d.sections.retain(|x| x.start != start); + // A section that starts an alternate layout stays (the layout needs it); it just + // continues the previous section's numbers. + if let Some(sec) = d.sections.iter_mut().find(|x| x.start == start && x.layout.is_some()) { + sec.start_number = None; + } else { + d.sections.retain(|x| x.start != start); + } // The pages after it follow the previous section's numbers again. d.repaginate(); return; @@ -74,6 +80,7 @@ impl SectionEdit { style: Default::default(), prefix: String::new(), marker: String::new(), + layout: None, include_prefix: false, }); if let Some(n) = self.start_number { diff --git a/crates/engine/src/cmd/linked.rs b/crates/engine/src/cmd/linked.rs index 0b80e3aab..43695d1f5 100644 --- a/crates/engine/src/cmd/linked.rs +++ b/crates/engine/src/cmd/linked.rs @@ -13,6 +13,7 @@ fn copy_into(d: &mut Document, parent: StoryId, child: StoryId) -> Result<()> { let st = d.story_mut(child).ok_or_else(|| bad("story.link", format!("no story {}", child.0)))?; let (frames, rev, file_link) = (std::mem::take(&mut st.frames), st.rev, st.file_link.take()); *st = Story { id: child, frames, rev: rev.wrapping_add(1), link: Some((parent, src.rev)), file_link, ..src }; + d.prune_story_text_ranges(child); Ok(()) } diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs index 3fc67f822..f048ba98b 100644 --- a/crates/engine/src/cmd/links.rs +++ b/crates/engine/src/cmd/links.rs @@ -1,9 +1,14 @@ //! Window › Links: placed graphics with their status, effective resolution and uses; relink, //! update, embed, go to. //! -//! Every placed graphic keeps its bytes in the document; a linked graphic also remembers its -//! file. Its status compares that file with the copy in the document: missing, modified (the -//! file's bytes differ) or OK. +//! A graphic placed from a file links to it ([`Storage::Linked`]): the document keeps the file's +//! path (absolute, and relative to the document), size, time and content hash, and a proxy +//! image; the bytes are read from the file when needed. Its status is OK while a file at one of +//! those paths holds the recorded bytes (same size and time, or the same hash), Modified when +//! files are there with other bytes, and Missing otherwise. Embed copies the bytes into the +//! document and keeps the link record, so Unembed can link to the file again. An embedded copy +//! from a document saved before linked storage (a link without a hash) is compared with its file +//! byte for byte. //! //! A linked text file (File › Place with Create Links) remembers its file's size and hash on the //! story instead; updating it imports the file again into the story. @@ -13,9 +18,12 @@ use std::path::Path; use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; use designcraft_compose::Cache; -use designcraft_doc::{AssetId, Content, Document, Fingerprint, Item, ItemId, Selection, Story, StoryId, TextFileLink}; +use designcraft_doc::{ + Asset, AssetData, AssetId, Content, Document, Fingerprint, Item, ItemId, LinkedSource, Selection, Storage, Story, StoryId, TextFileLink, +}; use designcraft_geom::Affine; use serde_json::{Value, json}; @@ -24,11 +32,11 @@ use crate::{EngineError, Result, Session}; pub fn specs() -> Vec { vec![ - cmd!(query "links.list", "Links", [], None, "{} → [{asset, name, path, status: ok|modified|missing|embedded, refused?: why a missing link isn't followed (a path on another computer, a device), pixels, pdfCrop (placed PDFs: the box shown), uses: [{id, page, ppi}]}], then linked text files: [{story, name, path, status (also tooLarge: unchanged size, too big to check), edited (the story was changed in the layout), uses: [{id, page}]}]", has_doc, |s, _| { + cmd!(query "links.list", "Links", [], None, "{} → [{asset, name, path, storage: linked|embedded (where a save keeps the bytes), status: ok|modified|missing|embedded|checking (a linked file still being hashed), refused?: why a missing link isn't followed (a path on another computer, a device), pixels, pdfCrop (placed PDFs: the box shown), uses: [{id, page, ppi}]}], then linked text files: [{story, name, path, status (also tooLarge: unchanged size, too big to check), edited (the story was changed in the layout), uses: [{id, page}]}]", has_doc, |s, _| { // Taken out for the call so the document needn't be cloned on every poll. - let mut checks = std::mem::take(&mut s.text_link_checks); - let links = s.doc().map(|d| list(&d.doc, &s.cache, d.path.as_deref().map(Path::new), &mut checks)); - s.text_link_checks = checks; + let mut checks = std::mem::take(&mut s.link_checks); + let links = s.doc().map(|d| list(&d.doc, &s.cache, d.path.as_deref().map(Path::new), Some(&mut checks), None, Some(&d.links)).unwrap_or_default()); + s.link_checks = checks; Ok(Value::Array(links?)) }), cmd!( @@ -63,22 +71,18 @@ pub fn specs() -> Vec { "Embed Link", ["Window", "Links"], None, - "{asset | story} — keep only the copy in the document (a text file: unlink the story)", + "{asset | story} — copy a linked graphic's file into the document (its link is kept for Unembed); fails when the file is missing or has changed (update or relink it first). A text file: unlink the story", has_doc, - |s, p| { - if let Some(sid) = story_param(p) { - return s.edit(|d, _| { - d.story_mut(sid).ok_or_else(|| bad("links.embed", "no such story"))?.file_link = None; - Ok(Value::Null) - }); - } - let aid = asset_param(p, "links.embed")?; - s.edit(|d, _| { - let a = d.assets.get_mut(&aid).ok_or_else(|| bad("links.embed", "no such graphic"))?; - Arc::make_mut(a).link = None; - Ok(Value::Null) - }) - } + embed + ), + cmd!( + "links.unembed", + "Unembed Link…", + ["Window", "Links"], + None, + "{asset, dir?} — link an embedded graphic to a file instead of keeping it in the document: its original file when that still holds the same bytes, else a file written into `dir` (an existing one with the same bytes is reused) → {path}. Not on the web", + can_unembed, + unembed ), cmd!(noundo "links.goTo", "Go To Link", ["Window", "Links"], None, "{asset | story} — selects the frames showing the graphic or the linked text", has_doc, |s, p| { let st = s.doc_mut()?; @@ -137,13 +141,19 @@ pub fn refused(link: &str, document: Option<&Path>) -> Option) -> bool { let Some(link) = &a.link else { return false }; #[cfg(not(target_arch = "wasm32"))] { + if a.storage == Storage::Linked { + return match LinkedSource::of(a, document) { + Some(source) => !crate::asset_io::candidates(&source).iter().any(crate::io::is_file), + None => true, + }; + } !crate::io::document_path(link, document).is_ok_and(crate::io::exists) } #[cfg(target_arch = "wasm32")] @@ -153,36 +163,340 @@ pub fn link_missing(a: &designcraft_doc::Asset, document: Option<&Path>) -> bool } } -/// Link status of an asset in the document at `document`. Only a regular file is compared, so a -/// link to a device (`/dev/zero`) or a FIFO is missing rather than read. -pub fn status(a: &designcraft_doc::Asset, document: Option<&Path>) -> &'static str { - let Some(link) = &a.link else { return "embedded" }; - // Nothing was read from the file (a package's link that wasn't followed): missing, as in - // Preflight. - if a.data.is_empty() { - return "missing"; +/// Linked images checked this session: (asset, the identity of its bytes, the file its link +/// resolves to) → (the file's size and time when it was read, whether it matched the bytes). The +/// resolved file, not the link text, is the key: a relative link names another file once the +/// document is saved elsewhere. The bytes' [`designcraft_doc::SourceKey`] (as the render cache +/// keys them) changes with every relink or update and is never reused, so a remembered answer +/// can never describe other bytes. +pub(crate) type ImageChecks = std::collections::HashMap<(AssetId, designcraft_doc::SourceKey, std::path::PathBuf), (Fingerprint, bool)>; + +/// The size and time to keep with `bytes` just read from a linked file, `before` being the +/// file's from before the read. Kept only when they can vouch for the bytes later: the size is +/// the bytes' (the file didn't change while it was read) and the time is [`settled`] (another +/// write in the same second, a file still being synced, would keep it). A linked text file's time +/// is kept on the same terms. +pub(crate) fn loaded_fingerprint(before: Option, bytes: &[u8]) -> Option { + before.filter(|f| f.size == bytes.len() as u64 && settled(f)) +} + +/// The modification time kept with a linked file whose time couldn't vouch for its bytes when +/// they were read ([`loaded_fingerprint`]): no file has it, so the file is told by its hash until +/// a check finds it holding the bytes and keeps its real time ([`remember_link_files`]). +pub(crate) const UNVERIFIED_MTIME: i64 = i64::MIN; + +/// The file bytes for a graphic were just read from. +pub(crate) struct FileLink { + /// The file's absolute path. + path: String, + /// Its size and time from before the read. + before: Option, +} + +impl FileLink { + pub(crate) fn of(path: &Path, before: Option) -> Self { + let path = std::path::absolute(path).unwrap_or_else(|_| path.to_path_buf()).to_string_lossy().into_owned(); + FileLink { path, before } } +} + +/// The proxy a linked graphic is drawn with while its file can't be read: none for video and +/// sound, or a file that doesn't decode. +pub(super) fn proxy_of(a: &Asset, bytes: &[u8]) -> Option { + if a.mime.starts_with("video/") || a.mime.starts_with("audio/") { + return None; + } + let p = designcraft_render::proxy::make_proxy(bytes, a.page)?; + Some(designcraft_doc::Proxy { mime: p.mime.into(), pixels: p.pixels, data: AssetData::embedded(p.data) }) +} + +/// Give `a` the bytes of a graphic being placed, relinked or updated (its `mime` and `page` set). +/// Bytes read from a file (`file`) link to it ([`link_to_file`]), unless `embed` or on the web, +/// where they are embedded with the link record kept. Other bytes (pasted, dropped, base64) are +/// embedded without a link. +pub(crate) fn give_bytes(a: &mut Asset, bytes: impl Into>>, file: Option, embed: bool, document: Option<&Path>) { + let bytes: Arc> = bytes.into(); + a.proxy = None; + let Some(file) = file else { + a.set_link(None, None); + a.link_relative = None; + a.link_hash = None; + a.storage = Storage::Embedded; + a.data = AssetData::embedded(bytes); + return; + }; + if embed || cfg!(target_arch = "wasm32") { + record_file(a, &bytes, file, document); + a.link_hash = Some(crate::asset_io::content_hash(&bytes)); + a.storage = Storage::Embedded; + a.data = AssetData::embedded(bytes); + return; + } + link_to_file(a, bytes, file, document, None); +} + +/// [`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`]. +#[must_use = "the hash and proxy are made only once the returned work is queued"] +pub(crate) fn give_placed( + a: &mut Asset, + bytes: impl Into>>, + file: Option, + embed: bool, + document: Option<&Path>, +) -> Option { + let bytes: Arc> = bytes.into(); + let file = match file { + Some(file) if !embed && cfg!(not(target_arch = "wasm32")) => file, + file => { + give_bytes(a, bytes, file, embed, document); + return None; + } + }; + record_file(a, &bytes, file, document); + a.link_hash = None; + link_recorded(a, Arc::clone(&bytes), designcraft_doc::SourceKey::fresh(), document, |_, _| None); + Some(super::native_links::Pending::of(a, bytes)) +} + +/// Link `a` to `file`, whose bytes (`bytes`) were just read: the file's record (paths, size and +/// time, content hash) and a proxy to draw while the file can't be read (`preview` when there is +/// one, else made from the bytes). The bytes stay in memory for the first draw. +pub(crate) fn link_to_file(a: &mut Asset, bytes: Arc>, file: FileLink, document: Option<&Path>, preview: Option) { + record_file(a, &bytes, file, document); + a.link_hash = Some(crate::asset_io::content_hash(&bytes)); + link_recorded(a, bytes, designcraft_doc::SourceKey::fresh(), document, |a, bytes| preview.or_else(|| proxy_of(a, bytes))); +} + +/// Add to a graphic placed with [`give_placed`] (or opened with a link that has no hash) its +/// content `hash` and `proxy`, made from the bytes it has under its current key: the hash when it +/// has none, the proxy when it is linked and has none. Its storage stays as it is (a graphic +/// embedded since with Links › Embed stays embedded). → whether `a` changed. +pub(super) fn add_prepared(a: &mut Asset, hash: &str, proxy: Option<&designcraft_doc::Proxy>) -> bool { + let mut changed = false; + if a.link_hash.is_none() { + a.link_hash = Some(hash.to_owned()); + // The same bytes: the key stays, so nothing decoded from them is decoded again. + if let Some(mut source) = a.data.linked_source().cloned() { + source.hash = Some(hash.to_owned()); + a.data = AssetData::linked_under(a.data.key(), source); + } + changed = true; + } + if a.storage == Storage::Linked + && a.proxy.is_none() + && let Some(proxy) = proxy + { + a.proxy = Some(proxy.clone()); + changed = true; + } + changed +} + +/// `a`, whose link record is complete, as a link to its file under `key`: drawn with `proxy`'s +/// image while the file can't be read, and `bytes` (just read from the file) kept in memory for +/// the first draw. Embedded under `key` when the record doesn't name a file. +fn link_recorded( + a: &mut Asset, + bytes: Arc>, + key: designcraft_doc::SourceKey, + document: Option<&Path>, + proxy: impl FnOnce(&Asset, &[u8]) -> Option, +) { + a.link_fingerprint = Some(a.link_fingerprint.unwrap_or(Fingerprint { size: bytes.len() as u64, mtime: UNVERIFIED_MTIME })); + let Some(source) = LinkedSource::of(a, document) else { + a.storage = Storage::Embedded; + a.proxy = None; + a.data = AssetData::embedded_under(key, bytes); + return; + }; + a.storage = Storage::Linked; + a.proxy = proxy(a, &bytes); + a.data = AssetData::linked_under(key, source); + a.data.keep_resident(bytes); +} + +/// Keep with `a` the record of `file`, which `bytes` were read from: its absolute path, its path +/// relative to the `document` file and the size and time that vouch for the bytes +/// ([`loaded_fingerprint`]). The caller sets the content hash. +fn record_file(a: &mut Asset, bytes: &[u8], file: FileLink, document: Option<&Path>) { + a.link_fingerprint = loaded_fingerprint(file.before, bytes); + a.link_relative = document.and_then(|d| super::native_links::relative_to(d, Path::new(&file.path))); + a.link = Some(file.path); +} + +/// Does `bytes` (a file's) hold `a`'s bytes: its recorded hash, or, without one, its bytes? +#[cfg(not(target_arch = "wasm32"))] +fn holds(a: &Asset, bytes: &[u8]) -> bool { + match &a.link_hash { + Some(hash) => *hash == crate::asset_io::content_hash(bytes), + None => a.data.resident().is_some_and(|d| *d == bytes), + } +} + +/// Status of a linked graphic: OK when a file at its absolute or relative path has the recorded +/// size and time (nothing is read), or the recorded size and the recorded bytes (hashed once per +/// new time, `checks`); Modified when files are there and none holds them; Missing when none is. +fn linked_status(a: &Asset, document: Option<&Path>, checks: &mut ImageChecks) -> (&'static str, Option) { + let Some(source) = LinkedSource::of(a, document) else { return ("missing", None) }; #[cfg(not(target_arch = "wasm32"))] { - let Ok(path) = crate::io::document_path(link, document) else { return "missing" }; - if !crate::io::is_file(&path) { - return "missing"; - } - match crate::io::metadata(&path) { - Err(_) => "missing", - Ok(m) if m.len() as usize != a.data.len() => "modified", - // Same size: compare the bytes (cheap for the sizes involved, and exact). - Ok(_) => match crate::io::read_capped(&path, a.data.len() as u64) { - Ok(b) if b == *a.data => "ok", - Ok(_) => "modified", - Err(_) => "missing", - }, + let mut status = "missing"; + for path in crate::asset_io::candidates(&source) { + let Some(meta) = crate::io::file_metadata(&path) else { continue }; + let now = crate::asset_io::fingerprint_from(&meta); + if Some(now) == source.fingerprint && settled(&now) { + return ("ok", None); + } + status = "modified"; + if now.size != source.len { + continue; + } + let key = (a.id, a.data.key(), path.clone()); + let same = match checks.get(&key) { + Some((at, same)) if *at == now => *same, + _ => { + let Ok(bytes) = crate::io::read_capped(&path, source.len) else { continue }; + let same = bytes.len() as u64 == source.len && holds(a, &bytes); + if settled(&now) { + checks.insert(key, (now, same)); + } + same + } + }; + if same { + return ("ok", settled(&now).then_some(now)); + } } + (status, None) } #[cfg(target_arch = "wasm32")] { - let _ = (link, document); - "ok" + let _ = (source, checks); + ("missing", None) + } +} + +/// Whether a linked image's files are there and none holds its bytes ([`linked_status`] +/// "modified"): Preflight's check, which reads a file only as the Links panel does, once per new +/// size and time (`checks`). +pub(crate) fn link_modified(a: &Asset, document: Option<&Path>, checks: &mut LinkListChecks) -> bool { + a.storage == Storage::Linked && linked_status(a, document, &mut checks.images).0 == "modified" +} + +/// Is the linked file still the one the asset's bytes were loaded from, going by the size and +/// time kept then ([`designcraft_doc::Asset::link_fingerprint`], [`loaded_fingerprint`])? Nothing +/// is read when it is, also on the first check after a document is opened, which matters on a +/// network share. A fingerprint of another size than the bytes isn't theirs and doesn't count; a +/// new time or no fingerprint leave it to the byte comparison. +#[cfg(not(target_arch = "wasm32"))] +fn loaded_unchanged(a: &designcraft_doc::Asset, now: Fingerprint) -> bool { + a.link_fingerprint.is_some_and(|loaded| loaded.size == a.data.len() && loaded == now && settled(&now)) +} + +/// Link status of a placed graphic (`ok`, `modified`, `missing`, `embedded`), reading the file +/// only when its size is the asset's and its time is neither the one the bytes were loaded at +/// ([`loaded_unchanged`]) nor the one remembered from the last read (`checks`): the Links panel +/// polls, and a document of press-size images would otherwise be read whole on every poll. A file +/// changed in the last two seconds is never remembered (see [`settled`]). +#[cfg(test)] +pub(crate) fn status_cached(a: &designcraft_doc::Asset, document: Option<&Path>, checks: &mut ImageChecks) -> &'static str { + image_status(a, document, checks, None).0 +} + +/// Whether the automation read roots let this session read a file at one of `a`'s link paths +/// (always without roots in force, and then nothing is asked of the file system). +fn may_read_link(a: &Asset, document: Option<&Path>) -> bool { + #[cfg(not(target_arch = "wasm32"))] + { + LinkedSource::of(a, document).is_some_and(|s| crate::asset_io::candidates(&s).iter().any(|p| crate::file_access::check_read(p).is_ok())) + } + #[cfg(target_arch = "wasm32")] + { + let _ = (a, document); + true + } +} + +/// Whether `a`'s bytes are the document's own copy, with no file to compare them with: embedded +/// with no link, or with the link record Embed keeps (it has a hash; a copy saved before linked +/// storage has none, and is compared with its file). +fn embedded_copy(a: &Asset) -> bool { + a.storage == Storage::Embedded && (a.link.is_none() || a.link_hash.is_some()) +} + +/// [`status_cached`], and the file's size and time when a read found the asset's bytes in it +/// although the fingerprint kept with the asset says nothing or something else: what +/// [`remember_link_files`] keeps, so the file isn't read again in another session. While the +/// background check the open of the document started (`open`) still has the asset's file to look +/// at, it is `checking`; after that the file is looked at as it is now, which may have changed +/// since. +fn image_status( + a: &designcraft_doc::Asset, + document: Option<&Path>, + checks: &mut ImageChecks, + open: Option<&super::native_links::OpenLinks>, +) -> (&'static str, Option) { + if embedded_copy(a) { + return ("embedded", None); + } + if a.storage == Storage::Linked { + if open.is_some_and(|o| o.checking() && o.status(a) == Some(super::native_links::LinkStatus::Checking)) { + // A file this session may not read (outside the automation read roots) is missing, + // whatever the background check finds. + return (if may_read_link(a, document) { "checking" } else { "missing" }, None); + } + return linked_status(a, document, checks); + } + let Some(link) = &a.link else { return ("embedded", None) }; + // Nothing was read from the file (a package's link that wasn't followed): missing, as in + // Preflight. + if a.data.is_empty() { + return ("missing", None); + } + #[cfg(not(target_arch = "wasm32"))] + { + let Ok(path) = crate::io::document_path(link, document) else { return ("missing", None) }; + if !crate::io::is_file(&path) { + return ("missing", None); + } + let now = match crate::io::metadata(&path) { + Err(_) => return ("missing", None), + Ok(m) => super::datamerge::fingerprint_from(&m), + }; + if loaded_unchanged(a, now) { + return ("ok", None); + } + if now.size != a.data.len() { + return ("modified", None); + } + let key = (a.id, a.data.key(), path.clone()); + if let Some((at, same)) = checks.get(&key) + && *at == now + { + return if *same { ("ok", Some(now)) } else { ("modified", None) }; + } + let same = match crate::io::read_capped(&path, a.data.len()) { + Ok(b) => a.data.load().is_ok_and(|d| b == *d), + Err(_) => return ("missing", None), + }; + // The time from before the read: a change during it is seen next time. + let settled = settled(&now); + if settled { + checks.insert(key, (now, same)); + } + if same { ("ok", settled.then_some(now)) } else { ("modified", None) } + } + #[cfg(target_arch = "wasm32")] + { + let _ = (link, document, checks); + ("ok", None) } } @@ -199,9 +513,13 @@ pub(crate) fn checkable_size(len: usize) -> bool { /// while the file was changed in the last two: another change in that second keeps the time. A /// time in the future (clock skew, a file copied from another machine) counts as settled, or such /// a file would be read on every poll; a later save gives it a time unlike the remembered one. +/// A file without a time ([`crate::asset_io::has_time`]) never is. pub(crate) fn settled(f: &Fingerprint) -> bool { #[cfg(not(target_arch = "wasm32"))] { + if !crate::asset_io::has_time(f) { + return false; + } let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| i64::try_from(d.as_secs()).unwrap_or(i64::MAX)); f.mtime > now || now.saturating_sub(f.mtime) >= 2 } @@ -317,17 +635,146 @@ fn shown<'a>(d: &'a Document, cache: &Cache, aid: AssetId) -> Vec> { out } -fn list(d: &Document, cache: &Cache, document: Option<&Path>, checks: &mut TextChecks) -> Vec { - let texts = d.stories.values().filter_map(|st| { - let l = st.file_link.as_ref()?; +/// What a check of a document's links remembers between runs: the linked text files and images +/// already compared with the document ([`TextChecks`], [`ImageChecks`]), so a poll reads nothing +/// unchanged. The [`Session`] keeps one for `links.list`; a caller that lists a document's links +/// itself ([`list_document_links`]) keeps its own. +#[derive(Default)] +pub struct LinkListChecks { + text: TextChecks, + images: ImageChecks, + /// Linked images the latest list read and found to hold the document's bytes, with the file's + /// size and time then ([`LinkListChecks::take_verified`]). + verified: Vec<(AssetId, Fingerprint)>, +} + +impl LinkListChecks { + /// The linked images the latest list found unchanged by comparing bytes, because the size + /// and time kept with them said nothing or something else: [`remember_link_files`] keeps the + /// file's current ones with them. + pub fn take_verified(&mut self) -> Vec<(AssetId, Fingerprint)> { + std::mem::take(&mut self.verified) + } + + /// Add what `other` remembers (the checks of another worker thread). + pub fn absorb(&mut self, other: LinkListChecks) { + self.text.extend(other.text); + self.images.extend(other.images); + } + + /// How many files are remembered. + pub fn len(&self) -> usize { + self.text.len() + self.images.len() + } + + /// Is nothing remembered yet? + pub fn is_empty(&self) -> bool { + self.len() == 0 + } +} + +/// The rows of `links.list` without looking at a linked file: `checking` stands where a file +/// would be read or asked for its size and time. A native UI shows these at once and fills in +/// what [`list_document_links`] finds on a worker thread, where a share that doesn't answer +/// can't stall it. +pub fn preview_document_links(d: &Document, cache: &Cache, document: Option<&Path>) -> Vec { + list(d, cache, document, None, None, None).unwrap_or_default() +} + +/// The rows of `links.list` for a document outside a [`Session`], so a native UI can check the +/// linked files on a worker thread. `checks` is what the worker remembers between calls. Another +/// thread sets `stop` to end the check before its next file (the one being asked may be on a +/// share that doesn't answer, and hundreds more may follow it): nothing is returned then. +pub fn list_document_links( + d: &Document, + cache: &Cache, + document: Option<&Path>, + checks: &mut LinkListChecks, + stop: &AtomicBool, +) -> Option> { + list(d, cache, document, Some(checks), Some(stop), None) +} + +/// Keep, with each linked image in `files`, the size and time its file had when a check read it +/// and found the document's bytes in it ([`LinkListChecks::take_verified`]). Later checks, and +/// the first one of another session, then don't read it: copying, restoring or checking out a +/// project folder gives every file a new time. `doc` is the document the check ran on: nothing +/// is kept when the active document isn't that one any more (other bytes may be linked by now), +/// or during a gesture. Nothing placed changes, so a saved document stays saved; the times go +/// into its file with the next save. → how many were kept +pub fn remember_link_files(s: &mut Session, doc: &Arc, files: &[(AssetId, Fingerprint)]) -> usize { + let Ok(st) = s.doc_mut() else { return 0 }; + if !Arc::ptr_eq(&st.doc, doc) || st.interaction.is_some() { + return 0; + } + let stale = |a: &designcraft_doc::Asset, f: &Fingerprint| a.link.is_some() && a.data.len() == f.size && a.link_fingerprint != Some(*f); + let fresh: Vec<(AssetId, Fingerprint)> = files.iter().filter(|(id, f)| st.doc.assets.get(id).is_some_and(|a| stale(a, f))).copied().collect(); + if fresh.is_empty() { + return 0; + } + let saved = !st.is_dirty(); + let document = st.path.clone(); + let d = Arc::make_mut(&mut st.doc); + for (id, f) in &fresh { + if let Some(a) = d.assets.get_mut(id) { + let a = Arc::make_mut(a); + a.link_fingerprint = Some(*f); + // Linked bytes are read by that time too (the same bytes, found in the file: the key + // stays, also for a link with no hash yet). + if a.data.is_linked() + && let Some(source) = LinkedSource::of(a, document.as_deref().map(Path::new)) + { + a.data = AssetData::linked_under(a.data.key(), source); + } + } + } + if saved { + st.saved_doc = Arc::clone(&st.doc); + } + fresh.len() +} + +/// `links.list`: every used placed graphic, then every linked text file, each with its status. +/// `files` is what was read this session (a poll reads nothing unchanged); without it no file is +/// looked at and a status that needs one is `checking` ([`preview_document_links`]). `None` when +/// `stop` was set before the last link was reached. +fn list( + d: &Document, + cache: &Cache, + document: Option<&Path>, + files: Option<&mut LinkListChecks>, + stop: Option<&AtomicBool>, + open: Option<&super::native_links::OpenLinks>, +) -> Option> { + let stopped = || stop.is_some_and(|stop| stop.load(Ordering::Relaxed)); + let (mut checks, mut images, mut verified) = match files { + Some(files) => { + files.verified.clear(); + (Some(&mut files.text), Some(&mut files.images), Some(&mut files.verified)) + } + None => (None, None, None), + }; + let texts = d.stories.values().filter_map(|st| Some((st, st.file_link.as_ref()?))).map(|(st, l)| { + if stopped() { + return None; + } let uses: Vec = st.frames.iter().map(|id| json!({"id": id.0, "page": d.page_of_item(*id).map(|p| d.page_name(p))})).collect(); - Some(json!({"story": st.id.0, "name": file_name(&l.path), "path": l.path, "status": text_status(l, checks, document), "refused": refused(&l.path, document).map(|r| r.to_string()), "edited": story_hash(st) != l.story_hash, "uses": uses})) + let why = refused(&l.path, document).map(|r| r.to_string()); + let status = match checks.as_deref_mut() { + Some(checks) => text_status(l, checks, document), + None if why.is_some() => "missing", + None => "checking", + }; + Some(json!({"story": st.id.0, "name": file_name(&l.path), "path": l.path, "status": status, "refused": why, "edited": story_hash(st) != l.story_hash, "uses": uses})) }); let used = d.used_assets(); d.assets .values() .filter(|a| used.contains(&a.id)) .map(|a| { + if stopped() { + return None; + } let uses: Vec = shown(d, cache, a.id) .into_iter() .map(|u| { @@ -350,7 +797,23 @@ fn list(d: &Document, cache: &Cache, document: Option<&Path>, checks: &mut TextC .collect(); let pdf_crop = (a.mime == "application/pdf").then(|| a.pdf_crop.name()); let why = a.link.as_deref().and_then(|l| refused(l, document)).map(|r| r.to_string()); - json!({"asset": a.id.0, "name": a.name, "path": a.link, "status": status(a, document), "refused": why, "pixels": a.pixels, "pdfCrop": pdf_crop, "uses": uses}) + let status = match images.as_deref_mut() { + Some(images) => { + let (status, file) = image_status(a, document, images, open); + if let (Some(verified), Some(file)) = (verified.as_deref_mut(), file) { + verified.push((a.id, file)); + } + status + } + None if embedded_copy(a) => "embedded", + None if a.data.is_empty() || why.is_some() => "missing", + None => open.and_then(|o| o.status(a)).map_or("checking", |s| s.as_str()), + }; + let storage = match a.storage { + Storage::Linked => "linked", + Storage::Embedded => "embedded", + }; + Some(json!({"asset": a.id.0, "name": a.name, "path": a.link, "storage": storage, "status": status, "refused": why, "pixels": a.pixels, "pdfCrop": pdf_crop, "uses": uses})) }) .chain(texts) .collect() @@ -425,10 +888,11 @@ fn reload(path: impl AsRef) -> Result<(Vec, (u32, u32))> { Err(EngineError::Other(format!("{}: files can't be read on the web", path.as_ref().display()))) } -/// The replacement for `a`: bytes read from `read`, with `link` recorded as the stored link. -/// Relink passes the file the user chose as both. Update passes the path the stored link resolved -/// to and the stored link itself, so refreshing a link never rewrites what the document holds. -fn relinked_asset(a: &designcraft_doc::Asset, read: &Path, link: &str) -> Result> { +/// The replacement for `a`: bytes read from the file at `read`, linked to it (its absolute path, +/// and its path relative to the `document` file) with a new hash and proxy. +fn relinked_asset(a: &designcraft_doc::Asset, read: &Path, document: Option<&Path>) -> Result> { + // 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 px = if page > 0 { @@ -440,16 +904,27 @@ fn relinked_asset(a: &designcraft_doc::Asset, read: &Path, link: &str) -> Result }; let mut a = a.clone(); a.mime = designcraft_render::image_mime(&bytes).to_string(); - a.data = Arc::new(bytes); a.pixels = Some(px); a.page = page; - a.name = Path::new(link).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| link.to_string()); - a.link = Some(link.to_string()); + 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(&mut a); + 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)) } +/// The file Update reads `a`'s bytes from: the first of a linked graphic's paths that holds a +/// file, or where the link of an embedded copy resolves. +fn update_source(a: &Asset, document: Option<&Path>) -> Option { + if a.storage == Storage::Linked { + let source = LinkedSource::of(a, document)?; + return crate::asset_io::candidates(&source).into_iter().find(|p| crate::io::is_file(p)); + } + crate::io::document_path(a.link.as_deref()?, document).ok() +} + +/// `links.relink`: a placed graphic or linked text file takes its bytes from `path` from now on. fn relink(s: &mut Session, p: &Value) -> Result { let path = str_param(p, "path").ok_or_else(|| bad("links.relink", "missing path"))?.to_string(); if let Some(sid) = story_param(p) { @@ -461,16 +936,22 @@ fn relink(s: &mut Session, p: &Value) -> Result { }); } let aid = asset_param(p, "links.relink")?; - let a = s.doc()?.doc.assets.get(&aid).ok_or_else(|| bad("links.relink", "no such graphic"))?; + let st = s.doc()?; + let a = st.doc.assets.get(&aid).ok_or_else(|| bad("links.relink", "no such graphic"))?; // Build the replacement before the edit: a file that cannot be read leaves the document as it was. - let fresh = relinked_asset(a, Path::new(&path), &path)?; - s.edit(|d, _| { + let fresh = relinked_asset(a, Path::new(&path), st.path.as_deref().map(Path::new))?; + let r = s.edit(|d, _| { let name = fresh.name.clone(); d.assets.insert(aid, fresh); Ok(json!({"name": name})) - }) + }); + s.link_checks.images.clear(); + designcraft_doc::asset_data::links_changed(); + r } +/// `links.relinkFolder`: relink graphics to same-named files in a folder and/or with another +/// extension (the missing ones by default). fn relink_folder(s: &mut Session, p: &Value) -> Result { let dir = str_param(p, "dir").map(std::path::PathBuf::from); if let Some(dir) = &dir { @@ -486,12 +967,15 @@ fn relink_folder(s: &mut Session, p: &Value) -> Result { } let missing_only = p.get("missingOnly").and_then(Value::as_bool).unwrap_or(dir.is_some() && ext.is_none()); let only: Option> = p.get("assets").and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_u64).collect()); + let mut images = std::mem::take(&mut s.link_checks.images); let st = s.doc()?; let (d, document) = (&st.doc, st.path.as_deref().map(Path::new)); let mut todo: Vec<(AssetId, std::path::PathBuf)> = Vec::new(); let mut not_found = Vec::new(); for a in d.assets.values() { - if only.as_ref().is_some_and(|o| !o.contains(&a.id.0)) || (missing_only && status(a, document) != "missing") { + if only.as_ref().is_some_and(|o| !o.contains(&a.id.0)) + || (missing_only && image_status(a, document, &mut images, Some(&st.links)).0 != "missing") + { continue; } let old = std::path::PathBuf::from(a.link.clone().unwrap_or_else(|| a.name.clone())); @@ -528,7 +1012,7 @@ fn relink_folder(s: &mut Session, p: &Value) -> Result { let mut fresh = Vec::new(); for (aid, path) in todo { let a = d.assets.get(&aid).ok_or_else(|| bad("links.relinkFolder", "no such graphic"))?; - fresh.push((aid, relinked_asset(a, &path, &path.to_string_lossy())?)); + fresh.push((aid, relinked_asset(a, &path, document)?)); } let n = fresh.len(); if n > 0 { @@ -538,17 +1022,182 @@ fn relink_folder(s: &mut Session, p: &Value) -> Result { } Ok(()) })?; + images.clear(); + designcraft_doc::asset_data::links_changed(); } + s.link_checks.images = images; Ok(json!({"relinked": n, "notFound": not_found})) } +/// Unembed reads and writes files: not on the web. +fn can_unembed(s: &Session) -> std::result::Result<(), String> { + has_doc(s)?; + if cfg!(target_arch = "wasm32") { + return Err("files can't be linked on the web".into()); + } + Ok(()) +} + +/// `links.embed`: the graphic's bytes go into the document, checked against the link record. +fn embed(s: &mut Session, p: &Value) -> Result { + const ID: &str = "links.embed"; + if let Some(sid) = story_param(p) { + return s.edit(|d, _| { + d.story_mut(sid).ok_or_else(|| bad(ID, "no such story"))?.file_link = None; + Ok(Value::Null) + }); + } + let aid = asset_param(p, ID)?; + let st = s.doc()?; + let document = st.path.as_deref().map(Path::new); + let a = st.doc.assets.get(&aid).ok_or_else(|| bad(ID, "no such graphic"))?; + if a.storage == Storage::Linked { + if cfg!(target_arch = "wasm32") { + return Err(bad(ID, format!("{}: linked files can't be read on the web", a.name))); + } + // Checked even when the bytes are in memory: what is embedded is what the file holds. + match linked_status(a, document, &mut ImageChecks::default()).0 { + "missing" => return Err(bad(ID, format!("{}: the linked file is missing; relink it, then embed it", a.name))), + "modified" => return Err(bad(ID, format!("{}: the linked file has changed; update or relink it, then embed it", a.name))), + _ => {} + } + } + let bytes = a.data.load().map_err(|e| bad(ID, format!("{}: {e}", a.name)))?; + // A link without a hash would be taken for a copy saved before linked storage. + let hash = a.link_hash.clone().or_else(|| a.link.is_some().then(|| crate::asset_io::content_hash(&bytes))); + let key = a.data.key(); + s.edit(|d, _| { + let a = Arc::make_mut(d.assets.get_mut(&aid).ok_or_else(|| bad(ID, "no such graphic"))?); + // The same bytes: what was decoded from them stays usable. + a.data = AssetData::embedded_under(key, bytes); + a.storage = Storage::Embedded; + a.proxy = None; + a.link_hash = hash; + Ok(Value::Null) + })?; + Ok(Value::Null) +} + +/// The file in `folder` named like the original (or `name` with an extension for `mime`) that +/// holds `bytes`: an existing one with exactly these bytes, else a new one written there. +#[cfg(not(target_arch = "wasm32"))] +fn write_into(folder: &Path, name: &str, mime: &str, bytes: &[u8]) -> Result { + const ID: &str = "links.unembed"; + if !crate::io::is_dir(folder) { + return Err(bad(ID, format!("{}: not a folder", folder.display()))); + } + let file = Path::new(name).file_name().map(|n| n.to_string_lossy().into_owned()).filter(|n| !n.is_empty()).unwrap_or_else(|| "graphic".into()); + let mut file = std::path::PathBuf::from(file); + if file.extension().is_none() { + let ext = match mime { + "image/jpeg" => "jpg", + "image/gif" => "gif", + "image/tiff" => "tif", + "image/webp" => "webp", + "image/svg+xml" => "svg", + "application/pdf" => "pdf", + "application/postscript" => "eps", + "image/png" => "png", + _ => "bin", + }; + file.set_extension(ext); + } + let stem = file.file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default(); + let ext = file.extension().map(|e| e.to_string_lossy().into_owned()).unwrap_or_default(); + for n in 0..1000u32 { + let candidate = if n == 0 { folder.join(&file) } else { folder.join(format!("{stem}-{n}.{ext}")) }; + if !crate::io::exists(&candidate) { + crate::io::write_file(&candidate, bytes).map_err(EngineError::Other)?; + return Ok(candidate); + } + if file_holds(&candidate, bytes) { + return Ok(candidate); + } + } + Err(bad(ID, format!("{}: no free file name for {}", folder.display(), file.display()))) +} + +/// Does the regular file at `path` hold exactly `bytes`? +#[cfg(not(target_arch = "wasm32"))] +fn file_holds(path: &Path, bytes: &[u8]) -> bool { + crate::io::file_metadata(path).is_some_and(|m| m.len() == bytes.len() as u64) + && crate::io::read_capped(path, bytes.len() as u64).is_ok_and(|b| b == bytes) +} + +/// `links.unembed`: an embedded graphic links to its original file, or to a copy written into `dir`. +fn unembed(s: &mut Session, p: &Value) -> Result { + const ID: &str = "links.unembed"; + can_unembed(s).map_err(|e| bad(ID, e))?; + let aid = asset_param(p, ID)?; + let st = s.doc()?; + let document = st.path.clone(); + let document = document.as_deref().map(Path::new); + let a = st.doc.assets.get(&aid).ok_or_else(|| bad(ID, "no such graphic"))?; + if a.storage == Storage::Linked { + return Err(bad(ID, format!("{} is already linked", a.name))); + } + let bytes = a + .data + .embedded_bytes() + .cloned() + .filter(|b| !b.is_empty()) + .ok_or_else(|| bad(ID, format!("{}: the document holds no bytes for it", a.name)))?; + #[cfg(not(target_arch = "wasm32"))] + { + let original = a.link.as_ref().and_then(|link| { + let source = LinkedSource { + path: link.clone(), + relative: a.link_relative.clone(), + document: document.map(Path::to_path_buf), + len: bytes.len() as u64, + fingerprint: None, + hash: None, + }; + crate::asset_io::candidates(&source).into_iter().find(|p| file_holds(p, &bytes)) + }); + let target = match (original, str_param(p, "dir")) { + (Some(original), _) => original, + (None, Some(dir)) => { + let dir = Path::new(dir); + crate::file_access::check_write(dir).map_err(EngineError::Other)?; + write_into(dir, &a.name, &a.mime, &bytes)? + } + (None, None) => return Err(bad(ID, format!("{}: its original file is missing or has changed; give `dir` to write it there", a.name))), + }; + let before = super::datamerge::fingerprint_of(&target); + let file = FileLink::of(&target, before); + let key = a.data.key(); + let mut linked = (**a).clone(); + give_bytes(&mut linked, Arc::clone(&bytes), Some(file), false, document); + // The same bytes: what was decoded from them stays usable. + if let Some(source) = linked.data.linked_source().cloned() { + linked.data = AssetData::linked_under(key, source); + linked.data.keep_resident(bytes); + } + let path = linked.link.clone(); + let r = s.edit(|d, _| { + d.assets.insert(aid, Arc::new(linked)); + Ok(json!({"path": path})) + }); + s.link_checks.images.clear(); + designcraft_doc::asset_data::links_changed(); + r + } + #[cfg(target_arch = "wasm32")] + { + let _ = (document, bytes); + Err(bad(ID, "files can't be linked on the web")) + } +} + +/// `links.update`: re-read the modified links (one, or every one) from where they resolve. fn update(s: &mut Session, p: &Value) -> Result { - let (d, document) = { + let (d, document, open) = { let st = s.doc()?; - (st.doc.clone(), st.path.clone()) + (st.doc.clone(), st.path.clone(), st.links.clone()) }; let document = document.as_deref().map(Path::new); - let checks = &mut s.text_link_checks; + let LinkListChecks { text: checks, images, .. } = &mut s.link_checks; let (only_asset, only_story) = (p.get("asset").and_then(Value::as_u64), story_param(p)); let all = only_asset.is_none() && only_story.is_none(); // A link craft-docpath refuses is missing, so it is never read or refreshed. @@ -563,13 +1212,14 @@ fn update(s: &mut Session, p: &Value) -> Result { }) .collect(); let mut fresh = Vec::new(); - for a in d.assets.values().filter(|a| all || only_asset == Some(a.id.0)).filter(|a| status(a, document) == "modified") { - // The bytes come from where the stored link resolves; the link itself stays as the - // document stored it, so refreshing never rewrites a relative link to an absolute one. - if let Some((link, at)) = a.link.as_deref().and_then(|l| resolved(l).map(|at| (l, at))) { - fresh.push((a.id, relinked_asset(a, &at, link)?)); + for a in + d.assets.values().filter(|a| all || only_asset == Some(a.id.0)).filter(|a| image_status(a, document, images, Some(&open)).0 == "modified") + { + if let Some(at) = update_source(a, document) { + fresh.push((a.id, relinked_asset(a, &at, document)?)); } } + drop(open); let mut fresh_texts = Vec::new(); for (sid, path, at) in texts { let (bytes, before) = read_text(&at)?; @@ -579,7 +1229,7 @@ fn update(s: &mut Session, p: &Value) -> Result { if n == 0 { return Ok(json!({"updated": 0})); } - s.edit(|d, _| { + let r = s.edit(|d, _| { for (aid, a) in fresh { d.assets.insert(aid, a); } @@ -588,7 +1238,10 @@ fn update(s: &mut Session, p: &Value) -> Result { warnings.extend(reimport(d, *sid, path, bytes, *before)?); } Ok(json!({"updated": n, "warnings": warnings})) - }) + }); + s.link_checks.images.clear(); + designcraft_doc::asset_data::links_changed(); + r } #[cfg(test)] @@ -613,6 +1266,7 @@ mod relink_folder_tests { std::fs::write(&path, r#""#).unwrap(); s.doc_mut().unwrap().selection = Default::default(); s.execute("file.place", &json!({"path": path.to_string_lossy()})).unwrap(); + crate::cmd::native_links::wait(&mut s); std::fs::rename(&path, dir.join("new").join(name)).unwrap(); } (s, dir) @@ -680,6 +1334,7 @@ mod relink_folder_tests { let mut s = Session::new(); s.execute("file.new", &json!({})).unwrap(); s.execute("file.place", &json!({"path": orig.to_string_lossy()})).unwrap(); + crate::cmd::native_links::wait(&mut s); // The file moves away: relink from the new folder. std::fs::rename(&orig, dir.join("new").join("logo.svg")).unwrap(); let r = s.execute("links.relinkFolder", &json!({"dir": dir.join("new").to_string_lossy()})).unwrap(); @@ -743,6 +1398,7 @@ mod shared_asset_tests { for (path, x) in [(&a, 72), (&b, 200)] { s.execute("edit.deselectAll", &json!({})).unwrap(); s.execute("file.place", &json!({"path": path.to_string_lossy(), "x": x, "y": 72})).unwrap(); + crate::cmd::native_links::wait(&mut s); } assert_eq!(s.doc().unwrap().doc.assets.len(), 2); let rows = |s: &mut Session| -> Vec<(String, Value)> { @@ -770,7 +1426,7 @@ mod shared_asset_tests { id: AssetId(id), name: "p.png".into(), mime: "image/png".into(), - data: Arc::new(data), + data: designcraft_doc::AssetData::embedded(data), ..Default::default() }; let mut src = Document::new(&NewDocument::default()); @@ -825,7 +1481,7 @@ mod shared_asset_tests { name: "p.png".into(), mime: "image/png".into(), link: None, - data: Arc::new(png(8, 4)), + data: designcraft_doc::AssetData::embedded(png(8, 4)), pixels: None, ..Default::default() }), @@ -902,7 +1558,6 @@ mod text_link_tests { /// A small Word file: a Title paragraph, then Body paragraphs (`body` is WordprocessingML). fn docx(body: &str) -> Vec { - use std::io::Write; const W: &str = r#"xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main""#; let styles = format!( r#" @@ -912,13 +1567,7 @@ mod text_link_tests { r#"Head {body}"# ); - let mut w = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); - let o = zip::write::SimpleFileOptions::default(); - for (n, c) in [("word/document.xml", doc), ("word/styles.xml", styles)] { - w.start_file(n, o).unwrap(); - w.write_all(c.as_bytes()).unwrap(); - } - w.finish().unwrap().into_inner() + crate::cmd::place_text::word_package(&doc, &styles) } fn text_rows(s: &mut Session) -> Vec { @@ -1055,6 +1704,7 @@ mod text_link_tests { let mut s = Session::new(); s.execute("file.new", &json!({})).unwrap(); s.execute("file.place", &json!({"path": path.to_string_lossy(), "link": true})).unwrap(); + crate::cmd::native_links::wait(&mut s); let status = |s: &mut Session| text_rows(s)[0]["status"].as_str().unwrap().to_string(); // Size and time as placed: not read. @@ -1096,6 +1746,16 @@ mod text_link_tests { let _ = std::fs::remove_dir_all(&dir); } + #[test] + fn placed_plain_text_drops_story_markers() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let b64 = crate::cmd::base64_encode("a\u{E009}b\u{E000}c\u{E002}d".as_bytes()); + let r = s.execute("file.place", &json!({"base64": b64, "name": "n.txt", "rect": [72, 72, 300, 200]})).unwrap(); + let st = s.doc().unwrap().doc.story(StoryId(r["story"].as_u64().unwrap())).unwrap(); + assert_eq!(st.text, "abcd"); + } + #[test] fn create_links_when_placing_text_files_preference() { let dir = std::env::temp_dir().join(format!("dc-text-link-pref-{}", std::process::id())); @@ -1126,6 +1786,7 @@ mod text_link_tests { let sid = fr["story"].as_u64().unwrap(); s.execute("text.select", &json!({"story": sid, "anchor": 6, "focus": 6})).unwrap(); let r = s.execute("file.place", &json!({"path": path.to_string_lossy()})).unwrap(); + crate::cmd::native_links::wait(&mut s); assert!(r["warnings"][0].as_str().unwrap().contains("not linked"), "{r}"); assert!(s.doc().unwrap().doc.story(StoryId(sid)).unwrap().file_link.is_none()); let _ = std::fs::remove_dir_all(&dir); diff --git a/crates/engine/src/cmd/links/tests.rs b/crates/engine/src/cmd/links/tests.rs index 8089b24ce..8de21fb14 100644 --- a/crates/engine/src/cmd/links/tests.rs +++ b/crates/engine/src/cmd/links/tests.rs @@ -4,6 +4,350 @@ fn png(w: u32, h: u32) -> Vec { designcraft_render::Rendered { width: w, height: h, pixels: vec![200u8; (w * h * 4) as usize] }.to_png() } +/// The Links panel polls `links.list` twice a second: a linked image whose file keeps its size +/// and time is not read again (press-size images would otherwise be read whole on every poll). +/// A new time is read once; changed bytes show as modified; an update is remembered. +#[cfg(all(unix, not(target_arch = "wasm32")))] +#[test] +fn unchanged_linked_images_are_not_read_again() { + use std::os::unix::fs::PermissionsExt; + let dir = std::env::temp_dir().join(format!("dc-image-link-poll-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("photo.png"); + // Two valid images of the same byte length (a uniform fill compresses to the same size + // whatever its value), so a change shows only in the bytes. + let a = png(40, 40); + let b = designcraft_render::Rendered { width: 40, height: 40, pixels: vec![100u8; 40 * 40 * 4] }.to_png(); + assert_eq!(a.len(), b.len(), "the test needs two files of one size"); + assert_ne!(a, b); + std::fs::write(&path, &a).unwrap(); + // Unreadable: a status that reads the file would say missing. + let readable = |on: bool| std::fs::set_permissions(&path, std::fs::Permissions::from_mode(if on { 0o644 } else { 0o000 })).unwrap(); + // A time `secs` ago (a file changed in the last two seconds is always read). + let touch = |secs: u64| { + let f = std::fs::File::options().write(true).open(&path).unwrap(); + f.set_modified(std::time::SystemTime::now() - std::time::Duration::from_secs(secs)).unwrap(); + }; + touch(60); + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + s.execute("file.place", &json!({"path": path.to_string_lossy(), "link": true})).unwrap(); + crate::cmd::native_links::wait(&mut s); + let status = |s: &mut Session| { + let l = s.execute("links.list", &json!({})).unwrap(); + l.as_array().unwrap().iter().find(|r| r.get("asset").is_some()).unwrap()["status"].as_str().unwrap().to_string() + }; + + // First poll reads and remembers; the second doesn't read. + assert_eq!(status(&mut s), "ok"); + readable(false); + if std::fs::read(&path).is_ok() { + // Running as root: permissions don't stop reads, so this can't be observed. + let _ = std::fs::remove_dir_all(&dir); + return; + } + assert_eq!(status(&mut s), "ok", "same size and time: not read"); + // Saved again unchanged (a new time): read once, then not again. + readable(true); + touch(30); + assert_eq!(status(&mut s), "ok"); + readable(false); + assert_eq!(status(&mut s), "ok", "the second poll doesn't read it"); + // Changed, same size, new time: modified — and remembered, not re-read. + readable(true); + std::fs::write(&path, &b).unwrap(); + touch(20); + assert_eq!(status(&mut s), "modified"); + readable(false); + assert_eq!(status(&mut s), "modified", "a modified answer is remembered too"); + // Updated: the document's bytes are the file's, so the next poll reads once and says ok. + readable(true); + assert_eq!(s.execute("links.update", &json!({})).unwrap()["updated"], 1); + assert_eq!(status(&mut s), "ok"); + readable(false); + assert_eq!(status(&mut s), "ok", "remembered after the update"); + // A different size needs no read at all. + readable(true); + std::fs::write(&path, png(41, 41)).unwrap(); + touch(10); + readable(false); + assert_eq!(status(&mut s), "modified", "size differs: decided from metadata"); + readable(true); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A file's time `secs` ago (a file changed in the last two seconds is always read). +#[cfg(not(target_arch = "wasm32"))] +fn set_age(path: &Path, secs: u64) { + let f = std::fs::File::options().write(true).open(path).unwrap(); + f.set_modified(std::time::SystemTime::now() - std::time::Duration::from_secs(secs)).unwrap(); +} + +/// The size and time an image was loaded at are kept with it, so a file that still has them is +/// not read at all, also on the first check after a document is opened (nothing is remembered +/// yet then, and reading every link of a document on a network share takes minutes). The bytes +/// here differ from the file's on purpose: a status that read the file would say modified. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_linked_image_at_its_loaded_size_and_time_is_not_read() { + let dir = std::env::temp_dir().join(format!("dc-image-link-loaded-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("photo.bin"); + std::fs::write(&path, b"file").unwrap(); + set_age(&path, 60); + let loaded = crate::cmd::datamerge::fingerprint_of(&path).unwrap(); + let asset = |link_fingerprint| designcraft_doc::Asset { + id: AssetId(1), + link: Some(path.to_string_lossy().into_owned()), + link_fingerprint, + data: designcraft_doc::AssetData::embedded(b"data".to_vec()), + ..Default::default() + }; + let status = |a: &designcraft_doc::Asset| status_cached(a, None, &mut ImageChecks::default()); + + assert_eq!(status(&asset(Some(loaded))), "ok", "the size and time it was loaded at: not read"); + // No fingerprint (a document from before they were kept) or another time: compared. + assert_eq!(status(&asset(None)), "modified"); + assert_eq!(status(&asset(Some(Fingerprint { mtime: loaded.mtime - 60, ..loaded }))), "modified", "a new time alone is compared"); + // Bytes replaced without their fingerprint: it is of another size, so it isn't theirs. + let swapped = designcraft_doc::Asset { data: designcraft_doc::AssetData::embedded(b"other bytes".to_vec()), ..asset(Some(loaded)) }; + assert_eq!(status(&swapped), "modified"); + // A time too recent to trust: another write in the same second would keep it. + set_age(&path, 0); + let recent = crate::cmd::datamerge::fingerprint_of(&path).unwrap(); + assert_eq!(status(&asset(Some(recent))), "modified"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A file saved again unchanged, or copied, restored from a backup or checked out again, has a +/// new time and the same bytes: it stays OK (only a new size is conclusive), read once per new +/// time. The fingerprint is saved with the document, so every link of a copied project folder +/// would otherwise show Modified. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_graphic_rewritten_with_the_same_bytes_stays_ok() { + let dir = std::env::temp_dir().join(format!("dc-link-touched-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("logo.png"); + let image = png(2, 2); + let rewrite = |bytes: &[u8], age: u64| { + std::fs::write(&path, bytes).unwrap(); + set_age(&path, age); + }; + rewrite(&image, 300); + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let aid = AssetId(s.execute("file.place", &json!({"path": path.to_string_lossy()})).unwrap()["asset"].as_u64().unwrap()); + crate::cmd::native_links::wait(&mut s); + rewrite(&image, 60); + let a = s.doc().unwrap().doc.assets[&aid].clone(); + assert!(a.link_fingerprint.is_some()); + assert_ne!(a.link_fingerprint, crate::cmd::datamerge::fingerprint_of(&path), "the file has another time than when it was placed"); + let mut checks = ImageChecks::default(); + assert_eq!(status_cached(&a, None, &mut checks), "ok"); + assert_eq!(s.execute("links.list", &json!({})).unwrap()[0]["status"], "ok"); + + // One byte changed, same size, at a time not seen before: compared again. + let mut changed = image.clone(); + if let Some(last) = changed.last_mut() { + *last ^= 0xff; + } + rewrite(&changed, 120); + assert_eq!(status_cached(&a, None, &mut checks), "modified"); + assert_eq!(s.execute("links.list", &json!({})).unwrap()[0]["status"], "modified"); + // Update remembers the file it read, so the next check needs no read. + assert_eq!(s.execute("links.update", &json!({})).unwrap()["updated"], 1); + let a = s.doc().unwrap().doc.assets[&aid].clone(); + assert_eq!(a.link_fingerprint, crate::cmd::datamerge::fingerprint_of(&path)); + assert_eq!(s.execute("links.list", &json!({})).unwrap()[0]["status"], "ok"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// The rows a UI shows while the files are checked on a worker thread come from the document +/// alone: no file is looked at, not even for its size, so a share that doesn't answer can't +/// hold them back. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn preview_rows_look_at_no_file() { + let dir = std::env::temp_dir().join(format!("dc-link-preview-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let (linked, embedded, gone) = (dir.join("linked.png"), dir.join("embedded.png"), dir.join("gone.png")); + for (path, width) in [(&linked, 10), (&embedded, 11), (&gone, 12)] { + std::fs::write(path, png(width, 10)).unwrap(); + set_age(path, 60); + } + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let place = |s: &mut Session, path: &Path, x: u32| { + let id = AssetId(s.execute("file.place", &json!({"path": path.to_string_lossy(), "x": x, "y": 72})).unwrap()["asset"].as_u64().unwrap()); + crate::cmd::native_links::wait(s); + id + }; + let ids = [place(&mut s, &linked, 72), place(&mut s, &embedded, 144), place(&mut s, &gone, 216)]; + s.execute("links.embed", &json!({"asset": ids[1].0})).unwrap(); + std::fs::remove_file(&gone).unwrap(); + let st = s.doc().unwrap(); + assert!(st.doc.assets[&ids[0]].link_fingerprint.is_some(), "a placed file is remembered by its size and time"); + let copy = &st.doc.assets[&ids[1]]; + assert_eq!(copy.storage, designcraft_doc::Storage::Embedded); + assert!(copy.link.is_some() && copy.link_hash.is_some(), "embed keeps the link record for Unembed"); + let statuses = |rows: &[Value]| -> Vec { + ids.iter().map(|id| rows.iter().find(|r| r["asset"] == id.0).unwrap()["status"].as_str().unwrap().to_string()).collect() + }; + + let (preview, seen) = crate::io::touched(|| preview_document_links(&st.doc, &s.cache, None)); + assert!(seen.is_empty(), "the preview looked at {seen:?}"); + assert_eq!(statuses(&preview), ["checking", "embedded", "checking"]); + + // The check fills them in, with the rest of each row as in the preview. + let checked = list_document_links(&st.doc, &s.cache, None, &mut LinkListChecks::default(), &AtomicBool::new(false)).unwrap(); + assert_eq!(statuses(&checked), ["ok", "embedded", "missing"]); + let without_status = |rows: &[Value]| -> Vec { + rows.iter() + .cloned() + .map(|mut row| { + if let Some(row) = row.as_object_mut() { + row.remove("status"); + } + row + }) + .collect() + }; + assert_eq!(without_status(&preview), without_status(&checked)); + assert_eq!(Value::Array(checked), s.execute("links.list", &json!({})).unwrap(), "the same rows as links.list"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// The size and time kept with bytes read from a linked file vouch for them later only if the +/// file wasn't being written then: a file changed in the same second, or still being synced, +/// keeps its time and size, and a status trusting them would say OK for other bytes. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_file_written_just_now_is_not_vouched_for_by_its_time() { + let dir = std::env::temp_dir().join(format!("dc-link-settled-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("photo.png"); + let image = png(3, 3); + std::fs::write(&path, &image).unwrap(); + let now = crate::cmd::datamerge::fingerprint_of(&path).unwrap(); + assert_eq!(loaded_fingerprint(Some(now), &image), None, "written in the last two seconds"); + set_age(&path, 60); + let settled = crate::cmd::datamerge::fingerprint_of(&path).unwrap(); + assert_eq!(loaded_fingerprint(Some(settled), &image), Some(settled)); + assert_eq!(loaded_fingerprint(Some(settled), &image[1..]), None, "the file changed while it was read"); + assert_eq!(loaded_fingerprint(None, &image), None); + + // Placed while it is that recent, then replaced by other bytes of the same size at the same + // time: the status reads the file instead of trusting the time. + std::fs::write(&path, &image).unwrap(); + let written = std::fs::metadata(&path).unwrap().modified().unwrap(); + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let aid = AssetId(s.execute("file.place", &json!({"path": path.to_string_lossy()})).unwrap()["asset"].as_u64().unwrap()); + crate::cmd::native_links::wait(&mut s); + let kept = s.doc().unwrap().doc.assets[&aid].link_fingerprint.unwrap(); + assert_eq!((kept.size, kept.mtime), (image.len() as u64, UNVERIFIED_MTIME), "the time can't vouch for the bytes"); + let mut other = image.clone(); + if let Some(last) = other.last_mut() { + *last ^= 0xff; + } + std::fs::write(&path, &other).unwrap(); + std::fs::File::options().write(true).open(&path).unwrap().set_modified(written).unwrap(); + assert_eq!(s.execute("links.list", &json!({})).unwrap()[0]["status"], "modified"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A check on a worker thread is told to stop when its document is no longer the one shown: it +/// ends before the next file instead of asking a share that doesn't answer about hundreds more. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_stopped_check_looks_at_no_further_file() { + let dir = std::env::temp_dir().join(format!("dc-link-stop-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + for (name, x) in [("a.png", 72), ("b.png", 144)] { + let path = dir.join(name); + std::fs::write(&path, png(x, 10)).unwrap(); + s.execute("file.place", &json!({"path": path.to_string_lossy(), "x": x, "y": 72})).unwrap(); + crate::cmd::native_links::wait(&mut s); + } + let st = s.doc().unwrap(); + let mut checks = LinkListChecks::default(); + + let stop = AtomicBool::new(true); + let (rows, seen) = crate::io::touched(|| list_document_links(&st.doc, &s.cache, None, &mut checks, &stop)); + assert_eq!(rows, None); + assert!(seen.is_empty(), "a stopped check looked at {seen:?}"); + + stop.store(false, Ordering::Relaxed); + assert_eq!(list_document_links(&st.doc, &s.cache, None, &mut checks, &stop).map(|rows| rows.len()), Some(2)); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A copied or restored project folder gives every linked file a new time. The check then +/// compares the bytes, and what it found is kept with the document, so neither later checks nor +/// the next session read the file again. The document isn't marked as changed by that. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_file_found_unchanged_by_its_bytes_is_remembered_with_the_document() { + let dir = std::env::temp_dir().join(format!("dc-link-remember-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("photo.png"); + std::fs::write(&path, png(4, 4)).unwrap(); + set_age(&path, 300); + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let aid = AssetId(s.execute("file.place", &json!({"path": path.to_string_lossy()})).unwrap()["asset"].as_u64().unwrap()); + crate::cmd::native_links::wait(&mut s); + s.execute("file.saveAs", &json!({"path": dir.join("doc.designcraft").to_string_lossy()})).unwrap(); + assert!(!s.doc().unwrap().is_dirty()); + set_age(&path, 60); + let file = crate::cmd::datamerge::fingerprint_of(&path).unwrap(); + let check = |s: &Session, checks: &mut LinkListChecks| { + let st = s.doc().unwrap(); + let rows = list_document_links(&st.doc, &s.cache, st.path.as_deref().map(Path::new), checks, &AtomicBool::new(false)).unwrap(); + (rows[0]["status"].as_str().unwrap().to_string(), checks.take_verified()) + }; + + // Read once and found unchanged; found again from what the check remembers. + let mut checks = LinkListChecks::default(); + assert_eq!(check(&s, &mut checks), ("ok".to_string(), vec![(aid, file)])); + assert_eq!(checks.len(), 1); + assert_eq!(check(&s, &mut checks), ("ok".to_string(), vec![(aid, file)])); + + // Not for another document state, another size, or a graphic that isn't linked. + let checked = s.doc().unwrap().doc.clone(); + let other = Arc::new((*checked).clone()); + assert_eq!(remember_link_files(&mut s, &other, &[(aid, file)]), 0); + assert_eq!(remember_link_files(&mut s, &checked, &[(aid, Fingerprint { size: file.size + 1, ..file })]), 0); + assert_eq!(remember_link_files(&mut s, &checked, &[(AssetId(u64::MAX), file)]), 0); + assert!(Arc::ptr_eq(&s.doc().unwrap().doc, &checked), "nothing kept, nothing changed"); + + assert_eq!(remember_link_files(&mut s, &checked, &[(aid, file)]), 1); + let st = s.doc().unwrap(); + assert_eq!(st.doc.assets[&aid].link_fingerprint, Some(file)); + assert!(!st.is_dirty(), "a saved document stays saved"); + let kept = s.doc().unwrap().doc.clone(); + assert_eq!(remember_link_files(&mut s, &kept, &[(aid, file)]), 0, "already kept"); + // The next check, with nothing remembered (another session), reads nothing and has nothing new. + assert_eq!(check(&s, &mut LinkListChecks::default()), ("ok".to_string(), vec![])); + + // What one worker remembers goes to the next. + let mut pooled = LinkListChecks::default(); + assert!(pooled.is_empty()); + pooled.absorb(checks); + assert_eq!(pooled.len(), 1); + let _ = std::fs::remove_dir_all(&dir); +} + /// A linked file's size is the document's choice, so a link is read under a cap (#1596). #[cfg(not(target_arch = "wasm32"))] #[test] @@ -90,7 +434,7 @@ fn eps_web_exports_convert_tiff_and_skip_bad_used_assets() { assert!(!opf.contains("image/tiff")); assert!(Arc::ptr_eq(&before, &s.doc().unwrap().doc)); s.edit(|d, _| { - Arc::make_mut(d.assets.get_mut(&aid).unwrap()).data = Arc::new(b"%!PS-Adobe-3.0 EPSF-3.0\n%%EOF\n".to_vec()); + Arc::make_mut(d.assets.get_mut(&aid).unwrap()).data = designcraft_doc::AssetData::embedded(b"%!PS-Adobe-3.0 EPSF-3.0\n%%EOF\n".to_vec()); Ok(()) }) .unwrap(); @@ -124,13 +468,14 @@ fn eps_status_tracks_source_bytes_across_save_update_relink_and_embed() { let mut s = Session::new(); s.execute("file.new", &json!({})).unwrap(); let aid = AssetId(s.execute("file.place", &json!({"path": path.to_string_lossy()})).unwrap()["asset"].as_u64().unwrap()); + crate::cmd::native_links::wait(&mut s); assert_eq!(s.execute("links.list", &json!({})).unwrap()[0]["status"], "ok"); let before = s.doc().unwrap().doc.clone(); assert_eq!(s.execute("links.update", &json!({})).unwrap()["updated"], 0); assert!(Arc::ptr_eq(&s.doc().unwrap().doc, &before), "unchanged EPS must not create an edit"); let saved = designcraft_format::save(&before).unwrap(); let reopened = designcraft_format::load(&saved).unwrap(); - assert_eq!(reopened.assets[&aid].data.as_slice(), first); + assert_eq!(reopened.assets[&aid].data.load().unwrap().as_slice(), first); let mut s = Session::new(); s.add_document(crate::DocState::new(reopened, None)); assert_eq!(s.execute("links.list", &json!({})).unwrap()[0]["status"], "ok"); @@ -138,7 +483,7 @@ fn eps_status_tracks_source_bytes_across_save_update_relink_and_embed() { assert_eq!(s.execute("links.list", &json!({})).unwrap()[0]["status"], "modified"); assert_eq!(s.execute("links.update", &json!({})).unwrap()["updated"], 1); assert_eq!(s.execute("links.list", &json!({})).unwrap()[0]["status"], "ok"); - assert_eq!(s.doc().unwrap().doc.assets[&aid].data.as_slice(), changed); + assert_eq!(s.doc().unwrap().doc.assets[&aid].data.load().unwrap().as_slice(), changed); std::fs::remove_file(&path).unwrap(); assert_eq!(s.execute("links.list", &json!({})).unwrap()[0]["status"], "missing"); let replacement = dir.join("replacement.eps"); @@ -154,9 +499,9 @@ fn eps_status_tracks_source_bytes_across_save_update_relink_and_embed() { std::fs::remove_file(&replacement).unwrap(); let embedded = designcraft_format::load(&designcraft_format::save(&s.doc().unwrap().doc).unwrap()).unwrap(); // The asset is embedded, so no link is followed and the document is irrelevant. - assert_eq!(status(&embedded.assets[&aid], None), "embedded"); - assert_eq!(embedded.assets[&aid].data.as_slice(), changed); - assert!(designcraft_render::decode_pixmap(&embedded.assets[&aid].data).is_some()); + assert_eq!(status_cached(&embedded.assets[&aid], None, &mut Default::default()), "embedded"); + assert_eq!(embedded.assets[&aid].data.load().unwrap().as_slice(), changed); + assert!(designcraft_render::decode_pixmap(&embedded.assets[&aid].data.load().unwrap()).is_some()); let _ = std::fs::remove_dir_all(dir); } @@ -170,11 +515,16 @@ fn eps_legacy_preview_document_is_upgraded_by_update() { let mut s = Session::new(); s.execute("file.new", &json!({})).unwrap(); let aid = AssetId(s.execute("file.place", &json!({"path": path.to_string_lossy()})).unwrap()["asset"].as_u64().unwrap()); + crate::cmd::native_links::wait(&mut s); let proxy = designcraft_images::eps_proxy(source).unwrap().0; + // A document saved before linked storage: the preview embedded, a link without a hash. s.edit(|d, _| { let a = Arc::make_mut(d.assets.get_mut(&aid).unwrap()); - a.data = Arc::new(proxy); + a.data = designcraft_doc::AssetData::embedded(proxy); a.mime = "image/png".into(); + a.storage = designcraft_doc::Storage::Embedded; + a.link_hash = None; + a.proxy = None; Ok(()) }) .unwrap(); @@ -183,9 +533,9 @@ fn eps_legacy_preview_document_is_upgraded_by_update() { s.add_document(crate::DocState::new(old, None)); assert_eq!(s.execute("links.update", &json!({})).unwrap()["updated"], 1); assert_eq!(s.execute("links.list", &json!({})).unwrap()[0]["status"], "ok"); - assert_eq!(s.doc().unwrap().doc.assets[&aid].data.as_slice(), source); + assert_eq!(s.doc().unwrap().doc.assets[&aid].data.load().unwrap().as_slice(), source); s.execute("edit.undo", &json!({})).unwrap(); - assert!(designcraft_render::decode_pixmap(&s.doc().unwrap().doc.assets[&aid].data).is_some(), "old preview remains renderable"); + assert!(designcraft_render::decode_pixmap(&s.doc().unwrap().doc.assets[&aid].data.load().unwrap()).is_some(), "old preview remains renderable"); s.execute("edit.redo", &json!({})).unwrap(); assert_eq!(s.execute("links.list", &json!({})).unwrap()[0]["status"], "ok"); let _ = std::fs::remove_dir_all(dir); @@ -208,7 +558,7 @@ fn eps_source_exports_preview_to_pdf_html_and_epub_without_editing_document() { // A document retaining the original EPS rather than the legacy preview-only asset. s.edit(|d, _| { let a = Arc::make_mut(d.assets.get_mut(&aid).unwrap()); - a.data = Arc::new(source.to_vec()); + a.data = designcraft_doc::AssetData::embedded(source.to_vec()); a.mime = "application/postscript".into(); Ok(()) }) @@ -239,7 +589,7 @@ fn eps_source_exports_preview_to_pdf_html_and_epub_without_editing_document() { assert!(opf.contains("media-type=\"image/png\"")); assert!(!opf.contains("application/postscript")); assert!(Arc::ptr_eq(&s.doc().unwrap().doc, &before), "exports must leave the source document intact"); - assert_eq!(before.assets[&aid].data.as_slice(), source); + assert_eq!(before.assets[&aid].data.load().unwrap().as_slice(), source); } #[test] @@ -254,6 +604,7 @@ fn eps_relink_update_and_folder_relink_retain_source() { let mut s = Session::new(); s.execute("file.new", &json!({})).unwrap(); s.execute("file.place", &json!({"path": original.to_string_lossy()})).unwrap(); + crate::cmd::native_links::wait(&mut s); let aid = s.doc().unwrap().doc.assets.keys().next().copied().unwrap(); std::fs::write(&original, eps(20)).unwrap(); assert_eq!(s.execute("links.update", &json!({})).unwrap()["updated"], 1); @@ -262,7 +613,7 @@ fn eps_relink_update_and_folder_relink_retain_source() { let a = &s.doc().unwrap().doc.assets[&aid]; assert_eq!(a.pixels, Some((60, 20))); assert_eq!(a.mime, "application/postscript"); - assert_eq!(a.data.as_slice(), eps(30).as_bytes()); + assert_eq!(a.data.load().unwrap().as_slice(), eps(30).as_bytes()); let moved = dir.join("new").join("replacement.eps"); std::fs::rename(&replacement, &moved).unwrap(); assert_eq!(s.execute("links.relinkFolder", &json!({"dir": dir.join("new").to_string_lossy()})).unwrap()["relinked"], 1); @@ -282,12 +633,13 @@ fn pdf_relink_and_update_preserve_selected_page_size() { let mut s = Session::new(); s.execute("file.new", &json!({})).unwrap(); s.execute("file.place", &json!({"path": original.to_string_lossy(), "pdfPage": 2})).unwrap(); + crate::cmd::native_links::wait(&mut s); let aid = s.doc().unwrap().doc.assets.keys().next().copied().unwrap(); s.execute("links.relink", &json!({"asset": aid.0, "path": replacement.to_string_lossy()})).unwrap(); let a = &s.doc().unwrap().doc.assets[&aid]; assert_eq!(a.page, 1); assert_eq!(a.pixels, Some((50, 60))); - assert!(designcraft_render::render_pdf_page(&a.data, a.page as usize, 64).is_some()); + assert!(designcraft_render::render_pdf_page(&a.data.load().unwrap(), a.page as usize, 64).is_some()); std::fs::write(&replacement, pdf(&[(70, 70), (80, 90)])).unwrap(); assert_eq!(s.execute("links.update", &json!({})).unwrap()["updated"], 1); assert_eq!(s.doc().unwrap().doc.assets[&aid].pixels, Some((80, 90))); @@ -312,6 +664,7 @@ fn pdf_reload_rejects_missing_page_without_edit() { let mut s = Session::new(); s.execute("file.new", &json!({})).unwrap(); s.execute("file.place", &json!({"path": original.to_string_lossy(), "pdfPage": 2})).unwrap(); + crate::cmd::native_links::wait(&mut s); let aid = s.doc().unwrap().doc.assets.keys().next().copied().unwrap(); if command == "links.update" { std::fs::write(&original, &short).unwrap(); @@ -333,7 +686,7 @@ fn pdf_reload_rejects_missing_page_without_edit() { assert_eq!(st.revision, revision); assert_eq!(st.history.undo.len(), undo); assert_eq!(s.journal.len(), journal); - assert!(designcraft_render::render_pdf_page(&st.doc.assets[&aid].data, 1, 64).is_some()); + assert!(designcraft_render::render_pdf_page(&st.doc.assets[&aid].data.load().unwrap(), 1, 64).is_some()); } let _ = std::fs::remove_dir_all(dir); } @@ -349,6 +702,7 @@ fn link_status_relink_update_embed() { let mut s = Session::new(); s.execute("file.new", &json!({})).unwrap(); s.execute("file.place", &json!({"path": a.to_string_lossy(), "x": 72, "y": 72, "width": 72})).unwrap(); + crate::cmd::native_links::wait(&mut s); let l = s.execute("links.list", &json!({})).unwrap(); assert_eq!(l[0]["status"], "ok"); assert_eq!(l[0]["uses"][0]["ppi"], 10.0, "10 px over 1 inch"); @@ -373,3 +727,272 @@ fn link_status_relink_update_embed() { assert_eq!(s.execute("links.list", &json!({})).unwrap()[0]["status"], "embedded"); let _ = std::fs::remove_dir_all(&dir); } + +/// A temporary folder, removed when dropped. +#[cfg(not(target_arch = "wasm32"))] +struct TempDir(std::path::PathBuf); + +#[cfg(not(target_arch = "wasm32"))] +impl TempDir { + fn new(name: &str) -> Self { + let dir = std::env::temp_dir().join(format!("dc-links-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + TempDir(dir) + } +} + +#[cfg(not(target_arch = "wasm32"))] +impl Drop for TempDir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +/// Two valid PNGs of one byte length with other pixels (a uniform fill compresses to the same size). +fn same_size_pngs() -> (Vec, Vec) { + let a = designcraft_render::Rendered { width: 30, height: 20, pixels: vec![200u8; 30 * 20 * 4] }.to_png(); + let b = designcraft_render::Rendered { width: 30, height: 20, pixels: vec![100u8; 30 * 20 * 4] }.to_png(); + assert_eq!(a.len(), b.len()); + (a, b) +} + +/// Place a file and let the background job link it ([`crate::cmd::native_links::prepare`]). +fn placed(s: &mut Session, params: Value) -> AssetId { + let id = AssetId(s.execute("file.place", ¶ms).unwrap()["asset"].as_u64().unwrap()); + crate::cmd::native_links::wait(s); + id +} + +fn asset_of(s: &Session, id: AssetId) -> Arc { + Arc::clone(&s.doc().unwrap().doc.assets[&id]) +} + +fn row(s: &mut Session, id: AssetId) -> Value { + s.execute("links.list", &json!({})).unwrap().as_array().unwrap().iter().find(|r| r["asset"] == id.0).unwrap().clone() +} + +/// The format version a saved bundle declares. +#[cfg(not(target_arch = "wasm32"))] +fn bundle_version(bytes: &[u8]) -> (u64, Vec) { + use std::io::Read; + let mut zip = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap(); + let names: Vec = zip.file_names().map(str::to_string).collect(); + let mut version = 0; + for name in names.iter().filter(|n| n.ends_with(".json")) { + let mut text = String::new(); + zip.by_name(name).unwrap().read_to_string(&mut text).unwrap(); + if let Ok(v) = serde_json::from_str::(&text) + && v.get("format").is_some() + { + version = v["version"].as_u64().unwrap(); + } + } + (version, names.into_iter().filter(|n| n.starts_with("assets/")).collect()) +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_file_placed_from_a_path_links_to_it_and_embed_true_embeds_it() { + use designcraft_doc::Storage; + let dir = TempDir::new("place"); + let path = dir.0.join("art.png"); + let (bytes, _) = same_size_pngs(); + std::fs::write(&path, &bytes).unwrap(); + set_age(&path, 60); + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + + let id = placed(&mut s, json!({"path": path.to_string_lossy()})); + let a = asset_of(&s, id); + assert_eq!(a.storage, Storage::Linked); + assert!(a.data.is_linked() && a.data.embedded_bytes().is_none(), "no embedded copy"); + assert_eq!(a.link.as_deref(), path.to_str()); + assert_eq!(a.link_hash.as_deref(), Some(crate::asset_io::content_hash(&bytes).as_str())); + assert!(a.proxy.as_ref().is_some_and(|p| p.pixels == (30, 20))); + assert_eq!(a.data.resident().as_deref(), Some(&bytes), "the bytes read for placing are kept for the first draw"); + let r = row(&mut s, id); + assert_eq!((r["storage"].as_str(), r["status"].as_str()), (Some("linked"), Some("ok"))); + let (version, stored) = bundle_version(&designcraft_format::save(&s.doc().unwrap().doc).unwrap()); + assert_eq!((version, stored), (5, vec![]), "linked: format 5 and no copy of the file"); + + let e = placed(&mut s, json!({"path": path.to_string_lossy(), "embed": true, "x": 200})); + let a = asset_of(&s, e); + assert_eq!(a.storage, Storage::Embedded); + assert_eq!(a.data.embedded_bytes().map(|b| b.as_slice()), Some(bytes.as_slice())); + assert!(a.link.is_some() && a.link_hash.is_some(), "the link record stays for Unembed"); + let r = row(&mut s, e); + assert_eq!((r["storage"].as_str(), r["status"].as_str()), (Some("embedded"), Some("embedded"))); +} + +/// Placing a large image links it at once and returns before its proxy and hash are made. A save +/// in between writes the link without a hash, with a proxy made for it then; the copy reopens as +/// that link, and its open hashes the file. The background job adds the hash and proxy to the +/// live document under the key its bytes were drawn with. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn placing_leaves_the_proxy_and_hash_to_the_background() { + use designcraft_doc::Storage; + let dir = TempDir::new("deferred"); + let path = dir.0.join("big.png"); + let bytes = png(1600, 1200); + std::fs::write(&path, &bytes).unwrap(); + set_age(&path, 60); + 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 a = asset_of(&s, id); + assert!(a.proxy.is_none() && a.link_hash.is_none(), "no proxy or hash is made while placing"); + assert_eq!((a.storage, a.link.as_deref()), (Storage::Linked, path.to_str())); + assert_eq!(a.data.resident().as_deref(), Some(&bytes), "the bytes read for placing are kept for drawing"); + assert!(s.doc().unwrap().links.checking(), "the background job is running"); + let key = a.data.key(); + + let early = dir.0.join("early.designcraft"); + s.execute("file.saveACopy", &json!({"path": early.to_string_lossy()})).unwrap(); + let mut t = Session::new(); + t.execute("file.open", &json!({"path": early.to_string_lossy()})).unwrap(); + crate::cmd::native_links::wait(&mut t); + let c = t.doc().unwrap().doc.assets.values().next().cloned().unwrap(); + assert_eq!(c.storage, Storage::Linked); + assert!(c.proxy.is_some(), "the save made the proxy"); + assert_eq!(c.data.load().unwrap().as_slice(), bytes.as_slice()); + let hash = crate::asset_io::content_hash(&bytes); + assert_eq!(c.link_hash.as_deref(), Some(hash.as_str()), "the open hashed the file that matched by size and time"); + + crate::cmd::native_links::wait(&mut s); + let a = asset_of(&s, id); + assert_eq!((a.storage, a.link_hash.as_deref()), (Storage::Linked, Some(hash.as_str()))); + assert_eq!(a.data.key(), key, "still under the key its decodes are cached by"); + assert!(a.proxy.as_ref().is_some_and(|p| p.pixels == (1024, 768)), "the proxy is made in the background"); + assert!(!s.doc().unwrap().links.checking()); +} + +/// Cmd-S right after placing a large photo writes a link and a proxy, not the photo. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_save_right_after_placing_writes_no_copy_of_the_file() { + let dir = TempDir::new("save-at-once"); + let path = dir.0.join("photo.png"); + // Opaque noise doesn't compress: the PNG is about as large as its pixels. + let mut seed = 0x2545_f491_u32; + let pixels = (0..800 * 600 * 4) + .map(|i| { + seed ^= seed << 13; + seed ^= seed >> 17; + seed ^= seed << 5; + if i % 4 == 3 { 255 } else { (seed >> 24) as u8 } + }) + .collect(); + let bytes = designcraft_render::Rendered { width: 800, height: 600, pixels }.to_png(); + std::fs::write(&path, &bytes).unwrap(); + set_age(&path, 60); + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + s.execute("file.place", &json!({"path": path.to_string_lossy()})).unwrap(); + let doc = dir.0.join("doc.designcraft"); + s.execute("file.save", &json!({"path": doc.to_string_lossy()})).unwrap(); + let saved = std::fs::metadata(&doc).unwrap().len(); + assert!(saved < bytes.len() as u64, "saved {saved} bytes for a {} byte photo", bytes.len()); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_modified_link_is_updated_undoably() { + let dir = TempDir::new("update"); + let path = dir.0.join("art.png"); + let (first, second) = same_size_pngs(); + std::fs::write(&path, &first).unwrap(); + set_age(&path, 60); + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let id = placed(&mut s, json!({"path": path.to_string_lossy()})); + let key = asset_of(&s, id).data.key(); + + std::fs::write(&path, &second).unwrap(); + set_age(&path, 30); + assert_eq!(row(&mut s, id)["status"], "modified"); + assert_eq!(asset_of(&s, id).data.load().unwrap().as_slice(), first, "changed bytes are never adopted"); + assert_eq!(s.execute("links.update", &json!({"asset": id.0})).unwrap()["updated"], 1); + let a = asset_of(&s, id); + assert_eq!(row(&mut s, id)["status"], "ok"); + assert_ne!(a.data.key(), key); + assert_eq!(a.link_hash.as_deref(), Some(crate::asset_io::content_hash(&second).as_str())); + assert_eq!(a.data.load().unwrap().as_slice(), second); + + s.execute("edit.undo", &json!({})).unwrap(); + let a = asset_of(&s, id); + assert_eq!((a.data.key(), a.link_hash.clone()), (key, Some(crate::asset_io::content_hash(&first)))); + assert_eq!(row(&mut s, id)["status"], "modified"); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn embed_refuses_a_missing_link_and_unembed_links_to_the_original_or_into_a_folder() { + use designcraft_doc::Storage; + let dir = TempDir::new("embed"); + let path = dir.0.join("art.png"); + let (first, second) = same_size_pngs(); + std::fs::write(&path, &first).unwrap(); + set_age(&path, 60); + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let id = placed(&mut s, json!({"path": path.to_string_lossy()})); + + std::fs::remove_file(&path).unwrap(); + let before = s.doc().unwrap().doc.clone(); + let err = s.execute("links.embed", &json!({"asset": id.0})).unwrap_err().to_string(); + assert!(err.contains("missing"), "{err}"); + assert!(Arc::ptr_eq(&s.doc().unwrap().doc, &before)); + + std::fs::write(&path, &first).unwrap(); + s.execute("links.embed", &json!({"asset": id.0})).unwrap(); + let a = asset_of(&s, id); + assert_eq!((a.storage, a.data.embedded_bytes().map(|b| b.to_vec())), (Storage::Embedded, Some(first.clone()))); + assert_eq!(row(&mut s, id)["status"], "embedded"); + + // The original still holds the bytes: linked to it again. + let r = s.execute("links.unembed", &json!({"asset": id.0})).unwrap(); + assert_eq!(r["path"].as_str(), path.to_str()); + assert_eq!(asset_of(&s, id).storage, Storage::Linked); + assert_eq!(row(&mut s, id)["status"], "ok"); + + // Changed since: no original, so the bytes are written into `dir` (and found there next time). + s.execute("links.embed", &json!({"asset": id.0})).unwrap(); + std::fs::write(&path, &second).unwrap(); + assert!(s.execute("links.unembed", &json!({"asset": id.0})).is_err(), "no original and no folder"); + let out = dir.0.join("out"); + std::fs::create_dir_all(&out).unwrap(); + let r = s.execute("links.unembed", &json!({"asset": id.0, "dir": out.to_string_lossy()})).unwrap(); + let written = out.join("art.png"); + assert_eq!(r["path"].as_str(), written.to_str()); + assert_eq!(std::fs::read(&written).unwrap(), first); + let r = row(&mut s, id); + assert_eq!((r["storage"].as_str(), r["status"].as_str()), (Some("linked"), Some("ok"))); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(asset_of(&s, id).storage, Storage::Embedded); + s.execute("links.unembed", &json!({"asset": id.0, "dir": out.to_string_lossy()})).unwrap(); + assert_eq!(std::fs::read_dir(&out).unwrap().count(), 1, "the file with the same bytes is reused"); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn every_image_the_place_cursor_loads_is_linked() { + let dir = TempDir::new("cursor"); + let files: Vec<_> = (0..3u32) + .map(|i| { + let path = dir.0.join(format!("{i}.png")); + std::fs::write(&path, png(10 + i, 10)).unwrap(); + json!({"path": path.to_string_lossy()}) + }) + .collect(); + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + s.execute("place.load", &json!({"files": files})).unwrap(); + crate::cmd::native_links::wait(&mut s); + s.execute("place.contactSheet", &json!({})).unwrap(); + let d = &s.doc().unwrap().doc; + let used = d.used_assets(); + assert_eq!(used.len(), 3); + assert!(used.iter().all(|id| d.assets[id].storage == designcraft_doc::Storage::Linked && d.assets[id].data.is_linked())); +} diff --git a/crates/engine/src/cmd/liquid.rs b/crates/engine/src/cmd/liquid.rs index 8c8d4be23..3df1fdd6b 100644 --- a/crates/engine/src/cmd/liquid.rs +++ b/crates/engine/src/cmd/liquid.rs @@ -70,8 +70,8 @@ pub(crate) fn apply(d: &mut Document, sr: SpreadRef, pi: usize, old: Rect) { let liquid_guides = |o: Orientation| pg.guides.iter().filter(|g| g.liquid && g.orientation == o).map(|g| g.position).collect::>(); let (vg, hg) = (liquid_guides(Orientation::Vertical), liquid_guides(Orientation::Horizontal)); // The page's objects: centres within its old horizontal extent (outer pages take the pasteboard). - let last = sp.pages.len() - 1; - let (lo, hi) = (if pi == 0 { f64::NEG_INFINITY } else { old.x0 }, if pi == last { f64::INFINITY } else { old.x1 }); + let Some((leftmost, rightmost)) = sp.outer_page_indices() else { return }; + let (lo, hi) = (if pi == leftmost { f64::NEG_INFINITY } else { old.x0 }, if pi == rightmost { f64::INFINITY } else { old.x1 }); let strokes = false; let Some(sp) = d.spread_mut(sr) else { return }; for it in &mut sp.items { @@ -200,79 +200,255 @@ pub fn specs() -> Vec { "Create Alternate Layout…", ["Layout"], None, - "{name, width, height, rule?: page rule for the copies (default: keep each page's)} — every page copied after the last at the new size (a new section marked `name`), objects following the liquid rules", + "{name, width, height, from?: source layout name|index (default: the first), fromName?: names the source layout, rule?: page rule for the copies (default: keep each page's)} → {layout, firstPage, pages} — the source layout's pages copied after the last page at the new size (a layout of their own, its own column in the Pages panel), objects following the liquid rules", has_doc, create_alternate ), + cmd!( + "layout.alternate.duplicate", + "Duplicate Alternate Layout", + ["Layout"], + None, + "{layout: name|index, name?: (default \" copy\")} → {layout, firstPage, pages} — the layout's pages and objects copied at the same size", + has_doc, + duplicate_alternate + ), + cmd!( + "layout.alternate.delete", + "Delete Alternate Layout", + ["Layout"], + None, + "{layout: name|index} — delete the layout's pages and their objects; the last layout cannot be deleted", + has_doc, + delete_alternate + ), + cmd!( + "layout.alternate.options", + "Alternate Layout Options…", + ["Layout"], + None, + "{layout: name|index, name?, width?, height?} → {layout} — rename the layout, or resize its pages (objects follow the liquid rules)", + has_doc, + alternate_options + ), ] } -fn create_alternate(s: &mut crate::Session, p: &Value) -> Result { - const ID: &str = "layout.createAlternate"; - let name = str_param(p, "name").unwrap_or("Alternate").to_string(); - let w = p.get("width").and_then(Value::as_f64).ok_or_else(|| bad(ID, "`width` required"))?.max(1.0); - let h = p.get("height").and_then(Value::as_f64).ok_or_else(|| bad(ID, "`height` required"))?.max(1.0); - let rule = p.get("rule").map(|_| rule_param(p, ID)).transpose()?; - let n = s.doc()?.doc.page_count(); - s.edit(|d, _| { - let src = d.clone(); - let parent = d.page_loc(n - 1).and_then(|(si, pi)| d.spreads[si].pages[pi].parent); - d.insert_pages(Some(n - 1), n, parent)?; - for i in 0..n { - let (Some((si, pi)), Some((ti, tj))) = (src.page_loc(i), d.page_loc(n + i)) else { continue }; - let from = &src.spreads[si]; - let pb = from.pages[pi].bounds(); - let last = from.pages.len() - 1; - let ids: Vec<_> = from - .items - .iter() - .filter(|it| { - let c = it.bounds().center().x; - (pi == 0 || c >= pb.x0) && (pi == last || c < pb.x1) - }) - .map(|it| it.id) - .collect(); - // The copy keeps the page's liquid rule (or takes the one given). - let to = d.spreads[ti].pages[tj].bounds(); - Arc::make_mut(&mut d.spreads[ti]).pages[tj].liquid = rule.unwrap_or(from.pages[pi].liquid); - Arc::make_mut(&mut d.spreads[ti]).pages[tj].guides = from.pages[pi] - .guides - .iter() - .cloned() - .map(|mut g| { - if g.orientation == Orientation::Vertical { - g.position += to.x0 - pb.x0; - } - g - }) - .collect(); - let new = super::object::duplicate_from(d, &src, &ids, SpreadRef::Doc(ti), designcraft_geom::Vec2::new(to.x0 - pb.x0, 0.0))?; - // The copies' stories stay linked to the originals (Links panel: update when they change). - for (old, new) in ids.iter().zip(&new) { - let (Some(os), Some(ns)) = - (src.item(*old).and_then(|i| i.text_frame()).map(|t| t.story), d.item(*new).and_then(|i| i.text_frame()).map(|t| t.story)) - else { - continue; - }; - let rev = src.story(os).map_or(0, |s| s.rev); - if let Some(st) = d.story_mut(ns) { - st.link = Some((os, rev)); - } - } - } - let pages: Vec = (n + 1..=2 * n).collect(); - super::layout::resize_pages(d, &pages, Some(w), Some(h)); - d.sections.retain(|x| x.start != n); +/// A layout named by a command parameter: its name or its index in [`Document::layouts`]. +fn layout_param(id: &str, d: &Document, v: Option<&Value>) -> Result { + let layouts = d.layouts(); + let found = match v { + Some(Value::Number(n)) => n.as_u64().and_then(|i| usize::try_from(i).ok()).and_then(|i| layouts.get(i)), + Some(Value::String(s)) => layouts.iter().find(|l| l.name == *s), + Some(_) => return Err(bad(id, "`layout` is a layout name or index")), + None => return Err(bad(id, "`layout` names a layout")), + }; + found.cloned().ok_or_else(|| bad(id, format!("no layout {}", v.map(Value::to_string).unwrap_or_default()))) +} + +/// A layout name parameter: trimmed, 1–100 characters. +fn layout_name(id: &str, v: &str) -> Result { + let v = v.trim(); + if v.is_empty() || v.chars().count() > 100 { + return Err(bad(id, "a layout name has 1 to 100 characters")); + } + Ok(v.to_string()) +} + +/// `base`, or `base 2`, `base 3`… when another layout (but `except`) has the name. +fn unique_layout_name(d: &Document, base: &str, except: Option) -> String { + let taken: Vec = d.layouts().into_iter().enumerate().filter(|(i, _)| Some(*i) != except).map(|(_, l)| l.name).collect(); + if !taken.iter().any(|t| t == base) { + return base.to_string(); + } + (2..=taken.len().saturating_add(2)).map(|k| format!("{base} {k}")).find(|c| !taken.contains(c)).unwrap_or_else(|| base.to_string()) +} + +/// The section starting at absolute page `start`, made when there is none. +fn section_at(d: &mut Document, start: usize) -> Option<&mut designcraft_doc::Section> { + if !d.sections.iter().any(|x| x.start == start) { d.sections.push(designcraft_doc::Section { - start: n, - start_number: Some(1), + start, + start_number: if start == 0 { Some(1) } else { None }, style: Default::default(), prefix: String::new(), - marker: name.clone(), + marker: String::new(), include_prefix: false, + layout: None, }); d.sections.sort_by_key(|x| x.start); - Ok(json!({"firstPage": n + 1, "pages": n})) + } + d.sections.iter_mut().find(|x| x.start == start) +} + +/// Copy the pages of layout `from` after the last page as a new layout `name`, sized `size` +/// (None keeps each page's), with `rule` as the copies' page rule. → {layout, firstPage, pages} +fn copy_layout( + id: &str, + d: &mut Document, + from: &designcraft_doc::LayoutRange, + name: &str, + size: Option<(f64, f64)>, + rule: Option, +) -> Result { + let n = d.page_count(); + let count = from.end.saturating_sub(from.start); + if count == 0 || from.end > n { + return Err(bad(id, format!("layout {} has no pages", from.name))); + } + let name = unique_layout_name(d, name, None); + let src = d.clone(); + let last_parent = d.page_loc(n.saturating_sub(1)).and_then(|(si, pi)| d.spreads.get(si).and_then(|sp| sp.pages.get(pi))).and_then(|p| p.parent); + d.insert_pages(n.checked_sub(1), count, last_parent)?; + // The new layout starts numbering at 1 and a spread of its own. + d.sections.retain(|x| x.start != n); + d.sections.push(designcraft_doc::Section { + start: n, + start_number: Some(1), + style: Default::default(), + prefix: String::new(), + marker: name.clone(), + include_prefix: false, + layout: Some(name.clone()), + }); + d.sections.sort_by_key(|x| x.start); + d.repaginate(); + for k in 0..count { + let i = from.start + k; + let (Some((si, pi)), Some((ti, tj))) = (src.page_loc(i), d.page_loc(n + k)) else { continue }; + let Some(from_sp) = src.spreads.get(si) else { continue }; + let Some(from_pg) = from_sp.pages.get(pi) else { continue }; + let pb = from_pg.bounds(); + let last = from_sp.pages.len().saturating_sub(1); + let ids: Vec<_> = from_sp + .items + .iter() + .filter(|it| { + let c = it.bounds().center().x; + (pi == 0 || c >= pb.x0) && (pi == last || c < pb.x1) + }) + .map(|it| it.id) + .collect(); + let Some(sp) = d.spreads.get_mut(ti) else { continue }; + let sp = Arc::make_mut(sp); + let Some(pg) = sp.pages.get_mut(tj) else { continue }; + // The copy is the page it copies (size, margins, columns, parent, guides), with the + // page rule given or its own. + let dx = pg.x - from_pg.x; + (pg.width, pg.height, pg.margins, pg.columns, pg.parent) = + (from_pg.width, from_pg.height, from_pg.margins, from_pg.columns.clone(), from_pg.parent); + pg.liquid = rule.unwrap_or(from_pg.liquid); + pg.guides = from_pg + .guides + .iter() + .cloned() + .map(|mut g| { + if g.orientation == Orientation::Vertical { + g.position += dx; + } + g + }) + .collect(); + sp.relayout(); + let to = sp.pages.get(tj).map_or(pb, |p| p.bounds()); + let new = super::object::duplicate_from(d, &src, &ids, SpreadRef::Doc(ti), designcraft_geom::Vec2::new(to.x0 - pb.x0, to.y0 - pb.y0))?; + // The copies' stories stay linked to the originals (Links panel: update when they change). + for (old, new) in ids.iter().zip(&new) { + let (Some(os), Some(ns)) = + (src.item(*old).and_then(|i| i.text_frame()).map(|t| t.story), d.item(*new).and_then(|i| i.text_frame()).map(|t| t.story)) + else { + continue; + }; + let rev = src.story(os).map_or(0, |s| s.rev); + if let Some(st) = d.story_mut(ns) { + st.link = Some((os, rev)); + } + } + } + if let Some((w, h)) = size { + let pages: Vec = (n + 1..=n + count).collect(); + super::layout::resize_pages(d, &pages, Some(w), Some(h)); + } + Ok(json!({"layout": name, "firstPage": n + 1, "pages": count})) +} + +fn create_alternate(s: &mut crate::Session, p: &Value) -> Result { + const ID: &str = "layout.createAlternate"; + let name = layout_name(ID, str_param(p, "name").unwrap_or("Alternate"))?; + let size = |k: &str| p.get(k).and_then(Value::as_f64).filter(|v| v.is_finite()).ok_or_else(|| bad(ID, format!("`{k}` is a number"))); + let (w, h) = (size("width")?.clamp(1.0, 15_552.0), size("height")?.clamp(1.0, 15_552.0)); + let rule = p.get("rule").map(|_| rule_param(p, ID)).transpose()?; + let from_name = str_param(p, "fromName").map(|v| layout_name(ID, v)).transpose()?; + let from = match p.get("from") { + None | Some(Value::Null) => s.doc()?.doc.layouts().into_iter().next().ok_or_else(|| bad(ID, "no layout"))?, + v => layout_param(ID, &s.doc()?.doc, v)?, + }; + s.edit(|d, _| { + if let Some(fname) = from_name { + let index = d.layouts().iter().position(|l| l.start == from.start); + let fname = unique_layout_name(d, &fname, index); + if let Some(sec) = section_at(d, from.start) { + sec.layout = Some(fname); + } + } + copy_layout(ID, d, &from, &name, Some((w, h)), rule) + }) +} + +fn duplicate_alternate(s: &mut crate::Session, p: &Value) -> Result { + const ID: &str = "layout.alternate.duplicate"; + let from = layout_param(ID, &s.doc()?.doc, p.get("layout"))?; + let name = match str_param(p, "name") { + Some(v) => layout_name(ID, v)?, + // Kept within a layout name's 100 characters. + None => format!("{} copy", from.name.chars().take(95).collect::()), + }; + s.edit(|d, _| copy_layout(ID, d, &from, &name, None, None)) +} + +fn delete_alternate(s: &mut crate::Session, p: &Value) -> Result { + const ID: &str = "layout.alternate.delete"; + let d = &s.doc()?.doc; + let layout = layout_param(ID, d, p.get("layout"))?; + if d.layouts().len() < 2 { + return Err(bad(ID, "the only layout cannot be deleted")); + } + let pages: Vec = (layout.start..layout.end).collect(); + s.edit(|d, sel| { + d.delete_pages(&pages)?; + *sel = Default::default(); + Ok(json!({"layout": layout.name, "pages": pages.len()})) + }) +} + +fn alternate_options(s: &mut crate::Session, p: &Value) -> Result { + const ID: &str = "layout.alternate.options"; + let d = &s.doc()?.doc; + let layout = layout_param(ID, d, p.get("layout"))?; + let index = d.layouts().iter().position(|l| l.start == layout.start); + let name = str_param(p, "name").map(|v| layout_name(ID, v)).transpose()?; + let dim = |k: &str| -> Result> { + p.get(k) + .map(|v| v.as_f64().filter(|v| v.is_finite()).map(|v| v.clamp(1.0, 15_552.0)).ok_or_else(|| bad(ID, format!("`{k}` is a number")))) + .transpose() + }; + let (w, h) = (dim("width")?, dim("height")?); + if name.as_ref().is_none_or(|n| *n == layout.name) && w.is_none() && h.is_none() { + return Ok(json!({"layout": layout.name})); + } + s.edit(|d, _| { + let mut out = layout.name.clone(); + if let Some(name) = name { + out = unique_layout_name(d, &name, index); + if let Some(sec) = section_at(d, layout.start) { + sec.layout = Some(out.clone()); + } + } + if w.is_some() || h.is_some() { + let pages: Vec = (layout.start + 1..=layout.end).collect(); + super::layout::resize_pages(d, &pages, w, h); + } + Ok(json!({"layout": out})) }) } @@ -342,4 +518,121 @@ mod tests { let links = s.execute("story.links", &json!({})).unwrap(); assert!(links.as_array().unwrap().iter().any(|l| l["parent"] == t["story"]), "{links}"); } + + fn layouts(s: &Session) -> Vec<(String, usize, usize)> { + s.doc().unwrap().doc.layouts().into_iter().map(|l| (l.name, l.start, l.end)).collect() + } + + #[test] + fn alternate_layouts_copy_one_layout_and_can_be_duplicated_renamed_and_deleted() { + let mut s = Session::new(); + s.execute("file.new", &json!({"pages": 3, "width": 600, "height": 800, "facingPages": true})).unwrap(); + assert_eq!(layouts(&s), vec![("Layout 1".into(), 0, 3)]); + let r = s.execute("layout.createAlternate", &json!({"name": "Tablet H", "width": 1024, "height": 768, "fromName": "Print"})).unwrap(); + assert_eq!(r["layout"], "Tablet H"); + assert_eq!(layouts(&s), vec![("Print".into(), 0, 3), ("Tablet H".into(), 3, 6)]); + // Again from the first layout: only its 3 pages are copied, and the name is made unique. + let r = s.execute("layout.createAlternate", &json!({"name": "Tablet H", "width": 768, "height": 1024, "from": "Print"})).unwrap(); + assert_eq!(r["layout"], "Tablet H 2"); + assert_eq!(layouts(&s).last().cloned(), Some(("Tablet H 2".into(), 6, 9))); + // Every layout starts a spread of its own. + let d = s.doc().unwrap().doc.clone(); + for l in d.layouts() { + assert_eq!(d.page_loc(l.start).unwrap().1, 0, "{l:?} starts a spread"); + } + let (si, pi) = d.page_loc(3).unwrap(); + assert!((d.spreads[si].pages[pi].width - 1024.0).abs() < 1e-6); + // Duplicate keeps the size; delete removes the layout's pages; undo brings them back. + let r = s.execute("layout.alternate.duplicate", &json!({"layout": "Tablet H"})).unwrap(); + assert_eq!(r["layout"], "Tablet H copy"); + let d = s.doc().unwrap().doc.clone(); + let (si, pi) = d.page_loc(9).unwrap(); + assert!((d.spreads[si].pages[pi].width - 1024.0).abs() < 1e-6); + assert_eq!(d.page_count(), 12); + s.execute("layout.alternate.delete", &json!({"layout": "Tablet H"})).unwrap(); + assert_eq!(layouts(&s), vec![("Print".into(), 0, 3), ("Tablet H 2".into(), 3, 6), ("Tablet H copy".into(), 6, 9)]); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(layouts(&s).len(), 4); + // Rename (kept unique) and resize. + let r = s.execute("layout.alternate.options", &json!({"layout": 3, "name": "Print"})).unwrap(); + assert_eq!(r["layout"], "Print 2"); + s.execute("layout.alternate.options", &json!({"layout": "Print 2", "width": 500})).unwrap(); + let d = s.doc().unwrap().doc.clone(); + let (si, pi) = d.page_loc(9).unwrap(); + assert!((d.spreads[si].pages[pi].width - 500.0).abs() < 1e-6); + // Deleting the first layout leaves the next one first. + s.execute("layout.alternate.delete", &json!({"layout": 0})).unwrap(); + assert_eq!(layouts(&s).first().cloned(), Some(("Tablet H".into(), 0, 3))); + // Inserting a page at the end of a layout keeps the next layout's pages its own. + s.execute("layout.pages.insert", &json!({"after": 2, "count": 1})).unwrap(); + assert_eq!(layouts(&s)[0], ("Tablet H".into(), 0, 4)); + assert_eq!(layouts(&s)[1].1, 4); + } + + #[test] + fn alternate_layout_commands_refuse_bad_input() { + let mut s = Session::new(); + s.execute("file.new", &json!({"pages": 1})).unwrap(); + // The only layout cannot be deleted. + assert!(s.execute("layout.alternate.delete", &json!({"layout": 0})).is_err()); + assert_eq!(s.doc().unwrap().doc.page_count(), 1); + for p in [json!({}), json!({"layout": "Nope"}), json!({"layout": 7}), json!({"layout": true}), json!({"layout": -1})] { + assert!(s.execute("layout.alternate.duplicate", &p).is_err(), "{p}"); + assert!(s.execute("layout.alternate.options", &p).is_err(), "{p}"); + } + assert!(s.execute("layout.alternate.options", &json!({"layout": 0, "name": " "})).is_err()); + assert!(s.execute("layout.alternate.options", &json!({"layout": 0, "width": "wide"})).is_err()); + assert!(s.execute("layout.createAlternate", &json!({"name": "", "width": 10, "height": 10})).is_err()); + assert!(s.execute("layout.createAlternate", &json!({"name": "X", "height": 10})).is_err()); + assert!(s.execute("layout.createAlternate", &json!({"name": "X", "width": 10, "height": 10, "from": "Nope"})).is_err()); + assert!(s.doc().unwrap().history.undo.is_empty()); + // A layout survives Numbering & Section Options › remove section. + s.execute("layout.createAlternate", &json!({"name": "Wide", "width": 900, "height": 600})).unwrap(); + s.execute("layout.section", &json!({"page": 2, "remove": true})).unwrap(); + assert_eq!(s.doc().unwrap().doc.layouts().len(), 2); + } + + #[test] + fn deleting_a_layouts_first_page_keeps_the_layout_when_a_section_follows() { + let mut s = Session::new(); + s.execute("file.new", &json!({"pages": 2, "facingPages": false})).unwrap(); + s.execute("layout.createAlternate", &json!({"name": "Wide", "width": 900, "height": 600})).unwrap(); + // The layout starts at page 3; a numbering section starts at page 4. + s.execute("layout.section", &json!({"page": 4, "startNumber": 7})).unwrap(); + s.execute("layout.pages.delete", &json!({"pages": [2]})).unwrap(); + let names: Vec<(String, usize, usize)> = layouts(&s); + assert_eq!(names, vec![("Layout 1".into(), 0, 2), ("Wide".into(), 2, 3)]); + // The kept section's numbering stays. + assert_eq!(s.doc().unwrap().doc.page_number(2), 7); + } + + #[test] + fn layouts_keep_their_pages_when_a_page_moves_across_them() { + let mut s = Session::new(); + s.execute("file.new", &json!({"pages": 3, "facingPages": false})).unwrap(); + s.execute("layout.createAlternate", &json!({"name": "Wide", "width": 900, "height": 600})).unwrap(); + assert_eq!(layouts(&s), vec![("Layout 1".into(), 0, 3), ("Wide".into(), 3, 6)]); + let wide = |s: &Session, i: usize| (s.doc().unwrap().doc.page(i).unwrap().width - 900.0).abs() < 1e-6; + // The first page to the end: it joins the last layout, and Wide keeps its own 3 pages. + s.execute("layout.pages.move", &json!({"from": 0, "to": 5})).unwrap(); + assert_eq!(layouts(&s), vec![("Layout 1".into(), 0, 2), ("Wide".into(), 2, 6)]); + assert!((2..5).all(|i| wide(&s, i)) && !wide(&s, 5) && !wide(&s, 1)); + // Wide's first page to the front: Wide starts at its next page. + s.execute("layout.pages.move", &json!({"from": 2, "to": 0})).unwrap(); + assert_eq!(layouts(&s), vec![("Layout 1".into(), 0, 3), ("Wide".into(), 3, 6)]); + assert!(wide(&s, 0) && (3..5).all(|i| wide(&s, i))); + } + + #[test] + fn layouts_survive_a_save_and_old_sections_load() { + let sec: designcraft_doc::Section = serde_json::from_value(json!({"start": 2, "marker": "x"})).unwrap(); + assert_eq!(sec.layout, None); + let mut s = Session::new(); + s.execute("file.new", &json!({"pages": 1})).unwrap(); + s.execute("layout.createAlternate", &json!({"name": "Wide", "width": 900, "height": 600})).unwrap(); + let d = &s.doc().unwrap().doc; + let back: Vec = serde_json::from_value(serde_json::to_value(&d.sections).unwrap()).unwrap(); + assert_eq!(back, d.sections); + assert!(back.iter().any(|x| x.layout.as_deref() == Some("Wide"))); + } } diff --git a/crates/engine/src/cmd/load_styles.rs b/crates/engine/src/cmd/load_styles.rs index 762f7b1fc..154306048 100644 --- a/crates/engine/src/cmd/load_styles.rs +++ b/crates/engine/src/cmd/load_styles.rs @@ -85,7 +85,7 @@ fn source(p: &Value, id: &str) -> Result { (Some(path), None) => (crate::io::read_file(path).map_err(|e| bad(id, e))?, path.to_string()), _ => return Err(bad(id, "give `path` or `base64`")), }; - if name.to_lowercase().ends_with(".idml") { + if craft_file_formats::detect(&name, &bytes) == Some(craft_file_formats::Format::Idml) { designcraft_idml::import_idml(&bytes).map_err(|e| bad(id, e.to_string())) } else { super::file::from_bytes(&bytes).map_err(|e| bad(id, e.to_string())) diff --git a/crates/engine/src/cmd/mathexpr.rs b/crates/engine/src/cmd/mathexpr.rs index e5342f79c..44171e098 100644 --- a/crates/engine/src/cmd/mathexpr.rs +++ b/crates/engine/src/cmd/mathexpr.rs @@ -2,8 +2,6 @@ //! text insertion point (an anchored object) or as a frame. The LaTeX is kept as the object's //! alt text, so it can be edited and exports accessibly. -use std::sync::Arc; - use designcraft_doc::{Asset, AssetId, Content, Graphic, Item, ItemId, Shape}; use designcraft_geom::{Affine, Rect, shapes}; use serde_json::{Value, json}; @@ -14,7 +12,13 @@ use crate::{Result, Session}; fn math_item(d: &mut designcraft_doc::Document, latex: &str, size: f64, lid: designcraft_doc::LayerId, at: (f64, f64)) -> Item { let (svg, (w, h)) = crate::math::to_svg(latex, size); let fresh = AssetId(d.alloc()); - let aid = d.add_asset(Asset { id: fresh, name: "math.svg".into(), mime: "image/svg+xml".into(), data: Arc::new(svg), ..Default::default() }); + let aid = d.add_asset(Asset { + id: fresh, + name: "math.svg".into(), + mime: "image/svg+xml".into(), + data: designcraft_doc::AssetData::embedded(svg), + ..Default::default() + }); let id = ItemId(d.alloc()); let r = Rect::new(at.0, at.1, at.0 + w, at.1 + h); let mut it = Item::new(id, lid, Shape::Rectangle, shapes::rectangle(r)); @@ -35,6 +39,11 @@ fn math_item(d: &mut designcraft_doc::Document, latex: &str, size: f64, lid: des it } +/// The `size` parameter in points: 12 by default (also for non-finite values), clamped to 2..=400. +fn size_param(p: &Value) -> f64 { + p.get("size").and_then(Value::as_f64).filter(|v| v.is_finite()).unwrap_or(12.0).clamp(2.0, 400.0) +} + pub fn specs() -> Vec { vec![ cmd!( @@ -48,7 +57,7 @@ pub fn specs() -> Vec { ), cmd!(query "math.svg", "Math Expression SVG", [], None, "{latex, size?} → {svg, width, height} — typeset without placing", has_doc, |_s, p| { let latex = str_param(p, "latex").ok_or_else(|| bad("math.svg", "`latex` required"))?; - let (svg, (w, h)) = crate::math::to_svg(latex, p.get("size").and_then(Value::as_f64).unwrap_or(12.0)); + let (svg, (w, h)) = crate::math::to_svg(latex, size_param(p)); Ok(json!({"svg": String::from_utf8_lossy(&svg), "width": w, "height": h})) }), ] @@ -56,7 +65,7 @@ pub fn specs() -> Vec { fn insert(s: &mut Session, p: &Value) -> Result { let latex = str_param(p, "latex").ok_or_else(|| bad("math.insert", "`latex` required"))?.to_string(); - let size = p.get("size").and_then(Value::as_f64).unwrap_or(12.0).clamp(2.0, 400.0); + let size = size_param(p); let lid = s.doc()?.active_layer; // Edit an existing expression in place. if let Some(id) = super::id_param(p, "id") { @@ -80,9 +89,11 @@ fn insert(s: &mut Session, p: &Value) -> Result { if let Some(t) = text { let it = math_item(d, &latex, size, lid, (0.0, 0.0)); let r = t.range(); + let del = r.start.min(d.story(t.story).map_or(0, |st| st.len()))..r.end.min(d.story(t.story).map_or(0, |st| st.len())); if let Some(st) = d.story_mut(t.story) { - st.delete(r.start.min(st.len())..r.end.min(st.len())); + st.delete(del.clone()); } + d.adjust_text_ranges(t.story, del, 0); let end = super::anchored::anchor_items(d, t.story, r.start, vec![it], &Default::default())?; sel.text = Some(designcraft_doc::TextSel { anchor: end, focus: end, ..t }); return Ok(json!({"inline": true, "pos": end})); @@ -102,6 +113,24 @@ mod tests { use crate::Session; + #[test] + fn math_svg_clamps_size_like_insert() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let dims = |s: &mut Session, size: f64| { + let r = s.execute("math.svg", &json!({"latex": "x", "size": size})).unwrap(); + (r["width"].as_f64().unwrap(), r["height"].as_f64().unwrap()) + }; + let (w2, h2) = dims(&mut s, 2.0); + let (w400, h400) = dims(&mut s, 400.0); + for size in [0.0, -5.0, 1e-300] { + assert_eq!(dims(&mut s, size), (w2, h2), "size {size}"); + } + for size in [1e9, 1e300] { + assert_eq!(dims(&mut s, size), (w400, h400), "size {size}"); + } + } + #[test] fn math_places_inline_and_as_frames() { let mut s = Session::new(); diff --git a/crates/engine/src/cmd/media.rs b/crates/engine/src/cmd/media.rs index a4e3f5ae6..deb4abf38 100644 --- a/crates/engine/src/cmd/media.rs +++ b/crates/engine/src/cmd/media.rs @@ -1,8 +1,6 @@ //! Window › Interactive › Media: placed video and sound (shown as a poster or a placeholder, //! exported as `
"#; - assert_eq!(validate(&dtd, ok), vec![]); - let bad = r#"no title
x
` +/// was unbounded in the one direction the budget was meant to close: `
` is fifteen +/// bytes, so the 512 MiB a part may decompress to holds some 36 million of them, and a `Cell` +/// each is tens of gigabytes with every table inside both caps (noted in review). +fn budgeted_size(rows: usize, cols: usize, reserved: usize) -> Option<(usize, usize, bool)> { + let (mut nr, mut nc) = designcraft_doc::table::clamped_size(rows, cols); + let left = MAX_IMPORT_TABLE_CELLS.checked_sub(reserved).filter(|left| *left > 0)?; + let over_budget = nr.saturating_mul(nc) > left; + if over_budget { + nc = nc.min(left); + nr = nr.min((left / nc).max(1)); + } + Some((nr, nc, over_budget)) +} + /// Preserve the legacy uniform field only when all four sides explicitly specify every /// property. Partial records must stay sparse so they can inherit from a parent style. pub(super) fn uniform_cell_stroke(edges: &[designcraft_doc::CellStrokeAttrs; 4]) -> Option { @@ -21,32 +54,68 @@ pub(super) fn uniform_cell_stroke(edges: &[designcraft_doc::CellStrokeAttrs; 4]) impl<'r> Importer<'r> { /// ``: rows, columns and cells (cell `Name` is `column:row`). - pub(super) fn table(&mut self, e: &El) -> Table { + pub(super) fn table(&mut self, e: &El) -> Option
{ + let model_table = craft_idml::model::Table::from_el(&crate::xml::to_craft(e)); + let table_options = model_table.values.table_options(); + let layout = craft_idml::model::TableLayout::from_table(&model_table); + // A file's row and column counts are its claim, and a table of them is allocated whole: a + // story holding one `
` with 5,000 of each asked for 25M cells, around 34 GB, which + // aborts the process instead of failing (#1583). What is read is clamped, and the rest of + // this function walks the clamped slices -- indexing `t.rows`/`t.columns` by the file's + // own counts would be out of bounds. + // + // Reserved before `Table::new`, so a cell's own story cannot spend the budget this table + // is counting on. + let Some((nr, nc, over_budget)) = budgeted_size(layout.rows.len().max(1), layout.columns.len().max(1), self.table_cells) else { + // Said once: the file that reaches this is the one with millions of tables in it. + if !self.table_budget_spent { + self.table_budget_spent = true; + self.warnings.push(format!( + "the tables in this file claim more than {MAX_IMPORT_TABLE_CELLS} cells between them: the rest of them were not read" + )); + } + return None; + }; + self.table_cells = self.table_cells.saturating_add(nr.saturating_mul(nc)); + if nr < layout.rows.len() || nc < layout.columns.len() { + let why = if over_budget { "more than the tables in one file can hold between them" } else { "more than a table can hold" }; + self.table_warnings += 1; + match self.table_warnings.cmp(&MAX_TABLE_WARNINGS) { + std::cmp::Ordering::Less => self.warnings.push(format!( + "a table of {} rows and {} columns was read as {nr} x {nc}: {why}", + layout.rows.len(), + layout.columns.len() + )), + std::cmp::Ordering::Equal => { + self.warnings.push(format!("more than {MAX_TABLE_WARNINGS} tables were read smaller than this file claims")) + } + std::cmp::Ordering::Greater => {} + } + } let id = self.alloc(); - let rows: Vec<&El> = e.find_all("Row").collect(); - let cols: Vec<&El> = e.find_all("Column").collect(); - let nr = rows.len().max(1); - let nc = cols.len().max(1); + let rows = &layout.rows[..nr.min(layout.rows.len())]; + let cols = &layout.columns[..nc.min(layout.columns.len())]; let mut t = Table::new(id, nr, nc, 0, 0, 0.0); - t.options.direction = if e.get("TableDirection") == Some("RightToLeftDirection") { + t.options.direction = if table_options.direction.as_deref() == Some("RightToLeftDirection") { designcraft_doc::TextDirection::RightToLeft } else { designcraft_doc::TextDirection::LeftToRight }; for (r, re) in rows.iter().enumerate() { - let auto = re.boolean("AutoGrow").unwrap_or(true); + let auto = re.auto_grow().unwrap_or(true); t.rows[r].mode = if auto { RowHeightMode::AtLeast } else { RowHeightMode::Exactly }; - t.rows[r].height = if auto { re.num("MinimumHeight").unwrap_or(3.0) } else { re.num("SingleRowHeight").unwrap_or(12.0) }; + t.rows[r].height = if auto { re.minimum_height().unwrap_or(3.0) } else { re.single_row_height().unwrap_or(12.0) }; } for (c, ce) in cols.iter().enumerate() { - t.columns[c].width = ce.num("SingleColumnWidth").unwrap_or(72.0).max(3.0); + t.columns[c].width = ce.single_column_width().unwrap_or(72.0).max(3.0); } - let h = e.num("HeaderRowCount").unwrap_or(0.0) as usize; - let f = e.num("FooterRowCount").unwrap_or(0.0) as usize; + let h = table_options.header_rows.unwrap_or(0.0) as usize; + let f = table_options.footer_rows.unwrap_or(0.0) as usize; if h.saturating_add(f) < nr { t.set_header_footer(h, f); } - let style_name = e.get("AppliedTableStyle").map(|r| self.table_style_ref(r)).unwrap_or_else(|| designcraft_doc::BASIC_TABLE.into()); + let style_name = + table_options.applied_style.as_deref().map(|r| self.table_style_ref(r)).unwrap_or_else(|| designcraft_doc::BASIC_TABLE.into()); let style = self.styles.resolve_table_style(&style_name); style.apply_to(&mut t, &self.styles.cell); // IDML distinguishes an explicit AppliedCellStyle from the effective region style. @@ -57,17 +126,17 @@ impl<'r> Importer<'r> { // materialized independently, so their edges retain their higher precedence. let mut border_unset = style.border.is_none() && style.borders.iter().all(|b| b.is_empty()); let mut borders = std::array::from_fn::<_, 4, _>(|i| t.options.border_for(i).clone()); - for (side, border) in ["TopBorder", "LeftBorder", "BottomBorder", "RightBorder"].iter().zip(&mut borders) { - let attrs = self.cell_stroke_attrs(e, side); + for (attrs, border) in table_options.borders.into_iter().zip(&mut borders) { + let attrs = self.map_stroke_values(attrs); border_unset &= attrs.is_empty(); attrs.apply_to(border); } t.options.border = borders[0].clone(); t.options.borders = borders.map(Some); - t.options.space_before = e.num("SpaceBefore").unwrap_or(t.options.space_before); - t.options.space_after = e.num("SpaceAfter").unwrap_or(t.options.space_after); - t.options.repeat_header = e.get("HeaderBehavior") != Some("RepeatOnce"); - t.options.repeat_footer = e.get("FooterBehavior") != Some("RepeatOnce"); + t.options.space_before = table_options.space_before.unwrap_or(t.options.space_before); + t.options.space_after = table_options.space_after.unwrap_or(t.options.space_after); + t.options.repeat_header = table_options.repeat_header; + t.options.repeat_footer = table_options.repeat_footer; // A local count may enable a pattern disabled by its parent style. Merge before // materialization so the parent's colors/tints are still available in that case. let mut row_fills = style.row_fills.clone(); @@ -83,26 +152,30 @@ impl<'r> Importer<'r> { column_strokes.merge(&self.alt_stroke_attrs(e, "Column")); column_strokes.apply_to(&mut t.options.column_strokes); let mut regions = Vec::new(); - for ce in e.find_all("Cell") { - let Some((c, r)) = - ce.get("Name").and_then(|n| n.split_once(':')).and_then(|(a, b)| Some((a.parse::().ok()?, b.parse::().ok()?))) - else { + for model_cell in model_table.cells() { + let options = model_cell.options(); + let Some((c, r)) = model_cell.position().map(|(c, r)| (c as usize, r as usize)) else { continue; }; if r >= nr || c >= nc { continue; } - let rs = (span(ce, "RowSpan").max(1.0) as usize).min(nr - r); - let cs = (span(ce, "ColumnSpan").max(1.0) as usize).min(nc - c); + // Preserve the prior importer behavior for malformed positive spans such as `inf`: + // saturate the float-to-integer conversion, then clamp before grid arithmetic. + let span = |key| model_cell.values.prop(key).and_then(|v| v.trim().parse::().ok()).unwrap_or(1.0).max(1.0) as usize; + let rs = span("RowSpan").min(nr - r); + let cs = span("ColumnSpan").min(nc - c); let mut cell = t.cell(r, c).cloned().unwrap_or_default(); - let cell_style = ce.get("AppliedCellStyle").map(|r| self.cell_style_ref(r)).unwrap_or_else(|| designcraft_doc::NO_CELL_STYLE.into()); + let cell_el = crate::xml::from_craft(model_cell.to_el()); + let cell_style = + model_cell.values.get("AppliedCellStyle").map(|r| self.cell_style_ref(r)).unwrap_or_else(|| designcraft_doc::NO_CELL_STYLE.into()); if cell_style != designcraft_doc::NO_CELL_STYLE { designcraft_doc::resolve_cell_style(&self.styles.cell, &cell_style).apply_to(&mut cell); } cell.style = if cell_style == designcraft_doc::NO_CELL_STYLE { String::new() } else { cell_style }; let default_para = cell.text.paras.first().cloned().unwrap_or_default(); - cell.text = self.story_with_para(StoryId(0), ce, default_para); - self.read_cell_attrs(&mut cell, ce, border_unset); + cell.text = self.story_with_para(StoryId(0), &cell_el, default_para); + self.read_cell_attrs(&mut cell, &options, border_unset); if let Some(slot) = t.cell_mut(r, c) { *slot = cell; } @@ -113,40 +186,40 @@ impl<'r> Importer<'r> { for rg in regions { let _ = t.merge(rg); } - t + Some(t) } /// A cell's local fill, insets, alignment, rotation and edge strokes. - fn read_cell_attrs(&mut self, cell: &mut designcraft_doc::Cell, ce: &El, border_unset: bool) { - if let Some(fc) = ce.get("FillColor") { + fn read_cell_attrs(&mut self, cell: &mut designcraft_doc::Cell, options: &craft_idml::model::CellOptions, border_unset: bool) { + if let Some(fc) = options.fill_color.as_deref() { cell.fill = self.swatch_ref(fc); } - if let Some(tint) = tint(ce.num("FillTint")) { + if let Some(tint) = tint(options.fill_tint) { cell.fill_tint = tint; } - for (i, k) in ["TopInset", "LeftInset", "BottomInset", "RightInset"].iter().enumerate() { - if let Some(v) = ce.num(k) { + for (i, inset) in options.insets.iter().enumerate() { + if let Some(v) = inset { cell.insets[i] = v.max(0.0); } } - if let Some(vj) = ce.get("VerticalJustification") { + if let Some(vj) = options.vertical_justification.as_deref() { cell.vj = names::vj_in(vj); } - if let Some(fb) = ce.get("FirstBaselineOffset") { + if let Some(fb) = options.first_baseline_offset.as_deref() { cell.first_baseline = names::first_baseline_in(fb); } - if let Some(min) = ce.num("MinimumFirstBaselineOffset").filter(|v| v.is_finite()) { + if let Some(min) = options.minimum_first_baseline_offset { cell.first_baseline_min = min.clamp(0.0, 8640.0); } - cell.rotation = ce.num("RotationAngle").unwrap_or(cell.rotation); + cell.rotation = options.rotation_angle.unwrap_or(cell.rotation); if cell.rotation != 0.0 { self.rotated_cells += 1; } - for (i, side) in ["TopEdge", "LeftEdge", "BottomEdge", "RightEdge"].iter().enumerate() { - let attrs = self.cell_stroke_attrs(ce, side); + for (i, values) in options.edge_strokes.iter().cloned().enumerate() { + let attrs = self.map_stroke_values(values); attrs.apply_to(&mut cell.strokes[i]); cell.stroke_defined[i] |= !attrs.is_empty(); - let priority = ce.prop(&format!("{side}StrokePriority")).and_then(|v| v.trim().parse::().ok()).unwrap_or(0); + let priority = options.edge_stroke_priorities[i]; cell.stroke_priorities[i] = priority; // Preserve style-defined edges and #102's positive-priority local overrides. cell.border_overrides[i] |= priority > 0; @@ -157,3 +230,64 @@ impl<'r> Importer<'r> { } } } + +#[cfg(test)] +mod budget_tests { + use super::{MAX_IMPORT_TABLE_CELLS, budgeted_size}; + + /// One table is capped, but a file chooses how many tables it has: three tables each at the + /// per-table cap asked for 750,000 cells, about 1 GB of `Cell`, with every table inside its + /// own limit (noted in review of #1583). + #[test] + fn the_tables_in_one_file_are_capped_between_them() { + let mut reserved = 0; + let mut sizes = Vec::new(); + for _ in 0..4 { + let size = budgeted_size(500, 1000, reserved); + if let Some((nr, nc, _)) = size { + reserved += nr * nc; + } + sizes.push(size); + } + assert_eq!(sizes[0], Some((250, 1000, false)), "the first table is held by the per-table cap alone"); + assert_eq!(sizes[1], Some((150, 1000, true)), "the second gets what is left of the file's budget"); + assert_eq!(sizes[2], None, "and the third is not read: there is nothing left to pay for it"); + assert_eq!(sizes[3], None, "nor any after it"); + assert_eq!(reserved, MAX_IMPORT_TABLE_CELLS, "the budget is spent exactly, not overspent"); + } + + /// The budget is a hard limit, not a floor: keeping one cell for every further table was + /// unbounded in the one direction the budget exists to close, since a `
` is + /// fifteen bytes and a part may decompress to 512 MiB (noted in review). + #[test] + fn a_spent_budget_stops_reading_tables_altogether() { + let claims = [(0, 0), (1, 1), (7, 3), (usize::MAX, usize::MAX), (1, usize::MAX), (usize::MAX, 1), (10_000, 1_000), (2, 0)]; + let mut reserved = 0usize; + let mut read = 0usize; + let mut skipped = 0usize; + // Every claim, several times over, in an order that exhausts the budget part way through. + for _ in 0..4 { + for (rows, cols) in claims { + match budgeted_size(rows.max(1), cols.max(1), reserved) { + Some((nr, nc, _)) => { + assert!(nr >= 1 && nc >= 1, "{rows} x {cols} was read as {nr} x {nc}: a table has nowhere to put its text"); + reserved += nr * nc; + read += 1; + } + None => skipped += 1, + } + assert!(reserved <= MAX_IMPORT_TABLE_CELLS, "{read} tables reserved {reserved} cells, past the budget"); + } + } + assert_eq!(reserved, MAX_IMPORT_TABLE_CELLS, "this sequence does reach the budget"); + assert!(skipped > 0, "and does go on asking after it: {skipped} tables were not read"); + } + + /// Below the budget nothing is clamped by it, so an ordinary file is read exactly as before. + #[test] + fn an_ordinary_file_is_not_touched_by_the_budget() { + for (rows, cols) in [(1, 1), (2, 3), (50, 20), (250, 1000)] { + assert_eq!(budgeted_size(rows, cols, 0), Some((rows, cols, false)), "{rows} x {cols}"); + } + } +} diff --git a/crates/idml/src/import/text_attrs.rs b/crates/idml/src/import/text_attrs.rs index 323c14b17..c4677ae75 100644 --- a/crates/idml/src/import/text_attrs.rs +++ b/crates/idml/src/import/text_attrs.rs @@ -1,4 +1,3 @@ -use super::object_style::corners; use super::story::MAX_STORY_NESTING; use super::values::tint; use super::{ @@ -20,174 +19,165 @@ fn tab_list_repaired(read: &[TabStop], sanitized: &[TabStop]) -> bool { } pub(super) fn mojikumi_row(e: &El) -> Result { - let number = |key: &str| -> Result { - let Some(raw) = e.prop(key) else { - return Ok(0.0); - }; - raw.trim().parse::().ok().filter(|v| v.is_finite()).ok_or_else(|| IdmlError::Invalid(format!("Mojikumi row has invalid {key}"))) - }; - let integer = |key: &str| -> Result { - let v = number(key)?; - if v.fract() != 0.0 || v < f64::from(i16::MIN) || v > f64::from(i16::MAX) { - return Err(IdmlError::Invalid(format!("Mojikumi {key} must be an in-range integer"))); - } - Ok(v as i16) - }; - let boolean = |key: &str| -> Result { - match e.prop(key).as_deref().map(str::trim) { - None | Some("false") => Ok(false), - Some("true") => Ok(true), - _ => Err(IdmlError::Invalid(format!("Mojikumi row has invalid {key}"))), - } - }; - let row = designcraft_doc::cjk::MojikumiAki { - target_class: integer("TargetMojikumiClass")?, - side_class: integer("SideMojikumiClass")?, - after: boolean("SideIsAfterTarget")?, - minimum: number("Minimum")?, - desired: number("Desired")?, - maximum: number("Maximum")?, - priority: integer("CompressionPriority")?, - does_not_float: boolean("AkiDoesNotFloat")?, - }; - Ok(row) + let model = craft_idml::model::MojikumiRow::from_el(&crate::xml::to_craft(e)).map_err(IdmlError::Invalid)?; + Ok(designcraft_doc::cjk::MojikumiAki { + target_class: model.target_class, + side_class: model.side_class, + after: model.after, + minimum: model.minimum, + desired: model.desired, + maximum: model.maximum, + priority: model.priority, + does_not_float: model.does_not_float, + }) } impl<'r> Importer<'r> { pub(super) fn char_attrs(&mut self, e: &El) -> CharAttrs { let mut a = CharAttrs::default(); - if let Some(f) = e.prop("AppliedFont") { + let cjk = craft_idml::model::CjkCharacterValues::from_el(&crate::xml::to_craft(e)); + let values = craft_idml::model::CharacterTypographyValues::from_el(&crate::xml::to_craft(e)); + if let Some(f) = values.applied_font { // Some writers append the style after a tab. Spaces are part of a family's name // ("Minion Pro " is another font than "Minion Pro"); line breaks around it aren't. let fam = f.split('\t').next().unwrap_or(&f).trim_matches(['\n', '\r']); a.font_family = self.composite_names.get(fam.trim()).cloned().or_else(|| names::font_family_in(fam)); } // "Nothing" leaves the style unset: it comes from the paragraph style. - a.font_style = e.prop("FontStyle").filter(|s| !matches!(s.trim(), "Nothing" | "$ID/Nothing")); - a.size = e.num("PointSize"); - a.leading = e.prop("Leading").and_then(|l| names::leading_in(l.trim())); + a.font_style = values.font_style.filter(|s| !matches!(s.trim(), "Nothing" | "$ID/Nothing")); + a.size = values.point_size; + a.leading = values.leading.as_deref().and_then(|leading| names::leading_in(leading.trim())); // Automatic kerning may carry an inactive numeric value (including the // 1e11 IDML sentinel). It must not become a multi-million-em advance. - a.kerning = e.prop("KerningMethod").and_then(|k| match k.trim().trim_start_matches("$ID/") { + a.kerning = values.kerning_method.as_deref().and_then(|k| match k.trim().trim_start_matches("$ID/") { "Optical" => Some(Kerning::Optical), "Metrics" | "Metrics - Roman Only" => Some(Kerning::Metrics), "None" => Some(Kerning::None), _ => None, }); if a.kerning.is_none() { - a.kerning = e.num("KerningValue").filter(|v| v.is_finite() && v.abs() < 1e10).map(Kerning::Manual); + a.kerning = values.kerning_value.filter(|v| v.is_finite() && v.abs() < 1e10).map(Kerning::Manual); } - a.tracking = e.num("Tracking"); - a.leading_aki = e.num("LeadingAki").map(|v| (v >= 0.0).then_some(v)); - a.trailing_aki = e.num("TrailingAki").map(|v| (v >= 0.0).then_some(v)); - a.tsume = e.num("Tsume").map(|v| (v / 100.0).clamp(0.0, 1.0)); - a.jidori = e.num("Jidori").map(|v| v.clamp(0.0, 10000.0) as u32); - a.leading_model = e.prop("LeadingModel").and_then(|v| crate::cjk::leading_in(&v)); - a.character_alignment = e.prop("CharacterAlignment").and_then(|v| crate::cjk::alignment_in(&v)); - a.h_scale = e.num("HorizontalScale").map(|v| v / 100.0); - a.v_scale = e.num("VerticalScale").map(|v| v / 100.0); - a.baseline_shift = e.num("BaselineShift"); - a.skew = e.num("Skew"); - if let Some(r) = e.prop("FillColor") { + a.tracking = values.tracking; + a.leading_aki = values.leading_aki.map(|v| (v >= 0.0).then_some(v)); + a.trailing_aki = values.trailing_aki.map(|v| (v >= 0.0).then_some(v)); + a.tsume = values.tsume.map(|v| (v / 100.0).clamp(0.0, 1.0)); + a.jidori = values.jidori.map(|v| v.clamp(0.0, 10000.0) as u32); + a.leading_model = values.leading_model.as_deref().and_then(crate::cjk::leading_in); + a.character_alignment = values.character_alignment.as_deref().and_then(crate::cjk::alignment_in); + a.h_scale = values.horizontal_scale.map(|v| v / 100.0); + a.v_scale = values.vertical_scale.map(|v| v / 100.0); + a.baseline_shift = values.baseline_shift; + a.skew = values.skew; + let special = craft_idml::model::CharacterSpecialValues::from_el(&crate::xml::to_craft(e)); + let appearance = craft_idml::model::CharacterAppearanceValues::from_el(&crate::xml::to_craft(e)); + if let Some(r) = appearance.fill_color { a.fill = Some(self.swatch_ref(r.trim())); } - a.fill_tint = tint(e.num("FillTint")); - if let Some(r) = e.prop("StrokeColor") { + a.fill_tint = tint(appearance.fill_tint); + if let Some(r) = appearance.stroke_color { a.stroke = Some(self.swatch_ref(r.trim())); } - a.stroke_tint = tint(e.num("StrokeTint")); - a.stroke_weight = e.num("StrokeWeight"); + a.stroke_tint = tint(appearance.stroke_tint); + a.stroke_weight = appearance.stroke_weight; // Text strokes are centred on the outline or lie outside it, behind the fill. - a.stroke_behind_fill = e.prop("StrokeAlignment").and_then(|v| match v.trim() { + a.stroke_behind_fill = appearance.stroke_alignment.as_deref().and_then(|v| match v.trim() { "OutsideAlignment" => Some(true), "CenterAlignment" => Some(false), _ => None, }); - a.capitalization = e.prop("Capitalization").and_then(|v| names::caps_in(v.trim())); - a.position = e.prop("Position").and_then(|v| names::position_in(v.trim())); - a.underline = e.boolean("Underline"); - a.strikethrough = e.boolean("StrikeThru"); - a.ligatures = e.boolean("Ligatures"); + a.capitalization = special.capitalization.as_deref().and_then(|v| names::caps_in(v.trim())); + a.position = special.position.as_deref().and_then(|v| names::position_in(v.trim())); + a.underline = appearance.underline; + a.strikethrough = appearance.strikethrough; + a.ligatures = appearance.ligatures; // Underline / strikethrough options (-9999 = automatic). - for k in ["Underline", "StrikeThru"] { - let num = |n: &str| e.num(&format!("{k}{n}")).filter(|v| *v > -9000.0); + for (underline, values) in [(true, appearance.underline_options), (false, appearance.strikethrough_options)] { // An explicit Text Color resets an inherited swatch; absence still inherits. // Resolve the sentinel before swatch_ref, which maps unknown names to [None]. - let color = e.prop(&format!("{k}Color")).map(|r| if r.trim() == "Text Color" { String::new() } else { self.swatch_ref(r.trim()) }); - let tint = tint(e.num(&format!("{k}Tint"))); - if k == "Underline" { - a.underline_weight = num("Weight").map(Some); - a.underline_offset = num("Offset").map(Some); + let color = values.color.map(|r| if r.trim() == "Text Color" { String::new() } else { self.swatch_ref(r.trim()) }); + let tint = tint(values.tint); + if underline { + a.underline_weight = values.weight.map(Some); + a.underline_offset = values.offset.map(Some); a.underline_color = color; a.underline_tint = tint; } else { - a.strikethrough_weight = num("Weight").map(Some); - a.strikethrough_offset = num("Offset").map(Some); + a.strikethrough_weight = values.weight.map(Some); + a.strikethrough_offset = values.offset.map(Some); a.strikethrough_color = color; a.strikethrough_tint = tint; } } read_otf_features(e, &mut a); - a.glyph_form = e.prop("GlyphForm"); - a.no_break = e.boolean("NoBreak"); - a.tate_chu_yoko = e.boolean("Tatechuyoko"); - a.tate_chu_yoko_x_offset = e.num("TatechuyokoXOffset"); - a.tate_chu_yoko_y_offset = e.num("TatechuyokoYOffset"); - a.warichu = e.boolean("Warichu"); - a.warichu_lines = e.num("WarichuLines").map(|v| v.max(2.0) as u32); - a.warichu_size = e.num("WarichuSize"); - a.warichu_line_spacing = e.num("WarichuLineSpacing"); - a.warichu_alignment = e.prop("WarichuAlignment").as_deref().and_then(crate::cjk::warichu_align_in); - a.warichu_chars_before_break = e.num("WarichuCharsBeforeBreak").map(|v| v.max(0.0) as u32); - a.warichu_chars_after_break = e.num("WarichuCharsAfterBreak").map(|v| v.max(0.0) as u32); - // InDesign writes the flag as a number (1); older writers wrote a boolean. - if let Some(on) = e.boolean("RubyFlag").or_else(|| e.num("RubyFlag").map(|v| v != 0.0)) { - a.ruby = Some(if on { e.prop("RubyString").unwrap_or_default() } else { String::new() }); + a.glyph_form = special.glyph_form; + a.no_break = special.no_break; + a.tate_chu_yoko = special.tate_chu_yoko; + a.tate_chu_yoko_x_offset = special.tate_chu_yoko_x_offset; + a.tate_chu_yoko_y_offset = special.tate_chu_yoko_y_offset; + a.warichu = special.warichu; + a.warichu_lines = special.warichu_lines.map(|v| v.max(2.0) as u32); + a.warichu_size = special.warichu_size; + a.warichu_line_spacing = special.warichu_line_spacing; + a.warichu_alignment = special.warichu_alignment.as_deref().and_then(crate::cjk::warichu_align_in); + a.warichu_chars_before_break = special.warichu_chars_before_break.map(|v| v.max(0.0) as u32); + a.warichu_chars_after_break = special.warichu_chars_after_break.map(|v| v.max(0.0) as u32); + let ruby_values = craft_idml::model::RubyValues::from_el(&crate::xml::to_craft(e)); + if let Some(on) = ruby_values.flag { + a.ruby = Some(if on { ruby_values.text.clone().unwrap_or_default() } else { String::new() }); } - crate::ruby::read(e, &mut a, |r| self.swatch_ref(r)); - if let Some(k) = e.get("KentenKind") { + crate::ruby::read_values(&ruby_values, &mut a, |r| self.swatch_ref(r)); + if let Some(k) = cjk.kenten_kind.as_deref() { a.kenten = Some(k != "None"); a.kenten_character = crate::cjk::kenten_character(k).map(str::to_string); if k == "Custom" { - a.kenten_character = e.prop("KentenCustomCharacter"); + a.kenten_character = cjk.kenten_custom_character.clone(); } } - a.digits = e.prop("DigitsType").and_then(|s| names::digits_in(s.trim())); - a.character_direction = e.prop("CharacterDirection").and_then(|s| crate::arabic::direction_in(&s)); - a.allow_kashidas = e.prop("Kashidas").and_then(|s| crate::arabic::kashidas_in(&s)); - a.diacritic_position = e.prop("DiacriticPosition").and_then(|s| crate::arabic::diacritic_in(&s)); - a.diacritic_x_offset = e.num("XOffsetDiacritic").filter(|v| v.is_finite()); - a.diacritic_y_offset = e.num("YOffsetDiacritic").filter(|v| v.is_finite()); - a.positional_form = e.prop("PositionalForm"); - self.cjk_settings_chars(e, &mut a); - if let Some(v) = e.get("AppliedConditions").filter(|v| !v.trim().is_empty()) { + a.digits = special.digits.as_deref().and_then(|s| names::digits_in(s.trim())); + a.character_direction = special.character_direction.as_deref().and_then(crate::arabic::direction_in); + a.allow_kashidas = special.allow_kashidas.as_deref().and_then(crate::arabic::kashidas_in); + a.diacritic_position = special.diacritic_position.as_deref().and_then(crate::arabic::diacritic_in); + a.diacritic_x_offset = special.diacritic_x_offset; + a.diacritic_y_offset = special.diacritic_y_offset; + a.positional_form = special.positional_form; + self.cjk_settings_chars(&cjk, &mut a); + if let Some(v) = special.applied_conditions.as_deref().filter(|v| !v.trim().is_empty()) { let names: Vec = v.split_whitespace().filter_map(|r| self.condition_names.get(r).cloned()).collect(); if !names.is_empty() { a.conditions = Some(names); } } - a.language = e.prop("AppliedLanguage").map(|l| l.trim().trim_start_matches("$ID/").to_string()); + a.language = special.applied_language.map(|l| l.trim().trim_start_matches("$ID/").to_string()); a } pub(super) fn para_attrs(&mut self, e: &El) -> ParaAttrs { let mut a = ParaAttrs::default(); - let u = |k: &str| e.num(k).map(|v| v.max(0.0) as u32); - let frac = |k: &str| e.num(k).map(|v| v / 100.0); - a.align = e.prop("Justification").and_then(|v| names::align_in(v.trim())); - a.kinsoku_hang = e.prop("KinsokuHangType").and_then(|v| match v.as_str() { + let alignment = craft_idml::model::ParagraphAlignmentValues::from_el(&crate::xml::to_craft(e)); + let flow = craft_idml::model::ParagraphFlowValues::from_el(&crate::xml::to_craft(e)); + let cjk = craft_idml::model::CjkParagraphValues::from_el(&crate::xml::to_craft(e)); + let span = craft_idml::model::ParagraphSpanValues::from_el(&crate::xml::to_craft(e)); + let list = craft_idml::model::ParagraphListValues::from_el(&crate::xml::to_craft(e)); + a.align = alignment.justification.as_deref().and_then(|v| names::align_in(v.trim())); + a.kinsoku_hang = cjk.kinsoku_hang.as_deref().and_then(|v| match v { "None" => Some(designcraft_doc::cjk::KinsokuHang::None), "KinsokuHangRegular" => Some(designcraft_doc::cjk::KinsokuHang::Regular), "KinsokuHangForce" => Some(designcraft_doc::cjk::KinsokuHang::Force), _ => None, }); - a.mojikumi = e.prop("Mojikumi").map(|name| self.mojikumi_names.get(&name).cloned().unwrap_or_else(|| unescape_id(&name))); - a.kinsoku_type = e.prop("KinsokuType"); - a.bunri_kinshi = e.boolean("BunriKinshi"); - a.rensuuji = e.boolean("Rensuuji"); - a.treat_ideographic_space_as_space = e.boolean("TreatIdeographicSpaceAsSpace"); - cjk_settings_para(e, &mut a); - if let Some(k) = e.prop("KinsokuSet") { + a.mojikumi = cjk.mojikumi.map(|name| self.mojikumi_names.get(&name).cloned().unwrap_or_else(|| unescape_id(&name))); + a.kinsoku_type = cjk.kinsoku_type; + a.bunri_kinshi = cjk.bunri_kinshi; + a.rensuuji = cjk.rensuuji; + a.treat_ideographic_space_as_space = cjk.treat_ideographic_space_as_space; + a.auto_tcy = cjk.auto_tcy.map(|value| value as u32); + a.auto_tcy_include_roman = cjk.auto_tcy_include_roman; + a.rotate_roman = cjk.rotate_single_byte_characters; + a.roman_word_break = cjk.allow_arbitrary_hyphenation; + a.grid_gyoudori = cjk.grid_gyoudori.map(|value| value as u32); + a.paragraph_gyoudori = cjk.paragraph_gyoudori; + if let Some(k) = cjk.kinsoku_set { if k == "Nothing" || k == "None" { a.kinsoku = Some(Some(Default::default())); } else if let Some(set) = self.kinsoku.get(&k) { @@ -196,42 +186,41 @@ impl<'r> Importer<'r> { a.kinsoku = Some(Some(set)); } } - a.direction = e.prop("ParagraphDirection").map(|v| { + a.direction = alignment.direction.map(|v| { if v.trim() == "RightToLeftDirection" { designcraft_doc::TextDirection::RightToLeft } else { designcraft_doc::TextDirection::LeftToRight } }); - a.kashidas = e.prop("Kashidas").and_then(|s| crate::arabic::kashidas_in(&s)); - a.arabic_justification = e.prop("ParagraphJustification"); - a.paragraph_kashida_width = e.num("ParagraphKashidaWidth").filter(|v| v.is_finite()).map(Some); - a.left_indent = e.num("LeftIndent"); - a.right_indent = e.num("RightIndent"); - a.first_line_indent = e.num("FirstLineIndent"); - a.last_line_indent = e.num("LastLineIndent"); - a.space_before = e.num("SpaceBefore"); - if let Some(r) = e.prop("AppliedNumberingList") { + a.kashidas = alignment.kashidas.as_deref().and_then(crate::arabic::kashidas_in); + a.arabic_justification = alignment.paragraph_justification; + a.paragraph_kashida_width = alignment.paragraph_kashida_width.map(Some); + a.left_indent = alignment.left_indent; + a.right_indent = alignment.right_indent; + a.first_line_indent = alignment.first_line_indent; + a.last_line_indent = alignment.last_line_indent; + a.space_before = alignment.space_before; + if let Some(r) = list.applied_list.as_deref() { let r = r.trim().trim_start_matches("NumberingList/"); a.list_name = Some(if r.starts_with("$ID/") { String::new() } else { unescape_id(r) }); } - match e.prop("NumberingContinue").as_deref().map(str::trim) { - Some("false") => a.start_at = Some(e.num("NumberingStartAt").map(|n| n.max(1.0) as u32)), - Some("true") => a.start_at = Some(None), + match list.numbering_continue { + Some(false) => a.start_at = Some(list.numbering_start_at.map(|value| value.max(1.0) as u32)), + Some(true) => a.start_at = Some(None), _ => {} } self.read_nested_styles(e, &mut a); - a.space_after = e.num("SpaceAfter"); + a.space_after = alignment.space_after; // A number, or an enumeration (Ignore) that turns it off even over a based-on style's value. - a.same_para_style_spacing = e.prop("SameParaStyleSpacing").map(|v| v.trim().parse::().ok().filter(|v| v.is_finite())); - a.drop_cap_lines = u("DropCapLines"); - a.drop_cap_chars = u("DropCapCharacters"); + a.same_para_style_spacing = alignment.same_para_style_spacing; + a.drop_cap_lines = alignment.drop_cap_lines.map(|v| v.max(0.0) as u32); + a.drop_cap_chars = alignment.drop_cap_chars.map(|v| v.max(0.0) as u32); // DropcapDetail bits: 1 = Align Left Edge, 2 = Scale for Descenders. - if let Some(v) = e.num("DropcapDetail").filter(|v| v.is_finite() && *v >= 0.0) { - let bits = v as u32; + if let Some(bits) = alignment.dropcap_detail { a.drop_cap_align_left = Some(bits & 1 != 0); a.drop_cap_scale_descenders = Some(bits & 2 != 0); } - if let Some(g) = e.prop("GridAlignment") { + if let Some(g) = alignment.grid_alignment { a.grid_align = Some(if g.trim() == "None" { GridAlign::None - } else if e.boolean("GridAlignFirstLineOnly") == Some(true) { + } else if alignment.grid_align_first_line_only == Some(true) { GridAlign::FirstLineOnly } else { GridAlign::AllLines @@ -240,142 +229,140 @@ impl<'r> Importer<'r> { a.grid_reference = Some(crate::cjk::grid_reference_in(&g)); } } - a.composer = e.prop("Composer").map(|c| composer_in(&c)); - a.hyphenate = e.boolean("Hyphenation"); - a.hyph_min_word = u("HyphenateWordsLongerThan"); - a.hyph_after_first = u("HyphenateAfterFirst"); - a.hyph_before_last = u("HyphenateBeforeLast"); - a.hyph_limit = u("HyphenateLadderLimit"); - a.hyph_zone = e.num("HyphenationZone"); - a.hyph_capitalized = e.boolean("HyphenateCapitalizedWords"); - a.hyph_last_word = e.boolean("HyphenateLastWord"); - a.hyph_across_column = e.boolean("HyphenateAcrossColumns"); - a.hyph_weight = e.num("HyphenWeight").map(|v| v / 10.0); - a.word_space_min = frac("MinimumWordSpacing"); - a.word_space_desired = frac("DesiredWordSpacing"); - a.word_space_max = frac("MaximumWordSpacing"); - a.letter_space_min = frac("MinimumLetterSpacing"); - a.letter_space_desired = frac("DesiredLetterSpacing"); - a.letter_space_max = frac("MaximumLetterSpacing"); - a.glyph_scale_min = frac("MinimumGlyphScaling"); - a.glyph_scale_desired = frac("DesiredGlyphScaling"); - a.glyph_scale_max = frac("MaximumGlyphScaling"); - a.auto_leading = frac("AutoLeading"); - a.single_word_justify = e.prop("SingleWordJustification").and_then(|v| names::align_in(v.trim())); - a.keep_with_next = u("KeepWithNext"); - a.keep_lines_together = e.boolean("KeepLinesTogether"); - a.ignore_optical_margin = e.boolean("IgnoreEdgeAlignment"); - a.keep_all_lines = e.boolean("KeepAllLinesTogether"); - a.keep_first = u("KeepFirstLines"); - a.keep_last = u("KeepLastLines"); - a.start_paragraph = e.prop("StartParagraph").and_then(|v| names::start_para_in(v.trim())); - if let Some(t) = e.prop("SpanColumnType") { - let n = e.prop("SpanSplitColumnCount").and_then(|v| v.trim().parse::().ok()).unwrap_or(0); + a.composer = alignment.composer.map(|c| composer_in(&c)); + a.hyphenate = flow.hyphenate; + a.hyph_min_word = flow.hyphenate_min_word.map(|v| v.max(0.0) as u32); + a.hyph_after_first = flow.hyphenate_after_first.map(|v| v.max(0.0) as u32); + a.hyph_before_last = flow.hyphenate_before_last.map(|v| v.max(0.0) as u32); + a.hyph_limit = flow.hyphenate_ladder_limit.map(|v| v.max(0.0) as u32); + a.hyph_zone = flow.hyphenation_zone; + a.hyph_capitalized = flow.hyphenate_capitalized; + a.hyph_last_word = flow.hyphenate_last_word; + a.hyph_across_column = flow.hyphenate_across_columns; + a.hyph_weight = flow.hyphen_weight.map(|v| v / 10.0); + a.word_space_min = flow.word_spacing[0].map(|v| v / 100.0); + a.word_space_desired = flow.word_spacing[1].map(|v| v / 100.0); + a.word_space_max = flow.word_spacing[2].map(|v| v / 100.0); + a.letter_space_min = flow.letter_spacing[0].map(|v| v / 100.0); + a.letter_space_desired = flow.letter_spacing[1].map(|v| v / 100.0); + a.letter_space_max = flow.letter_spacing[2].map(|v| v / 100.0); + a.glyph_scale_min = flow.glyph_scaling[0].map(|v| v / 100.0); + a.glyph_scale_desired = flow.glyph_scaling[1].map(|v| v / 100.0); + a.glyph_scale_max = flow.glyph_scaling[2].map(|v| v / 100.0); + a.auto_leading = flow.auto_leading.map(|v| v / 100.0); + a.single_word_justify = flow.single_word_justification.as_deref().and_then(|v| names::align_in(v.trim())); + a.keep_with_next = flow.keep_with_next.map(|v| v.max(0.0) as u32); + a.keep_lines_together = flow.keep_lines_together; + a.ignore_optical_margin = flow.ignore_edge_alignment; + a.keep_all_lines = flow.keep_all_lines_together; + a.keep_first = flow.keep_first_lines.map(|v| v.max(0.0) as u32); + a.keep_last = flow.keep_last_lines.map(|v| v.max(0.0) as u32); + a.start_paragraph = flow.start_paragraph.as_deref().and_then(|v| names::start_para_in(v.trim())); + if let Some(t) = span.kind { + let n = span.split_column_count.unwrap_or(0); a.span_columns = Some(match t.trim() { "SpanColumns" => SpanColumns::Span(n), "SplitColumns" => SpanColumns::Split(n.max(2)), _ => SpanColumns::Single, }); } - a.split_inside_gutter = e.num("SplitColumnInsideGutter").filter(|v| v.is_finite()); - a.split_outside_gutter = e.num("SplitColumnOutsideGutter").filter(|v| v.is_finite()); + a.split_inside_gutter = span.inside_gutter; + a.split_outside_gutter = span.outside_gutter; a.rule_above = self.rule(e, "RuleAbove"); a.rule_below = self.rule(e, "RuleBelow"); a.tabs = self.read_tabs(e); - a.list_type = e.prop("BulletsAndNumberingListType").map(|v| match v.trim() { + let list = craft_idml::model::ParagraphListValues::from_el(&crate::xml::to_craft(e)); + a.list_type = list.list_type.map(|value| match value.trim() { "BulletList" => ListType::Bullets, "NumberedList" => ListType::Numbers, _ => ListType::None, }); // A format with no counterpart (CJK, Arabic, Hebrew numbering) is left unset: decimal. - a.number_style = e.prop("NumberingFormat").and_then(|v| names::numbering_format_in(&v)); - a.number_expression = e.prop("NumberingExpression"); - a.list_separator = e.prop("BulletsTextAfter"); - if let Some(b) = e.prop_el("BulletChar") { - // A glyph of a named font (`GlyphWithFont`) has no character to map to. - let unicode = matches!(b.get("BulletCharacterType"), Some("UnicodeOnly" | "UnicodeWithFont")); - if let Some(c) = b.get("BulletCharacterValue").and_then(|v| v.trim().parse::().ok()).and_then(char::from_u32).filter(|_| unicode) { - a.bullet_char = Some(c.to_string()); - } + a.number_style = list.numbering_format.as_deref().and_then(names::numbering_format_in); + a.number_expression = list.expression; + a.list_separator = list.separator; + // A glyph of a named font (`GlyphWithFont`) has no character to map to. + let unicode = matches!(list.bullet_type.as_deref(), Some("UnicodeOnly" | "UnicodeWithFont")); + if unicode { + a.bullet_char = list + .bullet_value + .as_deref() + .and_then(|value| value.trim().parse::().ok()) + .and_then(char::from_u32) + .map(|value| value.to_string()); } - a.balance_ragged = e.prop("BalanceRaggedLines").map(|v| v.trim() != "NoBalancing" && v.trim() != "false"); - a.shading_on = e.boolean("ParagraphShadingOn"); - if let Some(c) = e.prop("ParagraphShadingColor") { - a.shading_color = Some(self.swatch_ref(c.trim())); - } - a.shading_tint = tint(e.num("ParagraphShadingTint")); - let sides = |f: &dyn Fn(&str) -> String| -> Option<[f64; 4]> { - let v = ["Top", "Left", "Bottom", "Right"].map(|s| e.num(&f(s))); - v.iter().any(Option::is_some).then(|| v.map(|x| x.unwrap_or(0.0))) + a.balance_ragged = list.balance_ragged.map(|value| value.trim() != "NoBalancing" && value.trim() != "false"); + let boxes = craft_idml::model::ParagraphBoxValues::from_el(&crate::xml::to_craft(e)); + a.shading_on = boxes.shading_on; + a.shading_color = boxes.shading_color.map(|color| self.swatch_ref(color.trim())); + a.shading_tint = tint(boxes.shading_tint); + a.shading_overprint = boxes.shading_overprint; + a.shading_offsets = boxes.shading_offsets; + a.border_on = boxes.border_on; + a.border_color = boxes.border_color.map(|color| self.swatch_ref(color.trim())); + a.border_tint = tint(boxes.border_tint); + a.border_overprint = boxes.border_overprint; + a.border_weights = boxes.border_weights; + a.border_offsets = boxes.border_offsets; + a.border_type = boxes.border_type.as_deref().map(|value| names::stroke_type_in(value.trim())); + a.border_cap = boxes.border_cap.as_deref().map(|value| names::cap_in(value.trim())); + a.border_join = boxes.border_join.as_deref().map(|value| names::join_in(value.trim())); + let map_corners = |values: Option<[(String, f64); 4]>| { + values.map(|values| values.map(|(shape, size)| designcraft_geom::corners::Corner { shape: names::corner_in(shape.trim()), size })) }; - a.shading_offsets = sides(&|s| format!("ParagraphShading{s}Offset")); - a.border_on = e.boolean("ParagraphBorderOn"); - if let Some(c) = e.prop("ParagraphBorderColor") { - a.border_color = Some(self.swatch_ref(c.trim())); + a.border_corners = map_corners(boxes.border_corners); + a.border_width = boxes.border_width.as_deref().map(|value| names::box_width_in(value.trim())); + a.border_top = boxes.border_top.as_deref().map(|value| names::box_top_in(value.trim())); + a.border_bottom = boxes.border_bottom.as_deref().map(|value| names::box_bottom_in(value.trim())); + a.border_display_if_splits = boxes.border_display_if_splits; + a.border_merge = boxes.border_merge; + a.border_gap_color = boxes.border_gap_color.map(|color| self.swatch_ref(color.trim())); + a.border_gap_tint = tint(boxes.border_gap_tint); + a.border_gap_overprint = boxes.border_gap_overprint; + a.shading_corners = map_corners(boxes.shading_corners); + a.shading_width = boxes.shading_width.as_deref().map(|value| names::box_width_in(value.trim())); + a.shading_top = boxes.shading_top.as_deref().map(|value| names::box_top_in(value.trim())); + a.shading_bottom = boxes.shading_bottom.as_deref().map(|value| names::box_bottom_in(value.trim())); + a.shading_clip = boxes.shading_clip; + a.shading_nonprinting = boxes.shading_nonprinting; + a.span_space_before = span.space_before; + a.span_space_after = span.space_after; + a.list_level = list.level.map(|value| value.round().clamp(1.0, designcraft_doc::LIST_LEVELS as f64) as u32); + if let Some(style) = list.bullet_character_style { + a.bullet_char_style = Some(self.char_style_ref(style.trim())); } - a.border_tint = tint(e.num("ParagraphBorderTint")); - a.border_weights = sides(&|s| format!("ParagraphBorder{s}LineWeight")); - a.border_offsets = sides(&|s| format!("ParagraphBorder{s}Offset")); - a.border_type = e.prop("ParagraphBorderType").map(|v| names::stroke_type_in(v.trim())); - a.border_cap = e.prop("ParagraphBorderStrokeEndCap").map(|v| names::cap_in(v.trim())); - a.border_join = e.prop("ParagraphBorderStrokeEndJoin").map(|v| names::join_in(v.trim())); - a.border_corners = corners(e, "ParagraphBorder"); - a.border_width = e.prop("ParagraphBorderWidth").map(|v| names::box_width_in(v.trim())); - a.border_top = e.prop("ParagraphBorderTopOrigin").map(|v| names::box_top_in(v.trim())); - a.border_bottom = e.prop("ParagraphBorderBottomOrigin").map(|v| names::box_bottom_in(v.trim())); - a.border_display_if_splits = e.boolean("ParagraphBorderDisplayIfSplits"); - a.border_merge = e.boolean("MergeConsecutiveParaBorders"); - if let Some(c) = e.prop("ParagraphBorderGapColor") { - a.border_gap_color = Some(self.swatch_ref(c.trim())); + if let Some(style) = list.numbering_character_style { + a.number_char_style = Some(self.char_style_ref(style.trim())); } - a.border_gap_tint = tint(e.num("ParagraphBorderGapTint")); - a.shading_corners = corners(e, "ParagraphShading"); - a.shading_width = e.prop("ParagraphShadingWidth").map(|v| names::box_width_in(v.trim())); - a.shading_top = e.prop("ParagraphShadingTopOrigin").map(|v| names::box_top_in(v.trim())); - a.shading_bottom = e.prop("ParagraphShadingBottomOrigin").map(|v| names::box_bottom_in(v.trim())); - a.shading_clip = e.boolean("ParagraphShadingClipToFrame"); - a.shading_nonprinting = e.boolean("ParagraphShadingSuppressPrinting"); - a.span_space_before = e.num("SpanColumnMinSpaceBefore").filter(|v| v.is_finite()); - a.span_space_after = e.num("SpanColumnMinSpaceAfter").filter(|v| v.is_finite()); - a.list_level = e.num("NumberingLevel").filter(|v| v.is_finite()).map(|v| v.round().clamp(1.0, designcraft_doc::LIST_LEVELS as f64) as u32); - if let Some(c) = e.prop("BulletsCharacterStyle") { - a.bullet_char_style = Some(self.char_style_ref(c.trim())); - } - if let Some(c) = e.prop("NumberingCharacterStyle") { - a.number_char_style = Some(self.char_style_ref(c.trim())); - } - a.bullet_align = e.prop("BulletsAlignment").map(|v| names::list_align_in(v.trim())); - a.number_align = e.prop("NumberingAlignment").map(|v| names::list_align_in(v.trim())); - a.restart_numbers = e.boolean("NumberingApplyRestartPolicy"); - if let Some(r) = e.prop_el("NumberingRestartPolicies") { + a.bullet_align = list.bullet_alignment.as_deref().map(|value| names::list_align_in(value.trim())); + a.number_align = list.numbering_alignment.as_deref().map(|value| names::list_align_in(value.trim())); + a.restart_numbers = list.restart_numbers; + if let Some(level) = list.restart_after_level { // A specific level restarts after that level; any other policy after any higher one. - let level = r.get("LowerLevel").and_then(|v| v.trim().parse::().ok()).unwrap_or(0); - a.restart_after_level = Some(if r.get("RestartPolicy").map(str::trim) == Some("SpecificPreviousLevel") { level } else { 0 }); + a.restart_after_level = Some(if list.restart_after_specific_level { level } else { 0 }); } - if let Some(f) = e.prop("BulletsFont") { - let f = f.trim(); - a.bullet_font = Some(if f == "$ID/" { String::new() } else { f.split('\t').next().unwrap_or(f).to_string() }); + if let Some(font) = list.bullet_font { + let font = font.trim(); + a.bullet_font = Some(if font == "$ID/" { String::new() } else { font.split('\t').next().unwrap_or(font).to_string() }); } - if let Some(f) = e.prop("BulletsFontStyle") { - let f = f.trim(); - a.bullet_font_style = Some(if f == "Nothing" || f == "$ID/" { String::new() } else { f.trim_start_matches("$ID/").to_string() }); + if let Some(style) = list.bullet_font_style { + let style = style.trim(); + a.bullet_font_style = + Some(if style == "Nothing" || style == "$ID/" { String::new() } else { style.trim_start_matches("$ID/").to_string() }); } a } fn read_nested_styles(&self, e: &El, attrs: &mut ParaAttrs) { - if let Some(list) = e.prop_el("AllNestedStyles") { - let styles: Vec = list - .find_all("ListItem") - .map(|item| { - let text = |key: &str| item.find(key).map(|element| element.text_content()).unwrap_or_default(); - let delimiter = item.find("Delimiter"); - designcraft_doc::NestedStyle { - style: self.listed_char_style_ref(&text("AppliedCharacterStyle")), - through: text("Inclusive").trim() != "false", - count: text("Repetition").trim().parse().unwrap_or(1), - until: names::nested_until_in(delimiter.and_then(|element| element.get("type")).unwrap_or("enumeration"), &text("Delimiter")), - } + let lists = craft_idml::model::NestedStyleValues::from_el(&crate::xml::to_craft(e)); + if let Some(values) = lists.nested { + let styles: Vec = values + .into_iter() + .map(|value| designcraft_doc::NestedStyle { + style: self.listed_char_style_ref(&value.character_style), + through: value.inclusive, + count: value.repetition, + until: names::nested_until_in(&value.delimiter_type, &value.delimiter), }) .collect(); // IDML has no drop cap style attribute: the drop cap's character style is the list's @@ -383,43 +370,37 @@ impl<'r> Importer<'r> { attrs.drop_cap_style = styles.first().filter(|style| style.is_drop_cap()).map(|style| style.style.clone()); attrs.nested_styles = Some(styles); } - if let Some(list) = e.prop_el("AllNestedLineStyles") { - let styles = list - .find_all("ListItem") - .map(|item| { - let text = |key: &str| item.find(key).map(|element| element.text_content()).unwrap_or_default(); - designcraft_doc::NestedLineStyle { - style: self.listed_char_style_ref(&text("AppliedCharacterStyle")), - lines: text("LineCount").trim().parse().unwrap_or(1), - } - }) - .collect(); - attrs.nested_line_styles = Some(styles); + if let Some(values) = lists.lines { + attrs.nested_line_styles = Some( + values + .into_iter() + .map(|value| designcraft_doc::NestedLineStyle { + style: self.listed_char_style_ref(&value.character_style), + lines: value.line_count, + }) + .collect(), + ); } - if let Some(list) = e.prop_el("AllGREPStyles") { - let styles = list - .find_all("ListItem") - .map(|item| { - let text = |key: &str| item.find(key).map(|element| element.text_content()).unwrap_or_default(); - designcraft_doc::GrepStyle { style: self.listed_char_style_ref(&text("AppliedCharacterStyle")), pattern: text("GrepExpression") } - }) - .collect(); - attrs.grep_styles = Some(styles); + if let Some(values) = lists.grep { + attrs.grep_styles = Some( + values + .into_iter() + .map(|value| designcraft_doc::GrepStyle { style: self.listed_char_style_ref(&value.character_style), pattern: value.expression }) + .collect(), + ); } } fn read_tabs(&mut self, e: &El) -> Option> { let list = e.prop_el("TabList")?; - let tabs: Vec<_> = list - .find_all("ListItem") - .map(|item| { - let get = |key: &str| item.find(key).map(|element| element.text_content()); - TabStop { - position: get("Position").and_then(|value| value.trim().parse::().ok()).filter(|value| value.is_finite()).unwrap_or(0.0), - align: names::tab_align_in(get("Alignment").unwrap_or_default().trim()), - leader: get("Leader").unwrap_or_default(), - align_on: get("AlignmentCharacter").filter(|character| character != ".").unwrap_or_default(), - } + let model_list = crate::xml::to_craft(list); + let tabs: Vec<_> = craft_idml::model::TabStopValues::from_list(&model_list) + .into_iter() + .map(|tab| TabStop { + position: tab.position, + align: names::tab_align_in(tab.alignment.trim()), + leader: tab.leader, + align_on: if tab.alignment_character == "." { String::new() } else { tab.alignment_character }, }) .collect(); let sanitized = TabStop::sanitized_list(tabs.clone()); @@ -431,12 +412,12 @@ impl<'r> Importer<'r> { } pub(super) fn ace_char(v: &str) -> Option { - match v.trim() { - "18" => Some(st::PAGE_NUMBER), - "19" => Some(st::SECTION_MARKER), - "7" => Some(st::INDENT_HERE), - "8" => Some(st::RIGHT_INDENT_TAB), - _ => None, + match craft_idml::model::Ace::from_decimal(v)? { + craft_idml::model::Ace::PageNumber => Some(st::PAGE_NUMBER), + craft_idml::model::Ace::SectionMarker => Some(st::SECTION_MARKER), + craft_idml::model::Ace::IndentToHere => Some(st::INDENT_HERE), + craft_idml::model::Ace::RightIndentTab => Some(st::RIGHT_INDENT_TAB), + craft_idml::model::Ace::FootnoteNumber | craft_idml::model::Ace::Other(_) => None, } } @@ -490,23 +471,10 @@ pub(super) fn inherits_drop_cap_style<'a>(styles: &'a Styles, mut name: Option<& false } -/// Auto tate-chu-yoko, Japanese composition and grid settings of a paragraph range or style. -fn cjk_settings_para(e: &El, a: &mut ParaAttrs) { - let count = |k: &str| e.num(k).filter(|v| v.is_finite()).map(|v| v.clamp(0.0, 1000.0) as u32); - a.auto_tcy = count("AutoTcy"); - a.auto_tcy_include_roman = e.boolean("AutoTcyIncludeRoman"); - a.rotate_roman = e.boolean("RotateSingleByteCharacters"); - // 欧文泣き別れ: the name is inferred (it follows TreatIdeographicSpaceAsSpace). - a.roman_word_break = e.boolean("AllowArbitraryHyphenation"); - a.grid_gyoudori = count("GridGyoudori"); - a.paragraph_gyoudori = e.boolean("ParagraphGyoudori"); -} - impl Importer<'_> { /// Kenten Settings, Kenten Color and Shatai of a character range or style. - fn cjk_settings_chars(&mut self, e: &El, a: &mut CharAttrs) { - let finite = |k: &str| e.num(k).filter(|v| v.is_finite()); - if let Some(kind) = e.get("KentenKind").and_then(crate::cjk::kenten_kind_in) { + fn cjk_settings_chars(&mut self, values: &craft_idml::model::CjkCharacterValues, a: &mut CharAttrs) { + if let Some(kind) = values.kenten_kind.as_deref().and_then(crate::cjk::kenten_kind_in) { a.kenten_kind = Some(kind); if a.kenten_character.as_deref().is_none_or(str::is_empty) && let Some(mark) = kind.mark() @@ -514,62 +482,45 @@ impl Importer<'_> { a.kenten_character = Some(mark.to_string()); } } - if let Some(f) = e.prop("KentenFont") { - let f = f.trim(); - a.kenten_font = Some(if f == "$ID/" { String::new() } else { f.to_string() }); + if let Some(font) = values.kenten_font.as_deref() { + let font = font.trim(); + a.kenten_font = Some(if font == "$ID/" { String::new() } else { font.to_string() }); } - if let Some(st) = e.prop("KentenFontStyle") { - let st = st.trim(); - a.kenten_font_style = Some(if st == "Nothing" { String::new() } else { st.to_string() }); + if let Some(style) = values.kenten_font_style.as_deref() { + let style = style.trim(); + a.kenten_font_style = Some(if style == "Nothing" { String::new() } else { style.to_string() }); } - a.kenten_size = finite("KentenFontSize").map(|v| (v > 0.0).then_some(v)); - a.kenten_x_scale = finite("KentenXScale").map(|v| v / 100.0); - a.kenten_y_scale = finite("KentenYScale").map(|v| v / 100.0); - a.kenten_distance = finite("KentenPlacement"); - a.kenten_position = e.prop("KentenPosition").and_then(|v| crate::cjk::kenten_position_in(&v)); - a.kenten_alignment = e.prop("KentenAlignment").and_then(|v| crate::cjk::kenten_alignment_in(&v)); - a.kenten_character_set = e.prop("KentenCharacterSet"); + a.kenten_size = values.kenten_size.map(|v| (v > 0.0).then_some(v)); + a.kenten_x_scale = values.kenten_x_scale.map(|v| v / 100.0); + a.kenten_y_scale = values.kenten_y_scale.map(|v| v / 100.0); + a.kenten_distance = values.kenten_distance; + a.kenten_position = values.kenten_position.as_deref().and_then(crate::cjk::kenten_position_in); + a.kenten_alignment = values.kenten_alignment.as_deref().and_then(crate::cjk::kenten_alignment_in); + a.kenten_character_set = values.kenten_character_set.clone(); // "Text Color" is the text's own colour; it resets an inherited swatch. - if let Some(r) = e.prop("KentenFillColor") { - a.kenten_fill = Some(if r.trim() == "Text Color" { String::new() } else { self.swatch_ref(r.trim()) }); + if let Some(color) = values.kenten_fill_color.as_deref() { + a.kenten_fill = Some(if color.trim() == "Text Color" { String::new() } else { self.swatch_ref(color.trim()) }); } - if let Some(r) = e.prop("KentenStrokeColor") { - a.kenten_stroke = Some(if r.trim() == "Text Color" { String::new() } else { self.swatch_ref(r.trim()) }); + if let Some(color) = values.kenten_stroke_color.as_deref() { + a.kenten_stroke = Some(if color.trim() == "Text Color" { String::new() } else { self.swatch_ref(color.trim()) }); } // Tints and weight: -1 is the text's. - a.kenten_fill_tint = finite("KentenTint").map(|v| (v >= 0.0).then(|| (v.min(100.0) / 100.0) as f32)); - a.kenten_stroke_tint = finite("KentenStrokeTint").map(|v| (v >= 0.0).then(|| (v.min(100.0) / 100.0) as f32)); - a.kenten_stroke_weight = finite("KentenWeight").map(|v| (v >= 0.0).then_some(v)); - a.kenten_overprint_fill = e.prop("KentenOverprintFill").and_then(|v| crate::cjk::overprint_in(&v)); - a.kenten_overprint_stroke = e.prop("KentenOverprintStroke").and_then(|v| crate::cjk::overprint_in(&v)); - a.shatai_magnification = finite("ShataiMagnification"); - a.shatai_angle = finite("ShataiDegreeAngle").map(|v| v / crate::cjk::SHATAI_ANGLE_UNITS); - a.shatai_adjust_rotation = e.boolean("ShataiAdjustRotation"); - a.shatai_adjust_tsume = e.boolean("ShataiAdjustTsume"); + a.kenten_fill_tint = values.kenten_fill_tint.map(|v| (v >= 0.0).then(|| (v.min(100.0) / 100.0) as f32)); + a.kenten_stroke_tint = values.kenten_stroke_tint.map(|v| (v >= 0.0).then(|| (v.min(100.0) / 100.0) as f32)); + a.kenten_stroke_weight = values.kenten_stroke_weight.map(|v| (v >= 0.0).then_some(v)); + a.kenten_overprint_fill = values.kenten_overprint_fill.as_deref().and_then(crate::cjk::overprint_in); + a.kenten_overprint_stroke = values.kenten_overprint_stroke.as_deref().and_then(crate::cjk::overprint_in); + a.shatai_magnification = values.shatai_magnification; + a.shatai_angle = values.shatai_angle.map(|v| v / crate::cjk::SHATAI_ANGLE_UNITS); + a.shatai_adjust_rotation = values.shatai_adjust_rotation; + a.shatai_adjust_tsume = values.shatai_adjust_tsume; } } /// OpenType features (only when the element sets any). fn read_otf_features(e: &El, a: &mut CharAttrs) { - let mut otf_list: Vec = Vec::new(); - let mut any = false; - for (tag, _, attr) in designcraft_doc::otf::TOGGLES { - if let Some(on) = e.boolean(attr) { - designcraft_doc::otf::set(&mut otf_list, tag, on); - any = true; - } - } - if let Some(fig) = e.prop("OTFFigureStyle") - && let Some((id, ..)) = designcraft_doc::otf::FIGURES.iter().find(|f| f.3 == fig.trim()) - { - designcraft_doc::otf::set_figures(&mut otf_list, id); - any = true; - } - if let Some(m) = e.num("OTFStylisticSets") { - designcraft_doc::otf::set_stylistic_sets(&mut otf_list, m.max(0.0) as u32); - any = true; - } - if any { - a.otf_features = Some(otf_list); + let features = craft_idml::model::OpenTypeFeatureValues::from_el(&crate::xml::to_craft(e)); + if features.present { + a.otf_features = Some(features.features); } } diff --git a/crates/idml/src/import/values.rs b/crates/idml/src/import/values.rs index 41ad7bfe6..a6237b7f0 100644 --- a/crates/idml/src/import/values.rs +++ b/crates/idml/src/import/values.rs @@ -1,4 +1,10 @@ -use super::{Affine, Color, El, Point, lab}; +use super::{Color, lab}; + +/// Parses a whitespace-separated list, rejecting non-finite values as a group. +pub(super) fn nums(s: &str) -> Vec { + let values: Vec = s.split_whitespace().filter_map(|value| value.parse().ok()).collect(); + if values.iter().all(|value| value.is_finite()) { values } else { Vec::new() } +} /// An XMP date property, written as an element or an attribute. pub(super) fn xmp_date(xmp: &str, key: &str) -> Option { @@ -18,35 +24,11 @@ pub(super) fn lab_to_color(l: f32, a: f32, b: f32) -> Color { Color::rgb(rgb[0], rgb[1], rgb[2]) } -/// The numbers in a whitespace-separated list; empty when any number is NaN or infinite (JSON -/// can't store them, and dropping just those would shift the rest). -pub(super) fn nums(s: &str) -> Vec { - let v: Vec = s.split_whitespace().filter_map(|v| v.parse().ok()).collect(); - if v.iter().all(|x| x.is_finite()) { v } else { Vec::new() } -} - -pub(super) fn parse_affine(s: Option<&str>) -> Affine { - match s.map(nums) { - Some(v) if v.len() == 6 => Affine::new([v[0], v[1], v[2], v[3], v[4], v[5]]), - _ => Affine::IDENTITY, - } -} - -pub(super) fn parse_point(s: Option<&str>) -> Option { - let v = nums(s?); - (v.len() >= 2).then(|| Point::new(v[0], v[1])) -} - /// IDML tint (percent; `-1` = the colour's own tint, 100 %) → 0..1. pub(super) fn tint(v: Option) -> Option { v.map(|t| if t < 0.0 || t.is_nan() { 1.0 } else { (t / 100.0).min(1.0) as f32 }) } -/// A cell span count; an infinite span is kept so it clamps to the table edge. -pub(super) fn span(e: &El, k: &str) -> f64 { - e.prop(k).and_then(|v| v.trim().parse::().ok()).unwrap_or(1.0) -} - pub(super) fn finite(v: Option) -> Option { v.filter(|v| v.is_finite()) } diff --git a/crates/idml/src/lib.rs b/crates/idml/src/lib.rs index 8f7b22ff9..08d78cae9 100644 --- a/crates/idml/src/lib.rs +++ b/crates/idml/src/lib.rs @@ -57,13 +57,15 @@ mod xml; #[cfg(test)] mod tests; -pub use export::{ExportOptions, export_idml, export_idml_with}; +pub use craft_idml::is_idml; +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}; /// The IDML package mimetype (content of the first, stored `mimetype` entry). -pub const MIMETYPE: &str = "application/vnd.adobe.indesign-idml-package"; +pub const MIMETYPE: &str = craft_idml::MIMETYPE; /// The DOM version written to every part. -pub const DOM_VERSION: &str = "16.0"; +pub const DOM_VERSION: &str = craft_idml::DOM_VERSION; #[derive(Debug, thiserror::Error)] pub enum IdmlError { @@ -77,94 +79,17 @@ pub enum IdmlError { pub type Result = std::result::Result; -/// Does `bytes` look like an IDML package (a ZIP whose first, stored entry is the IDML `mimetype`)? -pub fn is_idml(bytes: &[u8]) -> bool { - bytes.starts_with(b"PK\x03\x04") && bytes.get(30..38) == Some(b"mimetype") && { - let extra = bytes.get(28..30).map_or(0, |e| u16::from_le_bytes([e[0], e[1]]) as usize); - bytes.get(38 + extra..).is_some_and(|rest| rest.starts_with(MIMETYPE.as_bytes())) - } -} - -const B64: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; - -/// Base64 with line breaks every 76 characters (as embedded image `Contents` are written). -pub(crate) fn base64_encode(data: &[u8]) -> String { - let mut out = String::with_capacity(data.len().div_ceil(3) * 4 + data.len() / 57); - for (i, c) in data.chunks(3).enumerate() { - if i > 0 && i % 19 == 0 { - out.push('\n'); - } - let n = (c[0] as u32) << 16 | (*c.get(1).unwrap_or(&0) as u32) << 8 | *c.get(2).unwrap_or(&0) as u32; - out.push(B64[(n >> 18) as usize & 63] as char); - out.push(B64[(n >> 12) as usize & 63] as char); - out.push(if c.len() > 1 { B64[(n >> 6) as usize & 63] as char } else { '=' }); - out.push(if c.len() > 2 { B64[n as usize & 63] as char } else { '=' }); - } - out -} - -/// Lenient base64 decoding (whitespace and unknown characters are skipped). -pub(crate) fn base64_decode(s: &str) -> Vec { - let mut out = Vec::with_capacity(s.len() * 3 / 4); - let mut buf = 0u32; - let mut bits = 0; - for b in s.bytes() { - let v = match b { - b'A'..=b'Z' => b - b'A', - b'a'..=b'z' => b - b'a' + 26, - b'0'..=b'9' => b - b'0' + 52, - b'+' | b'-' => 62, - b'/' | b'_' => 63, - _ => continue, - } as u32; - buf = buf << 6 | v; - bits += 6; - if bits >= 8 { - bits -= 8; - out.push((buf >> bits) as u8); - } - } - out -} - -/// Sniff an image's MIME type and pixel size (PNG, JPEG, GIF, WebP, TIFF, PDF, EPS). +/// MIME and size metadata for a placed image, delegated to the shared format registry and image +/// boundary. The application keeps only its EPS proxy pixel-size policy. pub(crate) fn sniff_image(b: &[u8]) -> (Option<&'static str>, Option<(u32, u32)>) { - if designcraft_images::is_eps(b) { - return (Some("application/postscript"), designcraft_images::eps_pixel_size(b)); - } - let be32 = |i: usize| b.get(i..i + 4).map(|s| u32::from_be_bytes([s[0], s[1], s[2], s[3]])); - if b.starts_with(b"\x89PNG\r\n\x1a\n") { - return (Some("image/png"), be32(16).zip(be32(20))); - } - if b.starts_with(&[0xFF, 0xD8]) { - let mut i = 2; - while i + 9 < b.len() { - if b[i] != 0xFF { - i += 1; - continue; - } - let m = b[i + 1]; - let len = u16::from_be_bytes([b[i + 2], b[i + 3]]) as usize; - if matches!(m, 0xC0..=0xC3 | 0xC5..=0xC7 | 0xC9..=0xCB | 0xCD..=0xCF) { - let h = u16::from_be_bytes([b[i + 5], b[i + 6]]) as u32; - let w = u16::from_be_bytes([b[i + 7], b[i + 8]]) as u32; - return (Some("image/jpeg"), Some((w, h))); - } - i += 2 + len; - } - return (Some("image/jpeg"), None); - } - if b.starts_with(b"GIF8") && b.len() >= 10 { - return (Some("image/gif"), Some((u16::from_le_bytes([b[6], b[7]]) as u32, u16::from_le_bytes([b[8], b[9]]) as u32))); - } - if b.starts_with(b"RIFF") && b.get(8..12) == Some(b"WEBP") { - return (Some("image/webp"), None); - } - if b.starts_with(b"II*\0") || b.starts_with(b"MM\0*") { - return (Some("image/tiff"), None); - } - if b.starts_with(b"%PDF") { - return (Some("application/pdf"), None); - } - (None, None) + let Some(format) = craft_file_formats::detect("", b) else { return (None, None) }; + let mime = format.mime_type(); + let pixels = if format == craft_file_formats::Format::Eps { + designcraft_images::eps_pixel_size(b) + } else if mime.is_some_and(|mime| mime.starts_with("image/")) { + designcraft_images::pixel_size(b) + } else { + None + }; + (mime, pixels) } diff --git a/crates/idml/src/names.rs b/crates/idml/src/names.rs index b9102c9ae..0d3396462 100644 --- a/crates/idml/src/names.rs +++ b/crates/idml/src/names.rs @@ -120,10 +120,10 @@ pub fn liquid_rule_in(s: &str) -> designcraft_doc::LiquidRule { } pub fn escape_id(s: &str) -> String { - s.replace('%', "%25").replace(':', "%3a") + craft_idml::value::escape_id(s) } pub fn unescape_id(s: &str) -> String { - s.replace("%3a", ":").replace("%3A", ":").replace("%25", "%") + craft_idml::value::unescape_id(s) } /// An `AppliedFont` value → font family. InDesign can write the family with its `$ID/` prefix @@ -147,38 +147,15 @@ pub const OBJECT_BUILTINS: &[(&str, &str)] = /// Our style name → IDML `Name` (groups: `A/B` → `A:B`; a literal `:` or `\` is escaped as `\:` /// or `\\`, so it is not read back as a group separator). pub fn style_name_out(builtins: &[(&str, &str)], name: &str) -> String { - builtins - .iter() - .find(|(o, _)| *o == name) - .map(|(_, i)| i.to_string()) - .unwrap_or_else(|| name.replace('\\', "\\\\").replace(':', "\\:").replace('/', ":")) + craft_idml::value::style_name_out(builtins, name) } /// IDML `Name` → our style name. pub fn style_name_in(builtins: &[(&str, &str)], name: &str) -> String { - if let Some((o, _)) = builtins.iter().find(|(_, i)| *i == name) { - return o.to_string(); - } - let name = name.strip_prefix("$ID/").unwrap_or(name); - let mut out = String::with_capacity(name.len()); - let mut chars = name.chars(); - while let Some(c) = chars.next() { - match c { - '\\' => match chars.clone().next() { - Some(next @ ('\\' | ':')) => { - out.push(next); - chars.next(); - } - _ => out.push('\\'), - }, - ':' => out.push('/'), - _ => out.push(c), - } - } - out + craft_idml::value::style_name_in(builtins, name) } /// `ParagraphStyle/…` Self id for one of our names. pub fn style_self(kind: &str, builtins: &[(&str, &str)], name: &str) -> String { - format!("{kind}/{}", escape_id(&style_name_out(builtins, name))) + craft_idml::value::style_self(kind, builtins, name) } pub fn align_out(a: Align) -> &'static str { @@ -655,6 +632,8 @@ pub fn number_style_in(s: &str) -> NumberStyle { } } +/// IDML `MeasurementUnits` of a unit. Q is `Q`; `U` is a different unit, which DesignCraft +/// doesn't have. pub fn unit_out(u: Unit) -> &'static str { match u { Unit::Points => "Points", @@ -666,27 +645,14 @@ pub fn unit_out(u: Unit) -> &'static str { Unit::Ciceros => "Ciceros", Unit::Agates => "Agates", Unit::Pixels => "Pixels", - Unit::Q => "U", + Unit::Q => "Q", Unit::Ha => "Ha", } } -pub fn unit_in(s: &str) -> Unit { - [ - Unit::Points, - Unit::Picas, - Unit::Inches, - Unit::InchesDecimal, - Unit::Millimeters, - Unit::Centimeters, - Unit::Ciceros, - Unit::Agates, - Unit::Pixels, - Unit::Q, - Unit::Ha, - ] - .into_iter() - .find(|u| unit_out(*u) == s) - .unwrap_or(Unit::Points) +/// The unit an IDML `MeasurementUnits` value names, if DesignCraft has it (not `U`, `Bai`, +/// `Mils`, `AmericanPoints` or `Custom`). +pub fn unit_in(s: &str) -> Option { + Unit::ALL.into_iter().find(|u| unit_out(*u) == s) } /// IDML layer colour enumeration names for our layer colour table. @@ -858,28 +824,25 @@ pub fn digits_in(s: &str) -> Option { [Digits::Default, Digits::Arabic, Digits::Hindi, Digits::Farsi, Digits::Native].into_iter().find(|d| digits_out(*d) == s) } -/// A TOC separator in IDML's special-character notation: `^t` is a tab, `^^` a caret. +/// A TOC separator in IDML's special-character notation. pub fn toc_separator_out(s: &str) -> String { - s.replace('^', "^^").replace('\t', "^t") + designcraft_doc::story::toc_separator_notation(s) } -/// IDML TOC separator → text (`^t` and `^y`, the right indent tab, are tabs; other codes stay). +/// IDML may prefix a separator with its localized-string marker. pub fn toc_separator_in(s: &str) -> String { - let mut out = String::new(); - let mut it = s.chars(); - while let Some(c) = it.next() { - if c != '^' { - out.push(c); - continue; - } - match it.next() { - Some('t' | 'y') => out.push('\t'), - Some('^') => out.push('^'), - Some(o) => { - out.push('^'); - out.push(o); - } - None => out.push('^'), - } + designcraft_doc::story::toc_separator_text(s.strip_prefix("$ID/").unwrap_or(s)) +} + +#[cfg(test)] +mod toc_separator_tests { + use super::*; + + #[test] + fn localized_right_indent_tab_is_not_an_ordinary_tab() { + assert_eq!(toc_separator_in("$ID/^y"), "\u{E006}"); + assert_eq!(toc_separator_in("$ID/ ^y "), " \u{E006} "); + assert_eq!(toc_separator_in("^t"), "\t"); + assert_eq!(toc_separator_out("\u{E006}"), "^y"); + assert_eq!(toc_separator_in("^^y ^q ^"), "^y ^q ^"); } - out } diff --git a/crates/idml/src/ruby.rs b/crates/idml/src/ruby.rs index 352da63a1..dc4f8878e 100644 --- a/crates/idml/src/ruby.rs +++ b/crates/idml/src/ruby.rs @@ -50,52 +50,46 @@ fn name(table: &[(T, &'static str)], v: T) -> Option<&'stat table.iter().find(|(t, _)| *t == v).map(|(_, n)| *n) } -fn finite(e: &El, k: &str) -> Option { - e.num(k).filter(|v| v.is_finite()) -} - -/// Read the ruby settings of a style or range element into `a`. `swatch` maps a swatch -/// reference to the document's swatch name. -pub(crate) fn read(e: &El, a: &mut CharAttrs, mut swatch: impl FnMut(&str) -> String) { - a.ruby_type = e.prop("RubyType").and_then(|v| lookup(TYPES, &v)); - a.ruby_alignment = e.prop("RubyAlignment").and_then(|v| lookup(ALIGNMENTS, &v)); - a.ruby_position = e.prop("RubyPosition").and_then(|v| lookup(POSITIONS, &v)); - a.ruby_x_offset = finite(e, "RubyXOffset").map(|v| v.clamp(-1000.0, 1000.0)); - a.ruby_y_offset = finite(e, "RubyYOffset").map(|v| v.clamp(-1000.0, 1000.0)); - if let Some(f) = e.prop("RubyFont") { +/// Read neutral Ruby values into `a`. `swatch` maps a swatch reference to the document's swatch name. +pub(crate) fn read_values(values: &craft_idml::model::RubyValues, a: &mut CharAttrs, mut swatch: impl FnMut(&str) -> String) { + a.ruby_type = values.kind.as_deref().and_then(|value| lookup(TYPES, value)); + a.ruby_alignment = values.alignment.as_deref().and_then(|value| lookup(ALIGNMENTS, value)); + a.ruby_position = values.position.as_deref().and_then(|value| lookup(POSITIONS, value)); + a.ruby_x_offset = values.x_offset.map(|v| v.clamp(-1000.0, 1000.0)); + a.ruby_y_offset = values.y_offset.map(|v| v.clamp(-1000.0, 1000.0)); + if let Some(f) = &values.font { let f = f.trim(); let fam = f.split('\t').next().unwrap_or(f); a.ruby_font = Some(if fam == "$ID/" { String::new() } else { fam.to_string() }); } - if let Some(s) = e.prop("RubyFontStyle") { + if let Some(s) = &values.font_style { let s = s.trim(); a.ruby_font_style = Some(if s == "Nothing" { String::new() } else { s.to_string() }); } // -1: automatic (half the parent size). - a.ruby_font_size = finite(e, "RubyFontSize").map(|v| (v > 0.0).then_some(v.clamp(0.1, 1296.0))); - a.ruby_x_scale = finite(e, "RubyXScale").map(|v| (v / 100.0).clamp(0.01, 10.0)); - a.ruby_y_scale = finite(e, "RubyYScale").map(|v| (v / 100.0).clamp(0.01, 10.0)); - a.ruby_open_type_pro = e.boolean("RubyOpenTypePro"); - a.ruby_auto_tcy_digits = finite(e, "RubyAutoTcyDigits").map(|v| v.clamp(0.0, 9.0) as u32); - a.ruby_auto_tcy_include_roman = e.boolean("RubyAutoTcyIncludeRoman"); - a.ruby_auto_tcy_auto_scale = e.boolean("RubyAutoTcyAutoScale"); - a.ruby_overhang = e.boolean("RubyOverhang"); - a.ruby_overhang_amount = e.prop("RubyParentOverhangAmount").and_then(|v| lookup(OVERHANGS, &v)); - a.ruby_parent_spacing = e.prop("RubyParentSpacing").and_then(|v| lookup(SPACINGS, &v)); - a.ruby_auto_align = e.boolean("RubyAutoAlign"); - a.ruby_auto_scaling = e.boolean("RubyAutoScaling"); - a.ruby_scaling_min = finite(e, "RubyParentScalingPercent").map(|v| (v / 100.0).clamp(0.1, 1.0)); - let color = |r: String, swatch: &mut dyn FnMut(&str) -> String| if r.trim() == TEXT_COLOR { String::new() } else { swatch(r.trim()) }; - a.ruby_fill = e.prop("RubyFill").map(|r| color(r, &mut swatch)); - a.ruby_stroke = e.prop("RubyStroke").map(|r| color(r, &mut swatch)); + a.ruby_font_size = values.font_size.map(|v| (v > 0.0).then_some(v.clamp(0.1, 1296.0))); + a.ruby_x_scale = values.x_scale.map(|v| (v / 100.0).clamp(0.01, 10.0)); + a.ruby_y_scale = values.y_scale.map(|v| (v / 100.0).clamp(0.01, 10.0)); + a.ruby_open_type_pro = values.open_type_pro; + a.ruby_auto_tcy_digits = values.auto_tcy_digits.map(|v| v.clamp(0.0, 9.0) as u32); + a.ruby_auto_tcy_include_roman = values.auto_tcy_include_roman; + a.ruby_auto_tcy_auto_scale = values.auto_tcy_auto_scale; + a.ruby_overhang = values.overhang; + a.ruby_overhang_amount = values.parent_overhang.as_deref().and_then(|value| lookup(OVERHANGS, value)); + a.ruby_parent_spacing = values.parent_spacing.as_deref().and_then(|value| lookup(SPACINGS, value)); + a.ruby_auto_align = values.auto_align; + a.ruby_auto_scaling = values.auto_scaling; + a.ruby_scaling_min = values.parent_scaling.map(|v| (v / 100.0).clamp(0.1, 1.0)); + let color = |r: &str, swatch: &mut dyn FnMut(&str) -> String| if r.trim() == TEXT_COLOR { String::new() } else { swatch(r.trim()) }; + a.ruby_fill = values.fill.as_deref().map(|r| color(r, &mut swatch)); + a.ruby_stroke = values.stroke.as_deref().map(|r| color(r, &mut swatch)); // -1: automatic (the text's tint, stroke weight). let tint = |v: f64| (v >= 0.0).then_some((v / 100.0).clamp(0.0, 1.0) as f32); - a.ruby_fill_tint = finite(e, "RubyTint").map(tint); - a.ruby_stroke_tint = finite(e, "RubyStrokeTint").map(tint); - a.ruby_stroke_weight = finite(e, "RubyWeight").map(|v| (v >= 0.0).then_some(v.min(800.0))); - let overprint = |k: &str| e.prop(k).and_then(|v| overprint_in(&v)); - a.ruby_overprint_fill = overprint("RubyOverprintFill"); - a.ruby_overprint_stroke = overprint("RubyOverprintStroke"); + a.ruby_fill_tint = values.fill_tint.map(tint); + a.ruby_stroke_tint = values.stroke_tint.map(tint); + a.ruby_stroke_weight = values.stroke_weight.map(|v| (v >= 0.0).then_some(v.min(800.0))); + a.ruby_overprint_fill = values.overprint_fill.as_deref().and_then(overprint_in); + a.ruby_overprint_stroke = values.overprint_stroke.as_deref().and_then(overprint_in); } /// Ruby parent-text options (OpenType Pro, auto tate-chu-yoko, overhang, spacing, scaling). diff --git a/crates/idml/src/tests.rs b/crates/idml/src/tests.rs index 0d078c63c..e4a19619d 100644 --- a/crates/idml/src/tests.rs +++ b/crates/idml/src/tests.rs @@ -330,12 +330,19 @@ fn indesign_text_defaults() -> Vec { "RuleBelow": "false" => false, "true" => true, |r| r.0.rule_below.on; "RuleBelowColor": "Text Color" => designcraft_doc::TEXT_COLOR, "Color/Black" => "[Black]", |r| r.0.rule_below.color; "RuleBelowTint": "-1" => 1.0f32, "50" => 0.5f32, |r| r.0.rule_below.tint; + "RuleBelowType": "StrokeStyle/$ID/Solid" => designcraft_doc::StrokeType::Solid, "StrokeStyle/$ID/Wavy" => designcraft_doc::StrokeType::Wavy, |r| r.0.rule_below.kind; + "RuleBelowGapColor": "Swatch/None" => "[None]", "Color/Black" => "[Black]", |r| r.0.rule_below.gap_color; + "RuleBelowGapTint": "-1" => 1.0f32, "50" => 0.5f32, |r| r.0.rule_below.gap_tint; + "KeepRuleAboveInFrame": "false" => false, "true" => true, |r| r.0.rule_above.keep_in_frame; "ParagraphShadingOn": "false" => false, "true" => true, |r| r.0.shading_on; "ParagraphShadingColor": "Color/Black" => "[Black]", "Swatch/None" => "[None]", |r| r.0.shading_color; "ParagraphShadingTint": "20" => 0.2f32, "50" => 0.5f32, |r| r.0.shading_tint; "ParagraphBorderOn": "false" => false, "true" => true, |r| r.0.border_on; "ParagraphBorderColor": "Color/Black" => "[Black]", "Swatch/None" => "[None]", |r| r.0.border_color; "ParagraphBorderTint": "-1" => 1.0f32, "50" => 0.5f32, |r| r.0.border_tint; + "ParagraphShadingOverprint": "false" => false, "true" => true, |r| r.0.shading_overprint; + "ParagraphBorderOverprint": "false" => false, "true" => true, |r| r.0.border_overprint; + "ParagraphBorderGapOverprint": "false" => false, "true" => true, |r| r.0.border_gap_overprint; "FontStyle": "Regular" => "Regular", "Bold" => "Bold", |r| r.1.font_style; "PointSize": "12" => 12.0, "9" => 9.0, |r| r.1.size; "Leading": "Auto" => Leading::Auto, "14" => Leading::Points(14.0), |r| r.1.leading; @@ -554,6 +561,14 @@ fn basic_paragraph_is_normal_paragraph_style() { assert_eq!(back.styles.paragraph.iter().filter(|p| p.name == st::BASIC_PARAGRAPH).count(), 1); } +/// Like InDesign, the export carries the document's default story preference, which IDML readers expect. +#[test] +fn export_writes_the_document_story_preference() { + let d = import_idml_with(&fixture(), &|_| None).unwrap(); + let prefs = zip_text(&export_idml(&d), "Resources/Preferences.xml"); + assert!(prefs.contains(r#""#), "{prefs}"); +} + /// Page items, frames, tables and preferences an IDML file leaves unset are InDesign's defaults /// for a new document. #[test] @@ -1261,6 +1276,37 @@ fn round_trips_footnotes_and_options() { assert_eq!(back.footnote_options, d.footnote_options); } +/// IDML has no endnote structure written yet, so each endnote reference keeps its number as +/// superscript text: the place of the endnote isn't lost (#2753). +#[test] +fn exports_endnote_reference_numbers() { + let mut d = Document::new(&NewDocument::default()); + let lid = d.default_layer(); + let (_, sid) = + d.add_text_frame(SpreadRef::Doc(0), Rect::new(40.0, 40.0, 400.0, 400.0), lid, "One here, two there.", ParaFormat::default()).unwrap(); + { + let s = d.story_mut(sid).unwrap(); + s.insert_endnote(8, "First endnote.", ParaFormat::default()).unwrap(); + let at = s.text.find(" there").unwrap() + " there".len(); + s.insert_endnote(at, "Second endnote.", ParaFormat::default()).unwrap(); + } + d.endnote_options.start_at = 4; + d.endnote_options.prefix = "[".into(); + d.endnote_options.suffix = "]".into(); + d.check().unwrap(); + let bytes = export_idml(&d); + let xml = zip_text(&bytes, "Stories/"); + assert!(xml.contains("[4]"), "first reference number: {xml}"); + assert!(xml.contains("[5]"), "second reference number: {xml}"); + let back = import_idml(&bytes).unwrap(); + back.check().unwrap(); + let s = back.stories.values().find(|s| s.text.contains("One here")).unwrap(); + assert_eq!(s.text, "One here[4], two there[5]."); + let at = s.text.find("[4]").unwrap(); + assert_eq!(s.char_format_at(at + 1).over.position, Some(designcraft_doc::Position::Superscript)); + assert_eq!(s.char_format_at(0).over.position, None); +} + /// The structure InDesign writes: the footnote in its own superscript range, its text starting /// with the number marker and the separator. #[test] @@ -1291,7 +1337,7 @@ fn round_trips_cross_references() { d.add_text_frame(SpreadRef::Doc(0), Rect::new(40.0, 40.0, 400.0, 400.0), lid, "Results: found\nSee .", ParaFormat::default()).unwrap(); let target = d.paragraph_anchor(sid, 0).unwrap(); let at = d.story(sid).unwrap().text.find(" .").unwrap() + 1; - d.story_mut(sid).unwrap().insert_xref(at, designcraft_doc::CrossRef { target, format: "Paragraph Text".into() }); + d.story_mut(sid).unwrap().insert_xref(at, designcraft_doc::CrossRef { target, format: "Paragraph Text".into(), ..Default::default() }); d.xref_formats.push(designcraft_doc::XrefFormat { name: "Mine".into(), definition: "(, p. )".into(), @@ -1303,6 +1349,7 @@ fn round_trips_cross_references() { assert_eq!(s.text, d.story(sid).unwrap().text); assert_eq!(s.xrefs.len(), 1); assert_eq!(s.xrefs[0].format, "Paragraph Text"); + assert_eq!(s.xrefs[0].text, None, "generated text reads back as generated"); let (tsid, tpos) = back.find_anchor(s.xrefs[0].target).expect("target resolves"); assert_eq!((tsid, tpos), (s.id, 0)); let mine = back.xref_format("Mine").unwrap(); @@ -1348,6 +1395,426 @@ fn cross_reference_source_nesting_keeps_formatting() { assert_eq!(ga, gb); } +/// Three review findings about hyperlinks whose text is not in a story of the document. +/// +/// A table cell's and a footnote's story are built under the `StoryId(0)` placeholder, so a link +/// recorded against one names a story nothing can look up, with offsets into text that is not +/// there. Those links are dropped, and the report says where they were rather than claiming +/// their source was not a run of text. And the index's topic cross-references go in at the start +/// of the first story with text *after* the ranges were recorded, so a range in that story has +/// to move along with them or the link covers the wrong words. +#[test] +fn links_whose_text_is_not_in_a_document_story_are_dropped_and_the_rest_still_fit() { + const LINKS: &str = r#" + +