diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index d8eabea47..29b2c0c98 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -28,53 +28,9 @@ jobs: contents: read pull-requests: read uses: storytold/craft-common-actions/.github/workflows/refresh-contributors.yml@main - git-sources: - name: Git dependencies come from storytold - runs-on: ubuntu-latest - permissions: - contents: read - steps: - - name: Harden runner - uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 - with: - egress-policy: audit - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - persist-credentials: false - - name: 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 release: - needs: [git-sources, credits] + needs: credits permissions: contents: write packages: write diff --git a/.github/workflows/sonarcloud.yml b/.github/workflows/sonarcloud.yml index e78fe1ea3..c5731a0ae 100644 --- a/.github/workflows/sonarcloud.yml +++ b/.github/workflows/sonarcloud.yml @@ -18,4 +18,6 @@ jobs: sonarcloud: # Tracked at @main so org-wide CI improvements propagate without PR churn. uses: storytold/craft-common-actions/.github/workflows/sonarcloud.yml@main + with: + fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83 secrets: inherit diff --git a/Cargo.lock b/Cargo.lock index 549a9a728..823dba8aa 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -256,7 +256,7 @@ dependencies = [ "objc2-foundation 0.3.2", "parking_lot", "percent-encoding", - "windows-sys 0.59.0", + "windows-sys 0.52.0", "wl-clipboard-rs", "x11rb", ] @@ -1118,10 +1118,10 @@ dependencies = [ [[package]] name = "craft-designcraft-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=93d0998383aa150fa50a2ffbf49ef37786e37eca#93d0998383aa150fa50a2ffbf49ef37786e37eca" +source = "git+https://github.com/storytold/craft-libs?rev=b1b4602a71d19e09ad33f7752a10d6598cf39b2b#b1b4602a71d19e09ad33f7752a10d6598cf39b2b" dependencies = [ "craft-document-bundle", - "craft-eps 0.1.0 (git+https://github.com/storytold/craft-libs?rev=93d0998383aa150fa50a2ffbf49ef37786e37eca)", + "craft-eps 0.1.0 (git+https://github.com/storytold/craft-libs?rev=b1b4602a71d19e09ad33f7752a10d6598cf39b2b)", "serde", "serde_json", "thiserror 2.0.21", @@ -1148,9 +1148,9 @@ source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13af [[package]] name = "craft-document-bundle" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=93d0998383aa150fa50a2ffbf49ef37786e37eca#93d0998383aa150fa50a2ffbf49ef37786e37eca" +source = "git+https://github.com/storytold/craft-libs?rev=b1b4602a71d19e09ad33f7752a10d6598cf39b2b#b1b4602a71d19e09ad33f7752a10d6598cf39b2b" dependencies = [ - "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=93d0998383aa150fa50a2ffbf49ef37786e37eca)", + "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=b1b4602a71d19e09ad33f7752a10d6598cf39b2b)", "serde_json", "thiserror 2.0.21", "zip 9.1.1", @@ -1212,12 +1212,12 @@ dependencies = [ [[package]] name = "craft-eps" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=93d0998383aa150fa50a2ffbf49ef37786e37eca#93d0998383aa150fa50a2ffbf49ef37786e37eca" +source = "git+https://github.com/storytold/craft-libs?rev=b1b4602a71d19e09ad33f7752a10d6598cf39b2b#b1b4602a71d19e09ad33f7752a10d6598cf39b2b" [[package]] name = "craft-eps" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=ba24fe2435adb3c81ad6057faf36365fbba736cf#ba24fe2435adb3c81ad6057faf36365fbba736cf" +source = "git+https://github.com/storytold/craft-libs?rev=ba24fe2435adb3c81ad6057faf36365fbba736cf#6d0b33c0cd63ae4250c180a04eb4a4d66ab81448" [[package]] name = "craft-eps" @@ -1227,7 +1227,7 @@ source = "git+https://github.com/storytold/craft-libs?rev=eed3c28cf016723d004d6f [[package]] name = "craft-epub" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=ba24fe2435adb3c81ad6057faf36365fbba736cf#ba24fe2435adb3c81ad6057faf36365fbba736cf" +source = "git+https://github.com/storytold/craft-libs?rev=ba24fe2435adb3c81ad6057faf36365fbba736cf#6d0b33c0cd63ae4250c180a04eb4a4d66ab81448" dependencies = [ "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba24fe2435adb3c81ad6057faf36365fbba736cf)", "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba24fe2435adb3c81ad6057faf36365fbba736cf)", @@ -1762,7 +1762,7 @@ dependencies = [ [[package]] name = "craft-xml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=ba24fe2435adb3c81ad6057faf36365fbba736cf#ba24fe2435adb3c81ad6057faf36365fbba736cf" +source = "git+https://github.com/storytold/craft-libs?rev=ba24fe2435adb3c81ad6057faf36365fbba736cf#6d0b33c0cd63ae4250c180a04eb4a4d66ab81448" dependencies = [ "quick-xml 0.41.0", "thiserror 2.0.21", @@ -1848,7 +1848,7 @@ dependencies = [ [[package]] name = "craft-zip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=93d0998383aa150fa50a2ffbf49ef37786e37eca#93d0998383aa150fa50a2ffbf49ef37786e37eca" +source = "git+https://github.com/storytold/craft-libs?rev=b1b4602a71d19e09ad33f7752a10d6598cf39b2b#b1b4602a71d19e09ad33f7752a10d6598cf39b2b" dependencies = [ "flate2", "thiserror 2.0.21", @@ -1858,7 +1858,7 @@ dependencies = [ [[package]] name = "craft-zip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=ba24fe2435adb3c81ad6057faf36365fbba736cf#ba24fe2435adb3c81ad6057faf36365fbba736cf" +source = "git+https://github.com/storytold/craft-libs?rev=ba24fe2435adb3c81ad6057faf36365fbba736cf#6d0b33c0cd63ae4250c180a04eb4a4d66ab81448" dependencies = [ "flate2", "thiserror 2.0.21", @@ -2029,7 +2029,7 @@ dependencies = [ [[package]] name = "designcraft" -version = "0.20.1" +version = "0.21.0" dependencies = [ "arboard", "craft-update", @@ -2054,7 +2054,7 @@ dependencies = [ [[package]] name = "designcraft-cli" -version = "0.20.1" +version = "0.21.0" dependencies = [ "craft-file-formats", "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=bfea7d9800a9f14e496209f9df30e9ef45655701)", @@ -2073,7 +2073,7 @@ dependencies = [ [[package]] name = "designcraft-color" -version = "0.20.1" +version = "0.21.0" dependencies = [ "craft-cms", "kurbo", @@ -2085,7 +2085,7 @@ dependencies = [ [[package]] name = "designcraft-compose" -version = "0.20.1" +version = "0.21.0" dependencies = [ "designcraft-color", "designcraft-doc", @@ -2105,7 +2105,7 @@ dependencies = [ [[package]] name = "designcraft-doc" -version = "0.20.1" +version = "0.21.0" dependencies = [ "chrono", "designcraft-color", @@ -2118,7 +2118,7 @@ dependencies = [ [[package]] name = "designcraft-engine" -version = "0.20.1" +version = "0.21.0" dependencies = [ "caseless", "craft-atomic", @@ -2153,6 +2153,7 @@ dependencies = [ "same-file", "serde", "serde_json", + "sha2 0.10.9", "tempfile", "thiserror 2.0.21", "unicode-segmentation", @@ -2162,7 +2163,7 @@ dependencies = [ [[package]] name = "designcraft-epub" -version = "0.20.1" +version = "0.21.0" dependencies = [ "craft-epub", "designcraft-color", @@ -2172,7 +2173,7 @@ dependencies = [ [[package]] name = "designcraft-fonts" -version = "0.20.1" +version = "0.21.0" dependencies = [ "core-text", "harfrust 0.13.3", @@ -2185,7 +2186,7 @@ dependencies = [ [[package]] name = "designcraft-format" -version = "0.20.1" +version = "0.21.0" dependencies = [ "craft-designcraft-format", "designcraft-doc", @@ -2195,7 +2196,7 @@ dependencies = [ [[package]] name = "designcraft-geom" -version = "0.20.1" +version = "0.21.0" dependencies = [ "flo_curves", "kurbo", @@ -2208,7 +2209,7 @@ dependencies = [ [[package]] name = "designcraft-idml" -version = "0.20.1" +version = "0.21.0" dependencies = [ "craft-file-formats", "craft-idml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=899e396b9e2710fcdf1ad9b6249d6c456b7ca9a2)", @@ -2226,7 +2227,7 @@ dependencies = [ [[package]] name = "designcraft-images" -version = "0.20.1" +version = "0.21.0" dependencies = [ "craft-cms", "craft-eps 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba24fe2435adb3c81ad6057faf36365fbba736cf)", @@ -2238,6 +2239,7 @@ dependencies = [ "designcraft-fonts", "flate2", "image", + "jpeg-decoder", "log", "quick-xml 0.41.0", "skrifa 0.47.0", @@ -2246,7 +2248,7 @@ dependencies = [ [[package]] name = "designcraft-mcp" -version = "0.20.1" +version = "0.21.0" dependencies = [ "craft-file-formats", "designcraft-engine", @@ -2260,7 +2262,7 @@ dependencies = [ [[package]] name = "designcraft-pdf" -version = "0.20.1" +version = "0.21.0" dependencies = [ "chrono", "craft-cms", @@ -2286,7 +2288,7 @@ dependencies = [ [[package]] name = "designcraft-pptx" -version = "0.20.1" +version = "0.21.0" dependencies = [ "chrono", "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=bfea7d9800a9f14e496209f9df30e9ef45655701)", @@ -2307,8 +2309,9 @@ dependencies = [ [[package]] name = "designcraft-render" -version = "0.20.1" +version = "0.21.0" dependencies = [ + "bytemuck", "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=bfea7d9800a9f14e496209f9df30e9ef45655701)", "craft-pdf", "designcraft-color", @@ -2327,7 +2330,7 @@ dependencies = [ [[package]] name = "designcraft-textimport" -version = "0.20.1" +version = "0.21.0" dependencies = [ "craft-docx", "craft-file-formats", @@ -2341,7 +2344,7 @@ dependencies = [ [[package]] name = "designcraft-tools" -version = "0.20.1" +version = "0.21.0" dependencies = [ "designcraft-color", "designcraft-compose", @@ -2353,7 +2356,7 @@ dependencies = [ [[package]] name = "designcraft-ui-egui" -version = "0.20.1" +version = "0.21.0" dependencies = [ "craft-dialogs", "craft-file-formats", @@ -2388,7 +2391,7 @@ dependencies = [ [[package]] name = "designcraft-web" -version = "0.20.1" +version = "0.21.0" dependencies = [ "designcraft-engine", "designcraft-format", @@ -2778,7 +2781,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys 0.59.0", + "windows-sys 0.52.0", ] [[package]] @@ -4122,6 +4125,12 @@ dependencies = [ "libc", ] +[[package]] +name = "jpeg-decoder" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00810f1d8b74be64b13dbf3db89ac67740615d6c891f0e7b6179326533011a07" + [[package]] name = "jpeg-encoder" version = "0.6.1" @@ -5009,7 +5018,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967" dependencies = [ "libc", - "windows-sys 0.59.0", + "windows-sys 0.52.0", ] [[package]] @@ -5571,7 +5580,7 @@ dependencies = [ "once_cell", "socket2", "tracing", - "windows-sys 0.59.0", + "windows-sys 0.52.0", ] [[package]] @@ -5978,7 +5987,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys 0.12.1", - "windows-sys 0.59.0", + "windows-sys 0.52.0", ] [[package]] @@ -6037,7 +6046,7 @@ dependencies = [ "security-framework", "security-framework-sys", "webpki-root-certs", - "windows-sys 0.59.0", + "windows-sys 0.52.0", ] [[package]] @@ -6892,7 +6901,7 @@ dependencies = [ "getrandom 0.3.4", "once_cell", "rustix 1.1.5", - "windows-sys 0.59.0", + "windows-sys 0.52.0", ] [[package]] @@ -8131,7 +8140,7 @@ version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys 0.59.0", + "windows-sys 0.52.0", ] [[package]] @@ -8623,7 +8632,7 @@ checksum = "9440ea3e5aeabb0ac63af70daf835274065238cdd0cec83418f417eae38bacee" [[package]] name = "xtask" -version = "0.20.1" +version = "0.21.0" dependencies = [ "serde_json", ] diff --git a/Cargo.toml b/Cargo.toml index d56da61c2..ca4e86d21 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,7 +4,7 @@ members = ["crates/*", "apps/*", "xtask"] default-members = ["crates/*", "apps/designcraft", "apps/designcraft-cli", "xtask"] [workspace.package] -version = "0.20.1" +version = "0.21.0" edition = "2024" license = "MIT OR Apache-2.0" rust-version = "1.95" @@ -13,7 +13,7 @@ repository = "https://github.com/storytold/designcraft" [workspace.dependencies] # Shared reader and writer; publish the immutable revision before this consumer. craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "40525913633942f84b06d4837a8d90534a55d63f", version = "=0.1.0", default-features = false } -craft-designcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "93d0998383aa150fa50a2ffbf49ef37786e37eca", version = "=0.1.0" } +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" } @@ -82,6 +82,8 @@ skrifa = "0.47" harfrust = "0.13" vello_cpu = "0.2" vello_common = { version = "0.2", default-features = false } +# 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" diff --git a/ROADMAP.md b/ROADMAP.md index 006396b1d..50b299e8f 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -4,7 +4,7 @@ - 2026-10-23: placed-artwork layer options survive IDML and native round trips per placement, independently of shared assets. Unsupported visibility overrides are explicit import/preflight/PDF warnings; format 4 prevents older native readers from silently discarding them. Rendering parity is still open; see [graphic-layer-options.md](docs/graphic-layer-options.md). - FID1: PDF export normalizes mixed emitted gradient color spaces to RGB with an explicit warning; homogeneous device-space gradients retain their components. Linear/radial, midpoint, archival and print policies have synthetic regression coverage. -> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-11-04 · **Change:** minor (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) · **Target:** Adobe InDesign 2026 +> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-11-06 · **Change:** minor (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. @@ -12,7 +12,15 @@ 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 @@ -57,7 +65,7 @@ DesignCraft aims at full Adobe InDesign parity — and to be better: faster, ope - 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. @@ -68,7 +76,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. @@ -103,7 +111,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. @@ -387,6 +395,23 @@ list) · [roadmap.md](docs/roadmap.md) (milestones, plan) · [parity-checklist.m ## Progress log +- **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-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. @@ -400,6 +425,7 @@ list) · [roadmap.md](docs/roadmap.md) (milestones, plan) · [parity-checklist.m 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. @@ -410,6 +436,9 @@ Newest first. - **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). @@ -421,6 +450,7 @@ Newest first. - **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-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. @@ -459,6 +489,7 @@ Newest first. - **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. @@ -546,6 +577,9 @@ Newest first. - **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. diff --git a/apps/designcraft-cli/src/stress.rs b/apps/designcraft-cli/src/stress.rs index c9d5b3015..ce3e7ed7d 100644 --- a/apps/designcraft-cli/src/stress.rs +++ b/apps/designcraft-cli/src/stress.rs @@ -169,7 +169,7 @@ pub fn synthetic(spec: &Spec) -> Result { id, name: format!("art-{k}.png"), mime: "image/png".into(), - data: Arc::new(data), + data: designcraft_doc::AssetData::embedded(data), pixels: Some((aw, ah)), ..Default::default() }), diff --git a/apps/designcraft-web/src/browser_policy.rs b/apps/designcraft-web/src/browser_policy.rs index 524df6cc5..ca82c71ca 100644 --- a/apps/designcraft-web/src/browser_policy.rs +++ b/apps/designcraft-web/src/browser_policy.rs @@ -1,4 +1,4 @@ -//! Pure browser startup and download metadata policies. +//! Browser startup, download metadata, and atomic import policies. /// Query flags are case-sensitive decoded keys. Values are ignored: `?sample=false` /// still enables sample startup, and repeated keys have the same presence semantics. @@ -65,3 +65,40 @@ mod tests { } } } + +/// Read a drop in order, publishing nothing unless every file can be read. +pub(crate) async fn read_batch(files: impl IntoIterator, mut read: F) -> Result, E> +where + F: FnMut(T) -> Fut, + Fut: std::future::Future>, +{ + let mut result = Vec::new(); + for file in files { + result.push(read(file).await?); + } + Ok(result) +} + +#[cfg(test)] +mod batch_tests { + #[test] + fn failed_read_aborts_the_whole_batch() { + use std::{ + future::Future, + task::{Context, Poll, Waker}, + }; + let mut seen = Vec::new(); + let result = { + let future = super::read_batch([1, 2, 3], |n| { + seen.push(n); + std::future::ready(if n == 2 { Err("read failed") } else { Ok(n) }) + }); + let mut future = std::pin::pin!(future); + future.as_mut().poll(&mut Context::from_waker(Waker::noop())) + }; + assert_eq!(result, Poll::Ready(Err("read failed"))); + assert_eq!(seen, [1, 2]); + let mut success = std::pin::pin!(super::read_batch([3, 1], |n| std::future::ready(Ok::<_, ()>(n)))); + assert_eq!(success.as_mut().poll(&mut Context::from_waker(Waker::noop())), Poll::Ready(Ok(vec![3, 1]))); + } +} diff --git a/apps/designcraft-web/src/web.rs b/apps/designcraft-web/src/web.rs index 19bc3a122..4d4c936c1 100644 --- a/apps/designcraft-web/src/web.rs +++ b/apps/designcraft-web/src/web.rs @@ -76,7 +76,7 @@ pub fn start() { if has_query_flag(&query(), "sample") { let _ = app.run("file.newSample", serde_json::json!({})); } - Ok(Box::new(WebShell { app, inbox, graphics: creator_graphics })) + Ok(Box::new(WebShell { app, inbox, read_errors: Default::default(), graphics: creator_graphics })) }), ) .await; @@ -344,12 +344,18 @@ fn query() -> String { struct WebShell { app: DesignApp, inbox: Inbox, + /// Why a dropped file couldn't be read, for the status bar (the read finishes outside a frame). + read_errors: std::sync::Arc>>, graphics: GraphicsState, } impl eframe::App for WebShell { fn logic(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) { let graphics = self.graphics.clone(); + let errors = std::mem::take(&mut *self.read_errors.lock().unwrap_or_else(|e| e.into_inner())); + if let Some(error) = errors.into_iter().last() { + self.app.status(error); + } let _ = graphics.run_if_healthy(|| self.app.logic(ctx)); } @@ -357,18 +363,34 @@ impl eframe::App for WebShell { let _ = self.graphics.run_if_healthy(|| { // Dropped files belong to this host iteration's raw input, not to stale logic input: // read them here once, before the batch is saved as pending for a hidden pass. - for f in std::mem::take(&mut raw.dropped_files) { + // Files dropped together arrive together, in their order, so several images load the + // place cursor as one batch. + let dropped = std::mem::take(&mut raw.dropped_files); + if !dropped.is_empty() { let request = self.app.import_request("drop"); let inbox = self.inbox.clone(); + let read_errors = self.read_errors.clone(); let ctx = ctx.clone(); wasm_bindgen_futures::spawn_local(async move { - let name = f.path().file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| "dropped".into()); - match f.bytes_async().await { - Ok(bytes) => { - inbox.lock().unwrap_or_else(|e| e.into_inner()).push(ImportedFile { request, name, bytes }); + let files = crate::browser_policy::read_batch(dropped, |f| { + let request = request.clone(); + async move { + let name = f.path().file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| "dropped".into()); + let bytes = f.bytes_async().await.map_err(|e| format!("couldn't read dropped file {name}: {e}"))?; + Ok::<_, String>(ImportedFile { request, name, bytes }) + } + }) + .await; + match files { + Ok(files) => { + inbox.lock().unwrap_or_else(|e| e.into_inner()).extend(files); + ctx.request_repaint(); + } + Err(error) => { + log::error!("{error}"); + read_errors.lock().unwrap_or_else(|e| e.into_inner()).push(error); ctx.request_repaint(); } - Err(e) => log::error!("couldn't read dropped file {name}: {e}"), } }); } @@ -402,11 +424,18 @@ fn services(inbox: Inbox, ctx: egui::Context) -> Services { rfd::AsyncFileDialog::new().add_filter("DesignCraft, IDML or InDesign", DOC_EXTS) }; wasm_bindgen_futures::spawn_local(async move { - let Some(file) = dialog.pick_file().await else { - return; + // Place takes several files, loaded into the place cursor in the order chosen. + let handles = if request.purpose == "place" { + dialog.pick_files().await.unwrap_or_default() + } else { + dialog.pick_file().await.into_iter().collect() }; - let bytes = file.read().await; - inbox.lock().unwrap_or_else(|e| e.into_inner()).push(ImportedFile { request, name: file.file_name(), bytes }); + let mut files = Vec::with_capacity(handles.len()); + for file in handles { + let bytes = file.read().await; + files.push(ImportedFile { request: request.clone(), name: file.file_name(), bytes }); + } + inbox.lock().unwrap_or_else(|e| e.into_inner()).extend(files); ctx.request_repaint(); }); })), diff --git a/apps/designcraft/Cargo.toml b/apps/designcraft/Cargo.toml index b17258acd..b66041a04 100644 --- a/apps/designcraft/Cargo.toml +++ b/apps/designcraft/Cargo.toml @@ -27,7 +27,8 @@ winresource = "0.1" # Not called here: craft-dialogs shows the dialogs. rfd's default features keep its Wayland # support on, so portal dialogs get the window as their parent. rfd = { workspace = true } -arboard = { workspace = true } +# `image-data`: Edit › Paste reads bitmaps from the clipboard (src/clipboard_image.rs). +arboard = { workspace = true, features = ["image-data"] } [target.'cfg(all(unix, not(target_os = "macos")))'.dependencies] # The same winit eframe uses: to pick the X11 backend (file drag-and-drop) in main.rs. @@ -46,9 +47,10 @@ 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", "NSEvent", "NSResponder", "NSScreen", "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. diff --git a/apps/designcraft/src/clipboard_image.rs b/apps/designcraft/src/clipboard_image.rs new file mode 100644 index 000000000..0e8339ff4 --- /dev/null +++ b/apps/designcraft/src/clipboard_image.rs @@ -0,0 +1,135 @@ +//! The system clipboard's image for Edit › Paste (`Services::clipboard_image`): a bitmap +//! (Windows `CF_DIBV5` or `PNG`, the macOS pasteboard's TIFF or PNG, `image/png` on X11), else the +//! first image file of files copied in a file manager. The read runs on its own thread, and Paste +//! waits for it at most [`WAIT`], so an application that is slow to hand over the clipboard does +//! not freeze the window. While a read that timed out is still waiting, Paste starts no other. + +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::mpsc; +use std::time::Duration; + +use designcraft_ui_egui::ClipboardImage; + +/// How long Paste waits for the clipboard's image. +const WAIT: Duration = Duration::from_millis(1500); + +/// The largest image file Paste reads from a copied file list, in bytes. +const MAX_FILE_BYTES: u64 = 256 << 20; + +/// A clipboard read is running. +static READING: AtomicBool = AtomicBool::new(false); + +/// The clipboard's image, or `None` when it holds none or does not answer within [`WAIT`]. +pub fn read() -> Option { + within(&READING, WAIT, read_now) +} + +/// Clears the in-flight flag when the read's thread ends. +struct Reading(&'static AtomicBool); + +impl Drop for Reading { + fn drop(&mut self) { + self.0.store(false, Ordering::Release); + } +} + +/// `read`'s result when it arrives within `wait`. A read that takes longer finishes on its own +/// thread and is dropped; until it does, `busy` stays set and no other read starts. +fn within(busy: &'static AtomicBool, wait: Duration, read: impl FnOnce() -> Option + Send + 'static) -> Option { + if busy.swap(true, Ordering::AcqRel) { + log::warn!("clipboard image: the previous read has not finished"); + return None; + } + let (tx, rx) = mpsc::channel(); + let spawned = std::thread::Builder::new().name("clipboard image".into()).spawn(move || { + let _reading = Reading(busy); + let _ = tx.send(read()); + }); + if let Err(e) = spawned { + busy.store(false, Ordering::Release); + log::warn!("clipboard image: no thread to read it: {e}"); + return None; + } + match rx.recv_timeout(wait) { + Ok(image) => image, + Err(mpsc::RecvTimeoutError::Timeout) => { + log::warn!("clipboard image: the clipboard did not answer within {} ms", wait.as_millis()); + None + } + Err(mpsc::RecvTimeoutError::Disconnected) => None, + } +} + +/// The general pasteboard's change count, which AppKit raises with every copy. +#[cfg(target_os = "macos")] +pub fn change_count() -> Option { + i64::try_from(objc2_app_kit::NSPasteboard::generalPasteboard().changeCount()).ok() +} + +fn read_now() -> Option { + let mut clipboard = arboard::Clipboard::new().ok()?; + if let Ok(image) = clipboard.get_image() { + let width = u32::try_from(image.width).ok()?; + let height = u32::try_from(image.height).ok()?; + return Some(ClipboardImage::Pixels { width, height, rgba: image.bytes.into_owned() }); + } + first_image_file(&clipboard.get().file_list().ok()?) +} + +/// The first of `paths` that is an image file no larger than [`MAX_FILE_BYTES`], with its name. +fn first_image_file(paths: &[PathBuf]) -> Option { + paths.iter().find_map(|path| { + let ext = path.extension()?.to_str()?.to_ascii_lowercase(); + if !designcraft_engine::cmd::IMAGE_EXTENSIONS.contains(&ext.as_str()) || std::fs::metadata(path).ok()?.len() > MAX_FILE_BYTES { + return None; + } + // At most one byte past the limit is read, should the file grow after the size check. + let bytes = designcraft_engine::io::read_capped(path, MAX_FILE_BYTES).ok().filter(|b| b.len() as u64 <= MAX_FILE_BYTES)?; + Some(ClipboardImage::File { name: file_name(path), bytes }) + }) +} + +fn file_name(path: &Path) -> String { + path.file_name().map_or_else(|| path.to_string_lossy().into_owned(), |n| n.to_string_lossy().into_owned()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_read_that_does_not_answer_is_given_up_and_no_second_one_starts_meanwhile() { + static BUSY: AtomicBool = AtomicBool::new(false); + let (release, blocked) = mpsc::channel::<()>(); + // The read waits for a message that is only sent after Paste has given up on it. + assert_eq!(within(&BUSY, Duration::ZERO, move || blocked.recv().ok().map(|()| 1)), None); + let (started, ran) = mpsc::channel::<()>(); + let second = within(&BUSY, Duration::from_secs(60), move || started.send(()).ok().map(|()| 2)); + assert_eq!(second, None, "refused while the first read waits"); + assert!(ran.try_recv().is_err(), "the second read never ran"); + let _ = release.send(()); + while BUSY.load(Ordering::Acquire) { + std::thread::yield_now(); + } + assert_eq!(within(&BUSY, Duration::from_secs(60), || Some(3)), Some(3), "an answer is taken as soon as it comes"); + } + + #[test] + fn a_copied_file_list_pastes_its_first_image_file() { + let stamp = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos(); + let dir = std::env::temp_dir().join(format!("designcraft-clipboard-files-{}-{stamp}", std::process::id())); + std::fs::create_dir(&dir).unwrap(); + let (text, missing, png) = (dir.join("notes.txt"), dir.join("gone.png"), dir.join("Photo.PNG")); + std::fs::write(&text, b"text").unwrap(); + std::fs::write(&png, b"png bytes").unwrap(); + let picked = first_image_file(&[text, missing, png.clone()]); + let none = first_image_file(&[dir.join("a.txt")]); + let _ = std::fs::remove_dir_all(&dir); + match picked { + Some(ClipboardImage::File { name, bytes }) => assert_eq!((name.as_str(), bytes.as_slice()), ("Photo.PNG", b"png bytes".as_slice())), + _ => panic!("the image file is picked"), + } + assert!(none.is_none()); + } +} diff --git a/apps/designcraft/src/main.rs b/apps/designcraft/src/main.rs index ab6970332..5f465e46d 100644 --- a/apps/designcraft/src/main.rs +++ b/apps/designcraft/src/main.rs @@ -15,6 +15,7 @@ #[cfg(target_os = "macos")] mod apple_events; +mod clipboard_image; mod control_server; mod gpu; mod gpu_limits; @@ -227,6 +228,9 @@ 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() diff --git a/apps/designcraft/src/pointer.rs b/apps/designcraft/src/pointer.rs index 14bf9599a..3725cfbaa 100644 --- a/apps/designcraft/src/pointer.rs +++ b/apps/designcraft/src/pointer.rs @@ -11,6 +11,33 @@ pub fn screen_position() -> Option { // 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(); - let (x, y) = (at.x, height - at.y); + from_appkit(at.x, at.y, height) +} + +/// A point in AppKit's global coordinates (origin at the bottom left of the main display, the one +/// with the menu bar, y up) in winit's (origin at its top left, y down), given that display's +/// height. Only the main display's height: winit flips window positions the same way +/// (`flip_window_screen_coordinates`, against `CGMainDisplayID`), whatever display the window is +/// on, so a display left of or above the main one gives negative coordinates in both. +fn from_appkit(x: f64, y: f64, main_height: f64) -> Option { + let y = main_height - y; (x.is_finite() && y.is_finite()).then(|| egui::pos2(x as f32, y as f32)) } + +#[cfg(test)] +mod tests { + use super::from_appkit; + + #[test] + fn appkit_points_flip_against_the_main_display_only() { + // The main display is 1000 points high: its top left is (0, 0), its bottom left (0, 1000). + assert_eq!(from_appkit(0.0, 1000.0, 1000.0), Some(egui::pos2(0.0, 0.0))); + assert_eq!(from_appkit(200.0, 100.0, 1000.0), Some(egui::pos2(200.0, 900.0))); + // A second display above the main one, and one to its left: negative, as winit reports a + // window there. + assert_eq!(from_appkit(300.0, 1200.0, 1000.0), Some(egui::pos2(300.0, -200.0))); + assert_eq!(from_appkit(-800.0, 500.0, 1000.0), Some(egui::pos2(-800.0, 500.0))); + assert_eq!(from_appkit(f64::NAN, 0.0, 1000.0), None); + assert_eq!(from_appkit(0.0, 0.0, f64::INFINITY), None); + } +} diff --git a/contributors/people.toml b/contributors/people.toml index 5049c9493..617091888 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -87,3 +87,7 @@ sync_github_name = true [people.JonRC] real_name = "Jonathan Cardoso" display_name = "Jonathan Cardoso" + +[people.adikshan11] +real_name = "Adithya Shankaran" +sync_github_name = true diff --git a/crates/compose/src/cache.rs b/crates/compose/src/cache.rs index 5e4cb0911..b46f6ad9a 100644 --- a/crates/compose/src/cache.rs +++ b/crates/compose/src/cache.rs @@ -5,13 +5,19 @@ //! wrapping item on the frames' spreads, and the same for every story whose anchored objects wrap //! its text ([`crate::wrap::neighbours`]). An anchored frame's entry also records where its host //! story's composition places it. Entries hold clones of those `Arc`s, so the pointers -//! can't be reused by other allocations while the entry lives. +//! can't be reused by other allocations while the entry lives. The document's Alpha Channel +//! outlines count by serial number, which no other outline shares. +//! +//! When only the story itself differs from an entry's (an edit of its text or formatting), the +//! new composition starts from the entry's and composes the paragraphs the edit can change +//! ([`crate::reuse`]). use std::collections::{HashMap, 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}; @@ -50,6 +56,25 @@ struct Entry { _keep: (Arc, Arc, Vec>, Vec>), out: Arc, stamp: u64, + /// For composing the story again after an edit ([`crate::reuse`]). + trace: Option>, +} + +/// The story an entry was composed from, its composition and that composition's trace. +type Before = (Arc, Arc, Arc); + +/// How many leading values of a [`signature`] identify the story's own allocation and revision; +/// the rest is everything else the composition was made from. +const STORY_SIG: usize = 2; + +impl Entry { + /// What composing for `sig` can take from this entry: set when only the story itself differs + /// (an edit of its text or formatting) and the entry's composition left a trace. + fn before(&self, sig: &[usize]) -> Option { + let trace = self.trace.as_ref()?; + (self.sig.len() == sig.len() && self.sig.get(STORY_SIG..) == sig.get(STORY_SIG..)) + .then(|| (self._keep.0.clone(), self.out.clone(), trace.clone())) + } } #[derive(Default)] @@ -62,6 +87,9 @@ pub struct Cache { /// The composition each story (page-independent key) had before its latest recomposition, /// with the story revision it was composed from (repaint only the frames an edit changed). previous: Mutex, Arc)>>, + /// A cache this one reads without writing to: a composition or index found there for the same + /// inputs is used, and anything composed is kept here only. + base: Option>, } /// A signature's hash, standing in for it in another story's signature. @@ -85,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() } @@ -104,6 +147,18 @@ impl Cache { Self::default() } + /// An empty cache that also uses what `base` holds for the same inputs, and never changes + /// `base`. A reader of an older state of the document composes that state here instead of + /// replacing the compositions of the current state in `base`. + pub fn over(base: Arc) -> Self { + Cache { base: Some(base), ..Self::default() } + } + + /// The cache given to [`Cache::over`]. + pub fn base(&self) -> Option<&Arc> { + self.base.as_ref() + } + /// The composed story, from cache or freshly composed. `page` is the absolute page a /// parent-page item is shown on (its page number markers and variables are that page's), or /// `None` for a story's own frames. Pages are identified by index, not name: names repeat when @@ -128,6 +183,14 @@ impl Cache { c } + /// Where the host story places anchored text frame `fid`, one of story `sid`'s frames; `None` for + /// a frame on a spread. + pub fn placement(&self, doc: &Document, sid: StoryId, fid: designcraft_doc::ItemId) -> Option { + let mut resolved = Resolved::new(); + let placed = crate::placed::placements(doc, sid, &mut |host| self.resolve(doc, host, true, 1, &mut resolved)); + placed.into_iter().find_map(|(id, p)| (id == fid).then_some(p)) + } + /// [`Cache::get_on`], wrapped by other stories' anchored objects only when `cross` is set, for /// a story `depth` hosts down from the story asked for. fn get_with(&self, doc: &Document, sid: StoryId, on: ShownOn, cross: bool, depth: usize, resolved: &mut Resolved) -> Arc { @@ -244,14 +307,24 @@ 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(); } } @@ -259,18 +332,21 @@ impl Cache { let page = page.filter(|_| with_vars); let running = running.then(|| self.running_index(doc)); let others: Vec> = neighbours.iter().map(|n| self.neighbour(doc, *n, depth, resolved)).collect(); - let out = Arc::new(crate::wrap::compose_among( + let (out, trace) = crate::wrap::compose_among_traced( doc, sid, &ComposeOptions { page_name, section_marker, page, running, label: None, xrefs: with_xrefs.then(|| self.xref_index(doc)), placed }, &others.iter().map(|o| &**o).collect::>(), - )); + before.as_ref().map(|(story, composed, trace)| Reuse { story, composed, trace }), + ); + let (out, trace) = (Arc::new(out), trace.map(Arc::new)); let mut g = self.map.lock().unwrap_or_else(PoisonError::into_inner); let stamp = g.1; if g.0.len() > 4096 { g.0.retain(|_, e| stamp - e.stamp < 64); } - let replaced = g.0.insert(key, Entry { sig, _keep: (story.clone(), doc.styles.clone(), keep_items, keep_stories), out: out.clone(), stamp }); + let replaced = + g.0.insert(key, Entry { sig, _keep: (story.clone(), doc.styles.clone(), keep_items, keep_stories), out: out.clone(), stamp, trace }); drop(g); // Only the composition that is shown (not one made for another story's wrap). if key.1 == ShownOn::Own @@ -368,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 @@ -381,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 @@ -405,6 +493,7 @@ fn signature(doc: &Document, story: &Arc) -> (Vec, Vec>) sections_hash(doc) as usize, doc.font_scope as usize, usize::from(g.relative_to == designcraft_doc::GridRelative::TopMargin), + outlines_hash(doc) as usize, ]; sig.extend([g.start, g.increment].into_iter().flat_map(bits)); let mut keep = Vec::new(); diff --git a/crates/compose/src/grep.rs b/crates/compose/src/grep.rs index b387384f9..5a56920dc 100644 --- a/crates/compose/src/grep.rs +++ b/crates/compose/src/grep.rs @@ -432,15 +432,36 @@ impl Grep { Ok((out, more)) } - /// Matches in `text` and their replacements, `template` expanded per match (`$1`…; see - /// [`translate_replacement`]). Stops after the first match when `first_only`. - pub fn replacements(&self, text: &str, template: &str, first_only: bool) -> Result, String)>, GrepError> { + /// Matches in `text` that `keep` accepts and their replacements, `template` expanded per match + /// (`$1`…; see [`translate_replacement`]). Stops after the first kept match when `first_only`, + /// and with an error once the expanded replacements pass `max_bytes` in all (before any more + /// are made). + pub fn replacements( + &self, + text: &str, + template: &str, + first_only: bool, + max_bytes: usize, + keep: impl Fn(&Range) -> bool, + ) -> Result, String)>, GrepError> { let exp = fancy_regex::Expander::default(); let mut out = Vec::new(); + let mut bytes = 0usize; for caps in self.re.captures_iter(text) { let caps = caps.map_err(run_err)?; let Some(m) = caps.get(0) else { continue }; - out.push((m.range(), exp.expansion(template, &caps))); + if !keep(&m.range()) { + continue; + } + // Written into a buffer that refuses bytes past the budget, so an oversized + // expansion is rejected before it is allocated. + let mut w = BoundedBuf { buf: Vec::new(), left: max_bytes.saturating_sub(bytes) }; + if exp.write_expansion(&mut w, template, &caps).is_err() { + return Err(err(format!("the replacements would put more than {max_bytes} bytes in"))); + } + bytes += w.buf.len(); + let expanded = String::from_utf8(w.buf).map_err(|_| err("the replacement is not valid UTF-8".to_string()))?; + out.push((m.range(), expanded)); if first_only { break; } @@ -449,6 +470,27 @@ impl Grep { } } +/// A byte sink that fails a write that would pass its remaining budget (nothing is copied then). +struct BoundedBuf { + buf: Vec, + left: usize, +} + +impl std::io::Write for BoundedBuf { + fn write(&mut self, data: &[u8]) -> std::io::Result { + if data.len() > self.left { + return Err(std::io::ErrorKind::OutOfMemory.into()); + } + self.left -= data.len(); + self.buf.extend_from_slice(data); + Ok(data.len()) + } + + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } +} + fn run_err(e: fancy_regex::Error) -> GrepError { err(format!("GREP search stopped: {e}")) } @@ -520,7 +562,13 @@ 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] diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index abac72985..2942fb962 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -24,6 +24,7 @@ mod outline; mod overlay; mod parabox; mod placed; +mod reuse; mod ruby; pub mod shape; pub mod shatai; @@ -364,6 +365,9 @@ pub struct Exclusion { /// An anchored object in the frame's own story: it wraps only lines that start after this /// story byte (its anchor). pub after: Option, + /// For an anchored object in the frame's own story: the baseline of the line holding its + /// anchor when the exclusion was taken from it. + pub anchor_baseline: Option, } impl Exclusion { @@ -382,17 +386,50 @@ pub struct Contour { /// The frame path of an outline taken from a placed graphic: the frame clips the graphic, so /// the outline counts only within it (empty: no clip). pub clip: Vec>, + /// The placed graphic's clipping path, for an outline traced from the graphic's pixels: the + /// outline counts only inside it too (empty: none). An inverted clipping path is filled + /// even-odd ([`designcraft_doc::Graphic::clip_region`]). + pub graphic_clip: Vec>, + pub graphic_clip_even_odd: bool, pub offset: f64, } +/// A filled shape: closed polylines and their fill rule (non-zero, or even-odd). +#[derive(Clone, Copy)] +struct Region<'a> { + rings: &'a [Vec], + even_odd: bool, +} + +impl Region<'_> { + fn nonzero(rings: &[Vec]) -> Region<'_> { + Region { rings, even_odd: false } + } + + /// Is a point with this winding number filled? + fn fills(self, winding: i32) -> bool { + if self.even_odd { winding % 2 != 0 } else { winding != 0 } + } +} + /// Points a contour outline may have; a larger outline wraps around its bounding box. -const MAX_CONTOUR_POINTS: usize = 8192; +pub const MAX_CONTOUR_POINTS: usize = 8192; + +/// Edge visits a clipped contour may take for one line band; past it, the line's spans come from +/// the two shapes' projections instead of their intersection. +const MAX_CLIPPED_WORK: usize = 1 << 20; impl Contour { /// The outline of `path` (after `to_inner`), flattened; None if it is empty or too detailed. fn of(path: &designcraft_geom::BezPath, to_inner: designcraft_geom::Affine, offset: f64) -> Option { let rings = flatten_rings(path, to_inner)?; - offset.is_finite().then_some(Contour { rings, clip: Vec::new(), offset: offset.max(0.0) }) + offset.is_finite().then_some(Contour { + rings, + clip: Vec::new(), + graphic_clip: Vec::new(), + graphic_clip_even_odd: false, + offset: offset.max(0.0), + }) } /// This outline counted only within `frame` (after `to_inner`); unclipped if the frame is @@ -404,18 +441,41 @@ impl Contour { } } + /// This outline counted only inside the graphic's clipping region `clip` (after `to_inner`), + /// filled even-odd when `even_odd` is set; unchanged if the region is empty or too detailed. + fn within_graphic_clip(self, clip: &designcraft_geom::BezPath, even_odd: bool, to_inner: designcraft_geom::Affine) -> Contour { + match flatten_rings(clip, to_inner) { + Some(graphic_clip) => Contour { graphic_clip, graphic_clip_even_odd: even_odd, ..self }, + None => self, + } + } + /// The outline mapped by `a`. fn transformed(self, a: designcraft_geom::Affine) -> Contour { let map = |rings: Vec>| rings.into_iter().map(|r| r.into_iter().map(|p| a * p).collect()).collect(); - Contour { rings: map(self.rings), clip: map(self.clip), offset: self.offset } + Contour { + rings: map(self.rings), + clip: map(self.clip), + graphic_clip: map(self.graphic_clip), + graphic_clip_even_odd: self.graphic_clip_even_odd, + offset: self.offset, + } + } + + /// The clips the outline counts within. + fn clips(&self) -> impl Iterator> { + let frame = (!self.clip.is_empty()).then(|| Region::nonzero(&self.clip)); + let graphic = (!self.graphic_clip.is_empty()).then_some(Region { rings: &self.graphic_clip, even_odd: self.graphic_clip_even_odd }); + frame.into_iter().chain(graphic) } fn bounds(&self) -> Rect { - let Some(r) = rings_bounds(&self.rings) else { return Rect::ZERO }; - let r = match rings_bounds(&self.clip) { - Some(c) => r.intersect(c), - None => r, - }; + let Some(mut r) = rings_bounds(&self.rings) else { return Rect::ZERO }; + for c in self.clips() { + if let Some(b) = rings_bounds(c.rings) { + r = r.intersect(b); + } + } r.inflate(self.offset, self.offset) } @@ -425,12 +485,301 @@ impl Contour { fn band_extent(&self, y0: f64, y1: f64) -> Option<(f64, f64)> { let (y0, y1) = (y0 - self.offset, y1 + self.offset); let (mut lo, mut hi) = rings_band_extent(&self.rings, y0, y1)?; - if !self.clip.is_empty() { - let (a, b) = rings_band_extent(&self.clip, y0, y1)?; + for c in self.clips() { + let (a, b) = rings_band_extent(c.rings, y0, y1)?; (lo, hi) = (lo.max(a), hi.min(b)); } (lo <= hi).then_some((lo - self.offset, hi + self.offset)) } + + /// Occupied intervals across the whole line band, preserving gaps between parts of a + /// concave or compound outline. Project boundary edges and the filled middle slice: any + /// area that starts or ends inside the band is bounded by those projected edges. + fn band_spans(&self, y0: f64, y1: f64) -> Vec<(f64, f64)> { + let (low, high) = (y0 - self.offset, y1 + self.offset); + if !low.is_finite() || !high.is_finite() || high < low { + return self.band_extent(y0, y1).into_iter().collect(); + } + let mut spans = rings_band_spans(Region::nonzero(&self.rings), low, high); + // Extremely fragmented imported paths use the conservative outer extent, bounding the + // work of subtracting intervals from every line. A traced 128-column mask stays below it. + if spans.len() > 128 { + return self.band_extent(y0, y1).into_iter().collect(); + } + let clips: Vec = self.clips().collect(); + if !clips.is_empty() { + let projected: Vec> = clips.iter().map(|c| rings_band_spans(*c, low, high)).collect(); + // A fragmented clip, or shapes too detailed to compare within each line's budget, + // take the common part of the projections, which can block more than the clips show. + let mut shapes = vec![Region::nonzero(&self.rings)]; + shapes.extend(&clips); + let exact = if projected.iter().any(|p| p.len() > 128) { None } else { clipped_band_spans(&shapes, low, high) }; + spans = exact.unwrap_or_else(|| projected.iter().fold(spans, |s, p| intersect_spans(&s, p))); + } + merge_spans(spans.into_iter().map(|(a, b)| (a - self.offset, b + self.offset)).collect()) + } +} + +/// The sorted spans in both `a` and `b` (each sorted and merged). A zero-width span (a vertical +/// open path) is kept where the other covers it. +fn intersect_spans(a: &[(f64, f64)], b: &[(f64, f64)]) -> Vec<(f64, f64)> { + let mut out = Vec::new(); + let (mut i, mut j) = (0, 0); + while let (Some(&(p, q)), Some(&(r, s))) = (a.get(i), b.get(j)) { + let (lo, hi) = (p.max(r), q.min(s)); + if lo < hi || (lo == hi && (p == q || r == s)) { + out.push((lo, hi)); + } + if q < s { + i += 1; + } else { + j += 1; + } + } + out +} + +/// Occupied intervals across the band `y0..y1` of the part of the plane inside every one of +/// `shapes` (an outline and its clips). A vertical line through a point of that part either +/// crosses the middle of the band inside all the shapes, or stops inside the band on an edge of +/// one shape that lies inside the others. The spans are the middle slice of all the shapes and +/// the parts of each shape's edges in the band that lie inside the others, so a part of the +/// outline outside a clip blocks nothing, even where it shares x positions with the clip in the +/// same band. Only the edges that reach the band are visited. None when that takes more than +/// [`MAX_CLIPPED_WORK`] edge visits. +fn clipped_band_spans(shapes: &[Region], y0: f64, y1: f64) -> Option> { + let middle = y0 * 0.5 + y1 * 0.5; + let mut slices = shapes.iter().map(|s| merge_spans(middle_spans(*s, middle))); + let first = slices.next()?; + let mut spans = slices.fold(first, |a, b| intersect_spans(&a, &b)); + let banded: Vec = shapes.iter().map(|s| BandEdges::of(*s, y0, y1)).collect(); + let mut budget = MAX_CLIPPED_WORK; + for k in 0..banded.len() { + edges_inside(&banded, k, y0, y1, &mut budget, &mut spans)?; + } + Some(merge_spans(spans)) +} + +/// The edges of a shape that reach a line band, with a margin above and below. Every point +/// [`segment_inside`] tests lies within the margin, and an edge that doesn't reach a point's y +/// neither crosses the ray from it nor passes within a hair of it, so these edges give the same +/// inside and on-edge answers as the whole shape for those points. +struct BandEdges { + edges: Vec<(Point, Point)>, + even_odd: bool, +} + +impl BandEdges { + /// Margin added above and below the band; well above the side step in [`segment_inside`]. + const MARGIN: f64 = 1e-3; + + fn of(shape: Region, y0: f64, y1: f64) -> BandEdges { + let (lo, hi) = (y0 - Self::MARGIN, y1 + Self::MARGIN); + let mut edges = Vec::new(); + for ring in shape.rings { + let Some(&last) = ring.last() else { continue }; + let mut a = last; + for &b in ring { + if a.y.max(b.y) >= lo && a.y.min(b.y) <= hi { + edges.push((a, b)); + } + a = b; + } + } + BandEdges { edges, even_odd: shape.even_odd } + } + + /// Is a point with this winding number filled? + fn fills(&self, winding: i32) -> bool { + if self.even_odd { winding % 2 != 0 } else { winding != 0 } + } +} + +/// Takes `n` edge visits from `budget`; None when it doesn't hold that many. +fn spend(budget: &mut usize, n: usize) -> Option<()> { + *budget = budget.checked_sub(n)?; + Some(()) +} + +/// Pushes to `out` the x-ranges of the parts of the edges of `shapes[k]` within the band `y0..y1` +/// that bound the part of the plane inside all of `shapes` ([`segment_inside`]). None when +/// `budget` runs out. +fn edges_inside(shapes: &[BandEdges], k: usize, y0: f64, y1: f64, budget: &mut usize, out: &mut Vec<(f64, f64)>) -> Option<()> { + let n = shapes.iter().map(|o| o.edges.len()).sum::().max(1); + for &(a, b) in &shapes.get(k)?.edges { + let dy = b.y - a.y; + if a.y.max(b.y) >= y0 && a.y.min(b.y) <= y1 { + let (t0, t1) = if dy.abs() < 1e-12 { + (0.0, 1.0) + } else { + let (u, v) = ((y0 - a.y) / dy, (y1 - a.y) / dy); + (u.min(v).clamp(0.0, 1.0), u.max(v).clamp(0.0, 1.0)) + }; + let (p, q) = (a + (b - a) * t0, a + (b - a) * t1); + segment_inside(p, q, shapes, k, n, budget, out)?; + } + } + Some(()) +} + +/// Pushes to `out` the x-ranges of the parts of segment `p`–`q`, an edge of `shapes[k]`, that +/// bound the part of the plane inside all of `shapes` (`n` edges in all). The segment is split +/// where it meets the other shapes' edges, and each piece is tested at its middle: it counts when +/// the points just beside it on one side are inside all the shapes. Where `shapes[k]` has no area +/// on either side (an open path), it counts when it is inside the other shapes or on their +/// boundary. Each pass over the edges takes `n` from `budget`; None when it runs out. +fn segment_inside(p: Point, q: Point, shapes: &[BandEdges], k: usize, n: usize, budget: &mut usize, out: &mut Vec<(f64, f64)>) -> Option<()> { + let r = q - p; + let len2 = r.hypot2(); + if !len2.is_finite() { + return Some(()); + } + let at = |t: f64| p + r * t; + let in_others = |pt: Point| shapes.iter().enumerate().all(|(i, s)| i == k || inside_or_on(s, pt)); + spend(budget, n)?; + if len2 < 1e-24 { + if in_others(p) { + out.push((p.x, p.x)); + } + return Some(()); + } + // A step to either side of the segment, well above rounding at page coordinates. + let side = r.turn_90() * (1e-6 / len2.sqrt()); + let bounds_the_part = |m: Point| { + let own = shapes.get(k); + let in_own = |pt: Point| own.is_some_and(|s| inside_or_on(s, pt)); + let (a, b) = (m + side, m - side); + match (in_own(a), in_own(b)) { + (false, false) => in_others(m), + (ia, ib) => (ia && in_others(a)) || (ib && in_others(b)), + } + }; + let (ylo, yhi) = (p.y.min(q.y), p.y.max(q.y)); + let mut ts = vec![0.0, 1.0]; + for &(c, d) in shapes.iter().enumerate().filter(|(i, _)| *i != k).flat_map(|(_, s)| &s.edges) { + if c.y.max(d.y) >= ylo - 1e-9 && c.y.min(d.y) <= yhi + 1e-9 { + let e = d - c; + let denom = r.cross(e); + let w = c - p; + if denom.abs() > 1e-12 * (len2 * e.hypot2()).sqrt() { + let (t, u) = (w.cross(e) / denom, w.cross(r) / denom); + if (-1e-9..=1.0 + 1e-9).contains(&u) && (0.0..=1.0).contains(&t) { + ts.push(t); + } + } else if w.cross(r).abs() <= 1e-9 * len2.sqrt() { + // Collinear: the edge's ends split the segment. + for t in [w.dot(r) / len2, (d - p).dot(r) / len2] { + if (0.0..=1.0).contains(&t) { + ts.push(t); + } + } + } + } + } + ts.sort_by(f64::total_cmp); + ts.dedup_by(|a, b| (*a - *b).abs() < 1e-12); + for w in ts.windows(2) { + let (u, v) = (w[0], w[1]); + spend(budget, 3 * n)?; + if bounds_the_part(at(u * 0.5 + v * 0.5)) { + let (x0, x1) = (at(u).x, at(v).x); + out.push((x0.min(x1), x0.max(x1))); + } + } + Some(()) +} + +/// Is `pt`, a point within the band of `shape`'s edges, inside the shape or within a hair of one +/// of its edges? +fn inside_or_on(shape: &BandEdges, pt: Point) -> bool { + let mut winding = 0i32; + for &(a, b) in &shape.edges { + let e = b - a; + let len2 = e.hypot2(); + let t = if len2 > 0.0 { ((pt - a).dot(e) / len2).clamp(0.0, 1.0) } else { 0.0 }; + if (a + e * t - pt).hypot2() < 1e-18 { + return true; + } + if (a.y <= pt.y && pt.y < b.y) || (b.y <= pt.y && pt.y < a.y) { + let x = a.x + (pt.y - a.y) / e.y * e.x; + if x > pt.x { + winding += if e.y > 0.0 { 1 } else { -1 }; + } + } + } + shape.fills(winding) +} + +/// Sorted, overlapping spans joined. Zero-width spans (a vertical edge of an open path) are kept: +/// the wrap offset widens them, and without one they still split the line there. +fn merge_spans(mut spans: Vec<(f64, f64)>) -> Vec<(f64, f64)> { + spans.retain(|(a, b)| a.is_finite() && b.is_finite() && b >= a); + spans.sort_by(|a, b| a.0.total_cmp(&b.0)); + let mut out: Vec<(f64, f64)> = Vec::new(); + for (a, b) in spans { + if let Some(last) = out.last_mut().filter(|last| a <= last.1 + 1e-9) { + last.1 = last.1.max(b); + } else { + out.push((a, b)); + } + } + out +} + +fn rings_band_spans(shape: Region, y0: f64, y1: f64) -> Vec<(f64, f64)> { + let mut spans = middle_spans(shape, y0 * 0.5 + y1 * 0.5); + for ring in shape.rings { + let Some(&last) = ring.last() else { continue }; + let mut a = last; + for &b in ring { + let dy = b.y - a.y; + if a.y.max(b.y) >= y0 && a.y.min(b.y) <= y1 { + let (t0, t1) = if dy.abs() < 1e-12 { + (0.0, 1.0) + } else { + let (u, v) = ((y0 - a.y) / dy, (y1 - a.y) / dy); + (u.min(v).clamp(0.0, 1.0), u.max(v).clamp(0.0, 1.0)) + }; + let (x0, x1) = (a.x + t0 * (b.x - a.x), a.x + t1 * (b.x - a.x)); + spans.push((x0.min(x1), x0.max(x1))); + } + a = b; + } + } + merge_spans(spans) +} + +/// The intervals of the line at height `middle` inside `shape`, unsorted. +fn middle_spans(shape: Region, middle: f64) -> Vec<(f64, f64)> { + let mut spans = Vec::new(); + let mut crossings = Vec::new(); + for ring in shape.rings { + let Some(&last) = ring.last() else { continue }; + let mut a = last; + for &b in ring { + let dy = b.y - a.y; + if (a.y <= middle && middle < b.y) || (b.y <= middle && middle < a.y) { + let x = a.x + (middle - a.y) / dy * (b.x - a.x); + if x.is_finite() { + crossings.push((x, if dy > 0.0 { 1i32 } else { -1 })); + } + } + a = b; + } + } + crossings.sort_by(|a, b| a.0.total_cmp(&b.0)); + let mut winding = 0i32; + let mut previous = None; + for (x, delta) in crossings { + if shape.fills(winding) + && let Some(start) = previous + { + spans.push((start, x)); + } + winding += delta; + previous = Some(x); + } + spans } /// The closed polylines of `path` (after `to_inner`), flattened; None if it is empty or too detailed. @@ -493,19 +842,39 @@ fn rings_band_extent(rings: &[Vec], y0: f64, y1: f64) -> Option<(f64, f64 /// The wrap exclusion of `other` (an item whose inner space maps to the spread by `xf`) for a /// frame whose inner space is reached from the spread by `inv`. `left_page` places the object on /// a left page (for the spine sides). -pub fn exclusion(other: &Item, xf: Affine, inv: Affine, left_page: bool) -> Exclusion { +pub fn exclusion(doc: &Document, other: &Item, xf: Affine, inv: Affine, left_page: bool) -> Exclusion { let group = other.shape == designcraft_doc::Shape::Group; let b = if group { (xf * other.xf.inverse()).transform_rect_bbox(other.bounds()) } else { other.path.transformed(xf).bounds().unwrap_or(Rect::ZERO) }; - wrap_exclusion(&other.wrap, b, || (!group).then(|| contour_path(other, other.wrap.contour)), xf, inv, left_page) + let e = wrap_exclusion(&other.wrap, b, || (!group).then(|| contour_path(doc, other, &other.wrap)), xf, inv, left_page); + nothing_visible_wraps_nothing(doc, other, &other.wrap, e) } /// The wrap exclusion of the graphic placed in frame `it` (arguments as for [`exclusion`]): around /// the part of the graphic the frame shows. None if there is no graphic or it is not shown. -pub fn graphic_exclusion(it: &Item, xf: Affine, inv: Affine, left_page: bool) -> Option { +pub fn graphic_exclusion(doc: &Document, it: &Item, xf: Affine, inv: Affine, left_page: bool) -> Option { let g = it.graphic()?; let shown = g.shown_bounds(it.inner_bounds())?; - Some(wrap_exclusion(&g.wrap, xf.transform_rect_bbox(shown), || Some(contour_path(it, g.wrap.contour)), xf, inv, left_page)) + let e = wrap_exclusion(&g.wrap, xf.transform_rect_bbox(shown), || Some(contour_path(doc, it, &g.wrap)), xf, inv, left_page); + Some(nothing_visible_wraps_nothing(doc, it, &g.wrap, e)) +} + +/// An Alpha Channel contour around an image with no pixel more opaque than the threshold leaves +/// the text alone (the exclusion's mode becomes None). +fn nothing_visible_wraps_nothing(doc: &Document, it: &Item, wrap: &designcraft_doc::TextWrap, mut e: Exclusion) -> Exclusion { + if wrap.mode == WrapMode::Contour + && wrap.contour == designcraft_doc::ContourType::AlphaChannel + && wrap.path.is_none() + && let Some(g) = it.graphic() + && let Some(o) = doc.alpha_outline(g.asset, wrap.alpha_threshold) + && o.width > 0 + && o.height > 0 + && o.outer.subpaths.is_empty() + { + e.mode = WrapMode::None; + e.contour = None; + } + e } /// The exclusion of `wrap` around an object with spread-space bounds `b`; `outline` gives its @@ -513,7 +882,7 @@ pub fn graphic_exclusion(it: &Item, xf: Affine, inv: Affine, left_page: bool) -> fn wrap_exclusion( wrap: &designcraft_doc::TextWrap, b: Rect, - outline: impl FnOnce() -> Option<(designcraft_geom::BezPath, Option)>, + outline: impl FnOnce() -> Option, xf: Affine, inv: Affine, left_page: bool, @@ -531,37 +900,71 @@ fn wrap_exclusion( if let Some(custom) = wrap.path.as_ref().and_then(|p| Contour::of(&p.to_bezpath(), inv * xf, 0.0)) { let rect = custom.bounds(); let contour = matches!(wrap.mode, WrapMode::BoundingBox | WrapMode::Contour).then_some(custom); - return Exclusion { rect, mode: wrap.mode, side, contour, after: None }; + return Exclusion { rect, mode: wrap.mode, side, contour, after: None, anchor_baseline: None }; } - let contour = if wrap.mode == WrapMode::Contour { outline() } else { None }.and_then(|(path, frame)| { - let c = Contour::of(&path, inv * xf, o[0])?; - Some(match frame { - Some(frame) => c.within(&frame, inv * xf), - None => c, - }) + let contour = if wrap.mode == WrapMode::Contour { outline() } else { None }.and_then(|src| { + let mut c = Contour::of(&src.path, inv * xf, o[0])?; + if let Some(frame) = &src.frame { + c = c.within(frame, inv * xf); + } + if let Some((clip, even_odd)) = &src.graphic_clip { + c = c.within_graphic_clip(clip, *even_odd, inv * xf); + } + Some(c) }); let rect = contour.as_ref().map_or_else(|| inv.transform_rect_bbox(r), Contour::bounds); - Exclusion { rect, mode: wrap.mode, side, contour, after: None } + Exclusion { rect, mode: wrap.mode, side, contour, after: None, anchor_baseline: None } } -/// The outline a contour wrap of `kind` around frame `it` follows, in the frame's inner space, and -/// for an outline taken from the placed graphic, the frame path that clips it. Bounding Box -/// follows the part of the placed graphic the frame shows; Same As Clipping follows the graphic's -/// clipping path when it has one; detected edges, alpha channels and image paths need the image, -/// so they follow the frame's path (as other frames do). -fn contour_path(it: &Item, kind: designcraft_doc::ContourType) -> (designcraft_geom::BezPath, Option) { +/// The outline a contour wrap follows, in the frame's inner space, with what clips it. +struct Outline { + path: designcraft_geom::BezPath, + /// For an outline taken from the placed graphic: the frame path that clips it. + frame: Option, + /// For an outline traced from the graphic's pixels: the graphic's clipping region, and + /// whether it is filled even-odd. + graphic_clip: Option<(designcraft_geom::BezPath, bool)>, +} + +impl Outline { + fn clipped_by(path: designcraft_geom::BezPath, frame: designcraft_geom::BezPath) -> Outline { + Outline { path, frame: Some(frame), graphic_clip: None } + } +} + +/// The outline a contour wrap of `kind` around frame `it` follows. Bounding Box follows the part +/// of the placed graphic the frame shows; Same As Clipping follows the graphic's clipping path +/// when it has one; Alpha Channel follows the image's traced outline when the engine has traced +/// one, within the graphic's clipping path too; detected edges and image paths follow the frame's +/// path (as other frames do). +fn contour_path(doc: &Document, it: &Item, wrap: &designcraft_doc::TextWrap) -> Outline { let frame = designcraft_geom::corners::apply(&it.path, &it.corners); + let kind = wrap.contour; + if kind == designcraft_doc::ContourType::AlphaChannel + && let Some(g) = it.graphic() + && let Some(o) = doc.alpha_outline(g.asset, wrap.alpha_threshold) + && o.width > 0 + && o.height > 0 + { + let to_graphic = Affine::scale_non_uniform(g.size.0 / f64::from(o.width), g.size.1 / f64::from(o.height)); + let mut path = o.outer.to_bezpath(); + if wrap.inside_edges { + path.extend(o.holes.to_bezpath().iter()); + } + // The clipping path hides the pixels outside it. + return Outline { graphic_clip: g.clip_region(), ..Outline::clipped_by(g.xf * to_graphic * path, frame) }; + } if kind == designcraft_doc::ContourType::SameAsClipping && let Some((path, _)) = it.graphic().and_then(|g| g.clip_region()) { - return (path, Some(frame)); + return Outline::clipped_by(path, frame); } if kind == designcraft_doc::ContourType::BoundingBox && let Some(r) = it.graphic().and_then(|g| g.shown_bounds(it.inner_bounds())) { - return (designcraft_geom::kurbo::Shape::to_path(&r, 0.1), Some(frame)); + return Outline::clipped_by(designcraft_geom::kurbo::Shape::to_path(&r, 0.1), frame); } - (frame, None) + Outline { path: frame, frame: None, graphic_clip: None } } /// One frame of the thread, ready for composition. @@ -646,20 +1049,32 @@ const MAX_WRAP_DEPTH: usize = 64; /// the spread; `skip` is the text frame being wrapped; `left_page` tells whether a spread x is on /// a left page. #[allow(clippy::too_many_arguments)] -fn wrap_obstacles(it: &Item, parent: Affine, inv: Affine, skip: ItemId, left_page: &dyn Fn(f64) -> bool, depth: usize, out: &mut Vec) { +fn wrap_obstacles( + doc: &Document, + it: &Item, + parent: Affine, + inv: Affine, + skip: ItemId, + left_page: &dyn Fn(f64) -> bool, + depth: usize, + out: &mut Vec, +) { if it.id == skip || it.hidden || depth > MAX_WRAP_DEPTH { return; } let xf = parent * it.xf; let left = || left_page(parent.transform_rect_bbox(it.bounds()).center().x); + // An exclusion whose mode came back None (nothing visible to wrap) is left out. if it.wrap.mode != WrapMode::None { - out.push(exclusion(it, xf, inv, left())); + out.extend(Some(exclusion(doc, it, xf, inv, left())).filter(|e| e.mode != WrapMode::None)); } match &it.content { - Content::Graphic(g) if g.wrap.mode != WrapMode::None => out.extend(graphic_exclusion(it, xf, inv, left())), + Content::Graphic(g) if g.wrap.mode != WrapMode::None => { + out.extend(graphic_exclusion(doc, it, xf, inv, left()).filter(|e| e.mode != WrapMode::None)) + } Content::Group { .. } => { for c in it.shown_children() { - wrap_obstacles(c, xf, inv, skip, left_page, depth + 1, out); + wrap_obstacles(doc, c, xf, inv, skip, left_page, depth + 1, out); } } _ => {} @@ -676,7 +1091,7 @@ fn frame_wrap_exclusions(doc: &Document, sp: &designcraft_doc::Spread, item: &It if doc.layer(other.layer).is_some_and(|l| !l.visible) { continue; } - wrap_obstacles(other, Affine::IDENTITY, inv, item.id, &left, 0, exclusions); + wrap_obstacles(doc, other, Affine::IDENTITY, inv, item.id, &left, 0, exclusions); } let a = item.text_area(); exclusions.retain(|e| { @@ -790,10 +1205,7 @@ pub(crate) fn frame_specs_placed(doc: &Document, sid: StoryId, placed: &[(ItemId // area (all four insets) still bounds the lines. let outline = match &tf.options.path { Some(_) => None, - None => { - let bp = if item.corners.is_none() { item.path.to_bezpath() } else { designcraft_geom::corners::apply(&item.path, &item.corners) }; - FrameOutline::new(&bp, tf.options.inset[0]) - } + None => FrameOutline::of_item(item, tf.options.inset[0]), }; // Vertical type: composed in the turned box; wraps and page rects turned with it. let vertical = doc.frame_vertical(item); @@ -882,10 +1294,63 @@ struct SubstitutionInput<'a> { var_story: bool, var_cache: &'a mut HashMap<(Option, bool), Arc>>, notes: &'a mut Notes, + /// The marks in the story before `range`. + marks: MarkCounts, +} + +/// Endnote references, anchored-object marks and cross-reference marks in a stretch of story text. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +struct MarkCounts { + endnotes: usize, + objects: usize, + xrefs: usize, +} + +#[cfg(test)] +thread_local! { + /// Bytes of story text [`MarkCounts::of`] has read on this thread. + static MARK_BYTES_SCANNED: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +impl MarkCounts { + /// The marks in `text`. + fn of(text: &str) -> Self { + #[cfg(test)] + MARK_BYTES_SCANNED.with(|n| n.set(n.get() + text.len())); + let mut m = Self::default(); + for c in text.chars() { + match c { + designcraft_doc::ENDNOTE_REF => m.endnotes += 1, + designcraft_doc::OBJECT_MARK => m.objects += 1, + designcraft_doc::XREF_MARK => m.xrefs += 1, + _ => {} + } + } + m + } + + /// The marks before each paragraph of `ranges` (the story's paragraphs, in order), read in + /// one pass over the story. Empty when the story holds no endnotes, anchored objects or + /// cross-references. + fn before_paragraphs(story: &Story, ranges: &[Range]) -> Vec { + if story.endnotes.is_empty() && story.objects.is_empty() && story.xrefs.is_empty() { + return Vec::new(); + } + let mut total = Self::default(); + ranges + .iter() + .map(|r| { + let before = total; + let m = story.text.get(r.clone()).map_or_else(Self::default, Self::of); + total = Self { endnotes: total.endnotes + m.endnotes, objects: total.objects + m.objects, xrefs: total.xrefs + m.xrefs }; + before + }) + .collect() + } } fn paragraph_substitution(input: SubstitutionInput<'_>) -> SubstCtx { - let SubstitutionInput { doc, story, range: prange, props: pp, frame: cur_frame, opts, var_story, var_cache, notes } = input; + let SubstitutionInput { doc, story, range: prange, props: pp, frame: cur_frame, opts, var_story, var_cache, notes, marks } = input; let var_values = if var_story { let page = opts.page.or_else(|| cur_frame.and_then(|f| f.page)); // A parent page itself (not composed for one of the pages it applies to). @@ -907,13 +1372,13 @@ fn paragraph_substitution(input: SubstitutionInput<'_>) -> SubstCtx { }; if !story.endnotes.is_empty() { // Endnote reference numbers continue through the document. - let first = doc.endnote_start(story.id).saturating_add(story.text[..prange.start].matches(designcraft_doc::ENDNOTE_REF).count() as u32); + let first = doc.endnote_start(story.id).saturating_add(u32::try_from(marks.endnotes).unwrap_or(u32::MAX)); for (k, (i, _)) in story.text[prange.clone()].match_indices(designcraft_doc::ENDNOTE_REF).enumerate() { sub.notes.insert(prange.start + i, doc.endnote_options.label(first.saturating_add(k as u32))); } } if !story.objects.is_empty() { - let before = story.text[..prange.start].matches(designcraft_doc::OBJECT_MARK).count(); + let before = marks.objects; for (k, (i, _)) in story.text[prange.clone()].match_indices(designcraft_doc::OBJECT_MARK).enumerate() { let Some(o) = story.objects.get(before + k) else { continue }; let (w, h) = o.size(); @@ -926,7 +1391,7 @@ fn paragraph_substitution(input: SubstitutionInput<'_>) -> SubstCtx { } } if !story.xrefs.is_empty() { - sub.xrefs = xref::texts_in(doc, story, prange.clone(), opts.xrefs.as_deref()); + sub.xrefs = xref::texts_after(doc, story, prange.clone(), marks.xrefs, opts.xrefs.as_deref()); } if notes.active() { notes.number_refs(doc, prange.clone(), cur_frame.and_then(|f| f.page), &mut sub); @@ -1028,6 +1493,9 @@ fn frame_columns_and_text(frames: &[FrameSpec], direction: designcraft_doc::Text } struct ParagraphProgressInput<'a> { + /// Nothing is left to lay: the rest of the story is in place, or the pass is abandoned + /// ([`reuse::Pass::step`]). + done: bool, paragraph: usize, count: usize, balance_frames: usize, @@ -1047,7 +1515,10 @@ enum ParagraphProgress { } fn paragraph_progress(input: ParagraphProgressInput<'_>) -> ParagraphProgress { - let ParagraphProgressInput { paragraph, count, balance_frames, trial, limits, cursor, columns, frames, out, may_retry } = input; + let ParagraphProgressInput { done, paragraph, count, balance_frames, trial, limits, cursor, columns, frames, out, may_retry } = input; + if done { + return ParagraphProgress::Complete; + } if paragraph < count { return ParagraphProgress::Continue; } @@ -1437,8 +1908,14 @@ fn position_line(input: PositionLineInput<'_, '_>) -> LinePosition { if cur.last_baseline.is_some() { baseline += cur.last_reference - reference; } - let grid = f.grid.filter(|&(_, inc)| { - inc > 0.0 && inc.is_finite() && (pp.grid_align == GridAlign::AllLines || (pp.grid_align == GridAlign::FirstLineOnly && line_no == 0)) + // A step so small that the column holds more steps than an f64 can count is no grid: the + // line is placed as it is without one. + let countable = |g_start: f64, inc: f64| [baseline, col.y0, col.y1].iter().all(|y| ((y - g_start) / inc).is_finite()); + let grid = f.grid.filter(|&(g_start, inc)| { + inc > 0.0 + && inc.is_finite() + && countable(g_start, inc) + && (pp.grid_align == GridAlign::AllLines || (pp.grid_align == GridAlign::FirstLineOnly && line_no == 0)) }); if let Some((g_start, inc)) = grid { let n = pp.grid_gyoudori.min(grid::MAX_GYOUDORI); @@ -2671,6 +3148,40 @@ fn finish_paragraph(input: ParagraphFinishInput<'_>) -> ParagraphFinish { } fn compose_with_db(doc: &Document, story: &Story, frames: &[FrameSpec], opts: &ComposeOptions, db: &FontDb) -> ComposedStory { + compose_run(doc, story, frames, opts, db, None, false).map(|(out, _)| out).unwrap_or_default() +} + +/// [`compose`], leaving a trace for composing the story again after an edit when it can +/// ([`reuse`]). With `before` (the story before an edit, its composition and trace), only the +/// paragraphs the edit can change are composed, when the trace covers the edit. +pub(crate) fn compose_traced( + doc: &Document, + story: &Story, + frames: &[FrameSpec], + opts: &ComposeOptions, + before: Option>, +) -> (ComposedStory, Option) { + let db = FontDb::global(); + if before.is_some() + && let Some(done) = compose_run(doc, story, frames, opts, db, before.as_ref(), true) + { + return done; + } + compose_run(doc, story, frames, opts, db, None, true).unwrap_or_default() +} + +/// Compose `story` into `frames`, from its start or from what `before` holds for it; with +/// `traced`, also give the trace when the composition can leave one. `None` only with `before`: +/// its trace does not cover the edit, so the story has to be composed from its start. +fn compose_run( + doc: &Document, + story: &Story, + frames: &[FrameSpec], + opts: &ComposeOptions, + db: &FontDb, + before: Option<&reuse::Reuse<'_>>, + traced: bool, +) -> Option<(ComposedStory, Option)> { let db = &db.scoped(doc.font_scope); let mut out = ComposedStory { story: story.id, rev: story.rev, text_len: story.text.len(), ..Default::default() }; let mut styles_tab: Vec = Vec::new(); @@ -2699,6 +3210,8 @@ fn compose_with_db(doc: &Document, story: &Story, frames: &[FrameSpec], opts: &C let mut list_counter = ListCounter::default(); // Named lists number independently of layout: one pass up front, for the labels. let named_labels = named_list_labels(doc, story, ¶_ranges, &deleted); + // Endnote, anchored-object and cross-reference marks before each paragraph, for their numbers. + let marks_before = MarkCounts::before_paragraphs(story, ¶_ranges); // Border and shading of each paragraph set, drawn once the lines are in place. let mut boxes: Vec> = vec![None; np]; // Keep options: paragraphs are re-laid from a snapshot when a keep is violated, either forced @@ -2737,6 +3250,17 @@ fn compose_with_db(doc: &Document, story: &Story, frames: &[FrameSpec], opts: &C // and in split columns. let mut span_paras = vec![false; np]; let mut split_paras = vec![false; np]; + // Each paragraph's Align to Baseline Grid (vertical justification moves grid-aligned lines by + // whole grid steps). + let mut grid_paras = vec![GridAlign::None; np]; + // Composing again after an edit starts at the paragraph above it ([`reuse`]). The entries + // for the paragraphs before that one are never read: going back over a paragraph abandons the + // pass. + let plain = traced && reuse::plain(story, frames, opts, &named_labels, &deleted); + let (mut pass, start) = reuse::Pass::new(before, story, plain, reuse::Start { pi, cur, list_counter, info }, &mut out, &mut styles_tab); + (pi, cur, list_counter, info) = (start.pi, start.cur, start.list_counter, start.info); + snaps.extend((0..pi).map(|_| Snapshot::take(&out, &cur, &list_counter))); + note_snaps.resize(pi, (notes.num, notes.key, 0)); 'paras: while pi <= np { cur.pi = pi; cur.limits = Rc::clone(&limits); @@ -2747,8 +3271,12 @@ fn compose_with_db(doc: &Document, story: &Story, frames: &[FrameSpec], opts: &C note_snaps.truncate(pi); note_snaps.push((notes.num, notes.key, notes.placed.len())); info.truncate(pi); + // Whether nothing is left to lay: the rest of the story is in place, copied from its + // composition before an edit, or that composition turned out not to hold for this one. + let done = pass.step((pi, np), snaps.last(), &mut out, &mut styles_tab, &mut info); // A balancing trial whose band ran past its frame: re-lay the band with more room. - if trial.as_ref().is_some_and(|t| cur.fi > t.key.0) + if !done + && trial.as_ref().is_some_and(|t| cur.fi > t.key.0) && let Some(j) = trial_failed(&mut trial, &mut limits, balance_runs < balance_budget) { balance_runs += 1; @@ -2757,6 +3285,7 @@ fn compose_with_db(doc: &Document, story: &Story, frames: &[FrameSpec], opts: &C continue 'paras; } match paragraph_progress(ParagraphProgressInput { + done, paragraph: pi, count: np, balance_frames, @@ -2842,7 +3371,10 @@ fn compose_with_db(doc: &Document, story: &Story, frames: &[FrameSpec], opts: &C var_story, var_cache: &mut var_cache, notes: &mut notes, + marks: marks_before.get(pi).copied().unwrap_or_default(), }); + #[cfg(test)] + reuse::SHAPED.with(|n| n.set(n.get() + 1)); let shaped = shape_paragraph(ParagraphShapeInput { db, doc, @@ -2896,6 +3428,7 @@ fn compose_with_db(doc: &Document, story: &Story, frames: &[FrameSpec], opts: &C // it, a paragraph moves on to the next sub-column. let split_cfg = SplitCfg::of(&pp); split_paras[pi] = split_cfg.is_some(); + grid_paras[pi] = pp.grid_align; if cur.split.is_some_and(|s| Some(s.cfg) != split_cfg) { cur.split = None; } @@ -3114,17 +3647,21 @@ fn compose_with_db(doc: &Document, story: &Story, frames: &[FrameSpec], opts: &C cur.pending += if spans_in_current_frame || ends_split { pp.space_after.max(pp.span_space_after) } else { pp.space_after }; pi += 1; } - finish_composition(FinishInput { - doc, - story, - frames, - cols: &cols, - notes: &mut notes, - out: &mut out, - boxes: &boxes, - span_paras: &span_paras, - split_paras: &split_paras, - styles_tab, + pass.trace(reuse::plain_end(&span_paras, &split_paras, &boxes), &snaps, info).map(|trace| { + let out = finish_composition(FinishInput { + doc, + story, + frames, + cols: &cols, + notes: &mut notes, + out: &mut out, + boxes: &boxes, + span_paras: &span_paras, + split_paras: &split_paras, + grid_paras: &grid_paras, + styles_tab, + }); + (out, trace) }) } @@ -3138,12 +3675,15 @@ struct FinishInput<'a> { boxes: &'a [Option], span_paras: &'a [bool], split_paras: &'a [bool], + grid_paras: &'a [GridAlign], styles_tab: Vec, } fn finish_composition(input: FinishInput<'_>) -> ComposedStory { - let FinishInput { doc, story, frames, cols, notes, out, boxes, span_paras, split_paras, styles_tab } = input; + let FinishInput { doc, story, frames, cols, notes, out, boxes, span_paras, split_paras, grid_paras, styles_tab } = input; notes.finish(doc, story, frames, cols, out); + // The story byte of each anchored object's mark, found once for every frame that holds one. + let mut marks: Option> = None; // Ranges, content heights and vertical justification. for (fi, ft) in out.frames.iter_mut().enumerate() { let f = &frames[fi]; @@ -3159,7 +3699,12 @@ fn finish_composition(input: FinishInput<'_>) -> ComposedStory { let before: Vec = ft.tables.iter().map(|t| ft.lines.get(t.line).map_or(0.0, |l| l.baseline)).collect(); let spanned = ft.columns.len() > 1 && ft.lines.iter().any(|l| span_paras.get(l.para) == Some(&true)) || ft.lines.iter().any(|l| split_paras.get(l.para) == Some(&true)); - vertical_justify(ft, f, spanned, &doc.footnote_options); + let anchors: &[usize] = if ft.objects.is_empty() { + &[] + } else { + marks.get_or_insert_with(|| story.text.match_indices(designcraft_doc::OBJECT_MARK).map(|(i, _)| i).collect()) + }; + vertical_justify(ft, f, spanned, &doc.footnote_options, grid_paras, anchors); for (t, b) in ft.tables.iter_mut().zip(before) { let now = ft.lines.get(t.line).map_or(b, |l| l.baseline); t.shift(now - b); @@ -3568,7 +4113,7 @@ pub fn deleted_paras(story: &Story, ranges: &[Range]) -> Vec { } /// Where a placed paragraph sits (for keep resolution). -#[derive(Clone, Debug)] +#[derive(Clone, Debug, PartialEq)] struct ParaInfo { start: (usize, usize), /// Started at the top of a column (moving it can't help). @@ -4311,9 +4856,10 @@ fn wrap_slot( #[allow(clippy::too_many_arguments)] fn free_slots(f: &FrameSpec, col: Rect, y0: f64, y1: f64, desc: f64, size: f64, rtl: bool, line_start: usize) -> Vec<(f64, f64)> { // A shaped frame: the parts of the band its outline covers (a concave one can give several), - // descenders included: they stay inside the frame. + // descenders included: they stay inside the frame. The part of the band above the column's + // top is not tested, as in a rectangular frame: a Cap Height first line reaches above it. let mut free = match &f.outline { - Some(o) => o.intervals(col.x0, col.x1, y0, y1 + desc.max(0.0)), + Some(o) => o.intervals(col.x0, col.x1, y0.max(col.y0).min(y1), y1 + desc.max(0.0)), None => vec![(col.x0, col.x1)], }; let mut cut = f.outline.is_some(); @@ -4323,39 +4869,40 @@ fn free_slots(f: &FrameSpec, col: Rect, y0: f64, y1: f64, desc: f64, size: f64, let blocked = match ex.mode { WrapMode::JumpToNextColumn if y1 > r.y0 && r.x0 < col.x1 && r.x1 > col.x0 => return vec![], WrapMode::BoundingBox | WrapMode::Contour if overlaps_band => match &ex.contour { - Some(c) => c.band_extent(y0, y1), - None => Some((r.x0, r.x1)), + Some(c) => c.band_spans(y0, y1), + None => vec![(r.x0, r.x1)], }, - _ => None, + _ => Vec::new(), }; - let Some((a, b)) = blocked.filter(|&(a, b)| a < col.x1 && b > col.x0) else { continue }; - cut = true; - // One-sided wraps also block the column on the other side of the object. - let text_left = match ex.side { - WrapSide::LeftSide => Some(true), - WrapSide::RightSide => Some(false), - WrapSide::LargestArea => Some(r.x0 - col.x0 >= col.x1 - r.x1), - WrapSide::BothSides | WrapSide::TowardsSpine | WrapSide::AwayFromSpine => None, - }; - let (a, b) = match text_left { - Some(true) => (a, b.max(col.x1)), - Some(false) => (a.min(col.x0), b), - None => (a, b), - }; - let mut next = Vec::with_capacity(free.len() + 1); - for (fa, fb) in free { - if b <= fa || a >= fb { - next.push((fa, fb)); - continue; - } - if a > fa { - next.push((fa, a)); - } - if b < fb { - next.push((b, fb)); + for (a, b) in blocked.into_iter().filter(|&(a, b)| a < col.x1 && b > col.x0) { + cut = true; + // One-sided wraps also block the column on the other side of the object. + let text_left = match ex.side { + WrapSide::LeftSide => Some(true), + WrapSide::RightSide => Some(false), + WrapSide::LargestArea => Some(r.x0 - col.x0 >= col.x1 - r.x1), + WrapSide::BothSides | WrapSide::TowardsSpine | WrapSide::AwayFromSpine => None, + }; + let (a, b) = match text_left { + Some(true) => (a, b.max(col.x1)), + Some(false) => (a.min(col.x0), b), + None => (a, b), + }; + let mut next = Vec::with_capacity(free.len() + 1); + for (fa, fb) in free { + if b <= fa || a >= fb { + next.push((fa, fb)); + continue; + } + if a > fa { + next.push((fa, a)); + } + if b < fb { + next.push((b, fb)); + } } + free = next; } - free = next; } if cut { free.retain(|(a, b)| b - a >= size * 1.5); @@ -5483,8 +6030,17 @@ fn rule_decos(doc: &Document, r: &designcraft_doc::Rule, rect: Rect, (color, tin out } -/// `spanned`: a paragraph spans the frame's columns, so the lines move together. -fn vertical_justify(ft: &mut FrameText, f: &FrameSpec, spanned: bool, notes: &designcraft_doc::FootnoteOptions) { +/// `spanned`: a paragraph spans the frame's columns, so the lines move together. `anchors`: the +/// story byte of each anchored object's mark, by object index. +/// `grid_aligns`: each paragraph's Align to Baseline Grid setting. +fn vertical_justify( + ft: &mut FrameText, + f: &FrameSpec, + spanned: bool, + notes: &designcraft_doc::FootnoteOptions, + grid_aligns: &[GridAlign], + anchors: &[usize], +) { if ft.lines.is_empty() || f.opts.vertical_justification == VerticalJustification::Top { return; } @@ -5494,62 +6050,253 @@ fn vertical_justify(ft: &mut FrameText, f: &FrameSpec, spanned: bool, notes: &de // Per column (or all lines together). let ncols = if spanned { 1 } else { ft.columns.len().max(1) as u32 }; for c in 0..ncols { + let (rooms, follow) = wrap_rooms(ft, f, c, spanned, anchors); let idx: Vec = ft.lines.iter().enumerate().filter(|(_, l)| spanned || l.column == c).map(|(i, _)| i).collect(); - let (Some(&a), Some(_)) = (idx.first(), idx.last()) else { continue }; - let bottom = idx.iter().map(|&i| ft.lines[i].baseline + ft.lines[i].descent).fold(f64::NEG_INFINITY, f64::max); - let bottom = ft.tables.iter().filter(|t| spanned || t.column == c).map(|t| t.rect.y1).fold(bottom, f64::max); - let limit = ft + if idx.is_empty() { + continue; + } + let note_top = ft .notes .iter() .filter(|n| spanned || notes.span_columns || n.column == c) .map(|n| n.rect.y0 - notes.space_before) - .fold(f.area.y1, f64::min); - let space = limit - bottom; + .fold(f64::INFINITY, f64::min); + let limit = note_top.min(f.area.y1); + let tables = ft.tables.iter().filter(|t| spanned || t.column == c).map(|t| t.rect.y1).fold(f64::NEG_INFINITY, f64::max); + let last_baseline = idx.iter().map(|&i| ft.lines[i].baseline).fold(tables, f64::max); + let ink_bottom = idx.iter().map(|&i| ft.lines[i].baseline + ft.lines[i].descent).fold(tables, f64::max); + // The bottom of the text is the last baseline, as the top is the first baseline: the + // descenders of the last line hang below it, into the bottom inset and past it, in shaped + // frames as in rectangular ones. Above footnotes, and in vertical frames, the descenders + // stay inside the text area, as when the lines are fitted. + // `space`: the room under the bottom of the text. + let inside = f.vertical || note_top <= f.area.y1; + let space = if inside { limit - ink_bottom } else { limit - last_baseline }; + // Center and Bottom move the lines together: the nearest text wrap under them is the + // bottom of the room they move down into, so the room is the least any line has before a + // wrap stops it. Justify checks each row's room below. + let space = match f.opts.vertical_justification { + VerticalJustification::Justify => space, + _ => idx.iter().map(|&i| rooms[i]).fold(space, f64::min), + }; if space <= 0.0 { continue; } - let _ = a; - let before: Vec = idx.iter().map(|&i| ft.lines[i].baseline).collect(); - match f.opts.vertical_justification { - VerticalJustification::Center => idx.iter().for_each(|&i| ft.lines[i].baseline += space / 2.0), - VerticalJustification::Bottom => idx.iter().for_each(|&i| ft.lines[i].baseline += space), - VerticalJustification::Justify => { - // Segments of one line (beside an object) share a row and move together. - let rows: Vec = idx - .iter() - .scan((0usize, f64::NAN), |(row, prev), &i| { - let b = ft.lines[i].baseline; - if !prev.is_nan() && (b - *prev).abs() > 1e-9 { - *row += 1; - } - *prev = b; - Some(*row) - }) - .collect(); - let n = rows.last().copied().unwrap_or(0); - if n > 0 { - // Paragraph Spacing Limit: the space goes between paragraphs, up to the limit - // each; what is left spreads over every line (all of it with no limit). - let mut starts = vec![false; n + 1]; - for (&i, &k) in idx.iter().zip(&rows) { - if k > 0 && ft.lines[i].first_in_para { - starts[k] = true; - } - } - let gaps = starts.iter().filter(|s| **s).count(); - let limit = f.opts.vj_paragraph_spacing_limit.max(0.0); - let para = if gaps > 0 && limit > 0.0 { (space / gaps as f64).min(limit) } else { 0.0 }; + // Segments of one line (beside an object) share a row and move together. + let rows: Vec = idx + .iter() + .scan((0usize, f64::NAN), |(row, prev), &i| { + let b = ft.lines[i].baseline; + if !prev.is_nan() && (b - *prev).abs() > 1e-9 { + *row += 1; + } + *prev = b; + Some(*row) + }) + .collect(); + let n = rows.last().copied().unwrap_or(0); + // Paragraph Spacing Limit: with Justify the space goes between paragraphs, up to the limit + // each; what is left spreads over every line (all of it with no limit). + let mut starts = vec![false; n + 1]; + for (&i, &k) in idx.iter().zip(&rows) { + if k > 0 && ft.lines[i].first_in_para { + starts[k] = true; + } + } + let gaps = starts.iter().filter(|s| **s).count(); + let para_limit = f.opts.vj_paragraph_spacing_limit.max(0.0); + // How far each row moves when the text takes `space` more room. + let shifts = |space: f64| -> Vec { + match f.opts.vertical_justification { + VerticalJustification::Center => vec![space / 2.0; n + 1], + VerticalJustification::Bottom => vec![space; n + 1], + VerticalJustification::Justify if n > 0 => { + let para = if gaps > 0 && para_limit > 0.0 { (space / gaps as f64).min(para_limit) } else { 0.0 }; let per = (space - para * gaps as f64) / n as f64; let mut shift = vec![0.0; n + 1]; for k in 1..=n { shift[k] = shift[k - 1] + per + if starts[k] { para } else { 0.0 }; } - for (&i, &k) in idx.iter().zip(&rows) { - ft.lines[i].baseline += shift[k]; + shift + } + _ => vec![0.0; n + 1], + } + }; + // Only the last row's descenders hang below the bottom of the text: an earlier line whose + // ink reaches below the last baseline (tight leading) isn't moved past the text area. + // In a shaped frame each moved line's slot stays inside the outline from its top down to + // its baseline: a frame that narrows towards the bottom holds the text higher. Every moved + // line's descenders may cross the outline, as the last line's do below the bottom of the + // text; above footnotes, and in vertical frames, they stay inside. + let in_outline = |l: &Line, dy: f64| match &f.outline { + Some(o) => { + let b = l.baseline + dy; + let desc = if inside { l.descent.max(0.0) } else { 0.0 }; + let tol = 1e-6; + o.intervals(l.x0, l.x1, (b - l.ascent).max(f.area.y0).min(b), b + desc).iter().any(|&(a, z)| a <= l.x0 + tol && z >= l.x1 - tol) + } + None => true, + }; + // Each row moves no further than a text wrap under it allows. An object that moves with its + // anchor's row (Justify) lets a later row move its room plus how far the object moves. + let mut row_of = vec![None; ft.lines.len()]; + for (&i, &k) in idx.iter().zip(&rows) { + row_of[i] = Some(k); + } + let follow: Vec<(usize, usize, f64, f64)> = follow + .iter() + .filter_map(|&(i, a, room, pin)| Some((row_of.get(i).copied().flatten()?, row_of.get(a).copied().flatten()?, room.max(0.0), pin))) + .collect(); + // The object moves only once its anchor's row has moved `pin`. + let clear = |shift: &[f64]| { + idx.iter().zip(&rows).all(|(&i, &k)| shift[k] <= rooms[i].max(0.0) + 1e-9) + && follow.iter().all(|&(k, m, room, pin)| shift[k] <= room + (shift[m] - pin).max(0.0) + 1e-9) + }; + // The lowest lines are tested first: they are the ones a narrowing outline stops. + let fits = |shift: &[f64]| { + idx.iter().zip(&rows).rev().all(|(&i, &k)| { + let l = &ft.lines[i]; + shift[k] <= 0.0 || ((k == n || l.baseline + l.descent + shift[k] <= limit + 1e-9) && in_outline(l, shift[k])) + }) && clear(shift) + }; + // The room in 0..=`top` at which a moved line's band (from its top down to its baseline, or + // to its descent where `inside`), widened by the outline's inset, reaches one of the + // outline's corner heights: between two of these each line's fit changes only along the + // outline's straight edges. Empty when there are more than `MAX_BAND_BREAKS`. + const MAX_BAND_BREAKS: usize = 256; + let band_breaks = |o: &FrameOutline, top: f64| -> Vec { + let corners = o.corner_heights(); + let d = o.inset(); + // Each row's shift is linear in the room, apart from Justify's turn where the space + // between paragraphs reaches the Paragraph Spacing Limit. + let mut knots = vec![0.0, top]; + let turn = gaps as f64 * para_limit; + if f.opts.vertical_justification == VerticalJustification::Justify && turn > 0.0 && turn < top { + knots.insert(1, turn); + } + let at: Vec> = knots.iter().map(|&c| shifts(c)).collect(); + let mut out = Vec::new(); + for (&i, &k) in idx.iter().zip(&rows) { + let l = &ft.lines[i]; + let desc = if inside { l.descent.max(0.0) } else { 0.0 }; + for &y in &corners { + for v in [y + d - (l.baseline - l.ascent), y - d - (l.baseline + desc)] { + for (c, s) in knots.windows(2).zip(at.windows(2)) { + let (s0, s1) = (s[0][k], s[1][k]); + if s1 > s0 && v > s0 && v < s1 { + out.push(c[0] + (v - s0) * (c[1] - c[0]) / (s1 - s0)); + } + } + } + if out.len() > MAX_BAND_BREAKS { + return Vec::new(); } } } - _ => {} + out + }; + // In a rectangular frame fit decreases monotonically as the shift grows. A shaped + // frame can narrow and widen again, so scan from the largest shift before refining the + // first fitting interval. The scan takes even steps, the band breaks and a room on each + // side of every band break, so a band that fits over less room than one step is found + // too. This also bounds the room used for baseline-grid quantization and preserves + // clearance from fixed and anchor-following wraps. + let most_room = |top: f64| -> f64 { + if fits(&shifts(top)) { + return top; + } + let (mut lo, mut hi) = if let Some(o) = &f.outline { + let steps = top.ceil().clamp(64.0, 512.0) as usize; + // Each try is marked when it is a band break; only the gaps next to a break get a + // try in their middle. + let mut marked: Vec<(f64, bool)> = (0..steps).map(|j| (top * j as f64 / steps as f64, false)).collect(); + marked.extend(band_breaks(o, top).into_iter().map(|c| (c, true))); + marked.push((top, false)); + marked.sort_by(|a, b| a.0.total_cmp(&b.0)); + marked.dedup_by(|a, b| { + let same = (a.0 - b.0).abs() < 1e-9; + b.1 |= same && a.1; + same + }); + let mut tries: Vec = marked.windows(2).filter(|w| w[0].1 || w[1].1).map(|w| (w[0].0 + w[1].0) / 2.0).collect(); + tries.extend(marked.iter().map(|m| m.0)); + tries.sort_by(f64::total_cmp); + let mut found = (0.0, top); + for w in tries.windows(2).rev() { + if fits(&shifts(w[0])) { + found = (w[0], w[1]); + break; + } + } + found + } else { + (0.0, top) + }; + for _ in 0..60 { + let mid = (lo + hi) / 2.0; + if fits(&shifts(mid)) { + lo = mid; + } else { + hi = mid; + } + } + lo + }; + // Lines aligned to the baseline grid move by whole grid steps, so they stay on the grid. + // With Justify only the last row has to land on the grid (the first row doesn't move). + let on_grid = |i: usize| { + let line = &ft.lines[i]; + match grid_aligns.get(line.para) { + Some(GridAlign::AllLines) => true, + Some(GridAlign::FirstLineOnly) => line.first_in_para, + _ => false, + } + }; + let center = f.opts.vertical_justification == VerticalJustification::Center; + let step = f.grid.map(|(_, inc)| inc).filter(|inc| *inc > 0.0 && inc.is_finite()).filter(|_| match f.opts.vertical_justification { + VerticalJustification::Justify => idx.iter().zip(&rows).any(|(&i, &k)| k == n && on_grid(i)), + _ => idx.iter().any(|&i| on_grid(i)), + }); + let shift = match step { + None => shifts(most_room(space)), + // A step so small that the room holds more steps than an f64 can count: the lines take + // the room as they do without a grid, and stay within one step of a grid line. + Some(inc) if !(space / inc).is_finite() => shifts(most_room(space)), + Some(inc) => { + // The room one grid step takes: Center moves the lines by half the room. + let unit = if center { 2.0 * inc } else { inc }; + let room = most_room(if center { 2.0 * space } else { space }); + // The last baseline stays above the bottom of the text, and the rows above it fit. + let most = (space / inc + 1e-9).floor().min((room / unit + 1e-9).floor()).max(0.0); + // Bottom and Justify take the lowest grid line, Center the one nearest the middle. + let target = if center { (space / 2.0 / inc).round().min(most) } else { most }; + // A shaped frame can narrow and widen again, so the target step may not fit: take + // the fitting step nearest it, up to `most` (the lower one on a tie, and no step + // when that is as near), and leave the lines in place when none within + // `MAX_GRID_TRIES` steps of it fits. + const MAX_GRID_TRIES: usize = 512; + let mut steps = 0.0; + for d in 0..MAX_GRID_TRIES { + let (below, above) = (target - d as f64, target + d as f64); + if below <= 0.0 { + break; + } + if fits(&shifts(below * unit)) { + steps = below; + break; + } + if d > 0 && above <= most && fits(&shifts(above * unit)) { + steps = above; + break; + } + } + // With no step taken the lines stay put, even when Center's doubled step overflows. + shifts(if steps > 0.0 { steps * unit } else { 0.0 }) + } + }; + let before: Vec = idx.iter().map(|&i| ft.lines[i].baseline).collect(); + for (&i, &k) in idx.iter().zip(&rows) { + ft.lines[i].baseline += shift[k]; } // A drop cap moves with its line. for (&i, b) in idx.iter().zip(before) { @@ -5564,6 +6311,189 @@ fn vertical_justify(ft: &mut FrameText, f: &FrameSpec, spanned: bool, notes: &de } } +/// How far each line of column `c` (every column when `spanned`) may move down before a text +/// wrap stops it, by index in `ft.lines` (infinite without one); a table fragment's room counts +/// for its line. No line moves into a wrap under its slot. As when lines are set around a wrap, a +/// line's band runs from its top to its baseline, so a baseline may come down to a wrap's top; a +/// table fragment stops with its bottom there. A wrap without a contour counts by its bounding +/// box. Beside or under a contour, the line moves down only as far as its band stays clear of the +/// contour on its way down (to 0.01 pt). Only wraps that reach into a line's column (or the +/// columns it spans) count, as when the lines are set. An anchored object that moves with the +/// lines being justified (inline, above the line, or positioned from its anchor) is skipped, +/// except under Justify, where it moves with the row of its anchor's line: its wrap is taken where +/// the object sits before the lines move, and its rooms go in the second list as (line, anchor's +/// line, room, pin), so a line moves down at most the room plus how far the anchor's row moves +/// past `pin`. An object positioned from its anchor and kept within its column moves with its +/// anchor's row until it stops at the column's bottom, so in every mode a line moves down at most +/// the room under it plus the distance the object can move. Held at the column's top, the object +/// moves only after its anchor's row has moved `pin` (0 for the other objects), and until then a +/// line keeps the whole room. Justify keeps the first row in place, so its room stays infinite. `anchors` holds the story byte of each anchored object's mark, by object index. +fn wrap_rooms(ft: &FrameText, f: &FrameSpec, c: u32, spanned: bool, anchors: &[usize]) -> (Vec, Vec<(usize, usize, f64, f64)>) { + const EPS: f64 = 1e-6; + // One-sided wraps also block the column on the other side of the object: the x-range wrap + // `e` keeps text out of in column `col`, from the object's x-range `a..b` there (None when that + // range misses the column). + let sided = |e: &Exclusion, col: Rect, (a, b): (f64, f64)| -> Option<(f64, f64)> { + let r = e.rect; + (a < col.x1 && b > col.x0).then_some(match e.side { + WrapSide::LeftSide => (a, f64::INFINITY), + WrapSide::RightSide => (f64::NEG_INFINITY, b), + WrapSide::LargestArea if r.x0 - col.x0 >= col.x1 - r.x1 => (a, f64::INFINITY), + WrapSide::LargestArea => (f64::NEG_INFINITY, b), + WrapSide::BothSides | WrapSide::TowardsSpine | WrapSide::AwayFromSpine => (a, b), + }) + }; + // The x-range a wrap under the text keeps it out of in column `col`; None when text may stay beside it. + let blocked = |e: &Exclusion, col: Rect| -> Option<(f64, f64)> { + let r = e.rect; + match e.mode { + WrapMode::None => None, + WrapMode::JumpObject | WrapMode::JumpToNextColumn => (r.x0 < col.x1 && r.x1 > col.x0).then_some((f64::NEG_INFINITY, f64::INFINITY)), + WrapMode::BoundingBox | WrapMode::Contour => sided(e, col, (r.x0, r.x1)), + } + }; + let in_col = |k: u32| spanned || k == c; + let justify = f.opts.vertical_justification == VerticalJustification::Justify; + // The object whose mark is at each story byte, placed on one of these lines (the first one + // listed). + let mut by_anchor = HashMap::new(); + for o in ft.objects.iter().filter(|o| ft.lines.get(o.line).is_some_and(|l| in_col(l.column))) { + if let Some(&a) = anchors.get(o.index) { + by_anchor.entry(a).or_insert(o); + } + } + // An own-story anchored object whose anchor is on one of these lines and whose position + // follows its line moves with the text: the index in `ft.lines` of its anchor's line, how + // much lower the object was when the wrap was taken (an earlier pass placed the object after + // moving the lines), and, for one kept within its column, how far its line moves before the + // object leaves the column's top and how far the object then moves before it stops at the + // column's bottom (none and infinite for the others). + let moves_with_text = |e: &Exclusion| -> Option<(usize, f64, f64, f64)> { + let o = *by_anchor.get(&e.after?)?; + let l = ft.lines.get(o.line)?; + let now = l.baseline; + let dy = e.anchor_baseline.map_or(0.0, |b| b - now); + match &o.object.position { + designcraft_doc::AnchorPosition::Inline { .. } | designcraft_doc::AnchorPosition::AboveLine { .. } => { + Some((o.line, dy, 0.0, f64::INFINITY)) + } + designcraft_doc::AnchorPosition::Custom { y_relative, keep_within_column, y_offset, object_point, .. } + if *y_relative == designcraft_doc::anchored::AnchorRelative::Anchor => + { + if !keep_within_column { + return Some((o.line, dy, 0.0, f64::INFINITY)); + } + // Placed as the lines' final positions place it: from its anchor's baseline, + // held between the column's top and bottom. + let col = ft.columns.get(l.column as usize).copied().unwrap_or(f.area); + let h = o.size.1; + let ofy = [0.0, 0.5, 1.0][(*object_point / 3).min(2) as usize]; + let (lo, hi) = (col.y0, (col.y1 - h).max(col.y0)); + let place = |b: f64| b + y_offset - h * ofy; + let raw = place(now); + let y = raw.clamp(lo, hi); + let then = e.anchor_baseline.map_or(y, |b| place(b).clamp(lo, hi)); + Some((o.line, then - y, (lo - raw).max(0.0), (hi - y).max(0.0))) + } + designcraft_doc::AnchorPosition::Custom { .. } => None, + } + }; + // Each wrap's object is looked up once, not for every line. + let moving: Vec> = f.exclusions.iter().map(moves_with_text).collect(); + // Justify keeps the first row (its segments and a table on them) in place, so wraps under it + // set no limit. + let first = ft.lines.iter().find(|l| in_col(l.column)).map(|l| l.baseline); + let fixed = |line: usize| justify && ft.lines.get(line).zip(first).is_some_and(|(l, b)| (l.baseline - b).abs() <= 1e-9); + // (line, story byte, column, slot x-range, top, bottom) of each line (its band runs from its + // top to its baseline) and table fragment. + let lines = ft + .lines + .iter() + .enumerate() + .filter(|(_, l)| in_col(l.column)) + .map(|(i, l)| (i, l.range.start, l.column, l.x0, l.x1, l.baseline - l.ascent, l.baseline)); + let tables = ft.tables.iter().filter(|t| in_col(t.column)).map(|t| (t.line, t.anchor, t.column, t.rect.x0, t.rect.x1, t.rect.y0, t.rect.y1)); + let mut rooms = vec![f64::INFINITY; ft.lines.len()]; + let mut follow = Vec::new(); + for (line, start, k, x0, x1, top, bottom) in lines.chain(tables) { + let Some(&before) = rooms.get(line) else { continue }; + if fixed(line) { + continue; + } + let mut room = before; + // A line that spans columns reaches past its own column. + let col = ft.columns.get(k as usize).copied().unwrap_or(f.area); + let col = Rect { x0: col.x0.min(x0), x1: col.x1.max(x1), ..col }; + let meets = |(a, b): (f64, f64)| a < x1 - EPS && b > x0 + EPS; + for (e, &anchor) in f.exclusions.iter().zip(&moving).filter(|(e, _)| e.wraps_line(start)) { + // Center and Bottom move every row as far: only an object kept within its column, which + // can stop at the column's edges, holds the lines back. + if anchor.is_some_and(|(_, _, _, slack)| slack == f64::INFINITY) && !justify { + continue; + } + // The wrap where its object sits before the lines move (moved up by `dy`), and how + // far it lets this line move down (relative to its anchor's row for an object that + // moves with the text). + let dy = anchor.map_or(0.0, |(_, dy, _, _)| dy); + let cap = if anchor.is_some() { f64::INFINITY } else { room }; + let mut room_e = f64::INFINITY; + let r = Rect { y0: e.rect.y0 - dy, y1: e.rect.y1 - dy, ..e.rect }; + if let (WrapMode::BoundingBox | WrapMode::Contour, Some(contour)) = (e.mode, &e.contour) + && r.y1 > top + && sided(e, col, (r.x0, r.x1)).is_some_and(meets) + { + // A contour beside or under this line whose box reaches the line's slot (the + // contour stays inside its box). Moved down by `d`, the line's band sweeps from its + // top to its baseline plus `d`; the parts of the contour there only grow with `d`, + // so the furthest clear move is found by bisection to 0.01 pt. As when the line is + // set, the gaps between parts of the contour stay open. + let hits = |d: f64| contour.band_spans(top + dy, bottom + d + dy).into_iter().any(|x| sided(e, col, x).is_some_and(meets)); + let (mut lo, mut hi) = ((r.y0 - bottom).max(0.0), (r.y1 - top).min(f.area.y1 - bottom).min(cap)); + if lo < hi && hits(hi) { + if hits(lo) { + hi = lo; + } + for _ in 0..64 { + if hi - lo <= 0.01 { + break; + } + let mid = (lo + hi) / 2.0; + if hits(mid) { + hi = mid; + } else { + lo = mid; + } + } + room_e = lo; + } + } else if r.y0 >= bottom - EPS { + // A wrap at or under this line. + if blocked(e, col).is_some_and(meets) { + room_e = r.y0 - bottom; + } + } + match anchor { + // An object kept within its column moves once its line has moved `pin` (to leave + // the column's top) and stops after moving `slack` (at the column's bottom). + Some((a, _, pin, slack)) if room_e.is_finite() => { + if room_e >= pin { + if justify { + follow.push((line, a, room_e, pin)); + } + room = room.min(room_e + slack); + } else { + room = room.min(room_e); + } + } + Some(_) => {} + None => room = room.min(room_e), + } + } + rooms[line] = room; + } + (rooms, follow) +} + // ---------- caret and hit testing (Type tool) ---------- /// Two stacked glyphs this far apart in `y` sit on different rows (warichu). diff --git a/crates/compose/src/outline.rs b/crates/compose/src/outline.rs index bfc709710..dc7d97ac3 100644 --- a/crates/compose/src/outline.rs +++ b/crates/compose/src/outline.rs @@ -59,11 +59,32 @@ impl FrameOutline { Some(FrameOutline { edges, inset }) } + /// The outline of `item`'s path with its corner options applied, or None when that is the + /// item's own rectangle. The composer and the Properties panel's one Inset field both use it. + pub fn of_item(item: &designcraft_doc::Item, inset: f64) -> Option { + let bp = if item.corners.is_none() { item.path.to_bezpath() } else { designcraft_geom::corners::apply(&item.path, &item.corners) }; + FrameOutline::new(&bp, inset) + } + /// The outline mapped by `xf` (into a vertical frame's turned box). pub fn transformed(&self, xf: Affine) -> FrameOutline { FrameOutline { edges: self.edges.iter().map(|&(a, b)| (xf * a, xf * b)).collect(), inset: self.inset } } + /// The distance kept between text and the outline. + pub fn inset(&self) -> f64 { + self.inset + } + + /// The heights of the outline's corners, sorted and without repeats: the inside intervals of a + /// scanline change linearly between two of them. + pub fn corner_heights(&self) -> Vec { + let mut ys: Vec = self.edges.iter().map(|(a, _)| a.y).collect(); + ys.sort_by(f64::total_cmp); + ys.dedup_by(|a, b| (*a - *b).abs() < 1e-9); + ys + } + /// The parts of `[x0, x1]` inside the outline over the whole band `[y0, y1]`, at least the /// inset away from it: the inside intervals at every height of the band are intersected, and /// the inset is kept by testing the heights within the inset above and below the band, each diff --git a/crates/compose/src/placed.rs b/crates/compose/src/placed.rs index 33e4ff73c..0207f3af4 100644 --- a/crates/compose/src/placed.rs +++ b/crates/compose/src/placed.rs @@ -36,24 +36,42 @@ pub(crate) fn placements(doc: &Document, sid: StoryId, host: &mut dyn FnMut(Stor 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 }; - let composed = hosts.entry(owner).or_insert_with(|| host(owner)); - if let Some(p) = locate(doc, composed, fid) { + if let Some(p) = locate(doc, items, sid, fid, &mut hosts, host, 0) { out.push((fid, p)); } } out } -/// Where `cs` (a host story's composition) places item `fid`: in its frames' anchored objects, -/// footnotes and table cells. -fn locate(doc: &Document, cs: &ComposedStory, fid: ItemId) -> Option { +/// Where the host story of `fid`, an anchored frame of story `sid`, places it: in its frames' +/// anchored objects, footnotes and table cells. A host frame that is itself anchored is placed +/// the same way first, up to [`MAX_DEPTH`] hosts out. `items` is [`Document::anchored_items`]. +fn locate( + doc: &Document, + items: &[(StoryId, &Item)], + sid: StoryId, + fid: ItemId, + hosts: &mut HashMap>, + host: &mut dyn FnMut(StoryId) -> Arc, + depth: usize, +) -> Option { + if depth > MAX_DEPTH { + return None; + } + // A frame anchored in its own story would need its own composition to place it. + let owner = items.iter().find_map(|(owner, it)| (it.id == fid).then_some(*owner)).filter(|o| *o != sid)?; + let cs = hosts.entry(owner).or_insert_with(|| host(owner)).clone(); cs.frames.iter().find_map(|ft| { - let loc = doc.find(ft.frame)?; - let frame = doc.item_at(&loc)?; - let xf = in_frame(ft, doc.parent_xf(&loc) * doc.text_xf(frame), fid, 0)?; - Some(Placement { spread: loc.spread, xf }) + if let Some(loc) = doc.find(ft.frame) { + let frame = doc.item_at(&loc)?; + let xf = in_frame(ft, doc.parent_xf(&loc) * doc.text_xf(frame), fid, 0)?; + return Some(Placement { spread: loc.spread, xf }); + } + // The host frame is anchored too: find `fid` in it before placing the frame. + let local = in_frame(ft, Affine::IDENTITY, fid, 0)?; + let frame = items.iter().find_map(|(_, it)| (it.id == ft.frame).then_some(*it))?; + let outer = locate(doc, items, owner, ft.frame, hosts, host, depth + 1)?; + Some(Placement { spread: outer.spread, xf: outer.xf * doc.text_xf(frame) * local }) }) } diff --git a/crates/compose/src/reuse.rs b/crates/compose/src/reuse.rs new file mode 100644 index 000000000..4ac5a078c --- /dev/null +++ b/crates/compose/src/reuse.rs @@ -0,0 +1,738 @@ +//! Composing an edited story from the composition it had before the edit. +//! +//! A composition that laid every paragraph once leaves a [`Trace`]: the state it had before each +//! paragraph. Composing the story again after an edit starts at the paragraph before the first +//! changed one, in the state the trace holds for it and with the lines above it copied. It stops +//! at the first paragraph after the edit that it reaches in the state the trace holds for that +//! paragraph, and copies the lines from there on with their story offsets moved by the length of +//! the edit. The result is the composition a full pass over the edited story gives. +//! +//! Only plain stories are traced ([`plain`]): the features left out carry state between +//! paragraphs that the trace does not hold, or move lines after they are set. A composition that +//! goes back over a paragraph (keep options, column balancing, hyphenation across columns) +//! leaves no trace, and one that does so while it reuses a trace is abandoned for a full pass. + +use std::rc::Rc; + +use designcraft_doc::{CharRun, ListCounter, Story, VerticalJustification}; + +use crate::{Above, Band, ComposeOptions, ComposedStory, Cursor, FrameSpec, Line, ParaInfo, RunStyle, Snapshot}; + +#[cfg(test)] +thread_local! { + /// Paragraphs shaped on this thread (tests count the work an edit causes). + pub(crate) static SHAPED: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// The composition's state before a paragraph: the cursor, the list numbering, and how much of +/// the cursor's frame and of the run style table is filled. +#[derive(Clone, Debug)] +struct Mark { + fi: usize, + col: usize, + last_baseline: Option, + last_descent: f64, + last_reference: f64, + aki_below: Option, + pending: f64, + band: Band, + grid_next: Option<(f64, f64)>, + list_counter: ListCounter, + lines: usize, + decos: usize, + styles: usize, +} + +fn bits(v: Option) -> Option { + v.map(f64::to_bits) +} + +fn above_bits(a: Option) -> Option<[Option; 6]> { + a.map(|a| { + [ + Some(a.top.to_bits()), + Some(a.baseline.to_bits()), + Some(a.descent.to_bits()), + Some(a.reference.to_bits()), + bits(a.aki_below), + Some(a.pending.to_bits()), + ] + }) +} + +impl Mark { + /// The state `snap` holds with `styles` run styles in the table, or `None` when it has state + /// a mark does not hold (a split-column block, balanced column bottoms, tables). + fn of(snap: &Snapshot, styles: usize) -> Option { + let c = &snap.cur; + if c.split.is_some() || !c.limits.is_empty() || !c.split_limits.is_empty() || snap.tables != 0 { + return None; + } + Some(Mark { + fi: c.fi, + col: c.col, + last_baseline: c.last_baseline, + last_descent: c.last_descent, + last_reference: c.last_reference, + aki_below: c.aki_below, + pending: c.pending, + band: c.band, + grid_next: c.grid_next, + list_counter: snap.list_counter.clone(), + lines: snap.lines, + decos: snap.decos, + styles, + }) + } + + fn cursor(&self, pi: usize) -> Cursor { + Cursor { + fi: self.fi, + col: self.col, + last_baseline: self.last_baseline, + last_descent: self.last_descent, + last_reference: self.last_reference, + aki_below: self.aki_below, + pending: self.pending, + pi, + band: self.band, + limits: Rc::default(), + split: None, + split_limits: Rc::default(), + grid_next: self.grid_next, + } + } + + /// The mark with its paragraph numbers after the edit. + fn moved(&self, plan: &Plan) -> Mark { + let band = Band { para: plan.moved(self.band.para), tail: self.band.tail.map(|(p, c)| (plan.moved(p), c)), ..self.band }; + Mark { band, ..self.clone() } + } + + /// Whether composing on from `self` and from `other` sets the same lines. Numbers are + /// compared by their bits: a difference too small to show still changes what follows. + fn same(&self, other: &Mark) -> bool { + let (a, b) = (&self.band, &other.band); + self.fi == other.fi + && self.col == other.col + && bits(self.last_baseline) == bits(other.last_baseline) + && self.last_descent.to_bits() == other.last_descent.to_bits() + && self.last_reference.to_bits() == other.last_reference.to_bits() + && bits(self.aki_below) == bits(other.aki_below) + && self.pending.to_bits() == other.pending.to_bits() + && a.para == b.para + && a.line0 == b.line0 + && above_bits(a.above) == above_bits(b.above) + && a.tail == b.tail + && self.grid_next.map(|(x, y)| (x.to_bits(), y.to_bits())) == other.grid_next.map(|(x, y)| (x.to_bits(), y.to_bits())) + && self.list_counter == other.list_counter + && self.lines == other.lines + && self.decos == other.decos + && self.styles == other.styles + } +} + +/// What a composition leaves for composing the story again after an edit: its state before each +/// paragraph it laid (and after the last one), and where each paragraph sits. +#[derive(Debug)] +pub(crate) struct Trace { + marks: Vec, + info: Vec, +} + +/// A story as it was before an edit, its composition and that composition's trace. +#[derive(Clone, Copy)] +pub(crate) struct Reuse<'a> { + pub story: &'a Story, + pub composed: &'a ComposedStory, + pub trace: &'a Trace, +} + +/// How much of the composition before an edit holds for the edited story. +pub(crate) struct Plan { + /// The paragraph composing starts at. + pub resume: usize, + /// The first paragraph (numbered as in the edited story) that may take the lines it had + /// before the edit: the one before it is unchanged too. + pub rejoin: usize, + /// Paragraphs and bytes the edit added. + paras: isize, + bytes: isize, + /// The first paragraph the edit left as it was, numbered as before the edit. + old_tail: usize, +} + +impl Plan { + /// The number after the edit of paragraph `p` of the story before it. + fn moved(&self, p: usize) -> usize { + if p >= self.old_tail { p.wrapping_add_signed(self.paras) } else { p } + } + + /// The number before the edit of paragraph `pi` of the edited story's unchanged end. + fn before(&self, pi: usize) -> Option { + pi.checked_add_signed(self.paras.checked_neg()?) + } +} + +/// Whether a composition of `story` in `frames` can leave a trace, or use one. Footnotes, +/// endnotes, tables and anchored objects carry state of their own; named lists and tracked +/// deletions reach across paragraphs; vertical justification and column rules change a frame +/// after its lines are set; type on a path sizes its frame from the story; balanced columns are +/// laid more than once. +pub(crate) fn plain(story: &Story, frames: &[FrameSpec], opts: &ComposeOptions, labels: &[Option], deleted: &[bool]) -> bool { + story.notes.is_empty() + && story.endnotes.is_empty() + && story.objects.is_empty() + && story.tables.is_empty() + && opts.label.is_none() + && labels.iter().all(Option::is_none) + && !deleted.contains(&true) + && frames.iter().all(|f| { + let o = &f.opts; + o.vertical_justification == VerticalJustification::Top && !o.column_rule && o.path.is_none() && !(o.balance_columns && o.columns > 1) + }) +} + +/// Whether the paragraphs a composition laid are ones a trace covers: none spans or splits +/// columns (`span`, `split`, by paragraph) or has a border or shading (`boxes`), which are drawn +/// once every line is set. +pub(crate) fn plain_end(span: &[bool], split: &[bool], boxes: &[Option]) -> bool { + !span.contains(&true) && !split.contains(&true) && boxes.iter().all(Option::is_none) +} + +/// Bytes of text from the start of both run lists (in the order given) that have the same +/// character formats. +fn same_formats<'a>(mut old: impl Iterator, mut new: impl Iterator) -> usize { + let mut same = 0usize; + let (mut a, mut b): (Option<(&CharRun, usize)>, Option<(&CharRun, usize)>) = (None, None); + loop { + if a.is_none_or(|(_, left)| left == 0) { + a = old.find(|r| r.len > 0).map(|r| (r, r.len)); + } + if b.is_none_or(|(_, left)| left == 0) { + b = new.find(|r| r.len > 0).map(|r| (r, r.len)); + } + let (Some((ra, la)), Some((rb, lb))) = (a, b) else { return same }; + if ra.format != rb.format { + return same; + } + let step = la.min(lb); + same += step; + (a, b) = (Some((ra, la - step)), Some((rb, lb - step))); + } +} + +fn returns(text: &str) -> usize { + text.bytes().filter(|b| *b == b'\n').count() +} + +impl Reuse<'_> { + /// Where composing `new` (the story after the edit) starts and may stop, or `None` when the + /// edit changed something a trace does not cover. + pub(crate) fn plan(&self, new: &Story) -> Option { + let old = self.story; + if old.frames != new.frames + || old.direction != new.direction + || old.vertical != new.vertical + || old.optical_margin != new.optical_margin + || old.anchors != new.anchors + || old.xrefs != new.xrefs + || old.index_refs != new.index_refs + || old.editorial != new.editorial + { + return None; + } + let (o, n) = (old.text.as_bytes(), new.text.as_bytes()); + if old.paras.len() != returns(&old.text) + 1 || new.paras.len() != returns(&new.text) + 1 { + return None; + } + // The unchanged start: the same text in the same character formats, then whole paragraphs + // with the same paragraph formats. + let mut head = o.iter().zip(n).take_while(|(a, b)| a == b).count().min(same_formats(old.chars.iter(), new.chars.iter())); + while !new.text.is_char_boundary(head) { + head -= 1; + } + let whole = returns(new.text.get(..head)?); + let first = old.paras.iter().zip(&new.paras).take(whole).take_while(|(a, b)| a == b).count(); + if first < whole { + // A paragraph format changed above the first changed character. + head = match first.checked_sub(1) { + Some(k) => n.iter().enumerate().filter(|(_, b)| **b == b'\n').nth(k).map(|(i, _)| i + 1)?, + None => 0, + }; + } + // The unchanged end, which the unchanged start does not overlap. + let room = o.len().min(n.len()).checked_sub(head)?; + let mut tail = o + .iter() + .rev() + .zip(n.iter().rev()) + .take_while(|(a, b)| a == b) + .count() + .min(same_formats(old.chars.iter().rev(), new.chars.iter().rev())) + .min(room); + while !new.text.is_char_boundary(n.len() - tail) { + tail -= 1; + } + let after = returns(new.text.get(n.len() - tail..)?); + let after = old.paras.iter().rev().zip(new.paras.iter().rev()).take(after).take_while(|(a, b)| a == b).count(); + let (old_paras, new_paras) = (old.paras.len(), new.paras.len()); + Some(Plan { + // One paragraph above the first changed one: setting a paragraph reads the one after it. + resume: first.saturating_sub(1).min(self.trace.marks.len().checked_sub(1)?), + rejoin: new_paras.checked_sub(after)? + 1, + paras: isize::try_from(new_paras).ok()?.checked_sub(isize::try_from(old_paras).ok()?)?, + bytes: isize::try_from(n.len()).ok()?.checked_sub(isize::try_from(o.len()).ok()?)?, + old_tail: old_paras.checked_sub(after)?, + }) + } + + /// Put `out` and `styles` back as they were before paragraph `plan.resume`, and give the + /// cursor, list numbering and paragraph positions of that moment. `None` when the composition + /// before the edit does not match `out`'s frames. + pub(crate) fn restore(&self, plan: &Plan, out: &mut ComposedStory, styles: &mut Vec) -> Option<(Cursor, ListCounter, Vec)> { + let mark = self.trace.marks.get(plan.resume)?; + let before = self.composed; + if before.frames.len() != out.frames.len() || before.frames.iter().zip(&out.frames).any(|(a, b)| a.frame != b.frame) { + return None; + } + let info = self.trace.info.get(..plan.resume)?.to_vec(); + *styles = before.styles.get(..mark.styles)?.to_vec(); + for (i, (to, from)) in out.frames.iter_mut().zip(&before.frames).enumerate().take(mark.fi.saturating_add(1)) { + let (lines, decos) = if i < mark.fi { (from.lines.len(), from.decos.len()) } else { (mark.lines, mark.decos) }; + to.lines = from.lines.get(..lines)?.iter().map(|l| moved_line(l, 0, 0)).collect(); + to.decos = from.decos.get(..decos)?.to_vec(); + } + Some((mark.cursor(plan.resume), mark.list_counter.clone(), info)) + } + + /// At paragraph `pi` of the edited story, in the state `snap` with `styles` and `info` as + /// they are: when the composition before the edit was in that state before the same + /// paragraph, copy what it set from there on into `out`, `styles` and `info`, and say so. + /// + /// The copied lines keep their run-style indexes, so this needs `styles` to equal the old + /// table up to that point. A run style that the edit uses for the first time takes a new + /// index, and the story then composes on until the old composition added the same style at + /// the same index, or to its end. The result is the same; only the time differs. + pub(crate) fn rejoin( + &self, + plan: &Plan, + pi: usize, + snap: &Snapshot, + out: &mut ComposedStory, + styles: &mut Vec, + info: &mut Vec, + ) -> bool { + let before = self.composed; + let Some(k) = plan.before(pi) else { return false }; + let (Some(old), Some(new)) = (self.trace.marks.get(k), Mark::of(snap, styles.len())) else { return false }; + // The paragraph above is where it was, and no chain of keep-with-next paragraphs reaches + // back through it into the changed text. + let last = |v: &[ParaInfo], i: usize| i.checked_sub(1).and_then(|i| v.get(i).cloned()); + let same_above = matches!((last(&self.trace.info, k), last(info, pi)), (Some(a), Some(b)) if a == b && a.keep_with_next == 0); + if !same_above || info.len() != pi || !old.moved(plan).same(&new) || before.styles.get(..old.styles) != Some(styles.as_slice()) { + return false; + } + for (i, (to, from)) in out.frames.iter_mut().zip(&before.frames).enumerate().skip(old.fi) { + let (lines, decos) = if i == old.fi { (old.lines, old.decos) } else { (0, 0) }; + to.lines.extend(from.lines.get(lines..).unwrap_or_default().iter().map(|l| moved_line(l, plan.bytes, plan.paras))); + to.decos.extend(from.decos.get(decos..).unwrap_or_default().iter().cloned()); + } + out.overset_at = before.overset_at.map(|b| b.wrapping_add_signed(plan.bytes)); + styles.clone_from(&before.styles); + info.extend(self.trace.info.get(k..).unwrap_or_default().iter().cloned()); + true + } +} + +/// `line` with its story offsets and paragraph number moved, and without the keep-violation +/// flag, which is set again for the whole story once it is composed. +fn moved_line(line: &Line, bytes: isize, paras: isize) -> Line { + let at = |b: usize| b.wrapping_add_signed(bytes); + let mut l = Line { keep_violation: false, ..line.clone() }; + l.range = at(l.range.start)..at(l.range.end); + l.para = l.para.wrapping_add_signed(paras); + if bytes != 0 { + for g in &mut l.glyphs { + g.byte = at(g.byte); + } + } + if let Some(cap) = &mut l.drop_cap { + cap.end = at(cap.end); + } + l +} + +/// What one composition keeps for its trace, and what it reuses of the composition before an +/// edit. +pub(crate) struct Pass<'a> { + before: Option<(&'a Reuse<'a>, Plan)>, + /// The composition was to reuse the one before an edit and cannot: its result is not used. + abandoned: bool, + /// A trace is wanted and nothing rules one out so far. + traced: bool, + /// Run styles in the table before each paragraph. + styles: Vec, + /// The paragraph the next step should be at: another one means the layout went back over a + /// paragraph. + next: usize, + /// The paragraph the lines copied from before the edit start at. + rejoined: Option, +} + +/// Where a composition starts: the paragraph, the cursor, the list numbering and the positions +/// of the paragraphs above. +pub(crate) struct Start { + pub pi: usize, + pub cur: Cursor, + pub list_counter: ListCounter, + pub info: Vec, +} + +impl<'a> Pass<'a> { + /// The bookkeeping for composing `story`, and where to start. `traced`: a trace is wanted and + /// the story is [`plain`]. `fresh` is the start of the story. With `before`, `out` and + /// `styles` are filled with what holds from before the edit and the start is the paragraph + /// above the edit; when `before` cannot be used the pass is abandoned at its first step. + pub(crate) fn new( + before: Option<&'a Reuse<'a>>, + story: &Story, + traced: bool, + fresh: Start, + out: &mut ComposedStory, + styles: &mut Vec, + ) -> (Pass<'a>, Start) { + let mut pass = Pass { before: None, abandoned: false, traced, styles: Vec::with_capacity(story.paras.len() + 1), next: 0, rejoined: None }; + let Some(b) = before else { return (pass, fresh) }; + let resumed = traced.then(|| b.plan(story)).flatten().and_then(|plan| Some((b.restore(&plan, out, styles)?, plan))); + let Some(((cur, list_counter, info), plan)) = resumed else { + pass.abandoned = true; + return (pass, fresh); + }; + let pi = plan.resume; + // The counts for the paragraphs above are never read: their marks are kept as they are. + pass.styles.resize(pi, 0); + pass.next = pi; + pass.before = Some((b, plan)); + (pass, Start { pi, cur, list_counter, info }) + } + + /// Before paragraph `pi` of `count` is laid, in the state `snap`: whether nothing is left to + /// lay, because the rest of the story is in place (copied from the composition before the + /// edit into `out`, `styles` and `info`) or because the pass is abandoned. + pub(crate) fn step( + &mut self, + (pi, count): (usize, usize), + snap: Option<&Snapshot>, + out: &mut ComposedStory, + styles: &mut Vec, + info: &mut Vec, + ) -> bool { + self.styles.truncate(pi); + self.styles.push(styles.len()); + if pi != self.next { + // The layout went back over a paragraph. + self.traced = false; + self.abandoned |= self.before.is_some(); + } + self.next = pi + 1; + if self.abandoned { + return true; + } + if pi < count + && let (Some((before, plan)), Some(snap)) = (&self.before, snap) + && pi >= plan.rejoin + && before.rejoin(plan, pi, snap, out, styles, info) + { + self.rejoined = Some(pi); + return true; + } + false + } + + /// The trace of the finished composition, when it laid every paragraph once and `plain_end` + /// (no paragraph it laid uses something a trace does not cover): `snaps` holds the state + /// before each paragraph it laid itself, `info` every paragraph's position. The paragraphs + /// above the one a reusing composition started at keep the marks they had, and those after + /// the one it rejoined at the marks that followed before the edit. The outer `None` is for an + /// abandoned pass and for a reusing one that leaves no trace: the story has to be composed + /// from its start. + pub(crate) fn trace(self, plain_end: bool, snaps: &[Snapshot], info: Vec) -> Option> { + if self.abandoned { + return None; + } + let trace = if self.traced && plain_end { self.marks(snaps).map(|marks| Trace { marks, info }) } else { None }; + if self.before.is_some() && trace.is_none() { + return None; + } + Some(trace) + } + + fn marks(&self, snaps: &[Snapshot]) -> Option> { + let reused = self.before.as_ref(); + let start = reused.map_or(0, |(_, plan)| plan.resume); + let mut marks = Vec::with_capacity(snaps.len()); + if let Some((before, _)) = reused { + marks.extend(before.trace.marks.get(..start)?.iter().cloned()); + } + for (snap, styles) in snaps.iter().zip(&self.styles).skip(start) { + marks.push(Mark::of(snap, *styles)?); + } + if let (Some((before, plan)), Some(pi)) = (reused, self.rejoined) { + let k = plan.before(pi)?; + marks.extend(before.trace.marks.get(k + 1..)?.iter().map(|m| m.moved(plan))); + } + // Lines are only ever added to the cursor's frame, so the frames above it are complete. + marks.windows(2).all(|w| w[0].fi <= w[1].fi).then_some(marks) + } +} + +#[cfg(test)] +mod tests { + use designcraft_doc::build::NewDocument; + use designcraft_doc::{Align, Document, ItemId, ListType, ParaFormat, SpreadRef, StartParagraph, Story, StoryId, VerticalJustification}; + use designcraft_geom::Rect; + + use super::SHAPED; + use crate::Cache; + + const SENTENCE: &str = "The quick brown fox jumps over the lazy dog while the workbook keeps growing page by page."; + + /// A story of `paras` paragraphs of two to five lines, threaded through `frames` frames of 31 + /// lines each. + fn threaded(paras: usize, frames: usize) -> (Document, StoryId, Vec) { + let mut d = Document::new(&NewDocument::default()); + let lid = d.default_layer(); + let text = (0..paras).map(|i| vec![SENTENCE; 2 + i % 4].join(" ")).collect::>().join("\n"); + let rect = |i: usize| Rect::new(i as f64 * 600.0, 0.0, i as f64 * 600.0 + 540.0, 456.0); + let (first, sid) = d.add_text_frame(SpreadRef::Doc(0), rect(0), lid, &text, ParaFormat::default()).unwrap(); + let mut ids = vec![first]; + for i in 1..frames { + let (next, _) = d.add_text_frame(SpreadRef::Doc(0), rect(i), lid, "", ParaFormat::default()).unwrap(); + d.thread(ids[i - 1], next).unwrap(); + ids.push(next); + } + (d, sid, ids) + } + + /// What `f` returns and the paragraphs it shaped. + fn shaped(f: impl FnOnce() -> T) -> (T, usize) { + SHAPED.with(|n| n.set(0)); + let out = f(); + (out, SHAPED.with(|n| n.get())) + } + + /// Compose the edited story through `cache`, which holds its composition before the edit, and + /// check the result against composing it whole. Gives the paragraphs the cache shaped. + fn check(cache: &Cache, d: &Document, sid: StoryId, what: &str) -> usize { + let (cached, n) = shaped(|| cache.get(d, sid, None)); + let whole = Cache::new().get(d, sid, None); + assert_eq!(cached.frames.len(), whole.frames.len(), "{what}"); + for (fi, (a, b)) in cached.frames.iter().zip(&whole.frames).enumerate() { + assert_eq!(a.lines.len(), b.lines.len(), "{what}: lines in frame {fi}"); + for (li, (x, y)) in a.lines.iter().zip(&b.lines).enumerate() { + assert_eq!(format!("{x:?}"), format!("{y:?}"), "{what}: frame {fi} line {li}"); + } + } + assert!(format!("{cached:?}") == format!("{whole:?}"), "{what}: the composition differs from composing the story whole"); + n + } + + #[test] + fn a_typed_character_composes_the_paragraphs_around_it() { + for paras in [60, 240] { + let (mut d, sid, _) = threaded(paras, paras / 4); + let cache = Cache::new(); + let (first, whole) = shaped(|| cache.get(&d, sid, None)); + assert!(!first.is_overset()); + assert!(first.frames.iter().filter(|f| !f.lines.is_empty()).count() > paras / 12); + assert_eq!(whole, paras); + let len = d.story(sid).unwrap().len(); + for at in [10, len / 2, len - 1] { + d.story_mut(sid).unwrap().insert(at, "x"); + let n = check(&cache, &d, sid, "a typed character"); + assert!(n <= 3, "{n} of {paras} paragraphs composed for a character typed at {at}"); + } + } + } + + /// The preflight cache reads an unchanged composition through its base, while edits + /// composed in the reader keep their own incremental trace and never replace the base. + #[test] + fn a_read_through_cache_keeps_incremental_edits_local() { + use std::sync::Arc; + let (mut d, sid, _) = threaded(60, 15); + let original = d.clone(); + let base = Arc::new(Cache::new()); + let first = base.get(&original, sid, None); + let reader = Cache::over(Arc::clone(&base)); + assert!(Arc::ptr_eq(&reader.get(&d, sid, None), &first)); + d.story_mut(sid).unwrap().insert(10, "x"); + check(&reader, &d, sid, "first edit in reader"); + d.story_mut(sid).unwrap().insert(11, "y"); + let n = check(&reader, &d, sid, "second edit in reader"); + assert!(n <= 3, "reader shaped {n} paragraphs instead of reusing its trace"); + assert!(Arc::ptr_eq(&base.get(&original, sid, None), &first)); + assert!(base.composed_for(&d, sid).is_none()); + } + + #[test] + fn characters_typed_one_after_another_each_compose_the_paragraphs_around_them() { + let (mut d, sid, _) = threaded(80, 20); + let cache = Cache::new(); + cache.get(&d, sid, None); + let at = d.story(sid).unwrap().len() / 2; + for (i, c) in "one two\nthree".chars().enumerate() { + d.story_mut(sid).unwrap().insert(at + i, &c.to_string()); + let n = check(&cache, &d, sid, "typing"); + // A return adds a line, which moves the paragraphs below it in their frame: they are + // composed up to the end of the story. + assert!(c == '\n' || n <= 4, "{n} of 80 paragraphs composed for {c:?}"); + } + } + + #[test] + fn an_edit_that_moves_lines_composes_up_to_the_next_frame_the_text_starts_in() { + let (mut d, sid, _) = threaded(100, 24); + // Chapters of five paragraphs, each starting in the next frame. + let starts: Vec = + d.story(sid).unwrap().para_ranges().iter().enumerate().filter(|(i, _)| *i > 0 && i % 5 == 0).map(|(_, r)| r.start).collect(); + for at in starts { + d.story_mut(sid).unwrap().format_paras(at..at, |p| p.para.start_paragraph = Some(StartParagraph::NextFrame)); + } + let cache = Cache::new(); + let (first, whole) = shaped(|| cache.get(&d, sid, None)); + assert!(!first.is_overset()); + assert_eq!(whole, 100); + let at = d.story(sid).unwrap().para_ranges()[52].start + 20; + d.story_mut(sid).unwrap().insert(at, &format!(" {SENTENCE} {SENTENCE}")); + let n = check(&cache, &d, sid, "two more lines in a chapter"); + assert!(n <= 6, "{n} of 100 paragraphs composed for lines added to one chapter"); + } + + #[test] + fn edits_give_the_composition_of_the_edited_story() { + let (mut d, sid, _) = threaded(40, 12); + let original = d.clone(); + let cache = Cache::new(); + cache.get(&d, sid, None); + let edits: [(&str, fn(&mut Story)); 15] = [ + ("a character", |s| s.insert(s.len() / 2, "x")), + ("a return", |s| s.insert(s.len() / 2, "\n")), + ("a long insertion", |s| s.insert(s.len() / 3, &format!(" {SENTENCE} {SENTENCE} {SENTENCE}"))), + ("several paragraphs", |s| s.insert(s.len() / 3, &format!("\n{SENTENCE}\n{SENTENCE}\n"))), + ("a deleted character", |s| s.delete(s.len() / 2..s.len() / 2 + 1)), + ("a deleted return", |s| { + let at = s.text[..s.len() / 2].rfind('\n').unwrap(); + s.delete(at..at + 1); + }), + ("a deletion across paragraphs", |s| s.delete(s.len() / 4..s.len() / 4 + 900)), + ("a replacement", |s| s.replace(s.len() / 2..s.len() / 2 + 40, "replaced")), + ("larger type", |s| s.format_chars(s.len() / 2..s.len() / 2 + 60, |f| f.over.size = Some(18.0))), + ("a centered paragraph", |s| s.format_paras(s.len() / 2..s.len() / 2, |p| p.para.align = Some(Align::Center))), + ("text at the start", |s| s.insert(0, "Start. ")), + ("text at the end", |s| s.insert(s.len(), " End.")), + ("a two-byte character", |s| s.insert(s.len() / 2, "\u{e9}")), + ("everything deleted", |s| s.delete(0..s.len())), + ("text in an empty story", |s| s.insert(0, "Again.")), + ]; + for (what, edit) in edits { + edit(d.story_mut(sid).unwrap()); + check(&cache, &d, sid, what); + } + // Undo puts an earlier story back. + check(&cache, &original, sid, "the story before the edits"); + } + + #[test] + fn edits_in_and_above_overset_text_compose_right() { + let (mut d, sid, _) = threaded(60, 3); + let cache = Cache::new(); + assert!(cache.get(&d, sid, None).is_overset()); + let len = d.story(sid).unwrap().len(); + d.story_mut(sid).unwrap().insert(len - 10, "x"); + let n = check(&cache, &d, sid, "a character in overset text"); + assert!(n <= 1, "{n} paragraphs composed for a character typed in overset text"); + d.story_mut(sid).unwrap().insert(200, &format!(" {SENTENCE}")); + check(&cache, &d, sid, "a line added above overset text"); + d.story_mut(sid).unwrap().delete(100..len / 2); + check(&cache, &d, sid, "a deletion that brings overset text into the frames"); + } + + /// Stories with features a trace does not cover are composed whole after an edit. + #[test] + fn edits_of_stories_a_trace_does_not_cover_compose_right() { + let setups: [(&str, fn(&mut Document, StoryId, &[ItemId])); 6] = [ + ("keep options", |d, sid, _| { + let s = d.story_mut(sid).unwrap(); + s.format_paras(0..s.len(), |p| { + p.para.keep_with_next = Some(1); + p.para.keep_lines_together = Some(true); + }); + }), + ("balanced columns", |d, _, frames| { + for f in frames { + let o = &mut d.item_mut(*f).unwrap().text_frame_mut().unwrap().options; + (o.columns, o.balance_columns) = (2, true); + } + }), + ("vertical justification", |d, _, frames| { + for f in frames { + d.item_mut(*f).unwrap().text_frame_mut().unwrap().options.vertical_justification = VerticalJustification::Center; + } + }), + ("a numbered list", |d, sid, _| { + let s = d.story_mut(sid).unwrap(); + s.format_paras(0..s.len(), |p| p.para.list_type = Some(ListType::Numbers)); + }), + ("a footnote", |d, sid, _| { + d.story_mut(sid).unwrap().insert_note(300, "A synthetic footnote.", ParaFormat::default()); + }), + ("a column rule", |d, _, frames| { + for f in frames { + let o = &mut d.item_mut(*f).unwrap().text_frame_mut().unwrap().options; + (o.columns, o.column_rule) = (2, true); + } + }), + ]; + for (what, setup) in setups { + let (mut d, sid, frames) = threaded(30, 10); + setup(&mut d, sid, &frames); + let cache = Cache::new(); + cache.get(&d, sid, None); + let mid = d.story(sid).unwrap().len() / 2; + d.story_mut(sid).unwrap().insert(mid, "x"); + check(&cache, &d, sid, what); + d.story_mut(sid).unwrap().insert(mid, &format!("\n{SENTENCE} {SENTENCE}\n")); + check(&cache, &d, sid, what); + d.story_mut(sid).unwrap().delete(mid / 2..mid); + check(&cache, &d, sid, what); + } + } + + #[test] + fn a_run_of_mixed_edits_composes_right_after_each() { + let (mut d, sid, _) = threaded(40, 14); + let cache = Cache::new(); + cache.get(&d, sid, None); + let texts = ["x", " word", "\n", " several words in a row here", "\n\n", "A sentence. "]; + let mut seed = 0x2545_f491_u64; + let mut next = |below: usize| { + seed = seed.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1_442_695_040_888_963_407); + (seed >> 33) as usize % below.max(1) + }; + for step in 0..60 { + let s = d.story_mut(sid).unwrap(); + let at = next(s.len() + 1); + match next(4) { + 0 | 1 => s.insert(at, texts[next(texts.len())]), + 2 => s.delete(at..(at + next(120)).min(s.len())), + _ => { + let size = 9.0 + next(10) as f64; + s.format_chars(at..(at + next(60)).min(s.len()), |f| f.over.size = Some(size)); + } + } + check(&cache, &d, sid, &format!("step {step}")); + } + } +} diff --git a/crates/compose/src/table.rs b/crates/compose/src/table.rs index 5811887ae..0190aad05 100644 --- a/crates/compose/src/table.rs +++ b/crates/compose/src/table.rs @@ -53,6 +53,9 @@ pub struct TableFrag { pub column: u32, pub rect: Rect, pub cells: Vec, + /// The table rows in the fragment, each with its top and bottom; repeated header and footer + /// rows are left out. + pub rows: Vec<(usize, f64, f64)>, pub strokes: Vec, /// Index of the fragment's (glyph-less) line in the frame's lines. pub line: usize, @@ -89,6 +92,10 @@ impl TableFrag { c.clip = c.clip + v; c.origin += v; } + for r in &mut self.rows { + r.1 += dy; + r.2 += dy; + } for s in &mut self.strokes { s.a += v; s.b += v; @@ -500,6 +507,7 @@ fn emit( column: cur.col as u32, rect: Rect::new(x0, top, right, bottom), cells, + rows: rows.iter().filter(|r| !r.2).map(|&(r, y, _)| (r, y, y + heights[r])).collect(), strokes, line, first, diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs index f15f1e33d..f15ec4de4 100644 --- a/crates/compose/src/tests.rs +++ b/crates/compose/src/tests.rs @@ -513,6 +513,7 @@ fn hostile_wrap_geometry_terminates() { side: WrapSide::BothSides, contour: None, after: None, + anchor_baseline: None, }; let f = &mut specs[0]; f.exclusions.push(ex(f64::NAN, f64::NAN, f64::NAN, f64::NAN, WrapMode::JumpObject)); @@ -573,6 +574,498 @@ fn wrap_on_both_sides_sets_text_left_then_right_of_the_object() { assert!(!cs.is_overset()); } +/// A 60 × 200 pt frame at the origin holding `text` with vertical justification `vj`, and a bar +/// at `bar` whose text wrap `wrap` keeps 1 mm above it: (baseline, descent) of each line, the +/// text area and the wrap's top (None when the bar doesn't wrap the frame). +fn bar_chart_lines( + text: &str, + vj: designcraft_doc::VerticalJustification, + wrap: WrapMode, + side: WrapSide, + bar: Rect, +) -> (Vec<(f64, f64)>, Rect, Option) { + let (mut d, sid, fid) = doc_with(text, Rect::new(0.0, 0.0, 60.0, 200.0), ParaAttrs::default()); + d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.vertical_justification = vj; + let lid = d.default_layer(); + let id = ItemId(d.alloc()); + let mut it = designcraft_doc::Item::new(id, lid, designcraft_doc::Shape::Rectangle, designcraft_geom::shapes::rectangle(bar)); + it.wrap.mode = wrap; + it.wrap.side = side; + it.wrap.offsets = [72.0 / 25.4, 0.0, 0.0, 0.0]; + d.insert_item(SpreadRef::Doc(0), it, None).unwrap(); + let spec = frame_specs(&d, sid).remove(0); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + assert!(!cs.is_overset()); + let lines = all_lines(&cs).iter().map(|l| (l.baseline, l.descent)).collect(); + (lines, spec.area, spec.exclusions.first().map(|e| e.rect.y0)) +} + +/// Bottom, Center and Justify keep the lines out of a text wrap under them: a number aligned to +/// the bottom of its frame sits on the wrap's top offset over a bar instead of on the bar (#1831), +/// with every wrap mode that stops text there. +#[test] +fn vertical_justification_stops_at_a_wrap_under_the_text() { + use designcraft_doc::VerticalJustification::{Bottom, Center, Justify, Top}; + let bar = Rect::new(0.0, 150.0, 60.0, 300.0); + for wrap in [WrapMode::BoundingBox, WrapMode::Contour, WrapMode::JumpObject, WrapMode::JumpToNextColumn] { + let run = |vj, text| bar_chart_lines(text, vj, wrap, WrapSide::BothSides, bar); + let (top, _, wrap_top) = run(Top, "42"); + let wrap_top = wrap_top.unwrap(); + assert!((wrap_top - (150.0 - 72.0 / 25.4)).abs() < 1e-6, "{wrap:?}: the wrap's top is 1 mm above the bar: {wrap_top}"); + + let (bottom, _, _) = run(Bottom, "42"); + let b = bottom[0].0; + assert!((b - wrap_top).abs() < 1e-6, "{wrap:?}: Bottom put the baseline at {b}, not on the wrap's top at {wrap_top}"); + assert!(b > top[0].0 + 50.0, "{wrap:?}: Bottom moved the line down: {b}, {}", top[0].0); + + // Center takes half the room Bottom takes. + let (center, _, _) = run(Center, "42"); + assert!((center[0].0 - top[0].0 - (b - top[0].0) / 2.0).abs() < 1e-6, "{wrap:?}: Center at {}, Bottom at {b}", center[0].0); + + // Justify keeps the first baseline and puts the last where Bottom puts it. + let (top2, _, _) = run(Top, "12\n34"); + let (bottom2, _, _) = run(Bottom, "12\n34"); + let (justify, _, _) = run(Justify, "12\n34"); + assert_eq!(justify.len(), 2); + assert!((justify[0].0 - top2[0].0).abs() < 1e-6, "{wrap:?}: Justify moved the first line: {justify:?}"); + assert!((justify[1].0 - bottom2[1].0).abs() < 1e-6, "{wrap:?}: Justify {justify:?}, Bottom {bottom2:?}"); + assert!(justify[1].0 <= wrap_top + 1e-6); + } +} + +/// Without a wrap, or beside one, Bottom still moves the text down to the text area's bottom. +#[test] +fn vertical_justification_passes_wraps_that_do_not_stop_the_text() { + use designcraft_doc::VerticalJustification::Bottom; + // Wrap off: the number goes down over the bar. + let (lines, area, wrap_top) = bar_chart_lines("42", Bottom, WrapMode::None, WrapSide::BothSides, Rect::new(0.0, 150.0, 60.0, 300.0)); + assert!(wrap_top.is_none()); + assert!((lines[0].0 - area.y1).abs() < 1e-6, "{lines:?}, bottom {}", area.y1); + // A bar on the right half from the frame's top: the number is set beside it and goes down + // beside it. + let (lines, area, wrap_top) = bar_chart_lines("42", Bottom, WrapMode::BoundingBox, WrapSide::BothSides, Rect::new(30.0, 0.0, 60.0, 300.0)); + assert!(wrap_top.is_some()); + assert!((lines[0].0 - area.y1).abs() < 1e-6, "{lines:?}, bottom {}", area.y1); +} + +/// A one-sided wrap in the second column leaves the first column's lines free to go down, as it +/// leaves them when they are set. +#[test] +fn vertical_justification_passes_a_one_sided_wrap_in_another_column() { + let (mut d, sid, fid) = doc_with("One", Rect::new(0.0, 0.0, 400.0, 200.0), ParaAttrs::default()); + let o = &mut d.item_mut(fid).unwrap().text_frame_mut().unwrap().options; + o.columns = 2; + o.vertical_justification = designcraft_doc::VerticalJustification::Bottom; + let lid = d.default_layer(); + let mut it = designcraft_doc::Item::new( + ItemId(d.alloc()), + lid, + designcraft_doc::Shape::Rectangle, + designcraft_geom::shapes::rectangle(Rect::new(250.0, 100.0, 350.0, 300.0)), + ); + it.wrap.mode = WrapMode::BoundingBox; + it.wrap.side = WrapSide::RightSide; + d.insert_item(SpreadRef::Doc(0), it, None).unwrap(); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + let l = all_lines(&cs)[0]; + assert_eq!(l.column, 0); + assert!((l.baseline - 200.0).abs() < 1e-6, "baseline {}", l.baseline); +} + +/// Beside a contour that widens further down, Bottom moves a line only as far as its band stays +/// clear of the contour. +#[test] +fn vertical_justification_stops_where_a_contour_beside_the_text_widens() { + use designcraft_doc::VerticalJustification::{Bottom, Top}; + // Right edge fixed at 60, left edge x = 55 − 50y/190 from y = 0 down to y = 190. + let edge = |y: f64| 55.0 - 50.0 * y / 190.0; + let pts = [Point::new(55.0, 0.0), Point::new(60.0, 0.0), Point::new(60.0, 190.0), Point::new(5.0, 190.0)]; + let run = |vj| { + let (mut d, sid, fid) = doc_with("42", Rect::new(0.0, 0.0, 60.0, 200.0), ParaAttrs::default()); + d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.vertical_justification = vj; + let lid = d.default_layer(); + let path = designcraft_geom::path::PathData::single(designcraft_geom::path::SubPath::polyline(&pts, true)); + let mut it = designcraft_doc::Item::new(ItemId(d.alloc()), lid, designcraft_doc::Shape::Polygon, path); + it.wrap.mode = WrapMode::Contour; + it.wrap.side = WrapSide::BothSides; + d.insert_item(SpreadRef::Doc(0), it, None).unwrap(); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + assert!(!cs.is_overset()); + let l = all_lines(&cs)[0]; + (l.baseline, l.x1) + }; + let (top, x1) = run(Top); + assert!(x1 <= edge(top) + 1e-6, "Top sets the line clear of the contour: x1 {x1}, edge {}", edge(top)); + let (bottom, x1) = run(Bottom); + assert!(bottom >= top - 1e-6 && bottom < 190.0, "Bottom at {bottom}, Top at {top}"); + assert!(x1 <= edge(bottom) + 1e-6, "Bottom moved the line into the contour: baseline {bottom}, x1 {x1}, edge {}", edge(bottom)); +} + +/// Under a contour whose box starts beside the column and which widens into it further down, +/// Bottom moves a line down to where the contour meets its slot, not to the top of the box. +#[test] +fn vertical_justification_stops_where_a_contour_under_the_text_meets_it() { + // Left edge x = 70 − 40(y − 100)/90 from y = 100 down to y = 190: it crosses the column's + // right edge (60) at y = 122.5. + let pts = [Point::new(70.0, 100.0), Point::new(80.0, 100.0), Point::new(80.0, 190.0), Point::new(30.0, 190.0)]; + let (mut d, sid, fid) = doc_with("42", Rect::new(0.0, 0.0, 60.0, 200.0), ParaAttrs::default()); + d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.vertical_justification = designcraft_doc::VerticalJustification::Bottom; + let lid = d.default_layer(); + let path = designcraft_geom::path::PathData::single(designcraft_geom::path::SubPath::polyline(&pts, true)); + let mut it = designcraft_doc::Item::new(ItemId(d.alloc()), lid, designcraft_doc::Shape::Polygon, path); + it.wrap.mode = WrapMode::Contour; + it.wrap.side = WrapSide::BothSides; + d.insert_item(SpreadRef::Doc(0), it, None).unwrap(); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + assert!(!cs.is_overset()); + let b = all_lines(&cs)[0].baseline; + assert!(b <= 122.5 + 1e-6, "Bottom moved the baseline to {b}, past where the contour meets the column at 122.5"); + assert!(b > 122.0, "Bottom stopped the line at {b}, short of where the contour meets the column at 122.5"); +} + +/// A line set in the open middle of a U-shaped contour goes down between its arms: Bottom stops +/// it on the contour's base, not where the line starts because the arms span its slot. +#[test] +fn vertical_justification_moves_a_line_down_between_the_arms_of_a_contour() { + use designcraft_doc::VerticalJustification::{Bottom, Top}; + // Arms 0..15 and 45..60 from y = 0, joined by a base from y = 170 down to y = 190. + let pts = [ + Point::new(0.0, 0.0), + Point::new(15.0, 0.0), + Point::new(15.0, 170.0), + Point::new(45.0, 170.0), + Point::new(45.0, 0.0), + Point::new(60.0, 0.0), + Point::new(60.0, 190.0), + Point::new(0.0, 190.0), + ]; + let run = |vj| { + let (mut d, sid, fid) = doc_with("42", Rect::new(0.0, 0.0, 60.0, 200.0), ParaAttrs::default()); + d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.vertical_justification = vj; + let lid = d.default_layer(); + let path = designcraft_geom::path::PathData::single(designcraft_geom::path::SubPath::polyline(&pts, true)); + let mut it = designcraft_doc::Item::new(ItemId(d.alloc()), lid, designcraft_doc::Shape::Polygon, path); + it.wrap.mode = WrapMode::Contour; + it.wrap.side = WrapSide::BothSides; + d.insert_item(SpreadRef::Doc(0), it, None).unwrap(); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + assert!(!cs.is_overset()); + let l = all_lines(&cs)[0]; + (l.baseline, l.x0, l.x1) + }; + let (top, x0, x1) = run(Top); + assert!(x0 >= 15.0 - 1e-6 && x1 <= 45.0 + 1e-6, "Top sets the line between the arms: {x0}..{x1}"); + let (b, x0, x1) = run(Bottom); + assert!(x0 >= 15.0 - 1e-6 && x1 <= 45.0 + 1e-6, "Bottom keeps the line between the arms: {x0}..{x1}"); + assert!(b <= 170.0 + 1e-6, "Bottom moved the baseline to {b}, into the contour's base at 170"); + assert!(b > 169.9, "Bottom stopped the line at {b} (Top at {top}), short of the contour's base at 170"); +} + +/// An object anchored in the text and positioned from its anchor moves down with the lines, so +/// Center places lines above it as it places them without its wrap. +#[test] +fn vertical_justification_passes_an_anchored_object_that_moves_with_the_text() { + let baselines = |wrap| { + let (mut d, sid, fid) = doc_with("One\nTwo", Rect::new(0.0, 0.0, 300.0, 400.0), ParaAttrs::default()); + d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.vertical_justification = designcraft_doc::VerticalJustification::Center; + // Hung 40 pt under the first line's baseline, under the second line. + anchor_box(&mut d, sid, 1, 0.0, 40.0, true, wrap); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + all_lines(&cs).iter().map(|l| l.baseline).collect::>() + }; + let plain = baselines(WrapMode::None); + let wrapped = baselines(WrapMode::BoundingBox); + assert_eq!(plain.len(), 2); + assert!(plain[0] > 150.0, "Center moved the lines down: {plain:?}"); + assert_eq!(plain.len(), wrapped.len()); + assert!(plain.iter().zip(&wrapped).all(|(a, b)| (a - b).abs() < 1e-6), "without the wrap {plain:?}, with it {wrapped:?}"); +} + +/// Justify keeps the first line in place, so a wrap between it and the next line does not stop +/// the later lines from spreading down to the text area's bottom. +#[test] +fn vertical_justify_passes_a_wrap_under_the_first_line() { + let (mut d, sid, fid) = doc_with("One\nTwo\nSix", Rect::new(0.0, 0.0, 300.0, 400.0), ParaAttrs::default()); + d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.vertical_justification = designcraft_doc::VerticalJustification::Justify; + let lid = d.default_layer(); + let mut it = designcraft_doc::Item::new( + ItemId(d.alloc()), + lid, + designcraft_doc::Shape::Rectangle, + designcraft_geom::shapes::rectangle(Rect::new(0.0, 20.0, 300.0, 40.0)), + ); + it.wrap.mode = WrapMode::JumpObject; + d.insert_item(SpreadRef::Doc(0), it, None).unwrap(); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + let lines = all_lines(&cs); + assert_eq!(lines.len(), 3); + assert!( + lines[0].baseline < 20.0 && lines[1].baseline - lines[1].ascent >= 40.0 - 1e-6, + "{:?}", + lines.iter().map(|l| l.baseline).collect::>() + ); + let last = lines[2]; + assert!((last.baseline - 400.0).abs() < 1e-6, "{:?}", lines.iter().map(|l| l.baseline).collect::>()); +} + +/// Justify moves each row by its own share of the space, so a wrap between the second and third +/// rows limits the second row's move, not the third's. +#[test] +fn vertical_justify_limits_each_row_by_the_wrap_under_it() { + use designcraft_doc::VerticalJustification::{Justify, Top}; + let para = ParaAttrs { space_before: Some(40.0), ..Default::default() }; + let run = |vj, bar: Option| { + let (mut d, sid, fid) = doc_with("One\nTwo\nSix", Rect::new(0.0, 0.0, 300.0, 400.0), para.clone()); + d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.vertical_justification = vj; + if let Some(bar) = bar { + let lid = d.default_layer(); + let mut it = + designcraft_doc::Item::new(ItemId(d.alloc()), lid, designcraft_doc::Shape::Rectangle, designcraft_geom::shapes::rectangle(bar)); + it.wrap.mode = WrapMode::JumpObject; + d.insert_item(SpreadRef::Doc(0), it, None).unwrap(); + } + let cs = compose_story(&d, sid, &ComposeOptions::default()); + all_lines(&cs).iter().map(|l| (l.baseline, l.ascent, l.descent)).collect::>() + }; + let top = run(Top, None); + assert_eq!(top.len(), 3); + let b2 = top[1].0; + let (b3, a3, _) = top[2]; + // A bar 20 pt under the second baseline, clear of the third line. + let bar = Rect::new(0.0, b2 + 20.0, 300.0, b2 + 30.0); + assert!(b3 - a3 > bar.y1, "the third line starts under the bar: {top:?}"); + let set = run(Top, Some(bar)); + assert!(set.iter().zip(&top).all(|(a, b)| (a.0 - b.0).abs() < 1e-6), "the bar moves no line: {set:?}"); + let justify = run(Justify, Some(bar)); + assert!((justify[0].0 - top[0].0).abs() < 1e-6, "{justify:?}"); + // The second row's baseline comes down to the bar; the third row moves twice as far. + let moved = justify[1].0 - b2; + assert!((moved - 20.0).abs() < 1e-6, "the second row moved {moved}: {justify:?}"); + assert!((justify[2].0 - b3 - 2.0 * moved).abs() < 1e-6, "{justify:?}"); +} + +/// Each anchored object's own position decides whether its wrap moves with the text: a fixed +/// object without a wrap on the same line leaves the moving one skipped. +#[test] +fn vertical_justification_matches_each_wrap_to_its_anchored_object() { + let baselines = |wrap| { + let (mut d, sid, fid) = doc_with("One\nTwo", Rect::new(0.0, 0.0, 300.0, 400.0), ParaAttrs::default()); + d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.vertical_justification = designcraft_doc::VerticalJustification::Center; + // A fixed object from the frame's top, then one hung 40 pt under the first line. + anchor_box(&mut d, sid, 1, 150.0, 0.0, false, WrapMode::None); + anchor_box(&mut d, sid, 1 + OBJECT_LEN, 0.0, 40.0, true, wrap); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + assert_eq!(cs.frames[0].objects.len(), 2); + all_lines(&cs).iter().map(|l| l.baseline).collect::>() + }; + let plain = baselines(WrapMode::None); + let wrapped = baselines(WrapMode::BoundingBox); + assert!(plain[0] > 150.0, "Center moved the lines down: {plain:?}"); + assert_eq!(plain.len(), wrapped.len()); + assert!(plain.iter().zip(&wrapped).all(|(a, b)| (a - b).abs() < 1e-6), "without the wrap {plain:?}, with it {wrapped:?}"); +} + +/// An object positioned from its anchor but kept within its column can stop at the column's +/// bottom, so Bottom does not move the lines after its anchor into it. +#[test] +fn vertical_justification_stops_at_an_anchored_object_kept_within_its_column() { + let (mut d, sid, fid) = doc_with("One\nTwo", Rect::new(0.0, 0.0, 300.0, 400.0), ParaAttrs::default()); + d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.vertical_justification = designcraft_doc::VerticalJustification::Bottom; + anchor_box(&mut d, sid, 1, 0.0, 40.0, true, WrapMode::BoundingBox); + if let designcraft_doc::AnchorPosition::Custom { keep_within_column, .. } = + &mut std::sync::Arc::make_mut(&mut d.story_mut(sid).unwrap().objects[0]).position + { + *keep_within_column = true; + } + let cs = compose_story(&d, sid, &ComposeOptions::default()); + let lines = all_lines(&cs); + let o = &cs.frames[0].objects[0]; + let (top, bottom) = (o.origin.y, o.origin.y + 60.0); + assert!(bottom <= 400.0 + 1e-6, "the object stays in the column: {top}..{bottom}"); + let l = lines[1]; + assert!( + l.baseline <= top + 1e-6 || l.baseline - l.ascent >= bottom - 1e-6, + "the second line at {} meets the object at {top}..{bottom}", + l.baseline + ); +} + +/// An object positioned from its anchor and kept within its column moves with its anchor's line +/// until it reaches the column's bottom, so Bottom moves the lines above it down that far, not +/// only as far as where the object starts. +#[test] +fn vertical_justification_moves_an_object_kept_within_its_column_until_it_stops() { + use designcraft_doc::VerticalJustification::{Bottom, Center, Justify}; + for vj in [Bottom, Center, Justify] { + let (mut d, sid, fid) = doc_with("One\nTwo", Rect::new(0.0, 0.0, 300.0, 400.0), ParaAttrs::default()); + d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.vertical_justification = vj; + // Hung 40 pt under the first baseline, under the second line, and far above the column's + // bottom. + anchor_box(&mut d, sid, 1, 0.0, 40.0, true, WrapMode::BoundingBox); + if let designcraft_doc::AnchorPosition::Custom { keep_within_column, .. } = + &mut std::sync::Arc::make_mut(&mut d.story_mut(sid).unwrap().objects[0]).position + { + *keep_within_column = true; + } + let cs = compose_story(&d, sid, &ComposeOptions::default()); + let lines = all_lines(&cs); + let o = &cs.frames[0].objects[0]; + let (top, bottom) = (o.origin.y, o.origin.y + 60.0); + let l = lines[1]; + assert!(l.baseline <= top + 1e-6, "{vj:?}: the second line at {} meets the object at {top}..{bottom}", l.baseline); + match vj { + // The object stops at the column's bottom and the second line comes down onto it. + Bottom => { + assert!((bottom - 400.0).abs() < 1e-6, "{vj:?}: the object stopped at {top}..{bottom}, above the column's bottom"); + assert!(l.baseline > top - 0.01, "{vj:?}: the second line stopped at {}, above the object at {top}", l.baseline); + } + // Justify keeps the first line, and the object anchored in it, in place; the second + // line comes down onto the object. + Justify => { + assert!((top - lines[0].baseline - 40.0).abs() < 1e-6, "{vj:?}: the object moved to {top}..{bottom}"); + assert!(l.baseline > top - 0.01, "{vj:?}: the second line stopped at {}, above the object at {top}", l.baseline); + } + // Center moves the lines half of the room under them: the object moves with them. + _ => assert!(bottom < 400.0 - 1e-6 && l.baseline > 150.0, "{vj:?}: second line at {}, object at {top}..{bottom}", l.baseline), + } + } +} + +/// An object anchored in the first line, positioned from its anchor and kept within its column, +/// is held at the column's top. Justify keeps the first line in place, so the object stays there, +/// and the second line comes down onto the wider lower part of its contour. +#[test] +fn vertical_justify_keeps_the_room_under_an_object_held_at_the_columns_top() { + use designcraft_doc::anchored::AnchorRelative as R; + let (mut d, sid, fid) = doc_with("One\nTwo", Rect::new(0.0, 0.0, 300.0, 400.0), ParaAttrs::default()); + d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.vertical_justification = designcraft_doc::VerticalJustification::Justify; + // Beside the lines at x 250..300 down to y 100, then x 100..300 down to y 160. + let pts = [ + Point::new(150.0, 0.0), + Point::new(200.0, 0.0), + Point::new(200.0, 160.0), + Point::new(0.0, 160.0), + Point::new(0.0, 100.0), + Point::new(150.0, 100.0), + ]; + let lid = d.default_layer(); + let path = designcraft_geom::path::PathData::single(designcraft_geom::path::SubPath::polyline(&pts, true)); + let mut it = designcraft_doc::Item::new(ItemId(d.alloc()), lid, designcraft_doc::Shape::Polygon, path); + it.wrap.mode = WrapMode::Contour; + it.wrap.side = WrapSide::BothSides; + // 50 pt above the first baseline, so the column's top holds it. + let position = designcraft_doc::AnchorPosition::Custom { + x_relative: R::TextFrame, + y_relative: R::Anchor, + x_offset: 100.0, + y_offset: -50.0, + object_point: 0, + ref_point: 0, + keep_within_column: true, + spine_relative: false, + }; + d.story_mut(sid).unwrap().insert_object(1, designcraft_doc::AnchoredObject::new(it, position)); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + let lines = all_lines(&cs); + assert_eq!(lines.len(), 2); + let top = cs.frames[0].objects[0].origin.y; + assert!(lines[0].baseline < 50.0 && top.abs() < 1e-6, "the object is held at the column's top: {top}, {}", lines[0].baseline); + let wide = top + 100.0; + let b = lines[1].baseline; + assert!(b <= wide + 1e-6, "Justify moved the second line to {b}, into the contour's wider part at {wide}"); + assert!(b > wide - 0.01, "Justify stopped the second line at {b}, short of the contour's wider part at {wide}"); +} + +/// Justify keeps the first line in place and moves later lines further, so an object anchored in +/// the first line and hung under the last one still stops the lines after its anchor. +#[test] +fn vertical_justify_stops_at_an_object_anchored_above_the_lines_it_wraps() { + let (mut d, sid, fid) = doc_with("One\nTwo\nSix", Rect::new(0.0, 0.0, 300.0, 400.0), ParaAttrs::default()); + d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.vertical_justification = designcraft_doc::VerticalJustification::Justify; + anchor_box(&mut d, sid, 1, 0.0, 50.0, true, WrapMode::BoundingBox); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + let lines = all_lines(&cs); + assert_eq!(lines.len(), 3); + let top = cs.frames[0].objects[0].origin.y; + assert!((top - lines[0].baseline - 50.0).abs() < 1e-6, "the object hangs 50 pt under the first line: {top}, {}", lines[0].baseline); + let last = lines[2].baseline; + assert!(last <= top + 1e-6, "Justify moved the last line to {last}, into the object at {top}"); + assert!(last > lines[0].baseline + 40.0, "Justify spread the lines: {:?}", lines.iter().map(|l| l.baseline).collect::>()); +} + +/// Justify moves an object anchored in the second line with that line, so the third line spreads +/// down until it meets the object where it ends up, not where it started. +#[test] +fn vertical_justify_follows_an_object_anchored_in_a_later_line() { + let (mut d, sid, fid) = doc_with("One\nTwo\nSix", Rect::new(0.0, 0.0, 300.0, 400.0), ParaAttrs::default()); + d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.vertical_justification = designcraft_doc::VerticalJustification::Justify; + anchor_box(&mut d, sid, 5, 0.0, 40.0, true, WrapMode::BoundingBox); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + let lines = all_lines(&cs); + assert_eq!(lines.len(), 3); + let baselines = lines.iter().map(|l| l.baseline).collect::>(); + let top = cs.frames[0].objects[0].origin.y; + assert!((top - lines[1].baseline - 40.0).abs() < 1e-6, "the object hangs 40 pt under the second line: {top}, {baselines:?}"); + let last = lines[2].baseline; + assert!((top - last).abs() < 1e-6, "Justify moved the last line to {last}, not down to the object at {top}: {baselines:?}"); +} + +/// An Alpha Channel contour counts only where the graphic's clipping path shows the image: here +/// the visible pixels are in the right half and the clipping path shows the left half, so the +/// image wraps nothing; inverted, the clipping path shows the right half and the image wraps. +#[test] +fn an_alpha_channel_contour_stops_at_the_clipping_path() { + use designcraft_geom::{PathData, Point, SubPath}; + let rect = |x0: f64, x1: f64| { + PathData::single(SubPath::polyline(&[Point::new(x0, 0.0), Point::new(x1, 0.0), Point::new(x1, 200.0), Point::new(x0, 200.0)], true)) + }; + let lines_beside = |invert: bool| { + let (mut d, sid, _) = doc_with(&[LOREM; 4].join(" "), Rect::new(0.0, 0.0, 300.0, 800.0), ParaAttrs::default()); + let lid = d.default_layer(); + let asset = designcraft_doc::AssetId(d.alloc()); + let mut it = designcraft_doc::Item::new( + ItemId(d.alloc()), + lid, + designcraft_doc::Shape::Rectangle, + designcraft_geom::shapes::rectangle(Rect::new(150.0, 100.0, 300.0, 300.0)), + ); + let mut clip = designcraft_doc::ClippingPath::new(designcraft_doc::ClippingKind::DetectEdges, rect(0.0, 75.0)); + clip.invert = invert; + it.content = designcraft_doc::Content::Graphic(designcraft_doc::Graphic { + layer_options: None, + asset, + size: (150.0, 200.0), + xf: designcraft_geom::Affine::translate((150.0, 100.0)), + clip: Some(std::sync::Arc::new(clip)), + auto_fit: Default::default(), + fit_align: 0, + crop: [0.0; 4], + wrap: Default::default(), + fill: Default::default(), + }); + it.wrap.mode = WrapMode::Contour; + it.wrap.side = WrapSide::LeftSide; + it.wrap.contour = designcraft_doc::ContourType::AlphaChannel; + d.insert_item(SpreadRef::Doc(0), it, None).unwrap(); + d.alpha_outlines.push(std::sync::Arc::new(designcraft_doc::AlphaOutline { + asset, + threshold: designcraft_doc::DEFAULT_ALPHA_THRESHOLD, + width: 150, + height: 200, + outer: rect(75.0, 150.0), + holes: PathData::default(), + source: designcraft_doc::SourceKey(0), + serial: designcraft_doc::AlphaOutline::next_serial(), + })); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + cs.frames[0].lines.iter().filter(|l| l.baseline - l.ascent > 100.0 && l.baseline + l.descent < 300.0).map(|l| l.x1).collect::>() + }; + let shown_left = lines_beside(false); + assert!(!shown_left.is_empty() && shown_left.iter().all(|x| *x > 260.0), "nothing visible wraps nothing: {shown_left:?}"); + let shown_right = lines_beside(true); + assert!(!shown_right.is_empty() && shown_right.iter().all(|x| *x <= 225.0 + 1e-6), "the right half wraps: {shown_right:?}"); +} + /// Same As Clipping follows a placed graphic's clipping path: beside a triangle that widens /// downwards, text reaches further in at the narrow top than at the wide bottom. #[test] @@ -2291,7 +2784,7 @@ fn vertical_justification_counts_table_fragment_bottoms() { let mut spec = frame_specs(&d, sid).remove(0); spec.opts.vertical_justification = mode; - vertical_justify(&mut ft, &spec, false, &d.footnote_options); + vertical_justify(&mut ft, &spec, false, &d.footnote_options, &[], &[]); let moved = ft.lines[anchor].baseline - baseline; let limit = ft.notes[0].rect.y0 - d.footnote_options.space_before; @@ -2300,6 +2793,515 @@ fn vertical_justification_counts_table_fragment_bottoms() { } } +/// Center, Bottom and Justify place the text between its first baseline (where Top sets it) and +/// its last baseline: Bottom and Justify put the last baseline on the bottom inset, and Center +/// leaves as much room under the last baseline as above the first line (#1999). +#[test] +fn vertical_justification_measures_to_the_last_baseline() { + use designcraft_doc::VerticalJustification::{self, Bottom, Center, Justify, Top}; + let compose_inset = |mode: VerticalJustification, first: FirstBaseline, bottom_inset: f64| { + let (mut d, sid, fid) = doc_with("Typography\ngypsy", Rect::new(0.0, 0.0, 200.0, 300.0), ParaAttrs::default()); + let o = &mut d.item_mut(fid).unwrap().text_frame_mut().unwrap().options; + o.vertical_justification = mode; + o.first_baseline = first; + o.inset = [6.0, 6.0, bottom_inset, 6.0]; + let area = frame_specs(&d, sid)[0].area; + let cs = compose_story(&d, sid, &ComposeOptions::default()); + (area, all_lines(&cs).iter().map(|l| (l.baseline, l.descent)).collect::>()) + }; + let compose_with = |mode, first| compose_inset(mode, first, 9.0); + for first in [FirstBaseline::Ascent, FirstBaseline::CapHeight] { + let (area, top) = compose_with(Top, first); + assert!((area.y1 - 291.0).abs() < 1e-9, "the bottom inset bounds the text area: {area:?}"); + assert_eq!(top.len(), 2); + let last = |v: &[(f64, f64)]| v[v.len() - 1]; + + let (_, bottom) = compose_with(Bottom, first); + assert!((last(&bottom).0 - area.y1).abs() < 1e-6, "{first:?}: Bottom puts the last baseline on the inset: {bottom:?}"); + assert!(last(&bottom).0 + last(&bottom).1 > area.y1 + 1.0, "{first:?}: the descenders reach into the inset"); + assert!((bottom[1].0 - bottom[0].0 - (top[1].0 - top[0].0)).abs() < 1e-6, "{first:?}: Bottom keeps the leading"); + + let (_, justify) = compose_with(Justify, first); + assert!((justify[0].0 - top[0].0).abs() < 1e-6, "{first:?}: Justify keeps the first baseline: {justify:?}"); + assert!((last(&justify).0 - area.y1).abs() < 1e-6, "{first:?}: Justify puts the last baseline on the inset: {justify:?}"); + + let (_, center) = compose_with(Center, first); + let shift = center[0].0 - top[0].0; + assert!(shift > 1.0); + assert!((center[1].0 - top[1].0 - shift).abs() < 1e-6, "{first:?}: Center moves every line alike"); + assert!((area.y1 - last(¢er).0 - shift).abs() < 1e-6, "{first:?}: Center leaves equal room above and below: {center:?}"); + + // A bottom inset smaller than the descent: the last baseline still sits on the inset, and + // the descenders reach past the frame's edge. + for inset in [0.0, 1.0] { + for mode in [Bottom, Justify] { + let (area, lines) = compose_inset(mode, first, inset); + let (b, desc) = last(&lines); + assert!(desc > inset + 0.5); + assert!((b - area.y1).abs() < 1e-6, "{first:?} {mode:?} inset {inset}: last baseline at {b}, inset at {}", area.y1); + } + } + } +} + +/// With tight leading an earlier line's descenders can reach below the last baseline: Bottom keeps +/// them inside the text area, and only the last line's descenders hang into the bottom inset. +#[test] +fn vertical_justification_keeps_earlier_descenders_inside() { + use designcraft_doc::VerticalJustification::{self, Bottom, Center, Justify}; + let compose_with = |mode: VerticalJustification| { + let (mut d, sid, fid) = doc_with("Big\nx", Rect::new(0.0, 0.0, 200.0, 300.0), ParaAttrs::default()); + let o = &mut d.item_mut(fid).unwrap().text_frame_mut().unwrap().options; + o.vertical_justification = mode; + o.inset = [6.0; 4]; + let st = d.story_mut(sid).unwrap(); + st.format_chars(0..3, |f| f.over.size = Some(48.0)); + st.format_chars(4..5, |f| f.over.leading = Some(designcraft_doc::Leading::Points(2.0))); + let area = frame_specs(&d, sid)[0].area; + let cs = compose_story(&d, sid, &ComposeOptions::default()); + let lines: Vec<(f64, f64)> = all_lines(&cs).iter().map(|l| (l.baseline, l.descent)).collect(); + assert_eq!(lines.len(), 2); + if mode != Justify { + assert!(lines[0].0 + lines[0].1 > lines[1].0 + 1.0, "the first line's ink reaches below the last baseline: {lines:?}"); + } + (area, lines[0].0 + lines[0].1, lines[1].0) + }; + // Bottom moves both lines until the first line's ink meets the text area's bottom. + let (area, ink, _) = compose_with(Bottom); + assert!((ink - area.y1).abs() < 1e-6, "Bottom: first line's ink ends at {ink}, text area at {}", area.y1); + // Center moves both lines, as far as the first line's ink allows. + let (area, ink, _) = compose_with(Center); + assert!(ink <= area.y1 + 1e-6, "Center: first line's ink ends at {ink}, text area at {}", area.y1); + // Justify leaves the first line where it is, so the last baseline still reaches the inset. + let (area, _, last) = compose_with(Justify); + assert!((last - area.y1).abs() < 1e-6, "Justify: last baseline at {last}, text area at {}", area.y1); +} + +/// With Align to Baseline Grid, Center and Bottom move the lines by whole grid steps, so every +/// line stays on the grid: Bottom puts the last baseline on the lowest grid line above the bottom +/// inset, and Center on the grid line nearest the centered place. Justify keeps the first and last +/// lines on the grid and spreads the lines between them. +#[test] +fn vertical_justification_keeps_grid_aligned_lines_on_the_grid() { + use designcraft_doc::GridAlign; + use designcraft_doc::VerticalJustification::{self, Bottom, Center, Justify, Top}; + let compose_with = |mode: VerticalJustification, align: GridAlign| { + let mut area = Rect::ZERO; + let (lines, grid) = grid_doc("One\nTwo\nThree", ParaAttrs { grid_align: Some(align), ..Default::default() }, |d, sid| { + let spec = frame_specs(d, sid).remove(0); + area = spec.area; + d.item_mut(spec.id).unwrap().text_frame_mut().unwrap().options.vertical_justification = mode; + }); + (area, lines.iter().map(|l| l.baseline).collect::>(), grid) + }; + let (area, top, grid) = compose_with(Top, GridAlign::AllLines); + let inc = grid.1; + assert_eq!(top.len(), 3); + assert!(top.iter().all(|&b| on_grid(b, grid)), "Top: {top:?}"); + assert!(!on_grid(area.y1, grid), "the bottom inset is between grid lines: {area:?}"); + + let (_, bottom, _) = compose_with(Bottom, GridAlign::AllLines); + assert!(bottom.iter().all(|&b| on_grid(b, grid)), "Bottom keeps every line on the grid: {bottom:?}"); + let last = bottom[2]; + assert!(last <= area.y1 + 1e-6 && last > area.y1 - inc, "Bottom: last baseline {last} on the lowest grid line above {}", area.y1); + assert!((bottom[1] - bottom[0] - (top[1] - top[0])).abs() < 1e-6, "Bottom keeps the leading"); + + let (_, center, _) = compose_with(Center, GridAlign::AllLines); + assert!(center.iter().all(|&b| on_grid(b, grid)), "Center keeps every line on the grid: {center:?}"); + let shift = center[0] - top[0]; + let ideal = (area.y1 - top[2]) / 2.0; + assert!(shift > 1.0 && (shift - ideal).abs() <= inc / 2.0 + 1e-6, "Center: moved {shift}, centered at {ideal}"); + assert!(center[2] <= area.y1 + 1e-6); + + let (_, justify, _) = compose_with(Justify, GridAlign::AllLines); + assert!((justify[0] - top[0]).abs() < 1e-6, "Justify keeps the first baseline: {justify:?}"); + assert!(on_grid(justify[2], grid), "Justify keeps the last line on the grid: {justify:?}"); + assert!(justify[2] <= area.y1 + 1e-6 && justify[2] > area.y1 - inc, "Justify: last baseline {} near {}", justify[2], area.y1); + assert!((justify[1] - justify[0] - (justify[2] - justify[1])).abs() < 1e-6, "Justify spreads the lines evenly: {justify:?}"); + + // First lines only: each paragraph here is one line, so Bottom keeps every line on the grid. + let (_, first_only, _) = compose_with(Bottom, GridAlign::FirstLineOnly); + assert!(first_only.iter().all(|&b| on_grid(b, grid)), "Bottom, first lines only: {first_only:?}"); + + // Justify with a paragraph that wraps: with all lines aligned the last line lands on the grid; + // with first lines only it is not a first line, so it goes down to the bottom inset. + let wrapped = "The first line of this paragraph sits on the baseline grid, and the lines after it keep the leading they have."; + let justify_wrapped = |align: GridAlign| { + let (lines, _) = grid_doc(wrapped, ParaAttrs { grid_align: Some(align), ..Default::default() }, |d, sid| { + let spec = frame_specs(d, sid).remove(0); + d.item_mut(spec.id).unwrap().text_frame_mut().unwrap().options.vertical_justification = Justify; + }); + lines.iter().map(|l| l.baseline).collect::>() + }; + let all = justify_wrapped(GridAlign::AllLines); + assert!(all.len() >= 2, "the paragraph wraps: {all:?}"); + let last = all[all.len() - 1]; + assert!(on_grid(last, grid) && last <= area.y1 + 1e-6 && last > area.y1 - inc, "Justify, all lines: last baseline {last}"); + let first_lines = justify_wrapped(GridAlign::FirstLineOnly); + assert!(first_lines.len() >= 2, "the paragraph wraps: {first_lines:?}"); + let last = first_lines[first_lines.len() - 1]; + assert!((last - area.y1).abs() < 1e-6 && !on_grid(last, grid), "Justify, first lines only: last baseline {last}, inset at {}", area.y1); + + // Without grid alignment the last baseline goes down to the bottom inset. + let (_, free, _) = compose_with(Bottom, GridAlign::None); + assert!((free[2] - area.y1).abs() < 1e-6, "Bottom without the grid: {free:?}"); +} + +/// A grid increment too small for the room to be counted in steps, or too large to double, leaves +/// a grid-aligned line at a finite place inside the text area with Bottom, Center and Justify. +#[test] +fn vertical_justification_with_an_extreme_grid_increment_stays_finite() { + use designcraft_doc::GridAlign; + use designcraft_doc::VerticalJustification::{self, Bottom, Center, Justify, Top}; + // The grid starts at the line's natural baseline, so the line sits on it before it moves. + let (natural, grid) = grid_doc("One", ParaAttrs { grid_align: Some(GridAlign::None), ..Default::default() }, |_, _| {}); + let natural = natural[0].baseline; + let start = natural - grid.0; + let compose_with = |mode: VerticalJustification, inc: f64| { + let mut area = Rect::ZERO; + let (lines, _) = grid_doc("One", ParaAttrs { grid_align: Some(GridAlign::AllLines), ..Default::default() }, |d, sid| { + let spec = frame_specs(d, sid).remove(0); + area = spec.area; + let opts = &mut d.item_mut(spec.id).unwrap().text_frame_mut().unwrap().options; + opts.baseline_grid = Some(designcraft_doc::FrameBaselineGrid::new(start, inc)); + opts.vertical_justification = mode; + }); + (area, lines[0].baseline) + }; + for inc in [1e-310, 1e308] { + let (_, top) = compose_with(Top, inc); + assert!((top - natural).abs() < 1e-6, "Top with increment {inc:e}: baseline {top}, natural {natural}"); + for mode in [Bottom, Center, Justify] { + let (area, b) = compose_with(mode, inc); + assert!(b.is_finite() && b >= top - 1e-6 && b <= area.y1 + 1e-6, "{mode:?} with increment {inc:e}: baseline {b}, text area {area:?}"); + } + } + // A step far smaller than the room: Bottom takes the room as it does without a grid. + let (area, b) = compose_with(Bottom, 1e-310); + assert!((b - area.y1).abs() < 1e-6, "Bottom with a tiny increment: baseline {b}, text area {area:?}"); + // A step far larger than the room: the line does not move. + let (_, b) = compose_with(Center, 1e308); + assert!((b - natural).abs() < 1e-6, "Center with a huge increment: baseline {b}, natural {natural}"); + + // A grid that starts away from the line, with a step too small to count the distance: the line + // is placed as it is without a grid. + for mode in [Top, Bottom, Center, Justify] { + let mut area = Rect::ZERO; + let (lines, _) = grid_doc("One", ParaAttrs { grid_align: Some(GridAlign::AllLines), ..Default::default() }, |d, sid| { + let spec = frame_specs(d, sid).remove(0); + area = spec.area; + let opts = &mut d.item_mut(spec.id).unwrap().text_frame_mut().unwrap().options; + opts.baseline_grid = Some(designcraft_doc::FrameBaselineGrid::new(start - 5.0, 1e-310)); + opts.vertical_justification = mode; + }); + let b = lines[0].baseline; + assert!(b.is_finite() && b >= natural - 1e-6 && b <= area.y1 + 1e-6, "{mode:?}, grid away from the line: baseline {b}, text area {area:?}"); + if mode == Top { + assert!((b - natural).abs() < 1e-6, "Top, grid away from the line: baseline {b}, natural {natural}"); + } + } +} + +/// In a shaped frame that narrows and widens again, Align to Baseline Grid takes the grid step +/// nearest the place Bottom or Center would choose at which the line's slot fits the outline: +/// Bottom goes up past steps in the narrow part, and Center goes down a step when the step nearest +/// the middle is in the narrow part and the next one fits. +#[test] +fn vertical_justification_on_the_grid_skips_steps_that_leave_a_shaped_frame() { + use designcraft_doc::GridAlign; + use designcraft_doc::VerticalJustification::{self, Bottom, Center, Top}; + use designcraft_geom::{Anchor, PathData, Point, SubPath}; + // Full width down to 100 pt, a waist at 150 pt, full width again from 200 to 230 pt, then a + // point at 300 pt. + let pts = [(0.0, 0.0), (300.0, 0.0), (300.0, 100.0), (200.0, 150.0), (300.0, 200.0), (300.0, 230.0), (150.0, 300.0)]; + let pts: Vec<(f64, f64)> = pts.iter().copied().chain([(0.0, 230.0), (0.0, 200.0), (100.0, 150.0), (0.0, 100.0)]).collect(); + let compose_with = |mode: VerticalJustification, inc: f64| { + let para = ParaAttrs { grid_align: Some(GridAlign::AllLines), ..Default::default() }; + let (mut d, sid, fid) = doc_with("Typography", Rect::new(0.0, 0.0, 300.0, 300.0), para); + let it = d.item_mut(fid).unwrap(); + it.path = PathData::single(SubPath { anchors: pts.iter().map(|&(x, y)| Anchor::corner(Point::new(x, y))).collect(), closed: true }); + let o = &mut it.text_frame_mut().unwrap().options; + o.inset = [0.0; 4]; + o.baseline_grid = Some(designcraft_doc::FrameBaselineGrid::new(0.0, inc)); + o.vertical_justification = mode; + let grid = frame_specs(&d, sid)[0].grid.unwrap(); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + let l = all_lines(&cs)[0]; + (grid, l.baseline, l.baseline - l.ascent) + }; + let lower = |b: f64, band_top: f64| band_top >= 200.0 - 1e-6 && b <= 230.0 + 1e-6; + + // A 40 pt grid: the lowest room ends between 160 and 200 pt, and the steps above it down to + // 120 pt put the line in the waist. + let (grid, top, _) = compose_with(Top, 40.0); + assert!(on_grid(top, grid), "Top: baseline {top} on the grid {grid:?}"); + let (_, b, band_top) = compose_with(Bottom, 40.0); + assert!(on_grid(b, grid), "Bottom: baseline {b} on the grid {grid:?}"); + assert!(b <= 100.0 + 1e-6 || lower(b, band_top), "Bottom: the line's band {band_top}..{b} reaches into the narrow part"); + assert!(b > top, "Bottom moves the line down a grid step that fits: {b}, Top at {top}"); + + // A 45 pt grid: the step nearest the middle puts the baseline at 180 pt, in the waist; the + // step below it fits in the lower full-width part. + let (grid, b, band_top) = compose_with(Center, 45.0); + assert!(on_grid(b, grid), "Center: baseline {b} on the grid {grid:?}"); + assert!(lower(b, band_top), "Center: the line's band {band_top}..{b} is not in the lower full-width part"); +} + +/// A corner radius leaves a Cap Height first line where it sits in a rectangular frame, with Top +/// and with Center: a line's band above the text area isn't held to the frame's outline (#1999). +/// Center puts the last baseline halfway between where Top sets it and the bottom inset, also in +/// a frame too short for the descenders below it. +#[test] +fn a_corner_radius_keeps_a_cap_height_line_in_place() { + use designcraft_doc::VerticalJustification::{self, Bottom, Center, Justify, Top}; + use designcraft_geom::corners::{CornerOptions, CornerShape}; + let mm = 72.0 / 25.4; + let compose_tall = |height: f64, radius: f64, mode: VerticalJustification| { + let rect = Rect::new(0.0, 0.0, 29.553 * mm, height); + let (mut d, sid, fid) = doc_with("137mm", rect, ParaAttrs::default()); + let item = d.item_mut(fid).unwrap(); + item.corners = CornerOptions::uniform(CornerShape::Rounded, radius); + let o = &mut item.text_frame_mut().unwrap().options; + o.vertical_justification = mode; + o.first_baseline = FirstBaseline::CapHeight; + o.inset = [0.0; 4]; + d.story_mut(sid).unwrap().format_chars(0.."137mm".len(), |f| { + f.over.size = Some(19.0); + f.over.leading = Some(designcraft_doc::Leading::Points(19.0)); + }); + let spec = frame_specs(&d, sid).remove(0); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + assert!(!cs.is_overset()); + (spec.outline.is_some(), spec.area, cs.frames[0].lines[0].baseline) + }; + let compose_with = |radius: f64, mode: VerticalJustification| compose_tall(9.593 * mm, radius, mode); + let (square, area, top) = compose_with(0.0, Top); + let (rounded, _, rounded_top) = compose_with(0.1 * mm, Top); + assert!(!square && rounded, "only the radius gives the frame an outline"); + assert!((rounded_top - top).abs() < 1e-6, "Top: {rounded_top} with a radius, {top} without"); + let (_, _, center) = compose_with(0.0, Center); + let (_, _, rounded_center) = compose_with(0.1 * mm, Center); + assert!((center - (area.y1 + top) / 2.0).abs() < 1e-6, "Center: the last baseline halfway between {top} and {}: {center}", area.y1); + assert!((rounded_center - center).abs() < 1e-6, "Center: {rounded_center} with a radius, {center} without"); + + // Frames too short for the descenders under a centered last baseline. + for height in [22.0, 20.0, 19.0] { + let (_, area, top) = compose_tall(height, 0.0, Top); + let (_, _, center) = compose_tall(height, 0.0, Center); + assert!((center - (area.y1 + top) / 2.0).abs() < 1e-6, "{height} pt: Center at {center}, Top at {top}, inset at {}", area.y1); + } + + // A corner radius doesn't change where Bottom and Justify put the last baseline: on the + // bottom inset, as in a rectangular frame, with the descenders in the inset. Each radius is + // smaller than the inset, so the rounded corner stays clear of the text area. + for (insets, big) in [([6.0; 4], 4.0), ([0.0, 0.0, 12.0, 0.0], 6.0)] { + for mode in [Bottom, Justify] { + let compose_frame = |radius: f64| { + let (mut d, sid, fid) = doc_with("Typography\ngypsy", Rect::new(0.0, 0.0, 200.0, 100.0), ParaAttrs::default()); + let item = d.item_mut(fid).unwrap(); + item.corners = CornerOptions::uniform(CornerShape::Rounded, radius); + let o = &mut item.text_frame_mut().unwrap().options; + o.vertical_justification = mode; + o.inset = insets; + let area = frame_specs(&d, sid)[0].area; + let cs = compose_story(&d, sid, &ComposeOptions::default()); + (area, all_lines(&cs).iter().map(|l| l.baseline).collect::>()) + }; + let (area, square) = compose_frame(0.0); + for radius in [0.1 * mm, big] { + let (_, rounded) = compose_frame(radius); + assert_eq!(rounded.len(), square.len()); + for (r, s) in rounded.iter().zip(&square) { + assert!((r - s).abs() < 1e-6, "{mode:?} insets {insets:?} radius {radius}: {rounded:?} with a radius, {square:?} without"); + } + } + let last = square[square.len() - 1]; + assert!((last - area.y1).abs() < 1e-6, "{mode:?} insets {insets:?}: last baseline at {last}, inset at {}", area.y1); + } + } +} + +/// In a shaped frame, Center, Bottom and Justify keep each moved line's slot inside the outline: +/// a triangle that narrows downward holds the lines where their slots still fit, and one that +/// widens downward lets Bottom put the last baseline on the frame's bottom. +#[test] +fn vertical_justification_keeps_lines_inside_a_shaped_frame() { + use designcraft_doc::VerticalJustification::{self, Bottom, Center, Justify}; + use designcraft_geom::{Anchor, PathData, Point, SubPath}; + let r = Rect::new(0.0, 0.0, 300.0, 300.0); + let compose_with = |tri: [Point; 3], mode: VerticalJustification| { + let (mut d, sid, fid) = doc_with("Typography\ngypsy", r, ParaAttrs::default()); + let it = d.item_mut(fid).unwrap(); + it.path = PathData::single(SubPath { anchors: tri.iter().map(|&p| Anchor::corner(p)).collect(), closed: true }); + let o = &mut it.text_frame_mut().unwrap().options; + o.vertical_justification = mode; + o.inset = [0.0; 4]; + let spec = frame_specs(&d, sid).remove(0); + assert!(spec.outline.is_some()); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + let lines: Vec = all_lines(&cs).into_iter().cloned().collect(); + assert!(lines.len() >= 2, "{mode:?}: {lines:?}"); + (spec.area, lines) + }; + // Narrowing downward: |x - 150| <= (300 - y) / 2 over each slot's band, from the line's top to + // its baseline. + let down = [Point::new(0.0, 0.0), Point::new(300.0, 0.0), Point::new(150.0, 300.0)]; + for mode in [Center, Bottom, Justify] { + let (area, lines) = compose_with(down, mode); + for (k, l) in lines.iter().enumerate() { + let bottom = l.baseline; + let top = (l.baseline - l.ascent).max(area.y0); + for (x, y) in [(l.x0, top), (l.x1, top), (l.x0, bottom), (l.x1, bottom)] { + assert!((x - 150.0).abs() <= (300.0 - y) / 2.0 + 1e-3, "{mode:?}: line {k} corner ({x}, {y}) outside the triangle: {lines:?}"); + } + } + } + // Widening downward: moving down keeps every slot inside, so Bottom goes all the way. + let up = [Point::new(150.0, 0.0), Point::new(300.0, 300.0), Point::new(0.0, 300.0)]; + let (area, lines) = compose_with(up, Bottom); + let last = lines[lines.len() - 1].baseline; + assert!((last - area.y1).abs() < 1e-6, "Bottom: last baseline at {last}, frame bottom at {}: {lines:?}", area.y1); + + // Narrowing at a waist, full width again from 200 to 260 pt, then a point: Bottom sets the + // lines in the lower full-width part, past the waist. + let pts = [(0.0, 0.0), (300.0, 0.0), (300.0, 100.0), (200.0, 150.0), (300.0, 200.0), (300.0, 260.0), (150.0, 300.0)]; + let pts: Vec<(f64, f64)> = pts.iter().copied().chain([(0.0, 260.0), (0.0, 200.0), (100.0, 150.0), (0.0, 100.0)]).collect(); + let (mut d, sid, fid) = doc_with("Typography\ngypsy", r, ParaAttrs::default()); + let it = d.item_mut(fid).unwrap(); + it.path = PathData::single(SubPath { anchors: pts.iter().map(|&(x, y)| Anchor::corner(Point::new(x, y))).collect(), closed: true }); + let o = &mut it.text_frame_mut().unwrap().options; + o.vertical_justification = Bottom; + o.inset = [0.0; 4]; + let cs = compose_story(&d, sid, &ComposeOptions::default()); + let lines = all_lines(&cs); + let (first, last) = (lines[0], lines[lines.len() - 1]); + assert!(first.baseline - first.ascent >= 200.0 - 1e-6, "Bottom: first line top at {}", first.baseline - first.ascent); + assert!((last.baseline - 260.0).abs() < 1e-3, "Bottom: last baseline at {}", last.baseline); +} + +/// In a shaped frame, Center and Bottom move every line until its slot reaches the outline at its +/// baseline: an earlier line's descenders may cross the outline, as the last line's do. A frame +/// full width down to 20 pt and half width below it holds the first line's baseline at 20 pt. +#[test] +fn vertical_justification_lets_earlier_descenders_cross_a_shaped_frame() { + use designcraft_doc::VerticalJustification::{Bottom, Center}; + use designcraft_geom::{Anchor, PathData, Point, SubPath}; + let pts = [(0.0, 0.0), (300.0, 0.0), (300.0, 20.0), (150.0, 20.0), (150.0, 300.0), (0.0, 300.0)]; + for mode in [Center, Bottom] { + let (mut d, sid, fid) = doc_with("Typography\ngypsy", Rect::new(0.0, 0.0, 300.0, 300.0), ParaAttrs::default()); + let it = d.item_mut(fid).unwrap(); + it.path = PathData::single(SubPath { anchors: pts.iter().map(|&(x, y)| Anchor::corner(Point::new(x, y))).collect(), closed: true }); + let o = &mut it.text_frame_mut().unwrap().options; + o.vertical_justification = mode; + o.inset = [0.0; 4]; + assert!(frame_specs(&d, sid)[0].outline.is_some()); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + let lines = all_lines(&cs); + assert_eq!(lines.len(), 2, "{mode:?}: {lines:?}"); + let (first, last) = (lines[0], lines[1]); + assert!((first.x1 - 300.0).abs() < 1e-6 && (last.x1 - 150.0).abs() < 1e-6, "{mode:?}: slots {lines:?}"); + assert!(first.descent > 1.0, "{mode:?}: {first:?}"); + assert!((first.baseline - 20.0).abs() < 1e-3, "{mode:?}: first baseline at {}, step at 20", first.baseline); + assert!(last.baseline <= 300.0 + 1e-6, "{mode:?}: last baseline at {}", last.baseline); + } +} + +/// In a tall shaped frame, Bottom finds a band that the line fits in over less room than one step +/// of an even scan: in a frame that is half width from 40 pt down, apart from a full-width band +/// only 0.25 pt taller than the line at 1,800 pt, the line moves into that band. +#[test] +fn vertical_justification_finds_a_narrow_band_in_a_tall_shaped_frame() { + use designcraft_doc::VerticalJustification::{self, Bottom, Top}; + use designcraft_geom::{Anchor, PathData, Point, SubPath}; + let compose_with = |pts: &[(f64, f64)], mode: VerticalJustification| -> Vec { + let (mut d, sid, fid) = doc_with("Typography", Rect::new(0.0, 0.0, 300.0, 2000.0), ParaAttrs::default()); + let it = d.item_mut(fid).unwrap(); + if !pts.is_empty() { + it.path = PathData::single(SubPath { anchors: pts.iter().map(|&(x, y)| Anchor::corner(Point::new(x, y))).collect(), closed: true }); + } + let o = &mut it.text_frame_mut().unwrap().options; + o.vertical_justification = mode; + o.inset = [0.0; 4]; + assert_eq!(frame_specs(&d, sid)[0].outline.is_some(), !pts.is_empty()); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + assert!(!cs.is_overset(), "{mode:?}"); + all_lines(&cs).into_iter().cloned().collect() + }; + let ascent = compose_with(&[], Top)[0].ascent; + assert!(ascent > 1.0, "ascent {ascent}"); + let (y0, y1) = (1800.0, 1800.0 + ascent + 0.25); + let pts = + [(0.0, 0.0), (300.0, 0.0), (300.0, 40.0), (150.0, 40.0), (150.0, y0), (300.0, y0), (300.0, y1), (150.0, y1), (150.0, 2000.0), (0.0, 2000.0)]; + let lines = compose_with(&pts, Bottom); + assert_eq!(lines.len(), 1, "{lines:?}"); + let l = &lines[0]; + assert!((l.x1 - 300.0).abs() < 1e-6, "slot {l:?}"); + assert!(l.baseline - l.ascent >= y0 - 1e-6 && l.baseline <= y1 + 1e-6, "baseline at {}, band {y0}..{y1}", l.baseline); +} + +/// In a shaped frame with a text wrap under the text, Center, Bottom and Justify keep the lines +/// inside the outline and out of the wrap together: in a triangle that widens downward, Bottom and +/// Justify put the last baseline on the wrap's top and Center moves half as far; in one that +/// narrows downward, the outline stops the lines above the wrap, where they stop without it. +#[test] +fn vertical_justification_keeps_a_shaped_frame_and_a_wrap_under_the_text_together() { + use designcraft_doc::VerticalJustification::{self, Bottom, Center, Justify, Top}; + use designcraft_geom::{Anchor, PathData, Point, SubPath}; + let compose_with = |tri: [Point; 3], mode: VerticalJustification, bar: bool| { + let (mut d, sid, fid) = doc_with("Typography\ngypsy", Rect::new(0.0, 0.0, 300.0, 300.0), ParaAttrs::default()); + let it = d.item_mut(fid).unwrap(); + it.path = PathData::single(SubPath { anchors: tri.iter().map(|&p| Anchor::corner(p)).collect(), closed: true }); + let o = &mut it.text_frame_mut().unwrap().options; + o.vertical_justification = mode; + o.inset = [0.0; 4]; + if bar { + let lid = d.default_layer(); + let mut it = designcraft_doc::Item::new( + ItemId(d.alloc()), + lid, + designcraft_doc::Shape::Rectangle, + designcraft_geom::shapes::rectangle(Rect::new(0.0, 250.0, 300.0, 400.0)), + ); + it.wrap.mode = WrapMode::JumpObject; + d.insert_item(SpreadRef::Doc(0), it, None).unwrap(); + } + let cs = compose_story(&d, sid, &ComposeOptions::default()); + assert!(!cs.is_overset(), "{mode:?}"); + let lines: Vec = all_lines(&cs).into_iter().cloned().collect(); + assert!(lines.len() >= 2, "{mode:?}: {lines:?}"); + lines + }; + let up = [Point::new(150.0, 0.0), Point::new(300.0, 300.0), Point::new(0.0, 300.0)]; + let top = compose_with(up, Top, true); + let top_last = top[top.len() - 1].baseline; + for mode in [Bottom, Justify] { + let lines = compose_with(up, mode, true); + let last = lines[lines.len() - 1].baseline; + assert!((last - 250.0).abs() < 1e-3, "{mode:?}: last baseline at {last}, wrap top at 250: {lines:?}"); + for (k, l) in lines.iter().enumerate() { + let bottom = if k + 1 == lines.len() { l.baseline } else { l.baseline + l.descent }; + let top = l.baseline - l.ascent; + for (x, y) in [(l.x0, top), (l.x1, top), (l.x0, bottom), (l.x1, bottom)] { + assert!((x - 150.0).abs() <= y / 2.0 + 1e-3, "{mode:?}: line {k} corner ({x}, {y}) outside the triangle: {lines:?}"); + } + } + } + let center = compose_with(up, Center, true); + let center_last = center[center.len() - 1].baseline; + assert!((center_last - (top_last + 250.0) / 2.0).abs() < 1e-3, "Center: last baseline at {center_last}, Top at {top_last}"); + + let down = [Point::new(0.0, 0.0), Point::new(300.0, 0.0), Point::new(150.0, 300.0)]; + for mode in [Center, Bottom, Justify] { + let with = compose_with(down, mode, true); + let without = compose_with(down, mode, false); + assert!(without[without.len() - 1].baseline < 250.0, "{mode:?}: {without:?}"); + assert_eq!(with.len(), without.len()); + for (a, b) in with.iter().zip(&without) { + assert!((a.baseline - b.baseline).abs() < 1e-3, "{mode:?}: {with:?} with the wrap, {without:?} without"); + } + } +} + #[test] fn table_rows_clear_footnotes_and_continue_in_the_next_column() { for span in [false, true] { @@ -7581,6 +8583,38 @@ fn anchored_object_wraps_another_storys_text() { assert!(lines_in_band(&moved, 200.0, 260.0).iter().all(|l| l.x0 >= left + 100.0 - 1e-6)); } +/// An anchored frame whose wrap is set only on its placed graphic (Direct Selection) wraps +/// another story's text as a wrap set on the frame does. +#[test] +fn anchored_graphic_wrap_wraps_another_storys_text() { + let long = [LOREM; 3].join(" "); + let (mut d, a, fa) = doc_with("Anchor here.", Rect::new(0.0, 0.0, 300.0, 400.0), ParaAttrs::default()); + let lid = d.default_layer(); + let (_, b) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(320.0, 0.0, 620.0, 400.0), lid, &long, ParaFormat::default()).unwrap(); + let left = all_lines(&compose_story(&d, b, &ComposeOptions::default()))[0].x0; + let area = d.item(fa).unwrap().text_area(); + anchor_box(&mut d, a, 0, left - area.x0, 100.0 - area.y0, false, WrapMode::None); + let wrap = designcraft_doc::TextWrap { mode: WrapMode::BoundingBox, ..Default::default() }; + let obj = std::sync::Arc::make_mut(&mut d.story_mut(a).unwrap().objects[0]); + obj.item.content = designcraft_doc::Content::Graphic(designcraft_doc::Graphic { + layer_options: None, + asset: designcraft_doc::AssetId(1), + size: (100.0, 60.0), + xf: designcraft_geom::Affine::IDENTITY, + clip: None, + auto_fit: designcraft_doc::Fitting::None, + fit_align: 0, + crop: [0.0; 4], + wrap, + fill: Default::default(), + }); + let cs = compose_story(&d, b, &ComposeOptions::default()); + let band = lines_in_band(&cs, 100.0, 160.0); + assert!(!band.is_empty()); + assert!(band.iter().all(|l| l.x0 >= left + 100.0 - 1e-6), "{:?}", band.iter().map(|l| l.x0).collect::>()); + assert!(lines_in_band(&cs, 0.0, 80.0).iter().all(|l| (l.x0 - left).abs() < 1e-6)); +} + /// An anchored object's wrap is built as a page item's: a contour on both sides of an oval sets /// text left and right of it, closer in where the oval narrows. #[test] @@ -7688,6 +8722,73 @@ fn spine_relative_anchored_notes_stay_in_the_outside_margin_on_both_pages() { const OBJECT_LEN: usize = designcraft_doc::OBJECT_MARK.len_utf8(); +/// A story of `paras` paragraphs, each with an inline anchored object at its start, an endnote +/// reference after it and a cross-reference that shows `Ref.` for paragraph `k`. +fn story_with_marks(paras: usize) -> (Document, StoryId) { + let text = vec!["Some words, a note and an object."; paras].join("\n"); + let (mut d, sid, _) = doc_with(&text, Rect::new(0.0, 0.0, 400.0, 20_000.0), ParaAttrs::default()); + let starts: Vec = d.story(sid).unwrap().para_ranges().iter().map(|r| r.start).collect(); + let lid = d.default_layer(); + for (k, &s) in starts.iter().enumerate().rev() { + let it = designcraft_doc::Item::new( + ItemId(d.alloc()), + lid, + designcraft_doc::Shape::Rectangle, + designcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 6.0, 6.0)), + ); + let story = d.story_mut(sid).unwrap(); + story.insert_xref(s + 19, designcraft_doc::CrossRef { text: Some(format!("Ref{k}.")), ..Default::default() }); + story.insert_endnote(s + 10, "An endnote.", ParaFormat::default()); + story.insert_object(s, designcraft_doc::AnchoredObject::new(it, designcraft_doc::AnchorPosition::Inline { y_offset: 0.0 })); + } + (d, sid) +} + +/// The marks before each paragraph match a count from the story start, for every kind of mark. +#[test] +fn mark_counts_before_each_paragraph_match_a_count_from_the_start() { + let (d, sid) = story_with_marks(5); + let story = d.story(sid).unwrap(); + let ranges = story.para_ranges(); + let counts = MarkCounts::before_paragraphs(story, &ranges); + assert_eq!(counts.len(), ranges.len()); + for (k, (r, m)) in ranges.iter().zip(&counts).enumerate() { + let head = &story.text[..r.start]; + assert_eq!(m.endnotes, head.matches(designcraft_doc::ENDNOTE_REF).count(), "paragraph {k}"); + assert_eq!(m.objects, head.matches(designcraft_doc::OBJECT_MARK).count(), "paragraph {k}"); + assert_eq!(m.xrefs, head.matches(designcraft_doc::XREF_MARK).count(), "paragraph {k}"); + assert_eq!(*m, MarkCounts { endnotes: k, objects: k, xrefs: k }, "paragraph {k}"); + } + // Each paragraph shows its own cross-reference's text, so the composer numbers the + // cross-references from the marks before the paragraph. + let cs = compose_story(&d, sid, &ComposeOptions::default()); + let shown: String = cs.frames[0].lines.iter().flat_map(|l| l.glyphs.iter().filter(|g| g.visible).map(|g| g.rendered_char)).collect(); + let refs: Vec<&str> = shown.match_indices("Ref").map(|(i, _)| &shown[i..i + 5]).collect(); + assert_eq!(refs, ["Ref0.", "Ref1.", "Ref2.", "Ref3.", "Ref4."], "{shown:?}"); + // A story without endnotes, anchored objects or cross-references reads nothing. + let (plain, psid, _) = doc_with("One\nTwo", Rect::new(0.0, 0.0, 300.0, 300.0), ParaAttrs::default()); + let p = plain.story(psid).unwrap(); + assert!(MarkCounts::before_paragraphs(p, &p.para_ranges()).is_empty()); +} + +/// Composing a story with endnotes, anchored objects and cross-references reads its text for their numbers in one +/// pass, so four times the paragraphs read about four times the bytes, not sixteen times. +#[test] +fn composing_reads_marks_once_per_story() { + let scanned = |paras: usize| { + let (d, sid) = story_with_marks(paras); + MARK_BYTES_SCANNED.with(|n| n.set(0)); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + assert!(!cs.is_overset()); + assert_eq!(cs.frames[0].objects.len(), paras); + (MARK_BYTES_SCANNED.with(std::cell::Cell::get), d.story(sid).unwrap().text.len()) + }; + let (small, small_len) = scanned(40); + let (big, big_len) = scanned(160); + assert!(small > 0); + assert!(big * small_len <= 2 * small * big_len, "40 paragraphs read {small} of {small_len} bytes, 160 read {big} of {big_len}"); +} + #[test] fn anchored_object_wraps_its_own_storys_later_lines() { let text = [LOREM; 4].join(" "); @@ -8156,6 +9257,51 @@ fn cache_recomposes_when_the_baseline_grid_changes() { assert!((la.baseline - lb.baseline).abs() > 1.0, "{} {}", la.baseline, lb.baseline); } +/// A cache over another uses its compositions of the same state, and composes an older state +/// without replacing the other cache's composition of the current one. +#[test] +fn a_cache_over_another_reads_it_without_writing_to_it() { + let (old, sid, _) = doc_with(LOREM, Rect::new(0.0, 0.0, 200.0, 600.0), ParaAttrs::default()); + let mut new = old.clone(); + new.story_mut(sid).unwrap().rev += 1; + let base = Arc::new(Cache::new()); + let current = base.get(&new, sid, None); + let reader = Cache::over(Arc::clone(&base)); + assert!(reader.base().is_some_and(|b| Arc::ptr_eq(b, &base))); + assert!(Arc::ptr_eq(&reader.get(&new, sid, None), ¤t), "the base's composition is used"); + let earlier = reader.get(&old, sid, None); + assert!(!Arc::ptr_eq(&earlier, ¤t)); + assert!(Arc::ptr_eq(&reader.get(&old, sid, None), &earlier), "kept in the reader"); + assert!(Arc::ptr_eq(&base.get(&new, sid, None), ¤t), "the base keeps the current state's composition"); + assert!(base.composed_for(&old, sid).is_none(), "the base holds nothing of the older state"); +} + +/// The cross-reference and running-header indexes are built from compositions that depend on the +/// baseline grid and the font scope, so a change to either builds them again, in a cache and in a +/// cache over it. +#[test] +fn the_document_indexes_are_rebuilt_when_the_grid_or_font_scope_changes() { + let para = ParaAttrs { grid_align: Some(GridAlign::AllLines), ..Default::default() }; + let (d, _, _) = doc_with(LOREM, Rect::new(0.0, 0.0, 200.0, 600.0), para); + let base = Arc::new(Cache::new()); + let (xrefs, running) = (base.xref_index(&d), base.running_index(&d)); + let mut grid = d.clone(); + grid.settings.baseline_grid.increment = 30.0; + let mut scope = d.clone(); + scope.font_scope += 1; + for (changed, what) in [(&grid, "grid"), (&scope, "font scope")] { + let reader = Cache::over(Arc::clone(&base)); + assert!(!Arc::ptr_eq(&reader.xref_index(changed), &xrefs), "{what}: the base's cross-reference index is not used"); + assert!(!Arc::ptr_eq(&reader.running_index(changed), &running), "{what}: the base's running-header index is not used"); + let own = Cache::new(); + let (x, r) = (own.xref_index(&d), own.running_index(&d)); + assert!(!Arc::ptr_eq(&own.xref_index(changed), &x), "{what}: cross-reference index rebuilt"); + assert!(!Arc::ptr_eq(&own.running_index(changed), &r), "{what}: running-header index rebuilt"); + } + let reader = Cache::over(Arc::clone(&base)); + assert!(Arc::ptr_eq(&reader.xref_index(&d), &xrefs), "the same state uses the base's index"); +} + /// Two single pages 618 pt tall, top margins 36 and 48, each with an overset 11/13 story aligned /// to a baseline grid (start 0, increment 13) and a frame filling its margin box (bottom 582). fn grid_margin_doc(relative_to: designcraft_doc::GridRelative) -> (Document, [StoryId; 2]) { @@ -8437,6 +9583,123 @@ fn an_object_wraps_the_frame_its_anchor_lands_in_after_an_earlier_object_pushed_ assert_eq!(line_layout(&compose_story(&d, sid, &ComposeOptions::default())), line_layout(&cs)); } +#[test] +fn contour_intervals_preserve_the_gap_between_legs() { + let mut path = designcraft_geom::BezPath::new(); + path.move_to((0.0, 0.0)); + for p in [(40.0, 0.0), (40.0, 100.0), (30.0, 100.0), (30.0, 20.0), (10.0, 20.0), (10.0, 100.0), (0.0, 100.0)] { + path.line_to(p); + } + path.close_path(); + let c = Contour::of(&path, designcraft_geom::Affine::IDENTITY, 3.0).unwrap(); + assert_eq!(c.band_spans(50.0, 60.0), vec![(-3.0, 13.0), (27.0, 43.0)]); + assert_eq!(c.band_spans(5.0, 15.0), vec![(-3.0, 43.0)]); + let frame = designcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 35.0, 100.0)).to_bezpath(); + assert_eq!(c.within(&frame, designcraft_geom::Affine::IDENTITY).band_spans(50.0, 60.0), vec![(-3.0, 13.0), (27.0, 38.0)]); +} + +#[test] +fn contour_intervals_cover_the_whole_slanted_line_band() { + let mut path = designcraft_geom::BezPath::new(); + path.move_to((0.0, 0.0)); + for p in [(2.0, 0.0), (12.0, 10.0), (10.0, 10.0)] { + path.line_to(p); + } + path.close_path(); + let c = Contour::of(&path, designcraft_geom::Affine::IDENTITY, 0.0).unwrap(); + assert_eq!(c.band_spans(0.0, 10.0), vec![(0.0, 12.0)]); +} + +/// A vertical open path blocks the offset on both sides of it, and splits the line with no +/// offset; clipped to a frame that holds it, it still does. +#[test] +fn a_vertical_open_path_keeps_its_offset() { + let mut path = designcraft_geom::BezPath::new(); + path.move_to((10.0, 0.0)); + path.line_to((10.0, 100.0)); + let c = Contour::of(&path, designcraft_geom::Affine::IDENTITY, 3.0).unwrap(); + assert_eq!(c.band_spans(40.0, 50.0), vec![(7.0, 13.0)]); + let frame = designcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 20.0, 100.0)).to_bezpath(); + assert_eq!(c.within(&frame, designcraft_geom::Affine::IDENTITY).band_spans(40.0, 50.0), vec![(7.0, 13.0)]); + let c = Contour::of(&path, designcraft_geom::Affine::IDENTITY, 0.0).unwrap(); + assert_eq!(c.band_spans(40.0, 50.0), vec![(10.0, 10.0)]); +} + +/// An outline counts only where its frame shows it: a part of it in a notch of the frame blocks +/// nothing, even where the frame covers the same x positions lower in the same line band. +#[test] +fn a_clipped_contour_blocks_only_what_its_frame_shows() { + let poly = |pts: &[(f64, f64)]| { + let mut p = designcraft_geom::BezPath::new(); + p.move_to(pts[0]); + for &q in &pts[1..] { + p.line_to(q); + } + p.close_path(); + p + }; + let id = designcraft_geom::Affine::IDENTITY; + // An L-shaped frame with a notch at x 10..40 above y = 6. + let frame = poly(&[(0.0, 0.0), (10.0, 0.0), (10.0, 6.0), (40.0, 6.0), (40.0, 10.0), (0.0, 10.0)]); + // An outline in the notch only. + let c = Contour::of(&poly(&[(20.0, 0.0), (40.0, 0.0), (40.0, 4.0), (20.0, 4.0)]), id, 0.0).unwrap(); + assert_eq!(c.band_spans(0.0, 10.0), vec![(20.0, 40.0)]); + assert_eq!(c.within(&frame, id).band_spans(0.0, 10.0), Vec::<(f64, f64)>::new(), "the frame shows none of it"); + // Reaching below the notch, where the frame shows it from y = 6 to 8. + let c = Contour::of(&poly(&[(20.0, 0.0), (40.0, 0.0), (40.0, 8.0), (20.0, 8.0)]), id, 0.0).unwrap(); + assert_eq!(c.within(&frame, id).band_spans(0.0, 10.0), vec![(20.0, 40.0)]); + // A band that crosses both shapes whole keeps their common part, widened by the offset. + let c = Contour::of(&poly(&[(5.0, -10.0), (30.0, -10.0), (30.0, 20.0), (5.0, 20.0)]), id, 2.0).unwrap(); + assert_eq!(c.within(&frame, id).band_spans(7.0, 9.0), vec![(3.0, 32.0)]); + // A frame in more than 128 pieces across the band takes the common part of the projections. + let mut fragmented = frame.clone(); + for i in 0..200 { + let x = 1000.0 + 2.0 * f64::from(i); + fragmented.extend(poly(&[(x, 0.0), (x + 1.0, 0.0), (x + 1.0, 10.0), (x, 10.0)]).elements().iter().copied()); + } + let c = Contour::of(&poly(&[(20.0, 0.0), (40.0, 0.0), (40.0, 4.0), (20.0, 4.0)]), id, 0.0).unwrap(); + assert_eq!(c.within(&fragmented, id).band_spans(0.0, 10.0), vec![(20.0, 40.0)]); + // So does a frame and an outline too detailed to compare within a line's budget: here 2,000 + // points on the frame's bottom edge and on the outline's top edge. + let mut detailed = vec![(0.0, 0.0), (10.0, 0.0), (10.0, 6.0), (40.0, 6.0), (40.0, 10.0)]; + detailed.extend((1..2000).map(|i| (40.0 - 0.02 * f64::from(i), 10.0))); + detailed.push((0.0, 10.0)); + let mut notch: Vec<(f64, f64)> = (0..2000).map(|i| (20.0 + 0.01 * f64::from(i), 0.0)).collect(); + notch.extend([(40.0, 0.0), (40.0, 4.0), (20.0, 4.0)]); + let c = Contour::of(&poly(¬ch), id, 0.0).unwrap(); + assert_eq!(c.within(&poly(&detailed), id).band_spans(0.0, 10.0), vec![(20.0, 40.0)]); +} + +/// Edges far above or below a line band cost a clipped contour nothing there: an outline with +/// 7,000 points well below the band still gets the exact spans, not the projections' common part. +#[test] +fn a_clipped_contours_budget_counts_only_edges_in_the_band() { + let poly = |pts: &[(f64, f64)]| { + let mut p = designcraft_geom::BezPath::new(); + p.move_to(pts[0]); + for &q in &pts[1..] { + p.line_to(q); + } + p.close_path(); + p + }; + let id = designcraft_geom::Affine::IDENTITY; + // The L-shaped frame of the test above, with its notch at x 10..40 above y = 6. + let frame = poly(&[(0.0, 0.0), (10.0, 0.0), (10.0, 6.0), (40.0, 6.0), (40.0, 10.0), (0.0, 10.0)]); + // An outline in the notch and to the right of the frame, with 40 teeth along its top in the + // band and a 7,000-point zigzag along its bottom at y = 200. + let mut pts = vec![(20.0, 0.0)]; + for i in 0..40 { + let x = 40.0 + 0.5 * f64::from(i); + pts.extend([(x, 0.0), (x + 0.25, 0.5)]); + } + pts.push((60.0, 0.0)); + pts.extend((0..7000).map(|i| (60.0 - 10.0 * f64::from(i) / 6999.0, if i % 2 == 0 { 200.0 } else { 201.0 }))); + pts.extend([(50.0, 4.0), (20.0, 4.0)]); + let c = Contour::of(&poly(&pts), id, 0.0).unwrap(); + assert_eq!(c.within(&frame, id).band_spans(0.0, 10.0), Vec::<(f64, f64)>::new(), "the frame shows none of it"); +} + /// Rule Above's offset runs from the first line's baseline up to the rule's bottom edge, as in /// InDesign: a rule set clear of the cap height sits between the rows, not across the row above /// (an INDD project list whose rules crossed the previous paragraph's text). @@ -8566,6 +9829,170 @@ fn anchored_frames_in_one_host_compose_it_once() { assert_eq!(Cache::new().get(&d, nsid, None).frames.len(), compose_story(&d, nsid, &ComposeOptions::default()).frames.len()); } +/// A text frame anchored in a text frame that is itself anchored in a frame on page 1 is placed +/// through both hosts: on page 1, at the inner object's spot in the outer anchored frame. +#[test] +fn a_frame_anchored_in_an_anchored_frame_is_placed_through_both_hosts() { + let mut d = Document::new(&NewDocument { pages: 1, ..Default::default() }); + let lid = d.default_layer(); + let body = "One.\nTwo.\nThree."; + let (bf, sid) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(36.0, 36.0, 400.0, 400.0), lid, body, ParaFormat::default()).unwrap(); + let frame = |d: &mut Document, text: &str, w: f64, h: f64| { + let (fid, fsid) = (ItemId(d.alloc()), StoryId(d.alloc())); + let mut story = Story::with_text(fsid, text, ParaFormat::default()); + story.frames.push(fid); + d.stories.insert(fsid, Arc::new(story)); + let mut it = + designcraft_doc::Item::new(fid, lid, designcraft_doc::Shape::Rectangle, designcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, w, h))); + it.content = Content::Text(designcraft_doc::TextFrame { story: fsid, options: Default::default() }); + (it, fsid) + }; + let (outer, osid) = frame(&mut d, "Outer text", 200.0, 100.0); + let (inner, isid) = frame(&mut d, "Inner", 80.0, 30.0); + let (outer_id, inner_id) = (outer.id, inner.id); + d.story_mut(osid).unwrap().insert_object("Outer ".len(), designcraft_doc::AnchoredObject::new(inner, Default::default())); + d.story_mut(sid).unwrap().insert_object(body.find("Two").unwrap(), designcraft_doc::AnchoredObject::new(outer, Default::default())); + + let placed = placed::placements(&d, isid, &mut |h| Arc::new(compose_story(&d, h, &ComposeOptions::default()))); + assert_eq!(placed.len(), 1, "{placed:?}"); + let (id, p) = placed[0]; + assert_eq!((id, p.spread), (inner_id, SpreadRef::Doc(0))); + // The body frame's object, then the outer frame's object, each at its composed origin. + let host = compose_story(&d, sid, &ComposeOptions::default()); + let o1 = &host.frame(bf).unwrap().objects[0]; + let mid = compose_story(&d, osid, &ComposeOptions::default()); + let o2 = &mid.frame(outer_id).unwrap().objects[0]; + let want = d.item(bf).unwrap().xf + * Affine::translate(o1.origin.to_vec2()) + * d.anchored_item(outer_id).unwrap().xf + * Affine::translate(o2.origin.to_vec2()); + let (got, want) = (p.xf.as_coeffs(), want.as_coeffs()); + assert!(got.iter().zip(want).all(|(a, b)| (a - b).abs() < 1e-9), "{got:?} != {want:?}"); + assert_eq!(frame_specs_placed(&d, isid, &placed)[0].page, Some(0)); + // The cache places it the same way. + assert_eq!(Cache::new().get(&d, isid, None).frames.len(), 1); +} + +/// An unplaced `w` × `h` text frame showing a new story of `text`, ready to anchor. +fn anchored_text_frame(d: &mut Document, text: &str, w: f64, h: f64) -> (designcraft_doc::Item, StoryId) { + let lid = d.default_layer(); + let (fid, fsid) = (ItemId(d.alloc()), StoryId(d.alloc())); + let mut story = Story::with_text(fsid, text, ParaFormat::default()); + story.frames.push(fid); + d.stories.insert(fsid, Arc::new(story)); + let mut it = + designcraft_doc::Item::new(fid, lid, designcraft_doc::Shape::Rectangle, designcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, w, h))); + it.content = Content::Text(designcraft_doc::TextFrame { story: fsid, options: Default::default() }); + (it, fsid) +} + +/// A one-page document whose body frame holds `outer` anchored before its second line. Returns +/// the body frame and the body story's composition. +fn body_holding(d: &mut Document, outer: designcraft_doc::Item) -> (ItemId, ComposedStory) { + let lid = d.default_layer(); + let body = "One.\nTwo.\nThree."; + let (bf, sid) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(36.0, 36.0, 400.0, 400.0), lid, body, ParaFormat::default()).unwrap(); + d.story_mut(sid).unwrap().insert_object(body.find("Two").unwrap(), designcraft_doc::AnchoredObject::new(outer, Default::default())); + (bf, compose_story(d, sid, &ComposeOptions::default())) +} + +/// `isid`'s one frame, `inner`, is placed on page 1 with parent space `want`, and the cache +/// composes it there. +fn assert_placed_on_page_one(d: &Document, isid: StoryId, inner: ItemId, want: Affine) { + let placed = placed::placements(d, isid, &mut |h| Arc::new(compose_story(d, h, &ComposeOptions::default()))); + assert_eq!(placed.len(), 1, "{placed:?}"); + let (id, p) = placed[0]; + assert_eq!((id, p.spread), (inner, SpreadRef::Doc(0))); + let (got, want) = (p.xf.as_coeffs(), want.as_coeffs()); + assert!(got.iter().zip(want).all(|(a, b)| (a - b).abs() < 1e-9), "{got:?} != {want:?}"); + assert_eq!(frame_specs_placed(d, isid, &placed)[0].page, Some(0)); + assert_eq!(Cache::new().get(d, isid, None).frames.len(), 1); +} + +/// A text frame anchored in an anchored text frame that is a member of an anchored group with a +/// rotation and a scale is placed through the group's transform and the member's own. +#[test] +fn a_frame_anchored_in_a_grouped_anchored_frame_is_placed_through_the_group() { + let mut d = Document::new(&NewDocument { pages: 1, ..Default::default() }); + let (mut outer, osid) = anchored_text_frame(&mut d, "Outer text", 200.0, 100.0); + let (inner, isid) = anchored_text_frame(&mut d, "Inner", 80.0, 30.0); + let (outer_id, inner_id) = (outer.id, inner.id); + outer.xf = Affine::translate((12.0, 7.0)); + d.story_mut(osid).unwrap().insert_object("Outer ".len(), designcraft_doc::AnchoredObject::new(inner, Default::default())); + let mut g = + designcraft_doc::Item::new(ItemId(d.alloc()), d.default_layer(), designcraft_doc::Shape::Group, designcraft_geom::PathData::default()); + g.content = Content::Group { items: vec![Arc::new(outer)] }; + g.xf = Affine::rotate(0.25) * Affine::scale(1.25); + let (gid, gxf) = (g.id, g.xf); + let (bf, host) = body_holding(&mut d, g); + + let o1 = &host.frame(bf).unwrap().objects[0]; + // The composed group keeps its rotation and scale; its offset puts its box at the object's origin. + let gxf_placed = o1.object.item.xf; + assert_eq!((o1.object.item.id, gxf_placed.as_coeffs()[..4].to_vec()), (gid, gxf.as_coeffs()[..4].to_vec())); + let mid = compose_story(&d, osid, &ComposeOptions::default()); + let o2 = &mid.frame(outer_id).unwrap().objects[0]; + let want = d.text_xf(d.item(bf).unwrap()) + * Affine::translate(o1.origin.to_vec2()) + * gxf_placed + * d.text_xf(d.anchored_item(outer_id).unwrap()) + * Affine::translate(o2.origin.to_vec2()); + assert_placed_on_page_one(&d, isid, inner_id, want); +} + +/// A text frame anchored in a footnote of an anchored text frame is placed through the footnote's +/// spot in that frame as well as both hosts. +#[test] +fn a_frame_anchored_in_a_footnote_of_an_anchored_frame_is_placed_through_the_footnote() { + let mut d = Document::new(&NewDocument { pages: 1, ..Default::default() }); + let (outer, osid) = anchored_text_frame(&mut d, "Outer text", 200.0, 120.0); + let (inner, isid) = anchored_text_frame(&mut d, "Inner", 80.0, 30.0); + let (outer_id, inner_id) = (outer.id, inner.id); + let st = d.story_mut(osid).unwrap(); + st.insert_note("Outer".len(), "Note text", ParaFormat::default()); + Arc::make_mut(&mut st.notes[0]).text.insert_object("Note ".len(), designcraft_doc::AnchoredObject::new(inner, Default::default())); + let (bf, host) = body_holding(&mut d, outer); + + let o1 = &host.frame(bf).unwrap().objects[0]; + let mid = compose_story(&d, osid, &ComposeOptions::default()); + let note = &mid.frame(outer_id).unwrap().notes[0]; + let o2 = ¬e.text.frames[0].objects[0]; + let want = d.text_xf(d.item(bf).unwrap()) + * Affine::translate(o1.origin.to_vec2()) + * d.text_xf(d.anchored_item(outer_id).unwrap()) + * Affine::translate(note.origin.to_vec2()) + * Affine::translate(o2.origin.to_vec2()); + assert_placed_on_page_one(&d, isid, inner_id, want); +} + +/// A text frame anchored in a table cell of an anchored text frame is placed through the cell's +/// spot in that frame as well as both hosts. +#[test] +fn a_frame_anchored_in_a_table_cell_of_an_anchored_frame_is_placed_through_the_cell() { + let mut d = Document::new(&NewDocument { pages: 1, ..Default::default() }); + let (outer, osid) = anchored_text_frame(&mut d, "Outer text", 200.0, 150.0); + let (inner, isid) = anchored_text_frame(&mut d, "Inner", 80.0, 30.0); + let (outer_id, inner_id) = (outer.id, inner.id); + let mut table = designcraft_doc::Table::new(77, 1, 1, 0, 0, 180.0); + table.cells[0].text.insert(0, "Cell "); + table.cells[0].text.insert_object("Cell ".len(), designcraft_doc::AnchoredObject::new(inner, Default::default())); + let st = d.story_mut(osid).unwrap(); + let end = st.len(); + st.insert_table(end, table); + let (bf, host) = body_holding(&mut d, outer); + + let o1 = &host.frame(bf).unwrap().objects[0]; + let mid = compose_story(&d, osid, &ComposeOptions::default()); + let cell = &mid.frame(outer_id).unwrap().tables[0].cells[0]; + let o2 = &cell.text.frames[0].objects[0]; + let want = d.text_xf(d.item(bf).unwrap()) + * Affine::translate(o1.origin.to_vec2()) + * d.text_xf(d.anchored_item(outer_id).unwrap()) + * Affine::translate(cell.origin.to_vec2()) + * Affine::translate(o2.origin.to_vec2()); + assert_placed_on_page_one(&d, isid, inner_id, want); +} + /// A marginal note (an anchored text frame, Only Align First Line to Grid, 9/10) hangs 15 pt /// above its anchor's baseline on a right-hand page. It composes against the document grid where /// it is placed: its first line moves down onto the grid line, the second follows 10 pt below, diff --git a/crates/compose/src/wrap.rs b/crates/compose/src/wrap.rs index f28bba424..1424d9dd5 100644 --- a/crates/compose/src/wrap.rs +++ b/crates/compose/src/wrap.rs @@ -18,9 +18,10 @@ //! 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}; /// Most extra compositions of a story with its own anchored objects' wrap, however many objects @@ -46,10 +47,13 @@ pub(crate) struct Obstacle<'a> { xf: Affine, /// Story byte of the anchor, for obstacles in their own story. anchor: Option, + /// Baseline of the line holding the anchor, for obstacles in their own story. + anchor_baseline: Option, } +/// The wrap may be set on the frame or on its placed graphic (Direct Selection). fn wraps(o: &AnchoredObject) -> bool { - o.item.wrap.mode != WrapMode::None && !o.item.hidden + o.item.has_wrap() && !o.item.hidden } /// Does `story` have an anchored object whose wrap can push text? @@ -126,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 @@ -152,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); } } @@ -192,7 +198,22 @@ fn settled(a: &[Vec], b: &[Vec]) -> bool { /// Compose story `sid` with the wrapping anchored objects of `others` (compositions of its /// [`neighbours`]) and of its own. pub(crate) fn compose_among(doc: &Document, sid: StoryId, opts: &ComposeOptions, others: &[&ComposedStory]) -> ComposedStory { - let Some(st) = doc.story(sid) else { return ComposedStory { story: sid, ..Default::default() } }; + compose_among_traced(doc, sid, opts, others, None).0 +} + +/// [`compose_among`], also giving the trace for composing the story again after an edit, when +/// the composition leaves one ([`crate::reuse`]). `before` is the story before an edit with its +/// composition among the same `others` and that composition's trace: the paragraphs the edit +/// cannot change are taken from it. A story with wrapping anchored objects of its own is +/// composed whole and leaves no trace. +pub(crate) fn compose_among_traced( + doc: &Document, + sid: StoryId, + opts: &ComposeOptions, + others: &[&ComposedStory], + before: Option>, +) -> (ComposedStory, Option) { + let Some(st) = doc.story(sid) else { return (ComposedStory { story: sid, ..Default::default() }, None) }; let mut specs = crate::frame_specs_placed(doc, sid, &opts.placed); if !others.is_empty() { let mut obs = Vec::new(); @@ -206,10 +227,10 @@ 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..(own + 1).clamp(MIN_PASSES, MAX_PASSES) { @@ -220,5 +241,5 @@ pub(crate) fn compose_among(doc: &Document, sid: StoryId, opts: &ComposeOptions, out = crate::compose(doc, st, &with_exclusions(&specs, &added), opts); prev = added; } - out + (out, None) } diff --git a/crates/compose/src/xref.rs b/crates/compose/src/xref.rs index 1d72f1ee1..d658eb3d9 100644 --- a/crates/compose/src/xref.rs +++ b/crates/compose/src/xref.rs @@ -68,11 +68,26 @@ pub fn xref_text(doc: &Document, x: &xref::CrossRef, index: Option<&XrefIndex>) /// Generated text of the cross-references in `range` of `story`, by byte of their mark. pub fn texts_in(doc: &Document, story: &Story, range: std::ops::Range, index: Option<&XrefIndex>) -> HashMap { + if story.xrefs.is_empty() { + return HashMap::new(); + } + let before = story.text[..range.start].matches(XREF_MARK).count(); + texts_after(doc, story, range, before, index) +} + +/// [`texts_in`] for a caller that already knows `before`, the number of cross-reference marks in +/// `story` before `range`. +pub(crate) fn texts_after( + doc: &Document, + story: &Story, + range: std::ops::Range, + before: usize, + index: Option<&XrefIndex>, +) -> HashMap { let mut out = HashMap::new(); if story.xrefs.is_empty() { return out; } - let before = story.text[..range.start].matches(XREF_MARK).count(); for (k, (i, _)) in story.text[range.clone()].match_indices(XREF_MARK).enumerate() { if let Some(x) = story.xrefs.get(before + k) { out.insert(range.start + i, xref_text(doc, x, index)); diff --git a/crates/doc/src/anchored.rs b/crates/doc/src/anchored.rs index 524e2bfc5..f5c4b856c 100644 --- a/crates/doc/src/anchored.rs +++ b/crates/doc/src/anchored.rs @@ -749,7 +749,7 @@ mod tests { id, name: name.into(), mime: "application/pdf".into(), - data: Arc::new(format!("%PDF-1.7 {name}").into_bytes()), + data: crate::AssetData::embedded(format!("%PDF-1.7 {name}").into_bytes()), ..Default::default() }; let (mut a, host) = doc(); diff --git a/crates/doc/src/asset_data.rs b/crates/doc/src/asset_data.rs new file mode 100644 index 000000000..a4584c19c --- /dev/null +++ b/crates/doc/src/asset_data.rs @@ -0,0 +1,411 @@ +//! The bytes of a placed file ([`crate::Asset::data`]): held in memory (embedded) or read from +//! the linked file when needed. Caches of decoded images key by the value's [`SourceKey`], +//! which outlives the bytes: a decoded image stays usable after the encoded bytes are dropped. +//! +//! Linked bytes are read by the [`Loader`] the engine installs ([`install_loader`]; this crate +//! does no file I/O) and kept in a process-wide store of at most [`STORE_BUDGET`] bytes, least +//! recently used first out. A file over [`MAX_LINKED_BYTES`] is never read. + +use std::fmt; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Arc, Mutex, PoisonError, Weak}; + +use crate::datamerge::Fingerprint; + +mod store; + +pub use store::{Loaded, Loader, MAX_LINKED_BYTES, STORE_BUDGET, install_loader}; + +/// Names one version of an asset's bytes. Every [`AssetData`] made from new bytes gets a key no +/// other value in this process has had; clones share it. Keys are never reused, so a cache +/// entry under a key can't be mistaken for different bytes allocated later. Counting starts at +/// 1: `SourceKey(0)` names no bytes. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub struct SourceKey(pub u64); + +impl SourceKey { + /// A key no other value has had. + pub fn fresh() -> Self { + static NEXT: AtomicU64 = AtomicU64::new(1); + SourceKey(NEXT.fetch_add(1, Ordering::Relaxed)) + } +} + +/// Why an asset's bytes can't be had. +#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)] +pub enum Unavailable { + #[error("the linked file is missing")] + Missing, + #[error("the linked file has changed")] + Modified, + #[error("the linked file is too large to load")] + TooLarge, + #[error("no loader for linked files")] + NoLoader, +} + +/// Where a linked asset's bytes are, and what they must be: the [`crate::Asset`] link record +/// ([`LinkedSource::of`]) with the document it is resolved against. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct LinkedSource { + /// The file's absolute path ([`crate::Asset::link`]), tried first. + pub path: String, + /// The path relative to the document's folder ([`crate::Asset::link_relative`]), tried when + /// the absolute path doesn't hold the bytes. + pub relative: Option, + /// The document file `relative` is resolved against. + pub document: Option, + /// The size of the bytes. + pub len: u64, + /// Size and modification time of the file when it was known to hold the bytes: a file that + /// still has them is read without hashing. + pub fingerprint: Option, + /// The bytes' content hash ([`crate::Asset::link_hash`], `sha256:` and hex digits), checked + /// when the file's fingerprint differs. + pub hash: Option, +} + +impl LinkedSource { + /// The source `asset`'s link record names, resolved against the document file at + /// `document`. `None` without a link, or without the size its fingerprint records. + pub fn of(asset: &crate::Asset, document: Option<&Path>) -> Option { + let fingerprint = asset.link_fingerprint?; + Some(LinkedSource { + path: asset.link.clone()?, + relative: asset.link_relative.clone(), + document: document.map(Path::to_path_buf), + len: fingerprint.size, + fingerprint: Some(fingerprint), + hash: asset.link_hash.clone(), + }) + } +} + +/// A linked source, with the fingerprint a load last found the file at (hash-checked), so later +/// loads of a file whose time changed but whose bytes didn't skip the hash. +struct Linked { + source: LinkedSource, + trusted: Mutex>, +} + +impl Linked { + fn trusted(&self) -> Option { + *self.trusted.lock().unwrap_or_else(PoisonError::into_inner) + } + + fn trust(&self, fingerprint: Fingerprint) { + *self.trusted.lock().unwrap_or_else(PoisonError::into_inner) = Some(fingerprint); + } +} + +#[derive(Clone)] +enum Repr { + Embedded(Arc>), + Linked(Arc), +} + +/// An asset's bytes: embedded in the document, or linked (read from the file on demand). +/// Cloning is cheap and keeps the [`SourceKey`]. +#[derive(Clone)] +pub struct AssetData { + key: SourceKey, + repr: Repr, +} + +impl AssetData { + /// Embedded bytes, under a new key. + pub fn embedded(bytes: impl Into>>) -> Self { + AssetData { key: SourceKey::fresh(), repr: Repr::Embedded(bytes.into()) } + } + + /// Embedded bytes under `key`, which the caller made ([`SourceKey::fresh`]) for exactly these + /// bytes: bytes derived again from the same input (a layer variant of the same file) keep + /// the key their decodes are cached under. Different bytes under one key would draw stale + /// pixels. + pub fn embedded_under(key: SourceKey, bytes: impl Into>>) -> Self { + AssetData { key, repr: Repr::Embedded(bytes.into()) } + } + + /// The bytes of the linked file `source` names, under a new key. + pub fn linked(source: LinkedSource) -> Self { + AssetData { key: SourceKey::fresh(), repr: Repr::Linked(Arc::new(Linked { source, trusted: Mutex::new(None) })) } + } + + /// The linked file `source` names, under `key`: embedded bytes found identical to the file + /// (hash-checked by the caller) become a link without decoding them again. As with + /// [`AssetData::embedded_under`], other bytes under one key would draw stale pixels. + pub fn linked_under(key: SourceKey, source: LinkedSource) -> Self { + AssetData { key, repr: Repr::Linked(Arc::new(Linked { source, trusted: Mutex::new(None) })) } + } + + /// This value pointing at `source` (the file moved, the document was saved elsewhere, the + /// fingerprint was brought up to date). It keeps the key when both name the same bytes + /// (same size and content hash), so nothing decoded is decoded again. + pub fn with_source(&self, source: LinkedSource) -> Self { + let same = self.linked_source().is_some_and(|old| old.len == source.len && old.hash.is_some() && old.hash == source.hash); + let mut new = AssetData::linked(source); + if same { + new.key = self.key; + } + new + } + + /// The bytes, when they are embedded. + pub fn embedded_bytes(&self) -> Option<&Arc>> { + match &self.repr { + Repr::Embedded(b) => Some(b), + Repr::Linked(_) => None, + } + } + + /// Where linked bytes are read from. + pub fn linked_source(&self) -> Option<&LinkedSource> { + match &self.repr { + Repr::Embedded(_) => None, + Repr::Linked(l) => Some(&l.source), + } + } + + /// The bytes: embedded ones, or the linked file's (read once by the installed [`Loader`], + /// and kept while the store's budget allows). Concurrent loads of one value read it once. + pub fn load(&self) -> Result>, Unavailable> { + match &self.repr { + Repr::Embedded(b) => Ok(Arc::clone(b)), + Repr::Linked(l) => store::global().load(self.key, l, store::installed().as_deref()), + } + } + + /// The bytes for output: [`Self::load`], or for a linked file that has changed the file's + /// current bytes, flagged `true`, which are never cached. Linked bytes already in memory are + /// used only while the file still holds them ([`Loader::holds`]): output goes by the file as + /// it is now. + pub fn load_for_output(&self) -> Result<(Arc>, bool), Unavailable> { + if let Repr::Linked(l) = &self.repr + && let Some(kept) = store::global().resident(self.key) + && let Some(loader) = store::installed() + { + return match loader.holds(&l.source, l.trusted(), &kept) { + Ok(found) => { + if let Some(fingerprint) = found { + l.trust(fingerprint); + } + Ok((kept, false)) + } + Err(Unavailable::Modified) => loader.load_current(&l.source).map(|b| (Arc::new(b), true)), + Err(e) => Err(e), + }; + } + match self.load() { + Ok(b) => Ok((b, false)), + Err(Unavailable::Modified) => { + let (Some(source), Some(loader)) = (self.linked_source(), store::installed()) else { return Err(Unavailable::Modified) }; + loader.load_current(source).map(|b| (Arc::new(b), true)) + } + Err(e) => Err(e), + } + } + + /// The bytes without reading anything: embedded ones, or linked ones the store holds. + pub fn resident(&self) -> Option>> { + match &self.repr { + Repr::Embedded(b) => Some(Arc::clone(b)), + Repr::Linked(_) => store::global().resident(self.key), + } + } + + /// Keep `bytes`, just read from the linked file and checked by the caller to be the ones its + /// source names, in the store, so the first [`AssetData::load`] doesn't read the file again. + /// Embedded values, bytes of another size and bytes over the store's budget are ignored. + pub fn keep_resident(&self, bytes: Arc>) { + if let Repr::Linked(l) = &self.repr + && bytes.len() as u64 == l.source.len + { + store::global().keep(self.key, bytes); + } + } + + /// Drop the store's copy of linked bytes (they are read again when next loaded). + pub fn evict(&self) { + if self.is_linked() { + store::global().evict(self.key); + } + } + + pub fn key(&self) -> SourceKey { + self.key + } + + /// The size of the bytes. + pub fn len(&self) -> u64 { + match &self.repr { + Repr::Embedded(b) => b.len() as u64, + Repr::Linked(l) => l.source.len, + } + } + + pub fn is_empty(&self) -> bool { + self.len() == 0 + } + + pub fn is_linked(&self) -> bool { + matches!(self.repr, Repr::Linked(_)) + } + + /// A handle that doesn't keep embedded bytes alive, and upgrades to this value (same key) + /// while anything else does. + pub fn downgrade(&self) -> WeakAssetData { + let repr = match &self.repr { + Repr::Embedded(b) => WeakRepr::Embedded(Arc::downgrade(b)), + Repr::Linked(l) => WeakRepr::Linked(Arc::clone(l)), + }; + WeakAssetData { key: self.key, repr } + } +} + +/// Advances when linked files may have come back or changed ([`links_changed`]). +static LINK_GENERATION: AtomicU64 = AtomicU64::new(0); + +/// Say that linked files may have changed on disk (a relink, an update, a status check): caches +/// that remembered a linked file as unavailable ask for it again. +pub fn links_changed() { + LINK_GENERATION.fetch_add(1, Ordering::AcqRel); +} + +/// The count [`links_changed`] advances. +pub fn link_generation() -> u64 { + LINK_GENERATION.load(Ordering::Acquire) +} + +#[derive(Clone)] +enum WeakRepr { + Embedded(Weak>), + Linked(Arc), +} + +/// [`AssetData::downgrade`]. +#[derive(Clone)] +pub struct WeakAssetData { + key: SourceKey, + repr: WeakRepr, +} + +impl WeakAssetData { + /// The value, while its embedded bytes are held elsewhere. + pub fn upgrade(&self) -> Option { + let repr = match &self.repr { + WeakRepr::Embedded(w) => Repr::Embedded(w.upgrade()?), + WeakRepr::Linked(l) => Repr::Linked(Arc::clone(l)), + }; + Some(AssetData { key: self.key, repr }) + } + + pub fn key(&self) -> SourceKey { + self.key + } +} + +impl fmt::Debug for WeakAssetData { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("WeakAssetData").field("key", &self.key.0).finish() + } +} + +/// New embedded bytes ([`AssetData::embedded`]). +impl From> for AssetData { + fn from(bytes: Vec) -> Self { + AssetData::embedded(bytes) + } +} + +impl Default for AssetData { + fn default() -> Self { + AssetData::embedded(Vec::new()) + } +} + +/// Embedded bytes compare by content; linked ones are equal only as the same version. +impl PartialEq for AssetData { + fn eq(&self, other: &Self) -> bool { + match (&self.repr, &other.repr) { + (Repr::Embedded(a), Repr::Embedded(b)) => a == b, + (Repr::Linked(a), Repr::Linked(b)) => self.key == other.key && a.source.len == b.source.len, + _ => false, + } + } +} + +impl fmt::Debug for AssetData { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let kind = if self.is_linked() { "Linked" } else { "Embedded" }; + f.debug_struct(kind).field("key", &self.key.0).field("len", &self.len()).finish() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + pub(super) fn source(path: &str, len: u64) -> LinkedSource { + LinkedSource { path: path.into(), relative: None, document: None, len, fingerprint: None, hash: None } + } + + #[test] + fn clones_keep_the_key_and_new_bytes_get_a_new_one() { + let a = AssetData::embedded(vec![1, 2, 3]); + let b = a.clone(); + assert_eq!(a.key(), b.key()); + let c = AssetData::embedded(vec![1, 2, 3]); + assert_ne!(a.key(), c.key()); + assert_eq!(a, c, "embedded bytes compare by content"); + let shared = AssetData::embedded(Arc::clone(a.embedded_bytes().unwrap())); + assert_ne!(a.key(), shared.key(), "wrapping bytes again names a new version"); + assert_eq!(a.load().unwrap().as_slice(), [1, 2, 3]); + assert_eq!(a.len(), 3); + let weak = a.downgrade(); + assert_eq!(weak.upgrade().map(|d| d.key()), Some(a.key())); + drop((a, b)); + assert!(weak.upgrade().is_some(), "`shared` still holds the bytes"); + drop(shared); + assert!(weak.upgrade().is_none()); + } + + #[test] + fn linked_assets_keep_their_key_only_for_the_same_bytes() { + let mut s = source("/nowhere/no-loader.png", 10); + let l = AssetData::linked(s.clone()); + assert!(l.is_linked()); + assert_eq!(l.len(), 10); + assert!(l.embedded_bytes().is_none() && l.resident().is_none()); + assert!(AssetData::default().is_empty()); + assert_ne!(l.with_source(s.clone()).key(), l.key(), "no hash: nothing says the bytes are the same"); + s.hash = Some("sha256:00".into()); + let hashed = AssetData::linked(s.clone()); + s.path = "/elsewhere/no-loader.png".into(); + let moved = hashed.with_source(s.clone()); + assert_eq!((moved.key(), moved.linked_source().map(|s| s.path.as_str())), (hashed.key(), Some("/elsewhere/no-loader.png"))); + s.hash = Some("sha256:01".into()); + assert_ne!(hashed.with_source(s).key(), hashed.key(), "other bytes, another key"); + let weak = hashed.downgrade(); + drop(hashed); + assert!(weak.upgrade().is_some(), "a linked value holds no bytes to let go of"); + } + + #[test] + fn a_link_record_names_its_source() { + let fingerprint = Fingerprint { size: 7, mtime: 9 }; + let asset = crate::Asset { + link: Some("/a/b.png".into()), + link_relative: Some("b.png".into()), + link_fingerprint: Some(fingerprint), + link_hash: Some("sha256:ab".into()), + ..Default::default() + }; + let s = LinkedSource::of(&asset, Some(Path::new("/a/doc.dcx"))).unwrap(); + assert_eq!( + (s.len, s.fingerprint, s.relative.as_deref(), s.document.as_deref()), + (7, Some(fingerprint), Some("b.png"), Some(Path::new("/a/doc.dcx"))) + ); + assert!(LinkedSource::of(&crate::Asset { link_fingerprint: None, ..asset }, None).is_none(), "the size comes from the fingerprint"); + } +} diff --git a/crates/doc/src/asset_data/store.rs b/crates/doc/src/asset_data/store.rs new file mode 100644 index 000000000..787289a38 --- /dev/null +++ b/crates/doc/src/asset_data/store.rs @@ -0,0 +1,370 @@ +//! The process-wide store of linked files' bytes ([`super::AssetData::load`]). + +use std::collections::HashMap; +use std::sync::{Arc, Condvar, LazyLock, Mutex, MutexGuard, PoisonError, RwLock}; + +use super::{Linked, LinkedSource, SourceKey, Unavailable}; +use crate::datamerge::Fingerprint; + +/// Linked bytes kept in memory at most, over all files. A file larger than this is read for the +/// one load that asks for it and not kept. +pub const STORE_BUDGET: u64 = 512 << 20; + +/// The largest linked file read: a larger one is [`Unavailable::TooLarge`]. +pub const MAX_LINKED_BYTES: u64 = 1 << 30; + +/// A linked file's bytes as a [`Loader`] read them. +pub struct Loaded { + pub bytes: Vec, + /// The fingerprint the file had, when its bytes were found to be the expected ones by their + /// hash: later loads trust that fingerprint as they trust [`LinkedSource::fingerprint`]. + pub fingerprint: Option, +} + +/// Reads linked files (the engine's, [`install_loader`]). +pub trait Loader: Send + Sync { + /// The bytes of the file `source` names, if it holds the expected ones: its size is + /// `source.len`, and its fingerprint is `source.fingerprint` or `trusted`, or its content + /// hash is `source.hash`. Other bytes are [`Unavailable::Modified`]; no file is + /// [`Unavailable::Missing`]; one over [`MAX_LINKED_BYTES`] is [`Unavailable::TooLarge`]. + fn load(&self, source: &LinkedSource, trusted: Option) -> Result; + + /// The bytes the file `source` names has now, whatever they are (for output that uses the + /// current file of a modified link). Never cached. + fn load_current(&self, _source: &LinkedSource) -> Result, Unavailable> { + Err(Unavailable::NoLoader) + } + + /// Whether the file `source` names still holds `kept`, the bytes read from it earlier: by its + /// fingerprint as [`Self::load`] goes by it, else by its content hash, or for a source without + /// a hash by its bytes. → the file's fingerprint when it was read to tell, else `None`; + /// [`Unavailable::Modified`] when the files there hold other bytes. A loader that can't look + /// takes the kept bytes as the file's. + fn holds(&self, _source: &LinkedSource, _trusted: Option, _kept: &[u8]) -> Result, Unavailable> { + Ok(None) + } +} + +static LOADER: RwLock>> = RwLock::new(None); + +/// Read linked files with `loader` from now on (in the whole process). +pub fn install_loader(loader: Arc) { + *LOADER.write().unwrap_or_else(PoisonError::into_inner) = Some(loader); +} + +pub(super) fn installed() -> Option> { + LOADER.read().unwrap_or_else(PoisonError::into_inner).clone() +} + +pub(super) fn global() -> &'static Store { + static STORE: LazyLock = LazyLock::new(|| Store::new(STORE_BUDGET, MAX_LINKED_BYTES)); + &STORE +} + +type Outcome = Result>, Unavailable>; + +/// One load in progress, which the other loads of the same bytes wait for. +#[derive(Default)] +struct Flight { + outcome: Mutex>, + landed: Condvar, +} + +impl Flight { + fn wait(&self) -> Outcome { + let mut g = self.outcome.lock().unwrap_or_else(PoisonError::into_inner); + loop { + if let Some(outcome) = g.as_ref() { + return outcome.clone(); + } + g = self.landed.wait(g).unwrap_or_else(PoisonError::into_inner); + } + } +} + +struct Kept { + bytes: Arc>, + stamp: u64, +} + +#[derive(Default)] +struct Inner { + kept: HashMap, + flights: HashMap>, + bytes: u64, + clock: u64, +} + +impl Inner { + /// The bytes kept under `key`, marked used. + fn touch(&mut self, key: SourceKey) -> Option>> { + self.clock += 1; + let clock = self.clock; + self.kept.get_mut(&key).map(|k| { + k.stamp = clock; + Arc::clone(&k.bytes) + }) + } + + /// Keep `bytes` under `key`, dropping the least recently used others beyond `budget`. + fn keep(&mut self, key: SourceKey, bytes: Arc>, budget: u64) { + self.clock += 1; + let n = bytes.len() as u64; + if let Some(old) = self.kept.insert(key, Kept { bytes, stamp: self.clock }) { + self.bytes = self.bytes.saturating_sub(old.bytes.len() as u64); + } + self.bytes = self.bytes.saturating_add(n); + while self.bytes > budget { + let Some(oldest) = self.kept.iter().filter(|(k, _)| **k != key).min_by_key(|(_, k)| k.stamp).map(|(k, _)| *k) else { break }; + if let Some(old) = self.kept.remove(&oldest) { + self.bytes = self.bytes.saturating_sub(old.bytes.len() as u64); + } + } + } +} + +/// A single-flight, least-recently-used store of loaded bytes by [`SourceKey`]. +pub(super) struct Store { + inner: Mutex, + budget: u64, + cap: u64, +} + +/// Lands a flight when dropped: with its outcome, or as missing when the loader panicked, so +/// the loads waiting for it don't wait forever. +struct Landing<'a> { + store: &'a Store, + key: SourceKey, + flight: Arc, + outcome: Option, +} + +impl Drop for Landing<'_> { + fn drop(&mut self) { + let outcome = self.outcome.take().unwrap_or(Err(Unavailable::Missing)); + { + let mut g = self.store.lock(); + g.flights.remove(&self.key); + if let Ok(bytes) = &outcome + && bytes.len() as u64 <= self.store.budget + { + g.keep(self.key, Arc::clone(bytes), self.store.budget); + } + } + *self.flight.outcome.lock().unwrap_or_else(PoisonError::into_inner) = Some(outcome); + self.flight.landed.notify_all(); + } +} + +impl Store { + pub(super) fn new(budget: u64, cap: u64) -> Self { + Store { inner: Mutex::new(Inner::default()), budget, cap } + } + + fn lock(&self) -> MutexGuard<'_, Inner> { + self.inner.lock().unwrap_or_else(PoisonError::into_inner) + } + + /// The bytes of `linked`, kept under `key`: from the store, from a load of them in progress, + /// or read by `loader`. + pub(super) fn load(&self, key: SourceKey, linked: &Linked, loader: Option<&dyn Loader>) -> Outcome { + if linked.source.len > self.cap { + return Err(Unavailable::TooLarge); + } + let flight = { + let mut g = self.lock(); + if let Some(bytes) = g.touch(key) { + return Ok(bytes); + } + if let Some(f) = g.flights.get(&key).cloned() { + drop(g); + return f.wait(); + } + let Some(loader) = loader else { return Err(Unavailable::NoLoader) }; + let f = Arc::new(Flight::default()); + g.flights.insert(key, Arc::clone(&f)); + (f, loader) + }; + let (flight, loader) = flight; + let mut landing = Landing { store: self, key, flight, outcome: None }; + // Read outside the lock: other bytes load and are found meanwhile. + let outcome = match loader.load(&linked.source, linked.trusted()) { + Ok(l) if l.bytes.len() as u64 > self.cap => Err(Unavailable::TooLarge), + Ok(l) => { + if let Some(fingerprint) = l.fingerprint { + linked.trust(fingerprint); + } + Ok(Arc::new(l.bytes)) + } + Err(e) => Err(e), + }; + landing.outcome = Some(outcome.clone()); + drop(landing); + outcome + } + + /// The bytes kept under `key`, without loading them. + pub(super) fn resident(&self, key: SourceKey) -> Option>> { + self.lock().touch(key) + } + + /// Keep `bytes` under `key` as if a load had read them (not when over the budget). + pub(super) fn keep(&self, key: SourceKey, bytes: Arc>) { + if bytes.len() as u64 <= self.budget { + self.lock().keep(key, bytes, self.budget); + } + } + + pub(super) fn evict(&self, key: SourceKey) { + let mut g = self.lock(); + if let Some(old) = g.kept.remove(&key) { + g.bytes = g.bytes.saturating_sub(old.bytes.len() as u64); + } + } + + #[cfg(test)] + fn kept_bytes(&self) -> u64 { + self.lock().bytes + } +} + +#[cfg(test)] +mod tests { + use super::super::tests::source; + use super::super::{AssetData, Repr}; + use super::*; + use std::sync::atomic::{AtomicUsize, Ordering}; + + /// Serves `len` bytes of `fill` for every path, counting its reads; slow, so loads overlap. + #[derive(Default)] + struct Counting { + reads: AtomicUsize, + delay_ms: u64, + fail: Option, + trusted: Mutex>>, + } + + impl Loader for Counting { + fn load(&self, source: &LinkedSource, trusted: Option) -> Result { + self.reads.fetch_add(1, Ordering::SeqCst); + self.trusted.lock().unwrap().push(trusted); + std::thread::sleep(std::time::Duration::from_millis(self.delay_ms)); + if let Some(e) = self.fail { + return Err(e); + } + let fill = source.path.bytes().last().unwrap_or(0); + Ok(Loaded { bytes: vec![fill; source.len as usize], fingerprint: Some(Fingerprint { size: source.len, mtime: 5 }) }) + } + } + + fn linked(data: &AssetData) -> &Linked { + match &data.repr { + Repr::Linked(l) => l, + Repr::Embedded(_) => panic!("not linked"), + } + } + + fn load(store: &Store, data: &AssetData, loader: &dyn Loader) -> Outcome { + store.load(data.key(), linked(data), Some(loader)) + } + + #[test] + fn linked_bytes_are_read_once_and_kept() { + let store = Store::new(100, 1000); + let loader = Counting::default(); + let a = AssetData::linked(source("a", 10)); + assert_eq!(load(&store, &a, &loader).unwrap().as_slice(), [b'a'; 10]); + assert_eq!(load(&store, &a.clone(), &loader).unwrap().len(), 10); + assert_eq!(loader.reads.load(Ordering::SeqCst), 1); + assert_eq!(store.resident(a.key()).map(|b| b.len()), Some(10)); + assert_eq!(*loader.trusted.lock().unwrap(), [None]); + store.evict(a.key()); + load(&store, &a, &loader).unwrap(); + assert_eq!(loader.reads.load(Ordering::SeqCst), 2, "evicted bytes are read again"); + assert_eq!( + loader.trusted.lock().unwrap().last(), + Some(&Some(Fingerprint { size: 10, mtime: 5 })), + "a hash-checked fingerprint is trusted next time" + ); + assert_eq!(AssetData::linked(source("x", 1)).load(), Err(Unavailable::NoLoader), "no loader installed in these tests"); + } + + #[test] + fn the_least_recently_used_bytes_go_past_the_budget() { + let store = Store::new(100, 1000); + let loader = Counting::default(); + let [a, b, c] = ["a", "b", "c"].map(|p| AssetData::linked(source(p, 40))); + load(&store, &a, &loader).unwrap(); + load(&store, &b, &loader).unwrap(); + load(&store, &a, &loader).unwrap(); + load(&store, &c, &loader).unwrap(); + assert!(store.resident(b.key()).is_none(), "b was used least recently"); + assert!(store.resident(a.key()).is_some() && store.resident(c.key()).is_some()); + assert_eq!(store.kept_bytes(), 80); + } + + #[test] + fn a_file_over_the_budget_is_returned_but_not_kept_and_one_over_the_cap_is_not_read() { + let store = Store::new(100, 1000); + let loader = Counting::default(); + let small = AssetData::linked(source("s", 50)); + load(&store, &small, &loader).unwrap(); + let big = AssetData::linked(source("b", 200)); + assert_eq!(load(&store, &big, &loader).unwrap().len(), 200); + assert!(store.resident(big.key()).is_none()); + assert!(store.resident(small.key()).is_some(), "an unkept file evicts nothing"); + let huge = AssetData::linked(source("h", 1001)); + assert_eq!(load(&store, &huge, &loader), Err(Unavailable::TooLarge)); + assert_eq!(loader.reads.load(Ordering::SeqCst), 2); + } + + #[test] + fn concurrent_loads_of_the_same_bytes_read_once() { + let store = Store::new(1000, 1000); + let loader = Counting { delay_ms: 50, ..Default::default() }; + let a = AssetData::linked(source("a", 10)); + let got: Vec = std::thread::scope(|s| { + let handles: Vec<_> = (0..8).map(|_| s.spawn(|| load(&store, &a, &loader))).collect(); + handles.into_iter().map(|h| h.join().unwrap()).collect() + }); + assert!(got.iter().all(|g| g.as_ref().is_ok_and(|b| b.len() == 10))); + assert_eq!(loader.reads.load(Ordering::SeqCst), 1); + } + + #[test] + fn a_failed_load_is_shared_and_tried_again_later() { + let store = Store::new(1000, 1000); + let loader = Counting { delay_ms: 30, fail: Some(Unavailable::Modified), ..Default::default() }; + let a = AssetData::linked(source("a", 10)); + let got: Vec = std::thread::scope(|s| { + let handles: Vec<_> = (0..4).map(|_| s.spawn(|| load(&store, &a, &loader))).collect(); + handles.into_iter().map(|h| h.join().unwrap()).collect() + }); + assert!(got.iter().all(|g| *g == Err(Unavailable::Modified))); + assert!(store.resident(a.key()).is_none(), "nothing adopted"); + let reads = loader.reads.load(Ordering::SeqCst); + load(&store, &a, &loader).unwrap_err(); + assert_eq!(loader.reads.load(Ordering::SeqCst), reads + 1, "failures aren't remembered here"); + } + + /// A loader that panics lands its flight: the loads waiting for it return. + #[test] + fn a_panicking_loader_does_not_hang_the_waiters() { + struct Panics; + impl Loader for Panics { + fn load(&self, _: &LinkedSource, _: Option) -> Result { + std::thread::sleep(std::time::Duration::from_millis(30)); + panic!("loader fault"); + } + } + let store = Store::new(1000, 1000); + let a = AssetData::linked(source("a", 10)); + std::thread::scope(|s| { + let first = s.spawn(|| load(&store, &a, &Panics)); + std::thread::sleep(std::time::Duration::from_millis(5)); + let waiter = s.spawn(|| load(&store, &a, &Panics)); + assert!(first.join().is_err()); + assert!(waiter.join().is_ok_and(|r| r.is_err())); + }); + } +} diff --git a/crates/doc/src/assets.rs b/crates/doc/src/assets.rs index 0d100cee7..18f07326f 100644 --- a/crates/doc/src/assets.rs +++ b/crates/doc/src/assets.rs @@ -108,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()), + } } } @@ -132,7 +147,7 @@ pub fn insert_asset(assets: &mut BTreeMap>, mut asset: Asset 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)); @@ -165,7 +180,7 @@ impl AssetIndex { assets.insert(id, Arc::new(asset)); return id; } - let hash = self.fingerprint.hash_one(asset.data.as_slice()); + 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; @@ -173,7 +188,7 @@ impl AssetIndex { 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 = Arc::clone(&a.data), + Some(a) => asset.data = a.data.clone(), None => bucket.push(asset.id), } } @@ -381,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)) { @@ -411,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] @@ -426,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()); } } @@ -547,7 +568,10 @@ mod tests { assert_eq!(s, i); } assert_eq!(scanned.keys().collect::>(), indexed.keys().collect::>()); - assert!(Arc::ptr_eq(&indexed[&AssetId(5)].data, &indexed[&AssetId(6)].data), "identical bytes share one buffer"); + 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 @@ -581,7 +605,10 @@ mod tests { assert!(embedded != a && a != b && embedded != b); assert_eq!(d.assets[&embedded].link, None); assert_eq!(d.assets[&b].link.as_deref(), Some("/q/b.png")); - assert!(Arc::ptr_eq(&d.assets[&a].data, &d.assets[&b].data), "identical bytes share one buffer"); + assert!( + Arc::ptr_eq(d.assets[&a].data.embedded_bytes().unwrap(), d.assets[&b].data.embedded_bytes().unwrap()), + "identical bytes share one buffer" + ); } #[test] diff --git a/crates/doc/src/build.rs b/crates/doc/src/build.rs index f64394e03..3fc1062a7 100644 --- a/crates/doc/src/build.rs +++ b/crates/doc/src/build.rs @@ -165,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 { diff --git a/crates/doc/src/edit.rs b/crates/doc/src/edit.rs index cadc3d419..628fc8ee6 100644 --- a/crates/doc/src/edit.rs +++ b/crates/doc/src/edit.rs @@ -28,6 +28,22 @@ pub struct ItemLoc { pub path: ItemPath, } +/// A gap between adjacent items (or between an item and the page edge) on a spread. +#[derive(Clone, Debug, PartialEq)] +pub struct Gap { + /// True for a vertical gap (between left and right neighbours, moving along X); + /// false for a horizontal gap (between top and bottom neighbours, moving along Y). + pub vertical: bool, + /// Leading edge of the gap along its movement axis. + pub a: f64, + /// Trailing edge of the gap along its movement axis. + pub z: f64, + /// Items ending at `a` that resize when the gap moves. + pub before: Vec, + /// Items starting at `z` that resize when the gap moves. + pub after: Vec, +} + impl ItemLoc { /// Top-level index in the spread. pub fn top(&self) -> usize { @@ -648,6 +664,38 @@ impl Document { .map(|it| it.id) } + /// The gap at `p` (spread space) on spread `sr`: between left and right neighbours (vertical + /// gap moving along X), or above and below (horizontal gap moving along Y). + pub fn find_gap(&self, sr: SpreadRef, p: Point) -> Option { + let sp = self.spread(sr)?; + let page = sp.page_at_x(p.x).and_then(|i| sp.pages.get(i)).map(|pg| pg.bounds())?; + let items: Vec<(ItemId, Rect)> = sp + .items + .iter() + .filter(|it| !it.hidden && !it.locked && self.layer(it.layer).is_none_or(|l| !l.locked && l.visible)) + .map(|it| (it.id, it.bounds())) + .collect(); + if items.iter().any(|(_, b)| b.contains(p)) { + return None; + } + // Between left and right neighbours (a vertical gap), or above and below (horizontal). + let side = |vertical: bool| { + let (pos, lo, hi) = if vertical { (p.x, page.x0, page.x1) } else { (p.y, page.y0, page.y1) }; + let across = |b: &Rect| if vertical { b.y0 <= p.y && p.y <= b.y1 } else { b.x0 <= p.x && p.x <= b.x1 }; + let end = |b: &Rect| if vertical { b.x1 } else { b.y1 }; + let start = |b: &Rect| if vertical { b.x0 } else { b.y0 }; + let a = items.iter().filter(|(_, b)| across(b) && end(b) <= pos).map(|(_, b)| end(b)).fold(lo, f64::max); + let z = items.iter().filter(|(_, b)| across(b) && start(b) >= pos).map(|(_, b)| start(b)).fold(hi, f64::min); + let before: Vec = items.iter().filter(|(_, b)| across(b) && (end(b) - a).abs() < 0.5).map(|(i, _)| *i).collect(); + let after: Vec = items.iter().filter(|(_, b)| across(b) && (start(b) - z).abs() < 0.5).map(|(i, _)| *i).collect(); + (!before.is_empty() || !after.is_empty()).then_some(Gap { vertical, a, z, before, after }) + }; + match (side(true), side(false)) { + (Some(v), Some(h)) => Some(if v.z - v.a <= h.z - h.a { v } else { h }), + (v, h) => v.or(h), + } + } + /// The first item on a document or parent spread whose geometry isn't finite /// ([`Item::geometry_is_finite`]). pub fn non_finite_item(&self) -> Option { diff --git a/crates/doc/src/item.rs b/crates/doc/src/item.rs index d99bfebd4..29b97e15d 100644 --- a/crates/doc/src/item.rs +++ b/crates/doc/src/item.rs @@ -29,8 +29,8 @@ pub use paint::{ path_length_bound, }; pub use text_frame::{ - AutoSize, ColumnsKind, ContourType, FirstBaseline, FrameBaselineGrid, FrameGridRelative, PathAlign, PathType, TextFrame, TextFrameOptions, - TextWrap, VerticalJustification, WrapMode, WrapSide, vertical_text_xf, + AutoSize, ColumnsKind, ContourType, DEFAULT_ALPHA_THRESHOLD, FirstBaseline, FrameBaselineGrid, FrameGridRelative, PathAlign, PathType, TextFrame, + TextFrameOptions, TextWrap, VerticalJustification, WrapMode, WrapSide, vertical_text_xf, }; fn is_zero_usize(v: &usize) -> bool { diff --git a/crates/doc/src/item/effects.rs b/crates/doc/src/item/effects.rs index 46aac2e95..5babfbe40 100644 --- a/crates/doc/src/item/effects.rs +++ b/crates/doc/src/item/effects.rs @@ -308,6 +308,8 @@ impl Effects { ds.size = len("dropShadow.size", ds.size)?; ds.spread = pct("dropShadow.spread", ds.spread)?; self.feather = len("feather", self.feather)?; + // As IDML import reads it, so a round trip keeps it. + self.feather_options.choke = pct("featherOptions.choke", self.feather_options.choke)?; let e = &mut self.inner_shadow; e.opacity = opacity("innerShadow.opacity", e.opacity)?; e.angle = finite("innerShadow.angle", e.angle)?; diff --git a/crates/doc/src/item/text_frame.rs b/crates/doc/src/item/text_frame.rs index d8f7f29e3..3c9452546 100644 --- a/crates/doc/src/item/text_frame.rs +++ b/crates/doc/src/item/text_frame.rs @@ -240,6 +240,65 @@ impl Default for TextFrameOptions { } } +impl TextFrameOptions { + /// The JSON keys of the General options: columns, inset spacing, vertical justification and + /// Ignore Text Wrap. An object style's Text Frame General Options category sets these only. + pub const GENERAL_KEYS: [&str; 9] = [ + "columns", + "columnsKind", + "gutter", + "columnWidth", + "balanceColumns", + "inset", + "verticalJustification", + "vjParagraphSpacingLimit", + "ignoreWrap", + ]; + + /// Whether the General options (see [`Self::GENERAL_KEYS`]) of `self` and `other` are the same. + pub fn general_eq(&self, other: &TextFrameOptions) -> bool { + self.columns == other.columns + && self.columns_kind == other.columns_kind + && self.gutter == other.gutter + && self.column_width == other.column_width + && self.balance_columns == other.balance_columns + && self.inset == other.inset + && self.vertical_justification == other.vertical_justification + && self.vj_paragraph_spacing_limit == other.vj_paragraph_spacing_limit + && self.ignore_wrap == other.ignore_wrap + } + + /// Each General option that is `old`'s here takes `new`'s; the others stay. `true` when one + /// changed. + pub fn follow_general(&mut self, old: &TextFrameOptions, new: &TextFrameOptions) -> bool { + let mut changed = false; + macro_rules! follow { + ($($f:ident),*) => {$( + if self.$f == old.$f && self.$f != new.$f { + self.$f = new.$f; + changed = true; + } + )*}; + } + follow!(columns, columns_kind, gutter, column_width, balance_columns, inset, vertical_justification, vj_paragraph_spacing_limit, ignore_wrap); + changed + } + + /// Copies the General options of `from` (see [`Self::GENERAL_KEYS`]). Baseline, auto-size, + /// column rule and Type on a Path settings stay as they are. + pub fn set_general(&mut self, from: &TextFrameOptions) { + self.columns = from.columns; + self.columns_kind = from.columns_kind; + self.gutter = from.gutter; + self.column_width = from.column_width; + self.balance_columns = from.balance_columns; + self.inset = from.inset; + self.vertical_justification = from.vertical_justification; + self.vj_paragraph_spacing_limit = from.vj_paragraph_spacing_limit; + self.ignore_wrap = from.ignore_wrap; + } +} + #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub enum WrapMode { @@ -272,7 +331,7 @@ pub enum ContourType { BoundingBox, /// Edges detected in the image. Composition follows the frame path. DetectEdges, - /// The image's alpha channel. Composition follows the frame path. + /// The image's alpha channel. Composition follows the outline of the image's visible pixels. AlphaChannel, /// A path saved in the image. Composition follows the frame path. PhotoshopPath, @@ -284,7 +343,7 @@ pub enum ContourType { } /// Text Wrap panel settings. -#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase", default)] pub struct TextWrap { pub mode: WrapMode, @@ -298,6 +357,35 @@ pub struct TextWrap { /// item transforms it with the path; other path edits keep it as it is. #[serde(skip_serializing_if = "Option::is_none")] pub path: Option, + /// Contour Options › Include Inside Edges: an Alpha Channel contour also lets text into the + /// transparent holes it encloses (off: holes are blocked with the shape around them). + #[serde(skip_serializing_if = "std::ops::Not::not")] + pub inside_edges: bool, + /// Alpha Channel contour: pixels more opaque than this (0..254) count as the image. + #[serde(skip_serializing_if = "is_default_alpha_threshold")] + pub alpha_threshold: u8, +} + +/// DesignCraft's default alpha threshold for Alpha Channel contour wraps. +pub const DEFAULT_ALPHA_THRESHOLD: u8 = 25; + +fn is_default_alpha_threshold(t: &u8) -> bool { + *t == DEFAULT_ALPHA_THRESHOLD +} + +impl Default for TextWrap { + fn default() -> Self { + TextWrap { + mode: WrapMode::default(), + offsets: [0.0; 4], + invert: false, + side: WrapSide::default(), + contour: ContourType::default(), + path: None, + inside_edges: false, + alpha_threshold: DEFAULT_ALPHA_THRESHOLD, + } + } } impl TextWrap { diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index d9ee6d3e9..1efadfe2a 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -12,6 +12,7 @@ pub mod anchored; pub mod arabic; pub mod arrow; +pub mod asset_data; pub mod assets; pub mod attrs; pub mod build; @@ -44,6 +45,7 @@ use std::collections::BTreeMap; use std::sync::Arc; pub use anchored::{AnchorPosition, AnchoredObject, OBJECT_MARK}; +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::{ @@ -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}; @@ -251,6 +253,52 @@ impl Document { pub fn conditions_hide(&self, conds: &[String]) -> bool { !conds.is_empty() && conds.iter().all(|c| self.conditions.iter().any(|x| x.name == *c && !x.visible)) } + + /// Is text with character format `f`, in a paragraph whose base character attributes are + /// `base` (`Styles::resolve_para`), left off the page: hidden by its effective conditions + /// (the paragraph's and character style's included) or marked deleted? Exports leave it out + /// as composition does. + pub fn hides_run(&self, base: &CharProps, f: &CharFormat) -> bool { + let props = self.styles.resolve_char(base, f); + props.change == ChangeMark::Deleted || self.conditions_hide(&props.conditions) + } + + /// The byte ranges of `st` that show, in order: the runs [`Self::hides_run`] hides left out. + /// Paragraphs and runs are walked together, once; take it once per story. + pub fn visible_spans(&self, st: &Story) -> Vec> { + let mut out: Vec> = Vec::new(); + let runs: Vec<(std::ops::Range, &CharFormat)> = st.runs().collect(); + let mut k = 0; + for (pi, pr) in st.para_ranges().iter().enumerate() { + let base = st.paras.get(pi).map(|pf| self.styles.resolve_para(pf).1).unwrap_or_default(); + while runs.get(k).is_some_and(|(rr, _)| rr.end <= pr.start) { + k += 1; + } + for (rr, f) in runs.iter().skip(k).take_while(|(rr, _)| rr.start < pr.end) { + let (a, b) = (rr.start.max(pr.start), rr.end.min(pr.end)); + if a >= b || self.hides_run(&base, f) { + continue; + } + match out.last_mut() { + Some(last) if last.end == a => last.end = b, + _ => out.push(a..b), + } + } + } + out + } + + /// The text of `st` within `range` that lies in `spans` ([`Self::visible_spans`] of `st`). + pub fn visible_text(st: &Story, spans: &[std::ops::Range], range: std::ops::Range) -> String { + let first = spans.partition_point(|s| s.end <= range.start); + let mut out = String::new(); + for s in spans.iter().skip(first).take_while(|s| s.start < range.end) { + if let Some(t) = st.text.get(s.start.max(range.start)..s.end.min(range.end)) { + out.push_str(t); + } + } + out + } } /// Ink Manager settings for output, by swatch name. Output applies them through a @@ -574,8 +622,20 @@ pub struct Asset { /// clears them. #[serde(default, skip_serializing_if = "Option::is_none")] pub link_fingerprint: Option, + /// `link` relative to the document's folder, for finding the file after both moved. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub link_relative: Option, + /// The linked file's content hash (`sha256:` and hex digits). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub link_hash: Option, + /// Whether a save writes the bytes into the document or only the link to them. + #[serde(default, skip_serializing_if = "Storage::is_embedded")] + pub storage: Storage, + /// A small preview drawn while the full file can't be read. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub proxy: Option, #[serde(skip)] - pub data: Arc>, + pub data: AssetData, /// Pixel size for raster images. #[serde(default, skip_serializing_if = "Option::is_none")] pub pixels: Option<(u32, u32)>, @@ -593,7 +653,42 @@ pub struct Asset { pub pdf_box: Option<[f64; 4]>, } +/// An asset's bytes for output ([`Asset::output_bytes`]) and what to tell the user about them. +pub struct OutputBytes { + pub bytes: std::sync::Arc>, + /// A warning to report: the file on disk replaced a changed original, or the proxy stands in + /// for a missing one. + pub warning: Option, + /// The bytes are the asset's preview, not the original (a missing or unreadable link). + pub proxied: bool, +} + impl Asset { + /// The bytes an export uses: the original (a changed linked file's current bytes, with a + /// warning), or for a missing or unreadable one its proxy, with a warning. `Err` when + /// there is neither. + pub fn output_bytes(&self) -> std::result::Result { + match self.data.load_for_output() { + Ok((bytes, false)) => Ok(OutputBytes { bytes, warning: None, proxied: false }), + Ok((bytes, true)) => Ok(OutputBytes { + bytes, + warning: Some(format!("the linked file `{}` has changed; the file on disk is used", self.name)), + proxied: false, + }), + Err(e) => { + let proxy = self.proxy.as_ref().and_then(|p| p.data.load().ok()); + match proxy { + Some(bytes) => Ok(OutputBytes { + bytes, + warning: Some(format!("the linked file `{}` is unavailable ({e}); its preview is used", self.name)), + proxied: true, + }), + None => Err(e), + } + } + } + } + /// The part of the page a placed PDF shows, when [`Asset::pdf_box`] holds a usable box. pub fn shown_box(&self) -> Option<[f64; 4]> { self.shown(self.pdf_box?) @@ -614,6 +709,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")] @@ -657,6 +786,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 { @@ -713,6 +885,10 @@ pub struct Document { pub sections: Vec
, #[serde(default)] pub assets: BTreeMap>, + /// Alpha Channel contour outlines of placed images (see [`AlphaOutline`]), sorted by asset + /// and then threshold, at most one for each pair. Not saved. + #[serde(skip)] + pub alpha_outlines: Vec>, /// Hyperlinks (Window → Interactive → Hyperlinks). #[serde(default, skip_serializing_if = "Vec::is_empty")] pub hyperlinks: Vec, @@ -1023,6 +1199,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) } diff --git a/crates/doc/src/styles.rs b/crates/doc/src/styles.rs index 8aa5c8132..3a5ea58c3 100644 --- a/crates/doc/src/styles.rs +++ b/crates/doc/src/styles.rs @@ -1,10 +1,11 @@ //! Paragraph, character and object styles with based-on inheritance. +use designcraft_geom::corners::CornerOptions; use serde::{Deserialize, Serialize}; use crate::attrs::{CharAttrs, CharProps, ParaAttrs, ParaProps}; use crate::item::{Effects, Fill, Item, Stroke, TextFrameOptions}; -use crate::story::{BASIC_PARAGRAPH, CharFormat, NO_CHAR_STYLE, ParaFormat}; +use crate::story::{BASIC_PARAGRAPH, CharFormat, NO_CHAR_STYLE, ParaFormat, Story}; pub const NO_PARA_STYLE: &str = "[No Paragraph Style]"; pub const BASIC_GRAPHICS_FRAME: &str = "[Basic Graphics Frame]"; @@ -53,17 +54,30 @@ pub struct ObjectStyle { pub stroke: Option, #[serde(skip_serializing_if = "Option::is_none")] pub paragraph_style: Option, + /// Paragraph Styles › Apply Next Style: the paragraph style goes on a text frame's first + /// paragraph, and each paragraph after it takes the Next Style of the one before. + #[serde(skip_serializing_if = "std::ops::Not::not")] + pub apply_next_style: bool, #[serde(skip_serializing_if = "Option::is_none")] pub text_frame: Option, /// Effects (drop shadow, feather, glows…). An item using the style follows them until its own /// effects differ from the style's (a local override). #[serde(skip_serializing_if = "Option::is_none")] pub effects: Option, + /// Corner Options (Stroke & Corner Options): each corner's shape and size, by name (top left, + /// top right, bottom right, bottom left), as InDesign's; an item takes them at the anchors at + /// those corners ([`CornerOptions::named_to_path`]). + #[serde(skip_serializing_if = "Option::is_none")] + pub corners: Option, } impl ObjectStyle { - /// Gives `it` the fill, stroke, effects and text frame options this style sets. + /// Gives `it` the fill, stroke, corners, effects and text frame General options this style + /// sets. A text frame keeps its baseline, auto-size, column rule and Type on a Path settings. pub fn apply_to(&self, it: &mut Item) { + if let Some(c) = self.corners { + it.corners = c.named_to_path(&it.path); + } if let Some(f) = &self.fill { it.fill = f.clone(); } @@ -74,9 +88,62 @@ impl ObjectStyle { it.effects = e.clone(); } if let (Some(tf), Some(o)) = (it.text_frame_mut(), &self.text_frame) { - tf.options = o.clone(); + tf.options.set_general(o); } } + + /// The paragraph style of each of a text frame's `n` paragraphs under this style: its + /// paragraph style for all of them, or with Apply Next Style that one first and then each + /// one's Next Style. `None` when the style sets no paragraph style. + pub fn paragraph_styles(&self, styles: &Styles, n: usize) -> Option> { + let mut cur = self.paragraph_style.clone()?; + let mut out = Vec::with_capacity(n); + for _ in 0..n { + out.push(cur.clone()); + if self.apply_next_style + && let Some(next) = styles.para(&cur).and_then(|s| s.next_style.clone()) + { + cur = next; + } + } + Some(out) + } + + /// Whether a story's paragraphs are in the paragraph styles this style gives them (they + /// always are when it sets none). + pub fn story_follows(&self, styles: &Styles, st: &Story) -> bool { + self.paragraph_styles(styles, st.paras.len()).is_none_or(|want| st.paras.iter().zip(&want).all(|(f, w)| f.style == *w)) + } + + /// After an edit from `old`: the paragraphs of `st` still in the paragraph style `old` gives + /// them (every paragraph, when `old` set none) with the one this style gives each, where that + /// differs. A paragraph in another style is left out. + pub fn restyle_from(&self, old: &ObjectStyle, styles: &Styles, st: &Story) -> Vec<(usize, String)> { + let n = st.paras.len(); + let Some(want) = self.paragraph_styles(styles, n) else { return Vec::new() }; + let was = old.paragraph_styles(styles, n); + st.paras + .iter() + .zip(want) + .enumerate() + .filter(|(i, (f, w))| was.as_ref().is_none_or(|was| f.style == was[*i]) && f.style != *w) + .map(|(i, (_, w))| (i, w)) + .collect() + } + + /// Put a story's paragraphs in the paragraph styles this style gives them; `false` when it + /// sets none or they already are. + pub fn restyle(&self, styles: &Styles, st: &mut Story) -> bool { + if self.story_follows(styles, st) { + return false; + } + let Some(want) = self.paragraph_styles(styles, st.paras.len()) else { return false }; + for (f, w) in st.paras.iter_mut().zip(want) { + f.style = w; + } + st.rev = st.rev.wrapping_add(1); + true + } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index d4011d895..954385e38 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -8,6 +8,10 @@ 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-print = { workspace = true } craft-docpath = { workspace = true } @@ -38,6 +42,8 @@ craft-xml-dtd = { workspace = true } craft-svg = { workspace = true } caseless = { workspace = true } unicode-segmentation = { workspace = true } +# Content hashes of linked files (`asset_io::content_hash`). +sha2 = "0.10" [target.'cfg(not(target_arch = "wasm32"))'.dependencies] craft-atomic = { workspace = true } diff --git a/crates/engine/src/asset_io.rs b/crates/engine/src/asset_io.rs new file mode 100644 index 000000000..1f3b917e5 --- /dev/null +++ b/crates/engine/src/asset_io.rs @@ -0,0 +1,322 @@ +//! Reading linked files' bytes for the document model ([`designcraft_doc::asset_data`]): the +//! [`Loader`] every [`crate::Session`] installs. Files are read through [`crate::io`] (the +//! automation roots of the loading thread apply) and only ever yield the bytes the link record +//! names: other bytes at the path are [`Unavailable::Modified`] and are never handed out. +//! +//! The web build installs no loader: its linked assets are [`Unavailable::NoLoader`]. + +use std::path::{Path, PathBuf}; + +use designcraft_doc::asset_data::{Loaded, Loader, MAX_LINKED_BYTES}; +use designcraft_doc::{Fingerprint, LinkedSource, Unavailable}; + +/// Read linked files with [`FileLoader`] in this process (on the web: nothing to install). +pub fn install() { + #[cfg(not(target_arch = "wasm32"))] + designcraft_doc::asset_data::install_loader(std::sync::Arc::new(FileLoader)); +} + +/// The engine's [`Loader`]: [`read_linked`]. +pub struct FileLoader; + +impl Loader for FileLoader { + fn load(&self, source: &LinkedSource, trusted: Option) -> Result { + read_linked(source, trusted) + } + + fn load_current(&self, source: &LinkedSource) -> Result, Unavailable> { + read_current(source) + } + + fn holds(&self, source: &LinkedSource, trusted: Option, kept: &[u8]) -> Result, Unavailable> { + still_holds(source, trusted, kept) + } +} + +/// Whether a candidate file ([`candidates`]) still holds `kept`, the bytes read for `source` +/// earlier ([`Loader::holds`]): one of `source.len` bytes with the recorded or `trusted` +/// fingerprint (nothing is read), else one whose content hash is `source.hash`, or without a +/// hash whose bytes are `kept`. → the fingerprint of a file that was read to tell. +pub fn still_holds(source: &LinkedSource, trusted: Option, kept: &[u8]) -> Result, Unavailable> { + let mut seen = false; + for path in candidates(source) { + let Some(meta) = crate::io::file_metadata(&path) else { continue }; + seen = true; + let found = fingerprint_from(&meta); + if found.size != source.len { + continue; + } + if has_time(&found) && (Some(found) == source.fingerprint || Some(found) == trusted) { + return Ok(None); + } + let Ok(bytes) = crate::io::read_capped(&path, source.len) else { continue }; + let same = match &source.hash { + Some(hash) => *hash == content_hash(&bytes), + None => bytes == kept, + }; + if same { + return Ok(has_time(&found).then_some(found)); + } + } + Err(if seen { Unavailable::Modified } else { Unavailable::Missing }) +} + +/// The bytes of the first candidate file that exists, whatever they are (no fingerprint or hash +/// check): what an export uses for a link whose file has changed. +pub fn read_current(source: &LinkedSource) -> Result, Unavailable> { + for path in candidates(source) { + let Some(meta) = crate::io::file_metadata(&path) else { continue }; + if meta.len() > MAX_LINKED_BYTES { + return Err(Unavailable::TooLarge); + } + if let Ok(bytes) = crate::io::read_capped(&path, MAX_LINKED_BYTES) { + return Ok(bytes); + } + } + Err(Unavailable::Missing) +} + +/// `sha256:` and the hex digits of the SHA-256 of `bytes` ([`designcraft_doc::Asset::link_hash`]). +pub fn content_hash(bytes: &[u8]) -> String { + use sha2::Digest; + use std::fmt::Write; + let digest = sha2::Sha256::digest(bytes); + let mut out = String::with_capacity(7 + 64); + out.push_str("sha256:"); + for b in digest { + let _ = write!(out, "{b:02x}"); + } + out +} + +/// Size and modification time (whole seconds) from a file's metadata, as link records store them. +pub fn fingerprint_from(meta: &crate::io::Metadata) -> Fingerprint { + let mtime = meta + .modified() + .ok() + .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok()) + .map(|d| i64::try_from(d.as_secs()).unwrap_or(i64::MAX)) + .unwrap_or(0); + Fingerprint { size: meta.len(), mtime } +} + +/// Whether `f` has a modification time to tell the file by: [`fingerprint_from`] gives 0 where +/// the file system reports none, and two such files of one size would look the same. +pub fn has_time(f: &Fingerprint) -> bool { + f.mtime != 0 +} + +/// The files that may hold `source`'s bytes, in the order they are tried: the absolute path, +/// then the relative one resolved against the document. Paths [`crate::io::document_path`] +/// refuses are left out. +pub fn candidates(source: &LinkedSource) -> Vec { + let document = source.document.as_deref(); + let mut out: Vec = crate::io::document_path(&source.path, document).into_iter().collect(); + if let (Some(relative), Some(document)) = (source.relative.as_deref(), document) + && let Ok(p) = crate::io::document_path(relative, Some(document)) + && !out.contains(&p) + { + out.push(p); + } + out +} + +/// Why one candidate file doesn't serve. +enum Miss { + Absent, + Modified, + TooLarge, +} + +/// The bytes of the first candidate file ([`candidates`]) that holds `source`'s bytes: one of +/// `source.len` bytes whose fingerprint is `source.fingerprint` or `trusted`, or whose content +/// hash is `source.hash`. A source that records neither fingerprint nor hash is taken by its +/// size. The fingerprint of a file accepted by its hash is returned with the bytes. +pub fn read_linked(source: &LinkedSource, trusted: Option) -> Result { + if source.len > MAX_LINKED_BYTES { + return Err(Unavailable::TooLarge); + } + let mut worst = Miss::Absent; + for path in candidates(source) { + match read_candidate(&path, source, trusted) { + Ok(loaded) => return Ok(loaded), + Err(Miss::Absent) => {} + Err(miss @ Miss::TooLarge) => worst = miss, + Err(Miss::Modified) => { + if !matches!(worst, Miss::TooLarge) { + worst = Miss::Modified; + } + } + } + } + Err(match worst { + Miss::Absent => Unavailable::Missing, + Miss::Modified => Unavailable::Modified, + Miss::TooLarge => Unavailable::TooLarge, + }) +} + +fn read_candidate(path: &Path, source: &LinkedSource, trusted: Option) -> Result { + let meta = crate::io::file_metadata(path).ok_or(Miss::Absent)?; + let found = fingerprint_from(&meta); + if found.size > MAX_LINKED_BYTES { + return Err(Miss::TooLarge); + } + if found.size != source.len { + return Err(Miss::Modified); + } + let known = has_time(&found) && (Some(found) == source.fingerprint || Some(found) == trusted); + if !known && source.hash.is_none() && source.fingerprint.is_some() { + // Nothing to tell the bytes by. + return Err(Miss::Modified); + } + // At most one byte past the size: a file that grew since is caught without reading it all. + let bytes = crate::io::read_capped(path, source.len).map_err(|_| Miss::Absent)?; + if bytes.len() as u64 != source.len { + return Err(Miss::Modified); + } + if known { + return Ok(Loaded { bytes, fingerprint: None }); + } + match &source.hash { + Some(hash) if *hash != content_hash(&bytes) => Err(Miss::Modified), + Some(_) => Ok(Loaded { bytes, fingerprint: Some(found) }), + None => Ok(Loaded { bytes, fingerprint: None }), + } +} + +#[cfg(test)] +mod tests { + use super::*; + use designcraft_doc::AssetData; + + struct Dir(PathBuf); + + impl Dir { + fn new(name: &str) -> Self { + let dir = std::env::temp_dir().join(format!("dc-asset-io-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + Dir(dir) + } + } + + impl Drop for Dir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } + } + + /// The link record of the file at `path` as it is now. + fn source_of(path: &Path) -> LinkedSource { + let bytes = std::fs::read(path).unwrap(); + LinkedSource { + path: path.to_string_lossy().into_owned(), + relative: None, + document: None, + len: bytes.len() as u64, + fingerprint: Some(fingerprint_from(&std::fs::metadata(path).unwrap())), + hash: Some(content_hash(&bytes)), + } + } + + /// Set the file's modification time `secs` seconds into the past. + fn age(path: &Path, secs: u64) { + let file = std::fs::OpenOptions::new().write(true).open(path).unwrap(); + file.set_modified(std::time::SystemTime::now() - std::time::Duration::from_secs(secs)).unwrap(); + } + + #[test] + fn content_hashes_are_sha256_hex() { + assert_eq!(content_hash(b"abc"), "sha256:ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"); + } + + #[test] + fn a_linked_file_is_read_when_it_holds_the_recorded_bytes() { + let dir = Dir::new("read"); + let path = dir.0.join("a.png"); + std::fs::write(&path, b"original").unwrap(); + let source = source_of(&path); + assert_eq!(read_linked(&source, None).ok().map(|l| (l.bytes, l.fingerprint)), Some((b"original".to_vec(), None))); + // Same bytes, another time: accepted by the hash, and the new fingerprint returned. + age(&path, 1000); + let now = fingerprint_from(&std::fs::metadata(&path).unwrap()); + let loaded = read_linked(&source, None).ok().unwrap(); + assert_eq!((loaded.bytes.as_slice(), loaded.fingerprint), (b"original".as_slice(), Some(now))); + assert!(read_linked(&source, Some(now)).is_ok_and(|l| l.fingerprint.is_none()), "a trusted fingerprint needs no hash"); + let unverifiable = LinkedSource { hash: None, ..source.clone() }; + assert_eq!(read_linked(&unverifiable, None).err(), Some(Unavailable::Modified), "nothing to tell the bytes by"); + } + + #[test] + fn other_bytes_at_the_path_are_modified_and_a_missing_file_is_missing() { + let dir = Dir::new("modified"); + let path = dir.0.join("a.png"); + std::fs::write(&path, b"original").unwrap(); + let source = source_of(&path); + std::fs::write(&path, b"changed!").unwrap(); + age(&path, 1000); + assert_eq!(read_linked(&source, None).err(), Some(Unavailable::Modified), "same size, other bytes"); + std::fs::write(&path, b"longer than before").unwrap(); + assert_eq!(read_linked(&source, None).err(), Some(Unavailable::Modified), "another size"); + std::fs::remove_file(&path).unwrap(); + assert_eq!(read_linked(&source, None).err(), Some(Unavailable::Missing)); + let too_large = LinkedSource { len: MAX_LINKED_BYTES + 1, ..source }; + assert_eq!(read_linked(&too_large, None).err(), Some(Unavailable::TooLarge)); + } + + #[test] + fn the_relative_path_serves_when_the_absolute_one_does_not() { + let dir = Dir::new("relative"); + std::fs::create_dir_all(dir.0.join("moved/links")).unwrap(); + let away = dir.0.join("moved/links/a.png"); + std::fs::write(&away, b"original").unwrap(); + let mut source = source_of(&away); + source.path = dir.0.join("gone/links/a.png").to_string_lossy().into_owned(); + assert_eq!(read_linked(&source, None).err(), Some(Unavailable::Missing)); + source.relative = Some("links/a.png".into()); + source.document = Some(dir.0.join("moved/doc.dcx")); + assert_eq!(read_linked(&source, None).ok().map(|l| l.bytes), Some(b"original".to_vec())); + // A changed file at the absolute path doesn't hide the one that holds the bytes. + std::fs::create_dir_all(dir.0.join("gone/links")).unwrap(); + std::fs::write(dir.0.join("gone/links/a.png"), b"other!!!").unwrap(); + age(&dir.0.join("gone/links/a.png"), 1000); + assert_eq!(read_linked(&source, None).ok().map(|l| l.bytes), Some(b"original".to_vec())); + } + + /// A time of 0 is what a file system without times gives: it can't tell two files apart. + #[test] + fn a_file_without_a_time_is_told_by_its_hash() { + let dir = Dir::new("no-time"); + let path = dir.0.join("a.png"); + let at_epoch = |p: &Path| std::fs::OpenOptions::new().write(true).open(p).unwrap().set_modified(std::time::UNIX_EPOCH).unwrap(); + std::fs::write(&path, b"original").unwrap(); + at_epoch(&path); + let source = source_of(&path); + assert_eq!(source.fingerprint.map(|f| f.mtime), Some(0)); + std::fs::write(&path, b"changed!").unwrap(); + at_epoch(&path); + assert_eq!(read_linked(&source, None).err(), Some(Unavailable::Modified)); + } + + /// Through the installed loader and the store: a file changed on disk is never adopted. + #[test] + fn asset_data_loads_through_the_installed_loader() { + install(); + let dir = Dir::new("installed"); + let path = dir.0.join("a.png"); + std::fs::write(&path, b"original").unwrap(); + let data = AssetData::linked(source_of(&path)); + let changed = AssetData::linked(source_of(&path)); + assert_eq!(data.load().ok().map(|b| b.to_vec()), Some(b"original".to_vec())); + assert!(data.resident().is_some()); + std::fs::write(&path, b"changed!").unwrap(); + age(&path, 1000); + assert_eq!(data.load().ok().map(|b| b.to_vec()), Some(b"original".to_vec()), "kept bytes are the recorded ones"); + assert_eq!(changed.load().err(), Some(Unavailable::Modified)); + assert!(changed.resident().is_none(), "nothing adopted"); + std::fs::remove_file(&path).unwrap(); + data.evict(); + assert_eq!(data.load().err(), Some(Unavailable::Missing)); + } +} diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index dc1acaf15..803814d7e 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -1,5 +1,6 @@ //! The command registry. Ids follow InDesign's menu structure. +pub(crate) mod alpha_wrap; mod anchored; pub mod anchors; mod articles; @@ -33,6 +34,7 @@ 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; @@ -41,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; @@ -179,6 +183,7 @@ pub fn command_specs() -> &'static [CommandSpec] { 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()); @@ -197,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()); @@ -250,6 +256,11 @@ pub fn find_command(id: &str) -> Option<&'static CommandSpec> { pub(crate) fn bad(cmd: &str, msg: impl Into) -> EngineError { EngineError::BadParams { cmd: cmd.into(), msg: msg.into() } } + +/// The bytes of `asset`, or why `cmd` can't have them. +pub(crate) fn asset_bytes(cmd: &str, asset: &designcraft_doc::Asset) -> Result>> { + asset.data.load().map_err(|e| bad(cmd, format!("{}: {e}", asset.name))) +} /// `p` with `key` set to `v`. Parameters come from callers (control channel, MCP, scripts) and /// may not be an object: `p[key] = v` panics on an array or a string, so start from `{}` then. pub(crate) fn with_param(p: &Value, key: &str, v: Value) -> Value { @@ -332,12 +343,16 @@ pub(crate) fn named_targets(spec: &CommandSpec, p: &Value) -> Option } /// The table a call names with `table`, for a command whose params document an optional `table`. -/// `None` when the call names no table. [`table_story`] reads the `story` that goes with it. -pub(crate) fn named_table(spec: &CommandSpec, p: &Value) -> Option { +/// `None` when the call names no table. A `table` that is present but not a non-negative integer, +/// `null` included, is an error. [`table_story`] reads the `story` that goes with it. +pub(crate) fn named_table(spec: &CommandSpec, p: &Value, cmd: &str) -> Result> { if !spec.params.split(|c: char| !c.is_ascii_alphanumeric() && c != '?').any(|w| w == "table?") { - return None; + 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")), } - p.get("table").and_then(Value::as_u64) } /// The `story` a table command's call names alongside `table`, or `None` when the call has no @@ -376,5 +391,6 @@ pub use file::{ DOCUMENT_SNIFF_BYTES, RecentPreview, base64_decode, base64_encode, from_bytes, is_document, recent_preview, to_bytes, with_document_extension, }; pub use layout::chapter_numbering; +pub use paste_image::{IMAGE_EXTENSIONS, MAX_PASTED_PIXELS, PASTED_IMAGE_NAME, check_pasted_base64, check_pasted_size, pasted_pixels, pasted_png}; pub use paste_svg::is_svg_markup; pub(crate) use place_text::autoflow as place_text_autoflow; diff --git a/crates/engine/src/cmd/alpha_wrap.rs b/crates/engine/src/cmd/alpha_wrap.rs new file mode 100644 index 000000000..de092273d --- /dev/null +++ b/crates/engine/src/cmd/alpha_wrap.rs @@ -0,0 +1,598 @@ +//! Text Wrap › Contour › Alpha Channel: the outline of a placed raster's visible pixels. +//! +//! The outline is traced once per image and threshold, in the image's pixel space, and kept on +//! the document ([`designcraft_doc::AlphaOutline`]). Composition maps it through the graphic's +//! current transform, so it follows the image when it is moved, scaled or refitted. +use std::collections::BTreeSet; +use std::sync::Arc; + +use designcraft_doc::{AlphaOutline, AssetData, AssetId, ContourType, Document, Item, WrapMode}; +use designcraft_geom::{BezPath, PathData, Point}; + +/// Images larger than this many pixels aren't traced (their contour follows the frame). +const MAX_PIXELS: u64 = 40_000_000; +/// The finest grid an outline is traced on; coarser grids when the outline would be too long. +const MAX_GRID: u32 = 256; +/// Boundary edges an outline may have. +const MAX_EDGES: usize = 1 << 16; + +/// Trace the outlines new Alpha Channel contours need and drop the ones nothing uses. Cheap when +/// nothing changed: tracing happens only for an image and threshold not seen before. +pub(crate) fn sync(doc: &mut Document) { + let mut wanted: BTreeSet<(AssetId, u8)> = BTreeSet::new(); + // Every frame, in groups and Paste Into containers too, with the wrap set on the frame or on + // its placed graphic (Direct Selection sets the graphic's). + let mut want = |it: &Item| { + let Some(g) = it.graphic() else { return }; + for w in [&it.wrap, &g.wrap] { + if w.mode == WrapMode::Contour && w.contour == ContourType::AlphaChannel { + wanted.insert((g.asset, w.alpha_threshold)); + } + } + }; + for sp in doc.spreads.iter().chain(doc.parents.iter()) { + for top in &sp.items { + top.walk(&mut want); + } + } + // Objects anchored in text wrap the lines after their anchor; anchored_items lists their + // children too. + if doc.has_anchored_items() { + for (_, it) in doc.anchored_items() { + want(it); + } + } + if wanted.is_empty() && doc.alpha_outlines.is_empty() { + return; + } + // An outline traced from data the asset no longer has (relinked or updated) is traced again. + let assets = &doc.assets; + doc.alpha_outlines.retain(|o| wanted.contains(&(o.asset, o.threshold)) && assets.get(&o.asset).is_some_and(|a| o.traced_from(&a.data))); + let traced: BTreeSet<(AssetId, u8)> = doc.alpha_outlines.iter().map(|o| (o.asset, o.threshold)).collect(); + let kept = doc.alpha_outlines.len(); + for (asset, threshold) in wanted { + if traced.contains(&(asset, threshold)) { + continue; + } + let Some(a) = doc.assets.get(&asset).filter(|a| a.is_raster()) else { continue }; + // An image with no outline (unreadable, too large) is remembered as an empty + // one, so later edits don't decode it again; the contour is then the frame's. + // A linked image's original is not read here (a document opens without reading its + // links): its preview is traced, scaled to the original's size; with no preview, the + // image has no outline yet and is traced once its bytes are resident. + let o = if a.data.is_linked() && a.data.resident().is_none() { + let Some(proxy) = a.proxy.as_ref().and_then(|p| Some((p.data.load().ok()?, a.pixels?))) else { continue }; + trace_bytes(&proxy.0, a.data.key(), Some(proxy.1), asset, threshold).unwrap_or_else(|| no_outline(&a.data, asset, threshold)) + } else { + trace(&a.data, asset, threshold).unwrap_or_else(|| no_outline(&a.data, asset, threshold)) + }; + doc.alpha_outlines.push(Arc::new(o)); + } + // `Document::alpha_outline` finds an outline by binary search. + if doc.alpha_outlines.len() > kept { + doc.alpha_outlines.sort_by_key(|o| (o.asset, o.threshold)); + } +} + +/// The empty outline standing for an image `trace` found none in: zero-size, which composition +/// takes as no outline, and dropped like a traced one when the asset's data changes. +fn no_outline(data: &AssetData, asset: AssetId, threshold: u8) -> AlphaOutline { + AlphaOutline { + asset, + threshold, + width: 0, + height: 0, + outer: Default::default(), + holes: Default::default(), + source: data.key(), + serial: AlphaOutline::next_serial(), + } +} + +/// The outline of the pixels of `data` more opaque than `threshold`: an image with no +/// transparency gives its rectangle. None for an image that can't be read or is too large. +pub(crate) fn trace(data: &AssetData, asset: AssetId, threshold: u8) -> Option { + trace_bytes(&data.load().ok()?, data.key(), None, asset, threshold) +} + +/// [`trace`] of encoded `bytes` standing for the data under `source`. With `size`, the outline +/// is scaled to an image of that size (a preview traced for the original it stands for). +fn trace_bytes(bytes: &[u8], source: designcraft_doc::SourceKey, size: Option<(u32, u32)>, asset: AssetId, threshold: u8) -> Option { + let (w, h) = designcraft_images::pixel_size(bytes)?; + if w == 0 || h == 0 || u64::from(w) * u64::from(h) > MAX_PIXELS { + return None; + } + let img = designcraft_images::decode_rgba(bytes)?; + if img.width() != w || img.height() != h { + return None; + } + let mut grid = MAX_GRID; + // The previous grid's mask: a grid half as fine is made from it without reading the pixels again. + let mut finer: Option<(Vec, u32, u32)> = None; + while grid >= 16 { + let (cols, rows) = (w.min(grid), h.min(grid)); + let mask = match finer.as_ref().and_then(|(m, fc, fr)| coarsen(m, *fc, *fr, cols, rows)) { + Some(m) => m, + None => occupancy(img.as_raw(), w, h, cols, rows, threshold), + }; + // Composition follows an outline of at most MAX_CONTOUR_POINTS path elements (holes + // included, for Include Inside Edges): a ring of k points is k + 1 elements with its close. + let fits = |outer: &[Vec<(i32, i32)>], holes: &[Vec<(i32, i32)>]| { + outer.iter().chain(holes).map(|r| r.len() + 1).sum::() <= designcraft_compose::MAX_CONTOUR_POINTS + }; + if let Some((outer, holes)) = rings(&mask, cols as usize, rows as usize).filter(|(o, h)| fits(o, h)) { + let (tw, th) = size.filter(|&(a, b)| a > 0 && b > 0).unwrap_or((w, h)); + let (sx, sy) = (f64::from(tw) / f64::from(cols), f64::from(th) / f64::from(rows)); + let path = |rings: &[Vec<(i32, i32)>]| { + let mut p = BezPath::new(); + for ring in rings { + let mut pts = ring.iter().map(|&(x, y)| Point::new(f64::from(x) * sx, f64::from(y) * sy)); + let Some(first) = pts.next() else { continue }; + p.move_to(first); + for q in pts { + p.line_to(q); + } + p.close_path(); + } + PathData::from_bezpath(&p) + }; + let serial = AlphaOutline::next_serial(); + return Some(AlphaOutline { asset, threshold, width: tw, height: th, outer: path(&outer), holes: path(&holes), source, serial }); + } + finer = Some((mask, cols, rows)); + grid /= 2; + } + None +} + +/// The `cols` × `rows` mask made from a `fc` × `fr` one, when each side has the same number of +/// cells or twice as many (a pixel's coarse cell is then its fine cell, or half of it). None +/// otherwise: the pixels are read again. +fn coarsen(mask: &[bool], fc: u32, fr: u32, cols: u32, rows: u32) -> Option> { + let step = |fine: u32, coarse: u32| match fine { + f if f == coarse => Some(1), + f if u64::from(f) == 2 * u64::from(coarse) => Some(2), + _ => None, + }; + let (sx, sy) = (step(fc, cols)?, step(fr, rows)?); + let (fc, cols) = (fc as usize, cols as usize); + let mut out = vec![false; cols * rows as usize]; + for (i, _) in mask.iter().enumerate().filter(|(_, v)| **v) { + let (x, y) = (i % fc, i / fc); + if let Some(c) = out.get_mut(y / sy * cols + x / sx) { + *c = true; + } + } + Some(out) +} + +/// Which cells of a `cols` × `rows` grid hold a pixel of the `w` × `h` RGBA image `rgba` more +/// opaque than `threshold` (a cell is visible when any of its pixels is). +fn occupancy(rgba: &[u8], w: u32, h: u32, cols: u32, rows: u32, threshold: u8) -> Vec { + let mut mask = vec![false; (cols as usize) * (rows as usize)]; + // A pixel's cell is (x * cols / w, y * rows / h). Along a row the column is counted up as x + // passes each cell's edge (cols <= w, so at most one edge per pixel) instead of divided out. + for (y, row) in rgba.chunks_exact(w as usize * 4).take(h as usize).enumerate() { + let base = (y as u64 * u64::from(rows) / u64::from(h)) as usize * cols as usize; + let (mut gx, mut acc, mut edge) = (0usize, 0u64, u64::from(w)); + for px in row.as_chunks::<4>().0 { + if acc >= edge { + gx += 1; + edge += u64::from(w); + } + acc += u64::from(cols); + if px[3] > threshold + && let Some(c) = mask.get_mut(base + gx) + { + *c = true; + } + } + } + mask +} + +/// The closed boundaries of the visible cells, split into outer boundaries and the boundaries of +/// holes (by winding: each boundary keeps the visible cells on the same side). None when the +/// outline would have more than [`MAX_EDGES`] edges. +#[allow(clippy::type_complexity)] +fn rings(mask: &[bool], cols: usize, rows: usize) -> Option<(Vec>, Vec>)> { + use std::collections::BTreeMap; + let visible = |x: i32, y: i32| { + x >= 0 && y >= 0 && (x as usize) < cols && (y as usize) < rows && mask.get(y as usize * cols + x as usize).copied().unwrap_or(false) + }; + let mut edges: BTreeMap<(i32, i32), Vec<(i32, i32)>> = BTreeMap::new(); + let mut count = 0usize; + for y in 0..rows as i32 { + for x in 0..cols as i32 { + if !visible(x, y) { + continue; + } + for (open, a, b) in [ + (!visible(x, y - 1), (x, y), (x + 1, y)), + (!visible(x + 1, y), (x + 1, y), (x + 1, y + 1)), + (!visible(x, y + 1), (x + 1, y + 1), (x, y + 1)), + (!visible(x - 1, y), (x, y + 1), (x, y)), + ] { + if open { + count += 1; + if count > MAX_EDGES { + return None; + } + edges.entry(a).or_default().push(b); + } + } + } + } + let (mut outer, mut holes) = (Vec::new(), Vec::new()); + while let Some((&start, _)) = edges.first_key_value() { + let mut ring = vec![start]; + let mut at = start; + for _ in 0..=MAX_EDGES { + let next = edges.get_mut(&at).and_then(Vec::pop)?; + if edges.get(&at).is_some_and(Vec::is_empty) { + edges.remove(&at); + } + // Drop the middle of straight runs. + if let [.., a, b] = ring[..] + && (b.0 - a.0) * (next.1 - b.1) == (b.1 - a.1) * (next.0 - b.0) + { + ring.pop(); + } + if next == start { + break; + } + ring.push(next); + at = next; + } + // Shoelace in y-down space: positive for outer boundaries, negative for holes. + let area: i64 = ring + .iter() + .zip(ring.iter().cycle().skip(1)) + .map(|(&(x0, y0), &(x1, y1))| i64::from(x0) * i64::from(y1) - i64::from(x1) * i64::from(y0)) + .sum(); + if ring.len() >= 3 { + if area > 0 { outer.push(ring) } else { holes.push(ring) } + } + } + Some((outer, holes)) +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + use crate::Session; + + /// A 64 × 64 PNG: visible where `on(x, y)`. + fn png(on: impl Fn(usize, usize) -> bool) -> Vec { + png_sized(64, on) + } + + /// A `size` × `size` PNG: visible where `on(x, y)`. + fn png_sized(size: usize, on: impl Fn(usize, usize) -> bool) -> Vec { + let mut pixels = vec![0; size * size * 4]; + for y in 0..size { + for x in 0..size { + let i = (y * size + x) * 4; + pixels[i] = 120; + pixels[i + 3] = if on(x, y) { 255 } else { 0 }; + } + } + designcraft_render::Rendered { width: size as u32, height: size as u32, pixels }.to_png() + } + + /// An outline too detailed for composition (here 4,096 separate dots, 20,480 path elements + /// on the finest grid) is traced on a coarser grid until composition can follow it. + #[test] + fn a_fragmented_outline_is_traced_coarser_until_composition_can_follow_it() { + let dots = png_sized(256, |x, y| x % 4 == 0 && y % 4 == 0); + let o = trace(&AssetData::embedded(dots), AssetId(1), 25).unwrap(); + let elements = o.outer.to_bezpath().elements().len() + o.holes.to_bezpath().elements().len(); + assert!(elements > 0 && elements <= designcraft_compose::MAX_CONTOUR_POINTS, "{elements} path elements"); + } + + /// An image with no pixel more opaque than the threshold leaves the text alone: with the + /// frame's contour the caption over it is overset, with Alpha Channel it is set. + #[test] + fn an_image_with_nothing_visible_wraps_no_text() { + let (mut s, image, story) = page(&png(|_, _| false), [150.0, 150.0, 178.0, 178.0]); + assert!(overset(&s, story), "the frame's contour covers the caption"); + s.execute("object.textWrap", &json!({"ids": [image], "contour": "alphaChannel"})).unwrap(); + assert!(!overset(&s, story), "nothing visible: nothing wraps"); + // The same for the wrap set on the placed graphic. + s.execute("object.textWrap", &json!({"ids": [image], "mode": "none"})).unwrap(); + s.execute("object.textWrap", &json!({"ids": [image], "content": true, "mode": "contour", "contour": "alphaChannel"})).unwrap(); + assert!(!overset(&s, story)); + } + + #[test] + fn traces_outer_boundaries_and_holes_apart() { + // A ring: a square with a square hole. + let data = png(|x, y| (8..56).contains(&x) && (8..56).contains(&y) && !((24..40).contains(&x) && (24..40).contains(&y))); + let o = trace(&AssetData::embedded(data), AssetId(1), 25).unwrap(); + assert_eq!((o.width, o.height), (64, 64)); + assert_eq!((o.outer.subpaths.len(), o.holes.subpaths.len()), (1, 1)); + let (a, b) = (o.outer.bounds().unwrap(), o.holes.bounds().unwrap()); + assert_eq!((a.x0, a.y0, a.x1, a.y1), (8.0, 8.0, 56.0, 56.0)); + assert_eq!((b.x0, b.y0, b.x1, b.y1), (24.0, 24.0, 40.0, 40.0)); + // An opaque image's outline is its rectangle. + let o = trace(&AssetData::embedded(png(|_, _| true)), AssetId(1), 25).unwrap(); + let a = o.outer.bounds().unwrap(); + assert_eq!((a.x0, a.y0, a.x1, a.y1, o.holes.subpaths.len()), (0.0, 0.0, 64.0, 64.0, 0)); + } + + /// The cell masks match a pixel-by-pixel count (cell = x * cols / w, y * rows / h), and a + /// mask half as fine made from the finer one matches the mask read from the pixels. + #[test] + fn cell_masks_match_the_pixels_and_coarser_masks_match_the_finer_ones() { + let (w, h) = (600u32, 300u32); + // An irregular pattern: visible where a small hash says so. + let on = |x: u32, y: u32| (x.wrapping_mul(2_654_435_761) ^ y.wrapping_mul(40_503)).rotate_left(7).is_multiple_of(7); + let mut rgba = vec![0u8; (w * h * 4) as usize]; + for y in 0..h { + for x in 0..w { + rgba[((y * w + x) * 4 + 3) as usize] = if on(x, y) { 255 } else { 0 }; + } + } + for (cols, rows) in [(256, 256), (128, 128), (100, 37), (600, 300)] { + let mut expect = vec![false; (cols * rows) as usize]; + for y in 0..h { + for x in 0..w { + if on(x, y) { + expect[((y * rows / h) * cols + x * cols / w) as usize] = true; + } + } + } + assert_eq!(occupancy(&rgba, w, h, cols, rows, 25), expect, "{cols} x {rows}"); + } + let fine = occupancy(&rgba, w, h, 256, 256, 25); + assert_eq!(coarsen(&fine, 256, 256, 128, 128), Some(occupancy(&rgba, w, h, 128, 128, 25))); + // Same count on one side, twice on the other. + let fine = occupancy(&rgba, w, h, 128, 256, 25); + assert_eq!(coarsen(&fine, 128, 256, 128, 128), Some(occupancy(&rgba, w, h, 128, 128, 25))); + // Any other ratio is read from the pixels. + assert_eq!(coarsen(&fine, 128, 256, 100, 128), None); + } + + #[test] + fn an_alpha_channel_contour_is_traced_when_set_and_kept_out_of_the_saved_file() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let data = png(|x, _| (16..48).contains(&x)); + let id = s + .execute("file.place", &json!({"base64": crate::cmd::file::base64_encode(&data), "name": "cut.png", "x": 100, "y": 100, "width": 128})) + .unwrap()["id"] + .clone(); + assert!(s.doc().unwrap().doc.alpha_outlines.is_empty()); + s.execute("object.textWrap", &json!({"ids": [id], "mode": "contour", "contour": "alphaChannel"})).unwrap(); + let d = &s.doc().unwrap().doc; + assert_eq!(d.alpha_outlines.len(), 1); + // Saved and opened again: traced again on open. + let bytes = crate::cmd::file::to_bytes(d).unwrap(); + let back = crate::cmd::file::from_bytes(&bytes).unwrap(); + assert!(back.alpha_outlines.is_empty(), "not saved"); + let st = crate::DocState::new(back, None); + assert_eq!(st.doc.alpha_outlines.len(), 1, "traced on open"); + // Wrap off: the outline goes. + s.execute("object.textWrap", &json!({"ids": [id], "mode": "none"})).unwrap(); + assert!(s.doc().unwrap().doc.alpha_outlines.is_empty()); + } + + /// An outline is traced once: later edits keep it. + #[test] + fn an_outline_is_not_traced_on_every_edit() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let data = png(|_, _| true); + let id = s + .execute("file.place", &json!({"base64": crate::cmd::file::base64_encode(&data), "name": "solid.png", "x": 100, "y": 100, "width": 128})) + .unwrap()["id"] + .clone(); + s.execute("object.textWrap", &json!({"ids": [id], "mode": "contour", "contour": "alphaChannel"})).unwrap(); + let first = s.doc().unwrap().doc.alpha_outlines.clone(); + assert_eq!(first.len(), 1, "remembered"); + s.execute("frame.create", &json!({"rect": [300, 300, 350, 350]})).unwrap(); + let after = &s.doc().unwrap().doc.alpha_outlines; + assert!(Arc::ptr_eq(&first[0], &after[0]), "kept, not traced again"); + } + + /// An opaque image's Alpha Channel contour is its rectangle, not the frame: moved within its + /// frame, it leaves the empty part of the frame to the text. + #[test] + fn an_opaque_image_wraps_its_rectangle() { + let (mut s, image, story) = page(&png(|_, _| true), [105.0, 150.0, 125.0, 178.0]); + s.execute("object.textWrap", &json!({"ids": [image], "contour": "alphaChannel"})).unwrap(); + assert!(overset(&s, story), "the image covers the caption"); + // The graphic moved 30 pt right within its frame: the frame's left 30 pt are empty. + s.execute("selection.set", &json!({"ids": [image], "content": true})).unwrap(); + s.execute("transform.move", &json!({"dx": 30, "dy": 0})).unwrap(); + assert!(!overset(&s, story), "the empty part of the frame takes the caption"); + } + + /// Outlines are traced for a wrap set on the placed graphic and for frames inside groups, and + /// traced again when the image's data changes under the same asset (relink, link update). + #[test] + fn graphic_wraps_nested_frames_and_relinked_images_get_outlines() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let place = |s: &mut Session, x: u64| { + let data = png(|x, _| (16..48).contains(&x)); + s.execute("file.place", &json!({"base64": crate::cmd::file::base64_encode(&data), "name": "cut.png", "x": x, "y": 100, "width": 128})) + .unwrap()["id"] + .as_u64() + .unwrap() + }; + let image = place(&mut s, 100); + // The wrap on the graphic (Direct Selection), not the frame. + s.execute("object.textWrap", &json!({"ids": [image], "content": true, "mode": "contour", "contour": "alphaChannel"})).unwrap(); + let frame_wrap = s.doc().unwrap().doc.item(designcraft_doc::ItemId(image)).unwrap().wrap.mode; + assert_eq!(frame_wrap, WrapMode::None, "the frame has no wrap of its own"); + assert_eq!(s.doc().unwrap().doc.alpha_outlines.len(), 1, "traced for the graphic's wrap"); + // In a group with another frame: still traced. + let other = s.execute("frame.create", &json!({"rect": [300, 100, 350, 150]})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.group", &json!({"ids": [image, other]})).unwrap(); + let d = &s.doc().unwrap().doc; + assert!(d.find(designcraft_doc::ItemId(image)).unwrap().path.len() > 1, "the frame is nested"); + assert_eq!(d.alpha_outlines.len(), 1, "a nested frame keeps its outline"); + // A frame placed and grouped before its wrap is set: traced too. + let second = place(&mut s, 400); + let other2 = s.execute("frame.create", &json!({"rect": [600, 100, 650, 150]})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.group", &json!({"ids": [second, other2]})).unwrap(); + s.execute("object.textWrap", &json!({"ids": [second], "mode": "contour", "contour": "alphaChannel", "threshold": 200})).unwrap(); + assert_eq!(s.doc().unwrap().doc.alpha_outlines.len(), 2); + // The image data replaced under the same asset, as a relink does: traced again. + let Some(designcraft_doc::Content::Graphic(g)) = s.doc().unwrap().doc.item(designcraft_doc::ItemId(image)).map(|it| it.content.clone()) + else { + panic!("a graphic") + }; + let narrower = AssetData::embedded(png(|x, _| (24..40).contains(&x))); + s.edit(|d, _| { + let a = d.assets.get(&g.asset).unwrap(); + let mut a = (**a).clone(); + a.data = narrower.clone(); + d.assets.insert(g.asset, Arc::new(a)); + Ok(()) + }) + .unwrap(); + let d = &s.doc().unwrap().doc; + let o = d.alpha_outline(g.asset, designcraft_doc::DEFAULT_ALPHA_THRESHOLD).unwrap(); + assert!(o.traced_from(&narrower)); + let b = o.outer.bounds().unwrap(); + assert_eq!((b.x0, b.x1), (24.0, 40.0), "the new image's outline"); + } + + /// An outline traced after others is still found: a threshold lower than a kept outline's + /// is traced later and must not hide either outline from the lookup. + #[test] + fn outlines_traced_later_are_found_by_image_and_threshold() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let data = png(|x, _| (16..48).contains(&x)); + let image = s + .execute("file.place", &json!({"base64": crate::cmd::file::base64_encode(&data), "name": "cut.png", "x": 100, "y": 100, "width": 128})) + .unwrap()["id"] + .as_u64() + .unwrap(); + s.execute("object.textWrap", &json!({"ids": [image], "content": true, "mode": "contour", "contour": "alphaChannel", "threshold": 200})) + .unwrap(); + s.execute("object.textWrap", &json!({"ids": [image], "mode": "contour", "contour": "alphaChannel"})).unwrap(); + let d = &s.doc().unwrap().doc; + assert_eq!(d.alpha_outlines.len(), 2, "one outline for each threshold"); + let Some(g) = d.item(designcraft_doc::ItemId(image)).and_then(|it| it.graphic()) else { panic!("a graphic") }; + for threshold in [designcraft_doc::DEFAULT_ALPHA_THRESHOLD, 200] { + let o = d.alpha_outline(g.asset, threshold); + assert!(o.is_some_and(|o| o.threshold == threshold), "the outline at {threshold} is found"); + } + assert!(d.alpha_outline(g.asset, 100).is_none(), "no outline at a threshold nothing uses"); + } + + /// A wrap with the default threshold saves as it did before thresholds were stored; another + /// threshold is saved. + #[test] + fn the_default_threshold_is_left_out_of_a_saved_wrap() { + let v = serde_json::to_value(designcraft_doc::TextWrap::default()).unwrap(); + assert!(v.get("alphaThreshold").is_none(), "{v}"); + let back: designcraft_doc::TextWrap = serde_json::from_value(v).unwrap(); + assert_eq!(back.alpha_threshold, designcraft_doc::DEFAULT_ALPHA_THRESHOLD); + let w = designcraft_doc::TextWrap { alpha_threshold: 200, ..Default::default() }; + assert_eq!(serde_json::to_value(w).unwrap()["alphaThreshold"], 200); + } + + /// A relink that changes only the image data recomposes the text around the new outline. + #[test] + fn text_is_composed_again_around_a_relinked_images_outline() { + let (mut s, image, story) = page(&png(|x, _| x < 32), [180.0, 150.0, 220.0, 178.0]); + s.execute("object.textWrap", &json!({"ids": [image], "contour": "alphaChannel"})).unwrap(); + assert!(!overset(&s, story), "the left half is visible: the caption on the right is set"); + let Some(designcraft_doc::Content::Graphic(g)) = + s.doc().unwrap().doc.item(designcraft_doc::ItemId(image.as_u64().unwrap())).map(|it| it.content.clone()) + else { + panic!("a graphic") + }; + let right = AssetData::embedded(png(|x, _| x >= 32)); + s.edit(|d, _| { + let mut a = (**d.assets.get(&g.asset).unwrap()).clone(); + a.data = right.clone(); + d.assets.insert(g.asset, Arc::new(a)); + Ok(()) + }) + .unwrap(); + assert!(overset(&s, story), "the right half is visible now: it covers the caption"); + } + + /// An image anchored in text keeps its outline: anchored objects wrap the lines after their + /// anchor, and they are kept in the story, not on the spread. + #[test] + fn an_anchored_image_keeps_its_outline() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let data = png(|x, _| (16..48).contains(&x)); + let image = s + .execute("file.place", &json!({"base64": crate::cmd::file::base64_encode(&data), "name": "cut.png", "x": 100, "y": 100, "width": 128})) + .unwrap()["id"] + .as_u64() + .unwrap(); + s.execute("object.textWrap", &json!({"ids": [image], "mode": "contour", "contour": "alphaChannel"})).unwrap(); + assert_eq!(s.doc().unwrap().doc.alpha_outlines.len(), 1); + let t = s.execute("frame.create", &json!({"rect": [36, 300, 400, 500], "content": "text", "text": "Before after."})).unwrap(); + s.execute("anchored.insert", &json!({"ids": [image], "story": t["story"], "pos": 7})).unwrap(); + let d = &s.doc().unwrap().doc; + assert!(d.anchored_item(designcraft_doc::ItemId(image)).is_some(), "the image is in the text"); + assert_eq!(d.alpha_outlines.len(), 1, "the anchored image keeps its outline"); + } + + /// An image placed 128 pt wide at (100, 100) (2 pt per pixel), its wrap a contour with no + /// offset, and a caption frame at `caption` with 8 pt "Hi". + fn page(data: &[u8], caption: [f64; 4]) -> (Session, Value, u64) { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let image = s + .execute("file.place", &json!({"base64": crate::cmd::file::base64_encode(data), "name": "cut.png", "x": 100, "y": 100, "width": 128})) + .unwrap()["id"] + .clone(); + let c = s.execute("frame.create", &json!({"rect": caption, "content": "text", "text": "Hi"})).unwrap(); + s.execute("selection.set", &json!({"ids": [c["id"]]})).unwrap(); + s.execute("type.char", &json!({"size": 8})).unwrap(); + s.execute("object.textWrap", &json!({"ids": [image], "mode": "contour", "offset": 0})).unwrap(); + (s, image, c["story"].as_u64().unwrap()) + } + + fn overset(s: &Session, story: u64) -> bool { + s.cache.get(&s.doc().unwrap().doc, designcraft_doc::StoryId(story), None).is_overset() + } + + use serde_json::Value; + + /// A caption fits between two legs of a cutout, and the contour follows the image when it's + /// moved within its frame (it isn't a boundary stored where it was traced). + #[test] + fn an_alpha_channel_contour_keeps_gaps_open_and_follows_the_image() { + // Legs at pixels 8..20 and 44..56: 116..140 and 188..212 on the page. + let (mut s, image, story) = page(&png(|x, _| (8..20).contains(&x) || (44..56).contains(&x)), [150.0, 120.0, 178.0, 170.0]); + assert!(overset(&s, story), "the frame's contour covers the gap"); + s.execute("object.textWrap", &json!({"ids": [image], "contour": "alphaChannel"})).unwrap(); + assert!(!overset(&s, story), "the gap between the legs stays open"); + // The graphic moved 30 pt right within its frame: its left leg now covers the caption. + s.execute("selection.set", &json!({"ids": [image], "content": true})).unwrap(); + s.execute("transform.move", &json!({"dx": 30, "dy": 0})).unwrap(); + assert!(overset(&s, story), "the contour moved with the image"); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(!overset(&s, story)); + } + + /// A hole enclosed by the image stays blocked unless Include Inside Edges is on. + #[test] + fn holes_are_blocked_unless_inside_edges_are_included() { + // A ring: outer 116..212, hole 148..180 on the page. + let ring = png(|x, y| (8..56).contains(&x) && (8..56).contains(&y) && !((24..40).contains(&x) && (24..40).contains(&y))); + let (mut s, image, story) = page(&ring, [152.0, 152.0, 176.0, 176.0]); + s.execute("object.textWrap", &json!({"ids": [image], "contour": "alphaChannel"})).unwrap(); + assert!(overset(&s, story), "the hole is blocked with the ring around it"); + s.execute("object.textWrap", &json!({"ids": [image], "insideEdges": true})).unwrap(); + assert!(!overset(&s, story), "Include Inside Edges lets text into the hole"); + for bad in [json!({"ids": [image], "threshold": 255}), json!({"ids": [image], "insideEdges": 1})] { + assert!(s.execute("object.textWrap", &bad).is_err()); + } + } +} diff --git a/crates/engine/src/cmd/anchored.rs b/crates/engine/src/cmd/anchored.rs index d55cdf753..bc80b2e1c 100644 --- a/crates/engine/src/cmd/anchored.rs +++ b/crates/engine/src/cmd/anchored.rs @@ -544,7 +544,7 @@ mod text_frame_tests { let d = &s.doc().unwrap().doc; d.check().unwrap(); let mut files: Vec<_> = - d.anchored_items().iter().filter_map(|(_, i)| i.graphic()).map(|g| d.assets.get(&g.asset).map(|a| a.data.clone())).collect(); + d.anchored_items().iter().filter_map(|(_, i)| i.graphic()).map(|g| d.assets.get(&g.asset).map(|a| a.data.load().unwrap())).collect(); files.sort(); files } diff --git a/crates/engine/src/cmd/book.rs b/crates/engine/src/cmd/book.rs index 7a3995093..6160598df 100644 --- a/crates/engine/src/cmd/book.rs +++ b/crates/engine/src/cmd/book.rs @@ -1,6 +1,8 @@ //! Books (File › New / Open Book): an ordered list of documents with continuous page numbers, //! styles synchronised from a style source, and one PDF for the whole book. Saved as `.dcbook`. +use std::collections::{HashMap, HashSet}; + use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; @@ -181,6 +183,15 @@ fn paginate(s: &Session) -> Result { Ok(json!({"pages": next - 1, "chapters": chapters})) } +/// `list` with only the last entry of each name, in the order of those last entries. +#[cfg(not(target_arch = "wasm32"))] +fn keep_last(list: &[T], name: impl Fn(&T) -> &str) -> Vec<&T> { + let mut seen = HashSet::new(); + let mut out: Vec<&T> = list.iter().rev().filter(|x| seen.insert(name(x))).collect(); + out.reverse(); + out +} + #[cfg(not(target_arch = "wasm32"))] fn sync_styles(s: &Session) -> Result { let b = s.book.as_ref().ok_or_else(no_book)?; @@ -191,6 +202,11 @@ fn sync_styles(s: &Session) -> Result { let styles = src.styles.clone(); let swatches = src.swatches.clone(); drop(src); + // A name the source defines twice keeps its last definition, at its last position. + let paragraph = keep_last(&styles.paragraph, |x| x.name.as_str()); + let character = keep_last(&styles.character, |x| x.name.as_str()); + let (paragraph_names, character_names): (HashSet<&str>, HashSet<&str>) = + (paragraph.iter().map(|x| x.name.as_str()).collect(), character.iter().map(|x| x.name.as_str()).collect()); let mut n = 0; for (i, path) in paths.iter().enumerate() { if i == b.style_source { @@ -199,21 +215,27 @@ fn sync_styles(s: &Session) -> Result { writable_chapter(s, path, "book.syncStyles")?; let mut d = load(path)?; { + // The source's styles replace the chapter's of the same names and go last, in the + // source's order (one pass over each list, not one per style). let st = d.styles_mut(); - for ps in &styles.paragraph { - st.paragraph.retain(|x| x.name != ps.name); - st.paragraph.push(ps.clone()); - } - for cs in &styles.character { - st.character.retain(|x| x.name != cs.name); - st.character.push(cs.clone()); - } + st.paragraph.retain(|x| !paragraph_names.contains(x.name.as_str())); + st.paragraph.extend(paragraph.iter().map(|x| (*x).clone())); + st.character.retain(|x| !character_names.contains(x.name.as_str())); + st.character.extend(character.iter().map(|x| (*x).clone())); + } + // First index per name, as Document::swatch resolves colours. + let mut at: HashMap = HashMap::new(); + for (i, w) in d.swatches.iter().enumerate() { + at.entry(w.name.clone()).or_insert(i); } for sw in &swatches { - match d.swatches.iter_mut().find(|w| w.name == sw.name) { + match at.get(&sw.name).and_then(|i| d.swatches.get_mut(*i)) { Some(w) if !w.locked => *w = sw.clone(), Some(_) => {} - None => d.swatches.push(sw.clone()), + None => { + at.insert(sw.name.clone(), d.swatches.len()); + d.swatches.push(sw.clone()); + } } } batch.stage(path, &d)?; @@ -435,4 +457,13 @@ mod tests { assert_eq!(t.execute("book.open", &json!({"path": p("book.dcbook")})).unwrap()["documents"], 2); std::fs::remove_dir_all(&dir).ok(); } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn a_source_style_defined_twice_keeps_its_last_definition() { + let list = [("a", 1), ("b", 2), ("a", 3), ("c", 4)]; + let kept: Vec<_> = super::keep_last(&list, |x| x.0).into_iter().copied().collect(); + // As the one-style-at-a-time loop left them: each name once, at its last position. + assert_eq!(kept, [("b", 2), ("a", 3), ("c", 4)]); + } } diff --git a/crates/engine/src/cmd/color_theme.rs b/crates/engine/src/cmd/color_theme.rs index c406c72da..eb84bbae1 100644 --- a/crates/engine/src/cmd/color_theme.rs +++ b/crates/engine/src/cmd/color_theme.rs @@ -37,11 +37,12 @@ fn extract(s: &mut Session, p: &Value) -> Result { }; let graphic = st.doc.item(id).and_then(|it| it.graphic()).ok_or_else(|| bad(ID, "select one placed raster image"))?; let asset = st.doc.assets.get(&graphic.asset).filter(|a| a.is_raster()).ok_or_else(|| bad(ID, "a raster image is required"))?; - let (width, height) = designcraft_images::pixel_size(&asset.data).ok_or_else(|| bad(ID, "cannot read image dimensions"))?; + let bytes = crate::cmd::asset_bytes(ID, asset)?; + let (width, height) = designcraft_images::pixel_size(&bytes).ok_or_else(|| bad(ID, "cannot read image dimensions"))?; if width == 0 || height == 0 || u64::from(width) * u64::from(height) > 16_000_000 { return Err(bad(ID, "the image must contain between 1 and 16 million pixels")); } - let img = designcraft_images::decode_rgba(&asset.data).ok_or_else(|| bad(ID, "cannot decode this image"))?; + let img = designcraft_images::decode_rgba(&bytes).ok_or_else(|| bad(ID, "cannot decode this image"))?; // A regular 128 × 128 grid bounds work and includes both axes even for very thin images. let (nx, ny) = (width.min(128), height.min(128)); let mut samples = Vec::with_capacity((nx * ny) as usize); diff --git a/crates/engine/src/cmd/datamerge.rs b/crates/engine/src/cmd/datamerge.rs index 93ceaf8cb..424a7adaf 100644 --- a/crates/engine/src/cmd/datamerge.rs +++ b/crates/engine/src/cmd/datamerge.rs @@ -19,7 +19,8 @@ use serde_json::{Value, json}; use super::{CommandSpec, bad, cmd, has_doc, id_param, ok, str_param}; use crate::{DocState, Result, Session}; use fill::{FillReport, ImageCache, Maps, MissingImage, Sources, copy_item, fill_row, identity_map}; -use parse::{Table, TileInput, relative_between, select_records, status_of, table_from_bytes, table_from_grid, table_from_objects, tile}; +pub(crate) use parse::relative_between; +use parse::{Table, TileInput, select_records, status_of, table_from_bytes, table_from_grid, table_from_objects, tile}; #[cfg(not(target_arch = "wasm32"))] pub(crate) use parse::fingerprint_from; @@ -58,7 +59,7 @@ pub fn specs() -> Vec { "Insert Field", [], None, - "{field, role?: text|image|qr|hyperlink, story?, at?, end?, item?} → {id}", + "{field, role?: text|image|qr|hyperlink, story?, at?, end?, item?} → {id}; an image field at a text insertion point merges as an inline image; with the insertion point in a table cell or a note → {cell: true, marker} (a typed marker, not an anchored placeholder; an image field there is an error unless role is text)", has_doc, placeholder_add ), @@ -210,6 +211,8 @@ fn preview_cmd(s: &mut Session, p: &Value) -> Result { let images = ImageCache::default(); let sources = Sources { options: &options, data_dir: data_dir.as_deref(), doc_dir: doc_dir.as_deref(), images: &images }; fill_row(&mut doc, &source.fields, &row, record as u32, &maps, &sources); + // An image the record placed gets its Alpha Channel outline, as an edit's would. + crate::cmd::alpha_wrap::sync(&mut doc); st.doc = Arc::new(doc); st.preview_record = Some(record as u32); st.bump_revision(); @@ -261,6 +264,8 @@ fn merge_cmd(s: &mut Session, p: &Value) -> Result { merged.data_merge.placeholders.clear(); merged.title = format!("{} merged", src.title); let pages = merged.page_count(); + // The merged images' Alpha Channel outlines first: the overset count composes with them. + crate::cmd::alpha_wrap::sync(&mut merged); let overset = overset_count(&merged); let records = selected.len(); let missing_json: Vec = missing.iter().map(|m| json!({"record": m.record, "field": m.field, "path": m.path})).collect(); @@ -470,7 +475,7 @@ fn overset_count(doc: &Document) -> usize { .count() } -fn add_placeholder(d: &mut Document, sel: &Selection, p: &Value, name: &str) -> Result { +fn add_placeholder(d: &mut Document, sel: &mut Selection, p: &Value, name: &str) -> Result { let (source_id, field) = { let source = d.data_merge.sources.first().ok_or_else(|| bad("data.placeholder.add", "select a data source"))?; let field = @@ -484,8 +489,13 @@ fn add_placeholder(d: &mut Document, sel: &Selection, p: &Value, name: &str) -> true } else if explicit_story || role_param == Some("text") { false - } else if matches!(role_param, Some("image" | "qr")) { - true + } else if role_param == Some("qr") { + // A QR role with the insertion point in text is refused below rather than bound to a + // selected frame the caret is not in. + sel.text.is_none() + } else if role_param == Some("image") { + // An image role with the insertion point in text places an inline image there. + sel.text.is_none() } else { sel.text.is_none() && !sel.items.is_empty() }; @@ -497,6 +507,12 @@ fn add_placeholder(d: &mut Document, sel: &Selection, p: &Value, name: &str) -> DataFieldKind::Qr => PlaceholderRole::Qr, DataFieldKind::Text => return Err(bad("data.placeholder.add", "say which role to use on this frame")), } + } else if field.kind == DataFieldKind::Image { + // An image field at the insertion point places the image inline in the text. + PlaceholderRole::Image + } else if field.kind == DataFieldKind::Qr { + // A QR field at the insertion point is refused below: QR codes bind to a frame. + PlaceholderRole::Qr } else { PlaceholderRole::Text }; @@ -515,14 +531,58 @@ fn add_placeholder(d: &mut Document, sel: &Selection, p: &Value, name: &str) -> } PlaceholderAnchor::Item { id: item } } else { - if matches!(role, PlaceholderRole::Image | PlaceholderRole::Qr) { - return Err(bad("data.placeholder.add", "image and qr placeholders bind to a frame")); + if role == PlaceholderRole::Qr { + return Err(bad("data.placeholder.add", "qr placeholders bind to a frame")); + } + // The insertion point is in a table cell or a footnote: the field goes into that text as + // its marker, which the merge fills as it fills a typed one. Such a text is a story of its + // own that a placeholder can't name, and the selection's offsets are its own, so they used + // to put the marker in the table's story instead (#2315). + if !explicit_story + && let Some(t) = sel.text + && let Some(pressed) = t.cell + { + // The merge fills such a text with the record's value as text, so an image there + // would merge as its path. + if role == PlaceholderRole::Image { + return Err(bad( + "data.placeholder.add", + "an image field can't go in a table cell or a note; bind it to a frame, or insert it with role text to merge its path", + )); + } + if role != PlaceholderRole::Text { + return Err(bad("data.placeholder.add", "a hyperlink field can't go in a table cell or a note; insert it as text")); + } + // The merge finds a marker by its name, so a name that can't be read back out of one + // would stay a marker: say so rather than insert it. + if name.is_empty() || name.contains(['<', '>', '\n']) { + return Err(bad( + "data.placeholder.add", + format!("the field \"{name}\" can't be inserted in a table cell or a note: its name holds < > or a line break"), + )); + } + // A position a merged cell covers is the merged cell's: the field goes where it shows. + let cell = d.story(t.story).and_then(|st| st.tables.get(&pressed.table)).map_or(pressed, |tab| { + let (row, col) = tab.owner(pressed.row, pressed.col); + designcraft_doc::CellAddr { row, col, ..pressed } + }); + let marker = format!("<<{name}>>"); + let st = d.text_story_mut(t.story, Some(cell)).ok_or_else(|| bad("data.placeholder.add", "no table cell there"))?; + let at = if cell == pressed { t.range().start.min(st.text.len()) } else { st.text.len() }; + let at = designcraft_doc::floor_char_boundary(&st.text, at); + st.replace(at..at, &marker); + // The caret goes after the field, in that text, as after typing; a cell selection + // would have the next keystroke replace the whole cell, field and all. + let end = at + marker.len(); + sel.cells = None; + sel.text = Some(designcraft_doc::TextSel { anchor: end, focus: end, cell: Some(cell), ..t }); + return Ok(json!({"cell": true, "marker": marker})); } let (story, at, end) = text_target(p, sel).ok_or_else(|| bad("data.placeholder.add", "select text or a frame"))?; if d.story(story).is_none() { return Err(bad("data.placeholder.add", "no story")); } - if role == PlaceholderRole::Text { + if matches!(role, PlaceholderRole::Text | PlaceholderRole::Image) { let marker = format!("<<{name}>>"); let at = { let text = d.story(story).map(|st| st.text.clone()).unwrap_or_default(); @@ -532,6 +592,11 @@ fn add_placeholder(d: &mut Document, sel: &Selection, p: &Value, name: &str) -> st.replace(at..at, &marker); } d.adjust_text_ranges(story, at..at, marker.len()); + // The caret moves past the field, as after typing, so the next field goes after it. + if let Some(t) = sel.text.as_mut().filter(|t| t.story == story && t.cell.is_none()) { + let shift = |pos: usize| if pos >= at { pos + marker.len() } else { pos }; + (t.anchor, t.focus) = (shift(t.anchor), shift(t.focus)); + } PlaceholderAnchor::Text { story, start: at, end: at.saturating_add(marker.len()) } } else { let text = d.story(story).map(|st| st.text.clone()).unwrap_or_default(); @@ -574,7 +639,7 @@ pub(crate) fn sync_placeholders(doc: &mut Document) { } PlaceholderAnchor::Text { story, start, end } => { let text = doc.story(story).map(|st| st.text.clone()).unwrap_or_default(); - if ph.role != PlaceholderRole::Text { + if !matches!(ph.role, PlaceholderRole::Text | PlaceholderRole::Image) { if start <= end && end <= text.len() { keep.push(ph); } diff --git a/crates/engine/src/cmd/datamerge/fill.rs b/crates/engine/src/cmd/datamerge/fill.rs index a7b4a0ba6..24d097757 100644 --- a/crates/engine/src/cmd/datamerge/fill.rs +++ b/crates/engine/src/cmd/datamerge/fill.rs @@ -8,10 +8,10 @@ use std::path::{Path, PathBuf}; use std::sync::Arc; use designcraft_doc::{ - Asset, AssetId, Content, DataField, Fill, Fitting, Graphic, Hyperlink, HyperlinkDest, HyperlinkSource, Item, ItemId, MergeOptions, - PlaceholderAnchor, PlaceholderRole, Shape, SpreadRef, Story, StoryId, + AnchorPosition, AnchoredObject, Asset, AssetId, Content, DataField, DataFieldKind, Fill, Fitting, Graphic, Hyperlink, HyperlinkDest, + HyperlinkSource, Item, ItemId, MergeOptions, OBJECT_MARK, PlaceholderAnchor, PlaceholderRole, Shape, SpreadRef, Story, StoryId, }; -use designcraft_geom::{Affine, Rect, Vec2}; +use designcraft_geom::{Affine, Rect, Vec2, shapes}; use super::parse::image_candidates; use crate::EngineError; @@ -147,6 +147,16 @@ struct Rep { start: usize, end: usize, text: String, + /// An inline image that takes the range's place; `text` is then its object mark. + object: Option, +} + +/// An image field at a text range: the placed image goes into the text in the marker's place. +struct InlineImage { + story: StoryId, + start: usize, + end: usize, + field: String, } /// Where `fill_row` looks for linked images: the merge options and the two search folders. @@ -171,7 +181,7 @@ pub struct ImageCache { #[derive(Default)] struct ImageCacheInner { - files: std::collections::HashMap>>, + files: std::collections::HashMap, bytes: usize, } @@ -181,14 +191,16 @@ const MAX_CACHED_IMAGE_BYTES: usize = 256 << 20; impl ImageCache { /// The bytes of `path`, reading it once per merge. `read` is called only on a miss. - fn get_or_read(&self, path: &Path, read: impl FnOnce() -> Option>) -> Option>> { + fn get_or_read(&self, path: &Path, read: impl FnOnce() -> Option>) -> Option { if let Some(found) = self.inner.borrow().files.get(path) { return Some(found.clone()); } - let bytes = std::sync::Arc::new(read()?); + let bytes = read()?; + let len = bytes.len(); + let bytes = designcraft_doc::AssetData::embedded(bytes); let mut inner = self.inner.borrow_mut(); - if inner.bytes.saturating_add(bytes.len()) <= MAX_CACHED_IMAGE_BYTES { - inner.bytes = inner.bytes.saturating_add(bytes.len()); + if inner.bytes.saturating_add(len) <= MAX_CACHED_IMAGE_BYTES { + inner.bytes = inner.bytes.saturating_add(len); inner.files.insert(path.to_path_buf(), bytes.clone()); } Some(bytes) @@ -199,6 +211,7 @@ impl ImageCache { #[derive(Default)] struct Pending { reps: Vec, + images: Vec, links: Vec<(PlaceholderAnchor, HyperlinkDest, String)>, parent: bool, report: FillReport, @@ -225,9 +238,16 @@ pub fn fill_row( PlaceholderAnchor::Item { .. } => plan_item(doc, maps, ph, &cell, record, sources, &mut pending), } } - let Pending { mut reps, links, parent, mut report } = pending; - typed_reps(doc, fields, row, maps, &placeholders, &mut reps); + let Pending { mut reps, mut images, links, parent, mut report } = pending; + typed_reps(doc, fields, row, maps, &placeholders, &mut reps, &mut images); + for InlineImage { story, start, end, field } in images { + let cell = cell_of(fields, row, &field); + let object = inline_image(doc, story, &field, cell, record, sources, &mut report); + let text = if object.is_some() { OBJECT_MARK.to_string() } else { String::new() }; + reps.push(Rep { story, start, end, text, object }); + } apply_reps(doc, &reps); + fill_nested_markers(doc, fields, row, maps); for (anchor, dest, field) in links { let anchor = match anchor { PlaceholderAnchor::Text { story, start, end } => { @@ -261,13 +281,14 @@ fn plan_text( return; }; match ph.role { - PlaceholderRole::Text => pending.reps.push(Rep { story: mapped, start, end, text: cell }), + PlaceholderRole::Text => pending.reps.push(Rep { story: mapped, start, end, text: cell, object: None }), + PlaceholderRole::Image => pending.images.push(InlineImage { story: mapped, start, end, field: ph.field.clone() }), PlaceholderRole::Hyperlink => { if let Some(dest) = classify_link(&cell) { pending.links.push((PlaceholderAnchor::Text { story: mapped, start, end }, dest, ph.field.clone())); } } - PlaceholderRole::Image | PlaceholderRole::Qr => {} + PlaceholderRole::Qr => {} } } @@ -306,6 +327,7 @@ fn typed_reps( maps: &Maps, placeholders: &[designcraft_doc::Placeholder], reps: &mut Vec, + images: &mut Vec, ) { let mut stories: Vec<(StoryId, StoryId)> = maps.stories.iter().map(|(a, b)| (*a, *b)).collect(); stories.sort_by_key(|(a, _)| a.0); @@ -315,7 +337,9 @@ fn typed_reps( let covers: Vec<(usize, usize)> = placeholders .iter() .filter_map(|ph| match (&ph.role, &ph.anchor) { - (PlaceholderRole::Text, PlaceholderAnchor::Text { story, start, end }) if *story == original => Some((*start, *end)), + (PlaceholderRole::Text | PlaceholderRole::Image, PlaceholderAnchor::Text { story, start, end }) if *story == original => { + Some((*start, *end)) + } _ => None, }) .collect(); @@ -323,14 +347,85 @@ fn typed_reps( if covers.iter().any(|(a, b)| start < *b && end > *a) { continue; } - if !fields.iter().any(|f| f.name == name) { + let Some(field) = fields.iter().find(|f| f.name == name) else { continue }; + if field.kind == DataFieldKind::Image { + images.push(InlineImage { story: mapped, start, end, field: name }); continue; } - reps.push(Rep { story: mapped, start, end, text: cell_of(fields, row, &name).to_string() }); + reps.push(Rep { story: mapped, start, end, text: cell_of(fields, row, &name).to_string(), object: None }); } } } +/// How deep the merge follows texts inside texts (a table in a cell of a table, a note in a cell). +/// Documents don't come anywhere near it; a file that goes deeper is filled down to here instead of +/// exhausting the stack. +pub(super) const MAX_NESTED_DEPTH: usize = 32; + +/// The `<>` markers in the table cells, footnotes and endnotes of the stories being filled. +/// Those texts are stories inside their story, which no placeholder can name and `typed_reps` +/// doesn't read, so a field in a table was left as its marker (#2315). A story, table or note is +/// copied only when something inside it holds a marker of a known field. +fn fill_nested_markers(doc: &mut designcraft_doc::Document, fields: &[DataField], row: &[String], maps: &Maps) { + let mut mapped: Vec = maps.stories.values().copied().collect(); + mapped.sort(); + mapped.dedup(); + for sid in mapped { + if !doc.story(sid).is_some_and(|st| inner_has(st, fields, 0)) { + continue; + } + let Some(st) = doc.story_mut(sid) else { continue }; + fill_inner(st, fields, row, 0); + } +} + +/// Whether `st`'s own text holds a marker of a known field. +fn own_has(st: &Story, fields: &[DataField]) -> bool { + find_markers(&st.text).iter().any(|(_, _, name)| fields.iter().any(|f| f.name == *name)) +} + +/// Whether a text inside `st` (a table cell, footnote or endnote, or one inside those), not `st`'s +/// own text, holds a marker of a known field. +fn inner_has(st: &Story, fields: &[DataField], depth: usize) -> bool { + if depth >= MAX_NESTED_DEPTH { + return false; + } + let holds = |t: &Story| own_has(t, fields) || inner_has(t, fields, depth + 1); + st.tables.values().any(|t| t.cells.iter().any(|c| holds(&c.text))) || st.notes.iter().chain(&st.endnotes).any(|n| holds(&n.text)) +} + +/// Fill the known fields' markers in the texts inside `st`, not in its own text. +fn fill_inner(st: &mut Story, fields: &[DataField], row: &[String], depth: usize) { + if depth >= MAX_NESTED_DEPTH { + return; + } + let holds = |t: &Story| own_has(t, fields) || inner_has(t, fields, depth + 1); + for t in st.tables.values_mut() { + if t.cells.iter().any(|c| holds(&c.text)) { + for c in &mut Arc::make_mut(t).cells { + fill_own(&mut c.text, fields, row); + fill_inner(&mut c.text, fields, row, depth + 1); + } + } + } + for n in st.notes.iter_mut().chain(st.endnotes.iter_mut()) { + if holds(&n.text) { + let n = Arc::make_mut(n); + fill_own(&mut n.text, fields, row); + fill_inner(&mut n.text, fields, row, depth + 1); + } + } +} + +/// Replace the markers of known fields in `st`'s own text with the record's values. +fn fill_own(st: &mut Story, fields: &[DataField], row: &[String]) { + let found: Vec<(usize, usize, String)> = + find_markers(&st.text).into_iter().filter(|(_, _, name)| fields.iter().any(|f| f.name == *name)).collect(); + for (start, end, name) in found.into_iter().rev() { + st.replace(start..end, cell_of(fields, row, &name)); + } +} + fn find_markers(text: &str) -> Vec<(usize, usize, String)> { let mut out = Vec::new(); let mut i = 0; @@ -367,6 +462,15 @@ fn apply_reps(doc: &mut designcraft_doc::Document, reps: &[Rep]) { for r in mine { if r.start <= r.end && r.end <= st.text.len() { st.replace(r.start..r.end, &r.text); + // The replacement made a blank object for its mark; the image takes that slot. + if let Some(obj) = &r.object + && st.text.get(r.start..).is_some_and(|t| t.starts_with(OBJECT_MARK)) + { + let k = st.text[..r.start].matches(OBJECT_MARK).count(); + if let Some(slot) = st.objects.get_mut(k) { + *slot = Arc::new(obj.clone()); + } + } } } } @@ -420,10 +524,19 @@ fn create_link(doc: &mut designcraft_doc::Document, anchor: PlaceholderAnchor, d true } -fn place_image(doc: &mut designcraft_doc::Document, item: ItemId, field: &str, cell: &str, record: u32, sources: &Sources, report: &mut FillReport) { - let Sources { options, data_dir, doc_dir, images } = *sources; +/// An image file named by a cell: where it was found, its bytes, its pixel size and its natural size. +struct LoadedImage { + path: PathBuf, + bytes: designcraft_doc::AssetData, + pixels: (u32, u32), + natural: (f64, f64), +} + +/// The first candidate for `cell` that reads and decodes; `None` when none does. +fn load_image(cell: &str, sources: &Sources) -> Option { + let Sources { data_dir, doc_dir, images, .. } = *sources; let cands = image_candidates(cell, data_dir, doc_dir); - let found = cands.iter().find_map(|p| { + cands.iter().find_map(|p| { // Read once per merge: many records naming one file is the normal case, and reading it // per record is the amplification (#1595). let bytes = images.get_or_read(p, || { @@ -434,24 +547,101 @@ fn place_image(doc: &mut designcraft_doc::Document, item: ItemId, field: &str, c } crate::io::read_file(p).ok().filter(|b| !b.is_empty()) })?; - Some((p.clone(), bytes)) + // A file that does not decode leaves the search going, so a valid image at a later + // candidate is still found. + let raw = bytes.embedded_bytes()?; + let (pixels, natural) = designcraft_render::image_size(raw).zip(designcraft_render::natural_size(raw, 0))?; + Some(LoadedImage { path: p.clone(), bytes, pixels, natural }) + }) +} + +fn report_missing(report: &mut FillReport, record: u32, field: &str, cell: &str) { + report.missing.push(MissingImage { record, field: field.to_string(), path: cell.to_string() }); + report.warnings.push(format!("Record {record}, field {field}: missing image {cell}.")); +} + +/// Add `image` to the document as a new asset, linked to its file when the options say so. +fn add_image_asset(doc: &mut designcraft_doc::Document, image: LoadedImage, field: &str, options: &MergeOptions) -> AssetId { + let fresh = AssetId(doc.alloc()); + let name = image.path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| field.to_string()); + let link = options.link_images.then(|| image.path.to_string_lossy().into_owned()); + doc.add_asset(Asset { + id: fresh, + name, + mime: designcraft_render::image_mime(image.bytes.embedded_bytes().map_or(&[][..], |b| b.as_slice())).to_string(), + link, + // The cached buffer is shared with every other record naming this file, rather than + // copied per record (#1595). + data: image.bytes, + pixels: Some(image.pixels), + ..Default::default() + }) +} + +/// The image `cell` names, as an inline object for the text of `story`. It comes in at its +/// natural size, scaled down to fit the smallest text column of the story's frames (never scaled up). +fn inline_image( + doc: &mut designcraft_doc::Document, + story: StoryId, + field: &str, + cell: &str, + record: u32, + sources: &Sources, + report: &mut FillReport, +) -> Option { + let Some(image) = load_image(cell, sources) else { + report_missing(report, record, field, cell); + return None; + }; + let (nw, nh) = image.natural; + let frame = doc.story(story).and_then(|st| st.frames.first().copied()).and_then(|id| doc.item(id)); + let layer = frame.map_or_else(|| doc.default_layer(), |it| it.layer); + // The marker may flow into any of the story's frames: fit the smallest column among them. + let fit = designcraft_compose::frame_specs(doc, story) + .iter() + .flat_map(|f| f.columns()) + .map(|b| (b.width() / nw).min(b.height() / nh)) + .reduce(f64::min) + .unwrap_or(1.0); + let k = if fit.is_finite() && fit > 0.0 { fit.min(1.0) } else { 1.0 }; + let rect = Rect::new(0.0, 0.0, nw * k, nh * k); + let xf = Affine::scale(k); + if super::super::file::validate_placement((nw, nh), rect, xf, "data.merge").is_err() { + report.missing.push(MissingImage { record, field: field.to_string(), path: cell.to_string() }); + report.warnings.push(format!("Record {record}, field {field}: image {cell} exceeds finite geometry limits.")); + return None; + } + let asset = add_image_asset(doc, image, field, sources.options); + let mut it = Item::new(ItemId(doc.alloc()), layer, Shape::Rectangle, shapes::rectangle(rect)); + it.object_style = doc.styles.default_graphic_frame.clone(); + if let Some(e) = doc.styles.object_effects(&it.object_style) { + it.effects = e.clone(); + } + it.content = Content::Graphic(Graphic { + layer_options: None, + asset, + size: (nw, nh), + xf, + auto_fit: Fitting::None, + fit_align: 0, + crop: [0.0; 4], + wrap: Default::default(), + clip: None, + fill: Default::default(), }); - let Some((path, bytes)) = found else { + Some(AnchoredObject::new(it, AnchorPosition::default())) +} + +fn place_image(doc: &mut designcraft_doc::Document, item: ItemId, field: &str, cell: &str, record: u32, sources: &Sources, report: &mut FillReport) { + let options = sources.options; + let Some(image) = load_image(cell, sources) else { if let Some(it) = doc.item_mut(item) { it.content = Content::Unassigned; } - report.missing.push(MissingImage { record, field: field.to_string(), path: cell.to_string() }); - report.warnings.push(format!("Record {record}, field {field}: missing image {cell}.")); - return; - }; - let Some(((pw, ph), (nw, nh))) = designcraft_render::image_size(&bytes).zip(designcraft_render::natural_size(&bytes, 0)) else { - if let Some(it) = doc.item_mut(item) { - it.content = Content::Unassigned; - } - report.missing.push(MissingImage { record, field: field.to_string(), path: cell.to_string() }); - report.warnings.push(format!("Record {record}, field {field}: missing image {cell}.")); + report_missing(report, record, field, cell); return; }; + let (nw, nh) = image.natural; let Some(inner) = doc.item(item).map(|it| it.inner_bounds()) else { report.warnings.push(format!("Record {record}, field {field}: missing image {cell}.")); report.missing.push(MissingImage { record, field: field.to_string(), path: cell.to_string() }); @@ -488,20 +678,7 @@ fn place_image(doc: &mut designcraft_doc::Document, item: ItemId, field: &str, c report.warnings.push(format!("Record {record}, field {field}: image {cell} exceeds finite geometry limits.")); return; } - let fresh = AssetId(doc.alloc()); - let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| field.to_string()); - let link = options.link_images.then(|| path.to_string_lossy().into_owned()); - g.asset = doc.add_asset(Asset { - id: fresh, - name, - mime: designcraft_render::image_mime(&bytes).to_string(), - link, - // The cached buffer is shared with every other record naming this file, rather than - // copied per record (#1595). - data: bytes, - pixels: Some((pw, ph)), - ..Default::default() - }); + g.asset = add_image_asset(doc, image, field, options); if let Some(it) = doc.item_mut(item) { it.content = Content::Graphic(g); } @@ -662,4 +839,15 @@ mod image_path_tests { let found = image_candidates("img/x.png", Some(data), Some(doc)); assert_eq!(found, [data.join("img").join("x.png"), doc.join("img").join("x.png")]); } + + /// A path that starts with one separator is tried as it is, then beside the data file and the + /// document without the separator. Two separators still name another computer. + #[cfg(unix)] + #[test] + fn a_rooted_image_cell_is_also_tried_beside_the_data_and_the_document() { + let (data, doc) = (Path::new("/work/data"), Path::new("/work/doc")); + let found = image_candidates("/img/x.png", Some(data), Some(doc)); + assert_eq!(found, [Path::new("/img/x.png").to_path_buf(), data.join("img").join("x.png"), doc.join("img").join("x.png")]); + assert!(image_candidates("//192.0.2.1/img/x.png", Some(data), Some(doc)).is_empty()); + } } diff --git a/crates/engine/src/cmd/datamerge/parse.rs b/crates/engine/src/cmd/datamerge/parse.rs index d3d3a8302..435188f99 100644 --- a/crates/engine/src/cmd/datamerge/parse.rs +++ b/crates/engine/src/cmd/datamerge/parse.rs @@ -159,7 +159,11 @@ pub fn select_records(count: usize, records: &str, one: u32, range: &str, limit: let i = record_index(one, count)?; idx.push(i); } - "range" => select_range(range, count, &mut idx, &mut seen)?, + "range" => { + // Past this many records nothing more can be kept, so later ranges are only validated. + let keep = limit.filter(|l| *l > 0).map_or(count, |l| count.min(l as usize)); + select_range(range, count, keep, &mut idx, &mut seen)? + } other => return Err(format!("unknown records value \"{other}\"")), } if let Some(limit) = limit { @@ -175,7 +179,9 @@ pub fn select_records(count: usize, records: &str, one: u32, range: &str, limit: } /// Expand a comma-separated list of record numbers and `a-b` ranges into `idx`, skipping repeats. -fn select_range(range: &str, count: usize, idx: &mut Vec, seen: &mut std::collections::HashSet) -> Result<(), String> { +/// Every token is still checked, but once `idx` holds `keep` records no more are expanded, so +/// repeated or overlapping ranges cost nothing past that point. +fn select_range(range: &str, count: usize, keep: usize, idx: &mut Vec, seen: &mut std::collections::HashSet) -> Result<(), String> { if range.trim().is_empty() { return Err("no records".into()); } @@ -194,8 +200,11 @@ fn select_range(range: &str, count: usize, idx: &mut Vec, seen: &mut std: if a > b { return Err(format!("range {a}-{b} is reversed")); } + // Both ends in range means every record between them is. + record_index(a, count)?; + record_index(b, count)?; let mut n = a; - while n <= b { + while n <= b && idx.len() < keep { let i = record_index(n, count)?; if seen.insert(i) { idx.push(i); @@ -288,15 +297,18 @@ fn next_slot(col: i32, row: i32, rows_first: bool, fits_col: &impl Fn(i32) -> bo /// Files to try for an image cell: an absolute path as it is, a relative one beside the data /// file, then beside the document. Relative paths are not resolved against the process working /// directory, and paths that may not be followed ([`crate::io::document_path`]: URLs, other -/// computers, devices) are not candidates. +/// computers, devices) are not candidates. A path that starts with one separator (`\Photos\x.jpg`) +/// is tried as it is first, then beside the data file and the document with that separator dropped. pub fn image_candidates(cell: &str, data_dir: Option<&Path>, doc_dir: Option<&Path>) -> Vec { let cell = cell.trim(); if cell.is_empty() { return Vec::new(); } + let below = cell.strip_prefix(['\\', '/']).filter(|rest| !rest.is_empty() && !rest.starts_with(['\\', '/'])); let found = std::iter::once(crate::io::document_path(cell, None)) .chain(data_dir.map(|dir| crate::io::folder_path(cell, dir))) - .chain(doc_dir.map(|dir| crate::io::folder_path(cell, dir))); + .chain(doc_dir.map(|dir| crate::io::folder_path(cell, dir))) + .chain(below.into_iter().flat_map(|rest| [data_dir, doc_dir].into_iter().flatten().map(move |dir| crate::io::folder_path(rest, dir)))); let mut out: Vec = Vec::new(); for p in found.flatten() { if !out.contains(&p) { diff --git a/crates/engine/src/cmd/datamerge/tests.rs b/crates/engine/src/cmd/datamerge/tests.rs index 4793aac17..e631b69ea 100644 --- a/crates/engine/src/cmd/datamerge/tests.rs +++ b/crates/engine/src/cmd/datamerge/tests.rs @@ -749,6 +749,231 @@ fn role_overrides_column_kind_qr_and_hyperlink() { assert_eq!(kinds, vec!["email:a@b.c".to_string(), "url:https://example.com".to_string()]); } +fn write_png_sized(path: &Path, width: u32, height: u32) { + let pixels = vec![255; width as usize * height as usize * 4]; + let bytes = designcraft_render::Rendered { width, height, pixels }.to_png(); + assert_eq!(designcraft_render::image_size(&bytes), Some((width, height)), "the fixture png must decode"); + if let Some(dir) = path.parent() { + std::fs::create_dir_all(dir).unwrap(); + } + std::fs::write(path, bytes).unwrap(); +} + +/// The images anchored in the stories of document `index`, as (file name, width, height), by name. +fn inline_images(s: &Session, index: usize) -> Vec<(String, f64, f64)> { + let doc = &s.documents()[index].doc; + let mut out = Vec::new(); + for st in doc.stories.values() { + for o in &st.objects { + if let Content::Graphic(g) = &o.item.content { + let name = doc.assets.get(&g.asset).map(|a| a.name.clone()).unwrap_or_default(); + let (w, h) = o.size(); + out.push((name, w, h)); + } + } + } + out.sort_by(|a, b| a.0.cmp(&b.0)); + out +} + +/// An image field inserted at a text insertion point placed the path as text. It places the +/// image in the text: at its natural size, scaled down to fit the frame, with a missing file +/// reported and its marker removed. +#[test] +fn an_image_field_at_the_insertion_point_merges_as_an_inline_image() { + let dir = scratch("inline-image"); + let data = dir.join("data"); + write_png_sized(&data.join("pics").join("small.png"), 40, 20); + write_png_sized(&data.join("pics").join("wide.png"), 800, 100); + write(&data.join("cards.csv"), "Name,@Photo\nAda,pics/small.png\nGrace,pics/wide.png\nKai,pics/none.png\n"); + + let mut s = Session::new(); + new_doc(&mut s, 1); + exec(&mut s, "data.source.select", json!({"path": data.join("cards.csv")})); + let made = text_frame(&mut s, [36.0, 36.0, 236.0, 236.0], "Photo: ", None); + exec(&mut s, "text.select", json!({"story": made["story"], "anchor": 7, "focus": 7})); + exec(&mut s, "data.placeholder.add", json!({"field": "Photo"})); + let template = &s.documents()[0].doc; + assert_eq!(template.stories.values().next().unwrap().text, "Photo: <>"); + let width = template.item(designcraft_doc::ItemId(made["id"].as_u64().unwrap())).unwrap().inner_bounds().width(); + + exec(&mut s, "data.preview", json!({"record": 1})); + assert_eq!(inline_images(&s, 0).len(), 1, "the preview shows the image"); + exec(&mut s, "data.preview.stop", json!({})); + + let r = exec(&mut s, "data.merge", json!({})); + assert_eq!(r["records"], 3); + let missing = r["missingImages"].as_array().unwrap(); + assert_eq!(missing.len(), 1, "{missing:?}"); + assert_eq!((missing[0]["record"].as_u64(), missing[0]["path"].as_str()), (Some(3), Some("pics/none.png"))); + let mark = designcraft_doc::OBJECT_MARK; + assert_eq!(texts(&s), vec!["Photo: ".to_string(), format!("Photo: {mark}"), format!("Photo: {mark}")]); + let placed = inline_images(&s, s.active_index().unwrap()); + assert_eq!(placed.len(), 2, "{placed:?}"); + let (small, wide) = (&placed[0], &placed[1]); + assert_eq!(small.0, "small.png"); + assert!((small.1 - 40.0).abs() < 0.01 && (small.2 - 20.0).abs() < 0.01, "a small image keeps its natural size: {small:?}"); + assert_eq!(wide.0, "wide.png"); + assert!((wide.1 - width).abs() < 0.01 && (wide.2 - width / 8.0).abs() < 0.01, "a wide image is scaled down to the frame: {wide:?}"); +} + +/// A QR field at a text insertion point is refused instead of merging its payload as text. +#[test] +fn a_qr_field_at_the_insertion_point_is_refused() { + let mut s = Session::new(); + new_doc(&mut s, 1); + select_csv(&mut s, "@Photo,#Code\n/x.png,hello\n"); + let made = text_frame(&mut s, [36.0, 36.0, 300.0, 300.0], "Hi ", None); + exec(&mut s, "text.select", json!({"story": made["story"], "anchor": 3, "focus": 3})); + let msg = err(&mut s, "data.placeholder.add", json!({"field": "Code"})); + assert!(msg.contains("bind to a frame"), "{msg}"); + assert_eq!(texts(&s), vec!["Hi ".to_string()]); + assert!(s.documents()[0].doc.data_merge.placeholders.is_empty()); +} + +/// An explicit QR role at a text insertion point is refused too, rather than binding the QR code +/// to a selected frame the caret is not in. +#[test] +fn an_explicit_qr_role_at_the_insertion_point_is_refused() { + let mut s = Session::new(); + new_doc(&mut s, 1); + select_csv(&mut s, "Name,#Code\nAda,hello\n"); + let made = text_frame(&mut s, [36.0, 36.0, 300.0, 300.0], "Hi ", None); + let other = text_frame(&mut s, [36.0, 400.0, 300.0, 600.0], "", None); + let other_id = designcraft_doc::ItemId(other["id"].as_u64().unwrap()); + let sid = StoryId(made["story"].as_u64().unwrap()); + let doc = s.doc_mut().unwrap(); + doc.selection = Selection::text(TextSel { story: sid, anchor: 3, focus: 3, frame: None, cell: None }); + doc.selection.items = vec![other_id]; + let msg = err(&mut s, "data.placeholder.add", json!({"field": "Code", "role": "qr"})); + assert!(msg.contains("bind to a frame"), "{msg}"); + let doc = &s.documents()[0].doc; + assert!(doc.data_merge.placeholders.is_empty()); + assert_eq!(doc.item(other_id).unwrap().label, "", "the other frame is not bound"); +} + +/// Fields inserted one after another at the insertion point keep their order: the caret moves +/// past each marker, as after typing. +#[test] +fn fields_inserted_at_the_insertion_point_keep_their_order() { + let mut s = Session::new(); + new_doc(&mut s, 1); + select_csv(&mut s, "Name,City,@Photo\nAda,Paris,/x.png\n"); + let made = text_frame(&mut s, [36.0, 36.0, 300.0, 300.0], "Hi ", None); + exec(&mut s, "text.select", json!({"story": made["story"], "anchor": 3, "focus": 3})); + exec(&mut s, "data.placeholder.add", json!({"field": "Name", "role": "text"})); + exec(&mut s, "data.placeholder.add", json!({"field": "City", "role": "text"})); + exec(&mut s, "data.placeholder.add", json!({"field": "Photo"})); + assert_eq!(texts(&s), vec!["Hi <><><>".to_string()]); + let t = s.documents()[0].selection.text.unwrap(); + assert_eq!((t.anchor, t.focus), (28, 28)); +} + +/// A typed `<>` marker for an image column places the image too, from an absolute path; +/// an explicit text role still writes the path as text. +#[test] +fn a_typed_image_marker_places_the_image_and_a_text_role_keeps_the_path() { + let dir = scratch("typed-image"); + let pic = dir.join("pic.png"); + write_png_sized(&pic, 10, 30); + let mut s = Session::new(); + new_doc(&mut s, 1); + select_csv(&mut s, &format!("@Photo\n{}\n", pic.display())); + text_frame(&mut s, [36.0, 36.0, 300.0, 300.0], "A <> B", None); + let r = exec(&mut s, "data.merge", json!({})); + assert_eq!(r["missingImages"].as_array().map(Vec::len), Some(0)); + assert_eq!(texts(&s), vec![format!("A {} B", designcraft_doc::OBJECT_MARK)]); + let placed = inline_images(&s, s.active_index().unwrap()); + assert_eq!(placed.len(), 1); + assert!((placed[0].1 - 10.0).abs() < 0.01 && (placed[0].2 - 30.0).abs() < 0.01, "{placed:?}"); + + let mut s = Session::new(); + new_doc(&mut s, 1); + select_csv(&mut s, &format!("@Photo\n{}\n", pic.display())); + let made = text_frame(&mut s, [36.0, 36.0, 300.0, 300.0], "", None); + exec(&mut s, "text.select", json!({"story": made["story"], "anchor": 0, "focus": 0})); + exec(&mut s, "data.placeholder.add", json!({"field": "Photo", "role": "text"})); + exec(&mut s, "data.merge", json!({})); + assert_eq!(texts(&s), vec![pic.display().to_string()]); + assert!(inline_images(&s, s.active_index().unwrap()).is_empty()); +} + +/// An explicit image role at a text insertion point places an inline image too, and in a frame +/// with two columns the image is scaled down to one column's width. +#[test] +fn an_inline_image_role_at_text_fits_one_column() { + let dir = scratch("inline-columns"); + let pic = dir.join("wide.png"); + write_png_sized(&pic, 800, 100); + let mut s = Session::new(); + new_doc(&mut s, 1); + select_csv(&mut s, &format!("@Photo\n{}\n", pic.display())); + let made = text_frame(&mut s, [36.0, 36.0, 456.0, 336.0], "", None); + exec(&mut s, "object.textFrameOptions", json!({"ids": [made["id"]], "columns": 2, "gutter": 20})); + exec(&mut s, "text.select", json!({"story": made["story"], "anchor": 0, "focus": 0})); + exec(&mut s, "data.placeholder.add", json!({"field": "Photo", "role": "image"})); + let r = exec(&mut s, "data.merge", json!({})); + assert_eq!(r["missingImages"].as_array().map(Vec::len), Some(0), "{r}"); + let placed = inline_images(&s, s.active_index().unwrap()); + assert_eq!(placed.len(), 1, "{placed:?}"); + // 420 pt wide, less the 20 pt gutter, gives two 200 pt columns. + assert!((placed[0].1 - 200.0).abs() < 0.01 && (placed[0].2 - 25.0).abs() < 0.01, "{placed:?}"); + + // The story threads on into a 100 pt frame: the image fits that one, wherever the marker lands. + let mut s = Session::new(); + new_doc(&mut s, 1); + select_csv(&mut s, &format!("@Photo\n{}\n", pic.display())); + let made = text_frame(&mut s, [36.0, 36.0, 456.0, 336.0], "", None); + let small = exec(&mut s, "frame.create", json!({"rect": [36.0, 400.0, 136.0, 500.0], "content": "unassigned"})); + exec(&mut s, "text.thread", json!({"from": made["id"], "to": small["id"]})); + exec(&mut s, "text.select", json!({"story": made["story"], "anchor": 0, "focus": 0})); + exec(&mut s, "data.placeholder.add", json!({"field": "Photo"})); + exec(&mut s, "data.merge", json!({})); + let placed = inline_images(&s, s.active_index().unwrap()); + assert_eq!(placed.len(), 1, "{placed:?}"); + assert!(placed[0].1 <= 100.0 + 0.01, "{placed:?}"); +} + +/// A cell that starts with one separator (`\pics\a.png`) and names no file from the drive's root +/// is found beside the data file. +#[test] +fn an_image_path_with_a_leading_separator_is_found_beside_the_data_file() { + let dir = scratch("rooted-image"); + let data = dir.join("data"); + write_png_sized(&data.join("dc-merge-rooted-pics").join("a.png"), 12, 12); + write(&data.join("cards.csv"), "@Photo\n\\dc-merge-rooted-pics\\a.png\n/dc-merge-rooted-pics/a.png\n"); + let mut s = Session::new(); + new_doc(&mut s, 1); + exec(&mut s, "data.source.select", json!({"path": data.join("cards.csv")})); + let frame = exec(&mut s, "frame.create", json!({"rect": [36.0, 36.0, 80.0, 80.0], "content": "graphic"})); + exec(&mut s, "data.placeholder.add", json!({"field": "Photo", "item": frame["id"]})); + let r = exec(&mut s, "data.merge", json!({})); + assert_eq!(r["records"], 2); + assert_eq!(r["missingImages"].as_array().map(Vec::len), Some(0), "{r}"); +} + +/// A file at an earlier candidate that is not an image does not hide a valid image at a later +/// one: the search goes on past it. +#[test] +fn a_non_image_file_beside_the_data_does_not_hide_the_image_beside_the_document() { + let dir = scratch("undecodable-image"); + let (data, docs) = (dir.join("data"), dir.join("docs")); + write(&data.join("pics").join("a.png"), "not an image"); + write_png_sized(&docs.join("pics").join("a.png"), 12, 12); + write(&data.join("cards.csv"), "@Photo\npics/a.png\n"); + let mut s = Session::new(); + new_doc(&mut s, 1); + exec(&mut s, "data.source.select", json!({"path": data.join("cards.csv")})); + exec(&mut s, "file.save", json!({"path": docs.join("layout.designcraft")})); + let frame = exec(&mut s, "frame.create", json!({"rect": [36.0, 36.0, 80.0, 80.0], "content": "graphic"})); + exec(&mut s, "data.placeholder.add", json!({"field": "Photo", "item": frame["id"]})); + exec(&mut s, "data.options", json!({"linkImages": true})); + let r = exec(&mut s, "data.merge", json!({})); + assert_eq!(r["missingImages"].as_array().map(Vec::len), Some(0), "{r}"); + let link = graphic_link(&s).unwrap_or_default(); + assert!(link.contains("docs"), "{link}"); +} + #[test] fn single_record_merge_copies_pages_and_leaves_the_template() { let mut s = Session::new(); @@ -1310,3 +1535,267 @@ fn merged_records_give_anchored_objects_their_own_ids() { doc.check().unwrap(); designcraft_format::load(&designcraft_format::save(doc).unwrap()).unwrap(); } + +/// A record previewed into an image placeholder whose frame wraps with an Alpha Channel contour +/// gets the image's outline, as an edit would. +#[test] +fn a_previewed_image_gets_its_alpha_channel_outline() { + let dir = scratch("alpha-preview"); + let mut pixels = vec![0u8; 64 * 64 * 4]; + for y in 0..64 { + for x in 16..48 { + pixels[(y * 64 + x) * 4 + 3] = 255; + } + } + std::fs::write(dir.join("cut.png"), designcraft_render::Rendered { width: 64, height: 64, pixels }.to_png()).unwrap(); + write(&dir.join("pics.csv"), "Photo\ncut.png\n"); + let mut s = Session::new(); + new_doc(&mut s, 1); + exec(&mut s, "data.source.select", json!({"path": dir.join("pics.csv")})); + let frame = exec(&mut s, "frame.create", json!({"rect": [0.0, 0.0, 200.0, 100.0], "content": "graphic"})); + exec(&mut s, "data.placeholder.add", json!({"field": "Photo", "role": "image", "item": frame["id"]})); + exec(&mut s, "object.textWrap", json!({"ids": [frame["id"]], "mode": "contour", "contour": "alphaChannel"})); + assert!(s.doc().unwrap().doc.alpha_outlines.is_empty(), "no image placed yet"); + exec(&mut s, "data.preview", json!({"record": 1})); + let d = &s.doc().unwrap().doc; + assert_eq!(d.alpha_outlines.len(), 1, "the previewed image is traced"); + assert!(d.alpha_outlines[0].width > 0 && !d.alpha_outlines[0].outer.subpaths.is_empty()); + let _ = std::fs::remove_dir_all(&dir); +} + +/// The overset count data merge reports is composed with the merged images' Alpha Channel +/// outlines: a caption over the image's transparent part is set, not counted as overset. With a +/// bounding box wrap the same caption is overset, so the count depends on the outline. +#[test] +fn a_merge_counts_overset_text_with_the_merged_images_outlines() { + let (r, outlines) = merge_with_wrap("alpha-merge", json!({"mode": "contour", "contour": "alphaChannel", "offset": 0})); + assert_eq!(r["oversetStories"], 0, "the caption sits beside the image's visible pixels: {r}"); + assert_eq!(outlines, 1, "the merged document has the image's outline"); + let (r, _) = merge_with_wrap("alpha-merge-box", json!({"mode": "boundingBox", "offset": 0})); + assert_eq!(r["oversetStories"], 1, "the image's frame covers the caption: {r}"); +} + +/// Merges one record whose image is visible only in its left quarter into a graphic placeholder +/// with the text wrap `wrap`, beside a caption over the image's transparent part. Returns the +/// merge's answer and the number of nonempty Alpha Channel outlines in the merged document. +fn merge_with_wrap(name: &str, wrap: Value) -> (Value, usize) { + let dir = scratch(name); + // Visible only in the left quarter. + let mut pixels = vec![0u8; 64 * 64 * 4]; + for y in 0..64 { + for x in 0..16 { + pixels[(y * 64 + x) * 4 + 3] = 255; + } + } + std::fs::write(dir.join("cut.png"), designcraft_render::Rendered { width: 64, height: 64, pixels }.to_png()).unwrap(); + write(&dir.join("pics.csv"), "Photo\ncut.png\n"); + let mut s = Session::new(); + new_doc(&mut s, 1); + exec(&mut s, "data.source.select", json!({"path": dir.join("pics.csv")})); + let frame = exec(&mut s, "frame.create", json!({"rect": [100.0, 100.0, 300.0, 300.0], "content": "graphic"})); + exec(&mut s, "data.placeholder.add", json!({"field": "Photo", "role": "image", "item": frame["id"]})); + exec(&mut s, "data.options", json!({"fitting": "fitContentToFrame"})); + let mut params = wrap; + params["ids"] = json!([frame["id"]]); + exec(&mut s, "object.textWrap", params); + text_frame(&mut s, [220.0, 180.0, 290.0, 220.0], "Hi", None); + let r = exec(&mut s, "data.merge", json!({})); + let doc = &s.documents()[s.active_index().unwrap()].doc; + let outlines = doc.alpha_outlines.iter().filter(|o| o.width > 0 && !o.outer.subpaths.is_empty()).count(); + let _ = std::fs::remove_dir_all(&dir); + (r, outlines) +} + +/// The cell texts of the first table in the active document's first story that has one. +fn cell_texts(s: &Session) -> Vec { + let doc = &s.documents()[s.active_index().unwrap()].doc; + let t = doc.stories.values().find_map(|st| st.tables.values().next().cloned()).expect("a table"); + t.cells.iter().map(|c| c.text.text.clone()).collect() +} + +/// A field inserted with the insertion point in a table cell goes into that cell, and the +/// preview and the merge fill it. The cell's offsets used to put the marker in the table's own +/// story, outside the table, and the merge never read a cell's text (#2315). +#[test] +fn a_field_inserted_in_a_table_cell_goes_there_and_is_filled() { + let mut s = Session::new(); + new_doc(&mut s, 1); + select_csv(&mut s, "Name,City\nAda,London\nGrace,Arlington\n"); + let made = text_frame(&mut s, [36.0, 36.0, 400.0, 200.0], "Who\tWhere", None); + exec(&mut s, "text.select", json!({"story": made["story"], "anchor": 0, "focus": 9})); + exec(&mut s, "table.convertFromText", json!({"columnSeparator": "tab"})); + let story_text = |s: &Session| s.documents()[s.active_index().unwrap()].doc.stories.values().next().unwrap().text.clone(); + let before = story_text(&s); + exec(&mut s, "table.select", json!({"story": made["story"], "rows": [0, 0], "cols": [1, 1]})); + let r = exec(&mut s, "data.placeholder.add", json!({"field": "City"})); + assert_eq!(r["marker"], "<>", "{r}"); + assert_eq!(cell_texts(&s), ["Who", "<>Where"], "the marker is in the cell with the caret"); + assert_eq!(story_text(&s), before, "and not in the table's story"); + + exec(&mut s, "data.preview", json!({"record": 2})); + assert_eq!(cell_texts(&s), ["Who", "ArlingtonWhere"], "the preview fills the cell"); + exec(&mut s, "data.preview.stop", json!({})); + assert_eq!(cell_texts(&s), ["Who", "<>Where"], "stopping it puts the marker back"); + exec(&mut s, "data.merge", json!({})); + let merged = &s.documents()[s.active_index().unwrap()].doc; + let mut cities: Vec = + merged.stories.values().flat_map(|st| st.tables.values().map(|t| t.cells[1].text.text.clone()).collect::>()).collect(); + cities.sort(); + assert_eq!(cities, ["ArlingtonWhere", "LondonWhere"], "one table per record, filled"); +} + +/// A field typed (or inserted) in text that is then converted to a table is filled in its cell. +#[test] +fn a_field_converted_into_a_table_is_filled_in_its_cell() { + let mut s = Session::new(); + new_doc(&mut s, 1); + select_csv(&mut s, "Name,City\nAda,London\n"); + let made = text_frame(&mut s, [36.0, 36.0, 400.0, 200.0], "Name\t<>", None); + exec(&mut s, "text.select", json!({"story": made["story"], "anchor": 0, "focus": 13})); + exec(&mut s, "table.convertFromText", json!({"columnSeparator": "tab"})); + assert_eq!(cell_texts(&s), ["Name", "<>"]); + exec(&mut s, "data.preview", json!({"record": 1})); + assert_eq!(cell_texts(&s), ["Name", "Ada"], "the field is filled in its cell"); +} + +/// A table `Who⇥Where` with the caret in its second cell, and a source with `Name` and `City`. +fn table_with_caret_in_cell(s: &mut Session, csv: &str) -> Value { + new_doc(s, 1); + select_csv(s, csv); + let made = text_frame(s, [36.0, 36.0, 400.0, 200.0], "Who\tWhere", None); + exec(s, "text.select", json!({"story": made["story"], "anchor": 0, "focus": 9})); + exec(s, "table.convertFromText", json!({"columnSeparator": "tab"})); + exec(s, "table.select", json!({"story": made["story"], "rows": [0, 0], "cols": [1, 1]})); + made +} + +/// After a field goes into a cell the caret is after it, in that cell, and the cell selection is +/// gone: typing goes on after the field instead of replacing the cell, field and all. +#[test] +fn typing_after_a_field_inserted_in_a_cell_goes_on_after_it() { + let mut s = Session::new(); + table_with_caret_in_cell(&mut s, "Name,City\nAda,London\n"); + exec(&mut s, "data.placeholder.add", json!({"field": "City"})); + let sel = &s.documents()[s.active_index().unwrap()].selection; + assert!(sel.cells.is_none(), "no cell selection left"); + exec(&mut s, "text.insert", json!({"text": ", "})); + assert_eq!(cell_texts(&s), ["Who", "<>, Where"]); +} + +/// A position that a merged cell covers is the merged cell's: the field goes into the merged cell, +/// where it shows, not into the hidden one under it. +#[test] +fn a_field_inserted_in_a_merged_cell_goes_where_it_shows() { + let mut s = Session::new(); + let made = table_with_caret_in_cell(&mut s, "Name,City\nAda,London\n"); + exec(&mut s, "table.merge", json!({"story": made["story"], "rows": [0, 0], "cols": [0, 1]})); + exec(&mut s, "table.select", json!({"story": made["story"], "rows": [0, 0], "cols": [1, 1]})); + exec(&mut s, "data.placeholder.add", json!({"field": "City"})); + let cells = cell_texts(&s); + assert!(cells[0].contains("<>"), "in the merged cell: {cells:?}"); + assert!(!cells[1].contains("<>"), "not in the covered one: {cells:?}"); + exec(&mut s, "data.preview", json!({"record": 1})); + assert!(cell_texts(&s)[0].contains("London"), "and filled: {:?}", cell_texts(&s)); +} + +/// A field whose name a marker can't hold (it has `<` or `>`) can't be filled from a cell, so it +/// isn't inserted there; in body text it still becomes an anchored placeholder. +#[test] +fn a_field_named_with_angle_brackets_is_refused_in_a_cell() { + let mut s = Session::new(); + let made = table_with_caret_in_cell(&mut s, "Customer ,City\n7,London\n"); + let e = s.execute("data.placeholder.add", &json!({"field": "Customer "})).expect_err("refused").to_string(); + assert!(e.contains("can't be inserted in a table cell"), "{e}"); + assert_eq!(cell_texts(&s), ["Who", "Where"], "nothing inserted"); + let other = text_frame(&mut s, [36.0, 300.0, 400.0, 400.0], "No. ", None); + exec(&mut s, "text.select", json!({"story": other["story"], "anchor": 4, "focus": 4})); + assert!(exec(&mut s, "data.placeholder.add", json!({"field": "Customer "}))["id"].is_u64(), "body text still takes it"); + let _ = made; +} + +/// An image field with the insertion point in a table cell is refused with a message about image +/// fields, and nothing is inserted; with role text its marker goes into the cell. +#[test] +fn an_image_field_in_a_cell_is_refused_unless_its_role_is_text() { + let mut s = Session::new(); + table_with_caret_in_cell(&mut s, "Name,@Photo\nAda,pics/a.png\n"); + for params in [json!({"field": "Photo"}), json!({"field": "Photo", "role": "image"})] { + let e = s.execute("data.placeholder.add", ¶ms).expect_err("refused").to_string(); + assert!(e.contains("an image field can't go in a table cell or a note"), "{e}"); + assert!(!e.contains("hyperlink"), "{e}"); + assert_eq!(cell_texts(&s), ["Who", "Where"], "nothing inserted"); + } + let r = exec(&mut s, "data.placeholder.add", json!({"field": "Photo", "role": "text"})); + assert_eq!(r["marker"], "<>", "{r}"); + assert_eq!(cell_texts(&s), ["Who", "<>Where"]); + exec(&mut s, "data.preview", json!({"record": 1})); + assert_eq!(cell_texts(&s), ["Who", "pics/a.pngWhere"], "the text role merges the path"); +} + +/// Endnote text is filled too: it is a text inside its story, like a footnote's. +#[test] +fn a_field_in_an_endnote_is_filled() { + let mut s = Session::new(); + new_doc(&mut s, 1); + select_csv(&mut s, "Name,City\nAda,London\n"); + let made = text_frame(&mut s, [36.0, 36.0, 400.0, 200.0], "See the note", None); + exec(&mut s, "text.select", json!({"story": made["story"], "anchor": 12, "focus": 12})); + exec(&mut s, "endnote.insert", json!({"text": "From <>"})); + let endnotes = |s: &Session| -> Vec { + s.documents()[s.active_index().unwrap()].doc.stories.values().flat_map(|st| st.endnotes.iter().map(|e| e.text.text.clone())).collect() + }; + assert_eq!(endnotes(&s), ["From <>"]); + exec(&mut s, "data.preview", json!({"record": 1})); + assert_eq!(endnotes(&s), ["From London"]); +} + +/// Tables nested in cells far deeper than any document goes are filled down to the merge's depth +/// limit, and the preview returns instead of exhausting the stack. +#[test] +fn deeply_nested_tables_are_filled_down_to_the_limit_without_overflowing() { + use designcraft_doc::{Cell, ParaFormat, Table}; + let mut s = Session::new(); + new_doc(&mut s, 1); + select_csv(&mut s, "Name,City\nAda,London\n"); + let made = text_frame(&mut s, [36.0, 36.0, 400.0, 200.0], "x", None); + let sid = StoryId(made["story"].as_u64().unwrap()); + // `depth` tables, each in the one cell of the next, each cell's own text `<>`. + let nest = |depth: usize| { + let mut inner: Option = None; + for i in 0..depth { + let mut t = Table::new(1000 + i as u64, 1, 1, 0, 0, 100.0); + t.cells[0] = Cell::with_text("<>", ParaFormat::default()); + if let Some(child) = inner.take() { + t.cells[0].text.insert_table(0, child); + } + inner = Some(t); + } + inner.unwrap() + }; + s.edit(|d, _| { + d.story_mut(sid).unwrap().insert_table(0, nest(500)); + Ok(()) + }) + .unwrap(); + exec(&mut s, "data.preview", json!({"record": 1})); + let doc = &s.documents()[s.active_index().unwrap()].doc; + let mut t = doc.story(sid).unwrap().tables.values().next().unwrap().clone(); + let mut filled = Vec::new(); + for _ in 0..40 { + filled.push(t.cells[0].text.text.contains("Ada")); + let Some(next) = t.cells[0].text.tables.values().next().cloned() else { break }; + t = next; + } + assert!(filled[..super::fill::MAX_NESTED_DEPTH].iter().all(|f| *f), "filled down to the limit: {filled:?}"); + assert!(!filled[super::fill::MAX_NESTED_DEPTH], "and not past it"); +} + +#[test] +fn select_records_stops_expanding_once_the_limit_is_met_but_still_checks_every_range() { + // 4 billion records in a range would not finish if it were expanded; the limit stops it. + let idx = parse::select_records(u32::MAX as usize, "range", 1, "1-3,1-4294967295,2-4294967295", Some(5)).unwrap(); + assert_eq!(idx, vec![0, 1, 2, 3, 4]); + // A later token that is out of range is still an error. + assert!(parse::select_records(10, "range", 1, "1-10,5-11", Some(2)).is_err()); + assert!(parse::select_records(10, "range", 1, "1-2,0", Some(2)).is_err()); +} diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index ef7e95224..9b2ac1a1c 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -142,15 +142,18 @@ fn paste_text(s: &mut Session, text: Option, formatted: bool) -> Result< let mut stories = std::collections::HashMap::new(); let fresh: Vec = list .iter() - .map(|i| { - let mut i = i.clone(); - super::object::renumber(d, &items, &mut i, &mut stories); + .map(|orig| { + let mut i = orig.clone(); + if !super::object::renumber(d, &items, &mut i, &mut stories) { + return Err(designcraft_doc::DocError::Invalid(format!("{} nests groups or tables too deeply to copy", orig.id))); + } if d.layer(i.layer).is_none() { i.layer = d.default_layer(); } - i + Ok(i) }) - .collect(); + .collect::>()?; + super::object::retarget_copied_xrefs(d, &items, &stories); let end = super::anchored::anchor_items(d, t.story, r.start, fresh, &Default::default())?; sel.text = Some(designcraft_doc::TextSel { anchor: end, focus: end, ..t }); Ok(json!({"pos": end, "anchored": list.len()})) diff --git a/crates/engine/src/cmd/export.rs b/crates/engine/src/cmd/export.rs index 270fcfc4c..d65af9272 100644 --- a/crates/engine/src/cmd/export.rs +++ b/crates/engine/src/cmd/export.rs @@ -22,3 +22,6 @@ pub use registry::specs; #[cfg(test)] mod text_tests; + +#[cfg(test)] +mod linked_tests; diff --git a/crates/engine/src/cmd/export/flatten.rs b/crates/engine/src/cmd/export/flatten.rs index 21fec1c5e..730f28b4a 100644 --- a/crates/engine/src/cmd/export/flatten.rs +++ b/crates/engine/src/cmd/export/flatten.rs @@ -31,7 +31,7 @@ pub(super) fn flatten(d: &designcraft_doc::Document, cache: &designcraft_compose id: aid, name: format!("flattened-{}.png", aid.0), mime: "image/png".into(), - data: std::sync::Arc::new(img.to_png()), + data: designcraft_doc::AssetData::embedded(img.to_png()), pixels: Some((w, h)), ..Default::default() }), @@ -310,7 +310,7 @@ fn rasterize_where_with_links( id: aid, name: format!("effects-{}.png", id.0), mime: "image/png".into(), - data: std::sync::Arc::new(img.to_png()), + data: designcraft_doc::AssetData::embedded(img.to_png()), pixels: Some((w, h)), ..Default::default() }), @@ -426,7 +426,7 @@ pub(super) fn rasterize_layered(d: &designcraft_doc::Document) -> Result<(Option .filter(|it| it.has_pdf_layer_override()) .filter_map(|it| { let g = it.graphic()?; - let a = d.assets.get(&g.asset).filter(|a| designcraft_render::is_pdf(&a.data))?; + let a = d.assets.get(&g.asset).filter(|a| a.output_bytes().is_ok_and(|o| designcraft_render::is_pdf(&o.bytes)))?; Some((it.id, g.clone(), a.clone(), it.pdf_hidden_layers.clone())) }) .collect(); @@ -442,7 +442,8 @@ pub(super) fn rasterize_layered(d: &designcraft_doc::Document) -> Result<(Option let [l, t, r, b] = shown.unwrap_or([0.0, 0.0, 1.0, 1.0]); let page_side = (g.size.0 / (r - l)).max(g.size.1 / (b - t)); let side = (page_side * 300.0 / 72.0).clamp(64.0, 8000.0) as u32; - let png = designcraft_render::pdf_page_png_options_checked(&a.data, a.page as usize, side, Some(&hidden), shown) + let bytes = a.output_bytes().map_err(|e| EngineError::Other(format!("{}: {e}", a.name)))?.bytes; + let png = designcraft_render::pdf_page_png_options_checked(&bytes, a.page as usize, side, Some(&hidden), shown) .map_err(|e| EngineError::Other(format!("{}: {e}", a.name)))?; let px = designcraft_render::image_size(&png); let aid = designcraft_doc::AssetId(out.alloc()); @@ -452,7 +453,7 @@ pub(super) fn rasterize_layered(d: &designcraft_doc::Document) -> Result<(Option id: aid, name: format!("{}.png", a.name), mime: "image/png".into(), - data: std::sync::Arc::new(png), + data: designcraft_doc::AssetData::embedded(png), pixels: px, ..Default::default() }), @@ -540,7 +541,7 @@ mod placed_layer_tests { let aid = d.item(id).unwrap().graphic().unwrap().asset; let asset = Arc::make_mut(d.assets.get_mut(&aid).unwrap()); asset.mime = "image/png".into(); - asset.data = Arc::new(designcraft_render::Rendered { width: 1, height: 1, pixels: vec![0, 0, 0, 0] }.to_png()); + asset.data = designcraft_doc::AssetData::embedded(designcraft_render::Rendered { width: 1, height: 1, pixels: vec![0, 0, 0, 0] }.to_png()); let (copy, count) = super::rasterize_layered(d).unwrap(); assert_eq!(count, 0); assert!(copy.is_none()); diff --git a/crates/engine/src/cmd/export/formats.rs b/crates/engine/src/cmd/export/formats.rs index 845b9b1d7..915954cff 100644 --- a/crates/engine/src/cmd/export/formats.rs +++ b/crates/engine/src/cmd/export/formats.rs @@ -25,7 +25,8 @@ pub(super) fn print_booklet(s: &mut Session, p: &Value) -> Result { } } -/// HTML and reflowable EPUB embed the EPS preview; keep the session's source bytes intact. +/// HTML and reflowable EPUB read embedded bytes only: every used linked asset gets its output +/// bytes embedded, and EPS its preview. The session's own assets stay as they are. fn eps_previews(d: &designcraft_doc::Document) -> (Cow<'_, designcraft_doc::Document>, Vec) { // Match the exporter's reading order (including Article exclusions), not every asset // in the document: unused or hidden graphics must not prevent an export. @@ -48,17 +49,40 @@ fn eps_previews(d: &designcraft_doc::Document) -> (Cow<'_, designcraft_doc::Docu let mut out = Cow::Borrowed(d); let mut warnings = Vec::new(); for id in used { - let Some(a) = d.assets.get(&id).filter(|a| designcraft_images::is_eps(&a.data)) else { - continue; + let Some(a) = d.assets.get(&id) else { continue }; + let linked = a.data.is_linked(); + let got = match a.output_bytes() { + Ok(got) => got, + Err(e) => { + if linked { + warnings.push(format!("{}: the linked file is unavailable ({e}); graphic omitted", a.name)); + } + continue; + } }; - let png = designcraft_images::eps_png(&a.data); - if png.is_none() { - warnings.push(format!("{}: unusable EPS preview; graphic omitted", a.name)); + let bytes = got.bytes; + let eps = designcraft_images::is_eps(&bytes); + // Embedded bytes the writers read as they are; a linked asset's bytes are read here + // (the writers only see embedded data), and EPS is replaced by its preview. + if !eps && !linked { + continue; } + warnings.extend(got.warning); + let data = if eps { + let png = designcraft_images::eps_png(&bytes); + if png.is_none() { + warnings.push(format!("{}: unusable EPS preview; graphic omitted", a.name)); + } + png.unwrap_or_default() + } else { + bytes.as_ref().clone() + }; if let Some(a) = out.to_mut().assets.get_mut(&id) { let a = Arc::make_mut(a); - a.mime = "image/png".into(); - a.data = Arc::new(png.unwrap_or_default()); + if eps { + a.mime = "image/png".into(); + } + a.data = designcraft_doc::AssetData::embedded(data); } } (out, warnings) @@ -142,7 +166,7 @@ pub(super) fn export_text(s: &mut Session, p: &Value) -> Result { let text = match format { "rtf" => designcraft_textimport::export::rtf(doc, story), "tagged" => designcraft_textimport::tagged::tagged_text(doc, story), - _ => designcraft_textimport::export::plain_text(story), + _ => designcraft_textimport::export::plain_text(doc, story), }; match path { Some(path) => { @@ -159,13 +183,30 @@ fn page_text(d: &designcraft_doc::Document, cache: &designcraft_compose::Cache, let mut out = String::new(); for st in d.stories.values() { let cs = cache.get(d, st.id, None); + let spans = d.visible_spans(st); for ft in &cs.frames { if d.page_of_item(ft.frame) != Some(abs) { continue; } + // Pages render printing-only: a hidden or nonprinting frame or group around it, or a top-level item on a hidden or non-printable layer (members draw on its layer), isn't on the rendered page. + // Inside a multi-state object only the active state is drawn. + if d.find(ft.frame).is_some_and(|loc| { + (1..=loc.path.len()).any(|n| { + d.item_at(&designcraft_doc::ItemLoc { spread: loc.spread, path: loc.path[..n].to_vec() }).is_some_and(|it| { + it.hidden + || it.nonprinting + || n == 1 && d.layers.iter().any(|l| (!l.visible || !l.printable) && l.id == it.layer) + || n < loc.path.len() && !it.states.is_empty() && loc.path[n] != it.active_state + }) + }) + }) { + continue; + } for l in &ft.lines { let r = l.range.start.min(st.text.len())..l.range.end.min(st.text.len()); - let t: String = st.text[r].chars().filter(|c| !('\u{E000}'..='\u{F8FF}').contains(c)).collect(); + // The line's text as it shows: hidden conditional text and deletions left out. + let t: String = + designcraft_doc::Document::visible_text(st, &spans, r).chars().filter(|c| !('\u{E000}'..='\u{F8FF}').contains(c)).collect(); if !t.trim().is_empty() { out.push_str(t.trim_end_matches('\n')); out.push('\n'); diff --git a/crates/engine/src/cmd/export/linked_tests.rs b/crates/engine/src/cmd/export/linked_tests.rs new file mode 100644 index 000000000..4509a2fd1 --- /dev/null +++ b/crates/engine/src/cmd/export/linked_tests.rs @@ -0,0 +1,170 @@ +//! Export, preflight, package and alpha wrap with linked images: synthetic files in a temp dir. +#![cfg(not(target_arch = "wasm32"))] + +use std::path::{Path, PathBuf}; +use std::sync::Arc; + +use designcraft_doc::{AssetData, AssetId, LinkedSource, Proxy, Storage}; +use serde_json::{Value, json}; + +use crate::Session; +use crate::asset_io::{content_hash, fingerprint_from}; + +struct Dir(PathBuf); + +impl Dir { + fn new(name: &str) -> Self { + let dir = std::env::temp_dir().join(format!("dc-linked-output-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + Dir(dir) + } +} + +impl Drop for Dir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +/// A `w` × `h` PNG; transparent in its left half when `cut`. +fn png(w: usize, h: usize, cut: bool) -> Vec { + let mut pixels = Vec::new(); + for _ in 0..h { + for x in 0..w { + pixels.extend([200, 40, 40, if cut && x < w / 2 { 0 } else { 255 }]); + } + } + designcraft_render::Rendered { width: w as u32, height: h as u32, pixels }.to_png() +} + +/// A session with `bytes` placed, then made a linked asset to `file` (holding `bytes`) with a +/// proxy of them → the asset. +fn linked_session(file: &Path, bytes: &[u8]) -> (Session, AssetId) { + std::fs::write(file, bytes).unwrap(); + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + s.execute("file.place", &json!({"base64": crate::cmd::base64_encode(bytes), "name": "art.png", "x": 10, "y": 10, "width": 100})).unwrap(); + let id = *s.doc().unwrap().doc.assets.keys().next().unwrap(); + let proxy = designcraft_render::proxy::make_proxy(bytes, 0).unwrap(); + let st = s.doc_mut().unwrap(); + let a = Arc::make_mut(Arc::make_mut(&mut st.doc).assets.get_mut(&id).unwrap()); + a.link = Some(file.to_string_lossy().into_owned()); + a.link_fingerprint = Some(fingerprint_from(&std::fs::metadata(file).unwrap())); + a.link_hash = Some(content_hash(bytes)); + a.storage = Storage::Linked; + a.data = AssetData::linked(LinkedSource::of(a, None).unwrap()); + a.proxy = Some(Proxy { mime: proxy.mime.into(), pixels: proxy.pixels, data: AssetData::embedded(proxy.data) }); + (s, id) +} + +fn warnings(r: &Value) -> String { + r["warnings"].to_string() +} + +fn pdf_text(r: &Value) -> String { + String::from_utf8_lossy(&crate::cmd::base64_decode(r["base64"].as_str().unwrap())).into_owned() +} + +#[test] +fn a_missing_link_is_a_preflight_error_and_exports_its_proxy() { + let dir = Dir::new("missing"); + let file = dir.0.join("art.png"); + let (mut s, _) = linked_session(&file, &png(40, 20, false)); + std::fs::remove_file(&file).unwrap(); + let issues = s.execute("preflight.run", &json!({})).unwrap(); + assert!(issues.to_string().contains("missingLink"), "{issues}"); + let r = s.execute("file.exportPdf", &json!({})).unwrap(); + assert!(warnings(&r).contains("art.png") && warnings(&r).contains("preview"), "{}", warnings(&r)); + assert!(pdf_text(&r).contains("/Subtype /Image") || pdf_text(&r).contains("/Subtype/Image"), "the proxy is in the PDF"); +} + +#[test] +fn a_modified_link_is_a_preflight_warning_and_exports_the_file_on_disk() { + let dir = Dir::new("modified"); + let file = dir.0.join("art.png"); + let (mut s, _) = linked_session(&file, &png(40, 20, false)); + std::fs::write(&file, png(77, 33, false)).unwrap(); + let issues = s.execute("preflight.run", &json!({})).unwrap(); + assert!(issues.to_string().contains("modifiedLink"), "{issues}"); + let r = s.execute("file.exportPdf", &json!({})).unwrap(); + assert!(warnings(&r).contains("file on disk"), "{}", warnings(&r)); + let text = pdf_text(&r); + assert!(text.contains("/Width 77") || text.contains("/Width%2077") || text.contains("/Width\n77"), "the new file's pixels are in the PDF"); +} + +#[test] +fn a_package_copies_a_linked_file_from_disk_and_links_to_the_copy() { + let dir = Dir::new("package"); + let file = dir.0.join("art.png"); + let bytes = png(40, 20, false); + let (mut s, id) = linked_session(&file, &bytes); + let out = dir.0.join("out"); + s.execute("file.package", &json!({"dir": out.to_string_lossy(), "pdf": false, "idml": false})).unwrap(); + let copy = out.join("Links/art.png"); + assert_eq!(std::fs::read(©).unwrap(), bytes); + let doc = std::fs::read_dir(&out) + .unwrap() + .filter_map(Result::ok) + .map(|e| e.path()) + .find(|p| p.extension().is_some_and(|e| e == "designcraft")) + .unwrap(); + std::fs::remove_file(&file).unwrap(); + let mut t = Session::new(); + t.execute("file.open", &json!({"path": doc.to_string_lossy()})).unwrap(); + let a = &t.doc().unwrap().doc.assets[&id]; + assert_eq!((a.storage, a.link_relative.as_deref()), (Storage::Linked, Some("Links/art.png"))); + assert_eq!(a.data.load().unwrap().as_slice(), bytes.as_slice()); +} + +#[test] +fn opening_a_document_with_a_linked_alpha_wrap_image_reads_no_original() { + let dir = Dir::new("alpha"); + let file = dir.0.join("art.png"); + let (mut s, _) = linked_session(&file, &png(64, 64, true)); + let image = s.doc().unwrap().doc.spreads[0].items[0].id.0; + s.execute("object.textWrap", &json!({"ids": [image], "mode": "contour", "contour": "alphaChannel"})).unwrap(); + let path = dir.0.join("doc.designcraft"); + s.execute("file.save", &json!({"path": path.to_string_lossy()})).unwrap(); + let mut t = Session::new(); + t.execute("file.open", &json!({"path": path.to_string_lossy()})).unwrap(); + let d = &t.doc().unwrap().doc; + let a = d.assets.values().next().unwrap(); + assert!(a.data.is_linked() && a.data.resident().is_none(), "no original was read"); + let o = d.alpha_outlines.first().expect("the outline is traced from the proxy"); + assert_eq!((o.width, o.height), (64, 64), "scaled to the original's size"); +} + +#[test] +fn epub_and_html_carry_a_linked_graphic_and_a_modified_one_from_disk() { + let dir = Dir::new("epub"); + let file = dir.0.join("art.png"); + let (mut s, _) = linked_session(&file, &png(40, 20, false)); + let html = s.execute("file.exportHtml", &json!({})).unwrap(); + assert!(html["text"].as_str().unwrap().contains(" = z.file_names().map(str::to_string).collect(); + let image = names.iter().find(|n| n.starts_with("OEBPS/images/")).unwrap_or_else(|| panic!("no image in {names:?}")).clone(); + // A modified link exports the file on disk, with a warning. + std::fs::write(&file, png(77, 33, false)).unwrap(); + let r = s.execute("file.exportEpub", &json!({})).unwrap(); + assert!(warnings(&r).contains("file on disk"), "{}", warnings(&r)); + let mut z = zip::ZipArchive::new(std::io::Cursor::new(crate::cmd::base64_decode(r["base64"].as_str().unwrap()))).unwrap(); + let mut bytes = Vec::new(); + std::io::Read::read_to_end(&mut z.by_name(&image).unwrap(), &mut bytes).unwrap(); + assert_eq!(bytes, std::fs::read(&file).unwrap()); +} + +#[test] +fn a_package_copies_a_modified_link_from_disk_with_a_warning() { + let dir = Dir::new("package-modified"); + let file = dir.0.join("art.png"); + let (mut s, _) = linked_session(&file, &png(40, 20, false)); + let changed = png(77, 33, false); + std::fs::write(&file, &changed).unwrap(); + let out = dir.0.join("out"); + let r = s.execute("file.package", &json!({"dir": out.to_string_lossy(), "pdf": false, "idml": false})).unwrap(); + assert_eq!(std::fs::read(out.join("Links/art.png")).unwrap(), changed); + assert!(r.to_string().contains("file on disk"), "{r}"); +} diff --git a/crates/engine/src/cmd/export/pdf.rs b/crates/engine/src/cmd/export/pdf.rs index a11c4e22a..09a9b9a1e 100644 --- a/crates/engine/src/cmd/export/pdf.rs +++ b/crates/engine/src/cmd/export/pdf.rs @@ -712,4 +712,37 @@ mod overset_tests { let r = s.execute("file.exportPdf", &json!({"pages": [1], "spreads": true})).unwrap(); assert!(about(&r).is_empty(), "the cover's spread holds no overset frame: {r}"); } + + /// Plain print exports attach `/DefaultCMYK` without `/OutputIntents`, PDF/X-4 keeps both + /// cleanly, and PDF/X-1a omits `/DefaultCMYK`. + #[test] + fn export_pdf_command_attaches_default_cmyk_according_to_standard() { + let mut s = Session::new(); + s.execute("file.new", &json!({"intent": "print"})).unwrap(); + s.execute("frame.create", &json!({"rect": [36, 36, 200, 200]})).unwrap(); + s.execute("swatch.create", &json!({"name": "Slate", "color": {"c": 42.5, "m": 17.5, "y": 16.0, "k": 7.1}})).unwrap(); + s.execute("object.fill", &json!({"swatch": "Slate"})).unwrap(); + + let export = |s: &mut Session, extra: serde_json::Value| { + let res = s.execute("file.exportPdf", &extra).unwrap(); + let raw = crate::cmd::base64_decode(res["base64"].as_str().unwrap()); + (raw, res["warnings"].clone()) + }; + + let (plain, plain_w) = export(&mut s, json!({"tagged": true})); + assert_eq!(plain_w, json!([]), "plain export warnings: {plain_w}"); + let plain_text = String::from_utf8_lossy(&plain); + assert!(plain_text.contains("/DefaultCMYK ["), "plain export must carry /DefaultCMYK"); + assert!(!plain_text.contains("/OutputIntents"), "plain export must not carry /OutputIntents"); + + let (x4, x4_w) = export(&mut s, json!({"standard": "x4"})); + assert_eq!(x4_w, json!([]), "PDF/X-4 warnings: {x4_w}"); + let x4_text = String::from_utf8_lossy(&x4); + assert!(x4_text.contains("/DefaultCMYK ["), "PDF/X-4 export must carry /DefaultCMYK"); + assert!(x4_text.contains("/OutputIntents"), "PDF/X-4 export must keep /OutputIntents"); + + let (x1a, _) = export(&mut s, json!({"standard": "x1a"})); + let x1a_text = String::from_utf8_lossy(&x1a); + assert!(!x1a_text.contains("/DefaultCMYK"), "PDF/X-1a must not carry ICCBased DefaultCMYK"); + } } diff --git a/crates/engine/src/cmd/export/text_tests.rs b/crates/engine/src/cmd/export/text_tests.rs index b1b791d3b..48e255ef7 100644 --- a/crates/engine/src/cmd/export/text_tests.rs +++ b/crates/engine/src/cmd/export/text_tests.rs @@ -92,6 +92,25 @@ fn epub_cover_and_fixed_layout() { assert!(p1.contains("width=612, height=792") && p1.contains("Page one words"), "{p1}"); } +/// Fixed-layout page text leaves out frames in a multi-state object's inactive states. +#[test] +fn fixed_epub_text_skips_inactive_states() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let a = s.execute("frame.create", &json!({"rect": [72, 72, 200, 100], "content": "text", "text": "Active words", "caret": false})).unwrap()["id"] + .as_u64() + .unwrap(); + let b = + s.execute("frame.create", &json!({"rect": [72, 300, 200, 100], "content": "text", "text": "Inactive words", "caret": false})).unwrap()["id"] + .as_u64() + .unwrap(); + s.execute("states.create", &json!({"ids": [a, b]})).unwrap(); + let r = s.execute("file.exportFixedEpub", &json!({})).unwrap(); + let mut z = unzip(r["base64"].as_str().unwrap()); + let p1 = read(&mut z, "OEBPS/page1.xhtml"); + assert!(p1.contains("Active words") && !p1.contains("Inactive words"), "{p1}"); +} + /// #775: the fallback follows the font's class, and embedFonts packages the stylesheet's fonts /// (and reports those it can't). #[test] diff --git a/crates/engine/src/cmd/export_batch.rs b/crates/engine/src/cmd/export_batch.rs index 8e685475b..3b24f60c9 100644 --- a/crates/engine/src/cmd/export_batch.rs +++ b/crates/engine/src/cmd/export_batch.rs @@ -557,13 +557,17 @@ mod tests { assert!(pdf.starts_with(b"%PDF-")); } + /// An export name drops reserved characters, and a Windows device name (`CON`, `COM¹`, `LPT³`) + /// is written with a leading `_`. Two files built from one name stay distinct. #[test] fn names_are_made_safe_and_unique() { assert_eq!(safe_name("../a/b:c*?"), "a b c"); assert_eq!(safe_name(" ... "), "Untitled"); assert_eq!(safe_name(&"x".repeat(500)).chars().count(), MAX_NAME); // Windows device names name no file. - for (name, safe) in [("CON", "_CON"), ("nul", "_nul"), ("com1.x", "_com1.x"), ("Console", "Console")] { + for (name, safe) in + [("CON", "_CON"), ("nul", "_nul"), ("com1.x", "_com1.x"), ("COM¹", "_COM¹"), ("lpt³.x", "_lpt³.x"), ("Console", "Console")] + { assert_eq!(safe_name(name), safe); } let mut s = two_layouts(); diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index 44aaa85b7..b8429f860 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -21,7 +21,7 @@ mod snippets; pub use bytes::{DOCUMENT_SNIFF_BYTES, base64_decode, base64_encode, from_bytes, is_document, to_bytes, with_document_extension}; pub(crate) use open::load_document_fonts; pub use open::{RecentPreview, recent_preview}; -pub(crate) use place::{crop_pdf, read_source, validate_placement}; +pub(crate) use place::{crop_pdf, crop_pdf_from, document_of, prepare_placed, read_source, validate_placement}; pub use registry::specs; pub(crate) use snippets::{snippet_bytes, snippet_place}; diff --git a/crates/engine/src/cmd/file/eps_place_tests.rs b/crates/engine/src/cmd/file/eps_place_tests.rs index 2501a31d3..8a78422a3 100644 --- a/crates/engine/src/cmd/file/eps_place_tests.rs +++ b/crates/engine/src/cmd/file/eps_place_tests.rs @@ -167,8 +167,8 @@ fn eps_idml_roundtrip_preserves_source_and_resource_type() { let restored = designcraft_idml::import_idml(&idml).unwrap(); let a = restored.assets.values().next().unwrap(); assert_eq!(a.mime, "application/postscript"); - assert_eq!(a.data.as_slice(), bytes); - assert!(designcraft_render::decode_pixmap(&a.data).is_some()); + assert_eq!(a.data.load().unwrap().as_slice(), bytes); + assert!(designcraft_render::decode_pixmap(&a.data.load().unwrap()).is_some()); // A linked-only EPS keeps its type even when the external file is unavailable; // when the resolver supplies it, sniff the raw source rather than PNG metadata. let mut linked = (*source).clone(); @@ -186,7 +186,7 @@ fn eps_idml_roundtrip_preserves_source_and_resource_type() { .unwrap(); let a = resolved.assets.values().next().unwrap(); assert_eq!(a.mime, "application/postscript"); - assert_eq!(a.data.as_slice(), bytes); + assert_eq!(a.data.load().unwrap().as_slice(), bytes); } } @@ -197,7 +197,7 @@ fn eps_place_cursor_retains_source_and_uses_bounding_box_size() { s.execute("file.new", &json!({})).unwrap(); let result = s.execute("place.load", &json!({"base64": base64_encode(source), "name": "logo.eps"})).unwrap(); let aid = AssetId(result["asset"].as_u64().unwrap()); - assert_eq!(s.doc().unwrap().doc.assets[&aid].data.as_slice(), source); + assert_eq!(s.doc().unwrap().doc.assets[&aid].data.load().unwrap().as_slice(), source); assert_eq!(s.doc().unwrap().doc.assets[&aid].mime, "application/postscript"); assert_eq!(s.doc().unwrap().doc.assets[&aid].pixels, Some((201, 101))); let result = s.execute("place.drop", &json!({"x": 72, "y": 72})).unwrap(); diff --git a/crates/engine/src/cmd/file/open.rs b/crates/engine/src/cmd/file/open.rs index 9cb94f5ab..a2f5c709c 100644 --- a/crates/engine/src/cmd/file/open.rs +++ b/crates/engine/src/cmd/file/open.rs @@ -102,13 +102,15 @@ fn open_path(s: &mut Session, p: &Value) -> Result { }; crate::cmd::interchange::resolve_packaged_links(&mut d, Some(std::path::Path::new(path))); crate::cmd::datamerge::resolve_sources_on_open(&mut d, Some(std::path::Path::new(path))); + let links = crate::cmd::native_links::resolve(&mut d, Some(std::path::Path::new(path)), true); let (fonts, faces, font_warnings) = load_document_fonts(&mut d, path); warnings.extend(font_warnings); warnings.extend(crate::cmd::style::grep_style_warnings(&d)); let mut st = DocState::new(d, Some(path.to_string())); st.fonts = fonts; + let checks = crate::cmd::native_links::start(&mut st, links); let i = s.add_document(st); - Ok(json!({"index": i, "documentFonts": faces, "warnings": warnings})) + Ok(json!({"index": i, "documentFonts": faces, "warnings": warnings, "linkChecks": checks})) } #[cfg(target_arch = "wasm32")] { @@ -176,12 +178,16 @@ pub(super) fn file_open_bytes(s: &mut Session, p: &Value) -> Result { None => load_bytes(&b)?, }; crate::cmd::datamerge::resolve_sources_on_open(&mut d, None); + // No file to resolve relative links against, and nothing moved to links. + let links = crate::cmd::native_links::resolve(&mut d, None, false); if let Some(n) = str_param(p, "name") { // Titled as an IDML file opened from bytes is: without its extension. d.title = without_native_extension(n).to_string(); } - let i = s.add_document(DocState::new(d, None)); - Ok(json!({"index": i, "warnings": warnings})) + let mut st = DocState::new(d, None); + let checks = crate::cmd::native_links::start(&mut st, links); + let i = s.add_document(st); + Ok(json!({"index": i, "warnings": warnings, "linkChecks": checks})) } #[cfg(test)] diff --git a/crates/engine/src/cmd/file/place.rs b/crates/engine/src/cmd/file/place.rs index 6d5236734..7a8a37b95 100644 --- a/crates/engine/src/cmd/file/place.rs +++ b/crates/engine/src/cmd/file/place.rs @@ -4,9 +4,10 @@ use super::EngineError; use super::bytes::base64_encode; use super::bytes::{base64_decode, from_bytes}; use super::{ - Affine, Arc, Asset, AssetId, Content, Graphic, Item, ItemId, PdfCrop, Rect, Result, Selection, Session, Shape, Value, bad, json, ok, shapes, - str_param, + Affine, Asset, AssetId, Content, Graphic, Item, ItemId, PdfCrop, Rect, Result, Selection, Session, Shape, Value, bad, json, ok, shapes, str_param, }; +use crate::cmd::links::{FileLink, give_placed}; +use crate::cmd::native_links::Pending; pub(super) fn file_place(s: &mut Session, p: &Value) -> Result { // The file's size and time before it is read (a linked text file remembers them). @@ -38,9 +39,17 @@ pub(super) fn file_place(s: &mut Session, p: &Value) -> Result { } // Keep the EPS source for link comparison; rendering uses its preview at the bounding box size. let eps_size = eps_size(&bytes, "file.place")?; + // A file placed from a path links to it unless `embed`. + let embed = p.get("embed").and_then(Value::as_bool) == Some(true); + let document = document_of(s); // Video and sound: a media frame (Window › Interactive › Media). if let Some(mime) = designcraft_doc::media_mime(&name) { - return crate::cmd::media::place_media(s, p, name, mime, bytes, link); + let file = link.as_deref().map(|l| FileLink::of(std::path::Path::new(l), before)); + let mut asset = Asset { name, mime: mime.to_string(), ..Default::default() }; + let pending = give_placed(&mut asset, bytes, file, embed, document.as_deref()); + let r = crate::cmd::media::place_media(s, p, asset)?; + prepare_placed(s, pending); + return Ok(r); } // Text files (plain, Word, RTF) flow into frames. if designcraft_textimport::is_text_file(&name) { @@ -90,28 +99,24 @@ pub(super) fn file_place(s: &mut Session, p: &Value) -> Result { _ => PdfCrop::Crop, }; let mime = designcraft_render::image_mime(&bytes).to_string(); - let mut asset = Asset { - page: pdf_page, - name, - mime, - link, - link_fingerprint: crate::cmd::links::loaded_fingerprint(before, &bytes), - data: Arc::new(bytes), - pixels: Some((pw, ph)), - pdf_crop, - ..Default::default() - }; + let file = link.as_deref().map(|l| FileLink::of(std::path::Path::new(l), before)); + let mut asset = Asset { page: pdf_page, name, mime, pixels: Some((pw, ph)), pdf_crop, ..Default::default() }; // The graphic's natural size: the box in points (the whole page when the box can't be found, // and then the document says so). - let (bw, bh) = match crop_pdf(&mut asset) { + let cropped = crop_pdf_from(&mut asset, &bytes); + let pending = give_placed(&mut asset, bytes, file, embed, document.as_deref()); + let (bw, bh) = match cropped { Some(size) => size, None => { asset.pdf_crop = PdfCrop::Crop; (nw, nh) } }; + // A file joining the place cursor's queue goes after the ones already there, whatever is selected. + let load_cursor_param = p.get("loadCursor").and_then(Value::as_bool) == Some(true); + let append = p.get("append").and_then(Value::as_bool) == Some(true); let target_frame = crate::cmd::id_param(p, "frame").or_else(|| { - if ["x", "y", "spread", "width"].iter().any(|key| p.get(*key).is_some_and(|value| !value.is_null())) { + if (load_cursor_param && append) || ["x", "y", "spread", "width"].iter().any(|key| p.get(*key).is_some_and(|value| !value.is_null())) { return None; } let st = s.active()?; @@ -125,10 +130,12 @@ pub(super) fn file_place(s: &mut Session, p: &Value) -> Result { let lid = s.doc()?.active_layer; let px = p.get("x").and_then(Value::as_f64); let py = p.get("y").and_then(Value::as_f64); - if target_frame.is_none() && px.is_none() && py.is_none() && p.get("loadCursor").and_then(Value::as_bool) == Some(true) { - return load_cursor(s, asset, (bw, bh)); + if target_frame.is_none() && px.is_none() && py.is_none() && load_cursor_param { + let r = load_cursor(s, asset, (bw, bh), append)?; + prepare_placed(s, pending); + return Ok(r); } - s.edit(|d, sel| { + let r = s.edit(|d, sel| { let fresh = AssetId(d.alloc()); let aid = d.add_asset(Asset { id: fresh, ..asset }); // The width the whole page (or image) gets; the height follows the proportions. @@ -191,32 +198,77 @@ pub(super) fn file_place(s: &mut Session, p: &Value) -> Result { }; *sel = Selection::items(vec![id]); Ok(json!({"id": id.0, "asset": aid.0})) - }) + })?; + prepare_placed(s, pending); + Ok(r) +} + +/// Have the hash and proxy of graphics just placed into the active document made in the +/// background ([`crate::cmd::native_links::prepare`]). +pub(crate) fn prepare_placed(s: &mut Session, pending: impl IntoIterator) { + if let Ok(st) = s.doc_mut() { + crate::cmd::native_links::prepare(st, pending.into_iter().collect()); + } } /// Sets `a.pdf_box` to where its `pdf_crop` box sits on its page and returns the box's size in /// points. The crop box is the whole page and has none; nor has a page that can't be read, which -/// keeps its crop choice (a missing link relinked later gets its box then). +/// keeps its crop choice (a missing link relinked later gets its box then). Only a PDF with +/// another box chosen is read. pub(crate) fn crop_pdf(a: &mut Asset) -> Option<(f64, f64)> { a.pdf_box = None; - if a.pdf_crop == PdfCrop::Crop || !designcraft_render::is_pdf(&a.data) { + if !crops_pdf(a) { return None; } - let (frac, size) = designcraft_render::pdf_crop_box(&a.data, a.page as usize, a.pdf_crop)?; + let bytes = a.data.load().ok()?; + crop_pdf_from(a, &bytes) +} + +/// [`crop_pdf`] with `a`'s bytes, `bytes`, in hand. +pub(crate) fn crop_pdf_from(a: &mut Asset, bytes: &[u8]) -> Option<(f64, f64)> { + a.pdf_box = None; + if !crops_pdf(a) || !designcraft_render::is_pdf(bytes) { + return None; + } + let (frac, size) = designcraft_render::pdf_crop_box(bytes, a.page as usize, a.pdf_crop)?; a.pdf_box = Some(frac); Some(size) } -pub(crate) fn read_source(p: &Value) -> Result<(Vec, String, Option)> { - read_linked_source(p).map(|(bytes, name, link, _)| (bytes, name, link)) +/// Whether `a` is a PDF placed with a box other than its crop box, which only its bytes locate. +fn crops_pdf(a: &Asset) -> bool { + a.pdf_crop != PdfCrop::Crop && a.mime == "application/pdf" } -/// [`read_source`], with the size and time to keep with a linked file's bytes -/// ([`crate::cmd::links::loaded_fingerprint`]): the file's from before it is read, not those of a -/// later version that replaces it while a network or syncing source is being loaded. -fn read_linked_source(p: &Value) -> Result<(Vec, String, Option, Option)> { +/// A file to place: its bytes and name, and its link record when it was read from a path. +pub(crate) struct Source { + pub bytes: Vec, + pub name: String, + file: Option, + /// `embed: true`: the bytes are kept in the document instead of linking the file. + embed: bool, +} + +impl Source { + /// Give `a` these bytes: linked to the file they were read from once the returned work is + /// done, else embedded ([`give_placed`]). `a`'s `mime` and `page` are set. + pub(crate) fn give(self, a: &mut Asset, document: Option<&std::path::Path>) -> Option { + give_placed(a, self.bytes, self.file, self.embed, document) + } +} + +/// The file of the document open in `s`, which relative links are recorded against. +pub(crate) fn document_of(s: &Session) -> Option { + s.doc().ok()?.path.as_deref().map(std::path::PathBuf::from) +} + +/// The file `p` names: `{path, embed?}` or `{base64, name?}`. Its size and time are taken before +/// it is read, so a later version that replaces it while a network or syncing source is being +/// loaded isn't vouched for ([`crate::cmd::links::loaded_fingerprint`]). +pub(crate) fn read_source(p: &Value) -> Result { + let embed = p.get("embed").and_then(Value::as_bool) == Some(true); if let Some(b) = str_param(p, "base64") { - return Ok((base64_decode(b), str_param(p, "name").unwrap_or("image").to_string(), None, None)); + return Ok(Source { bytes: base64_decode(b), name: str_param(p, "name").unwrap_or("image").to_string(), file: None, embed }); } let path = str_param(p, "path").ok_or_else(|| bad("place", "missing `path` or `base64`"))?; let before = crate::cmd::datamerge::fingerprint_from_path(path); @@ -225,8 +277,8 @@ fn read_linked_source(p: &Value) -> Result<(Vec, String, Option, Opt #[cfg(target_arch = "wasm32")] let b: Vec = vec![]; let name = std::path::Path::new(path).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| path.into()); - let loaded = crate::cmd::links::loaded_fingerprint(before, &b); - Ok((b, name, Some(path.to_string()), loaded)) + let file = Some(FileLink::of(std::path::Path::new(path), before)); + Ok(Source { bytes: b, name, file, embed }) } fn eps_size(bytes: &[u8], command: &str) -> Result> { @@ -254,35 +306,126 @@ pub(crate) fn validate_placement(size: (f64, f64), frame: Rect, xf: Affine, comm Ok(()) } +/// Decode and validate the complete batch before replacing the placement cursor. pub(super) fn place_load(s: &mut Session, p: &Value) -> Result { - let (bytes, name, link, link_fingerprint) = read_linked_source(p)?; - let (pw, ph) = designcraft_render::image_size(&bytes).ok_or_else(|| bad("place.load", "unsupported or corrupt image"))?; - let natural = eps_size(&bytes, "place.load")?.or_else(|| designcraft_render::natural_size(&bytes, 0)).unwrap_or((pw as f64, ph as f64)); - let mime = designcraft_render::image_mime(&bytes).to_string(); - let asset = Asset { name, mime, link, link_fingerprint, data: Arc::new(bytes), pixels: Some((pw, ph)), ..Default::default() }; - load_cursor(s, asset, natural) + let append = p.get("append").and_then(Value::as_bool) == Some(true); + let embed = p.get("embed").and_then(Value::as_bool) == Some(true); + let document = document_of(s); + if p.get("files").is_none() { + let source = read_source(p)?; + let bytes = &source.bytes; + let (pw, ph) = designcraft_render::image_size(bytes).ok_or_else(|| bad("place.load", "unsupported or corrupt image"))?; + let natural = eps_size(bytes, "place.load")?.or_else(|| designcraft_render::natural_size(bytes, 0)).unwrap_or((pw as f64, ph as f64)); + let mut asset = Asset { + name: source.name.clone(), + mime: designcraft_render::image_mime(bytes).to_string(), + pixels: Some((pw, ph)), + ..Default::default() + }; + let pending = source.give(&mut asset, document.as_deref()); + let r = load_cursor(s, asset, natural, append)?; + prepare_placed(s, pending); + return Ok(r); + } + let sources = p.get("files").and_then(Value::as_array).ok_or_else(|| bad("place.load", "files must be an array"))?; + if sources.is_empty() || sources.len() > MAX_LOADED_IMAGES { + return Err(bad("place.load", format!("select between 1 and {MAX_LOADED_IMAGES} images"))); + } + check_cursor_room(s, sources.len(), append, "place.load")?; + let mut images = Vec::with_capacity(sources.len()); + let mut pending = Vec::new(); + for source in sources { + let mut source = read_source(source)?; + source.embed |= embed; + let bytes = &source.bytes; + let (pw, ph) = + designcraft_render::image_size(bytes).ok_or_else(|| bad("place.load", format!("unsupported or corrupt image: {}", source.name)))?; + let size = eps_size(bytes, "place.load")?.or_else(|| designcraft_render::natural_size(bytes, 0)).unwrap_or((pw as f64, ph as f64)); + validate_placement(size, Rect::new(0.0, 0.0, size.0, size.1), Affine::IDENTITY, "place.load")?; + let mut asset = Asset { + name: source.name.clone(), + mime: designcraft_render::image_mime(bytes).to_string(), + pixels: Some((pw, ph)), + ..Default::default() + }; + pending.extend(source.give(&mut asset, document.as_deref())); + images.push((asset, size)); + } + let queue = s.edit(|d, _| { + let mut queue = std::collections::VecDeque::with_capacity(images.len()); + for (mut asset, size) in images { + asset.id = AssetId(d.alloc()); + queue.push_back(crate::LoadedGraphic { asset: d.add_asset(asset), size }); + } + Ok(queue) + })?; + prepare_placed(s, pending); + if append && s.loaded.is_some() { + s.loaded_queue.extend(queue); + } else { + s.loaded_queue = queue; + s.loaded = s.loaded_queue.pop_front(); + } + s.set_tool("placeGun"); + Ok(json!({"remaining": loaded_count(s), "loaded": true})) } -/// Adds `asset` to the document (with a fresh id) and loads it into the place cursor. -fn load_cursor(s: &mut Session, mut asset: Asset, size: (f64, f64)) -> Result { +/// Most images the place cursor holds, and so most one `place.load` takes. +const MAX_LOADED_IMAGES: usize = 1000; + +/// Whether `incoming` images fit in the place cursor: appended, they go after the ones it holds. +fn check_cursor_room(s: &Session, incoming: usize, append: bool, command: &str) -> Result<()> { + let held = if append { loaded_count(s) } else { 0 }; + if held.saturating_add(incoming) > MAX_LOADED_IMAGES { + return Err(bad(command, format!("the place cursor holds at most {MAX_LOADED_IMAGES} images, and it has {held}"))); + } + Ok(()) +} + +/// How many images the place cursor holds: the current one and those queued after it. +fn loaded_count(s: &Session) -> usize { + s.loaded_queue.len().saturating_add(usize::from(s.loaded.is_some())) +} + +/// Add a decoded asset with a fresh id, replacing the previous placement queue (or, with +/// `append` and an image already loaded, queued after it). +fn load_cursor(s: &mut Session, mut asset: Asset, size: (f64, f64), append: bool) -> Result { + check_cursor_room(s, 1, append, "place.load")?; let name = asset.name.clone(); let (pw, ph) = asset.pixels.unwrap_or_default(); let aid = s.edit(|d, _| { asset.id = AssetId(d.alloc()); Ok(d.add_asset(asset)) })?; - s.loaded = Some(crate::LoadedGraphic { asset: aid, size }); + let image = crate::LoadedGraphic { asset: aid, size }; + if append && s.loaded.is_some() { + s.loaded_queue.push_back(image); + } else { + s.loaded_queue.clear(); + s.loaded = Some(image); + } s.set_tool("placeGun"); Ok(json!({"asset": aid.0, "name": name, "width": pw, "height": ph, "loaded": true})) } -pub(super) fn place_drop(s: &mut Session, p: &Value) -> Result { - let crate::LoadedGraphic { asset: aid, size: (nw, nh) } = s.loaded.ok_or_else(|| bad("place.drop", "nothing loaded in the place cursor"))?; - // Undo can remove the loaded graphic's asset. - if !s.doc()?.doc.assets.contains_key(&aid) { - s.loaded = None; - return Err(bad("place.drop", "the loaded graphic is no longer in the document")); +/// Cancel every pending image if Undo removed an asset used by the cursor. +fn validate_place_cursor(s: &mut Session, command: &str) -> Result<()> { + // An empty cursor is its own error, and leaves the tool as it is. + if s.loaded.is_none() { + return Err(bad(command, "nothing loaded in the place cursor")); } + let valid = s.loaded.iter().chain(s.loaded_queue.iter()).all(|image| s.doc().is_ok_and(|d| d.doc.assets.contains_key(&image.asset))); + if !valid { + s.unload_place_cursor(); + return Err(bad(command, "the loaded graphic is no longer in the document")); + } + Ok(()) +} + +/// Place the current image and advance the cursor only after success. +pub(super) fn place_drop(s: &mut Session, p: &Value) -> Result { + validate_place_cursor(s, "place.drop")?; + let crate::LoadedGraphic { asset: aid, size: (nw, nh) } = s.loaded.ok_or_else(|| bad("place.drop", "nothing loaded in the place cursor"))?; let sr = crate::cmd::spread_param(p, "place.drop")?; let lid = s.doc()?.active_layer; let frame = crate::cmd::id_param(p, "frame"); @@ -340,11 +483,184 @@ pub(super) fn place_drop(s: &mut Session, p: &Value) -> Result { *sel = Selection::items(vec![id]); Ok(json!({"id": id.0})) })?; - s.loaded = None; - s.set_tool("selection"); + advance_place_cursor(s); Ok(r) } +/// Advance in file order, returning to selection when the queue is exhausted. +fn advance_place_cursor(s: &mut Session) { + s.loaded = s.loaded_queue.pop_front(); + if s.loaded.is_none() { + s.set_tool("selection"); + } +} + +/// Drop the current loaded image without placing it and move to the next; the last one ends placing. +pub(super) fn place_skip(s: &mut Session, _p: &Value) -> Result { + validate_place_cursor(s, "place.skip")?; + advance_place_cursor(s); + Ok(json!({"remaining": loaded_count(s)})) +} + +/// Rotate the loaded images: `dir` 1 makes the next one current (the current one goes to the back), +/// -1 the previous one (the last goes to the front). +pub(super) fn place_cycle(s: &mut Session, p: &Value) -> Result { + const ID: &str = "place.cycle"; + let dir = p.get("dir").and_then(Value::as_i64).filter(|d| matches!(d, 1 | -1)).ok_or_else(|| bad(ID, "dir must be 1 or -1"))?; + validate_place_cursor(s, ID)?; + if let Some(current) = s.loaded { + if dir == 1 { + s.loaded_queue.push_back(current); + s.loaded = s.loaded_queue.pop_front(); + } else if let Some(last) = s.loaded_queue.pop_back() { + s.loaded_queue.push_front(current); + s.loaded = Some(last); + } + } + Ok(json!({"remaining": loaded_count(s)})) +} + +/// Validate bounded grid dimensions and a finite nonnegative gutter. +fn grid_dimensions(p: &Value, command: &str, default_columns: usize, default_rows: usize) -> Result<(usize, usize, f64)> { + let dimension = |key, default| -> Result { + match p.get(key) { + None => Ok(default), + Some(v) => v + .as_u64() + .filter(|n| (1..=100).contains(n)) + .and_then(|n| usize::try_from(n).ok()) + .ok_or_else(|| bad(command, "rows and columns must be integers between 1 and 100")), + } + }; + let gutter = crate::cmd::f64_or(p, "gutter", 6.0); + if !gutter.is_finite() || gutter < 0.0 { + return Err(bad(command, "gutter must be finite and nonnegative")); + } + Ok((dimension("columns", default_columns)?, dimension("rows", default_rows)?, gutter)) +} + +/// Calculate row-major cells, rejecting gutters that leave no usable space. +fn grid_cells(rect: Rect, columns: usize, rows: usize, gutter: f64, command: &str) -> Result> { + let (columns, rows) = (columns.max(1), rows.max(1)); + let w = (rect.width() - gutter * columns.saturating_sub(1) as f64) / columns as f64; + let h = (rect.height() - gutter * rows.saturating_sub(1) as f64) / rows as f64; + if ![rect.x0, rect.y0, rect.x1, rect.y1, w, h].iter().all(|v| v.is_finite()) || w <= 0.0 || h <= 0.0 { + return Err(bad(command, "the grid area is too small for its rows, columns and gutter")); + } + Ok((0..rows) + .flat_map(|row| { + (0..columns).map(move |column| { + let x = rect.x0 + column as f64 * (w + gutter); + let y = rect.y0 + row as f64 * (h + gutter); + Rect::new(x, y, x + w, y + h) + }) + }) + .collect()) +} + +/// Insert a proportionally fitted image into one grid cell. +fn insert_grid_image( + d: &mut designcraft_doc::Document, + spread: designcraft_doc::SpreadRef, + layer: designcraft_doc::LayerId, + image: crate::LoadedGraphic, + rect: Rect, + command: &str, +) -> Result { + let crate::LoadedGraphic { asset, size: (nw, nh) } = image; + if !d.assets.contains_key(&asset) { + return Err(bad(command, "a loaded image is no longer in the document")); + } + let k = (rect.width() / nw).min(rect.height() / nh); + let xf = Affine::translate((rect.x0 + (rect.width() - nw * k) / 2.0, rect.y0 + (rect.height() - nh * k) / 2.0)) * Affine::scale(k); + validate_placement((nw, nh), rect, xf, command)?; + let id = ItemId(d.alloc()); + let mut item = Item::new(id, layer, Shape::Rectangle, shapes::rectangle(rect)); + item.object_style = d.styles.default_graphic_frame.clone(); + if let Some(effects) = d.styles.object_effects(&item.object_style) { + item.effects = effects.clone(); + } + item.content = Content::Graphic(Graphic { + layer_options: None, + asset, + size: (nw, nh), + xf, + auto_fit: designcraft_doc::Fitting::FitProportionally, + fit_align: 4, + crop: [0.0; 4], + clip: None, + wrap: Default::default(), + fill: Default::default(), + }); + d.insert_item(spread, item, None)?; + Ok(id) +} + +/// Place a row-major grid as one undoable edit. +pub(super) fn place_grid(s: &mut Session, p: &Value) -> Result { + const ID: &str = "place.grid"; + validate_place_cursor(s, ID)?; + let (columns, rows, gutter) = grid_dimensions(p, ID, 1, 1)?; + let rect = crate::cmd::rect_param(p, "rect").ok_or_else(|| bad(ID, "missing rect"))?; + let cells = grid_cells(rect, columns, rows, gutter, ID)?; + let images: Vec<_> = s.loaded.iter().chain(s.loaded_queue.iter()).copied().take(cells.len()).collect(); + if images.is_empty() { + return Err(bad(ID, "nothing loaded in the place cursor")); + } + let layer = s.doc()?.active_layer; + let spread = crate::cmd::spread_param(p, ID)?; + let ids = s.edit(|d, sel| { + let mut ids = Vec::with_capacity(images.len()); + for (image, rect) in images.iter().zip(cells) { + ids.push(insert_grid_image(d, spread, layer, *image, rect, ID)?); + } + *sel = Selection::items(ids.clone()); + Ok(ids) + })?; + for _ in &ids { + advance_place_cursor(s); + } + Ok(json!({"ids": ids.iter().map(|id| id.0).collect::>(), "remaining": loaded_count(s)})) +} + +/// Place all queued images on new pages as one undoable edit. +pub(super) fn place_contact_sheet(s: &mut Session, p: &Value) -> Result { + const ID: &str = "place.contactSheet"; + validate_place_cursor(s, ID)?; + let (columns, rows, gutter) = grid_dimensions(p, ID, 3, 4)?; + let margin = crate::cmd::f64_or(p, "margin", 36.0); + if !margin.is_finite() || margin < 0.0 { + return Err(bad(ID, "invalid margin")); + } + let images: Vec<_> = s.loaded.iter().chain(s.loaded_queue.iter()).copied().collect(); + if images.is_empty() { + return Err(bad(ID, "load images first using File > Place")); + } + let layer = s.doc()?.active_layer; + let per_page = columns.saturating_mul(rows).max(1); + let count = images.len().div_ceil(per_page); + let ids = s.edit(|d, sel| { + let after = d.page_count().saturating_sub(1); + d.insert_pages(Some(after), count, None)?; + let mut ids = Vec::with_capacity(images.len()); + for (page_offset, chunk) in images.chunks(per_page).enumerate() { + let index = after.saturating_add(1).saturating_add(page_offset); + let (si, pi) = d.page_loc(index).ok_or_else(|| bad(ID, "missing page"))?; + let b = d.spreads.get(si).and_then(|sp| sp.pages.get(pi)).ok_or_else(|| bad(ID, "missing page"))?.bounds(); + let cells = grid_cells(Rect::new(b.x0 + margin, b.y0 + margin, b.x1 - margin, b.y1 - margin), columns, rows, gutter, ID)?; + for (image, rect) in chunk.iter().zip(cells) { + ids.push(insert_grid_image(d, designcraft_doc::SpreadRef::Doc(si), layer, *image, rect, ID)?); + } + } + *sel = Selection::items(ids.clone()); + Ok(ids) + })?; + for _ in &ids { + advance_place_cursor(s); + } + Ok(json!({"pages": count, "images": ids.len()})) +} + /// File › Place of an IDML or DesignCraft document: the objects of one page (`layoutPage`, /// 1-based) grouped, top-left at x/y (default: the source position on the first page). fn place_layout_page(s: &mut Session, p: &Value, bytes: &[u8], format: Option) -> Result { @@ -414,6 +730,64 @@ pub(super) mod image_place_tests { Ok(file) } + /// With nothing in the place cursor, placing says so and leaves the tool as it is (the + /// cursor's graphic gone from the document is another error). + #[test] + fn an_empty_place_cursor_says_so_and_keeps_the_tool() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + s.set_tool("rectangleFrame"); + for (cmd, p) in + [("place.drop", json!({"x": 10, "y": 10})), ("place.grid", json!({"rect": [0, 0, 100, 100]})), ("place.contactSheet", json!({}))] + { + let e = s.execute(cmd, &p).unwrap_err().to_string(); + assert!(e.contains("nothing loaded"), "{cmd}: {e}"); + assert_eq!(s.tool_id(), "rectangleFrame", "{cmd}"); + } + } + + fn test_png(shade: u8) -> String { + let png = designcraft_render::Rendered { width: 4, height: 4, pixels: vec![shade; 4 * 4 * 4] }.to_png(); + crate::cmd::base64_encode(&png) + } + + fn loaded_names(s: &Session) -> Vec { + let Ok(st) = s.doc() else { return Vec::new() }; + let d = &st.doc; + s.loaded.iter().chain(s.loaded_queue.iter()).map(|g| d.assets[&g.asset].name.clone()).collect() + } + + #[test] + fn skip_drops_the_current_image_and_the_last_one_ends_placing() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let files: Vec<_> = (0..3).map(|i| json!({"base64": test_png(i as u8), "name": format!("{i}.png")})).collect(); + s.execute("place.load", &json!({"files": files})).unwrap(); + assert_eq!(s.execute("place.skip", &json!({})).unwrap()["remaining"], 2); + assert_eq!(loaded_names(&s), ["1.png", "2.png"]); + s.execute("place.skip", &json!({})).unwrap(); + assert_eq!(s.tool_id(), "placeGun"); + s.execute("place.skip", &json!({})).unwrap(); + assert!(s.loaded.is_none()); + assert_eq!(s.tool_id(), "selection"); + assert!(s.execute("place.skip", &json!({})).is_err()); + } + + #[test] + fn cycle_rotates_the_loaded_images_both_ways() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let files: Vec<_> = (0..3).map(|i| json!({"base64": test_png(i as u8), "name": format!("{i}.png")})).collect(); + s.execute("place.load", &json!({"files": files})).unwrap(); + s.execute("place.cycle", &json!({"dir": 1})).unwrap(); + assert_eq!(loaded_names(&s), ["1.png", "2.png", "0.png"]); + s.execute("place.cycle", &json!({"dir": -1})).unwrap(); + s.execute("place.cycle", &json!({"dir": -1})).unwrap(); + assert_eq!(loaded_names(&s), ["2.png", "0.png", "1.png"]); + assert!(s.execute("place.cycle", &json!({"dir": 2})).is_err()); + assert!(s.execute("place.cycle", &json!({})).is_err()); + } + #[test] fn consecutive_path_placements_create_distinct_graphics() { let images = [image_file_with_color(30).unwrap(), image_file_with_color(31).unwrap(), image_file_with_color(32).unwrap()]; @@ -479,9 +853,9 @@ pub(super) mod image_place_tests { }; // Written just now: another write in the same second would keep its time, so the time - // can't vouch for the bytes later and isn't kept. + // can't vouch for the bytes later: only the size is kept, with a time no file has. let asset = load(&mut session); - assert_eq!(asset.link_fingerprint, None); + assert_eq!(asset.link_fingerprint.map(|f| f.mtime), Some(crate::cmd::links::UNVERIFIED_MTIME)); assert_eq!(asset.link.as_deref(), image.path().to_str()); // A file that has been as it is for a while is remembered by its size and time. @@ -589,6 +963,96 @@ pub(super) mod image_place_tests { } } + /// A `width` x `height` PNG with a pHYs chunk of `ppm` pixels per meter on both axes, or none. + fn png_with_density(width: u32, height: u32, ppm: Option) -> std::io::Result { + fn crc32(data: &[u8]) -> u32 { + let mut crc = 0xFFFF_FFFFu32; + for &b in data { + crc ^= b as u32; + for _ in 0..8 { + crc = if crc & 1 == 1 { (crc >> 1) ^ 0xEDB8_8320 } else { crc >> 1 }; + } + } + !crc + } + let pixels = [30, 90, 180, 255].repeat((width * height) as usize); + let png = designcraft_render::Rendered { width, height, pixels }.to_png(); + assert_eq!(&png[12..16], b"IHDR"); + let mut bytes = png[..33].to_vec(); + if let Some(ppm) = ppm { + let mut phys = Vec::new(); + phys.extend_from_slice(&ppm.to_be_bytes()); + phys.extend_from_slice(&ppm.to_be_bytes()); + phys.push(1); + bytes.extend_from_slice(&(phys.len() as u32).to_be_bytes()); + bytes.extend_from_slice(b"pHYs"); + bytes.extend_from_slice(&phys); + let mut c = b"pHYs".to_vec(); + c.extend_from_slice(&phys); + bytes.extend_from_slice(&crc32(&c).to_be_bytes()); + } + bytes.extend_from_slice(&png[33..]); + let file = tempfile::Builder::new().suffix(".png").tempfile()?; + std::fs::write(file.path(), bytes)?; + Ok(file) + } + + #[test] + fn placed_photo_honors_its_embedded_resolution() { + // #1991: a placed graphic's embedded density sets its size (600 dpi: 40 px place + // 4.8 pt wide), instead of a pixel always becoming a point. + let file = png_with_density(40, 20, Some(23622)).unwrap(); + let mut session = Session::new(); + session.execute("file.new", &json!({})).unwrap(); + let placed = session.execute("file.place", &json!({"path": file.path(), "x": 10.0, "y": 20.0})).unwrap(); + let document = &session.doc().unwrap().doc; + let item = document.item(ItemId(placed["id"].as_u64().unwrap())).unwrap(); + let b = item.bounds(); + assert!((b.x0 - 10.0).abs() < 1e-9 && (b.y0 - 20.0).abs() < 1e-9, "{b:?}"); + assert!((b.width() - 4.8).abs() < 0.01 && (b.height() - 2.4).abs() < 0.01, "{b:?}"); + } + + /// File › Place, then a click: an 11 x 17 in image (330 x 510 px at 30 ppi) comes in at + /// 792 x 1224 pt, keeps that size through a save and reopen, and an image with no stored + /// resolution comes in at 72 ppi (330 x 510 pt). + #[test] + fn a_clicked_image_keeps_its_print_size_through_save_and_reopen() { + // 1181 pixels per meter is 29.9974 ppi. + let (w, h) = (330.0 * 72.0 / (1181.0 * 0.0254), 510.0 * 72.0 / (1181.0 * 0.0254)); + for (ppm, (ew, eh)) in [(Some(1181), (w, h)), (None, (330.0, 510.0))] { + let image = png_with_density(330, 510, ppm).unwrap(); + let mut session = Session::new(); + session.execute("file.new", &json!({})).unwrap(); + session.execute("file.place", &json!({"path": image.path(), "loadCursor": true})).unwrap(); + session.execute("place.drop", &json!({"x": 0, "y": 0})).unwrap(); + // The bounds and natural size of the document's one placed graphic. + let shown = |session: &Session| { + let doc = &session.doc().unwrap().doc; + let graphics: Vec<_> = doc + .all_items() + .into_iter() + .filter_map(|id| doc.item(id)) + .filter_map(|item| match &item.content { + Content::Graphic(g) => Some((item.bounds(), g.size)), + _ => None, + }) + .collect(); + assert_eq!(graphics.len(), 1, "{graphics:?}"); + graphics[0] + }; + let (b, size) = shown(&session); + assert!((b.width() - ew).abs() < 1e-6 && (b.height() - eh).abs() < 1e-6, "{ppm:?}: {b:?}"); + assert!((size.0 - ew).abs() < 1e-6 && (size.1 - eh).abs() < 1e-6, "{ppm:?}: {size:?}"); + + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("placed.designcraft"); + session.execute("file.save", &json!({"path": path.to_string_lossy()})).unwrap(); + let mut reopened = Session::new(); + reopened.execute("file.open", &json!({"path": path.to_string_lossy()})).unwrap(); + assert_eq!(shown(&reopened), (b, size), "{ppm:?}"); + } + } + #[test] fn explicit_frame_wins_over_placement_and_selection() { let image = image_file().unwrap(); @@ -923,3 +1387,80 @@ mod nested_frame_tests { assert_eq!(d.spreads[0].items.len(), 1, "no new object"); } } + +#[cfg(test)] +mod cursor_cap_tests { + use serde_json::{Value, json}; + + use super::MAX_LOADED_IMAGES; + use crate::Session; + + fn png() -> String { + let png = designcraft_render::Rendered { width: 4, height: 4, pixels: [200, 90, 30, 255].repeat(16) }.to_png(); + super::super::base64_encode(&png) + } + + /// A session whose place cursor holds `held` images, loaded without decoding each of them. + fn holding(held: usize) -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + s.execute("place.load", &json!({"base64": png(), "name": "first.png"})).unwrap(); + let first = s.loaded.unwrap(); + s.loaded_queue = std::iter::repeat_n(first, held - 1).collect(); + s + } + + fn count(s: &Session) -> usize { + super::loaded_count(s) + } + + /// Every way of adding to the cursor stops at the cap, and a refused add changes nothing. + #[test] + fn appending_stops_at_the_cap_on_the_whole_cursor() { + let image = png(); + let single = json!({"base64": image, "name": "a.png", "append": true}); + let placed = json!({"base64": image, "name": "a.png", "append": true, "loadCursor": true}); + let two = json!({"files": [{"base64": image, "name": "a.png"}, {"base64": image, "name": "b.png"}], "append": true}); + for (command, params) in [("place.load", &single), ("file.place", &placed), ("place.load", &two)] { + let mut s = holding(MAX_LOADED_IMAGES); + let assets = s.doc().unwrap().doc.assets.len(); + assert!(s.execute(command, params).is_err(), "{command} {params}"); + assert_eq!(count(&s), MAX_LOADED_IMAGES, "{command} {params}"); + assert_eq!(s.doc().unwrap().doc.assets.len(), assets, "{command} {params}"); + } + // One over, as a batch. + let mut s = holding(MAX_LOADED_IMAGES - 1); + assert!(s.execute("place.load", &two).is_err()); + assert_eq!(count(&s), MAX_LOADED_IMAGES - 1); + } + + /// The last places up to the cap load, and an unreadable batch reports the cap before decoding. + #[test] + fn appending_up_to_the_cap_still_loads() { + let image = png(); + for params in + [json!({"base64": image, "name": "a.png", "append": true}), json!({"files": [{"base64": image, "name": "a.png"}], "append": true})] + { + let mut s = holding(MAX_LOADED_IMAGES - 1); + s.execute("place.load", ¶ms).unwrap(); + assert_eq!(count(&s), MAX_LOADED_IMAGES, "{params}"); + } + let mut s = holding(MAX_LOADED_IMAGES); + let error = + s.execute("place.load", &json!({"files": [{"base64": "not an image", "name": "a.png"}], "append": true})).unwrap_err().to_string(); + assert!(error.contains(&MAX_LOADED_IMAGES.to_string()), "{error}"); + } + + /// Without `append` the new images replace the cursor, so what it holds doesn't count. + #[test] + fn replacing_a_full_cursor_is_not_capped() { + let image = png(); + let mut s = holding(MAX_LOADED_IMAGES); + let result: Value = s.execute("place.load", &json!({"base64": image, "name": "a.png"})).unwrap(); + assert_eq!(result["loaded"], true); + assert_eq!(count(&s), 1); + let mut s = holding(MAX_LOADED_IMAGES); + s.execute("place.load", &json!({"files": [{"base64": image, "name": "a.png"}]})).unwrap(); + assert_eq!(count(&s), 1); + } +} diff --git a/crates/engine/src/cmd/file/registry.rs b/crates/engine/src/cmd/file/registry.rs index c1f522956..f59144fe6 100644 --- a/crates/engine/src/cmd/file/registry.rs +++ b/crates/engine/src/cmd/file/registry.rs @@ -1,10 +1,8 @@ -#[cfg(not(target_arch = "wasm32"))] -use super::EngineError; -use super::bytes::{base64_encode, to_bytes, to_bytes_with_preview, with_document_extension}; +use super::bytes::{base64_encode, to_bytes}; use super::new::{file_new, file_sample, save_preset}; use super::open::{file_open, file_open_bytes, file_open_recent, has_recent, recent_entry}; -use super::place::{file_place, place_drop, place_load, read_source}; -use super::save::{FolderAccess, can_revert, file_revert, file_save, recovery_dir}; +use super::place::{file_place, place_contact_sheet, place_cycle, place_drop, place_grid, place_load, place_skip, read_source}; +use super::save::{FolderAccess, can_revert, file_revert, file_save, file_save_a_copy, recovery_dir}; use super::snippets::{snippet_export, snippet_place}; use super::{CommandSpec, PRESETS, Value, always, bad, cmd, has_doc, json, ok, str_param}; @@ -52,36 +50,44 @@ pub fn specs() -> Vec { }), cmd!(noundo "file.save", "Save", ["File"], Some("Cmd+S"), "{path?} — a `path` without the .designcraft extension gets it → {path: the file written, bytes}", has_doc, file_save), cmd!(noundo "file.saveAs", "Save As…", ["File"], Some("Cmd+Shift+S"), "{path} — a path without the .designcraft extension gets it → {path: the file written, bytes}", has_doc, file_save), - cmd!(noundo "file.saveACopy", "Save a Copy…", ["File"], None, "{path} — writes the document without changing which file it is or its unsaved state; a path without the .designcraft extension gets it → {path: the file written, bytes}", has_doc, |s, p| { - let path = str_param(p, "path").ok_or_else(|| bad("file.saveACopy", "missing `path`"))?; - let path = with_document_extension(path); - let mut copy = (*s.doc()?.doc).clone(); - crate::cmd::datamerge::refresh_relative_paths(&mut copy, std::path::Path::new(&path)); - let bytes = to_bytes_with_preview(©, &s.cache)?; - #[cfg(not(target_arch = "wasm32"))] - crate::io::write_file(&path, &bytes).map_err(EngineError::Other)?; - Ok(json!({"path": path, "bytes": bytes.len()})) - }), + cmd!(noundo "file.saveACopy", "Save a Copy…", ["File"], None, "{path, embedLinks?: copy every linked file in (fails when one is missing or changed)} — writes the document without changing which file it is or its unsaved state; a path without the .designcraft extension gets it → {path: the file written, bytes, warnings}", has_doc, file_save_a_copy), cmd!(noundo "file.revert", "Revert", ["File"], None, "{} — back to the last saved version (not undoable)", can_revert, file_revert), cmd!(query "file.recovery.list", "Recovery Data", [], None, "{dir?} → [{uid, path, title, saved}] unsaved documents left by a crash (default: the session's recovery folder)", always, |s, p| { let dir = recovery_dir(s, p, FolderAccess::Read)?; Ok(Value::Array(crate::recovery::list(&dir).into_iter().map(|(uid, mut m)| { m["uid"] = json!(uid); m }).collect())) }), - cmd!(noundo "file.recovery.save", "Save Recovery Data", [], None, "{dir?} — write every unsaved document to the recovery folder (the app does this on a timer)", always, |s, p| { + cmd!(noundo "file.recovery.save", "Save Recovery Data", [], None, + "{dir?, background?} — write every unsaved document to the recovery folder (the app does this on a timer; `background` queues the writes and returns at once) → {saved} or {queued}", + always, |s, p| { + let background = match p.get("background") { + None | Some(Value::Null) => false, + Some(v) => v.as_bool().ok_or_else(|| bad("file.recovery.save", "`background` must be true or false"))?, + }; let dir = recovery_dir(s, p, FolderAccess::Write)?; + if background { + return Ok(json!({"queued": crate::recovery::start_tracked(s, &dir)?})); + } Ok(json!({"saved": crate::recovery::save_tracked(s, &dir)?})) }), + cmd!(query "file.recovery.progress", "Recovery Progress", [], None, + "{} → {written, busy, errors} recovery data queued in the background has been written", always, |s, _| { + let done = crate::recovery::finished(s); + Ok(json!({"written": done.written, "busy": done.busy, "errors": done.errors})) + }), cmd!(noundo "file.recovery.open", "Recover Documents", [], None, "{dir?} — reopen documents left in the recovery folder (unsaved)", always, |s, p| { // Reopening removes the entries it read. let dir = recovery_dir(s, p, FolderAccess::ReadWrite)?; Ok(json!({"opened": crate::recovery::open(s, &dir)?})) }), - cmd!(query "file.serialize", "Serialize", [], None, "{} → {base64, bytes} the .designcraft file", has_doc, |s, _| { + cmd!(query "file.serialize", "Serialize", [], None, "{} → {base64, bytes, warnings} the .designcraft file (on the web, linked files stay links, with a warning)", has_doc, |s, _| { let st = s.doc()?; // Preview fill is session state. Serialize the unfilled template. let doc = st.preview_stash.as_deref().unwrap_or(st.doc.as_ref()); + let proxied = crate::cmd::native_links::with_proxies(doc, || false); + let doc = proxied.as_ref().unwrap_or(doc); let bytes = to_bytes(doc)?; - Ok(json!({"base64": base64_encode(&bytes), "bytes": bytes.len()})) + let warnings = crate::cmd::native_links::web_save_warnings(doc); + Ok(json!({"base64": base64_encode(&bytes), "bytes": bytes.len(), "warnings": warnings})) }), cmd!(noundo "file.close", "Close", ["File"], Some("Cmd+W"), "{index?}", has_doc, |s, p| { let i = p.get("index").and_then(Value::as_u64).map(|v| v as usize).or(s.active_index()).unwrap_or(0); @@ -97,8 +103,8 @@ pub fn specs() -> Vec { cmd!(query "place.styles", "Import Options: Styles", [], None, "{path | base64, name} → {paragraph: [name], character: [name], conflicts: [name]} — the styles a Word/RTF file brings (for styleMap / styleConflicts)", has_doc, |s, p| { - let (bytes, name, _) = read_source(p)?; - let imp = designcraft_textimport::import(&name, &bytes).map_err(|e| bad("place.styles", e.to_string()))?; + let source = read_source(p)?; + let imp = designcraft_textimport::import(&source.name, &source.bytes).map_err(|e| bad("place.styles", e.to_string()))?; let st = &s.doc()?.doc.styles; let conflicts: Vec<&str> = imp .para_styles @@ -123,17 +129,43 @@ pub fn specs() -> Vec { "Load Place Cursor", [], None, - "{path | base64, name?} — load a graphic into the place cursor (then click/drag with the placeGun tool)", + "{path | base64, name?, files?: [{path | base64, name?, embed?}], append? (keep the images already loaded and queue these after them), embed? (keep every image's bytes in the document; default: images read from a path link to their files)} — load up to 1000 images into the place cursor, in order (then click/drag with the placeGun tool)", has_doc, place_load ), cmd!("place.drop", "Place Loaded Graphic", [], None, "{spread?, x, y, rect?: [x0,y0,x1,y1], frame?: id}", has_doc, place_drop), + cmd!( + "place.grid", + "Place Image Grid", + [], + None, + "{spread?, rect: [x0,y0,x1,y1], columns?: 1, rows?: 1, gutter?: 6} — place queued images in row order", + has_doc, + place_grid + ), + cmd!( + "place.contactSheet", + "Place Contact Sheet", + ["File"], + None, + "{columns?: 3, rows?: 4, gutter?: 6, margin?: 36} — place all loaded images on new pages", + has_doc, + place_contact_sheet + ), + cmd!(noundo "place.skip", "Skip Loaded Image", [], None, "{} — drops the current loaded image without placing it and loads the next; the last one ends placing", has_doc, place_skip), + cmd!(noundo "place.cycle", "Cycle Loaded Images", [], None, "{dir: 1|-1} — makes the next (1) or previous (-1) loaded image the current one", has_doc, place_cycle), + cmd!(noundo "place.cancel", "Cancel Image Placement", [], None, "{} — clears every loaded image", has_doc, |s, _| { + s.loaded = None; + s.loaded_queue.clear(); + s.set_tool("selection"); + ok() + }), cmd!( "file.place", "Place…", ["File"], Some("Cmd+D"), - "{path?|base64?, name?, frame?: id (place into), spread?, x?, y?, width?: finite number > 0 (null: absent), height? (video/audio), pdfPage?: n (1-based, Image Import Options), pdfCrop?: crop|art|trim|bleed|media|contentVisible|contentAll (the box the graphic shows; `width` is the whole page's), loadCursor? (with no frame to fill and no x/y, an image loads into the place cursor, as File › Place), layoutPage?: n (IDML / .designcraft: that page's objects as a group), page?, rect?: [x0,y0,x1,y1] (text: a new frame there), autoflow? (threads one frame per page column from the first frame on, adding pages until the text fits), removeStyles?, styleMap?: {imported name: document style}, styleConflicts?: useExisting|redefine|autoRename, link? (keep the file linked in the Links panel; default: the linkTextFiles preference)} — places an image into `frame` when given; otherwise any explicit x/y/spread/width creates a new frame; otherwise uses the selected empty or graphic frame, or creates a new frame; text files (.txt, .docx, .rtf, .md) and Excel workbooks (.xlsx, as a table) go into the insertion point, the selected frame or a new frame on `page`/`rect`", + "{path?|base64?, name?, embed? (keep the file's bytes in the document; default: a graphic placed from a path links to its file, base64 bytes and the web always embed), frame?: id (place into), spread?, x?, y?, width?: finite number > 0 (null: absent), height? (video/audio), pdfPage?: n (1-based, Image Import Options), pdfCrop?: crop|art|trim|bleed|media|contentVisible|contentAll (the box the graphic shows; `width` is the whole page's), loadCursor? (with no frame to fill and no x/y, an image loads into the place cursor, as File › Place), append? (with loadCursor: queue the image after those already loaded instead of replacing them), layoutPage?: n (IDML / .designcraft: that page's objects as a group), page?, rect?: [x0,y0,x1,y1] (text: a new frame there), autoflow? (threads one frame per page column from the first frame on, adding pages until the text fits), removeStyles?, styleMap?: {imported name: document style}, styleConflicts?: useExisting|redefine|autoRename, link? (keep the file linked in the Links panel; default: the linkTextFiles preference)} — places an image into `frame` when given; otherwise any explicit x/y/spread/width creates a new frame; otherwise uses the selected empty or graphic frame, or creates a new frame; text files (.txt, .docx, .rtf, .md) and Excel workbooks (.xlsx, as a table) go into the insertion point, the selected frame or a new frame on `page`/`rect`", has_doc, file_place ), diff --git a/crates/engine/src/cmd/file/save.rs b/crates/engine/src/cmd/file/save.rs index d12bf03fa..7d5b1ba19 100644 --- a/crates/engine/src/cmd/file/save.rs +++ b/crates/engine/src/cmd/file/save.rs @@ -19,16 +19,28 @@ pub(super) fn file_save(s: &mut Session, p: &Value) -> Result { // Before anything about the document changes: a refused save leaves it as it was. crate::file_access::check_write(&path).map_err(EngineError::Other)?; // Prepare paths for the destination without changing the live document until persistence succeeds. - let mut saved = (*st.doc).clone(); - crate::cmd::datamerge::refresh_relative_paths(&mut saved, std::path::Path::new(&path)); - let paths_changed = saved.data_merge != st.doc.data_merge; - let saved = if paths_changed { Arc::new(saved) } else { st.doc.clone() }; + let destination = std::path::Path::new(&path); + let from = st.path.as_deref().map(std::path::Path::new); + let linked = crate::cmd::native_links::for_destination(&st.doc, from, destination); + let links_changed = linked.is_some(); + let mut saved = linked.unwrap_or_else(|| (*st.doc).clone()); + crate::cmd::datamerge::refresh_relative_paths(&mut saved, destination); + // Proxies the background job hasn't made yet are made here, on this thread: the save is + // synchronous. The document keeps them. + let proxied = crate::cmd::native_links::with_proxies(&saved, || false); + let proxies_made = proxied.is_some(); + let saved = proxied.unwrap_or(saved); + let changed = links_changed || proxies_made || saved.data_merge != st.doc.data_merge; + let saved = if changed { Arc::new(saved) } else { st.doc.clone() }; + let warnings = crate::cmd::native_links::web_save_warnings(&saved); let bytes = to_bytes_with_preview(&saved, &s.cache)?; #[cfg(not(target_arch = "wasm32"))] crate::io::write_file(&path, &bytes).map_err(EngineError::Other)?; let st = s.doc_mut()?; - if paths_changed { - st.doc = saved; + // Images saved as links let go of their bytes; linked files resolve against the new file. + let doc = crate::cmd::native_links::after_save(&saved, destination).map_or(saved, Arc::new); + if !Arc::ptr_eq(&doc, &st.doc) { + st.doc = doc; st.bump_revision(); } st.path = Some(path.clone()); @@ -41,7 +53,35 @@ pub(super) fn file_save(s: &mut Session, p: &Value) -> Result { crate::recovery::discard_document(s, index, recovery_dir.as_deref()); s.prefs.note_recent_file(&path); } - Ok(json!({"path": path, "bytes": bytes.len()})) + Ok(json!({"path": path, "bytes": bytes.len(), "warnings": warnings})) +} + +/// `file.saveACopy`: the document written to `path` without changing which file it is or its +/// unsaved state. With `embedLinks`, every linked file is copied in: a document that opens +/// anywhere. +pub(super) fn file_save_a_copy(s: &mut Session, p: &Value) -> Result { + let path = str_param(p, "path").ok_or_else(|| bad("file.saveACopy", "missing `path`"))?; + let path = with_document_extension(path); + let embed = match p.get("embedLinks") { + None | Some(Value::Null) => false, + Some(v) => v.as_bool().ok_or_else(|| bad("file.saveACopy", "`embedLinks` must be true or false"))?, + }; + let st = s.doc()?; + let destination = std::path::Path::new(&path); + let from = st.path.as_deref().map(std::path::Path::new); + let mut copy = crate::cmd::native_links::for_destination(&st.doc, from, destination).unwrap_or_else(|| (*st.doc).clone()); + crate::cmd::datamerge::refresh_relative_paths(&mut copy, destination); + if embed { + crate::cmd::native_links::embed_linked(&mut copy, "file.saveACopy")?; + } + if let Some(proxied) = crate::cmd::native_links::with_proxies(©, || false) { + copy = proxied; + } + let warnings = crate::cmd::native_links::web_save_warnings(©); + let bytes = to_bytes_with_preview(©, &s.cache)?; + #[cfg(not(target_arch = "wasm32"))] + crate::io::write_file(&path, &bytes).map_err(EngineError::Other)?; + Ok(json!({"path": path, "bytes": bytes.len(), "warnings": warnings})) } /// Which access a recovery command needs to the folder it is given. @@ -95,14 +135,17 @@ pub(super) fn file_revert(s: &mut Session, _: &Value) -> Result { } else { from_bytes(&bytes)? }; - // As opened again: the fonts beside it now (unchanged files are shared, not read again). + // As opened again: the fonts beside it now (unchanged files are shared, not read again), + // its linked files found again. let (fonts, _, _) = load_document_fonts(&mut d, &path); + let links = crate::cmd::native_links::resolve(&mut d, Some(std::path::Path::new(&path)), true); let uid = s.doc()?.uid; let recovery_dir = s.recovery_dir.clone(); let index = s.active_index().ok_or(EngineError::NoDocument)?; let mut fresh = DocState::new(d, Some(path.clone())); fresh.fonts = fonts; fresh.uid = uid; + crate::cmd::native_links::start(&mut fresh, links); // A new state has a revision no state had before, so caches don't show the old document. crate::recovery::discard_document(s, index, recovery_dir.as_deref()); *s.doc_mut()? = fresh; diff --git a/crates/engine/src/cmd/file/snippets.rs b/crates/engine/src/cmd/file/snippets.rs index 5ff1f3795..21d986dce 100644 --- a/crates/engine/src/cmd/file/snippets.rs +++ b/crates/engine/src/cmd/file/snippets.rs @@ -23,8 +23,7 @@ pub(super) fn snippet_export(s: &mut Session, p: &Value) -> Result { } pub(crate) fn snippet_place(s: &mut Session, p: &Value) -> Result { - let (bytes, _, _) = read_source(p)?; - let src = from_bytes(&bytes)?; + let src = from_bytes(&read_source(p)?.bytes)?; let ids: Vec = src.spreads.first().map(|sp| sp.items.iter().map(|i| i.id).collect()).unwrap_or_default(); if ids.is_empty() { return Err(bad("snippet.place", "the snippet is empty")); diff --git a/crates/engine/src/cmd/find.rs b/crates/engine/src/cmd/find.rs index b9ab42550..63a1debb9 100644 --- a/crates/engine/src/cmd/find.rs +++ b/crates/engine/src/cmd/find.rs @@ -316,19 +316,27 @@ impl Search { ) -> Result, String)>> { let limit = if first_only { 1 } else { usize::MAX }; match (&self.re, self.spans(d, sid, cell, r)) { - (Some(re), None) if grep => re.replacements(text, rep, first_only).map_err(|e| bad("find.change", e)), - (Some(re), Some(spans)) if grep => Ok(re - .replacements(text, rep, false) - .map_err(|e| bad("find.change", e))? - .into_iter() - .filter(|(m, _)| within(&spans, m)) - .take(limit) - .collect()), - _ => Ok(self.find_all(d, sid, cell, r, text, limit)?.into_iter().map(|m| (m, rep.to_string())).collect()), + (Some(re), spans) if grep => re + .replacements(text, rep, first_only, MAX_CHANGE_BYTES, |m| spans.as_ref().is_none_or(|s| within(s, m))) + .map_err(|e| bad("find.change", e)), + _ => { + let found = self.find_all(d, sid, cell, r, text, limit)?; + // Every match gets its own copy of the change: bounded before any is made. + if found.len().saturating_mul(rep.len()) > MAX_CHANGE_BYTES { + return Err(bad( + "find.change", + format!("changing {} matches to {} bytes each would put more than {MAX_CHANGE_BYTES} bytes in", found.len(), rep.len()), + )); + } + Ok(found.into_iter().map(|m| (m, rep.to_string())).collect()) + } } } } +/// The most text one Change All may put into a story: the matches times the change's length. +const MAX_CHANGE_BYTES: usize = 64 << 20; + #[derive(Clone, Debug, PartialEq, Eq)] enum Domain { Document, diff --git a/crates/engine/src/cmd/find/tests.rs b/crates/engine/src/cmd/find/tests.rs index 348acd294..edea872ad 100644 --- a/crates/engine/src/cmd/find/tests.rs +++ b/crates/engine/src/cmd/find/tests.rs @@ -959,3 +959,21 @@ fn change_takes_any_selection_find_next_made() { assert_eq!(s.doc().unwrap().doc.story(sid).unwrap().text, if grep { "a" } else { "ab" }); } } + +/// Change All with a long change and many matches is refused before any copy of the change is +/// made, not after the memory for all of them has gone. +#[test] +fn change_all_is_bounded_by_what_it_would_put_in() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let text = "x ".repeat(2048); + s.execute("frame.create", &json!({"rect": [36, 36, 300, 300], "content": "text", "text": text})).unwrap(); + let huge = "y".repeat(40_000); + let e = s.execute("find.change", &json!({"find": "x", "change": huge})).unwrap_err().to_string(); + assert!(e.contains("would put more than"), "{e}"); + // GREP replacements are held to the same total while they are made. + let e = s.execute("find.change", &json!({"find": "x", "change": huge, "grep": true})).unwrap_err().to_string(); + assert!(e.contains("would put more than"), "{e}"); + let r = s.execute("find.change", &json!({"find": "x", "change": "yy"})).unwrap(); + assert_eq!(r["count"], 2048); +} diff --git a/crates/engine/src/cmd/interchange.rs b/crates/engine/src/cmd/interchange.rs index eefb46541..940404aa9 100644 --- a/crates/engine/src/cmd/interchange.rs +++ b/crates/engine/src/cmd/interchange.rs @@ -17,7 +17,7 @@ use crate::{DocState, EngineError, Result, Session}; pub fn specs() -> Vec { vec![ cmd!(query "file.exportIdml", "Export IDML…", [], None, - "{path?, embedImages?: true} — writes an IDML package to `path`, or returns {base64} without a path", + "{path?, embedImages?: true} — writes an IDML package to `path`, or returns {base64} without a path; `warnings` names each image written as a link because the embedded-image limit was reached", has_doc, export_idml), cmd!(noundo "file.openIdml", "Open IDML", [], None, "{path | base64, name?} — opens an IDML package, or an InDesign document or template (.indd, .indt: converted to IDML first; its conversion warnings join `warnings`), as a new document (linked images are read next to the file or from its Links/ folder; the fonts in a `Document Fonts` folder beside it load first) → {index, documentFonts, warnings: conversion warnings, package parts missing, font files skipped, GREP styles whose pattern can't compile}", @@ -29,15 +29,19 @@ fn export_idml(s: &mut Session, p: &Value) -> Result { let st = s.doc()?; let opts = designcraft_idml::ExportOptions { embed_images: p.get("embedImages").and_then(Value::as_bool).unwrap_or(true) }; let layer_doc = with_pdf_layer_variants(&st.doc, opts.embed_images)?; - let bytes = designcraft_idml::export_idml_with(layer_doc.as_ref().unwrap_or(&st.doc), &opts); - match str_param(p, "path") { + let (bytes, warnings) = designcraft_idml::export_idml_report(layer_doc.as_ref().unwrap_or(&st.doc), &opts); + let mut out = match str_param(p, "path") { Some(path) => { #[cfg(not(target_arch = "wasm32"))] crate::io::write_file(path, &bytes).map_err(EngineError::Other)?; - Ok(json!({"path": path, "bytes": bytes.len()})) + json!({"path": path, "bytes": bytes.len()}) } - None => Ok(json!({"base64": base64_encode(&bytes), "bytes": bytes.len()})), + None => json!({"base64": base64_encode(&bytes), "bytes": bytes.len()}), + }; + if !warnings.is_empty() { + out["warnings"] = json!(warnings); } + Ok(out) } /// Whether a placement holds an Object Layer Options choice an export can still apply: a graphic @@ -45,7 +49,8 @@ fn export_idml(s: &mut Session, p: &Value) -> Result { /// replaced with another format) is not one, so the package report does not name it. pub(crate) fn has_applicable_pdf_layer_overrides(doc: &Document) -> bool { doc.placed_items().into_iter().any(|it| { - it.has_pdf_layer_override() && it.graphic().and_then(|g| doc.assets.get(&g.asset)).is_some_and(|a| designcraft_render::is_pdf(&a.data)) + it.has_pdf_layer_override() + && it.graphic().and_then(|g| doc.assets.get(&g.asset)).is_some_and(|a| a.data.load().is_ok_and(|b| designcraft_render::is_pdf(&b))) }) } @@ -62,7 +67,8 @@ fn with_pdf_layer_variants(doc: &Document, embed: bool) -> Result Result) { + let Some(bytes) = asset.data.embedded_bytes().cloned() else { return }; + let Some(path) = asset.link.clone() else { return }; + let preview = asset.proxy.take().and_then(|p| preview_proxy(&p)); + let (whole, fallback) = match preview { + Some(p) if shows_whole(asset, &bytes, &p) => (Some(p), None), + p => (None, p), + }; + // The fingerprint kept by the read (none for a file just written: its hash tells its bytes). + let file = super::links::FileLink::of(std::path::Path::new(&path), asset.link_fingerprint); + super::links::link_to_file(asset, bytes, file, package, whole); + if asset.storage == designcraft_doc::Storage::Linked && asset.proxy.is_none() { + asset.proxy = fallback; + } +} + +/// A document's stored preview of a linked graphic as a proxy: checked to decode, and made again +/// within the proxy limits ([`designcraft_render::proxy`]) when it is bigger or in another +/// format (a larger one wouldn't be kept by the saved document). `None` when it doesn't decode. +#[cfg(not(target_arch = "wasm32"))] +fn preview_proxy(preview: &designcraft_doc::Proxy) -> Option { + use designcraft_render::proxy::{MAX_BYTES, MAX_SIDE_PX, make_proxy}; + let bytes = preview.data.embedded_bytes()?; + let mime = designcraft_render::image_mime(bytes); + let fits = bytes.len() <= MAX_BYTES + && matches!(mime, "image/jpeg" | "image/png") + && designcraft_render::image_size(bytes).is_some_and(|(w, h)| w.max(h) <= MAX_SIDE_PX); + if fits && let Some(pm) = designcraft_render::decode_pixmap(bytes) { + let pixels = (u32::from(pm.width()), u32::from(pm.height())); + return Some(designcraft_doc::Proxy { mime: mime.into(), pixels, data: preview.data.clone() }); + } + let p = make_proxy(bytes, 0)?; + Some(designcraft_doc::Proxy { mime: p.mime.into(), pixels: p.pixels, data: designcraft_doc::AssetData::embedded(p.data) }) +} + +/// Whether `preview` shows the whole of `asset`'s image (`bytes`, its file's), as a proxy must: +/// a raster whose preview has the image's proportions. A PDF's preview shows its crop, which may +/// not be the page the proxy stands for, and other files' proportions aren't known here. +#[cfg(not(target_arch = "wasm32"))] +fn shows_whole(asset: &designcraft_doc::Asset, bytes: &[u8], preview: &designcraft_doc::Proxy) -> bool { + if designcraft_render::is_pdf(bytes) || asset.mime == "application/pdf" { + return false; + } + let Some((w, h)) = designcraft_render::image_size(bytes) else { return false }; + let (pw, ph) = preview.pixels; + if w == 0 || h == 0 || pw == 0 || ph == 0 { + return false; + } + // Proportions equal but for the preview's rounding to whole pixels. + let (ratio, preview_ratio) = (f64::from(w) / f64::from(h), f64::from(pw) / f64::from(ph)); + (preview_ratio / ratio - 1.0).abs() <= 1.0 / f64::from(pw) + 1.0 / f64::from(ph) + 0.01 +} + /// Placed PDFs read from IDML name their crop (`PDFCrop`): find where each box sits on its page, /// which the IDML reader can't (it doesn't parse PDFs). The box spans the graphic's /// `GraphicBounds`; a graphic without bounds takes the box's size. Bounding Box crops interpret @@ -347,6 +420,10 @@ fn is_graphic(bytes: &[u8]) -> bool { pub(crate) fn resolve_packaged_links(document: &mut Document, package: Option<&std::path::Path>) { let Some(package) = package else { return }; for asset in document.assets.values_mut() { + // Linked storage finds its files itself (`native_links::resolve`). + if asset.storage == designcraft_doc::Storage::Linked { + continue; + } let Some(link) = asset.link.as_deref() else { continue }; if link.len() > MAX_LINK_PATH_BYTES { continue; @@ -537,7 +614,7 @@ mod tests { let doc = import(&idml, Some(&dir.join("x.idml"))).unwrap(); let asset = doc.assets.values().next().unwrap(); - assert_eq!(*asset.data, png, "the packaged graphic must render even when its author-machine path no longer exists"); + assert_eq!(*asset.data.resident().unwrap(), png, "the packaged graphic must render even when its author-machine path no longer exists"); let resolved = std::path::absolute(&path).unwrap(); assert_eq!(asset.link.as_deref(), resolved.to_str(), "remember the resolved link so update and preflight use the packaged file"); let expected = super::super::datamerge::fingerprint_from(&std::fs::metadata(&path).unwrap()); @@ -557,7 +634,7 @@ mod tests { let doc = import(&idml, Some(&dir.join("x.idml"))).unwrap(); let asset = doc.assets.values().next().unwrap(); - assert_eq!(*asset.data, png); + assert_eq!(*asset.data.resident().unwrap(), png); assert_eq!(asset.link.as_deref(), std::path::absolute(&path).unwrap().to_str()); assert_eq!(super::super::links::status_cached(asset, None, &mut Default::default()), "ok"); std::fs::remove_dir_all(dir).unwrap(); @@ -573,12 +650,95 @@ mod tests { let doc = import(&idml, Some(&dir.join("x.idml"))).unwrap(); let asset = doc.assets.values().next().unwrap(); - assert_eq!(*asset.data, png); + assert_eq!(*asset.data.resident().unwrap(), png); assert_eq!(asset.link.as_deref(), std::path::absolute(&path).unwrap().to_str()); assert_eq!(super::super::links::status_cached(asset, None, &mut Default::default()), "ok"); std::fs::remove_dir_all(dir).unwrap(); } + #[test] + fn a_link_that_resolves_imports_as_a_linked_asset() { + let dir = std::env::temp_dir().join(format!("dc-idml-linked-import-{}", std::process::id())); + let path = dir.join("Links").join("logo.png"); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + let (idml, png) = linked_idml("/original-computer/project/logo.png", false).unwrap(); + std::fs::write(&path, &png).unwrap(); + + let doc = import(&idml, Some(&dir.join("x.idml"))).unwrap(); + let asset = doc.assets.values().next().unwrap(); + assert_eq!(asset.storage, designcraft_doc::Storage::Linked); + assert!(asset.data.embedded_bytes().is_none(), "no embedded original"); + assert!(asset.data.is_linked() && asset.data.resident().is_some(), "the bytes read are resident for the first draw"); + assert_eq!(asset.link_hash.as_deref(), Some(crate::asset_io::content_hash(&png).as_str())); + assert_eq!(asset.link_relative.as_deref(), Some("Links/logo.png")); + assert!(asset.proxy.is_some(), "a proxy made from the file"); + assert_eq!(asset.data.load().ok().map(|b| (*b).clone()), Some(png)); + std::fs::remove_dir_all(dir).unwrap(); + } + + /// A document's stored preview stands in for a linked file only when it decodes and shows + /// the whole image, within the proxy limits (made again when bigger); otherwise the proxy is + /// made from the file. + #[test] + fn a_stored_preview_is_the_proxy_only_when_it_decodes_and_shows_the_whole_image() { + use designcraft_render::proxy::{MAX_BYTES, MAX_SIDE_PX}; + let dir = std::env::temp_dir().join(format!("dc-idml-previews-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("photo.png"); + let png = |width: u32, height: u32| designcraft_render::Rendered { width, height, pixels: vec![255; (width * height * 4) as usize] }.to_png(); + let original = png(400, 200); + std::fs::write(&path, &original).unwrap(); + let linked_with = |preview: Vec| { + let mut a = designcraft_doc::Asset { + name: "photo.png".into(), + mime: "image/png".into(), + link: Some(path.to_str().unwrap().into()), + data: designcraft_doc::AssetData::embedded(original.clone()), + pixels: Some((400, 200)), + proxy: Some(designcraft_doc::Proxy { mime: "image/png".into(), pixels: (1, 1), data: designcraft_doc::AssetData::embedded(preview) }), + ..Default::default() + }; + link_read_file(&mut a, None); + assert_eq!(a.storage, designcraft_doc::Storage::Linked); + let proxy = a.proxy.expect("a proxy"); + let bytes = proxy.data.embedded_bytes().expect("embedded").clone(); + let pm = designcraft_render::decode_pixmap(&bytes).expect("the proxy decodes"); + assert_eq!((u32::from(pm.width()), u32::from(pm.height())), proxy.pixels); + assert!(bytes.len() <= MAX_BYTES && proxy.pixels.0.max(proxy.pixels.1) <= MAX_SIDE_PX); + (proxy.pixels, bytes) + }; + let small = png(100, 50); + assert_eq!(linked_with(small.clone()), ((100, 50), Arc::new(small)), "kept as it is"); + assert_eq!(linked_with(png(2048, 1024)).0, (1024, 512), "made again within the limits"); + assert_eq!(linked_with(png(100, 100)).0, (400, 200), "a crop of the image: made from the file"); + assert_eq!(linked_with(b"not an image".to_vec()).0, (400, 200), "undecodable: made from the file"); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn a_link_that_does_not_resolve_keeps_its_path_for_relink() { + let (idml, _) = linked_idml("/original-computer/project/logo.png", false).unwrap(); + let doc = import(&idml, None).unwrap(); + let asset = doc.assets.values().next().unwrap(); + assert_eq!(asset.storage, designcraft_doc::Storage::Embedded); + assert_eq!(asset.link.as_deref(), Some("/original-computer/project/logo.png")); + assert!(asset.data.embedded_bytes().is_some_and(|b| b.is_empty()) && asset.link_hash.is_none()); + } + + #[test] + fn a_graphic_embedded_in_the_idml_stays_embedded_beside_its_file() { + let dir = std::env::temp_dir().join(format!("dc-idml-embedded-stays-{}", std::process::id())); + let path = dir.join("logo.png"); + std::fs::create_dir_all(&dir).unwrap(); + let (idml, png) = linked_idml(path.to_str().unwrap(), true).unwrap(); + std::fs::write(&path, &png).unwrap(); + let doc = import(&idml, Some(&dir.join("x.idml"))).unwrap(); + let asset = doc.assets.values().next().unwrap(); + assert_eq!(asset.storage, designcraft_doc::Storage::Embedded); + assert_eq!(asset.data.embedded_bytes().map(|b| (**b).clone()), Some(png)); + std::fs::remove_dir_all(dir).unwrap(); + } + #[test] fn embedded_link_resolution_preserves_originals_and_image_bytes() { let nonce = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos(); @@ -594,7 +754,7 @@ mod tests { let doc = import(&idml, Some(&package.join("x.idml"))).unwrap(); let asset = doc.assets.values().next().unwrap(); assert_eq!(std::path::Path::new(asset.link.as_deref().unwrap()), original.as_path(), "an existing original stays authoritative"); - assert_eq!(*asset.data, png); + assert_eq!(**asset.data.embedded_bytes().unwrap(), png); assert_eq!(super::super::links::status_cached(asset, None, &mut Default::default()), "modified"); std::fs::remove_file(&original).unwrap(); @@ -602,7 +762,7 @@ mod tests { let doc = import(&idml, Some(&package.join("x.idml"))).unwrap(); let asset = doc.assets.values().next().unwrap(); assert_eq!(asset.link.as_deref(), copy.to_str()); - assert_eq!(*asset.data, png, "rebinding must not replace embedded pixels"); + assert_eq!(**asset.data.embedded_bytes().unwrap(), png, "rebinding must not replace embedded pixels"); assert_eq!(super::super::links::status_cached(asset, None, &mut Default::default()), "modified"); std::fs::remove_file(©).unwrap(); @@ -611,7 +771,7 @@ mod tests { let doc = import(&idml, folder).unwrap(); let asset = doc.assets.values().next().unwrap(); assert_eq!(std::path::Path::new(asset.link.as_deref().unwrap()), original.as_path(), "keep a missing link when there is no candidate"); - assert_eq!(*asset.data, png); + assert_eq!(**asset.data.embedded_bytes().unwrap(), png); assert_eq!(super::super::links::status_cached(asset, None, &mut Default::default()), "missing"); } let oversized = "a/".repeat(MAX_LINK_PATH_BYTES); @@ -621,7 +781,7 @@ mod tests { resolve_packaged_links(&mut doc, Some(&packaged)); let asset = doc.assets.values().next().unwrap(); assert_eq!(asset.link.as_deref(), Some(oversized.as_str())); - assert_eq!(*asset.data, png); + assert_eq!(**asset.data.embedded_bytes().unwrap(), png); std::fs::remove_dir_all(dir).unwrap(); } @@ -668,12 +828,12 @@ mod tests { let (idml, _) = linked_idml(away.to_str().unwrap(), false).unwrap(); let doc = import(&idml, Some(&package)).unwrap(); let asset = doc.assets.values().next().unwrap(); - assert_eq!((&*asset.data, asset.link.as_deref()), (&png, away.to_str())); + assert_eq!((&*asset.data.resident().unwrap(), asset.link.as_deref()), (&png, away.to_str())); assert_eq!(super::super::links::status_cached(asset, None, &mut Default::default()), "ok"); std::fs::write(dir.join("Links").join("logo.png"), &png).unwrap(); let (idml, _) = linked_idml("Links/logo.png", false).unwrap(); let doc = import(&idml, Some(&package)).unwrap(); - assert_eq!(*doc.assets.values().next().unwrap().data, png); + assert_eq!(*doc.assets.values().next().unwrap().data.resident().unwrap(), png); std::fs::remove_dir_all(base).unwrap(); } @@ -773,14 +933,14 @@ mod nested_layer_tests { for (id, expected) in ids.into_iter().zip([states(false, true), states(true, true)]) { let item = copy.placed_items().into_iter().find(|i| i.id == id).unwrap(); let asset = ©.assets[&item.graphic().unwrap().asset]; - assert_eq!(designcraft_render::pdf_layers(&asset.data), expected, "{location}: placement {id}"); + assert_eq!(designcraft_render::pdf_layers(&asset.data.load().unwrap()), expected, "{location}: placement {id}"); assert_ne!(asset.id, original_asset); assert!(asset.link.is_none()); assert!(!item.pdf_layer_override && item.pdf_hidden_layers.is_empty()); } assert_eq!(copy.item(control).unwrap().graphic().unwrap().asset, original_asset); assert!(Arc::ptr_eq(©.assets[&original_asset], &source.assets[&original_asset])); - assert_eq!(designcraft_render::pdf_layers(&source.assets[&original_asset].data), states(true, false)); + assert_eq!(designcraft_render::pdf_layers(&source.assets[&original_asset].data.load().unwrap()), states(true, false)); assert!(source.placed_items().into_iter().filter(|i| ids.contains(&i.id)).all(|i| i.has_pdf_layer_override())); } @@ -790,8 +950,12 @@ mod nested_layer_tests { let result = session.execute("file.exportIdml", &json!({})).unwrap(); let bytes = base64_decode(result["base64"].as_str().unwrap()); let imported = designcraft_idml::import_idml(&bytes).unwrap(); - let mut roundtrip: Vec<_> = - imported.assets.values().filter(|a| designcraft_render::is_pdf(&a.data)).map(|a| designcraft_render::pdf_layers(&a.data)).collect(); + let mut roundtrip: Vec<_> = imported + .assets + .values() + .filter(|a| designcraft_render::is_pdf(&a.data.load().unwrap())) + .map(|a| designcraft_render::pdf_layers(&a.data.load().unwrap())) + .collect(); let mut expected = vec![states(true, false), states(false, true), states(true, true)]; roundtrip.sort(); expected.sort(); @@ -875,8 +1039,12 @@ mod nested_layer_tests { doc.check().unwrap(); let result = s.execute("file.exportIdml", &json!({})).unwrap(); let imported = designcraft_idml::import_idml(&base64_decode(result["base64"].as_str().unwrap())).unwrap(); - let mut layers: Vec<_> = - imported.assets.values().filter(|a| designcraft_render::is_pdf(&a.data)).map(|a| designcraft_render::pdf_layers(&a.data)).collect(); + let mut layers: Vec<_> = imported + .assets + .values() + .filter(|a| designcraft_render::is_pdf(&a.data.load().unwrap())) + .map(|a| designcraft_render::pdf_layers(&a.data.load().unwrap())) + .collect(); layers.sort(); assert_eq!(layers, vec![states(false, true), states(true, false)]); } diff --git a/crates/engine/src/cmd/layout/layers.rs b/crates/engine/src/cmd/layout/layers.rs index 80fbc9d28..6601e11e0 100644 --- a/crates/engine/src/cmd/layout/layers.rs +++ b/crates/engine/src/cmd/layout/layers.rs @@ -1,4 +1,9 @@ -use super::{LAYER_COLORS, LayerId, Result, Session, Value, bad, ok}; +use std::collections::{HashMap, HashSet}; +use std::sync::Arc; + +use designcraft_doc::{Guide, Hyperlink, HyperlinkSource, Item, ItemId, SpreadRef, Story, StoryId}; + +use super::{LAYER_COLORS, Layer, LayerId, Result, Session, Value, bad, json, ok}; /// Layer Options: every field in one undo step; a bad name or colour changes nothing. pub(super) fn set_layer(s: &mut Session, p: &Value) -> Result { @@ -53,6 +58,325 @@ pub(super) fn set_layer(s: &mut Session, p: &Value) -> Result { }) } +/// Duplicate Layer: a new layer above `id` with its settings and a copy of every object on it, on document and parent +/// spreads, in one undo step. Copied text frames stay threaded to the other copied frames of their story, and each copy +/// of a story holds all of its text. A copied override of a parent item overrides that item's copy, or is detached when +/// the parent item is on another layer. Pages hide a parent item's copy where they hide the parent item. Hyperlinks on +/// copied objects and text get copies that go to the same destinations. +pub(super) fn duplicate_layer(s: &mut Session, p: &Value) -> Result { + const ID: &str = "layer.duplicate"; + let id = LayerId(p.get("id").and_then(Value::as_u64).ok_or_else(|| bad(ID, "missing id"))?); + let r = s.edit(|d, _| { + let i = d.layers.iter().position(|l| l.id == id).ok_or_else(|| bad(ID, "no such layer"))?; + let mut seen = HashMap::new(); + if d.spreads.iter().chain(&d.parents).flat_map(|sp| sp.items.iter()).any(|it| it.layer == id && too_deep(it, d, &mut seen)) { + return Err(bad(ID, "the layer's objects are nested too deeply to copy")); + } + let new_id = LayerId(d.alloc()); + let mut layer = d.layers[i].clone(); + layer.id = new_id; + layer.name = copy_name(&d.layers, &layer.name); + d.layers.insert(i, layer); + let src = d.clone(); + let mut stories = HashMap::new(); + let mut ids = HashMap::new(); + let refs = (0..src.parents.len()).map(SpreadRef::Parent).chain((0..src.spreads.len()).map(SpreadRef::Doc)); + let mut copies = Vec::new(); + for r in refs { + let Some(sp) = src.spread(r) else { continue }; + for it in sp.items.iter().filter(|it| it.layer == id) { + let mut copy = Item::clone(it); + if !super::super::object::renumber(d, &src, &mut copy, &mut stories) { + return Err(bad(ID, "the layer's objects are nested too deeply to copy")); + } + map_ids(it, ©, &mut ids); + copies.push((r, copy)); + } + } + // The story copies hold copies of the original's anchored objects with ids of their own (and copies of the + // stories of anchored text frames): record each copy's id against the original's. + for (old, new) in &stories { + if let (Some(orig), Some(copy)) = (src.story(*old), d.story(*new)) { + map_anchored(orig, copy, &mut ids); + } + } + // Every copy, anchored objects included, has its id before overrides are pointed at the copied parent items and + // live captions at the copied objects. + for (r, mut copy) in copies { + move_copy(&mut copy, new_id, &ids); + d.insert_item(r, copy, None)?; + } + for new in stories.values() { + if let Some(st) = d.story_mut(*new) { + move_anchored(st, new_id, &ids); + } + } + // Each story copy gets its frames in the original order, text anchors of its own, which its cross-references + // and those of the other copies point at, and tables with ids of their own, the tables in its cells and notes + // included, allocated in story order. + let mut anchors = HashMap::new(); + // The copies' own anchors are given ids below, so only the other stories' anchors count as taken. + let copied: HashSet = stories.values().copied().collect(); + let mut used = HashSet::new(); + for st in d.stories.values().filter(|st| !copied.contains(&st.id)) { + anchor_ids(st, &mut used); + } + let mut order: Vec<(StoryId, StoryId)> = stories.iter().map(|(old, new)| (*old, *new)).collect(); + order.sort_unstable_by_key(|(_, new)| *new); + for (old, new) in &order { + let Some(mut st) = d.story(*new).cloned() else { continue }; + if let Some((parent, revision)) = st.link { + st.link = Some((stories.get(&parent).copied().unwrap_or(parent), revision)); + } + st.frames = src.story(*old).map(|o| o.frames.iter().filter_map(|f| ids.get(f).copied()).collect()).unwrap_or_default(); + // The copy's anchors may already have new ids: each is keyed by the id of the original's anchor, which the + // copied cross-references still point at. + let originals: Vec = src.story(*old).map(|o| o.anchors.iter().map(|a| a.id).collect()).unwrap_or_default(); + for ((k, a), orig_id) in (1..).zip(st.anchors.iter_mut()).zip(originals) { + // `story id << 24 | n`, as anchors are made, or a new id when another anchor has that one or the story id + // does not fit. + let made = new.0.checked_mul(1 << 24).and_then(|base| base.checked_add(k)).filter(|id| !used.contains(id)); + let id = match made { + Some(id) => id, + None => loop { + let id = d.alloc(); + if !used.contains(&id) { + break id; + } + }, + }; + anchors.insert(orig_id, id); + used.insert(id); + Arc::make_mut(a).id = id; + } + renumber_tables(d, &mut st); + renumber_nested_anchors(d, &mut st, &mut anchors, &mut used); + d.stories.insert(*new, Arc::new(st)); + } + for new in stories.values() { + if let Some(st) = d.story_mut(*new) { + remap_xrefs(st, &anchors); + } + } + // The hyperlinks of copied objects and copied text get copies with ids of their own and the same destinations. + let links: Vec<_> = src + .hyperlinks + .iter() + .filter_map(|h| { + let source = match &h.source { + HyperlinkSource::Item { id } => HyperlinkSource::Item { id: *ids.get(id)? }, + HyperlinkSource::Text { story, start, end } => HyperlinkSource::Text { story: *stories.get(story)?, start: *start, end: *end }, + }; + Some((h, source)) + }) + .collect(); + for (h, source) in links { + let id = d.alloc(); + d.hyperlinks.push(Hyperlink { id, source, ..h.clone() }); + } + // A page, document or parent, hides a parent item's copy where it hides the parent item, and its ruler guides on + // the layer get copies on the new layer. + let hidden = |pg: &designcraft_doc::Page| -> Vec { pg.overridden.iter().filter_map(|o| ids.get(o).copied()).collect() }; + for sp in d.spreads.iter_mut().chain(d.parents.iter_mut()) { + if sp.pages.iter().all(|pg| hidden(pg).is_empty() && pg.guides.iter().all(|g| g.layer != Some(id))) { + continue; + } + for pg in &mut Arc::make_mut(sp).pages { + let copies = hidden(pg); + pg.overridden.extend(copies); + let guides: Vec<_> = pg.guides.iter().filter(|g| g.layer == Some(id)).map(|g| Guide { layer: Some(new_id), ..g.clone() }).collect(); + pg.guides.extend(guides); + } + } + Ok(new_id) + })?; + s.doc_mut()?.active_layer = r; + Ok(json!({"id": r.0})) +} + +/// The name of a copy of layer `name`: " copy", then " copy 2" and up while a layer has the name. +fn copy_name(layers: &[Layer], name: &str) -> String { + let base = format!("{name} copy"); + let taken = |n: &str| layers.iter().any(|l| l.name == n); + if !taken(&base) { + return base; + } + (2..).map(|k| format!("{base} {k}")).find(|n| !taken(n)).unwrap_or(base) +} + +/// Record each id of `orig` and its descendants against the matching id in `copy`. +fn map_ids(orig: &Item, copy: &Item, ids: &mut HashMap) { + ids.insert(orig.id, copy.id); + for (o, c) in orig.children().iter().zip(copy.children()) { + map_ids(o, c, ids); + } +} + +/// A layer whose groups, anchored objects, table cells and notes nest deeper than this, counted from an object on a +/// spread through the stories its anchored text frames show, is not duplicated. +const MAX_COPY_DEPTH: usize = 64; + +/// Whether `it`, with the stories its text frames reach directly or through anchored text frames, nests groups, +/// anchored objects, table cells and notes deeper than [`MAX_COPY_DEPTH`] in all: a story counts from the depth of the +/// frame that shows it, as copying it recurses on from there. `seen` holds the deepest level each story was checked at; +/// a story reached again no deeper is skipped. +fn too_deep(it: &Item, d: &designcraft_doc::Document, seen: &mut HashMap) -> bool { + fn item(it: &Item, depth: usize, next: &mut Vec<(StoryId, usize)>) -> bool { + if let Some(t) = it.text_frame() { + next.push((t.story, depth)); + } + depth > MAX_COPY_DEPTH || it.children().iter().any(|c| item(c, depth + 1, next)) + } + fn story(st: &Story, depth: usize, next: &mut Vec<(StoryId, usize)>) -> bool { + depth > MAX_COPY_DEPTH + || st.objects.iter().any(|o| item(&o.item, depth + 1, next)) + || st.tables.values().flat_map(|t| &t.cells).any(|c| story(&c.text, depth + 1, next)) + || st.notes.iter().chain(&st.endnotes).any(|n| story(&n.text, depth + 1, next)) + } + let mut next = Vec::new(); + if item(it, 0, &mut next) { + return true; + } + while let Some((sid, depth)) = next.pop() { + if seen.get(&sid).is_some_and(|&checked| checked >= depth) { + continue; + } + seen.insert(sid, depth); + if let Some(st) = d.story(sid) + && story(st, depth, &mut next) + { + return true; + } + } + false +} + +/// Run [`map_ids`] on the items anchored in story `orig` and in its copy `copy`, and in the stories of their table cells +/// and notes. [`too_deep`] bounds the nesting. +fn map_anchored(orig: &Story, copy: &Story, ids: &mut HashMap) { + for (o, c) in orig.objects.iter().zip(©.objects) { + map_ids(&o.item, &c.item, ids); + } + // Copied tables have new ids, given in the order of the old ones, so the two maps list them in the same order. + for (t, ct) in orig.tables.values().zip(copy.tables.values()) { + for (o, c) in t.cells.iter().zip(&ct.cells) { + map_anchored(&o.text, &c.text, ids); + } + } + for (o, c) in orig.notes.iter().chain(&orig.endnotes).zip(copy.notes.iter().chain(©.endnotes)) { + map_anchored(&o.text, &c.text, ids); + } +} + +/// Give the tables of `st`, and the tables in the stories of its table cells and notes, new ids from `d`, and point the +/// paragraphs that hold them at the new ids. [`too_deep`] bounds the nesting. +fn renumber_tables(d: &mut designcraft_doc::Document, st: &mut Story) { + let mut tables = HashMap::new(); + for (t, mut table) in std::mem::take(&mut st.tables) { + let n = d.alloc(); + let table_mut = Arc::make_mut(&mut table); + table_mut.id = n; + for c in &mut table_mut.cells { + renumber_tables(d, &mut c.text); + } + tables.insert(t, n); + st.tables.insert(n, table); + } + for pf in &mut st.paras { + pf.table = pf.table.and_then(|t| tables.get(&t).copied()); + } + for n in st.notes.iter_mut().chain(st.endnotes.iter_mut()) { + renumber_tables(d, &mut Arc::make_mut(n).text); + } +} + +/// Add the ids of the text anchors in `st`, and in the stories of its table cells and notes at any depth, to `used`. +/// The walk keeps its own stack, so a story on another layer that nests deeper than [`too_deep`] allows is read too. +fn anchor_ids(st: &Story, used: &mut HashSet) { + let mut stack = vec![st]; + while let Some(st) = stack.pop() { + used.extend(st.anchors.iter().map(|a| a.id)); + stack.extend(st.tables.values().flat_map(|t| t.cells.iter().map(|c| &c.text))); + stack.extend(st.notes.iter().chain(st.endnotes.iter()).map(|n| &n.text)); + } +} + +/// Give the text anchors in the stories of the table cells and notes of `st` new ids from `d` that are not in `used` +/// (recorded in `anchors` and `used`). [`too_deep`] bounds the nesting. +fn renumber_nested_anchors(d: &mut designcraft_doc::Document, st: &mut Story, anchors: &mut HashMap, used: &mut HashSet) { + fn child(d: &mut designcraft_doc::Document, st: &mut Story, anchors: &mut HashMap, used: &mut HashSet) { + for anchor in &mut st.anchors { + let id = loop { + let id = d.alloc(); + if used.insert(id) { + break id; + } + }; + anchors.insert(anchor.id, id); + Arc::make_mut(anchor).id = id; + } + renumber_nested_anchors(d, st, anchors, used); + } + for table in st.tables.values_mut() { + for cell in &mut Arc::make_mut(table).cells { + child(d, &mut cell.text, anchors, used); + } + } + for note in st.notes.iter_mut().chain(st.endnotes.iter_mut()) { + child(d, &mut Arc::make_mut(note).text, anchors, used); + } +} + +/// Point the cross-references in `st`, and in the stories of its table cells and notes, at the anchors `map` gives for +/// their targets. [`too_deep`] bounds the nesting. +fn remap_xrefs(st: &mut Story, map: &HashMap) { + for x in &mut st.xrefs { + if let Some(n) = map.get(&x.target) { + Arc::make_mut(x).target = *n; + } + } + for t in st.tables.values_mut() { + for c in &mut Arc::make_mut(t).cells { + remap_xrefs(&mut c.text, map); + } + } + for n in st.notes.iter_mut().chain(st.endnotes.iter_mut()) { + remap_xrefs(&mut Arc::make_mut(n).text, map); + } +} + +/// Put `it` and its descendants on layer `to`, and point overrides at the copied parent items and live captions at the +/// copied objects. A copy whose parent item was not copied is detached from it, so the original override stays the only +/// one of that item. +fn move_copy(it: &mut Item, to: LayerId, ids: &HashMap) { + it.layer = to; + it.overrides = it.overrides.and_then(|o| ids.get(&o).copied()); + if let Some(c) = &mut it.live_caption + && let Some(n) = ids.get(&c.source) + { + c.source = *n; + } + for c in it.children_mut().into_iter().flatten() { + move_copy(Arc::make_mut(c), to, ids); + } +} + +/// Run [`move_copy`] on the anchored objects of `st` and of the stories of its table cells and notes. [`too_deep`] bounds +/// the nesting. +fn move_anchored(st: &mut Story, to: LayerId, ids: &HashMap) { + for o in &mut st.objects { + move_copy(&mut Arc::make_mut(o).item, to, ids); + } + for t in st.tables.values_mut() { + for c in &mut Arc::make_mut(t).cells { + move_anchored(&mut c.text, to, ids); + } + } + for n in st.notes.iter_mut().chain(st.endnotes.iter_mut()) { + move_anchored(&mut Arc::make_mut(n).text, to, ids); + } +} + #[cfg(test)] mod layer_tests { use serde_json::json; @@ -96,6 +420,770 @@ mod layer_tests { assert_eq!(d.layers.len(), 1); assert_eq!(d.item(designcraft_doc::ItemId(f)).unwrap().layer.0, l4); } + + fn on_layer(d: &designcraft_doc::Document, layer: u64) -> Vec> { + d.spreads.iter().chain(&d.parents).flat_map(|sp| sp.items.iter().filter(|i| i.layer.0 == layer).cloned()).collect() + } + + #[test] + fn duplicate_layer_copies_settings_and_objects_above_the_original() { + let mut s = crate::Session::new(); + s.execute("file.new", &json!({"pages": 2, "facingPages": false})).unwrap(); + let base = s.doc().unwrap().doc.layers[0].id.0; + let art = s.execute("layer.new", &json!({"name": "Art"})).unwrap()["id"].as_u64().unwrap(); + s.execute("layer.set", &json!({"id": art, "color": "Red", "printable": false, "showGuides": false})).unwrap(); + let rect = s.execute("frame.create", &json!({"rect": [10, 10, 50, 50]})).unwrap()["id"].as_u64().unwrap(); + s.execute("frame.create", &json!({"spread": 1, "rect": [10, 10, 60, 60]})).unwrap(); + s.execute("guide.add", &json!({"orientation": "horizontal", "position": 200, "page": 0, "liquid": true})).unwrap(); + s.execute("layer.activate", &json!({"id": base})).unwrap(); + s.execute("frame.create", &json!({"rect": [100, 100, 150, 150]})).unwrap(); + s.execute("guide.add", &json!({"orientation": "vertical", "position": 300, "page": 0})).unwrap(); + s.execute("layer.set", &json!({"id": art, "locked": true})).unwrap(); + let before = s.doc().unwrap().doc.clone(); + let copy = s.execute("layer.duplicate", &json!({"id": art})).unwrap()["id"].as_u64().unwrap(); + let d = s.doc().unwrap().doc.clone(); + assert_eq!(d.layers.iter().map(|l| l.id.0).collect::>(), [copy, art, base], "the copy sits right above the original"); + let (l, o) = (d.layer(designcraft_doc::LayerId(copy)).unwrap(), d.layer(designcraft_doc::LayerId(art)).unwrap()); + assert_eq!(l.name, "Art copy"); + assert_eq!((l.color, l.visible, l.locked, l.printable, l.show_guides), (o.color, o.visible, o.locked, o.printable, o.show_guides)); + assert_eq!(s.doc().unwrap().active_layer.0, copy); + let (orig, copies) = (on_layer(&d, art), on_layer(&d, copy)); + assert_eq!(copies.len(), 2, "both spreads' objects"); + for (a, b) in orig.iter().zip(&copies) { + assert_ne!(a.id, b.id); + assert_eq!((a.xf, a.path.clone()), (b.xf, b.path.clone())); + assert_eq!(d.find(a.id).unwrap().spread, d.find(b.id).unwrap().spread); + } + assert_eq!(on_layer(&d, base).len(), 1, "other layers' objects stay as they were"); + let guides = &d.spreads[0].pages[0].guides; + assert_eq!(guides.len(), 3, "Art's guide gets a copy; the base layer's does not"); + let (g, c) = (&guides[0], &guides[2]); + assert_eq!((g.layer, c.layer), (Some(designcraft_doc::LayerId(art)), Some(designcraft_doc::LayerId(copy)))); + assert_eq!((g.orientation, g.position, g.liquid), (c.orientation, c.position, c.liquid)); + assert!(d.item(designcraft_doc::ItemId(rect)).is_some()); + // A second copy gets a name of its own; bad ids change nothing. + s.execute("layer.duplicate", &json!({"id": art})).unwrap(); + assert_eq!(s.doc().unwrap().doc.layers[1].name, "Art copy 2"); + s.execute("edit.undo", &json!({})).unwrap(); + for bad in [json!({"id": 999}), json!({})] { + assert!(s.execute("layer.duplicate", &bad).is_err(), "{bad}"); + } + // One undo step. + s.execute("edit.undo", &json!({})).unwrap(); + let d = &s.doc().unwrap().doc; + assert_eq!(d.layers, before.layers); + assert_eq!(d.all_items(), before.all_items()); + } + + #[test] + fn duplicate_layer_keeps_linked_story_parents_with_their_copies() { + for copy_parent in [true, false] { + let mut s = crate::Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let parent = s.execute("frame.create", &json!({"rect": [0, 0, 100, 100], "content": "text", "text": "Original"})).unwrap(); + let layer = if copy_parent { + s.doc().unwrap().active_layer.0 + } else { + s.execute("layer.new", &json!({"name": "Linked"})).unwrap()["id"].as_u64().unwrap() + }; + let child = s.execute("story.placeAndLink", &json!({"story": parent["story"], "rect": [100, 0, 200, 100]})).unwrap(); + let copy = s.execute("layer.duplicate", &json!({"id": layer})).unwrap()["id"].as_u64().unwrap(); + let d = &s.doc().unwrap().doc; + let copies = on_layer(d, copy); + let copied_stories: Vec<_> = copies.iter().map(|item| d.story(item.text_frame().unwrap().story).unwrap()).collect(); + let copied_child = copied_stories.iter().find(|story| story.link.is_some()).unwrap().id; + let expected_parent = if copy_parent { + copied_stories.iter().find(|story| story.link.is_none()).unwrap().id + } else { + designcraft_doc::StoryId(parent["story"].as_u64().unwrap()) + }; + assert_eq!(d.story(copied_child).unwrap().link.unwrap().0, expected_parent); + s.execute("story.setText", &json!({"story": expected_parent.0, "text": "Edited source"})).unwrap(); + s.execute("story.updateLink", &json!({"story": copied_child.0})).unwrap(); + assert_eq!(s.doc().unwrap().doc.story(copied_child).unwrap().text, "Edited source"); + assert_eq!(s.doc().unwrap().doc.story(designcraft_doc::StoryId(child["story"].as_u64().unwrap())).unwrap().text, "Original"); + if copy_parent { + s.execute("story.setText", &json!({"story": parent["story"], "text": "Edited original"})).unwrap(); + s.execute("story.updateLink", &json!({"story": copied_child.0})).unwrap(); + assert_eq!(s.doc().unwrap().doc.story(copied_child).unwrap().text, "Edited source"); + } + } + } + + #[test] + fn duplicate_layer_keeps_threads_on_the_layer_only() { + let mut s = crate::Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let base = s.doc().unwrap().doc.layers[0].id.0; + let text = |s: &mut crate::Session, rect: [f64; 4], t: &str| { + s.execute("frame.create", &json!({"rect": rect, "content": "text", "text": t})).unwrap()["id"].as_u64().unwrap() + }; + // a → b on Base, c on Art at the end of the same thread. + let b = text(&mut s, [10.0, 200.0, 100.0, 240.0], ""); + let a = text(&mut s, [10.0, 10.0, 100.0, 50.0], "One two three four five six seven eight nine ten eleven twelve"); + s.execute("text.thread", &json!({"from": a, "to": b})).unwrap(); + let art = s.execute("layer.new", &json!({"name": "Art"})).unwrap()["id"].as_u64().unwrap(); + let c = text(&mut s, [300.0, 10.0, 400.0, 50.0], ""); + s.execute("text.thread", &json!({"from": b, "to": c})).unwrap(); + let _ = art; + let copy = s.execute("layer.duplicate", &json!({"id": base})).unwrap()["id"].as_u64().unwrap(); + let d = s.doc().unwrap().doc.clone(); + let story = |id: u64| d.item(designcraft_doc::ItemId(id)).and_then(|i| i.text_frame()).map(|t| t.story).unwrap(); + let orig = d.story(story(a)).unwrap(); + assert_eq!(orig.frames.iter().map(|f| f.0).collect::>(), [a, b, c], "the original thread is unchanged"); + let copies = on_layer(&d, copy); + assert_eq!(copies.len(), 2); + let sid = copies[0].text_frame().unwrap().story; + assert_eq!(copies[1].text_frame().unwrap().story, sid, "the copies share one story"); + let st = d.story(sid).unwrap(); + assert_ne!(sid, orig.id); + assert_eq!(st.text, orig.text, "the copy holds the whole text"); + // Thread order as in the original (a's copy first, though b's copy was made first), without c. + let pos = |id: designcraft_doc::ItemId| d.find(id).map(|l| l.path.clone()); + let order: Vec<_> = st.frames.iter().map(|f| d.item(*f).unwrap().path.clone()).collect(); + let want: Vec<_> = [a, b].iter().map(|f| d.item(designcraft_doc::ItemId(*f)).unwrap().path.clone()).collect(); + assert_eq!(order, want); + assert!(st.frames.iter().all(|f| pos(*f).is_some())); + } + + #[test] + fn duplicate_layer_copies_parent_items_and_their_overrides() { + let mut s = crate::Session::new(); + s.execute("file.new", &json!({"pages": 3, "facingPages": false})).unwrap(); + let base = s.doc().unwrap().doc.layers[0].id.0; + let folio = json!({"spread": {"kind": "parent", "index": 0}, "rect": [72, 720, 300, 750], "content": "text", "text": "Folio"}); + let parent = s.execute("frame.create", &folio).unwrap()["id"].as_u64().unwrap(); + let o = s.execute("layout.overrideParentItems", &json!({"page": 1})).unwrap()["ids"][0].as_u64().unwrap(); + // Page 3's override is deleted, which keeps the parent item hidden there. + let gone = s.execute("layout.overrideParentItems", &json!({"page": 2})).unwrap()["ids"][0].as_u64().unwrap(); + s.execute("selection.set", &json!({"ids": [gone]})).unwrap(); + s.execute("edit.clear", &json!({})).unwrap(); + // Parent B, based on A, hides the folio on its page. + s.execute("layout.parents.new", &json!({"prefix": "B"})).unwrap(); + s.edit(|d, _| { + let a = d.parents[0].id; + let bp = std::sync::Arc::make_mut(&mut d.parents[1]); + bp.parent.as_mut().unwrap().based_on = Some(a); + bp.pages[0].parent = Some(a); + bp.pages[0].overridden.push(designcraft_doc::ItemId(parent)); + Ok(()) + }) + .unwrap(); + let copy = s.execute("layer.duplicate", &json!({"id": base})).unwrap()["id"].as_u64().unwrap(); + let d = s.doc().unwrap().doc.clone(); + let copies = on_layer(&d, copy); + assert_eq!(copies.len(), 2, "the parent item and page 2's override"); + let p2 = copies.iter().find(|i| matches!(d.find(i.id).unwrap().spread, designcraft_doc::SpreadRef::Parent(0))).unwrap(); + let o2 = copies.iter().find(|i| i.overrides.is_some()).unwrap(); + assert_ne!((p2.id.0, o2.id.0), (parent, o)); + assert_eq!(o2.overrides, Some(p2.id), "the override's copy overrides the parent item's copy"); + assert_eq!(d.page_of_item(o2.id), Some(1)); + let overridden = |page: usize| { + let (si, pi) = d.page_loc(page).unwrap(); + d.spreads[si].pages[pi].overridden.clone() + }; + assert_eq!(overridden(1), [designcraft_doc::ItemId(parent), p2.id], "page 2 hides both parent items"); + assert_eq!(overridden(2), [designcraft_doc::ItemId(parent), p2.id], "page 3 too, without an override"); + assert!(overridden(0).is_empty(), "page 1 shows both"); + assert_eq!(d.parents[1].pages[0].overridden, [designcraft_doc::ItemId(parent), p2.id], "parent B hides both"); + } + + #[test] + fn duplicate_layer_moves_whole_groups_and_finds_later_parent_items() { + let mut s = crate::Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let base = s.doc().unwrap().doc.layers[0].id.0; + let a = s.execute("frame.create", &json!({"rect": [0, 0, 10, 10]})).unwrap()["id"].as_u64().unwrap(); + s.execute("layer.new", &json!({"name": "Art"})).unwrap(); + let b = s.execute("frame.create", &json!({"rect": [20, 0, 30, 10]})).unwrap()["id"].as_u64().unwrap(); + // The group takes the base layer from its first member; b stays on Art inside it. + let g = s.execute("object.group", &json!({"ids": [a, b]})).unwrap()["id"].as_u64().unwrap(); + s.execute("layer.activate", &json!({"id": base})).unwrap(); + // Parent A's item overrides one on parent B, which comes after it in the document. + s.execute("layout.parents.new", &json!({"prefix": "B"})).unwrap(); + let on_b = + s.execute("frame.create", &json!({"spread": {"kind": "parent", "index": 1}, "rect": [0, 0, 50, 50]})).unwrap()["id"].as_u64().unwrap(); + let on_a = + s.execute("frame.create", &json!({"spread": {"kind": "parent", "index": 0}, "rect": [0, 0, 50, 50]})).unwrap()["id"].as_u64().unwrap(); + s.edit(|d, _| { + d.item_mut(designcraft_doc::ItemId(on_a)).unwrap().overrides = Some(designcraft_doc::ItemId(on_b)); + Ok(()) + }) + .unwrap(); + let d = s.doc().unwrap().doc.clone(); + let layer_of = |id: u64| d.item(designcraft_doc::ItemId(id)).unwrap().layer.0; + assert_eq!((layer_of(g), layer_of(b)), (base, d.layers.iter().find(|l| l.name == "Art").unwrap().id.0)); + let copy = s.execute("layer.duplicate", &json!({"id": base})).unwrap()["id"].as_u64().unwrap(); + let d = s.doc().unwrap().doc.clone(); + let copies = on_layer(&d, copy); + let group = copies.iter().find(|i| !i.children().is_empty()).unwrap(); + assert!(group.children().iter().all(|c| c.layer.0 == copy), "the copied group is on the new layer as a whole"); + let in_parent = + |i: usize| copies.iter().find(|c| matches!(d.find(c.id).unwrap().spread, designcraft_doc::SpreadRef::Parent(p) if p == i)).unwrap(); + assert_eq!(in_parent(0).overrides, Some(in_parent(1).id), "A's copy overrides B's copy"); + } + + #[test] + fn duplicate_layer_gives_anchored_objects_their_own_ids() { + let mut s = crate::Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let base = s.doc().unwrap().doc.layers[0].id.0; + let text = json!({"rect": [72, 72, 400, 400], "content": "text", "text": "Before after."}); + let f = s.execute("frame.create", &text).unwrap()["id"].as_u64().unwrap(); + let sid = s.doc().unwrap().doc.item(designcraft_doc::ItemId(f)).unwrap().text_frame().unwrap().story; + let b = s.execute("frame.create", &json!({"rect": [450, 450, 474, 490]})).unwrap()["id"].as_u64().unwrap(); + s.execute("anchored.insert", &json!({"ids": [b], "story": sid.0, "pos": 7})).unwrap(); + // Two anchored text frames threaded in one story, as IDML import makes them. + let threaded = s + .edit(|d, _| { + use designcraft_doc::{AnchoredObject, ParaFormat}; + let (r, r2) = (designcraft_geom::Rect::new(0.0, 0.0, 60.0, 30.0), designcraft_geom::Rect::new(0.0, 0.0, 80.0, 40.0)); + let (first, story) = d.add_text_frame(designcraft_doc::SpreadRef::Doc(0), r, d.default_layer(), "Symbol", ParaFormat::default())?; + let (second, spare) = d.add_text_frame(designcraft_doc::SpreadRef::Doc(0), r2, d.default_layer(), "", ParaFormat::default())?; + let mut items = Vec::new(); + for f in [first, second] { + let mut it = d.item(f).cloned().ok_or(designcraft_doc::DocError::NoItem(f))?; + if let designcraft_doc::Content::Text(tf) = &mut it.content { + tf.story = story; + } + items.push(it); + } + d.stories.remove(&spare); + d.story_mut(story).ok_or(designcraft_doc::DocError::NoStory(story))?.frames = vec![first, second]; + std::sync::Arc::make_mut(&mut d.spreads[0]).items.retain(|i| i.id != first && i.id != second); + let st = d.story_mut(sid).ok_or(designcraft_doc::DocError::NoStory(sid))?; + for it in items.into_iter().rev() { + st.insert_object(0, AnchoredObject::new(it, Default::default())); + } + Ok(story) + }) + .unwrap(); + s.doc().unwrap().doc.check().unwrap(); + let copy = s.execute("layer.duplicate", &json!({"id": base})).unwrap()["id"].as_u64().unwrap(); + let d = &s.doc().unwrap().doc; + d.check().unwrap(); + let symbols: Vec<_> = d.anchored_items().into_iter().filter_map(|(_, i)| i.text_frame().map(|t| (i.id, t.story))).collect(); + assert_eq!(symbols.len(), 4); + let copied = symbols.iter().map(|s| s.1).find(|s| *s != threaded).unwrap(); + let st = d.story(copied).unwrap(); + assert_eq!(st.text, "Symbol"); + assert_eq!(st.frames.len(), 2, "the copies share one story"); + let order = |story: &designcraft_doc::Story| story.frames.iter().map(|f| d.anchored_item(*f).unwrap().path.clone()).collect::>(); + assert_eq!(order(st), order(d.story(threaded).unwrap()), "in the original thread order"); + let anchored: Vec<_> = d.anchored_items().into_iter().filter(|(_, i)| i.text_frame().is_none()).map(|(_, i)| (i.id, i.layer.0)).collect(); + assert_eq!(anchored.len(), 2); + assert_ne!(anchored[0].0, anchored[1].0, "the copy's anchored object has an id of its own"); + let mut layers: Vec<_> = anchored.iter().map(|a| a.1).collect(); + layers.sort_unstable(); + let mut want = vec![base, copy]; + want.sort_unstable(); + assert_eq!(layers, want, "the copy's anchored object is on the new layer"); + } + + #[test] + fn duplicate_layer_points_copied_live_captions_at_the_copied_objects() { + let mut s = crate::Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let base = s.doc().unwrap().doc.layers[0].id.0; + let a = s.execute("frame.create", &json!({"rect": [72, 72, 272, 172]})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.altText", &json!({"text": "First", "ids": [a]})).unwrap(); + s.execute("object.caption", &json!({"ids": [a], "text": "Photo: {altText}", "live": true})).unwrap(); + let copy = s.execute("layer.duplicate", &json!({"id": base})).unwrap()["id"].as_u64().unwrap(); + let d = &s.doc().unwrap().doc; + let copies = on_layer(d, copy); + let frame = copies.iter().find(|i| i.live_caption.is_none()).unwrap(); + let caption = copies.iter().find_map(|i| i.live_caption.as_ref()).unwrap(); + assert_eq!(caption.source, frame.id, "the caption's copy follows the frame's copy"); + assert_ne!(frame.id.0, a); + } + + #[test] + fn duplicate_layer_points_copied_live_captions_at_copied_anchored_objects() { + let mut s = crate::Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let base = s.doc().unwrap().doc.layers[0].id.0; + let a = s.execute("frame.create", &json!({"rect": [450, 450, 474, 490]})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.caption", &json!({"ids": [a], "text": "{name}", "live": true})).unwrap(); + let text = json!({"rect": [72, 72, 400, 400], "content": "text", "text": "Before after."}); + let f = s.execute("frame.create", &text).unwrap()["id"].as_u64().unwrap(); + let sid = s.doc().unwrap().doc.item(designcraft_doc::ItemId(f)).unwrap().text_frame().unwrap().story; + // The caption's source moves into the story and keeps its id. + s.execute("anchored.insert", &json!({"ids": [a], "story": sid.0, "pos": 7})).unwrap(); + let copy = s.execute("layer.duplicate", &json!({"id": base})).unwrap()["id"].as_u64().unwrap(); + let d = &s.doc().unwrap().doc; + let anchored = d.anchored_items().into_iter().map(|(_, i)| i).find(|i| i.layer.0 == copy).unwrap(); + assert_ne!(anchored.id.0, a); + let copies = on_layer(d, copy); + let caption = copies.iter().find_map(|i| i.live_caption.as_ref()).unwrap(); + assert_eq!(caption.source, anchored.id, "the caption's copy follows the anchored object's copy"); + } + + #[test] + fn duplicate_layer_copies_the_hyperlinks_of_its_objects_and_text() { + use designcraft_doc::{HyperlinkDest, HyperlinkSource}; + let mut s = crate::Session::new(); + s.execute("file.new", &json!({"pages": 2})).unwrap(); + let base = s.doc().unwrap().doc.layers[0].id.0; + let a = s.execute("frame.create", &json!({"rect": [72, 72, 172, 172]})).unwrap()["id"].as_u64().unwrap(); + s.execute("hyperlink.create", &json!({"ids": [a], "url": "https://example.com/a", "name": "Logo"})).unwrap(); + let t = s.execute("frame.create", &json!({"rect": [72, 200, 400, 300], "content": "text", "text": "Read more here"})).unwrap(); + let sid = s.doc().unwrap().doc.item(designcraft_doc::ItemId(t["id"].as_u64().unwrap())).unwrap().text_frame().unwrap().story; + s.execute("text.select", &json!({"story": sid.0, "anchor": 5, "focus": 9})).unwrap(); + s.execute("hyperlink.create", &json!({"page": 2})).unwrap(); + s.execute("layer.new", &json!({"name": "Art"})).unwrap(); + let other = s.execute("frame.create", &json!({"rect": [300, 72, 400, 172]})).unwrap()["id"].as_u64().unwrap(); + s.execute("hyperlink.create", &json!({"ids": [other], "email": "info@example.com"})).unwrap(); + let before = s.doc().unwrap().doc.hyperlinks.clone(); + let copy = s.execute("layer.duplicate", &json!({"id": base})).unwrap()["id"].as_u64().unwrap(); + let d = s.doc().unwrap().doc.clone(); + assert_eq!(d.hyperlinks[..3], before[..], "the original hyperlinks are unchanged"); + let copies = on_layer(&d, copy); + let frame = copies.iter().find(|i| i.text_frame().is_none()).unwrap().id; + let story = copies.iter().find_map(|i| i.text_frame()).unwrap().story; + let added = &d.hyperlinks[3..]; + assert_eq!(added.len(), 2, "the other layer's hyperlink gets no copy"); + assert_eq!((&added[0].name, &added[0].source, &added[0].dest), (&before[0].name, &HyperlinkSource::Item { id: frame }, &before[0].dest)); + assert_eq!(added[1].source, HyperlinkSource::Text { story, start: 5, end: 9 }); + assert_eq!((&added[1].name, &added[1].dest), (&before[1].name, &HyperlinkDest::Page(1))); + let ids: std::collections::HashSet = d.hyperlinks.iter().map(|h| h.id).collect(); + assert_eq!(ids.len(), 5, "each copy has an id of its own"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc.hyperlinks, before, "one undo step removes the copies"); + } + + #[test] + fn duplicate_layer_gives_copied_text_anchors_their_own_ids() { + let mut s = crate::Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let base = s.doc().unwrap().doc.layers[0].id.0; + let text = json!({"rect": [72, 72, 400, 400], "content": "text", "text": "Heading\rSee "}); + let f = s.execute("frame.create", &text).unwrap()["id"].as_u64().unwrap(); + let sid = s.doc().unwrap().doc.item(designcraft_doc::ItemId(f)).unwrap().text_frame().unwrap().story; + let anchor = s + .edit(|d, _| { + let a = d.paragraph_anchor(sid, 0).ok_or(designcraft_doc::DocError::NoStory(sid))?; + let format = d.xref_formats[0].name.clone(); + let st = d.story_mut(sid).ok_or(designcraft_doc::DocError::NoStory(sid))?; + let end = st.len(); + st.insert_xref(end, designcraft_doc::CrossRef { target: a, format, ..Default::default() }); + Ok(a) + }) + .unwrap(); + let copy = s.execute("layer.duplicate", &json!({"id": base})).unwrap()["id"].as_u64().unwrap(); + let d = &s.doc().unwrap().doc; + let copied = on_layer(d, copy)[0].text_frame().unwrap().story; + let (orig, st) = (d.story(sid).unwrap(), d.story(copied).unwrap()); + assert_eq!((orig.anchors[0].id, orig.xrefs[0].target), (anchor, anchor), "the original is unchanged"); + assert_ne!(st.anchors[0].id, anchor, "the copy's anchor has an id of its own"); + assert_eq!(st.anchors[0].name, orig.anchors[0].name); + assert_eq!(st.xrefs[0].target, st.anchors[0].id, "the copied cross-reference points at the copied paragraph"); + assert_eq!(d.find_anchor(st.anchors[0].id).map(|a| a.0), Some(copied)); + } + + #[test] + fn duplicate_layer_gives_copied_text_anchors_ids_no_other_anchor_has() { + use std::sync::Arc; + + let mut s = crate::Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let base = s.doc().unwrap().doc.layers[0].id.0; + let f = s.execute("frame.create", &json!({"rect": [72, 72, 400, 400], "content": "text", "text": "Head"})).unwrap()["id"].as_u64().unwrap(); + let sid = s.doc().unwrap().doc.item(designcraft_doc::ItemId(f)).unwrap().text_frame().unwrap().story; + s.execute("layer.new", &json!({"name": "Art"})).unwrap(); + let g = s.execute("frame.create", &json!({"rect": [72, 450, 400, 600], "content": "text", "text": "Other"})).unwrap()["id"].as_u64().unwrap(); + let other = s.doc().unwrap().doc.item(designcraft_doc::ItemId(g)).unwrap().text_frame().unwrap().story; + let d = Arc::make_mut(&mut s.doc_mut().unwrap().doc); + d.story_mut(sid).unwrap().insert_anchor(0, "Heading"); + // A story on another layer holds the ids the copy's first anchor would take, as anchors loaded from a file can. + let next = d.next_id; + let st = d.story_mut(other).unwrap(); + for k in 1..=64 { + st.insert_anchor(0, "Taken"); + Arc::make_mut(&mut st.anchors[0]).id = ((next + k) << 24) + 1; + } + s.execute("layer.duplicate", &json!({"id": base})).unwrap(); + let d = &s.doc().unwrap().doc; + let all: Vec = d.stories.values().flat_map(|st| st.anchors.iter().map(|a| a.id)).collect(); + assert_eq!(all.len(), 66); + let unique: std::collections::HashSet<_> = all.iter().collect(); + assert_eq!(unique.len(), all.len(), "the copied anchor has an id no other anchor has"); + } + + #[test] + fn duplicate_layer_remaps_anchors_in_cells_and_notes() { + use designcraft_doc::Story; + use std::sync::Arc; + + fn add_anchor(st: &mut Story, id: u64) { + st.insert_anchor(0, "Nested heading"); + Arc::make_mut(&mut st.anchors[0]).id = id; + st.insert_xref(st.len(), designcraft_doc::CrossRef { target: id, ..Default::default() }); + } + fn collect(st: &Story, values: &mut Vec<(u64, u64)>) { + for (a, x) in st.anchors.iter().zip(st.xrefs.iter()) { + values.push((a.id, x.target)); + } + for table in st.tables.values() { + for cell in &table.cells { + collect(&cell.text, values); + } + } + for note in st.notes.iter().chain(st.endnotes.iter()) { + collect(¬e.text, values); + } + } + let mut s = crate::Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let base = s.doc().unwrap().doc.layers[0].id.0; + let f = s.execute("frame.create", &json!({"rect": [72, 72, 400, 400], "content": "text", "text": "Rows"})).unwrap()["id"].as_u64().unwrap(); + let sid = s.doc().unwrap().doc.item(designcraft_doc::ItemId(f)).unwrap().text_frame().unwrap().story; + let d = Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let table_id = d.alloc(); + let nested_id = d.alloc(); + let anchor_ids = [d.alloc(), d.alloc(), d.alloc(), d.alloc()]; + let mut table = designcraft_doc::Table::new(table_id, 1, 1, 0, 0, 40.0); + let cell = &mut table.cells[0].text; + add_anchor(cell, anchor_ids[0]); + let mut nested = designcraft_doc::Table::new(nested_id, 1, 1, 0, 0, 20.0); + add_anchor(&mut nested.cells[0].text, anchor_ids[1]); + cell.insert_table(cell.len(), nested); + cell.insert_note(cell.len(), "Footnote", Default::default()).unwrap(); + add_anchor(&mut Arc::make_mut(&mut cell.notes[0]).text, anchor_ids[2]); + cell.insert_endnote(cell.len(), "Endnote", Default::default()).unwrap(); + add_anchor(&mut Arc::make_mut(&mut cell.endnotes[0]).text, anchor_ids[3]); + d.story_mut(sid).unwrap().insert_table(0, table); + let mut original = Vec::new(); + collect(d.story(sid).unwrap(), &mut original); + assert_eq!(original.len(), 4); + let copy = s.execute("layer.duplicate", &json!({"id": base})).unwrap()["id"].as_u64().unwrap(); + let d = &s.doc().unwrap().doc; + let copied = on_layer(d, copy)[0].text_frame().unwrap().story; + let mut after = Vec::new(); + collect(d.story(copied).unwrap(), &mut after); + assert_eq!(after.len(), original.len()); + let unique: std::collections::HashSet<_> = after.iter().map(|(id, _)| *id).collect(); + assert_eq!(unique.len(), after.len()); + for (id, target) in &after { + assert!(!anchor_ids.contains(id), "copied nested anchor retains original id {id}"); + assert_eq!(id, target, "copied reference points to its copied anchor"); + } + let mut unchanged = Vec::new(); + collect(d.story(sid).unwrap(), &mut unchanged); + assert_eq!(unchanged, original); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.redo", &json!({})).unwrap(); + let mut redone = Vec::new(); + collect(s.doc().unwrap().doc.story(copied).unwrap(), &mut redone); + assert_eq!(redone, after); + } + + #[test] + fn duplicate_layer_gives_objects_anchored_in_endnotes_of_cells_their_own_ids() { + use designcraft_doc::AnchoredObject; + use std::sync::Arc; + + let mut s = crate::Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let base = s.doc().unwrap().doc.layers[0].id.0; + let a = s.execute("frame.create", &json!({"rect": [450, 450, 474, 490]})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.caption", &json!({"ids": [a], "text": "{name}", "live": true})).unwrap(); + let f = s.execute("frame.create", &json!({"rect": [72, 72, 400, 400], "content": "text", "text": "Rows"})).unwrap()["id"].as_u64().unwrap(); + let sid = s.doc().unwrap().doc.item(designcraft_doc::ItemId(f)).unwrap().text_frame().unwrap().story; + let d = Arc::make_mut(&mut s.doc_mut().unwrap().doc); + // The caption's source moves into an endnote of a table cell and keeps its id. + let it = d.item(designcraft_doc::ItemId(a)).cloned().unwrap(); + Arc::make_mut(&mut d.spreads[0]).items.retain(|i| i.id.0 != a); + let mut table = designcraft_doc::Table::new(d.alloc(), 1, 1, 0, 0, 40.0); + let cell = &mut table.cells[0].text; + cell.insert_endnote(cell.len(), "Endnote", Default::default()).unwrap(); + Arc::make_mut(&mut cell.endnotes[0]).text.insert_object(0, AnchoredObject::new(it, Default::default())); + d.story_mut(sid).unwrap().insert_table(0, table); + d.check().unwrap(); + let copy = s.execute("layer.duplicate", &json!({"id": base})).unwrap()["id"].as_u64().unwrap(); + let d = &s.doc().unwrap().doc; + d.check().unwrap(); + let anchored: Vec<_> = d.anchored_items().into_iter().map(|(_, i)| (i.id, i.layer.0)).collect(); + assert_eq!(anchored.len(), 2); + let copied = anchored.iter().find(|i| i.1 == copy).unwrap().0; + assert_ne!(copied.0, a, "the copy has an id of its own"); + let caption = on_layer(d, copy).iter().find_map(|i| i.live_caption.clone()).unwrap(); + assert_eq!(caption.source, copied, "the caption's copy follows the anchored object's copy"); + } + + #[test] + fn duplicate_layer_gives_copied_cell_anchors_ids_no_other_anchor_has() { + use std::sync::Arc; + + fn ids(st: &designcraft_doc::Story, out: &mut Vec) { + out.extend(st.anchors.iter().map(|a| a.id)); + for table in st.tables.values() { + for cell in &table.cells { + ids(&cell.text, out); + } + } + } + let mut s = crate::Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let base = s.doc().unwrap().doc.layers[0].id.0; + let f = s.execute("frame.create", &json!({"rect": [72, 72, 400, 400], "content": "text", "text": "Rows"})).unwrap()["id"].as_u64().unwrap(); + let sid = s.doc().unwrap().doc.item(designcraft_doc::ItemId(f)).unwrap().text_frame().unwrap().story; + let d = Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let table_id = d.alloc(); + // The cell's anchors take the ids the document hands out next, as anchors made in a cell story can. + let start = d.alloc(); + let mut table = designcraft_doc::Table::new(table_id, 1, 1, 0, 0, 40.0); + let cell = &mut table.cells[0].text; + for k in 1..=64 { + cell.insert_anchor(0, "Heading"); + Arc::make_mut(&mut cell.anchors[0]).id = start + k; + } + d.story_mut(sid).unwrap().insert_table(0, table); + let mut original = Vec::new(); + ids(d.story(sid).unwrap(), &mut original); + assert_eq!(original.len(), 64); + let copy = s.execute("layer.duplicate", &json!({"id": base})).unwrap()["id"].as_u64().unwrap(); + let d = &s.doc().unwrap().doc; + let copied = on_layer(d, copy)[0].text_frame().unwrap().story; + let mut after = Vec::new(); + ids(d.story(copied).unwrap(), &mut after); + assert_eq!(after.len(), original.len()); + for id in &after { + assert!(!original.contains(id), "copied cell anchor {id} has the id of an original anchor"); + } + } + + #[test] + fn duplicate_layer_gives_copied_tables_their_own_ids() { + let mut s = crate::Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let base = s.doc().unwrap().doc.layers[0].id.0; + let text = json!({"rect": [72, 72, 400, 400], "content": "text", "text": "Rows"}); + let f = s.execute("frame.create", &text).unwrap()["id"].as_u64().unwrap(); + let sid = s.doc().unwrap().doc.item(designcraft_doc::ItemId(f)).unwrap().text_frame().unwrap().story; + s.execute("text.select", &json!({"story": sid.0, "anchor": 4, "focus": 4})).unwrap(); + let table = s.execute("table.insert", &json!({"rows": 1, "cols": 2})).unwrap()["table"].as_u64().unwrap(); + let copy = s.execute("layer.duplicate", &json!({"id": base})).unwrap()["id"].as_u64().unwrap(); + let d = &s.doc().unwrap().doc; + let copied = on_layer(d, copy)[0].text_frame().unwrap().story; + let st = d.story(copied).unwrap(); + let tables: Vec = st.tables.keys().copied().collect(); + assert_eq!(tables.len(), 1); + let new = tables[0]; + assert_ne!(new, table, "the copy's table has an id of its own"); + assert_eq!(st.tables[&new].id, new); + assert_eq!(st.paras.iter().filter_map(|pf| pf.table).collect::>(), [new], "the copied paragraph holds the copied table"); + d.check().unwrap(); + s.execute("table.insertRow", &json!({"table": new})).unwrap(); + let d = &s.doc().unwrap().doc; + assert_eq!(d.story(sid).unwrap().tables[&table].nrows(), 1, "the original table is unchanged"); + assert_eq!(d.story(copied).unwrap().tables[&new].nrows(), 2, "a command naming the copy's table changes the copy"); + } + + #[test] + fn duplicate_layer_gives_tables_in_copied_cells_their_own_ids() { + let mut s = crate::Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let base = s.doc().unwrap().doc.layers[0].id.0; + let text = json!({"rect": [72, 72, 400, 400], "content": "text", "text": "Rows"}); + let f = s.execute("frame.create", &text).unwrap()["id"].as_u64().unwrap(); + let sid = s.doc().unwrap().doc.item(designcraft_doc::ItemId(f)).unwrap().text_frame().unwrap().story; + s.execute("text.select", &json!({"story": sid.0, "anchor": 4, "focus": 4})).unwrap(); + let table = s.execute("table.insert", &json!({"rows": 1, "cols": 2})).unwrap()["table"].as_u64().unwrap(); + let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let inner = d.alloc(); + let deepest = d.alloc(); + let mut nested = designcraft_doc::Table::new(inner, 1, 1, 0, 0, 40.0); + nested.cells[0].text.insert_table(0, designcraft_doc::Table::new(deepest, 1, 1, 0, 0, 20.0)); + d.story_mut(sid).unwrap().table_mut(table).unwrap().cells[0].text.insert_table(0, nested); + let copy = s.execute("layer.duplicate", &json!({"id": base})).unwrap()["id"].as_u64().unwrap(); + let d = &s.doc().unwrap().doc; + let copied = on_layer(d, copy)[0].text_frame().unwrap().story; + let outer = d.story(copied).unwrap().tables.values().next().unwrap(); + let cell = &outer.cells[0].text; + let new_inner = *cell.tables.keys().next().unwrap(); + assert_ne!(new_inner, inner, "a table in a copied cell has an id of its own"); + assert_eq!(cell.tables[&new_inner].id, new_inner); + assert_eq!(cell.paras.iter().filter_map(|pf| pf.table).collect::>(), [new_inner], "the copied cell holds the copied table"); + let inner_cell = &cell.tables[&new_inner].cells[0].text; + let new_deepest = *inner_cell.tables.keys().next().unwrap(); + assert_ne!(new_deepest, deepest, "a table nested deeper has an id of its own"); + assert_eq!(inner_cell.paras.iter().filter_map(|pf| pf.table).collect::>(), [new_deepest]); + let ids = [outer.id, new_inner, new_deepest, table, inner, deepest]; + assert_eq!(ids.iter().collect::>().len(), ids.len(), "every table id is unique: {ids:?}"); + let orig = d.story(sid).unwrap().tables[&table].cells[0].text.tables.keys().copied().collect::>(); + assert_eq!(orig, [inner], "the original's nested table keeps its id"); + } + + #[test] + fn duplicate_layer_numbers_copied_tables_and_anchored_objects_in_story_order() { + let mut s = crate::Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let base = s.doc().unwrap().doc.layers[0].id.0; + for k in 0..8 { + let y = 72 + 80 * k; + let text = json!({"rect": [72, y, 400, y + 60], "content": "text", "text": "Rows"}); + let f = s.execute("frame.create", &text).unwrap()["id"].as_u64().unwrap(); + let sid = s.doc().unwrap().doc.item(designcraft_doc::ItemId(f)).unwrap().text_frame().unwrap().story; + s.execute("text.select", &json!({"story": sid.0, "anchor": 4, "focus": 4})).unwrap(); + s.execute("table.insert", &json!({"rows": 1, "cols": 2})).unwrap(); + let b = s.execute("frame.create", &json!({"rect": [450, y, 474, y + 40]})).unwrap()["id"].as_u64().unwrap(); + s.execute("anchored.insert", &json!({"ids": [b], "story": sid.0, "pos": 0})).unwrap(); + } + let copy = s.execute("layer.duplicate", &json!({"id": base})).unwrap()["id"].as_u64().unwrap(); + let d = &s.doc().unwrap().doc; + d.check().unwrap(); + let mut stories: Vec<_> = on_layer(d, copy).iter().filter_map(|i| i.text_frame().map(|t| t.story)).collect(); + stories.sort_unstable(); + assert_eq!(stories.len(), 8); + let tables: Vec = stories.iter().map(|sid| *d.story(*sid).unwrap().tables.keys().next().unwrap()).collect(); + let objects: Vec = stories.iter().map(|sid| d.story(*sid).unwrap().objects[0].item.id.0).collect(); + assert!(tables.is_sorted(), "the copied tables take ids in story order: {tables:?}"); + assert!(objects.is_sorted(), "the copied anchored objects take ids in story order: {objects:?}"); + } + + /// 40 stories, each holding two anchored text frames threaded in the next: 2^40 paths, 40 stories. + #[test] + fn duplicate_layer_checks_each_shared_story_once() { + let mut s = crate::Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let base = s.doc().unwrap().doc.layers[0].id.0; + let f = s.execute("frame.create", &json!({"rect": [72, 72, 400, 400], "content": "text", "text": "Top"})).unwrap()["id"].as_u64().unwrap(); + let top = s.doc().unwrap().doc.item(designcraft_doc::ItemId(f)).unwrap().text_frame().unwrap().story; + s.edit(|d, _| { + use designcraft_doc::{AnchoredObject, ParaFormat}; + let r = designcraft_geom::Rect::new(0.0, 0.0, 60.0, 30.0); + let mut outer = top; + for _ in 0..40 { + let (a, inner) = d.add_text_frame(designcraft_doc::SpreadRef::Doc(0), r, d.default_layer(), "Link", ParaFormat::default())?; + let (b, spare) = d.add_text_frame(designcraft_doc::SpreadRef::Doc(0), r, d.default_layer(), "", ParaFormat::default())?; + let mut items = Vec::new(); + for f in [a, b] { + let mut it = d.item(f).cloned().ok_or(designcraft_doc::DocError::NoItem(f))?; + if let designcraft_doc::Content::Text(tf) = &mut it.content { + tf.story = inner; + } + items.push(it); + } + d.stories.remove(&spare); + d.story_mut(inner).ok_or(designcraft_doc::DocError::NoStory(inner))?.frames = vec![a, b]; + std::sync::Arc::make_mut(&mut d.spreads[0]).items.retain(|i| i.id != a && i.id != b); + let st = d.story_mut(outer).ok_or(designcraft_doc::DocError::NoStory(outer))?; + for it in items.into_iter().rev() { + st.insert_object(0, AnchoredObject::new(it, Default::default())); + } + outer = inner; + } + Ok(()) + }) + .unwrap(); + s.doc().unwrap().doc.check().unwrap(); + let before = s.doc().unwrap().doc.stories.len(); + s.execute("layer.duplicate", &json!({"id": base})).unwrap(); + let d = &s.doc().unwrap().doc; + d.check().unwrap(); + assert_eq!(d.stories.len(), 2 * before, "one copy of each story"); + } + + #[test] + fn duplicate_layer_refuses_objects_nested_too_deeply() { + let mut s = crate::Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let base = s.doc().unwrap().doc.layers[0].id.0; + let mut g = s.execute("frame.create", &json!({"rect": [0, 0, 10, 10]})).unwrap()["id"].as_u64().unwrap(); + for _ in 0..super::MAX_COPY_DEPTH + 1 { + let f = s.execute("frame.create", &json!({"rect": [0, 0, 10, 10]})).unwrap()["id"].as_u64().unwrap(); + g = s.execute("object.group", &json!({"ids": [g, f]})).unwrap()["id"].as_u64().unwrap(); + } + let before = s.doc().unwrap().doc.layers.clone(); + assert!(s.execute("layer.duplicate", &json!({"id": base})).is_err()); + assert_eq!(s.doc().unwrap().doc.layers, before, "nothing changes"); + } + + /// Two stories, each anchoring groups nested 40 deep, the innermost group of the first holding a text frame that + /// shows the second: within the limit in each story, past it in all. + #[test] + fn duplicate_layer_refuses_nesting_too_deep_across_stories() { + use designcraft_doc::{AnchoredObject, Content, Item, ItemId}; + use std::sync::Arc; + + fn nest(d: &mut designcraft_doc::Document, mut it: Item, levels: usize) -> Item { + for _ in 0..levels { + let mut group = it.clone(); + group.id = ItemId(d.alloc()); + group.content = Content::Group { items: vec![Arc::new(it)] }; + it = group; + } + it + } + let mut s = crate::Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let base = s.doc().unwrap().doc.layers[0].id.0; + let f = s.execute("frame.create", &json!({"rect": [72, 72, 400, 400], "content": "text", "text": "Top"})).unwrap()["id"].as_u64().unwrap(); + let g = s.execute("frame.create", &json!({"rect": [0, 0, 60, 30], "content": "text", "text": "Inner"})).unwrap()["id"].as_u64().unwrap(); + let h = s.execute("frame.create", &json!({"rect": [0, 0, 10, 10]})).unwrap()["id"].as_u64().unwrap(); + let d = Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let top = d.item(ItemId(f)).unwrap().text_frame().unwrap().story; + let (inner_frame, leaf) = (d.item(ItemId(g)).cloned().unwrap(), d.item(ItemId(h)).cloned().unwrap()); + let inner = inner_frame.text_frame().unwrap().story; + Arc::make_mut(&mut d.spreads[0]).items.retain(|i| i.id.0 != g && i.id.0 != h); + let deep_leaf = nest(d, leaf, 40); + d.story_mut(inner).unwrap().insert_object(0, AnchoredObject::new(deep_leaf, Default::default())); + let deep_frame = nest(d, inner_frame, 40); + d.story_mut(top).unwrap().insert_object(0, AnchoredObject::new(deep_frame, Default::default())); + let before = s.doc().unwrap().doc.layers.clone(); + assert!(s.execute("layer.duplicate", &json!({"id": base})).is_err()); + assert_eq!(s.doc().unwrap().doc.layers, before, "nothing changes"); + } + + /// An empty group inside 64 others: within the layer's depth check, which counts the objects below a group, but + /// past the limit of the copy, which counts the group itself. + #[test] + fn duplicate_layer_refuses_an_empty_group_at_the_copy_limit() { + use designcraft_doc::{Content, ItemId}; + use std::sync::Arc; + + let mut s = crate::Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let base = s.doc().unwrap().doc.layers[0].id.0; + let f = s.execute("frame.create", &json!({"rect": [0, 0, 10, 10]})).unwrap()["id"].as_u64().unwrap(); + let d = Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let mut it = d.item(ItemId(f)).cloned().unwrap(); + it.content = Content::Group { items: Vec::new() }; + for _ in 0..super::MAX_COPY_DEPTH { + let mut group = it.clone(); + group.id = ItemId(d.alloc()); + group.content = Content::Group { items: vec![Arc::new(it)] }; + it = group; + } + let items = &mut Arc::make_mut(&mut d.spreads[0]).items; + items.retain(|i| i.id.0 != f); + items.push(Arc::new(it)); + let before = s.doc().unwrap().doc.clone(); + let e = s.execute("layer.duplicate", &json!({"id": base})).unwrap_err().to_string(); + assert!(e.contains("too deeply to copy"), "{e}"); + assert_eq!(s.doc().unwrap().doc, before, "nothing changes"); + } + + #[test] + fn duplicate_layer_detaches_overrides_of_parent_items_on_other_layers() { + let mut s = crate::Session::new(); + s.execute("file.new", &json!({"pages": 2, "facingPages": false})).unwrap(); + let base = s.doc().unwrap().doc.layers[0].id.0; + s.execute("layer.new", &json!({"name": "Art"})).unwrap(); + let logo = json!({"spread": {"kind": "parent", "index": 0}, "rect": [72, 72, 144, 144]}); + let parent = s.execute("frame.create", &logo).unwrap()["id"].as_u64().unwrap(); + let o = s.execute("layout.overrideParentItems", &json!({"page": 1})).unwrap()["ids"][0].as_u64().unwrap(); + s.execute("selection.set", &json!({"ids": [o]})).unwrap(); + s.execute("object.setLayer", &json!({"layer": base})).unwrap(); + let copy = s.execute("layer.duplicate", &json!({"id": base})).unwrap()["id"].as_u64().unwrap(); + let d = &s.doc().unwrap().doc; + let copies = on_layer(d, copy); + assert_eq!(copies.len(), 1, "the override only: the parent item is on Art"); + assert_eq!(copies[0].overrides, None, "a plain object, so the original override stays the only one"); + assert_eq!(d.item(designcraft_doc::ItemId(o)).unwrap().overrides, Some(designcraft_doc::ItemId(parent))); + let (si, pi) = d.page_loc(1).unwrap(); + assert_eq!(d.spreads[si].pages[pi].overridden, [designcraft_doc::ItemId(parent)]); + } } #[cfg(test)] diff --git a/crates/engine/src/cmd/layout/registry.rs b/crates/engine/src/cmd/layout/registry.rs index 2140d35d8..f120c80f6 100644 --- a/crates/engine/src/cmd/layout/registry.rs +++ b/crates/engine/src/cmd/layout/registry.rs @@ -1,4 +1,4 @@ -use super::layers::set_layer; +use super::layers::{duplicate_layer, set_layer}; use super::margins::{adjust_layout, column_guides_unlocked, margin_boxes, move_column_guide, set_margins_columns, set_page_width}; use super::pages::{document_setup, page_options, page_size}; use super::parents::{ @@ -713,6 +713,15 @@ pub fn specs() -> Vec { s.doc_mut()?.active_layer = r; Ok(json!({"id": r.0})) }), + cmd!( + "layer.duplicate", + "Duplicate Layer", + [], + None, + "{id} → {id}. Adds a copy of the layer's settings and objects (document and parent spreads) above it, named \" copy\"", + has_doc, + duplicate_layer + ), cmd!( "layer.set", "Layer Options…", diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs index 22e31cf64..f048ba98b 100644 --- a/crates/engine/src/cmd/links.rs +++ b/crates/engine/src/cmd/links.rs @@ -1,9 +1,14 @@ //! Window › Links: placed graphics with their status, effective resolution and uses; relink, //! update, embed, go to. //! -//! Every placed graphic keeps its bytes in the document; a linked graphic also remembers its -//! file. Its status compares that file with the copy in the document: missing, modified (the -//! file's bytes differ) or OK. +//! A graphic placed from a file links to it ([`Storage::Linked`]): the document keeps the file's +//! path (absolute, and relative to the document), size, time and content hash, and a proxy +//! image; the bytes are read from the file when needed. Its status is OK while a file at one of +//! those paths holds the recorded bytes (same size and time, or the same hash), Modified when +//! files are there with other bytes, and Missing otherwise. Embed copies the bytes into the +//! document and keeps the link record, so Unembed can link to the file again. An embedded copy +//! from a document saved before linked storage (a link without a hash) is compared with its file +//! byte for byte. //! //! A linked text file (File › Place with Create Links) remembers its file's size and hash on the //! story instead; updating it imports the file again into the story. @@ -16,7 +21,9 @@ use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; use designcraft_compose::Cache; -use designcraft_doc::{AssetId, Content, Document, Fingerprint, Item, ItemId, Selection, Story, StoryId, TextFileLink}; +use designcraft_doc::{ + Asset, AssetData, AssetId, Content, Document, Fingerprint, Item, ItemId, LinkedSource, Selection, Storage, Story, StoryId, TextFileLink, +}; use designcraft_geom::Affine; use serde_json::{Value, json}; @@ -25,10 +32,10 @@ use crate::{EngineError, Result, Session}; pub fn specs() -> Vec { vec![ - cmd!(query "links.list", "Links", [], None, "{} → [{asset, name, path, status: ok|modified|missing|embedded, refused?: why a missing link isn't followed (a path on another computer, a device), pixels, pdfCrop (placed PDFs: the box shown), uses: [{id, page, ppi}]}], then linked text files: [{story, name, path, status (also tooLarge: unchanged size, too big to check), edited (the story was changed in the layout), uses: [{id, page}]}]", has_doc, |s, _| { + cmd!(query "links.list", "Links", [], None, "{} → [{asset, name, path, storage: linked|embedded (where a save keeps the bytes), status: ok|modified|missing|embedded|checking (a linked file still being hashed), refused?: why a missing link isn't followed (a path on another computer, a device), pixels, pdfCrop (placed PDFs: the box shown), uses: [{id, page, ppi}]}], then linked text files: [{story, name, path, status (also tooLarge: unchanged size, too big to check), edited (the story was changed in the layout), uses: [{id, page}]}]", has_doc, |s, _| { // Taken out for the call so the document needn't be cloned on every poll. let mut checks = std::mem::take(&mut s.link_checks); - let links = s.doc().map(|d| list(&d.doc, &s.cache, d.path.as_deref().map(Path::new), Some(&mut checks), None).unwrap_or_default()); + let links = s.doc().map(|d| list(&d.doc, &s.cache, d.path.as_deref().map(Path::new), Some(&mut checks), None, Some(&d.links)).unwrap_or_default()); s.link_checks = checks; Ok(Value::Array(links?)) }), @@ -64,22 +71,18 @@ pub fn specs() -> Vec { "Embed Link", ["Window", "Links"], None, - "{asset | story} — keep only the copy in the document (a text file: unlink the story)", + "{asset | story} — copy a linked graphic's file into the document (its link is kept for Unembed); fails when the file is missing or has changed (update or relink it first). A text file: unlink the story", has_doc, - |s, p| { - if let Some(sid) = story_param(p) { - return s.edit(|d, _| { - d.story_mut(sid).ok_or_else(|| bad("links.embed", "no such story"))?.file_link = None; - Ok(Value::Null) - }); - } - let aid = asset_param(p, "links.embed")?; - s.edit(|d, _| { - let a = d.assets.get_mut(&aid).ok_or_else(|| bad("links.embed", "no such graphic"))?; - Arc::make_mut(a).set_link(None, None); - Ok(Value::Null) - }) - } + embed + ), + cmd!( + "links.unembed", + "Unembed Link…", + ["Window", "Links"], + None, + "{asset, dir?} — link an embedded graphic to a file instead of keeping it in the document: its original file when that still holds the same bytes, else a file written into `dir` (an existing one with the same bytes is reused) → {path}. Not on the web", + can_unembed, + unembed ), cmd!(noundo "links.goTo", "Go To Link", ["Window", "Links"], None, "{asset | story} — selects the frames showing the graphic or the linked text", has_doc, |s, p| { let st = s.doc_mut()?; @@ -145,6 +148,12 @@ pub fn link_missing(a: &designcraft_doc::Asset, document: Option<&Path>) -> bool let Some(link) = &a.link else { return false }; #[cfg(not(target_arch = "wasm32"))] { + if a.storage == Storage::Linked { + return match LinkedSource::of(a, document) { + Some(source) => !crate::asset_io::candidates(&source).iter().any(crate::io::is_file), + None => true, + }; + } !crate::io::document_path(link, document).is_ok_and(crate::io::exists) } #[cfg(target_arch = "wasm32")] @@ -157,10 +166,10 @@ pub fn link_missing(a: &designcraft_doc::Asset, document: Option<&Path>) -> bool /// Linked images checked this session: (asset, the identity of its bytes, the file its link /// resolves to) → (the file's size and time when it was read, whether it matched the bytes). The /// resolved file, not the link text, is the key: a relative link names another file once the -/// document is saved elsewhere. The bytes' identity (their `Arc`'s address, as the render cache -/// keys them) changes with every relink, update or undo, so a remembered answer can never -/// describe other bytes. -pub(crate) type ImageChecks = std::collections::HashMap<(AssetId, usize, std::path::PathBuf), (Fingerprint, bool)>; +/// document is saved elsewhere. The bytes' [`designcraft_doc::SourceKey`] (as the render cache +/// keys them) changes with every relink or update and is never reused, so a remembered answer +/// can never describe other bytes. +pub(crate) type ImageChecks = std::collections::HashMap<(AssetId, designcraft_doc::SourceKey, std::path::PathBuf), (Fingerprint, bool)>; /// The size and time to keep with `bytes` just read from a linked file, `before` being the /// file's from before the read. Kept only when they can vouch for the bytes later: the size is @@ -171,6 +180,216 @@ pub(crate) fn loaded_fingerprint(before: Option, bytes: &[u8]) -> O before.filter(|f| f.size == bytes.len() as u64 && settled(f)) } +/// The modification time kept with a linked file whose time couldn't vouch for its bytes when +/// they were read ([`loaded_fingerprint`]): no file has it, so the file is told by its hash until +/// a check finds it holding the bytes and keeps its real time ([`remember_link_files`]). +pub(crate) const UNVERIFIED_MTIME: i64 = i64::MIN; + +/// The file bytes for a graphic were just read from. +pub(crate) struct FileLink { + /// The file's absolute path. + path: String, + /// Its size and time from before the read. + before: Option, +} + +impl FileLink { + pub(crate) fn of(path: &Path, before: Option) -> Self { + let path = std::path::absolute(path).unwrap_or_else(|_| path.to_path_buf()).to_string_lossy().into_owned(); + FileLink { path, before } + } +} + +/// The proxy a linked graphic is drawn with while its file can't be read: none for video and +/// sound, or a file that doesn't decode. +pub(super) fn proxy_of(a: &Asset, bytes: &[u8]) -> Option { + if a.mime.starts_with("video/") || a.mime.starts_with("audio/") { + return None; + } + let p = designcraft_render::proxy::make_proxy(bytes, a.page)?; + Some(designcraft_doc::Proxy { mime: p.mime.into(), pixels: p.pixels, data: AssetData::embedded(p.data) }) +} + +/// Give `a` the bytes of a graphic being placed, relinked or updated (its `mime` and `page` set). +/// Bytes read from a file (`file`) link to it ([`link_to_file`]), unless `embed` or on the web, +/// where they are embedded with the link record kept. Other bytes (pasted, dropped, base64) are +/// embedded without a link. +pub(crate) fn give_bytes(a: &mut Asset, bytes: impl Into>>, file: Option, embed: bool, document: Option<&Path>) { + let bytes: Arc> = bytes.into(); + a.proxy = None; + let Some(file) = file else { + a.set_link(None, None); + a.link_relative = None; + a.link_hash = None; + a.storage = Storage::Embedded; + a.data = AssetData::embedded(bytes); + return; + }; + if embed || cfg!(target_arch = "wasm32") { + record_file(a, &bytes, file, document); + a.link_hash = Some(crate::asset_io::content_hash(&bytes)); + a.storage = Storage::Embedded; + a.data = AssetData::embedded(bytes); + return; + } + link_to_file(a, bytes, file, document, None); +} + +/// [`give_bytes`] for a graphic being placed, leaving out the work that grows with the file: the +/// graphic links to its file at once, with the file's size and time as its fingerprint and the +/// bytes just read kept in memory for drawing, and its content hash and proxy are made in the +/// background ([`super::native_links::prepare`] the returned work once the asset is in the +/// document; [`add_prepared`] adds them). A link without a hash is complete: its status goes by +/// size and time until the hash is in. Placing many press-size images would otherwise decode and +/// hash each one before the app responds again. Embedded placements, bytes without a file and +/// the web (no threads) are [`give_bytes`]. +#[must_use = "the hash and proxy are made only once the returned work is queued"] +pub(crate) fn give_placed( + a: &mut Asset, + bytes: impl Into>>, + file: Option, + embed: bool, + document: Option<&Path>, +) -> Option { + let bytes: Arc> = bytes.into(); + let file = match file { + Some(file) if !embed && cfg!(not(target_arch = "wasm32")) => file, + file => { + give_bytes(a, bytes, file, embed, document); + return None; + } + }; + record_file(a, &bytes, file, document); + a.link_hash = None; + link_recorded(a, Arc::clone(&bytes), designcraft_doc::SourceKey::fresh(), document, |_, _| None); + Some(super::native_links::Pending::of(a, bytes)) +} + +/// Link `a` to `file`, whose bytes (`bytes`) were just read: the file's record (paths, size and +/// time, content hash) and a proxy to draw while the file can't be read (`preview` when there is +/// one, else made from the bytes). The bytes stay in memory for the first draw. +pub(crate) fn link_to_file(a: &mut Asset, bytes: Arc>, file: FileLink, document: Option<&Path>, preview: Option) { + record_file(a, &bytes, file, document); + a.link_hash = Some(crate::asset_io::content_hash(&bytes)); + link_recorded(a, bytes, designcraft_doc::SourceKey::fresh(), document, |a, bytes| preview.or_else(|| proxy_of(a, bytes))); +} + +/// Add to a graphic placed with [`give_placed`] (or opened with a link that has no hash) its +/// content `hash` and `proxy`, made from the bytes it has under its current key: the hash when it +/// has none, the proxy when it is linked and has none. Its storage stays as it is (a graphic +/// embedded since with Links › Embed stays embedded). → whether `a` changed. +pub(super) fn add_prepared(a: &mut Asset, hash: &str, proxy: Option<&designcraft_doc::Proxy>) -> bool { + let mut changed = false; + if a.link_hash.is_none() { + a.link_hash = Some(hash.to_owned()); + // The same bytes: the key stays, so nothing decoded from them is decoded again. + if let Some(mut source) = a.data.linked_source().cloned() { + source.hash = Some(hash.to_owned()); + a.data = AssetData::linked_under(a.data.key(), source); + } + changed = true; + } + if a.storage == Storage::Linked + && a.proxy.is_none() + && let Some(proxy) = proxy + { + a.proxy = Some(proxy.clone()); + changed = true; + } + changed +} + +/// `a`, whose link record is complete, as a link to its file under `key`: drawn with `proxy`'s +/// image while the file can't be read, and `bytes` (just read from the file) kept in memory for +/// the first draw. Embedded under `key` when the record doesn't name a file. +fn link_recorded( + a: &mut Asset, + bytes: Arc>, + key: designcraft_doc::SourceKey, + document: Option<&Path>, + proxy: impl FnOnce(&Asset, &[u8]) -> Option, +) { + a.link_fingerprint = Some(a.link_fingerprint.unwrap_or(Fingerprint { size: bytes.len() as u64, mtime: UNVERIFIED_MTIME })); + let Some(source) = LinkedSource::of(a, document) else { + a.storage = Storage::Embedded; + a.proxy = None; + a.data = AssetData::embedded_under(key, bytes); + return; + }; + a.storage = Storage::Linked; + a.proxy = proxy(a, &bytes); + a.data = AssetData::linked_under(key, source); + a.data.keep_resident(bytes); +} + +/// Keep with `a` the record of `file`, which `bytes` were read from: its absolute path, its path +/// relative to the `document` file and the size and time that vouch for the bytes +/// ([`loaded_fingerprint`]). The caller sets the content hash. +fn record_file(a: &mut Asset, bytes: &[u8], file: FileLink, document: Option<&Path>) { + a.link_fingerprint = loaded_fingerprint(file.before, bytes); + a.link_relative = document.and_then(|d| super::native_links::relative_to(d, Path::new(&file.path))); + a.link = Some(file.path); +} + +/// Does `bytes` (a file's) hold `a`'s bytes: its recorded hash, or, without one, its bytes? +#[cfg(not(target_arch = "wasm32"))] +fn holds(a: &Asset, bytes: &[u8]) -> bool { + match &a.link_hash { + Some(hash) => *hash == crate::asset_io::content_hash(bytes), + None => a.data.resident().is_some_and(|d| *d == bytes), + } +} + +/// Status of a linked graphic: OK when a file at its absolute or relative path has the recorded +/// size and time (nothing is read), or the recorded size and the recorded bytes (hashed once per +/// new time, `checks`); Modified when files are there and none holds them; Missing when none is. +fn linked_status(a: &Asset, document: Option<&Path>, checks: &mut ImageChecks) -> (&'static str, Option) { + let Some(source) = LinkedSource::of(a, document) else { return ("missing", None) }; + #[cfg(not(target_arch = "wasm32"))] + { + let mut status = "missing"; + for path in crate::asset_io::candidates(&source) { + let Some(meta) = crate::io::file_metadata(&path) else { continue }; + let now = crate::asset_io::fingerprint_from(&meta); + if Some(now) == source.fingerprint && settled(&now) { + return ("ok", None); + } + status = "modified"; + if now.size != source.len { + continue; + } + let key = (a.id, a.data.key(), path.clone()); + let same = match checks.get(&key) { + Some((at, same)) if *at == now => *same, + _ => { + let Ok(bytes) = crate::io::read_capped(&path, source.len) else { continue }; + let same = bytes.len() as u64 == source.len && holds(a, &bytes); + if settled(&now) { + checks.insert(key, (now, same)); + } + same + } + }; + if same { + return ("ok", settled(&now).then_some(now)); + } + } + (status, None) + } + #[cfg(target_arch = "wasm32")] + { + let _ = (source, checks); + ("missing", None) + } +} + +/// Whether a linked image's files are there and none holds its bytes ([`linked_status`] +/// "modified"): Preflight's check, which reads a file only as the Links panel does, once per new +/// size and time (`checks`). +pub(crate) fn link_modified(a: &Asset, document: Option<&Path>, checks: &mut LinkListChecks) -> bool { + a.storage == Storage::Linked && linked_status(a, document, &mut checks.images).0 == "modified" +} + /// Is the linked file still the one the asset's bytes were loaded from, going by the size and /// time kept then ([`designcraft_doc::Asset::link_fingerprint`], [`loaded_fingerprint`])? Nothing /// is read when it is, also on the first check after a document is opened, which matters on a @@ -178,7 +397,7 @@ pub(crate) fn loaded_fingerprint(before: Option, bytes: &[u8]) -> O /// new time or no fingerprint leave it to the byte comparison. #[cfg(not(target_arch = "wasm32"))] fn loaded_unchanged(a: &designcraft_doc::Asset, now: Fingerprint) -> bool { - a.link_fingerprint.is_some_and(|loaded| loaded.size == a.data.len() as u64 && loaded == now && settled(&now)) + a.link_fingerprint.is_some_and(|loaded| loaded.size == a.data.len() && loaded == now && settled(&now)) } /// Link status of a placed graphic (`ok`, `modified`, `missing`, `embedded`), reading the file @@ -186,14 +405,55 @@ fn loaded_unchanged(a: &designcraft_doc::Asset, now: Fingerprint) -> bool { /// ([`loaded_unchanged`]) nor the one remembered from the last read (`checks`): the Links panel /// polls, and a document of press-size images would otherwise be read whole on every poll. A file /// changed in the last two seconds is never remembered (see [`settled`]). +#[cfg(test)] pub(crate) fn status_cached(a: &designcraft_doc::Asset, document: Option<&Path>, checks: &mut ImageChecks) -> &'static str { - image_status(a, document, checks).0 + image_status(a, document, checks, None).0 +} + +/// Whether the automation read roots let this session read a file at one of `a`'s link paths +/// (always without roots in force, and then nothing is asked of the file system). +fn may_read_link(a: &Asset, document: Option<&Path>) -> bool { + #[cfg(not(target_arch = "wasm32"))] + { + LinkedSource::of(a, document).is_some_and(|s| crate::asset_io::candidates(&s).iter().any(|p| crate::file_access::check_read(p).is_ok())) + } + #[cfg(target_arch = "wasm32")] + { + let _ = (a, document); + true + } +} + +/// Whether `a`'s bytes are the document's own copy, with no file to compare them with: embedded +/// with no link, or with the link record Embed keeps (it has a hash; a copy saved before linked +/// storage has none, and is compared with its file). +fn embedded_copy(a: &Asset) -> bool { + a.storage == Storage::Embedded && (a.link.is_none() || a.link_hash.is_some()) } /// [`status_cached`], and the file's size and time when a read found the asset's bytes in it /// although the fingerprint kept with the asset says nothing or something else: what -/// [`remember_link_files`] keeps, so the file isn't read again in another session. -fn image_status(a: &designcraft_doc::Asset, document: Option<&Path>, checks: &mut ImageChecks) -> (&'static str, Option) { +/// [`remember_link_files`] keeps, so the file isn't read again in another session. While the +/// background check the open of the document started (`open`) still has the asset's file to look +/// at, it is `checking`; after that the file is looked at as it is now, which may have changed +/// since. +fn image_status( + a: &designcraft_doc::Asset, + document: Option<&Path>, + checks: &mut ImageChecks, + open: Option<&super::native_links::OpenLinks>, +) -> (&'static str, Option) { + if embedded_copy(a) { + return ("embedded", None); + } + if a.storage == Storage::Linked { + if open.is_some_and(|o| o.checking() && o.status(a) == Some(super::native_links::LinkStatus::Checking)) { + // A file this session may not read (outside the automation read roots) is missing, + // whatever the background check finds. + return (if may_read_link(a, document) { "checking" } else { "missing" }, None); + } + return linked_status(a, document, checks); + } let Some(link) = &a.link else { return ("embedded", None) }; // Nothing was read from the file (a package's link that wasn't followed): missing, as in // Preflight. @@ -213,17 +473,17 @@ fn image_status(a: &designcraft_doc::Asset, document: Option<&Path>, checks: &mu if loaded_unchanged(a, now) { return ("ok", None); } - if now.size != a.data.len() as u64 { + if now.size != a.data.len() { return ("modified", None); } - let key = (a.id, Arc::as_ptr(&a.data) as usize, path.clone()); + let key = (a.id, a.data.key(), path.clone()); if let Some((at, same)) = checks.get(&key) && *at == now { return if *same { ("ok", Some(now)) } else { ("modified", None) }; } - let same = match crate::io::read_capped(&path, a.data.len() as u64) { - Ok(b) => b == *a.data, + let same = match crate::io::read_capped(&path, a.data.len()) { + Ok(b) => a.data.load().is_ok_and(|d| b == *d), Err(_) => return ("missing", None), }; // The time from before the read: a change during it is seen next time. @@ -253,9 +513,13 @@ pub(crate) fn checkable_size(len: usize) -> bool { /// while the file was changed in the last two: another change in that second keeps the time. A /// time in the future (clock skew, a file copied from another machine) counts as settled, or such /// a file would be read on every poll; a later save gives it a time unlike the remembered one. +/// A file without a time ([`crate::asset_io::has_time`]) never is. pub(crate) fn settled(f: &Fingerprint) -> bool { #[cfg(not(target_arch = "wasm32"))] { + if !crate::asset_io::has_time(f) { + return false; + } let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| i64::try_from(d.as_secs()).unwrap_or(i64::MAX)); f.mtime > now || now.saturating_sub(f.mtime) >= 2 } @@ -414,7 +678,7 @@ impl LinkListChecks { /// what [`list_document_links`] finds on a worker thread, where a share that doesn't answer /// can't stall it. pub fn preview_document_links(d: &Document, cache: &Cache, document: Option<&Path>) -> Vec { - list(d, cache, document, None, None).unwrap_or_default() + list(d, cache, document, None, None, None).unwrap_or_default() } /// The rows of `links.list` for a document outside a [`Session`], so a native UI can check the @@ -428,7 +692,7 @@ pub fn list_document_links( checks: &mut LinkListChecks, stop: &AtomicBool, ) -> Option> { - list(d, cache, document, Some(checks), Some(stop)) + list(d, cache, document, Some(checks), Some(stop), None) } /// Keep, with each linked image in `files`, the size and time its file had when a check read it @@ -443,16 +707,25 @@ pub fn remember_link_files(s: &mut Session, doc: &Arc, files: &[(Asset if !Arc::ptr_eq(&st.doc, doc) || st.interaction.is_some() { return 0; } - let stale = |a: &designcraft_doc::Asset, f: &Fingerprint| a.link.is_some() && a.data.len() as u64 == f.size && a.link_fingerprint != Some(*f); + let stale = |a: &designcraft_doc::Asset, f: &Fingerprint| a.link.is_some() && a.data.len() == f.size && a.link_fingerprint != Some(*f); let fresh: Vec<(AssetId, Fingerprint)> = files.iter().filter(|(id, f)| st.doc.assets.get(id).is_some_and(|a| stale(a, f))).copied().collect(); if fresh.is_empty() { return 0; } let saved = !st.is_dirty(); + let document = st.path.clone(); let d = Arc::make_mut(&mut st.doc); for (id, f) in &fresh { if let Some(a) = d.assets.get_mut(id) { - Arc::make_mut(a).link_fingerprint = Some(*f); + let a = Arc::make_mut(a); + a.link_fingerprint = Some(*f); + // Linked bytes are read by that time too (the same bytes, found in the file: the key + // stays, also for a link with no hash yet). + if a.data.is_linked() + && let Some(source) = LinkedSource::of(a, document.as_deref().map(Path::new)) + { + a.data = AssetData::linked_under(a.data.key(), source); + } } } if saved { @@ -465,7 +738,14 @@ pub fn remember_link_files(s: &mut Session, doc: &Arc, files: &[(Asset /// `files` is what was read this session (a poll reads nothing unchanged); without it no file is /// looked at and a status that needs one is `checking` ([`preview_document_links`]). `None` when /// `stop` was set before the last link was reached. -fn list(d: &Document, cache: &Cache, document: Option<&Path>, files: Option<&mut LinkListChecks>, stop: Option<&AtomicBool>) -> Option> { +fn list( + d: &Document, + cache: &Cache, + document: Option<&Path>, + files: Option<&mut LinkListChecks>, + stop: Option<&AtomicBool>, + open: Option<&super::native_links::OpenLinks>, +) -> Option> { let stopped = || stop.is_some_and(|stop| stop.load(Ordering::Relaxed)); let (mut checks, mut images, mut verified) = match files { Some(files) => { @@ -519,17 +799,21 @@ fn list(d: &Document, cache: &Cache, document: Option<&Path>, files: Option<&mut let why = a.link.as_deref().and_then(|l| refused(l, document)).map(|r| r.to_string()); let status = match images.as_deref_mut() { Some(images) => { - let (status, file) = image_status(a, document, images); + let (status, file) = image_status(a, document, images, open); if let (Some(verified), Some(file)) = (verified.as_deref_mut(), file) { verified.push((a.id, file)); } status } - None if a.link.is_none() => "embedded", + None if embedded_copy(a) => "embedded", None if a.data.is_empty() || why.is_some() => "missing", - None => "checking", + None => open.and_then(|o| o.status(a)).map_or("checking", |s| s.as_str()), }; - Some(json!({"asset": a.id.0, "name": a.name, "path": a.link, "status": status, "refused": why, "pixels": a.pixels, "pdfCrop": pdf_crop, "uses": uses})) + let storage = match a.storage { + Storage::Linked => "linked", + Storage::Embedded => "embedded", + }; + Some(json!({"asset": a.id.0, "name": a.name, "path": a.link, "storage": storage, "status": status, "refused": why, "pixels": a.pixels, "pdfCrop": pdf_crop, "uses": uses})) }) .chain(texts) .collect() @@ -604,14 +888,12 @@ fn reload(path: impl AsRef) -> Result<(Vec, (u32, u32))> { Err(EngineError::Other(format!("{}: files can't be read on the web", path.as_ref().display()))) } -/// The replacement for `a`: bytes read from `read`, with `link` recorded as the stored link. -/// Relink passes the file the user chose as both. Update passes the path the stored link resolved -/// to and the stored link itself, so refreshing a link never rewrites what the document holds. -fn relinked_asset(a: &designcraft_doc::Asset, read: &Path, link: &str) -> Result> { +/// The replacement for `a`: bytes read from the file at `read`, linked to it (its absolute path, +/// and its path relative to the `document` file) with a new hash and proxy. +fn relinked_asset(a: &designcraft_doc::Asset, read: &Path, document: Option<&Path>) -> Result> { // The size and time from before the read: a change during it is seen by the next check. let before = super::datamerge::fingerprint_of(read); let (bytes, px) = reload(read)?; - let loaded = loaded_fingerprint(before, &bytes); let page = if designcraft_render::is_pdf(&bytes) { a.page } else { 0 }; let px = if page > 0 { designcraft_render::pdf_page_size(&bytes, page as usize) @@ -622,16 +904,26 @@ fn relinked_asset(a: &designcraft_doc::Asset, read: &Path, link: &str) -> Result }; let mut a = a.clone(); a.mime = designcraft_render::image_mime(&bytes).to_string(); - a.data = Arc::new(bytes); a.pixels = Some(px); a.page = page; - a.name = Path::new(link).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| link.to_string()); - a.set_link(Some(link.to_string()), loaded); + a.name = file_name(&read.to_string_lossy()); // A placed PDF keeps its crop choice; its box is found on the new file. - super::file::crop_pdf(&mut a); + super::file::crop_pdf_from(&mut a, &bytes); + let file = FileLink::of(read, before); + give_bytes(&mut a, bytes, Some(file), false, document); Ok(Arc::new(a)) } +/// The file Update reads `a`'s bytes from: the first of a linked graphic's paths that holds a +/// file, or where the link of an embedded copy resolves. +fn update_source(a: &Asset, document: Option<&Path>) -> Option { + if a.storage == Storage::Linked { + let source = LinkedSource::of(a, document)?; + return crate::asset_io::candidates(&source).into_iter().find(|p| crate::io::is_file(p)); + } + crate::io::document_path(a.link.as_deref()?, document).ok() +} + /// `links.relink`: a placed graphic or linked text file takes its bytes from `path` from now on. fn relink(s: &mut Session, p: &Value) -> Result { let path = str_param(p, "path").ok_or_else(|| bad("links.relink", "missing path"))?.to_string(); @@ -644,15 +936,17 @@ fn relink(s: &mut Session, p: &Value) -> Result { }); } let aid = asset_param(p, "links.relink")?; - let a = s.doc()?.doc.assets.get(&aid).ok_or_else(|| bad("links.relink", "no such graphic"))?; + let st = s.doc()?; + let a = st.doc.assets.get(&aid).ok_or_else(|| bad("links.relink", "no such graphic"))?; // Build the replacement before the edit: a file that cannot be read leaves the document as it was. - let fresh = relinked_asset(a, Path::new(&path), &path)?; + let fresh = relinked_asset(a, Path::new(&path), st.path.as_deref().map(Path::new))?; let r = s.edit(|d, _| { let name = fresh.name.clone(); d.assets.insert(aid, fresh); Ok(json!({"name": name})) }); s.link_checks.images.clear(); + designcraft_doc::asset_data::links_changed(); r } @@ -679,7 +973,9 @@ fn relink_folder(s: &mut Session, p: &Value) -> Result { let mut todo: Vec<(AssetId, std::path::PathBuf)> = Vec::new(); let mut not_found = Vec::new(); for a in d.assets.values() { - if only.as_ref().is_some_and(|o| !o.contains(&a.id.0)) || (missing_only && status_cached(a, document, &mut images) != "missing") { + if only.as_ref().is_some_and(|o| !o.contains(&a.id.0)) + || (missing_only && image_status(a, document, &mut images, Some(&st.links)).0 != "missing") + { continue; } let old = std::path::PathBuf::from(a.link.clone().unwrap_or_else(|| a.name.clone())); @@ -716,7 +1012,7 @@ fn relink_folder(s: &mut Session, p: &Value) -> Result { let mut fresh = Vec::new(); for (aid, path) in todo { let a = d.assets.get(&aid).ok_or_else(|| bad("links.relinkFolder", "no such graphic"))?; - fresh.push((aid, relinked_asset(a, &path, &path.to_string_lossy())?)); + fresh.push((aid, relinked_asset(a, &path, document)?)); } let n = fresh.len(); if n > 0 { @@ -727,16 +1023,178 @@ fn relink_folder(s: &mut Session, p: &Value) -> Result { Ok(()) })?; images.clear(); + designcraft_doc::asset_data::links_changed(); } s.link_checks.images = images; Ok(json!({"relinked": n, "notFound": not_found})) } +/// Unembed reads and writes files: not on the web. +fn can_unembed(s: &Session) -> std::result::Result<(), String> { + has_doc(s)?; + if cfg!(target_arch = "wasm32") { + return Err("files can't be linked on the web".into()); + } + Ok(()) +} + +/// `links.embed`: the graphic's bytes go into the document, checked against the link record. +fn embed(s: &mut Session, p: &Value) -> Result { + const ID: &str = "links.embed"; + if let Some(sid) = story_param(p) { + return s.edit(|d, _| { + d.story_mut(sid).ok_or_else(|| bad(ID, "no such story"))?.file_link = None; + Ok(Value::Null) + }); + } + let aid = asset_param(p, ID)?; + let st = s.doc()?; + let document = st.path.as_deref().map(Path::new); + let a = st.doc.assets.get(&aid).ok_or_else(|| bad(ID, "no such graphic"))?; + if a.storage == Storage::Linked { + if cfg!(target_arch = "wasm32") { + return Err(bad(ID, format!("{}: linked files can't be read on the web", a.name))); + } + // Checked even when the bytes are in memory: what is embedded is what the file holds. + match linked_status(a, document, &mut ImageChecks::default()).0 { + "missing" => return Err(bad(ID, format!("{}: the linked file is missing; relink it, then embed it", a.name))), + "modified" => return Err(bad(ID, format!("{}: the linked file has changed; update or relink it, then embed it", a.name))), + _ => {} + } + } + let bytes = a.data.load().map_err(|e| bad(ID, format!("{}: {e}", a.name)))?; + // A link without a hash would be taken for a copy saved before linked storage. + let hash = a.link_hash.clone().or_else(|| a.link.is_some().then(|| crate::asset_io::content_hash(&bytes))); + let key = a.data.key(); + s.edit(|d, _| { + let a = Arc::make_mut(d.assets.get_mut(&aid).ok_or_else(|| bad(ID, "no such graphic"))?); + // The same bytes: what was decoded from them stays usable. + a.data = AssetData::embedded_under(key, bytes); + a.storage = Storage::Embedded; + a.proxy = None; + a.link_hash = hash; + Ok(Value::Null) + })?; + Ok(Value::Null) +} + +/// The file in `folder` named like the original (or `name` with an extension for `mime`) that +/// holds `bytes`: an existing one with exactly these bytes, else a new one written there. +#[cfg(not(target_arch = "wasm32"))] +fn write_into(folder: &Path, name: &str, mime: &str, bytes: &[u8]) -> Result { + const ID: &str = "links.unembed"; + if !crate::io::is_dir(folder) { + return Err(bad(ID, format!("{}: not a folder", folder.display()))); + } + let file = Path::new(name).file_name().map(|n| n.to_string_lossy().into_owned()).filter(|n| !n.is_empty()).unwrap_or_else(|| "graphic".into()); + let mut file = std::path::PathBuf::from(file); + if file.extension().is_none() { + let ext = match mime { + "image/jpeg" => "jpg", + "image/gif" => "gif", + "image/tiff" => "tif", + "image/webp" => "webp", + "image/svg+xml" => "svg", + "application/pdf" => "pdf", + "application/postscript" => "eps", + "image/png" => "png", + _ => "bin", + }; + file.set_extension(ext); + } + let stem = file.file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default(); + let ext = file.extension().map(|e| e.to_string_lossy().into_owned()).unwrap_or_default(); + for n in 0..1000u32 { + let candidate = if n == 0 { folder.join(&file) } else { folder.join(format!("{stem}-{n}.{ext}")) }; + if !crate::io::exists(&candidate) { + crate::io::write_file(&candidate, bytes).map_err(EngineError::Other)?; + return Ok(candidate); + } + if file_holds(&candidate, bytes) { + return Ok(candidate); + } + } + Err(bad(ID, format!("{}: no free file name for {}", folder.display(), file.display()))) +} + +/// Does the regular file at `path` hold exactly `bytes`? +#[cfg(not(target_arch = "wasm32"))] +fn file_holds(path: &Path, bytes: &[u8]) -> bool { + crate::io::file_metadata(path).is_some_and(|m| m.len() == bytes.len() as u64) + && crate::io::read_capped(path, bytes.len() as u64).is_ok_and(|b| b == bytes) +} + +/// `links.unembed`: an embedded graphic links to its original file, or to a copy written into `dir`. +fn unembed(s: &mut Session, p: &Value) -> Result { + const ID: &str = "links.unembed"; + can_unembed(s).map_err(|e| bad(ID, e))?; + let aid = asset_param(p, ID)?; + let st = s.doc()?; + let document = st.path.clone(); + let document = document.as_deref().map(Path::new); + let a = st.doc.assets.get(&aid).ok_or_else(|| bad(ID, "no such graphic"))?; + if a.storage == Storage::Linked { + return Err(bad(ID, format!("{} is already linked", a.name))); + } + let bytes = a + .data + .embedded_bytes() + .cloned() + .filter(|b| !b.is_empty()) + .ok_or_else(|| bad(ID, format!("{}: the document holds no bytes for it", a.name)))?; + #[cfg(not(target_arch = "wasm32"))] + { + let original = a.link.as_ref().and_then(|link| { + let source = LinkedSource { + path: link.clone(), + relative: a.link_relative.clone(), + document: document.map(Path::to_path_buf), + len: bytes.len() as u64, + fingerprint: None, + hash: None, + }; + crate::asset_io::candidates(&source).into_iter().find(|p| file_holds(p, &bytes)) + }); + let target = match (original, str_param(p, "dir")) { + (Some(original), _) => original, + (None, Some(dir)) => { + let dir = Path::new(dir); + crate::file_access::check_write(dir).map_err(EngineError::Other)?; + write_into(dir, &a.name, &a.mime, &bytes)? + } + (None, None) => return Err(bad(ID, format!("{}: its original file is missing or has changed; give `dir` to write it there", a.name))), + }; + let before = super::datamerge::fingerprint_of(&target); + let file = FileLink::of(&target, before); + let key = a.data.key(); + let mut linked = (**a).clone(); + give_bytes(&mut linked, Arc::clone(&bytes), Some(file), false, document); + // The same bytes: what was decoded from them stays usable. + if let Some(source) = linked.data.linked_source().cloned() { + linked.data = AssetData::linked_under(key, source); + linked.data.keep_resident(bytes); + } + let path = linked.link.clone(); + let r = s.edit(|d, _| { + d.assets.insert(aid, Arc::new(linked)); + Ok(json!({"path": path})) + }); + s.link_checks.images.clear(); + designcraft_doc::asset_data::links_changed(); + r + } + #[cfg(target_arch = "wasm32")] + { + let _ = (document, bytes); + Err(bad(ID, "files can't be linked on the web")) + } +} + /// `links.update`: re-read the modified links (one, or every one) from where they resolve. fn update(s: &mut Session, p: &Value) -> Result { - let (d, document) = { + let (d, document, open) = { let st = s.doc()?; - (st.doc.clone(), st.path.clone()) + (st.doc.clone(), st.path.clone(), st.links.clone()) }; let document = document.as_deref().map(Path::new); let LinkListChecks { text: checks, images, .. } = &mut s.link_checks; @@ -754,13 +1212,14 @@ fn update(s: &mut Session, p: &Value) -> Result { }) .collect(); let mut fresh = Vec::new(); - for a in d.assets.values().filter(|a| all || only_asset == Some(a.id.0)).filter(|a| status_cached(a, document, images) == "modified") { - // The bytes come from where the stored link resolves; the link itself stays as the - // document stored it, so refreshing never rewrites a relative link to an absolute one. - if let Some((link, at)) = a.link.as_deref().and_then(|l| resolved(l).map(|at| (l, at))) { - fresh.push((a.id, relinked_asset(a, &at, link)?)); + for a in + d.assets.values().filter(|a| all || only_asset == Some(a.id.0)).filter(|a| image_status(a, document, images, Some(&open)).0 == "modified") + { + if let Some(at) = update_source(a, document) { + fresh.push((a.id, relinked_asset(a, &at, document)?)); } } + drop(open); let mut fresh_texts = Vec::new(); for (sid, path, at) in texts { let (bytes, before) = read_text(&at)?; @@ -781,6 +1240,7 @@ fn update(s: &mut Session, p: &Value) -> Result { Ok(json!({"updated": n, "warnings": warnings})) }); s.link_checks.images.clear(); + designcraft_doc::asset_data::links_changed(); r } @@ -806,6 +1266,7 @@ mod relink_folder_tests { std::fs::write(&path, r#""#).unwrap(); s.doc_mut().unwrap().selection = Default::default(); s.execute("file.place", &json!({"path": path.to_string_lossy()})).unwrap(); + crate::cmd::native_links::wait(&mut s); std::fs::rename(&path, dir.join("new").join(name)).unwrap(); } (s, dir) @@ -873,6 +1334,7 @@ mod relink_folder_tests { let mut s = Session::new(); s.execute("file.new", &json!({})).unwrap(); s.execute("file.place", &json!({"path": orig.to_string_lossy()})).unwrap(); + crate::cmd::native_links::wait(&mut s); // The file moves away: relink from the new folder. std::fs::rename(&orig, dir.join("new").join("logo.svg")).unwrap(); let r = s.execute("links.relinkFolder", &json!({"dir": dir.join("new").to_string_lossy()})).unwrap(); @@ -936,6 +1398,7 @@ mod shared_asset_tests { for (path, x) in [(&a, 72), (&b, 200)] { s.execute("edit.deselectAll", &json!({})).unwrap(); s.execute("file.place", &json!({"path": path.to_string_lossy(), "x": x, "y": 72})).unwrap(); + crate::cmd::native_links::wait(&mut s); } assert_eq!(s.doc().unwrap().doc.assets.len(), 2); let rows = |s: &mut Session| -> Vec<(String, Value)> { @@ -963,7 +1426,7 @@ mod shared_asset_tests { id: AssetId(id), name: "p.png".into(), mime: "image/png".into(), - data: Arc::new(data), + data: designcraft_doc::AssetData::embedded(data), ..Default::default() }; let mut src = Document::new(&NewDocument::default()); @@ -1018,7 +1481,7 @@ mod shared_asset_tests { name: "p.png".into(), mime: "image/png".into(), link: None, - data: Arc::new(png(8, 4)), + data: designcraft_doc::AssetData::embedded(png(8, 4)), pixels: None, ..Default::default() }), @@ -1095,7 +1558,6 @@ mod text_link_tests { /// A small Word file: a Title paragraph, then Body paragraphs (`body` is WordprocessingML). fn docx(body: &str) -> Vec { - use std::io::Write; const W: &str = r#"xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main""#; let styles = format!( r#" @@ -1105,13 +1567,7 @@ mod text_link_tests { r#"Head {body}"# ); - let mut w = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); - let o = zip::write::SimpleFileOptions::default(); - for (n, c) in [("word/document.xml", doc), ("word/styles.xml", styles)] { - w.start_file(n, o).unwrap(); - w.write_all(c.as_bytes()).unwrap(); - } - w.finish().unwrap().into_inner() + crate::cmd::place_text::word_package(&doc, &styles) } fn text_rows(s: &mut Session) -> Vec { @@ -1248,6 +1704,7 @@ mod text_link_tests { let mut s = Session::new(); s.execute("file.new", &json!({})).unwrap(); s.execute("file.place", &json!({"path": path.to_string_lossy(), "link": true})).unwrap(); + crate::cmd::native_links::wait(&mut s); let status = |s: &mut Session| text_rows(s)[0]["status"].as_str().unwrap().to_string(); // Size and time as placed: not read. @@ -1329,6 +1786,7 @@ mod text_link_tests { let sid = fr["story"].as_u64().unwrap(); s.execute("text.select", &json!({"story": sid, "anchor": 6, "focus": 6})).unwrap(); let r = s.execute("file.place", &json!({"path": path.to_string_lossy()})).unwrap(); + crate::cmd::native_links::wait(&mut s); assert!(r["warnings"][0].as_str().unwrap().contains("not linked"), "{r}"); assert!(s.doc().unwrap().doc.story(StoryId(sid)).unwrap().file_link.is_none()); let _ = std::fs::remove_dir_all(&dir); diff --git a/crates/engine/src/cmd/links/tests.rs b/crates/engine/src/cmd/links/tests.rs index 733891dbf..8de21fb14 100644 --- a/crates/engine/src/cmd/links/tests.rs +++ b/crates/engine/src/cmd/links/tests.rs @@ -33,6 +33,7 @@ fn unchanged_linked_images_are_not_read_again() { let mut s = Session::new(); s.execute("file.new", &json!({})).unwrap(); s.execute("file.place", &json!({"path": path.to_string_lossy(), "link": true})).unwrap(); + crate::cmd::native_links::wait(&mut s); let status = |s: &mut Session| { let l = s.execute("links.list", &json!({})).unwrap(); l.as_array().unwrap().iter().find(|r| r.get("asset").is_some()).unwrap()["status"].as_str().unwrap().to_string() @@ -101,7 +102,7 @@ fn a_linked_image_at_its_loaded_size_and_time_is_not_read() { id: AssetId(1), link: Some(path.to_string_lossy().into_owned()), link_fingerprint, - data: Arc::new(b"data".to_vec()), + data: designcraft_doc::AssetData::embedded(b"data".to_vec()), ..Default::default() }; let status = |a: &designcraft_doc::Asset| status_cached(a, None, &mut ImageChecks::default()); @@ -111,7 +112,7 @@ fn a_linked_image_at_its_loaded_size_and_time_is_not_read() { assert_eq!(status(&asset(None)), "modified"); assert_eq!(status(&asset(Some(Fingerprint { mtime: loaded.mtime - 60, ..loaded }))), "modified", "a new time alone is compared"); // Bytes replaced without their fingerprint: it is of another size, so it isn't theirs. - let swapped = designcraft_doc::Asset { data: Arc::new(b"other bytes".to_vec()), ..asset(Some(loaded)) }; + let swapped = designcraft_doc::Asset { data: designcraft_doc::AssetData::embedded(b"other bytes".to_vec()), ..asset(Some(loaded)) }; assert_eq!(status(&swapped), "modified"); // A time too recent to trust: another write in the same second would keep it. set_age(&path, 0); @@ -140,6 +141,7 @@ fn a_graphic_rewritten_with_the_same_bytes_stays_ok() { let mut s = Session::new(); s.execute("file.new", &json!({})).unwrap(); let aid = AssetId(s.execute("file.place", &json!({"path": path.to_string_lossy()})).unwrap()["asset"].as_u64().unwrap()); + crate::cmd::native_links::wait(&mut s); rewrite(&image, 60); let a = s.doc().unwrap().doc.assets[&aid].clone(); assert!(a.link_fingerprint.is_some()); @@ -181,14 +183,18 @@ fn preview_rows_look_at_no_file() { let mut s = Session::new(); s.execute("file.new", &json!({})).unwrap(); let place = |s: &mut Session, path: &Path, x: u32| { - AssetId(s.execute("file.place", &json!({"path": path.to_string_lossy(), "x": x, "y": 72})).unwrap()["asset"].as_u64().unwrap()) + let id = AssetId(s.execute("file.place", &json!({"path": path.to_string_lossy(), "x": x, "y": 72})).unwrap()["asset"].as_u64().unwrap()); + crate::cmd::native_links::wait(s); + id }; let ids = [place(&mut s, &linked, 72), place(&mut s, &embedded, 144), place(&mut s, &gone, 216)]; s.execute("links.embed", &json!({"asset": ids[1].0})).unwrap(); std::fs::remove_file(&gone).unwrap(); let st = s.doc().unwrap(); assert!(st.doc.assets[&ids[0]].link_fingerprint.is_some(), "a placed file is remembered by its size and time"); - assert!(st.doc.assets[&ids[1]].link_fingerprint.is_none(), "embed forgets the file"); + let copy = &st.doc.assets[&ids[1]]; + assert_eq!(copy.storage, designcraft_doc::Storage::Embedded); + assert!(copy.link.is_some() && copy.link_hash.is_some(), "embed keeps the link record for Unembed"); let statuses = |rows: &[Value]| -> Vec { ids.iter().map(|id| rows.iter().find(|r| r["asset"] == id.0).unwrap()["status"].as_str().unwrap().to_string()).collect() }; @@ -243,7 +249,9 @@ fn a_file_written_just_now_is_not_vouched_for_by_its_time() { let mut s = Session::new(); s.execute("file.new", &json!({})).unwrap(); let aid = AssetId(s.execute("file.place", &json!({"path": path.to_string_lossy()})).unwrap()["asset"].as_u64().unwrap()); - assert_eq!(s.doc().unwrap().doc.assets[&aid].link_fingerprint, None); + crate::cmd::native_links::wait(&mut s); + let kept = s.doc().unwrap().doc.assets[&aid].link_fingerprint.unwrap(); + assert_eq!((kept.size, kept.mtime), (image.len() as u64, UNVERIFIED_MTIME), "the time can't vouch for the bytes"); let mut other = image.clone(); if let Some(last) = other.last_mut() { *last ^= 0xff; @@ -268,6 +276,7 @@ fn a_stopped_check_looks_at_no_further_file() { let path = dir.join(name); std::fs::write(&path, png(x, 10)).unwrap(); s.execute("file.place", &json!({"path": path.to_string_lossy(), "x": x, "y": 72})).unwrap(); + crate::cmd::native_links::wait(&mut s); } let st = s.doc().unwrap(); let mut checks = LinkListChecks::default(); @@ -297,6 +306,7 @@ fn a_file_found_unchanged_by_its_bytes_is_remembered_with_the_document() { let mut s = Session::new(); s.execute("file.new", &json!({})).unwrap(); let aid = AssetId(s.execute("file.place", &json!({"path": path.to_string_lossy()})).unwrap()["asset"].as_u64().unwrap()); + crate::cmd::native_links::wait(&mut s); s.execute("file.saveAs", &json!({"path": dir.join("doc.designcraft").to_string_lossy()})).unwrap(); assert!(!s.doc().unwrap().is_dirty()); set_age(&path, 60); @@ -424,7 +434,7 @@ fn eps_web_exports_convert_tiff_and_skip_bad_used_assets() { assert!(!opf.contains("image/tiff")); assert!(Arc::ptr_eq(&before, &s.doc().unwrap().doc)); s.edit(|d, _| { - Arc::make_mut(d.assets.get_mut(&aid).unwrap()).data = Arc::new(b"%!PS-Adobe-3.0 EPSF-3.0\n%%EOF\n".to_vec()); + Arc::make_mut(d.assets.get_mut(&aid).unwrap()).data = designcraft_doc::AssetData::embedded(b"%!PS-Adobe-3.0 EPSF-3.0\n%%EOF\n".to_vec()); Ok(()) }) .unwrap(); @@ -458,13 +468,14 @@ fn eps_status_tracks_source_bytes_across_save_update_relink_and_embed() { let mut s = Session::new(); s.execute("file.new", &json!({})).unwrap(); let aid = AssetId(s.execute("file.place", &json!({"path": path.to_string_lossy()})).unwrap()["asset"].as_u64().unwrap()); + crate::cmd::native_links::wait(&mut s); assert_eq!(s.execute("links.list", &json!({})).unwrap()[0]["status"], "ok"); let before = s.doc().unwrap().doc.clone(); assert_eq!(s.execute("links.update", &json!({})).unwrap()["updated"], 0); assert!(Arc::ptr_eq(&s.doc().unwrap().doc, &before), "unchanged EPS must not create an edit"); let saved = designcraft_format::save(&before).unwrap(); let reopened = designcraft_format::load(&saved).unwrap(); - assert_eq!(reopened.assets[&aid].data.as_slice(), first); + assert_eq!(reopened.assets[&aid].data.load().unwrap().as_slice(), first); let mut s = Session::new(); s.add_document(crate::DocState::new(reopened, None)); assert_eq!(s.execute("links.list", &json!({})).unwrap()[0]["status"], "ok"); @@ -472,7 +483,7 @@ fn eps_status_tracks_source_bytes_across_save_update_relink_and_embed() { assert_eq!(s.execute("links.list", &json!({})).unwrap()[0]["status"], "modified"); assert_eq!(s.execute("links.update", &json!({})).unwrap()["updated"], 1); assert_eq!(s.execute("links.list", &json!({})).unwrap()[0]["status"], "ok"); - assert_eq!(s.doc().unwrap().doc.assets[&aid].data.as_slice(), changed); + assert_eq!(s.doc().unwrap().doc.assets[&aid].data.load().unwrap().as_slice(), changed); std::fs::remove_file(&path).unwrap(); assert_eq!(s.execute("links.list", &json!({})).unwrap()[0]["status"], "missing"); let replacement = dir.join("replacement.eps"); @@ -489,8 +500,8 @@ fn eps_status_tracks_source_bytes_across_save_update_relink_and_embed() { let embedded = designcraft_format::load(&designcraft_format::save(&s.doc().unwrap().doc).unwrap()).unwrap(); // The asset is embedded, so no link is followed and the document is irrelevant. assert_eq!(status_cached(&embedded.assets[&aid], None, &mut Default::default()), "embedded"); - assert_eq!(embedded.assets[&aid].data.as_slice(), changed); - assert!(designcraft_render::decode_pixmap(&embedded.assets[&aid].data).is_some()); + assert_eq!(embedded.assets[&aid].data.load().unwrap().as_slice(), changed); + assert!(designcraft_render::decode_pixmap(&embedded.assets[&aid].data.load().unwrap()).is_some()); let _ = std::fs::remove_dir_all(dir); } @@ -504,11 +515,16 @@ fn eps_legacy_preview_document_is_upgraded_by_update() { let mut s = Session::new(); s.execute("file.new", &json!({})).unwrap(); let aid = AssetId(s.execute("file.place", &json!({"path": path.to_string_lossy()})).unwrap()["asset"].as_u64().unwrap()); + crate::cmd::native_links::wait(&mut s); let proxy = designcraft_images::eps_proxy(source).unwrap().0; + // A document saved before linked storage: the preview embedded, a link without a hash. s.edit(|d, _| { let a = Arc::make_mut(d.assets.get_mut(&aid).unwrap()); - a.data = Arc::new(proxy); + a.data = designcraft_doc::AssetData::embedded(proxy); a.mime = "image/png".into(); + a.storage = designcraft_doc::Storage::Embedded; + a.link_hash = None; + a.proxy = None; Ok(()) }) .unwrap(); @@ -517,9 +533,9 @@ fn eps_legacy_preview_document_is_upgraded_by_update() { s.add_document(crate::DocState::new(old, None)); assert_eq!(s.execute("links.update", &json!({})).unwrap()["updated"], 1); assert_eq!(s.execute("links.list", &json!({})).unwrap()[0]["status"], "ok"); - assert_eq!(s.doc().unwrap().doc.assets[&aid].data.as_slice(), source); + assert_eq!(s.doc().unwrap().doc.assets[&aid].data.load().unwrap().as_slice(), source); s.execute("edit.undo", &json!({})).unwrap(); - assert!(designcraft_render::decode_pixmap(&s.doc().unwrap().doc.assets[&aid].data).is_some(), "old preview remains renderable"); + assert!(designcraft_render::decode_pixmap(&s.doc().unwrap().doc.assets[&aid].data.load().unwrap()).is_some(), "old preview remains renderable"); s.execute("edit.redo", &json!({})).unwrap(); assert_eq!(s.execute("links.list", &json!({})).unwrap()[0]["status"], "ok"); let _ = std::fs::remove_dir_all(dir); @@ -542,7 +558,7 @@ fn eps_source_exports_preview_to_pdf_html_and_epub_without_editing_document() { // A document retaining the original EPS rather than the legacy preview-only asset. s.edit(|d, _| { let a = Arc::make_mut(d.assets.get_mut(&aid).unwrap()); - a.data = Arc::new(source.to_vec()); + a.data = designcraft_doc::AssetData::embedded(source.to_vec()); a.mime = "application/postscript".into(); Ok(()) }) @@ -573,7 +589,7 @@ fn eps_source_exports_preview_to_pdf_html_and_epub_without_editing_document() { assert!(opf.contains("media-type=\"image/png\"")); assert!(!opf.contains("application/postscript")); assert!(Arc::ptr_eq(&s.doc().unwrap().doc, &before), "exports must leave the source document intact"); - assert_eq!(before.assets[&aid].data.as_slice(), source); + assert_eq!(before.assets[&aid].data.load().unwrap().as_slice(), source); } #[test] @@ -588,6 +604,7 @@ fn eps_relink_update_and_folder_relink_retain_source() { let mut s = Session::new(); s.execute("file.new", &json!({})).unwrap(); s.execute("file.place", &json!({"path": original.to_string_lossy()})).unwrap(); + crate::cmd::native_links::wait(&mut s); let aid = s.doc().unwrap().doc.assets.keys().next().copied().unwrap(); std::fs::write(&original, eps(20)).unwrap(); assert_eq!(s.execute("links.update", &json!({})).unwrap()["updated"], 1); @@ -596,7 +613,7 @@ fn eps_relink_update_and_folder_relink_retain_source() { let a = &s.doc().unwrap().doc.assets[&aid]; assert_eq!(a.pixels, Some((60, 20))); assert_eq!(a.mime, "application/postscript"); - assert_eq!(a.data.as_slice(), eps(30).as_bytes()); + assert_eq!(a.data.load().unwrap().as_slice(), eps(30).as_bytes()); let moved = dir.join("new").join("replacement.eps"); std::fs::rename(&replacement, &moved).unwrap(); assert_eq!(s.execute("links.relinkFolder", &json!({"dir": dir.join("new").to_string_lossy()})).unwrap()["relinked"], 1); @@ -616,12 +633,13 @@ fn pdf_relink_and_update_preserve_selected_page_size() { let mut s = Session::new(); s.execute("file.new", &json!({})).unwrap(); s.execute("file.place", &json!({"path": original.to_string_lossy(), "pdfPage": 2})).unwrap(); + crate::cmd::native_links::wait(&mut s); let aid = s.doc().unwrap().doc.assets.keys().next().copied().unwrap(); s.execute("links.relink", &json!({"asset": aid.0, "path": replacement.to_string_lossy()})).unwrap(); let a = &s.doc().unwrap().doc.assets[&aid]; assert_eq!(a.page, 1); assert_eq!(a.pixels, Some((50, 60))); - assert!(designcraft_render::render_pdf_page(&a.data, a.page as usize, 64).is_some()); + assert!(designcraft_render::render_pdf_page(&a.data.load().unwrap(), a.page as usize, 64).is_some()); std::fs::write(&replacement, pdf(&[(70, 70), (80, 90)])).unwrap(); assert_eq!(s.execute("links.update", &json!({})).unwrap()["updated"], 1); assert_eq!(s.doc().unwrap().doc.assets[&aid].pixels, Some((80, 90))); @@ -646,6 +664,7 @@ fn pdf_reload_rejects_missing_page_without_edit() { let mut s = Session::new(); s.execute("file.new", &json!({})).unwrap(); s.execute("file.place", &json!({"path": original.to_string_lossy(), "pdfPage": 2})).unwrap(); + crate::cmd::native_links::wait(&mut s); let aid = s.doc().unwrap().doc.assets.keys().next().copied().unwrap(); if command == "links.update" { std::fs::write(&original, &short).unwrap(); @@ -667,7 +686,7 @@ fn pdf_reload_rejects_missing_page_without_edit() { assert_eq!(st.revision, revision); assert_eq!(st.history.undo.len(), undo); assert_eq!(s.journal.len(), journal); - assert!(designcraft_render::render_pdf_page(&st.doc.assets[&aid].data, 1, 64).is_some()); + assert!(designcraft_render::render_pdf_page(&st.doc.assets[&aid].data.load().unwrap(), 1, 64).is_some()); } let _ = std::fs::remove_dir_all(dir); } @@ -683,6 +702,7 @@ fn link_status_relink_update_embed() { let mut s = Session::new(); s.execute("file.new", &json!({})).unwrap(); s.execute("file.place", &json!({"path": a.to_string_lossy(), "x": 72, "y": 72, "width": 72})).unwrap(); + crate::cmd::native_links::wait(&mut s); let l = s.execute("links.list", &json!({})).unwrap(); assert_eq!(l[0]["status"], "ok"); assert_eq!(l[0]["uses"][0]["ppi"], 10.0, "10 px over 1 inch"); @@ -707,3 +727,272 @@ fn link_status_relink_update_embed() { assert_eq!(s.execute("links.list", &json!({})).unwrap()[0]["status"], "embedded"); let _ = std::fs::remove_dir_all(&dir); } + +/// A temporary folder, removed when dropped. +#[cfg(not(target_arch = "wasm32"))] +struct TempDir(std::path::PathBuf); + +#[cfg(not(target_arch = "wasm32"))] +impl TempDir { + fn new(name: &str) -> Self { + let dir = std::env::temp_dir().join(format!("dc-links-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + TempDir(dir) + } +} + +#[cfg(not(target_arch = "wasm32"))] +impl Drop for TempDir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +/// Two valid PNGs of one byte length with other pixels (a uniform fill compresses to the same size). +fn same_size_pngs() -> (Vec, Vec) { + let a = designcraft_render::Rendered { width: 30, height: 20, pixels: vec![200u8; 30 * 20 * 4] }.to_png(); + let b = designcraft_render::Rendered { width: 30, height: 20, pixels: vec![100u8; 30 * 20 * 4] }.to_png(); + assert_eq!(a.len(), b.len()); + (a, b) +} + +/// Place a file and let the background job link it ([`crate::cmd::native_links::prepare`]). +fn placed(s: &mut Session, params: Value) -> AssetId { + let id = AssetId(s.execute("file.place", ¶ms).unwrap()["asset"].as_u64().unwrap()); + crate::cmd::native_links::wait(s); + id +} + +fn asset_of(s: &Session, id: AssetId) -> Arc { + Arc::clone(&s.doc().unwrap().doc.assets[&id]) +} + +fn row(s: &mut Session, id: AssetId) -> Value { + s.execute("links.list", &json!({})).unwrap().as_array().unwrap().iter().find(|r| r["asset"] == id.0).unwrap().clone() +} + +/// The format version a saved bundle declares. +#[cfg(not(target_arch = "wasm32"))] +fn bundle_version(bytes: &[u8]) -> (u64, Vec) { + use std::io::Read; + let mut zip = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap(); + let names: Vec = zip.file_names().map(str::to_string).collect(); + let mut version = 0; + for name in names.iter().filter(|n| n.ends_with(".json")) { + let mut text = String::new(); + zip.by_name(name).unwrap().read_to_string(&mut text).unwrap(); + if let Ok(v) = serde_json::from_str::(&text) + && v.get("format").is_some() + { + version = v["version"].as_u64().unwrap(); + } + } + (version, names.into_iter().filter(|n| n.starts_with("assets/")).collect()) +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_file_placed_from_a_path_links_to_it_and_embed_true_embeds_it() { + use designcraft_doc::Storage; + let dir = TempDir::new("place"); + let path = dir.0.join("art.png"); + let (bytes, _) = same_size_pngs(); + std::fs::write(&path, &bytes).unwrap(); + set_age(&path, 60); + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + + let id = placed(&mut s, json!({"path": path.to_string_lossy()})); + let a = asset_of(&s, id); + assert_eq!(a.storage, Storage::Linked); + assert!(a.data.is_linked() && a.data.embedded_bytes().is_none(), "no embedded copy"); + assert_eq!(a.link.as_deref(), path.to_str()); + assert_eq!(a.link_hash.as_deref(), Some(crate::asset_io::content_hash(&bytes).as_str())); + assert!(a.proxy.as_ref().is_some_and(|p| p.pixels == (30, 20))); + assert_eq!(a.data.resident().as_deref(), Some(&bytes), "the bytes read for placing are kept for the first draw"); + let r = row(&mut s, id); + assert_eq!((r["storage"].as_str(), r["status"].as_str()), (Some("linked"), Some("ok"))); + let (version, stored) = bundle_version(&designcraft_format::save(&s.doc().unwrap().doc).unwrap()); + assert_eq!((version, stored), (5, vec![]), "linked: format 5 and no copy of the file"); + + let e = placed(&mut s, json!({"path": path.to_string_lossy(), "embed": true, "x": 200})); + let a = asset_of(&s, e); + assert_eq!(a.storage, Storage::Embedded); + assert_eq!(a.data.embedded_bytes().map(|b| b.as_slice()), Some(bytes.as_slice())); + assert!(a.link.is_some() && a.link_hash.is_some(), "the link record stays for Unembed"); + let r = row(&mut s, e); + assert_eq!((r["storage"].as_str(), r["status"].as_str()), (Some("embedded"), Some("embedded"))); +} + +/// Placing a large image links it at once and returns before its proxy and hash are made. A save +/// in between writes the link without a hash, with a proxy made for it then; the copy reopens as +/// that link, and its open hashes the file. The background job adds the hash and proxy to the +/// live document under the key its bytes were drawn with. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn placing_leaves_the_proxy_and_hash_to_the_background() { + use designcraft_doc::Storage; + let dir = TempDir::new("deferred"); + let path = dir.0.join("big.png"); + let bytes = png(1600, 1200); + std::fs::write(&path, &bytes).unwrap(); + set_age(&path, 60); + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let id = AssetId(s.execute("file.place", &json!({"path": path.to_string_lossy()})).unwrap()["asset"].as_u64().unwrap()); + let a = asset_of(&s, id); + assert!(a.proxy.is_none() && a.link_hash.is_none(), "no proxy or hash is made while placing"); + assert_eq!((a.storage, a.link.as_deref()), (Storage::Linked, path.to_str())); + assert_eq!(a.data.resident().as_deref(), Some(&bytes), "the bytes read for placing are kept for drawing"); + assert!(s.doc().unwrap().links.checking(), "the background job is running"); + let key = a.data.key(); + + let early = dir.0.join("early.designcraft"); + s.execute("file.saveACopy", &json!({"path": early.to_string_lossy()})).unwrap(); + let mut t = Session::new(); + t.execute("file.open", &json!({"path": early.to_string_lossy()})).unwrap(); + crate::cmd::native_links::wait(&mut t); + let c = t.doc().unwrap().doc.assets.values().next().cloned().unwrap(); + assert_eq!(c.storage, Storage::Linked); + assert!(c.proxy.is_some(), "the save made the proxy"); + assert_eq!(c.data.load().unwrap().as_slice(), bytes.as_slice()); + let hash = crate::asset_io::content_hash(&bytes); + assert_eq!(c.link_hash.as_deref(), Some(hash.as_str()), "the open hashed the file that matched by size and time"); + + crate::cmd::native_links::wait(&mut s); + let a = asset_of(&s, id); + assert_eq!((a.storage, a.link_hash.as_deref()), (Storage::Linked, Some(hash.as_str()))); + assert_eq!(a.data.key(), key, "still under the key its decodes are cached by"); + assert!(a.proxy.as_ref().is_some_and(|p| p.pixels == (1024, 768)), "the proxy is made in the background"); + assert!(!s.doc().unwrap().links.checking()); +} + +/// Cmd-S right after placing a large photo writes a link and a proxy, not the photo. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_save_right_after_placing_writes_no_copy_of_the_file() { + let dir = TempDir::new("save-at-once"); + let path = dir.0.join("photo.png"); + // Opaque noise doesn't compress: the PNG is about as large as its pixels. + let mut seed = 0x2545_f491_u32; + let pixels = (0..800 * 600 * 4) + .map(|i| { + seed ^= seed << 13; + seed ^= seed >> 17; + seed ^= seed << 5; + if i % 4 == 3 { 255 } else { (seed >> 24) as u8 } + }) + .collect(); + let bytes = designcraft_render::Rendered { width: 800, height: 600, pixels }.to_png(); + std::fs::write(&path, &bytes).unwrap(); + set_age(&path, 60); + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + s.execute("file.place", &json!({"path": path.to_string_lossy()})).unwrap(); + let doc = dir.0.join("doc.designcraft"); + s.execute("file.save", &json!({"path": doc.to_string_lossy()})).unwrap(); + let saved = std::fs::metadata(&doc).unwrap().len(); + assert!(saved < bytes.len() as u64, "saved {saved} bytes for a {} byte photo", bytes.len()); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_modified_link_is_updated_undoably() { + let dir = TempDir::new("update"); + let path = dir.0.join("art.png"); + let (first, second) = same_size_pngs(); + std::fs::write(&path, &first).unwrap(); + set_age(&path, 60); + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let id = placed(&mut s, json!({"path": path.to_string_lossy()})); + let key = asset_of(&s, id).data.key(); + + std::fs::write(&path, &second).unwrap(); + set_age(&path, 30); + assert_eq!(row(&mut s, id)["status"], "modified"); + assert_eq!(asset_of(&s, id).data.load().unwrap().as_slice(), first, "changed bytes are never adopted"); + assert_eq!(s.execute("links.update", &json!({"asset": id.0})).unwrap()["updated"], 1); + let a = asset_of(&s, id); + assert_eq!(row(&mut s, id)["status"], "ok"); + assert_ne!(a.data.key(), key); + assert_eq!(a.link_hash.as_deref(), Some(crate::asset_io::content_hash(&second).as_str())); + assert_eq!(a.data.load().unwrap().as_slice(), second); + + s.execute("edit.undo", &json!({})).unwrap(); + let a = asset_of(&s, id); + assert_eq!((a.data.key(), a.link_hash.clone()), (key, Some(crate::asset_io::content_hash(&first)))); + assert_eq!(row(&mut s, id)["status"], "modified"); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn embed_refuses_a_missing_link_and_unembed_links_to_the_original_or_into_a_folder() { + use designcraft_doc::Storage; + let dir = TempDir::new("embed"); + let path = dir.0.join("art.png"); + let (first, second) = same_size_pngs(); + std::fs::write(&path, &first).unwrap(); + set_age(&path, 60); + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let id = placed(&mut s, json!({"path": path.to_string_lossy()})); + + std::fs::remove_file(&path).unwrap(); + let before = s.doc().unwrap().doc.clone(); + let err = s.execute("links.embed", &json!({"asset": id.0})).unwrap_err().to_string(); + assert!(err.contains("missing"), "{err}"); + assert!(Arc::ptr_eq(&s.doc().unwrap().doc, &before)); + + std::fs::write(&path, &first).unwrap(); + s.execute("links.embed", &json!({"asset": id.0})).unwrap(); + let a = asset_of(&s, id); + assert_eq!((a.storage, a.data.embedded_bytes().map(|b| b.to_vec())), (Storage::Embedded, Some(first.clone()))); + assert_eq!(row(&mut s, id)["status"], "embedded"); + + // The original still holds the bytes: linked to it again. + let r = s.execute("links.unembed", &json!({"asset": id.0})).unwrap(); + assert_eq!(r["path"].as_str(), path.to_str()); + assert_eq!(asset_of(&s, id).storage, Storage::Linked); + assert_eq!(row(&mut s, id)["status"], "ok"); + + // Changed since: no original, so the bytes are written into `dir` (and found there next time). + s.execute("links.embed", &json!({"asset": id.0})).unwrap(); + std::fs::write(&path, &second).unwrap(); + assert!(s.execute("links.unembed", &json!({"asset": id.0})).is_err(), "no original and no folder"); + let out = dir.0.join("out"); + std::fs::create_dir_all(&out).unwrap(); + let r = s.execute("links.unembed", &json!({"asset": id.0, "dir": out.to_string_lossy()})).unwrap(); + let written = out.join("art.png"); + assert_eq!(r["path"].as_str(), written.to_str()); + assert_eq!(std::fs::read(&written).unwrap(), first); + let r = row(&mut s, id); + assert_eq!((r["storage"].as_str(), r["status"].as_str()), (Some("linked"), Some("ok"))); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(asset_of(&s, id).storage, Storage::Embedded); + s.execute("links.unembed", &json!({"asset": id.0, "dir": out.to_string_lossy()})).unwrap(); + assert_eq!(std::fs::read_dir(&out).unwrap().count(), 1, "the file with the same bytes is reused"); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn every_image_the_place_cursor_loads_is_linked() { + let dir = TempDir::new("cursor"); + let files: Vec<_> = (0..3u32) + .map(|i| { + let path = dir.0.join(format!("{i}.png")); + std::fs::write(&path, png(10 + i, 10)).unwrap(); + json!({"path": path.to_string_lossy()}) + }) + .collect(); + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + s.execute("place.load", &json!({"files": files})).unwrap(); + crate::cmd::native_links::wait(&mut s); + s.execute("place.contactSheet", &json!({})).unwrap(); + let d = &s.doc().unwrap().doc; + let used = d.used_assets(); + assert_eq!(used.len(), 3); + assert!(used.iter().all(|id| d.assets[id].storage == designcraft_doc::Storage::Linked && d.assets[id].data.is_linked())); +} diff --git a/crates/engine/src/cmd/mathexpr.rs b/crates/engine/src/cmd/mathexpr.rs index 0c8a120c3..44171e098 100644 --- a/crates/engine/src/cmd/mathexpr.rs +++ b/crates/engine/src/cmd/mathexpr.rs @@ -2,8 +2,6 @@ //! text insertion point (an anchored object) or as a frame. The LaTeX is kept as the object's //! alt text, so it can be edited and exports accessibly. -use std::sync::Arc; - use designcraft_doc::{Asset, AssetId, Content, Graphic, Item, ItemId, Shape}; use designcraft_geom::{Affine, Rect, shapes}; use serde_json::{Value, json}; @@ -14,7 +12,13 @@ use crate::{Result, Session}; fn math_item(d: &mut designcraft_doc::Document, latex: &str, size: f64, lid: designcraft_doc::LayerId, at: (f64, f64)) -> Item { let (svg, (w, h)) = crate::math::to_svg(latex, size); let fresh = AssetId(d.alloc()); - let aid = d.add_asset(Asset { id: fresh, name: "math.svg".into(), mime: "image/svg+xml".into(), data: Arc::new(svg), ..Default::default() }); + let aid = d.add_asset(Asset { + id: fresh, + name: "math.svg".into(), + mime: "image/svg+xml".into(), + data: designcraft_doc::AssetData::embedded(svg), + ..Default::default() + }); let id = ItemId(d.alloc()); let r = Rect::new(at.0, at.1, at.0 + w, at.1 + h); let mut it = Item::new(id, lid, Shape::Rectangle, shapes::rectangle(r)); diff --git a/crates/engine/src/cmd/media.rs b/crates/engine/src/cmd/media.rs index eab1027f6..deb4abf38 100644 --- a/crates/engine/src/cmd/media.rs +++ b/crates/engine/src/cmd/media.rs @@ -1,8 +1,6 @@ //! Window › Interactive › Media: placed video and sound (shown as a poster or a placeholder, //! exported as `