Merge current release into native format cutover

This commit is contained in:
Dylan M. Taylor committed 2026-11-14 22:30:51 +00:00
commit 494c07f53a
276 files changed
+33388 -2574

No files matched your search

+1 -45
View File
@@ -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
+2
View File
@@ -18,4 +18,6 @@ jobs:
sonarcloud:
# Tracked at @main so org-wide CI improvements propagate without PR churn.
uses: storytold/craft-common-actions/.github/workflows/sonarcloud.yml@main
with:
fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
secrets: inherit
Generated
+48 -39
View File
@@ -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",
]
+4 -2
View File
@@ -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"
+38 -4
View File
@@ -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.
+1 -1
View File
@@ -169,7 +169,7 @@ pub fn synthetic(spec: &Spec) -> Result<Document, String> {
id,
name: format!("art-{k}.png"),
mime: "image/png".into(),
data: Arc::new(data),
data: designcraft_doc::AssetData::embedded(data),
pixels: Some((aw, ah)),
..Default::default()
}),
+38 -1
View File
@@ -1,4 +1,4 @@
//! Pure browser startup and download metadata policies.
//! Browser startup, download metadata, and atomic import policies.
/// Query flags are case-sensitive decoded keys. Values are ignored: `?sample=false`
/// still enables sample startup, and repeated keys have the same presence semantics.
@@ -65,3 +65,40 @@ mod tests {
}
}
}
/// Read a drop in order, publishing nothing unless every file can be read.
pub(crate) async fn read_batch<T, R, E, F, Fut>(files: impl IntoIterator<Item = T>, mut read: F) -> Result<Vec<R>, E>
where
F: FnMut(T) -> Fut,
Fut: std::future::Future<Output = Result<R, E>>,
{
let mut result = Vec::new();
for file in files {
result.push(read(file).await?);
}
Ok(result)
}
#[cfg(test)]
mod batch_tests {
#[test]
fn failed_read_aborts_the_whole_batch() {
use std::{
future::Future,
task::{Context, Poll, Waker},
};
let mut seen = Vec::new();
let result = {
let future = super::read_batch([1, 2, 3], |n| {
seen.push(n);
std::future::ready(if n == 2 { Err("read failed") } else { Ok(n) })
});
let mut future = std::pin::pin!(future);
future.as_mut().poll(&mut Context::from_waker(Waker::noop()))
};
assert_eq!(result, Poll::Ready(Err("read failed")));
assert_eq!(seen, [1, 2]);
let mut success = std::pin::pin!(super::read_batch([3, 1], |n| std::future::ready(Ok::<_, ()>(n))));
assert_eq!(success.as_mut().poll(&mut Context::from_waker(Waker::noop())), Poll::Ready(Ok(vec![3, 1])));
}
}
+40 -11
View File
@@ -76,7 +76,7 @@ pub fn start() {
if has_query_flag(&query(), "sample") {
let _ = app.run("file.newSample", serde_json::json!({}));
}
Ok(Box::new(WebShell { app, inbox, graphics: creator_graphics }))
Ok(Box::new(WebShell { app, inbox, read_errors: Default::default(), graphics: creator_graphics }))
}),
)
.await;
@@ -344,12 +344,18 @@ fn query() -> String {
struct WebShell {
app: DesignApp,
inbox: Inbox,
/// Why a dropped file couldn't be read, for the status bar (the read finishes outside a frame).
read_errors: std::sync::Arc<std::sync::Mutex<Vec<String>>>,
graphics: GraphicsState,
}
impl eframe::App for WebShell {
fn logic(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
let graphics = self.graphics.clone();
let errors = std::mem::take(&mut *self.read_errors.lock().unwrap_or_else(|e| e.into_inner()));
if let Some(error) = errors.into_iter().last() {
self.app.status(error);
}
let _ = graphics.run_if_healthy(|| self.app.logic(ctx));
}
@@ -357,18 +363,34 @@ impl eframe::App for WebShell {
let _ = self.graphics.run_if_healthy(|| {
// Dropped files belong to this host iteration's raw input, not to stale logic input:
// read them here once, before the batch is saved as pending for a hidden pass.
for f in std::mem::take(&mut raw.dropped_files) {
// Files dropped together arrive together, in their order, so several images load the
// place cursor as one batch.
let dropped = std::mem::take(&mut raw.dropped_files);
if !dropped.is_empty() {
let request = self.app.import_request("drop");
let inbox = self.inbox.clone();
let read_errors = self.read_errors.clone();
let ctx = ctx.clone();
wasm_bindgen_futures::spawn_local(async move {
let name = f.path().file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| "dropped".into());
match f.bytes_async().await {
Ok(bytes) => {
inbox.lock().unwrap_or_else(|e| e.into_inner()).push(ImportedFile { request, name, bytes });
let files = crate::browser_policy::read_batch(dropped, |f| {
let request = request.clone();
async move {
let name = f.path().file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| "dropped".into());
let bytes = f.bytes_async().await.map_err(|e| format!("couldn't read dropped file {name}: {e}"))?;
Ok::<_, String>(ImportedFile { request, name, bytes })
}
})
.await;
match files {
Ok(files) => {
inbox.lock().unwrap_or_else(|e| e.into_inner()).extend(files);
ctx.request_repaint();
}
Err(error) => {
log::error!("{error}");
read_errors.lock().unwrap_or_else(|e| e.into_inner()).push(error);
ctx.request_repaint();
}
Err(e) => log::error!("couldn't read dropped file {name}: {e}"),
}
});
}
@@ -402,11 +424,18 @@ fn services(inbox: Inbox, ctx: egui::Context) -> Services {
rfd::AsyncFileDialog::new().add_filter("DesignCraft, IDML or InDesign", DOC_EXTS)
};
wasm_bindgen_futures::spawn_local(async move {
let Some(file) = dialog.pick_file().await else {
return;
// Place takes several files, loaded into the place cursor in the order chosen.
let handles = if request.purpose == "place" {
dialog.pick_files().await.unwrap_or_default()
} else {
dialog.pick_file().await.into_iter().collect()
};
let bytes = file.read().await;
inbox.lock().unwrap_or_else(|e| e.into_inner()).push(ImportedFile { request, name: file.file_name(), bytes });
let mut files = Vec::with_capacity(handles.len());
for file in handles {
let bytes = file.read().await;
files.push(ImportedFile { request: request.clone(), name: file.file_name(), bytes });
}
inbox.lock().unwrap_or_else(|e| e.into_inner()).extend(files);
ctx.request_repaint();
});
})),
+5 -3
View File
@@ -27,7 +27,8 @@ winresource = "0.1"
# Not called here: craft-dialogs shows the dialogs. rfd's default features keep its Wayland
# support on, so portal dialogs get the window as their parent.
rfd = { workspace = true }
arboard = { workspace = true }
# `image-data`: Edit › Paste reads bitmaps from the clipboard (src/clipboard_image.rs).
arboard = { workspace = true, features = ["image-data"] }
[target.'cfg(all(unix, not(target_os = "macos")))'.dependencies]
# The same winit eframe uses: to pick the X11 backend (file drag-and-drop) in main.rs.
@@ -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.
+135
View File
@@ -0,0 +1,135 @@
//! The system clipboard's image for Edit › Paste (`Services::clipboard_image`): a bitmap
//! (Windows `CF_DIBV5` or `PNG`, the macOS pasteboard's TIFF or PNG, `image/png` on X11), else the
//! first image file of files copied in a file manager. The read runs on its own thread, and Paste
//! waits for it at most [`WAIT`], so an application that is slow to hand over the clipboard does
//! not freeze the window. While a read that timed out is still waiting, Paste starts no other.
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc;
use std::time::Duration;
use designcraft_ui_egui::ClipboardImage;
/// How long Paste waits for the clipboard's image.
const WAIT: Duration = Duration::from_millis(1500);
/// The largest image file Paste reads from a copied file list, in bytes.
const MAX_FILE_BYTES: u64 = 256 << 20;
/// A clipboard read is running.
static READING: AtomicBool = AtomicBool::new(false);
/// The clipboard's image, or `None` when it holds none or does not answer within [`WAIT`].
pub fn read() -> Option<ClipboardImage> {
within(&READING, WAIT, read_now)
}
/// Clears the in-flight flag when the read's thread ends.
struct Reading(&'static AtomicBool);
impl Drop for Reading {
fn drop(&mut self) {
self.0.store(false, Ordering::Release);
}
}
/// `read`'s result when it arrives within `wait`. A read that takes longer finishes on its own
/// thread and is dropped; until it does, `busy` stays set and no other read starts.
fn within<T: Send + 'static>(busy: &'static AtomicBool, wait: Duration, read: impl FnOnce() -> Option<T> + Send + 'static) -> Option<T> {
if busy.swap(true, Ordering::AcqRel) {
log::warn!("clipboard image: the previous read has not finished");
return None;
}
let (tx, rx) = mpsc::channel();
let spawned = std::thread::Builder::new().name("clipboard image".into()).spawn(move || {
let _reading = Reading(busy);
let _ = tx.send(read());
});
if let Err(e) = spawned {
busy.store(false, Ordering::Release);
log::warn!("clipboard image: no thread to read it: {e}");
return None;
}
match rx.recv_timeout(wait) {
Ok(image) => image,
Err(mpsc::RecvTimeoutError::Timeout) => {
log::warn!("clipboard image: the clipboard did not answer within {} ms", wait.as_millis());
None
}
Err(mpsc::RecvTimeoutError::Disconnected) => None,
}
}
/// The general pasteboard's change count, which AppKit raises with every copy.
#[cfg(target_os = "macos")]
pub fn change_count() -> Option<i64> {
i64::try_from(objc2_app_kit::NSPasteboard::generalPasteboard().changeCount()).ok()
}
fn read_now() -> Option<ClipboardImage> {
let mut clipboard = arboard::Clipboard::new().ok()?;
if let Ok(image) = clipboard.get_image() {
let width = u32::try_from(image.width).ok()?;
let height = u32::try_from(image.height).ok()?;
return Some(ClipboardImage::Pixels { width, height, rgba: image.bytes.into_owned() });
}
first_image_file(&clipboard.get().file_list().ok()?)
}
/// The first of `paths` that is an image file no larger than [`MAX_FILE_BYTES`], with its name.
fn first_image_file(paths: &[PathBuf]) -> Option<ClipboardImage> {
paths.iter().find_map(|path| {
let ext = path.extension()?.to_str()?.to_ascii_lowercase();
if !designcraft_engine::cmd::IMAGE_EXTENSIONS.contains(&ext.as_str()) || std::fs::metadata(path).ok()?.len() > MAX_FILE_BYTES {
return None;
}
// At most one byte past the limit is read, should the file grow after the size check.
let bytes = designcraft_engine::io::read_capped(path, MAX_FILE_BYTES).ok().filter(|b| b.len() as u64 <= MAX_FILE_BYTES)?;
Some(ClipboardImage::File { name: file_name(path), bytes })
})
}
fn file_name(path: &Path) -> String {
path.file_name().map_or_else(|| path.to_string_lossy().into_owned(), |n| n.to_string_lossy().into_owned())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_read_that_does_not_answer_is_given_up_and_no_second_one_starts_meanwhile() {
static BUSY: AtomicBool = AtomicBool::new(false);
let (release, blocked) = mpsc::channel::<()>();
// The read waits for a message that is only sent after Paste has given up on it.
assert_eq!(within(&BUSY, Duration::ZERO, move || blocked.recv().ok().map(|()| 1)), None);
let (started, ran) = mpsc::channel::<()>();
let second = within(&BUSY, Duration::from_secs(60), move || started.send(()).ok().map(|()| 2));
assert_eq!(second, None, "refused while the first read waits");
assert!(ran.try_recv().is_err(), "the second read never ran");
let _ = release.send(());
while BUSY.load(Ordering::Acquire) {
std::thread::yield_now();
}
assert_eq!(within(&BUSY, Duration::from_secs(60), || Some(3)), Some(3), "an answer is taken as soon as it comes");
}
#[test]
fn a_copied_file_list_pastes_its_first_image_file() {
let stamp = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos();
let dir = std::env::temp_dir().join(format!("designcraft-clipboard-files-{}-{stamp}", std::process::id()));
std::fs::create_dir(&dir).unwrap();
let (text, missing, png) = (dir.join("notes.txt"), dir.join("gone.png"), dir.join("Photo.PNG"));
std::fs::write(&text, b"text").unwrap();
std::fs::write(&png, b"png bytes").unwrap();
let picked = first_image_file(&[text, missing, png.clone()]);
let none = first_image_file(&[dir.join("a.txt")]);
let _ = std::fs::remove_dir_all(&dir);
match picked {
Some(ClipboardImage::File { name, bytes }) => assert_eq!((name.as_str(), bytes.as_slice()), ("Photo.PNG", b"png bytes".as_slice())),
_ => panic!("the image file is picked"),
}
assert!(none.is_none());
}
}
+4
View File
@@ -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()
+28 -1
View File
@@ -11,6 +11,33 @@ pub fn screen_position() -> Option<egui::Pos2> {
// 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<egui::Pos2> {
let y = main_height - y;
(x.is_finite() && y.is_finite()).then(|| egui::pos2(x as f32, y as f32))
}
#[cfg(test)]
mod tests {
use super::from_appkit;
#[test]
fn appkit_points_flip_against_the_main_display_only() {
// The main display is 1000 points high: its top left is (0, 0), its bottom left (0, 1000).
assert_eq!(from_appkit(0.0, 1000.0, 1000.0), Some(egui::pos2(0.0, 0.0)));
assert_eq!(from_appkit(200.0, 100.0, 1000.0), Some(egui::pos2(200.0, 900.0)));
// A second display above the main one, and one to its left: negative, as winit reports a
// window there.
assert_eq!(from_appkit(300.0, 1200.0, 1000.0), Some(egui::pos2(300.0, -200.0)));
assert_eq!(from_appkit(-800.0, 500.0, 1000.0), Some(egui::pos2(-800.0, 500.0)));
assert_eq!(from_appkit(f64::NAN, 0.0, 1000.0), None);
assert_eq!(from_appkit(0.0, 0.0, f64::INFINITY), None);
}
}
+4
View File
@@ -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
+96 -7
View File
@@ -5,13 +5,19 @@
//! wrapping item on the frames' spreads, and the same for every story whose anchored objects wrap
//! its text ([`crate::wrap::neighbours`]). An anchored frame's entry also records where its host
//! story's composition places it. Entries hold clones of those `Arc`s, so the pointers
//! can't be reused by other allocations while the entry lives.
//! can't be reused by other allocations while the entry lives. The document's Alpha Channel
//! outlines count by serial number, which no other outline shares.
//!
//! When only the story itself differs from an entry's (an edit of its text or formatting), the
//! new composition starts from the entry's and composes the paragraphs the edit can change
//! ([`crate::reuse`]).
use std::collections::{HashMap, 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<Story>, Arc<Styles>, Vec<Arc<Item>>, Vec<Arc<Story>>),
out: Arc<ComposedStory>,
stamp: u64,
/// For composing the story again after an edit ([`crate::reuse`]).
trace: Option<Arc<Trace>>,
}
/// The story an entry was composed from, its composition and that composition's trace.
type Before = (Arc<Story>, Arc<ComposedStory>, Arc<Trace>);
/// How many leading values of a [`signature`] identify the story's own allocation and revision;
/// the rest is everything else the composition was made from.
const STORY_SIG: usize = 2;
impl Entry {
/// What composing for `sig` can take from this entry: set when only the story itself differs
/// (an edit of its text or formatting) and the entry's composition left a trace.
fn before(&self, sig: &[usize]) -> Option<Before> {
let trace = self.trace.as_ref()?;
(self.sig.len() == sig.len() && self.sig.get(STORY_SIG..) == sig.get(STORY_SIG..))
.then(|| (self._keep.0.clone(), self.out.clone(), trace.clone()))
}
}
#[derive(Default)]
@@ -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<HashMap<StoryId, (Vec<usize>, Arc<ComposedStory>)>>,
/// A cache this one reads without writing to: a composition or index found there for the same
/// inputs is used, and anything composed is kept here only.
base: Option<Arc<Cache>>,
}
/// A signature's hash, standing in for it in another story's signature.
@@ -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<Cache>) -> Self {
Cache { base: Some(base), ..Self::default() }
}
/// The cache given to [`Cache::over`].
pub fn base(&self) -> Option<&Arc<Cache>> {
self.base.as_ref()
}
/// The composed story, from cache or freshly composed. `page` is the absolute page a
/// parent-page item is shown on (its page number markers and variables are that page's), or
/// `None` for a story's own frames. Pages are identified by index, not name: names repeat when
@@ -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<crate::Placement> {
let mut resolved = Resolved::new();
let placed = crate::placed::placements(doc, sid, &mut |host| self.resolve(doc, host, true, 1, &mut resolved));
placed.into_iter().find_map(|(id, p)| (id == fid).then_some(p))
}
/// [`Cache::get_on`], wrapped by other stories' anchored objects only when `cross` is set, for
/// a story `depth` hosts down from the story asked for.
fn get_with(&self, doc: &Document, sid: StoryId, on: ShownOn, cross: bool, depth: usize, resolved: &mut Resolved) -> Arc<ComposedStory> {
@@ -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<Arc<ComposedStory>> = 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::<Vec<_>>(),
));
before.as_ref().map(|(story, composed, trace)| Reuse { story, composed, trace }),
);
let (out, trace) = (Arc::new(out), trace.map(Arc::new));
let mut g = self.map.lock().unwrap_or_else(PoisonError::into_inner);
let stamp = g.1;
if g.0.len() > 4096 {
g.0.retain(|_, e| stamp - e.stamp < 64);
}
let replaced = g.0.insert(key, Entry { sig, _keep: (story.clone(), doc.styles.clone(), keep_items, keep_stories), out: out.clone(), stamp });
let replaced =
g.0.insert(key, Entry { sig, _keep: (story.clone(), doc.styles.clone(), keep_items, keep_stories), out: out.clone(), stamp, trace });
drop(g);
// Only the composition that is shown (not one made for another story's wrap).
if key.1 == ShownOn::Own
@@ -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<Story>) -> (Vec<usize>, Vec<Arc<Item>>)
sections_hash(doc) as usize,
doc.font_scope as usize,
usize::from(g.relative_to == designcraft_doc::GridRelative::TopMargin),
outlines_hash(doc) as usize,
];
sig.extend([g.start, g.increment].into_iter().flat_map(bits));
let mut keep = Vec::new();
+53 -5
View File
@@ -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<Vec<(Range<usize>, 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<usize>) -> bool,
) -> Result<Vec<(Range<usize>, String)>, GrepError> {
let exp = fancy_regex::Expander::default();
let mut out = Vec::new();
let mut bytes = 0usize;
for caps in self.re.captures_iter(text) {
let caps = caps.map_err(run_err)?;
let Some(m) = caps.get(0) else { continue };
out.push((m.range(), exp.expansion(template, &caps)));
if !keep(&m.range()) {
continue;
}
// Written into a buffer that refuses bytes past the budget, so an oversized
// expansion is rejected before it is allocated.
let mut w = BoundedBuf { buf: Vec::new(), left: max_bytes.saturating_sub(bytes) };
if exp.write_expansion(&mut w, template, &caps).is_err() {
return Err(err(format!("the replacements would put more than {max_bytes} bytes in")));
}
bytes += w.buf.len();
let expanded = String::from_utf8(w.buf).map_err(|_| err("the replacement is not valid UTF-8".to_string()))?;
out.push((m.range(), expanded));
if first_only {
break;
}
@@ -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<u8>,
left: usize,
}
impl std::io::Write for BoundedBuf {
fn write(&mut self, data: &[u8]) -> std::io::Result<usize> {
if data.len() > self.left {
return Err(std::io::ErrorKind::OutOfMemory.into());
}
self.left -= data.len();
self.buf.extend_from_slice(data);
Ok(data.len())
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
fn run_err(e: fancy_regex::Error) -> GrepError {
err(format!("GREP search stopped: {e}"))
}
@@ -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]
+1066 -136
View File
File diff suppressed because it is too large. Load diff
+21
View File
@@ -59,11 +59,32 @@ impl FrameOutline {
Some(FrameOutline { edges, inset })
}
/// The outline of `item`'s path with its corner options applied, or None when that is the
/// item's own rectangle. The composer and the Properties panel's one Inset field both use it.
pub fn of_item(item: &designcraft_doc::Item, inset: f64) -> Option<FrameOutline> {
let bp = if item.corners.is_none() { item.path.to_bezpath() } else { designcraft_geom::corners::apply(&item.path, &item.corners) };
FrameOutline::new(&bp, inset)
}
/// The outline mapped by `xf` (into a vertical frame's turned box).
pub fn transformed(&self, xf: Affine) -> FrameOutline {
FrameOutline { edges: self.edges.iter().map(|&(a, b)| (xf * a, xf * b)).collect(), inset: self.inset }
}
/// The distance kept between text and the outline.
pub fn inset(&self) -> f64 {
self.inset
}
/// The heights of the outline's corners, sorted and without repeats: the inside intervals of a
/// scanline change linearly between two of them.
pub fn corner_heights(&self) -> Vec<f64> {
let mut ys: Vec<f64> = self.edges.iter().map(|(a, _)| a.y).collect();
ys.sort_by(f64::total_cmp);
ys.dedup_by(|a, b| (*a - *b).abs() < 1e-9);
ys
}
/// The parts of `[x0, x1]` inside the outline over the whole band `[y0, y1]`, at least the
/// inset away from it: the inside intervals at every height of the band are intersected, and
/// the inset is kept by testing the heights within the inset above and below the band, each
+29 -11
View File
@@ -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<Placement> {
/// Where the host story of `fid`, an anchored frame of story `sid`, places it: in its frames'
/// anchored objects, footnotes and table cells. A host frame that is itself anchored is placed
/// the same way first, up to [`MAX_DEPTH`] hosts out. `items` is [`Document::anchored_items`].
fn locate(
doc: &Document,
items: &[(StoryId, &Item)],
sid: StoryId,
fid: ItemId,
hosts: &mut HashMap<StoryId, Arc<ComposedStory>>,
host: &mut dyn FnMut(StoryId) -> Arc<ComposedStory>,
depth: usize,
) -> Option<Placement> {
if depth > MAX_DEPTH {
return None;
}
// A frame anchored in its own story would need its own composition to place it.
let owner = items.iter().find_map(|(owner, it)| (it.id == fid).then_some(*owner)).filter(|o| *o != sid)?;
let cs = hosts.entry(owner).or_insert_with(|| host(owner)).clone();
cs.frames.iter().find_map(|ft| {
let loc = doc.find(ft.frame)?;
let frame = doc.item_at(&loc)?;
let xf = in_frame(ft, doc.parent_xf(&loc) * doc.text_xf(frame), fid, 0)?;
Some(Placement { spread: loc.spread, xf })
if let Some(loc) = doc.find(ft.frame) {
let frame = doc.item_at(&loc)?;
let xf = in_frame(ft, doc.parent_xf(&loc) * doc.text_xf(frame), fid, 0)?;
return Some(Placement { spread: loc.spread, xf });
}
// The host frame is anchored too: find `fid` in it before placing the frame.
let local = in_frame(ft, Affine::IDENTITY, fid, 0)?;
let frame = items.iter().find_map(|(_, it)| (it.id == ft.frame).then_some(*it))?;
let outer = locate(doc, items, owner, ft.frame, hosts, host, depth + 1)?;
Some(Placement { spread: outer.spread, xf: outer.xf * doc.text_xf(frame) * local })
})
}
+738
View File
@@ -0,0 +1,738 @@
//! Composing an edited story from the composition it had before the edit.
//!
//! A composition that laid every paragraph once leaves a [`Trace`]: the state it had before each
//! paragraph. Composing the story again after an edit starts at the paragraph before the first
//! changed one, in the state the trace holds for it and with the lines above it copied. It stops
//! at the first paragraph after the edit that it reaches in the state the trace holds for that
//! paragraph, and copies the lines from there on with their story offsets moved by the length of
//! the edit. The result is the composition a full pass over the edited story gives.
//!
//! Only plain stories are traced ([`plain`]): the features left out carry state between
//! paragraphs that the trace does not hold, or move lines after they are set. A composition that
//! goes back over a paragraph (keep options, column balancing, hyphenation across columns)
//! leaves no trace, and one that does so while it reuses a trace is abandoned for a full pass.
use std::rc::Rc;
use designcraft_doc::{CharRun, ListCounter, Story, VerticalJustification};
use crate::{Above, Band, ComposeOptions, ComposedStory, Cursor, FrameSpec, Line, ParaInfo, RunStyle, Snapshot};
#[cfg(test)]
thread_local! {
/// Paragraphs shaped on this thread (tests count the work an edit causes).
pub(crate) static SHAPED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
/// The composition's state before a paragraph: the cursor, the list numbering, and how much of
/// the cursor's frame and of the run style table is filled.
#[derive(Clone, Debug)]
struct Mark {
fi: usize,
col: usize,
last_baseline: Option<f64>,
last_descent: f64,
last_reference: f64,
aki_below: Option<f64>,
pending: f64,
band: Band,
grid_next: Option<(f64, f64)>,
list_counter: ListCounter,
lines: usize,
decos: usize,
styles: usize,
}
fn bits(v: Option<f64>) -> Option<u64> {
v.map(f64::to_bits)
}
fn above_bits(a: Option<Above>) -> Option<[Option<u64>; 6]> {
a.map(|a| {
[
Some(a.top.to_bits()),
Some(a.baseline.to_bits()),
Some(a.descent.to_bits()),
Some(a.reference.to_bits()),
bits(a.aki_below),
Some(a.pending.to_bits()),
]
})
}
impl Mark {
/// The state `snap` holds with `styles` run styles in the table, or `None` when it has state
/// a mark does not hold (a split-column block, balanced column bottoms, tables).
fn of(snap: &Snapshot, styles: usize) -> Option<Mark> {
let c = &snap.cur;
if c.split.is_some() || !c.limits.is_empty() || !c.split_limits.is_empty() || snap.tables != 0 {
return None;
}
Some(Mark {
fi: c.fi,
col: c.col,
last_baseline: c.last_baseline,
last_descent: c.last_descent,
last_reference: c.last_reference,
aki_below: c.aki_below,
pending: c.pending,
band: c.band,
grid_next: c.grid_next,
list_counter: snap.list_counter.clone(),
lines: snap.lines,
decos: snap.decos,
styles,
})
}
fn cursor(&self, pi: usize) -> Cursor {
Cursor {
fi: self.fi,
col: self.col,
last_baseline: self.last_baseline,
last_descent: self.last_descent,
last_reference: self.last_reference,
aki_below: self.aki_below,
pending: self.pending,
pi,
band: self.band,
limits: Rc::default(),
split: None,
split_limits: Rc::default(),
grid_next: self.grid_next,
}
}
/// The mark with its paragraph numbers after the edit.
fn moved(&self, plan: &Plan) -> Mark {
let band = Band { para: plan.moved(self.band.para), tail: self.band.tail.map(|(p, c)| (plan.moved(p), c)), ..self.band };
Mark { band, ..self.clone() }
}
/// Whether composing on from `self` and from `other` sets the same lines. Numbers are
/// compared by their bits: a difference too small to show still changes what follows.
fn same(&self, other: &Mark) -> bool {
let (a, b) = (&self.band, &other.band);
self.fi == other.fi
&& self.col == other.col
&& bits(self.last_baseline) == bits(other.last_baseline)
&& self.last_descent.to_bits() == other.last_descent.to_bits()
&& self.last_reference.to_bits() == other.last_reference.to_bits()
&& bits(self.aki_below) == bits(other.aki_below)
&& self.pending.to_bits() == other.pending.to_bits()
&& a.para == b.para
&& a.line0 == b.line0
&& above_bits(a.above) == above_bits(b.above)
&& a.tail == b.tail
&& self.grid_next.map(|(x, y)| (x.to_bits(), y.to_bits())) == other.grid_next.map(|(x, y)| (x.to_bits(), y.to_bits()))
&& self.list_counter == other.list_counter
&& self.lines == other.lines
&& self.decos == other.decos
&& self.styles == other.styles
}
}
/// What a composition leaves for composing the story again after an edit: its state before each
/// paragraph it laid (and after the last one), and where each paragraph sits.
#[derive(Debug)]
pub(crate) struct Trace {
marks: Vec<Mark>,
info: Vec<ParaInfo>,
}
/// A story as it was before an edit, its composition and that composition's trace.
#[derive(Clone, Copy)]
pub(crate) struct Reuse<'a> {
pub story: &'a Story,
pub composed: &'a ComposedStory,
pub trace: &'a Trace,
}
/// How much of the composition before an edit holds for the edited story.
pub(crate) struct Plan {
/// The paragraph composing starts at.
pub resume: usize,
/// The first paragraph (numbered as in the edited story) that may take the lines it had
/// before the edit: the one before it is unchanged too.
pub rejoin: usize,
/// Paragraphs and bytes the edit added.
paras: isize,
bytes: isize,
/// The first paragraph the edit left as it was, numbered as before the edit.
old_tail: usize,
}
impl Plan {
/// The number after the edit of paragraph `p` of the story before it.
fn moved(&self, p: usize) -> usize {
if p >= self.old_tail { p.wrapping_add_signed(self.paras) } else { p }
}
/// The number before the edit of paragraph `pi` of the edited story's unchanged end.
fn before(&self, pi: usize) -> Option<usize> {
pi.checked_add_signed(self.paras.checked_neg()?)
}
}
/// Whether a composition of `story` in `frames` can leave a trace, or use one. Footnotes,
/// endnotes, tables and anchored objects carry state of their own; named lists and tracked
/// deletions reach across paragraphs; vertical justification and column rules change a frame
/// after its lines are set; type on a path sizes its frame from the story; balanced columns are
/// laid more than once.
pub(crate) fn plain(story: &Story, frames: &[FrameSpec], opts: &ComposeOptions, labels: &[Option<String>], deleted: &[bool]) -> bool {
story.notes.is_empty()
&& story.endnotes.is_empty()
&& story.objects.is_empty()
&& story.tables.is_empty()
&& opts.label.is_none()
&& labels.iter().all(Option::is_none)
&& !deleted.contains(&true)
&& frames.iter().all(|f| {
let o = &f.opts;
o.vertical_justification == VerticalJustification::Top && !o.column_rule && o.path.is_none() && !(o.balance_columns && o.columns > 1)
})
}
/// Whether the paragraphs a composition laid are ones a trace covers: none spans or splits
/// columns (`span`, `split`, by paragraph) or has a border or shading (`boxes`), which are drawn
/// once every line is set.
pub(crate) fn plain_end<T>(span: &[bool], split: &[bool], boxes: &[Option<T>]) -> bool {
!span.contains(&true) && !split.contains(&true) && boxes.iter().all(Option::is_none)
}
/// Bytes of text from the start of both run lists (in the order given) that have the same
/// character formats.
fn same_formats<'a>(mut old: impl Iterator<Item = &'a CharRun>, mut new: impl Iterator<Item = &'a CharRun>) -> usize {
let mut same = 0usize;
let (mut a, mut b): (Option<(&CharRun, usize)>, Option<(&CharRun, usize)>) = (None, None);
loop {
if a.is_none_or(|(_, left)| left == 0) {
a = old.find(|r| r.len > 0).map(|r| (r, r.len));
}
if b.is_none_or(|(_, left)| left == 0) {
b = new.find(|r| r.len > 0).map(|r| (r, r.len));
}
let (Some((ra, la)), Some((rb, lb))) = (a, b) else { return same };
if ra.format != rb.format {
return same;
}
let step = la.min(lb);
same += step;
(a, b) = (Some((ra, la - step)), Some((rb, lb - step)));
}
}
fn returns(text: &str) -> usize {
text.bytes().filter(|b| *b == b'\n').count()
}
impl Reuse<'_> {
/// Where composing `new` (the story after the edit) starts and may stop, or `None` when the
/// edit changed something a trace does not cover.
pub(crate) fn plan(&self, new: &Story) -> Option<Plan> {
let old = self.story;
if old.frames != new.frames
|| old.direction != new.direction
|| old.vertical != new.vertical
|| old.optical_margin != new.optical_margin
|| old.anchors != new.anchors
|| old.xrefs != new.xrefs
|| old.index_refs != new.index_refs
|| old.editorial != new.editorial
{
return None;
}
let (o, n) = (old.text.as_bytes(), new.text.as_bytes());
if old.paras.len() != returns(&old.text) + 1 || new.paras.len() != returns(&new.text) + 1 {
return None;
}
// The unchanged start: the same text in the same character formats, then whole paragraphs
// with the same paragraph formats.
let mut head = o.iter().zip(n).take_while(|(a, b)| a == b).count().min(same_formats(old.chars.iter(), new.chars.iter()));
while !new.text.is_char_boundary(head) {
head -= 1;
}
let whole = returns(new.text.get(..head)?);
let first = old.paras.iter().zip(&new.paras).take(whole).take_while(|(a, b)| a == b).count();
if first < whole {
// A paragraph format changed above the first changed character.
head = match first.checked_sub(1) {
Some(k) => n.iter().enumerate().filter(|(_, b)| **b == b'\n').nth(k).map(|(i, _)| i + 1)?,
None => 0,
};
}
// The unchanged end, which the unchanged start does not overlap.
let room = o.len().min(n.len()).checked_sub(head)?;
let mut tail = o
.iter()
.rev()
.zip(n.iter().rev())
.take_while(|(a, b)| a == b)
.count()
.min(same_formats(old.chars.iter().rev(), new.chars.iter().rev()))
.min(room);
while !new.text.is_char_boundary(n.len() - tail) {
tail -= 1;
}
let after = returns(new.text.get(n.len() - tail..)?);
let after = old.paras.iter().rev().zip(new.paras.iter().rev()).take(after).take_while(|(a, b)| a == b).count();
let (old_paras, new_paras) = (old.paras.len(), new.paras.len());
Some(Plan {
// One paragraph above the first changed one: setting a paragraph reads the one after it.
resume: first.saturating_sub(1).min(self.trace.marks.len().checked_sub(1)?),
rejoin: new_paras.checked_sub(after)? + 1,
paras: isize::try_from(new_paras).ok()?.checked_sub(isize::try_from(old_paras).ok()?)?,
bytes: isize::try_from(n.len()).ok()?.checked_sub(isize::try_from(o.len()).ok()?)?,
old_tail: old_paras.checked_sub(after)?,
})
}
/// Put `out` and `styles` back as they were before paragraph `plan.resume`, and give the
/// cursor, list numbering and paragraph positions of that moment. `None` when the composition
/// before the edit does not match `out`'s frames.
pub(crate) fn restore(&self, plan: &Plan, out: &mut ComposedStory, styles: &mut Vec<RunStyle>) -> Option<(Cursor, ListCounter, Vec<ParaInfo>)> {
let mark = self.trace.marks.get(plan.resume)?;
let before = self.composed;
if before.frames.len() != out.frames.len() || before.frames.iter().zip(&out.frames).any(|(a, b)| a.frame != b.frame) {
return None;
}
let info = self.trace.info.get(..plan.resume)?.to_vec();
*styles = before.styles.get(..mark.styles)?.to_vec();
for (i, (to, from)) in out.frames.iter_mut().zip(&before.frames).enumerate().take(mark.fi.saturating_add(1)) {
let (lines, decos) = if i < mark.fi { (from.lines.len(), from.decos.len()) } else { (mark.lines, mark.decos) };
to.lines = from.lines.get(..lines)?.iter().map(|l| moved_line(l, 0, 0)).collect();
to.decos = from.decos.get(..decos)?.to_vec();
}
Some((mark.cursor(plan.resume), mark.list_counter.clone(), info))
}
/// At paragraph `pi` of the edited story, in the state `snap` with `styles` and `info` as
/// they are: when the composition before the edit was in that state before the same
/// paragraph, copy what it set from there on into `out`, `styles` and `info`, and say so.
///
/// The copied lines keep their run-style indexes, so this needs `styles` to equal the old
/// table up to that point. A run style that the edit uses for the first time takes a new
/// index, and the story then composes on until the old composition added the same style at
/// the same index, or to its end. The result is the same; only the time differs.
pub(crate) fn rejoin(
&self,
plan: &Plan,
pi: usize,
snap: &Snapshot,
out: &mut ComposedStory,
styles: &mut Vec<RunStyle>,
info: &mut Vec<ParaInfo>,
) -> bool {
let before = self.composed;
let Some(k) = plan.before(pi) else { return false };
let (Some(old), Some(new)) = (self.trace.marks.get(k), Mark::of(snap, styles.len())) else { return false };
// The paragraph above is where it was, and no chain of keep-with-next paragraphs reaches
// back through it into the changed text.
let last = |v: &[ParaInfo], i: usize| i.checked_sub(1).and_then(|i| v.get(i).cloned());
let same_above = matches!((last(&self.trace.info, k), last(info, pi)), (Some(a), Some(b)) if a == b && a.keep_with_next == 0);
if !same_above || info.len() != pi || !old.moved(plan).same(&new) || before.styles.get(..old.styles) != Some(styles.as_slice()) {
return false;
}
for (i, (to, from)) in out.frames.iter_mut().zip(&before.frames).enumerate().skip(old.fi) {
let (lines, decos) = if i == old.fi { (old.lines, old.decos) } else { (0, 0) };
to.lines.extend(from.lines.get(lines..).unwrap_or_default().iter().map(|l| moved_line(l, plan.bytes, plan.paras)));
to.decos.extend(from.decos.get(decos..).unwrap_or_default().iter().cloned());
}
out.overset_at = before.overset_at.map(|b| b.wrapping_add_signed(plan.bytes));
styles.clone_from(&before.styles);
info.extend(self.trace.info.get(k..).unwrap_or_default().iter().cloned());
true
}
}
/// `line` with its story offsets and paragraph number moved, and without the keep-violation
/// flag, which is set again for the whole story once it is composed.
fn moved_line(line: &Line, bytes: isize, paras: isize) -> Line {
let at = |b: usize| b.wrapping_add_signed(bytes);
let mut l = Line { keep_violation: false, ..line.clone() };
l.range = at(l.range.start)..at(l.range.end);
l.para = l.para.wrapping_add_signed(paras);
if bytes != 0 {
for g in &mut l.glyphs {
g.byte = at(g.byte);
}
}
if let Some(cap) = &mut l.drop_cap {
cap.end = at(cap.end);
}
l
}
/// What one composition keeps for its trace, and what it reuses of the composition before an
/// edit.
pub(crate) struct Pass<'a> {
before: Option<(&'a Reuse<'a>, Plan)>,
/// The composition was to reuse the one before an edit and cannot: its result is not used.
abandoned: bool,
/// A trace is wanted and nothing rules one out so far.
traced: bool,
/// Run styles in the table before each paragraph.
styles: Vec<usize>,
/// The paragraph the next step should be at: another one means the layout went back over a
/// paragraph.
next: usize,
/// The paragraph the lines copied from before the edit start at.
rejoined: Option<usize>,
}
/// Where a composition starts: the paragraph, the cursor, the list numbering and the positions
/// of the paragraphs above.
pub(crate) struct Start {
pub pi: usize,
pub cur: Cursor,
pub list_counter: ListCounter,
pub info: Vec<ParaInfo>,
}
impl<'a> Pass<'a> {
/// The bookkeeping for composing `story`, and where to start. `traced`: a trace is wanted and
/// the story is [`plain`]. `fresh` is the start of the story. With `before`, `out` and
/// `styles` are filled with what holds from before the edit and the start is the paragraph
/// above the edit; when `before` cannot be used the pass is abandoned at its first step.
pub(crate) fn new(
before: Option<&'a Reuse<'a>>,
story: &Story,
traced: bool,
fresh: Start,
out: &mut ComposedStory,
styles: &mut Vec<RunStyle>,
) -> (Pass<'a>, Start) {
let mut pass = Pass { before: None, abandoned: false, traced, styles: Vec::with_capacity(story.paras.len() + 1), next: 0, rejoined: None };
let Some(b) = before else { return (pass, fresh) };
let resumed = traced.then(|| b.plan(story)).flatten().and_then(|plan| Some((b.restore(&plan, out, styles)?, plan)));
let Some(((cur, list_counter, info), plan)) = resumed else {
pass.abandoned = true;
return (pass, fresh);
};
let pi = plan.resume;
// The counts for the paragraphs above are never read: their marks are kept as they are.
pass.styles.resize(pi, 0);
pass.next = pi;
pass.before = Some((b, plan));
(pass, Start { pi, cur, list_counter, info })
}
/// Before paragraph `pi` of `count` is laid, in the state `snap`: whether nothing is left to
/// lay, because the rest of the story is in place (copied from the composition before the
/// edit into `out`, `styles` and `info`) or because the pass is abandoned.
pub(crate) fn step(
&mut self,
(pi, count): (usize, usize),
snap: Option<&Snapshot>,
out: &mut ComposedStory,
styles: &mut Vec<RunStyle>,
info: &mut Vec<ParaInfo>,
) -> bool {
self.styles.truncate(pi);
self.styles.push(styles.len());
if pi != self.next {
// The layout went back over a paragraph.
self.traced = false;
self.abandoned |= self.before.is_some();
}
self.next = pi + 1;
if self.abandoned {
return true;
}
if pi < count
&& let (Some((before, plan)), Some(snap)) = (&self.before, snap)
&& pi >= plan.rejoin
&& before.rejoin(plan, pi, snap, out, styles, info)
{
self.rejoined = Some(pi);
return true;
}
false
}
/// The trace of the finished composition, when it laid every paragraph once and `plain_end`
/// (no paragraph it laid uses something a trace does not cover): `snaps` holds the state
/// before each paragraph it laid itself, `info` every paragraph's position. The paragraphs
/// above the one a reusing composition started at keep the marks they had, and those after
/// the one it rejoined at the marks that followed before the edit. The outer `None` is for an
/// abandoned pass and for a reusing one that leaves no trace: the story has to be composed
/// from its start.
pub(crate) fn trace(self, plain_end: bool, snaps: &[Snapshot], info: Vec<ParaInfo>) -> Option<Option<Trace>> {
if self.abandoned {
return None;
}
let trace = if self.traced && plain_end { self.marks(snaps).map(|marks| Trace { marks, info }) } else { None };
if self.before.is_some() && trace.is_none() {
return None;
}
Some(trace)
}
fn marks(&self, snaps: &[Snapshot]) -> Option<Vec<Mark>> {
let reused = self.before.as_ref();
let start = reused.map_or(0, |(_, plan)| plan.resume);
let mut marks = Vec::with_capacity(snaps.len());
if let Some((before, _)) = reused {
marks.extend(before.trace.marks.get(..start)?.iter().cloned());
}
for (snap, styles) in snaps.iter().zip(&self.styles).skip(start) {
marks.push(Mark::of(snap, *styles)?);
}
if let (Some((before, plan)), Some(pi)) = (reused, self.rejoined) {
let k = plan.before(pi)?;
marks.extend(before.trace.marks.get(k + 1..)?.iter().map(|m| m.moved(plan)));
}
// Lines are only ever added to the cursor's frame, so the frames above it are complete.
marks.windows(2).all(|w| w[0].fi <= w[1].fi).then_some(marks)
}
}
#[cfg(test)]
mod tests {
use designcraft_doc::build::NewDocument;
use designcraft_doc::{Align, Document, ItemId, ListType, ParaFormat, SpreadRef, StartParagraph, Story, StoryId, VerticalJustification};
use designcraft_geom::Rect;
use super::SHAPED;
use crate::Cache;
const SENTENCE: &str = "The quick brown fox jumps over the lazy dog while the workbook keeps growing page by page.";
/// A story of `paras` paragraphs of two to five lines, threaded through `frames` frames of 31
/// lines each.
fn threaded(paras: usize, frames: usize) -> (Document, StoryId, Vec<ItemId>) {
let mut d = Document::new(&NewDocument::default());
let lid = d.default_layer();
let text = (0..paras).map(|i| vec![SENTENCE; 2 + i % 4].join(" ")).collect::<Vec<_>>().join("\n");
let rect = |i: usize| Rect::new(i as f64 * 600.0, 0.0, i as f64 * 600.0 + 540.0, 456.0);
let (first, sid) = d.add_text_frame(SpreadRef::Doc(0), rect(0), lid, &text, ParaFormat::default()).unwrap();
let mut ids = vec![first];
for i in 1..frames {
let (next, _) = d.add_text_frame(SpreadRef::Doc(0), rect(i), lid, "", ParaFormat::default()).unwrap();
d.thread(ids[i - 1], next).unwrap();
ids.push(next);
}
(d, sid, ids)
}
/// What `f` returns and the paragraphs it shaped.
fn shaped<T>(f: impl FnOnce() -> T) -> (T, usize) {
SHAPED.with(|n| n.set(0));
let out = f();
(out, SHAPED.with(|n| n.get()))
}
/// Compose the edited story through `cache`, which holds its composition before the edit, and
/// check the result against composing it whole. Gives the paragraphs the cache shaped.
fn check(cache: &Cache, d: &Document, sid: StoryId, what: &str) -> usize {
let (cached, n) = shaped(|| cache.get(d, sid, None));
let whole = Cache::new().get(d, sid, None);
assert_eq!(cached.frames.len(), whole.frames.len(), "{what}");
for (fi, (a, b)) in cached.frames.iter().zip(&whole.frames).enumerate() {
assert_eq!(a.lines.len(), b.lines.len(), "{what}: lines in frame {fi}");
for (li, (x, y)) in a.lines.iter().zip(&b.lines).enumerate() {
assert_eq!(format!("{x:?}"), format!("{y:?}"), "{what}: frame {fi} line {li}");
}
}
assert!(format!("{cached:?}") == format!("{whole:?}"), "{what}: the composition differs from composing the story whole");
n
}
#[test]
fn a_typed_character_composes_the_paragraphs_around_it() {
for paras in [60, 240] {
let (mut d, sid, _) = threaded(paras, paras / 4);
let cache = Cache::new();
let (first, whole) = shaped(|| cache.get(&d, sid, None));
assert!(!first.is_overset());
assert!(first.frames.iter().filter(|f| !f.lines.is_empty()).count() > paras / 12);
assert_eq!(whole, paras);
let len = d.story(sid).unwrap().len();
for at in [10, len / 2, len - 1] {
d.story_mut(sid).unwrap().insert(at, "x");
let n = check(&cache, &d, sid, "a typed character");
assert!(n <= 3, "{n} of {paras} paragraphs composed for a character typed at {at}");
}
}
}
/// The preflight cache reads an unchanged composition through its base, while edits
/// composed in the reader keep their own incremental trace and never replace the base.
#[test]
fn a_read_through_cache_keeps_incremental_edits_local() {
use std::sync::Arc;
let (mut d, sid, _) = threaded(60, 15);
let original = d.clone();
let base = Arc::new(Cache::new());
let first = base.get(&original, sid, None);
let reader = Cache::over(Arc::clone(&base));
assert!(Arc::ptr_eq(&reader.get(&d, sid, None), &first));
d.story_mut(sid).unwrap().insert(10, "x");
check(&reader, &d, sid, "first edit in reader");
d.story_mut(sid).unwrap().insert(11, "y");
let n = check(&reader, &d, sid, "second edit in reader");
assert!(n <= 3, "reader shaped {n} paragraphs instead of reusing its trace");
assert!(Arc::ptr_eq(&base.get(&original, sid, None), &first));
assert!(base.composed_for(&d, sid).is_none());
}
#[test]
fn characters_typed_one_after_another_each_compose_the_paragraphs_around_them() {
let (mut d, sid, _) = threaded(80, 20);
let cache = Cache::new();
cache.get(&d, sid, None);
let at = d.story(sid).unwrap().len() / 2;
for (i, c) in "one two\nthree".chars().enumerate() {
d.story_mut(sid).unwrap().insert(at + i, &c.to_string());
let n = check(&cache, &d, sid, "typing");
// A return adds a line, which moves the paragraphs below it in their frame: they are
// composed up to the end of the story.
assert!(c == '\n' || n <= 4, "{n} of 80 paragraphs composed for {c:?}");
}
}
#[test]
fn an_edit_that_moves_lines_composes_up_to_the_next_frame_the_text_starts_in() {
let (mut d, sid, _) = threaded(100, 24);
// Chapters of five paragraphs, each starting in the next frame.
let starts: Vec<usize> =
d.story(sid).unwrap().para_ranges().iter().enumerate().filter(|(i, _)| *i > 0 && i % 5 == 0).map(|(_, r)| r.start).collect();
for at in starts {
d.story_mut(sid).unwrap().format_paras(at..at, |p| p.para.start_paragraph = Some(StartParagraph::NextFrame));
}
let cache = Cache::new();
let (first, whole) = shaped(|| cache.get(&d, sid, None));
assert!(!first.is_overset());
assert_eq!(whole, 100);
let at = d.story(sid).unwrap().para_ranges()[52].start + 20;
d.story_mut(sid).unwrap().insert(at, &format!(" {SENTENCE} {SENTENCE}"));
let n = check(&cache, &d, sid, "two more lines in a chapter");
assert!(n <= 6, "{n} of 100 paragraphs composed for lines added to one chapter");
}
#[test]
fn edits_give_the_composition_of_the_edited_story() {
let (mut d, sid, _) = threaded(40, 12);
let original = d.clone();
let cache = Cache::new();
cache.get(&d, sid, None);
let edits: [(&str, fn(&mut Story)); 15] = [
("a character", |s| s.insert(s.len() / 2, "x")),
("a return", |s| s.insert(s.len() / 2, "\n")),
("a long insertion", |s| s.insert(s.len() / 3, &format!(" {SENTENCE} {SENTENCE} {SENTENCE}"))),
("several paragraphs", |s| s.insert(s.len() / 3, &format!("\n{SENTENCE}\n{SENTENCE}\n"))),
("a deleted character", |s| s.delete(s.len() / 2..s.len() / 2 + 1)),
("a deleted return", |s| {
let at = s.text[..s.len() / 2].rfind('\n').unwrap();
s.delete(at..at + 1);
}),
("a deletion across paragraphs", |s| s.delete(s.len() / 4..s.len() / 4 + 900)),
("a replacement", |s| s.replace(s.len() / 2..s.len() / 2 + 40, "replaced")),
("larger type", |s| s.format_chars(s.len() / 2..s.len() / 2 + 60, |f| f.over.size = Some(18.0))),
("a centered paragraph", |s| s.format_paras(s.len() / 2..s.len() / 2, |p| p.para.align = Some(Align::Center))),
("text at the start", |s| s.insert(0, "Start. ")),
("text at the end", |s| s.insert(s.len(), " End.")),
("a two-byte character", |s| s.insert(s.len() / 2, "\u{e9}")),
("everything deleted", |s| s.delete(0..s.len())),
("text in an empty story", |s| s.insert(0, "Again.")),
];
for (what, edit) in edits {
edit(d.story_mut(sid).unwrap());
check(&cache, &d, sid, what);
}
// Undo puts an earlier story back.
check(&cache, &original, sid, "the story before the edits");
}
#[test]
fn edits_in_and_above_overset_text_compose_right() {
let (mut d, sid, _) = threaded(60, 3);
let cache = Cache::new();
assert!(cache.get(&d, sid, None).is_overset());
let len = d.story(sid).unwrap().len();
d.story_mut(sid).unwrap().insert(len - 10, "x");
let n = check(&cache, &d, sid, "a character in overset text");
assert!(n <= 1, "{n} paragraphs composed for a character typed in overset text");
d.story_mut(sid).unwrap().insert(200, &format!(" {SENTENCE}"));
check(&cache, &d, sid, "a line added above overset text");
d.story_mut(sid).unwrap().delete(100..len / 2);
check(&cache, &d, sid, "a deletion that brings overset text into the frames");
}
/// Stories with features a trace does not cover are composed whole after an edit.
#[test]
fn edits_of_stories_a_trace_does_not_cover_compose_right() {
let setups: [(&str, fn(&mut Document, StoryId, &[ItemId])); 6] = [
("keep options", |d, sid, _| {
let s = d.story_mut(sid).unwrap();
s.format_paras(0..s.len(), |p| {
p.para.keep_with_next = Some(1);
p.para.keep_lines_together = Some(true);
});
}),
("balanced columns", |d, _, frames| {
for f in frames {
let o = &mut d.item_mut(*f).unwrap().text_frame_mut().unwrap().options;
(o.columns, o.balance_columns) = (2, true);
}
}),
("vertical justification", |d, _, frames| {
for f in frames {
d.item_mut(*f).unwrap().text_frame_mut().unwrap().options.vertical_justification = VerticalJustification::Center;
}
}),
("a numbered list", |d, sid, _| {
let s = d.story_mut(sid).unwrap();
s.format_paras(0..s.len(), |p| p.para.list_type = Some(ListType::Numbers));
}),
("a footnote", |d, sid, _| {
d.story_mut(sid).unwrap().insert_note(300, "A synthetic footnote.", ParaFormat::default());
}),
("a column rule", |d, _, frames| {
for f in frames {
let o = &mut d.item_mut(*f).unwrap().text_frame_mut().unwrap().options;
(o.columns, o.column_rule) = (2, true);
}
}),
];
for (what, setup) in setups {
let (mut d, sid, frames) = threaded(30, 10);
setup(&mut d, sid, &frames);
let cache = Cache::new();
cache.get(&d, sid, None);
let mid = d.story(sid).unwrap().len() / 2;
d.story_mut(sid).unwrap().insert(mid, "x");
check(&cache, &d, sid, what);
d.story_mut(sid).unwrap().insert(mid, &format!("\n{SENTENCE} {SENTENCE}\n"));
check(&cache, &d, sid, what);
d.story_mut(sid).unwrap().delete(mid / 2..mid);
check(&cache, &d, sid, what);
}
}
#[test]
fn a_run_of_mixed_edits_composes_right_after_each() {
let (mut d, sid, _) = threaded(40, 14);
let cache = Cache::new();
cache.get(&d, sid, None);
let texts = ["x", " word", "\n", " several words in a row here", "\n\n", "A sentence. "];
let mut seed = 0x2545_f491_u64;
let mut next = |below: usize| {
seed = seed.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1_442_695_040_888_963_407);
(seed >> 33) as usize % below.max(1)
};
for step in 0..60 {
let s = d.story_mut(sid).unwrap();
let at = next(s.len() + 1);
match next(4) {
0 | 1 => s.insert(at, texts[next(texts.len())]),
2 => s.delete(at..(at + next(120)).min(s.len())),
_ => {
let size = 9.0 + next(10) as f64;
s.format_chars(at..(at + next(60)).min(s.len()), |f| f.over.size = Some(size));
}
}
check(&cache, &d, sid, &format!("step {step}"));
}
}
}
+8
View File
@@ -53,6 +53,9 @@ pub struct TableFrag {
pub column: u32,
pub rect: Rect,
pub cells: Vec<PlacedCell>,
/// The table rows in the fragment, each with its top and bottom; repeated header and footer
/// rows are left out.
pub rows: Vec<(usize, f64, f64)>,
pub strokes: Vec<StrokeSeg>,
/// Index of the fragment's (glyph-less) line in the frame's lines.
pub line: usize,
@@ -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,
File diff suppressed because it is too large. Load diff
+29 -8
View File
@@ -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<usize>,
/// Baseline of the line holding the anchor, for obstacles in their own story.
anchor_baseline: Option<f64>,
}
/// The wrap may be set on the frame or on its placed graphic (Direct Selection).
fn wraps(o: &AnchoredObject) -> bool {
o.item.wrap.mode != WrapMode::None && !o.item.hidden
o.item.has_wrap() && !o.item.hidden
}
/// Does `story` have an anchored object whose wrap can push text?
@@ -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<Exclusion>], b: &[Vec<Exclusion>]) -> bool {
/// Compose story `sid` with the wrapping anchored objects of `others` (compositions of its
/// [`neighbours`]) and of its own.
pub(crate) fn compose_among(doc: &Document, sid: StoryId, opts: &ComposeOptions, others: &[&ComposedStory]) -> ComposedStory {
let Some(st) = doc.story(sid) else { return ComposedStory { story: sid, ..Default::default() } };
compose_among_traced(doc, sid, opts, others, None).0
}
/// [`compose_among`], also giving the trace for composing the story again after an edit, when
/// the composition leaves one ([`crate::reuse`]). `before` is the story before an edit with its
/// composition among the same `others` and that composition's trace: the paragraphs the edit
/// cannot change are taken from it. A story with wrapping anchored objects of its own is
/// composed whole and leaves no trace.
pub(crate) fn compose_among_traced(
doc: &Document,
sid: StoryId,
opts: &ComposeOptions,
others: &[&ComposedStory],
before: Option<Reuse<'_>>,
) -> (ComposedStory, Option<Trace>) {
let Some(st) = doc.story(sid) else { return (ComposedStory { story: sid, ..Default::default() }, None) };
let mut specs = crate::frame_specs_placed(doc, sid, &opts.placed);
if !others.is_empty() {
let mut obs = Vec::new();
@@ -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)
}
+16 -1
View File
@@ -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<usize>, index: Option<&XrefIndex>) -> HashMap<usize, String> {
if story.xrefs.is_empty() {
return HashMap::new();
}
let before = story.text[..range.start].matches(XREF_MARK).count();
texts_after(doc, story, range, before, index)
}
/// [`texts_in`] for a caller that already knows `before`, the number of cross-reference marks in
/// `story` before `range`.
pub(crate) fn texts_after(
doc: &Document,
story: &Story,
range: std::ops::Range<usize>,
before: usize,
index: Option<&XrefIndex>,
) -> HashMap<usize, String> {
let mut out = HashMap::new();
if story.xrefs.is_empty() {
return out;
}
let before = story.text[..range.start].matches(XREF_MARK).count();
for (k, (i, _)) in story.text[range.clone()].match_indices(XREF_MARK).enumerate() {
if let Some(x) = story.xrefs.get(before + k) {
out.insert(range.start + i, xref_text(doc, x, index));
+1 -1
View File
@@ -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();
+411
View File
@@ -0,0 +1,411 @@
//! The bytes of a placed file ([`crate::Asset::data`]): held in memory (embedded) or read from
//! the linked file when needed. Caches of decoded images key by the value's [`SourceKey`],
//! which outlives the bytes: a decoded image stays usable after the encoded bytes are dropped.
//!
//! Linked bytes are read by the [`Loader`] the engine installs ([`install_loader`]; this crate
//! does no file I/O) and kept in a process-wide store of at most [`STORE_BUDGET`] bytes, least
//! recently used first out. A file over [`MAX_LINKED_BYTES`] is never read.
use std::fmt;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex, PoisonError, Weak};
use crate::datamerge::Fingerprint;
mod store;
pub use store::{Loaded, Loader, MAX_LINKED_BYTES, STORE_BUDGET, install_loader};
/// Names one version of an asset's bytes. Every [`AssetData`] made from new bytes gets a key no
/// other value in this process has had; clones share it. Keys are never reused, so a cache
/// entry under a key can't be mistaken for different bytes allocated later. Counting starts at
/// 1: `SourceKey(0)` names no bytes.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct SourceKey(pub u64);
impl SourceKey {
/// A key no other value has had.
pub fn fresh() -> Self {
static NEXT: AtomicU64 = AtomicU64::new(1);
SourceKey(NEXT.fetch_add(1, Ordering::Relaxed))
}
}
/// Why an asset's bytes can't be had.
#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
pub enum Unavailable {
#[error("the linked file is missing")]
Missing,
#[error("the linked file has changed")]
Modified,
#[error("the linked file is too large to load")]
TooLarge,
#[error("no loader for linked files")]
NoLoader,
}
/// Where a linked asset's bytes are, and what they must be: the [`crate::Asset`] link record
/// ([`LinkedSource::of`]) with the document it is resolved against.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct LinkedSource {
/// The file's absolute path ([`crate::Asset::link`]), tried first.
pub path: String,
/// The path relative to the document's folder ([`crate::Asset::link_relative`]), tried when
/// the absolute path doesn't hold the bytes.
pub relative: Option<String>,
/// The document file `relative` is resolved against.
pub document: Option<PathBuf>,
/// The size of the bytes.
pub len: u64,
/// Size and modification time of the file when it was known to hold the bytes: a file that
/// still has them is read without hashing.
pub fingerprint: Option<Fingerprint>,
/// The bytes' content hash ([`crate::Asset::link_hash`], `sha256:` and hex digits), checked
/// when the file's fingerprint differs.
pub hash: Option<String>,
}
impl LinkedSource {
/// The source `asset`'s link record names, resolved against the document file at
/// `document`. `None` without a link, or without the size its fingerprint records.
pub fn of(asset: &crate::Asset, document: Option<&Path>) -> Option<Self> {
let fingerprint = asset.link_fingerprint?;
Some(LinkedSource {
path: asset.link.clone()?,
relative: asset.link_relative.clone(),
document: document.map(Path::to_path_buf),
len: fingerprint.size,
fingerprint: Some(fingerprint),
hash: asset.link_hash.clone(),
})
}
}
/// A linked source, with the fingerprint a load last found the file at (hash-checked), so later
/// loads of a file whose time changed but whose bytes didn't skip the hash.
struct Linked {
source: LinkedSource,
trusted: Mutex<Option<Fingerprint>>,
}
impl Linked {
fn trusted(&self) -> Option<Fingerprint> {
*self.trusted.lock().unwrap_or_else(PoisonError::into_inner)
}
fn trust(&self, fingerprint: Fingerprint) {
*self.trusted.lock().unwrap_or_else(PoisonError::into_inner) = Some(fingerprint);
}
}
#[derive(Clone)]
enum Repr {
Embedded(Arc<Vec<u8>>),
Linked(Arc<Linked>),
}
/// An asset's bytes: embedded in the document, or linked (read from the file on demand).
/// Cloning is cheap and keeps the [`SourceKey`].
#[derive(Clone)]
pub struct AssetData {
key: SourceKey,
repr: Repr,
}
impl AssetData {
/// Embedded bytes, under a new key.
pub fn embedded(bytes: impl Into<Arc<Vec<u8>>>) -> Self {
AssetData { key: SourceKey::fresh(), repr: Repr::Embedded(bytes.into()) }
}
/// Embedded bytes under `key`, which the caller made ([`SourceKey::fresh`]) for exactly these
/// bytes: bytes derived again from the same input (a layer variant of the same file) keep
/// the key their decodes are cached under. Different bytes under one key would draw stale
/// pixels.
pub fn embedded_under(key: SourceKey, bytes: impl Into<Arc<Vec<u8>>>) -> Self {
AssetData { key, repr: Repr::Embedded(bytes.into()) }
}
/// The bytes of the linked file `source` names, under a new key.
pub fn linked(source: LinkedSource) -> Self {
AssetData { key: SourceKey::fresh(), repr: Repr::Linked(Arc::new(Linked { source, trusted: Mutex::new(None) })) }
}
/// The linked file `source` names, under `key`: embedded bytes found identical to the file
/// (hash-checked by the caller) become a link without decoding them again. As with
/// [`AssetData::embedded_under`], other bytes under one key would draw stale pixels.
pub fn linked_under(key: SourceKey, source: LinkedSource) -> Self {
AssetData { key, repr: Repr::Linked(Arc::new(Linked { source, trusted: Mutex::new(None) })) }
}
/// This value pointing at `source` (the file moved, the document was saved elsewhere, the
/// fingerprint was brought up to date). It keeps the key when both name the same bytes
/// (same size and content hash), so nothing decoded is decoded again.
pub fn with_source(&self, source: LinkedSource) -> Self {
let same = self.linked_source().is_some_and(|old| old.len == source.len && old.hash.is_some() && old.hash == source.hash);
let mut new = AssetData::linked(source);
if same {
new.key = self.key;
}
new
}
/// The bytes, when they are embedded.
pub fn embedded_bytes(&self) -> Option<&Arc<Vec<u8>>> {
match &self.repr {
Repr::Embedded(b) => Some(b),
Repr::Linked(_) => None,
}
}
/// Where linked bytes are read from.
pub fn linked_source(&self) -> Option<&LinkedSource> {
match &self.repr {
Repr::Embedded(_) => None,
Repr::Linked(l) => Some(&l.source),
}
}
/// The bytes: embedded ones, or the linked file's (read once by the installed [`Loader`],
/// and kept while the store's budget allows). Concurrent loads of one value read it once.
pub fn load(&self) -> Result<Arc<Vec<u8>>, Unavailable> {
match &self.repr {
Repr::Embedded(b) => Ok(Arc::clone(b)),
Repr::Linked(l) => store::global().load(self.key, l, store::installed().as_deref()),
}
}
/// The bytes for output: [`Self::load`], or for a linked file that has changed the file's
/// current bytes, flagged `true`, which are never cached. Linked bytes already in memory are
/// used only while the file still holds them ([`Loader::holds`]): output goes by the file as
/// it is now.
pub fn load_for_output(&self) -> Result<(Arc<Vec<u8>>, bool), Unavailable> {
if let Repr::Linked(l) = &self.repr
&& let Some(kept) = store::global().resident(self.key)
&& let Some(loader) = store::installed()
{
return match loader.holds(&l.source, l.trusted(), &kept) {
Ok(found) => {
if let Some(fingerprint) = found {
l.trust(fingerprint);
}
Ok((kept, false))
}
Err(Unavailable::Modified) => loader.load_current(&l.source).map(|b| (Arc::new(b), true)),
Err(e) => Err(e),
};
}
match self.load() {
Ok(b) => Ok((b, false)),
Err(Unavailable::Modified) => {
let (Some(source), Some(loader)) = (self.linked_source(), store::installed()) else { return Err(Unavailable::Modified) };
loader.load_current(source).map(|b| (Arc::new(b), true))
}
Err(e) => Err(e),
}
}
/// The bytes without reading anything: embedded ones, or linked ones the store holds.
pub fn resident(&self) -> Option<Arc<Vec<u8>>> {
match &self.repr {
Repr::Embedded(b) => Some(Arc::clone(b)),
Repr::Linked(_) => store::global().resident(self.key),
}
}
/// Keep `bytes`, just read from the linked file and checked by the caller to be the ones its
/// source names, in the store, so the first [`AssetData::load`] doesn't read the file again.
/// Embedded values, bytes of another size and bytes over the store's budget are ignored.
pub fn keep_resident(&self, bytes: Arc<Vec<u8>>) {
if let Repr::Linked(l) = &self.repr
&& bytes.len() as u64 == l.source.len
{
store::global().keep(self.key, bytes);
}
}
/// Drop the store's copy of linked bytes (they are read again when next loaded).
pub fn evict(&self) {
if self.is_linked() {
store::global().evict(self.key);
}
}
pub fn key(&self) -> SourceKey {
self.key
}
/// The size of the bytes.
pub fn len(&self) -> u64 {
match &self.repr {
Repr::Embedded(b) => b.len() as u64,
Repr::Linked(l) => l.source.len,
}
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
pub fn is_linked(&self) -> bool {
matches!(self.repr, Repr::Linked(_))
}
/// A handle that doesn't keep embedded bytes alive, and upgrades to this value (same key)
/// while anything else does.
pub fn downgrade(&self) -> WeakAssetData {
let repr = match &self.repr {
Repr::Embedded(b) => WeakRepr::Embedded(Arc::downgrade(b)),
Repr::Linked(l) => WeakRepr::Linked(Arc::clone(l)),
};
WeakAssetData { key: self.key, repr }
}
}
/// Advances when linked files may have come back or changed ([`links_changed`]).
static LINK_GENERATION: AtomicU64 = AtomicU64::new(0);
/// Say that linked files may have changed on disk (a relink, an update, a status check): caches
/// that remembered a linked file as unavailable ask for it again.
pub fn links_changed() {
LINK_GENERATION.fetch_add(1, Ordering::AcqRel);
}
/// The count [`links_changed`] advances.
pub fn link_generation() -> u64 {
LINK_GENERATION.load(Ordering::Acquire)
}
#[derive(Clone)]
enum WeakRepr {
Embedded(Weak<Vec<u8>>),
Linked(Arc<Linked>),
}
/// [`AssetData::downgrade`].
#[derive(Clone)]
pub struct WeakAssetData {
key: SourceKey,
repr: WeakRepr,
}
impl WeakAssetData {
/// The value, while its embedded bytes are held elsewhere.
pub fn upgrade(&self) -> Option<AssetData> {
let repr = match &self.repr {
WeakRepr::Embedded(w) => Repr::Embedded(w.upgrade()?),
WeakRepr::Linked(l) => Repr::Linked(Arc::clone(l)),
};
Some(AssetData { key: self.key, repr })
}
pub fn key(&self) -> SourceKey {
self.key
}
}
impl fmt::Debug for WeakAssetData {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("WeakAssetData").field("key", &self.key.0).finish()
}
}
/// New embedded bytes ([`AssetData::embedded`]).
impl From<Vec<u8>> for AssetData {
fn from(bytes: Vec<u8>) -> Self {
AssetData::embedded(bytes)
}
}
impl Default for AssetData {
fn default() -> Self {
AssetData::embedded(Vec::new())
}
}
/// Embedded bytes compare by content; linked ones are equal only as the same version.
impl PartialEq for AssetData {
fn eq(&self, other: &Self) -> bool {
match (&self.repr, &other.repr) {
(Repr::Embedded(a), Repr::Embedded(b)) => a == b,
(Repr::Linked(a), Repr::Linked(b)) => self.key == other.key && a.source.len == b.source.len,
_ => false,
}
}
}
impl fmt::Debug for AssetData {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let kind = if self.is_linked() { "Linked" } else { "Embedded" };
f.debug_struct(kind).field("key", &self.key.0).field("len", &self.len()).finish()
}
}
#[cfg(test)]
mod tests {
use super::*;
pub(super) fn source(path: &str, len: u64) -> LinkedSource {
LinkedSource { path: path.into(), relative: None, document: None, len, fingerprint: None, hash: None }
}
#[test]
fn clones_keep_the_key_and_new_bytes_get_a_new_one() {
let a = AssetData::embedded(vec![1, 2, 3]);
let b = a.clone();
assert_eq!(a.key(), b.key());
let c = AssetData::embedded(vec![1, 2, 3]);
assert_ne!(a.key(), c.key());
assert_eq!(a, c, "embedded bytes compare by content");
let shared = AssetData::embedded(Arc::clone(a.embedded_bytes().unwrap()));
assert_ne!(a.key(), shared.key(), "wrapping bytes again names a new version");
assert_eq!(a.load().unwrap().as_slice(), [1, 2, 3]);
assert_eq!(a.len(), 3);
let weak = a.downgrade();
assert_eq!(weak.upgrade().map(|d| d.key()), Some(a.key()));
drop((a, b));
assert!(weak.upgrade().is_some(), "`shared` still holds the bytes");
drop(shared);
assert!(weak.upgrade().is_none());
}
#[test]
fn linked_assets_keep_their_key_only_for_the_same_bytes() {
let mut s = source("/nowhere/no-loader.png", 10);
let l = AssetData::linked(s.clone());
assert!(l.is_linked());
assert_eq!(l.len(), 10);
assert!(l.embedded_bytes().is_none() && l.resident().is_none());
assert!(AssetData::default().is_empty());
assert_ne!(l.with_source(s.clone()).key(), l.key(), "no hash: nothing says the bytes are the same");
s.hash = Some("sha256:00".into());
let hashed = AssetData::linked(s.clone());
s.path = "/elsewhere/no-loader.png".into();
let moved = hashed.with_source(s.clone());
assert_eq!((moved.key(), moved.linked_source().map(|s| s.path.as_str())), (hashed.key(), Some("/elsewhere/no-loader.png")));
s.hash = Some("sha256:01".into());
assert_ne!(hashed.with_source(s).key(), hashed.key(), "other bytes, another key");
let weak = hashed.downgrade();
drop(hashed);
assert!(weak.upgrade().is_some(), "a linked value holds no bytes to let go of");
}
#[test]
fn a_link_record_names_its_source() {
let fingerprint = Fingerprint { size: 7, mtime: 9 };
let asset = crate::Asset {
link: Some("/a/b.png".into()),
link_relative: Some("b.png".into()),
link_fingerprint: Some(fingerprint),
link_hash: Some("sha256:ab".into()),
..Default::default()
};
let s = LinkedSource::of(&asset, Some(Path::new("/a/doc.dcx"))).unwrap();
assert_eq!(
(s.len, s.fingerprint, s.relative.as_deref(), s.document.as_deref()),
(7, Some(fingerprint), Some("b.png"), Some(Path::new("/a/doc.dcx")))
);
assert!(LinkedSource::of(&crate::Asset { link_fingerprint: None, ..asset }, None).is_none(), "the size comes from the fingerprint");
}
}
+370
View File
@@ -0,0 +1,370 @@
//! The process-wide store of linked files' bytes ([`super::AssetData::load`]).
use std::collections::HashMap;
use std::sync::{Arc, Condvar, LazyLock, Mutex, MutexGuard, PoisonError, RwLock};
use super::{Linked, LinkedSource, SourceKey, Unavailable};
use crate::datamerge::Fingerprint;
/// Linked bytes kept in memory at most, over all files. A file larger than this is read for the
/// one load that asks for it and not kept.
pub const STORE_BUDGET: u64 = 512 << 20;
/// The largest linked file read: a larger one is [`Unavailable::TooLarge`].
pub const MAX_LINKED_BYTES: u64 = 1 << 30;
/// A linked file's bytes as a [`Loader`] read them.
pub struct Loaded {
pub bytes: Vec<u8>,
/// The fingerprint the file had, when its bytes were found to be the expected ones by their
/// hash: later loads trust that fingerprint as they trust [`LinkedSource::fingerprint`].
pub fingerprint: Option<Fingerprint>,
}
/// Reads linked files (the engine's, [`install_loader`]).
pub trait Loader: Send + Sync {
/// The bytes of the file `source` names, if it holds the expected ones: its size is
/// `source.len`, and its fingerprint is `source.fingerprint` or `trusted`, or its content
/// hash is `source.hash`. Other bytes are [`Unavailable::Modified`]; no file is
/// [`Unavailable::Missing`]; one over [`MAX_LINKED_BYTES`] is [`Unavailable::TooLarge`].
fn load(&self, source: &LinkedSource, trusted: Option<Fingerprint>) -> Result<Loaded, Unavailable>;
/// The bytes the file `source` names has now, whatever they are (for output that uses the
/// current file of a modified link). Never cached.
fn load_current(&self, _source: &LinkedSource) -> Result<Vec<u8>, Unavailable> {
Err(Unavailable::NoLoader)
}
/// Whether the file `source` names still holds `kept`, the bytes read from it earlier: by its
/// fingerprint as [`Self::load`] goes by it, else by its content hash, or for a source without
/// a hash by its bytes. → the file's fingerprint when it was read to tell, else `None`;
/// [`Unavailable::Modified`] when the files there hold other bytes. A loader that can't look
/// takes the kept bytes as the file's.
fn holds(&self, _source: &LinkedSource, _trusted: Option<Fingerprint>, _kept: &[u8]) -> Result<Option<Fingerprint>, Unavailable> {
Ok(None)
}
}
static LOADER: RwLock<Option<Arc<dyn Loader>>> = RwLock::new(None);
/// Read linked files with `loader` from now on (in the whole process).
pub fn install_loader(loader: Arc<dyn Loader>) {
*LOADER.write().unwrap_or_else(PoisonError::into_inner) = Some(loader);
}
pub(super) fn installed() -> Option<Arc<dyn Loader>> {
LOADER.read().unwrap_or_else(PoisonError::into_inner).clone()
}
pub(super) fn global() -> &'static Store {
static STORE: LazyLock<Store> = LazyLock::new(|| Store::new(STORE_BUDGET, MAX_LINKED_BYTES));
&STORE
}
type Outcome = Result<Arc<Vec<u8>>, Unavailable>;
/// One load in progress, which the other loads of the same bytes wait for.
#[derive(Default)]
struct Flight {
outcome: Mutex<Option<Outcome>>,
landed: Condvar,
}
impl Flight {
fn wait(&self) -> Outcome {
let mut g = self.outcome.lock().unwrap_or_else(PoisonError::into_inner);
loop {
if let Some(outcome) = g.as_ref() {
return outcome.clone();
}
g = self.landed.wait(g).unwrap_or_else(PoisonError::into_inner);
}
}
}
struct Kept {
bytes: Arc<Vec<u8>>,
stamp: u64,
}
#[derive(Default)]
struct Inner {
kept: HashMap<SourceKey, Kept>,
flights: HashMap<SourceKey, Arc<Flight>>,
bytes: u64,
clock: u64,
}
impl Inner {
/// The bytes kept under `key`, marked used.
fn touch(&mut self, key: SourceKey) -> Option<Arc<Vec<u8>>> {
self.clock += 1;
let clock = self.clock;
self.kept.get_mut(&key).map(|k| {
k.stamp = clock;
Arc::clone(&k.bytes)
})
}
/// Keep `bytes` under `key`, dropping the least recently used others beyond `budget`.
fn keep(&mut self, key: SourceKey, bytes: Arc<Vec<u8>>, budget: u64) {
self.clock += 1;
let n = bytes.len() as u64;
if let Some(old) = self.kept.insert(key, Kept { bytes, stamp: self.clock }) {
self.bytes = self.bytes.saturating_sub(old.bytes.len() as u64);
}
self.bytes = self.bytes.saturating_add(n);
while self.bytes > budget {
let Some(oldest) = self.kept.iter().filter(|(k, _)| **k != key).min_by_key(|(_, k)| k.stamp).map(|(k, _)| *k) else { break };
if let Some(old) = self.kept.remove(&oldest) {
self.bytes = self.bytes.saturating_sub(old.bytes.len() as u64);
}
}
}
}
/// A single-flight, least-recently-used store of loaded bytes by [`SourceKey`].
pub(super) struct Store {
inner: Mutex<Inner>,
budget: u64,
cap: u64,
}
/// Lands a flight when dropped: with its outcome, or as missing when the loader panicked, so
/// the loads waiting for it don't wait forever.
struct Landing<'a> {
store: &'a Store,
key: SourceKey,
flight: Arc<Flight>,
outcome: Option<Outcome>,
}
impl Drop for Landing<'_> {
fn drop(&mut self) {
let outcome = self.outcome.take().unwrap_or(Err(Unavailable::Missing));
{
let mut g = self.store.lock();
g.flights.remove(&self.key);
if let Ok(bytes) = &outcome
&& bytes.len() as u64 <= self.store.budget
{
g.keep(self.key, Arc::clone(bytes), self.store.budget);
}
}
*self.flight.outcome.lock().unwrap_or_else(PoisonError::into_inner) = Some(outcome);
self.flight.landed.notify_all();
}
}
impl Store {
pub(super) fn new(budget: u64, cap: u64) -> Self {
Store { inner: Mutex::new(Inner::default()), budget, cap }
}
fn lock(&self) -> MutexGuard<'_, Inner> {
self.inner.lock().unwrap_or_else(PoisonError::into_inner)
}
/// The bytes of `linked`, kept under `key`: from the store, from a load of them in progress,
/// or read by `loader`.
pub(super) fn load(&self, key: SourceKey, linked: &Linked, loader: Option<&dyn Loader>) -> Outcome {
if linked.source.len > self.cap {
return Err(Unavailable::TooLarge);
}
let flight = {
let mut g = self.lock();
if let Some(bytes) = g.touch(key) {
return Ok(bytes);
}
if let Some(f) = g.flights.get(&key).cloned() {
drop(g);
return f.wait();
}
let Some(loader) = loader else { return Err(Unavailable::NoLoader) };
let f = Arc::new(Flight::default());
g.flights.insert(key, Arc::clone(&f));
(f, loader)
};
let (flight, loader) = flight;
let mut landing = Landing { store: self, key, flight, outcome: None };
// Read outside the lock: other bytes load and are found meanwhile.
let outcome = match loader.load(&linked.source, linked.trusted()) {
Ok(l) if l.bytes.len() as u64 > self.cap => Err(Unavailable::TooLarge),
Ok(l) => {
if let Some(fingerprint) = l.fingerprint {
linked.trust(fingerprint);
}
Ok(Arc::new(l.bytes))
}
Err(e) => Err(e),
};
landing.outcome = Some(outcome.clone());
drop(landing);
outcome
}
/// The bytes kept under `key`, without loading them.
pub(super) fn resident(&self, key: SourceKey) -> Option<Arc<Vec<u8>>> {
self.lock().touch(key)
}
/// Keep `bytes` under `key` as if a load had read them (not when over the budget).
pub(super) fn keep(&self, key: SourceKey, bytes: Arc<Vec<u8>>) {
if bytes.len() as u64 <= self.budget {
self.lock().keep(key, bytes, self.budget);
}
}
pub(super) fn evict(&self, key: SourceKey) {
let mut g = self.lock();
if let Some(old) = g.kept.remove(&key) {
g.bytes = g.bytes.saturating_sub(old.bytes.len() as u64);
}
}
#[cfg(test)]
fn kept_bytes(&self) -> u64 {
self.lock().bytes
}
}
#[cfg(test)]
mod tests {
use super::super::tests::source;
use super::super::{AssetData, Repr};
use super::*;
use std::sync::atomic::{AtomicUsize, Ordering};
/// Serves `len` bytes of `fill` for every path, counting its reads; slow, so loads overlap.
#[derive(Default)]
struct Counting {
reads: AtomicUsize,
delay_ms: u64,
fail: Option<Unavailable>,
trusted: Mutex<Vec<Option<Fingerprint>>>,
}
impl Loader for Counting {
fn load(&self, source: &LinkedSource, trusted: Option<Fingerprint>) -> Result<Loaded, Unavailable> {
self.reads.fetch_add(1, Ordering::SeqCst);
self.trusted.lock().unwrap().push(trusted);
std::thread::sleep(std::time::Duration::from_millis(self.delay_ms));
if let Some(e) = self.fail {
return Err(e);
}
let fill = source.path.bytes().last().unwrap_or(0);
Ok(Loaded { bytes: vec![fill; source.len as usize], fingerprint: Some(Fingerprint { size: source.len, mtime: 5 }) })
}
}
fn linked(data: &AssetData) -> &Linked {
match &data.repr {
Repr::Linked(l) => l,
Repr::Embedded(_) => panic!("not linked"),
}
}
fn load(store: &Store, data: &AssetData, loader: &dyn Loader) -> Outcome {
store.load(data.key(), linked(data), Some(loader))
}
#[test]
fn linked_bytes_are_read_once_and_kept() {
let store = Store::new(100, 1000);
let loader = Counting::default();
let a = AssetData::linked(source("a", 10));
assert_eq!(load(&store, &a, &loader).unwrap().as_slice(), [b'a'; 10]);
assert_eq!(load(&store, &a.clone(), &loader).unwrap().len(), 10);
assert_eq!(loader.reads.load(Ordering::SeqCst), 1);
assert_eq!(store.resident(a.key()).map(|b| b.len()), Some(10));
assert_eq!(*loader.trusted.lock().unwrap(), [None]);
store.evict(a.key());
load(&store, &a, &loader).unwrap();
assert_eq!(loader.reads.load(Ordering::SeqCst), 2, "evicted bytes are read again");
assert_eq!(
loader.trusted.lock().unwrap().last(),
Some(&Some(Fingerprint { size: 10, mtime: 5 })),
"a hash-checked fingerprint is trusted next time"
);
assert_eq!(AssetData::linked(source("x", 1)).load(), Err(Unavailable::NoLoader), "no loader installed in these tests");
}
#[test]
fn the_least_recently_used_bytes_go_past_the_budget() {
let store = Store::new(100, 1000);
let loader = Counting::default();
let [a, b, c] = ["a", "b", "c"].map(|p| AssetData::linked(source(p, 40)));
load(&store, &a, &loader).unwrap();
load(&store, &b, &loader).unwrap();
load(&store, &a, &loader).unwrap();
load(&store, &c, &loader).unwrap();
assert!(store.resident(b.key()).is_none(), "b was used least recently");
assert!(store.resident(a.key()).is_some() && store.resident(c.key()).is_some());
assert_eq!(store.kept_bytes(), 80);
}
#[test]
fn a_file_over_the_budget_is_returned_but_not_kept_and_one_over_the_cap_is_not_read() {
let store = Store::new(100, 1000);
let loader = Counting::default();
let small = AssetData::linked(source("s", 50));
load(&store, &small, &loader).unwrap();
let big = AssetData::linked(source("b", 200));
assert_eq!(load(&store, &big, &loader).unwrap().len(), 200);
assert!(store.resident(big.key()).is_none());
assert!(store.resident(small.key()).is_some(), "an unkept file evicts nothing");
let huge = AssetData::linked(source("h", 1001));
assert_eq!(load(&store, &huge, &loader), Err(Unavailable::TooLarge));
assert_eq!(loader.reads.load(Ordering::SeqCst), 2);
}
#[test]
fn concurrent_loads_of_the_same_bytes_read_once() {
let store = Store::new(1000, 1000);
let loader = Counting { delay_ms: 50, ..Default::default() };
let a = AssetData::linked(source("a", 10));
let got: Vec<Outcome> = std::thread::scope(|s| {
let handles: Vec<_> = (0..8).map(|_| s.spawn(|| load(&store, &a, &loader))).collect();
handles.into_iter().map(|h| h.join().unwrap()).collect()
});
assert!(got.iter().all(|g| g.as_ref().is_ok_and(|b| b.len() == 10)));
assert_eq!(loader.reads.load(Ordering::SeqCst), 1);
}
#[test]
fn a_failed_load_is_shared_and_tried_again_later() {
let store = Store::new(1000, 1000);
let loader = Counting { delay_ms: 30, fail: Some(Unavailable::Modified), ..Default::default() };
let a = AssetData::linked(source("a", 10));
let got: Vec<Outcome> = std::thread::scope(|s| {
let handles: Vec<_> = (0..4).map(|_| s.spawn(|| load(&store, &a, &loader))).collect();
handles.into_iter().map(|h| h.join().unwrap()).collect()
});
assert!(got.iter().all(|g| *g == Err(Unavailable::Modified)));
assert!(store.resident(a.key()).is_none(), "nothing adopted");
let reads = loader.reads.load(Ordering::SeqCst);
load(&store, &a, &loader).unwrap_err();
assert_eq!(loader.reads.load(Ordering::SeqCst), reads + 1, "failures aren't remembered here");
}
/// A loader that panics lands its flight: the loads waiting for it return.
#[test]
fn a_panicking_loader_does_not_hang_the_waiters() {
struct Panics;
impl Loader for Panics {
fn load(&self, _: &LinkedSource, _: Option<Fingerprint>) -> Result<Loaded, Unavailable> {
std::thread::sleep(std::time::Duration::from_millis(30));
panic!("loader fault");
}
}
let store = Store::new(1000, 1000);
let a = AssetData::linked(source("a", 10));
std::thread::scope(|s| {
let first = s.spawn(|| load(&store, &a, &Panics));
std::thread::sleep(std::time::Duration::from_millis(5));
let waiter = s.spawn(|| load(&store, &a, &Panics));
assert!(first.join().is_err());
assert!(waiter.join().is_ok_and(|r| r.is_err()));
});
}
}
+36 -9
View File
@@ -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<AssetId, Arc<Asset>>, 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::<Vec<_>>(), indexed.keys().collect::<Vec<_>>());
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]
+1
View File
@@ -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 {
+48
View File
@@ -28,6 +28,22 @@ pub struct ItemLoc {
pub path: ItemPath,
}
/// A gap between adjacent items (or between an item and the page edge) on a spread.
#[derive(Clone, Debug, PartialEq)]
pub struct Gap {
/// True for a vertical gap (between left and right neighbours, moving along X);
/// false for a horizontal gap (between top and bottom neighbours, moving along Y).
pub vertical: bool,
/// Leading edge of the gap along its movement axis.
pub a: f64,
/// Trailing edge of the gap along its movement axis.
pub z: f64,
/// Items ending at `a` that resize when the gap moves.
pub before: Vec<ItemId>,
/// Items starting at `z` that resize when the gap moves.
pub after: Vec<ItemId>,
}
impl ItemLoc {
/// Top-level index in the spread.
pub fn top(&self) -> usize {
@@ -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<Gap> {
let sp = self.spread(sr)?;
let page = sp.page_at_x(p.x).and_then(|i| sp.pages.get(i)).map(|pg| pg.bounds())?;
let items: Vec<(ItemId, Rect)> = sp
.items
.iter()
.filter(|it| !it.hidden && !it.locked && self.layer(it.layer).is_none_or(|l| !l.locked && l.visible))
.map(|it| (it.id, it.bounds()))
.collect();
if items.iter().any(|(_, b)| b.contains(p)) {
return None;
}
// Between left and right neighbours (a vertical gap), or above and below (horizontal).
let side = |vertical: bool| {
let (pos, lo, hi) = if vertical { (p.x, page.x0, page.x1) } else { (p.y, page.y0, page.y1) };
let across = |b: &Rect| if vertical { b.y0 <= p.y && p.y <= b.y1 } else { b.x0 <= p.x && p.x <= b.x1 };
let end = |b: &Rect| if vertical { b.x1 } else { b.y1 };
let start = |b: &Rect| if vertical { b.x0 } else { b.y0 };
let a = items.iter().filter(|(_, b)| across(b) && end(b) <= pos).map(|(_, b)| end(b)).fold(lo, f64::max);
let z = items.iter().filter(|(_, b)| across(b) && start(b) >= pos).map(|(_, b)| start(b)).fold(hi, f64::min);
let before: Vec<ItemId> = items.iter().filter(|(_, b)| across(b) && (end(b) - a).abs() < 0.5).map(|(i, _)| *i).collect();
let after: Vec<ItemId> = items.iter().filter(|(_, b)| across(b) && (start(b) - z).abs() < 0.5).map(|(i, _)| *i).collect();
(!before.is_empty() || !after.is_empty()).then_some(Gap { vertical, a, z, before, after })
};
match (side(true), side(false)) {
(Some(v), Some(h)) => Some(if v.z - v.a <= h.z - h.a { v } else { h }),
(v, h) => v.or(h),
}
}
/// The first item on a document or parent spread whose geometry isn't finite
/// ([`Item::geometry_is_finite`]).
pub fn non_finite_item(&self) -> Option<ItemId> {
+2 -2
View File
@@ -29,8 +29,8 @@ pub use paint::{
path_length_bound,
};
pub use text_frame::{
AutoSize, ColumnsKind, ContourType, FirstBaseline, FrameBaselineGrid, FrameGridRelative, PathAlign, PathType, TextFrame, TextFrameOptions,
TextWrap, VerticalJustification, WrapMode, WrapSide, vertical_text_xf,
AutoSize, ColumnsKind, ContourType, DEFAULT_ALPHA_THRESHOLD, FirstBaseline, FrameBaselineGrid, FrameGridRelative, PathAlign, PathType, TextFrame,
TextFrameOptions, TextWrap, VerticalJustification, WrapMode, WrapSide, vertical_text_xf,
};
fn is_zero_usize(v: &usize) -> bool {
+2
View File
@@ -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)?;
+90 -2
View File
@@ -240,6 +240,65 @@ impl Default for TextFrameOptions {
}
}
impl TextFrameOptions {
/// The JSON keys of the General options: columns, inset spacing, vertical justification and
/// Ignore Text Wrap. An object style's Text Frame General Options category sets these only.
pub const GENERAL_KEYS: [&str; 9] = [
"columns",
"columnsKind",
"gutter",
"columnWidth",
"balanceColumns",
"inset",
"verticalJustification",
"vjParagraphSpacingLimit",
"ignoreWrap",
];
/// Whether the General options (see [`Self::GENERAL_KEYS`]) of `self` and `other` are the same.
pub fn general_eq(&self, other: &TextFrameOptions) -> bool {
self.columns == other.columns
&& self.columns_kind == other.columns_kind
&& self.gutter == other.gutter
&& self.column_width == other.column_width
&& self.balance_columns == other.balance_columns
&& self.inset == other.inset
&& self.vertical_justification == other.vertical_justification
&& self.vj_paragraph_spacing_limit == other.vj_paragraph_spacing_limit
&& self.ignore_wrap == other.ignore_wrap
}
/// Each General option that is `old`'s here takes `new`'s; the others stay. `true` when one
/// changed.
pub fn follow_general(&mut self, old: &TextFrameOptions, new: &TextFrameOptions) -> bool {
let mut changed = false;
macro_rules! follow {
($($f:ident),*) => {$(
if self.$f == old.$f && self.$f != new.$f {
self.$f = new.$f;
changed = true;
}
)*};
}
follow!(columns, columns_kind, gutter, column_width, balance_columns, inset, vertical_justification, vj_paragraph_spacing_limit, ignore_wrap);
changed
}
/// Copies the General options of `from` (see [`Self::GENERAL_KEYS`]). Baseline, auto-size,
/// column rule and Type on a Path settings stay as they are.
pub fn set_general(&mut self, from: &TextFrameOptions) {
self.columns = from.columns;
self.columns_kind = from.columns_kind;
self.gutter = from.gutter;
self.column_width = from.column_width;
self.balance_columns = from.balance_columns;
self.inset = from.inset;
self.vertical_justification = from.vertical_justification;
self.vj_paragraph_spacing_limit = from.vj_paragraph_spacing_limit;
self.ignore_wrap = from.ignore_wrap;
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum WrapMode {
@@ -272,7 +331,7 @@ pub enum ContourType {
BoundingBox,
/// Edges detected in the image. Composition follows the frame path.
DetectEdges,
/// The image's alpha channel. Composition follows the frame path.
/// The image's alpha channel. Composition follows the outline of the image's visible pixels.
AlphaChannel,
/// A path saved in the image. Composition follows the frame path.
PhotoshopPath,
@@ -284,7 +343,7 @@ pub enum ContourType {
}
/// Text Wrap panel settings.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default)]
pub struct TextWrap {
pub mode: WrapMode,
@@ -298,6 +357,35 @@ pub struct TextWrap {
/// item transforms it with the path; other path edits keep it as it is.
#[serde(skip_serializing_if = "Option::is_none")]
pub path: Option<PathData>,
/// Contour Options › Include Inside Edges: an Alpha Channel contour also lets text into the
/// transparent holes it encloses (off: holes are blocked with the shape around them).
#[serde(skip_serializing_if = "std::ops::Not::not")]
pub inside_edges: bool,
/// Alpha Channel contour: pixels more opaque than this (0..254) count as the image.
#[serde(skip_serializing_if = "is_default_alpha_threshold")]
pub alpha_threshold: u8,
}
/// DesignCraft's default alpha threshold for Alpha Channel contour wraps.
pub const DEFAULT_ALPHA_THRESHOLD: u8 = 25;
fn is_default_alpha_threshold(t: &u8) -> bool {
*t == DEFAULT_ALPHA_THRESHOLD
}
impl Default for TextWrap {
fn default() -> Self {
TextWrap {
mode: WrapMode::default(),
offsets: [0.0; 4],
invert: false,
side: WrapSide::default(),
contour: ContourType::default(),
path: None,
inside_edges: false,
alpha_threshold: DEFAULT_ALPHA_THRESHOLD,
}
}
}
impl TextWrap {
+184 -2
View File
@@ -12,6 +12,7 @@
pub mod anchored;
pub mod arabic;
pub mod arrow;
pub mod asset_data;
pub mod assets;
pub mod attrs;
pub mod build;
@@ -44,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<std::ops::Range<usize>> {
let mut out: Vec<std::ops::Range<usize>> = Vec::new();
let runs: Vec<(std::ops::Range<usize>, &CharFormat)> = st.runs().collect();
let mut k = 0;
for (pi, pr) in st.para_ranges().iter().enumerate() {
let base = st.paras.get(pi).map(|pf| self.styles.resolve_para(pf).1).unwrap_or_default();
while runs.get(k).is_some_and(|(rr, _)| rr.end <= pr.start) {
k += 1;
}
for (rr, f) in runs.iter().skip(k).take_while(|(rr, _)| rr.start < pr.end) {
let (a, b) = (rr.start.max(pr.start), rr.end.min(pr.end));
if a >= b || self.hides_run(&base, f) {
continue;
}
match out.last_mut() {
Some(last) if last.end == a => last.end = b,
_ => out.push(a..b),
}
}
}
out
}
/// The text of `st` within `range` that lies in `spans` ([`Self::visible_spans`] of `st`).
pub fn visible_text(st: &Story, spans: &[std::ops::Range<usize>], range: std::ops::Range<usize>) -> String {
let first = spans.partition_point(|s| s.end <= range.start);
let mut out = String::new();
for s in spans.iter().skip(first).take_while(|s| s.start < range.end) {
if let Some(t) = st.text.get(s.start.max(range.start)..s.end.min(range.end)) {
out.push_str(t);
}
}
out
}
}
/// Ink Manager settings for output, by swatch name. Output applies them through a
@@ -574,8 +622,20 @@ pub struct Asset {
/// clears them.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub link_fingerprint: Option<Fingerprint>,
/// `link` relative to the document's folder, for finding the file after both moved.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub link_relative: Option<String>,
/// The linked file's content hash (`sha256:` and hex digits).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub link_hash: Option<String>,
/// Whether a save writes the bytes into the document or only the link to them.
#[serde(default, skip_serializing_if = "Storage::is_embedded")]
pub storage: Storage,
/// A small preview drawn while the full file can't be read.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub proxy: Option<Proxy>,
#[serde(skip)]
pub data: Arc<Vec<u8>>,
pub data: AssetData,
/// Pixel size for raster images.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub pixels: Option<(u32, u32)>,
@@ -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<Vec<u8>>,
/// A warning to report: the file on disk replaced a changed original, or the proxy stands in
/// for a missing one.
pub warning: Option<String>,
/// The bytes are the asset's preview, not the original (a missing or unreadable link).
pub proxied: bool,
}
impl Asset {
/// The bytes an export uses: the original (a changed linked file's current bytes, with a
/// warning), or for a missing or unreadable one its proxy, with a warning. `Err` when
/// there is neither.
pub fn output_bytes(&self) -> std::result::Result<OutputBytes, Unavailable> {
match self.data.load_for_output() {
Ok((bytes, false)) => Ok(OutputBytes { bytes, warning: None, proxied: false }),
Ok((bytes, true)) => Ok(OutputBytes {
bytes,
warning: Some(format!("the linked file `{}` has changed; the file on disk is used", self.name)),
proxied: false,
}),
Err(e) => {
let proxy = self.proxy.as_ref().and_then(|p| p.data.load().ok());
match proxy {
Some(bytes) => Ok(OutputBytes {
bytes,
warning: Some(format!("the linked file `{}` is unavailable ({e}); its preview is used", self.name)),
proxied: true,
}),
None => Err(e),
}
}
}
}
/// The part of the page a placed PDF shows, when [`Asset::pdf_box`] holds a usable box.
pub fn shown_box(&self) -> Option<[f64; 4]> {
self.shown(self.pdf_box?)
@@ -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<Section>,
#[serde(default)]
pub assets: BTreeMap<AssetId, Arc<Asset>>,
/// Alpha Channel contour outlines of placed images (see [`AlphaOutline`]), sorted by asset
/// and then threshold, at most one for each pair. Not saved.
#[serde(skip)]
pub alpha_outlines: Vec<Arc<AlphaOutline>>,
/// Hyperlinks (Window → Interactive → Hyperlinks).
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub hyperlinks: Vec<Hyperlink>,
@@ -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)
}
+70 -3
View File
@@ -1,10 +1,11 @@
//! Paragraph, character and object styles with based-on inheritance.
use designcraft_geom::corners::CornerOptions;
use serde::{Deserialize, Serialize};
use crate::attrs::{CharAttrs, CharProps, ParaAttrs, ParaProps};
use crate::item::{Effects, Fill, Item, Stroke, TextFrameOptions};
use crate::story::{BASIC_PARAGRAPH, CharFormat, NO_CHAR_STYLE, ParaFormat};
use crate::story::{BASIC_PARAGRAPH, CharFormat, NO_CHAR_STYLE, ParaFormat, Story};
pub const NO_PARA_STYLE: &str = "[No Paragraph Style]";
pub const BASIC_GRAPHICS_FRAME: &str = "[Basic Graphics Frame]";
@@ -53,17 +54,30 @@ pub struct ObjectStyle {
pub stroke: Option<Stroke>,
#[serde(skip_serializing_if = "Option::is_none")]
pub paragraph_style: Option<String>,
/// Paragraph Styles › Apply Next Style: the paragraph style goes on a text frame's first
/// paragraph, and each paragraph after it takes the Next Style of the one before.
#[serde(skip_serializing_if = "std::ops::Not::not")]
pub apply_next_style: bool,
#[serde(skip_serializing_if = "Option::is_none")]
pub text_frame: Option<TextFrameOptions>,
/// Effects (drop shadow, feather, glows…). An item using the style follows them until its own
/// effects differ from the style's (a local override).
#[serde(skip_serializing_if = "Option::is_none")]
pub effects: Option<Effects>,
/// Corner Options (Stroke & Corner Options): each corner's shape and size, by name (top left,
/// top right, bottom right, bottom left), as InDesign's; an item takes them at the anchors at
/// those corners ([`CornerOptions::named_to_path`]).
#[serde(skip_serializing_if = "Option::is_none")]
pub corners: Option<CornerOptions>,
}
impl ObjectStyle {
/// Gives `it` the fill, stroke, effects and text frame options this style sets.
/// Gives `it` the fill, stroke, corners, effects and text frame General options this style
/// sets. A text frame keeps its baseline, auto-size, column rule and Type on a Path settings.
pub fn apply_to(&self, it: &mut Item) {
if let Some(c) = self.corners {
it.corners = c.named_to_path(&it.path);
}
if let Some(f) = &self.fill {
it.fill = f.clone();
}
@@ -74,9 +88,62 @@ impl ObjectStyle {
it.effects = e.clone();
}
if let (Some(tf), Some(o)) = (it.text_frame_mut(), &self.text_frame) {
tf.options = o.clone();
tf.options.set_general(o);
}
}
/// The paragraph style of each of a text frame's `n` paragraphs under this style: its
/// paragraph style for all of them, or with Apply Next Style that one first and then each
/// one's Next Style. `None` when the style sets no paragraph style.
pub fn paragraph_styles(&self, styles: &Styles, n: usize) -> Option<Vec<String>> {
let mut cur = self.paragraph_style.clone()?;
let mut out = Vec::with_capacity(n);
for _ in 0..n {
out.push(cur.clone());
if self.apply_next_style
&& let Some(next) = styles.para(&cur).and_then(|s| s.next_style.clone())
{
cur = next;
}
}
Some(out)
}
/// Whether a story's paragraphs are in the paragraph styles this style gives them (they
/// always are when it sets none).
pub fn story_follows(&self, styles: &Styles, st: &Story) -> bool {
self.paragraph_styles(styles, st.paras.len()).is_none_or(|want| st.paras.iter().zip(&want).all(|(f, w)| f.style == *w))
}
/// After an edit from `old`: the paragraphs of `st` still in the paragraph style `old` gives
/// them (every paragraph, when `old` set none) with the one this style gives each, where that
/// differs. A paragraph in another style is left out.
pub fn restyle_from(&self, old: &ObjectStyle, styles: &Styles, st: &Story) -> Vec<(usize, String)> {
let n = st.paras.len();
let Some(want) = self.paragraph_styles(styles, n) else { return Vec::new() };
let was = old.paragraph_styles(styles, n);
st.paras
.iter()
.zip(want)
.enumerate()
.filter(|(i, (f, w))| was.as_ref().is_none_or(|was| f.style == was[*i]) && f.style != *w)
.map(|(i, (_, w))| (i, w))
.collect()
}
/// Put a story's paragraphs in the paragraph styles this style gives them; `false` when it
/// sets none or they already are.
pub fn restyle(&self, styles: &Styles, st: &mut Story) -> bool {
if self.story_follows(styles, st) {
return false;
}
let Some(want) = self.paragraph_styles(styles, st.paras.len()) else { return false };
for (f, w) in st.paras.iter_mut().zip(want) {
f.style = w;
}
st.rev = st.rev.wrapping_add(1);
true
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+6
View File
@@ -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 }
+322
View File
@@ -0,0 +1,322 @@
//! Reading linked files' bytes for the document model ([`designcraft_doc::asset_data`]): the
//! [`Loader`] every [`crate::Session`] installs. Files are read through [`crate::io`] (the
//! automation roots of the loading thread apply) and only ever yield the bytes the link record
//! names: other bytes at the path are [`Unavailable::Modified`] and are never handed out.
//!
//! The web build installs no loader: its linked assets are [`Unavailable::NoLoader`].
use std::path::{Path, PathBuf};
use designcraft_doc::asset_data::{Loaded, Loader, MAX_LINKED_BYTES};
use designcraft_doc::{Fingerprint, LinkedSource, Unavailable};
/// Read linked files with [`FileLoader`] in this process (on the web: nothing to install).
pub fn install() {
#[cfg(not(target_arch = "wasm32"))]
designcraft_doc::asset_data::install_loader(std::sync::Arc::new(FileLoader));
}
/// The engine's [`Loader`]: [`read_linked`].
pub struct FileLoader;
impl Loader for FileLoader {
fn load(&self, source: &LinkedSource, trusted: Option<Fingerprint>) -> Result<Loaded, Unavailable> {
read_linked(source, trusted)
}
fn load_current(&self, source: &LinkedSource) -> Result<Vec<u8>, Unavailable> {
read_current(source)
}
fn holds(&self, source: &LinkedSource, trusted: Option<Fingerprint>, kept: &[u8]) -> Result<Option<Fingerprint>, Unavailable> {
still_holds(source, trusted, kept)
}
}
/// Whether a candidate file ([`candidates`]) still holds `kept`, the bytes read for `source`
/// earlier ([`Loader::holds`]): one of `source.len` bytes with the recorded or `trusted`
/// fingerprint (nothing is read), else one whose content hash is `source.hash`, or without a
/// hash whose bytes are `kept`. → the fingerprint of a file that was read to tell.
pub fn still_holds(source: &LinkedSource, trusted: Option<Fingerprint>, kept: &[u8]) -> Result<Option<Fingerprint>, Unavailable> {
let mut seen = false;
for path in candidates(source) {
let Some(meta) = crate::io::file_metadata(&path) else { continue };
seen = true;
let found = fingerprint_from(&meta);
if found.size != source.len {
continue;
}
if has_time(&found) && (Some(found) == source.fingerprint || Some(found) == trusted) {
return Ok(None);
}
let Ok(bytes) = crate::io::read_capped(&path, source.len) else { continue };
let same = match &source.hash {
Some(hash) => *hash == content_hash(&bytes),
None => bytes == kept,
};
if same {
return Ok(has_time(&found).then_some(found));
}
}
Err(if seen { Unavailable::Modified } else { Unavailable::Missing })
}
/// The bytes of the first candidate file that exists, whatever they are (no fingerprint or hash
/// check): what an export uses for a link whose file has changed.
pub fn read_current(source: &LinkedSource) -> Result<Vec<u8>, Unavailable> {
for path in candidates(source) {
let Some(meta) = crate::io::file_metadata(&path) else { continue };
if meta.len() > MAX_LINKED_BYTES {
return Err(Unavailable::TooLarge);
}
if let Ok(bytes) = crate::io::read_capped(&path, MAX_LINKED_BYTES) {
return Ok(bytes);
}
}
Err(Unavailable::Missing)
}
/// `sha256:` and the hex digits of the SHA-256 of `bytes` ([`designcraft_doc::Asset::link_hash`]).
pub fn content_hash(bytes: &[u8]) -> String {
use sha2::Digest;
use std::fmt::Write;
let digest = sha2::Sha256::digest(bytes);
let mut out = String::with_capacity(7 + 64);
out.push_str("sha256:");
for b in digest {
let _ = write!(out, "{b:02x}");
}
out
}
/// Size and modification time (whole seconds) from a file's metadata, as link records store them.
pub fn fingerprint_from(meta: &crate::io::Metadata) -> Fingerprint {
let mtime = meta
.modified()
.ok()
.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
.map(|d| i64::try_from(d.as_secs()).unwrap_or(i64::MAX))
.unwrap_or(0);
Fingerprint { size: meta.len(), mtime }
}
/// Whether `f` has a modification time to tell the file by: [`fingerprint_from`] gives 0 where
/// the file system reports none, and two such files of one size would look the same.
pub fn has_time(f: &Fingerprint) -> bool {
f.mtime != 0
}
/// The files that may hold `source`'s bytes, in the order they are tried: the absolute path,
/// then the relative one resolved against the document. Paths [`crate::io::document_path`]
/// refuses are left out.
pub fn candidates(source: &LinkedSource) -> Vec<PathBuf> {
let document = source.document.as_deref();
let mut out: Vec<PathBuf> = crate::io::document_path(&source.path, document).into_iter().collect();
if let (Some(relative), Some(document)) = (source.relative.as_deref(), document)
&& let Ok(p) = crate::io::document_path(relative, Some(document))
&& !out.contains(&p)
{
out.push(p);
}
out
}
/// Why one candidate file doesn't serve.
enum Miss {
Absent,
Modified,
TooLarge,
}
/// The bytes of the first candidate file ([`candidates`]) that holds `source`'s bytes: one of
/// `source.len` bytes whose fingerprint is `source.fingerprint` or `trusted`, or whose content
/// hash is `source.hash`. A source that records neither fingerprint nor hash is taken by its
/// size. The fingerprint of a file accepted by its hash is returned with the bytes.
pub fn read_linked(source: &LinkedSource, trusted: Option<Fingerprint>) -> Result<Loaded, Unavailable> {
if source.len > MAX_LINKED_BYTES {
return Err(Unavailable::TooLarge);
}
let mut worst = Miss::Absent;
for path in candidates(source) {
match read_candidate(&path, source, trusted) {
Ok(loaded) => return Ok(loaded),
Err(Miss::Absent) => {}
Err(miss @ Miss::TooLarge) => worst = miss,
Err(Miss::Modified) => {
if !matches!(worst, Miss::TooLarge) {
worst = Miss::Modified;
}
}
}
}
Err(match worst {
Miss::Absent => Unavailable::Missing,
Miss::Modified => Unavailable::Modified,
Miss::TooLarge => Unavailable::TooLarge,
})
}
fn read_candidate(path: &Path, source: &LinkedSource, trusted: Option<Fingerprint>) -> Result<Loaded, Miss> {
let meta = crate::io::file_metadata(path).ok_or(Miss::Absent)?;
let found = fingerprint_from(&meta);
if found.size > MAX_LINKED_BYTES {
return Err(Miss::TooLarge);
}
if found.size != source.len {
return Err(Miss::Modified);
}
let known = has_time(&found) && (Some(found) == source.fingerprint || Some(found) == trusted);
if !known && source.hash.is_none() && source.fingerprint.is_some() {
// Nothing to tell the bytes by.
return Err(Miss::Modified);
}
// At most one byte past the size: a file that grew since is caught without reading it all.
let bytes = crate::io::read_capped(path, source.len).map_err(|_| Miss::Absent)?;
if bytes.len() as u64 != source.len {
return Err(Miss::Modified);
}
if known {
return Ok(Loaded { bytes, fingerprint: None });
}
match &source.hash {
Some(hash) if *hash != content_hash(&bytes) => Err(Miss::Modified),
Some(_) => Ok(Loaded { bytes, fingerprint: Some(found) }),
None => Ok(Loaded { bytes, fingerprint: None }),
}
}
#[cfg(test)]
mod tests {
use super::*;
use designcraft_doc::AssetData;
struct Dir(PathBuf);
impl Dir {
fn new(name: &str) -> Self {
let dir = std::env::temp_dir().join(format!("dc-asset-io-{name}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
Dir(dir)
}
}
impl Drop for Dir {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
/// The link record of the file at `path` as it is now.
fn source_of(path: &Path) -> LinkedSource {
let bytes = std::fs::read(path).unwrap();
LinkedSource {
path: path.to_string_lossy().into_owned(),
relative: None,
document: None,
len: bytes.len() as u64,
fingerprint: Some(fingerprint_from(&std::fs::metadata(path).unwrap())),
hash: Some(content_hash(&bytes)),
}
}
/// Set the file's modification time `secs` seconds into the past.
fn age(path: &Path, secs: u64) {
let file = std::fs::OpenOptions::new().write(true).open(path).unwrap();
file.set_modified(std::time::SystemTime::now() - std::time::Duration::from_secs(secs)).unwrap();
}
#[test]
fn content_hashes_are_sha256_hex() {
assert_eq!(content_hash(b"abc"), "sha256:ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad");
}
#[test]
fn a_linked_file_is_read_when_it_holds_the_recorded_bytes() {
let dir = Dir::new("read");
let path = dir.0.join("a.png");
std::fs::write(&path, b"original").unwrap();
let source = source_of(&path);
assert_eq!(read_linked(&source, None).ok().map(|l| (l.bytes, l.fingerprint)), Some((b"original".to_vec(), None)));
// Same bytes, another time: accepted by the hash, and the new fingerprint returned.
age(&path, 1000);
let now = fingerprint_from(&std::fs::metadata(&path).unwrap());
let loaded = read_linked(&source, None).ok().unwrap();
assert_eq!((loaded.bytes.as_slice(), loaded.fingerprint), (b"original".as_slice(), Some(now)));
assert!(read_linked(&source, Some(now)).is_ok_and(|l| l.fingerprint.is_none()), "a trusted fingerprint needs no hash");
let unverifiable = LinkedSource { hash: None, ..source.clone() };
assert_eq!(read_linked(&unverifiable, None).err(), Some(Unavailable::Modified), "nothing to tell the bytes by");
}
#[test]
fn other_bytes_at_the_path_are_modified_and_a_missing_file_is_missing() {
let dir = Dir::new("modified");
let path = dir.0.join("a.png");
std::fs::write(&path, b"original").unwrap();
let source = source_of(&path);
std::fs::write(&path, b"changed!").unwrap();
age(&path, 1000);
assert_eq!(read_linked(&source, None).err(), Some(Unavailable::Modified), "same size, other bytes");
std::fs::write(&path, b"longer than before").unwrap();
assert_eq!(read_linked(&source, None).err(), Some(Unavailable::Modified), "another size");
std::fs::remove_file(&path).unwrap();
assert_eq!(read_linked(&source, None).err(), Some(Unavailable::Missing));
let too_large = LinkedSource { len: MAX_LINKED_BYTES + 1, ..source };
assert_eq!(read_linked(&too_large, None).err(), Some(Unavailable::TooLarge));
}
#[test]
fn the_relative_path_serves_when_the_absolute_one_does_not() {
let dir = Dir::new("relative");
std::fs::create_dir_all(dir.0.join("moved/links")).unwrap();
let away = dir.0.join("moved/links/a.png");
std::fs::write(&away, b"original").unwrap();
let mut source = source_of(&away);
source.path = dir.0.join("gone/links/a.png").to_string_lossy().into_owned();
assert_eq!(read_linked(&source, None).err(), Some(Unavailable::Missing));
source.relative = Some("links/a.png".into());
source.document = Some(dir.0.join("moved/doc.dcx"));
assert_eq!(read_linked(&source, None).ok().map(|l| l.bytes), Some(b"original".to_vec()));
// A changed file at the absolute path doesn't hide the one that holds the bytes.
std::fs::create_dir_all(dir.0.join("gone/links")).unwrap();
std::fs::write(dir.0.join("gone/links/a.png"), b"other!!!").unwrap();
age(&dir.0.join("gone/links/a.png"), 1000);
assert_eq!(read_linked(&source, None).ok().map(|l| l.bytes), Some(b"original".to_vec()));
}
/// A time of 0 is what a file system without times gives: it can't tell two files apart.
#[test]
fn a_file_without_a_time_is_told_by_its_hash() {
let dir = Dir::new("no-time");
let path = dir.0.join("a.png");
let at_epoch = |p: &Path| std::fs::OpenOptions::new().write(true).open(p).unwrap().set_modified(std::time::UNIX_EPOCH).unwrap();
std::fs::write(&path, b"original").unwrap();
at_epoch(&path);
let source = source_of(&path);
assert_eq!(source.fingerprint.map(|f| f.mtime), Some(0));
std::fs::write(&path, b"changed!").unwrap();
at_epoch(&path);
assert_eq!(read_linked(&source, None).err(), Some(Unavailable::Modified));
}
/// Through the installed loader and the store: a file changed on disk is never adopted.
#[test]
fn asset_data_loads_through_the_installed_loader() {
install();
let dir = Dir::new("installed");
let path = dir.0.join("a.png");
std::fs::write(&path, b"original").unwrap();
let data = AssetData::linked(source_of(&path));
let changed = AssetData::linked(source_of(&path));
assert_eq!(data.load().ok().map(|b| b.to_vec()), Some(b"original".to_vec()));
assert!(data.resident().is_some());
std::fs::write(&path, b"changed!").unwrap();
age(&path, 1000);
assert_eq!(data.load().ok().map(|b| b.to_vec()), Some(b"original".to_vec()), "kept bytes are the recorded ones");
assert_eq!(changed.load().err(), Some(Unavailable::Modified));
assert!(changed.resident().is_none(), "nothing adopted");
std::fs::remove_file(&path).unwrap();
data.evict();
assert_eq!(data.load().err(), Some(Unavailable::Missing));
}
}
+20 -4
View File
@@ -1,5 +1,6 @@
//! The command registry. Ids follow InDesign's menu structure.
pub(crate) mod alpha_wrap;
mod anchored;
pub mod anchors;
mod articles;
@@ -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<String>) -> EngineError {
EngineError::BadParams { cmd: cmd.into(), msg: msg.into() }
}
/// The bytes of `asset`, or why `cmd` can't have them.
pub(crate) fn asset_bytes(cmd: &str, asset: &designcraft_doc::Asset) -> Result<std::sync::Arc<Vec<u8>>> {
asset.data.load().map_err(|e| bad(cmd, format!("{}: {e}", asset.name)))
}
/// `p` with `key` set to `v`. Parameters come from callers (control channel, MCP, scripts) and
/// may not be an object: `p[key] = v` panics on an array or a string, so start from `{}` then.
pub(crate) fn with_param(p: &Value, key: &str, v: Value) -> Value {
@@ -332,12 +343,16 @@ pub(crate) fn named_targets(spec: &CommandSpec, p: &Value) -> Option<Vec<ItemId>
}
/// 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<u64> {
/// `None` when the call names no table. A `table` that is present but not a non-negative integer,
/// `null` included, is an error. [`table_story`] reads the `story` that goes with it.
pub(crate) fn named_table(spec: &CommandSpec, p: &Value, cmd: &str) -> Result<Option<u64>> {
if !spec.params.split(|c: char| !c.is_ascii_alphanumeric() && c != '?').any(|w| w == "table?") {
return 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;
+598
View File
@@ -0,0 +1,598 @@
//! Text Wrap › Contour › Alpha Channel: the outline of a placed raster's visible pixels.
//!
//! The outline is traced once per image and threshold, in the image's pixel space, and kept on
//! the document ([`designcraft_doc::AlphaOutline`]). Composition maps it through the graphic's
//! current transform, so it follows the image when it is moved, scaled or refitted.
use std::collections::BTreeSet;
use std::sync::Arc;
use designcraft_doc::{AlphaOutline, AssetData, AssetId, ContourType, Document, Item, WrapMode};
use designcraft_geom::{BezPath, PathData, Point};
/// Images larger than this many pixels aren't traced (their contour follows the frame).
const MAX_PIXELS: u64 = 40_000_000;
/// The finest grid an outline is traced on; coarser grids when the outline would be too long.
const MAX_GRID: u32 = 256;
/// Boundary edges an outline may have.
const MAX_EDGES: usize = 1 << 16;
/// Trace the outlines new Alpha Channel contours need and drop the ones nothing uses. Cheap when
/// nothing changed: tracing happens only for an image and threshold not seen before.
pub(crate) fn sync(doc: &mut Document) {
let mut wanted: BTreeSet<(AssetId, u8)> = BTreeSet::new();
// Every frame, in groups and Paste Into containers too, with the wrap set on the frame or on
// its placed graphic (Direct Selection sets the graphic's).
let mut want = |it: &Item| {
let Some(g) = it.graphic() else { return };
for w in [&it.wrap, &g.wrap] {
if w.mode == WrapMode::Contour && w.contour == ContourType::AlphaChannel {
wanted.insert((g.asset, w.alpha_threshold));
}
}
};
for sp in doc.spreads.iter().chain(doc.parents.iter()) {
for top in &sp.items {
top.walk(&mut want);
}
}
// Objects anchored in text wrap the lines after their anchor; anchored_items lists their
// children too.
if doc.has_anchored_items() {
for (_, it) in doc.anchored_items() {
want(it);
}
}
if wanted.is_empty() && doc.alpha_outlines.is_empty() {
return;
}
// An outline traced from data the asset no longer has (relinked or updated) is traced again.
let assets = &doc.assets;
doc.alpha_outlines.retain(|o| wanted.contains(&(o.asset, o.threshold)) && assets.get(&o.asset).is_some_and(|a| o.traced_from(&a.data)));
let traced: BTreeSet<(AssetId, u8)> = doc.alpha_outlines.iter().map(|o| (o.asset, o.threshold)).collect();
let kept = doc.alpha_outlines.len();
for (asset, threshold) in wanted {
if traced.contains(&(asset, threshold)) {
continue;
}
let Some(a) = doc.assets.get(&asset).filter(|a| a.is_raster()) else { continue };
// An image with no outline (unreadable, too large) is remembered as an empty
// one, so later edits don't decode it again; the contour is then the frame's.
// A linked image's original is not read here (a document opens without reading its
// links): its preview is traced, scaled to the original's size; with no preview, the
// image has no outline yet and is traced once its bytes are resident.
let o = if a.data.is_linked() && a.data.resident().is_none() {
let Some(proxy) = a.proxy.as_ref().and_then(|p| Some((p.data.load().ok()?, a.pixels?))) else { continue };
trace_bytes(&proxy.0, a.data.key(), Some(proxy.1), asset, threshold).unwrap_or_else(|| no_outline(&a.data, asset, threshold))
} else {
trace(&a.data, asset, threshold).unwrap_or_else(|| no_outline(&a.data, asset, threshold))
};
doc.alpha_outlines.push(Arc::new(o));
}
// `Document::alpha_outline` finds an outline by binary search.
if doc.alpha_outlines.len() > kept {
doc.alpha_outlines.sort_by_key(|o| (o.asset, o.threshold));
}
}
/// The empty outline standing for an image `trace` found none in: zero-size, which composition
/// takes as no outline, and dropped like a traced one when the asset's data changes.
fn no_outline(data: &AssetData, asset: AssetId, threshold: u8) -> AlphaOutline {
AlphaOutline {
asset,
threshold,
width: 0,
height: 0,
outer: Default::default(),
holes: Default::default(),
source: data.key(),
serial: AlphaOutline::next_serial(),
}
}
/// The outline of the pixels of `data` more opaque than `threshold`: an image with no
/// transparency gives its rectangle. None for an image that can't be read or is too large.
pub(crate) fn trace(data: &AssetData, asset: AssetId, threshold: u8) -> Option<AlphaOutline> {
trace_bytes(&data.load().ok()?, data.key(), None, asset, threshold)
}
/// [`trace`] of encoded `bytes` standing for the data under `source`. With `size`, the outline
/// is scaled to an image of that size (a preview traced for the original it stands for).
fn trace_bytes(bytes: &[u8], source: designcraft_doc::SourceKey, size: Option<(u32, u32)>, asset: AssetId, threshold: u8) -> Option<AlphaOutline> {
let (w, h) = designcraft_images::pixel_size(bytes)?;
if w == 0 || h == 0 || u64::from(w) * u64::from(h) > MAX_PIXELS {
return None;
}
let img = designcraft_images::decode_rgba(bytes)?;
if img.width() != w || img.height() != h {
return None;
}
let mut grid = MAX_GRID;
// The previous grid's mask: a grid half as fine is made from it without reading the pixels again.
let mut finer: Option<(Vec<bool>, u32, u32)> = None;
while grid >= 16 {
let (cols, rows) = (w.min(grid), h.min(grid));
let mask = match finer.as_ref().and_then(|(m, fc, fr)| coarsen(m, *fc, *fr, cols, rows)) {
Some(m) => m,
None => occupancy(img.as_raw(), w, h, cols, rows, threshold),
};
// Composition follows an outline of at most MAX_CONTOUR_POINTS path elements (holes
// included, for Include Inside Edges): a ring of k points is k + 1 elements with its close.
let fits = |outer: &[Vec<(i32, i32)>], holes: &[Vec<(i32, i32)>]| {
outer.iter().chain(holes).map(|r| r.len() + 1).sum::<usize>() <= designcraft_compose::MAX_CONTOUR_POINTS
};
if let Some((outer, holes)) = rings(&mask, cols as usize, rows as usize).filter(|(o, h)| fits(o, h)) {
let (tw, th) = size.filter(|&(a, b)| a > 0 && b > 0).unwrap_or((w, h));
let (sx, sy) = (f64::from(tw) / f64::from(cols), f64::from(th) / f64::from(rows));
let path = |rings: &[Vec<(i32, i32)>]| {
let mut p = BezPath::new();
for ring in rings {
let mut pts = ring.iter().map(|&(x, y)| Point::new(f64::from(x) * sx, f64::from(y) * sy));
let Some(first) = pts.next() else { continue };
p.move_to(first);
for q in pts {
p.line_to(q);
}
p.close_path();
}
PathData::from_bezpath(&p)
};
let serial = AlphaOutline::next_serial();
return Some(AlphaOutline { asset, threshold, width: tw, height: th, outer: path(&outer), holes: path(&holes), source, serial });
}
finer = Some((mask, cols, rows));
grid /= 2;
}
None
}
/// The `cols` × `rows` mask made from a `fc` × `fr` one, when each side has the same number of
/// cells or twice as many (a pixel's coarse cell is then its fine cell, or half of it). None
/// otherwise: the pixels are read again.
fn coarsen(mask: &[bool], fc: u32, fr: u32, cols: u32, rows: u32) -> Option<Vec<bool>> {
let step = |fine: u32, coarse: u32| match fine {
f if f == coarse => Some(1),
f if u64::from(f) == 2 * u64::from(coarse) => Some(2),
_ => None,
};
let (sx, sy) = (step(fc, cols)?, step(fr, rows)?);
let (fc, cols) = (fc as usize, cols as usize);
let mut out = vec![false; cols * rows as usize];
for (i, _) in mask.iter().enumerate().filter(|(_, v)| **v) {
let (x, y) = (i % fc, i / fc);
if let Some(c) = out.get_mut(y / sy * cols + x / sx) {
*c = true;
}
}
Some(out)
}
/// Which cells of a `cols` × `rows` grid hold a pixel of the `w` × `h` RGBA image `rgba` more
/// opaque than `threshold` (a cell is visible when any of its pixels is).
fn occupancy(rgba: &[u8], w: u32, h: u32, cols: u32, rows: u32, threshold: u8) -> Vec<bool> {
let mut mask = vec![false; (cols as usize) * (rows as usize)];
// A pixel's cell is (x * cols / w, y * rows / h). Along a row the column is counted up as x
// passes each cell's edge (cols <= w, so at most one edge per pixel) instead of divided out.
for (y, row) in rgba.chunks_exact(w as usize * 4).take(h as usize).enumerate() {
let base = (y as u64 * u64::from(rows) / u64::from(h)) as usize * cols as usize;
let (mut gx, mut acc, mut edge) = (0usize, 0u64, u64::from(w));
for px in row.as_chunks::<4>().0 {
if acc >= edge {
gx += 1;
edge += u64::from(w);
}
acc += u64::from(cols);
if px[3] > threshold
&& let Some(c) = mask.get_mut(base + gx)
{
*c = true;
}
}
}
mask
}
/// The closed boundaries of the visible cells, split into outer boundaries and the boundaries of
/// holes (by winding: each boundary keeps the visible cells on the same side). None when the
/// outline would have more than [`MAX_EDGES`] edges.
#[allow(clippy::type_complexity)]
fn rings(mask: &[bool], cols: usize, rows: usize) -> Option<(Vec<Vec<(i32, i32)>>, Vec<Vec<(i32, i32)>>)> {
use std::collections::BTreeMap;
let visible = |x: i32, y: i32| {
x >= 0 && y >= 0 && (x as usize) < cols && (y as usize) < rows && mask.get(y as usize * cols + x as usize).copied().unwrap_or(false)
};
let mut edges: BTreeMap<(i32, i32), Vec<(i32, i32)>> = BTreeMap::new();
let mut count = 0usize;
for y in 0..rows as i32 {
for x in 0..cols as i32 {
if !visible(x, y) {
continue;
}
for (open, a, b) in [
(!visible(x, y - 1), (x, y), (x + 1, y)),
(!visible(x + 1, y), (x + 1, y), (x + 1, y + 1)),
(!visible(x, y + 1), (x + 1, y + 1), (x, y + 1)),
(!visible(x - 1, y), (x, y + 1), (x, y)),
] {
if open {
count += 1;
if count > MAX_EDGES {
return None;
}
edges.entry(a).or_default().push(b);
}
}
}
}
let (mut outer, mut holes) = (Vec::new(), Vec::new());
while let Some((&start, _)) = edges.first_key_value() {
let mut ring = vec![start];
let mut at = start;
for _ in 0..=MAX_EDGES {
let next = edges.get_mut(&at).and_then(Vec::pop)?;
if edges.get(&at).is_some_and(Vec::is_empty) {
edges.remove(&at);
}
// Drop the middle of straight runs.
if let [.., a, b] = ring[..]
&& (b.0 - a.0) * (next.1 - b.1) == (b.1 - a.1) * (next.0 - b.0)
{
ring.pop();
}
if next == start {
break;
}
ring.push(next);
at = next;
}
// Shoelace in y-down space: positive for outer boundaries, negative for holes.
let area: i64 = ring
.iter()
.zip(ring.iter().cycle().skip(1))
.map(|(&(x0, y0), &(x1, y1))| i64::from(x0) * i64::from(y1) - i64::from(x1) * i64::from(y0))
.sum();
if ring.len() >= 3 {
if area > 0 { outer.push(ring) } else { holes.push(ring) }
}
}
Some((outer, holes))
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
use crate::Session;
/// A 64 × 64 PNG: visible where `on(x, y)`.
fn png(on: impl Fn(usize, usize) -> bool) -> Vec<u8> {
png_sized(64, on)
}
/// A `size` × `size` PNG: visible where `on(x, y)`.
fn png_sized(size: usize, on: impl Fn(usize, usize) -> bool) -> Vec<u8> {
let mut pixels = vec![0; size * size * 4];
for y in 0..size {
for x in 0..size {
let i = (y * size + x) * 4;
pixels[i] = 120;
pixels[i + 3] = if on(x, y) { 255 } else { 0 };
}
}
designcraft_render::Rendered { width: size as u32, height: size as u32, pixels }.to_png()
}
/// An outline too detailed for composition (here 4,096 separate dots, 20,480 path elements
/// on the finest grid) is traced on a coarser grid until composition can follow it.
#[test]
fn a_fragmented_outline_is_traced_coarser_until_composition_can_follow_it() {
let dots = png_sized(256, |x, y| x % 4 == 0 && y % 4 == 0);
let o = trace(&AssetData::embedded(dots), AssetId(1), 25).unwrap();
let elements = o.outer.to_bezpath().elements().len() + o.holes.to_bezpath().elements().len();
assert!(elements > 0 && elements <= designcraft_compose::MAX_CONTOUR_POINTS, "{elements} path elements");
}
/// An image with no pixel more opaque than the threshold leaves the text alone: with the
/// frame's contour the caption over it is overset, with Alpha Channel it is set.
#[test]
fn an_image_with_nothing_visible_wraps_no_text() {
let (mut s, image, story) = page(&png(|_, _| false), [150.0, 150.0, 178.0, 178.0]);
assert!(overset(&s, story), "the frame's contour covers the caption");
s.execute("object.textWrap", &json!({"ids": [image], "contour": "alphaChannel"})).unwrap();
assert!(!overset(&s, story), "nothing visible: nothing wraps");
// The same for the wrap set on the placed graphic.
s.execute("object.textWrap", &json!({"ids": [image], "mode": "none"})).unwrap();
s.execute("object.textWrap", &json!({"ids": [image], "content": true, "mode": "contour", "contour": "alphaChannel"})).unwrap();
assert!(!overset(&s, story));
}
#[test]
fn traces_outer_boundaries_and_holes_apart() {
// A ring: a square with a square hole.
let data = png(|x, y| (8..56).contains(&x) && (8..56).contains(&y) && !((24..40).contains(&x) && (24..40).contains(&y)));
let o = trace(&AssetData::embedded(data), AssetId(1), 25).unwrap();
assert_eq!((o.width, o.height), (64, 64));
assert_eq!((o.outer.subpaths.len(), o.holes.subpaths.len()), (1, 1));
let (a, b) = (o.outer.bounds().unwrap(), o.holes.bounds().unwrap());
assert_eq!((a.x0, a.y0, a.x1, a.y1), (8.0, 8.0, 56.0, 56.0));
assert_eq!((b.x0, b.y0, b.x1, b.y1), (24.0, 24.0, 40.0, 40.0));
// An opaque image's outline is its rectangle.
let o = trace(&AssetData::embedded(png(|_, _| true)), AssetId(1), 25).unwrap();
let a = o.outer.bounds().unwrap();
assert_eq!((a.x0, a.y0, a.x1, a.y1, o.holes.subpaths.len()), (0.0, 0.0, 64.0, 64.0, 0));
}
/// The cell masks match a pixel-by-pixel count (cell = x * cols / w, y * rows / h), and a
/// mask half as fine made from the finer one matches the mask read from the pixels.
#[test]
fn cell_masks_match_the_pixels_and_coarser_masks_match_the_finer_ones() {
let (w, h) = (600u32, 300u32);
// An irregular pattern: visible where a small hash says so.
let on = |x: u32, y: u32| (x.wrapping_mul(2_654_435_761) ^ y.wrapping_mul(40_503)).rotate_left(7).is_multiple_of(7);
let mut rgba = vec![0u8; (w * h * 4) as usize];
for y in 0..h {
for x in 0..w {
rgba[((y * w + x) * 4 + 3) as usize] = if on(x, y) { 255 } else { 0 };
}
}
for (cols, rows) in [(256, 256), (128, 128), (100, 37), (600, 300)] {
let mut expect = vec![false; (cols * rows) as usize];
for y in 0..h {
for x in 0..w {
if on(x, y) {
expect[((y * rows / h) * cols + x * cols / w) as usize] = true;
}
}
}
assert_eq!(occupancy(&rgba, w, h, cols, rows, 25), expect, "{cols} x {rows}");
}
let fine = occupancy(&rgba, w, h, 256, 256, 25);
assert_eq!(coarsen(&fine, 256, 256, 128, 128), Some(occupancy(&rgba, w, h, 128, 128, 25)));
// Same count on one side, twice on the other.
let fine = occupancy(&rgba, w, h, 128, 256, 25);
assert_eq!(coarsen(&fine, 128, 256, 128, 128), Some(occupancy(&rgba, w, h, 128, 128, 25)));
// Any other ratio is read from the pixels.
assert_eq!(coarsen(&fine, 128, 256, 100, 128), None);
}
#[test]
fn an_alpha_channel_contour_is_traced_when_set_and_kept_out_of_the_saved_file() {
let mut s = Session::new();
s.execute("file.new", &json!({})).unwrap();
let data = png(|x, _| (16..48).contains(&x));
let id = s
.execute("file.place", &json!({"base64": crate::cmd::file::base64_encode(&data), "name": "cut.png", "x": 100, "y": 100, "width": 128}))
.unwrap()["id"]
.clone();
assert!(s.doc().unwrap().doc.alpha_outlines.is_empty());
s.execute("object.textWrap", &json!({"ids": [id], "mode": "contour", "contour": "alphaChannel"})).unwrap();
let d = &s.doc().unwrap().doc;
assert_eq!(d.alpha_outlines.len(), 1);
// Saved and opened again: traced again on open.
let bytes = crate::cmd::file::to_bytes(d).unwrap();
let back = crate::cmd::file::from_bytes(&bytes).unwrap();
assert!(back.alpha_outlines.is_empty(), "not saved");
let st = crate::DocState::new(back, None);
assert_eq!(st.doc.alpha_outlines.len(), 1, "traced on open");
// Wrap off: the outline goes.
s.execute("object.textWrap", &json!({"ids": [id], "mode": "none"})).unwrap();
assert!(s.doc().unwrap().doc.alpha_outlines.is_empty());
}
/// An outline is traced once: later edits keep it.
#[test]
fn an_outline_is_not_traced_on_every_edit() {
let mut s = Session::new();
s.execute("file.new", &json!({})).unwrap();
let data = png(|_, _| true);
let id = s
.execute("file.place", &json!({"base64": crate::cmd::file::base64_encode(&data), "name": "solid.png", "x": 100, "y": 100, "width": 128}))
.unwrap()["id"]
.clone();
s.execute("object.textWrap", &json!({"ids": [id], "mode": "contour", "contour": "alphaChannel"})).unwrap();
let first = s.doc().unwrap().doc.alpha_outlines.clone();
assert_eq!(first.len(), 1, "remembered");
s.execute("frame.create", &json!({"rect": [300, 300, 350, 350]})).unwrap();
let after = &s.doc().unwrap().doc.alpha_outlines;
assert!(Arc::ptr_eq(&first[0], &after[0]), "kept, not traced again");
}
/// An opaque image's Alpha Channel contour is its rectangle, not the frame: moved within its
/// frame, it leaves the empty part of the frame to the text.
#[test]
fn an_opaque_image_wraps_its_rectangle() {
let (mut s, image, story) = page(&png(|_, _| true), [105.0, 150.0, 125.0, 178.0]);
s.execute("object.textWrap", &json!({"ids": [image], "contour": "alphaChannel"})).unwrap();
assert!(overset(&s, story), "the image covers the caption");
// The graphic moved 30 pt right within its frame: the frame's left 30 pt are empty.
s.execute("selection.set", &json!({"ids": [image], "content": true})).unwrap();
s.execute("transform.move", &json!({"dx": 30, "dy": 0})).unwrap();
assert!(!overset(&s, story), "the empty part of the frame takes the caption");
}
/// Outlines are traced for a wrap set on the placed graphic and for frames inside groups, and
/// traced again when the image's data changes under the same asset (relink, link update).
#[test]
fn graphic_wraps_nested_frames_and_relinked_images_get_outlines() {
let mut s = Session::new();
s.execute("file.new", &json!({})).unwrap();
let place = |s: &mut Session, x: u64| {
let data = png(|x, _| (16..48).contains(&x));
s.execute("file.place", &json!({"base64": crate::cmd::file::base64_encode(&data), "name": "cut.png", "x": x, "y": 100, "width": 128}))
.unwrap()["id"]
.as_u64()
.unwrap()
};
let image = place(&mut s, 100);
// The wrap on the graphic (Direct Selection), not the frame.
s.execute("object.textWrap", &json!({"ids": [image], "content": true, "mode": "contour", "contour": "alphaChannel"})).unwrap();
let frame_wrap = s.doc().unwrap().doc.item(designcraft_doc::ItemId(image)).unwrap().wrap.mode;
assert_eq!(frame_wrap, WrapMode::None, "the frame has no wrap of its own");
assert_eq!(s.doc().unwrap().doc.alpha_outlines.len(), 1, "traced for the graphic's wrap");
// In a group with another frame: still traced.
let other = s.execute("frame.create", &json!({"rect": [300, 100, 350, 150]})).unwrap()["id"].as_u64().unwrap();
s.execute("object.group", &json!({"ids": [image, other]})).unwrap();
let d = &s.doc().unwrap().doc;
assert!(d.find(designcraft_doc::ItemId(image)).unwrap().path.len() > 1, "the frame is nested");
assert_eq!(d.alpha_outlines.len(), 1, "a nested frame keeps its outline");
// A frame placed and grouped before its wrap is set: traced too.
let second = place(&mut s, 400);
let other2 = s.execute("frame.create", &json!({"rect": [600, 100, 650, 150]})).unwrap()["id"].as_u64().unwrap();
s.execute("object.group", &json!({"ids": [second, other2]})).unwrap();
s.execute("object.textWrap", &json!({"ids": [second], "mode": "contour", "contour": "alphaChannel", "threshold": 200})).unwrap();
assert_eq!(s.doc().unwrap().doc.alpha_outlines.len(), 2);
// The image data replaced under the same asset, as a relink does: traced again.
let Some(designcraft_doc::Content::Graphic(g)) = s.doc().unwrap().doc.item(designcraft_doc::ItemId(image)).map(|it| it.content.clone())
else {
panic!("a graphic")
};
let narrower = AssetData::embedded(png(|x, _| (24..40).contains(&x)));
s.edit(|d, _| {
let a = d.assets.get(&g.asset).unwrap();
let mut a = (**a).clone();
a.data = narrower.clone();
d.assets.insert(g.asset, Arc::new(a));
Ok(())
})
.unwrap();
let d = &s.doc().unwrap().doc;
let o = d.alpha_outline(g.asset, designcraft_doc::DEFAULT_ALPHA_THRESHOLD).unwrap();
assert!(o.traced_from(&narrower));
let b = o.outer.bounds().unwrap();
assert_eq!((b.x0, b.x1), (24.0, 40.0), "the new image's outline");
}
/// An outline traced after others is still found: a threshold lower than a kept outline's
/// is traced later and must not hide either outline from the lookup.
#[test]
fn outlines_traced_later_are_found_by_image_and_threshold() {
let mut s = Session::new();
s.execute("file.new", &json!({})).unwrap();
let data = png(|x, _| (16..48).contains(&x));
let image = s
.execute("file.place", &json!({"base64": crate::cmd::file::base64_encode(&data), "name": "cut.png", "x": 100, "y": 100, "width": 128}))
.unwrap()["id"]
.as_u64()
.unwrap();
s.execute("object.textWrap", &json!({"ids": [image], "content": true, "mode": "contour", "contour": "alphaChannel", "threshold": 200}))
.unwrap();
s.execute("object.textWrap", &json!({"ids": [image], "mode": "contour", "contour": "alphaChannel"})).unwrap();
let d = &s.doc().unwrap().doc;
assert_eq!(d.alpha_outlines.len(), 2, "one outline for each threshold");
let Some(g) = d.item(designcraft_doc::ItemId(image)).and_then(|it| it.graphic()) else { panic!("a graphic") };
for threshold in [designcraft_doc::DEFAULT_ALPHA_THRESHOLD, 200] {
let o = d.alpha_outline(g.asset, threshold);
assert!(o.is_some_and(|o| o.threshold == threshold), "the outline at {threshold} is found");
}
assert!(d.alpha_outline(g.asset, 100).is_none(), "no outline at a threshold nothing uses");
}
/// A wrap with the default threshold saves as it did before thresholds were stored; another
/// threshold is saved.
#[test]
fn the_default_threshold_is_left_out_of_a_saved_wrap() {
let v = serde_json::to_value(designcraft_doc::TextWrap::default()).unwrap();
assert!(v.get("alphaThreshold").is_none(), "{v}");
let back: designcraft_doc::TextWrap = serde_json::from_value(v).unwrap();
assert_eq!(back.alpha_threshold, designcraft_doc::DEFAULT_ALPHA_THRESHOLD);
let w = designcraft_doc::TextWrap { alpha_threshold: 200, ..Default::default() };
assert_eq!(serde_json::to_value(w).unwrap()["alphaThreshold"], 200);
}
/// A relink that changes only the image data recomposes the text around the new outline.
#[test]
fn text_is_composed_again_around_a_relinked_images_outline() {
let (mut s, image, story) = page(&png(|x, _| x < 32), [180.0, 150.0, 220.0, 178.0]);
s.execute("object.textWrap", &json!({"ids": [image], "contour": "alphaChannel"})).unwrap();
assert!(!overset(&s, story), "the left half is visible: the caption on the right is set");
let Some(designcraft_doc::Content::Graphic(g)) =
s.doc().unwrap().doc.item(designcraft_doc::ItemId(image.as_u64().unwrap())).map(|it| it.content.clone())
else {
panic!("a graphic")
};
let right = AssetData::embedded(png(|x, _| x >= 32));
s.edit(|d, _| {
let mut a = (**d.assets.get(&g.asset).unwrap()).clone();
a.data = right.clone();
d.assets.insert(g.asset, Arc::new(a));
Ok(())
})
.unwrap();
assert!(overset(&s, story), "the right half is visible now: it covers the caption");
}
/// An image anchored in text keeps its outline: anchored objects wrap the lines after their
/// anchor, and they are kept in the story, not on the spread.
#[test]
fn an_anchored_image_keeps_its_outline() {
let mut s = Session::new();
s.execute("file.new", &json!({})).unwrap();
let data = png(|x, _| (16..48).contains(&x));
let image = s
.execute("file.place", &json!({"base64": crate::cmd::file::base64_encode(&data), "name": "cut.png", "x": 100, "y": 100, "width": 128}))
.unwrap()["id"]
.as_u64()
.unwrap();
s.execute("object.textWrap", &json!({"ids": [image], "mode": "contour", "contour": "alphaChannel"})).unwrap();
assert_eq!(s.doc().unwrap().doc.alpha_outlines.len(), 1);
let t = s.execute("frame.create", &json!({"rect": [36, 300, 400, 500], "content": "text", "text": "Before after."})).unwrap();
s.execute("anchored.insert", &json!({"ids": [image], "story": t["story"], "pos": 7})).unwrap();
let d = &s.doc().unwrap().doc;
assert!(d.anchored_item(designcraft_doc::ItemId(image)).is_some(), "the image is in the text");
assert_eq!(d.alpha_outlines.len(), 1, "the anchored image keeps its outline");
}
/// An image placed 128 pt wide at (100, 100) (2 pt per pixel), its wrap a contour with no
/// offset, and a caption frame at `caption` with 8 pt "Hi".
fn page(data: &[u8], caption: [f64; 4]) -> (Session, Value, u64) {
let mut s = Session::new();
s.execute("file.new", &json!({})).unwrap();
let image = s
.execute("file.place", &json!({"base64": crate::cmd::file::base64_encode(data), "name": "cut.png", "x": 100, "y": 100, "width": 128}))
.unwrap()["id"]
.clone();
let c = s.execute("frame.create", &json!({"rect": caption, "content": "text", "text": "Hi"})).unwrap();
s.execute("selection.set", &json!({"ids": [c["id"]]})).unwrap();
s.execute("type.char", &json!({"size": 8})).unwrap();
s.execute("object.textWrap", &json!({"ids": [image], "mode": "contour", "offset": 0})).unwrap();
(s, image, c["story"].as_u64().unwrap())
}
fn overset(s: &Session, story: u64) -> bool {
s.cache.get(&s.doc().unwrap().doc, designcraft_doc::StoryId(story), None).is_overset()
}
use serde_json::Value;
/// A caption fits between two legs of a cutout, and the contour follows the image when it's
/// moved within its frame (it isn't a boundary stored where it was traced).
#[test]
fn an_alpha_channel_contour_keeps_gaps_open_and_follows_the_image() {
// Legs at pixels 8..20 and 44..56: 116..140 and 188..212 on the page.
let (mut s, image, story) = page(&png(|x, _| (8..20).contains(&x) || (44..56).contains(&x)), [150.0, 120.0, 178.0, 170.0]);
assert!(overset(&s, story), "the frame's contour covers the gap");
s.execute("object.textWrap", &json!({"ids": [image], "contour": "alphaChannel"})).unwrap();
assert!(!overset(&s, story), "the gap between the legs stays open");
// The graphic moved 30 pt right within its frame: its left leg now covers the caption.
s.execute("selection.set", &json!({"ids": [image], "content": true})).unwrap();
s.execute("transform.move", &json!({"dx": 30, "dy": 0})).unwrap();
assert!(overset(&s, story), "the contour moved with the image");
s.execute("edit.undo", &json!({})).unwrap();
assert!(!overset(&s, story));
}
/// A hole enclosed by the image stays blocked unless Include Inside Edges is on.
#[test]
fn holes_are_blocked_unless_inside_edges_are_included() {
// A ring: outer 116..212, hole 148..180 on the page.
let ring = png(|x, y| (8..56).contains(&x) && (8..56).contains(&y) && !((24..40).contains(&x) && (24..40).contains(&y)));
let (mut s, image, story) = page(&ring, [152.0, 152.0, 176.0, 176.0]);
s.execute("object.textWrap", &json!({"ids": [image], "contour": "alphaChannel"})).unwrap();
assert!(overset(&s, story), "the hole is blocked with the ring around it");
s.execute("object.textWrap", &json!({"ids": [image], "insideEdges": true})).unwrap();
assert!(!overset(&s, story), "Include Inside Edges lets text into the hole");
for bad in [json!({"ids": [image], "threshold": 255}), json!({"ids": [image], "insideEdges": 1})] {
assert!(s.execute("object.textWrap", &bad).is_err());
}
}
}
+1 -1
View File
@@ -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
}
+41 -10
View File
@@ -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<Value> {
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<T>(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<Value> {
let b = s.book.as_ref().ok_or_else(no_book)?;
@@ -191,6 +202,11 @@ fn sync_styles(s: &Session) -> Result<Value> {
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<Value> {
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<String, usize> = 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)]);
}
}
+3 -2
View File
@@ -37,11 +37,12 @@ fn extract(s: &mut Session, p: &Value) -> Result<Value> {
};
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);
+74 -9
View File
@@ -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<CommandSpec> {
"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<Value> {
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<Value> {
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<Value> = 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<Value> {
fn add_placeholder(d: &mut Document, sel: &mut Selection, p: &Value, name: &str) -> Result<Value> {
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);
}
+232 -44
View File
@@ -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<AnchoredObject>,
}
/// 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<PathBuf, std::sync::Arc<Vec<u8>>>,
files: std::collections::HashMap<PathBuf, designcraft_doc::AssetData>,
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<Vec<u8>>) -> Option<std::sync::Arc<Vec<u8>>> {
fn get_or_read(&self, path: &Path, read: impl FnOnce() -> Option<Vec<u8>>) -> Option<designcraft_doc::AssetData> {
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<Rep>,
images: Vec<InlineImage>,
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<Rep>,
images: &mut Vec<InlineImage>,
) {
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 `<<Field>>` 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<StoryId> = 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<LoadedImage> {
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<AnchoredObject> {
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());
}
}
+17 -5
View File
@@ -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<usize>, seen: &mut std::collections::HashSet<usize>) -> 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<usize>, seen: &mut std::collections::HashSet<usize>) -> 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<usize>, 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<PathBuf> {
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<PathBuf> = Vec::new();
for p in found.flatten() {
if !out.contains(&p) {
+489
View File
@@ -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: <<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 <<Name>><<City>><<Photo>>".to_string()]);
let t = s.documents()[0].selection.text.unwrap();
assert_eq!((t.anchor, t.focus), (28, 28));
}
/// A typed `<<name>>` 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 <<Photo>> 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<String> {
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"], "<<City>>", "{r}");
assert_eq!(cell_texts(&s), ["Who", "<<City>>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", "<<City>>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<String> =
merged.stories.values().flat_map(|st| st.tables.values().map(|t| t.cells[1].text.text.clone()).collect::<Vec<_>>()).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<<Name>>", 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", "<<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", "<<City>>, 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("<<City>>"), "in the merged cell: {cells:?}");
assert!(!cells[1].contains("<<City>>"), "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 <ID>,City\n7,London\n");
let e = s.execute("data.placeholder.add", &json!({"field": "Customer <ID>"})).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>"}))["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", &params).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"], "<<Photo>>", "{r}");
assert_eq!(cell_texts(&s), ["Who", "<<Photo>>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 <<City>>"}));
let endnotes = |s: &Session| -> Vec<String> {
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 <<City>>"]);
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 `<<Name>>`.
let nest = |depth: usize| {
let mut inner: Option<Table> = 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("<<Name>>", 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());
}
+8 -5
View File
@@ -142,15 +142,18 @@ fn paste_text(s: &mut Session, text: Option<String>, formatted: bool) -> Result<
let mut stories = std::collections::HashMap::new();
let fresh: Vec<designcraft_doc::Item> = 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::<std::result::Result<_, _>>()?;
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()}))
+3
View File
@@ -22,3 +22,6 @@ pub use registry::specs;
#[cfg(test)]
mod text_tests;
#[cfg(test)]
mod linked_tests;
+7 -6
View File
@@ -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());
+51 -10
View File
@@ -25,7 +25,8 @@ pub(super) fn print_booklet(s: &mut Session, p: &Value) -> Result<Value> {
}
}
/// 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<String>) {
// 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<Value> {
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');
@@ -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<u8> {
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(&copy).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("<img"), "the linked graphic is in the HTML");
let r = s.execute("file.exportEpub", &json!({})).unwrap();
let z = zip::ZipArchive::new(std::io::Cursor::new(crate::cmd::base64_decode(r["base64"].as_str().unwrap()))).unwrap();
let names: Vec<String> = 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}");
}
+33
View File
@@ -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");
}
}
@@ -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]
+5 -1
View File
@@ -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();
+1 -1
View File
@@ -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};
@@ -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();
+9 -3
View File
@@ -102,13 +102,15 @@ fn open_path(s: &mut Session, p: &Value) -> Result<Value> {
};
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<Value> {
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)]
+592 -51
View File
@@ -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<Value> {
// 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<Value> {
}
// 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<Value> {
_ => 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<Value> {
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<Value> {
};
*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<Item = Pending>) {
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<u8>, String, Option<String>)> {
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<u8>, String, Option<String>, Option<designcraft_doc::Fingerprint>)> {
/// 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<u8>,
pub name: String,
file: Option<FileLink>,
/// `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<Pending> {
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<std::path::PathBuf> {
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<Source> {
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<u8>, String, Option<String>, Opt
#[cfg(target_arch = "wasm32")]
let b: Vec<u8> = 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<Option<(f64, f64)>> {
@@ -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<Value> {
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<Value> {
/// 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<Value> {
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<Value> {
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<Value> {
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<Value> {
*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<Value> {
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<Value> {
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<usize> {
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<Vec<Rect>> {
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<ItemId> {
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<Value> {
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::<Vec<_>>(), "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<Value> {
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<craft_file_formats::Format>) -> Result<Value> {
@@ -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<String> {
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<u32>) -> std::io::Result<tempfile::NamedTempFile> {
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", &params).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);
}
}
+54 -22
View File
@@ -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<CommandSpec> {
}),
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(&copy, &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<CommandSpec> {
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<CommandSpec> {
"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
),
+51 -8
View File
@@ -19,16 +19,28 @@ pub(super) fn file_save(s: &mut Session, p: &Value) -> Result<Value> {
// 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<Value> {
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<Value> {
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(&copy, || false) {
copy = proxied;
}
let warnings = crate::cmd::native_links::web_save_warnings(&copy);
let bytes = to_bytes_with_preview(&copy, &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<Value> {
} 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;
+1 -2
View File
@@ -23,8 +23,7 @@ pub(super) fn snippet_export(s: &mut Session, p: &Value) -> Result<Value> {
}
pub(crate) fn snippet_place(s: &mut Session, p: &Value) -> Result<Value> {
let (bytes, _, _) = read_source(p)?;
let src = from_bytes(&bytes)?;
let src = from_bytes(&read_source(p)?.bytes)?;
let ids: Vec<ItemId> = 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"));
+17 -9
View File
@@ -316,19 +316,27 @@ impl Search {
) -> Result<Vec<(Range<usize>, 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,
+18
View File
@@ -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<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);
}
+194 -26
View File
@@ -17,7 +17,7 @@ use crate::{DocState, EngineError, Result, Session};
pub fn specs() -> Vec<CommandSpec> {
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<Value> {
let st = s.doc()?;
let opts = designcraft_idml::ExportOptions { embed_images: p.get("embedImages").and_then(Value::as_bool).unwrap_or(true) };
let layer_doc = with_pdf_layer_variants(&st.doc, opts.embed_images)?;
let bytes = 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<Value> {
/// 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<Option<Documen
.into_iter()
.filter(|it| it.has_pdf_layer_override())
.filter_map(|it| {
let asset = it.graphic().and_then(|g| doc.assets.get(&g.asset)).filter(|a| designcraft_render::is_pdf(&a.data))?;
let asset =
it.graphic().and_then(|g| doc.assets.get(&g.asset)).filter(|a| a.data.load().is_ok_and(|b| designcraft_render::is_pdf(&b)))?;
Some((it.id, asset, it.pdf_hidden_layers.clone(), it.pdf_layer_override))
})
.collect();
@@ -85,11 +91,12 @@ fn with_pdf_layer_variants(doc: &Document, embed: bool) -> Result<Option<Documen
continue;
}
expected.insert(id, signature);
let bytes = designcraft_render::pdf_hide_layers(&asset.data, &hidden)
let source = asset.data.load().map_err(|e| EngineError::Other(format!("{}: {e}", asset.name)))?;
let bytes = designcraft_render::pdf_hide_layers(&source, &hidden)
.ok_or_else(|| EngineError::Other(format!("{}: PDF layer choices could not be applied", asset.name)))?;
let mut variant = (**asset).clone();
variant.id = designcraft_doc::AssetId(out.alloc());
variant.data = std::sync::Arc::new(bytes);
variant.data = designcraft_doc::AssetData::embedded(bytes);
variant.set_link(None, None);
let aid = variant.id;
out.assets.insert(aid, std::sync::Arc::new(variant));
@@ -175,7 +182,7 @@ fn import_report_with_previews(
#[cfg(not(target_arch = "wasm32"))]
{
let (path, data, fingerprint) = read_packaged_link(link, package)?;
resolved.borrow_mut().insert(link.to_string(), (path, fingerprint));
resolved.borrow_mut().insert(link.to_string(), (path, fingerprint, data.len() as u64));
Some(data)
}
#[cfg(target_arch = "wasm32")]
@@ -191,9 +198,17 @@ fn import_report_with_previews(
let document = {
let mut document = document;
for asset in document.assets.values_mut() {
if let Some((path, fingerprint)) = asset.link.as_ref().and_then(|link| resolved.borrow().get(link).cloned()) {
if let Some((path, fingerprint, len)) = asset.link.as_ref().and_then(|link| resolved.borrow().get(link).cloned()) {
// Relocated packages must also use the new path for preflight and link updates.
std::sync::Arc::make_mut(asset).set_link(Some(path), fingerprint);
// Bytes read from the file stay a link to it; graphics embedded in the IDML (whose
// size differs from the file's, or that share no read) stay embedded.
if asset.data.embedded_bytes().is_some_and(|b| b.len() as u64 == len) {
link_read_file(std::sync::Arc::make_mut(asset), package);
} else if asset.proxy.is_some() {
// An embedded graphic draws its own bytes.
std::sync::Arc::make_mut(asset).proxy = None;
}
}
}
resolve_packaged_links(&mut document, package);
@@ -202,6 +217,64 @@ fn import_report_with_previews(
Ok((document, warnings, story_ids))
}
/// `asset`, whose embedded bytes were just read from the file its link names, as a linked asset
/// ([`super::links::link_to_file`]), drawn while the file can't be read with a proxy: the
/// document's preview of it when that shows the whole image ([`preview_proxy`],
/// [`shows_whole`]), else one made from the file, else the preview.
#[cfg(not(target_arch = "wasm32"))]
fn link_read_file(asset: &mut designcraft_doc::Asset, package: Option<&std::path::Path>) {
let Some(bytes) = asset.data.embedded_bytes().cloned() else { return };
let Some(path) = asset.link.clone() else { return };
let preview = asset.proxy.take().and_then(|p| preview_proxy(&p));
let (whole, fallback) = match preview {
Some(p) if shows_whole(asset, &bytes, &p) => (Some(p), None),
p => (None, p),
};
// The fingerprint kept by the read (none for a file just written: its hash tells its bytes).
let file = super::links::FileLink::of(std::path::Path::new(&path), asset.link_fingerprint);
super::links::link_to_file(asset, bytes, file, package, whole);
if asset.storage == designcraft_doc::Storage::Linked && asset.proxy.is_none() {
asset.proxy = fallback;
}
}
/// A document's stored preview of a linked graphic as a proxy: checked to decode, and made again
/// within the proxy limits ([`designcraft_render::proxy`]) when it is bigger or in another
/// format (a larger one wouldn't be kept by the saved document). `None` when it doesn't decode.
#[cfg(not(target_arch = "wasm32"))]
fn preview_proxy(preview: &designcraft_doc::Proxy) -> Option<designcraft_doc::Proxy> {
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<u8>| {
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(&copy).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 = &copy.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(&copy.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)]);
}
File diff suppressed because it is too large. Load diff
+10 -1
View File
@@ -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<CommandSpec> {
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 \"<name> copy\"",
has_doc,
duplicate_layer
),
cmd!(
"layer.set",
"Layer Options…",
+530 -72
View File
@@ -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<CommandSpec> {
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<CommandSpec> {
"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<Fingerprint>, 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<Fingerprint>,
}
impl FileLink {
pub(crate) fn of(path: &Path, before: Option<Fingerprint>) -> 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<designcraft_doc::Proxy> {
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<Arc<Vec<u8>>>, file: Option<FileLink>, embed: bool, document: Option<&Path>) {
let bytes: Arc<Vec<u8>> = 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<Arc<Vec<u8>>>,
file: Option<FileLink>,
embed: bool,
document: Option<&Path>,
) -> Option<super::native_links::Pending> {
let bytes: Arc<Vec<u8>> = 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<Vec<u8>>, file: FileLink, document: Option<&Path>, preview: Option<designcraft_doc::Proxy>) {
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<Vec<u8>>,
key: designcraft_doc::SourceKey,
document: Option<&Path>,
proxy: impl FnOnce(&Asset, &[u8]) -> Option<designcraft_doc::Proxy>,
) {
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<Fingerprint>) {
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<Fingerprint>, 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<Fingerprint>) {
/// [`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<Fingerprint>) {
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<Value> {
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<Vec<Value>> {
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<Document>, 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<Document>, 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<Vec<Value>> {
fn list(
d: &Document,
cache: &Cache,
document: Option<&Path>,
files: Option<&mut LinkListChecks>,
stop: Option<&AtomicBool>,
open: Option<&super::native_links::OpenLinks>,
) -> Option<Vec<Value>> {
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<Path>) -> Result<(Vec<u8>, (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<Arc<designcraft_doc::Asset>> {
/// 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<Arc<designcraft_doc::Asset>> {
// 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<std::path::PathBuf> {
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<Value> {
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<Value> {
});
}
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<Value> {
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<Value> {
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<Value> {
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<Value> {
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<std::path::PathBuf> {
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<Value> {
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<Value> {
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<Value> {
})
.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<Value> {
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#"<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10"/>"#).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<u8> {
use std::io::Write;
const W: &str = r#"xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main""#;
let styles = format!(
r#"<w:styles {W}><w:style w:type="paragraph" w:styleId="Title"><w:name w:val="Title"/><w:rPr><w:sz w:val="56"/></w:rPr></w:style>
@@ -1105,13 +1567,7 @@ mod text_link_tests {
r#"<w:document {W}><w:body><w:p><w:pPr><w:pStyle w:val="Title"/></w:pPr><w:r><w:t>Head</w:t></w:r></w:p>
<w:p><w:pPr><w:pStyle w:val="Body"/></w:pPr>{body}</w:p></w:body></w:document>"#
);
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<Value> {
@@ -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);
+307 -18
View File
@@ -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<String> {
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<u8>, Vec<u8>) {
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", &params).unwrap()["asset"].as_u64().unwrap());
crate::cmd::native_links::wait(s);
id
}
fn asset_of(s: &Session, id: AssetId) -> Arc<designcraft_doc::Asset> {
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<String>) {
use std::io::Read;
let mut zip = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
let names: Vec<String> = 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::<Value>(&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()));
}
+7 -3
View File
@@ -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));
+26 -22
View File
@@ -1,8 +1,6 @@
//! Window › Interactive › Media: placed video and sound (shown as a poster or a placeholder,
//! exported as `<video>` / `<audio>` in EPUB).
use std::sync::Arc;
use designcraft_doc::{Asset, AssetId, Content, Graphic, Item, ItemId, MediaOptions, Shape};
use designcraft_geom::{Affine, Rect, shapes};
use serde_json::{Value, json};
@@ -10,8 +8,9 @@ use serde_json::{Value, json};
use super::{CommandSpec, bad, cmd, has_selection, ok, targets};
use crate::{Result, Session};
pub(crate) fn place_media(s: &mut Session, p: &Value, name: String, mime: &str, bytes: Vec<u8>, link: Option<String>) -> Result<Value> {
let video = mime.starts_with("video/");
/// Place a video or sound file: `asset` has its name, type and bytes.
pub(crate) fn place_media(s: &mut Session, p: &Value, asset: Asset) -> Result<Value> {
let video = asset.mime.starts_with("video/");
let (w, h) = (
p.get("width").and_then(Value::as_f64).unwrap_or(if video { 320.0 } else { 200.0 }),
p.get("height").and_then(Value::as_f64).unwrap_or(if video { 180.0 } else { 48.0 }),
@@ -26,10 +25,9 @@ pub(crate) fn place_media(s: &mut Session, p: &Value, name: String, mime: &str,
let spread = super::spread_param(p, "file.place")?;
let lid = s.doc()?.active_layer;
let (px, py) = (p.get("x").and_then(Value::as_f64), p.get("y").and_then(Value::as_f64));
let mime = mime.to_string();
s.edit(|d, sel| {
let fresh = AssetId(d.alloc());
let aid = d.add_asset(Asset { id: fresh, name, mime, link, data: Arc::new(bytes), ..Default::default() });
let aid = d.add_asset(Asset { id: fresh, ..asset });
let id = match target {
Some(fid) => {
let it = d.item_mut(fid).ok_or(designcraft_doc::DocError::NoItem(fid))?;
@@ -92,27 +90,31 @@ pub fn specs() -> Vec<CommandSpec> {
// A poster image is read before the edit.
let poster = match p.get("poster") {
Some(Value::Object(_)) => {
let (bytes, name, link) = super::file::read_source(&p["poster"])?;
let px = designcraft_render::image_size(&bytes).ok_or_else(|| bad("media.options", "the poster isn't a readable image"))?;
Some(Some((bytes, name, link, px)))
let source = super::file::read_source(&p["poster"])?;
let px =
designcraft_render::image_size(&source.bytes).ok_or_else(|| bad("media.options", "the poster isn't a readable image"))?;
let mut poster = Asset {
name: source.name.clone(),
mime: designcraft_render::image_mime(&source.bytes).to_string(),
pixels: Some(px),
..Default::default()
};
let pending = source.give(&mut poster, super::file::document_of(s).as_deref());
Some(Some((poster, pending)))
}
Some(Value::Null) => Some(None),
_ => None,
};
s.edit(|d, _| {
let (poster, pending) = match poster {
Some(Some((poster, pending))) => (Some(Some(poster)), pending),
Some(None) => (Some(None), None),
None => (None, None),
};
let r = s.edit(|d, _| {
let poster_id = match poster {
Some(Some((bytes, name, link, px))) => {
Some(Some(poster)) => {
let fresh = AssetId(d.alloc());
let mime = designcraft_render::image_mime(&bytes).to_string();
Some(Some(d.add_asset(Asset {
id: fresh,
name,
mime,
link,
data: Arc::new(bytes),
pixels: Some(px),
..Default::default()
})))
Some(Some(d.add_asset(Asset { id: fresh, ..poster })))
}
Some(None) => Some(None),
None => None,
@@ -139,7 +141,9 @@ pub fn specs() -> Vec<CommandSpec> {
return Err(bad("media.options", "select a video or sound"));
}
ok()
})
})?;
super::file::prepare_placed(s, pending);
Ok(r)
}
),
cmd!(query "media.get", "Media", [], None, "{id?} → {kind, name, playOnPageLoad, loop, controls, poster}", has_selection, |s, p| {
+905
View File
@@ -0,0 +1,905 @@
//! Linked assets in native documents ([`Storage::Linked`]): the paths a save or a recovery
//! entry records for them, which file an open finds each one in, the background check that a
//! file still holds the recorded bytes, and the move to links of documents saved while every
//! placed file was embedded.
//!
//! No original is read into memory on open, and none is written into a document or a recovery
//! entry; Save a Copy `{embedLinks: true}` is the one save that copies them in.
//!
//! A linked file is looked for at its absolute path, then at its path relative to the document
//! ([`crate::asset_io::candidates`]). A file with the recorded size and modification time holds
//! the bytes. One with the recorded size and another time is hashed on a background thread: the
//! first whose hash is the recorded one is the file, and its time is kept with the asset; when
//! none matches the link is Modified and the file's bytes are never used.
//!
//! Graphics placed from files link to them at once. The same thread makes their content hash
//! and proxy ([`prepare`]), and hashes linked files that an open found by size and time and that
//! have no hash yet. A save makes the proxies still missing ([`with_proxies`]), never a hash.
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Condvar, Mutex, PoisonError};
use designcraft_doc::{Asset, AssetData, AssetId, Document, Fingerprint, LinkedSource, SourceKey, Storage};
use serde_json::{Value, json};
use super::{CommandSpec, always, bad, cmd};
use crate::{DocState, Result, Session};
pub fn specs() -> Vec<CommandSpec> {
vec![cmd!(noundo "links.progress", "Link Checks", [], None,
"{} — apply what the background checks of opened documents' linked files found (the UI calls this while `checking`) → {checking: the active document's files are still being checked, remaining: how many of them, notice?: a message for the status line, given once}",
always, |s, _| {
s.poll_link_checks();
let Ok(st) = s.doc_mut() else { return Ok(json!({"checking": false, "remaining": 0})) };
let mut out = json!({"checking": st.links.checking(), "remaining": st.links.remaining()});
if let Some(notice) = st.links.take_notice() {
out["notice"] = Value::String(notice);
}
Ok(out)
})]
}
/// What the open of a document found for a linked file.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum LinkStatus {
/// A file holds the recorded bytes.
Ok,
/// The background check is looking for the file, and hashes one of the recorded size whose
/// time is new.
Checking,
/// Files are there, none with the recorded bytes.
Modified,
/// No file at either path, or one that may not be followed.
Missing,
}
impl LinkStatus {
/// The Links panel's word for it.
pub fn as_str(self) -> &'static str {
match self {
LinkStatus::Ok => "ok",
LinkStatus::Checking => "checking",
LinkStatus::Modified => "modified",
LinkStatus::Missing => "missing",
}
}
}
/// A document's linked files as its open found them ([`DocState::links`]), and the background
/// check still running for them. The check stops when the last copy of the document's state is
/// dropped (closed, reverted).
#[derive(Clone, Default)]
pub struct OpenLinks {
status: BTreeMap<AssetId, (SourceKey, LinkStatus)>,
job: Option<Arc<JobHandle>>,
/// Embedded images the check found identical to their linked files, so far.
migrated: usize,
notice: Option<String>,
}
impl std::fmt::Debug for OpenLinks {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("OpenLinks").field("status", &self.status.len()).field("checking", &self.checking()).finish()
}
}
impl OpenLinks {
/// What the open found for `asset`, while its bytes are the ones it looked at: a relink or
/// an update gives them a new key, and their status is the Links panel's own check then.
pub fn status(&self, asset: &Asset) -> Option<LinkStatus> {
self.status.get(&asset.id).filter(|(key, _)| *key == asset.data.key()).map(|(_, status)| *status)
}
/// Whether files are still being checked in the background.
pub fn checking(&self) -> bool {
self.job.is_some()
}
/// How many files the background check has still to look at, the one it is on included.
pub fn remaining(&self) -> usize {
self.job.as_ref().map_or(0, |handle| {
let state = lock(&handle.0);
state.work.len().saturating_add(usize::from(state.busy))
})
}
/// The status-line message about images that will be saved as links, once.
pub fn take_notice(&mut self) -> Option<String> {
self.notice.take()
}
}
/// One file check for the background thread.
#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
enum Work {
/// Find the file that holds `source`'s bytes: one at its absolute or relative path with the
/// recorded size and time (hashed when the record has no hash), else one of the recorded size
/// whose content hash is the recorded one.
Find { asset: AssetId, key: SourceKey, source: LinkedSource },
/// Compare the file at `source`'s path (the first of its candidates that has the size of the
/// embedded `bytes`) with the embedded bytes of a document saved before linked storage.
Migrate { asset: AssetId, key: SourceKey, bytes: Arc<Vec<u8>>, source: LinkedSource, page: u32 },
/// Hash the `bytes` of graphics just placed from a file, and make their proxy with `proxy`.
Prepare { key: SourceKey, bytes: Arc<Vec<u8>>, page: u32, proxy: bool },
}
/// What a [`Work`] found. `key` is the asset's bytes' key when the check started: a result for
/// bytes that were replaced since is dropped.
#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
enum Outcome {
/// The file at `path` holds the bytes; `fingerprint` is its size and time, when they can
/// vouch for the bytes later ([`super::links::settled`]), and `hash` the content hash of a
/// record that had none.
Holds { asset: AssetId, key: SourceKey, path: PathBuf, fingerprint: Option<Fingerprint>, hash: Option<String> },
/// Files are there; none holds the bytes.
Differs { asset: AssetId, key: SourceKey },
/// No file at either path, or one that may not be followed.
Absent { asset: AssetId, key: SourceKey },
/// The embedded bytes are the file's.
Confirmed {
asset: AssetId,
key: SourceKey,
path: PathBuf,
fingerprint: Fingerprint,
hash: String,
proxy: Option<designcraft_render::proxy::ProxyImage>,
},
/// The file isn't (or can't be shown to be) the embedded bytes: they stay embedded.
Unconfirmed,
/// The content hash and proxy of placed graphics' bytes ([`Work::Prepare`]).
Prepared { key: SourceKey, hash: String, proxy: Option<designcraft_render::proxy::ProxyImage> },
}
/// A graphic placed from a file whose content hash and proxy are still to be made
/// ([`super::links::give_placed`]); [`prepare`] has them made in the background.
#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
pub(crate) struct Pending {
key: SourceKey,
bytes: Arc<Vec<u8>>,
page: u32,
proxy: bool,
}
impl Pending {
/// The work for `a`, linked with `bytes` just read from its file. Video and sound get no proxy.
pub(super) fn of(a: &Asset, bytes: Arc<Vec<u8>>) -> Self {
Pending { key: a.data.key(), bytes, page: a.page, proxy: !media(a) }
}
}
/// Video and sound, which have no image proxy.
fn media(a: &Asset) -> bool {
a.mime.starts_with("video/") || a.mime.starts_with("audio/")
}
#[derive(Default)]
#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
struct Job {
cancel: AtomicBool,
state: Mutex<JobState>,
changed: Condvar,
}
#[derive(Default)]
#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
struct JobState {
work: Vec<Work>,
results: Vec<Outcome>,
done: bool,
/// A piece of work taken from `work` is being done.
busy: bool,
}
impl Job {
#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
fn cancelled(&self) -> bool {
self.cancel.load(Ordering::Relaxed)
}
}
/// The document state's hold on its [`Job`]: dropping the last one stops the job.
#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
struct JobHandle(Arc<Job>);
impl Drop for JobHandle {
fn drop(&mut self) {
self.0.cancel.store(true, Ordering::Relaxed);
}
}
/// What [`resolve`] found, for [`start`].
#[derive(Default)]
pub(crate) struct Opened {
status: BTreeMap<AssetId, (SourceKey, LinkStatus)>,
work: Vec<Work>,
}
/// Point each linked asset of `d`, opened from the file `document`, at its file, and queue the
/// look for the file that holds its bytes for the background check ([`start`]): nothing is read
/// or asked for its size here, so a share that doesn't answer can't stall the open. A file found
/// at the relative path becomes the link. With `migrate` (a document opened from its file,
/// neither from bytes nor recovered), embedded assets of a document saved before linked storage
/// are queued for a byte comparison with their linked files.
pub(crate) fn resolve(d: &mut Document, document: Option<&Path>, migrate: bool) -> Opened {
let mut opened = Opened::default();
let ids: Vec<AssetId> = d.assets.keys().copied().collect();
for id in ids {
let Some(asset) = d.assets.get_mut(&id) else { continue };
if asset.storage == Storage::Linked {
let Some(source) = LinkedSource::of(asset, document) else {
opened.status.insert(id, (asset.data.key(), LinkStatus::Missing));
continue;
};
let a = Arc::make_mut(asset);
a.data = a.data.with_source(source.clone());
let key = a.data.key();
// No files on the web: the link record is kept as it is.
let status = if cfg!(target_arch = "wasm32") {
LinkStatus::Missing
} else {
opened.work.push(Work::Find { asset: id, key, source });
LinkStatus::Checking
};
opened.status.insert(id, (key, status));
} else if migrate
&& let Some(document) = document
&& let Some(work) = migration(asset, document)
{
opened.work.push(work);
}
}
opened
}
/// `path` (a file found to hold `a`'s bytes) as `a`'s link, with its path relative to the
/// document and its bytes (under their key) read from there.
fn adopt_path(a: &mut Asset, path: &Path, document: Option<&Path>) {
let found = path.to_string_lossy().into_owned();
if a.link.as_deref() == Some(found.as_str()) {
return;
}
a.link = Some(found);
if let Some(relative) = document.and_then(|d| relative_to(d, path)) {
a.link_relative = Some(relative);
}
if let Some(source) = LinkedSource::of(a, document) {
a.data = AssetData::linked_under(a.data.key(), source);
}
}
/// `target` relative to the folder of the document file `document`, as link records store it.
pub(super) fn relative_to(document: &Path, target: &Path) -> Option<String> {
let document = std::path::absolute(document).ok()?;
let dir = document.parent()?;
let relative = super::datamerge::relative_between(dir, target);
// Stored with forward slashes, which every platform's resolver reads.
#[cfg(windows)]
let relative = relative.replace('\\', "/");
Some(relative)
}
/// An embedded asset of a document saved before linked storage: it has a link and no content
/// hash, which every link recorded since carries.
#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
fn legacy(a: &Asset) -> bool {
a.storage == Storage::Embedded && a.link.is_some() && a.link_hash.is_none()
}
/// The byte comparison that would let a [`legacy`] asset be saved as a link.
fn migration(a: &Asset, document: &Path) -> Option<Work> {
#[cfg(not(target_arch = "wasm32"))]
{
if !legacy(a) {
return None;
}
let bytes = Arc::clone(a.data.embedded_bytes()?);
if bytes.is_empty() {
return None;
}
let source = LinkedSource {
path: a.link.clone()?,
relative: a.link_relative.clone(),
document: Some(document.to_path_buf()),
len: bytes.len() as u64,
fingerprint: None,
hash: None,
};
Some(Work::Migrate { asset: a.id, key: a.data.key(), bytes, source, page: a.page })
}
#[cfg(target_arch = "wasm32")]
{
let _ = (a, document);
None
}
}
/// Keep what [`resolve`] found with the document's state and start the background check.
/// → how many files it checks.
pub(crate) fn start(st: &mut DocState, opened: Opened) -> usize {
st.links = OpenLinks { status: opened.status, ..Default::default() };
let n = opened.work.len();
if n == 0 {
return 0;
}
#[cfg(not(target_arch = "wasm32"))]
{
st.links.job = Some(spawn(opened.work.into_iter().rev().collect(), Vec::new()));
}
#[cfg(target_arch = "wasm32")]
let _ = opened.work;
n
}
/// A background job for `work` (taken from the end), its results starting with `results`.
#[cfg(not(target_arch = "wasm32"))]
fn spawn(work: Vec<Work>, results: Vec<Outcome>) -> Arc<JobHandle> {
let job = Arc::new(Job::default());
{
let mut state = lock(&job);
state.work = work;
state.results = results;
}
let roots = crate::file_access::current();
let worker = Arc::clone(&job);
let worker_roots = roots.clone();
let spawned = std::thread::Builder::new().name("designcraft-links".into()).spawn(move || run_all(&worker, worker_roots.as_ref()));
if let Err(e) = spawned {
// No thread: check here rather than leave the links unchecked.
log::warn!("checking linked files without a thread: {e}");
run_all(&job, roots.as_ref());
}
Arc::new(JobHandle(job))
}
/// Have the content hash and proxy of graphics just placed into `st`'s document made in the
/// background, in the order given; [`Session::poll_link_checks`] adds them when they are in.
pub(crate) fn prepare(st: &mut DocState, pending: Vec<Pending>) {
if pending.is_empty() {
return;
}
#[cfg(not(target_arch = "wasm32"))]
{
// Taken from the end: the first placed is made first, before checks still waiting.
let work: Vec<Work> =
pending.into_iter().rev().map(|Pending { key, bytes, page, proxy }| Work::Prepare { key, bytes, page, proxy }).collect();
let mut results = Vec::new();
if let Some(handle) = &st.links.job {
let mut state = lock(&handle.0);
if !state.done {
state.work.extend(work);
return;
}
// The job has ended: a new one takes over what it found and nobody has applied yet.
results = std::mem::take(&mut state.results);
}
st.links.job = Some(spawn(work, results));
}
#[cfg(target_arch = "wasm32")]
let _ = st;
}
fn lock(job: &Job) -> std::sync::MutexGuard<'_, JobState> {
job.state.lock().unwrap_or_else(PoisonError::into_inner)
}
#[cfg(not(target_arch = "wasm32"))]
fn run_all(job: &Job, roots: Option<&Arc<crate::file_access::AutomationRoots>>) {
crate::file_access::confine(roots, || {
while !job.cancelled() {
// Ended in the same step the queue is found empty: work queued later starts a new job.
let next = {
let mut state = lock(job);
let next = state.work.pop();
state.done |= next.is_none();
state.busy = next.is_some();
next
};
let Some(work) = next else { break };
// A file that trips a decoder (the proxy) leaves its asset as it was.
let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| check(work, &job.cancel)));
match outcome {
Ok(Some(outcome)) => lock(job).results.push(outcome),
Ok(None) => break,
Err(payload) => log::warn!("checking a linked file: {}", crate::guard::panic_message(payload.as_ref())),
}
job.changed.notify_all();
}
});
{
let mut state = lock(job);
state.done = true;
state.busy = false;
}
job.changed.notify_all();
}
/// Bytes read between two looks at the cancel flag.
#[cfg(not(target_arch = "wasm32"))]
const CHUNK: usize = 1 << 20;
/// Run one check → `None` when cancelled.
#[cfg(not(target_arch = "wasm32"))]
fn check(work: Work, cancel: &AtomicBool) -> Option<Outcome> {
match work {
Work::Find { asset, key, source } => {
let found: Vec<(PathBuf, Fingerprint)> =
crate::asset_io::candidates(&source).into_iter().filter_map(|p| fingerprint(&p).map(|f| (p, f))).collect();
if let Some((path, at)) = found.iter().find(|(_, f)| super::links::settled(f) && Some(*f) == source.fingerprint) {
// A record without a hash gets the file's, read while it keeps that size and time.
let hash = match source.hash {
Some(_) => None,
None => read_file(path, source.len, cancel, |_, _| true)?.filter(|_| fingerprint(path) == Some(*at)),
};
return Some(Outcome::Holds { asset, key, path: path.clone(), fingerprint: None, hash });
}
if found.is_empty() {
return Some(Outcome::Absent { asset, key });
}
let Some(hash) = &source.hash else { return Some(Outcome::Differs { asset, key }) };
for (path, before) in found.iter().filter(|(_, f)| f.size == source.len) {
match read_file(path, source.len, cancel, |_, _| true)? {
Some(found) if found == *hash && fingerprint(path) == Some(*before) => {
let fingerprint = super::links::settled(before).then_some(*before);
return Some(Outcome::Holds { asset, key, path: path.clone(), fingerprint, hash: None });
}
_ => {}
}
}
Some(Outcome::Differs { asset, key })
}
Work::Migrate { asset, key, bytes, source, page } => {
let len = bytes.len() as u64;
let Some((path, before)) =
crate::asset_io::candidates(&source).into_iter().find_map(|p| fingerprint(&p).filter(|f| f.size == len).map(|f| (p, f)))
else {
return Some(Outcome::Unconfirmed);
};
let same = |at: usize, chunk: &[u8]| at.checked_add(chunk.len()).and_then(|end| bytes.get(at..end)) == Some(chunk);
let read = read_file(&path, bytes.len() as u64, cancel, same)?;
// Changed while it was read: not the bytes it had.
if read.is_none() || fingerprint(&path) != Some(before) {
return Some(Outcome::Unconfirmed);
}
let hash = crate::asset_io::content_hash(&bytes);
let proxy = designcraft_render::proxy::make_proxy(&bytes, page);
// A time that can't vouch for the bytes (changed in the last seconds, or none) is
// kept as one no file has: saves then go by the hash, not by size and time.
let fingerprint = if super::links::settled(&before) { before } else { Fingerprint { size: len, mtime: super::links::UNVERIFIED_MTIME } };
Some(Outcome::Confirmed { asset, key, path, fingerprint, hash, proxy })
}
Work::Prepare { key, bytes, page, proxy } => {
let hash = hash_bytes(&bytes, cancel)?;
if cancel.load(Ordering::Relaxed) {
return None;
}
let proxy = if proxy { designcraft_render::proxy::make_proxy(&bytes, page) } else { None };
Some(Outcome::Prepared { key, hash, proxy })
}
}
}
/// [`crate::asset_io::content_hash`] of `bytes`, a chunk at a time → `None` when cancelled.
#[cfg(not(target_arch = "wasm32"))]
fn hash_bytes(bytes: &[u8], cancel: &AtomicBool) -> Option<String> {
use sha2::Digest;
let mut hasher = sha2::Sha256::new();
for chunk in bytes.chunks(CHUNK) {
if cancel.load(Ordering::Relaxed) {
return None;
}
hasher.update(chunk);
}
Some(hex(hasher))
}
/// `sha256:` and the hex digits of what `hasher` was given.
#[cfg(not(target_arch = "wasm32"))]
fn hex(hasher: sha2::Sha256) -> String {
use sha2::Digest;
use std::fmt::Write;
let mut hex = String::with_capacity(7 + 64);
hex.push_str("sha256:");
for b in hasher.finalize() {
let _ = write!(hex, "{b:02x}");
}
hex
}
#[cfg(not(target_arch = "wasm32"))]
fn fingerprint(path: &Path) -> Option<Fingerprint> {
crate::io::file_metadata(path).map(|m| crate::asset_io::fingerprint_from(&m))
}
/// Read the file at `path`, which must be `len` bytes, handing each chunk to `keep` (with its
/// offset) until it says no → the content hash of a file of `len` bytes that `keep` kept to the
/// end, `Some(None)` for any other file, `None` when cancelled.
#[cfg(not(target_arch = "wasm32"))]
fn read_file(path: &Path, len: u64, cancel: &AtomicBool, mut keep: impl FnMut(usize, &[u8]) -> bool) -> Option<Option<String>> {
use sha2::Digest;
use std::io::Read;
let Ok(file) = crate::io::open(path) else { return Some(None) };
// One byte past the size: a file that grew is seen without reading all of it.
let mut file = file.take(len.saturating_add(1));
let mut hasher = sha2::Sha256::new();
let mut buf = vec![0u8; CHUNK];
let mut at = 0usize;
loop {
if cancel.load(Ordering::Relaxed) {
return None;
}
let n = match file.read(&mut buf) {
Ok(0) => break,
Ok(n) => n,
Err(e) if e.kind() == std::io::ErrorKind::Interrupted => continue,
Err(_) => return Some(None),
};
let Some(chunk) = buf.get(..n) else { return Some(None) };
if !keep(at, chunk) {
return Some(None);
}
hasher.update(chunk);
at = at.saturating_add(n);
}
if at as u64 != len {
return Some(None);
}
Some(Some(hex(hasher)))
}
impl Session {
/// Apply what the background checks of the open documents' linked files found → whether a
/// document changed. Nothing found changes what a document shows or makes it unsaved: a
/// file's new time, the link to the file that was found, an embedded image that will be
/// saved as a link. Results wait while a gesture or a data-merge preview runs.
pub fn poll_link_checks(&mut self) -> bool {
let mut changed = false;
for st in &mut self.docs {
changed |= apply(st);
}
if changed {
designcraft_doc::asset_data::links_changed();
}
changed
}
}
fn apply(st: &mut DocState) -> bool {
let Some(job) = st.links.job.clone() else { return false };
if st.interaction.is_some() || st.preview_stash.is_some() {
return false;
}
let (results, done) = {
let mut state = lock(&job.0);
(std::mem::take(&mut state.results), state.done)
};
if done {
st.links.job = None;
}
let document = st.path.as_deref().map(PathBuf::from);
let clean = !st.is_dirty();
let found = !results.is_empty();
let mut changed = false;
for outcome in results {
changed |= apply_one(st, outcome, document.as_deref());
}
if changed && clean {
st.saved_doc = Arc::clone(&st.doc);
}
if done && st.links.migrated > 0 {
st.links.notice = Some(notice(st.links.migrated));
}
// A status changed, or the check ended: either way something to tell.
found || done
}
/// The asset `id` of the live document to change, while its bytes are still `key`'s.
fn current(st: &mut DocState, id: AssetId, key: SourceKey) -> Option<&mut Asset> {
if st.doc.assets.get(&id).is_none_or(|a| a.data.key() != key) {
return None;
}
Arc::make_mut(&mut st.doc).assets.get_mut(&id).map(Arc::make_mut)
}
fn apply_one(st: &mut DocState, outcome: Outcome, document: Option<&Path>) -> bool {
match outcome {
Outcome::Holds { asset, key, path, fingerprint, hash } => {
let held = held(st, asset, key, &path, fingerprint, document);
let hashed = hash.is_some_and(|hash| add_everywhere(st, key, &hash, None));
held || hashed
}
Outcome::Differs { asset, key } => {
found(st, asset, key, LinkStatus::Modified);
false
}
Outcome::Absent { asset, key } => {
found(st, asset, key, LinkStatus::Missing);
false
}
Outcome::Confirmed { asset, key, path, fingerprint, hash, proxy } => {
let Some(a) = current(st, asset, key) else { return false };
if a.storage != Storage::Embedded {
return false;
}
a.link = Some(path.to_string_lossy().into_owned());
if let Some(relative) = document.and_then(|d| relative_to(d, &path)) {
a.link_relative = Some(relative);
}
a.link_fingerprint = Some(fingerprint);
a.link_hash = Some(hash);
a.proxy = proxy.map(doc_proxy);
a.storage = Storage::Linked;
st.links.status.insert(asset, (key, LinkStatus::Ok));
st.links.migrated = st.links.migrated.saturating_add(1);
true
}
Outcome::Unconfirmed => false,
Outcome::Prepared { key, hash, proxy } => add_everywhere(st, key, &hash, proxy.map(doc_proxy).as_ref()),
}
}
/// Keep `status` for asset `id`, while its bytes are still `key`'s.
fn found(st: &mut DocState, id: AssetId, key: SourceKey, status: LinkStatus) {
if st.doc.assets.get(&id).is_some_and(|a| a.data.key() == key) {
st.links.status.insert(id, (key, status));
}
}
/// A proxy the background job made, as a document keeps it.
fn doc_proxy(p: designcraft_render::proxy::ProxyImage) -> designcraft_doc::Proxy {
designcraft_doc::Proxy { mime: p.mime.into(), pixels: p.pixels, data: AssetData::embedded(p.data) }
}
/// The file at `path` holds asset `id`'s bytes (still `key`'s): its link, with `fingerprint`
/// when the file's time can vouch for them. → whether the document changed.
fn held(st: &mut DocState, id: AssetId, key: SourceKey, path: &Path, fingerprint: Option<Fingerprint>, document: Option<&Path>) -> bool {
let unchanged = fingerprint.is_none()
&& st.doc.assets.get(&id).is_some_and(|a| a.data.key() == key && a.link.as_deref() == Some(path.to_string_lossy().as_ref()));
if unchanged {
// The file at the recorded path, with the recorded size and time: nothing to change.
st.links.status.insert(id, (key, LinkStatus::Ok));
return false;
}
let Some(a) = current(st, id, key) else { return false };
if let Some(f) = fingerprint {
a.link_fingerprint = Some(f);
}
adopt_path(a, path, document);
// The file holds the same bytes: the key stays, also for a record with no hash.
if let Some(source) = LinkedSource::of(a, document) {
a.data = AssetData::linked_under(key, source);
}
st.links.status.insert(id, (key, LinkStatus::Ok));
true
}
/// Add the content `hash` and `proxy` of the bytes `key` to the graphics that have those bytes
/// and lack them ([`super::links::add_prepared`]), in the live document, the undo history and the
/// last saved state alike: a redo of an undone placement, or an undo to before an open-time
/// check, then has them too. → whether the live document changed.
fn add_everywhere(st: &mut DocState, key: SourceKey, hash: &str, proxy: Option<&designcraft_doc::Proxy>) -> bool {
// Each document changed once, its holders sharing the result: a history entry that was the
// saved state still is.
let mut done: Vec<(Arc<Document>, Arc<Document>)> = Vec::new();
let mut add = |doc: &mut Arc<Document>| {
if let Some((_, after)) = done.iter().find(|(before, _)| Arc::ptr_eq(before, doc)) {
*doc = Arc::clone(after);
return true;
}
let before = Arc::clone(doc);
let changed = add_to(doc, key, hash, proxy);
if changed {
done.push((before, Arc::clone(doc)));
}
changed
};
let changed = add(&mut st.doc);
for entry in st.history.undo.iter_mut().chain(st.history.redo.iter_mut()) {
add(&mut entry.doc);
}
add(&mut st.saved_doc);
changed
}
/// [`add_everywhere`] for one version of the document → whether `doc` changed.
fn add_to(doc: &mut Arc<Document>, key: SourceKey, hash: &str, proxy: Option<&designcraft_doc::Proxy>) -> bool {
let wants = |a: &Asset| a.data.key() == key && (a.link_hash.is_none() || (proxy.is_some() && a.storage == Storage::Linked && a.proxy.is_none()));
let ids: Vec<AssetId> = doc.assets.values().filter(|a| wants(a)).map(|a| a.id).collect();
if ids.is_empty() {
return false;
}
let d = Arc::make_mut(doc);
for id in ids {
if let Some(a) = d.assets.get_mut(&id).map(Arc::make_mut) {
super::links::add_prepared(a, hash, proxy);
}
}
true
}
/// The status line's message once `n` embedded images were found identical to their files.
fn notice(n: usize) -> String {
if n == 1 {
"1 image will be saved as a link to its file (Links ▸ Embed keeps a copy)".into()
} else {
format!("{n} images will be saved as links to their files (Links ▸ Embed keeps a copy)")
}
}
/// `d` as saved to the file `destination`, when that changes it (else `None`; the live document
/// isn't touched). `from` is the file `d` was opened from or last saved to, which relative links
/// are resolved against: each link becomes the absolute path it names, with its path relative to
/// the destination's folder. An embedded image to be saved as a link (a document saved before
/// linked storage, [`resolve`]) whose file has changed since the check is embedded in this save
/// after all.
pub(crate) fn for_destination(d: &Document, from: Option<&Path>, destination: &Path) -> Option<Document> {
rewrite(d, from, destination, false)
}
/// [`for_destination`] for a recovery snapshot of `d`, whose file is `document`. Embedded images
/// to be saved as links stay as the document's file has them (embedded, to be compared with their
/// files again), so a recovered document never depends on a file the user hasn't saved a link to.
pub(crate) fn for_recovery(d: &Document, document: &Path) -> Option<Document> {
rewrite(d, Some(document), document, true)
}
fn rewrite(d: &Document, from: Option<&Path>, destination: &Path, recovery: bool) -> Option<Document> {
let mut changes: Vec<(AssetId, Option<String>, Option<String>, bool)> = Vec::new();
for a in d.assets.values() {
let Some(link) = a.link.as_deref() else { continue };
let absolute = crate::io::document_path(link, from).ok();
let new_link = absolute.as_ref().map(|p| p.to_string_lossy().into_owned()).filter(|p| p != link);
let relative = absolute.as_deref().and_then(|p| relative_to(destination, p)).filter(|r| a.link_relative.as_ref() != Some(r));
let embed = a.storage == Storage::Linked && !a.data.is_linked() && (recovery || !still_there(a, from));
if new_link.is_some() || relative.is_some() || embed {
changes.push((a.id, new_link, relative, embed));
}
}
if changes.is_empty() {
return None;
}
let mut saved = d.clone();
for (id, link, relative, embed) in changes {
let Some(a) = saved.assets.get_mut(&id).map(Arc::make_mut) else { continue };
if let Some(link) = link {
a.link = Some(link);
}
if let Some(relative) = relative {
a.link_relative = Some(relative);
}
if embed {
a.storage = Storage::Embedded;
if recovery {
// As the document's file has it: the next open from that file compares it again.
a.link_hash = None;
a.proxy = None;
}
}
}
Some(saved)
}
/// Whether a file still has the size and time `a`'s link recorded when its bytes were found in it
/// (a time that can vouch for them, [`super::links::settled`]).
fn still_there(a: &Asset, document: Option<&Path>) -> bool {
#[cfg(not(target_arch = "wasm32"))]
{
let Some(source) = LinkedSource::of(a, document) else { return false };
crate::asset_io::candidates(&source)
.iter()
.any(|p| fingerprint(p).is_some_and(|f| super::links::settled(&f) && Some(f) == source.fingerprint))
}
#[cfg(target_arch = "wasm32")]
{
let _ = (a, document);
false
}
}
/// After `d` was saved to `destination`: linked assets read their files relative to it, and
/// embedded images saved as links let go of their bytes (read from the file when next needed;
/// what was decoded of them stays). → the document with that, when it changes anything.
pub(crate) fn after_save(d: &Document, destination: &Path) -> Option<Document> {
let relinked: Vec<(AssetId, AssetData)> = d
.assets
.values()
.filter(|a| a.storage == Storage::Linked && (cfg!(not(target_arch = "wasm32")) || a.data.is_linked()))
.filter_map(|a| {
let source = LinkedSource::of(a, Some(destination))?;
if a.data.linked_source() == Some(&source) {
return None;
}
// The record names the same bytes, now resolved against the destination: the key
// stays, also for a link with no hash yet. Embedded bytes are linked only once their
// hash was found in the file (`Confirmed`).
Some((a.id, AssetData::linked_under(a.data.key(), source)))
})
.collect();
if relinked.is_empty() {
return None;
}
let mut out = d.clone();
for (id, data) in relinked {
if let Some(a) = out.assets.get_mut(&id) {
Arc::make_mut(a).data = data;
}
}
Some(out)
}
/// `d` as a save writes it, when that changes it: each linked graphic without a proxy (placed
/// moments ago, its proxy still being made in the background) gets one from its bytes, so a saved
/// link always has a preview to draw while its file can't be read. Nothing is hashed: a link
/// without a hash is saved without one. A graphic whose bytes can't be read or don't decode stays
/// without a proxy. `None` when no graphic needs one, or once `cancelled` says so.
pub(crate) fn with_proxies(d: &Document, cancelled: impl Fn() -> bool) -> Option<Document> {
let wanting: Vec<AssetId> = d.assets.values().filter(|a| a.storage == Storage::Linked && a.proxy.is_none() && !media(a)).map(|a| a.id).collect();
if wanting.is_empty() {
return None;
}
let mut out = d.clone();
let mut changed = false;
for id in wanting {
if cancelled() {
return None;
}
let Some(asset) = out.assets.get_mut(&id) else { continue };
let Ok(bytes) = asset.data.load() else { continue };
// A file that trips a decoder leaves its graphic without a proxy, not the save undone.
let made = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| super::links::proxy_of(asset, &bytes)));
match made {
Ok(Some(proxy)) => {
Arc::make_mut(asset).proxy = Some(proxy);
changed = true;
}
Ok(None) => {}
Err(payload) => log::warn!("making the proxy of {}: {}", asset.name, crate::guard::panic_message(payload.as_ref())),
}
}
changed.then_some(out)
}
/// `d` with every linked file it uses copied in (Save a Copy `{embedLinks: true}`): a document
/// that opens anywhere. Fails, naming the image, when a file is missing or has changed.
pub(crate) fn embed_linked(d: &mut Document, command: &str) -> Result<()> {
for id in d.used_assets() {
let Some(asset) = d.assets.get_mut(&id) else { continue };
if asset.storage != Storage::Linked {
continue;
}
let bytes =
asset.data.load().map_err(|e| bad(command, format!("{}: {e}; relink or update it to save a copy with its linked files", asset.name)))?;
let a = Arc::make_mut(asset);
a.data = AssetData::embedded(bytes);
a.storage = Storage::Embedded;
a.proxy = None;
}
Ok(())
}
/// On the web, a save keeps linked files as links only: it can't read them to embed them.
pub(crate) fn web_save_warnings(d: &Document) -> Vec<String> {
let n = d.assets.values().filter(|a| a.storage == Storage::Linked).count();
if cfg!(target_arch = "wasm32") && n > 0 {
vec![format!("{n} linked files are saved as links only: the web version can't read them to embed them")]
} else {
Vec::new()
}
}
/// Wait until the background checks of `s`'s documents are done, then apply them.
#[cfg(test)]
pub(crate) fn wait(s: &mut Session) {
for st in &s.docs {
let Some(job) = st.links.job.clone() else { continue };
let mut state = lock(&job.0);
while !state.done {
state = job.0.changed.wait_timeout(state, std::time::Duration::from_secs(10)).unwrap_or_else(PoisonError::into_inner).0;
}
}
s.poll_link_checks();
}
#[cfg(test)]
mod tests;
+387
View File
@@ -0,0 +1,387 @@
#![cfg(not(target_arch = "wasm32"))]
use std::path::{Path, PathBuf};
use std::sync::Arc;
use designcraft_doc::{Asset, AssetData, AssetId, LinkedSource, Storage, Unavailable};
use serde_json::json;
use super::{LinkStatus, wait};
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-native-links-{name}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(dir.join("links")).unwrap();
Dir(dir)
}
}
impl Drop for Dir {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
fn png(red: u8) -> Vec<u8> {
designcraft_render::Rendered { width: 40, height: 20, pixels: [red, 90, 180, 255].repeat(800) }.to_png()
}
/// Place `bytes` in the active document (embedded, from base64) → its asset.
fn place(s: &mut Session, bytes: &[u8]) -> AssetId {
let before: Vec<AssetId> = s.doc().unwrap().doc.assets.keys().copied().collect();
s.execute("file.place", &json!({"base64": crate::cmd::base64_encode(bytes), "name": "art.png", "x": 0, "y": 0})).unwrap();
*s.doc().unwrap().doc.assets.keys().find(|id| !before.contains(id)).unwrap()
}
/// Make asset `id` a link to `file`, as Place from a file records one: linked storage when
/// `linked`, else embedded with its link, as documents saved before linked storage have it.
fn link_to(s: &mut Session, id: AssetId, file: &Path, linked: bool) {
let bytes = std::fs::read(file).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()));
if linked {
a.link_hash = Some(content_hash(&bytes));
a.storage = Storage::Linked;
a.data = AssetData::linked(LinkedSource::of(a, None).unwrap());
}
}
/// A saved document at `dir/doc.designcraft` linking to `dir/links/art.png` → its asset.
fn saved_linked(dir: &Dir) -> (PathBuf, AssetId) {
let image = dir.0.join("links/art.png");
std::fs::write(&image, png(30)).unwrap();
age(&image, 100);
let mut s = Session::new();
s.execute("file.new", &json!({})).unwrap();
let id = place(&mut s, &png(30));
link_to(&mut s, id, &image, true);
let doc = dir.0.join("doc.designcraft");
s.execute("file.save", &json!({"path": doc.to_string_lossy()})).unwrap();
(doc, id)
}
/// Open the file at `path`, with its background check of linked files still to come.
fn opened(path: &Path) -> Session {
let mut s = Session::new();
s.execute("file.open", &json!({"path": path.to_string_lossy()})).unwrap();
s
}
/// Open the file at `path` and wait for its background check of linked files.
fn open(path: &Path) -> Session {
let mut s = opened(path);
wait(&mut s);
s
}
fn asset(s: &Session, id: AssetId) -> Arc<Asset> {
Arc::clone(&s.doc().unwrap().doc.assets[&id])
}
fn status(s: &Session, id: AssetId) -> Option<LinkStatus> {
s.doc().unwrap().links.status(&asset(s, id))
}
/// The names of the entries in the package at `path` that hold placed files.
fn stored_assets(path: &Path) -> Vec<String> {
let zip = zip::ZipArchive::new(std::fs::File::open(path).unwrap()).unwrap();
zip.file_names().filter(|n| n.starts_with("assets/")).map(str::to_string).collect()
}
/// 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();
}
/// The bytes of `path` with one byte changed: the same size, other bytes.
fn flip_a_byte(path: &Path) {
let mut bytes = std::fs::read(path).unwrap();
let mid = bytes.len() / 2;
bytes[mid] ^= 0xff;
std::fs::write(path, bytes).unwrap();
}
#[test]
fn a_linked_save_writes_no_original_and_records_the_relative_path() {
let dir = Dir::new("save");
let (doc, id) = saved_linked(&dir);
assert!(stored_assets(&doc).is_empty(), "{:?}", stored_assets(&doc));
let s = open(&doc);
let a = asset(&s, id);
assert_eq!((a.storage, a.link_relative.as_deref()), (Storage::Linked, Some("links/art.png")));
assert!(a.data.is_linked() && a.data.resident().is_none(), "nothing is read on open, nor by its check");
assert_eq!(status(&s, id), Some(LinkStatus::Ok), "the recorded size and time: no check needed");
assert!(!s.doc().unwrap().links.checking());
assert_eq!(a.data.load().unwrap().as_slice(), png(30));
}
#[test]
fn a_moved_folder_finds_its_files_by_relative_path() {
let dir = Dir::new("moved");
let (_, id) = saved_linked(&dir);
let moved = Dir(dir.0.with_file_name(format!("{}-moved", dir.0.file_name().unwrap().to_string_lossy())));
let _ = std::fs::remove_dir_all(&moved.0);
std::fs::rename(&dir.0, &moved.0).unwrap();
let s = open(&moved.0.join("doc.designcraft"));
let a = asset(&s, id);
assert_eq!(status(&s, id), Some(LinkStatus::Ok));
assert_eq!(a.link.as_deref(), Some(moved.0.join("links/art.png").to_string_lossy().as_ref()), "the file found is the link now");
assert!(!s.doc().unwrap().is_dirty());
assert_eq!(a.data.load().unwrap().as_slice(), png(30));
}
#[test]
fn the_absolute_file_wins_and_otherwise_the_one_with_the_bytes() {
let dir = Dir::new("both");
let (_, id) = saved_linked(&dir);
// A copy of the folder: both paths hold the bytes, the copy under a new time.
let copy = Dir::new("both-copy");
std::fs::copy(dir.0.join("doc.designcraft"), copy.0.join("doc.designcraft")).unwrap();
std::fs::copy(dir.0.join("links/art.png"), copy.0.join("links/art.png")).unwrap();
age(&copy.0.join("links/art.png"), 50);
let s = open(&copy.0.join("doc.designcraft"));
assert_eq!(status(&s, id), Some(LinkStatus::Ok));
assert_eq!(asset(&s, id).link.as_deref(), Some(dir.0.join("links/art.png").to_string_lossy().as_ref()), "the absolute path is tried first");
// The original changes (same size): the copy holds the bytes, found by its hash.
flip_a_byte(&dir.0.join("links/art.png"));
age(&dir.0.join("links/art.png"), 10);
let mut s = opened(&copy.0.join("doc.designcraft"));
assert_eq!(status(&s, id), Some(LinkStatus::Checking));
wait(&mut s);
let a = asset(&s, id);
assert_eq!(status(&s, id), Some(LinkStatus::Ok));
assert_eq!(a.link.as_deref(), Some(copy.0.join("links/art.png").to_string_lossy().as_ref()));
assert_eq!(a.link_fingerprint, Some(fingerprint_from(&std::fs::metadata(copy.0.join("links/art.png")).unwrap())));
assert_eq!(a.data.load().unwrap().as_slice(), png(30));
}
#[test]
fn a_touched_file_with_the_same_bytes_is_ok_and_keeps_its_new_time() {
let dir = Dir::new("touched");
let (doc, id) = saved_linked(&dir);
let image = dir.0.join("links/art.png");
age(&image, 1000);
let mut s = opened(&doc);
let key = asset(&s, id).data.key();
assert_eq!(status(&s, id), Some(LinkStatus::Checking));
wait(&mut s);
let a = asset(&s, id);
assert_eq!(status(&s, id), Some(LinkStatus::Ok));
assert_eq!(a.link_fingerprint, Some(fingerprint_from(&std::fs::metadata(&image).unwrap())), "the new time is kept");
assert_eq!(a.data.key(), key, "the same bytes keep their key");
assert!(!s.doc().unwrap().is_dirty(), "a new time is no change to save");
assert!(!s.doc().unwrap().links.checking());
}
#[test]
fn changed_bytes_are_modified_and_never_adopted() {
let dir = Dir::new("changed");
let (doc, id) = saved_linked(&dir);
let image = dir.0.join("links/art.png");
let recorded = asset(&open(&doc), id).link_hash.clone();
flip_a_byte(&image);
age(&image, 1000);
let mut s = open(&doc);
wait(&mut s);
let a = asset(&s, id);
assert_eq!(status(&s, id), Some(LinkStatus::Modified));
assert_eq!(a.link_hash, recorded);
assert_eq!(a.data.load().err(), Some(Unavailable::Modified));
// Another size: modified without reading it.
std::fs::write(&image, b"short").unwrap();
assert_eq!(status(&open(&doc), id), Some(LinkStatus::Modified));
std::fs::remove_file(&image).unwrap();
assert_eq!(status(&open(&doc), id), Some(LinkStatus::Missing));
}
#[test]
fn migration_links_confirmed_images_and_drops_the_copy_only_after_confirmation() {
let dir = Dir::new("migrate");
let (same, changed) = (dir.0.join("links/same.png"), dir.0.join("links/changed.png"));
std::fs::write(&same, png(30)).unwrap();
std::fs::write(&changed, png(31)).unwrap();
age(&same, 100);
let mut s = Session::new();
s.execute("file.new", &json!({})).unwrap();
let (a, b) = (place(&mut s, &png(30)), place(&mut s, &png(31)));
link_to(&mut s, a, &same, false);
link_to(&mut s, b, &changed, false);
let doc = dir.0.join("doc.designcraft");
s.execute("file.save", &json!({"path": doc.to_string_lossy()})).unwrap();
assert_eq!(stored_assets(&doc).len(), 2, "a document as saved before linked storage");
// One file changes since (same size, other bytes).
flip_a_byte(&changed);
let mut s = opened(&doc);
assert!(asset(&s, a).data.embedded_bytes().is_some() && asset(&s, a).storage == Storage::Embedded, "nothing changes before the comparison");
wait(&mut s);
let (left, kept) = (asset(&s, a), asset(&s, b));
assert_eq!(left.storage, Storage::Linked);
assert_eq!(left.link_hash.as_deref(), Some(content_hash(&png(30)).as_str()));
assert!(left.proxy.is_some(), "a proxy for when the file can't be read");
assert!(left.data.embedded_bytes().is_some(), "the bytes stay until the save");
assert_eq!((kept.storage, kept.link_hash.as_deref(), kept.data.embedded_bytes().is_some()), (Storage::Embedded, None, true));
assert!(!s.doc().unwrap().is_dirty());
let r = s.execute("links.progress", &json!({})).unwrap();
assert_eq!(r, json!({"checking": false, "remaining": 0, "notice": "1 image will be saved as a link to its file (Links ▸ Embed keeps a copy)"}));
assert_eq!(s.execute("links.progress", &json!({})).unwrap(), json!({"checking": false, "remaining": 0}), "told once");
let key = left.data.key();
s.execute("file.save", &json!({})).unwrap();
assert_eq!(stored_assets(&doc), [format!("assets/{}.png", b.0)], "only the changed file's image stays in the document");
let saved = asset(&s, a);
assert!(saved.data.is_linked() && saved.data.key() == key, "linked now, under the key its decodes are cached by");
assert_eq!(saved.data.load().unwrap().as_slice(), png(30));
// Reopened: a linked image, and the changed one is compared again.
let mut s = open(&doc);
wait(&mut s);
assert_eq!((asset(&s, a).storage, status(&s, a)), (Storage::Linked, Some(LinkStatus::Ok)));
assert_eq!(asset(&s, b).storage, Storage::Embedded);
}
#[test]
fn byte_opened_and_recovered_documents_are_not_migrated_and_recovery_holds_no_originals() {
let dir = Dir::new("recovery");
let image = dir.0.join("links/art.png");
std::fs::write(&image, png(30)).unwrap();
let mut s = Session::new();
s.execute("file.new", &json!({})).unwrap();
let legacy = place(&mut s, &png(30));
link_to(&mut s, legacy, &image, false);
let bytes = s.execute("file.serialize", &json!({})).unwrap();
let mut t = Session::new();
let r = t.execute("file.openBytes", &json!({"name": "doc.designcraft", "base64": bytes["base64"]})).unwrap();
assert_eq!(r["linkChecks"], 0, "{r}");
let (doc, id) = saved_linked(&dir);
let mut s = open(&doc);
s.execute("frame.create", &json!({"rect": [36, 36, 300, 200]})).unwrap();
let recovery = dir.0.join("recovery");
s.execute("file.recovery.save", &json!({"dir": recovery.to_string_lossy()})).unwrap();
let entry = recovery.join(format!("{}.designcraft", s.doc().unwrap().uid));
assert!(entry.exists());
assert!(stored_assets(&entry).is_empty(), "{:?}", stored_assets(&entry));
drop(s);
let mut r = Session::new();
r.execute("file.recovery.open", &json!({"dir": recovery.to_string_lossy()})).unwrap();
wait(&mut r);
let a = asset(&r, id);
assert_eq!((a.storage, a.link_relative.as_deref()), (Storage::Linked, Some("links/art.png")));
assert_eq!(a.data.linked_source().and_then(|s| s.document.clone()), Some(doc.clone()), "resolved against the document's file");
assert_eq!(status(&r, id), Some(LinkStatus::Ok));
assert_eq!(a.data.load().unwrap().as_slice(), png(30));
}
#[test]
fn save_a_copy_with_embedded_links_is_portable() {
let dir = Dir::new("portable");
let (doc, id) = saved_linked(&dir);
let mut s = open(&doc);
let copy = dir.0.join("copy.designcraft");
s.execute("file.saveACopy", &json!({"path": copy.to_string_lossy(), "embedLinks": true})).unwrap();
assert_eq!(stored_assets(&copy), [format!("assets/{}.png", id.0)]);
assert!(asset(&s, id).data.is_linked(), "the document itself stays linked");
std::fs::remove_file(dir.0.join("links/art.png")).unwrap();
let t = open(&copy);
let a = asset(&t, id);
assert_eq!((a.storage, a.data.embedded_bytes().map(|b| b.to_vec())), (Storage::Embedded, Some(png(30))));
// A missing file (its bytes no longer kept in memory): no portable copy, and a plain one
// still saves.
asset(&s, id).data.evict();
let e = s.execute("file.saveACopy", &json!({"path": copy.to_string_lossy(), "embedLinks": true})).unwrap_err();
assert!(e.to_string().contains("art.png") && e.to_string().contains("missing"), "{e}");
s.execute("file.saveACopy", &json!({"path": copy.to_string_lossy()})).unwrap();
assert!(stored_assets(&copy).is_empty());
assert!(s.execute("file.saveACopy", &json!({"path": copy.to_string_lossy(), "embedLinks": 1})).is_err());
}
#[test]
fn the_open_looks_for_files_in_the_background() {
let dir = Dir::new("background");
let (doc, id) = saved_linked(&dir);
let mut s = opened(&doc);
assert_eq!(status(&s, id), Some(LinkStatus::Checking), "nothing is asked of the file system on open");
assert!(s.doc().unwrap().links.checking());
wait(&mut s);
assert_eq!(status(&s, id), Some(LinkStatus::Ok));
assert!(!s.doc().unwrap().is_dirty());
}
/// The open's statuses don't outlive a change to the file: Update reads a file edited since,
/// and a file missing at the open counts once it is back.
#[test]
fn a_file_changed_or_restored_after_the_open_is_seen() {
let dir = Dir::new("after-open");
let (doc, id) = saved_linked(&dir);
let image = dir.0.join("links/art.png");
let mut s = open(&doc);
assert_eq!(status(&s, id), Some(LinkStatus::Ok));
std::fs::write(&image, png(77)).unwrap();
age(&image, 10);
let r = s.execute("links.update", &json!({"asset": id.0})).unwrap();
assert_eq!(r["updated"], 1, "{r}");
assert_eq!(asset(&s, id).data.load().unwrap().as_slice(), png(77));
let restored = Dir::new("restored");
let (doc, id) = saved_linked(&restored);
let image = restored.0.join("links/art.png");
let original = std::fs::read(&image).unwrap();
std::fs::remove_file(&image).unwrap();
let mut s = open(&doc);
assert_eq!(status(&s, id), Some(LinkStatus::Missing));
std::fs::write(&image, &original).unwrap();
age(&image, 10);
let rows = s.execute("links.list", &json!({})).unwrap();
let row = rows.as_array().unwrap().iter().find(|r| r["asset"] == id.0).cloned().unwrap();
assert_eq!(row["status"], "ok", "{row}");
}
#[test]
fn preflight_reads_no_linked_original() {
let dir = Dir::new("preflight");
let (doc, id) = saved_linked(&dir);
let mut s = open(&doc);
let issues = s.execute("preflight.run", &json!({})).unwrap();
assert!(!issues.to_string().contains("modifiedLink"), "{issues}");
assert!(asset(&s, id).data.resident().is_none(), "the original isn't read");
flip_a_byte(&dir.0.join("links/art.png"));
age(&dir.0.join("links/art.png"), 10);
let issues = s.execute("preflight.run", &json!({})).unwrap();
assert!(issues.to_string().contains("modifiedLink"), "{issues}");
}
#[test]
fn recovery_keeps_images_not_yet_saved_as_links() {
let dir = Dir::new("recover-migrated");
let image = dir.0.join("links/art.png");
std::fs::write(&image, png(30)).unwrap();
age(&image, 100);
let mut s = Session::new();
s.execute("file.new", &json!({})).unwrap();
let id = place(&mut s, &png(30));
link_to(&mut s, id, &image, false);
let doc = dir.0.join("doc.designcraft");
s.execute("file.save", &json!({"path": doc.to_string_lossy()})).unwrap();
let mut s = open(&doc);
assert_eq!(asset(&s, id).storage, Storage::Linked, "found identical to its file, to be saved as a link");
s.execute("frame.create", &json!({"rect": [36, 36, 300, 200]})).unwrap();
let recovery = dir.0.join("recovery");
s.execute("file.recovery.save", &json!({"dir": recovery.to_string_lossy()})).unwrap();
let entry = recovery.join(format!("{}.designcraft", s.doc().unwrap().uid));
assert_eq!(stored_assets(&entry), [format!("assets/{}.png", id.0)], "the bytes stay in the snapshot");
drop(s);
let mut r = Session::new();
r.execute("file.recovery.open", &json!({"dir": recovery.to_string_lossy()})).unwrap();
wait(&mut r);
let a = asset(&r, id);
assert_eq!((a.storage, a.data.embedded_bytes().map(|b| b.to_vec())), (Storage::Embedded, Some(png(30))));
}
File diff suppressed because it is too large. Load diff
+43 -13
View File
@@ -11,7 +11,7 @@ use std::io::Write;
use super::{CommandSpec, bad, cmd, has_doc, str_param};
use crate::{EngineError, Result, Session};
use designcraft_compose::ComposedStory;
use designcraft_doc::{AssetId, Document};
use designcraft_doc::{AssetId, Document, Fingerprint, LinkedSource, Storage};
use designcraft_fonts::{FaceRef, FontFace, FontSource};
use serde_json::{Value, json};
@@ -230,7 +230,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Package…",
["File"],
None,
"{dir: folder to create, idml?: true, pdf?: false|true|{…options of file.exportPdf}, instructions?: text} — the document (its placed files relinked to Links/), Links/, the font files that draw its text in Document Fonts/ (fallback fonts included; unless their licence restricts it), an IDML copy (linking the files in Links/, nothing embedded), an optional PDF and a report → {dir, files, report, warnings: PDF export warnings}",
"{dir: folder to create, idml?: true, pdf?: false|true|{…options of file.exportPdf}, instructions?: text} — the document (its placed files relinked to Links/), Links/, the font files that draw its text in Document Fonts/ (fallback fonts included; unless their licence restricts it), an IDML copy (linking the files in Links/, nothing embedded), an optional PDF and a report → {dir, files, report, warnings: link and PDF export warnings}",
has_doc,
package
),
@@ -325,11 +325,18 @@ fn unique_name(base: String, taken: &mut Taken) -> String {
/// `relative_to` names the folder `dir` is, beside the saved document: the links then read
/// `Links/logo.png`, so a package holds no path from the machine that made it (#340). `None` links
/// the copies by their full paths (Links › Copy Link(s) To, which relinks the open document).
fn write_links(d: &Document, root: &OutputRoot, dir: &Path, only: Option<&[AssetId]>, relative_to: Option<&str>) -> Result<(Document, Vec<PathBuf>)> {
fn write_links(
d: &Document,
root: &OutputRoot,
dir: &Path,
only: Option<&[AssetId]>,
relative_to: Option<&str>,
) -> Result<(Document, Vec<PathBuf>, Vec<String>)> {
root.validate_directory(dir)?;
let mut out = d.clone();
let mut taken = Taken::default();
let mut written = Vec::new();
let mut warnings = Vec::new();
// Only files something places; the saved document leaves the others out.
let ids = d.used_assets();
for id in ids {
@@ -339,12 +346,17 @@ fn write_links(d: &Document, root: &OutputRoot, dir: &Path, only: Option<&[Asset
let Some(a) = d.assets.get(&id) else { continue };
// A missing link has no bytes: an empty file under its name would read as present, so it
// keeps its old (missing) path instead.
if a.data.is_empty() {
// Bytes that can't be had are left like a missing link.
// A changed file is copied as it is on disk now, with a warning.
let Some((bytes, modified)) = a.data.load_for_output().ok().filter(|(b, _)| !b.is_empty()) else {
continue;
};
if modified {
warnings.push(format!("the linked file `{}` has changed; the file on disk is copied", a.name));
}
let name = link_name(a.link.as_deref().unwrap_or(&a.name), id, &mut taken);
let path = dir.join(&name);
root.write(&path, a.data.as_slice())?;
root.write(&path, bytes.as_slice())?;
let mut na = (**a).clone();
let link = match relative_to {
Some(folder) => format!("{folder}/{name}"),
@@ -353,11 +365,30 @@ fn write_links(d: &Document, root: &OutputRoot, dir: &Path, only: Option<&[Asset
// The copy is the linked file now, and the original's size and time say nothing of it.
// Its own are too recent to vouch for it yet: the first check compares the bytes and
// keeps them (`remember_link_files`).
na.set_link(Some(link), None);
if na.storage == Storage::Linked {
// A linked original stays a link, to its copy, told by its hash until then. Its
// bytes are read from the copy (by its full path: the package's document reads its
// copies once opened beside them).
let hash = crate::asset_io::content_hash(&bytes);
let fingerprint = Fingerprint { size: bytes.len() as u64, mtime: super::links::UNVERIFIED_MTIME };
na.link_relative = relative_to.map(|_| link.clone());
na.link_hash = Some(hash.clone());
na.set_link(Some(link), Some(fingerprint));
na.data = na.data.with_source(LinkedSource {
path: path.to_string_lossy().into_owned(),
relative: None,
document: None,
len: fingerprint.size,
fingerprint: Some(fingerprint),
hash: Some(hash),
});
} else {
na.set_link(Some(link), None);
}
out.assets.insert(id, Arc::new(na));
written.push(path);
}
Ok((out, written))
Ok((out, written, warnings))
}
/// Copy the font file of `face` into `dir` (created when first needed) unless its licence
@@ -456,7 +487,7 @@ fn package(s: &mut Session, p: &Value) -> Result<Value> {
let pre = s.execute("preflight.run", &json!({})).unwrap_or(Value::Null);
let d = s.doc()?.doc.clone();
let links_dir = root.child(LINKS_FOLDER)?;
let (packed, mut files) = write_links(&d, &root, &links_dir, None, Some(LINKS_FOLDER))?;
let (packed, mut files, mut warnings) = write_links(&d, &root, &links_dir, None, Some(LINKS_FOLDER))?;
let doc_path = package_output_path(&dir, &title, "designcraft")?;
root.write(&doc_path, &super::to_bytes(&packed)?)?;
files.insert(0, doc_path);
@@ -499,12 +530,11 @@ fn package(s: &mut Session, p: &Value) -> Result<Value> {
idml_layer_note = "\nPlaced PDF layers\nThe IDML copy links the placed PDFs, so it shows their file defaults. The DesignCraft document keeps each placement's Object Layer Options choice.\n";
}
}
let mut warnings = Vec::new();
if let Some(params) = pdf {
let path = package_output_path(&dir, &title, "pdf")?;
let pdf = super::export::pdf_report(&packed, &s.cache, &params)?;
root.write(&path, &pdf.bytes)?;
warnings = pdf.warnings;
warnings.extend(pdf.warnings);
files.push(path);
}
// The printing instructions first, as the form gave them; then the report: fonts (missing
@@ -532,7 +562,7 @@ fn package(s: &mut Session, p: &Value) -> Result<Value> {
}
}
if !warnings.is_empty() {
r += "\nPDF export warnings\n";
r += "\nWarnings\n";
for warning in &warnings {
r += &format!(" {warning}\n");
}
@@ -550,12 +580,12 @@ fn copy_links(s: &mut Session, p: &Value) -> Result<Value> {
let only: Option<Vec<AssetId>> = p.get("assets").and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_u64).map(AssetId).collect());
let d = s.doc()?.doc.clone();
let root = OutputRoot::new(dir.clone())?;
let (relinked, written) = write_links(&d, &root, &dir, only.as_deref(), None)?;
let (relinked, written, warnings) = write_links(&d, &root, &dir, only.as_deref(), None)?;
s.edit(|doc, _| {
doc.assets = relinked.assets;
Ok(())
})?;
Ok(json!({"copied": written.len()}))
Ok(json!({"copied": written.len(), "warnings": warnings}))
}
#[cfg(test)]
+12 -4
View File
@@ -112,7 +112,8 @@ fn relocated_packages_rebind_embedded_image_links_on_open() {
let mut opened = Session::new();
opened.execute(command, &json!({"path": moved.join(format!("OwnedPackage.{extension}")).to_string_lossy()})).unwrap();
let asset = opened.doc().unwrap().doc.assets.values().next().unwrap();
assert_eq!(*asset.data, png, "{extension}: the packaged pixels");
// The IDML copy links Links/owned.png, so its graphic opens as a link to that file.
assert_eq!(asset.data.load().ok().as_deref(), Some(&png), "{extension}: the packaged pixels");
assert_eq!(asset.link.as_deref(), expected.to_str(), "{extension}: use the relocated Links file");
let links = opened.execute("links.list", &json!({})).unwrap();
assert_eq!(links[0]["status"], "ok", "{extension}");
@@ -244,8 +245,10 @@ fn package_leaves_missing_links_missing() {
let mut s = Session::new();
s.execute("file.new", &json!({"title": "TwoLinks"})).unwrap();
s.execute("file.place", &json!({"path": gone.to_string_lossy(), "x": 10, "y": 10})).unwrap();
crate::cmd::native_links::wait(&mut s);
s.execute("edit.deselectAll", &json!({})).unwrap();
s.execute("file.place", &json!({"path": kept.to_string_lossy(), "x": 10, "y": 200})).unwrap();
crate::cmd::native_links::wait(&mut s);
let idml = dir.join("TwoLinks.idml");
s.execute("file.exportIdml", &json!({"path": idml.to_string_lossy(), "embedImages": false})).unwrap();
std::fs::remove_file(&gone).unwrap();
@@ -267,6 +270,8 @@ fn package_leaves_missing_links_missing() {
for (command, extension) in [("file.open", "designcraft"), ("file.openIdml", "idml")] {
let mut opened = Session::new();
opened.execute(command, &json!({"path": out.join(format!("TwoLinks.{extension}")).to_string_lossy()})).unwrap();
// The open checks linked files in the background.
super::super::native_links::wait(&mut opened);
assert_eq!(status(&mut opened, "gone.svg"), Some(json!("missing")), "{extension}");
assert_eq!(status(&mut opened, "kept.svg"), Some(json!("ok")), "{extension}");
}
@@ -310,6 +315,7 @@ fn package_writes_document_links_and_report() {
let mut s = Session::new();
s.execute("file.new", &json!({})).unwrap();
s.execute("file.place", &json!({"path": svg.to_string_lossy(), "x": 100, "y": 100})).unwrap();
crate::cmd::native_links::wait(&mut s);
assert_eq!(s.doc().unwrap().doc.assets.values().next().unwrap().link_fingerprint, fingerprint(&svg));
s.execute("frame.create", &json!({"rect": [72, 300, 400, 400], "content": "text", "text": "Hello"})).unwrap();
let out = dir.join("Pkg");
@@ -329,15 +335,17 @@ fn package_writes_document_links_and_report() {
let link = packed.assets.values().next().unwrap().link.clone().unwrap();
assert!(link.contains("Links"), "{link}");
// The link is the copy now: the original file's size and time don't go with it (the copy's
// own are too recent to vouch for it; the first check compares the bytes and keeps them).
// own are too recent to vouch for it; the first check compares the bytes by their hash and
// keeps them).
let unverified = Some(super::super::links::UNVERIFIED_MTIME);
assert!(fingerprint(&out.join("Links").join("logo.svg")).is_some());
assert_eq!(packed.assets.values().next().unwrap().link_fingerprint, None);
assert_eq!(packed.assets.values().next().unwrap().link_fingerprint.map(|f| f.mtime), unverified);
// Copy Links To relinks the open document.
let r = s.execute("links.copyTo", &json!({"dir": dir.join("Copies").to_string_lossy()})).unwrap();
assert_eq!(r["copied"], 1);
let relinked = s.doc().unwrap().doc.assets.values().next().unwrap().clone();
assert!(relinked.link.as_deref().unwrap().contains("Copies"));
assert_eq!(relinked.link_fingerprint, None);
assert_eq!(relinked.link_fingerprint.map(|f| f.mtime), unverified);
let _ = std::fs::remove_dir_all(&dir);
}
+318
View File
@@ -0,0 +1,318 @@
//! Paste a bitmap from the system clipboard (a screenshot, an image copied in a web browser or an
//! image editor, an image file copied in a file manager) as a placed image. The pixels are
//! embedded in the document, so a save and reopen or an IDML export keeps them.
use designcraft_doc::Content;
use designcraft_geom::Point;
use serde_json::{Value, json};
use super::{CommandSpec, Result, Session, bad, cmd, has_doc, spread_param};
const ID: &str = "edit.pasteImage";
/// The most pixels a pasted image may have (8,000 × 8,000).
pub const MAX_PASTED_PIXELS: u64 = 64_000_000;
/// The largest pasted image file, in bytes.
const MAX_PASTED_BYTES: usize = 256 << 20;
/// The extensions a pasted image's name may end in.
pub const IMAGE_EXTENSIONS: [&str; 8] = ["png", "jpg", "jpeg", "gif", "webp", "tif", "tiff", "bmp"];
/// The name a pasted bitmap gets in the Links panel when it comes with none.
pub const PASTED_IMAGE_NAME: &str = "Pasted image.png";
pub fn specs() -> Vec<CommandSpec> {
vec![cmd!(
"edit.pasteImage",
"Paste Image",
[],
None,
"{base64: an image file (PNG/JPEG/GIF/WebP/TIFF/BMP) as base64, name?: its name in the Links panel ending in an image extension (default \"Pasted image.png\"), spread?, at?: [x, y] (spread coords of the image's center; default the first page's center)} → {id, asset} — embedded; a selected empty frame takes the image, otherwise a new frame holds it at one point per pixel, as File › Place sizes an image, and at most 60% of the page width",
has_doc,
paste_image
)]
}
/// Whether a `width × height` bitmap is small enough to paste; the error says why not.
pub fn check_pasted_size(width: u32, height: u32) -> std::result::Result<(), String> {
if width == 0 || height == 0 {
return Err("the image on the clipboard has no pixels".into());
}
if u64::from(width) * u64::from(height) > MAX_PASTED_PIXELS {
return Err(format!(
"the image on the clipboard is {width} × {height} pixels; images of up to 64 million pixels can be pasted (save it and use File › Place)"
));
}
Ok(())
}
/// Whether an image file given as base64 is small enough to paste, checked before it is
/// decoded; the error says why not.
pub fn check_pasted_base64(b64: &str) -> std::result::Result<(), String> {
check_pasted_base64_len(b64.len())
}
fn check_pasted_base64_len(len: usize) -> std::result::Result<(), String> {
if len / 4 * 3 > MAX_PASTED_BYTES {
return Err(format!("the image is larger than {} MB", MAX_PASTED_BYTES >> 20));
}
Ok(())
}
/// Unpremultiplied RGBA pixels from the clipboard, rows top to bottom, as a PNG file for
/// [`edit.pasteImage`](specs).
pub fn pasted_png(width: u32, height: u32, rgba: Vec<u8>) -> std::result::Result<Vec<u8>, String> {
check_pasted_size(width, height)?;
if (rgba.len() as u64) != u64::from(width) * u64::from(height) * 4 {
return Err("the image on the clipboard has the wrong number of pixels".into());
}
designcraft_images::png_from_rgba(width, height, rgba).ok_or_else(|| "the image on the clipboard can't be stored".to_string())
}
/// An image file's pixels: (width, height, unpremultiplied RGBA). `None` when it is not a raster
/// DesignCraft reads or has more pixels than [`MAX_PASTED_PIXELS`].
pub fn pasted_pixels(bytes: &[u8]) -> Option<(u32, u32, Vec<u8>)> {
let (w, h) = raster_size(bytes)?;
check_pasted_size(w, h).ok()?;
let img = designcraft_images::decode_rgba(bytes)?;
Some((img.width(), img.height(), img.into_raw()))
}
/// A raster's pixel size; `None` for vector formats (PDF, SVG, EPS) and unreadable data.
fn raster_size(bytes: &[u8]) -> Option<(u32, u32)> {
if designcraft_images::is_pdf(bytes) || designcraft_images::is_svg(bytes) || designcraft_images::is_eps(bytes) {
return None;
}
designcraft_images::pixel_size(bytes)
}
fn paste_image(s: &mut Session, p: &Value) -> Result<Value> {
let b64 = match p.get("base64") {
Some(Value::String(b)) if !b.is_empty() => b,
Some(_) => return Err(bad(ID, "`base64` must be a non-empty string")),
None => return Err(bad(ID, "missing base64")),
};
check_pasted_base64(b64).map_err(|e| bad(ID, e))?;
let name = match p.get("name") {
None | Some(Value::Null) => PASTED_IMAGE_NAME,
Some(Value::String(n)) if !n.trim().is_empty() => n.as_str(),
Some(_) => return Err(bad(ID, "`name` must be a non-empty string")),
};
// File › Place picks text and layout import by the name's extension: keep it an image's.
let ext = name.rsplit_once('.').map(|(_, e)| e.to_ascii_lowercase()).unwrap_or_default();
if !IMAGE_EXTENSIONS.contains(&ext.as_str()) {
return Err(bad(ID, format!("`name` must end in an image extension ({})", IMAGE_EXTENSIONS.join(", "))));
}
let bytes = super::base64_decode(b64);
let (pw, ph) = raster_size(&bytes).ok_or_else(|| bad(ID, "the clipboard doesn't hold an image DesignCraft can read"))?;
check_pasted_size(pw, ph).map_err(|e| bad(ID, e))?;
// The header can be whole while the pixels after it are cut off: decode the whole raster so
// a damaged image is refused instead of stored.
if designcraft_images::decode_rgba(&bytes).is_none() {
return Err(bad(ID, "the image on the clipboard is damaged and can't be read"));
}
let sr = spread_param(p, ID)?;
let at = match p.get("at") {
None | Some(Value::Null) => None,
Some(_) => {
let at = super::point_param(p, "at").ok_or_else(|| bad(ID, "`at` must be [x, y]"))?;
if !(at.x.is_finite() && at.y.is_finite()) {
return Err(bad(ID, "`at` must be finite"));
}
Some(at)
}
};
// A selected empty frame takes the image, as File › Place fills it.
let st = s.doc()?;
let empty_frame = match st.selection.items.as_slice() {
[only] if st.doc.item(*only).is_some_and(|it| !it.locked && it.path.encloses_area() && matches!(it.content, Content::Unassigned)) => {
Some(only.0)
}
_ => None,
};
if let Some(frame) = empty_frame {
return place(s, &json!({"base64": b64, "name": name, "frame": frame}));
}
let d = &s.doc()?.doc;
let sp = d.spread(sr).ok_or_else(|| bad(ID, "no such spread"))?;
let center = match at {
Some(at) => at,
None => sp.pages.first().map_or(Point::ZERO, |pg| pg.bounds().center()),
};
// The size File › Place gives it: one point per pixel (`designcraft_images::natural_size`), at
// most 60% of the page width.
let (nw, nh) = designcraft_render::natural_size(&bytes, 0).unwrap_or((f64::from(pw), f64::from(ph)));
let w = nw.min(d.settings.page_width * 0.6);
let h = nh * w / nw;
let spread = p.get("spread").cloned().unwrap_or(Value::Null);
place(s, &json!({"base64": b64, "name": name, "spread": spread, "x": center.x - w / 2.0, "y": center.y - h / 2.0}))
}
/// Runs `file.place` inside this command. Only `edit.pasteImage` stays in the journal, so a
/// replay of the journal places the image once.
fn place(s: &mut Session, params: &Value) -> Result<Value> {
let journal = s.journal.len();
let r = s.execute("file.place", params);
s.journal.truncate(journal);
r
}
#[cfg(test)]
mod tests {
use super::*;
use crate::cmd::{base64_decode, base64_encode};
use designcraft_doc::{ItemId, SpreadRef};
/// A `w × h` PNG whose pixels count up, so a changed pixel shows.
fn png(w: u32, h: u32) -> Vec<u8> {
let rgba: Vec<u8> = (0..w * h * 4).map(|i| (i % 251) as u8).collect();
pasted_png(w, h, rgba).unwrap()
}
fn doc() -> Session {
let mut s = Session::new();
s.execute("file.new", &json!({})).unwrap();
s
}
fn placed_png(s: &Session, id: ItemId) -> Vec<u8> {
let d = &s.doc().unwrap().doc;
let Content::Graphic(g) = &d.item(id).unwrap().content else { panic!("not a graphic") };
let a = &d.assets[&g.asset];
assert_eq!(a.link, None, "embedded, not linked");
a.data.load().unwrap().to_vec()
}
#[test]
fn a_pasted_bitmap_is_embedded_at_the_center_and_kept_by_save_and_idml() {
let mut s = doc();
let png = png(40, 30);
let undo = s.doc().unwrap().history.undo.len();
let r = s.execute(ID, &json!({"base64": base64_encode(&png), "at": [300, 400]})).unwrap();
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "one undo step");
let id = ItemId(r["id"].as_u64().unwrap());
let st = s.doc().unwrap();
assert_eq!(st.selection.items, [id], "the pasted image is selected");
let b = st.doc.item(id).unwrap().bounds();
assert!(
(b.x0 - 280.0).abs() < 1e-9 && (b.y0 - 385.0).abs() < 1e-9 && (b.width() - 40.0).abs() < 1e-9 && (b.height() - 30.0).abs() < 1e-9,
"{b:?}"
);
assert_eq!(placed_png(&s, id), png);
assert_eq!(s.doc().unwrap().doc.assets[&designcraft_doc::AssetId(r["asset"].as_u64().unwrap())].name, PASTED_IMAGE_NAME);
let saved = s.execute("file.serialize", &json!({})).unwrap();
let mut t = Session::new();
t.execute("file.openBytes", &json!({"name": "a.designcraft", "base64": saved["base64"]})).unwrap();
assert_eq!(placed_png(&t, id), png, "saved with the document");
let idml = s.execute("file.exportIdml", &json!({})).unwrap();
let imported = designcraft_idml::import_idml(&base64_decode(idml["base64"].as_str().unwrap())).unwrap();
assert!(imported.assets.values().any(|a| **a.data.embedded_bytes().unwrap() == png), "the IDML package carries the pixels");
}
#[test]
fn without_a_point_the_image_lands_in_the_middle_of_the_first_page_and_shrinks_to_the_page() {
let mut s = doc();
let r = s.execute(ID, &json!({"base64": base64_encode(&png(1000, 10))})).unwrap();
let d = &s.doc().unwrap().doc;
let b = d.item(ItemId(r["id"].as_u64().unwrap())).unwrap().bounds();
let page = d.spread(SpreadRef::Doc(0)).unwrap().pages[0].bounds();
let w = d.settings.page_width * 0.6;
assert!((b.width() - w).abs() < 1e-9 && (b.height() - w / 100.0).abs() < 1e-9, "{b:?}");
assert!((b.center().x - page.center().x).abs() < 1e-9 && (b.center().y - page.center().y).abs() < 1e-9, "{b:?}");
}
#[test]
fn a_selected_empty_frame_takes_the_image() {
let mut s = doc();
let frame = s.execute("frame.create", &json!({"rect": [100, 100, 200, 300]})).unwrap()["id"].as_u64().unwrap();
s.execute("selection.set", &json!({"ids": [frame]})).unwrap();
let items = s.doc().unwrap().doc.spreads[0].items.len();
let r = s.execute(ID, &json!({"base64": base64_encode(&png(10, 10)), "at": [500, 500]})).unwrap();
assert_eq!(r["id"].as_u64(), Some(frame));
assert_eq!(s.doc().unwrap().doc.spreads[0].items.len(), items, "no new frame");
// A frame that already holds a graphic gets a new frame beside it instead.
let r = s.execute(ID, &json!({"base64": base64_encode(&png(10, 10)), "at": [500, 500]})).unwrap();
assert_ne!(r["id"].as_u64(), Some(frame));
assert_eq!(s.doc().unwrap().doc.spreads[0].items.len(), items + 1);
}
#[test]
fn bad_input_is_refused_and_leaves_no_undo_step() {
let mut s = doc();
let ok = base64_encode(&png(2, 2));
let undo = s.doc().unwrap().history.undo.len();
for (p, want) in [
(json!({}), "missing base64"),
(json!({"base64": 5}), "`base64` must be a non-empty string"),
(json!({"base64": ""}), "`base64` must be a non-empty string"),
(json!({"base64": base64_encode(b"just text")}), "doesn't hold an image"),
(json!({"base64": base64_encode(b"<svg xmlns='http://www.w3.org/2000/svg'/>")}), "doesn't hold an image"),
(json!({"base64": ok, "name": ""}), "`name` must be a non-empty string"),
(json!({"base64": ok, "name": 3}), "`name` must be a non-empty string"),
(json!({"base64": ok, "name": "notes.txt"}), "`name` must end in an image extension"),
(json!({"base64": ok, "name": "page.idml"}), "`name` must end in an image extension"),
(json!({"base64": ok, "name": "png"}), "`name` must end in an image extension"),
(json!({"base64": ok, "at": [1]}), "`at` must be [x, y]"),
(json!({"base64": ok, "spread": 9}), "no such spread"),
] {
let e = s.execute(ID, &p).unwrap_err().to_string();
assert!(e.contains(want), "{p}: {e}");
}
assert_eq!(s.doc().unwrap().history.undo.len(), undo, "nothing changed");
}
#[test]
fn base64_past_the_file_limit_is_refused_by_its_length() {
let limit = MAX_PASTED_BYTES / 3 * 4;
assert!(check_pasted_base64_len(limit).is_ok());
let e = check_pasted_base64_len(limit + 4).unwrap_err();
assert!(e.contains("larger than 256 MB"), "{e}");
}
#[test]
fn a_damaged_image_with_a_whole_header_is_refused() {
let mut s = doc();
let whole = png(40, 30);
let cut = &whole[..whole.len() / 2];
assert_eq!(raster_size(cut), Some((40, 30)), "the header still reads");
let (undo, assets) = (s.doc().unwrap().history.undo.len(), s.doc().unwrap().doc.assets.len());
let e = s.execute(ID, &json!({"base64": base64_encode(cut)})).unwrap_err().to_string();
assert!(e.contains("damaged"), "{e}");
let st = s.doc().unwrap();
assert_eq!((st.history.undo.len(), st.doc.assets.len()), (undo, assets), "nothing stored");
}
#[test]
fn each_paste_is_one_journal_entry_and_replays_once() {
let mut s = doc();
let frame = s.execute("frame.create", &json!({"rect": [100, 100, 200, 300]})).unwrap()["id"].as_u64().unwrap();
s.execute("selection.set", &json!({"ids": [frame]})).unwrap();
let start = s.journal.len();
let b64 = base64_encode(&png(10, 10));
s.execute(ID, &json!({"base64": b64, "at": [500, 500]})).unwrap();
s.execute(ID, &json!({"base64": b64, "at": [500, 500]})).unwrap();
let entries = s.journal[start..].to_vec();
assert_eq!(entries.iter().map(|(id, _)| id.as_str()).collect::<Vec<_>>(), [ID, ID], "the frame and the new-frame paths");
let items = |s: &Session| s.doc().unwrap().doc.spreads[0].items.len();
let mut t = doc();
t.execute("frame.create", &json!({"rect": [100, 100, 200, 300]})).unwrap();
t.execute("selection.set", &json!({"ids": [frame]})).unwrap();
for (id, p) in &entries {
t.execute(id, p).unwrap();
}
assert_eq!(items(&t), items(&s), "the replay places each image once");
}
#[test]
fn images_beyond_the_pixel_limit_are_refused_before_they_are_encoded() {
let e = pasted_png(9000, 8000, Vec::new()).unwrap_err();
assert!(e.contains("9000 × 8000 pixels") && e.contains("64 million"), "{e}");
assert!(pasted_png(0, 5, Vec::new()).is_err());
assert!(pasted_png(2, 2, vec![0; 15]).unwrap_err().contains("wrong number of pixels"));
assert_eq!(pasted_pixels(&png(3, 2)).map(|(w, h, px)| (w, h, px.len())), Some((3, 2, 24)));
assert_eq!(pasted_pixels(b"%PDF-1.4"), None, "vector files are not pasted as pixels");
}
}
+42 -9
View File
@@ -3,6 +3,8 @@
//! clipboard as SVG markup; each path becomes a DesignCraft path with its fill and stroke, groups
//! stay groups, and text comes in as outlines.
use std::collections::{HashMap, HashSet};
use craft_svg::tree::document::{Document as SvgDocument, LineCap, LineJoin, Node as SvgNode, Paint as SvgPaint, Segment};
use designcraft_doc::{Content, Fill, Item, ItemId, Selection, Shape, Stroke, StrokeType};
use designcraft_geom::{Affine, BezPath, PathData, Point, Rect};
@@ -167,16 +169,46 @@ fn bounds(art: &[Art]) -> Option<Rect> {
.reduce(|a, b| a.union(b))
}
/// The document's RGB colour swatches by colour and its swatch names, looked up once per paste
/// (a pasted SVG can hold tens of thousands of colours).
struct PasteSwatches {
by_rgb: HashMap<[u32; 3], String>,
names: HashSet<String>,
}
impl PasteSwatches {
/// An RGB colour as a key: equal colours, equal keys (`+ 0.0` makes -0 and 0 one key).
fn key(r: f32, g: f32, b: f32) -> [u32; 3] {
[(r + 0.0).to_bits(), (g + 0.0).to_bits(), (b + 0.0).to_bits()]
}
fn new(d: &designcraft_doc::Document) -> Self {
use designcraft_color::swatch::SwatchValue;
let mut by_rgb = HashMap::new();
for w in &d.swatches {
if let SwatchValue::Color { color: designcraft_color::Color::Rgb { r, g, b }, .. } = &w.value {
// The first swatch of a colour is the one, as a search from the start finds it.
by_rgb.entry(Self::key(*r, *g, *b)).or_insert_with(|| w.name.clone());
}
}
Self { by_rgb, names: d.swatches.iter().map(|w| w.name.clone()).collect() }
}
}
/// The swatch holding exactly `rgb`: an existing process colour, else a new unnamed one (hidden
/// from the Swatches panel until Add to Swatches), as InDesign does for pasted colours.
fn swatch_for(d: &mut designcraft_doc::Document, rgb: [u8; 3]) -> String {
fn swatch_for(d: &mut designcraft_doc::Document, known: &mut PasteSwatches, rgb: [u8; 3]) -> String {
use designcraft_color::swatch::{Swatch, SwatchValue};
let color = designcraft_color::Color::rgb8(rgb[0], rgb[1], rgb[2]);
if let Some(w) = d.swatches.iter().find(|w| matches!(&w.value, SwatchValue::Color { color: c, .. } if *c == color)) {
return w.name.clone();
let designcraft_color::Color::Rgb { r, g, b } = color else { return String::new() };
let key = PasteSwatches::key(r, g, b);
if let Some(name) = known.by_rgb.get(&key) {
return name.clone();
}
let base = format!("R={} G={} B={}", rgb[0], rgb[1], rgb[2]);
let name = designcraft_doc::Styles::unique_name(|n| d.swatch(n).is_some(), &base);
let name = designcraft_doc::Styles::unique_name(|n| known.names.contains(n), &base);
known.names.insert(name.clone());
known.by_rgb.insert(key, name.clone());
d.swatches.push(Swatch {
name: name.clone(),
value: SwatchValue::Color { color, color_type: designcraft_color::ColorType::Process },
@@ -187,7 +219,7 @@ fn swatch_for(d: &mut designcraft_doc::Document, rgb: [u8; 3]) -> String {
name
}
fn build(d: &mut designcraft_doc::Document, art: Vec<Art>, layer: designcraft_doc::LayerId, shift: Affine) -> Vec<Item> {
fn build(d: &mut designcraft_doc::Document, known: &mut PasteSwatches, art: Vec<Art>, layer: designcraft_doc::LayerId, shift: Affine) -> Vec<Item> {
let mut out = Vec::new();
for a in art {
match a {
@@ -205,12 +237,12 @@ fn build(d: &mut designcraft_doc::Document, art: Vec<Art>, layer: designcraft_do
let paint = fill.map(|f| f.opacity).or(stroke.as_ref().map(|(c, _)| c.opacity)).unwrap_or(1.0);
let mut it = Item::new(ItemId(d.alloc()), layer, if line { Shape::GraphicLine } else { Shape::Path }, data);
it.fill = match fill {
Some(f) => Fill::swatch(&swatch_for(d, f.rgb)),
Some(f) => Fill::swatch(&swatch_for(d, known, f.rgb)),
None => Fill::none(),
};
it.stroke = match stroke {
Some((c, s)) => Stroke {
swatch: swatch_for(d, c.rgb),
swatch: swatch_for(d, known, c.rgb),
weight: s.width,
cap: s.cap,
join: s.join,
@@ -224,7 +256,7 @@ fn build(d: &mut designcraft_doc::Document, art: Vec<Art>, layer: designcraft_do
out.push(it);
}
Art::Group(items, opacity) => {
let children = build(d, items, layer, shift);
let children = build(d, known, items, layer, shift);
if children.is_empty() {
continue;
}
@@ -279,7 +311,8 @@ fn paste_svg(s: &mut Session, p: &Value) -> Result<Value> {
warnings.push(format!("{} embedded image(s) left out (place images with File › Place)", notes.images));
}
s.edit(|d, sel| {
let items = build(d, art, layer, shift);
let mut known = PasteSwatches::new(d);
let items = build(d, &mut known, art, layer, shift);
let mut ids = Vec::new();
for it in items {
ids.push(it.id);
+58 -9
View File
@@ -4,7 +4,7 @@
use std::sync::Arc;
use designcraft_doc::{Content, Document, Fill, Item, ItemId, Selection, Shape, SpreadRef, Stroke};
use designcraft_geom::{Affine, BezPath, PathData, SubPath};
use designcraft_geom::{Affine, BezPath, PathData, Shape as _, SubPath};
use serde_json::{Value, json};
use super::{CommandSpec, bad, cmd, has_selection, point_param, targets};
@@ -75,22 +75,39 @@ fn spread_xf(d: &Document, id: ItemId) -> Option<(SpreadRef, Affine)> {
Some((loc.spread, d.parent_xf(&loc) * d.item_at(&loc)?.xf))
}
/// Containment tests `orient_holes` makes at most (after the bounding-box filter). A compound path
/// of thousands of nested contours would otherwise take quadratic time; past this the command is
/// refused rather than leave later subpaths with the wrong direction.
const MAX_HOLE_TESTS: usize = 4_000_000;
/// Orient subpaths so those nested an odd number of times run against the others: with the
/// non-zero rule they become holes.
fn orient_holes(path: &mut PathData) {
fn orient_holes(path: &mut PathData, command: &str) -> Result<()> {
orient_holes_within(path, command, MAX_HOLE_TESTS)
}
fn orient_holes_within(path: &mut PathData, command: &str, max_tests: usize) -> Result<()> {
let beziers: Vec<BezPath> = path.subpaths.iter().map(|s| PathData::single(s.clone()).to_bezpath()).collect();
// A point outside a contour's box is outside the contour: most pairs are skipped without a winding count.
let boxes: Vec<_> = beziers.iter().map(BezPath::bounding_box).collect();
let n = path.subpaths.len();
let mut tests = 0usize;
for (i, sp) in path.subpaths.iter_mut().enumerate() {
let Some(p) = sp.anchors.first().map(|a| a.p) else { continue };
let depth = beziers
.iter()
.enumerate()
.filter(|(j, bezier)| *j != i && designcraft_geom::hit::fill_contains(bezier, designcraft_geom::FillRule::NonZero, p))
.count();
let mut depth = 0;
for j in (0..n).filter(|&j| j != i && boxes[j].inflate(1e-6, 1e-6).contains(p)) {
tests += 1;
if tests > max_tests {
return Err(bad(command, "too many nested contours to tell holes from fills"));
}
depth += usize::from(designcraft_geom::hit::fill_contains(&beziers[j], designcraft_geom::FillRule::NonZero, p));
}
let cw = sp.area() > 0.0;
if cw == (depth % 2 == 1) {
sp.reverse();
}
}
Ok(())
}
fn make_compound(s: &mut Session, p: &Value) -> Result<Value> {
@@ -117,7 +134,7 @@ fn make_compound(s: &mut Session, p: &Value) -> Result<Value> {
}
let it = d.item_mut(base_id).ok_or(designcraft_doc::DocError::NoItem(base_id))?;
it.path = PathData::new(subpaths);
orient_holes(&mut it.path);
orient_holes(&mut it.path, "object.makeCompoundPath")?;
it.shape = Shape::Path;
*sel = Selection::items(vec![base_id]);
Ok(json!({"id": base_id.0}))
@@ -161,7 +178,7 @@ fn pathfinder(s: &mut Session, p: &Value) -> Result<Value> {
}
let it = d.item_mut(keep).ok_or(designcraft_doc::DocError::NoItem(keep))?;
it.path = result.transformed(kxf.inverse());
orient_holes(&mut it.path);
orient_holes(&mut it.path, "object.pathfinder")?;
it.shape = Shape::Path;
it.corners = Default::default();
*sel = Selection::items(vec![keep]);
@@ -411,6 +428,38 @@ mod tests {
s.doc().unwrap().doc.check().unwrap();
}
#[test]
fn orient_holes_alternates_nested_contours_and_skips_distant_ones() {
use designcraft_geom::{Rect, shapes::rectangle};
let mut subs: Vec<SubPath> = Vec::new();
for k in 0..3 {
let o = 10.0 * f64::from(k);
subs.extend(rectangle(Rect::new(o, o, 100.0 - o, 100.0 - o)).subpaths);
}
// Thousands of separate contours cost no winding counts (their boxes miss each other).
for k in 0..3000 {
let x = 200.0 + 20.0 * f64::from(k);
subs.extend(rectangle(Rect::new(x, 0.0, x + 10.0, 10.0)).subpaths);
}
let mut path = PathData::new(subs);
orient_holes(&mut path, "test").unwrap();
let cw: Vec<bool> = path.subpaths.iter().map(|s| s.area() > 0.0).collect();
assert_eq!(cw[..3], [true, false, true]);
assert!(cw[3..].iter().all(|c| *c));
}
#[test]
fn orient_holes_refuses_past_its_budget_instead_of_half_orienting() {
use designcraft_geom::{Rect, shapes::rectangle};
let mut subs: Vec<SubPath> = Vec::new();
for k in 0..4 {
let o = 10.0 * f64::from(k);
subs.extend(rectangle(Rect::new(o, o, 100.0 - o, 100.0 - o)).subpaths);
}
assert!(orient_holes_within(&mut PathData::new(subs.clone()), "test", 3).is_err());
assert!(orient_holes_within(&mut PathData::new(subs), "test", 100).is_ok());
}
#[test]
fn pathfinder_subtracts_front_from_back() {
let mut s = Session::new();
+2 -1
View File
@@ -9,7 +9,8 @@ fn placed_pdf(s: &Session, id: designcraft_doc::ItemId) -> Option<std::sync::Arc
let d = &s.active()?.doc;
let g = d.item(id)?.graphic()?;
let a = d.assets.get(&g.asset)?;
designcraft_render::is_pdf(&a.data).then(|| a.data.clone())
let bytes = a.data.load().ok()?;
designcraft_render::is_pdf(&bytes).then_some(bytes)
}
pub fn specs() -> Vec<CommandSpec> {
+8 -8
View File
@@ -383,10 +383,10 @@ fn placed_pdf_all_on_is_distinct_from_defaults_and_survives_exports() {
let idml = s.execute("file.exportIdml", &json!({})).unwrap();
let bytes = super::super::file::base64_decode(idml["base64"].as_str().unwrap());
let imported = designcraft_idml::import_idml(&bytes).unwrap();
let pdf_asset = imported.assets.values().find(|a| designcraft_render::is_pdf(&a.data)).unwrap();
assert!(designcraft_render::pdf_layers(&pdf_asset.data).iter().all(|(_, on)| *on));
let pdf_asset = imported.assets.values().find(|a| designcraft_render::is_pdf(&a.data.load().unwrap())).unwrap();
assert!(designcraft_render::pdf_layers(&pdf_asset.data.load().unwrap()).iter().all(|(_, on)| *on));
assert!(s.execute("file.exportIdml", &json!({"embedImages":false})).is_err());
assert_eq!(s.doc().unwrap().doc.assets.values().find(|a| a.name == "off.pdf").unwrap().data.as_slice(), pdf);
assert_eq!(s.doc().unwrap().doc.assets.values().find(|a| a.name == "off.pdf").unwrap().data.load().unwrap().as_slice(), pdf);
s.execute("object.layerOptions", &json!({"ids":[id],"hidden":[]})).unwrap();
assert!(!visible(&mut s), "legacy empty list still resets defaults");
s.execute("object.layerOptions", &json!({"ids":[id],"hidden":[],"useDefaults":false})).unwrap();
@@ -412,8 +412,8 @@ fn parent_page_choices_reach_idml_variants_and_raster_export() {
// Embedded IDML: the parent-page placement gets its own variant, like a document one.
let idml = s.execute("file.exportIdml", &json!({})).unwrap();
let imported = designcraft_idml::import_idml(&super::super::file::base64_decode(idml["base64"].as_str().unwrap())).unwrap();
let asset = imported.assets.values().find(|a| designcraft_render::is_pdf(&a.data)).unwrap();
assert!(designcraft_render::pdf_layers(&asset.data).iter().all(|(_, on)| *on), "the embedded copy shows every layer");
let asset = imported.assets.values().find(|a| designcraft_render::is_pdf(&a.data.load().unwrap())).unwrap();
assert!(designcraft_render::pdf_layers(&asset.data.load().unwrap()).iter().all(|(_, on)| *on), "the embedded copy shows every layer");
// An external-only copy would keep the original file's defaults: the choice is rejected.
let err = s.execute("file.exportIdml", &json!({"embedImages": false})).unwrap_err().to_string();
assert!(err.contains("embedded images"), "{err}");
@@ -437,7 +437,7 @@ fn an_anchored_placement_keeps_its_layer_choice_in_saves_and_exports() {
id: asset,
name: "anchored.pdf".into(),
mime: "application/pdf".into(),
data: std::sync::Arc::new(pdf),
data: designcraft_doc::AssetData::embedded(pdf),
..Default::default()
});
let mut item =
@@ -464,10 +464,10 @@ fn an_anchored_placement_keeps_its_layer_choice_in_saves_and_exports() {
// Embedded IDML carries a variant that shows every layer.
let idml = s.execute("file.exportIdml", &json!({})).unwrap();
let imported = designcraft_idml::import_idml(&super::super::file::base64_decode(idml["base64"].as_str().unwrap())).unwrap();
let copies: Vec<_> = imported.assets.values().filter(|a| designcraft_render::is_pdf(&a.data)).collect();
let copies: Vec<_> = imported.assets.values().filter(|a| designcraft_render::is_pdf(&a.data.load().unwrap())).collect();
assert!(!copies.is_empty(), "the anchored placement is exported");
assert!(
copies.iter().all(|a| designcraft_render::pdf_layers(&a.data).iter().all(|(_, on)| *on)),
copies.iter().all(|a| designcraft_render::pdf_layers(&a.data.load().unwrap()).iter().all(|(_, on)| *on)),
"the embedded copy must not fall back to the file's defaults"
);
// An external-only copy would keep the original file's defaults.
+25 -15
View File
@@ -506,6 +506,29 @@ pub(super) fn place_text(
})
}
/// A minimal Word package for tests: the document and its styles, with the content types and
/// relationships that tell a reader where those parts are.
#[cfg(test)]
pub(crate) fn word_package(document: &str, styles: &str) -> Vec<u8> {
use std::io::Write;
const CONTENT_TYPES: &str = r#"<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/><Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/><Override PartName="/word/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml"/></Types>"#;
const ROOT_RELS: &str = r#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>"#;
const DOCUMENT_RELS: &str = r#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/></Relationships>"#;
let mut w = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
let o = zip::write::SimpleFileOptions::default();
for (n, c) in [
("[Content_Types].xml", CONTENT_TYPES),
("_rels/.rels", ROOT_RELS),
("word/_rels/document.xml.rels", DOCUMENT_RELS),
("word/document.xml", document),
("word/styles.xml", styles),
] {
w.start_file(n, o).unwrap();
w.write_all(c.as_bytes()).unwrap();
}
w.finish().unwrap().into_inner()
}
#[cfg(test)]
mod tests;
@@ -710,7 +733,6 @@ mod pdf_page_tests {
}
fn word_file() -> Vec<u8> {
use std::io::Write;
const W: &str = r#"xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main""#;
let styles = format!(
r#"<w:styles {W}><w:style w:type="paragraph" w:styleId="Normal"><w:name w:val="Normal"/></w:style>
@@ -721,13 +743,7 @@ mod pdf_page_tests {
r#"<w:document {W}><w:body><w:p><w:pPr><w:pStyle w:val="Title"/></w:pPr><w:r><w:t>Head</w:t></w:r></w:p>
<w:p><w:pPr><w:pStyle w:val="Body"/></w:pPr><w:r><w:t>Text</w:t></w:r></w:p></w:body></w:document>"#
);
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()
super::word_package(&doc, &styles)
}
#[test]
@@ -770,19 +786,13 @@ mod pdf_page_tests {
#[test]
fn word_normal_comes_in_as_its_own_style() {
// Regression (#722): Normal's formatting (over Word's document defaults) was dropped.
use std::io::Write;
const W: &str = r#"xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main""#;
let styles = format!(
r#"<w:styles {W}><w:docDefaults><w:rPrDefault><w:rPr><w:sz w:val="22"/></w:rPr></w:rPrDefault></w:docDefaults>
<w:style w:type="paragraph" w:styleId="Normal"><w:name w:val="Normal"/><w:rPr><w:rFonts w:ascii="Georgia"/><w:sz w:val="26"/></w:rPr></w:style></w:styles>"#
);
let doc = format!(r#"<w:document {W}><w:body><w:p><w:r><w:t>Plain</w:t></w:r></w:p></w:body></w:document>"#);
let mut w = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
for (n, c) in [("word/document.xml", doc), ("word/styles.xml", styles)] {
w.start_file(n, zip::write::SimpleFileOptions::default()).unwrap();
w.write_all(c.as_bytes()).unwrap();
}
let b64 = crate::cmd::base64_encode(&w.finish().unwrap().into_inner());
let b64 = crate::cmd::base64_encode(&super::word_package(&doc, &styles));
let basic = designcraft_doc::story::BASIC_PARAGRAPH;
let placed = |s: &Session, story: &serde_json::Value| {
let d = &s.doc().unwrap().doc;
+2 -11
View File
@@ -311,7 +311,6 @@ fn autoflow_adds_the_pages_odd_and_even_page_breaks_ask_for() {
#[test]
fn autoflow_sizes_no_frame_by_one_a_start_option_ends_early() {
// Regression (#1209): the title frame a start option ends early isn't a frame's worth of text.
use std::io::Write;
const W: &str = r#"xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main""#;
let para = |style: &str, text: &str| format!(r#"<w:p><w:pPr><w:pStyle w:val="{style}"/></w:pPr><w:r><w:t>{text}</w:t></w:r></w:p>"#);
let body = [para("Title", "Front"), para("Chapter", "Chapter one"), para("Body", "lorem ipsum dolor sit amet ".repeat(60).trim())].concat();
@@ -319,16 +318,8 @@ fn autoflow_sizes_no_frame_by_one_a_start_option_ends_early() {
.iter()
.map(|s| format!(r#"<w:style w:type="paragraph" w:styleId="{s}"><w:name w:val="{s}"/></w:style>"#))
.collect();
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", format!(r#"<w:document {W}><w:body>{body}</w:body></w:document>"#)),
("word/styles.xml", format!(r#"<w:styles {W}>{styles}</w:styles>"#)),
] {
w.start_file(n, o).unwrap();
w.write_all(c.as_bytes()).unwrap();
}
let docx = w.finish().unwrap().into_inner();
let docx =
super::word_package(&format!(r#"<w:document {W}><w:body>{body}</w:body></w:document>"#), &format!(r#"<w:styles {W}>{styles}</w:styles>"#));
for (start, pages) in [("nextOddPage", 5), ("nextEvenPage", 4)] {
let mut s = Session::new();
s.execute("file.new", &json!({"pages": 3, "facingPages": true})).unwrap();
+47 -18
View File
@@ -2,14 +2,14 @@
//! fonts and glyphs, missing or low-resolution graphics, RGB content in print documents, empty
//! text frames, white or [Paper] set to overprint.
use designcraft_compose::ComposedStory;
use designcraft_compose::{Cache, ComposedStory};
use designcraft_doc::{Content, Document, Intent, Item, SpreadRef};
use designcraft_fonts::FaceRef;
use designcraft_geom::Affine;
use serde::Serialize;
use serde_json::{Value, json};
use super::{CommandSpec, cmd, has_doc};
use super::{CommandSpec, LinkListChecks, cmd, has_doc};
use crate::{Result, Session};
mod white_overprint;
@@ -99,8 +99,7 @@ fn missing_glyphs(
/// its centre is on, and every page it reaches (see [`pages_of`]).
type Located = (designcraft_doc::ItemId, Option<usize>, Vec<usize>);
fn overset_location(s: &Session, target: designcraft_doc::ItemId) -> Option<Located> {
let d = &s.active()?.doc;
fn overset_location(d: &Document, cache: &Cache, target: designcraft_doc::ItemId) -> Option<Located> {
let at = |id: designcraft_doc::ItemId, loc: &designcraft_doc::ItemLoc| {
let it = d.item(id);
let xf = d.parent_xf(loc);
@@ -131,7 +130,7 @@ fn overset_location(s: &Session, target: designcraft_doc::ItemId) -> Option<Loca
let embedded = d.anchored_items();
while seen.insert(current) {
let owner = embedded.iter().find_map(|(owner, it)| (it.id == current).then_some(*owner))?;
let cs = s.cache.get(d, owner, None);
let cs = cache.get(d, owner, None);
// Search each host frame separately, including objects in its notes and cells.
let frame = cs.frames.iter().find(|f| contains(f, current))?;
current = frame.frame;
@@ -227,7 +226,7 @@ pub fn overset_warnings(s: &Session, pages: Option<&[usize]>) -> Vec<String> {
out.push(format!("a story with no text frame: {n} character(s) of it are not in the export"));
continue;
}
let location = last.and_then(|f| overset_location(s, f));
let location = last.and_then(|f| overset_location(d, &s.cache, f));
let centre = location.as_ref().and_then(|(_, page, _)| *page);
let touched: &[usize] = location.as_ref().map(|(_, _, ps)| ps.as_slice()).unwrap_or_default();
// A sheet draws its spread's items without asking which page they are on, so a frame
@@ -261,10 +260,39 @@ pub fn overset_warnings(s: &Session, pages: Option<&[usize]>) -> Vec<String> {
out
}
pub fn check(s: &Session, min_ppi: f64) -> Vec<Issue> {
let Some(st) = s.active() else { return vec![] };
let d = &st.doc;
let document = st.path.as_deref().map(std::path::Path::new);
/// The active document's issues. Linked files are looked at as `links.list` looks at them, with
/// what it remembers of them.
pub fn check(s: &mut Session, min_ppi: f64) -> Vec<Issue> {
let mut links = std::mem::take(&mut s.link_checks);
let issues = match s.active() {
Some(st) => check_document(&st.doc, &s.cache, st.path.as_deref().map(std::path::Path::new), min_ppi, &mut links),
None => vec![],
};
s.link_checks = links;
issues
}
/// [`check`] of document `d` saved at `document` (relative links resolve against it), with the
/// compositions in `cache`. It needs no session, so it can run on another thread. `links` is what
/// the caller remembers of linked files between checks: a file is read only when its size is the
/// recorded one and its time is new.
/// A linked file that is not the one placed: exports use the file as it is now.
fn modified_link(d: &Document, it: &Item, page: Option<usize>, document: Option<&std::path::Path>, links: &mut LinkListChecks) -> Option<Issue> {
let Content::Graphic(g) = &it.content else { return None };
let a = d.assets.get(&g.asset)?;
if !a.data.is_linked() || !super::links::link_modified(a, document, links) {
return None;
}
Some(Issue {
severity: "warning",
kind: "modifiedLink",
message: format!("Modified link: {} (exports use the file as it is now)", a.link.as_deref().unwrap_or(&a.name)),
item: Some(it.id.0),
page,
})
}
pub fn check_document(d: &Document, cache: &Cache, document: Option<&std::path::Path>, min_ppi: f64, links: &mut LinkListChecks) -> Vec<Issue> {
let mut out = Vec::new();
// Stories: overset and fonts.
let mut missing_fonts: Vec<String> = Vec::new();
@@ -274,11 +302,11 @@ pub fn check(s: &Session, min_ppi: f64) -> Vec<Issue> {
// a cell's or an unplaced story, which has no frame of its own).
let mut white_text: std::collections::BTreeMap<Option<designcraft_doc::ItemId>, Vec<&'static str>> = std::collections::BTreeMap::new();
for story in d.stories.values() {
let cs = s.cache.get(d, story.id, None);
let cs = cache.get(d, story.id, None);
missing_glyphs(&cs, None, 0, &mut missing);
if cs.is_overset() {
let last = story.frames.last().copied();
let location = last.and_then(|f| overset_location(s, f));
let location = last.and_then(|f| overset_location(d, cache, f));
let n = story.text.get(cs.overset_at.unwrap_or(0)..).unwrap_or("").chars().count();
let unplaced = story.frames.is_empty();
out.push(Issue {
@@ -336,7 +364,7 @@ pub fn check(s: &Session, min_ppi: f64) -> Vec<Issue> {
let props = d.styles.resolve_char(&base, f);
let white = white_overprint::adornments(d, &props);
if !white.is_empty() {
let shown = shown.get_or_insert_with(|| white_overprint::frame_ranges(s, d, story));
let shown = shown.get_or_insert_with(|| white_overprint::frame_ranges(cache, d, story));
for frame in white_overprint::frames_showing(story, shown, run.start.max(range.start)..run.end.min(range.end)) {
let parts = white_text.entry(frame).or_default();
for part in &white {
@@ -386,7 +414,7 @@ pub fn check(s: &Session, min_ppi: f64) -> Vec<Issue> {
for message in unsupported_typography {
out.push(Issue { severity: "warning", kind: "unsupportedTypography", message, item: None, page: None });
}
let (white_items, printed_frames) = white_overprint::printed(s, d);
let (white_items, printed_frames) = white_overprint::printed(cache, d);
for (item, parts) in white_text {
// A frame PDF export leaves out (hidden, nonprinting, on a hidden or nonprintable layer,
// on a parent page no page shows) prints none of its text.
@@ -430,6 +458,7 @@ pub fn check(s: &Session, min_ppi: f64) -> Vec<Issue> {
page,
});
}
out.extend(modified_link(d, it, page, document, links));
match &it.content {
Content::Graphic(g) => match d.assets.get(&g.asset) {
None => out.push(Issue { severity: "error", kind: "missingLink", message: "Missing graphic".into(), item: Some(it.id.0), page }),
@@ -445,7 +474,7 @@ pub fn check(s: &Session, min_ppi: f64) -> Vec<Issue> {
}),
Some(a) => {
// Placed PDF and SVG pages export as vectors; `pixels` is only the preview's.
let vector = designcraft_images::is_pdf(&a.data) || designcraft_images::is_svg(&a.data);
let vector = a.mime == "application/pdf" || a.mime == "image/svg+xml";
if let Some((pw, ph)) = a.pixels.filter(|_| !vector) {
// Measure each image axis in points, not its rotated bounding box or
// cropped frame. Either axis can fall below the minimum resolution.
@@ -571,10 +600,10 @@ mod arabic_tests {
let r = s.execute("frame.create", &json!({"rect": [0, 0, 300, 200], "content": "text", "text": text})).unwrap();
s.execute("text.select", &json!({"story": r["story"], "anchor": 0, "focus": text.len()})).unwrap();
s.execute("type.char", &json!({"attrs": {"diacriticPosition": "openType", "diacriticXOffset": 150}})).unwrap();
assert!(!check(&s, 150.0).iter().any(|i| i.kind == "unsupportedTypography"));
assert!(!check(&mut s, 150.0).iter().any(|i| i.kind == "unsupportedTypography"));
s.execute("type.para", &json!({"attrs": {"arabicJustification": "NaskhJustification", "paragraphKashidaWidth": 2}})).unwrap();
s.execute("type.char", &json!({"attrs": {"diacriticPosition": "tight"}})).unwrap();
let issues = check(&s, 150.0);
let issues = check(&mut s, 150.0);
let typography: Vec<_> = issues.iter().filter(|i| i.kind == "unsupportedTypography").collect();
assert_eq!(typography.len(), 3, "{typography:?}");
assert!(typography.iter().all(|i| i.severity == "warning"));
@@ -665,7 +694,7 @@ mod mojikumi_nested_tests {
pf.para.mojikumi = Some("MojikumiTable/Unrecognized".into());
cell.insert_note(0, "Note", pf);
d.story_mut(sid).unwrap().insert_table(0, table);
let issues = check(&s, 150.0);
let issues = check(&mut s, 150.0);
assert_eq!(issues.iter().filter(|i| i.kind == "unsupportedTypography" && i.message.contains("Unrecognized")).count(), 1);
}
}
@@ -12,13 +12,13 @@ use std::ops::Range;
use std::sync::Arc;
use designcraft_color::{Color, ColorType, SwatchValue, swatch};
use designcraft_compose::Cache;
use designcraft_doc::cjk_settings::AdornmentOverprint;
use designcraft_doc::{AnchoredObject, CharProps, Content, Document, Item, ItemId, SpreadRef, Story, StrokeType};
use designcraft_geom::Affine;
use designcraft_pdf::{drawn_children, item_exported, layer_exported, shown_parent_items};
use super::{Issue, page_of};
use crate::Session;
/// The issue's `kind`.
pub(super) const KIND: &str = "whiteOverprint";
@@ -100,7 +100,7 @@ enum On {
/// that show them, and anchored objects in the frames that place them. Returns the white
/// overprint issues of those items, and the page each text frame among them is first drawn on
/// (the frames whose ruby and kenten print).
pub(super) fn printed(s: &Session, d: &Document) -> (Vec<Issue>, BTreeMap<ItemId, Option<usize>>) {
pub(super) fn printed(cache: &Cache, d: &Document) -> (Vec<Issue>, BTreeMap<ItemId, Option<usize>>) {
let mut issues = Vec::new();
let mut frames = BTreeMap::new();
// A parent page's item shows on every page based on it: it is reported once, on the first.
@@ -129,7 +129,7 @@ pub(super) fn printed(s: &Session, d: &Document) -> (Vec<Issue>, BTreeMap<ItemId
let children: Vec<_> = drawn_children(it).map(|c| (Node::Item(c.clone()), inside, composed)).collect();
if let Content::Text(tf) = &it.content {
frames.entry(it.id).or_insert(page);
let cs = s.cache.get(d, tf.story, composed);
let cs = cache.get(d, tf.story, composed);
// The frame's anchored objects, and those in its footnotes and table cells.
let mut pending: Vec<_> = cs.frame(it.id).into_iter().collect();
while let Some(frame) = pending.pop() {
@@ -146,11 +146,11 @@ pub(super) fn printed(s: &Session, d: &Document) -> (Vec<Issue>, BTreeMap<ItemId
/// The byte ranges `story`'s frames show, for [`frames_showing`]: none for a story with no frame
/// of its own.
pub(super) fn frame_ranges(s: &Session, d: &Document, story: &Story) -> Vec<(ItemId, Range<usize>)> {
pub(super) fn frame_ranges(cache: &Cache, d: &Document, story: &Story) -> Vec<(ItemId, Range<usize>)> {
if story.frames.is_empty() {
return Vec::new();
}
s.cache.get(d, story.id, None).frames.iter().map(|f| (f.frame, f.range.clone())).collect()
cache.get(d, story.id, None).frames.iter().map(|f| (f.frame, f.range.clone())).collect()
}
/// The frames of `story` that show the bytes `run` (`shown`: [`frame_ranges`]). `None` stands
+2 -1
View File
@@ -133,7 +133,8 @@ fn convert_shape(s: &mut Session, p: &Value) -> Result<Value> {
const ID: &str = "object.convertShape";
let to = str_param(p, "to").ok_or_else(|| bad(ID, "`to` required"))?.to_string();
let ids = targets(s, p)?;
let sides = s.prefs.polygon_sides;
// The preference as object.polygon takes it: 3–100 sides, whatever prefs.set was given.
let sides = s.prefs.polygon_sides.clamp(3, 100);
let inset = s.prefs.star_inset;
s.edit(|d, _| {
let mut changed = 0;
+20
View File
@@ -161,6 +161,9 @@ const COMMON: &[&str] = &[
"yay",
];
/// Longest word [`suggest`] makes candidates for.
pub const MAX_SUGGEST_CHARS: usize = 40;
/// Is `w` (lowercase) a known word, allowing common inflections of dictionary stems?
pub fn known(dict: &Dictionary, user: &[String], w: &str) -> bool {
// A typographer's apostrophe (don’t, we’re) is the word list's straight one.
@@ -207,6 +210,11 @@ pub fn known(dict: &Dictionary, user: &[String], w: &str) -> bool {
/// Up to 6 suggestions at edit distance 1, ranked: transpositions, replacements, deletions, insertions.
pub fn suggest(dict: &Dictionary, w: &str) -> Vec<String> {
// Each candidate is a copy of the word: 53 per position, quadratic in its length. No word of
// a dictionary is this long, so no edit of such a "word" is one either. Checked before collecting.
if w.chars().take(MAX_SUGGEST_CHARS + 1).count() > MAX_SUGGEST_CHARS {
return Vec::new();
}
let chars: Vec<char> = w.chars().collect();
let mut out: Vec<String> = Vec::new();
let mut push = |c: Vec<char>| {
@@ -325,6 +333,18 @@ mod tests {
assert!(known(d, &["designcraft".into()], "designcraft"));
}
/// A "word" longer than any in the dictionary gets no candidates: there would be more than
/// fifty copies of it per character.
#[test]
fn very_long_words_get_no_suggestions() {
// The dictionary holds the longest allowed word, so deleting one letter of the 41-letter
// input would be a hit if the length cap were not applied.
let d = Dictionary::from_entries(vec![("a".repeat(MAX_SUGGEST_CHARS), 0)]);
assert_eq!(suggest(&d, &"a".repeat(MAX_SUGGEST_CHARS)), Vec::<String>::new());
assert_eq!(suggest(&d, &"a".repeat(MAX_SUGGEST_CHARS - 1)), vec!["a".repeat(MAX_SUGGEST_CHARS)]);
assert!(suggest(&d, &"a".repeat(MAX_SUGGEST_CHARS + 1)).is_empty());
}
#[test]
fn user_dictionary_replaces_and_counts() {
let mut s = Session::new();
+4 -4
View File
@@ -173,7 +173,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Apply Object Style",
[],
None,
"{name, ids?} — sets the style's fill, stroke, effects and text frame options on the items",
"{name, ids?} — sets the style's fill, stroke, corners, effects and text frame General options on the items, and its paragraph styles on their text; records nothing when the items already have them",
super::has_selection,
apply_object
),
@@ -182,7 +182,7 @@ pub fn specs() -> Vec<CommandSpec> {
"New Object Style…",
[],
None,
"{name, fromSelection?: true (fill, stroke, effects and text frame options of the first selected item), fill?, paragraphStyle?, effects?: {dropShadow?, feather?, innerShadow?, outerGlow?, innerGlow?, bevel?, satin?, gradientFeather?, directionalFeather?}, dropShadow?: {on?, color?, opacity? (0–1), angle?, globalLight?, distance?, size?, spread?}, feather?: width, innerShadow?, outerGlow?, innerGlow?, bevel?, satin?, gradientFeather?, directionalFeather?} → {name} (made unique)",
"{name, fromSelection?: true (fill, stroke, corners, effects and text frame options of the first selected item), fill?: swatch | {swatch?, tint?}, stroke?: {swatch?, weight?, tint?, type?, …} (swatches must exist; tint and gapTint 0–1; unknown fill, stroke and stroke type keys are refused), corners?: {shape?, size?} | {corners: [{shape, size}] ×4}, paragraphStyle?: a paragraph style (null: none; the text of a frame the style is applied to takes it), applyNextStyle?: bool (each paragraph after the first takes the Next Style of the one before), textFrame?: {columns? (1–40), columnsKind?, gutter?, columnWidth?, balanceColumns?, inset?: [top, left, bottom, right] | one number for all four, verticalJustification?: top|center|bottom|justify, vjParagraphSpacingLimit?, ignoreWrap?} | null (Text Frame General Options, named as `document.inspect` names text frame options; lengths 0–15552 pt; other keys are refused; a frame keeps its baseline, auto-size and column rule settings; null: the style sets none), effects?: {dropShadow?, feather?, innerShadow?, outerGlow?, innerGlow?, bevel?, satin?, gradientFeather?, directionalFeather?}, dropShadow?: {on?, color?, opacity? (0–1), angle?, globalLight?, distance?, size?, spread?}, feather?: width, innerShadow?, outerGlow?, innerGlow?, bevel?, satin?, gradientFeather?, directionalFeather?} → {name} (made unique)",
has_doc,
create_object
),
@@ -191,7 +191,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Object Style Options…",
[],
None,
"{name, effects?: {…} | null (the style no longer sets effects), dropShadow?, feather?, innerShadow?, outerGlow?, innerGlow?, bevel?, satin?, gradientFeather?, directionalFeather?} — effect objects merge field by field into the style's effects (fields as in `document.inspect` item effects); values that aren't finite numbers are refused, the others clamped (opacities 0–1, sizes and distances ≥ 0); items using the style whose effects match the style's (no effects, when the style set none) take the new effects, items with their own effects keep them → {name, updated}",
"{name, rename?: new name (every use follows), fill?: swatch | {swatch?, tint?} | null, stroke?: {swatch?, weight?, tint?, type?, …} | null (swatches must exist; tint and gapTint 0–1; unknown fill, stroke and stroke type keys are refused), corners?: {shape?: none|rounded|inverseRounded|inset|bevel|fancy, size?} | {corners: [{shape, size}] ×4} | null (null: the style no longer sets it; items keep theirs), paragraphStyle?: a paragraph style (null: none; the text of a frame the style is applied to takes it), applyNextStyle?: bool (each paragraph after the first takes the Next Style of the one before), textFrame?: {columns? (1–40), columnsKind?, gutter?, columnWidth?, balanceColumns?, inset?: [top, left, bottom, right] | one number for all four, verticalJustification?: top|center|bottom|justify, vjParagraphSpacingLimit?, ignoreWrap?} | null (Text Frame General Options, named as `document.inspect` names text frame options; lengths 0–15552 pt; other keys are refused; a frame keeps its baseline, auto-size and column rule settings; null: the style sets none), effects?: {…} | null (the style no longer sets effects), dropShadow?, feather?, innerShadow?, outerGlow?, innerGlow?, bevel?, satin?, gradientFeather?, directionalFeather?} — effect objects merge field by field into the style's effects (fields as in `document.inspect` item effects); values that aren't finite numbers are refused, the others clamped (opacities 0–1, sizes and distances ≥ 0); items using the style whose effects (fill, stroke, corners) match the style's (an item's defaults, when the style set none) take the new ones, items with their own keep them; the text of frames still in the old paragraph styles takes the new ones → {name, updated, restyled}",
has_doc,
edit_object
),
@@ -200,7 +200,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Clear Object Style Overrides",
[],
None,
"{ids?} — each item takes its object style's fill, stroke, effects and text frame options again → {changed}",
"{ids?} — each item takes its object style's fill, stroke, effects and text frame options again, and a text frame's story its paragraph style → {changed}",
super::has_selection,
clear_object_overrides
),
+1 -1
View File
@@ -309,7 +309,7 @@ fn sample_item(
return None;
}
let asset = d.assets.get(&g.asset).filter(|a| a.is_raster())?;
let img = designcraft_images::decode_rgba(&asset.data)?;
let img = designcraft_images::decode_rgba(&asset.data.load().ok()?)?;
let (pw, ph) = img.dimensions();
let px = ((gp.x / w * f64::from(pw)) as u32).min(pw.checked_sub(1)?);
let py = ((gp.y / h * f64::from(ph)) as u32).min(ph.checked_sub(1)?);
+377 -41
View File
@@ -4,6 +4,18 @@ pub(super) fn apply_object(s: &mut Session, p: &Value) -> Result<Value> {
let name = str_param(p, "name").ok_or_else(|| bad("style.object.apply", "missing name"))?.to_string();
let os = s.doc()?.doc.styles.object_style(&name).cloned().ok_or_else(|| bad("style.object.apply", format!("no object style `{name}`")))?;
let ids = crate::cmd::targets(s, p)?;
// Nothing to record when every target already has the style and its attributes, and its text
// the style's paragraph styles.
let d = &s.doc()?.doc;
let unchanged = ids.iter().filter_map(|id| d.item(*id)).all(|it| {
let mut next = it.clone();
next.object_style = name.clone();
os.apply_to(&mut next);
next == *it && it.text_frame().and_then(|tf| d.story(tf.story)).is_none_or(|st| os.story_follows(&d.styles, st))
});
if unchanged {
return Ok(Value::Null);
}
s.edit(|d, _| {
let mut stories = Vec::new();
for id in &ids {
@@ -14,12 +26,11 @@ pub(super) fn apply_object(s: &mut Session, p: &Value) -> Result<Value> {
stories.push(tf.story);
}
}
if let Some(ps) = &os.paragraph_style {
for sid in stories {
if let Some(st) = d.story_mut(sid) {
let len = st.len();
st.format_paras(0..len, |f| f.style = ps.clone());
}
// The text takes the style's paragraph style (with Apply Next Style, a chain of them).
let styles = d.styles.clone();
for sid in stories {
if let Some(st) = d.story_mut(sid) {
os.restyle(&styles, st);
}
}
Ok(Value::Null)
@@ -28,18 +39,33 @@ pub(super) fn apply_object(s: &mut Session, p: &Value) -> Result<Value> {
pub(super) fn clear_object_overrides(s: &mut Session, p: &Value) -> Result<Value> {
let ids = crate::cmd::targets(s, p)?;
// Each target with its style's attributes applied, kept only where that changes the item.
// Each target with its style's attributes applied, kept only where that changes the item;
// and a text frame's story back in the style's paragraph style, as applying the style does.
let d = &s.doc()?.doc;
let changed: Vec<Item> = ids
.iter()
.filter_map(|id| {
let it = d.item(*id)?;
let mut next = it.clone();
d.styles.object_style(&it.object_style)?.apply_to(&mut next);
(next != *it).then_some(next)
})
.collect();
if changed.is_empty() {
let mut changed: Vec<Item> = Vec::new();
let mut restyled: Vec<(designcraft_doc::StoryId, ObjectStyle)> = Vec::new();
let mut n = 0;
for id in &ids {
let Some(it) = d.item(*id) else { continue };
let Some(os) = d.styles.object_style(&it.object_style) else { continue };
let mut next = it.clone();
os.apply_to(&mut next);
let item_changed = next != *it;
if item_changed {
changed.push(next);
}
let mut story_changed = false;
if let Some(tf) = it.text_frame()
&& d.story(tf.story).is_some_and(|st| !os.story_follows(&d.styles, st))
{
story_changed = true;
if !restyled.iter().any(|(sid, _)| *sid == tf.story) {
restyled.push((tf.story, os.clone()));
}
}
n += usize::from(item_changed || story_changed);
}
if n == 0 {
return Ok(json!({"changed": 0}));
}
s.edit(|d, _| {
@@ -48,7 +74,13 @@ pub(super) fn clear_object_overrides(s: &mut Session, p: &Value) -> Result<Value
*it = next.clone();
}
}
Ok(json!({"changed": changed.len()}))
let styles = d.styles.clone();
for (sid, os) in &restyled {
if let Some(st) = d.story_mut(*sid) {
os.restyle(&styles, st);
}
}
Ok(json!({"changed": n}))
})
}
@@ -99,20 +131,35 @@ fn merge_json(base: &mut Value, top: Value, depth: usize) {
pub(super) fn create_object(s: &mut Session, p: &Value) -> Result<Value> {
let base = str_param(p, "name").unwrap_or("Object Style 1").to_string();
let from_sel = p.get("fromSelection").and_then(Value::as_bool).unwrap_or(true);
const CREATE: &str = "style.object.create";
check_swatches(CREATE, s, p)?;
let from_sel = bool_param(CREATE, p, "fromSelection")?.unwrap_or(true);
let src = if from_sel { s.doc()?.selection.items.first().and_then(|i| s.doc().ok()?.doc.item(*i).cloned()) } else { None };
let mut os = ObjectStyle::default();
if let Some(it) = &src {
os.fill = Some(it.fill.clone());
os.stroke = Some(it.stroke.clone());
os.corners = Some(it.corners.path_to_named(&it.path));
os.text_frame = it.text_frame().map(|t| t.options.clone());
os.effects = Some(it.effects.clone());
}
if let Some(sw) = str_param(p, "fill") {
os.fill = Some(designcraft_doc::Fill::swatch(sw));
if let Some(f) = fill_param(CREATE, p, os.fill.as_ref())? {
os.fill = f;
}
if let Some(ps) = str_param(p, "paragraphStyle") {
os.paragraph_style = Some(ps.to_string());
if let Some(st) = stroke_param(CREATE, p, os.stroke.as_ref())? {
os.stroke = st;
}
if let Some(c) = corners_param(CREATE, p, os.corners.unwrap_or_default())? {
os.corners = c;
}
if let Some(ps) = paragraph_style_param(CREATE, s, p)? {
os.paragraph_style = ps;
}
if let Some(next) = bool_param(CREATE, p, "applyNextStyle")? {
os.apply_next_style = next;
}
if let Some(tf) = text_frame_param(CREATE, p, os.text_frame.as_ref())? {
os.text_frame = tf;
}
if let Some(e) = effects_param("style.object.create", p, os.effects.as_ref().unwrap_or(&Effects::default()))? {
os.effects = Some(e);
@@ -125,6 +172,175 @@ pub(super) fn create_object(s: &mut Session, p: &Value) -> Result<Value> {
})
}
/// The swatches this call gives (`fill` as a name or `fill.swatch`, `stroke.swatch` and
/// `stroke.gapSwatch`) must be swatches of the document.
fn check_swatches(cmd: &str, s: &Session, p: &Value) -> Result<()> {
let doc = &s.doc()?.doc;
let given = [
("fill", p.get("fill").and_then(|f| f.as_str().or_else(|| f.get("swatch").and_then(Value::as_str)))),
("stroke", p.get("stroke").and_then(|f| f.get("swatch")).and_then(Value::as_str)),
("stroke gap", p.get("stroke").and_then(|f| f.get("gapSwatch")).and_then(Value::as_str)),
];
for (key, name) in given {
if let Some(name) = name {
crate::cmd::object::known_swatch(doc, name, cmd, key)?;
}
}
Ok(())
}
/// `paragraphStyle`: a paragraph style's name, or null (the object style sets none).
fn paragraph_style_param(cmd: &str, s: &Session, p: &Value) -> Result<Option<Option<String>>> {
match p.get("paragraphStyle") {
None => Ok(None),
Some(Value::Null) => Ok(Some(None)),
Some(Value::String(n)) if s.doc()?.doc.styles.para(n).is_some() => Ok(Some(Some(n.clone()))),
Some(Value::String(n)) => Err(bad(cmd, format!("no paragraph style `{n}`"))),
Some(_) => Err(bad(cmd, "`paragraphStyle` must be a paragraph style's name or null")),
}
}
/// `textFrame` (a text frame's General options, as `document.inspect` shows them) merged over
/// `base`, or null; refused when it names another key, the columns aren't 1–40 or a gutter, width
/// or inset isn't 0–15552 pt. `inset` is `[top, left, bottom, right]` or one number for all four.
fn text_frame_param(
cmd: &str,
p: &Value,
base: Option<&designcraft_doc::TextFrameOptions>,
) -> Result<Option<Option<designcraft_doc::TextFrameOptions>>> {
let general = designcraft_doc::TextFrameOptions::GENERAL_KEYS;
let mut p = p.clone();
if let Some(Value::Object(o)) = p.get_mut("textFrame") {
if let Some(k) = o.keys().find(|k| !general.contains(&k.as_str())) {
return Err(bad(cmd, format!("textFrame.{k} is not a General option ({})", general.join(", "))));
}
if let Some(n) = o.get("inset").filter(|v| v.is_number()).cloned() {
o.insert("inset".into(), json!([n, n, n, n]));
}
}
let tf = group_param(cmd, &p, "textFrame", base.unwrap_or(&designcraft_doc::TextFrameOptions::default()), &[])?;
if let Some(Some(o)) = &tf {
// Only the values given in this call are checked.
let given = |k: &str| p.get("textFrame").is_some_and(|t| t.get(k).is_some());
if given("columns") && !(1..=40).contains(&o.columns) {
return Err(bad(cmd, "text frame columns must be 1–40"));
}
let lengths = [("gutter", o.gutter), ("columnWidth", o.column_width), ("vjParagraphSpacingLimit", o.vj_paragraph_spacing_limit)];
let mut lengths = lengths.into_iter().filter(|(k, _)| given(k)).map(|(_, v)| v).chain(o.inset.into_iter().filter(|_| given("inset")));
if !lengths.all(|v| v.is_finite() && (0.0..=15552.0).contains(&v)) {
return Err(bad(cmd, "a text frame's gutter, widths and insets must be 0–15552 pt"));
}
}
Ok(tf)
}
/// A true/false parameter, when given.
fn bool_param(cmd: &str, p: &Value, key: &str) -> Result<Option<bool>> {
match p.get(key) {
None => Ok(None),
Some(Value::Bool(b)) => Ok(Some(*b)),
Some(_) => Err(bad(cmd, format!("`{key}` must be true or false"))),
}
}
/// `p.stroke` merged over `base` (as [`group_param`]), refused when the weight isn't a number ≥ 0,
/// the tint or gap tint isn't 0–1, or the type has a field its kind doesn't take.
fn stroke_param(cmd: &str, p: &Value, base: Option<&designcraft_doc::Stroke>) -> Result<Option<Option<designcraft_doc::Stroke>>> {
let optional = ["gapOverprint", "gradientAngle", "gradientVector"];
let base = base.cloned().unwrap_or_default();
// A type without `kind` keeps the style's kind, so it takes that kind's fields.
if let Some(t) = p.get("stroke").and_then(|s| s.get("type")) {
let base_kind = serde_json::to_value(&base.kind).ok().and_then(|k| k.get("kind").and_then(Value::as_str).map(str::to_string));
crate::cmd::object::check_stroke_type_fields(t, base_kind.as_deref(), cmd)?;
}
let st = group_param(cmd, p, "stroke", &base, &optional)?;
if let Some(Some(st)) = &st {
if !(st.weight.is_finite() && st.weight >= 0.0) {
return Err(bad(cmd, "stroke weight must be a number ≥ 0"));
}
if !(0.0..=1.0).contains(&st.tint) {
return Err(bad(cmd, "stroke tint must be 0..1"));
}
if !(0.0..=1.0).contains(&st.gap_tint) {
return Err(bad(cmd, "stroke gap tint must be 0..1"));
}
}
Ok(st)
}
/// `p[key]`, an attribute group of a style, merged field by field over `base`: `None` when not
/// given, `Some(None)` for null (the style no longer sets it). A field `base` doesn't write and
/// `optional` doesn't name is refused.
fn group_param<T: serde::Serialize + serde::de::DeserializeOwned>(
cmd: &str,
p: &Value,
key: &str,
base: &T,
optional: &[&str],
) -> Result<Option<Option<T>>> {
match p.get(key) {
None => Ok(None),
Some(Value::Null) => Ok(Some(None)),
Some(v @ Value::Object(given)) => {
let mut cur = serde_json::to_value(base).map_err(|e| bad(cmd, e.to_string()))?;
if let Some(k) = given.keys().find(|k| cur.get(k.as_str()).is_none() && !optional.contains(&k.as_str())) {
return Err(bad(cmd, format!("{key}.{k} is not a {key} setting")));
}
merge_json(&mut cur, v.clone(), 0);
serde_json::from_value(cur).map(|t| Some(Some(t))).map_err(|e| bad(cmd, format!("{key}: {e}")))
}
Some(_) => Err(bad(cmd, format!("`{key}` must be an object or null"))),
}
}
/// `fill`: a swatch name, `{swatch?, tint?}` over `base`, or null.
fn fill_param(cmd: &str, p: &Value, base: Option<&designcraft_doc::Fill>) -> Result<Option<Option<designcraft_doc::Fill>>> {
if let Some(sw) = p.get("fill").and_then(Value::as_str) {
return Ok(Some(Some(designcraft_doc::Fill::swatch(sw))));
}
let fill = group_param(cmd, p, "fill", base.unwrap_or(&designcraft_doc::Fill::default()), &["gradientAngle", "gradientVector"])?;
if let Some(Some(f)) = &fill
&& !(f.tint.is_finite() && (0.0..=1.0).contains(&f.tint))
{
return Err(bad(cmd, "fill tint must be 0–1"));
}
Ok(fill)
}
/// `corners`: `{shape?, size?}` for all four, `{corners: [{shape, size}] ×4}`, or null.
fn corners_param(
cmd: &str,
p: &Value,
base: designcraft_geom::corners::CornerOptions,
) -> Result<Option<Option<designcraft_geom::corners::CornerOptions>>> {
let Some(v) = p.get("corners") else { return Ok(None) };
if v.is_null() {
return Ok(Some(None));
}
let o = v.as_object().ok_or_else(|| bad(cmd, "`corners` must be an object or null"))?;
if let Some(k) = o.keys().find(|k| !["shape", "size", "corners"].contains(&k.as_str())) {
return Err(bad(cmd, format!("corners.{k} is not a corner setting (shape, size, corners)")));
}
let mut c = if o.contains_key("corners") {
serde_json::from_value::<designcraft_geom::corners::CornerOptions>(v.clone()).map_err(|e| bad(cmd, format!("corners: {e}")))?
} else {
base
};
if let Some(sh) = o.get("shape") {
let shape = serde_json::from_value(sh.clone()).map_err(|e| bad(cmd, format!("corner shape: {e}")))?;
c.corners.iter_mut().for_each(|k| k.shape = shape);
}
if let Some(sz) = o.get("size") {
let size = sz.as_f64().filter(|v| v.is_finite()).ok_or_else(|| bad(cmd, "corner size must be a number"))?;
c.corners.iter_mut().for_each(|k| k.size = size);
}
// Sizes given in this call must be 0–10000 pt.
if (o.contains_key("corners") || o.contains_key("size")) && !c.corners.iter().all(|k| k.size.is_finite() && (0.0..=10_000.0).contains(&k.size)) {
return Err(bad(cmd, "corner sizes must be 0–10000 pt"));
}
Ok(Some(Some(c)))
}
pub(super) fn edit_object(s: &mut Session, p: &Value) -> Result<Value> {
const CMD: &str = "style.object.edit";
let name = str_param(p, "name").ok_or_else(|| bad(CMD, "missing name"))?.to_string();
@@ -132,33 +348,153 @@ pub(super) fn edit_object(s: &mut Session, p: &Value) -> Result<Value> {
return Err(bad(CMD, format!("`{name}` can't be edited")));
}
let old = s.doc()?.doc.styles.object_style(&name).cloned().ok_or_else(|| bad(CMD, format!("no object style `{name}`")))?;
let effects = if p.get("effects").is_some_and(Value::is_null) {
check_swatches(CMD, s, p)?;
let mut new = old.clone();
if p.get("effects").is_some_and(Value::is_null) {
if EFFECT_KEYS.iter().any(|k| p.get(k).is_some()) {
return Err(bad(CMD, "`effects: null` can't be combined with effect settings"));
}
None
} else {
match effects_param(CMD, p, old.effects.as_ref().unwrap_or(&Effects::default()))? {
Some(e) => Some(e),
None => return Ok(json!({"name": name, "updated": 0})),
new.effects = None;
} else if let Some(e) = effects_param(CMD, p, old.effects.as_ref().unwrap_or(&Effects::default()))? {
new.effects = Some(e);
}
if let Some(f) = fill_param(CMD, p, old.fill.as_ref())? {
new.fill = f;
}
if let Some(st) = stroke_param(CMD, p, old.stroke.as_ref())? {
new.stroke = st;
}
if let Some(c) = corners_param(CMD, p, old.corners.unwrap_or_default())? {
new.corners = c;
}
if let Some(ps) = paragraph_style_param(CMD, s, p)? {
new.paragraph_style = ps;
}
if let Some(next) = bool_param(CMD, p, "applyNextStyle")? {
new.apply_next_style = next;
}
if let Some(tf) = text_frame_param(CMD, p, old.text_frame.as_ref())? {
new.text_frame = tf;
}
if p.get("rename").is_some_and(|r| !r.is_string()) {
return Err(bad(CMD, "`rename` must be a style name"));
}
let rename = str_param(p, "rename").map(str::trim).filter(|r| *r != name).map(str::to_string);
if let Some(r) = &rename {
let builtin = name.starts_with('[') && name.ends_with(']');
if builtin || r.is_empty() || (r.starts_with('[') && r.ends_with(']')) {
return Err(bad(CMD, format!("`{name}` can't be renamed to `{r}`")));
}
};
if effects == old.effects {
return Ok(json!({"name": name, "updated": 0}));
if s.doc()?.doc.styles.object_style(r).is_some() {
return Err(bad(CMD, format!("an object style is already named `{r}`")));
}
new.name = r.clone();
}
if new == old {
return Ok(json!({"name": name, "updated": 0, "restyled": 0}));
}
s.edit(|d, _| {
let Some(os) = d.styles_mut().object.iter_mut().find(|o| o.name == name) else {
return Err(bad(CMD, format!("no object style `{name}`")));
};
os.effects = effects.clone();
// An item follows the style while its effects are the style's. When the style didn't set
// effects before, only items without effects of their own follow (the default styles are
// on most frames).
let follows = old.effects.clone().unwrap_or_default();
let updated = match &effects {
Some(new) => d.update_items(|it| it.object_style == name && it.effects == follows, |it| it.effects = new.clone()),
None => 0,
*os = new.clone();
if let Some(r) = &rename {
let st = d.styles_mut();
for o in &mut st.object {
if o.based_on.as_deref() == Some(name.as_str()) {
o.based_on = Some(r.clone());
}
}
for n in [&mut st.default_text_frame, &mut st.default_graphic_frame] {
if *n == name {
*n = r.clone();
}
}
d.update_placed_items(|it| it.object_style == name, |it| it.object_style = r.clone());
}
// An item follows each attribute the style sets while it has the style's value. When the
// style didn't set it before, items with the default follow (the default styles are on
// most frames). An attribute the style no longer sets stays as it is on the items.
let effects = (new.effects != old.effects).then_some(new.effects.clone()).flatten().map(|e| (old.effects.clone().unwrap_or_default(), e));
let fill = (new.fill != old.fill).then_some(new.fill.clone()).flatten().map(|f| (old.fill.clone().unwrap_or_default(), f));
let stroke = (new.stroke != old.stroke).then_some(new.stroke.clone()).flatten().map(|f| (old.stroke.clone(), f));
// With no stroke in the style before, an item with no stroke (a frame's default) or a
// 1 pt black one (a drawn shape's default) follows.
let stroke_follows = |it: &Item, old: &Option<designcraft_doc::Stroke>| match old {
Some(o) => it.stroke == *o,
None => {
it.stroke == designcraft_doc::Stroke::none()
|| (matches!(it.content, designcraft_doc::Content::Unassigned) && it.stroke == designcraft_doc::Stroke::default())
}
};
Ok(json!({"name": name, "updated": updated}))
let corners = (new.corners != old.corners).then_some(new.corners).flatten().map(|c| (old.corners.unwrap_or_default(), c));
let frame =
(new.text_frame != old.text_frame).then_some(new.text_frame.clone()).flatten().map(|t| (old.text_frame.clone().unwrap_or_default(), t));
let follows = |it: &Item| {
effects.as_ref().is_some_and(|(o, _)| it.effects == *o)
|| fill.as_ref().is_some_and(|(o, _)| it.fill == *o)
|| stroke.as_ref().is_some_and(|(o, _)| stroke_follows(it, o))
|| corners.as_ref().is_some_and(|(o, _)| it.corners == o.named_to_path(&it.path))
|| frame.as_ref().is_some_and(|(o, n)| it.text_frame().is_some_and(|t| t.options.clone().follow_general(o, n)))
};
let updated = d.update_placed_items(
|it| it.object_style == new.name && follows(it),
|it| {
if let Some((o, n)) = &effects
&& it.effects == *o
{
it.effects = n.clone();
}
if let Some((o, n)) = &fill
&& it.fill == *o
{
it.fill = n.clone();
}
if let Some((o, n)) = &stroke
&& stroke_follows(it, o)
{
it.stroke = n.clone();
}
if let Some((o, n)) = &corners
&& it.corners == o.named_to_path(&it.path)
{
it.corners = n.named_to_path(&it.path);
}
// Each General option follows on its own, so a frame's own inset stays while a
// new column count reaches it.
if let Some((o, n)) = &frame
&& let Some(tf) = it.text_frame_mut()
{
tf.options.follow_general(o, n);
}
},
);
// Each paragraph of the frames using the style takes the new paragraph style (or chain)
// while it is in the old one's; when the style set none before, every paragraph does.
let mut restyled = 0;
if new.paragraph_style.is_some() && (new.paragraph_style != old.paragraph_style || new.apply_next_style != old.apply_next_style) {
// Frames on spreads and parents, in groups, and anchored in stories, table cells and
// notes (as IDML import places them).
let mut stories: Vec<_> =
d.placed_items().into_iter().filter(|i| i.object_style == new.name).filter_map(|i| i.text_frame().map(|tf| tf.story)).collect();
stories.sort_unstable();
stories.dedup();
let styles = d.styles.clone();
for sid in stories {
let changes = d.story(sid).map(|st| new.restyle_from(&old, &styles, st)).unwrap_or_default();
if !changes.is_empty()
&& let Some(st) = d.story_mut(sid)
{
for (i, w) in changes {
if let Some(f) = st.paras.get_mut(i) {
f.style = w;
}
}
st.rev = st.rev.wrapping_add(1);
restyled += 1;
}
}
}
Ok(json!({"name": new.name, "updated": updated, "restyled": restyled}))
})
}
+75 -1
View File
@@ -241,9 +241,14 @@ pub(super) fn redefine(s: &mut Session, p: &Value, paragraph: bool) -> Result<Va
let char_changes = inherited.delta(&current);
let result = s.edit(|d, _| {
if paragraph {
let before = d.styles.resolve_para_style(&name).0;
let style = d.styles_mut().para_mut(&name).ok_or_else(|| bad(command, "paragraph style no longer exists"))?;
style.para.merge(&para_changes);
style.chars.merge(&char_changes);
// Minimum ≤ Desired ≤ Maximum holds in the rows the redefinition changes, over the
// styles based on this one and the paragraphs that use them.
let rows = crate::cmd::text::justification_rows_changed(&before, &d.styles.resolve_para_style(&name).0);
check_justification_after_edit(d, &name, rows, command)?;
} else {
let style =
d.styles_mut().character.iter_mut().find(|st| st.name == name).ok_or_else(|| bad(command, "character style no longer exists"))?;
@@ -362,12 +367,24 @@ pub(super) fn apply_para(s: &mut Session, p: &Value) -> Result<Value> {
s.edit(|d, _| {
let styles = d.styles.clone();
let (style_para, style_chars) = styles.resolve_para_style(&name);
// Minimum ≤ Desired ≤ Maximum holds in each justification row the style changes in a
// paragraph, over the overrides the paragraph keeps.
let mut refused = None;
for t in &targets {
if let Some(st) = d.text_story_mut(t.story, t.cell) {
let last = if t.range.is_empty() { t.range.start } else { t.range.end.saturating_sub(1) };
let touched = st.para_at(t.range.start)..=st.para_at(last);
let before: Vec<_> = st.paras.get(touched.clone()).unwrap_or_default().iter().map(|pf| styles.resolve_para(pf).0).collect();
apply_para_in_story(st, &t.range, &name, clear, (&style_para, &style_chars), &styles);
if refused.is_none() {
refused = st.paras.get(touched).unwrap_or_default().iter().zip(&before).find_map(|(pf, old)| {
let new = styles.resolve_para(pf).0;
crate::cmd::text::justification_order_error(&new, crate::cmd::text::justification_rows_changed(old, &new))
});
}
}
}
ok()
refused.map_or_else(ok, |m| Err(bad("style.paragraph.apply", m)))
})
}
@@ -416,6 +433,50 @@ fn continue_numbering(p: Option<&Value>, para: &mut ParaAttrs) {
}
}
/// After an edit of paragraph style `name`: Minimum ≤ Desired ≤ Maximum in `rows` for the style,
/// the styles based on it and the story paragraphs that use any of them.
fn check_justification_after_edit(d: &designcraft_doc::Document, name: &str, rows: [bool; 3], command_id: &str) -> Result<()> {
if !rows.contains(&true) {
return Ok(());
}
let styles = &d.styles;
let affected: Vec<&str> = styles.paragraph.iter().map(|st| st.name.as_str()).filter(|n| styles.para_based_on_cycles(name, n)).collect();
for n in &affected {
if let Some(m) = crate::cmd::text::justification_order_error(&styles.resolve_para_style(n).0, rows) {
return Err(bad(command_id, if *n == name { m } else { format!("paragraph style {n:?}: {m}") }));
}
}
for st in d.stories.values() {
let mut check = |pf: &designcraft_doc::ParaFormat| {
if affected.contains(&pf.style.as_str()) { crate::cmd::text::justification_order_error(&styles.resolve_para(pf).0, rows) } else { None }
};
if let Some(m) = first_in_nested_paras(st, &mut check) {
return Err(bad(command_id, format!("a paragraph of story {}: {m}", st.id.0)));
}
}
Ok(())
}
/// The first answer `f` gives for a paragraph of `story`, its table cells, footnotes or endnotes,
/// at any depth. The walk keeps its own stack, so a deeply nested document can't exhaust the
/// call stack.
fn first_in_nested_paras(story: &designcraft_doc::Story, f: &mut impl FnMut(&designcraft_doc::ParaFormat) -> Option<String>) -> Option<String> {
let mut pending = vec![story];
while let Some(story) = pending.pop() {
if let Some(m) = story.paras.iter().find_map(&mut *f) {
return Some(m);
}
pending.extend(story.tables.values().flat_map(|t| t.cells.iter().map(|c| &c.text)));
pending.extend(story.notes.iter().chain(&story.endnotes).map(|n| &n.text));
}
None
}
/// The justification rows the `para` object of `p` sets or clears.
fn justification_rows_given(p: &Value) -> [bool; 3] {
crate::cmd::text::justification_rows_named(p.get("para").and_then(Value::as_object).into_iter().flat_map(|o| o.keys().map(String::as_str)))
}
/// The style `p[key]` names: none when absent or null; anything but a name is refused.
fn style_name_param(cmd: &str, p: &Value, key: &str) -> Result<Option<String>> {
match p.get(key) {
@@ -434,6 +495,7 @@ pub(super) fn create_para(s: &mut Session, p: &Value) -> Result<Value> {
continue_numbering(p.get("para"), &mut para);
explicit_default_kinsoku(&mut para, p.get("para"));
check_grep_styles("style.paragraph.create", &para)?;
let mut rows = justification_rows_given(p);
let mut chars: CharAttrs = attrs("style.paragraph.create", "chars", p, |a: &mut CharAttrs, k, v| a.set_json(k, v))?;
// Validate caller-supplied fills, not selection fills retained after a swatch is deleted.
crate::cmd::text::validate_char_fill(&s.doc()?.doc, &chars, "style.paragraph.create")?;
@@ -445,6 +507,7 @@ pub(super) fn create_para(s: &mut Session, p: &Value) -> Result<Value> {
let mut full = ParaProps_to_attrs(&pp);
full.merge(&para);
para = full;
rows = [true; 3];
}
if let Ok(cp) = serde_json::from_value::<designcraft_doc::CharProps>(cur["chars"].clone()) {
let mut full = CharProps_to_attrs(&cp);
@@ -452,6 +515,8 @@ pub(super) fn create_para(s: &mut Session, p: &Value) -> Result<Value> {
chars = full;
}
}
// The values taken from the selection are checked with the given ones.
crate::cmd::text::validate_para_values(&para, "style.paragraph.create")?;
s.edit(|d, _| {
let name = Styles::unique_name(|n| d.styles.para(n).is_some(), &base);
if let Some(b) = &based_on
@@ -467,6 +532,9 @@ pub(super) fn create_para(s: &mut Session, p: &Value) -> Result<Value> {
return Err(bad("style.paragraph.create", format!("no style `{n}`")));
}
d.styles_mut().paragraph.push(ParagraphStyle { name: name.clone(), based_on, next_style: next, para, chars, shortcut: String::new() });
// Minimum ≤ Desired ≤ Maximum holds over what the style resolves to.
let (resolved, _) = d.styles.resolve_para_style(&name);
crate::cmd::text::validate_justification_order(&resolved, rows, "style.paragraph.create")?;
Ok(json!({"name": name}))
})
}
@@ -578,9 +646,15 @@ pub(super) fn edit_para(s: &mut Session, p: &Value) -> Result<Value> {
continue_numbering(p.get("para"), &mut para);
explicit_default_kinsoku(&mut para, p.get("para"));
check_grep_styles("style.paragraph.edit", &para)?;
crate::cmd::text::validate_para_values(&para, "style.paragraph.edit")?;
let st = d.styles_mut().para_mut(&name).ok_or_else(|| bad("style.paragraph.edit", format!("no style `{name}`")))?;
st.para.merge(&para);
st.chars.merge(&chars);
// Minimum ≤ Desired ≤ Maximum holds over what the style resolves to: in the rows the edit
// names, or in every row when it changes Based On or resets the style.
let rows = if reset || based.is_some() { [true; 3] } else { justification_rows_given(p) };
check_justification_after_edit(d, &name, rows, "style.paragraph.edit")?;
let st = d.styles_mut().para_mut(&name).ok_or_else(|| bad("style.paragraph.edit", format!("no style `{name}`")))?;
match next {
Some(Value::String(n)) => st.next_style = Some(n),
Some(Value::Null) => st.next_style = None,
+16 -15
View File
@@ -62,9 +62,10 @@ pub(super) fn drop_cells(s: &mut Session, p: &Value) -> Result<Value> {
pub(super) fn place_graphic(s: &mut Session, p: &Value) -> Result<Value> {
const ID: &str = "table.placeGraphic";
let g = target(s, p, ID)?;
let (bytes, name, link) = crate::cmd::file::read_source(p)?;
let (pw, ph) = designcraft_render::image_size(&bytes).ok_or_else(|| bad(ID, "unsupported or corrupt image"))?;
let (nw, nh) = designcraft_render::natural_size(&bytes, 0).ok_or_else(|| bad(ID, "invalid image dimensions"))?;
let source = crate::cmd::file::read_source(p)?;
let bytes = &source.bytes;
let (pw, ph) = designcraft_render::image_size(bytes).ok_or_else(|| bad(ID, "unsupported or corrupt image"))?;
let (nw, nh) = designcraft_render::natural_size(bytes, 0).ok_or_else(|| bad(ID, "invalid image dimensions"))?;
let fill = p.get("fit").and_then(Value::as_str) == Some("fill");
// Compute fitting before the edit: a small EPS can overflow in a huge cell.
let t = s.doc()?.doc.story(g.story).and_then(|st| st.tables.get(&g.table)).ok_or_else(|| bad(ID, "no table"))?;
@@ -78,18 +79,16 @@ pub(super) fn place_graphic(s: &mut Session, p: &Value) -> Result<Value> {
let k = if fill { (bw / nw).max(bh / nh) } else { (bw / nw).min(bh / nh) };
let xf = designcraft_geom::Affine::translate(((bw - nw * k) / 2.0, (bh - nh * k) / 2.0)) * designcraft_geom::Affine::scale(k);
crate::cmd::file::validate_placement((nw, nh), designcraft_geom::Rect::new(0.0, 0.0, bw, bh), xf, ID)?;
s.edit(|d, sel| {
let mut asset = designcraft_doc::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, crate::cmd::file::document_of(s).as_deref());
let placed = s.edit(|d, sel| {
let fresh = designcraft_doc::AssetId(d.alloc());
let mime = designcraft_render::image_mime(&bytes).to_string();
let aid = d.add_asset(designcraft_doc::Asset {
id: fresh,
name,
mime,
link,
data: std::sync::Arc::new(bytes),
pixels: Some((pw, ph)),
..Default::default()
});
let aid = d.add_asset(designcraft_doc::Asset { id: fresh, ..asset });
let st = d.story_mut(g.story).ok_or_else(|| bad(ID, "no story"))?;
let t = st.table_mut(g.table).ok_or_else(|| bad(ID, "no table"))?;
let cell = t.cell_mut(r, c).ok_or_else(|| bad(ID, format!("no cell {r},{c}")))?;
@@ -107,7 +106,9 @@ pub(super) fn place_graphic(s: &mut Session, p: &Value) -> Result<Value> {
});
clamp_selection(d, sel);
Ok(json!({"asset": aid.0, "row": r, "col": c}))
})
})?;
crate::cmd::file::prepare_placed(s, pending);
Ok(placed)
}
pub(super) fn sort_rows(s: &mut Session, p: &Value) -> Result<Value> {
+17 -13
View File
@@ -70,19 +70,23 @@ pub(super) fn get(s: &mut Session, p: &Value) -> Result<Value> {
let g = target(s, p, "table.get")?;
let st = s.doc()?;
let t = st.doc.story(g.story).and_then(|x| x.tables.get(&g.table)).ok_or_else(|| bad("table.get", "no table"))?;
let owners = t.owners();
let cells: Vec<Value> = (0..t.nrows())
.flat_map(|r| (0..t.ncols()).map(move |c| (r, c)))
.filter(|&(r, c)| owners[r * t.ncols() + c] == (r, c))
.filter_map(|(r, c)| {
let cell = t.cell(r, c)?;
Some(json!({"row": r, "col": c, "rowSpan": cell.row_span, "colSpan": cell.col_span, "text": cell.text.text, "fill": cell.fill,
"insets": cell.insets, "vj": cell.vj, "firstBaseline": cell.first_baseline, "firstBaselineMin": cell.first_baseline_min, "rotation": cell.rotation, "style": cell.style}))
})
.collect();
Ok(json!({
let mut out = json!({
"story": g.story.0, "table": g.table, "anchor": st.doc.story(g.story).and_then(|x| x.table_anchor(g.table)),
"rows": t.rows, "columns": t.columns, "headerRows": t.header_rows(), "footerRows": t.footer_rows(),
"cells": cells, "options": t.options, "range": g.range, "style": t.style,
}))
"options": t.options, "range": g.range, "style": t.style,
});
if p.get("cells").and_then(Value::as_bool) != Some(false) {
let owners = t.owners();
let cells: Vec<Value> = (0..t.nrows())
.flat_map(|r| (0..t.ncols()).map(move |c| (r, c)))
.filter(|&(r, c)| owners[r * t.ncols() + c] == (r, c))
.filter_map(|(r, c)| {
let cell = t.cell(r, c)?;
Some(json!({"row": r, "col": c, "rowSpan": cell.row_span, "colSpan": cell.col_span, "text": cell.text.text, "fill": cell.fill,
"insets": cell.insets, "vj": cell.vj, "firstBaseline": cell.first_baseline, "firstBaselineMin": cell.first_baseline_min, "rotation": cell.rotation, "style": cell.style}))
})
.collect();
out["cells"] = json!(cells);
}
Ok(out)
}
+12 -3
View File
@@ -1,7 +1,7 @@
use super::cell::{get_cell_stroke, set_cell};
use super::content::{drop_cells, place_graphic, sort_rows};
use super::options::{get, options};
use super::selection::{move_rc, select, step_cell, toggle_selection};
use super::selection::{go_to_row, move_rc, select, step_cell, toggle_selection};
use super::sizing::{distribute_cols, distribute_rows, resize_border, set_col_width, set_row_height};
use super::structure::{
can_convert_rows, convert_from_text, convert_rows, convert_to_text, delete_cols, delete_rows, delete_table, insert, insert_col, insert_row,
@@ -210,7 +210,7 @@ fn table_specs() -> Vec<CommandSpec> {
"Convert Cell to Graphic Cell",
["Table"],
None,
"{path? | base64?, name?: with base64, fit?: proportional|fill (default proportional), story?, table?, rows?: [a, b] | row?, cols?: [a, b] | col? (the target cells; default: the selection)} — an image in the target cell (its text is kept but hidden)",
"{path? | base64?, name?: with base64, embed? (keep the bytes in the document; default: an image from a path links to its file), fit?: proportional|fill (default proportional), story?, table?, rows?: [a, b] | row?, cols?: [a, b] | col? (the target cells; default: the selection)} — an image in the target cell (its text is kept but hidden)",
in_table,
place_graphic
),
@@ -396,6 +396,15 @@ fn table_specs() -> Vec<CommandSpec> {
cmd!(noundo "table.selectColumn", "Select Column", ["Table", "Select"], None, "{story?, table?, rows?: [a, b] | row?, cols?: [a, b] | col? (the target cells; default: the selection)}", in_table, |s, p| {
select(s, &crate::cmd::with_param(p, "what", json!("column")))
}),
cmd!(
noundo "table.goToRow",
"Go to Row…",
["Table"],
None,
"{row: number (from 1, counted within the section), section?: header|body|footer (default: body), story?, table?}: selects the row → {story, table, range, page: the document page showing the row (from 1), spread: {kind: doc|parent, index} of the spread showing it, rowBounds: [x0, y0, x1, y1] of the row on that spread; each null when the row is overset, and page on a parent spread}",
in_table_or_ids,
go_to_row
),
cmd!(noundo "table.nextCell", "Next Cell", [], None, "{}", in_cell, |s, _| step_cell(s, true)),
cmd!(noundo "table.prevCell", "Previous Cell", [], None, "{}", in_cell, |s, _| step_cell(s, false)),
cmd!(
@@ -407,6 +416,6 @@ fn table_specs() -> Vec<CommandSpec> {
in_cell,
|s, _| toggle_selection(s)
),
cmd!(query "table.get", "Get Table", [], None, "{story?, table?, rows?: [a,b] | row?, cols?: [a,b] | col?} → rows, columns, cells (text, spans, fill), options", in_table_or_ids, get),
cmd!(query "table.get", "Get Table", [], None, "{story?, table?, rows?: [a,b] | row?, cols?: [a,b] | col?, cells?: bool (false leaves out the cells)} → rows, columns, cells (text, spans, fill), options. Supplied `story` and `table` values must be nonnegative integer IDs. When a table ID occurs in multiple stories, supply `story` with `table`.", in_table_or_ids, get),
]
}
+318 -2
View File
@@ -24,16 +24,113 @@ pub(super) fn select(s: &mut Session, p: &Value) -> Result<Value> {
_ => {}
}
let st = s.doc_mut()?;
let frame = st.selection.text.and_then(|t| t.frame);
// The caret goes in the cell that covers the range's first position, a merged one included.
let (row, col) = st.doc.story(g.story).and_then(|x| x.tables.get(&g.table)).map_or((r.r0, r.c0), |t| t.owner(r.r0, r.c0));
// The caret's frame is kept only within the same story.
let frame = st.selection.text.filter(|t| t.story == g.story).and_then(|t| t.frame);
st.selection = Selection {
cells: Some(TableSel { story: g.story, table: g.table, range: r }),
text: Some(TextSel { story: g.story, anchor: 0, focus: 0, frame, cell: Some(CellAddr { table: g.table, row: r.r0, col: r.c0 }) }),
text: Some(TextSel { story: g.story, anchor: 0, focus: 0, frame, cell: Some(CellAddr { table: g.table, row, col }) }),
..Default::default()
};
st.bump_revision();
Ok(json!({"story": g.story.0, "table": g.table, "range": r}))
}
/// Table › Go to Row…: select row `row` (from 1) of the header, body or footer rows.
pub(super) fn go_to_row(s: &mut Session, p: &Value) -> Result<Value> {
const ID: &str = "table.goToRow";
// Only the table comes from `p`: `row` here counts within a section, not from the table's top.
let mut at = serde_json::Map::new();
for key in ["story", "table"] {
if let Some(v) = p.get(key) {
at.insert(key.into(), v.clone());
}
}
let g = target(s, &Value::Object(at), ID)?;
let n = p.get("row").and_then(Value::as_u64).filter(|&n| n >= 1).ok_or_else(|| bad(ID, "row must be a whole number from 1"))?;
let (index, owners, nc) = {
let st = s.doc()?;
let t = st.doc.story(g.story).and_then(|x| x.tables.get(&g.table)).ok_or_else(|| bad(ID, "no table"))?;
let (h, f, nr) = (t.header_rows(), t.footer_rows(), t.nrows());
let (section, first, count) = match str_param(p, "section").unwrap_or("body") {
"header" => ("header", 0, h),
"body" => ("body", h, nr.saturating_sub(h + f)),
"footer" => ("footer", nr.saturating_sub(f), f),
other => return Err(bad(ID, format!("unknown section `{other}` (header, body or footer)"))),
};
if count == 0 {
return Err(bad(ID, format!("the table has no {section} rows")));
}
let n = usize::try_from(n).unwrap_or(usize::MAX);
if n > count {
return Err(bad(ID, format!("row {n} is past the last of the table's {count} {section} rows")));
}
(first + n - 1, t.owners(), t.ncols())
};
let r = select(s, &json!({"story": g.story.0, "table": g.table, "rows": [index, index], "what": "row"}))?;
// The page of the frame that shows the row: the cells that start in it or reach it from above.
let start = index.saturating_mul(nc);
let cells: Vec<(usize, usize)> = owners.get(start..start.saturating_add(nc)).map(<[_]>::to_vec).unwrap_or_default();
let st = s.doc()?;
let cs = s.cache.get(&st.doc, g.story, None);
// The part of the table that shows the row, its frame, and the cells that cover the row there.
let placed = cs.frames.iter().find_map(|ft| {
ft.tables.iter().filter(|t| t.table == g.table).find_map(|t| {
let covering: Vec<designcraft_geom::Rect> =
t.cells.iter().filter(|c| !c.repeated && cells.contains(&(c.row, c.col))).map(|c| c.rect).collect();
(!covering.is_empty()).then_some((ft.frame, t, covering))
})
});
let frame = placed.as_ref().map(|(f, _, _)| *f);
let on_spread = frame.and_then(|f| frame_on_spread(&st.doc, &s.cache, g.story, f));
// The document page under the row's first cell: a frame can span two pages of a spread.
let page = placed.as_ref().zip(on_spread).and_then(|((_, _, covering), (spread, xf))| {
let designcraft_doc::SpreadRef::Doc(si) = spread else { return None };
let at = xf * covering.first()?.center();
Some(st.doc.first_page_of_spread(si) + st.doc.spreads.get(si)?.page_at_x(at.x).unwrap_or(0) + 1)
});
// The row on its spread: across, the cells that cover it; from top to bottom, the row alone, also
// inside cells merged across several rows.
let bounds = placed.as_ref().zip(on_spread).and_then(|((_, t, covering), (_, xf))| {
let across = covering.iter().copied().reduce(|a, b| a.union(b))?;
let &(_, top, bottom) = t.rows.iter().find(|r| r.0 == index)?;
Some(xf.transform_rect_bbox(designcraft_geom::Rect::new(across.x0, top, across.x1, bottom)))
});
let spread = on_spread.map(|(si, _)| si);
// The caret is shown in the frame that shows the row, and in no frame when the row is overset.
if let Some(t) = s.doc_mut()?.selection.text.as_mut() {
t.frame = frame;
}
Ok(json!({
"story": r["story"],
"table": r["table"],
"range": r["range"],
"page": page,
"spread": spread,
"rowBounds": bounds.map(|b| [b.x0, b.y0, b.x1, b.y1]),
}))
}
/// The spread (a document or parent spread) that text frame `frame` of story `sid` is on, and the
/// transform from the frame's inner space to that spread's coordinates. An anchored frame is where
/// its host story places it.
fn frame_on_spread(
doc: &designcraft_doc::Document,
cache: &designcraft_compose::Cache,
sid: StoryId,
frame: designcraft_doc::ItemId,
) -> Option<(designcraft_doc::SpreadRef, designcraft_geom::Affine)> {
let (spread, parent, it) = match doc.find(frame) {
Some(loc) => (loc.spread, doc.parent_xf(&loc), doc.item_at(&loc)?),
None => {
let p = cache.placement(doc, sid, frame)?;
(p.spread, p.xf, doc.anchored_item(frame)?)
}
};
Some((spread, parent * doc.text_xf(it)))
}
/// Move the caret to the next/previous cell (Tab / Shift-Tab), selecting its text. Tab in the last
/// cell adds a row.
pub(crate) fn step_cell(s: &mut Session, forward: bool) -> Result<Value> {
@@ -138,3 +235,222 @@ pub(super) fn move_rc(s: &mut Session, p: &Value, rows: bool) -> Result<Value> {
Ok(json!({"from": from, "to": to}))
})
}
#[cfg(test)]
mod go_to_row_tests {
use designcraft_doc::CellRange;
use serde_json::json;
use crate::Session;
/// A table of 1 header, 3 body and 1 footer rows, 2 columns wide, with the caret in its first cell.
fn session() -> Session {
let mut s = Session::new();
s.execute("file.new", &json!({})).unwrap();
let r = s.execute("frame.create", &json!({"rect": [72, 72, 500, 700], "content": "text", "text": ""})).unwrap();
s.execute("text.select", &json!({"story": r["story"], "anchor": 0, "focus": 0})).unwrap();
s.execute("table.insert", &json!({"rows": 3, "cols": 2, "headerRows": 1, "footerRows": 1})).unwrap();
s
}
fn selected(s: &Session) -> CellRange {
s.doc().unwrap().selection.cells.unwrap().range
}
#[test]
fn go_to_row_selects_a_row_counted_within_its_section() {
let mut s = session();
let r = s.execute("table.goToRow", &json!({"row": 2})).unwrap();
assert_eq!(selected(&s), CellRange { r0: 2, c0: 0, r1: 2, c1: 1 }, "the second body row, under the header row");
assert_eq!(r["page"], 1);
s.execute("table.goToRow", &json!({"row": 1, "section": "header"})).unwrap();
assert_eq!(selected(&s), CellRange { r0: 0, c0: 0, r1: 0, c1: 1 });
s.execute("table.goToRow", &json!({"row": 1, "section": "footer"})).unwrap();
assert_eq!(selected(&s), CellRange { r0: 4, c0: 0, r1: 4, c1: 1 });
s.execute("table.goToRow", &json!({"row": 3, "section": "body"})).unwrap();
assert_eq!(selected(&s), CellRange { r0: 3, c0: 0, r1: 3, c1: 1 });
// The caret goes to the row's first cell.
assert_eq!(s.doc().unwrap().selection.text.and_then(|t| t.cell).map(|c| (c.row, c.col)), Some((3, 0)));
}
#[test]
fn go_to_row_refuses_rows_outside_the_section() {
let mut s = session();
s.execute("table.goToRow", &json!({"row": 1})).unwrap();
let before = selected(&s);
for p in [
json!({"row": 4}),
json!({"row": 0}),
json!({"row": -1}),
json!({"row": "2"}),
json!({}),
json!({"row": 2, "section": "footer"}),
json!({"row": 1, "section": "side"}),
] {
assert!(s.execute("table.goToRow", &p).is_err(), "{p}");
assert_eq!(selected(&s), before, "{p} leaves the selection");
}
s.execute("table.options", &json!({"headerRows": 0, "footerRows": 0})).unwrap();
assert!(s.execute("table.goToRow", &json!({"row": 1, "section": "header"})).is_err());
assert!(s.execute("table.goToRow", &json!({"row": 1, "section": "footer"})).is_err());
}
#[test]
fn go_to_row_selects_a_row_of_a_named_table_outside_the_selection() {
let mut s = session();
let t = s.execute("table.get", &json!({})).unwrap();
let other = s.execute("frame.create", &json!({"rect": [72, 720, 500, 760], "content": "text", "text": "Notes"})).unwrap();
// A click in the other frame: the caret is shown in that frame.
s.execute("text.placeCaret", &json!({"frame": other["id"], "point": [80, 730]})).unwrap();
assert_eq!(s.doc().unwrap().selection.text.and_then(|t| t.frame).map(|f| f.0), other["id"].as_u64());
assert!(s.execute("table.goToRow", &json!({"row": 2})).is_err(), "no table named and none selected");
s.execute("table.goToRow", &json!({"story": t["story"], "table": t["table"], "row": 2})).unwrap();
assert_eq!(selected(&s), CellRange { r0: 2, c0: 0, r1: 2, c1: 1 });
let frame = s.doc().unwrap().selection.text.and_then(|t| t.frame).map(|f| f.0);
assert_ne!(frame, other["id"].as_u64(), "the caret is not left in the other story's frame");
// table.select naming the table from another story does not keep that story's frame either.
s.execute("text.placeCaret", &json!({"frame": other["id"], "point": [80, 730]})).unwrap();
s.execute("table.select", &json!({"story": t["story"], "table": t["table"], "what": "table"})).unwrap();
let frame = s.doc().unwrap().selection.text.and_then(|t| t.frame).map(|f| f.0);
assert_ne!(frame, other["id"].as_u64());
}
#[test]
fn go_to_row_names_the_page_that_shows_the_row() {
let mut s = Session::new();
s.execute("file.new", &json!({"pages": 2, "facingPages": false})).unwrap();
let a = s.execute("frame.create", &json!({"rect": [72, 72, 400, 200], "content": "text", "text": ""})).unwrap();
let b = s.execute("frame.create", &json!({"spread": 1, "rect": [72, 72, 400, 600], "content": "unassigned"})).unwrap();
s.execute("text.thread", &json!({"from": a["id"], "to": b["id"]})).unwrap();
s.execute("text.select", &json!({"story": a["story"], "anchor": 0, "focus": 0})).unwrap();
s.execute("table.insert", &json!({"rows": 20, "cols": 2, "headerRows": 1})).unwrap();
for row in 0..21 {
s.execute("table.setRowHeight", &json!({"row": row, "height": 20, "mode": "exactly"})).unwrap();
}
assert_eq!(s.execute("table.goToRow", &json!({"row": 1})).unwrap()["page"], 1);
assert_eq!(s.execute("table.goToRow", &json!({"row": 20})).unwrap()["page"], 2);
let frame = s.doc().unwrap().selection.text.and_then(|t| t.frame).map(|f| f.0);
assert_eq!(frame, b["id"].as_u64(), "the caret is in the frame that shows the row");
// The row on its spread: one row tall, in the frame on the second spread.
let r = s.execute("table.goToRow", &json!({"row": 20})).unwrap();
assert_eq!(r["spread"], json!({"kind": "doc", "index": 1}));
let at: Vec<f64> = r["rowBounds"].as_array().map(|a| a.iter().filter_map(serde_json::Value::as_f64).collect()).unwrap_or_default();
assert!(at.len() == 4 && (at[3] - at[1] - 20.0).abs() < 1e-6 && at[0] >= 72.0 && at[2] <= 401.0 && at[1] >= 72.0 && at[3] <= 600.0, "{at:?}");
// The header row repeats on page 2; the row itself is the one on page 1.
assert_eq!(s.execute("table.goToRow", &json!({"row": 1, "section": "header"})).unwrap()["page"], 1);
}
#[test]
fn go_to_row_leaves_no_caret_frame_for_an_overset_row() {
let mut s = Session::new();
s.execute("file.new", &json!({})).unwrap();
let a = s.execute("frame.create", &json!({"rect": [72, 72, 400, 200], "content": "text", "text": ""})).unwrap();
s.execute("text.select", &json!({"story": a["story"], "anchor": 0, "focus": 0})).unwrap();
s.execute("table.insert", &json!({"rows": 20, "cols": 2})).unwrap();
for row in 0..20 {
s.execute("table.setRowHeight", &json!({"row": row, "height": 20, "mode": "exactly"})).unwrap();
}
let frame = |s: &Session| s.doc().unwrap().selection.text.and_then(|t| t.frame).map(|f| f.0);
s.execute("table.goToRow", &json!({"row": 1})).unwrap();
assert_eq!(frame(&s), a["id"].as_u64());
let r = s.execute("table.goToRow", &json!({"row": 20})).unwrap();
assert_eq!((r["page"].clone(), r["spread"].clone()), (json!(null), json!(null)), "{r}");
assert_eq!(frame(&s), None, "no frame shows the overset row");
}
#[test]
fn go_to_row_puts_the_caret_in_a_merged_cell_that_covers_the_row() {
let mut s = session();
// Body rows 1 and 2 (table rows 1 and 2) share one merged cell in column 0.
s.execute("table.merge", &json!({"rows": [1, 2], "col": 0})).unwrap();
s.execute("table.goToRow", &json!({"row": 2})).unwrap();
assert_eq!(selected(&s), CellRange { r0: 2, c0: 0, r1: 2, c1: 1 });
assert_eq!(s.doc().unwrap().selection.text.and_then(|t| t.cell).map(|c| (c.row, c.col)), Some((1, 0)));
}
#[test]
fn go_to_row_bounds_a_row_inside_cells_merged_across_rows() {
let mut s = session();
for (row, height) in [20, 10, 40, 20, 20].into_iter().enumerate() {
s.execute("table.setRowHeight", &json!({"row": row, "height": height, "mode": "exactly"})).unwrap();
}
// Every column's cell covers body rows 1 to 3 (table rows 1 to 3), so no cell starts in body row 2.
s.execute("table.merge", &json!({"rows": [1, 3], "cols": [0, 0]})).unwrap();
s.execute("table.merge", &json!({"rows": [1, 3], "cols": [1, 1]})).unwrap();
let bounds = |s: &mut Session, p: serde_json::Value| -> Vec<f64> {
let r = s.execute("table.goToRow", &p).unwrap();
r["rowBounds"].as_array().map(|a| a.iter().filter_map(serde_json::Value::as_f64).collect()).unwrap_or_default()
};
let header = bounds(&mut s, json!({"row": 1, "section": "header"}));
let row = bounds(&mut s, json!({"row": 2}));
assert_eq!((header.len(), row.len()), (4, 4));
assert!((row[1] - (header[3] + 10.0)).abs() < 1e-6 && (row[3] - row[1] - 40.0).abs() < 1e-6, "{header:?} {row:?}");
assert_eq!((row[0], row[2]), (header[0], header[2]), "the row spans the table across");
}
#[test]
fn go_to_row_finds_a_row_in_an_anchored_text_frame() {
use designcraft_doc::{AnchorPosition, AnchoredObject, Content, Item, ItemId, Shape, Story, StoryId, TextFrame};
let mut s = Session::new();
s.execute("file.new", &json!({})).unwrap();
let host = s.execute("frame.create", &json!({"rect": [72, 72, 500, 400], "content": "text", "text": "Host text"})).unwrap();
// A text frame anchored in the host's text, its own story holding the table.
let sid = {
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
let (fid, sid) = (ItemId(d.alloc()), StoryId(d.alloc()));
let mut story = Story::with_text(sid, "", Default::default());
story.frames.push(fid);
d.stories.insert(sid, std::sync::Arc::new(story));
let layer = d.item(ItemId(host["id"].as_u64().unwrap())).unwrap().layer;
let mut it =
Item::new(fid, layer, Shape::Rectangle, designcraft_geom::shapes::rectangle(designcraft_geom::Rect::new(0.0, 0.0, 200.0, 100.0)));
it.content = Content::Text(TextFrame { story: sid, options: Default::default() });
let host_story = StoryId(host["story"].as_u64().unwrap());
d.story_mut(host_story).unwrap().insert_object(4, AnchoredObject::new(it, AnchorPosition::default()));
sid
};
s.execute("text.select", &json!({"story": sid.0, "anchor": 0, "focus": 0})).unwrap();
s.execute("table.insert", &json!({"rows": 2, "cols": 2})).unwrap();
let r = s.execute("table.goToRow", &json!({"row": 2})).unwrap();
assert_eq!((r["page"].clone(), r["spread"].clone()), (json!(1), json!({"kind": "doc", "index": 0})), "{r}");
assert_eq!(r["rowBounds"].as_array().map(Vec::len), Some(4), "{r}");
}
#[test]
fn go_to_row_finds_a_row_on_a_parent_spread() {
let mut s = Session::new();
s.execute("file.new", &json!({})).unwrap();
let f = s
.execute("frame.create", &json!({"spread": {"kind": "parent", "index": 0}, "rect": [72, 72, 400, 400], "content": "text", "text": ""}))
.unwrap();
s.execute("text.select", &json!({"story": f["story"], "anchor": 0, "focus": 0})).unwrap();
s.execute("table.insert", &json!({"rows": 2, "cols": 2})).unwrap();
let r = s.execute("table.goToRow", &json!({"row": 2})).unwrap();
assert_eq!((r["page"].clone(), r["spread"].clone()), (json!(null), json!({"kind": "parent", "index": 0})), "{r}");
assert_eq!(r["rowBounds"].as_array().map(Vec::len), Some(4), "{r}");
}
#[test]
fn table_get_without_cells_reads_the_rows_alone() {
// The Go to Row dialog reads the row counts and the selection, not every cell's text.
let mut s = session();
s.execute("table.goToRow", &json!({"row": 2})).unwrap();
let t = s.execute("table.get", &json!({"cells": false})).unwrap();
assert!(t.get("cells").is_none(), "{t}");
assert_eq!((t["headerRows"].clone(), t["footerRows"].clone(), t["range"]["r0"].clone()), (json!(1), json!(1), json!(2)));
assert_eq!(t["rows"].as_array().map(Vec::len), Some(5));
assert_eq!(s.execute("table.get", &json!({})).unwrap()["cells"].as_array().map(Vec::len), Some(10));
}
#[test]
fn go_to_row_names_the_page_under_the_row_in_a_frame_across_the_spine() {
let mut s = Session::new();
s.execute("file.new", &json!({"pages": 3, "facingPages": true})).unwrap();
// Pages 2 and 3 meet at x = 612; the frame's center is on page 3, the narrow table on page 2.
let f = s.execute("frame.create", &json!({"spread": 1, "rect": [400, 72, 900, 400], "content": "text", "text": ""})).unwrap();
s.execute("text.select", &json!({"story": f["story"], "anchor": 0, "focus": 0})).unwrap();
s.execute("table.insert", &json!({"rows": 2, "cols": 2})).unwrap();
s.execute("table.setColumnWidth", &json!({"cols": [0, 1], "width": 50})).unwrap();
assert_eq!(s.execute("table.goToRow", &json!({"row": 2})).unwrap()["page"], 2);
}
}
+6 -1
View File
@@ -133,6 +133,11 @@ fn reapply_cell_styles(d: &mut Document, names: &[String]) {
/// Include descendants when editing an inherited style, with the resolver's depth limit.
fn dependent_styles<'a>(name: &str, styles: impl Iterator<Item = (&'a str, Option<&'a str>)>) -> Vec<String> {
let styles: Vec<_> = styles.collect();
// The first style of a name is the one, as the resolver's lookup finds it.
let mut based_on: std::collections::HashMap<&str, Option<&str>> = std::collections::HashMap::new();
for (n, base) in &styles {
based_on.entry(n).or_insert(*base);
}
styles
.iter()
.filter(|(candidate, _)| {
@@ -142,7 +147,7 @@ fn dependent_styles<'a>(name: &str, styles: impl Iterator<Item = (&'a str, Optio
if current_name == name {
return true;
}
current = styles.iter().find(|(n, _)| *n == current_name).and_then(|(_, base)| *base);
current = based_on.get(current_name).copied().flatten();
}
false
})
+24 -6
View File
@@ -8,10 +8,12 @@ use super::{
pub(super) fn in_table(s: &Session) -> std::result::Result<(), String> {
has_doc(s)?;
let st = s.active().ok_or("no document open")?;
if st.selection.cells.is_some() || st.selection.text.is_some_and(|t| t.cell.is_some()) {
// Footnote text is addressed as a cell too, but isn't in a table.
if st.selection.cells.is_some() || st.selection.text.is_some_and(|t| t.cell.is_some_and(|c| c.footnote_id().is_none())) {
return Ok(());
}
if let Some(t) = st.selection.text
&& t.cell.is_none()
&& st.doc.story(t.story).is_some_and(|x| x.table_at(t.focus).is_some())
{
return Ok(());
@@ -41,8 +43,20 @@ pub(super) struct Tgt {
pub(super) range: CellRange,
}
fn find_table(doc: &Document, id: u64) -> Option<StoryId> {
doc.stories.iter().find(|(_, s)| s.tables.contains_key(&id)).map(|(k, _)| *k)
fn find_table(doc: &Document, id: u64, cmd: &str) -> Result<StoryId> {
let mut stories = doc.stories.iter().filter(|(_, story)| story.tables.contains_key(&id)).map(|(sid, _)| *sid);
let first = stories.next().ok_or_else(|| bad(cmd, format!("no table {id}")))?;
if stories.next().is_some() {
return Err(bad(cmd, format!("table {id} exists in multiple stories; specify `story`")));
}
Ok(first)
}
fn id_param(p: &Value, key: &str, cmd: &str) -> Result<Option<u64>> {
match p.get(key) {
None => Ok(None),
Some(value) => value.as_u64().map(Some).ok_or_else(|| bad(cmd, format!("`{key}` must be a nonnegative integer"))),
}
}
fn pair(p: &Value, many: &str, one: &str) -> Option<(usize, usize)> {
@@ -57,15 +71,19 @@ fn pair(p: &Value, many: &str, one: &str) -> Option<(usize, usize)> {
pub(super) fn target(s: &Session, p: &Value, cmd: &str) -> Result<Tgt> {
let st = s.doc()?;
let doc = &st.doc;
let explicit_table = p.get("table").and_then(Value::as_u64);
let explicit_table = id_param(p, "table", cmd)?;
let explicit_story = table_story(p, cmd)?.map(StoryId);
let (story, table, range) = if let Some(tid) = explicit_table {
let explicit_story = table_story(p, cmd)?.map(StoryId);
let sid = explicit_story.or_else(|| find_table(doc, tid)).ok_or_else(|| bad(cmd, format!("no table {tid}")))?;
let sid = match explicit_story {
Some(sid) => sid,
None => find_table(doc, tid, cmd)?,
};
(sid, tid, None)
} else if let Some(c) = st.selection.cells {
(c.story, c.table, Some(c.range))
} else if let Some(t) = st.selection.text {
match t.cell {
Some(c) if c.footnote_id().is_some() => return Err(bad(cmd, "place the insertion point in a table")),
Some(c) => (t.story, c.table, Some(CellRange::cell(c.row, c.col))),
None => {
let tid = doc.story(t.story).and_then(|x| x.table_at(t.focus)).ok_or_else(|| bad(cmd, "the insertion point is not in a table"))?;
+179 -13
View File
@@ -2,7 +2,7 @@
use designcraft_compose as compose;
use designcraft_doc::story::floor_char_boundary;
use designcraft_doc::{CellAddr, CharAttrs, Content, ItemId, ParaAttrs, Selection, StoryId, TextSel};
use designcraft_doc::{Align, CellAddr, CharAttrs, Content, ItemId, ParaAttrs, Selection, StoryId, TextSel};
use designcraft_geom::Point;
use serde_json::{Value, json};
@@ -25,7 +25,8 @@ pub use edit::{PLACEHOLDER, quote_marks};
use edit::{change_case, delete, delete_surrounding, fill_placeholder, insert};
pub(crate) use format::{
Target, TypingFormat, apply_char_attrs, effective_char_format, format_chars, format_paras, format_targets, format_targets_pub,
rename_typing_swatch, validate_char_fill,
justification_order_error, justification_rows_changed, justification_rows_named, rename_typing_swatch, validate_char_fill,
validate_justification_order, validate_para_values,
};
use format::{break_link, kern_pair, kern_step, link_style, para_toggle, pick_up_format, step_size, swap_fill_stroke};
use opentype::{open_type, open_type_features, set_features};
@@ -234,22 +235,25 @@ pub fn specs() -> Vec<CommandSpec> {
"Paragraph Formatting",
[],
None,
"{attrs: {align?, leftIndent?, firstLineIndent?, spaceBefore?, spaceAfter?, dropCapLines?, dropCapChars?, dropCapStyle?, dropCapAlignLeft?, dropCapScaleDescenders?, hyphenate?: bool (default true), composer?, opticalMargin?: bool (hang at each character's own size; a story with story.options opticalMargin overrides it), ignoreOpticalMargin?: bool (no hang in the paragraph), tabs?, ruleAbove?/ruleBelow?: {on?, weight?, color?, tint?, columnWidth?, offset?, leftIndent?, rightIndent?} (only the named rule fields change), …}}",
"{attrs: {align?, leftIndent?, rightIndent?, spaceBefore?, spaceAfter?, sameParaStyleSpacing? (pt, each 0..15552), firstLineIndent?, lastLineIndent? (pt, each -15552..15552), wordSpaceMin?/wordSpaceDesired?/wordSpaceMax? (0..10, 1 = 100%), letterSpaceMin?/…Desired?/…Max? (-1..5), glyphScaleMin?/…Desired?/…Max? (0.5..2) (each row Minimum ≤ Desired ≤ Maximum), autoLeading? (0..5 of the type size), singleWordJustify?: left|center|right|fullyJustified, dropCapLines?, dropCapChars?, dropCapStyle?, dropCapAlignLeft?, dropCapScaleDescenders?, hyphenate?: bool (default true), composer?, opticalMargin?: bool (hang at each character's own size; a story with story.options opticalMargin overrides it), ignoreOpticalMargin?: bool (no hang in the paragraph), tabs?, ruleAbove?/ruleBelow?: {on?, weight?, color?, tint?, columnWidth?, offset?, leftIndent?, rightIndent?} (only the named rule fields change), …}}",
has_text_or_frames,
|s, p| format_paras(s, p.get("attrs").unwrap_or(p))
),
cmd!("type.align", "Align", [], None, "{align: left|center|right|leftJustified|…}", has_text_or_frames, |s, p| {
format_paras(s, &json!({"align": p.get("align").cloned().unwrap_or(json!("left"))}))
cmd!("type.align", "Align", [], None, "{align: left|center|right|leftJustified|…|null} (required)", has_text_or_frames, |s, p| {
let align = p.get("align").cloned().ok_or_else(|| bad("type.align", "`align` required"))?;
// A value that isn't an alignment goes to `format_paras`, which names the error.
match serde_json::from_value::<Option<Align>>(align.clone()) {
Ok(a) => align_paras(s, a),
Err(_) => format_paras(s, &json!({ "align": align })),
}
}),
cmd!("type.alignLeft", "Align Left", [], Some("Cmd+Shift+L"), "{}", has_text_or_frames, |s, _| format_paras(s, &json!({"align": "left"}))),
cmd!("type.alignCenter", "Align Center", [], Some("Cmd+Shift+C"), "{}", has_text_or_frames, |s, _| format_paras(
cmd!("type.alignLeft", "Align Left", [], Some("Cmd+Shift+L"), "{}", has_text_or_frames, |s, _| align_paras(s, Some(Align::Left))),
cmd!("type.alignCenter", "Align Center", [], Some("Cmd+Shift+C"), "{}", has_text_or_frames, |s, _| align_paras(s, Some(Align::Center))),
cmd!("type.alignRight", "Align Right", [], Some("Cmd+Shift+R"), "{}", has_text_or_frames, |s, _| align_paras(s, Some(Align::Right))),
cmd!("type.justify", "Justify Left", [], Some("Cmd+Shift+J"), "{}", has_text_or_frames, |s, _| align_paras(s, Some(Align::LeftJustified))),
cmd!("type.justifyAll", "Justify all lines", [], Some("Cmd+Shift+F"), "{}", has_text_or_frames, |s, _| align_paras(
s,
&json!({"align": "center"})
)),
cmd!("type.alignRight", "Align Right", [], Some("Cmd+Shift+R"), "{}", has_text_or_frames, |s, _| format_paras(s, &json!({"align": "right"}))),
cmd!("type.justify", "Justify Left", [], Some("Cmd+Shift+J"), "{}", has_text_or_frames, |s, _| format_paras(
s,
&json!({"align": "leftJustified"})
Some(Align::FullyJustified)
)),
cmd!(
"type.bold",
@@ -442,3 +446,165 @@ pub fn specs() -> Vec<CommandSpec> {
),
]
}
/// Sets the alignment of the paragraphs a formatting command targets (`None` removes the
/// override, back to the style's value). When each of them already carries that value as its
/// own, or there is no paragraph to change, the document is left as it is and no undo step is
/// recorded.
fn align_paras(s: &mut Session, align: Option<Align>) -> Result<Value> {
let targets = format_targets(s);
let doc = &s.doc()?.doc;
let unchanged = targets.iter().all(|t| {
doc.text_story(t.story, t.cell).is_none_or(|st| {
let (a, b) = (st.para_at(t.range.start), st.para_at(t.range.end.max(t.range.start)));
st.paras.get(a..=b).is_none_or(|paras| paras.iter().all(|p| p.para.align == align))
})
});
if unchanged {
return ok();
}
format_paras(s, &json!({ "align": align }))
}
#[cfg(test)]
mod alignment_shortcut_tests {
use designcraft_doc::{Align, Document};
use serde_json::{Value, json};
use crate::Session;
fn undo_steps(s: &Session) -> usize {
s.doc().unwrap().history.undo.len()
}
fn selection_align(s: &mut Session) -> Value {
s.execute("type.selectionAttrs", &json!({})).unwrap()["para"]["align"].clone()
}
/// The resolved alignment of every paragraph of the story whose text starts with `start`.
fn story_aligns(d: &Document, start: &str) -> Vec<Align> {
let st = d.stories.values().find(|st| st.text.starts_with(start)).unwrap();
st.paras.iter().map(|p| d.styles.resolve_para(p).0.align).collect()
}
/// Justify All Lines is ⇧⌘F (Shift+Ctrl+F), next to Justify Left ⇧⌘J.
#[test]
fn justify_all_lines_has_its_shortcut_and_justifies_the_last_line_too() {
let mut s = Session::new();
s.execute("file.new", &json!({})).unwrap();
let r = s.execute("frame.create", &json!({"rect": [36, 36, 300, 200], "content": "text", "text": "Spring issue"})).unwrap();
s.execute("text.select", &json!({"story": r["story"], "anchor": 3, "focus": 3})).unwrap();
// From Justify Left, so the result is not a default or a neighboring justification.
s.execute("type.justify", &json!({})).unwrap();
assert_eq!(s.execute("type.selectionAttrs", &json!({})).unwrap()["para"]["align"], "leftJustified");
s.execute("type.justifyAll", &json!({})).unwrap();
assert_eq!(s.execute("type.selectionAttrs", &json!({})).unwrap()["para"]["align"], "fullyJustified");
assert_eq!(crate::find_command("type.justifyAll").and_then(|c| c.shortcut), Some("Cmd+Shift+F"));
}
/// A second press of an alignment shortcut, or `type.align` with the value the paragraphs
/// already have, leaves the document and the undo list alone.
#[test]
fn an_alignment_the_paragraphs_already_have_records_no_undo_step() {
let mut s = Session::new();
s.execute("file.new", &json!({})).unwrap();
let r = s.execute("frame.create", &json!({"rect": [36, 36, 300, 200], "content": "text", "text": "One\nTwo"})).unwrap();
s.execute("text.select", &json!({"story": r["story"], "anchor": 0, "focus": 5})).unwrap();
for (id, params, align) in [
("type.justifyAll", json!({}), "fullyJustified"),
("type.align", json!({"align": "center"}), "center"),
("type.alignLeft", json!({}), "left"),
("type.alignCenter", json!({}), "center"),
("type.alignRight", json!({}), "right"),
("type.justify", json!({}), "leftJustified"),
] {
let before = undo_steps(&s);
s.execute(id, &params).unwrap();
assert_eq!(selection_align(&mut s), align, "{id}");
assert_eq!(undo_steps(&s), before + 1, "{id}: one step");
let rev = s.doc().unwrap().doc.clone();
s.execute(id, &params).unwrap();
assert_eq!(undo_steps(&s), before + 1, "{id} again: no step");
assert!(std::sync::Arc::ptr_eq(&rev, &s.doc().unwrap().doc), "{id} again: the document is unchanged");
}
// Removing the override: once it is gone, a second removal does nothing.
s.execute("type.align", &json!({"align": null})).unwrap();
let before = undo_steps(&s);
s.execute("type.align", &json!({"align": null})).unwrap();
assert_eq!(undo_steps(&s), before);
// One paragraph that differs is enough to apply it, to both.
s.execute("text.select", &json!({"story": r["story"], "anchor": 0, "focus": 0})).unwrap();
s.execute("type.justifyAll", &json!({})).unwrap();
s.execute("text.select", &json!({"story": r["story"], "anchor": 0, "focus": 5})).unwrap();
let before = undo_steps(&s);
s.execute("type.justifyAll", &json!({})).unwrap();
assert_eq!(undo_steps(&s), before + 1);
assert_eq!(story_aligns(&s.doc().unwrap().doc, "One"), [Align::FullyJustified; 2]);
}
/// The shortcut commands take no parameters: a misspelled call is refused and changes nothing.
#[test]
fn justify_all_lines_refuses_parameters() {
let mut s = Session::new();
s.execute("file.new", &json!({})).unwrap();
let r = s.execute("frame.create", &json!({"rect": [36, 36, 300, 200], "content": "text", "text": "Spring"})).unwrap();
s.execute("text.select", &json!({"story": r["story"], "anchor": 1, "focus": 1})).unwrap();
let before = undo_steps(&s);
assert!(s.execute("type.justifyAll", &json!({"align": "left"})).is_err());
assert_eq!(selection_align(&mut s), "left");
assert_eq!(undo_steps(&s), before);
}
/// With text frames selected, every paragraph of their stories, across threaded frames;
/// other selected frames are skipped, and a selection with no text frame is refused.
#[test]
fn justify_all_lines_on_frames_reaches_threaded_text_and_skips_other_frames() {
let mut s = Session::new();
s.execute("file.new", &json!({})).unwrap();
let a = s.execute("frame.create", &json!({"rect": [36, 36, 300, 60], "content": "text", "text": "Alpha\nBeta\nGamma\nDelta"})).unwrap();
let b = s.execute("frame.create", &json!({"rect": [36, 300, 300, 500], "content": "text"})).unwrap();
s.execute("text.thread", &json!({"from": a["id"], "to": b["id"]})).unwrap();
let rect = s.execute("frame.create", &json!({"rect": [400, 36, 500, 136]})).unwrap();
s.execute("selection.set", &json!({"ids": [rect["id"]]})).unwrap();
let before = undo_steps(&s);
assert!(s.execute("type.justifyAll", &json!({})).is_err(), "no text frame selected");
assert_eq!(undo_steps(&s), before);
// The second frame of the thread and the rectangle.
s.execute("selection.set", &json!({"ids": [b["id"], rect["id"]]})).unwrap();
s.execute("type.justifyAll", &json!({})).unwrap();
assert_eq!(undo_steps(&s), before + 1);
assert_eq!(story_aligns(&s.doc().unwrap().doc, "Alpha"), [Align::FullyJustified; 4]);
}
/// Over a paragraph style's alignment, Justify All Lines is a local override: the style keeps
/// its value, and removing the override goes back to it.
#[test]
fn justify_all_lines_overrides_the_paragraph_style() {
let mut s = Session::new();
s.execute("file.new", &json!({})).unwrap();
let r = s.execute("frame.create", &json!({"rect": [36, 36, 300, 200], "content": "text", "text": "Spring issue"})).unwrap();
s.execute("text.select", &json!({"story": r["story"], "anchor": 2, "focus": 2})).unwrap();
s.execute("style.paragraph.create", &json!({"name": "Caption", "para": {"align": "right"}})).unwrap();
s.execute("style.paragraph.apply", &json!({"name": "Caption"})).unwrap();
assert_eq!(selection_align(&mut s), "right");
s.execute("type.justifyAll", &json!({})).unwrap();
assert_eq!(selection_align(&mut s), "fullyJustified");
let d = &s.doc().unwrap().doc;
assert_eq!(d.styles.resolve_para_style("Caption").0.align, Align::Right);
s.execute("type.align", &json!({"align": null})).unwrap();
assert_eq!(selection_align(&mut s), "right");
}
/// IDML writes the paragraph's Justification as FullyJustified and reads it back.
#[test]
fn justify_all_lines_survives_idml_export_and_import() {
let mut s = Session::new();
s.execute("file.new", &json!({})).unwrap();
let r = s.execute("frame.create", &json!({"rect": [36, 36, 300, 200], "content": "text", "text": "Spring\nissue"})).unwrap();
s.execute("text.select", &json!({"story": r["story"], "anchor": 0, "focus": 0})).unwrap();
s.execute("type.justifyAll", &json!({})).unwrap();
let bytes = designcraft_idml::export_idml(&s.doc().unwrap().doc);
s.execute("file.openIdml", &json!({"base64": crate::cmd::base64_encode(&bytes), "name": "in.idml"})).unwrap();
assert_eq!(story_aligns(&s.doc().unwrap().doc, "Spring"), [Align::FullyJustified, Align::Left]);
}
}
+5 -2
View File
@@ -487,12 +487,15 @@ pub(super) fn change_case(s: &mut Session, p: &Value) -> Result<Value> {
let mut changes = Vec::new();
for seg in segs.iter().rev() {
let old = st.slice(seg.clone()).to_string();
let new: String = starts.iter().zip(&mapped).filter(|(b, _)| seg.contains(b)).map(|(_, m)| m.as_str()).collect();
// The characters in this run: `starts` is sorted, so a search finds the slice.
let (from, to) = (starts.partition_point(|b| *b < seg.start), starts.partition_point(|b| *b < seg.end));
let new: String = mapped.get(from..to).unwrap_or_default().iter().map(String::as_str).collect();
if new != old {
delta += new.len() as isize - old.len() as isize;
st.replace(seg.clone(), &new);
// Per-character changes (back to front), so ranges inside the run keep their boundaries.
for (i, (b, m)) in starts.iter().zip(&mapped).enumerate().rev().filter(|(_, (b, _))| seg.contains(b)) {
for i in (from..to.min(mapped.len())).rev() {
let (b, m) = (&starts[i], &mapped[i]);
let ce = starts.get(i + 1).copied().unwrap_or(r.end);
if m.len() != ce - b {
changes.push((*b..ce, m.len()));
+369 -2
View File
@@ -146,6 +146,118 @@ pub(crate) const MIN_TYPE_SIZE: f64 = 0.1;
pub(crate) const MAX_TYPE_SIZE: f64 = 1296.0;
/// Left and right indents, Space Before, Space After and Space Between Paragraphs Using Same
/// Style: 0 to 15552 pt, the limit `object.textFrameOptions` applies to its Paragraph Spacing
/// Limit. First and last line indents may be negative, down to -15552 pt.
pub(crate) const MAX_PARA_SPACE: f64 = 15552.0;
/// The justification rows as fractions (1.0 = 100%): key stem, label, range.
const JUSTIFICATION_ROWS: [(&str, &str, f64, f64); 3] =
[("wordSpace", "word spacing", 0.0, 10.0), ("letterSpace", "letter spacing", -1.0, 5.0), ("glyphScale", "glyph scaling", 0.5, 2.0)];
/// Auto Leading: 0% to 500% of the type size.
const MAX_AUTO_LEADING: f64 = 5.0;
/// A fraction shown as a percent, without float noise (1.33 is "133").
fn percent(v: f64) -> String {
let p = (v * 100.0 * 1000.0).round() / 1000.0;
format!("{p}")
}
/// Checks the paragraph spacing and justification values `attrs` sets: left and right indents,
/// Space Before, Space After and same-style spacing 0 to [`MAX_PARA_SPACE`] pt, first and last
/// line indents -[`MAX_PARA_SPACE`] to [`MAX_PARA_SPACE`] pt; word spacing 0% to 1000%, letter spacing
/// -100% to 500% and glyph scaling 50% to 200%; Auto Leading 0% to 500%; Single Word
/// Justification left, center, right or fullyJustified. [`validate_justification_order`] checks
/// the order of each row once the values are applied.
pub(crate) fn validate_para_values(attrs: &ParaAttrs, command_id: &str) -> Result<()> {
use designcraft_doc::Align;
let spaces = [
("leftIndent", attrs.left_indent, 0.0),
("rightIndent", attrs.right_indent, 0.0),
("firstLineIndent", attrs.first_line_indent, -MAX_PARA_SPACE),
("lastLineIndent", attrs.last_line_indent, -MAX_PARA_SPACE),
("spaceBefore", attrs.space_before, 0.0),
("spaceAfter", attrs.space_after, 0.0),
("sameParaStyleSpacing", attrs.same_para_style_spacing.flatten(), 0.0),
];
for (key, v, lo) in spaces {
if let Some(v) = v
&& !(lo..=MAX_PARA_SPACE).contains(&v)
{
return Err(bad(command_id, format!("{key} {v}: {lo} to {MAX_PARA_SPACE} pt")));
}
}
let rows = [
[attrs.word_space_min, attrs.word_space_desired, attrs.word_space_max],
[attrs.letter_space_min, attrs.letter_space_desired, attrs.letter_space_max],
[attrs.glyph_scale_min, attrs.glyph_scale_desired, attrs.glyph_scale_max],
];
for ((stem, label, lo, hi), given) in JUSTIFICATION_ROWS.into_iter().zip(rows) {
for (suffix, v) in ["Min", "Desired", "Max"].into_iter().zip(given) {
if let Some(v) = v
&& !(lo..=hi).contains(&v)
{
return Err(bad(command_id, format!("{stem}{suffix} {}%: {label} is {}% to {}%", percent(v), percent(lo), percent(hi))));
}
}
}
if let Some(v) = attrs.auto_leading
&& !(0.0..=MAX_AUTO_LEADING).contains(&v)
{
return Err(bad(command_id, format!("autoLeading {}%: 0% to {}%", percent(v), percent(MAX_AUTO_LEADING))));
}
if let Some(a) = attrs.single_word_justify
&& !matches!(a, Align::Left | Align::Center | Align::Right | Align::FullyJustified)
{
return Err(bad(command_id, format!("singleWordJustify {}: left, center, right or fullyJustified", json!(a))));
}
Ok(())
}
/// The justification rows (word spacing, letter spacing, glyph scaling) that attribute names in
/// `keys` set or clear.
pub(crate) fn justification_rows_named<'a>(keys: impl IntoIterator<Item = &'a str>) -> [bool; 3] {
let mut rows = [false; 3];
for key in keys {
let key = key.replace('_', "").to_ascii_lowercase();
for (row, (stem, ..)) in rows.iter_mut().zip(JUSTIFICATION_ROWS) {
*row |= key.starts_with(&stem.to_ascii_lowercase());
}
}
rows
}
/// Each justification row marked in `rows` needs Minimum ≤ Desired ≤ Maximum in `resolved`, the
/// attributes of the paragraph or style after the change.
pub(crate) fn validate_justification_order(resolved: &designcraft_doc::ParaProps, rows: [bool; 3], command_id: &str) -> Result<()> {
justification_order_error(resolved, rows).map_or(Ok(()), |m| Err(bad(command_id, m)))
}
/// The justification rows of resolved paragraph attributes: Minimum, Desired, Maximum.
fn justification_values(resolved: &designcraft_doc::ParaProps) -> [[f64; 3]; 3] {
[
[resolved.word_space_min, resolved.word_space_desired, resolved.word_space_max],
[resolved.letter_space_min, resolved.letter_space_desired, resolved.letter_space_max],
[resolved.glyph_scale_min, resolved.glyph_scale_desired, resolved.glyph_scale_max],
]
}
/// The justification rows whose values differ between `before` and `after`.
pub(crate) fn justification_rows_changed(before: &designcraft_doc::ParaProps, after: &designcraft_doc::ParaProps) -> [bool; 3] {
let (b, a) = (justification_values(before), justification_values(after));
[b[0] != a[0], b[1] != a[1], b[2] != a[2]]
}
/// What [`validate_justification_order`] refuses, as a message.
pub(crate) fn justification_order_error(resolved: &designcraft_doc::ParaProps, rows: [bool; 3]) -> Option<String> {
let values = justification_values(resolved);
JUSTIFICATION_ROWS.into_iter().zip(values).zip(rows).find_map(|(((_, label, ..), [min, desired, max]), checked)| {
(checked && (min > desired || desired > max))
.then(|| format!("{label} needs Minimum ≤ Desired ≤ Maximum, not {}%, {}%, {}%", percent(min), percent(desired), percent(max)))
})
}
/// Byte `pos` is the hidden paragraph mark of an *empty* paragraph: the only character on that
/// line, and so the one a line-affecting attribute like leading can land on right away instead of
/// waiting for the next typed character (otherwise an empty line could never get its own leading).
@@ -315,11 +427,15 @@ pub(crate) fn format_paras(s: &mut Session, attrs: &Value) -> Result<Value> {
a.set_json_over(k, v, &designcraft_doc::ParaProps::default()).map_err(|e| bad("type.para", e))?;
}
crate::cmd::style::check_grep_styles("type.para", &a)?;
validate_para_values(&a, "type.para")?;
let rows = justification_rows_named(obj.keys().map(String::as_str));
// `null` removes the override (back to the style's value).
let cleared: Vec<String> = obj.iter().filter(|(_, v)| v.is_null()).map(|(k, _)| k.clone()).collect();
let targets = format_targets(s);
s.edit(|d, _| {
let styles = d.styles.clone();
// Minimum ≤ Desired ≤ Maximum holds over each paragraph's own values once they change.
let mut refused = None;
for t in &targets {
if let Some(st) = d.text_story_mut(t.story, t.cell) {
st.format_paras(t.range.clone(), |p| {
@@ -332,10 +448,15 @@ pub(crate) fn format_paras(s: &mut Session, attrs: &Value) -> Result<Value> {
for k in &cleared {
let _ = p.para.set_json(k, &Value::Null);
}
if refused.is_none()
&& let Err(e) = validate_justification_order(&styles.resolve_para(p).0, rows, "type.para")
{
refused = Some(e);
}
});
}
}
ok()
refused.map_or_else(ok, Err)
})
}
@@ -1075,11 +1196,51 @@ mod pick_up_format_tests {
}
#[cfg(test)]
mod size_bounds_tests {
mod align_param_tests {
use serde_json::json;
use crate::Session;
/// `type.align` with empty params (`{}`) or a bare value (`"center"`) applied Align Left.
/// A misspelled key and an unknown value were already refused, and each case checks which
/// check refuses it.
#[test]
fn type_align_without_a_value_is_refused_and_changes_nothing() {
let mut s = Session::new();
s.execute("file.new", &json!({"pages": 1})).unwrap();
let f = s.execute("frame.create", &json!({"rect": [20, 20, 400, 300], "content": "text", "text": "Hello world"})).unwrap();
s.execute("text.select", &json!({"story": f["story"].clone(), "anchor": 0, "focus": 5})).unwrap();
s.execute("type.align", &json!({"align": "right"})).unwrap();
let align = |s: &mut Session| s.execute("type.selectionAttrs", &json!({})).unwrap()["para"]["align"].clone();
assert_eq!(align(&mut s), json!("right"));
let steps = s.doc().unwrap().history.undo.len();
// `{}` and `"center"` reach the command without `align`. The parameter check refuses
// `{"alignment": …}` and the value parser refuses `"middle"`.
for (params, refusal) in [
(json!({}), "`align` required"),
(json!("center"), "`align` required"),
(json!({"alignment": "center"}), "unknown parameter `alignment`"),
(json!({"align": "middle"}), "middle"),
] {
let err = s.execute("type.align", &params).unwrap_err().to_string();
assert!(err.contains(refusal), "{params}: {err}");
assert_eq!(align(&mut s), json!("right"), "{params}");
assert_eq!(s.doc().unwrap().history.undo.len(), steps, "{params}: no undo step");
}
// A named value still applies, and null removes the override.
s.execute("type.align", &json!({"align": "center"})).unwrap();
assert_eq!(align(&mut s), json!("center"));
s.execute("type.align", &json!({"align": null})).unwrap();
assert_eq!(align(&mut s), json!("left"));
}
}
#[cfg(test)]
mod size_bounds_tests {
use serde_json::{Value, json};
use crate::Session;
/// Type size was not checked anywhere: `{"size": 0}` set type with no size at all, a negative
/// size was accepted the same way, and 1e9 pt asked the composer for a line a million times
/// the height of the page. The range is the one `type.ruby` already applies, 0.1 to 1296 pt.
@@ -1111,6 +1272,212 @@ mod size_bounds_tests {
assert!(e.contains("0.1 to 1296 pt"), "{command}: {e}");
}
}
/// `type.para` set any number for paragraph indents, spacing and justification: a negative
/// left indent or Space Before, word spacing of 5000% and a Minimum above Maximum all went into the paragraph,
/// and Single Word Justification took any alignment. Values outside the ranges are refused,
/// nothing changes, and the ends of each range still apply.
#[test]
fn paragraph_spacing_and_justification_outside_their_ranges_are_refused() {
let mut s = Session::new();
s.execute("file.new", &json!({"pages": 1})).unwrap();
let f = s.execute("frame.create", &json!({"rect": [20, 20, 400, 300], "content": "text", "text": "Hello world\nSecond"})).unwrap();
let select_all = |s: &mut Session| {
s.execute("text.select", &json!({"story": f["story"].clone(), "anchor": 0, "focus": 18})).unwrap();
};
let para = |s: &mut Session| s.execute("type.selectionAttrs", &json!({})).unwrap()["para"].clone();
select_all(&mut s);
let before = para(&mut s);
for (attrs, says) in [
(json!({"spaceBefore": -1}), "spaceBefore -1: 0 to 15552 pt"),
(json!({"spaceAfter": 15553}), "spaceAfter 15553: 0 to 15552 pt"),
(json!({"sameParaStyleSpacing": -2}), "sameParaStyleSpacing -2: 0 to 15552 pt"),
(json!({"leftIndent": -50}), "leftIndent -50: 0 to 15552 pt"),
(json!({"rightIndent": -20}), "rightIndent -20: 0 to 15552 pt"),
(json!({"rightIndent": 1e300}), "rightIndent 1"),
(json!({"firstLineIndent": -15553}), "firstLineIndent -15553: -15552 to 15552 pt"),
(json!({"lastLineIndent": 15553}), "lastLineIndent 15553: -15552 to 15552 pt"),
(json!({"wordSpaceMax": 10.5}), "wordSpaceMax 1050%: word spacing is 0% to 1000%"),
(json!({"wordSpaceMin": -0.1}), "wordSpaceMin -10%: word spacing is 0% to 1000%"),
(json!({"letterSpaceMin": -1.5}), "letterSpaceMin -150%: letter spacing is -100% to 500%"),
(json!({"letterSpaceMax": 5.5}), "letterSpaceMax 550%: letter spacing is -100% to 500%"),
(json!({"glyphScaleMin": 0.4}), "glyphScaleMin 40%: glyph scaling is 50% to 200%"),
(json!({"glyphScaleDesired": 2.1}), "glyphScaleDesired 210%: glyph scaling is 50% to 200%"),
(json!({"autoLeading": 6}), "autoLeading 600%: 0% to 500%"),
(json!({"autoLeading": -0.1}), "autoLeading -10%: 0% to 500%"),
(json!({"singleWordJustify": "leftJustified"}), "singleWordJustify \"leftJustified\": left, center, right or fullyJustified"),
// Desired word spacing is 100%, so a Minimum of 120% alone is out of order.
(json!({"wordSpaceMin": 1.2}), "word spacing needs Minimum ≤ Desired ≤ Maximum, not 120%, 100%, 133%"),
(
json!({"glyphScaleMin": 0.9, "glyphScaleDesired": 1.1, "glyphScaleMax": 1.0}),
"glyph scaling needs Minimum ≤ Desired ≤ Maximum, not 90%, 110%, 100%",
),
] {
select_all(&mut s);
let e = s.execute("type.para", &json!({"attrs": attrs})).expect_err("refused").to_string();
assert!(e.contains(says), "{attrs}: {e}");
assert_eq!(para(&mut s), before, "{attrs}");
}
// The ends of each range apply and read back.
for attrs in [
json!({"spaceBefore": 0, "spaceAfter": 15552, "sameParaStyleSpacing": 15552}),
json!({"leftIndent": 0, "rightIndent": 15552, "firstLineIndent": -15552, "lastLineIndent": 15552}),
json!({"leftIndent": 18, "rightIndent": 0, "firstLineIndent": -18, "lastLineIndent": 0}),
json!({"wordSpaceMin": 0, "wordSpaceDesired": 0, "wordSpaceMax": 10}),
json!({"letterSpaceMin": -1, "letterSpaceDesired": 0, "letterSpaceMax": 5}),
json!({"glyphScaleMin": 0.5, "glyphScaleDesired": 1, "glyphScaleMax": 2}),
json!({"autoLeading": 5}),
json!({"autoLeading": 0, "singleWordJustify": "center"}),
] {
select_all(&mut s);
s.execute("type.para", &json!({"attrs": attrs})).unwrap_or_else(|e| panic!("{attrs}: {e}"));
let got = para(&mut s);
let same = |a: &Value, b: &Value| a.as_f64().zip(b.as_f64()).map_or(a == b, |(a, b)| a == b);
for (k, v) in attrs.as_object().unwrap() {
assert!(same(&got[k], v), "{k}: {} for {v}", got[k]);
}
}
// The order holds over each paragraph's own values: with Desired 300% in the second
// paragraph only, a Maximum of 200% for both is refused and neither paragraph changes.
s.execute("text.select", &json!({"story": f["story"].clone(), "anchor": 12, "focus": 18})).unwrap();
s.execute("type.para", &json!({"attrs": {"wordSpaceMax": 5, "wordSpaceDesired": 3}})).unwrap();
select_all(&mut s);
let before = para(&mut s);
let e = s.execute("type.para", &json!({"attrs": {"wordSpaceMax": 2}})).expect_err("refused").to_string();
assert!(e.contains("not 0%, 300%, 200%"), "{e}");
assert_eq!(para(&mut s), before);
// Clearing a value is checked too: with Minimum 250% in the second paragraph, clearing
// its Desired back to the style's 100% is refused.
let second = |s: &mut Session| {
s.execute("text.select", &json!({"story": f["story"].clone(), "anchor": 12, "focus": 18})).unwrap();
};
second(&mut s);
s.execute("type.para", &json!({"attrs": {"wordSpaceMin": 2.5}})).unwrap();
second(&mut s);
let e = s.execute("type.para", &json!({"attrs": {"wordSpaceDesired": null}})).expect_err("refused").to_string();
assert!(e.contains("word spacing needs Minimum ≤ Desired ≤ Maximum, not 250%, 100%, 500%"), "{e}");
second(&mut s);
assert_eq!(para(&mut s)["wordSpaceDesired"].as_f64(), Some(3.0));
// Paragraph styles are checked the same way, over what the style resolves to.
let e = s.execute("style.paragraph.create", &json!({"name": "Loose", "para": {"autoLeading": 6}})).expect_err("refused").to_string();
assert!(e.contains("autoLeading 600%"), "{e}");
s.execute("style.paragraph.create", &json!({"name": "Body", "para": {"wordSpaceDesired": 1.2}})).unwrap();
let e = s.execute("style.paragraph.create", &json!({"name": "Tight", "para": {"wordSpaceMax": 0.9}})).expect_err("refused").to_string();
assert!(e.contains("not 80%, 100%, 90%"), "{e}");
let e = s
.execute("style.paragraph.create", &json!({"name": "Child", "basedOn": "Body", "para": {"wordSpaceMax": 1.1}}))
.expect_err("refused")
.to_string();
assert!(e.contains("not 80%, 120%, 110%"), "{e}");
let e = s.execute("style.paragraph.edit", &json!({"name": "Body", "para": {"wordSpaceMin": 1.3}})).expect_err("refused").to_string();
assert!(e.contains("not 130%, 120%, 133%"), "{e}");
let e = s.execute("style.paragraph.edit", &json!({"name": "Body", "para": {"spaceAfter": -3}})).expect_err("refused").to_string();
assert!(e.contains("spaceAfter -3: 0 to 15552 pt"), "{e}");
let style = s.doc().unwrap().doc.styles.para("Body").unwrap().para.clone();
assert_eq!((style.word_space_min, style.space_after), (None, None));
for name in ["Loose", "Tight", "Child"] {
assert!(s.doc().unwrap().doc.styles.para(name).is_none(), "{name}");
}
// A new Based On is checked over every row of what the style then resolves to.
s.execute("style.paragraph.create", &json!({"name": "Wide", "para": {"wordSpaceMin": 1.2, "wordSpaceDesired": 1.3}})).unwrap();
s.execute("style.paragraph.create", &json!({"name": "Narrow", "para": {"wordSpaceMax": 1.1}})).unwrap();
let e = s.execute("style.paragraph.edit", &json!({"name": "Wide", "basedOn": "Narrow"})).expect_err("refused").to_string();
assert!(e.contains("not 120%, 130%, 110%"), "{e}");
assert_eq!(s.doc().unwrap().doc.styles.para("Wide").unwrap().based_on, None);
// An edit is checked over the styles based on the edited style and the paragraphs using
// them, too.
s.execute("style.paragraph.create", &json!({"name": "Parent"})).unwrap();
s.execute("style.paragraph.create", &json!({"name": "Kid", "basedOn": "Parent", "para": {"wordSpaceMax": 1.1}})).unwrap();
let e = s.execute("style.paragraph.edit", &json!({"name": "Parent", "para": {"wordSpaceDesired": 1.2}})).expect_err("refused").to_string();
assert!(e.contains("paragraph style \"Kid\": word spacing needs Minimum ≤ Desired ≤ Maximum, not 80%, 120%, 110%"), "{e}");
// A footnote paragraph with its own Maximum of 10%, under a style edit that sets Desired
// to 20%.
select_all(&mut s);
s.execute("style.paragraph.apply", &json!({"name": "Parent", "clearOverrides": true})).unwrap();
s.execute("text.select", &json!({"story": f["story"].clone(), "anchor": 5, "focus": 5})).unwrap();
s.execute("footnote.insert", &json!({"text": "Note"})).unwrap();
s.execute("style.paragraph.apply", &json!({"name": "Parent", "clearOverrides": true})).unwrap();
s.execute("type.para", &json!({"attrs": {"letterSpaceMax": 0.1}})).unwrap();
let e = s
.execute("style.paragraph.edit", &json!({"name": "Parent", "para": {"letterSpaceDesired": 0.2, "letterSpaceMax": 0.5}}))
.expect_err("refused")
.to_string();
assert!(
e.contains(&format!("a paragraph of story {}: letter spacing needs Minimum ≤ Desired ≤ Maximum, not 0%, 20%, 10%", f["story"])),
"{e}"
);
assert_eq!(s.doc().unwrap().doc.styles.para("Parent").unwrap().para.letter_space_desired, None);
}
/// Applying or redefining a paragraph style could leave a paragraph's own override and the
/// style's values out of order: a Maximum of 10% kept over a style's Desired of 20%. Both are
/// refused and nothing changes; Clear Overrides still applies the style.
#[test]
fn applying_or_redefining_a_style_keeps_justification_in_order() {
let mut s = Session::new();
s.execute("file.new", &json!({"pages": 1})).unwrap();
let f = s.execute("frame.create", &json!({"rect": [20, 20, 400, 300], "content": "text", "text": "Hello world\nSecond"})).unwrap();
let sid = designcraft_doc::StoryId(f["story"].as_u64().unwrap());
let select = |s: &mut Session, anchor: u64, focus: u64| {
s.execute("text.select", &json!({"story": f["story"].clone(), "anchor": anchor, "focus": focus})).unwrap();
};
let styles = |s: &Session| s.doc().unwrap().doc.story(sid).unwrap().paras.iter().map(|p| p.style.clone()).collect::<Vec<_>>();
let letter = |s: &mut Session| {
let p = s.execute("type.selectionAttrs", &json!({})).unwrap()["para"].clone();
[p["letterSpaceMin"].as_f64(), p["letterSpaceDesired"].as_f64(), p["letterSpaceMax"].as_f64()]
};
s.execute("style.paragraph.create", &json!({"name": "Wide", "para": {"letterSpaceDesired": 0.2, "letterSpaceMax": 0.5}})).unwrap();
select(&mut s, 0, 18);
s.execute("type.para", &json!({"attrs": {"letterSpaceMax": 0.1}})).unwrap();
let before = styles(&s);
select(&mut s, 0, 18);
let e = s.execute("style.paragraph.apply", &json!({"name": "Wide"})).expect_err("refused").to_string();
assert!(e.contains("style.paragraph.apply") && e.contains("letter spacing needs Minimum ≤ Desired ≤ Maximum, not 0%, 20%, 10%"), "{e}");
assert_eq!(styles(&s), before);
select(&mut s, 0, 18);
assert_eq!(letter(&mut s), [Some(0.0), Some(0.0), Some(0.1)]);
// A style that changes no justification row applies over the same override.
s.execute("style.paragraph.create", &json!({"name": "Airy", "para": {"spaceAfter": 6}})).unwrap();
select(&mut s, 0, 18);
s.execute("style.paragraph.apply", &json!({"name": "Airy"})).unwrap();
select(&mut s, 0, 18);
s.execute("style.paragraph.apply", &json!({"name": "Wide", "clearOverrides": true})).unwrap();
assert_eq!(styles(&s), ["Wide", "Wide"]);
select(&mut s, 0, 18);
assert_eq!(letter(&mut s), [Some(0.0), Some(0.2), Some(0.5)]);
// Redefine Style from a paragraph whose Desired is 30% while the second paragraph keeps a
// Maximum of 25%.
select(&mut s, 12, 18);
s.execute("type.para", &json!({"attrs": {"letterSpaceMax": 0.25}})).unwrap();
select(&mut s, 0, 5);
s.execute("type.para", &json!({"attrs": {"letterSpaceDesired": 0.3}})).unwrap();
select(&mut s, 0, 5);
let e = s.execute("style.paragraph.redefine", &json!({})).expect_err("refused").to_string();
assert!(
e.contains("style.paragraph.redefine")
&& e.contains(&format!("a paragraph of story {}: letter spacing needs Minimum ≤ Desired ≤ Maximum, not 0%, 30%, 25%", sid.0)),
"{e}"
);
assert_eq!(s.doc().unwrap().doc.styles.para("Wide").unwrap().para.letter_space_desired, Some(0.2));
// A new style from a selection whose paragraph holds a value no command sets (as an
// import could leave) is refused the same way as a given value.
s.edit(|d, _| {
for pf in &mut d.story_mut(sid).unwrap().paras {
pf.para.left_indent = Some(-30.0);
}
Ok(())
})
.unwrap();
select(&mut s, 0, 5);
let e = s.execute("style.paragraph.create", &json!({"name": "Captured", "fromSelection": true})).expect_err("refused").to_string();
assert!(e.contains("leftIndent -30: 0 to 15552 pt"), "{e}");
assert!(s.doc().unwrap().doc.styles.para("Captured").is_none());
select(&mut s, 0, 5);
s.execute("style.paragraph.create", &json!({"name": "Captured", "fromSelection": true, "para": {"leftIndent": 0}})).unwrap();
assert_eq!(s.doc().unwrap().doc.styles.para("Captured").unwrap().para.left_indent, Some(0.0));
}
}
#[cfg(test)]
+12 -5
View File
@@ -60,10 +60,13 @@ fn plain(t: &str) -> String {
}
/// A paragraph's text with inline-tagged runs as elements.
fn para_xml(st: &designcraft_doc::Story, r: std::ops::Range<usize>) -> String {
/// `runs` are the story's runs in order (collected once per story): only those reaching the
/// paragraph are visited, found by binary search.
fn para_xml(st: &designcraft_doc::Story, runs: &[(std::ops::Range<usize>, &designcraft_doc::CharFormat)], r: std::ops::Range<usize>) -> String {
let mut out = String::new();
let mut open: Option<String> = None;
for (rr, f) in st.runs() {
let first = runs.partition_point(|(rr, _)| rr.end <= r.start);
for (rr, f) in runs.iter().skip(first).take_while(|(rr, _)| rr.start < r.end) {
let (a, b) = (rr.start.max(r.start), rr.end.min(r.end));
if a >= b {
continue;
@@ -97,8 +100,10 @@ pub fn export_xml(d: &Document) -> String {
let Some(st) = d.story(tf.story) else { continue };
let mapped = |style: &str| d.xml.style_map.iter().find(|(s, _)| s == style).map(|(_, t)| t.clone());
// Paragraph text with inline tags already escaped.
let paras: Vec<(Option<String>, String)> =
st.para_ranges().into_iter().enumerate().map(|(i, r)| (mapped(&st.paras[i].style), para_xml(st, r))).collect();
let paras: Vec<(Option<String>, String)> = {
let runs: Vec<_> = st.runs().collect();
st.para_ranges().into_iter().enumerate().map(|(i, r)| (mapped(&st.paras[i].style), para_xml(st, &runs, r))).collect()
};
if paras.iter().any(|(m, _)| m.is_some()) {
out.push_str(&format!(" <{tag}>\n"));
for (m, text) in paras {
@@ -318,8 +323,10 @@ pub fn specs() -> Vec<CommandSpec> {
let dtd = crate::dtd::parse(&text).map_err(|e| bad("xml.loadDtd", e))?;
let names: Vec<String> = dtd.element_names().map(str::to_string).collect();
s.edit(|d, _| {
// The tags there are, then those added: one set, not a search per element.
let mut known: std::collections::HashSet<String> = d.xml.tags.iter().map(|t| t.name.clone()).collect();
for n in &names {
if valid_name(n) && !d.xml.tags.iter().any(|t| t.name == *n) {
if valid_name(n) && known.insert(n.clone()) {
let color = COLORS[d.xml.tags.len() % COLORS.len()];
d.xml.tags.push(XmlTag { name: n.clone(), color });
}
+12 -5
View File
@@ -265,10 +265,11 @@ fn inside(path: &Path, root: &Path) -> bool {
root.components().all(|r| path.next() == Some(r))
}
/// A Windows device name (`CON`, `NUL`, `COM1`… also with an extension), which names no file.
/// A Windows device name (`CON`, `NUL`, `COM1`, `COM¹`… also with an extension or a colon), which names no file.
pub(crate) fn is_device_name(component: &str) -> bool {
let stem = component.split('.').next().unwrap_or(component).trim_end_matches(' ').to_ascii_uppercase();
let numbered = |prefix: &str| stem.strip_prefix(prefix).is_some_and(|n| matches!(n, "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9"));
let stem = component.split(['.', ':']).next().unwrap_or(component).trim_end_matches(' ').to_ascii_uppercase();
let numbered =
|prefix: &str| stem.strip_prefix(prefix).is_some_and(|n| matches!(n, "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" | "¹" | "²" | "³"));
matches!(stem.as_str(), "CON" | "PRN" | "AUX" | "NUL" | "CLOCK$" | "CONIN$" | "CONOUT$") || numbered("COM") || numbered("LPT")
}
@@ -526,6 +527,8 @@ mod tests {
let _ = std::fs::remove_dir_all(base);
}
/// On Windows an existing file spelled in another case is still inside its root, and `NUL`,
/// `COM1` and `COM¹` are refused.
#[cfg(windows)]
#[test]
fn windows_ignores_case_and_refuses_devices() {
@@ -536,6 +539,8 @@ mod tests {
let e = roots.check(s(base.join("out/NUL")), Access::Write).unwrap_err();
assert!(e.contains("reserved device names"), "{e}");
assert!(roots.check(s(base.join("out/com1.txt")), Access::Write).is_err());
let e = roots.check(s(base.join("out/COM¹.txt")), Access::Write).unwrap_err();
assert!(e.contains("reserved device names"), "{e}");
assert_eq!(roots.check(s(base.join("out/console.txt")), Access::Write), Ok(()));
let _ = std::fs::remove_dir_all(base);
}
@@ -561,6 +566,8 @@ mod tests {
let _ = std::fs::remove_dir_all(base);
}
/// `COM¹` to `LPT³`, and a device name before a colon, are reserved. `COM⁴`, `com¹0`, `lpt¹x`
/// and `console:x` are file names.
#[test]
fn inside_compares_components_exactly() {
assert!(inside(Path::new("/work/in/a"), Path::new("/work/in")));
@@ -571,10 +578,10 @@ mod tests {
#[test]
fn device_names() {
for d in ["CON", "nul", "Com1", "LPT9.txt", "aux.designcraft", "NUL "] {
for d in ["CON", "nul", "Com1", "LPT9.txt", "aux.designcraft", "NUL ", "COM¹", "Lpt²", "lpt³.txt", "COM1:", "nul:x", "COM¹:"] {
assert!(is_device_name(d), "{d}");
}
for f in ["console", "com10", "COM0", "lpt", "a.designcraft", "nul-x"] {
for f in ["console", "com10", "COM0", "lpt", "a.designcraft", "nul-x", "COM⁴", "com¹0", "lpt¹x", "console:x"] {
assert!(!is_device_name(f), "{f}");
}
}
Loaded 100 of 276 files, more files were not shown because too many files have changed in this diff. Show more