UI1994: merge main and preserve current hidden-character rendering

This commit is contained in:
Markus Reimr committed 2026-11-18 17:26:44 +01:00
commit 5d16cd0499
523 files changed
+87423 -15088

No files matched your search

+28
View File
@@ -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
+4
View File
@@ -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
+13 -39
View File
@@ -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 }}
+2
View File
@@ -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
+2 -2
View File
@@ -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
+72 -16
View File
@@ -1,15 +1,65 @@
<!-- craft-house-rules:start core source=dde09ea31e2e457f5b4653a6e76f7cdf55944bdf sha256=540e6cea75d12d0710c3dca89658328e81e508ecef102446ca5bb95b7c0b92bb -->
## 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.
<!-- craft-house-rules:end -->
<!-- craft-house-rules:start rust source=dde09ea31e2e457f5b4653a6e76f7cdf55944bdf sha256=387e0ccb4b49e567f60951d7d6fff7305054c89f43ad812b9993dc7c38528013 -->
## 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.
<!-- craft-house-rules:end -->
# 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<T, E>`** 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.<username>]` 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.
+5 -4
View File
@@ -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) |
+1 -41
View File
@@ -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<T, E>`** 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
Generated
+1220 -94
View File
File diff suppressed because it is too large. Load diff
+38 -21
View File
@@ -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" }
+103
View File
@@ -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'
+16 -9
View File
@@ -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`.
<table>
@@ -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-<ver>-macos-universal.dmg` | Signed and notarized |
| App and bundled CLI, universal (Apple silicon + Intel) | `designcraft-<ver>-macos-universal.dmg` | Signed and notarized |
| Command-line tool, universal | `designcraft-cli-<ver>-macos-universal.zip` | Signed and notarized |
### Linux
@@ -338,7 +336,16 @@ stand on its own.
| <img src="https://raw.githubusercontent.com/storytold/lightcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.lightcraft.png" alt="" width="32" height="32"> | **LightCraft** | Photo library and raw development | [GitHub](https://github.com/storytold/lightcraft) | [Website](https://getartcraft.com/apps/lightcraft) |
| <img src="https://raw.githubusercontent.com/storytold/pdfcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.pdfcraft.png" alt="" width="32" height="32"> | **PdfCraft** | Reading, organizing and protecting PDFs | [GitHub](https://github.com/storytold/pdfcraft) | [Website](https://getartcraft.com/apps/pdfcraft) |
| <img src="https://raw.githubusercontent.com/storytold/effectcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.effectcraft.png" alt="" width="32" height="32"> | **EffectCraft** | Motion graphics and visual effects | [GitHub](https://github.com/storytold/effectcraft) | [Website](https://getartcraft.com/apps/effectcraft) |
| <img src="https://raw.githubusercontent.com/storytold/designcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.designcraft.png" alt="" width="32" height="32"> | **DesignCraft** | **Page layout and publishing · you are here** | [GitHub](https://github.com/storytold/designcraft) | [Website](https://getartcraft.com/apps/designcraft) |
| <img src="https://raw.githubusercontent.com/storytold/designcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.designcraft.png" alt="" width="32" height="32"> | **DesignCraft** | Page layout and publishing | [GitHub](https://github.com/storytold/designcraft) | [Website](https://getartcraft.com/apps/designcraft) |
| <img src="https://raw.githubusercontent.com/storytold/figcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.figcraft.png" alt="" width="32" height="32"> | **FigCraft** | Interface design and prototyping | [GitHub](https://github.com/storytold/figcraft) | [Website](https://getartcraft.com/apps/figcraft) |
| <img src="https://raw.githubusercontent.com/storytold/wordcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.wordcraft.png" alt="" width="32" height="32"> | **WordCraft** | Word processing and documents | [GitHub](https://github.com/storytold/wordcraft) | [Website](https://getartcraft.com/apps/wordcraft) |
| <img src="https://raw.githubusercontent.com/storytold/soundcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.soundcraft.png" alt="" width="32" height="32"> | **SoundCraft** | Audio recording and editing | [GitHub](https://github.com/storytold/soundcraft) | [Website](https://getartcraft.com/apps/soundcraft) |
| <img src="https://raw.githubusercontent.com/storytold/deckcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.deckcraft.png" alt="" width="32" height="32"> | **DeckCraft** | Presentations and slide decks | [GitHub](https://github.com/storytold/deckcraft) | [Website](https://getartcraft.com/apps/deckcraft) |
| <img src="https://raw.githubusercontent.com/storytold/cadcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.cadcraft.png" alt="" width="32" height="32"> | **CADCraft** | Computer-aided design | [GitHub](https://github.com/storytold/cadcraft) | [Website](https://getartcraft.com/apps/cadcraft) |
| <img src="https://raw.githubusercontent.com/storytold/gridcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.gridcraft.png" alt="" width="32" height="32"> | **GridCraft** | Spreadsheets and data | [GitHub](https://github.com/storytold/gridcraft) | [Website](https://getartcraft.com/apps/gridcraft) |
| <img src="https://raw.githubusercontent.com/storytold/texturecraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.texturecraft.png" alt="" width="32" height="32"> | **TextureCraft** | 3D texture painting | [GitHub](https://github.com/storytold/texturecraft) | [Website](https://getartcraft.com/apps/texturecraft) |
| <img src="https://raw.githubusercontent.com/storytold/craft-anything/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.craft-anything.png" alt="" width="32" height="32"> | **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) |
| <img src="https://raw.githubusercontent.com/tangency-labs/solidcraft/main/assets/icons/app/linux/exports/hicolor/64x64/apps/io.tangencylabs.solidcraft.png" alt="" width="32" height="32"> | **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.
+185 -23
View File
@@ -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 `<Image FillColor>` 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.
+3
View File
@@ -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 }
+14 -2
View File
@@ -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);
+207 -26
View File
@@ -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<String, String> {
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::<f64>().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 `<sub> --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<String> = 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<String> = 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;
}
}
}
// `<sub> --help` asks about that subcommand, which every parser but `script`'s read as an
// unknown option (photocraft#423). It goes to stdout and succeeds, as `--help` does.
//
// 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::<u32>().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<u8>, size: Option<u32>) -> Result<Vec<u8>, 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<Value> = 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<Value> = 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());
+3
View File
@@ -97,6 +97,9 @@ fn row(rows: &mut Vec<Row>, name: impl Into<String>, ms: f64, budget: Option<f64
/// Measure `doc`. `runs` = repetitions per row (median).
fn measure(doc: &Document, runs: usize) -> Result<Vec<Row>, 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();
+1 -1
View File
@@ -169,7 +169,7 @@ pub fn synthetic(spec: &Spec) -> Result<Document, String> {
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()
}),
+395
View File
@@ -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<i32>,
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 `<sub> --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: `<sub> --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}");
}
}
/// `<sub> --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", "<name>"),
as_path.replace("nope.pdf", "<name>"),
"`--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<u8> {
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:?}");
}
}
+341 -1
View File
@@ -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: `<sub> --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::<Vec<_>>());
// 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:?}");
}
/// `<sub> --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"];
+1
View File
@@ -1 +1,2 @@
mod args;
mod cli;
+38 -1
View File
@@ -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<T, R, E, F, Fut>(files: impl IntoIterator<Item = T>, mut read: F) -> Result<Vec<R>, E>
where
F: FnMut(T) -> Fut,
Fut: std::future::Future<Output = Result<R, E>>,
{
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])));
}
}
+40 -11
View File
@@ -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<std::sync::Mutex<Vec<String>>>,
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();
});
})),
+14 -4
View File
@@ -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"] }
+135
View File
@@ -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<ClipboardImage> {
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<T: Send + 'static>(busy: &'static AtomicBool, wait: Duration, read: impl FnOnce() -> Option<T> + Send + 'static) -> Option<T> {
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> {
i64::try_from(objc2_app_kit::NSPasteboard::generalPasteboard().changeCount()).ok()
}
fn read_now() -> Option<ClipboardImage> {
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<ClipboardImage> {
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());
}
}
+6 -1
View File
@@ -678,7 +678,12 @@ fn restart_without<'a>(graphics_failed: bool, frames: u64, picked: Option<&'a st
/// ended it.
pub fn finish(outcome: Result<eframe::Result, String>, 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)),
+20 -2
View File
@@ -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");
+31 -9
View File
@@ -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(_)));
}
}
+20 -3
View File
@@ -121,10 +121,22 @@ pub fn rotate(dir: &Path) -> std::io::Result<(PathBuf, File)> {
Ok((path, file))
}
/// One formatted log line: `<timestamp> <LEVEL> [<thread>] <target>: <message>\n`.
/// One formatted log line: `<timestamp> <LEVEL> [<thread>] <target>: <message>\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]
+22 -4
View File
@@ -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<String>) -> Option<u16> {
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::<Vec<_>>()) {
if let Some(result) = craft_update::self_update::finish(&designcraft_ui_egui::UPDATE_APP, &std::env::args_os().skip(1).collect::<Vec<_>>()) {
std::process::exit(i32::from(result.is_err()));
}
// First, so every start-up record (and the engine's panic hook, installed with the first
@@ -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);
+7 -4
View File
@@ -41,9 +41,10 @@ struct RecentMenu {
separator: Option<PredefinedMenuItem>,
}
/// 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<Accelerator> {
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<Submenu>,
) {
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);
+43
View File
@@ -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<egui::Pos2> {
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<egui::Pos2> {
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);
}
}
+352
View File
@@ -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<WindowFrameFn> {
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<HWND> {
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<i32>, work: Option<i32>| 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<Edge> {
let mut edges = Vec::new();
for class in ["Shell_TrayWnd", "Shell_SecondaryTrayWnd"] {
let mut after: Option<HWND> = 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<Edge> {
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<Rect> {
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<WindowFrameFn> {
None
}
}
+2 -4
View File
@@ -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
+28 -5
View File
@@ -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"
+10 -1
View File
@@ -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]);
+106 -18
View File
@@ -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<f32> {
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<GradientStop> = 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<f32> = 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();
+8
View File
@@ -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();
+35 -13
View File
@@ -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<Swatch> {
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<Swatch> {
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<Swatch> {
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<String> = 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();
+1 -1
View File
@@ -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"] }
+64 -25
View File
@@ -53,8 +53,12 @@ pub struct Spacing {
pub optical_size: Option<f64>,
/// 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<Vec<Break>> {
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::<f64>() + 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::<f64>();
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));
+134 -16
View File
@@ -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<Option<usize>> 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<ComposedStory>>;
struct Entry {
sig: Vec<usize>,
_keep: (Arc<Story>, Arc<Styles>, Vec<Arc<Item>>, Vec<Arc<Story>>),
out: Arc<ComposedStory>,
stamp: u64,
/// For composing the story again after an edit ([`crate::reuse`]).
trace: Option<Arc<Trace>>,
}
/// The story an entry was composed from, its composition and that composition's trace.
type Before = (Arc<Story>, Arc<ComposedStory>, Arc<Trace>);
/// 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<Before> {
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<HashMap<StoryId, (Vec<usize>, Arc<ComposedStory>)>>,
/// 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<Arc<Cache>>,
}
/// 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<Cache>) -> Self {
Cache { base: Some(base), ..Self::default() }
}
/// The cache given to [`Cache::over`].
pub fn base(&self) -> Option<&Arc<Cache>> {
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<ComposedStory> {
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<ComposedStory> {
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<crate::Placement> {
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<ComposedStory> {
fn get_with(&self, doc: &Document, sid: StoryId, on: ShownOn, cross: bool, depth: usize, resolved: &mut Resolved) -> Arc<ComposedStory> {
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<Arc<ComposedStory>> = neighbours.iter().map(|n| self.neighbour(doc, *n, depth)).collect();
let out = Arc::new(crate::wrap::compose_among(
let others: Vec<Arc<ComposedStory>> = 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::<Vec<_>>(),
));
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<ComposedStory> {
fn neighbour(&self, doc: &Document, sid: StoryId, depth: usize, resolved: &mut Resolved) -> Arc<ComposedStory> {
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<Story>) -> (Vec<usize>, Vec<Arc<Item>>)
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();
+125 -15
View File
@@ -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<name>`, `\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<Vec<Range<usize>>, 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<Option<(Range<usize>, 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<Vec<(Range<usize>, 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<Range<usize>>, 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<usize>) -> bool,
) -> Result<Vec<(Range<usize>, 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<u8>,
left: usize,
}
impl std::io::Write for BoundedBuf {
fn write(&mut self, data: &[u8]) -> std::io::Result<usize> {
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"(?<x>a\g<x>\g<x>)", r"(?<x>a|b\g<x>)", 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"(?<x>a)\k<x>", "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]
+547 -8
View File
@@ -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<usize>, 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<usize>, 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<Item = char>) -> 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<Item = (usize, char, bool)>) -> bool {
let mut chars: Vec<char> = Vec::new();
let mut last: Option<usize> = 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<usize> {
@@ -211,6 +368,7 @@ pub fn hyphen_points_in(word: &str, lim: &Limits, lang: Lang) -> Vec<usize> {
}
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<usize> {
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<usize> {
return vec![];
}
let v: Vec<bool> = 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::<Vec<char>>());
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<usize> {
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<usize> {
#[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::<String>()
};
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<char> = "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<usize> {
let n = c.len();
if n < 4 || !c.iter().all(|c| c.is_alphabetic()) {
return vec![];
}
let v: Vec<bool> = 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<char> = 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<char> = "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<char> = 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<char> = {
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");
}
}
+18 -2
View File
@@ -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<Dictionary, String> {
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<u8> = 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}");
}
}
+1
View File
@@ -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,
+1412 -183
View File
File diff suppressed because it is too large. Load diff
+5 -2
View File
@@ -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<usize> {
let mut v: Vec<usize> = 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,
+21
View File
@@ -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<FrameOutline> {
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<f64> {
let mut ys: Vec<f64> = 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
+34 -9
View File
@@ -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<R>(pattern: &str, f: impl FnOnce(&mut Option<Grep>) -> R) -> R {
})
}
fn is_event(u: &NestedUntil, c: char, prev: Option<char>, next: Option<char>) -> 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<char>, c: char, prev: Option<char>, next: Option<char>) -> 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<char>, next: Option<char>) ->
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<usize>, 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<char> = 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<usize>, 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();
+156 -12
View File
@@ -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<f64> = pattern.iter().copied().filter(|v| v.is_finite() && *v >= 0.0).collect();
Some(if p.iter().sum::<f64>() > 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<BezPath> {
use kurbo::{ParamCurve, ParamCurveArclen, PathEl, PathSeg};
// Subpaths as (segments, closed).
let mut subs: Vec<(Vec<PathSeg>, 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<f64> = 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<kurbo::Point> {
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<f64> = 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<f64> = 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<f64> = 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<f64> = xs.windows(2).map(|p| p[1] - p[0]).collect();
assert_even(&gaps, l / n as f64);
}
}
}
+33 -11
View File
@@ -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<ComposedStory>) -> Vec<(ItemId, Placement)> {
let Some(st) = doc.story(sid) else { return Vec::new() };
let mut anchored = None;
let mut hosts: HashMap<StoryId, Arc<ComposedStory>> = 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<Placement> {
/// 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<StoryId, Arc<ComposedStory>>,
host: &mut dyn FnMut(StoryId) -> Arc<ComposedStory>,
depth: usize,
) -> Option<Placement> {
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 })
})
}
+738
View File
@@ -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<usize> = 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<f64>,
last_descent: f64,
last_reference: f64,
aki_below: Option<f64>,
pending: f64,
band: Band,
grid_next: Option<(f64, f64)>,
list_counter: ListCounter,
lines: usize,
decos: usize,
styles: usize,
}
fn bits(v: Option<f64>) -> Option<u64> {
v.map(f64::to_bits)
}
fn above_bits(a: Option<Above>) -> Option<[Option<u64>; 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<Mark> {
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<Mark>,
info: Vec<ParaInfo>,
}
/// 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<usize> {
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<String>], 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<T>(span: &[bool], split: &[bool], boxes: &[Option<T>]) -> 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<Item = &'a CharRun>, mut new: impl Iterator<Item = &'a CharRun>) -> 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<Plan> {
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<RunStyle>) -> Option<(Cursor, ListCounter, Vec<ParaInfo>)> {
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<RunStyle>,
info: &mut Vec<ParaInfo>,
) -> 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<usize>,
/// 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<usize>,
}
/// 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<ParaInfo>,
}
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<RunStyle>,
) -> (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<RunStyle>,
info: &mut Vec<ParaInfo>,
) -> 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<ParaInfo>) -> Option<Option<Trace>> {
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<Vec<Mark>> {
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<ItemId>) {
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::<Vec<_>>().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<T>(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<usize> =
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}"));
}
}
}
+1
View File
@@ -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,
+133 -11
View File
@@ -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<bool> {
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<usize> = 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<FontFace>)> = 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<bool>) -> 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<usize>, String)]) -> Vec<(usize, Option<usize>)> {
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<usize> = 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<usize>, 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<usize>, 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");
}
}
+57 -6
View File
@@ -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<designcraft_doc::Graphic>,
/// The cell's diagonal lines (Cell Options › Diagonal Lines), corner to corner of `rect`.
pub diagonals: Vec<StrokeSeg>,
/// 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<PlacedCell>,
/// 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<StrokeSeg>,
/// 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<f64> = 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<Rect>],
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<usize, f64> = 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,
+36
View File
@@ -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);
File diff suppressed because it is too large. Load diff
+40 -6
View File
@@ -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<Hit>) -> 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<Hit>> = 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<usize, (String, String)> = 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<usize>, running: Option<&RunningIndex>) -> Vec<String> {
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, `<Name>`, as InDesign
/// does. Elsewhere without a page (the pasteboard), it is its text before and after.
pub fn values_shown(doc: &Document, page: Option<usize>, parent: bool, running: Option<&RunningIndex>) -> Vec<String> {
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),
+79 -1
View File
@@ -108,6 +108,11 @@ fn trace_counts(take: &[Vec<usize>], n: usize, m: usize) -> Option<Vec<usize>> {
(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<usize> {
@@ -121,6 +126,9 @@ fn split_even(advs: &[f64], n: usize, before: usize, after: usize) -> Vec<usize>
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<usize>
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<usize> {
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::<usize>(), 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::<usize>(), 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]);
}
}
+46 -13
View File
@@ -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<usize>,
/// Baseline of the line holding the anchor, for obstacles in their own story.
anchor_baseline: Option<f64>,
}
/// 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<Exclusion>], b: &[Vec<Exclusion>]) -> 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<Reuse<'_>>,
) -> (ComposedStory, Option<Trace>) {
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)
}
+23 -2
View File
@@ -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("<fullPara />", |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<usize>, index: Option<&XrefIndex>) -> HashMap<usize, String> {
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<usize>,
before: usize,
index: Option<&XrefIndex>,
) -> HashMap<usize, String> {
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));
+682
View File
@@ -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<StoryId, Arc<Story>> {
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<Arc<Story>>) {
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<Arc<Story>>,
assets: Option<&Document>,
path: &mut Vec<StoryId>,
copies: &mut HashMap<StoryId, StoryId>,
) {
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<ItemId, StoryId> = HashMap::new();
let mut empty: HashMap<StoryId, StoryId> = 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(&copy) {
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<ItemId> {
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<StoryId> = 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<StoryId> =
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(&copy);
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(&copy);
assert_eq!(stories.len(), 2 * LAYERS);
let before: HashSet<StoryId> = d.stories.keys().copied().collect();
d.adopt_anchored(&mut copy, &|id| stories.get(&id).cloned());
let added: Vec<StoryId> = 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<usize> = 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, &copy);
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::<HashSet<_>>().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, &copy);
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<String> = 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<String> = 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");
}
}
+6 -1
View File
@@ -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();
+411
View File
@@ -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<String>,
/// The document file `relative` is resolved against.
pub document: Option<PathBuf>,
/// 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<Fingerprint>,
/// The bytes' content hash ([`crate::Asset::link_hash`], `sha256:` and hex digits), checked
/// when the file's fingerprint differs.
pub hash: Option<String>,
}
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<Self> {
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<Option<Fingerprint>>,
}
impl Linked {
fn trusted(&self) -> Option<Fingerprint> {
*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<Vec<u8>>),
Linked(Arc<Linked>),
}
/// 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<Arc<Vec<u8>>>) -> 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<Arc<Vec<u8>>>) -> 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<Vec<u8>>> {
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<Arc<Vec<u8>>, 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<Vec<u8>>, 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<Arc<Vec<u8>>> {
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<Vec<u8>>) {
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<Vec<u8>>),
Linked(Arc<Linked>),
}
/// [`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<AssetData> {
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<Vec<u8>> for AssetData {
fn from(bytes: Vec<u8>) -> 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");
}
}
+370
View File
@@ -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<u8>,
/// 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<Fingerprint>,
}
/// 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<Fingerprint>) -> Result<Loaded, Unavailable>;
/// 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<Vec<u8>, 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<Fingerprint>, _kept: &[u8]) -> Result<Option<Fingerprint>, Unavailable> {
Ok(None)
}
}
static LOADER: RwLock<Option<Arc<dyn Loader>>> = RwLock::new(None);
/// Read linked files with `loader` from now on (in the whole process).
pub fn install_loader(loader: Arc<dyn Loader>) {
*LOADER.write().unwrap_or_else(PoisonError::into_inner) = Some(loader);
}
pub(super) fn installed() -> Option<Arc<dyn Loader>> {
LOADER.read().unwrap_or_else(PoisonError::into_inner).clone()
}
pub(super) fn global() -> &'static Store {
static STORE: LazyLock<Store> = LazyLock::new(|| Store::new(STORE_BUDGET, MAX_LINKED_BYTES));
&STORE
}
type Outcome = Result<Arc<Vec<u8>>, Unavailable>;
/// One load in progress, which the other loads of the same bytes wait for.
#[derive(Default)]
struct Flight {
outcome: Mutex<Option<Outcome>>,
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<Vec<u8>>,
stamp: u64,
}
#[derive(Default)]
struct Inner {
kept: HashMap<SourceKey, Kept>,
flights: HashMap<SourceKey, Arc<Flight>>,
bytes: u64,
clock: u64,
}
impl Inner {
/// The bytes kept under `key`, marked used.
fn touch(&mut self, key: SourceKey) -> Option<Arc<Vec<u8>>> {
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<Vec<u8>>, 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<Inner>,
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<Flight>,
outcome: Option<Outcome>,
}
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<Arc<Vec<u8>>> {
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<Vec<u8>>) {
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<Unavailable>,
trusted: Mutex<Vec<Option<Fingerprint>>>,
}
impl Loader for Counting {
fn load(&self, source: &LinkedSource, trusted: Option<Fingerprint>) -> Result<Loaded, Unavailable> {
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<Outcome> = 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<Outcome> = 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<Fingerprint>) -> Result<Loaded, Unavailable> {
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()));
});
}
}
+141 -8
View File
@@ -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<String>, loaded: Option<Fingerprint>) {
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<AssetId, Arc<Asset>>, 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<AssetId, Arc<Asset>>, 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<String>), Vec<AssetId>>,
/// One asset per distinct non-empty byte content, for buffer sharing.
bytes: HashMap<u64, Vec<AssetId>>,
}
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<AssetId, Arc<Asset>>, 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::<Vec<_>>(), indexed.keys().collect::<Vec<_>>());
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]
+8 -8
View File
@@ -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<f64> = None,
kenten_size: Option<f64> = 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<f32> = None,
kenten_fill_tint: Option<f32> = None => "deserialize_explicit_value",
kenten_stroke: String = String::new(),
kenten_stroke_tint: Option<f32> = None,
kenten_stroke_weight: Option<f64> = None,
kenten_stroke_tint: Option<f32> = None => "deserialize_explicit_value",
kenten_stroke_weight: Option<f64> = 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<f64> = None,
ruby_font_size: Option<f64> = 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<f32> = None,
ruby_fill_tint: Option<f32> = None => "deserialize_explicit_value",
ruby_stroke: String = String::new(),
ruby_stroke_tint: Option<f32> = None,
ruby_stroke_weight: Option<f64> = None,
ruby_stroke_tint: Option<f32> = None => "deserialize_explicit_value",
ruby_stroke_weight: Option<f64> = 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.
+1
View File
@@ -88,6 +88,7 @@ pub fn language_tag(language: &str) -> Option<&'static str> {
"urdu" => "ur",
"hebrew" => "he",
"georgian" => "ka",
"esperanto" => "eo",
_ => return None,
})
}
+16 -3
View File
@@ -113,7 +113,10 @@ attr_set! {
kinsoku: Option<crate::cjk::Kinsoku> = 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<f64> = None,
list_tab: Option<f64> = 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());
+36 -1
View File
@@ -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,
}
}
}
+2
View File
@@ -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);
+188 -19
View File
@@ -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<bool> = (0..self.page_count()).map(|i| self.page_number(i) % 2 == 1).collect();
let odd: Vec<bool> = 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<usize> = self.sections.iter().filter(|s| s.layout.is_some() && s.start > 0).map(|s| s.start).collect();
let mut breaks: Vec<bool> = Vec::new();
// Collect pages with their items (items in page-relative coordinates) and their numbers' parity.
let mut pages: Vec<(Page, Vec<Arc<Item>>)> = Vec::new();
let mut parity: Vec<bool> = 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<ItemId> = 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<usize> = 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<ItemId> {
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<String> {
// 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<Option<&str>> = 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<Section>, left: usize) -> Vec<Section> {
let mut kept: Vec<Section> = 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<SpreadId> = 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);
}
}
+241 -2
View File
@@ -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<ItemId>,
/// Items starting at `z` that resize when the gap moves.
pub after: Vec<ItemId>,
}
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<ItemId> {
let sp = self.spread(sr)?;
let mut items: Vec<&Arc<Item>> = 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<Gap> {
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<ItemId> = items.iter().filter(|(_, b)| across(b) && (end(b) - a).abs() < 0.5).map(|(i, _)| *i).collect();
let after: Vec<ItemId> = 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<ItemId> {
@@ -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<usize>, 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<usize>, 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<usize>, 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());
+5 -1
View File
@@ -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 }));
+29 -2
View File
@@ -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::<DropShadow>(saved).unwrap().mode, BlendMode::Screen, "round trip");
}
#[test]
fn graphics_without_a_clipping_path_load_and_save_as_before() {
let g = Graphic {
+21 -1
View File
@@ -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)?;
+90 -2
View File
@@ -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<PathData>,
/// 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 {
+414 -12
View File
@@ -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<std::ops::Range<usize>> {
let mut out: Vec<std::ops::Range<usize>> = Vec::new();
let runs: Vec<(std::ops::Range<usize>, &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<usize>], range: std::ops::Range<usize>) -> 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<String>,
/// 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<Fingerprint>,
/// `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<String>,
/// The linked file's content hash (`sha256:` and hex digits).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub link_hash: Option<String>,
/// 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<Proxy>,
#[serde(skip)]
pub data: Arc<Vec<u8>>,
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<Vec<u8>>,
/// A warning to report: the file on disk replaced a changed original, or the proxy stands in
/// for a missing one.
pub warning: Option<String>,
/// 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<OutputBytes, Unavailable> {
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<Section>,
#[serde(default)]
pub assets: BTreeMap<AssetId, Arc<Asset>>,
/// 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<Arc<AlphaOutline>>,
/// Hyperlinks (Window → Interactive → Hyperlinks).
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub hyperlinks: Vec<Hyperlink>,
@@ -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<String>,
/// 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<Bookmark>,
/// 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<LayoutRange> {
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<LayoutRange> = 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<u32> {
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<u32>, 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<ItemId>> = 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<ItemId, Option<StoryId>> = 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<ItemId, Option<StoryId>> = 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<StoryId, Vec<StoryId>> = 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);
+58
View File
@@ -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();
+5 -1
View File
@@ -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 }));
+53 -2
View File
@@ -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<Rect> = 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<usize> {
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<usize> {
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<String>,
}
#[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]
+4 -1
View File
@@ -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<usize>,
/// 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")]
+121 -9
View File
@@ -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<usize>) -> Vec<(usize, std::ops::Range<usize>)> {
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<usize>)> =
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::<usize>(), 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);
}
}
+87 -5
View File
@@ -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<Stroke>,
#[serde(skip_serializing_if = "Option::is_none")]
pub paragraph_style: Option<String>,
/// 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<TextFrameOptions>,
/// 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<Effects>,
/// 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<CornerOptions>,
}
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<Vec<String>> {
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
+12 -5
View File
@@ -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;
+112 -1
View File
@@ -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 `<Table>` with 5,000 `<Row/>` and 5,000 `<Column/>` -- 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::<Cell>() > 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, &para, &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:?}");
}
}
}
+53
View File
@@ -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<crate::Graphic>,
/// 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(),
}
}
}
+5 -7
View File
@@ -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(&regions);
}
+22 -6
View File
@@ -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<String>], 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', " "));
+20
View File
@@ -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);
+285
View File
@@ -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::<Vec<_>>(), [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::<Vec<_>>());
d.sections = vec![sec(3, None)];
assert_eq!(d.page_numbers(6), (0..6).map(|i| d.page_number(i)).collect::<Vec<_>>());
// 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<u64> = st.notes.iter().map(|x| x.id).collect();
assert_eq!(ids.len(), n);
let ids: std::collections::HashSet<u64> = 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));
}
+35 -2
View File
@@ -175,6 +175,9 @@ pub fn parse_iso_date(s: &str) -> Option<i64> {
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<i64> {
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<i64> { 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));
+89 -6
View File
@@ -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 `<pageNum />` shows the destination's page.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub text: Option<String>,
/// The page last shown (for edited text whose destination is gone).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub page: Option<String>,
}
/// The `<pageNum />` building block, as it appears in [`CrossRef::text`].
pub const PAGE_NUM_BLOCK: &str = "<pageNum />";
/// 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<usize> {
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<String> {
let mut v = self.xref_values(target)?;
v.page = PAGE_NUM_BLOCK.into();
Some(expand(self.xref_format(format).map_or("<fullPara />", |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("<partialPara delim=\">\" includeDelim=\"false\" />|", &v), "Intro |");
}
#[test]
fn unterminated_lt_still_gets_typographic_quotes() {
let v = XrefValues { para: "Intro".into(), ..Default::default() };
assert_eq!(expand("\"<paraText />\" <", &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("<x a=\"b> <fullPara />", &v);
assert!(out.contains("Intro > the start"), "{out}");
}
#[test]
fn edited_text_fills_in_its_page_numbers() {
assert_eq!(expand_edited("p. <pageNum /> and <pageNum />", "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 ");
+18
View File
@@ -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");
}
@@ -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:?}");
}
+13 -2
View File
@@ -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 }
+322
View File
@@ -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<Fingerprint>) -> Result<Loaded, Unavailable> {
read_linked(source, trusted)
}
fn load_current(&self, source: &LinkedSource) -> Result<Vec<u8>, Unavailable> {
read_current(source)
}
fn holds(&self, source: &LinkedSource, trusted: Option<Fingerprint>, kept: &[u8]) -> Result<Option<Fingerprint>, 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<Fingerprint>, kept: &[u8]) -> Result<Option<Fingerprint>, 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<Vec<u8>, 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<PathBuf> {
let document = source.document.as_deref();
let mut out: Vec<PathBuf> = 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<Fingerprint>) -> Result<Loaded, Unavailable> {
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<Fingerprint>) -> Result<Loaded, Miss> {
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));
}
}
+37
View File
@@ -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<String>) -> 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<std::sync::Arc<Vec<u8>>> {
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<Vec<ItemId>
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<Option<u64>> {
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<Option<u64>> {
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<Vec<ItemId>> {
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;
+598
View File
@@ -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<AlphaOutline> {
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<AlphaOutline> {
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<bool>, 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::<usize>() <= 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<Vec<bool>> {
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<bool> {
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<(i32, i32)>>, Vec<Vec<(i32, i32)>>)> {
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<u8> {
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<u8> {
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());
}
}
}
Loaded 100 of 523 files, more files were not shown because too many files have changed in this diff. Show more