mirror of
https://github.com/storytold/designcraft.git
synced 2026-11-24 00:46:29 +00:00
Merge branch 'main' into readme-gentoo
# Conflicts: # contributors/people.toml
This commit is contained in:
Generated
+52
-32
@@ -796,6 +796,15 @@ dependencies = [
|
||||
"libm",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-pdf"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c3487320b2d1de657b860b3c8abb44e1f2b32bd8#c3487320b2d1de657b860b3c8abb44e1f2b32bd8"
|
||||
dependencies = [
|
||||
"krilla",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-print"
|
||||
version = "0.1.0"
|
||||
@@ -887,8 +896,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "designcraft"
|
||||
version = "0.7.1"
|
||||
version = "0.8.0"
|
||||
dependencies = [
|
||||
"arboard",
|
||||
"designcraft-engine",
|
||||
"designcraft-ui-egui",
|
||||
"eframe",
|
||||
@@ -904,7 +914,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "designcraft-cli"
|
||||
version = "0.7.1"
|
||||
version = "0.8.0"
|
||||
dependencies = [
|
||||
"designcraft-color",
|
||||
"designcraft-compose",
|
||||
@@ -920,7 +930,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "designcraft-color"
|
||||
version = "0.7.1"
|
||||
version = "0.8.0"
|
||||
dependencies = [
|
||||
"kurbo",
|
||||
"moxcms",
|
||||
@@ -932,7 +942,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "designcraft-compose"
|
||||
version = "0.7.1"
|
||||
version = "0.8.0"
|
||||
dependencies = [
|
||||
"designcraft-color",
|
||||
"designcraft-doc",
|
||||
@@ -945,11 +955,12 @@ dependencies = [
|
||||
"regex",
|
||||
"unicode-bidi",
|
||||
"unicode-bidi-mirroring",
|
||||
"unicode-segmentation",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "designcraft-doc"
|
||||
version = "0.7.1"
|
||||
version = "0.8.0"
|
||||
dependencies = [
|
||||
"designcraft-color",
|
||||
"designcraft-geom",
|
||||
@@ -961,7 +972,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "designcraft-engine"
|
||||
version = "0.7.1"
|
||||
version = "0.8.0"
|
||||
dependencies = [
|
||||
"caseless",
|
||||
"craft-print",
|
||||
@@ -989,13 +1000,14 @@ dependencies = [
|
||||
"serde_json",
|
||||
"tempfile",
|
||||
"thiserror 2.0.21",
|
||||
"unicode-segmentation",
|
||||
"wasm-bindgen-test",
|
||||
"zip",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "designcraft-epub"
|
||||
version = "0.7.1"
|
||||
version = "0.8.0"
|
||||
dependencies = [
|
||||
"designcraft-color",
|
||||
"designcraft-doc",
|
||||
@@ -1004,7 +1016,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "designcraft-fonts"
|
||||
version = "0.7.1"
|
||||
version = "0.8.0"
|
||||
dependencies = [
|
||||
"harfrust 0.13.3",
|
||||
"kurbo",
|
||||
@@ -1016,7 +1028,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "designcraft-format"
|
||||
version = "0.7.1"
|
||||
version = "0.8.0"
|
||||
dependencies = [
|
||||
"designcraft-doc",
|
||||
"serde",
|
||||
@@ -1027,7 +1039,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "designcraft-geom"
|
||||
version = "0.7.1"
|
||||
version = "0.8.0"
|
||||
dependencies = [
|
||||
"flo_curves",
|
||||
"kurbo",
|
||||
@@ -1040,7 +1052,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "designcraft-idml"
|
||||
version = "0.7.1"
|
||||
version = "0.8.0"
|
||||
dependencies = [
|
||||
"designcraft-color",
|
||||
"designcraft-compose",
|
||||
@@ -1053,7 +1065,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "designcraft-images"
|
||||
version = "0.7.1"
|
||||
version = "0.8.0"
|
||||
dependencies = [
|
||||
"designcraft-color",
|
||||
"designcraft-fonts",
|
||||
@@ -1064,7 +1076,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "designcraft-mcp"
|
||||
version = "0.7.1"
|
||||
version = "0.8.0"
|
||||
dependencies = [
|
||||
"designcraft-engine",
|
||||
"designcraft-geom",
|
||||
@@ -1077,8 +1089,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "designcraft-pdf"
|
||||
version = "0.7.1"
|
||||
version = "0.8.0"
|
||||
dependencies = [
|
||||
"craft-pdf",
|
||||
"designcraft-color",
|
||||
"designcraft-compose",
|
||||
"designcraft-doc",
|
||||
@@ -1089,7 +1102,6 @@ dependencies = [
|
||||
"hayro-interpret",
|
||||
"hayro-syntax",
|
||||
"image",
|
||||
"krilla",
|
||||
"krilla-svg",
|
||||
"kurbo",
|
||||
"log",
|
||||
@@ -1099,7 +1111,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "designcraft-render"
|
||||
version = "0.7.1"
|
||||
version = "0.8.0"
|
||||
dependencies = [
|
||||
"designcraft-color",
|
||||
"designcraft-compose",
|
||||
@@ -1117,7 +1129,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "designcraft-textimport"
|
||||
version = "0.7.1"
|
||||
version = "0.8.0"
|
||||
dependencies = [
|
||||
"designcraft-doc",
|
||||
"quick-xml 0.38.4",
|
||||
@@ -1126,7 +1138,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "designcraft-tools"
|
||||
version = "0.7.1"
|
||||
version = "0.8.0"
|
||||
dependencies = [
|
||||
"designcraft-color",
|
||||
"designcraft-compose",
|
||||
@@ -1138,7 +1150,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "designcraft-ui-egui"
|
||||
version = "0.7.1"
|
||||
version = "0.8.0"
|
||||
dependencies = [
|
||||
"craft-ui",
|
||||
"designcraft-color",
|
||||
@@ -1166,7 +1178,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "designcraft-web"
|
||||
version = "0.7.1"
|
||||
version = "0.8.0"
|
||||
dependencies = [
|
||||
"designcraft-engine",
|
||||
"designcraft-format",
|
||||
@@ -2004,13 +2016,13 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "hayro"
|
||||
version = "0.7.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c4caa128ab87fd48ffb7490617cf93f77f606820dffbc9fd9ef6ab0ed077f56d"
|
||||
source = "git+https://github.com/storytold/pdfcraft?rev=b5467d93a0ffaa5e5e6658bccdf8655a3ba689c9#b5467d93a0ffaa5e5e6658bccdf8655a3ba689c9"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"hayro-interpret",
|
||||
"image",
|
||||
"kurbo",
|
||||
"log",
|
||||
"pic-scale",
|
||||
"vello_cpu 0.0.8",
|
||||
]
|
||||
@@ -2034,8 +2046,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "hayro-interpret"
|
||||
version = "0.7.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f2613d0406898995042d0794c4245b2f2fba1246490c8ac593769bba6551129d"
|
||||
source = "git+https://github.com/storytold/pdfcraft?rev=b5467d93a0ffaa5e5e6658bccdf8655a3ba689c9#b5467d93a0ffaa5e5e6658bccdf8655a3ba689c9"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"hayro-cmap",
|
||||
@@ -2045,7 +2056,7 @@ dependencies = [
|
||||
"phf",
|
||||
"rustc-hash 2.1.3",
|
||||
"siphasher",
|
||||
"skrifa 0.42.1",
|
||||
"skrifa 0.47.0",
|
||||
"smallvec",
|
||||
"yoke",
|
||||
]
|
||||
@@ -2053,8 +2064,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "hayro-jbig2"
|
||||
version = "0.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "69374b3668dd45aeb3d3145cda68f2c7b4f223aaa2511e67d076f1c7d741388d"
|
||||
source = "git+https://github.com/storytold/pdfcraft?rev=b5467d93a0ffaa5e5e6658bccdf8655a3ba689c9#b5467d93a0ffaa5e5e6658bccdf8655a3ba689c9"
|
||||
dependencies = [
|
||||
"fearless_simd",
|
||||
"hayro-ccitt",
|
||||
@@ -2078,8 +2088,7 @@ checksum = "885c5ef0654933139a9b9546fc2c69e18d37f38aa2520f079092b1be18f1fcaa"
|
||||
[[package]]
|
||||
name = "hayro-syntax"
|
||||
version = "0.7.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0edeafd70aa2db743de8ede8637d07ec87db05efe69cde371d03f1b185fcef27"
|
||||
source = "git+https://github.com/storytold/pdfcraft?rev=b5467d93a0ffaa5e5e6658bccdf8655a3ba689c9#b5467d93a0ffaa5e5e6658bccdf8655a3ba689c9"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"hayro-ccitt",
|
||||
@@ -2088,6 +2097,7 @@ dependencies = [
|
||||
"memchr",
|
||||
"rustc-hash 2.1.3",
|
||||
"smallvec",
|
||||
"stringprep",
|
||||
"zune-jpeg",
|
||||
]
|
||||
|
||||
@@ -2437,8 +2447,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "krilla"
|
||||
version = "0.8.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "27da593198b20eeba65caeb73c2bbeec3e53ab08fa549898312ce81c4fce5e33"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c3487320b2d1de657b860b3c8abb44e1f2b32bd8#c3487320b2d1de657b860b3c8abb44e1f2b32bd8"
|
||||
dependencies = [
|
||||
"base64",
|
||||
"bumpalo",
|
||||
@@ -4199,6 +4208,17 @@ dependencies = [
|
||||
"float-cmp",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "stringprep"
|
||||
version = "0.1.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7b4df3d392d81bd458a8a621b8bffbd2302a12ffe288a9d931670948749463b1"
|
||||
dependencies = [
|
||||
"unicode-bidi",
|
||||
"unicode-normalization",
|
||||
"unicode-properties",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "subsetter"
|
||||
version = "0.2.6"
|
||||
@@ -5685,7 +5705,7 @@ checksum = "9440ea3e5aeabb0ac63af70daf835274065238cdd0cec83418f417eae38bacee"
|
||||
|
||||
[[package]]
|
||||
name = "xtask"
|
||||
version = "0.7.1"
|
||||
version = "0.8.0"
|
||||
dependencies = [
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
+10
-3
@@ -4,13 +4,15 @@ members = ["crates/*", "apps/*", "xtask"]
|
||||
default-members = ["crates/*", "apps/designcraft", "apps/designcraft-cli", "xtask"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.7.1"
|
||||
version = "0.8.0"
|
||||
edition = "2024"
|
||||
license = "MIT OR Apache-2.0"
|
||||
rust-version = "1.95"
|
||||
repository = "https://github.com/storytold/designcraft"
|
||||
|
||||
[workspace.dependencies]
|
||||
# Shared writer; the immutable revision must be published before this consumer.
|
||||
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "c3487320b2d1de657b860b3c8abb44e1f2b32bd8", version = "=0.1.0", default-features = false }
|
||||
craft-print = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "d991bf6792f8ade99c51358bf3c1d902c8cd96b5" }
|
||||
# internal
|
||||
designcraft-geom = { path = "crates/geom" }
|
||||
@@ -57,12 +59,11 @@ image = { version = "0.25", default-features = false, features = ["png", "jpeg",
|
||||
tiff = "0.11"
|
||||
# SVG (same usvg as krilla-svg).
|
||||
resvg = { version = "0.47", default-features = false, features = ["text"] }
|
||||
krilla-svg = "0.8"
|
||||
krilla-svg = "=0.8.1"
|
||||
# Boolean operations on Bézier paths (Pathfinder).
|
||||
flo_curves = "0.8"
|
||||
# QR codes (Object › Generate QR Code); MIT.
|
||||
qrcodegen = "1.8"
|
||||
krilla = { version = "0.8", features = ["pdf"] }
|
||||
hayro = "0.7"
|
||||
quick-xml = "0.38"
|
||||
zip = { version = "3", default-features = false, features = ["deflate"] }
|
||||
@@ -100,4 +101,10 @@ debug = 0
|
||||
|
||||
# Opt-in cancelable macOS termination on the pinned winit 0.30 line.
|
||||
[patch.crates-io]
|
||||
krilla = { git = "https://github.com/storytold/craft-libs", rev = "c3487320b2d1de657b860b3c8abb44e1f2b32bd8", version = "=0.8.2" }
|
||||
winit = { git = "https://github.com/skylartaylor/winit.git", rev = "3d51077fd1a966f84df9ef287839dc84fd5b4ca7" }
|
||||
# The hayro crates from pdfcraft's vendor/ directory, with the patches its README lists.
|
||||
hayro = { git = "https://github.com/storytold/pdfcraft", rev = "b5467d93a0ffaa5e5e6658bccdf8655a3ba689c9" }
|
||||
hayro-interpret = { git = "https://github.com/storytold/pdfcraft", rev = "b5467d93a0ffaa5e5e6658bccdf8655a3ba689c9" }
|
||||
hayro-syntax = { git = "https://github.com/storytold/pdfcraft", rev = "b5467d93a0ffaa5e5e6658bccdf8655a3ba689c9" }
|
||||
hayro-jbig2 = { git = "https://github.com/storytold/pdfcraft", rev = "b5467d93a0ffaa5e5e6658bccdf8655a3ba689c9" }
|
||||
|
||||
@@ -52,12 +52,23 @@ list (author, source, license) is in ASSETS.md.
|
||||
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
|
||||
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
- Norwegian hyphenation patterns, embedded through the hypher crate (feature "norwegian"):
|
||||
hyph-no.tex from hyph-utf8, https://github.com/hyphenation/tex-hyphen.
|
||||
Copyright (C) Rune Kleveland and Ole Michael Selberg. Copying and distribution of this file,
|
||||
with or without modification, is permitted in any medium without royalty provided the copyright
|
||||
notice and this notice are preserved (additionally distributed under the LaTeX Project Public
|
||||
License in CTAN distributions).
|
||||
- Japanese fonts (craft-fonts): builds made with craft-fonts (CRAFT_FONTS_DIR; all official
|
||||
releases) embed the fonts listed in
|
||||
https://github.com/storytold/craft-fonts/blob/main/ATTRIBUTION.md (BIZ UDPGothic, BIZ UDMincho,
|
||||
Shippori Mincho), under the SIL Open Font License 1.1. Their licence texts ship with the
|
||||
packages as OFL-<family>.txt. Builds without CRAFT_FONTS_DIR do not include them.
|
||||
- All UI icons are drawn in code (crates/ui-egui/src/icons.rs) and are original work, MIT OR Apache-2.0.
|
||||
- hayro PDF crates (placed PDFs): hayro, hayro-interpret, hayro-syntax and hayro-jbig2
|
||||
(Apache-2.0 OR MIT) are pdfcraft's patched copies, fetched by git from its vendor/ directory at
|
||||
the commit that Cargo.toml pins (https://github.com/storytold/pdfcraft, MIT OR Apache-2.0).
|
||||
hayro-interpret embeds PDFium's Foxit standard-14 fonts under PDFium's BSD-style license
|
||||
(vendor/hayro-interpret/assets/LICENSE_FOXIT) and a CMYK profile under CC0-1.0.
|
||||
|
||||
Rust dependencies (vello_cpu, kurbo, skrifa, harfrust, image, egui, eframe, …) are permissively
|
||||
licensed (MIT/Apache-2.0/BSD/ISC/Zlib) and fetched through crates.io.
|
||||
|
||||
@@ -141,6 +141,7 @@ The file stops growing at 16 MiB. `--version` writes no file.
|
||||
|---|---|
|
||||
| `RUST_LOG` | Log levels for standard error and the log file. Default: `info` for DesignCraft's own crates, `warn` for everything else. env_logger-style directives replace that, e.g. `RUST_LOG=debug`, `RUST_LOG=warn,designcraft_render=trace` or `RUST_LOG=info,wgpu_core=warn`; a directive ending in `*` covers every target starting with it (`designcraft*=debug`). |
|
||||
| `WGPU_BACKEND` | The graphics backend that composites the window: `dx12`, `vulkan`, `gl` or `metal` (a comma-separated list lets wgpu choose among them). Default: DirectX 12 on Windows, Vulkan on Linux, Metal on macOS, with OpenGL as the fallback. Setting it also turns off the start-up fallback described below. |
|
||||
| `WGPU_VALIDATION_INDIRECT_CALL` | `1` turns wgpu's check of indirect draw arguments back on. DesignCraft draws nothing indirectly and turns it off, since the compute shader the check needs fails to compile on some drivers (Metal on an Intel Iris Pro), which lost the device before the window opened. |
|
||||
|
||||
The logger is `apps/designcraft/src/logging.rs`; the web build logs to the browser console instead.
|
||||
|
||||
@@ -222,6 +223,7 @@ Installers and executables are code-signed.
|
||||
| Flatpak | `designcraft-<ver>-linux-x86_64.flatpak` | `designcraft-<ver>-linux-aarch64.flatpak` | Sandboxed; `flatpak install --user <file>` |
|
||||
| Debian/Ubuntu | `designcraft-<ver>-linux-x86_64.deb` | `designcraft-<ver>-linux-aarch64.deb` | |
|
||||
| Fedora/RHEL/openSUSE | `designcraft-<ver>-linux-x86_64.rpm` | `designcraft-<ver>-linux-aarch64.rpm` | |
|
||||
| Arch Linux/Manjaro | `designcraft-<ver>-linux-x86_64.pkg.tar.zst` | `designcraft-<ver>-linux-aarch64.pkg.tar.zst` | `sudo pacman -U <file>`; installs as `ai.storyteller.designcraft`, replacing an AUR package |
|
||||
| Tarball | `designcraft-<ver>-linux-x86_64.tar.gz` | `designcraft-<ver>-linux-aarch64.tar.gz` | Unpack anywhere |
|
||||
|
||||
RISC-V (riscv64): `designcraft-<ver>-linux-riscv64.tar.gz` only, cross-compiled; needs glibc 2.39+ (Ubuntu 24.04 or newer).
|
||||
|
||||
+80
-13
@@ -1,8 +1,13 @@
|
||||
# DesignCraft roadmap
|
||||
|
||||
**Stage: pre-alpha** · next: alpha, ~0% and ~15–25 h away; beta ~28 points and ~420–750 h beyond that (the core-workflow gate, not the percentage: ready for real work is already ~47%)
|
||||
**Stage: pre-alpha** · next: alpha, ~5–7 h away; beta ~28 points and ~420–750 h beyond that (the core-workflow gate, not the percentage: ready for real work is already ~47%)
|
||||
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-12 · **Change:** minor (cancelable macOS Dock Quit) · **Target:** Adobe InDesign 2026
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-12 · **Change:** minor (text threads by hand; the alpha gate waits on Primary Text Frame page fixes) · **Target:** Adobe InDesign 2026
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-13 · **Change:** minor (parent canvas refresh) · **Target:** Adobe InDesign 2026
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-13 · **Change:** minor (bounded control click/drag input) · **Target:** Adobe InDesign 2026
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-12 · **Change:** minor (text stroke behind fill) · **Target:** Adobe InDesign 2026
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-13 · **Change:** minor (text threads by hand; the alpha gate waits on Primary Text Frame page fixes; Links source paths) · **Target:** Adobe InDesign 2026
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-13 · **Change:** minor (table anchors keep their own paragraphs) · **Target:** Adobe InDesign 2026
|
||||
|
||||
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.
|
||||
@@ -25,15 +30,14 @@ format + IDML), scriptable by agents (MCP), and available on the web.
|
||||
| Essentials user | ~54% | 135–250 (~50% parallel) | start-up robustness, context menus and copy/paste, threading, fonts, Windows printing |
|
||||
|
||||
**Why pre-alpha:** it fails one of InDesign's core workflows, the alpha gate in
|
||||
[docs/roadmap.md](docs/roadmap.md#alpha-gate). A user can't thread a story from one frame to
|
||||
another: the in and out ports are drawn, but clicking the out port does nothing and there is no
|
||||
thread or unthread command. Long text flows only through autoflow on Place and Primary Text
|
||||
Frame, which users report adding and keeping pages wrongly (#165, #140, #194, #352). Everything
|
||||
else in the gate works end to end on macOS (document setup, styles, images, object editing, PDF
|
||||
export, save and reopen), and ready for real work (~47%) is above the alpha bar, so manual
|
||||
threading is the whole distance to alpha. Beyond that, beta needs INDD opening, IDML proven on
|
||||
real files, composition compared with InDesign's, and basic editing fixed on Windows and Linux.
|
||||
Details: [docs/target-app-parity.md](docs/target-app-parity.md).
|
||||
[docs/roadmap.md](docs/roadmap.md#alpha-gate). Text threads by hand (click a port, then click or
|
||||
draw a frame; thread and unthread commands), but Primary Text Frame autoflow adds pages users
|
||||
can't delete (#165). Everything else in the gate works end to end on macOS (document setup,
|
||||
styles, images, object editing, PDF export, save and reopen), and ready for real work (~47%) is
|
||||
above the alpha bar, so the Primary Text Frame page fixes are the whole distance to alpha.
|
||||
Beyond that, beta needs INDD opening, IDML proven on real files, composition compared with
|
||||
InDesign's, and basic editing fixed on Windows and Linux. Details:
|
||||
[docs/target-app-parity.md](docs/target-app-parity.md).
|
||||
|
||||
## By dimension
|
||||
|
||||
@@ -99,14 +103,14 @@ Interface strings translated, of 1,724 measured. Detail: [docs/localization-pari
|
||||
| Korean | ko | none | 0% |
|
||||
| Vietnamese | vi | none | 0% |
|
||||
|
||||
Also shipped: Italian (85%), Ukrainian (83%).
|
||||
Also shipped: Italian (85%), Ukrainian (83%), Georgian (100%).
|
||||
|
||||
## Upcoming
|
||||
|
||||
Ranked; detail and estimates in [docs/roadmap.md](docs/roadmap.md), the full list in
|
||||
[docs/gaps.md](docs/gaps.md).
|
||||
|
||||
1. **Alpha gate:** manual text threading (out-port click, thread/unthread commands) and Primary Text Frame fixes (#165) (15–25 h)
|
||||
1. **Alpha gate:** Primary Text Frame page fixes: autoflow adds pages users can't delete (#165) (5–7 h)
|
||||
2. Basic editing on every platform: copy/paste, context menus, caret formatting (30–50 h)
|
||||
3. CI running `cargo xtask ci` on pull requests (4–8 h)
|
||||
4. Open INDD through a clean-room converter, owner decision on #114 (20–60 h)
|
||||
@@ -127,9 +131,65 @@ list) · [roadmap.md](docs/roadmap.md) (milestones, plan) · [parity-checklist.m
|
||||
|
||||
## Progress log
|
||||
|
||||
- **2026-10-13** · Switching between document and parent pages refreshes the canvas immediately, preventing black parent pages and stale document objects when the zoom stays the same. Ordinary edits retain partial repainting. No readiness percentage change.
|
||||
|
||||
Newest first.
|
||||
|
||||
- **2026-10-14** · The Type tool draws a new text frame over a locked empty frame, as InDesign does, instead of turning the locked frame into a text frame. No readiness percentage change.
|
||||
- **2026-10-14** · 100% black shows as pure black on screen by default, as InDesign's Appearance of Black does out of the box (Display All Blacks as Rich Black); Preferences › Appearance of Black › Display All Blacks Accurately still shows it as the dark grey it prints, and a saved choice is kept. No readiness percentage change.
|
||||
- **2026-10-14** · Pathfinder keeps the frontmost object, as InDesign does: a photo placed over shapes and intersected with them shows through the shapes (it was dropped, and the shapes kept their black fill); Add, Exclude Overlap and Minus Back take the front object's fill too, Subtract still keeps the back one. No readiness percentage change.
|
||||
- **2026-10-14** · The Color panel's Tint field keeps what is typed while it has focus and applies it on Enter or when it loses focus, clamped to 0–100 %. Typing 60 over 100 % no longer snaps back to 100 after the first digit (10060), and a typed tint is no longer ignored. No readiness percentage change.
|
||||
- **2026-10-15** · IDML: ruler guides import and export (they were dropped). Each page's guides come in measured from the document's ruler origin (spread, page or spine), with Fit to Page, Locked and their layer, parent pages' included, and go out again under their pages. No readiness percentage change.
|
||||
- **2026-10-15** · Find Font no longer reports a style missing when it differs from the installed one only in spacing or case (InDesign files can name `Regular ` with a trailing space); the text was already drawn in the right face. No readiness percentage change.
|
||||
- **2026-10-15** · A line of text is set when its baseline fits in the frame, as in InDesign: descenders may hang below the frame's bottom. A frame sized to the cap height of a big heading (103 pt in a 2.77 cm frame, as Zero2Graphic's magazine tutorial draws them) no longer oversets. No readiness percentage change.
|
||||
- **2026-10-15** · A story that ends with a return is no longer overset when only its empty last paragraph doesn't fit, as in InDesign (Preflight said "Overset text: 0 characters" for a caption InDesign shows with no errors). No readiness percentage change.
|
||||
- **2026-10-13** · Object › Fitting has InDesign's shortcuts: Fill Frame Proportionally ⌘⌥⇧C, Fit Content Proportionally ⌘⌥⇧E, Fit Frame to Content ⌘⌥C, Fit Content to Frame ⌘⌥E, Center Content ⌘⇧E. No readiness percentage change.
|
||||
- **2026-10-13** · Gradients between process colours blend as inks, as InDesign shows them: magenta to cyan passes through C 50 M 50 (a light lilac) on screen instead of the darker RGB mix, and a midpoint between CMYK or grey stops no longer turns the PDF shading RGB. No readiness percentage change.
|
||||
- **2026-10-14** · The Swatches panel has InDesign's header: a Fill/Stroke proxy, Formatting Affects Container/Text and the Tint of the colour in front (a tint alone keeps each object's own swatch). Clicking a swatch applies it to the fill or stroke in front (of the text, when formatting affects text), and the bottom row has New Color Group, New Swatch and Delete Swatch. No readiness percentage change.
|
||||
- **2026-10-14** · With the Page tool, the Control panel shows the page as InDesign's does: W/H from a reference point, page-size preset (US Business Card added), orientation, Liquid Page Rule (now with Controlled by Parent) and Show Parent Page Overlay, which draws the parent page's size over a resized page. No readiness percentage change.
|
||||
- **2026-10-14** · On an object-based page the Page tool shows a selected object's liquid pins and resize locks as InDesign does: a click pins a side to the page edge or locks the width or height, with InDesign's tooltips. No readiness percentage change.
|
||||
- **2026-10-14** · The Liquid Layout panel follows InDesign's: Liquid Page Rule with the page number, Content › Auto-Fit, and Object Constraints › Resize with Page and Pin for the selected object on an object-based page; Create Alternate Layout moved to the Layout menu. No readiness percentage change.
|
||||
- **2026-10-14** · With the Page tool, the Control panel shows the page as InDesign's does: W/H from a reference point, page-size preset (US Business Card added), orientation, Liquid Page Rule (now with Controlled by Parent) and Show Parent Page Overlay, which draws the parent page's size over a resized page. No readiness percentage change.
|
||||
- **2026-10-14** · With the Page tool, the Control panel shows the page as InDesign's does: W/H from a reference point, page-size preset (US Business Card added), orientation, Liquid Page Rule and Show Parent Page Overlay, which draws the parent page's size over a resized page. No readiness percentage change.
|
||||
- **2026-10-14** · The Page tool works as InDesign's: a click selects a page and shows its handles and liquid page rule; dragging a handle previews the rule and springs back, Alt-drag resizes the page from the opposite edge, Shift keeps proportions, with a W/H readout. No readiness percentage change.
|
||||
- **2026-10-14** · With the Page tool, a guide dragged from a ruler is a liquid guide (dashed), as in InDesign; guide-based pages stretch the objects it crosses. No readiness percentage change.
|
||||
- **2026-10-14** · The Pages panel menu follows InDesign's order: Insert Pages…, Move Pages…, Duplicate Spread (and at End of Document), Delete Page/Spread, New Parent…, Apply Parent to Pages, Override All Parent Page Items, Parent Pages, Create Alternate Layout…, Numbering & Section Options…, Allow Selected Spread to Shuffle. No readiness percentage change.
|
||||
- **2026-10-14** · Pages panel: Alt-drag copies a page, a page dropped on Create new page is duplicated at the end, Edit page size offers the presets and Custom Page Size…; duplicated pages keep their own size, rule and guides; thumbnails of pages of their own size stay in their rows. No readiness percentage change.
|
||||
- **2026-10-12 (PDFW)** · PDF, booklet and book composition share guarded writing, metadata and font preparation through craft-pdf. Layout, shaping, placed graphics, colour policy, tagging and PDF/X postprocessing remain in DesignCraft. Failed native drawing returns an export error; failed writer cleanup cannot serialize an incomplete document. No readiness percentage change.
|
||||
|
||||
- **2026-10-13** · Copy with a placed graphic selected (Direct Selection) copies just the graphic, uncropped, where it sits on the page and without the frame's stroke, so Paste Into puts the whole image in place; Cut and Delete then remove only the graphic and leave its frame empty. Nested selections copy in their spread coordinates. No readiness percentage change.
|
||||
- **2026-10-13** · Object effects (Basic Feather, Inner Glow, shadows, glows, bevel, satin, directional and gradient feathers) apply to frames with pasted-in content, on screen and in image exports: the frame, its clipped content and its stroke are one object to the effect. PDF export still has no soft effects for any object. No readiness percentage change.
|
||||
- **2026-10-13** · Links rows show their source paths; selecting a link shows its full path wrapped inside the panel, so same-named files from different folders can be distinguished. No readiness percentage change.
|
||||
- **2026-10-13** · The Text Wrap panel is laid out as InDesign's: the wrap buttons with Invert, and the four offsets (Top, Left, Bottom, Right) showing the object's values, with the link button that sets them all the same. It used to show a single offset, always 0. No readiness percentage change.
|
||||
- **2026-10-13** · Radial gradients stretch with the object's box, as InDesign draws them: by default an ellipse reaching the frame's sides (it was a circle reaching only the longer side), and a Gradient Swatch tool drag keeps the box's proportions; on screen and in PDF. No readiness percentage change.
|
||||
- **2026-10-13** · The Window menu follows InDesign's order (Arrange, Workspace, then the panels alphabetically with Color, Editorial, Object & Layout, Styles… submenus), and Window › Workspace lists the workspaces as InDesign does, now with Essentials Classic: the Control panel and an icon column of named panel groups. No readiness percentage change.
|
||||
- **2026-10-14** · In a facing document, pages take their side from their section's page numbers, as InDesign shuffles them: a section that starts at 1 on a left page moves it to the right and the pages after it follow, with their objects. No readiness percentage change.
|
||||
- **2026-10-14** · The Type menu follows InDesign's order (Size, Character ⌘T, Paragraph ⌥⌘T, Glyphs, the style panels, Notes, footnotes and endnotes, then the insert submenus and Show Hidden Characters); Current Page Number has ⌥⇧⌘N. No readiness percentage change.
|
||||
- **2026-10-14** · Colour parameters: a bare `{c,m,y,k}` is always read as 0..100, so C 1 is a 1 % tint and no longer
|
||||
solid cyan; fractions take the colour's own `{model: "cmyk", …}` form (#910). No readiness percentage change.
|
||||
- **2026-10-14** · The Tools panel follows InDesign's: Gradient Swatch and Gradient Feather are tools of their own; in two columns Content Collector and Placer, Apply Color / Gradient / None and Normal / Preview each get a button; View Options holds Frame Edges, Rulers, Guides, Smart Guides, Baseline Grid and Hidden Characters; Apply Color (,) and Apply Gradient (.) reuse the last colour and gradient. No readiness percentage change.
|
||||
- **2026-10-12** · Text threads by hand: click a selected text frame's in or out port to load
|
||||
the text cursor, then click a frame to thread it, click empty space for a column-wide frame or
|
||||
drag one (it snaps like frame drawing); Shift-click autoflows, Alt-click stays loaded on the
|
||||
frame just added; click the linked frame or double-click a port to break the thread.
|
||||
`text.thread`, `text.unthread`, `text.removeFromThread` with undo; locked frames and layers
|
||||
refuse threads. The alpha gate now waits only on the Primary Text Frame page fixes (#165). No
|
||||
readiness percentage change.
|
||||
- **2026-10-14** · Georgian interface (`ka`, Edit ▸ Interface Language ▸ ქართული): every catalog key
|
||||
translated, count captions as `noun: n`.
|
||||
- **2026-10-13** · Layout ▸ Table of Contents opens a real dialog: title and title style, Include Paragraph Styles and Other Styles lists with Add and Remove, and per style its entry style, page number position (after, before, none), separator and level. Replace Existing regenerates the current table of contents in place; otherwise OK makes a new frame on the page in view. IDML export writes the definition as a TOC style that import reads back, so Update works after a round trip. No readiness percentage change.
|
||||
- **2026-10-13** · Control-channel clicks and drags validate positive counts and the complete pending-event budget before queuing input (#732). Oversized requests leave pending gestures intact, preventing unbounded click-count allocation. No readiness percentage change.
|
||||
- **2026-10-13** · Backspace between two consecutive tables, pasting a table next to a table anchor, and pasting several paragraphs right before one keep every table on its own anchor paragraph. Previously a table was dropped or left without its anchor, and the saved file failed to reopen. No readiness percentage change.
|
||||
- **2026-10-13** · Dialogs and the About window move when you drag their title row, so the page behind them can be seen. A dragged dialog may go partly off-screen, but its title row stays reachable; each dialog opens centred, and again after the window is resized. No readiness percentage change.
|
||||
- **2026-10-13** · Command scripts look up only a well-formed `$N.path` / `$last.path` reference; other strings starting with `$`, such as a GREP replacement of `$1` and a nonbreaking space, stay as written, and `$$` writes a literal `$` (#749). No readiness percentage change.
|
||||
- **2026-10-13** · An explicit recovery folder (`file.recovery.save` with `dir`) never overwrites or deletes another running app's checkpoints. Document uids start at 1 in every process, so two apps saving recovery to one chosen folder replaced or removed each other's `<uid>.designcraft`. A run replaces or removes only the entries it wrote or recovered there, refuses an occupied uid, and refuses a folder whose run lock another app holds. No readiness percentage change.
|
||||
- **2026-10-13** · Path edits (`path.setAnchor`, `path.moveAnchors`, `path.appendAnchor`, `path.reverse`, `path.close`, anchor add/delete/convert, Erase, Smooth and Scissors) refuse a path that is locked, sits in a locked group or on a locked layer (#735). Properties links to the Stroke, Character, Paragraph, Effects, Text Wrap and Info panels open them in a customized panel layout too (#736). No readiness percentage change.
|
||||
- **2026-10-13** · IDML export keeps parent item overrides: each page lists its overridden parent items and the local copy keeps its link to the parent item, so a reopened IDML file shows only the local copy (#725). No readiness percentage change.
|
||||
- **2026-10-13** · macOS: a command chosen with the mouse in the menu bar runs at once. It used to wait for the next mouse move or key press over the window, so File › Open, Place and Save As seemed to take 10–20 seconds to open their dialogs. No readiness percentage change.
|
||||
- **2026-10-13** · Text recomposes when the document baseline grid changes, when a layer holding a text-wrap object is shown or hidden, or when a section's start number, numbering style, prefix or marker changes; the composition cache keyed only on the section count and item identities and kept the old layout. No readiness percentage change.
|
||||
- **2026-10-12** · macOS Dock Quit uses the same unsaved-document prompts as window and menu Quit. Repeated requests keep the current answers; Cancel retains every tab and unsaved recovery checkpoint, and completed Save/Don't Save answers exit through the ordinary event loop. No readiness percentage change.
|
||||
- **2026-10-12** · Text strokes can sit behind the fill: the stroke lies wholly outside the letters at its full weight on screen, in PNG and in PDF, set from the Properties panel or Character Style Options. IDML `StrokeAlignment` on text imports and exports as this setting, so imported text with outside-aligned strokes keeps its letter shapes (#619). No readiness percentage change.
|
||||
- **2026-10-12** · Placed Word documents keep their bullets and numbering (#626): `numbering.xml` levels become bullet or numbered paragraphs with Word's number formats, label text, start numbers, restarts and list indents, also when a paragraph style carries the list. No readiness percentage change.
|
||||
- **2026-10-12** · Orderly native exit writes the latest recovery state after finalizing current quit approvals; incomplete or stale plans keep their documents, and Undo to the saved state clears stale recovery. Unavailable or failed recovery is reported. Cancelable macOS Dock Quit remains open (#544). No readiness percentage change.
|
||||
- **2026-10-12** · Recovered documents keep a checkpoint until saved, closed or reverted, including a second crash before autosave. Restarted document IDs and explicit recovery folders preserve other snapshots; failed republishing retains the original. No readiness percentage change.
|
||||
- **2026-10-12** · Book numbering and style updates prepare every chapter before saving. Only closed native chapters are changed; imported IDML remains a read-only style/PDF source. If a later disk write fails, the error names the completed chapters; the batch is not a whole-book transaction. No readiness percentage change.
|
||||
@@ -138,6 +198,7 @@ Newest first.
|
||||
- **2026-10-12** · The Pen tool continues an open path from either end point, as in InDesign: the cursor shows it over an end point, a click there carries on drawing that path, a drag first reshapes the end point's direction lines, and the other end closes it. Object › Paths › Reverse Path (`path.reverse`); `path.setAnchor`; `path.appendAnchor` and `path.close` take a subpath. No readiness percentage change.
|
||||
- **2026-10-12** · Editing type on a path: the Type tool clicks, drags and double-clicks along the curve (the character under the pointer, not one on the straightened line), a click on the letters themselves hits the frame, and the caret and highlight bend with the path. No readiness percentage change.
|
||||
- **2026-10-12** · Type on a path has start and end brackets, as in InDesign: selected path type shows them across the path, and dragging either with the Selection or Direct Selection tool moves where the text starts or ends (text past the end bracket is overset). `type.pathOptions {end}`; IDML reads and writes EndBracket. No readiness percentage change.
|
||||
- **2026-10-12** · The Eyedropper puts a colour sampled from an image on the stroke when the toolbox's Stroke box is in front, as in InDesign (a line takes it on its stroke). No readiness percentage change.
|
||||
- **2026-10-12** · Window close and application/menu Quit ask about unsaved documents; later Cancel keeps every tab open, including earlier Don't Save choices. Approvals are rechecked after edits. Cancelable macOS Dock Quit remains open (#544). No readiness percentage change.
|
||||
- **2026-10-12** · Each running app keeps recovery data in its own locked folder; current folder and lock ownership are checked before writes and cleanup. Failed isolation disables recovery with a warning instead of sharing document IDs. No readiness percentage change.
|
||||
- **2026-10-12** · Native engine saves and exports replace files atomically; failed writes retain the original, private staging preserves Unix permissions, and valid long filenames work. Desktop Services and CLI raster exports remain separate follow-ups. No readiness percentage change.
|
||||
@@ -147,13 +208,18 @@ Newest first.
|
||||
- **2026-10-11** · `story.replaceRange`, `story.setText`, notes, footnotes, endnotes, type on a path and table cells read `\r` and `\r\n` as paragraph returns, as `frame.create` and `text.insert` already did. No readiness percentage change.
|
||||
- **2026-10-11** · The View menu follows InDesign's: proofing first, then zoom, Rotate Spread, Screen Mode, Display Performance, rulers, Extras, Grids & Guides and Structure; the view items that sat at the end of the Type menu moved there. No readiness percentage change.
|
||||
- **2026-10-12** · Underlines and strikethroughs are drawn as one bar per stretch of text on screen, as in PDF export: a bar per letter left faint seams between the letters. No readiness percentage change.
|
||||
- **2026-10-13** · Placed PDFs are drawn through pdfcraft's patched hayro crates: calculator functions whose `idiv` divides by zero or overflows, chains of stitching functions a hundred thousand deep, and mesh shadings with points far off the page, ten thousand overlapping triangles or forty thousand patches no longer panic, overflow the stack, run for over a minute or use more than 2 GiB of memory. A page with a `/UserUnit`, and its trim, bleed and art boxes, are sized in points. No readiness percentage change.
|
||||
- **2026-10-12** · Properties › Transform shows rotation, shear and X/Y scale, and Rotate 90° and Flip Horizontal/Vertical buttons, as InDesign's does. No readiness percentage change.
|
||||
- **2026-10-12** · Edit › Step and Repeat has its InDesign dialog: Repeat (Count, or Rows and Columns with Create as a grid), Offset (Vertical, Horizontal, in ruler units) and Preview, which shows the copies while the dialog is open; Cancel takes them away and OK makes them as one undo step. No readiness percentage change.
|
||||
- **2026-10-12** · Double-clicking the Fill or Stroke box in the Tools panel opens the Color Picker with the selection's colour, as in InDesign (it opened the Swatches panel). No readiness percentage change.
|
||||
- **2026-10-12** · The Effects panel shows the level its settings apply to ("Group: Color Dodge 100%") and, as in InDesign, Isolate Blending and Knockout Group for a selected group. No readiness percentage change.
|
||||
- **2026-10-11** · Properties gains InDesign's Pathfinder section (Add, Subtract, Intersect, Exclude Overlap, Minus Back) with several objects selected; section titles and icon buttons have accessible names. No readiness percentage change.
|
||||
- **2026-10-12** · The Eyedropper samples a placed image: clicking the photo with text (or objects) selected fills them with the image's colour under the pointer, as an unnamed colour (`color.sample`), as in InDesign. Images on locked layers can be sampled. No readiness percentage change.
|
||||
- **2026-10-12** · The section marker character shows its section's marker text on document pages (nothing when the section has none) instead of the word "Section", which stays on parent pages; editing the marker recomposes (#556). No readiness percentage change.
|
||||
- **2026-10-12** · On screen, blend modes blend with the objects below and not with the paper, as in InDesign and in PDF export: a Color Dodge or Screen object over blank paper shows as it is. No readiness percentage change.
|
||||
- **2026-10-12** · A gradient feather on a group fades the group as one, on screen and in PDF. Before, the screen ignored it, and PDF masked the group with a box of zero size because a group has no path of its own. No readiness percentage change.
|
||||
- **2026-10-12** · Words in capitals hyphenate like capitalized words (FERRUM COM-MODI), as in InDesign; Hyphenate Capitalized Words off keeps them whole. No readiness percentage change.
|
||||
- **2026-10-12** · Load Swatches refuses an `.ase` file with more than 100,000 colors, and `swatch.load` merges a file of 100,000 colors in under 0.1 s (it took 9.6 s of CPU in a test build). No readiness percentage change.
|
||||
- **2026-10-11** · `transform.move {copy}`, Edit › Duplicate and Step and Repeat return the copies' ids, so a script can go on with them. No readiness percentage change.
|
||||
- **2026-10-11** · `object.fill` and `object.stroke` refuse a swatch name the document doesn't have (it painted nothing) and suggest the name meant (`Paper` → `[Paper]`). No readiness percentage change.
|
||||
- **2026-10-11 (printing):** `file.printers` and `file.print` use craft-libs/craft-print for CUPS and Windows. DesignCraft retains PDF export, page selection, spreads, marks and bleed; dry runs create no temporary PDF or print job. Windows selects matching or default driver paper and shrinks oversized sheets without enlarging smaller ones; queue duplex defaults are preserved. Headless tests exercise exported bytes, job settings, dry runs and refusals; shared native Windows CI passes, including paused-queue submission and cleanup. PostScript, production print controls and physical output validation remain open. No readiness percentage change.
|
||||
@@ -195,6 +261,7 @@ Newest first.
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-10-12 | minor | Manual text threading landed; alpha distance 15–25 h → 5–7 h (Primary Text Frame page fixes, #165) |
|
||||
| 2026-10-10 | minor | Full number 42% → 47% (method aligned with the standard: plain weighted sum, no new evidence); readiness table with hours per audience |
|
||||
| 2026-10-10 | minor | Headline adds mainstream practitioner (~42%) and essentials user (~54%); method in docs/target-app-parity.md |
|
||||
| 2026-10-10 | minor | Stage alpha → pre-alpha under the new core-workflow gate: manual text threading is missing; alpha gate table added to docs/roadmap.md |
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
//! Parse `--automation-read-root` / `--automation-write-root` before the server starts. A malformed
|
||||
//! flag must not silently remove a root and leave the server unconfined.
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
pub struct AutomationArgs {
|
||||
pub read_root: Option<PathBuf>,
|
||||
pub write_root: Option<PathBuf>,
|
||||
read_given: bool,
|
||||
write_given: bool,
|
||||
}
|
||||
|
||||
impl AutomationArgs {
|
||||
pub fn new(read_root: Option<PathBuf>, write_root: Option<PathBuf>) -> Self {
|
||||
Self { read_root, write_root, read_given: false, write_given: false }
|
||||
}
|
||||
|
||||
/// Returns whether this argument is a root flag. A second occurrence of a flag is an error,
|
||||
/// including when the two spellings (`--flag DIR`, `--flag=DIR`) are mixed.
|
||||
pub fn consume(&mut self, arg: &str, args: &mut impl Iterator<Item = String>) -> Result<bool, String> {
|
||||
let (flag, inline) = arg.split_once('=').map_or((arg, None), |(flag, value)| (flag, Some(value)));
|
||||
let (root, given) = match flag {
|
||||
"--automation-read-root" => (&mut self.read_root, &mut self.read_given),
|
||||
"--automation-write-root" => (&mut self.write_root, &mut self.write_given),
|
||||
_ => return Ok(false),
|
||||
};
|
||||
if *given {
|
||||
return Err(format!("{flag} given twice"));
|
||||
}
|
||||
let value = match inline {
|
||||
Some(value) => value.to_owned(),
|
||||
None => {
|
||||
let value = args.next().ok_or_else(|| format!("{flag} needs a folder"))?;
|
||||
if value.starts_with('-') {
|
||||
return Err(format!("{flag} needs a folder; use {flag}=<dir> for a folder starting with '-'"));
|
||||
}
|
||||
value
|
||||
}
|
||||
};
|
||||
if value.is_empty() {
|
||||
return Err(format!("{flag} needs a non-empty folder"));
|
||||
}
|
||||
*root = Some(value.into());
|
||||
*given = true;
|
||||
Ok(true)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn roots_are_taken_once_and_other_arguments_are_left() {
|
||||
let mut roots = AutomationArgs::new(None, None);
|
||||
let mut args = ["a folder".to_owned(), "doc.designcraft".to_owned()].into_iter();
|
||||
assert!(roots.consume("--automation-read-root", &mut args).unwrap());
|
||||
assert!(roots.consume("--automation-write-root=out", &mut args).unwrap());
|
||||
assert!(!roots.consume("--sample", &mut args).unwrap());
|
||||
assert_eq!(roots.read_root, Some("a folder".into()));
|
||||
assert_eq!(roots.write_root, Some("out".into()));
|
||||
assert_eq!(args.next().as_deref(), Some("doc.designcraft"));
|
||||
assert!(roots.consume("--automation-read-root=other", &mut args).is_err());
|
||||
assert_eq!(roots.read_root, Some("a folder".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_operands_leave_roots_unchanged() {
|
||||
for flag in ["--automation-read-root", "--automation-write-root"] {
|
||||
for operand in [None, Some(""), Some("--version"), Some("--connect"), Some("-folder")] {
|
||||
let mut roots = AutomationArgs::new(Some("read".into()), Some("write".into()));
|
||||
let mut args = operand.map(str::to_owned).into_iter();
|
||||
assert!(roots.consume(flag, &mut args).is_err(), "{flag} {operand:?}");
|
||||
assert_eq!(roots.read_root, Some("read".into()));
|
||||
assert_eq!(roots.write_root, Some("write".into()));
|
||||
}
|
||||
let mut roots = AutomationArgs::new(None, None);
|
||||
assert!(roots.consume(&format!("{flag}="), &mut std::iter::empty()).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_dash_folder_and_relative_dash_folder_are_valid() {
|
||||
let mut roots = AutomationArgs::new(None, None);
|
||||
assert!(roots.consume("--automation-read-root=-folder", &mut std::iter::empty()).unwrap());
|
||||
assert!(roots.consume("--automation-write-root", &mut ["./-folder".to_owned()].into_iter()).unwrap());
|
||||
assert_eq!(roots.read_root, Some("-folder".into()));
|
||||
assert_eq!(roots.write_root, Some("./-folder".into()));
|
||||
}
|
||||
}
|
||||
@@ -9,7 +9,8 @@
|
||||
//! # run a command script (crates/engine/src/script.rs): `$N.path` references
|
||||
//! designcraft-cli app [--port PORT] COMMAND [JSON] # run a command in the running app (designcraft --control PORT)
|
||||
//! designcraft-cli app [--port PORT] --method METHOD [JSON] # any control-channel method (ui.screenshot, ui.render, …)
|
||||
//! designcraft-cli mcp [--connect PORT] [--sample] # MCP server over stdio (docs/mcp.md)
|
||||
//! designcraft-cli mcp [--connect PORT] [--sample] [--automation-read-root DIR] [--automation-write-root DIR]
|
||||
//! # MCP server over stdio (docs/mcp.md); the roots confine the files it reads and writes
|
||||
//! designcraft-cli perf [--pages N] [--frames N] [--chars N] [--images N] [--runs N] [--strict] # budgets on a synthetic stress document
|
||||
//! designcraft-cli bench FILE [--runs N] # the same measurements on one document
|
||||
//! designcraft-cli validate-pdf FILE.pdf # run the built-in PDF/X-4 conformance checks
|
||||
@@ -30,13 +31,14 @@ macro_rules! outln {
|
||||
}};
|
||||
}
|
||||
|
||||
mod automation_args;
|
||||
mod perf;
|
||||
|
||||
use designcraft_engine::Session;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
/// The usage block. Shared by `--help` (stdout, success) and an unknown command (stderr, failure).
|
||||
const USAGE: &str = "usage: designcraft-cli run [--in FILE | --sample] [--cmd ID[=JSON]]... [--page N] [--scale S] [--pdf-options JSON] [--export OUT] [--all-pages DIR]\n (--page, --scale and --pdf-options apply to the exports that follow them)\n designcraft-cli commands [FILTER]\n designcraft-cli describe COMMAND\n designcraft-cli script [FILE|-] [--in FILE | --sample] [--connect PORT] [--save OUT] [--export OUT] [--keep-going]\n designcraft-cli app [--port PORT] COMMAND [JSON] | --method METHOD [JSON]\n designcraft-cli mcp [--connect PORT] [--sample]\n designcraft-cli perf [--pages N] [--runs N] [--strict]\n designcraft-cli bench FILE [--runs N]\n designcraft-cli links\n designcraft-cli --version";
|
||||
const USAGE: &str = "usage: designcraft-cli run [--in FILE | --sample] [--cmd ID[=JSON]]... [--page N] [--scale S] [--pdf-options JSON] [--export OUT] [--all-pages DIR]\n (--page, --scale and --pdf-options apply to the exports that follow them)\n designcraft-cli commands [FILTER]\n designcraft-cli describe COMMAND\n designcraft-cli script [FILE|-] [--in FILE | --sample] [--connect PORT] [--save OUT] [--export OUT] [--keep-going]\n designcraft-cli app [--port PORT] COMMAND [JSON] | --method METHOD [JSON]\n designcraft-cli mcp [--connect PORT] [--sample] [--automation-read-root DIR] [--automation-write-root DIR]\n the two roots confine every file the agent's commands read (open, placed images, data sources, libraries) and\n write (save, export, package) to those folders, links followed. A root left out grants none of its access.\n They run the in-process server, so they conflict with --connect (a running app is not confined by them).\n designcraft-cli perf [--pages N] [--runs N] [--strict]\n designcraft-cli bench FILE [--runs N]\n designcraft-cli links\n designcraft-cli --version";
|
||||
|
||||
/// `script --help`: the script syntax, otherwise only in `describe script.run` and docs/agents.md.
|
||||
const SCRIPT_HELP: &str = r#"usage: designcraft-cli script [FILE|-] [--in FILE | --sample] [--connect PORT] [--save OUT] [--export OUT] [--keep-going]
|
||||
@@ -55,6 +57,8 @@ References to earlier results (in string parameters):
|
||||
comments and blank lines are not steps. `$last` is the previous step.
|
||||
Paths go through result fields and array indices: "$1.story", "$3.ids.0".
|
||||
"${N.path}" inside a longer string, replaced by the value's text: "Frame ${0.id}".
|
||||
Any other string starting with `$` stays as written ("$1-$2", "$5 off").
|
||||
"$$" a literal `$` anywhere: "$$1" passes `$1` (a GREP group), "$${0.id}" passes `${0.id}`.
|
||||
|
||||
Text parameters: "\n" starts a new paragraph, "\u2028" is a forced line break, "\t" a tab.
|
||||
Most commands ignore parameters they do not know instead of rejecting them: check names
|
||||
@@ -160,16 +164,31 @@ fn validate_pdf(path: Option<&str>) -> Result<(), String> {
|
||||
/// `mcp` (headless, in-process engine) or `mcp --connect PORT|HOST:PORT` (drive a running app
|
||||
/// started with `designcraft --control PORT`). JSON-RPC on stdin/stdout; logs on stderr.
|
||||
fn mcp(args: &[String]) -> Result<(), String> {
|
||||
use designcraft_engine::file_access::{self, AutomationRoots};
|
||||
use designcraft_mcp::{Backend, Headless, Remote, Server, control_addr};
|
||||
let mut connect: Option<String> = None;
|
||||
let mut sample = false;
|
||||
let mut it = args.iter();
|
||||
let mut roots_args = automation_args::AutomationArgs::new(None, None);
|
||||
let mut it = args.iter().cloned();
|
||||
while let Some(a) = it.next() {
|
||||
match a.as_str() {
|
||||
"--connect" => connect = Some(it.next().cloned().ok_or("--connect needs a port or host:port")?),
|
||||
"--sample" => sample = true,
|
||||
other => return Err(format!("unknown mcp option `{other}` (usage: designcraft-cli mcp [--connect PORT] [--sample])")),
|
||||
if roots_args.consume(&a, &mut it)? {
|
||||
continue;
|
||||
}
|
||||
match a.as_str() {
|
||||
"--connect" => connect = Some(it.next().ok_or("--connect needs a port or host:port")?),
|
||||
"--sample" => sample = true,
|
||||
other => {
|
||||
return Err(format!(
|
||||
"unknown mcp option `{other}` (usage: designcraft-cli mcp [--connect PORT] [--sample] [--automation-read-root DIR] [--automation-write-root DIR])"
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
let roots = AutomationRoots::new(roots_args.read_root.as_deref(), roots_args.write_root.as_deref())?;
|
||||
if roots.is_some() && connect.is_some() {
|
||||
return Err("--automation-read-root and --automation-write-root confine the in-process server; a running app is not confined by them, \
|
||||
so drop --connect (or use --connect without the roots)"
|
||||
.into());
|
||||
}
|
||||
let backend: Box<dyn Backend> = match connect {
|
||||
Some(c) => {
|
||||
@@ -181,9 +200,17 @@ fn mcp(args: &[String]) -> Result<(), String> {
|
||||
}
|
||||
None => {
|
||||
let mut h = Headless::with_document();
|
||||
// `--sample` is the operator's own choice, made before the roots come into force.
|
||||
if sample {
|
||||
h.session.execute("file.newSample", &json!({})).map_err(|e| e.to_string())?;
|
||||
}
|
||||
if let Some(roots) = roots {
|
||||
// Every thread of this process, not only the server's: nothing reaches past the roots.
|
||||
file_access::confine_process(roots.clone());
|
||||
let show = |root: Option<&std::path::Path>| root.map_or_else(|| "none".to_string(), |r| r.display().to_string());
|
||||
eprintln!("designcraft-cli: files confined: read root {}, write root {}", show(roots.read_root()), show(roots.write_root()));
|
||||
h = h.with_automation_roots(Some(roots));
|
||||
}
|
||||
Box::new(h)
|
||||
}
|
||||
};
|
||||
@@ -261,7 +288,11 @@ fn run(args: &[String]) -> Result<(), String> {
|
||||
"--page" => page = val()?.parse().map_err(|_| "bad --page")?,
|
||||
"--scale" => scale = val()?.parse().map_err(|_| "bad --scale")?,
|
||||
"--pdf-options" => {
|
||||
pdf_opts = serde_json::from_str(&val()?).map_err(|e| format!("--pdf-options: {e}"))?;
|
||||
pdf_opts = match serde_json::from_str(&val()?).map_err(|e| format!("--pdf-options: {e}"))? {
|
||||
Value::Null => json!({}),
|
||||
o @ Value::Object(_) => o,
|
||||
_ => return Err("--pdf-options: expected a JSON object".to_string()),
|
||||
};
|
||||
}
|
||||
"--export" => {
|
||||
let out = val()?;
|
||||
|
||||
@@ -138,6 +138,24 @@ fn run_export_options_come_before_their_export() {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// `--pdf-options` must be a JSON object; any other JSON value used to panic when the PDF path was set on it.
|
||||
#[test]
|
||||
fn pdf_options_that_are_not_an_object_are_an_error_not_a_panic() {
|
||||
let dir = std::env::temp_dir().join(format!("dc-cli-pdfopts-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let pdf = dir.join("out.pdf");
|
||||
let pdf = pdf.to_str().unwrap();
|
||||
for val in ["[]", "true", "1", r#""x""#] {
|
||||
let out = cli().args(["run", "--sample", "--pdf-options", val, "--export", pdf]).output().unwrap();
|
||||
let err = String::from_utf8_lossy(&out.stderr);
|
||||
assert_eq!(out.status.code(), Some(1), "{val}: {err}");
|
||||
assert!(err.contains("--pdf-options") && !err.contains("panicked"), "{val}: {err}");
|
||||
}
|
||||
let out = cli().args(["run", "--sample", "--pdf-options", "null", "--export", pdf]).output().unwrap();
|
||||
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn raster_export_preserves_an_existing_reader_and_private_symlink_target() {
|
||||
@@ -169,3 +187,124 @@ fn raster_export_preserves_an_existing_reader_and_private_symlink_target() {
|
||||
assert_eq!(std::fs::metadata(&target).unwrap().permissions().mode() & 0o777, 0o600);
|
||||
assert!(std::fs::symlink_metadata(alias).unwrap().file_type().is_symlink());
|
||||
}
|
||||
|
||||
/// Send `calls` (tool name, arguments) to `designcraft-cli mcp <args>`; returns whether it exited
|
||||
/// cleanly, its stderr, and the stdout lines after `initialize`, one per call.
|
||||
fn mcp_session(args: &[&str], calls: &[(&str, serde_json::Value)]) -> (bool, String, Vec<serde_json::Value>) {
|
||||
let mut child = cli().arg("mcp").args(args).stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped()).spawn().unwrap();
|
||||
{
|
||||
let stdin = child.stdin.as_mut().unwrap();
|
||||
writeln!(stdin, r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"protocolVersion":"2025-06-18"}}}}"#).unwrap();
|
||||
for (i, (name, arguments)) in calls.iter().enumerate() {
|
||||
let call = serde_json::json!({"jsonrpc": "2.0", "id": i + 2, "method": "tools/call", "params": {"name": name, "arguments": arguments}});
|
||||
writeln!(stdin, "{call}").unwrap();
|
||||
}
|
||||
}
|
||||
let out = child.wait_with_output().unwrap();
|
||||
let stdout = String::from_utf8(out.stdout).unwrap();
|
||||
let replies = stdout.lines().skip(1).map(|l| serde_json::from_str(l).unwrap()).collect();
|
||||
(out.status.success(), String::from_utf8_lossy(&out.stderr).into_owned(), replies)
|
||||
}
|
||||
|
||||
fn text(reply: &serde_json::Value) -> &str {
|
||||
reply["result"]["content"][0]["text"].as_str().unwrap()
|
||||
}
|
||||
|
||||
/// A `.designcraft` file with one page, made with the CLI itself.
|
||||
fn make_document(path: &std::path::Path) {
|
||||
let out = cli().args(["run", "--cmd", "file.new={}", "--cmd"]).arg(format!("file.save={}", serde_json::json!({"path": path}))).output().unwrap();
|
||||
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
|
||||
assert!(path.exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mcp_automation_roots_confine_the_server() {
|
||||
let base = std::env::temp_dir().join(format!("dc-cli-roots-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
let (work, elsewhere) = (base.join("work"), base.join("elsewhere"));
|
||||
std::fs::create_dir_all(&work).unwrap();
|
||||
std::fs::create_dir_all(&elsewhere).unwrap();
|
||||
make_document(&work.join("in.designcraft"));
|
||||
make_document(&elsewhere.join("secret.designcraft"));
|
||||
let work_s = work.to_str().unwrap();
|
||||
let secret = elsewhere.join("secret.designcraft").to_str().unwrap().to_string();
|
||||
|
||||
// Both spellings of the flags; inside works, outside is refused with a readable message.
|
||||
let read_flag = format!("--automation-read-root={work_s}");
|
||||
let calls = [
|
||||
("open_document", serde_json::json!({"path": work.join("in.designcraft").to_str().unwrap()})),
|
||||
("open_document", serde_json::json!({"path": secret})),
|
||||
("save_document", serde_json::json!({"path": work.join("saved.designcraft").to_str().unwrap()})),
|
||||
("save_document", serde_json::json!({"path": elsewhere.join("saved.designcraft").to_str().unwrap()})),
|
||||
("export_png", serde_json::json!({"path": elsewhere.join("page.png").to_str().unwrap()})),
|
||||
("render_page", serde_json::json!({"path": elsewhere.join("render.png").to_str().unwrap()})),
|
||||
];
|
||||
let (success, stderr, replies) = mcp_session(&[&read_flag, "--automation-write-root", work_s], &calls);
|
||||
assert!(success, "{stderr}");
|
||||
assert!(stderr.contains("files confined"), "{stderr}");
|
||||
assert_eq!(replies[0]["result"]["isError"], false, "{}", replies[0]);
|
||||
assert_eq!(replies[1]["result"]["isError"], true);
|
||||
assert!(text(&replies[1]).contains("outside the read root"), "{}", text(&replies[1]));
|
||||
assert_eq!(replies[2]["result"]["isError"], false, "{}", replies[2]);
|
||||
assert!(work.join("saved.designcraft").exists());
|
||||
for reply in &replies[3..] {
|
||||
assert_eq!(reply["result"]["isError"], true, "{reply}");
|
||||
assert!(text(reply).contains("outside the write root"), "{}", text(reply));
|
||||
}
|
||||
for name in ["saved.designcraft", "page.png", "render.png"] {
|
||||
assert!(!elsewhere.join(name).exists(), "{name} was written outside the write root");
|
||||
}
|
||||
|
||||
// A root left out grants none of its access.
|
||||
let save = [("new_document", serde_json::json!({})), calls[2].clone()];
|
||||
let (_, _, replies) = mcp_session(&[&read_flag], &save);
|
||||
assert_eq!(replies[1]["result"]["isError"], true);
|
||||
assert!(text(&replies[1]).contains("write authority is absent"), "{}", text(&replies[1]));
|
||||
let (_, _, replies) = mcp_session(&["--automation-write-root", work_s], &calls[..1]);
|
||||
assert_eq!(replies[0]["result"]["isError"], true);
|
||||
assert!(text(&replies[0]).contains("read authority is absent"), "{}", text(&replies[0]));
|
||||
|
||||
// No flags: nothing is confined.
|
||||
let (success, _, replies) = mcp_session(&[], &calls[1..2]);
|
||||
assert!(success);
|
||||
assert_eq!(replies[0]["result"]["isError"], false, "{}", replies[0]);
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mcp_automation_root_flags_are_checked_up_front() {
|
||||
let base = std::env::temp_dir().join(format!("dc-cli-roots-args-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
std::fs::create_dir_all(&base).unwrap();
|
||||
let dir = base.to_str().unwrap();
|
||||
let missing = base.join("missing");
|
||||
let fails = |args: &[&str], needle: &str| {
|
||||
let mut full = vec!["mcp"];
|
||||
full.extend_from_slice(args);
|
||||
let o = cli().args(&full).output().unwrap();
|
||||
assert!(!o.status.success(), "{args:?}");
|
||||
let err = String::from_utf8_lossy(&o.stderr).into_owned();
|
||||
assert!(err.contains(needle), "{args:?}: {err}");
|
||||
};
|
||||
// The flags confine the in-process server, so they cannot be combined with --connect.
|
||||
fails(&["--connect", "7979", "--automation-read-root", dir], "--connect");
|
||||
fails(&["--automation-write-root", dir, "--connect", "7979"], "--connect");
|
||||
fails(&["--automation-read-root", dir, "--automation-read-root", dir], "given twice");
|
||||
fails(&["--automation-write-root", dir, "--automation-write-root", dir], "given twice");
|
||||
fails(&["--automation-read-root", dir, "--automation-read-root=x"], "given twice");
|
||||
fails(&["--automation-read-root"], "needs a folder");
|
||||
fails(&["--automation-write-root", "--sample"], "needs a folder");
|
||||
fails(&["--automation-read-root", missing.to_str().unwrap()], "cannot open the automation read root");
|
||||
fails(&["--automation-write-root="], "needs a non-empty folder");
|
||||
// A file is not a folder.
|
||||
std::fs::write(base.join("f.txt"), "x").unwrap();
|
||||
fails(&["--automation-write-root", base.join("f.txt").to_str().unwrap()], "cannot open the automation write root");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn usage_lists_the_automation_root_flags() {
|
||||
let out = cli().arg("--help").output().unwrap();
|
||||
let usage = String::from_utf8_lossy(&out.stdout);
|
||||
assert!(usage.contains("--automation-read-root DIR") && usage.contains("--automation-write-root DIR"), "{usage}");
|
||||
}
|
||||
|
||||
@@ -25,6 +25,7 @@ winresource = "0.1"
|
||||
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
|
||||
rfd = { workspace = true }
|
||||
arboard = { workspace = true }
|
||||
|
||||
[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.
|
||||
|
||||
@@ -45,7 +45,7 @@ impl eframe::App for App {
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
if self.menu.is_none() && std::env::var_os("DESIGNCRAFT_NO_NATIVE_MENU").is_none() {
|
||||
self.menu = Some(native_menu::NativeMenu::install(&mut self.app));
|
||||
self.menu = Some(native_menu::NativeMenu::install(&mut self.app, ctx));
|
||||
}
|
||||
if let Some(m) = &mut self.menu {
|
||||
m.poll(&mut self.app, ctx);
|
||||
@@ -210,6 +210,7 @@ fn services() -> Services {
|
||||
pick_save: Some(Box::new(|name: &str| rfd::FileDialog::new().set_file_name(name).save_file().map(|p| p.to_string_lossy().to_string()))),
|
||||
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())),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
@@ -289,6 +290,14 @@ fn main() -> eframe::Result {
|
||||
{
|
||||
create.instance_descriptor.backends = s.backends();
|
||||
}
|
||||
// Nothing draws or dispatches indirectly, so wgpu's check of indirect arguments only costs a
|
||||
// compute shader when the device is created, one that Metal can't compile on an Intel Iris
|
||||
// Pro: the device is lost and the window never opens. `WGPU_VALIDATION_INDIRECT_CALL=1` turns
|
||||
// the check back on.
|
||||
if let eframe::egui_wgpu::WgpuSetup::CreateNew(create) = &mut options.wgpu_options.wgpu_setup {
|
||||
create.instance_descriptor.flags =
|
||||
create.instance_descriptor.flags.difference(eframe::wgpu::InstanceFlags::VALIDATION_INDIRECT_CALL).with_env();
|
||||
}
|
||||
// winit has no file drag-and-drop on Wayland (only on X11), so dropping images from the file
|
||||
// manager showed a "no" cursor. Run through XWayland when it's there; DESIGNCRAFT_WAYLAND=1
|
||||
// keeps the native Wayland backend.
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::str::FromStr;
|
||||
use std::sync::mpsc::{Receiver, channel};
|
||||
|
||||
use designcraft_ui_egui::DesignApp;
|
||||
use designcraft_ui_egui::menus::{self, Item};
|
||||
@@ -19,6 +20,7 @@ enum Handle {
|
||||
pub struct NativeMenu {
|
||||
_menu: Menu,
|
||||
items: HashMap<String, (String, Value, Handle)>,
|
||||
events: Receiver<MenuEvent>,
|
||||
last_refresh: f64,
|
||||
}
|
||||
|
||||
@@ -31,7 +33,15 @@ fn accel(sc: &str) -> Option<Accelerator> {
|
||||
}
|
||||
|
||||
impl NativeMenu {
|
||||
pub fn install(app: &mut DesignApp) -> Self {
|
||||
pub fn install(app: &mut DesignApp, ctx: &egui::Context) -> Self {
|
||||
// A click in the menu bar reaches the app with no input over the window, so nothing would
|
||||
// draw the frame that runs the command until the pointer or a key comes back: wake egui.
|
||||
let (tx, events) = channel();
|
||||
let repaint = ctx.clone();
|
||||
MenuEvent::set_event_handler(Some(move |e: MenuEvent| {
|
||||
let _ = tx.send(e);
|
||||
repaint.request_repaint();
|
||||
}));
|
||||
let menu = Menu::new();
|
||||
let mut items = HashMap::new();
|
||||
let mut counter = 0usize;
|
||||
@@ -72,11 +82,11 @@ impl NativeMenu {
|
||||
(p.is_null() && accel(sc).is_some()).then(|| id.clone())
|
||||
})
|
||||
.collect();
|
||||
Self { _menu: menu, items, last_refresh: 0.0 }
|
||||
Self { _menu: menu, items, events, last_refresh: 0.0 }
|
||||
}
|
||||
|
||||
pub fn poll(&mut self, app: &mut DesignApp, ctx: &egui::Context) {
|
||||
while let Ok(ev) = MenuEvent::receiver().try_recv() {
|
||||
while let Ok(ev) = self.events.try_recv() {
|
||||
if let Some((cmd, params, _)) = self.items.get(ev.id.as_ref()) {
|
||||
menus::activate_native(app, ctx, &cmd.clone(), ¶ms.clone());
|
||||
}
|
||||
|
||||
@@ -17,6 +17,10 @@
|
||||
# To remove your names, delete your entry (or set fields empty) in a PR. The next
|
||||
# contributors.py run, and the next build, drop them.
|
||||
|
||||
[people.dotCooCoo]
|
||||
real_name = "Robert Lee"
|
||||
sync_github_name = true
|
||||
|
||||
[people.echelon]
|
||||
real_name = "Brandon Thomas"
|
||||
display_name = "Brandon Thomas"
|
||||
@@ -31,6 +35,14 @@ sync_github_name = true
|
||||
[people.thaynej]
|
||||
real_name = "Jeffrey Thayne"
|
||||
|
||||
[people.webdevtodayjason]
|
||||
display_name = "Jason Brashear"
|
||||
|
||||
[people.Nmarello]
|
||||
real_name = "Nick Marello"
|
||||
display_name = "Nick Marello"
|
||||
sync_github_name = false
|
||||
|
||||
[people.switch87]
|
||||
real_name = "Gert Pellin"
|
||||
display_name = "Gert Pellin"
|
||||
|
||||
+24
-1
@@ -11,8 +11,12 @@ pub enum AseError {
|
||||
Signature,
|
||||
#[error("the file ends early")]
|
||||
Truncated,
|
||||
#[error("the file holds more than {MAX_COLORS} colors")]
|
||||
TooManyColors,
|
||||
}
|
||||
|
||||
/// The most colors [`read`] accepts in one file.
|
||||
pub const MAX_COLORS: usize = 100_000;
|
||||
const COLOR: u16 = 0x0001;
|
||||
#[cfg(test)]
|
||||
const GROUP_START: u16 = 0xC001;
|
||||
@@ -56,6 +60,7 @@ impl R<'_> {
|
||||
}
|
||||
|
||||
/// The colour swatches in an `.ase` file (groups are flattened).
|
||||
/// A file with more than [`MAX_COLORS`] colors is an error.
|
||||
pub fn read(bytes: &[u8]) -> Result<Vec<Swatch>, AseError> {
|
||||
let mut r = R { b: bytes, i: 0 };
|
||||
if r.take(4)? != b"ASEF" {
|
||||
@@ -63,7 +68,7 @@ pub fn read(bytes: &[u8]) -> Result<Vec<Swatch>, AseError> {
|
||||
}
|
||||
r.take(4)?; // version
|
||||
let blocks = r.u32()?;
|
||||
let mut out = Vec::new();
|
||||
let (mut out, mut colors) = (Vec::new(), 0usize);
|
||||
for _ in 0..blocks {
|
||||
let kind = r.u16()?;
|
||||
let len = r.u32()? as usize;
|
||||
@@ -72,6 +77,10 @@ pub fn read(bytes: &[u8]) -> Result<Vec<Swatch>, AseError> {
|
||||
if kind != COLOR {
|
||||
continue;
|
||||
}
|
||||
colors += 1;
|
||||
if colors > MAX_COLORS {
|
||||
return Err(AseError::TooManyColors);
|
||||
}
|
||||
let mut b = R { b: body, i: 0 };
|
||||
let name = b.name()?;
|
||||
let model = b.take(4)?.to_vec();
|
||||
@@ -191,4 +200,18 @@ mod tests {
|
||||
let SwatchValue::Color { color, .. } = &w[0].value else { panic!() };
|
||||
assert!(color.to_rgb().iter().all(|v| *v > 0.98), "Lab white: {color:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn more_than_max_colors_is_an_error() {
|
||||
let gray = Swatch {
|
||||
name: "G".into(),
|
||||
value: SwatchValue::Color { color: Color::Gray { k: 0.5 }, color_type: ColorType::Process },
|
||||
locked: false,
|
||||
named: true,
|
||||
hidden: false,
|
||||
};
|
||||
let sw = vec![gray; MAX_COLORS + 1];
|
||||
assert_eq!(read(&write(&sw)).err(), Some(AseError::TooManyColors));
|
||||
assert_eq!(read(&write(&sw[1..])).map(|w| w.len()), Ok(MAX_COLORS), "up to the limit");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -230,13 +230,6 @@ pub fn register_icc(bytes: &[u8], name: Option<String>) -> Result<ProfileInfo, C
|
||||
Ok(info)
|
||||
}
|
||||
|
||||
/// Load a `.icc`/`.icm` file from disk (native only).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub fn load_icc_file(path: &std::path::Path) -> Result<ProfileInfo, CmsError> {
|
||||
let bytes = std::fs::read(path).map_err(|e| CmsError::Io(format!("{}: {e}", path.display())))?;
|
||||
register_icc(&bytes, None)
|
||||
}
|
||||
|
||||
/// A colour-management context: resolved working spaces plus conversion settings.
|
||||
#[derive(Clone)]
|
||||
pub struct Cms {
|
||||
|
||||
@@ -188,10 +188,8 @@ fn bad_icc_rejected() {
|
||||
#[test]
|
||||
fn loads_system_cmyk_icc() {
|
||||
let path = std::path::Path::new("/System/Library/ColorSync/Profiles/Generic CMYK Profile.icc");
|
||||
if !path.exists() {
|
||||
return;
|
||||
}
|
||||
let info = load_icc_file(path).unwrap();
|
||||
let Ok(bytes) = std::fs::read(path) else { return };
|
||||
let info = register_icc(&bytes, None).unwrap();
|
||||
assert_eq!(info.kind, ProfileKind::Cmyk);
|
||||
assert!(profiles().iter().any(|p| p.name == info.name && !p.builtin));
|
||||
let c = Cms::new(&ColorSettings { cmyk: info.name.clone(), ..Default::default() }).unwrap();
|
||||
|
||||
@@ -103,6 +103,26 @@ impl Gradient {
|
||||
}
|
||||
out
|
||||
}
|
||||
/// Stops for a renderer that blends between them in RGB: the expanded stops, plus samples
|
||||
/// through each span that isn't RGB at both ends, so process colours keep blending as inks.
|
||||
pub fn display_stops(&self) -> Vec<(f32, Color, f32)> {
|
||||
const STEPS: usize = 16;
|
||||
let stops = self.expanded_stops();
|
||||
let mut out: Vec<(f32, Color, f32)> = Vec::with_capacity(stops.len() * STEPS);
|
||||
for (i, s) in stops.iter().enumerate() {
|
||||
out.push(*s);
|
||||
let Some(n) = stops.get(i + 1) else { continue };
|
||||
if matches!((s.1, n.1), (Color::Rgb { .. }, Color::Rgb { .. })) || n.0 - s.0 <= 1e-4 {
|
||||
continue;
|
||||
}
|
||||
for j in 1..STEPS {
|
||||
let t = s.0 + (n.0 - s.0) * j as f32 / STEPS as f32;
|
||||
let (c, a) = self.sample(t);
|
||||
out.push((t, c, a));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
pub fn reverse(&mut self) {
|
||||
// A midpoint belongs to the segment after its stop, so it moves with that segment and mirrors.
|
||||
let mids: Vec<_> = self.stops.iter().rev().skip(1).map(|s| 1.0 - s.midpoint).collect();
|
||||
@@ -199,6 +219,25 @@ mod tests {
|
||||
assert!((mid - 0.5).abs() < 1e-5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn process_stops_blend_as_inks() {
|
||||
// LYH Studio episode 6: magenta to cyan is C 50 M 50 halfway (a light lilac), not the RGB mix.
|
||||
let mut g = Gradient::default();
|
||||
g.stops[0].color = Color::cmyk(0.0, 1.0, 0.0, 0.0);
|
||||
g.stops[1].color = Color::cmyk(1.0, 0.0, 0.0, 0.0);
|
||||
assert_eq!(g.sample(0.5).0, Color::cmyk(0.5, 0.5, 0.0, 0.0));
|
||||
let d = g.display_stops();
|
||||
assert_eq!(d.len(), 17, "sampled through the span");
|
||||
assert!(d.iter().any(|(o, c, _)| (*o - 0.5).abs() < 1e-6 && *c == Color::cmyk(0.5, 0.5, 0.0, 0.0)));
|
||||
// A midpoint stays an ink too; RGB stops aren't sampled.
|
||||
g.stops[0].midpoint = 0.25;
|
||||
assert!(matches!(g.expanded_stops()[1].1, Color::Cmyk { .. }));
|
||||
assert_eq!(Gradient::default().display_stops().len(), 2);
|
||||
// Grey and CMYK meet as inks; RGB with anything else blends in RGB.
|
||||
assert_eq!(Color::gray(1.0).lerp(&Color::cmyk(1.0, 0.0, 0.0, 0.0), 0.5), Color::cmyk(0.5, 0.0, 0.0, 0.5));
|
||||
assert!(matches!(Color::rgb(1.0, 0.0, 0.0).lerp(&Color::cmyk(1.0, 0.0, 0.0, 0.0), 0.5), Color::Rgb { .. }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn midpoint_shifts() {
|
||||
let mut g = Gradient::default();
|
||||
|
||||
+10
-1
@@ -169,8 +169,17 @@ impl Color {
|
||||
let [r, g, b] = self.to_rgb();
|
||||
Color::rgb(1.0 - r, 1.0 - g, 1.0 - b)
|
||||
}
|
||||
/// Linear interpolation in display RGB.
|
||||
/// The colour `t` of the way to `other`. Process inks blend as inks (CMYK with CMYK or grey,
|
||||
/// grey with grey), as InDesign blends a gradient's stops; anything else blends in RGB.
|
||||
pub fn lerp(&self, other: &Color, t: f32) -> Color {
|
||||
let l = |a: f32, b: f32| a + (b - a) * t;
|
||||
match (*self, *other) {
|
||||
(Color::Cmyk { c, m, y, k }, Color::Cmyk { c: c2, m: m2, y: y2, k: k2 }) => return Color::cmyk(l(c, c2), l(m, m2), l(y, y2), l(k, k2)),
|
||||
(Color::Gray { k }, Color::Gray { k: k2 }) => return Color::gray(l(k, k2)),
|
||||
(Color::Gray { k }, Color::Cmyk { .. }) => return Color::cmyk(0.0, 0.0, 0.0, k).lerp(other, t),
|
||||
(Color::Cmyk { .. }, Color::Gray { k }) => return self.lerp(&Color::cmyk(0.0, 0.0, 0.0, k), t),
|
||||
_ => {}
|
||||
}
|
||||
let a = self.to_rgb();
|
||||
let b = other.to_rgb();
|
||||
Color::rgb(a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t, a[2] + (b[2] - a[2]) * t)
|
||||
|
||||
@@ -10,6 +10,7 @@ workspace = true
|
||||
|
||||
[dependencies]
|
||||
unicode-bidi = { workspace = true }
|
||||
unicode-segmentation = { workspace = true }
|
||||
unicode-bidi-mirroring = { workspace = true }
|
||||
designcraft-geom = { workspace = true }
|
||||
designcraft-color = { workspace = true }
|
||||
@@ -18,7 +19,7 @@ designcraft-fonts = { workspace = true }
|
||||
log = { workspace = true }
|
||||
regex = { workspace = true }
|
||||
miniz_oxide = "0.8"
|
||||
hypher = { version = "0.1.8", default-features = false, features = ["alloc", "portuguese", "spanish"] }
|
||||
hypher = { version = "0.1.8", default-features = false, features = ["alloc", "portuguese", "spanish", "norwegian"] }
|
||||
|
||||
[dev-dependencies]
|
||||
designcraft-fonts = { workspace = true, features = ["testing"] }
|
||||
|
||||
@@ -303,8 +303,17 @@ fn items(glyphs: &[Glyph], hyph_after: &[bool], emergency_after: &[bool], sp: &S
|
||||
let n = glyphs.len();
|
||||
let mut hy_cache = Vec::new();
|
||||
let mut last_space = NONE;
|
||||
// Spaces before the paragraph end or a forced break hang: they take no room on the line (as
|
||||
// in InDesign, where "2 VOOR " fits a frame as wide as "2 VOOR").
|
||||
let mut hangs = vec![false; n];
|
||||
for i in (0..n).rev() {
|
||||
hangs[i] = glyphs[i].is_space() && glyphs.get(i + 1).is_none_or(|nx| hangs[i + 1] || is_forced(nx.ch));
|
||||
}
|
||||
for (i, g) in glyphs.iter().enumerate() {
|
||||
let prev_hang = if i > 0 { right_hang(&glyphs[i - 1], sp) } else { 0.0 };
|
||||
if hangs[i] {
|
||||
continue;
|
||||
}
|
||||
if is_forced(g.ch) {
|
||||
it.push(Item::glue(0.0, INF, 0.0));
|
||||
ig.push(i);
|
||||
|
||||
@@ -47,7 +47,18 @@ 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);
|
||||
h.finish()
|
||||
}
|
||||
|
||||
/// Everything page names and section markers are made from.
|
||||
fn sections_hash(doc: &Document) -> u64 {
|
||||
use std::hash::{Hash, Hasher};
|
||||
let mut h = std::collections::hash_map::DefaultHasher::new();
|
||||
doc.sections.len().hash(&mut h);
|
||||
for s in &doc.sections {
|
||||
(s.start, s.start_number, s.style as u8, &s.prefix, &s.marker, s.include_prefix).hash(&mut h);
|
||||
}
|
||||
h.finish()
|
||||
}
|
||||
|
||||
@@ -67,10 +78,18 @@ impl Cache {
|
||||
// The key holds the page's index, which a renumbering doesn't change: its name (section
|
||||
// start number, style, prefix) is part of the signature.
|
||||
let page_name = page.map(|p| doc.page_name(p));
|
||||
let section_marker = page.map(|p| crate::section_marker(doc, p));
|
||||
if let Some(name) = &page_name {
|
||||
use std::hash::{Hash, Hasher};
|
||||
let mut h = std::collections::hash_map::DefaultHasher::new();
|
||||
name.hash(&mut h);
|
||||
(name, §ion_marker).hash(&mut h);
|
||||
sig.push(h.finish() as usize);
|
||||
}
|
||||
if story.text.contains(designcraft_doc::story::SECTION_MARKER) {
|
||||
// Frames on document pages show their section's marker text.
|
||||
use std::hash::{Hash, Hasher};
|
||||
let mut h = std::collections::hash_map::DefaultHasher::new();
|
||||
doc.sections.iter().for_each(|s| (s.start, &s.marker).hash(&mut h));
|
||||
sig.push(h.finish() as usize);
|
||||
}
|
||||
let with_vars = crate::vars::has_vars(story);
|
||||
@@ -144,7 +163,7 @@ impl Cache {
|
||||
let out = Arc::new(crate::compose_story(
|
||||
doc,
|
||||
sid,
|
||||
&ComposeOptions { page_name, page, running, label: None, xrefs: with_xrefs.then(|| self.xref_index(doc)) },
|
||||
&ComposeOptions { page_name, section_marker, page, running, label: None, xrefs: with_xrefs.then(|| self.xref_index(doc)) },
|
||||
));
|
||||
let mut g = self.map.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let stamp = g.1;
|
||||
@@ -253,8 +272,17 @@ impl Cache {
|
||||
|
||||
fn signature(doc: &Document, story: &Arc<Story>) -> (Vec<usize>, Vec<Arc<Item>>) {
|
||||
// The document's font scope: another document's fonts of the same name set it differently.
|
||||
let mut sig =
|
||||
vec![Arc::as_ptr(story) as usize, story.rev as usize, Arc::as_ptr(&doc.styles) as usize, doc.sections.len(), doc.font_scope as usize];
|
||||
// Sections name the pages under the frames (page-number and section markers).
|
||||
let g = &doc.settings.baseline_grid;
|
||||
let mut sig = vec![
|
||||
Arc::as_ptr(story) as usize,
|
||||
story.rev as usize,
|
||||
Arc::as_ptr(&doc.styles) as usize,
|
||||
sections_hash(doc) as usize,
|
||||
doc.font_scope as usize,
|
||||
g.start.to_bits() as usize,
|
||||
g.increment.to_bits() as usize,
|
||||
];
|
||||
let mut keep = Vec::new();
|
||||
let mut spreads = Vec::new();
|
||||
for f in &story.frames {
|
||||
@@ -273,6 +301,8 @@ fn signature(doc: &Document, story: &Arc<Story>) -> (Vec<usize>, Vec<Arc<Item>>)
|
||||
for it in &sp.items {
|
||||
if it.wrap.mode != WrapMode::None {
|
||||
sig.push(Arc::as_ptr(it) as usize);
|
||||
// Wrap objects on hidden layers don't wrap text.
|
||||
sig.push(usize::from(doc.layer(it.layer).is_some_and(|l| l.visible)));
|
||||
keep.push(it.clone());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
//! Hyphenation. English uses the bundled dictionary and patterns below. Other languages use the
|
||||
//! Liang patterns compiled into `hypher`, one cargo feature per language: Spanish is Javier Bezos's
|
||||
//! `hyph-es.tex` 5.0 from hyph-utf8, MIT; Portuguese is `hyph-pt.tex` 1.4 from hyph-utf8 (Pedro J.
|
||||
//! de Rezende, J. Joao Dias Almeida, Leonardo Araujo, Aline Benevides), BSD-3-Clause (see NOTICE).
|
||||
//! de Rezende, J. Joao Dias Almeida, Leonardo Araujo, Aline Benevides), BSD-3-Clause; Norwegian is
|
||||
//! `hyph-no.tex` from hyph-utf8 (Rune Kleveland, Ole Michael Selberg), permissive (see NOTICE).
|
||||
//!
|
||||
//! English lookup order for each word:
|
||||
//! 1. the **dictionary** ([`Dictionary::en_us`]) — the public-domain Moby Hyphenator II word list
|
||||
@@ -411,6 +412,26 @@ mod tests {
|
||||
assert_eq!(h("pós-graduação"), "pós-gra-du-a-ção", "each part of a compound");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn norwegian_uses_the_hyph_no_patterns() {
|
||||
let nb = Lang::for_language("Norwegian: Bokmål").unwrap();
|
||||
assert_eq!(nb, Lang::for_language("Norwegian").unwrap());
|
||||
assert_eq!(nb, Lang::for_language("Norwegian: Nynorsk").unwrap());
|
||||
assert_eq!(nb, Lang::for_language("nb").unwrap());
|
||||
assert_eq!(nb, Lang::for_language("nn").unwrap());
|
||||
assert_eq!(nb, Lang::for_language("no").unwrap());
|
||||
assert_ne!(nb, Lang::for_language("Spanish").unwrap());
|
||||
let h = |w: &str| {
|
||||
let pts = hyphen_points_in(w, &Limits::default(), nb);
|
||||
w.chars().enumerate().map(|(i, c)| if pts.contains(&i) { format!("-{c}") } else { c.to_string() }).collect::<String>()
|
||||
};
|
||||
assert_eq!(h("kaller"), "kal-ler");
|
||||
assert_eq!(h("bilde"), "bil-de");
|
||||
assert_eq!(h("sjøfugl"), "sjø-fugl");
|
||||
assert_eq!(h("sirkulasjonen"), "sir-ku-la-sjo-nen");
|
||||
assert_eq!(h("beveger"), "be-ve-ger");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn heuristic_fallback() {
|
||||
let c: Vec<char> = "happen".chars().collect();
|
||||
|
||||
+613
-101
File diff suppressed because it is too large
Load Diff
+70
-22
@@ -5,6 +5,11 @@
|
||||
//! the first footnote and the space between footnotes). A line that would collide moves to the
|
||||
//! next column with its footnotes. After the story is laid out the footnotes of each column are
|
||||
//! stacked against the column bottom, with the separator rule above the first one.
|
||||
//!
|
||||
//! The footnotes of a column read as one text: the first footnote's first baseline sits at the
|
||||
//! First Baseline offset below the top of the footnote area, and each later footnote's first
|
||||
//! baseline sits its first line's leading (plus Space Between Footnotes) below the previous
|
||||
//! footnote's last baseline. Only the last footnote's descent counts toward the area's height.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::ops::Range;
|
||||
@@ -22,10 +27,38 @@ pub(crate) struct Placed {
|
||||
k: usize,
|
||||
fi: usize,
|
||||
col: usize,
|
||||
h: f64,
|
||||
m: NoteMetrics,
|
||||
text: Arc<ComposedStory>,
|
||||
}
|
||||
|
||||
/// Vertical metrics of a composed footnote, relative to the top of its composed text.
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
pub(crate) struct NoteMetrics {
|
||||
/// First and last baselines (the first one includes the First Baseline offset).
|
||||
first: f64,
|
||||
last: f64,
|
||||
/// Leading of the first line: its baseline's distance below the previous footnote's last.
|
||||
lead: f64,
|
||||
/// Descent of the last line.
|
||||
descent: f64,
|
||||
}
|
||||
|
||||
/// Height of footnotes stacked baseline to baseline, from the top of the footnote area to the
|
||||
/// last footnote's descent.
|
||||
fn stack_height<'a>(notes: impl IntoIterator<Item = &'a NoteMetrics>, space_between: f64) -> f64 {
|
||||
let mut h: Option<f64> = None;
|
||||
let mut descent = 0.0;
|
||||
for m in notes {
|
||||
let last = match h {
|
||||
None => m.last,
|
||||
Some(prev) => prev + space_between + m.lead + (m.last - m.first),
|
||||
};
|
||||
h = Some(last);
|
||||
descent = m.descent;
|
||||
}
|
||||
h.map_or(0.0, |h| h + descent)
|
||||
}
|
||||
|
||||
pub(crate) struct Notes {
|
||||
/// Byte offsets of the reference characters (index = footnote index).
|
||||
refs: Vec<usize>,
|
||||
@@ -36,7 +69,7 @@ pub(crate) struct Notes {
|
||||
pub key: Option<usize>,
|
||||
pub placed: Vec<Placed>,
|
||||
/// Composed footnote text by (index, label, width).
|
||||
cache: HashMap<(usize, String, u64), (Arc<ComposedStory>, f64)>,
|
||||
cache: HashMap<(usize, String, u64), (Arc<ComposedStory>, NoteMetrics)>,
|
||||
notes: Vec<Arc<designcraft_doc::Footnote>>,
|
||||
}
|
||||
|
||||
@@ -88,7 +121,7 @@ impl Notes {
|
||||
v
|
||||
}
|
||||
|
||||
fn compose(&mut self, doc: &Document, k: usize, w: f64, f: &FrameSpec, opts: &ComposeOptions) -> (Arc<ComposedStory>, f64) {
|
||||
fn compose(&mut self, doc: &Document, k: usize, w: f64, f: &FrameSpec, opts: &ComposeOptions) -> (Arc<ComposedStory>, NoteMetrics) {
|
||||
let o = &doc.footnote_options;
|
||||
let label = format!("{}{}", o.label(self.numbers[k], true), o.separator);
|
||||
let key = (k, label.clone(), w.to_bits());
|
||||
@@ -102,6 +135,7 @@ impl Notes {
|
||||
vertical: false,
|
||||
exclusions: vec![],
|
||||
page_name: f.page_name.clone(),
|
||||
section_marker: f.section_marker.clone(),
|
||||
page: f.page,
|
||||
grid: None,
|
||||
left_page: f.left_page,
|
||||
@@ -109,14 +143,19 @@ impl Notes {
|
||||
};
|
||||
let nopts = ComposeOptions {
|
||||
page_name: opts.page_name.clone(),
|
||||
section_marker: opts.section_marker.clone(),
|
||||
page: opts.page,
|
||||
running: opts.running.clone(),
|
||||
label: Some(label),
|
||||
xrefs: opts.xrefs.clone(),
|
||||
};
|
||||
let cs = crate::compose(doc, &self.notes[k].text, std::slice::from_ref(&spec), &nopts);
|
||||
let h = cs.frames.first().and_then(|ft| ft.lines.last()).map_or(0.0, |l| l.baseline + l.descent);
|
||||
let v = (Arc::new(cs), h);
|
||||
let lines = cs.frames.first().map(|ft| ft.lines.as_slice()).unwrap_or_default();
|
||||
let m = match (lines.first(), lines.last()) {
|
||||
(Some(a), Some(z)) => NoteMetrics { first: a.baseline, last: z.baseline, lead: a.leading, descent: z.descent },
|
||||
_ => NoteMetrics::default(),
|
||||
};
|
||||
let v = (Arc::new(cs), m);
|
||||
self.cache.insert(key, v.clone());
|
||||
v
|
||||
}
|
||||
@@ -125,25 +164,20 @@ impl Notes {
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn reserve(&mut self, doc: &Document, fi: usize, col: usize, extra: &[usize], w: f64, f: &FrameSpec, opts: &ComposeOptions) -> f64 {
|
||||
let o = &doc.footnote_options;
|
||||
let mut n = 0usize;
|
||||
let mut h = 0.0;
|
||||
for p in self.placed.iter().filter(|p| p.fi == fi && p.col == col) {
|
||||
n += 1;
|
||||
h += p.h;
|
||||
}
|
||||
let (space_between, space_before) = (o.space_between, o.space_before);
|
||||
let mut ms: Vec<NoteMetrics> = self.placed.iter().filter(|p| p.fi == fi && p.col == col).map(|p| p.m).collect();
|
||||
for &k in extra {
|
||||
n += 1;
|
||||
h += self.compose(doc, k, w, f, opts).1;
|
||||
ms.push(self.compose(doc, k, w, f, opts).1);
|
||||
}
|
||||
if n == 0 { 0.0 } else { h + o.space_between * (n - 1) as f64 + o.space_before }
|
||||
if ms.is_empty() { 0.0 } else { stack_height(&ms, space_between) + space_before }
|
||||
}
|
||||
|
||||
pub fn place(&mut self, doc: &Document, k: usize, fi: usize, col: usize, w: f64, f: &FrameSpec, opts: &ComposeOptions) {
|
||||
if self.placed.iter().any(|p| p.k == k) {
|
||||
return;
|
||||
}
|
||||
let (text, h) = self.compose(doc, k, w, f, opts);
|
||||
self.placed.push(Placed { k, fi, col, h, text });
|
||||
let (text, m) = self.compose(doc, k, w, f, opts);
|
||||
self.placed.push(Placed { k, fi, col, m, text });
|
||||
}
|
||||
|
||||
/// Stack each column's footnotes against its bottom, rule above the first.
|
||||
@@ -159,7 +193,7 @@ impl Notes {
|
||||
for (fi, ci) in groups {
|
||||
let (Some(_), Some(col)) = (frames.get(fi), cols.get(fi).and_then(|c| c.get(ci))) else { continue };
|
||||
let here: Vec<&Placed> = self.placed.iter().filter(|p| p.fi == fi && p.col == ci).collect();
|
||||
let total: f64 = here.iter().map(|p| p.h).sum::<f64>() + o.space_between * (here.len() - 1) as f64;
|
||||
let total = stack_height(here.iter().map(|p| &p.m), o.space_between);
|
||||
let top = col.y1 - total;
|
||||
let ft = &mut out.frames[fi];
|
||||
if o.rule.on && o.rule.weight > 0.0 {
|
||||
@@ -171,20 +205,29 @@ impl Notes {
|
||||
tint: o.rule.tint,
|
||||
});
|
||||
}
|
||||
let mut y = top;
|
||||
// Previous footnote's last baseline and bottom.
|
||||
let mut prev: Option<(f64, f64)> = None;
|
||||
for p in here {
|
||||
let note = &story.notes[p.k];
|
||||
let Some(note) = story.notes.get(p.k) else { continue };
|
||||
let (y, y0) = match prev {
|
||||
None => (top, top),
|
||||
Some((last, bottom)) => {
|
||||
let first = last + o.space_between + p.m.lead;
|
||||
(first - p.m.first, (bottom + o.space_between).min(first))
|
||||
}
|
||||
};
|
||||
let y1 = y + p.m.last + p.m.descent;
|
||||
ft.notes.push(PlacedNote {
|
||||
id: note.id,
|
||||
index: p.k,
|
||||
column: ci as u32,
|
||||
label: o.label(self.numbers[p.k], true),
|
||||
origin: Point::new(col.x0, y),
|
||||
rect: Rect::new(col.x0, y, col.x1, y + p.h),
|
||||
rect: Rect::new(col.x0, y0, col.x1, y1),
|
||||
text: p.text.clone(),
|
||||
source: Arc::from(note.text.text.as_str()),
|
||||
});
|
||||
y += p.h + o.space_between;
|
||||
prev = Some((y + p.m.last, y1));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -197,10 +240,15 @@ pub fn find_note(cs: &ComposedStory, id: u64) -> Option<(usize, &PlacedNote)> {
|
||||
|
||||
/// Footnote text hit at frame-inner point `p`: (footnote id, byte in the footnote's story).
|
||||
pub fn hit_note(cs: &ComposedStory, fi: usize, p: Point) -> Option<(u64, usize)> {
|
||||
hit_note_with(cs, fi, p, crate::hit)
|
||||
}
|
||||
|
||||
/// [`hit_note`] with the hit test for the note's text (see [`crate::hit_cell_with`]).
|
||||
pub fn hit_note_with(cs: &ComposedStory, fi: usize, p: Point, hit: fn(&ComposedStory, usize, Point) -> Option<usize>) -> Option<(u64, usize)> {
|
||||
let ft = cs.frames.get(fi)?;
|
||||
let n = ft.notes.iter().find(|n| n.rect.contains(p))?;
|
||||
let local = Point::new(p.x - n.origin.x, p.y - n.origin.y);
|
||||
Some((n.id, crate::hit(&n.text, 0, local).unwrap_or(0)))
|
||||
Some((n.id, hit(&n.text, 0, local).unwrap_or(0)))
|
||||
}
|
||||
|
||||
/// Caret geometry for byte `pos` of a footnote's story, in frame inner space:
|
||||
|
||||
@@ -22,12 +22,15 @@ fn is_event(u: &NestedUntil, c: char, prev: Option<char>, next: Option<char>) ->
|
||||
NestedUntil::ForcedLineBreak => c == designcraft_doc::FORCED_LINE_BREAK,
|
||||
NestedUntil::EmSpace => c == '\u{2003}',
|
||||
NestedUntil::EnSpace => c == '\u{2002}',
|
||||
// Counted by position, not by character (see `overlays`).
|
||||
NestedUntil::Dropcap => false,
|
||||
NestedUntil::Chars(s) => s.contains(c),
|
||||
}
|
||||
}
|
||||
|
||||
/// Character-style ranges for the paragraph `text[range]`, in application order (later wins).
|
||||
pub(crate) fn overlays(text: &str, range: Range<usize>, nested: &[NestedStyle], grep: &[GrepStyle]) -> Vec<(Range<usize>, String)> {
|
||||
/// The paragraph's drop cap ends at `drop_end` (`range.start` without one).
|
||||
pub(crate) fn overlays(text: &str, range: Range<usize>, nested: &[NestedStyle], grep: &[GrepStyle], drop_end: usize) -> Vec<(Range<usize>, String)> {
|
||||
let mut out = Vec::new();
|
||||
let para = &text[range.clone()];
|
||||
// The paragraph's own end mark isn't styled.
|
||||
@@ -37,17 +40,22 @@ pub(crate) fn overlays(text: &str, range: Range<usize>, nested: &[NestedStyle],
|
||||
if pos >= end {
|
||||
break;
|
||||
}
|
||||
let mut count = 0;
|
||||
let mut stop = end;
|
||||
let chars: Vec<(usize, char)> = text[pos..end].char_indices().map(|(i, c)| (pos + i, c)).collect();
|
||||
for (k, &(i, c)) in chars.iter().enumerate() {
|
||||
let prev = if k > 0 { Some(chars[k - 1].1) } else { None };
|
||||
let next = chars.get(k + 1).map(|x| x.1);
|
||||
if is_event(&ns.until, c, prev, next) {
|
||||
count += 1;
|
||||
if count >= ns.count.max(1) {
|
||||
stop = if ns.through { i + c.len_utf8() } else { i };
|
||||
break;
|
||||
if ns.until == NestedUntil::Dropcap {
|
||||
// Through the drop cap runs to its end; up to it (it starts the paragraph) is nothing.
|
||||
stop = if ns.through { drop_end.max(pos).min(end) } else { pos };
|
||||
} else {
|
||||
let mut count = 0;
|
||||
let chars: Vec<(usize, char)> = text[pos..end].char_indices().map(|(i, c)| (pos + i, c)).collect();
|
||||
for (k, &(i, c)) in chars.iter().enumerate() {
|
||||
let prev = if k > 0 { Some(chars[k - 1].1) } else { None };
|
||||
let next = chars.get(k + 1).map(|x| x.1);
|
||||
if is_event(&ns.until, c, prev, next) {
|
||||
count += 1;
|
||||
if count >= ns.count.max(1) {
|
||||
stop = if ns.through { i + c.len_utf8() } else { i };
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -84,14 +92,21 @@ mod tests {
|
||||
let text = "Q: what is 42? A drop of 7 words.\n".to_string();
|
||||
let n = |style: &str, through: bool, count: u32, until: NestedUntil| NestedStyle { style: style.into(), through, count, until };
|
||||
// Through the first ':' then up to the second word end.
|
||||
let o = overlays(&text, 0..text.len(), &[n("Lead", true, 1, NestedUntil::Chars(":".into())), n("Next", false, 2, NestedUntil::Words)], &[]);
|
||||
let o =
|
||||
overlays(&text, 0..text.len(), &[n("Lead", true, 1, NestedUntil::Chars(":".into())), n("Next", false, 2, NestedUntil::Words)], &[], 0);
|
||||
assert_eq!(&text[o[0].0.clone()], "Q:");
|
||||
assert_eq!(&text[o[1].0.clone()], " what is", "up to the end of the second word");
|
||||
// Digits by GREP.
|
||||
let o = overlays(&text, 0..text.len(), &[], &[GrepStyle { style: "Num".into(), pattern: r"\d+".into() }]);
|
||||
let o = overlays(&text, 0..text.len(), &[], &[GrepStyle { style: "Num".into(), pattern: r"\d+".into() }], 0);
|
||||
let got: Vec<&str> = o.iter().map(|(r, _)| &text[r.clone()]).collect();
|
||||
assert_eq!(got, ["42", "7"]);
|
||||
// Through the drop cap (its first 2 bytes here); up to it is nothing; without one, nothing.
|
||||
let d = |through: bool| n("Cap", through, 1, NestedUntil::Dropcap);
|
||||
let o = overlays(&text, 0..text.len(), &[d(true), n("Next", true, 1, NestedUntil::Words)], &[], 2);
|
||||
assert_eq!((&text[o[0].0.clone()], &text[o[1].0.clone()]), ("Q:", " what "));
|
||||
assert_eq!(&text[overlays(&text, 0..text.len(), &[d(false), n("Next", true, 1, NestedUntil::Words)], &[], 2)[0].0.clone()], "Q: ");
|
||||
assert!(overlays(&text, 0..text.len(), &[d(true)], &[], 0).is_empty());
|
||||
// A bad pattern is ignored.
|
||||
assert!(overlays(&text, 0..text.len(), &[], &[GrepStyle { style: "X".into(), pattern: "(".into() }]).is_empty());
|
||||
assert!(overlays(&text, 0..text.len(), &[], &[GrepStyle { style: "X".into(), pattern: "(".into() }], 0).is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -28,9 +28,14 @@ pub struct Glyph {
|
||||
/// Baseline shift (positive = up), including super/subscript.
|
||||
pub shift: f64,
|
||||
pub ascent: f64,
|
||||
/// The font's typographic ascender at the point size (vertical scale doesn't apply): the Ascent
|
||||
/// first baseline offset.
|
||||
pub typo_ascent: f64,
|
||||
pub descent: f64,
|
||||
/// The leading this character asks for (absolute, or auto = size × auto %).
|
||||
pub leading: f64,
|
||||
/// Cap height and x height, scaled like `ascent`: the Cap Height and x Height first baseline
|
||||
/// offsets.
|
||||
pub cap: f64,
|
||||
pub xh: f64,
|
||||
pub size: f64,
|
||||
@@ -64,6 +69,9 @@ pub struct Glyph {
|
||||
/// Upright in a vertical frame: shaped top to bottom (`adv` is its vertical advance) and hung
|
||||
/// from its vertical origin on the line's centre (see [`crate::PlacedGlyph::vertical_xf`]).
|
||||
pub upright: bool,
|
||||
/// Part of the bullet or number the paragraph's list adds: not the line's own text, so it
|
||||
/// doesn't raise the Ascent first baseline.
|
||||
pub list_label: bool,
|
||||
}
|
||||
|
||||
impl Glyph {
|
||||
@@ -88,6 +96,7 @@ pub struct ShapedPara {
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct SubstCtx {
|
||||
pub page_name: Option<String>,
|
||||
/// The section marker text of the page being composed (`None` on parent pages: "Section").
|
||||
pub section_marker: Option<String>,
|
||||
/// Text variable values by index (on the page being composed).
|
||||
pub vars: Arc<Vec<String>>,
|
||||
@@ -138,6 +147,7 @@ impl StyleTable<'_> {
|
||||
stroke: p.stroke.clone(),
|
||||
stroke_tint: p.stroke_tint,
|
||||
stroke_weight: p.stroke_weight,
|
||||
stroke_behind_fill: p.stroke_behind_fill,
|
||||
underline: p.underline,
|
||||
strikethrough: p.strikethrough,
|
||||
underline_rule: crate::Rule {
|
||||
@@ -185,7 +195,8 @@ impl StyleTable<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolve and shape one paragraph.
|
||||
/// Resolve and shape one paragraph. Its drop cap ends at byte `drop.0` (`range.start` without
|
||||
/// one) and takes the character style `drop.1` ("" = none).
|
||||
pub(crate) fn shape_para(
|
||||
db: &ScopedFonts<'_>,
|
||||
styles: &Styles,
|
||||
@@ -199,13 +210,37 @@ pub(crate) fn shape_para(
|
||||
nested: &[designcraft_doc::NestedStyle],
|
||||
grep: &[designcraft_doc::GrepStyle],
|
||||
lines: &[(std::ops::Range<usize>, String)],
|
||||
drop: (usize, &str),
|
||||
) -> ShapedPara {
|
||||
let _ = pi;
|
||||
let mut glyphs = Vec::with_capacity(range.len());
|
||||
// Nested line styles lie under nested and GREP styles (later overlays win).
|
||||
// Nested line styles lie under nested and GREP styles, and the drop cap's style over them all
|
||||
// (later overlays win).
|
||||
let mut overlays: Vec<(std::ops::Range<usize>, String)> = lines.to_vec();
|
||||
// The drop cap's style is the nested styles' leading "through 1 Dropcap" entry (the form IDML
|
||||
// stores it in). Set (`[None]` included), it restyles that entry; a real one stands in for a
|
||||
// missing entry. Either way the nested styles after it start after the drop cap.
|
||||
let set = Some(drop.1).filter(|s| !s.is_empty());
|
||||
let cap_style = set.filter(|s| *s != designcraft_doc::NO_CHAR_STYLE);
|
||||
let with_cap: Vec<designcraft_doc::NestedStyle>;
|
||||
let nested = match set {
|
||||
Some(s) if nested.first().is_some_and(designcraft_doc::NestedStyle::is_drop_cap) => {
|
||||
with_cap = std::iter::once(designcraft_doc::NestedStyle::drop_cap(s)).chain(nested.iter().skip(1).cloned()).collect();
|
||||
&with_cap[..]
|
||||
}
|
||||
Some(s) if cap_style.is_some() && !nested.is_empty() => {
|
||||
with_cap = std::iter::once(designcraft_doc::NestedStyle::drop_cap(s)).chain(nested.iter().cloned()).collect();
|
||||
&with_cap[..]
|
||||
}
|
||||
_ => nested,
|
||||
};
|
||||
if !nested.is_empty() || !grep.is_empty() {
|
||||
overlays.extend(crate::overlay::overlays(&story.text, range.clone(), nested, grep));
|
||||
overlays.extend(crate::overlay::overlays(&story.text, range.clone(), nested, grep, drop.0));
|
||||
}
|
||||
if let Some(s) = cap_style
|
||||
&& drop.0 > range.start
|
||||
{
|
||||
overlays.push((range.start..drop.0, s.to_string()));
|
||||
}
|
||||
// Each run, cut where nested / GREP styles start and end.
|
||||
let mut segments: Vec<(usize, usize, Option<&str>, &designcraft_doc::CharFormat)> = Vec::new();
|
||||
@@ -273,7 +308,7 @@ pub(crate) fn shape_para(
|
||||
}
|
||||
let mut g = control_glyph(&face, &props, auto_leading, style, a + i, c);
|
||||
g.ch = HIDDEN;
|
||||
(g.ascent, g.descent, g.leading, g.cap, g.xh) = (0.0, 0.0, 0.0, 0.0, 0.0);
|
||||
(g.ascent, g.typo_ascent, g.descent, g.leading, g.cap, g.xh) = (0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
|
||||
glyphs.push(g);
|
||||
}
|
||||
continue;
|
||||
@@ -586,7 +621,14 @@ fn shape_run_raw(
|
||||
} else {
|
||||
sub.page_name.clone().unwrap_or_else(|| "#".into())
|
||||
};
|
||||
shape_segment(db, text, i..i + c.len_utf8(), Some(&s), p, &primary, auto_leading, style, out, sub.vertical);
|
||||
if s.is_empty() {
|
||||
// A section without marker text: the character takes no space.
|
||||
let mut g = control_glyph(&primary, p, auto_leading, style, i, c);
|
||||
g.adv = 0.0;
|
||||
out.push(g);
|
||||
} else {
|
||||
shape_segment(db, text, i..i + c.len_utf8(), Some(&s), p, &primary, auto_leading, style, out, sub.vertical);
|
||||
}
|
||||
}
|
||||
designcraft_doc::OBJECT_MARK => {
|
||||
let mut g = control_glyph(&primary, p, auto_leading, style, i, c);
|
||||
@@ -597,10 +639,18 @@ fn shape_run_raw(
|
||||
Some(y) => {
|
||||
g.adv = o.w;
|
||||
g.ascent = g.ascent.max(o.h + y);
|
||||
g.typo_ascent = g.typo_ascent.max(o.h + y);
|
||||
g.cap = g.cap.max(o.h + y);
|
||||
g.xh = g.xh.max(o.h + y);
|
||||
g.descent = g.descent.max(-y);
|
||||
}
|
||||
// Pushes its line down by its height and spacing.
|
||||
None => g.ascent += o.h + o.space,
|
||||
None => {
|
||||
g.ascent += o.h + o.space;
|
||||
g.typo_ascent += o.h + o.space;
|
||||
g.cap += o.h + o.space;
|
||||
g.xh += o.h + o.space;
|
||||
}
|
||||
}
|
||||
if auto || o.y_offset.is_none() {
|
||||
g.leading = g.leading.max(g.ascent + g.descent);
|
||||
@@ -771,6 +821,7 @@ fn control_glyph(face: &Arc<FontFace>, p: &CharProps, auto_leading: TypeEnv, sty
|
||||
sy: k * p.v_scale,
|
||||
shift,
|
||||
ascent,
|
||||
typo_ascent: face.typo_ascent * k,
|
||||
descent,
|
||||
leading,
|
||||
cap,
|
||||
@@ -796,6 +847,7 @@ fn control_glyph(face: &Arc<FontFace>, p: &CharProps, auto_leading: TypeEnv, sty
|
||||
shaping_rtl: false,
|
||||
lang: designcraft_doc::language_tag(&p.language),
|
||||
upright: false,
|
||||
list_label: false,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -889,6 +941,7 @@ fn shape_segment(
|
||||
sy: k * p.v_scale,
|
||||
shift,
|
||||
ascent,
|
||||
typo_ascent: face.typo_ascent * k,
|
||||
descent,
|
||||
leading,
|
||||
cap,
|
||||
@@ -918,6 +971,7 @@ fn shape_segment(
|
||||
shaping_rtl: sg.rtl,
|
||||
lang,
|
||||
upright: up,
|
||||
list_label: false,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -112,6 +112,7 @@ fn compose_cell(doc: &Document, cell: &Cell, w: f64, opts: &ComposeOptions, left
|
||||
vertical: false,
|
||||
exclusions: vec![],
|
||||
page_name: opts.page_name.clone(),
|
||||
section_marker: opts.section_marker.clone(),
|
||||
page: opts.page,
|
||||
grid: None,
|
||||
left_page,
|
||||
@@ -442,6 +443,7 @@ fn emit(
|
||||
spacing: 1.0,
|
||||
hj: 0,
|
||||
keep_violation: false,
|
||||
drop_cap: None,
|
||||
});
|
||||
ft.tables.push(TableFrag {
|
||||
table: table.id,
|
||||
@@ -602,6 +604,17 @@ fn fragment_strokes(
|
||||
|
||||
/// The cell under `p` (frame inner space) in frame `fi`: (table, row, col, story byte in the cell).
|
||||
pub fn hit_cell(cs: &ComposedStory, fi: usize, p: Point) -> Option<(u64, usize, usize, usize)> {
|
||||
hit_cell_with(cs, fi, p, crate::hit)
|
||||
}
|
||||
|
||||
/// [`hit_cell`] with the hit test for the cell's text: [`crate::hit`] (caret position) or
|
||||
/// [`crate::hit_char`] (character under the point).
|
||||
pub fn hit_cell_with(
|
||||
cs: &ComposedStory,
|
||||
fi: usize,
|
||||
p: Point,
|
||||
hit: fn(&ComposedStory, usize, Point) -> Option<usize>,
|
||||
) -> Option<(u64, usize, usize, usize)> {
|
||||
let ft = cs.frames.get(fi)?;
|
||||
for t in &ft.tables {
|
||||
if !t.rect.contains(p) {
|
||||
@@ -610,7 +623,7 @@ pub fn hit_cell(cs: &ComposedStory, fi: usize, p: Point) -> Option<(u64, usize,
|
||||
for c in &t.cells {
|
||||
if c.rect.contains(p) {
|
||||
let local = Point::new(p.x - c.origin.x, p.y - c.origin.y);
|
||||
let b = crate::hit(&c.text, 0, local).unwrap_or(0);
|
||||
let b = hit(&c.text, 0, local).unwrap_or(0);
|
||||
return Some((t.table, c.row, c.col, b));
|
||||
}
|
||||
}
|
||||
|
||||
+1331
-3
File diff suppressed because it is too large
Load Diff
@@ -19,15 +19,17 @@ pub fn has_xrefs(st: &Story) -> bool {
|
||||
}
|
||||
|
||||
impl XrefIndex {
|
||||
/// `get` composes a story (normally through the cache). Stories that themselves hold
|
||||
/// cross-references are composed without resolving them (their anchors' pages hardly move).
|
||||
/// `get` composes a story (normally through the cache). Stories that hold cross-references or
|
||||
/// running headers are composed without resolving them (their anchors' pages hardly move):
|
||||
/// through the cache they would build this index again, directly or by way of the running-header index.
|
||||
pub fn build(doc: &Document, get: &dyn Fn(StoryId) -> Arc<ComposedStory>) -> XrefIndex {
|
||||
let mut pages = HashMap::new();
|
||||
for (sid, st) in &doc.stories {
|
||||
if st.anchors.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let cs = if has_xrefs(st) { Arc::new(crate::compose_story(doc, *sid, &Default::default())) } else { get(*sid) };
|
||||
let indexed = has_xrefs(st) || crate::vars::has_running(doc, st);
|
||||
let cs = if indexed { Arc::new(crate::compose_story(doc, *sid, &Default::default())) } else { get(*sid) };
|
||||
for a in &st.anchors {
|
||||
let Some(pos) = st.anchor_pos(a.id) else { continue };
|
||||
if let Some((page, ..)) = crate::vars::place(doc, &cs, pos) {
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
//! shown); each placement's frame data (transform, crop, fitting) lives on its [`Graphic`].
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet, HashMap};
|
||||
use std::hash::BuildHasher;
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::story::Story;
|
||||
@@ -246,10 +247,19 @@ impl Document {
|
||||
if !self.asset_refs(&mut |_| {}) {
|
||||
return 0;
|
||||
}
|
||||
let mut reps: HashMap<(usize, &str, u32), Vec<&Arc<Asset>>> = HashMap::new();
|
||||
let fingerprint = std::collections::hash_map::RandomState::new();
|
||||
let mut hashes = HashMap::new();
|
||||
let mut reps: HashMap<_, Vec<&Arc<Asset>>> = HashMap::new();
|
||||
let mut map = HashMap::new();
|
||||
for a in self.assets.values() {
|
||||
let bucket = reps.entry((a.data.len(), a.mime.as_str(), a.page)).or_default();
|
||||
// Empty, unlinked assets never compare equal. Don't build a quadratic bucket
|
||||
// of them, and hash a shared immutable buffer only once per compaction.
|
||||
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 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)) {
|
||||
Some(r) => {
|
||||
map.insert(a.id, r.id);
|
||||
@@ -280,6 +290,56 @@ mod tests {
|
||||
Asset { id: AssetId(id), name: "p.png".into(), mime: "image/png".into(), link: None, data: Arc::new(data.to_vec()), pixels: None, page: 0 }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn equal_size_assets_keep_distinct_contents_and_merge_exact_copies() {
|
||||
let mut d = Document::new(&Default::default());
|
||||
for id in 1..=256u64 {
|
||||
let mut bytes = vec![42; 1024];
|
||||
bytes[1016..].copy_from_slice(&id.to_le_bytes());
|
||||
d.assets.insert(AssetId(id), Arc::new(asset(id, &bytes)));
|
||||
d.assets.insert(AssetId(id + 256), Arc::new(asset(id + 256, &bytes)));
|
||||
}
|
||||
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());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compaction_preserves_asset_identity_and_missing_data_rules() {
|
||||
let mut d = Document::new(&Default::default());
|
||||
let mut cases = vec![asset(1, b"same"), asset(2, b"same"), asset(3, b"same"), asset(4, b"same")];
|
||||
cases[1].mime = "application/pdf".into();
|
||||
cases[2].page = 1;
|
||||
cases[3].link = Some("/linked.png".into());
|
||||
cases.extend([asset(5, b""), asset(6, b""), asset(7, b""), asset(8, b"")]);
|
||||
cases[6].link = Some("/missing.png".into());
|
||||
cases[7].link = Some("/missing.png".into());
|
||||
for a in cases {
|
||||
d.assets.insert(a.id, Arc::new(a));
|
||||
}
|
||||
assert_eq!(d.merge_duplicate_assets(), 1);
|
||||
assert_eq!(d.assets.keys().copied().collect::<Vec<_>>(), (1..=7).map(AssetId).collect::<Vec<_>>());
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[ignore = "manual bounded timing comparison; no timing assertion"]
|
||||
fn equal_size_assets_timing() {
|
||||
for count in [500, 1000, 2000] {
|
||||
let mut d = Document::new(&Default::default());
|
||||
for id in 1..=count as u64 {
|
||||
let mut bytes = vec![42; 8192];
|
||||
bytes[8184..].copy_from_slice(&id.to_le_bytes());
|
||||
d.assets.insert(AssetId(id), Arc::new(asset(id, &bytes)));
|
||||
}
|
||||
let start = std::time::Instant::now();
|
||||
assert_eq!(d.merge_duplicate_assets(), 0);
|
||||
eprintln!("{count} distinct 8 KiB assets: {:?}", start.elapsed());
|
||||
}
|
||||
}
|
||||
|
||||
fn graphic_item(id: u64, asset: u64, crop: f64) -> Item {
|
||||
let mut it = Item::new(ItemId(id), LayerId(1), Shape::Rectangle, shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)));
|
||||
it.content = Content::Graphic(Graphic {
|
||||
|
||||
+56
-2
@@ -190,6 +190,13 @@ impl Digits {
|
||||
}
|
||||
}
|
||||
|
||||
/// Does `c` belong to a script that capitalizes the first letter of sentences, words and headings?
|
||||
/// Georgian doesn't: Unicode maps Mkhedruli to Mtavruli capitals, but those are only for all-caps
|
||||
/// text, never for a sentence's, a title's or an index heading's first letter.
|
||||
pub fn capitalizes(c: char) -> bool {
|
||||
!matches!(c, '\u{10A0}'..='\u{10FF}' | '\u{1C90}'..='\u{1CBF}' | '\u{2D00}'..='\u{2D2F}')
|
||||
}
|
||||
|
||||
/// The BCP 47 tag of a language name as InDesign and IDML write it ("English: USA", "Chinese:
|
||||
/// Simplified", or a locale code such as "de_DE_2006"), for the shaper's localized forms (`locl`)
|
||||
/// and everything that depends on the language (quotes, hyphenation and spelling, line breaking,
|
||||
@@ -272,6 +279,7 @@ pub fn language_tag(language: &str) -> Option<&'static str> {
|
||||
"persian" | "farsi" => "fa",
|
||||
"urdu" => "ur",
|
||||
"hebrew" => "he",
|
||||
"georgian" => "ka",
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
@@ -431,6 +439,8 @@ pub enum NestedUntil {
|
||||
ForcedLineBreak,
|
||||
EmSpace,
|
||||
EnSpace,
|
||||
/// The paragraph's drop cap characters.
|
||||
Dropcap,
|
||||
/// Any of these characters.
|
||||
Chars(String),
|
||||
}
|
||||
@@ -467,6 +477,18 @@ impl Default for NestedStyle {
|
||||
}
|
||||
}
|
||||
|
||||
impl NestedStyle {
|
||||
/// The drop cap's character style as a nested style: `style` through 1 drop cap.
|
||||
pub fn drop_cap(style: &str) -> Self {
|
||||
NestedStyle { style: style.into(), through: true, count: 1, until: NestedUntil::Dropcap }
|
||||
}
|
||||
|
||||
/// Is this the form a drop cap's character style takes at the start of a nested style list?
|
||||
pub fn is_drop_cap(&self) -> bool {
|
||||
self.until == NestedUntil::Dropcap && self.through && self.count == 1
|
||||
}
|
||||
}
|
||||
|
||||
/// A character style applied to every match of a regular expression in the paragraph.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", default)]
|
||||
@@ -530,12 +552,16 @@ pub struct TabStop {
|
||||
pub align_on: String,
|
||||
}
|
||||
|
||||
/// The colour of a paragraph rule that follows the paragraph's text colour.
|
||||
pub const TEXT_COLOR: &str = "Text Color";
|
||||
|
||||
/// A paragraph rule (Rule Above / Rule Below).
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct Rule {
|
||||
pub on: bool,
|
||||
pub weight: f64,
|
||||
/// A swatch, or [`TEXT_COLOR`].
|
||||
pub color: String,
|
||||
pub tint: f32,
|
||||
/// Width: column (true) or text (false).
|
||||
@@ -547,7 +573,7 @@ pub struct Rule {
|
||||
|
||||
impl Default for Rule {
|
||||
fn default() -> Self {
|
||||
Rule { on: false, weight: 1.0, color: "[Black]".into(), tint: 1.0, column_width: true, offset: 0.0, left_indent: 0.0, right_indent: 0.0 }
|
||||
Rule { on: false, weight: 1.0, color: TEXT_COLOR.into(), tint: 1.0, column_width: true, offset: 0.0, left_indent: 0.0, right_indent: 0.0 }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -735,6 +761,9 @@ attr_set! {
|
||||
stroke: String = "[None]".into(),
|
||||
stroke_tint: f32 = 1.0,
|
||||
stroke_weight: f64 = 1.0,
|
||||
/// Stroke behind fill: the stroke is painted under the fill and lies wholly outside the
|
||||
/// letters at its full weight, so the letters keep their shape. Off, it straddles the outline.
|
||||
stroke_behind_fill: bool = false,
|
||||
capitalization: Capitalization = Capitalization::Normal,
|
||||
position: Position = Position::Normal,
|
||||
underline: bool = false,
|
||||
@@ -809,8 +838,17 @@ attr_set! {
|
||||
last_line_indent: f64 = 0.0,
|
||||
space_before: f64 = 0.0,
|
||||
space_after: f64 = 0.0,
|
||||
/// Drop cap: the paragraph's first `drop_cap_chars` characters (code points, never
|
||||
/// splitting a base from its combining marks) set `drop_cap_lines` lines tall, in the
|
||||
/// character style `drop_cap_style` ("" or `[None]`: the text's own formatting).
|
||||
drop_cap_lines: u32 = 0,
|
||||
drop_cap_chars: u32 = 0,
|
||||
drop_cap_style: String = String::new(),
|
||||
/// Align Left Edge: the drop cap's ink starts at the indent (its first letter's left side
|
||||
/// bearing is taken off), and the lines beside it start where its advance ends.
|
||||
drop_cap_align_left: bool = true,
|
||||
/// Scale for Descenders (kept and round-tripped; doesn't change the layout).
|
||||
drop_cap_scale_descenders: bool = false,
|
||||
/// Nested styles, in order from the paragraph start.
|
||||
nested_styles: Vec<NestedStyle> = Vec::new(),
|
||||
/// GREP styles: a character style for every match of a pattern (applied after nested).
|
||||
@@ -855,7 +893,8 @@ attr_set! {
|
||||
// Keeps
|
||||
keep_with_next: u32 = 0,
|
||||
keep_lines_together: bool = false,
|
||||
keep_all_lines: bool = true,
|
||||
/// All lines in paragraph (true) or at start/end of paragraph (false).
|
||||
keep_all_lines: bool = false,
|
||||
keep_first: u32 = 2,
|
||||
keep_last: u32 = 2,
|
||||
start_paragraph: StartParagraph = StartParagraph::Anywhere,
|
||||
@@ -961,6 +1000,20 @@ mod tests {
|
||||
assert_eq!(a.rule_below, None, "null clears the override");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stroke_behind_fill_is_saved_only_when_set() {
|
||||
assert!(!CharProps::default().stroke_behind_fill);
|
||||
assert_eq!(serde_json::to_value(CharAttrs::default()).unwrap(), serde_json::json!({}));
|
||||
let mut a = CharAttrs::default();
|
||||
a.set_json("strokeBehindFill", &serde_json::json!(true)).unwrap();
|
||||
let v = serde_json::to_value(&a).unwrap();
|
||||
assert_eq!(v, serde_json::json!({"strokeBehindFill": true}));
|
||||
assert_eq!(serde_json::from_value::<CharAttrs>(v).unwrap(), a);
|
||||
let mut p = CharProps::default();
|
||||
p.apply(&a);
|
||||
assert!(p.stroke_behind_fill);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn digits_map_to_their_script() {
|
||||
assert_eq!(Digits::Default.map('7', "Arabic"), '7');
|
||||
@@ -976,6 +1029,7 @@ mod tests {
|
||||
assert_eq!(language_tag("English: USA"), Some("en-US"));
|
||||
assert_eq!(language_tag("English: Australian"), Some("en"));
|
||||
assert_eq!(language_tag("Turkish"), Some("tr"));
|
||||
assert_eq!(language_tag("Georgian"), Some("ka"));
|
||||
assert_eq!(language_tag("Japanese"), Some("ja"));
|
||||
assert_eq!(language_tag("Korean"), Some("ko"));
|
||||
assert_eq!(language_tag("Chinese"), Some("zh"));
|
||||
|
||||
+17
-6
@@ -226,6 +226,7 @@ impl Document {
|
||||
liquid: Default::default(),
|
||||
transition: None,
|
||||
view_rotation: 0,
|
||||
show_parent_overlay: false,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -267,15 +268,26 @@ impl Document {
|
||||
|
||||
/// Redistribute document pages into spreads (facing: page 1 alone on the right, then pairs).
|
||||
/// Items move with the page their centre is on. Spreads with `allow_shuffle == false` are kept.
|
||||
/// Facing pages take their side from their page number, as InDesign shuffles them: an odd
|
||||
/// number is a right page (a left page bound right to left), so a section that starts at 1 on
|
||||
/// a left page moves it to the right and the pages after it follow.
|
||||
pub fn repaginate(&mut self) {
|
||||
// Collect pages with their items (items in page-relative coordinates).
|
||||
let odd: Vec<bool> = (0..self.page_count()).map(|i| self.page_number(i) % 2 == 1).collect();
|
||||
// Collect pages with their items (items in page-relative coordinates) and their numbers' parity.
|
||||
let mut pages: Vec<(Page, Vec<Arc<Item>>)> = Vec::new();
|
||||
let mut parity: Vec<bool> = Vec::new();
|
||||
let mut kept: Vec<(usize, Arc<Spread>)> = Vec::new();
|
||||
let mut abs = 0;
|
||||
for sp in self.spreads.drain(..) {
|
||||
if !sp.allow_shuffle && sp.pages.len() > 1 {
|
||||
abs += sp.pages.len();
|
||||
kept.push((pages.len(), sp));
|
||||
continue;
|
||||
}
|
||||
for _ in &sp.pages {
|
||||
parity.push(odd.get(abs).copied().unwrap_or(abs % 2 == 0));
|
||||
abs += 1;
|
||||
}
|
||||
let mut sp = Arc::unwrap_or_clone(sp);
|
||||
let mut per: Vec<Vec<Arc<Item>>> = vec![Vec::new(); sp.pages.len()];
|
||||
for it in std::mem::take(&mut sp.items) {
|
||||
@@ -326,13 +338,12 @@ impl Document {
|
||||
}
|
||||
spreads.push(sp);
|
||||
};
|
||||
// An even start page number (Document Setup › Start Page #) begins with a left page.
|
||||
let shift = usize::from(self.sections.iter().find(|x| x.start == 0).and_then(|x| x.start_number).is_some_and(|n| n % 2 == 0));
|
||||
for (i, (mut p, items)) in pages.into_iter().enumerate() {
|
||||
if facing {
|
||||
// Page i (0-based) is a right page when its number is odd (1, 3, 5 …).
|
||||
// A page is a right page when its number is odd (1, 3, 5 …), counting each
|
||||
// section from its start number (Document Setup › Start Page # included).
|
||||
// Bound right to left, odd pages are left pages and spreads start on the right.
|
||||
let odd = (i + shift) % 2 == 0;
|
||||
let odd = parity.get(i).copied().unwrap_or(i % 2 == 0);
|
||||
p.side = if odd != rtl { PageSide::Right } else { PageSide::Left };
|
||||
let starts = if rtl { PageSide::Right } else { PageSide::Left };
|
||||
if p.side == starts && !cur.is_empty() {
|
||||
@@ -373,7 +384,7 @@ impl Document {
|
||||
return Ok(vec![]);
|
||||
}
|
||||
let n = self.page_count();
|
||||
let at = after.map_or(0, |a| (a + 1).min(n));
|
||||
let at = after.map_or(0, |a| a.saturating_add(1).min(n));
|
||||
let template = self.page(at.saturating_sub(1).min(n.saturating_sub(1))).cloned();
|
||||
let (cols, gutter, margins) =
|
||||
template.as_ref().map(|t| (t.columns.count, t.columns.gutter, t.margins)).unwrap_or((1, 12.0, Margins::uniform(36.0)));
|
||||
|
||||
+229
-63
@@ -200,87 +200,229 @@ impl Document {
|
||||
Ok((id, sid))
|
||||
}
|
||||
|
||||
/// Thread `from` → `to`: `to` joins `from`'s story right after `from`. If `to` held its own text,
|
||||
/// that text is appended to the story (as a new paragraph) and its old story is removed.
|
||||
/// Thread `from` → `to`: `to` joins `from`'s story right after `from` (between `from` and the
|
||||
/// frame that followed it, if any). If `to` held its own text, that text is appended to the
|
||||
/// story (as new paragraphs) and its old story is removed; frames that followed `to` come
|
||||
/// along, frames before it keep an empty story of their own. An empty (unassigned) `from` or
|
||||
/// `to` becomes a text frame. `from`'s story keeps its id.
|
||||
pub fn thread(&mut self, from: ItemId, to: ItemId) -> Result<()> {
|
||||
if from == to {
|
||||
return Err(DocError::Invalid("cannot thread a frame to itself".into()));
|
||||
}
|
||||
let fs = self.item(from).and_then(|i| i.text_frame()).map(|t| t.story).ok_or(DocError::NoItem(from))?;
|
||||
// Convert unassigned/graphic-less frames into text frames.
|
||||
let ts = match self.item(to).ok_or(DocError::NoItem(to))?.content.clone() {
|
||||
Content::Text(t) => Some(t.story),
|
||||
Content::Unassigned => None,
|
||||
_ => return Err(DocError::Invalid("can only thread to text or empty frames".into())),
|
||||
self.check_thread_links(from, to, false)?;
|
||||
let ts = self.frame_story(to)?;
|
||||
let fs = match self.frame_story(from)? {
|
||||
Some(s) => s,
|
||||
None => self.give_empty_story(from)?,
|
||||
};
|
||||
if ts == Some(fs) {
|
||||
return Err(DocError::Invalid("frames are already in the same story".into()));
|
||||
}
|
||||
if let Some(ts) = ts {
|
||||
let other = self.stories.remove(&ts).ok_or(DocError::NoStory(ts))?;
|
||||
let other = Arc::unwrap_or_clone(other);
|
||||
// Frames of the other story after `to` follow along; frames before it are left as empty new stories.
|
||||
let pos_to = other.frames.iter().position(|f| *f == to).unwrap_or(0);
|
||||
let before: Vec<ItemId> = other.frames[..pos_to].to_vec();
|
||||
let after: Vec<ItemId> = other.frames[pos_to..].to_vec();
|
||||
{
|
||||
let st = self.story_mut(fs).ok_or(DocError::NoStory(fs))?;
|
||||
if !other.text.is_empty() {
|
||||
st.text.push('\n');
|
||||
st.text.push_str(&other.text);
|
||||
st.paras.extend(other.paras.iter().cloned());
|
||||
// Char runs: '\n' takes the last run's format, then the other story's runs.
|
||||
if let Some(last) = st.chars.last_mut() {
|
||||
last.len += 1;
|
||||
}
|
||||
st.chars.extend(other.chars.iter().filter(|r| r.len > 0).cloned());
|
||||
st.tables.extend(other.tables.iter().map(|(k, v)| (*k, v.clone())));
|
||||
for n in &other.notes {
|
||||
let id = st.next_note_id();
|
||||
st.notes.push(Arc::new(crate::Footnote { id, text: n.text.clone() }));
|
||||
}
|
||||
st.anchors.extend(other.anchors.iter().cloned());
|
||||
st.xrefs.extend(other.xrefs.iter().cloned());
|
||||
st.index_refs.extend(other.index_refs.iter().cloned());
|
||||
st.objects.extend(other.objects.iter().cloned());
|
||||
st.rev += 1;
|
||||
}
|
||||
let at = st.frames.iter().position(|f| *f == from).map_or(st.frames.len(), |p| p + 1);
|
||||
for (k, f) in after.iter().enumerate() {
|
||||
st.frames.insert(at + k, *f);
|
||||
}
|
||||
}
|
||||
for f in &after {
|
||||
if let Some(t) = self.item_mut(*f).and_then(Item::text_frame_mut) {
|
||||
t.story = fs;
|
||||
}
|
||||
}
|
||||
if !before.is_empty() {
|
||||
let nid = StoryId(self.alloc());
|
||||
let mut ns = Story::new(nid);
|
||||
ns.frames = before.clone();
|
||||
ns.vertical = other.vertical;
|
||||
ns.direction = other.direction;
|
||||
for f in &before {
|
||||
if let Some(t) = self.item_mut(*f).and_then(Item::text_frame_mut) {
|
||||
t.story = nid;
|
||||
}
|
||||
}
|
||||
self.stories.insert(nid, Arc::new(ns));
|
||||
}
|
||||
} else {
|
||||
let Some(ts) = ts else {
|
||||
let st = self.story_mut(fs).ok_or(DocError::NoStory(fs))?;
|
||||
let at = st.frames.iter().position(|f| *f == from).map_or(st.frames.len(), |p| p + 1);
|
||||
st.frames.insert(at, to);
|
||||
st.rev += 1;
|
||||
let it = self.item_mut(to).ok_or(DocError::NoItem(to))?;
|
||||
it.content = Content::Text(TextFrame { story: fs, options: TextFrameOptions::default() });
|
||||
}
|
||||
if let Some(st) = self.story_mut(fs) {
|
||||
return Ok(());
|
||||
};
|
||||
let mut other = Arc::unwrap_or_clone(self.stories.remove(&ts).ok_or(DocError::NoStory(ts))?);
|
||||
// Frames of the other story from `to` on follow along; frames before it are left as an empty new story.
|
||||
let pos_to = other.frames.iter().position(|f| *f == to).unwrap_or(0);
|
||||
let after = other.frames.split_off(pos_to);
|
||||
let before = std::mem::take(&mut other.frames);
|
||||
let (vertical, direction) = (other.vertical, other.direction);
|
||||
let offset;
|
||||
{
|
||||
let st = self.story_mut(fs).ok_or(DocError::NoStory(fs))?;
|
||||
offset = if st.text.is_empty() { 0 } else { st.text.len().saturating_add(1) };
|
||||
// The story keeps its own direction, even when it was empty and takes the other's text.
|
||||
let own = (st.vertical, st.direction);
|
||||
st.append_story(other);
|
||||
(st.vertical, st.direction) = own;
|
||||
let at = st.frames.iter().position(|f| *f == from).map_or(st.frames.len(), |p| p + 1);
|
||||
for (k, f) in after.iter().enumerate() {
|
||||
st.frames.insert(at + k, *f);
|
||||
}
|
||||
st.rev += 1;
|
||||
}
|
||||
self.remap_thread_story_refs(ts, fs, offset);
|
||||
for f in &after {
|
||||
if let Some(t) = self.item_mut(*f).and_then(Item::text_frame_mut) {
|
||||
t.story = fs;
|
||||
}
|
||||
}
|
||||
if !before.is_empty() {
|
||||
let nid = StoryId(self.alloc());
|
||||
let mut ns = Story::new(nid);
|
||||
ns.frames = before.clone();
|
||||
ns.vertical = vertical;
|
||||
ns.direction = direction;
|
||||
for f in &before {
|
||||
if let Some(t) = self.item_mut(*f).and_then(Item::text_frame_mut) {
|
||||
t.story = nid;
|
||||
}
|
||||
}
|
||||
self.stories.insert(nid, Arc::new(ns));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// [`Document::thread`], except that an empty `from` alone in its story, threaded in front of
|
||||
/// the first frame of `to`'s story, joins that story: the story with the text keeps its id
|
||||
/// (and whatever refers to it).
|
||||
pub fn thread_keeping_story(&mut self, from: ItemId, to: ItemId) -> Result<()> {
|
||||
let fs = self.frame_story(from)?;
|
||||
let from_empty = fs.is_none_or(|fs| self.story(fs).is_some_and(|s| s.text.is_empty() && s.frames == [from]));
|
||||
let ts = self.frame_story(to)?;
|
||||
let to_first = ts.and_then(|ts| self.story(ts)).is_some_and(|s| s.frames.first() == Some(&to));
|
||||
let (Some(ts), true, true) = (ts, from_empty, to_first && from != to) else { return self.thread(from, to) };
|
||||
self.check_thread_links(from, to, true)?;
|
||||
if let Some(fs) = fs {
|
||||
self.stories.remove(&fs);
|
||||
self.remap_thread_story_refs(fs, ts, 0);
|
||||
}
|
||||
let st = self.story_mut(ts).ok_or(DocError::NoStory(ts))?;
|
||||
st.frames.insert(0, from);
|
||||
st.rev += 1;
|
||||
let it = self.item_mut(from).ok_or(DocError::NoItem(from))?;
|
||||
match it.text_frame_mut() {
|
||||
Some(t) => t.story = ts,
|
||||
None => it.content = Content::Text(TextFrame { story: ts, options: TextFrameOptions::default() }),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Story-external text addresses move with the incoming text when threading merges stories.
|
||||
/// Linked children follow the surviving whole story, including for an empty removed parent;
|
||||
/// their copied content stays unchanged until an explicit Update Link.
|
||||
fn remap_thread_story_refs(&mut self, from: StoryId, to: StoryId, offset: usize) {
|
||||
// The child's old snapshot is not a snapshot of the newly merged parent. Force it
|
||||
// out of date even when the old and surviving revision numbers happen to coincide.
|
||||
let stale_rev = self.story(to).map_or(0, |st| st.rev.wrapping_sub(1));
|
||||
for st in self.stories.values_mut() {
|
||||
if st.link.is_some_and(|(parent, _)| parent == from) {
|
||||
Arc::make_mut(st).link = Some((to, stale_rev));
|
||||
}
|
||||
}
|
||||
for link in &mut self.hyperlinks {
|
||||
if let crate::HyperlinkSource::Text { story, start, end } = &mut link.source
|
||||
&& *story == from
|
||||
{
|
||||
*story = to;
|
||||
*start = start.saturating_add(offset);
|
||||
*end = end.saturating_add(offset);
|
||||
}
|
||||
}
|
||||
for placeholder in &mut self.data_merge.placeholders {
|
||||
if let crate::PlaceholderAnchor::Text { story, start, end } = &mut placeholder.anchor
|
||||
&& *story == from
|
||||
{
|
||||
*story = to;
|
||||
*start = start.saturating_add(offset);
|
||||
*end = end.saturating_add(offset);
|
||||
}
|
||||
}
|
||||
if self.settings.primary_story == Some(from) {
|
||||
self.settings.primary_story = Some(to);
|
||||
}
|
||||
}
|
||||
|
||||
/// A linked child is replaced wholesale on update. Only empty, unlinked frame
|
||||
/// extensions can join it without losing a link or newly appended body text.
|
||||
fn check_thread_links(&self, from: ItemId, to: ItemId, keep_to: bool) -> Result<()> {
|
||||
let fs = self.frame_story(from)?;
|
||||
let ts = self.frame_story(to)?;
|
||||
let first = fs.and_then(|id| self.story(id));
|
||||
let second = ts.and_then(|id| self.story(id));
|
||||
let incompatible = if keep_to {
|
||||
first.is_some_and(|st| st.link.is_some()) || second.is_some_and(|st| st.link.is_some_and(|(parent, _)| Some(parent) == fs))
|
||||
} else {
|
||||
second.is_some_and(|st| st.link.is_some())
|
||||
|| first.is_some_and(|st| {
|
||||
st.link.is_some()
|
||||
&& second.is_some_and(|incoming| !incoming.text.is_empty() || st.link.is_some_and(|(parent, _)| parent == incoming.id))
|
||||
})
|
||||
};
|
||||
if incompatible {
|
||||
return Err(DocError::Invalid("unlink the linked story before merging its text".into()));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Can a user thread `from` → `to`? Both are text frames or empty frames (not lines), on
|
||||
/// document spreads or on the same parent spread, not in one story already, and no frame
|
||||
/// threads into `to` yet. [`Document::thread`] itself is less strict (import and autoflow).
|
||||
pub fn check_thread(&self, from: ItemId, to: ItemId) -> Result<()> {
|
||||
if from == to {
|
||||
return Err(DocError::Invalid("cannot thread a frame to itself".into()));
|
||||
}
|
||||
for id in [from, to] {
|
||||
let it = self.item(id).ok_or(DocError::NoItem(id))?;
|
||||
if !matches!(it.content, Content::Text(_) | Content::Unassigned) || it.shape == Shape::GraphicLine {
|
||||
return Err(DocError::Invalid(format!("{id} is not a text frame or an empty frame")));
|
||||
}
|
||||
if it.locked || self.layer(it.layer).is_some_and(|l| l.locked) {
|
||||
return Err(DocError::Invalid(format!("{id} is locked or on a locked layer")));
|
||||
}
|
||||
}
|
||||
let (Some(fl), Some(tl)) = (self.find(from), self.find(to)) else { return Err(DocError::NoItem(to)) };
|
||||
let same_place = match (fl.spread, tl.spread) {
|
||||
(SpreadRef::Doc(_), SpreadRef::Doc(_)) => true,
|
||||
(a, b) => a == b,
|
||||
};
|
||||
if !same_place {
|
||||
return Err(DocError::Invalid("frames on a parent spread thread only to frames on the same parent".into()));
|
||||
}
|
||||
let story = |id: ItemId| self.item(id).and_then(|i| i.text_frame()).map(|t| t.story);
|
||||
if story(from).is_some() && story(from) == story(to) {
|
||||
return Err(DocError::Invalid("the frames are already in the same thread".into()));
|
||||
}
|
||||
// Generated text is rebuilt from its source data. Merging body text into it would
|
||||
// silently discard that text on the next update (endnotes update after every edit).
|
||||
let generated = |sid| {
|
||||
self.endnote_story == Some(sid)
|
||||
|| self.toc.as_ref().is_some_and(|t| t.story == sid)
|
||||
|| self.index.as_ref().is_some_and(|i| i.story == sid)
|
||||
};
|
||||
let (fs, ts) = (story(from), story(to));
|
||||
if fs.is_some_and(generated) && ts.and_then(|sid| self.story(sid)).is_some_and(|st| !st.text.is_empty()) {
|
||||
return Err(DocError::Invalid("cannot merge body text into a generated story".into()));
|
||||
}
|
||||
if ts.is_some_and(generated) && fs.and_then(|sid| self.story(sid)).is_some_and(|st| !st.text.is_empty() || st.frames != [from]) {
|
||||
return Err(DocError::Invalid("a generated story can only take a new empty first frame".into()));
|
||||
}
|
||||
let keep_to = fs.is_none_or(|sid| self.story(sid).is_some_and(|st| st.text.is_empty() && st.frames == [from]))
|
||||
&& ts.and_then(|sid| self.story(sid)).is_some_and(|st| st.frames.first() == Some(&to));
|
||||
self.check_thread_links(from, to, keep_to)?;
|
||||
if self.prev_frame(to).is_some() {
|
||||
return Err(DocError::Invalid(format!("text already flows into {to} from another frame: break that thread first")));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The story of a frame that can take part in a thread: `Some` for a text frame, `None` for
|
||||
/// an empty (unassigned) frame.
|
||||
fn frame_story(&self, id: ItemId) -> Result<Option<StoryId>> {
|
||||
match &self.item(id).ok_or(DocError::NoItem(id))?.content {
|
||||
Content::Text(t) => Ok(Some(t.story)),
|
||||
Content::Unassigned => Ok(None),
|
||||
_ => Err(DocError::Invalid("can only thread text frames or empty frames".into())),
|
||||
}
|
||||
}
|
||||
|
||||
/// Make an empty frame a text frame with a new empty story.
|
||||
fn give_empty_story(&mut self, id: ItemId) -> Result<StoryId> {
|
||||
let sid = StoryId(self.alloc());
|
||||
let mut st = Story::new(sid);
|
||||
st.frames.push(id);
|
||||
let it = self.item_mut(id).ok_or(DocError::NoItem(id))?;
|
||||
it.content = Content::Text(TextFrame { story: sid, options: TextFrameOptions::default() });
|
||||
self.stories.insert(sid, Arc::new(st));
|
||||
Ok(sid)
|
||||
}
|
||||
|
||||
/// Break the thread after `frame`: the following frames become a new empty story (the text
|
||||
/// stays with the first part and may become overset).
|
||||
pub fn unthread_after(&mut self, frame: ItemId) -> Result<()> {
|
||||
@@ -309,6 +451,30 @@ impl Document {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Take `frame` out of its thread: the frames before and after it join up and keep the text,
|
||||
/// `frame` stays on the page with a new empty story.
|
||||
pub fn remove_from_thread(&mut self, frame: ItemId) -> Result<()> {
|
||||
let sid = self.item(frame).and_then(|i| i.text_frame()).map(|t| t.story).ok_or(DocError::NoItem(frame))?;
|
||||
let (vertical, direction) = {
|
||||
let st = self.story_mut(sid).ok_or(DocError::NoStory(sid))?;
|
||||
if st.frames.len() < 2 {
|
||||
return Err(DocError::Invalid(format!("frame {frame} is not threaded to another frame")));
|
||||
}
|
||||
st.frames.retain(|f| *f != frame);
|
||||
st.rev += 1;
|
||||
(st.vertical, st.direction)
|
||||
};
|
||||
let nid = StoryId(self.alloc());
|
||||
let mut ns = Story::new(nid);
|
||||
ns.frames = vec![frame];
|
||||
ns.vertical = vertical;
|
||||
ns.direction = direction;
|
||||
self.stories.insert(nid, Arc::new(ns));
|
||||
let t = self.item_mut(frame).and_then(Item::text_frame_mut).ok_or(DocError::NoItem(frame))?;
|
||||
t.story = nid;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Next / previous frame in a thread.
|
||||
pub fn next_frame(&self, frame: ItemId) -> Option<ItemId> {
|
||||
let st = self.story(self.item(frame)?.text_frame()?.story)?;
|
||||
|
||||
@@ -21,3 +21,24 @@ id_type!(SpreadId, "sp");
|
||||
id_type!(PageId, "p");
|
||||
id_type!(LayerId, "l");
|
||||
id_type!(AssetId, "a");
|
||||
|
||||
/// Fresh story-local id. Keep monotonically increasing ids normally; a loaded MAX id must
|
||||
/// not make the next insertion overwrite it. In that case choose the first unused gap.
|
||||
pub(crate) fn next_local_id(ids: impl Iterator<Item = u64> + Clone) -> u64 {
|
||||
if let Some(next) = ids.clone().max().unwrap_or(0).checked_add(1) {
|
||||
return next;
|
||||
}
|
||||
let mut used: Vec<_> = ids.collect();
|
||||
used.sort_unstable();
|
||||
let mut next = 1u64;
|
||||
for id in used {
|
||||
if id > next {
|
||||
break;
|
||||
}
|
||||
if id == next {
|
||||
// An allocated Vec cannot contain every u64 id, so this always finds a gap.
|
||||
next = next.saturating_add(1);
|
||||
}
|
||||
}
|
||||
next
|
||||
}
|
||||
|
||||
+33
-2
@@ -137,7 +137,12 @@ pub fn build(spec: &IndexSpec, refs: &[Resolved], page_name: &dyn Fn(usize) -> S
|
||||
let mut heading: Option<char> = None;
|
||||
for (key, n) in &root {
|
||||
if spec.section_headings {
|
||||
let c = key.chars().next().map(|c| if c.is_alphabetic() { c.to_uppercase().next().unwrap_or(c) } else { '#' });
|
||||
// Georgian headings stay Mkhedruli (no capitals; Mtavruli is only for all-caps text).
|
||||
let c = key.chars().next().map(|c| match c {
|
||||
c if !c.is_alphabetic() => '#',
|
||||
c if crate::capitalizes(c) => c.to_uppercase().next().unwrap_or(c),
|
||||
c => c,
|
||||
});
|
||||
if c != heading {
|
||||
heading = c;
|
||||
if let Some(c) = c {
|
||||
@@ -184,10 +189,15 @@ fn entry_text(spec: &IndexSpec, n: &Node, page_name: &dyn Fn(usize) -> String) -
|
||||
t
|
||||
}
|
||||
|
||||
// `build` limits topic paths to four levels, bounding this traversal.
|
||||
fn run_in_subtopics(spec: &IndexSpec, n: &Node, page_name: &dyn Fn(usize) -> String) -> Vec<String> {
|
||||
n.children.values().flat_map(|c| [entry_text(spec, c, page_name)].into_iter().chain(run_in_subtopics(spec, c, page_name))).collect()
|
||||
}
|
||||
|
||||
fn emit(spec: &IndexSpec, n: &Node, level: usize, page_name: &dyn Fn(usize) -> String, out: &mut Vec<(String, String)>) {
|
||||
if spec.run_in && level == 1 {
|
||||
let mut t = entry_text(spec, n, page_name);
|
||||
let subs: Vec<String> = n.children.values().map(|c| entry_text(spec, c, page_name)).collect();
|
||||
let subs = run_in_subtopics(spec, n, page_name);
|
||||
if !subs.is_empty() {
|
||||
t.push_str(": ");
|
||||
t.push_str(&subs.join(&spec.between_entries));
|
||||
@@ -209,6 +219,19 @@ mod tests {
|
||||
Resolved { r: IndexRef { topics: topics.iter().map(|s| s.to_string()).collect(), sort: vec![], range }, pages }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn run_in_keeps_all_topic_levels_in_sort_order() {
|
||||
let refs = vec![
|
||||
r(&["Typography", "kerning", "pairs", "optical"], IndexRange::CurrentPage, Some((4, 4))),
|
||||
r(&["Typography", "kerning", "pairs"], IndexRange::CurrentPage, Some((2, 2))),
|
||||
r(&["Typography", "leading"], IndexRange::CurrentPage, Some((6, 6))),
|
||||
r(&["Typography", "kerning", "adjustment"], IndexRange::See("Spacing".into()), None),
|
||||
];
|
||||
let spec = IndexSpec { run_in: true, title: String::new(), section_headings: false, between_entries: " / ".into(), ..IndexSpec::default() };
|
||||
let out = build(&spec, &refs, &|p| (p + 1).to_string());
|
||||
assert_eq!(out, [("Index Level 1".into(), "Typography: kerning / adjustment See Spacing / pairs 3 / optical 5 / leading 7".into())]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn builds_nested_index() {
|
||||
let refs = vec![
|
||||
@@ -243,4 +266,12 @@ mod tests {
|
||||
let run_in = build(&IndexSpec { run_in: true, section_headings: false, title: String::new(), ..spec }, &refs[..2], &|p| (p + 1).to_string());
|
||||
assert_eq!(run_in, [("Index Level 1".to_string(), "Typography 2\u{2013}4: kerning 5".to_string())]);
|
||||
}
|
||||
#[test]
|
||||
fn georgian_section_heads_stay_mkhedruli() {
|
||||
let refs = vec![r(&["ასო"], IndexRange::CurrentPage, Some((0, 0))), r(&["ბადე"], IndexRange::CurrentPage, Some((1, 1)))];
|
||||
let out = build(&IndexSpec::default(), &refs, &|p| (p + 1).to_string());
|
||||
let heads: Vec<&str> = out.iter().filter(|(s, _)| s == "Index Section Head").map(|(_, t)| t.as_str()).collect();
|
||||
assert_eq!(heads, ["ა", "ბ"]);
|
||||
assert!(crate::capitalizes('a') && !crate::capitalizes('ა') && !crate::capitalizes('Ა'));
|
||||
}
|
||||
}
|
||||
|
||||
+118
-4
@@ -32,6 +32,28 @@ impl Default for Fill {
|
||||
}
|
||||
|
||||
impl Fill {
|
||||
/// A radial gradient's ellipse on an object whose bounds (in its own space) are `b`: centre and
|
||||
/// horizontal and vertical radii. As in InDesign, a radial gradient stretches with the object's
|
||||
/// box: by default it's centred and reaches the box's sides (an ellipse in a non-square box);
|
||||
/// with a Gradient Swatch tool vector it's centred at the vector's start, and the vector's
|
||||
/// length, measured with the box made square, sets its size.
|
||||
pub fn radial_ellipse(&self, b: designcraft_geom::Rect) -> (designcraft_geom::Point, f64, f64) {
|
||||
let k = if b.width() > 1e-9 && b.height() > 1e-9 { b.height() / b.width() } else { 1.0 };
|
||||
match self.gradient_vector {
|
||||
Some([x0, y0, x1, y1]) => {
|
||||
let r = designcraft_geom::Vec2::new(x1 - x0, (y1 - y0) / k).hypot();
|
||||
(designcraft_geom::Point::new(x0, y0), r, r * k)
|
||||
}
|
||||
// A box with no width or height (a straight line's) has no ellipse: a circle across
|
||||
// its length.
|
||||
None if b.width() <= 1e-9 || b.height() <= 1e-9 => {
|
||||
let r = b.width().max(b.height()).max(1e-3) / 2.0;
|
||||
(b.center(), r, r)
|
||||
}
|
||||
None => (b.center(), b.width() / 2.0, b.height() / 2.0),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn none() -> Self {
|
||||
Fill { swatch: designcraft_color::swatch::NONE.into(), tint: 1.0, gradient_angle: None, gradient_vector: None, overprint: false }
|
||||
}
|
||||
@@ -281,6 +303,10 @@ pub enum FirstBaseline {
|
||||
Leading,
|
||||
XHeight,
|
||||
Fixed,
|
||||
/// The top of the font's em box: its `BASE` em box; else, for a CJK font, its OS/2 typo
|
||||
/// ascender when the typo ascender and descender span one em; else half an em above half the
|
||||
/// cap height.
|
||||
EmboxHeight,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
@@ -321,7 +347,7 @@ pub struct TextFrameOptions {
|
||||
pub first_baseline_min: f64,
|
||||
pub ignore_wrap: bool,
|
||||
pub auto_size: AutoSize,
|
||||
/// Reference point (0..9) that stays fixed when auto-sizing.
|
||||
/// Reference point (0..9, row-major from the top left) that stays fixed when auto-sizing.
|
||||
pub auto_size_ref: u8,
|
||||
pub column_rule: bool,
|
||||
pub column_rule_weight: f64,
|
||||
@@ -382,7 +408,7 @@ impl Default for TextFrameOptions {
|
||||
first_baseline_min: 0.0,
|
||||
ignore_wrap: false,
|
||||
auto_size: AutoSize::Off,
|
||||
auto_size_ref: 1,
|
||||
auto_size_ref: 4,
|
||||
column_rule: false,
|
||||
column_rule_weight: 1.0,
|
||||
column_rule_color: designcraft_color::swatch::BLACK.into(),
|
||||
@@ -1105,6 +1131,29 @@ impl Item {
|
||||
self.path.bounds().unwrap_or(Rect::ZERO)
|
||||
}
|
||||
|
||||
/// The box a gradient feather spans, in item space: the path's bounds, or a group's visible
|
||||
/// objects' (a group has no path of its own). Only the active states contribute, including in
|
||||
/// nested groups. Walk iteratively so deeply nested documents don't exhaust the call stack.
|
||||
pub fn feather_bounds(&self) -> Rect {
|
||||
if !self.is_group() {
|
||||
return self.inner_bounds();
|
||||
}
|
||||
let mut stack: Vec<_> = self.shown_children().map(|c| (c.as_ref(), c.xf)).collect();
|
||||
let mut bounds: Option<Rect> = None;
|
||||
while let Some((it, xf)) = stack.pop() {
|
||||
if it.hidden {
|
||||
continue;
|
||||
}
|
||||
if it.is_group() {
|
||||
stack.extend(it.shown_children().map(|c| (c.as_ref(), xf * c.xf)));
|
||||
} else {
|
||||
let b = xf.transform_rect_bbox(it.inner_bounds());
|
||||
bounds = Some(bounds.map_or(b, |have| have.union(b)));
|
||||
}
|
||||
}
|
||||
bounds.unwrap_or(Rect::ZERO)
|
||||
}
|
||||
|
||||
/// Spread-space geometric bounds (axis-aligned box of the transformed path; groups: union).
|
||||
/// A group (its bounds are its children's). A frame holding pasted-into items is not.
|
||||
pub fn is_group(&self) -> bool {
|
||||
@@ -1156,13 +1205,29 @@ impl Item {
|
||||
b.inflate(w, w)
|
||||
}
|
||||
|
||||
/// The frame's text area (inner space) after inset.
|
||||
/// The text frame's text area (inner space): inside the part of a visible stroke that lies
|
||||
/// within the frame, then the inset, on each edge.
|
||||
pub fn text_area(&self) -> Rect {
|
||||
let r = self.inner_bounds();
|
||||
let inset = self.text_frame().map(|t| t.options.inset).unwrap_or([0.0; 4]);
|
||||
let s = self.stroke_inside();
|
||||
let inset = self.text_frame().map(|t| t.options.inset).unwrap_or([0.0; 4]).map(|v| v + s);
|
||||
Rect::new(r.x0 + inset[1], r.y0 + inset[0], (r.x1 - inset[3]).max(r.x0 + inset[1]), (r.y1 - inset[2]).max(r.y0 + inset[0]))
|
||||
}
|
||||
|
||||
/// How far a visible stroke reaches inside the path: half its weight centred, all of it inside,
|
||||
/// none outside.
|
||||
fn stroke_inside(&self) -> f64 {
|
||||
let w = self.stroke.weight;
|
||||
if self.stroke.is_none() || !w.is_finite() {
|
||||
return 0.0;
|
||||
}
|
||||
match self.stroke.align {
|
||||
StrokeAlign::Center => w / 2.0,
|
||||
StrokeAlign::Inside => w,
|
||||
StrokeAlign::Outside => 0.0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Spread-space centre.
|
||||
pub fn center(&self) -> Point {
|
||||
self.bounds().center()
|
||||
@@ -1207,6 +1272,32 @@ mod tests {
|
||||
assert_eq!(it.visible_bounds(), Rect::new(8.0, 18.0, 112.0, 72.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_area_starts_inside_the_stroke() {
|
||||
let mut it = Item::new(ItemId(1), LayerId(1), Shape::Rectangle, shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 50.0)));
|
||||
it.content = Content::Text(TextFrame { story: StoryId(2), options: TextFrameOptions { inset: [5.0, 6.0, 7.0, 8.0], ..Default::default() } });
|
||||
let unstroked = Rect::new(6.0, 5.0, 92.0, 43.0);
|
||||
let stroked = |align: StrokeAlign, swatch: &str| {
|
||||
let mut it = it.clone();
|
||||
it.stroke = Stroke { weight: 4.0, align, swatch: swatch.into(), ..Stroke::default() };
|
||||
it.text_area()
|
||||
};
|
||||
let black = designcraft_color::swatch::BLACK;
|
||||
// The part of the stroke inside the frame, on every edge, then the inset.
|
||||
assert_eq!(stroked(StrokeAlign::Center, black), Rect::new(8.0, 7.0, 90.0, 41.0));
|
||||
assert_eq!(stroked(StrokeAlign::Inside, black), Rect::new(10.0, 9.0, 88.0, 39.0));
|
||||
assert_eq!(stroked(StrokeAlign::Outside, black), unstroked);
|
||||
// A stroke without a colour doesn't count.
|
||||
assert_eq!(stroked(StrokeAlign::Inside, designcraft_color::swatch::NONE), unstroked);
|
||||
// Nor does a weight that isn't a number.
|
||||
it.stroke = Stroke { weight: f64::NAN, ..Stroke::default() };
|
||||
assert_eq!(it.text_area(), unstroked);
|
||||
// A stroke wider than the frame leaves no room for text.
|
||||
it.stroke = Stroke { weight: 200.0, align: StrokeAlign::Inside, ..Stroke::default() };
|
||||
let a = it.text_area();
|
||||
assert!(a.width() == 0.0 && a.height() == 0.0, "{a:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_bounds_union_children() {
|
||||
let a = Item::new(ItemId(1), LayerId(1), Shape::Rectangle, shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)));
|
||||
@@ -1219,6 +1310,29 @@ mod tests {
|
||||
assert_eq!(n, 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn feather_bounds_follow_visible_states_in_nested_groups() {
|
||||
let a = Item::new(ItemId(1), LayerId(1), Shape::Rectangle, shapes::rectangle(Rect::new(10.0, 20.0, 30.0, 40.0)));
|
||||
let mut b = a.clone();
|
||||
b.id = ItemId(2);
|
||||
b.xf = Affine::translate((500.0, 500.0));
|
||||
let mut state = Item::new(ItemId(3), LayerId(1), Shape::Group, PathData::default());
|
||||
state.content = Content::Group { items: vec![Arc::new(a), Arc::new(b)] };
|
||||
state.states = vec!["Visible".into(), "Inactive".into()];
|
||||
assert_eq!(state.feather_bounds(), Rect::new(10.0, 20.0, 30.0, 40.0));
|
||||
state.active_state = 1;
|
||||
assert_eq!(state.feather_bounds(), Rect::new(510.0, 520.0, 530.0, 540.0));
|
||||
state.active_state = 0;
|
||||
state.xf = Affine::translate((5.0, 10.0)) * Affine::scale(2.0);
|
||||
let mut hidden = state.clone();
|
||||
hidden.id = ItemId(4);
|
||||
hidden.hidden = true;
|
||||
hidden.xf = Affine::translate((-1000.0, -1000.0));
|
||||
let mut outer = Item::new(ItemId(5), LayerId(1), Shape::Group, PathData::default());
|
||||
outer.content = Content::Group { items: vec![Arc::new(state), Arc::new(hidden)] };
|
||||
assert_eq!(outer.feather_bounds(), Rect::new(25.0, 50.0, 65.0, 90.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn serde_roundtrip() {
|
||||
let mut it = Item::new(ItemId(1), LayerId(1), Shape::Oval, shapes::ellipse(Rect::new(0.0, 0.0, 10.0, 10.0)));
|
||||
|
||||
+28
-7
@@ -143,7 +143,7 @@ impl Default for DocumentGrid {
|
||||
}
|
||||
|
||||
/// A named numbered list.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", default)]
|
||||
pub struct NumberedList {
|
||||
pub name: String,
|
||||
@@ -151,12 +151,6 @@ pub struct NumberedList {
|
||||
pub continue_across_stories: bool,
|
||||
}
|
||||
|
||||
impl Default for NumberedList {
|
||||
fn default() -> Self {
|
||||
NumberedList { name: String::new(), continue_across_stories: true }
|
||||
}
|
||||
}
|
||||
|
||||
/// A conditional-text condition: its indicator colour (screen only) and whether text with it shows.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
@@ -584,6 +578,30 @@ pub struct TocEntry {
|
||||
/// 1-based nesting level.
|
||||
#[serde(default = "one")]
|
||||
pub level: u8,
|
||||
/// Paragraph style of this style's entries; `None` is the generated "TOC Level n" style.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub entry_style: Option<String>,
|
||||
#[serde(default)]
|
||||
pub page_number: TocPageNumber,
|
||||
/// Text between the entry and its page number; `None` is a tab.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub separator: Option<String>,
|
||||
}
|
||||
|
||||
impl TocEntry {
|
||||
pub fn new(style: impl Into<String>, level: u8) -> Self {
|
||||
Self { style: style.into(), level, entry_style: None, page_number: TocPageNumber::After, separator: None }
|
||||
}
|
||||
}
|
||||
|
||||
/// Where an entry's page number goes.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum TocPageNumber {
|
||||
#[default]
|
||||
After,
|
||||
Before,
|
||||
None,
|
||||
}
|
||||
|
||||
fn one() -> u8 {
|
||||
@@ -598,6 +616,9 @@ pub struct Toc {
|
||||
pub entries: Vec<TocEntry>,
|
||||
#[serde(default)]
|
||||
pub page_numbers: bool,
|
||||
/// Paragraph style of the title; `None` is the generated "TOC Title" style.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub title_style: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
|
||||
@@ -178,7 +178,7 @@ impl Story {
|
||||
}
|
||||
|
||||
pub(crate) fn next_note_id(&self) -> u64 {
|
||||
self.notes.iter().map(|n| n.id).max().unwrap_or(0) + 1
|
||||
crate::ids::next_local_id(self.notes.iter().map(|n| n.id))
|
||||
}
|
||||
|
||||
/// Insert empty footnotes for `n` new reference characters before which `k` references sit.
|
||||
|
||||
@@ -31,7 +31,7 @@ pub const FIGURES: &[(&str, &str, &[&str], &str)] = &[
|
||||
|
||||
/// Features shaping turns on by itself: "off" is an explicit `-tag`.
|
||||
fn default_on(tag: &str) -> bool {
|
||||
matches!(tag, "calt" | "locl" | "mark")
|
||||
matches!(tag, "calt" | "liga" | "locl" | "mark")
|
||||
}
|
||||
|
||||
pub fn is_on(list: &[String], tag: &str) -> bool {
|
||||
|
||||
+23
-1
@@ -114,6 +114,9 @@ pub struct Page {
|
||||
/// Liquid page rule: how objects follow when the page changes size.
|
||||
#[serde(default, skip_serializing_if = "LiquidRule::is_off")]
|
||||
pub liquid: LiquidRule,
|
||||
/// Page tool › Show Parent Page Overlay: the parent page's size drawn over this page.
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
pub show_parent_overlay: bool,
|
||||
/// Window › Interactive › Page Transitions (the spread's first page holds the spread's).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub transition: Option<PageTransition>,
|
||||
@@ -208,6 +211,8 @@ pub enum LiquidRule {
|
||||
GuideBased,
|
||||
/// Each object's pins and resize settings decide (`Item::liquid`).
|
||||
ObjectBased,
|
||||
/// The rule of the page's parent page (InDesign's "Controlled by Parent"; Off without one).
|
||||
ControlledByParent,
|
||||
}
|
||||
|
||||
impl LiquidRule {
|
||||
@@ -246,7 +251,8 @@ impl Page {
|
||||
|
||||
/// Split `area` into `n` equal columns separated by `gutter`.
|
||||
pub fn column_rects(area: Rect, n: u32, gutter: f64) -> Vec<Rect> {
|
||||
let n = n.max(1) as usize;
|
||||
// The public allocator also receives native/imported options, outside command validation.
|
||||
let n = n.clamp(1, 216) as usize;
|
||||
let w = ((area.width() - gutter * (n as f64 - 1.0)) / n as f64).max(0.0);
|
||||
(0..n).map(|i| Rect::new(area.x0 + i as f64 * (w + gutter), area.y0, area.x0 + i as f64 * (w + gutter) + w, area.y1)).collect()
|
||||
}
|
||||
@@ -367,6 +373,7 @@ mod tests {
|
||||
liquid: Default::default(),
|
||||
transition: None,
|
||||
view_rotation: 0,
|
||||
show_parent_overlay: false,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -403,3 +410,18 @@ mod tests {
|
||||
assert_eq!(s.page_at_x(5000.0), Some(1));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod column_allocation_safety_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn column_allocation_caps_page_count_and_preserves_geometry() {
|
||||
let area = Rect::new(0., 0., 300., 100.);
|
||||
// Fail safely at a small boundary before exercising hostile counts.
|
||||
assert_eq!(column_rects(area, 217, 0.).len(), 216);
|
||||
assert_eq!(column_rects(area, u32::MAX, 0.).len(), 216);
|
||||
assert_eq!(column_rects(area, 0, 12.), vec![area]);
|
||||
assert_eq!(column_rects(area, 2, 12.), vec![Rect::new(0., 0., 144., 100.), Rect::new(156., 0., 300., 100.)]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -80,6 +80,9 @@ pub struct Selection {
|
||||
/// Key object for Align.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub key: Option<ItemId>,
|
||||
/// The page selected with the Page tool (absolute index).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub page: Option<usize>,
|
||||
}
|
||||
|
||||
impl Selection {
|
||||
|
||||
+152
-11
@@ -57,18 +57,25 @@ impl Story {
|
||||
if src.text.is_empty() {
|
||||
return pos;
|
||||
}
|
||||
// Text first (creates empty marker entries), then formats and marker payloads.
|
||||
// The table anchored in the paragraph at `pos` keeps its anchor wherever the paste moves it.
|
||||
let p0 = self.para_at(pos);
|
||||
let own = self.paras.get(p0).and_then(|p| p.table).and_then(|id| {
|
||||
let r = self.para_ranges().get(p0)?.clone();
|
||||
Some((r.start + self.text.get(r)?.find(TABLE_ANCHOR)?, id))
|
||||
});
|
||||
// Text first (creates empty marker entries), then formats and marker payloads; tables are
|
||||
// fixed up once at the end.
|
||||
let mut at = pos;
|
||||
for (r, f) in src.runs() {
|
||||
if r.is_empty() {
|
||||
continue;
|
||||
}
|
||||
self.insert_with(at, &src.text[r.clone()], f.clone());
|
||||
self.insert_with_raw(at, &src.text[r.clone()], f.clone());
|
||||
at += r.len();
|
||||
}
|
||||
let end = at;
|
||||
let mut claims: Vec<(usize, u64)> = own.map(|(a, id)| (if a >= pos { a + (end - pos) } else { a }, id)).into_iter().collect();
|
||||
// Paragraph formats of the pasted paragraphs after the first.
|
||||
let p0 = self.para_at(pos);
|
||||
for (k, pf) in src.paras.iter().enumerate().skip(1) {
|
||||
if let Some(p) = self.paras.get_mut(p0 + k) {
|
||||
*p = crate::story::ParaFormat { table: None, ..pf.clone() };
|
||||
@@ -106,25 +113,85 @@ impl Story {
|
||||
*slot = Arc::new(crate::xref::TextAnchor { id, name: a.name.clone() });
|
||||
}
|
||||
}
|
||||
// Tables: re-attach by paragraph (fresh ids so a pasted copy never shares an id).
|
||||
// Tables: re-attach at their anchors (fresh ids so a pasted copy never shares an id).
|
||||
if !src.tables.is_empty() {
|
||||
let mut next = self.tables.keys().max().copied().unwrap_or(0) + 1;
|
||||
for (k, pf) in src.paras.iter().enumerate() {
|
||||
let ranges = src.para_ranges();
|
||||
for (pf, r) in src.paras.iter().zip(ranges) {
|
||||
let Some(tid) = pf.table else { continue };
|
||||
let Some(t) = src.tables.get(&tid) else { continue };
|
||||
let pi = p0 + k;
|
||||
let Some(k) = src.text.get(r.clone()).and_then(|t| t.find(TABLE_ANCHOR)) else { continue };
|
||||
let mut t = (**t).clone();
|
||||
t.id = next;
|
||||
next += 1;
|
||||
claims.push((pos + r.start + k, t.id));
|
||||
self.tables.insert(t.id, Arc::new(t));
|
||||
if let Some(p) = self.paras.get_mut(pi) {
|
||||
p.table = Some(next - 1);
|
||||
}
|
||||
}
|
||||
let splits = self.fix_tables_with(&claims);
|
||||
self.rev += 1;
|
||||
// Past any return the fix-up put inside the pasted text.
|
||||
end + splits.iter().filter(|&&s| s < end).count()
|
||||
}
|
||||
|
||||
/// Append the whole of `other` as new paragraphs after this story's text (threading two
|
||||
/// stories merges them this way). Its formatting, notes, endnotes, editorial notes, markers,
|
||||
/// anchored objects and tables come along; footnotes, endnotes, editorial notes and tables get
|
||||
/// ids that are free in this story. An empty story simply takes `other`'s content. Frames stay.
|
||||
pub fn append_story(&mut self, mut other: Story) {
|
||||
if other.text.is_empty() {
|
||||
return;
|
||||
}
|
||||
if self.text.is_empty() {
|
||||
let (id, frames, rev, link) = (self.id, std::mem::take(&mut self.frames), self.rev, self.link.take());
|
||||
*self = Story { id, frames, rev: rev.saturating_add(1), link, ..other };
|
||||
return;
|
||||
}
|
||||
if !other.tables.is_empty() {
|
||||
let mut ids = std::collections::HashMap::new();
|
||||
let mut next = crate::ids::next_local_id(self.tables.keys().copied());
|
||||
for (old, t) in std::mem::take(&mut other.tables) {
|
||||
let new = next;
|
||||
let mut t = Arc::unwrap_or_clone(t);
|
||||
t.id = new;
|
||||
ids.insert(old, new);
|
||||
self.tables.insert(new, Arc::new(t));
|
||||
// Continue through free ids without rescanning the table map for its maximum.
|
||||
// On exhaustion wrap to gaps; an allocated map cannot occupy every u64 id.
|
||||
next = next.checked_add(1).unwrap_or(1);
|
||||
while self.tables.contains_key(&next) {
|
||||
next = next.checked_add(1).unwrap_or(1);
|
||||
}
|
||||
}
|
||||
self.fix_tables();
|
||||
for p in &mut other.paras {
|
||||
p.table = p.table.and_then(|id| ids.get(&id).copied());
|
||||
}
|
||||
}
|
||||
self.rev += 1;
|
||||
end
|
||||
self.text.push('\n');
|
||||
self.text.push_str(&other.text);
|
||||
// The paragraph end takes the last run's format.
|
||||
if let Some(last) = self.chars.last_mut() {
|
||||
last.len += 1;
|
||||
}
|
||||
self.chars.extend(other.chars.into_iter().filter(|r| r.len > 0));
|
||||
self.paras.extend(other.paras);
|
||||
for n in other.notes {
|
||||
let id = self.next_note_id();
|
||||
self.notes.push(Arc::new(crate::notes::Footnote { id, text: n.text.clone() }));
|
||||
}
|
||||
for n in other.endnotes {
|
||||
let id = crate::ids::next_local_id(self.endnotes.iter().map(|x| x.id));
|
||||
self.endnotes.push(Arc::new(crate::notes::Footnote { id, text: n.text.clone() }));
|
||||
}
|
||||
for n in other.editorial {
|
||||
let id = crate::ids::next_local_id(self.editorial.iter().map(|x| x.id));
|
||||
self.editorial.push(Arc::new(crate::endnotes::EditorialNote { id, ..(*n).clone() }));
|
||||
}
|
||||
self.anchors.extend(other.anchors);
|
||||
self.xrefs.extend(other.xrefs);
|
||||
self.index_refs.extend(other.index_refs);
|
||||
self.objects.extend(other.objects);
|
||||
self.rev = self.rev.saturating_add(1);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -133,6 +200,32 @@ mod tests {
|
||||
use super::*;
|
||||
use crate::story::ParaFormat;
|
||||
|
||||
#[test]
|
||||
fn pasting_a_table_next_to_another_gives_each_its_own_paragraph() {
|
||||
let mut s = Story::with_text(StoryId(1), "x", ParaFormat::default());
|
||||
let a = s.insert_table(1, crate::Table::new(5, 1, 1, 0, 0, 10.0));
|
||||
let n = TABLE_ANCHOR.len_utf8();
|
||||
let copy = s.extract(a..a + n);
|
||||
// After the anchor: the copy follows the original.
|
||||
let mut after = s.clone();
|
||||
let end = after.insert_story(a + n, ©);
|
||||
after.check().unwrap();
|
||||
assert_eq!(after.text, format!("x\n{TABLE_ANCHOR}\n{TABLE_ANCHOR}\n"));
|
||||
assert_eq!((after.table_anchor(5), after.table_anchor(6)), (Some(a), Some(a + n + 1)));
|
||||
assert_eq!(end, a + 2 * n + 1);
|
||||
// Before the anchor: the copy comes first and the original keeps its table.
|
||||
let mut before = s.clone();
|
||||
let end = before.insert_story(a, ©);
|
||||
before.check().unwrap();
|
||||
assert_eq!((before.table_anchor(6), before.table_anchor(5)), (Some(a), Some(a + n + 1)));
|
||||
assert_eq!(end, a + n);
|
||||
// Paragraphs pasted before the anchor keep the table too.
|
||||
let mut text = s.clone();
|
||||
text.insert_story(a, &Story::with_text(StoryId(2), "Hello\nWorld", ParaFormat::default()));
|
||||
text.check().unwrap();
|
||||
assert_eq!(text.table_anchor(5), Some(a + "Hello\nWorld".len()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn copy_paste_keeps_formatting_and_notes() {
|
||||
let mut a = Story::with_text(StoryId(1), "Alpha beta\nGamma delta", ParaFormat::default());
|
||||
@@ -159,4 +252,52 @@ mod tests {
|
||||
assert_eq!(part.notes.len(), 1);
|
||||
assert!(a.extract(2..8).notes.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn append_tables_preserves_sparse_and_wrapping_ids() {
|
||||
for existing in [vec![1, 3, u64::MAX], vec![1, 3, u64::MAX - 1], vec![1, 3, 8]] {
|
||||
let story = |id, ids: &[u64]| {
|
||||
let mut s = Story::with_text(StoryId(id), &vec![crate::TABLE_ANCHOR.to_string(); ids.len()].join("\n"), ParaFormat::default());
|
||||
for (p, &tid) in s.paras.iter_mut().zip(ids) {
|
||||
p.table = Some(tid);
|
||||
let mut t = crate::table::Table::new(tid, 1, 1, 0, 0, 100.0);
|
||||
t.cells[0].text = Story::with_text(StoryId(0), &format!("{id}:{tid}"), ParaFormat::default());
|
||||
s.tables.insert(tid, Arc::new(t));
|
||||
}
|
||||
s
|
||||
};
|
||||
let mut a = story(1, &existing);
|
||||
let b = story(2, &[1, 2, 3]);
|
||||
a.check().unwrap();
|
||||
b.check().unwrap();
|
||||
a.append_story(b);
|
||||
a.check().unwrap();
|
||||
assert_eq!(a.tables.len(), 6);
|
||||
for (p, tid) in a.paras.iter().take(3).zip(&existing) {
|
||||
assert_eq!(p.table, Some(*tid));
|
||||
assert_eq!(a.tables[tid].cells[0].text.text, format!("1:{tid}"));
|
||||
}
|
||||
for (p, tid) in a.paras.iter().skip(3).zip(1..=3) {
|
||||
assert_eq!(a.tables[&p.table.unwrap()].cells[0].text.text, format!("2:{tid}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn append_story_with_maximal_ids_does_not_overflow() {
|
||||
let mut a = Story::with_text(StoryId(1), "Alpha", ParaFormat::default());
|
||||
a.tables.insert(u64::MAX, Arc::new(crate::table::Table::new(u64::MAX, 1, 1, 0, 0, 100.0)));
|
||||
let note = |id| Arc::new(crate::notes::Footnote { id, text: Story::with_text(StoryId(0), "n", ParaFormat::default()) });
|
||||
a.endnotes.push(note(u64::MAX));
|
||||
a.notes.push(note(u64::MAX));
|
||||
a.rev = u64::MAX;
|
||||
let mut b = Story::with_text(StoryId(2), "Beta", ParaFormat::default());
|
||||
b.tables.insert(1, Arc::new(crate::table::Table::new(1, 1, 1, 0, 0, 100.0)));
|
||||
b.endnotes.push(note(1));
|
||||
b.notes.push(note(1));
|
||||
a.append_story(b);
|
||||
assert_eq!(a.text, "Alpha\nBeta");
|
||||
assert_eq!(a.endnotes.len(), 2);
|
||||
assert_eq!(a.notes.len(), 2);
|
||||
}
|
||||
}
|
||||
|
||||
+14
-8
@@ -255,7 +255,8 @@ impl Story {
|
||||
self.insert_with_raw(pos, text, fmt);
|
||||
}
|
||||
|
||||
fn insert_with_raw(&mut self, pos: usize, text: &str, fmt: CharFormat) {
|
||||
/// [`Story::insert_with`] without the table fix-up.
|
||||
pub(crate) fn insert_with_raw(&mut self, pos: usize, text: &str, fmt: CharFormat) {
|
||||
if text.is_empty() {
|
||||
return;
|
||||
}
|
||||
@@ -332,20 +333,25 @@ impl Story {
|
||||
self.marks_deleted(a, b);
|
||||
let pi = self.para_at(a);
|
||||
let removed = self.text[a..b].bytes().filter(|c| *c == b'\n').count();
|
||||
// Merged paragraphs keep a table whose anchor survives the deletion.
|
||||
// Merged paragraphs keep the tables whose anchors survive the deletion (the fix-up gives
|
||||
// each its own paragraph again).
|
||||
let mut claims = Vec::new();
|
||||
if removed > 0 && !self.tables.is_empty() {
|
||||
let ranges = self.para_ranges();
|
||||
let first = self.paras[pi].table.filter(|_| self.text[ranges[pi].start..a].contains(TABLE_ANCHOR));
|
||||
let last = self.paras[pi + removed]
|
||||
.table
|
||||
.filter(|_| self.text[b.min(ranges[pi + removed].end)..ranges[pi + removed].end].contains(TABLE_ANCHOR));
|
||||
self.paras[pi].table = first.or(last);
|
||||
let anchor = |pi: usize, r: std::ops::Range<usize>| {
|
||||
self.paras[pi].table.and_then(|id| self.text[r.clone()].find(TABLE_ANCHOR).map(|k| (r.start + k, id)))
|
||||
};
|
||||
let first = anchor(pi, ranges[pi].start..a);
|
||||
let end = ranges[pi + removed].end;
|
||||
let last = anchor(pi + removed, b.min(end)..end).map(|(at, id)| (at.saturating_sub(b - a), id));
|
||||
self.paras[pi].table = first.or(last).map(|(_, id)| id);
|
||||
claims.extend(first.into_iter().chain(last));
|
||||
}
|
||||
self.paras.drain(pi + 1..pi + 1 + removed);
|
||||
self.text.replace_range(a..b, "");
|
||||
self.remove_run_bytes(a, b - a);
|
||||
self.normalize();
|
||||
self.fix_tables();
|
||||
self.fix_tables_with(&claims);
|
||||
self.rev += 1;
|
||||
}
|
||||
|
||||
|
||||
@@ -692,8 +692,8 @@ impl Styles {
|
||||
self.object.iter().find(|s| s.name == name)
|
||||
}
|
||||
|
||||
/// The paragraph style chain from root to `name` (cycle-safe).
|
||||
fn para_chain(&self, name: &str) -> Vec<&ParagraphStyle> {
|
||||
/// The paragraph style chain from root to `name` (cycle-safe): resolution starts at its first.
|
||||
pub fn para_chain(&self, name: &str) -> Vec<&ParagraphStyle> {
|
||||
let mut chain = Vec::new();
|
||||
let mut cur = self.para(name);
|
||||
while let Some(s) = cur {
|
||||
|
||||
+119
-7
@@ -444,6 +444,25 @@ impl Table {
|
||||
v
|
||||
}
|
||||
|
||||
/// Owning cells touched by the range, once each in row-major order. Bounds are clipped
|
||||
/// to the grid; resolving covered positions does not expand the selection rectangle.
|
||||
pub fn selected_owners(&self, range: CellRange) -> Vec<(usize, usize)> {
|
||||
let (nr, nc) = (self.nrows(), self.ncols());
|
||||
if range.r0 >= nr || range.c0 >= nc || range.r0 > range.r1 || range.c0 > range.c1 {
|
||||
return Vec::new();
|
||||
}
|
||||
let owners = self.owners();
|
||||
let mut selected = std::collections::BTreeSet::new();
|
||||
for r in range.r0..=range.r1.min(nr - 1) {
|
||||
for c in range.c0..=range.c1.min(nc - 1) {
|
||||
if let Some(&owner) = owners.get(r * nc + c) {
|
||||
selected.insert(owner);
|
||||
}
|
||||
}
|
||||
}
|
||||
selected.into_iter().collect()
|
||||
}
|
||||
|
||||
/// The owning (top-left) cell address of grid position (r, c).
|
||||
pub fn owner(&self, r: usize, c: usize) -> (usize, usize) {
|
||||
self.owners().get(r * self.ncols() + c).copied().unwrap_or((r, c))
|
||||
@@ -1086,21 +1105,61 @@ impl Story {
|
||||
|
||||
/// Keep paragraphs and tables consistent after an edit: a paragraph keeps its table only if it
|
||||
/// still contains an anchor character, every table is referenced once, and tables nobody
|
||||
/// references are dropped.
|
||||
/// references are dropped. An anchor that shares a table's paragraph with another anchor gets
|
||||
/// a paragraph of its own again, so a table paragraph always holds exactly one anchor.
|
||||
pub(crate) fn fix_tables(&mut self) {
|
||||
self.fix_tables_with(&[]);
|
||||
}
|
||||
|
||||
/// [`Story::fix_tables`] for an edit that knows which table an anchor belongs to: `claims` are
|
||||
/// `(anchor byte offset, table id)` pairs that win over the paragraphs' table ids (a paragraph
|
||||
/// names one table, so merging two anchor paragraphs would otherwise lose one). Every other
|
||||
/// table takes the first unclaimed anchor of its paragraph. Returns the byte offsets, before
|
||||
/// the fix-up, where it inserted paragraph returns.
|
||||
pub(crate) fn fix_tables_with(&mut self, claims: &[(usize, u64)]) -> Vec<usize> {
|
||||
if self.tables.is_empty() && self.paras.iter().all(|p| p.table.is_none()) {
|
||||
return;
|
||||
return Vec::new();
|
||||
}
|
||||
let ranges = self.para_ranges();
|
||||
let mut owner = std::collections::BTreeMap::new();
|
||||
let mut used = std::collections::HashSet::new();
|
||||
for (p, r) in self.paras.iter_mut().zip(ranges) {
|
||||
if let Some(id) = p.table
|
||||
&& (!self.text[r].contains(TABLE_ANCHOR) || !self.tables.contains_key(&id) || !used.insert(id))
|
||||
for &(at, id) in claims {
|
||||
if self.text.get(at..).is_some_and(|t| t.starts_with(TABLE_ANCHOR))
|
||||
&& self.tables.contains_key(&id)
|
||||
&& !owner.contains_key(&at)
|
||||
&& used.insert(id)
|
||||
{
|
||||
p.table = None;
|
||||
owner.insert(at, id);
|
||||
}
|
||||
}
|
||||
let ranges = self.para_ranges();
|
||||
for (p, r) in self.paras.iter().zip(&ranges) {
|
||||
let Some(id) = p.table.filter(|id| self.tables.contains_key(id) && !used.contains(id)) else { continue };
|
||||
let free = self.text[r.clone()].match_indices(TABLE_ANCHOR).map(|(k, _)| r.start + k).find(|at| !owner.contains_key(at));
|
||||
if let Some(at) = free {
|
||||
used.insert(id);
|
||||
owner.insert(at, id);
|
||||
}
|
||||
}
|
||||
// A paragraph holding a table's anchor and other anchors is split before each later anchor.
|
||||
let mut splits = Vec::new();
|
||||
for r in &ranges {
|
||||
let anchors: Vec<usize> = self.text[r.clone()].match_indices(TABLE_ANCHOR).map(|(k, _)| r.start + k).collect();
|
||||
if anchors.len() > 1 && anchors.iter().any(|at| owner.contains_key(at)) {
|
||||
splits.extend(anchors.into_iter().skip(1));
|
||||
}
|
||||
}
|
||||
for &at in splits.iter().rev() {
|
||||
self.insert_raw(at, "\n");
|
||||
}
|
||||
// Each owned anchor, moved past the returns inserted before it, names its paragraph's table.
|
||||
let owner: std::collections::BTreeMap<usize, u64> =
|
||||
owner.into_iter().map(|(at, id)| (at + splits.partition_point(|&s| s <= at), id)).collect();
|
||||
let ranges = self.para_ranges();
|
||||
for (p, r) in self.paras.iter_mut().zip(ranges) {
|
||||
p.table = owner.range(r).next().map(|(_, &id)| id);
|
||||
}
|
||||
self.tables.retain(|id, _| used.contains(id));
|
||||
splits
|
||||
}
|
||||
|
||||
/// Check table invariants (part of [`Story::check`]).
|
||||
@@ -1136,6 +1195,35 @@ mod tests {
|
||||
Story::with_text(StoryId(1), t, ParaFormat::default())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selected_owners_include_covered_cells_without_expanding_range() {
|
||||
for column in [true, false] {
|
||||
let mut t = Table::new(1, 2, 2, 0, 0, 120.0);
|
||||
let range = if column { CellRange::new(0, 1, 1, 1) } else { CellRange::new(1, 0, 1, 1) };
|
||||
assert_eq!(t.selected_owners(range), if column { vec![(0, 1), (1, 1)] } else { vec![(1, 0), (1, 1)] });
|
||||
t.merge(if column { CellRange::new(0, 0, 0, 1) } else { CellRange::new(0, 0, 1, 0) }).unwrap();
|
||||
assert_eq!(t.selected_owners(range), vec![(0, 0), (1, 1)]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selected_owners_are_bounded_sorted_and_unique() {
|
||||
let mut t = Table::new(1, 3, 3, 0, 0, 180.0);
|
||||
t.merge(CellRange::new(0, 0, 1, 1)).unwrap();
|
||||
assert_eq!(t.selected_owners(CellRange::new(1, 1, usize::MAX, usize::MAX)), vec![(0, 0), (1, 2), (2, 1), (2, 2)]);
|
||||
assert_eq!(t.selected_owners(CellRange::new(0, 0, 1, 1)), vec![(0, 0)], "covered positions do not duplicate an owner");
|
||||
assert!(t.selected_owners(CellRange::new(3, 0, usize::MAX, usize::MAX)).is_empty());
|
||||
assert!(t.selected_owners(CellRange::new(0, 3, usize::MAX, usize::MAX)).is_empty());
|
||||
assert!(t.selected_owners(CellRange { r0: 1, c0: 0, r1: 0, c1: 1 }).is_empty());
|
||||
t.rows.clear();
|
||||
t.cells.clear();
|
||||
assert!(t.selected_owners(CellRange::cell(0, 0)).is_empty());
|
||||
|
||||
let mut right = Table::new(2, 2, 2, 0, 0, 120.0);
|
||||
right.merge(CellRange::new(0, 1, 1, 1)).unwrap();
|
||||
assert_eq!(right.selected_owners(CellRange::new(1, 0, 1, 1)), vec![(0, 1), (1, 0)], "owner order, not encounter order");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn insert_table_gets_own_paragraph() {
|
||||
let mut s = story("before after");
|
||||
@@ -1171,6 +1259,30 @@ mod tests {
|
||||
assert!(s.tables.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deleting_the_return_between_two_tables_keeps_both() {
|
||||
// Backspace at the start of the second table's paragraph.
|
||||
let mut s = story("x");
|
||||
let a1 = s.insert_table(1, Table::new(1, 1, 1, 0, 0, 10.0));
|
||||
let a2 = s.insert_table(s.len(), Table::new(2, 1, 1, 0, 0, 10.0));
|
||||
let before = s.text.clone();
|
||||
s.delete(a2 - 1..a2);
|
||||
s.check().unwrap();
|
||||
assert_eq!(s.text, before);
|
||||
assert_eq!((s.table_anchor(1), s.table_anchor(2)), (Some(a1), Some(a2)));
|
||||
// Deleting the table between two others keeps the outer ones on their own anchors.
|
||||
let mut s = story("x");
|
||||
for id in 1..=3 {
|
||||
s.insert_table(s.len(), Table::new(id, 1, 1, 0, 0, 10.0));
|
||||
}
|
||||
let (a1, a3) = (s.table_anchor(1).unwrap(), s.table_anchor(3).unwrap());
|
||||
s.delete(a1 + TABLE_ANCHOR.len_utf8()..a3);
|
||||
s.check().unwrap();
|
||||
assert_eq!(s.text, format!("x\n{TABLE_ANCHOR}\n{TABLE_ANCHOR}\n"));
|
||||
assert_eq!(s.tables.keys().copied().collect::<Vec<_>>(), [1, 3]);
|
||||
assert_eq!(s.table_anchor(3), Some(a1 + TABLE_ANCHOR.len_utf8() + 1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn edits_around_the_anchor_keep_the_table() {
|
||||
let mut s = story("ab\ncd");
|
||||
|
||||
@@ -42,6 +42,126 @@ fn thread_to_empty_frame_converts_it() {
|
||||
assert!(d.thread(a, a).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn threading_merges_tables_notes_and_endnotes() {
|
||||
let mut d = doc();
|
||||
let lid = d.default_layer();
|
||||
let (a, sa) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(10.0, 10.0, 100.0, 100.0), lid, "first", ParaFormat::default()).unwrap();
|
||||
let (b, sb) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(110.0, 10.0, 200.0, 100.0), lid, "second", ParaFormat::default()).unwrap();
|
||||
for (sid, note) in [(sa, "Note A"), (sb, "Note B")] {
|
||||
let st = d.story_mut(sid).unwrap();
|
||||
st.insert_note(3, note, ParaFormat::default());
|
||||
// Both stories hold a table with id 1.
|
||||
let n = st.len();
|
||||
st.insert_table(n, crate::table::Table::new(1, 2, 2, 0, 0, 80.0));
|
||||
}
|
||||
let st = d.story_mut(sb).unwrap();
|
||||
st.insert_endnote(2, "End B", ParaFormat::default());
|
||||
st.insert(1, &crate::NOTE_MARK.to_string());
|
||||
d.thread(a, b).unwrap();
|
||||
d.check().unwrap();
|
||||
let st = d.story(sa).unwrap();
|
||||
assert!(d.story(sb).is_none());
|
||||
assert_eq!(st.tables.len(), 2);
|
||||
assert_eq!(st.notes.len(), 2);
|
||||
assert_eq!(st.notes[1].text.text, "Note B");
|
||||
assert_eq!(st.endnotes.len(), 1);
|
||||
assert_eq!(st.endnotes[0].text.text, "End B");
|
||||
assert_eq!(st.editorial.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_frame_threaded_before_a_story_joins_it_at_the_front() {
|
||||
let mut d = doc();
|
||||
let lid = d.default_layer();
|
||||
let (a, sa) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(10.0, 10.0, 100.0, 100.0), lid, "", ParaFormat::default()).unwrap();
|
||||
let (b, sb) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(110.0, 10.0, 200.0, 100.0), lid, "Hello", ParaFormat::default()).unwrap();
|
||||
d.thread_keeping_story(a, b).unwrap();
|
||||
d.check().unwrap();
|
||||
assert!(d.story(sa).is_none());
|
||||
let st = d.story(sb).unwrap();
|
||||
assert_eq!(st.frames, vec![a, b]);
|
||||
assert_eq!(st.text, "Hello");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_story_takes_the_threaded_text_without_a_blank_paragraph() {
|
||||
let mut d = doc();
|
||||
let lid = d.default_layer();
|
||||
let (a, _) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(10.0, 10.0, 100.0, 100.0), lid, "", ParaFormat::default()).unwrap();
|
||||
let (a2, _) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(10.0, 110.0, 100.0, 200.0), lid, "", ParaFormat::default()).unwrap();
|
||||
d.thread(a, a2).unwrap();
|
||||
let (b, _) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(110.0, 10.0, 200.0, 100.0), lid, "Hello", ParaFormat::default()).unwrap();
|
||||
d.thread(a2, b).unwrap();
|
||||
d.check().unwrap();
|
||||
let st = d.story(d.item(a).unwrap().text_frame().unwrap().story).unwrap();
|
||||
assert_eq!(st.frames, vec![a, a2, b]);
|
||||
assert_eq!(st.text, "Hello");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn threading_from_an_empty_frame_makes_it_a_text_frame() {
|
||||
let mut d = doc();
|
||||
let lid = d.default_layer();
|
||||
let id = ItemId(d.alloc());
|
||||
let it = Item::new(id, lid, Shape::Rectangle, designcraft_geom::shapes::rectangle(Rect::new(0.0, 200.0, 50.0, 300.0)));
|
||||
d.insert_item(SpreadRef::Doc(0), it, None).unwrap();
|
||||
let (b, _) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(110.0, 10.0, 200.0, 100.0), lid, "Hello", ParaFormat::default()).unwrap();
|
||||
d.thread(id, b).unwrap();
|
||||
d.check().unwrap();
|
||||
let st = d.story(d.item(id).unwrap().text_frame().unwrap().story).unwrap();
|
||||
assert_eq!(st.frames, vec![id, b]);
|
||||
assert_eq!(st.text, "Hello");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn removing_a_frame_from_its_thread_keeps_the_text_in_the_others() {
|
||||
let mut d = doc();
|
||||
let lid = d.default_layer();
|
||||
let (a, sa) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(10.0, 10.0, 100.0, 100.0), lid, "words", ParaFormat::default()).unwrap();
|
||||
let (b, _) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(110.0, 10.0, 200.0, 100.0), lid, "", ParaFormat::default()).unwrap();
|
||||
let (c, _) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(210.0, 10.0, 300.0, 100.0), lid, "", ParaFormat::default()).unwrap();
|
||||
d.thread(a, b).unwrap();
|
||||
d.thread(b, c).unwrap();
|
||||
d.remove_from_thread(b).unwrap();
|
||||
d.check().unwrap();
|
||||
assert_eq!(d.story(sa).unwrap().frames, vec![a, c]);
|
||||
assert_eq!(d.story(sa).unwrap().text, "words");
|
||||
let own = d.item(b).unwrap().text_frame().unwrap().story;
|
||||
assert_ne!(own, sa);
|
||||
assert!(d.story(own).unwrap().text.is_empty());
|
||||
// A frame alone in its story has no thread to leave.
|
||||
assert!(d.remove_from_thread(b).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_frame_removed_from_a_vertical_thread_stays_vertical() {
|
||||
let mut d = doc();
|
||||
let lid = d.default_layer();
|
||||
let (a, sa) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(10.0, 10.0, 100.0, 100.0), lid, "縦書き", ParaFormat::default()).unwrap();
|
||||
let (b, _) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(110.0, 10.0, 200.0, 100.0), lid, "", ParaFormat::default()).unwrap();
|
||||
d.story_mut(sa).unwrap().vertical = true;
|
||||
d.thread(a, b).unwrap();
|
||||
d.remove_from_thread(b).unwrap();
|
||||
d.check().unwrap();
|
||||
assert!(d.frame_vertical(d.item(a).unwrap()));
|
||||
assert!(d.frame_vertical(d.item(b).unwrap()), "the removed frame keeps the story's direction");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_frame_removed_from_a_right_to_left_thread_keeps_its_column_order() {
|
||||
let mut d = doc();
|
||||
let lid = d.default_layer();
|
||||
let (a, sa) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(10.0, 10.0, 100.0, 100.0), lid, "نص", ParaFormat::default()).unwrap();
|
||||
let (b, _) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(110.0, 10.0, 200.0, 100.0), lid, "", ParaFormat::default()).unwrap();
|
||||
d.story_mut(sa).unwrap().direction = crate::TextDirection::RightToLeft;
|
||||
d.thread(a, b).unwrap();
|
||||
d.remove_from_thread(b).unwrap();
|
||||
d.check().unwrap();
|
||||
let own = d.item(b).unwrap().text_frame().unwrap().story;
|
||||
assert_eq!(d.story(own).unwrap().direction, crate::TextDirection::RightToLeft);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn frames_keep_their_story_direction_through_threading() {
|
||||
let mut d = doc();
|
||||
|
||||
@@ -30,6 +30,7 @@ log = { workspace = true }
|
||||
regex = { workspace = true }
|
||||
quick-xml = { workspace = true }
|
||||
caseless = { workspace = true }
|
||||
unicode-segmentation = { workspace = true }
|
||||
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
|
||||
tempfile = { workspace = true }
|
||||
|
||||
@@ -36,11 +36,6 @@ pub fn write_atomic(path: &Path, bytes: &[u8]) -> io::Result<()> {
|
||||
write_atomic_with(path, |f| f.write_all(bytes))
|
||||
}
|
||||
|
||||
/// [`write_atomic`] for a command's `path` parameter: the error names the path.
|
||||
pub(crate) fn write_file(path: &str, bytes: &[u8]) -> crate::Result<()> {
|
||||
write_atomic(Path::new(path), bytes).map_err(|e| crate::EngineError::Other(format!("{path}: {e}")))
|
||||
}
|
||||
|
||||
/// Atomically replace (or create) `path` with what `fill` writes into the temporary file. When
|
||||
/// `fill`, the flush or the rename fails, the temporary file is removed, `path` is untouched and
|
||||
/// the error is returned.
|
||||
|
||||
@@ -5,6 +5,7 @@ use designcraft_doc::{Document, ItemId, Shape};
|
||||
use designcraft_geom::{Affine, Anchor, AnchorKind, Point};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::object::path_editable;
|
||||
use super::{CommandSpec, bad, cmd, has_doc, point_param};
|
||||
use crate::{Result, Session};
|
||||
|
||||
@@ -69,6 +70,7 @@ fn erase_or_smooth(s: &mut Session, p: &Value, smooth: bool) -> Result<Value> {
|
||||
.map(|a| a.iter().filter_map(|v| Some(Point::new(v.get(0)?.as_f64()?, v.get(1)?.as_f64()?))).collect())
|
||||
.unwrap_or_default();
|
||||
s.edit(|d, _| {
|
||||
path_editable(d, id, cmd)?;
|
||||
let inv = to_inner(d, id).ok_or(designcraft_doc::DocError::NoItem(id))?;
|
||||
let scale = inv.determinant().abs().sqrt().max(1e-9);
|
||||
let it = d.item_mut(id).ok_or(designcraft_doc::DocError::NoItem(id))?;
|
||||
@@ -135,6 +137,7 @@ fn add_anchor(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let at = point_param(p, "at").ok_or_else(|| bad("path.addAnchor", "missing at"))?;
|
||||
let tol = p.get("tolerance").and_then(Value::as_f64).unwrap_or(4.0);
|
||||
s.edit(|d, _| {
|
||||
path_editable(d, id, "path.addAnchor")?;
|
||||
let inv = to_inner(d, id).ok_or(designcraft_doc::DocError::NoItem(id))?;
|
||||
let it = d.item_mut(id).ok_or(designcraft_doc::DocError::NoItem(id))?;
|
||||
let q = inv * at;
|
||||
@@ -154,6 +157,7 @@ fn add_anchor(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
fn delete_anchor(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (id, si, ai) = anchor_param(p, "path.deleteAnchor")?;
|
||||
s.edit(|d, sel| {
|
||||
path_editable(d, id, "path.deleteAnchor")?;
|
||||
let it = d.item_mut(id).ok_or(designcraft_doc::DocError::NoItem(id))?;
|
||||
let sp = it.path.subpaths.get_mut(si).ok_or_else(|| bad("path.deleteAnchor", "no such subpath"))?;
|
||||
if ai >= sp.anchors.len() {
|
||||
@@ -181,6 +185,7 @@ fn convert_anchor(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let to = point_param(p, "to");
|
||||
let corner = p.get("corner").and_then(Value::as_bool);
|
||||
s.edit(|d, _| {
|
||||
path_editable(d, id, "path.convertAnchor")?;
|
||||
let inv = to_inner(d, id).ok_or(designcraft_doc::DocError::NoItem(id))?;
|
||||
let it = d.item_mut(id).ok_or(designcraft_doc::DocError::NoItem(id))?;
|
||||
let sp = it.path.subpaths.get_mut(si).ok_or_else(|| bad("path.convertAnchor", "no such subpath"))?;
|
||||
|
||||
@@ -28,7 +28,7 @@ fn no_book() -> EngineError {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn save(b: &Book) -> Result<()> {
|
||||
let bytes = serde_json::to_vec_pretty(b).map_err(|e| EngineError::Other(e.to_string()))?;
|
||||
crate::atomic::write_file(&b.path, &bytes)
|
||||
crate::io::write_file(&b.path, &bytes).map_err(EngineError::Other)
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
@@ -38,14 +38,14 @@ fn save(_: &Book) -> Result<()> {
|
||||
|
||||
fn load(path: &str) -> Result<designcraft_doc::Document> {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
let bytes = std::fs::read(path).map_err(|e| EngineError::Other(format!("{path}: {e}")))?;
|
||||
let bytes = crate::io::read_file(path).map_err(EngineError::Other)?;
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
let bytes: Vec<u8> = {
|
||||
let _ = path;
|
||||
vec![]
|
||||
};
|
||||
if path.to_lowercase().ends_with(".idml") {
|
||||
return designcraft_idml::import_idml(&bytes).map_err(|e| EngineError::Other(format!("{path}: {e}")));
|
||||
return super::interchange::import_idml_confined(&bytes).map_err(|e| EngineError::Other(format!("{path}: {e}")));
|
||||
}
|
||||
super::file::from_bytes(&bytes).map_err(|e| EngineError::Other(format!("{path}: {e}")))
|
||||
}
|
||||
@@ -90,7 +90,7 @@ impl ChapterBatch {
|
||||
}
|
||||
|
||||
fn commit(self) -> Result<()> {
|
||||
self.commit_with(write_staged_chapter)
|
||||
self.commit_with(|path, staged| crate::io::replace_with(path, staged))
|
||||
}
|
||||
|
||||
fn commit_with(self, mut write: impl FnMut(&std::path::Path, &std::path::Path) -> std::io::Result<()>) -> Result<()> {
|
||||
@@ -110,12 +110,6 @@ impl ChapterBatch {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn write_staged_chapter(path: &std::path::Path, staged: &std::path::Path) -> std::io::Result<()> {
|
||||
let mut input = std::fs::File::open(staged)?;
|
||||
crate::atomic::write_atomic_with(path, |file| std::io::copy(&mut input, file).map(|_| ()))
|
||||
}
|
||||
|
||||
/// Batch commands only write closed native chapters. IDML is an imported source, and an open
|
||||
/// chapter's model (including unsaved edits) cannot be reconciled by a disk-only book update.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
@@ -125,16 +119,16 @@ fn writable_chapter(s: &Session, path: &str, command: &'static str) -> Result<()
|
||||
if Path::new(path).extension().and_then(|ext| ext.to_str()).is_some_and(|ext| ext.eq_ignore_ascii_case("idml")) {
|
||||
return Err(bad(command, format!("cannot change imported IDML chapter {path}; convert it to a native DesignCraft document first")));
|
||||
}
|
||||
let target = std::fs::canonicalize(path).map_err(|e| EngineError::Other(format!("{path}: {e}")))?;
|
||||
if s.docs.iter().any(|doc| doc.path.as_ref().is_some_and(|open| std::fs::canonicalize(open).is_ok_and(|open| open == target))) {
|
||||
let target = crate::io::canonicalize(path).map_err(|e| EngineError::Other(format!("{path}: {e}")))?;
|
||||
if s.docs.iter().any(|doc| doc.path.as_ref().is_some_and(|open| crate::io::canonicalize(open).is_ok_and(|open| open == target))) {
|
||||
return Err(bad(command, format!("chapter {path} is open; close it before updating the book")));
|
||||
}
|
||||
if !std::fs::metadata(&target).is_ok_and(|metadata| metadata.is_file()) {
|
||||
if !crate::io::is_file(&target) {
|
||||
return Err(bad(command, format!("chapter {path} is not a regular file")));
|
||||
}
|
||||
// Check both the file and its resolved parent without truncating it. Replacement needs a
|
||||
// writable directory even when an in-place write would be permitted.
|
||||
std::fs::OpenOptions::new().write(true).open(&target).map_err(|e| EngineError::Other(format!("{path}: {e}")))?;
|
||||
crate::io::writable(&target).map_err(|e| EngineError::Other(format!("{path}: {e}")))?;
|
||||
let parent = target.parent().ok_or_else(|| bad(command, format!("chapter {path} has no parent folder")))?;
|
||||
tempfile::Builder::new().prefix(".designcraft-book-check-").tempfile_in(parent).map_err(|e| EngineError::Other(format!("{path}: {e}")))?;
|
||||
Ok(())
|
||||
@@ -248,7 +242,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
cmd!(noundo "book.open", "Open Book", [], None, "{path} → {documents}", always, |s, p| {
|
||||
let path = str_param(p, "path").ok_or_else(|| bad("book.open", "`path` required"))?.to_string();
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
let text = std::fs::read_to_string(&path).map_err(|e| EngineError::Other(format!("{path}: {e}")))?;
|
||||
let text = crate::io::read_to_string(&path).map_err(EngineError::Other)?;
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
let text = String::new();
|
||||
let mut b: Book = serde_json::from_str(&text).map_err(|e| bad("book.open", format!("not a book: {e}")))?;
|
||||
@@ -331,7 +325,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
match str_param(p, "path") {
|
||||
Some(path) => {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
crate::atomic::write_file(path, &bytes)?;
|
||||
crate::io::write_file(path, &bytes).map_err(EngineError::Other)?;
|
||||
Ok(json!({"path": path, "bytes": bytes.len(), "pages": pages}))
|
||||
}
|
||||
None => Ok(json!({"base64": super::file::base64_encode(&bytes), "bytes": bytes.len(), "pages": pages})),
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use super::{ChapterBatch, MAX_BATCH_CHAPTERS, write_staged_chapter};
|
||||
use super::{ChapterBatch, MAX_BATCH_CHAPTERS};
|
||||
use crate::Session;
|
||||
use serde_json::json;
|
||||
|
||||
@@ -26,7 +26,7 @@ fn a_commit_failure_reports_the_completed_prefix_and_cleans_staging() {
|
||||
let error = batch
|
||||
.commit_with(|path, staged| {
|
||||
calls += 1;
|
||||
if path == second { Err(std::io::Error::other("synthetic disk full")) } else { write_staged_chapter(path, staged) }
|
||||
if path == second { Err(std::io::Error::other("synthetic disk full")) } else { crate::io::replace_with(path, staged) }
|
||||
})
|
||||
.unwrap_err()
|
||||
.to_string();
|
||||
|
||||
@@ -45,7 +45,8 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
let path = str_param(p, "path").ok_or_else(|| bad("color.loadProfile", "`path` required"))?;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
let info = cms::load_icc_file(std::path::Path::new(path)).map_err(|e| bad("color.loadProfile", e.to_string()))?;
|
||||
let bytes = crate::io::read_file(path).map_err(|e| bad("color.loadProfile", e))?;
|
||||
let info = cms::register_icc(&bytes, None).map_err(|e| bad("color.loadProfile", e.to_string()))?;
|
||||
Ok(json!(info))
|
||||
}
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
|
||||
@@ -340,11 +340,11 @@ fn place_image(
|
||||
let cands = image_candidates(cell, data_dir, doc_dir);
|
||||
let found = cands.iter().find_map(|p| {
|
||||
// Refuse huge files before reading them; a too-large image counts as missing.
|
||||
let len = std::fs::metadata(p).ok()?.len();
|
||||
let len = crate::io::metadata(p).ok()?.len();
|
||||
if len == 0 || len > super::MAX_IMAGE_FILE_BYTES {
|
||||
return None;
|
||||
}
|
||||
std::fs::read(p).ok().filter(|b| !b.is_empty()).map(|b| (p.clone(), b))
|
||||
crate::io::read_file(p).ok().filter(|b| !b.is_empty()).map(|b| (p.clone(), b))
|
||||
});
|
||||
let Some((path, bytes)) = found else {
|
||||
if let Some(it) = doc.item_mut(item) {
|
||||
|
||||
@@ -619,7 +619,7 @@ pub(crate) fn refresh_relative_paths(doc: &mut Document, doc_path: &Path) {
|
||||
/// again as `relative_path` beside the document.
|
||||
pub(crate) fn resolve_sources_on_open(doc: &mut Document, doc_path: Option<&Path>) {
|
||||
for src in &mut doc.data_merge.sources {
|
||||
let abs_exists = src.path.as_deref().is_some_and(|p| Path::new(p).is_file());
|
||||
let abs_exists = src.path.as_deref().is_some_and(crate::io::is_file);
|
||||
if abs_exists {
|
||||
if let Some(path) = src.path.clone() {
|
||||
src.status = status_of(Path::new(&path), src.fingerprint);
|
||||
@@ -630,7 +630,7 @@ pub(crate) fn resolve_sources_on_open(doc: &mut Document, doc_path: Option<&Path
|
||||
&& let Some(dir) = doc_path.parent()
|
||||
{
|
||||
let candidate = dir.join(&rel);
|
||||
if candidate.is_file() {
|
||||
if crate::io::is_file(&candidate) {
|
||||
let saved = candidate.to_string_lossy().into_owned();
|
||||
src.fingerprint = fingerprint_of(Path::new(&saved));
|
||||
src.status = SourceStatus::Ok;
|
||||
@@ -768,12 +768,14 @@ fn read_path(path: &str) -> std::result::Result<Vec<u8>, String> {
|
||||
}
|
||||
|
||||
fn read_path_capped(path: &str, cap: u64) -> std::result::Result<Vec<u8>, String> {
|
||||
match std::fs::metadata(path) {
|
||||
match crate::io::metadata(path) {
|
||||
Ok(m) if m.len() > cap => return Err(format!("{path}: the data file is larger than {} MiB", cap / (1024 * 1024))),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Err(format!("{path}: the data file is missing")),
|
||||
_ => {}
|
||||
}
|
||||
match std::fs::read(path) {
|
||||
// The roots' own message when they refuse the path.
|
||||
crate::file_access::check_read(path)?;
|
||||
match crate::io::read(path) {
|
||||
Ok(b) => Ok(b),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Err(format!("{path}: the data file is missing")),
|
||||
Err(e) => Err(format!("{path}: {e}")),
|
||||
|
||||
@@ -330,7 +330,7 @@ pub fn relative_between(from_dir: &Path, target: &Path) -> String {
|
||||
}
|
||||
|
||||
pub fn fingerprint_of(path: &Path) -> Option<Fingerprint> {
|
||||
let meta = std::fs::metadata(path).ok()?;
|
||||
let meta = crate::io::metadata(path).ok()?;
|
||||
let mtime = meta
|
||||
.modified()
|
||||
.ok()
|
||||
|
||||
+377
-19
@@ -20,13 +20,6 @@ fn has_clip(s: &Session) -> std::result::Result<(), String> {
|
||||
if s.clipboard.is_some() || text { Ok(()) } else { Err("clipboard is empty".into()) }
|
||||
}
|
||||
|
||||
fn has_clip_or_text(s: &Session) -> std::result::Result<(), String> {
|
||||
if s.active().is_some_and(|d| d.selection.text.is_some()) {
|
||||
return Ok(());
|
||||
}
|
||||
has_clip(s)
|
||||
}
|
||||
|
||||
fn has_selection_or_text(s: &Session) -> std::result::Result<(), String> {
|
||||
if s.active().and_then(|d| d.selection.text).is_some_and(|t| !t.is_caret()) {
|
||||
return Ok(());
|
||||
@@ -74,7 +67,7 @@ fn paste_text(s: &mut Session, text: Option<String>, formatted: bool) -> Result<
|
||||
}
|
||||
}
|
||||
let use_clip = formatted && clip.as_ref().is_some_and(|(_, p)| text.as_ref().is_none_or(|x| x.replace("\r\n", "\n") == *p));
|
||||
// Footnotes, cross-references and tables only paste into story text, not cells or footnotes.
|
||||
// Footnotes, endnotes, editorial notes, cross-references and tables cannot be pasted into cells or footnotes.
|
||||
if use_clip && let Some((slice, _)) = clip {
|
||||
let slice = if t.cell.is_some() { strip_objects(&slice) } else { (*slice).clone() };
|
||||
return s.edit(|d, sel| {
|
||||
@@ -88,12 +81,84 @@ fn paste_text(s: &mut Session, text: Option<String>, formatted: bool) -> Result<
|
||||
});
|
||||
}
|
||||
let text = text.or_else(|| clip.map(|(_, p)| p)).ok_or_else(|| super::bad("edit.paste", "clipboard is empty"))?;
|
||||
s.execute("text.insert", &json!({"text": text.replace("\r\n", "\n").replace('\r', "\n"), "raw": true}))
|
||||
let text = outside_text(&text)?;
|
||||
s.execute("text.insert", &json!({"text": text, "raw": true}))
|
||||
}
|
||||
|
||||
/// Text from the system clipboard as story text: Unix line ends, and none of the private-use
|
||||
/// characters (U+E000–U+E1FF) that stories use as markers for breaks, footnotes, tables and
|
||||
/// variables, since a stray one would be read as a marker without its payload.
|
||||
fn outside_text(text: &str) -> Result<String> {
|
||||
let text: String = text.replace("\r\n", "\n").replace('\r', "\n").chars().filter(|c| !('\u{E000}'..='\u{E1FF}').contains(c)).collect();
|
||||
if text.is_empty() { Err(super::bad("edit.paste", "the clipboard holds no text")) } else { Ok(text) }
|
||||
}
|
||||
|
||||
/// Pasted text with no insertion point: a new text frame holding it, as wide as the first column
|
||||
/// of the page's margin area and as tall as the text (at most the margin area's height), centred
|
||||
/// on `at` (spread coordinates) or else on the margin area. The frame ends up selected. With
|
||||
/// `slice` (the text copied here), the frame's story is that formatted copy.
|
||||
fn paste_text_frame(s: &mut Session, p: &Value, text: &str, slice: Option<&designcraft_doc::Story>) -> Result<Value> {
|
||||
use designcraft_geom::{Point, Rect, shapes};
|
||||
const LIMIT: f64 = 1.0e5;
|
||||
let sr = super::spread_param(p, "spread")?;
|
||||
let at = super::point_param(p, "at")
|
||||
.filter(|a| a.x.is_finite() && a.y.is_finite())
|
||||
.map(|a| Point::new(a.x.clamp(-LIMIT, LIMIT), a.y.clamp(-LIMIT, LIMIT)));
|
||||
let lid = s.doc()?.active_layer;
|
||||
let cache = s.cache.clone();
|
||||
let text = if slice.is_some() { String::new() } else { outside_text(text)? };
|
||||
s.edit(|d, sel| {
|
||||
let sp = d.spread(sr).ok_or_else(|| super::bad("edit.paste", "no such spread"))?;
|
||||
let page = at.and_then(|a| sp.page_at_x(a.x)).and_then(|i| sp.pages.get(i)).or_else(|| sp.pages.first());
|
||||
let page = page.ok_or_else(|| super::bad("edit.paste", "the spread has no pages"))?;
|
||||
let margins = page.margin_rect();
|
||||
let column = page.column_rects().first().copied().unwrap_or(margins);
|
||||
let w = column.width().max(12.0);
|
||||
let max_h = margins.height().max(12.0);
|
||||
let c = at.unwrap_or(Point::new(column.center().x, margins.center().y));
|
||||
let rect = |h: f64| Rect::new(c.x - w / 2.0, c.y - h / 2.0, c.x + w / 2.0, c.y + h / 2.0);
|
||||
let para = match slice.and_then(|sl| sl.paras.first()) {
|
||||
Some(pf) => designcraft_doc::ParaFormat { table: None, ..pf.clone() },
|
||||
None => designcraft_doc::ParaFormat { style: d.styles.default_paragraph.clone(), ..Default::default() },
|
||||
};
|
||||
let (id, sid) = d.add_text_frame(sr, rect(max_h), lid, &text, para)?;
|
||||
if let Some(sl) = slice {
|
||||
d.story_mut(sid).ok_or(designcraft_doc::DocError::NoStory(sid))?.insert_story(0, sl);
|
||||
}
|
||||
// Shrink to the composed text unless it already fills the frame.
|
||||
let composed = cache.get(d, sid, None);
|
||||
if !composed.is_overset()
|
||||
&& let Some(ft) = composed.frame(id)
|
||||
{
|
||||
let inset = d.item(id).and_then(|i| i.text_frame()).map_or(0.0, |tf| tf.options.inset[0] + tf.options.inset[2]);
|
||||
let h = (ft.content_height + inset + 0.5).clamp(12.0, max_h);
|
||||
if h.is_finite()
|
||||
&& h < max_h
|
||||
&& let Some(it) = d.item_mut(id)
|
||||
{
|
||||
it.path = shapes::rectangle(rect(h));
|
||||
// Keep the full height if the last line no longer fits.
|
||||
if cache.get(d, sid, None).is_overset()
|
||||
&& let Some(it) = d.item_mut(id)
|
||||
{
|
||||
it.path = shapes::rectangle(rect(max_h));
|
||||
}
|
||||
}
|
||||
}
|
||||
*sel = Selection::items(vec![id]);
|
||||
Ok(json!({"id": id.0, "story": sid.0}))
|
||||
})
|
||||
}
|
||||
|
||||
fn strip_objects(st: &designcraft_doc::Story) -> designcraft_doc::Story {
|
||||
let mut out = st.clone();
|
||||
let marks = [designcraft_doc::FOOTNOTE_REF, designcraft_doc::XREF_MARK, designcraft_doc::TABLE_ANCHOR];
|
||||
let marks = [
|
||||
designcraft_doc::FOOTNOTE_REF,
|
||||
designcraft_doc::ENDNOTE_REF,
|
||||
designcraft_doc::NOTE_MARK,
|
||||
designcraft_doc::XREF_MARK,
|
||||
designcraft_doc::TABLE_ANCHOR,
|
||||
];
|
||||
while let Some(i) = out.text.find(marks) {
|
||||
let n = out.text[i..].chars().next().map_or(1, char::len_utf8);
|
||||
out.delete(i..i + n);
|
||||
@@ -110,6 +175,8 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
st.doc = e.doc;
|
||||
st.selection = e.selection;
|
||||
st.revision += 1;
|
||||
// Pending typing overrides belong to the current edit state, not a restored snapshot.
|
||||
s.typing_format = None;
|
||||
Ok(json!({"undone": e.label}))
|
||||
}),
|
||||
cmd!(noundo "edit.redo", "Redo", ["Edit"], Some("Cmd+Shift+Z"), "{}", can_redo, |s, _| {
|
||||
@@ -119,6 +186,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
st.doc = e.doc;
|
||||
st.selection = e.selection;
|
||||
st.revision += 1;
|
||||
s.typing_format = None;
|
||||
Ok(json!({"redone": e.label}))
|
||||
}),
|
||||
cmd!(noundo "selection.set", "Select", [], None, "{ids: [id], add?: bool, content?: bool}", has_doc, |s, p| {
|
||||
@@ -189,11 +257,20 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
return super::text::delete_selection(s);
|
||||
}
|
||||
let ids = super::targets(s, p)?;
|
||||
// With a placed graphic itself selected (Direct Selection), only the graphic goes: its
|
||||
// frame stays, empty and selected (as in InDesign). Other items are deleted.
|
||||
let content = s.doc()?.selection.content && p.get("ids").is_none();
|
||||
s.edit(|d, sel| {
|
||||
let mut kept = Vec::new();
|
||||
for id in &ids {
|
||||
let _ = d.remove_item(*id);
|
||||
if let Some(it) = d.item_mut(*id).filter(|it| content && matches!(it.content, designcraft_doc::Content::Graphic(_))) {
|
||||
it.content = designcraft_doc::Content::Unassigned;
|
||||
kept.push(*id);
|
||||
} else {
|
||||
let _ = d.remove_item(*id);
|
||||
}
|
||||
}
|
||||
*sel = Selection::default();
|
||||
*sel = Selection::items(kept);
|
||||
Ok(json!({"deleted": ids.len()}))
|
||||
})
|
||||
}),
|
||||
@@ -227,11 +304,18 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Paste",
|
||||
["Edit"],
|
||||
Some("Cmd+V"),
|
||||
"{inPlace?: bool, text?: the system clipboard's text (pastes it unless it is what was copied here)}",
|
||||
has_clip_or_text,
|
||||
"{inPlace?: bool, text?: the system clipboard's text (pastes it unless it is what was copied here; with no insertion point it becomes a new text frame), spread?, at?: [x, y] (spread coords: the new text frame's centre)}",
|
||||
// The system clipboard may hold text from another app, so Paste is always available.
|
||||
has_doc,
|
||||
|s, p| {
|
||||
let text = super::str_param(p, "text").filter(|t| !t.is_empty());
|
||||
if s.doc()?.selection.text.is_some() {
|
||||
return paste_text(s, super::str_param(p, "text").map(str::to_string), true);
|
||||
return paste_text(s, text.map(str::to_string), true);
|
||||
}
|
||||
if let Some(text) = text {
|
||||
// What our own text copy put on the clipboard keeps its formatting.
|
||||
let slice = s.text_clipboard.clone().filter(|(_, plain)| text.replace("\r\n", "\n") == *plain).map(|(slice, _)| slice);
|
||||
return paste_text_frame(s, p, text, slice.as_deref());
|
||||
}
|
||||
let Some(clip) = s.clipboard.clone() else {
|
||||
return Err(super::bad("edit.paste", "clipboard is empty"));
|
||||
@@ -266,12 +350,15 @@ pub(crate) fn clip_doc(s: &Session) -> Result<designcraft_doc::Document> {
|
||||
let st = s.doc()?;
|
||||
let mut d = (*st.doc).clone();
|
||||
let keep: Vec<ItemId> = st.selection.items.clone();
|
||||
// Gather the selected items (keep their spread coordinates) into spread 0.
|
||||
// Gather the selected items (in their spread coordinates, nested ones too) into spread 0.
|
||||
let mut items = Vec::new();
|
||||
for id in &keep {
|
||||
if let Some(it) = st.doc.item(*id) {
|
||||
items.push(Arc::new(it.clone()));
|
||||
}
|
||||
let (Some(it), Some(loc)) = (st.doc.item(*id), st.doc.find(*id)) else { continue };
|
||||
let parent = st.doc.parent_xf(&loc);
|
||||
items.push(Arc::new(match &it.content {
|
||||
designcraft_doc::Content::Graphic(g) if st.selection.content => graphic_alone(it, g, parent),
|
||||
_ => designcraft_doc::Item { xf: parent * it.xf, ..it.clone() },
|
||||
}));
|
||||
}
|
||||
for sp in d.spreads.iter_mut() {
|
||||
Arc::make_mut(sp).items.clear();
|
||||
@@ -307,6 +394,22 @@ pub(crate) fn clip_doc(s: &Session) -> Result<designcraft_doc::Document> {
|
||||
Ok(d)
|
||||
}
|
||||
|
||||
/// A placed graphic on its own, as InDesign copies one selected with Direct Selection: a frame of
|
||||
/// the whole graphic's bounds (uncropped), where the graphic sits on the spread (`parent` is the
|
||||
/// frame's parent transform), without the frame's fill, stroke or effects.
|
||||
fn graphic_alone(frame: &designcraft_doc::Item, g: &designcraft_doc::Graphic, parent: designcraft_geom::Affine) -> designcraft_doc::Item {
|
||||
let r = designcraft_geom::Rect::new(0.0, 0.0, g.size.0, g.size.1);
|
||||
let mut it = designcraft_doc::Item::new(frame.id, frame.layer, designcraft_doc::Shape::Rectangle, designcraft_geom::shapes::rectangle(r));
|
||||
it.xf = parent * frame.xf * g.xf;
|
||||
it.content = designcraft_doc::Content::Graphic(designcraft_doc::Graphic {
|
||||
xf: designcraft_geom::Affine::IDENTITY,
|
||||
auto_fit: designcraft_doc::Fitting::None,
|
||||
crop: [0.0; 4],
|
||||
..g.clone()
|
||||
});
|
||||
it
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod text_clipboard_tests {
|
||||
use super::*;
|
||||
@@ -316,6 +419,87 @@ mod text_clipboard_tests {
|
||||
s.doc().unwrap().doc.item(ItemId(r["id"].as_u64().unwrap())).unwrap().text_frame().unwrap().story
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paste_text_with_no_insertion_point_makes_a_text_frame() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
let items = |s: &Session| s.doc().unwrap().doc.spreads[0].items.len();
|
||||
// Text from another app, nothing copied here: a new, selected text frame.
|
||||
let r = s.execute("edit.paste", &json!({"text": "From elsewhere\r\nSecond line"})).unwrap();
|
||||
let id = ItemId(r["id"].as_u64().unwrap());
|
||||
let d = s.doc().unwrap();
|
||||
assert_eq!(d.selection.items, vec![id]);
|
||||
assert!(d.selection.text.is_none(), "selected as an object");
|
||||
let it = d.doc.item(id).unwrap();
|
||||
assert_eq!(d.doc.story(it.text_frame().unwrap().story).unwrap().text, "From elsewhere\nSecond line");
|
||||
let page = &d.doc.spreads[0].pages[0];
|
||||
let (b, m) = (it.bounds(), page.margin_rect());
|
||||
assert!((b.width() - page.column_rects()[0].width()).abs() < 1e-6, "{b:?}");
|
||||
assert!(b.height() < m.height() / 2.0, "fits two lines: {b:?}");
|
||||
assert!((b.center().y - m.center().y).abs() < 1e-6, "{b:?}");
|
||||
assert!(!s.cache.get(&d.doc, it.text_frame().unwrap().story, None).is_overset());
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(items(&s), 0, "one undo removes it");
|
||||
// Centred on `at`; hostile numbers are clamped.
|
||||
let r = s.execute("edit.paste", &json!({"text": "Here", "at": [200.0, 300.0]})).unwrap();
|
||||
let b = s.doc().unwrap().doc.item(ItemId(r["id"].as_u64().unwrap())).unwrap().bounds();
|
||||
assert!((b.center().x - 200.0).abs() < 1e-6 && (b.center().y - 300.0).abs() < 1e-6, "{b:?}");
|
||||
assert!(s.execute("edit.paste", &json!({"text": "Far", "at": [1e300, -1e300], "spread": 99})).is_err());
|
||||
s.execute("edit.paste", &json!({"text": "Far", "at": [1e300, -1e300]})).unwrap();
|
||||
// Copied objects paste when no text is given.
|
||||
s.execute("edit.deselectAll", &json!({})).unwrap();
|
||||
let rect = s.execute("frame.create", &json!({"rect": [72, 72, 200, 160]})).unwrap()["id"].clone();
|
||||
s.execute("selection.set", &json!({"ids": [rect]})).unwrap();
|
||||
s.execute("edit.copy", &json!({})).unwrap();
|
||||
let n = items(&s);
|
||||
let r = s.execute("edit.paste", &json!({})).unwrap();
|
||||
assert_eq!(r["ids"].as_array().unwrap().len(), 1);
|
||||
assert_eq!(items(&s), n + 1);
|
||||
assert!(s.doc().unwrap().doc.item(ItemId(r["ids"][0].as_u64().unwrap())).unwrap().text_frame().is_none());
|
||||
s.doc().unwrap().doc.check().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn outside_text_never_pastes_markers() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
// Private-use characters from another app would read as footnote, table or variable markers.
|
||||
let dirty = "a\u{E00A}b\u{E009}c\u{E1FF}d\u{E200}";
|
||||
let r = s.execute("edit.paste", &json!({"text": dirty})).unwrap();
|
||||
let st = s.doc().unwrap().doc.item(ItemId(r["id"].as_u64().unwrap())).unwrap().text_frame().unwrap().story;
|
||||
assert_eq!(s.doc().unwrap().doc.story(st).unwrap().text, "abcd\u{E200}");
|
||||
s.doc().unwrap().doc.check().unwrap();
|
||||
let b = frame(&mut s, "Target");
|
||||
s.execute("text.select", &json!({"story": b.0, "anchor": 6, "focus": 6})).unwrap();
|
||||
s.execute("edit.paste", &json!({"text": dirty})).unwrap();
|
||||
s.execute("edit.pasteWithoutFormatting", &json!({"text": dirty})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.story(b).unwrap().text, "Targetabcd\u{E200}abcd\u{E200}");
|
||||
assert!(s.execute("edit.paste", &json!({"text": "\u{E00A}"})).is_err());
|
||||
s.doc().unwrap().doc.check().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn copied_text_pasted_with_no_insertion_point_keeps_its_formatting() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
let a = frame(&mut s, "Bold words\nSecond");
|
||||
s.execute("text.select", &json!({"story": a.0, "anchor": 0, "focus": 4})).unwrap();
|
||||
s.execute("type.bold", &json!({})).unwrap();
|
||||
s.execute("text.select", &json!({"story": a.0, "anchor": 11, "focus": 17})).unwrap();
|
||||
s.execute("type.para", &json!({"attrs": {"align": "center"}})).unwrap();
|
||||
s.execute("text.select", &json!({"story": a.0, "anchor": 0, "focus": 17})).unwrap();
|
||||
let copied = s.execute("edit.copy", &json!({})).unwrap()["text"].as_str().unwrap().to_string();
|
||||
s.execute("edit.deselectAll", &json!({})).unwrap();
|
||||
let r = s.execute("edit.paste", &json!({"text": copied})).unwrap();
|
||||
let d = s.doc().unwrap();
|
||||
let st = d.doc.story(d.doc.item(ItemId(r["id"].as_u64().unwrap())).unwrap().text_frame().unwrap().story).unwrap();
|
||||
assert_eq!(st.text, "Bold words\nSecond");
|
||||
assert_eq!(st.char_format_at(2).over.font_style.as_deref(), Some("Bold"));
|
||||
assert_eq!(st.char_format_at(7).over.font_style, None);
|
||||
assert_eq!(st.paras[1], d.doc.story(a).unwrap().paras[1]);
|
||||
d.doc.check().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn formatted_copy_paste_and_plain_paste() {
|
||||
let mut s = Session::new();
|
||||
@@ -355,6 +539,124 @@ mod text_clipboard_tests {
|
||||
s.doc().unwrap().doc.check().unwrap();
|
||||
}
|
||||
|
||||
fn note_clipboard_session() -> (Session, designcraft_doc::StoryId) {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
let source = frame(&mut s, "aéz");
|
||||
s.execute("text.select", &json!({"story": source.0, "anchor": 1, "focus": 1})).unwrap();
|
||||
s.execute("endnote.insert", &json!({"text": "Citation A"})).unwrap();
|
||||
s.execute("note.new", &json!({"text": "Memo A", "author": "Ed"})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.story(source).unwrap().text, "a\u{E00F}\u{E010}éz");
|
||||
s.execute("text.select", &json!({"story": source.0, "anchor": 0, "focus": 10})).unwrap();
|
||||
s.execute("type.char", &json!({"attrs": {"fontStyle": "Bold"}})).unwrap();
|
||||
assert_eq!(s.execute("edit.copy", &json!({})).unwrap(), json!({"text": "aéz"}));
|
||||
(s, source)
|
||||
}
|
||||
|
||||
fn assert_child_note_paste(
|
||||
s: &mut Session,
|
||||
source: designcraft_doc::StoryId,
|
||||
parent: designcraft_doc::StoryId,
|
||||
cell: designcraft_doc::CellAddr,
|
||||
endpoints: (usize, usize),
|
||||
) {
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let selected = s.doc().unwrap().selection.text.unwrap();
|
||||
assert_eq!((selected.story, selected.cell, selected.anchor, selected.focus), (parent, Some(cell), endpoints.0, endpoints.1));
|
||||
assert_eq!(selected.frame, None);
|
||||
let before_child = before.text_story(parent, Some(cell)).unwrap();
|
||||
assert_eq!(before_child.text, "L----R");
|
||||
let clipboard = s.text_clipboard.clone();
|
||||
let history = s.execute("document.history", &json!({})).unwrap();
|
||||
assert_eq!(history["redo"], json!([]));
|
||||
|
||||
let result = s.execute("edit.paste", &json!({})).unwrap();
|
||||
let after = s.doc().unwrap().doc.clone();
|
||||
let child = after.text_story(parent, Some(cell)).unwrap();
|
||||
assert_eq!(child.text, "LaézR", "root-only note markers must not enter child text");
|
||||
assert_eq!(child.len(), 6);
|
||||
assert_eq!(result, json!({"pos": 5, "formatted": true}));
|
||||
assert_eq!(s.doc().unwrap().selection, Selection::text(designcraft_doc::TextSel { anchor: 5, focus: 5, ..selected }));
|
||||
assert!(child.endnotes.is_empty() && child.editorial.is_empty());
|
||||
for pos in [1, 2, 4] {
|
||||
let (_, format) = child.runs().find(|(range, _)| range.contains(&pos)).unwrap();
|
||||
assert_eq!(format.over.font_style.as_deref(), Some("Bold"));
|
||||
}
|
||||
// Inspect actual run coverage: char_format_at at a run boundary means the preceding run.
|
||||
for pos in [0, 5] {
|
||||
let (_, old_format) = before_child.runs().find(|(range, _)| range.contains(&pos)).unwrap();
|
||||
let (_, new_format) = child.runs().find(|(range, _)| range.contains(&pos)).unwrap();
|
||||
assert_eq!(new_format, old_format);
|
||||
}
|
||||
assert_eq!(after.story(parent).unwrap().text, before.story(parent).unwrap().text);
|
||||
assert_eq!(after.story(parent).unwrap().chars, before.story(parent).unwrap().chars);
|
||||
assert_eq!(after.story(source), before.story(source));
|
||||
assert_eq!(s.text_clipboard, clipboard);
|
||||
|
||||
let mut pasted_history = history.clone();
|
||||
pasted_history["undo"].as_array_mut().unwrap().push(json!("Paste"));
|
||||
assert_eq!(s.execute("document.history", &json!({})).unwrap(), pasted_history);
|
||||
assert_eq!(s.execute("edit.undo", &json!({})).unwrap(), json!({"undone": "Paste"}));
|
||||
assert_eq!(s.doc().unwrap().doc, before);
|
||||
let mut undone_history = history;
|
||||
undone_history["redo"] = json!(["Paste"]);
|
||||
assert_eq!(s.execute("document.history", &json!({})).unwrap(), undone_history);
|
||||
// This filter does not change which selection Undo restores.
|
||||
assert_eq!(s.execute("edit.redo", &json!({})).unwrap(), json!({"redone": "Paste"}));
|
||||
assert_eq!(s.doc().unwrap().doc, after);
|
||||
assert_eq!(s.execute("document.history", &json!({})).unwrap(), pasted_history);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn formatted_child_paste_filters_endnotes_and_editorial_in_cells() {
|
||||
let (mut s, source) = note_clipboard_session();
|
||||
let parent = frame(&mut s, "PZ");
|
||||
s.execute("text.select", &json!({"story": parent.0, "anchor": 1, "focus": 1})).unwrap();
|
||||
let table_id = s.execute("table.insert", &json!({"rows": 1, "cols": 2})).unwrap()["table"].as_u64().unwrap();
|
||||
s.execute("text.insert", &json!({"text": "L----R"})).unwrap();
|
||||
s.execute("table.nextCell", &json!({})).unwrap();
|
||||
s.execute("text.insert", &json!({"text": "NEIGHBOR"})).unwrap();
|
||||
s.execute("table.prevCell", &json!({})).unwrap();
|
||||
s.execute("text.move", &json!({"dir": "storyStart"})).unwrap();
|
||||
s.execute("text.move", &json!({"dir": "right"})).unwrap();
|
||||
for _ in 0..4 {
|
||||
s.execute("text.move", &json!({"dir": "right", "extend": true})).unwrap();
|
||||
}
|
||||
let before_table = s.doc().unwrap().doc.story(parent).unwrap().tables[&table_id].clone();
|
||||
let cell = designcraft_doc::CellAddr { table: table_id, row: 0, col: 0 };
|
||||
assert_child_note_paste(&mut s, source, parent, cell, (1, 5));
|
||||
let table = &s.doc().unwrap().doc.story(parent).unwrap().tables[&table_id];
|
||||
assert_eq!(table.cell(0, 1).unwrap().text.text, "NEIGHBOR");
|
||||
let mut expected_table = (*before_table).clone();
|
||||
expected_table.cells[0].text = table.cells[0].text.clone();
|
||||
assert_eq!(table.as_ref(), &expected_table);
|
||||
|
||||
// The same clipboard must still retain both markers when pasted into an ordinary root story.
|
||||
let root = frame(&mut s, "L----R");
|
||||
s.execute("text.select", &json!({"story": root.0, "anchor": 1, "focus": 5})).unwrap();
|
||||
assert_eq!(s.execute("edit.paste", &json!({})).unwrap(), json!({"pos": 11, "formatted": true}));
|
||||
assert_eq!(s.doc().unwrap().doc.story(root).unwrap().text, "La\u{E00F}\u{E010}ézR");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn formatted_child_paste_filters_endnotes_and_editorial_in_footnotes() {
|
||||
let (mut s, source) = note_clipboard_session();
|
||||
let parent = frame(&mut s, "PZ");
|
||||
let neighbor = s.execute("footnote.insert", &json!({"text": "NEIGHBOR"})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("text.select", &json!({"story": parent.0, "anchor": 1, "focus": 1})).unwrap();
|
||||
let target = s.execute("footnote.insert", &json!({"text": "L----R"})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("text.move", &json!({"dir": "left"})).unwrap();
|
||||
for _ in 0..4 {
|
||||
s.execute("text.move", &json!({"dir": "left", "extend": true})).unwrap();
|
||||
}
|
||||
let before = s.doc().unwrap().doc.story(parent).unwrap().clone();
|
||||
assert_child_note_paste(&mut s, source, parent, designcraft_doc::CellAddr::footnote(target), (5, 1));
|
||||
let after = s.doc().unwrap().doc.story(parent).unwrap();
|
||||
assert_eq!(after.note(neighbor).unwrap().text.text, "NEIGHBOR");
|
||||
assert_eq!(after.note(neighbor), before.note(neighbor));
|
||||
assert_eq!(after.notes.iter().map(|note| note.id).collect::<Vec<_>>(), before.notes.iter().map(|note| note.id).collect::<Vec<_>>());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn change_case_keeps_runs() {
|
||||
let mut s = Session::new();
|
||||
@@ -375,6 +677,22 @@ mod text_clipboard_tests {
|
||||
assert_eq!(s.doc().unwrap().selection.text.unwrap().range(), 0..st.len());
|
||||
st.check().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn change_case_leaves_georgian_without_initial_capitals() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
let a = frame(&mut s, "ᲒᲐᲛᲐᲠᲯᲝᲑᲐ ᲛᲡᲝᲤᲚᲘᲝ. ᲐᲮᲐᲚᲘ word");
|
||||
let len = s.doc().unwrap().doc.story(a).unwrap().len();
|
||||
s.execute("text.select", &json!({"story": a.0, "anchor": 0, "focus": len})).unwrap();
|
||||
// Georgian has no title or sentence capitals: Mtavruli is only for all-caps text.
|
||||
s.execute("type.changeCase", &json!({"case": "title"})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.story(a).unwrap().text, "გამარჯობა მსოფლიო. ახალი Word");
|
||||
s.execute("type.changeCase", &json!({"case": "sentence"})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.story(a).unwrap().text, "გამარჯობა მსოფლიო. ახალი word");
|
||||
s.execute("type.changeCase", &json!({"case": "upper"})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.story(a).unwrap().text, "ᲒᲐᲛᲐᲠᲯᲝᲑᲐ ᲛᲡᲝᲤᲚᲘᲝ. ᲐᲮᲐᲚᲘ WORD");
|
||||
}
|
||||
}
|
||||
|
||||
fn paste_into(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -454,4 +772,44 @@ mod paste_into_tests {
|
||||
assert!(img.pixel(120, 120)[0] > 200, "{:?}", img.pixel(120, 120));
|
||||
s.doc().unwrap().doc.check().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_selected_graphic_copies_and_clears_on_its_own() {
|
||||
let dir = std::env::temp_dir().join(format!("dc-graphic-alone-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let png = dir.join("photo.png");
|
||||
std::fs::write(&png, designcraft_render::Rendered { width: 200, height: 100, pixels: vec![40u8; 200 * 100 * 4] }.to_png()).unwrap();
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
// A square frame showing the middle of a wide photo (cropped left and right).
|
||||
let frame = s.execute("frame.create", &json!({"rect": [100, 100, 200, 200]})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("file.place", &json!({"path": png.to_string_lossy(), "frame": frame})).unwrap();
|
||||
s.execute("object.fit", &json!({"mode": "fillProportionally", "ids": [frame]})).unwrap();
|
||||
s.execute("object.stroke", &json!({"ids": [frame], "swatch": "[Black]", "weight": 4})).unwrap();
|
||||
// Direct Selection on the photo, Copy: the whole photo, where it is, without the frame's stroke.
|
||||
s.execute("selection.set", &json!({"ids": [frame], "content": true})).unwrap();
|
||||
s.execute("edit.copy", &json!({})).unwrap();
|
||||
let clip = s.clipboard.clone().unwrap();
|
||||
let it = &clip.spreads[0].items[0];
|
||||
assert!(matches!(&it.content, designcraft_doc::Content::Graphic(g) if g.crop == [0.0; 4]));
|
||||
assert_eq!(it.bounds(), designcraft_geom::Rect::new(50.0, 100.0, 250.0, 200.0));
|
||||
assert!(it.stroke.weight == 0.0 || it.stroke.swatch == "[None]", "{:?}", it.stroke);
|
||||
// Paste Into a shape over it: the photo lands in place, inside the shape.
|
||||
let shape = s.execute("frame.create", &json!({"rect": [60, 90, 240, 210], "shape": "ellipse"})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("selection.set", &json!({"ids": [shape]})).unwrap();
|
||||
s.execute("edit.pasteInto", &json!({})).unwrap();
|
||||
let d = s.doc().unwrap().doc.clone();
|
||||
let kid = d.item(ItemId(shape)).unwrap().children()[0].clone();
|
||||
let at = d.parent_xf(&d.find(kid.id).unwrap()) * kid.xf;
|
||||
assert!((at * designcraft_geom::Point::new(0.0, 0.0) - designcraft_geom::Point::new(50.0, 100.0)).hypot() < 1e-6);
|
||||
assert!((at * designcraft_geom::Point::new(200.0, 100.0) - designcraft_geom::Point::new(250.0, 200.0)).hypot() < 1e-6);
|
||||
// Delete with the photo selected: the frame stays, empty.
|
||||
s.execute("selection.set", &json!({"ids": [frame], "content": true})).unwrap();
|
||||
assert_eq!(s.execute("edit.clear", &json!({})).unwrap()["deleted"], 1);
|
||||
let d = s.doc().unwrap().doc.clone();
|
||||
assert!(matches!(d.item(ItemId(frame)).unwrap().content, designcraft_doc::Content::Unassigned));
|
||||
assert_eq!(s.doc().unwrap().selection, Selection::items(vec![ItemId(frame)]));
|
||||
d.check().unwrap();
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -44,7 +44,7 @@ fn print_booklet(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
match str_param(p, "path") {
|
||||
Some(path) => {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
crate::atomic::write_file(path, &r.bytes)?;
|
||||
crate::io::write_file(path, &r.bytes).map_err(EngineError::Other)?;
|
||||
Ok(json!({"path": path, "bytes": r.bytes.len(), "sheets": r.pages, "warnings": r.warnings}))
|
||||
}
|
||||
None => Ok(json!({"base64": super::file::base64_encode(&r.bytes), "bytes": r.bytes.len(), "sheets": r.pages, "warnings": r.warnings})),
|
||||
@@ -59,7 +59,7 @@ fn export_html(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
match str_param(p, "path") {
|
||||
Some(path) => {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
crate::atomic::write_file(path, text.as_bytes())?;
|
||||
crate::io::write_file(path, text.as_bytes()).map_err(EngineError::Other)?;
|
||||
Ok(json!({"path": path, "bytes": text.len()}))
|
||||
}
|
||||
None => Ok(json!({"bytes": text.len(), "text": text})),
|
||||
@@ -91,7 +91,7 @@ fn export_text(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
match path {
|
||||
Some(path) => {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
crate::atomic::write_file(path, text.as_bytes())?;
|
||||
crate::io::write_file(path, text.as_bytes()).map_err(EngineError::Other)?;
|
||||
Ok(json!({"path": path, "bytes": text.len()}))
|
||||
}
|
||||
None => Ok(json!({"bytes": text.len(), "text": text})),
|
||||
@@ -160,7 +160,7 @@ fn export_epub(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
match p.get("path").and_then(Value::as_str) {
|
||||
Some(path) => {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
crate::atomic::write_file(path, &bytes)?;
|
||||
crate::io::write_file(path, &bytes).map_err(crate::EngineError::Other)?;
|
||||
Ok(serde_json::json!({"path": path, "bytes": bytes.len()}))
|
||||
}
|
||||
None => Ok(serde_json::json!({"base64": super::file::base64_encode(&bytes), "bytes": bytes.len()})),
|
||||
@@ -598,7 +598,7 @@ fn export_pdf(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn write_file(path: &str, bytes: &[u8]) -> Result<()> {
|
||||
crate::atomic::write_file(path, bytes)
|
||||
crate::io::write_file(path, bytes).map_err(EngineError::Other)
|
||||
}
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn write_file(path: &str, _bytes: &[u8]) -> Result<()> {
|
||||
@@ -850,6 +850,45 @@ mod placed_pdf_print_tests {
|
||||
let e = s.execute("file.exportPdf", &json!({"standard": "x4"})).unwrap_err().to_string();
|
||||
assert!(e.contains("logo.pdf is PDF 2.0") && e.contains("PDF 1.6"), "{e}");
|
||||
}
|
||||
|
||||
/// A one-page PDF with a black box whose catalog says `/Version /1.7`, as TCPDF writes it.
|
||||
fn catalog_v17(header: &str) -> Vec<u8> {
|
||||
let content = "0 0 0 1 k 0 0 200 200 re f";
|
||||
let mut pdf = format!("{header}\n").into_bytes();
|
||||
let mut offsets = Vec::new();
|
||||
for body in [
|
||||
"<</Type/Catalog/Pages 2 0 R/Version /1.7>>".to_owned(),
|
||||
"<</Type/Pages/Kids[3 0 R]/Count 1>>".to_owned(),
|
||||
"<</Type/Page/Parent 2 0 R/MediaBox[0 0 200 200]/Contents 4 0 R/Resources<<>>>>".to_owned(),
|
||||
format!("<</Length {}>>\nstream\n{content}\nendstream", content.len()),
|
||||
] {
|
||||
offsets.push(pdf.len());
|
||||
pdf.extend_from_slice(format!("{} 0 obj\n{body}\nendobj\n", offsets.len()).as_bytes());
|
||||
}
|
||||
let xref = pdf.len();
|
||||
pdf.extend_from_slice(b"xref\n0 5\n0000000000 65535 f\r\n");
|
||||
for offset in offsets {
|
||||
pdf.extend_from_slice(format!("{offset:010} 00000 n\r\n").as_bytes());
|
||||
}
|
||||
pdf.extend_from_slice(format!("trailer\n<</Size 5/Root 1 0 R>>\nstartxref\n{xref}\n%%EOF\n").as_bytes());
|
||||
pdf
|
||||
}
|
||||
|
||||
/// A placed PDF whose catalog `/Version /1.7` overrides its header failed the PDF/X-4 export
|
||||
/// with "logo.pdf is PDF 1.7", though a 1.7 header alone is relabelled (#907).
|
||||
#[test]
|
||||
fn catalog_version_17_placed_in_pdfx4() {
|
||||
for header in ["%PDF-1.7", "%PDF-1.4"] {
|
||||
let pdf = catalog_v17(header);
|
||||
assert_eq!(hayro_syntax::Pdf::new(pdf.clone()).unwrap().version(), hayro_syntax::PdfVersion::Pdf17);
|
||||
let mut s = page_with(&pdf);
|
||||
let r = s.execute("file.exportPdf", &json!({"standard": "x4"})).unwrap_or_else(|e| panic!("{header}: {e}"));
|
||||
assert!(r["warnings"].to_string().contains("logo.pdf: a PDF 1.7 placed in a PDF 1.6 file"), "{}", r["warnings"]);
|
||||
let out = base64_decode(r["base64"].as_str().unwrap());
|
||||
assert!(out.starts_with(b"%PDF-1.6"));
|
||||
assert_eq!(hayro_syntax::Pdf::new(out).unwrap().version(), hayro_syntax::PdfVersion::Pdf16);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
+136
-34
@@ -29,20 +29,21 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
super::datamerge::refresh_relative_paths(&mut copy, std::path::Path::new(&path));
|
||||
let bytes = to_bytes(©);
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
crate::atomic::write_file(&path, &bytes)?;
|
||||
crate::io::write_file(&path, &bytes).map_err(EngineError::Other)?;
|
||||
Ok(json!({"path": path, "bytes": bytes.len()}))
|
||||
}),
|
||||
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)?;
|
||||
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| {
|
||||
let dir = recovery_dir(s, p)?;
|
||||
let dir = recovery_dir(s, p, FolderAccess::Write)?;
|
||||
Ok(json!({"saved": crate::recovery::save_tracked(s, &dir)?}))
|
||||
}),
|
||||
cmd!(noundo "file.recovery.open", "Recover Documents", [], None, "{dir?} — reopen documents left in the recovery folder (unsaved)", always, |s, p| {
|
||||
let dir = recovery_dir(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, _| {
|
||||
@@ -102,7 +103,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Place…",
|
||||
["File"],
|
||||
Some("Cmd+D"),
|
||||
"{path?|base64?, name?, frame?: id (place into), spread?, x?, y?, width?, pdfPage?: n (1-based, Image Import Options), pdfCrop?: crop|trim|bleed|art|media, layoutPage?: n (IDML / .designcraft: that page's objects as a group)} — places an image (into the selected empty frame if any); 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` — {autoflow?: adds pages with threaded frames until the text fits, removeStyles?, styleMap?: {imported name: document style}, styleConflicts?: useExisting|redefine|autoRename}",
|
||||
"{path?|base64?, name?, frame?: id (place into), spread?, x?, y?, width?, pdfPage?: n (1-based, Image Import Options), pdfCrop?: crop|trim|bleed|art|media, loadCursor?: with no frame to fill and no x/y, an image loads into the place cursor (File › Place), layoutPage?: n (IDML / .designcraft: that page's objects as a group)} — places an image (into the selected empty frame if any); 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` — {autoflow?: adds pages with threaded frames until the text fits, removeStyles?, styleMap?: {imported name: document style}, styleConflicts?: useExisting|redefine|autoRename}",
|
||||
has_doc,
|
||||
file_place
|
||||
),
|
||||
@@ -157,14 +158,30 @@ fn file_sample(s: &mut Session, _p: &Value) -> Result<Value> {
|
||||
Ok(json!({"index": i}))
|
||||
}
|
||||
|
||||
/// An InDesign file that DesignCraft can't open yet, with how to bring it over. Decoding one as a
|
||||
/// DesignCraft document only reported "not a DesignCraft document: expected value at line 1
|
||||
/// column 1" (#21).
|
||||
fn foreign_document(name: &str) -> Option<&'static str> {
|
||||
let ext = std::path::Path::new(name).extension().and_then(|e| e.to_str())?.to_ascii_lowercase();
|
||||
match ext.as_str() {
|
||||
"indd" | "indt" => Some(
|
||||
"InDesign documents (.indd) and templates (.indt) can't be opened yet. In InDesign, choose File ▸ Export… ▸ InDesign Markup (IDML) and open the .idml in DesignCraft.",
|
||||
),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn file_open(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let path = str_param(p, "path").ok_or_else(|| bad("file.open", "missing `path`"))?;
|
||||
if let Some(hint) = foreign_document(path) {
|
||||
return Err(EngineError::Other(format!("{path}: {hint}")));
|
||||
}
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
if path.to_ascii_lowercase().ends_with(".idml") {
|
||||
return super::interchange::open_idml(s, p);
|
||||
}
|
||||
let bytes = std::fs::read(path).map_err(|e| EngineError::Other(format!("{path}: {e}")))?;
|
||||
let bytes = crate::io::read_file(path).map_err(EngineError::Other)?;
|
||||
let mut d = from_bytes(&bytes)?;
|
||||
super::interchange::resolve_packaged_links(&mut d, std::path::Path::new(path).parent());
|
||||
super::datamerge::resolve_sources_on_open(&mut d, Some(std::path::Path::new(path)));
|
||||
@@ -189,7 +206,10 @@ pub(crate) fn load_document_fonts(d: &mut Document, path: &str) -> (Option<Arc<c
|
||||
{
|
||||
use designcraft_fonts::DOCUMENT_FONTS_FOLDER;
|
||||
let Some(folder) = std::path::Path::new(path).parent().map(document_fonts_folder) else { return (None, 0, Vec::new()) };
|
||||
let r = designcraft_fonts::FontDb::global().load_document_fonts(&folder);
|
||||
// A document's folder is the agent's to name (a recovery entry or a book lists paths too):
|
||||
// the fonts crate asks the automation roots about the folder and each font file, so fonts
|
||||
// outside the read root stay unloaded.
|
||||
let r = designcraft_fonts::FontDb::global().load_document_fonts(&folder, &|p| crate::file_access::check_read(p));
|
||||
d.font_scope = r.scope;
|
||||
let scope = (r.scope != 0).then(|| Arc::new(crate::FontScope(r.scope)));
|
||||
(scope, r.faces, r.skipped.into_iter().map(|s| format!("{DOCUMENT_FONTS_FOLDER}: {s}")).collect())
|
||||
@@ -207,18 +227,23 @@ pub(crate) fn load_document_fonts(d: &mut Document, path: &str) -> (Option<Arc<c
|
||||
fn document_fonts_folder(dir: &std::path::Path) -> std::path::PathBuf {
|
||||
use designcraft_fonts::DOCUMENT_FONTS_FOLDER;
|
||||
let exact = dir.join(DOCUMENT_FONTS_FOLDER);
|
||||
if exact.is_dir() {
|
||||
if crate::io::is_dir(&exact) {
|
||||
return exact;
|
||||
}
|
||||
std::fs::read_dir(dir)
|
||||
crate::io::read_dir(dir)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.flatten()
|
||||
.find(|e| e.file_name().to_str().is_some_and(|n| n.eq_ignore_ascii_case(DOCUMENT_FONTS_FOLDER)) && e.path().is_dir())
|
||||
.find(|e| e.file_name().to_str().is_some_and(|n| n.eq_ignore_ascii_case(DOCUMENT_FONTS_FOLDER)) && crate::io::is_dir(e.path()))
|
||||
.map_or(exact, |e| e.path())
|
||||
}
|
||||
|
||||
fn file_open_bytes(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if let Some(name) = str_param(p, "name")
|
||||
&& let Some(hint) = foreign_document(name)
|
||||
{
|
||||
return Err(EngineError::Other(format!("{name}: {hint}")));
|
||||
}
|
||||
let b = base64_decode(str_param(p, "base64").unwrap_or(""));
|
||||
// IDML packages are recognised by their stored `mimetype` first entry.
|
||||
if designcraft_idml::is_idml(&b) {
|
||||
@@ -239,6 +264,8 @@ fn file_save(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
.map(str::to_string)
|
||||
.or_else(|| st.path.clone())
|
||||
.ok_or_else(|| bad("file.save", "missing `path` (document has never been saved)"))?;
|
||||
// Before anything about the document changes: a refused save leaves it as it was.
|
||||
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();
|
||||
super::datamerge::refresh_relative_paths(&mut saved, std::path::Path::new(&path));
|
||||
@@ -246,7 +273,7 @@ fn file_save(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let saved = if paths_changed { Arc::new(saved) } else { st.doc.clone() };
|
||||
let bytes = to_bytes(&saved);
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
crate::atomic::write_file(&path, &bytes)?;
|
||||
crate::io::write_file(&path, &bytes).map_err(EngineError::Other)?;
|
||||
if paths_changed {
|
||||
st.doc = saved;
|
||||
st.revision = st.revision.saturating_add(1);
|
||||
@@ -268,7 +295,7 @@ fn file_place(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
(base64_decode(b), str_param(p, "name").unwrap_or("image").to_string(), None)
|
||||
} else if let Some(path) = str_param(p, "path") {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
let b = std::fs::read(path).map_err(|e| EngineError::Other(format!("{path}: {e}")))?;
|
||||
let b = crate::io::read_file(path).map_err(EngineError::Other)?;
|
||||
#[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());
|
||||
@@ -340,6 +367,11 @@ fn file_place(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let px = p.get("x").and_then(Value::as_f64);
|
||||
let py = p.get("y").and_then(Value::as_f64);
|
||||
let want_w = p.get("width").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) {
|
||||
let mime = designcraft_render::image_mime(&bytes).to_string();
|
||||
let asset = Asset { page: pdf_page, id: AssetId(0), name, mime, link, data: Arc::new(bytes), pixels: Some((pw, ph)) };
|
||||
return load_cursor(s, asset, (nw, nh), crop_box);
|
||||
}
|
||||
s.edit(|d, sel| {
|
||||
let fresh = AssetId(d.alloc());
|
||||
let mime = designcraft_render::image_mime(&bytes).to_string();
|
||||
@@ -435,7 +467,7 @@ pub(crate) fn read_source(p: &Value) -> Result<(Vec<u8>, String, Option<String>)
|
||||
}
|
||||
let path = str_param(p, "path").ok_or_else(|| bad("place", "missing `path` or `base64`"))?;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
let b = std::fs::read(path).map_err(|e| EngineError::Other(format!("{path}: {e}")))?;
|
||||
let b = crate::io::read_file(path).map_err(EngineError::Other)?;
|
||||
#[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());
|
||||
@@ -446,18 +478,32 @@ fn place_load(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (bytes, name, link) = read_source(p)?;
|
||||
let (pw, ph) = designcraft_render::image_size(&bytes).ok_or_else(|| bad("place.load", "unsupported or corrupt image"))?;
|
||||
let natural = 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 { page: 0, id: AssetId(0), name, mime, link, data: Arc::new(bytes), pixels: Some((pw, ph)) };
|
||||
load_cursor(s, asset, natural, None)
|
||||
}
|
||||
|
||||
/// 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), crop: Option<(f64, f64, f64, f64)>) -> Result<Value> {
|
||||
let name = asset.name.clone();
|
||||
let (pw, ph) = asset.pixels.unwrap_or_default();
|
||||
let aid = s.edit(|d, _| {
|
||||
let fresh = AssetId(d.alloc());
|
||||
let mime = designcraft_render::image_mime(&bytes).to_string();
|
||||
Ok(d.add_asset(Asset { page: 0, id: fresh, name: name.clone(), mime, link: link.clone(), data: Arc::new(bytes), pixels: Some((pw, ph)) }))
|
||||
asset.id = AssetId(d.alloc());
|
||||
Ok(d.add_asset(asset))
|
||||
})?;
|
||||
s.loaded = Some((aid, natural));
|
||||
s.loaded = Some(crate::LoadedGraphic { asset: aid, size, crop });
|
||||
s.set_tool("placeGun");
|
||||
Ok(json!({"asset": aid.0, "name": name, "width": pw, "height": ph}))
|
||||
Ok(json!({"asset": aid.0, "name": name, "width": pw, "height": ph, "loaded": true}))
|
||||
}
|
||||
|
||||
fn place_drop(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (aid, (nw, nh)) = s.loaded.ok_or_else(|| bad("place.drop", "nothing loaded in the place cursor"))?;
|
||||
let crate::LoadedGraphic { asset: aid, size: (nw, nh), crop } =
|
||||
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"));
|
||||
}
|
||||
let sr = super::spread_param(p, "place.drop")?;
|
||||
let lid = s.doc()?.active_layer;
|
||||
let frame = super::id_param(p, "frame");
|
||||
@@ -481,12 +527,14 @@ fn place_drop(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
None => {
|
||||
// Drag: fit proportionally into the dragged rect; click: actual size at the point.
|
||||
// The frame shows the crop box when one was chosen.
|
||||
let (bx, by, bw, bh) = crop.unwrap_or((0.0, 0.0, nw, nh));
|
||||
let (frame_r, k) = match rect {
|
||||
Some(r) if r.width() > 2.0 && r.height() > 2.0 => {
|
||||
let k = (r.width() / nw).min(r.height() / nh);
|
||||
(Rect::new(r.x0, r.y0, r.x0 + nw * k, r.y0 + nh * k), k)
|
||||
let k = (r.width() / bw).min(r.height() / bh);
|
||||
(Rect::new(r.x0, r.y0, r.x0 + bw * k, r.y0 + bh * k), k)
|
||||
}
|
||||
_ => (Rect::new(x, y, x + nw, y + nh), 1.0),
|
||||
_ => (Rect::new(x, y, x + bw, y + bh), 1.0),
|
||||
};
|
||||
let id = ItemId(d.alloc());
|
||||
let mut it = Item::new(id, lid, Shape::Rectangle, shapes::rectangle(frame_r));
|
||||
@@ -494,7 +542,7 @@ fn place_drop(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
it.content = Content::Graphic(Graphic {
|
||||
asset: aid,
|
||||
size: (nw, nh),
|
||||
xf: Affine::translate((frame_r.x0, frame_r.y0)) * Affine::scale(k),
|
||||
xf: Affine::translate((frame_r.x0 - bx * k, frame_r.y0 - by * k)) * Affine::scale(k),
|
||||
auto_fit: Default::default(),
|
||||
fit_align: 4,
|
||||
crop: [0.0; 4],
|
||||
@@ -522,7 +570,7 @@ fn snippet_export(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
match str_param(p, "path") {
|
||||
Some(path) => {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
crate::atomic::write_file(path, &bytes)?;
|
||||
crate::io::write_file(path, &bytes).map_err(EngineError::Other)?;
|
||||
Ok(json!({"path": path, "bytes": bytes.len(), "items": d.spreads.first().map(|s| s.items.len()).unwrap_or(0)}))
|
||||
}
|
||||
None => Ok(json!({"base64": base64_encode(&bytes), "bytes": bytes.len()})),
|
||||
@@ -534,7 +582,7 @@ fn snippet_export(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
fn place_layout_page(s: &mut Session, p: &Value, name: &str, bytes: &[u8]) -> Result<Value> {
|
||||
const ID: &str = "file.place";
|
||||
let src = if name.to_lowercase().ends_with(".idml") {
|
||||
designcraft_idml::import_idml(bytes).map_err(|e| bad(ID, e.to_string()))?
|
||||
super::interchange::import_idml_confined(bytes).map_err(|e| bad(ID, e.to_string()))?
|
||||
} else {
|
||||
from_bytes(bytes)?
|
||||
};
|
||||
@@ -612,17 +660,36 @@ pub(crate) fn snippet_place(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
})
|
||||
}
|
||||
|
||||
fn recovery_dir(s: &Session, p: &Value) -> Result<std::path::PathBuf> {
|
||||
/// Which access a recovery command needs to the folder it is given.
|
||||
#[derive(Clone, Copy)]
|
||||
enum FolderAccess {
|
||||
Read,
|
||||
Write,
|
||||
ReadWrite,
|
||||
}
|
||||
|
||||
/// The recovery folder: `dir` when the command names one, else the session's own (set by the
|
||||
/// host application, so not the automation roots' business). A named folder is checked against
|
||||
/// the roots for `access`.
|
||||
fn recovery_dir(s: &Session, p: &Value, access: FolderAccess) -> Result<std::path::PathBuf> {
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
{
|
||||
let _ = (s, p);
|
||||
let _ = (s, p, access);
|
||||
Err(EngineError::Other("no recovery folder on the web".into()))
|
||||
}
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
str_param(p, "dir")
|
||||
.map(std::path::PathBuf::from)
|
||||
.or_else(|| s.recovery_dir.clone())
|
||||
.ok_or_else(|| bad("file.recovery", "no recovery folder (give `dir`)"))
|
||||
{
|
||||
let Some(named) = str_param(p, "dir") else {
|
||||
return s.recovery_dir.clone().ok_or_else(|| bad("file.recovery", "no recovery folder (give `dir`)"));
|
||||
};
|
||||
if matches!(access, FolderAccess::Read | FolderAccess::ReadWrite) {
|
||||
crate::file_access::check_read(named).map_err(EngineError::Other)?;
|
||||
}
|
||||
if matches!(access, FolderAccess::Write | FolderAccess::ReadWrite) {
|
||||
crate::file_access::check_write(named).map_err(EngineError::Other)?;
|
||||
}
|
||||
Ok(std::path::PathBuf::from(named))
|
||||
}
|
||||
}
|
||||
|
||||
fn can_revert(s: &Session) -> std::result::Result<(), String> {
|
||||
@@ -639,10 +706,10 @@ fn file_revert(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
let mut d = if path.to_ascii_lowercase().ends_with(".idml") {
|
||||
let bytes = std::fs::read(&path).map_err(|e| EngineError::Other(format!("{path}: {e}")))?;
|
||||
designcraft_idml::import_idml(&bytes).map_err(|e| EngineError::Other(e.to_string()))?
|
||||
let bytes = crate::io::read_file(&path).map_err(EngineError::Other)?;
|
||||
super::interchange::import_idml_confined(&bytes).map_err(|e| EngineError::Other(e.to_string()))?
|
||||
} else {
|
||||
from_bytes(&std::fs::read(&path).map_err(|e| EngineError::Other(format!("{path}: {e}")))?)?
|
||||
from_bytes(&crate::io::read_file(&path).map_err(EngineError::Other)?)?
|
||||
};
|
||||
// As opened again: the fonts beside it now (unchanged files are shared, not read again).
|
||||
let (fonts, _, _) = load_document_fonts(&mut d, &path);
|
||||
@@ -866,6 +933,21 @@ mod document_fonts_tests {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_indesign_file_says_how_to_bring_it_over() {
|
||||
// The extension decides (any case), not the bytes: no InDesign-made file is needed.
|
||||
let dir = temp_dir("indd");
|
||||
let path = dir.join("Brochure.INDD");
|
||||
std::fs::write(&path, b"not a DesignCraft document").unwrap();
|
||||
let mut s = Session::new();
|
||||
let e = s.execute("file.open", &json!({"path": path.to_string_lossy()})).unwrap_err().to_string();
|
||||
assert!(e.contains("InDesign Markup (IDML)") && !e.contains("expected value"), "{e}");
|
||||
let e = s.execute("file.openBytes", &json!({"name": "Brochure.indt", "base64": ""})).unwrap_err().to_string();
|
||||
assert!(e.contains("InDesign Markup (IDML)"), "{e}");
|
||||
assert!(s.doc().is_err(), "nothing was opened");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_document_fonts_folder_is_found_whatever_its_case() {
|
||||
const FAMILY: &str = "DocFont Case Test";
|
||||
@@ -989,4 +1071,24 @@ mod document_fonts_tests {
|
||||
assert!(glyph_faces(&s).iter().all(|(_, f)| f.family == FAMILY));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bold_and_italic_link_the_document_fonts_styles() {
|
||||
const FAMILY: &str = "DocFont Linked";
|
||||
let dir = temp_dir("linked");
|
||||
std::fs::write(dir.join(DOCUMENT_FONTS_FOLDER).join("linked.ttf"), font_with(FAMILY, &['H', 'e', 'l', 'o']).unwrap()).unwrap();
|
||||
let path = dir.join("Linked.designcraft");
|
||||
write_document(&path, FAMILY);
|
||||
|
||||
let mut s = Session::new();
|
||||
open(&mut s, &path);
|
||||
let sid = *s.doc().unwrap().doc.stories.keys().next().unwrap();
|
||||
s.execute("text.select", &json!({"story": sid.0, "anchor": 0, "focus": 0})).unwrap();
|
||||
// The family is the document's alone: its Regular is the style without bold or italic.
|
||||
let r = s.execute("type.bold", &json!({"on": false})).unwrap();
|
||||
assert_eq!(r["fontStyle"], "Regular", "{r}");
|
||||
let r = s.execute("type.italic", &json!({"on": false})).unwrap();
|
||||
assert_eq!(r["fontStyle"], "Regular", "{r}");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
}
|
||||
|
||||
+880
-41
File diff suppressed because it is too large
Load Diff
@@ -73,7 +73,7 @@ fn list(d: &Document) -> Vec<Value> {
|
||||
.into_iter()
|
||||
.map(|((family, style), n)| {
|
||||
let missing = !db.has_family(&family);
|
||||
let style_missing = !missing && !db.styles(&family).iter().any(|s| s.eq_ignore_ascii_case(&style));
|
||||
let style_missing = !missing && !db.styles(&family).iter().any(|s| designcraft_fonts::same_style(s, &style));
|
||||
let source = (!missing).then(|| match db.face(&family, &style).source {
|
||||
FontSource::Bundled => "bundled",
|
||||
FontSource::Installed(_) => "installed",
|
||||
@@ -225,4 +225,22 @@ mod tests {
|
||||
assert_eq!((&l[0]["family"], &l[0]["missing"]), (&json!("Nope (OTF)"), &json!(true)), "{l}");
|
||||
assert!(kinds(&mut s).iter().any(|k| k == "missingFont"));
|
||||
}
|
||||
|
||||
/// A style name that differs only in spacing (Montilla Design's file sets `Regular ` with a
|
||||
/// trailing space) is the face the text is drawn in, not a missing style.
|
||||
#[test]
|
||||
fn a_style_with_extra_spacing_is_not_missing() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
let r = s.execute("frame.create", &json!({"rect": [72, 72, 400, 300], "content": "text", "text": "Text"})).unwrap();
|
||||
let sid = s.doc().unwrap().doc.item(designcraft_doc::ItemId(r["id"].as_u64().unwrap())).unwrap().text_frame().unwrap().story;
|
||||
s.execute("text.select", &json!({"story": sid.0, "anchor": 0, "focus": 4})).unwrap();
|
||||
s.execute("type.char", &json!({"fontFamily": "Source Serif 4", "fontStyle": "Regular "})).unwrap();
|
||||
let l = s.execute("font.list", &json!({})).unwrap();
|
||||
let entry = l.as_array().unwrap().iter().find(|f| f["style"] == "Regular ").unwrap();
|
||||
assert_eq!((&entry["missing"], &entry["styleMissing"]), (&json!(false), &json!(false)), "{l}");
|
||||
s.execute("type.char", &json!({"fontFamily": "Source Serif 4", "fontStyle": "Nope"})).unwrap();
|
||||
let l = s.execute("font.list", &json!({})).unwrap();
|
||||
assert_eq!(l[0]["styleMissing"], json!(true), "{l}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -21,7 +21,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"New Guide",
|
||||
[],
|
||||
None,
|
||||
"{orientation: horizontal|vertical, position (spread coordinate), spread?, page? (index in the spread; default: the page under `at` or the position), at? (the other coordinate), spreadGuide?: bool} → {page, index}",
|
||||
"{orientation: horizontal|vertical, position (spread coordinate), spread?, page? (index in the spread; default: the page under `at` or the position), at? (the other coordinate), spreadGuide?: bool, liquid?: bool (a liquid guide, as the Page tool draws from the rulers)} → {page, index}",
|
||||
has_doc,
|
||||
add
|
||||
),
|
||||
@@ -98,6 +98,7 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let pos = finite_number(p, "position", "guide.add")?.ok_or_else(|| bad("guide.add", "missing position"))?;
|
||||
let r = super::spread_param(p, "guide.add")?;
|
||||
let spread_guide = p.get("spreadGuide").and_then(Value::as_bool).unwrap_or(false);
|
||||
let liquid = p.get("liquid").and_then(Value::as_bool).unwrap_or(false);
|
||||
let d = &s.doc()?.doc;
|
||||
let pi = match optional_usize(p, "page", "guide.add")? {
|
||||
Some(pi) => pi,
|
||||
@@ -114,7 +115,14 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
s.edit(|d, _| {
|
||||
let sp = d.spread_mut(r).ok_or_else(|| bad("guide.add", "no such spread"))?;
|
||||
let pg = sp.pages.get_mut(pi).ok_or_else(|| bad("guide.add", "no such page"))?;
|
||||
pg.guides.push(Guide { orientation: o, position: pos, spread: spread_guide, locked: false, layer: Some(layer), liquid: false });
|
||||
pg.guides.push(Guide {
|
||||
orientation: o,
|
||||
position: pos,
|
||||
spread: spread_guide,
|
||||
locked: false,
|
||||
layer: Some(layer),
|
||||
liquid: liquid && !spread_guide,
|
||||
});
|
||||
Ok(json!({"page": pi, "index": pg.guides.len() - 1}))
|
||||
})
|
||||
}
|
||||
|
||||
@@ -25,13 +25,19 @@ fn export_idml(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
match str_param(p, "path") {
|
||||
Some(path) => {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
crate::atomic::write_file(path, &bytes)?;
|
||||
crate::io::write_file(path, &bytes).map_err(EngineError::Other)?;
|
||||
Ok(json!({"path": path, "bytes": bytes.len()}))
|
||||
}
|
||||
None => Ok(json!({"base64": base64_encode(&bytes), "bytes": bytes.len()})),
|
||||
}
|
||||
}
|
||||
|
||||
/// [`designcraft_idml::import_idml`] with the linked images read through [`crate::io`], so the
|
||||
/// automation read root applies to the paths the package names.
|
||||
pub(crate) fn import_idml_confined(bytes: &[u8]) -> designcraft_idml::Result<Document> {
|
||||
designcraft_idml::import_idml_with(bytes, &|path| crate::io::read_file(path).ok())
|
||||
}
|
||||
|
||||
/// Import IDML bytes; `dir` is the folder the package came from (for relative link lookup).
|
||||
pub fn import(bytes: &[u8], dir: Option<&std::path::Path>) -> Result<Document> {
|
||||
import_report(bytes, dir).map(|(document, _)| document)
|
||||
@@ -112,10 +118,10 @@ pub(crate) fn resolve_packaged_links(document: &mut Document, dir: Option<&std::
|
||||
let Some(dir) = dir else { return };
|
||||
for asset in document.assets.values_mut() {
|
||||
let Some(link) = asset.link.as_deref() else { continue };
|
||||
if link.len() > MAX_LINK_PATH_BYTES || std::path::Path::new(link).is_file() {
|
||||
if link.len() > MAX_LINK_PATH_BYTES || crate::io::is_file(link) {
|
||||
continue;
|
||||
}
|
||||
let Some(path) = packaged_link_candidates(link, Some(dir)).into_iter().find(|p| p.is_file()) else { continue };
|
||||
let Some(path) = packaged_link_candidates(link, Some(dir)).into_iter().find(|p| crate::io::is_file(p)) else { continue };
|
||||
// Preserve ordinary Windows paths rather than canonicalizing to a verbatim URI.
|
||||
let path = std::path::absolute(&path).unwrap_or(path);
|
||||
std::sync::Arc::make_mut(asset).link = Some(path.to_string_lossy().into_owned());
|
||||
@@ -125,7 +131,7 @@ pub(crate) fn resolve_packaged_links(document: &mut Document, dir: Option<&std::
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn read_packaged_link(link: &str, dir: Option<&std::path::Path>) -> Option<(String, Vec<u8>)> {
|
||||
for path in packaged_link_candidates(link, dir) {
|
||||
if let Ok(bytes) = std::fs::read(&path) {
|
||||
if let Ok(bytes) = crate::io::read_file(&path) {
|
||||
// Keep ordinary Windows drive/UNC syntax for IDML URI export; canonicalize
|
||||
// would introduce a verbatim prefix that is not an IDML file URI.
|
||||
let path = std::path::absolute(&path).unwrap_or(path);
|
||||
@@ -140,7 +146,7 @@ pub(crate) fn open_idml(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
(base64_decode(b), None, str_param(p, "name").map(|n| n.trim_end_matches(".idml").to_string()))
|
||||
} else if let Some(path) = str_param(p, "path") {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
let b = std::fs::read(path).map_err(|e| EngineError::Other(format!("{path}: {e}")))?;
|
||||
let b = crate::io::read_file(path).map_err(EngineError::Other)?;
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
let b: Vec<u8> = Vec::new();
|
||||
let pp = std::path::Path::new(path);
|
||||
|
||||
+275
-21
@@ -88,7 +88,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
let count = p.get("count").and_then(Value::as_u64).unwrap_or(1).clamp(1, 9999) as usize;
|
||||
let st = s.doc()?;
|
||||
let n = st.doc.page_count();
|
||||
let after = p.get("after").and_then(Value::as_u64).map(|v| v as usize).unwrap_or(n - 1);
|
||||
let after = p.get("after").and_then(Value::as_u64).map(|v| usize::try_from(v).unwrap_or(usize::MAX)).unwrap_or(n.saturating_sub(1));
|
||||
let parent = parent_ref(&st.doc, p.get("parent")).unwrap_or_else(|| st.doc.parents.first().map(|x| x.id));
|
||||
s.edit(|d, _| {
|
||||
let ids = d.insert_pages(Some(after), count, parent)?;
|
||||
@@ -135,21 +135,63 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
ok()
|
||||
})
|
||||
}),
|
||||
cmd!("layout.pages.duplicateSpread", "Duplicate Spread", ["Layout", "Pages"], None, "{spread}", has_doc, |s, p| {
|
||||
let si = p.get("spread").and_then(Value::as_u64).unwrap_or(0) as usize;
|
||||
s.edit(|d, _| {
|
||||
let sp = d.spreads.get(si).cloned().ok_or_else(|| bad("layout.pages.duplicateSpread", "no such spread"))?;
|
||||
let after = d.first_page_of_spread(si) + sp.pages.len() - 1;
|
||||
let parent = sp.pages.first().and_then(|p| p.parent);
|
||||
d.insert_pages(Some(after), sp.pages.len(), parent)?;
|
||||
// Copy items onto the new spread(s) at the same positions.
|
||||
let src = d.clone();
|
||||
let ids: Vec<_> = sp.items.iter().map(|i| i.id).collect();
|
||||
let (nsi, _) = d.page_loc(after + 1).ok_or_else(|| bad("layout.pages.duplicateSpread", "insert failed"))?;
|
||||
super::object::duplicate_from(d, &src, &ids, designcraft_doc::SpreadRef::Doc(nsi), designcraft_geom::Vec2::ZERO)?;
|
||||
ok()
|
||||
})
|
||||
}),
|
||||
cmd!(
|
||||
"layout.pages.duplicateSpread",
|
||||
"Duplicate Spread",
|
||||
["Layout", "Pages"],
|
||||
None,
|
||||
"{spread, atEnd?: bool (Duplicate Spread at End of Document; the Pages panel's New Page button takes a dropped page there), to?: page index the copied pages move to, in the same undo step (the Pages panel's Alt-drag)} → {page: the copy's first page (0-based)} — the spread's pages (size, margins, columns, guides, liquid rule) and items",
|
||||
has_doc,
|
||||
|s, p| {
|
||||
let si = p.get("spread").and_then(Value::as_u64).unwrap_or(0) as usize;
|
||||
let at_end = p.get("atEnd").and_then(Value::as_bool).unwrap_or(false);
|
||||
let to = p.get("to").and_then(Value::as_u64).map(|t| t as usize);
|
||||
s.edit(|d, _| {
|
||||
let sp = d.spreads.get(si).cloned().ok_or_else(|| bad("layout.pages.duplicateSpread", "no such spread"))?;
|
||||
// The copies land at `to`..`to + n` of the document with them in it.
|
||||
if to.is_some_and(|t| t > d.page_count()) {
|
||||
return Err(bad("layout.pages.duplicateSpread", "no such page"));
|
||||
}
|
||||
let after = if at_end { d.page_count() - 1 } else { d.first_page_of_spread(si) + sp.pages.len() - 1 };
|
||||
let parent = sp.pages.first().and_then(|p| p.parent);
|
||||
d.insert_pages(Some(after), sp.pages.len(), parent)?;
|
||||
// The copies are the pages they copy: size, margins, columns, guides, liquid rule.
|
||||
for (k, src) in sp.pages.iter().enumerate() {
|
||||
let Some((nsi, npi)) = d.page_loc(after + 1 + k) else { continue };
|
||||
let nsp = std::sync::Arc::make_mut(&mut d.spreads[nsi]);
|
||||
let pg = &mut nsp.pages[npi];
|
||||
let dx = pg.x - src.x;
|
||||
(pg.width, pg.height, pg.margins, pg.columns, pg.liquid) =
|
||||
(src.width, src.height, src.margins, src.columns.clone(), src.liquid);
|
||||
pg.guides = src.guides.clone();
|
||||
for g in pg.guides.iter_mut().filter(|g| g.orientation == designcraft_doc::Orientation::Vertical) {
|
||||
g.position += dx;
|
||||
}
|
||||
nsp.relayout();
|
||||
}
|
||||
// Copy items onto the new spread(s) at the same positions.
|
||||
let src = d.clone();
|
||||
let ids: Vec<_> = sp.items.iter().map(|i| i.id).collect();
|
||||
let (nsi, _) = d.page_loc(after + 1).ok_or_else(|| bad("layout.pages.duplicateSpread", "insert failed"))?;
|
||||
super::object::duplicate_from(d, &src, &ids, designcraft_doc::SpreadRef::Doc(nsi), designcraft_geom::Vec2::ZERO)?;
|
||||
let first = after + 1;
|
||||
let Some(to) = to else { return Ok(json!({"page": first})) };
|
||||
// Moving a page shifts the ones between; order the moves so each copy keeps
|
||||
// its place among the others.
|
||||
let n = sp.pages.len();
|
||||
if first < to {
|
||||
for k in (0..n).rev() {
|
||||
d.move_page(first + k, to + k)?;
|
||||
}
|
||||
} else {
|
||||
for k in 0..n {
|
||||
d.move_page(first + k, to + k)?;
|
||||
}
|
||||
}
|
||||
Ok(json!({"page": to}))
|
||||
})
|
||||
}
|
||||
),
|
||||
cmd!(
|
||||
"layout.pages.applyParent",
|
||||
"Apply Parent to Pages…",
|
||||
@@ -376,10 +418,48 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Page Size",
|
||||
[],
|
||||
None,
|
||||
"{pages: [1-based page numbers], width?, height?, preset?: \"A4\"|\"Letter\"|…} — pages of their own size (Page tool); objects on the pages keep their place on them",
|
||||
"{pages: [1-based page numbers], width?, height?, preset?: \"A4\"|\"Letter\"|…, anchor?: 0–8 (reference point that stays put, row-major from the top-left; default 0)} — pages of their own size (Page tool); objects keep their place relative to the anchor, or follow the page's liquid rule",
|
||||
has_doc,
|
||||
page_size
|
||||
),
|
||||
cmd!(
|
||||
"layout.pageOptions",
|
||||
"Page Options",
|
||||
[],
|
||||
None,
|
||||
"{pages: [1-based], showParentOverlay?: bool} — Page tool options (Show Parent Page Overlay: the parent page's size drawn over the page)",
|
||||
has_doc,
|
||||
page_options
|
||||
),
|
||||
cmd!(
|
||||
noundo "layout.selectPage",
|
||||
"Select Page",
|
||||
[],
|
||||
None,
|
||||
"{page: 1-based | null, ids?: [item ids] (objects selected with it: the Page tool on an object-based page)} — the page the Page tool selects (its handles, the Control panel)",
|
||||
has_doc,
|
||||
|s, p| {
|
||||
let n = s.doc()?.doc.page_count();
|
||||
let page = match p.get("page") {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(v) => Some(v.as_u64().filter(|v| *v >= 1 && *v as usize <= n).ok_or_else(|| bad("layout.selectPage", format!("`page`: 1–{n}")))? as usize - 1),
|
||||
};
|
||||
let ids: Vec<designcraft_doc::ItemId> = {
|
||||
let d = &s.doc()?.doc;
|
||||
p.get("ids")
|
||||
.and_then(Value::as_array)
|
||||
.map(|a| a.iter().filter_map(Value::as_u64).map(designcraft_doc::ItemId).filter(|id| d.item(*id).is_some()).collect())
|
||||
.unwrap_or_default()
|
||||
};
|
||||
let st = s.doc_mut()?;
|
||||
if page.is_some() {
|
||||
st.selection = designcraft_doc::Selection::items(ids);
|
||||
}
|
||||
st.selection.page = page;
|
||||
st.revision += 1;
|
||||
Ok(json!({"page": page.map(|p| p + 1)}))
|
||||
}
|
||||
),
|
||||
cmd!(
|
||||
"layout.section",
|
||||
"Numbering & Section Options…",
|
||||
@@ -396,11 +476,16 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
let start = page - 1;
|
||||
let p = p.clone();
|
||||
s.edit(|d, _| {
|
||||
// The settings the command does not name stay as the section was: read it
|
||||
// before the list is rebuilt (#717).
|
||||
let existing = d.sections.iter().find(|x| x.start == start).cloned();
|
||||
d.sections.retain(|x| x.start != start || start == 0);
|
||||
if p.get("remove").and_then(Value::as_bool).unwrap_or(false) && start != 0 {
|
||||
// The pages after it follow the previous section's numbers again.
|
||||
d.repaginate();
|
||||
return ok();
|
||||
}
|
||||
let mut sec = d.sections.iter().find(|x| x.start == start).cloned().unwrap_or(designcraft_doc::Section {
|
||||
let mut sec = existing.unwrap_or(designcraft_doc::Section {
|
||||
start,
|
||||
start_number: None,
|
||||
style: Default::default(),
|
||||
@@ -428,6 +513,8 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
d.sections.retain(|x| x.start != start);
|
||||
d.sections.push(sec);
|
||||
d.sections.sort_by_key(|x| x.start);
|
||||
// Facing pages take their sides from their numbers: odd on the right.
|
||||
d.repaginate();
|
||||
Ok(json!({"names": (0..d.page_count()).map(|i| d.page_name(i)).collect::<Vec<_>>()}))
|
||||
})
|
||||
}
|
||||
@@ -640,8 +727,32 @@ fn page_size(s: &mut crate::Session, p: &Value) -> Result<Value> {
|
||||
w = Some(pr.width);
|
||||
h = Some(pr.height);
|
||||
}
|
||||
let anchor = match p.get("anchor") {
|
||||
None | Some(Value::Null) => 0,
|
||||
Some(v) => v.as_u64().filter(|a| *a <= 8).ok_or_else(|| bad("layout.pageSize", "`anchor`: 0–8"))? as usize,
|
||||
};
|
||||
s.edit(|d, _| {
|
||||
resize_pages(d, &pages, w, h);
|
||||
resize_pages_from(d, &pages, w, h, anchor);
|
||||
Ok(json!({"pages": pages.len()}))
|
||||
})
|
||||
}
|
||||
|
||||
fn page_options(s: &mut crate::Session, p: &Value) -> Result<Value> {
|
||||
let pages: Vec<usize> =
|
||||
p.get("pages").and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_u64).map(|n| n as usize).collect()).unwrap_or_default();
|
||||
let n = s.doc()?.doc.page_count();
|
||||
if pages.is_empty() || pages.iter().any(|x| *x == 0 || *x > n) {
|
||||
return Err(bad("layout.pageOptions", "give `pages` (1-based)"));
|
||||
}
|
||||
let overlay = p.get("showParentOverlay").and_then(Value::as_bool);
|
||||
s.edit(|d, _| {
|
||||
for page in &pages {
|
||||
let Some((si, pi)) = d.page_loc(page - 1) else { continue };
|
||||
let pg = &mut std::sync::Arc::make_mut(&mut d.spreads[si]).pages[pi];
|
||||
if let Some(v) = overlay {
|
||||
pg.show_parent_overlay = v;
|
||||
}
|
||||
}
|
||||
Ok(json!({"pages": pages.len()}))
|
||||
})
|
||||
}
|
||||
@@ -649,14 +760,35 @@ fn page_size(s: &mut crate::Session, p: &Value) -> Result<Value> {
|
||||
/// Give `pages` (1-based) their own size. Objects stay on their page; pages with a liquid rule
|
||||
/// re-flow their objects by it.
|
||||
pub(crate) fn resize_pages(d: &mut designcraft_doc::Document, pages: &[usize], w: Option<f64>, h: Option<f64>) {
|
||||
resize_pages_from(d, pages, w, h, 0);
|
||||
}
|
||||
|
||||
/// [`resize_pages`] keeping reference point `anchor` (0–8, row-major from the top-left) in place:
|
||||
/// the page grows away from it, so objects keep their place relative to it.
|
||||
pub(crate) fn resize_pages_from(d: &mut designcraft_doc::Document, pages: &[usize], w: Option<f64>, h: Option<f64>, anchor: usize) {
|
||||
let (fx, fy) = ((anchor % 3) as f64 / 2.0, (anchor / 3).min(2) as f64 / 2.0);
|
||||
{
|
||||
for page in pages {
|
||||
let Some((si, pi)) = d.page_loc(page - 1) else { continue };
|
||||
let sp = std::sync::Arc::make_mut(&mut d.spreads[si]);
|
||||
let old: Vec<f64> = sp.pages.iter().map(|x| x.x).collect();
|
||||
let old_bounds = sp.pages[pi].bounds();
|
||||
// The page's own objects (outer pages take the pasteboard beside them).
|
||||
let last = sp.pages.len() - 1;
|
||||
let (lo, hi) = (if pi == 0 { f64::NEG_INFINITY } else { old_bounds.x0 }, if pi == last { f64::INFINITY } else { old_bounds.x1 });
|
||||
let own: Vec<usize> = sp
|
||||
.items
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, it)| {
|
||||
let c = it.bounds().center().x;
|
||||
c >= lo && c < hi
|
||||
})
|
||||
.map(|(i, _)| i)
|
||||
.collect();
|
||||
let pg = &mut sp.pages[pi];
|
||||
let dw = w.map_or(0.0, |w| w.max(1.0) - pg.width);
|
||||
let dh = h.map_or(0.0, |h| h.max(1.0) - pg.height);
|
||||
if let Some(w) = w {
|
||||
pg.width = w.max(1.0);
|
||||
}
|
||||
@@ -693,8 +825,22 @@ pub(crate) fn resize_pages(d: &mut designcraft_doc::Document, pages: &[usize], w
|
||||
}
|
||||
}
|
||||
}
|
||||
// Liquid rules: objects were carried along with the page's left edge.
|
||||
let moved = old_bounds + designcraft_geom::Vec2::new(new[pi] - old[pi], 0.0);
|
||||
// Growing away from the anchor: the page's objects and guides keep their place
|
||||
// relative to it.
|
||||
let shift = designcraft_geom::Vec2::new(fx * dw, fy * dh);
|
||||
if shift != designcraft_geom::Vec2::ZERO {
|
||||
for i in &own {
|
||||
if let Some(it) = sp.items.get_mut(*i) {
|
||||
let it = std::sync::Arc::make_mut(it);
|
||||
it.xf = designcraft_geom::Affine::translate(shift) * it.xf;
|
||||
}
|
||||
}
|
||||
for g in &mut sp.pages[pi].guides {
|
||||
g.position += if g.orientation == designcraft_doc::Orientation::Vertical { shift.x } else { shift.y };
|
||||
}
|
||||
}
|
||||
// Liquid rules: objects were carried along with the page's left edge (and the anchor).
|
||||
let moved = old_bounds + designcraft_geom::Vec2::new(new[pi] - old[pi], 0.0) + shift;
|
||||
super::liquid::apply(d, designcraft_doc::SpreadRef::Doc(si), pi, moved);
|
||||
}
|
||||
}
|
||||
@@ -895,6 +1041,28 @@ mod page_numbering_view_tests {
|
||||
assert_eq!(s.resolve_page("1"), Some(0));
|
||||
assert_eq!(s.resolve_page("9"), None);
|
||||
}
|
||||
|
||||
/// `layout.section` edits one named setting; the others stay as the section was (#717).
|
||||
#[test]
|
||||
fn updating_a_section_keeps_settings_the_command_does_not_name() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"pages": 4})).unwrap();
|
||||
s.execute(
|
||||
"layout.section",
|
||||
&json!({"page": 2, "startNumber": 1, "style": "lowerRoman", "prefix": "A-", "includePrefix": true, "marker": "First"}),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(s.page_label(1), "A-i");
|
||||
s.execute("layout.section", &json!({"page": 2, "marker": "Second"})).unwrap();
|
||||
let d = s.doc().unwrap().doc.clone();
|
||||
let sec = d.sections.iter().find(|x| x.start == 1).expect("the page-2 section is still the only one there");
|
||||
assert_eq!(sec.marker, "Second");
|
||||
assert_eq!(sec.start_number, Some(1), "startNumber is kept");
|
||||
assert_eq!(sec.style, designcraft_doc::NumberStyle::LowerRoman, "style is kept");
|
||||
assert_eq!(sec.prefix, "A-", "prefix is kept");
|
||||
assert!(sec.include_prefix, "includePrefix is kept");
|
||||
assert_eq!(s.page_label(1), "A-i");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -921,3 +1089,89 @@ mod adjust_tests {
|
||||
assert_eq!(b, b2);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod section_side_tests {
|
||||
use serde_json::json;
|
||||
|
||||
use crate::Session;
|
||||
|
||||
/// Each spread's pages as (name, side), side `L`, `R` or `S`.
|
||||
fn spreads(s: &Session) -> Vec<Vec<(String, char)>> {
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let mut abs = 0;
|
||||
d.spreads
|
||||
.iter()
|
||||
.map(|sp| {
|
||||
sp.pages
|
||||
.iter()
|
||||
.map(|p| {
|
||||
let side = match p.side {
|
||||
designcraft_doc::PageSide::Left => 'L',
|
||||
designcraft_doc::PageSide::Right => 'R',
|
||||
designcraft_doc::PageSide::Single => 'S',
|
||||
};
|
||||
abs += 1;
|
||||
(d.page_name(abs - 1), side)
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn pages(v: &[&[(&str, char)]]) -> Vec<Vec<(String, char)>> {
|
||||
v.iter().map(|sp| sp.iter().map(|(n, c)| (n.to_string(), *c)).collect()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_section_starting_at_one_on_a_left_page_moves_it_to_the_right() {
|
||||
// Chris Nielsen's "Numbering Page Sections" (7:03): with the spread 8–9 selected, the
|
||||
// section starts on page 8, which becomes a lone right-hand page 1; the pages after it
|
||||
// shuffle and their objects go with them. Undo puts them back.
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 612, "height": 792, "facingPages": true, "pages": 10})).unwrap();
|
||||
let id = s.execute("frame.create", &json!({"spread": 4, "rect": [700, 100, 800, 200], "content": "text", "text": "TOPIC"})).unwrap()["id"]
|
||||
.as_u64()
|
||||
.unwrap();
|
||||
let page_of = |s: &Session| {
|
||||
let d = &s.doc().unwrap().doc;
|
||||
d.page_of_item(designcraft_doc::ItemId(id)).unwrap()
|
||||
};
|
||||
assert_eq!(page_of(&s), 8, "page 9, the right page of the spread 8–9");
|
||||
let before = spreads(&s);
|
||||
s.execute("layout.section", &json!({"page": 8, "startNumber": 1})).unwrap();
|
||||
assert_eq!(
|
||||
spreads(&s),
|
||||
pages(&[
|
||||
&[("1", 'R')],
|
||||
&[("2", 'L'), ("3", 'R')],
|
||||
&[("4", 'L'), ("5", 'R')],
|
||||
&[("6", 'L'), ("7", 'R')],
|
||||
&[("1", 'R')],
|
||||
&[("2", 'L'), ("3", 'R')],
|
||||
])
|
||||
);
|
||||
assert_eq!(page_of(&s), 8, "the object stays on its page, now the left page of a spread");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(spreads(&s), before);
|
||||
// On a right page (the video's page 9) nothing moves; an even start on a right page moves
|
||||
// it to the left.
|
||||
s.execute("layout.section", &json!({"page": 9, "startNumber": 1})).unwrap();
|
||||
assert_eq!(spreads(&s)[4], pages(&[&[("8", 'L'), ("1", 'R')]])[0]);
|
||||
s.execute("layout.section", &json!({"page": 9, "startNumber": 2})).unwrap();
|
||||
assert_eq!(spreads(&s)[4..], pages(&[&[("8", 'L')], &[("2", 'L'), ("3", 'R')]]));
|
||||
// Removing the section numbers the pages on from 9 again.
|
||||
s.execute("layout.section", &json!({"page": 9, "remove": true})).unwrap();
|
||||
assert_eq!(spreads(&s), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn single_sided_documents_keep_their_pages() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"facingPages": false, "pages": 4})).unwrap();
|
||||
s.execute("layout.section", &json!({"page": 2, "startNumber": 1})).unwrap();
|
||||
let sp = spreads(&s);
|
||||
assert_eq!(sp.len(), 4);
|
||||
assert!(sp.iter().all(|p| p.len() == 1 && p[0].1 == 'S'), "{sp:?}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -29,7 +29,7 @@ impl Library {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if let Some(p) = &self.path {
|
||||
let bytes = serde_json::to_vec_pretty(self).map_err(|e| crate::EngineError::Other(e.to_string()))?;
|
||||
crate::atomic::write_file(p, &bytes)?;
|
||||
crate::io::write_file(p, &bytes).map_err(crate::EngineError::Other)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -56,7 +56,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
(Some(j), _) => (j.to_string(), None),
|
||||
(None, Some(path)) => {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
let t = std::fs::read_to_string(path).map_err(|e| crate::EngineError::Other(format!("{path}: {e}")))?;
|
||||
let t = crate::io::read_to_string(path).map_err(crate::EngineError::Other)?;
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
let t = String::new();
|
||||
(t, Some(path.to_string()))
|
||||
|
||||
@@ -93,11 +93,11 @@ pub fn status(a: &designcraft_doc::Asset) -> &'static str {
|
||||
let Some(path) = &a.link else { return "embedded" };
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
match std::fs::metadata(path) {
|
||||
match crate::io::metadata(path) {
|
||||
Err(_) => "missing",
|
||||
Ok(m) if m.len() as usize != a.data.len() => "modified",
|
||||
// Same size: compare the bytes (cheap for the sizes involved, and exact).
|
||||
Ok(_) => match std::fs::read(path) {
|
||||
Ok(_) => match crate::io::read_file(path) {
|
||||
Ok(b) if b == *a.data => "ok",
|
||||
Ok(_) => "modified",
|
||||
Err(_) => "missing",
|
||||
@@ -145,7 +145,7 @@ fn list(d: &Document) -> Vec<Value> {
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn reload(path: &str) -> Result<(Vec<u8>, (u32, u32))> {
|
||||
let b = std::fs::read(path).map_err(|e| EngineError::Other(format!("{path}: {e}")))?;
|
||||
let b = crate::io::read_file(path).map_err(EngineError::Other)?;
|
||||
let px = designcraft_render::image_size(&b).ok_or_else(|| bad("links", format!("{path}: unsupported or corrupt image")))?;
|
||||
Ok((b, px))
|
||||
}
|
||||
@@ -174,6 +174,10 @@ fn relink(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
fn relink_folder(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let dir = str_param(p, "dir").map(std::path::PathBuf::from);
|
||||
if let Some(dir) = &dir {
|
||||
// Refused outright: candidates outside the automation read root would only look missing.
|
||||
crate::file_access::check_read(dir).map_err(EngineError::Other)?;
|
||||
}
|
||||
let ext = str_param(p, "extension").map(|e| e.trim_start_matches('.').to_string());
|
||||
if dir.is_none() && ext.is_none() {
|
||||
return Err(bad("links.relinkFolder", "give `dir` and/or `extension`"));
|
||||
@@ -194,7 +198,7 @@ fn relink_folder(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let folder = dir.clone().or_else(|| old.parent().map(|p| p.to_path_buf())).unwrap_or_default();
|
||||
let cand = folder.join(&name);
|
||||
if cand.exists() {
|
||||
if crate::io::exists(&cand) {
|
||||
todo.push((a.id, cand));
|
||||
} else {
|
||||
not_found.push(name.to_string_lossy().to_string());
|
||||
@@ -427,4 +431,46 @@ mod shared_asset_tests {
|
||||
assert_eq!((g.asset, g.crop), (same, [1.0; 4]));
|
||||
assert_eq!(dst.assets.len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pasted_missing_graphic_does_not_show_an_unrelated_target_asset() {
|
||||
use designcraft_doc::build::NewDocument;
|
||||
use designcraft_doc::{Asset, Graphic, Item, ItemId, Shape, SpreadRef};
|
||||
let mut src = Document::new(&NewDocument::default());
|
||||
let mut dst = Document::new(&NewDocument::default());
|
||||
// The source graphic points at an asset the source does not have; the target uses that id for another image.
|
||||
let missing = AssetId(src.alloc());
|
||||
dst.assets.insert(
|
||||
missing,
|
||||
Arc::new(Asset {
|
||||
id: missing,
|
||||
name: "p.png".into(),
|
||||
mime: "image/png".into(),
|
||||
link: None,
|
||||
data: Arc::new(png(8, 4)),
|
||||
pixels: None,
|
||||
page: 0,
|
||||
}),
|
||||
);
|
||||
let iid = ItemId(src.alloc());
|
||||
let mut it = Item::new(
|
||||
iid,
|
||||
src.default_layer(),
|
||||
Shape::Rectangle,
|
||||
designcraft_geom::shapes::rectangle(designcraft_geom::Rect::new(0.0, 0.0, 9.0, 9.0)),
|
||||
);
|
||||
it.content = Content::Graphic(Graphic {
|
||||
asset: missing,
|
||||
size: (4.0, 4.0),
|
||||
xf: designcraft_geom::Affine::IDENTITY,
|
||||
auto_fit: Default::default(),
|
||||
fit_align: 4,
|
||||
crop: [1.0; 4],
|
||||
});
|
||||
src.insert_item(SpreadRef::Doc(0), it, None).unwrap();
|
||||
let ids = super::super::object::duplicate_from(&mut dst, &src, &[iid], SpreadRef::Doc(0), designcraft_geom::Vec2::ZERO).unwrap();
|
||||
let g = dst.item(ids[0]).and_then(|i| i.graphic()).unwrap();
|
||||
assert_ne!(g.asset, missing);
|
||||
assert!(!dst.assets.contains_key(&g.asset));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -35,7 +35,7 @@ fn axis(lo: f64, hi: f64, o: (f64, f64), n: (f64, f64), pin_lo: bool, pin_hi: bo
|
||||
fn target(rule: LiquidRule, b: Rect, old: Rect, new: Rect, liquid: Option<ObjectLiquid>, vguides: &[f64], hguides: &[f64]) -> Rect {
|
||||
let (ox, oy, nx, ny) = ((old.x0, old.x1), (old.y0, old.y1), (new.x0, new.x1), (new.y0, new.y1));
|
||||
match rule {
|
||||
LiquidRule::Off => b,
|
||||
LiquidRule::Off | LiquidRule::ControlledByParent => b,
|
||||
LiquidRule::ReCenter => b + (new.center() - old.center()),
|
||||
LiquidRule::Scale => {
|
||||
let k = (new.width() / old.width()).min(new.height() / old.height());
|
||||
@@ -63,7 +63,7 @@ fn target(rule: LiquidRule, b: Rect, old: Rect, new: Rect, liquid: Option<Object
|
||||
pub(crate) fn apply(d: &mut Document, sr: SpreadRef, pi: usize, old: Rect) {
|
||||
let Some(sp) = d.spread(sr) else { return };
|
||||
let Some(pg) = sp.pages.get(pi) else { return };
|
||||
let (rule, new) = (pg.liquid, pg.bounds());
|
||||
let (rule, new) = (effective_rule(d, sr, pi), pg.bounds());
|
||||
if rule == LiquidRule::Off || old == new || old.width() < 1e-6 || old.height() < 1e-6 {
|
||||
return;
|
||||
}
|
||||
@@ -108,8 +108,24 @@ pub(crate) fn apply(d: &mut Document, sr: SpreadRef, pi: usize, old: Rect) {
|
||||
}
|
||||
}
|
||||
|
||||
/// The rule page `pi` of spread `sr` follows: its own, or its parent page's when it's controlled
|
||||
/// by the parent (Off when that's unset too).
|
||||
pub(crate) fn effective_rule(d: &Document, sr: SpreadRef, pi: usize) -> LiquidRule {
|
||||
let Some(pg) = d.spread(sr).and_then(|sp| sp.pages.get(pi)) else { return LiquidRule::Off };
|
||||
if pg.liquid != LiquidRule::ControlledByParent {
|
||||
return pg.liquid;
|
||||
}
|
||||
let SpreadRef::Doc(si) = sr else { return LiquidRule::Off };
|
||||
let abs = d.first_page_of_spread(si) + pi;
|
||||
match d.parent_page_for(abs).and_then(|(ppi, ppg)| d.parents.get(ppi)?.pages.get(ppg).map(|p| p.liquid)) {
|
||||
Some(LiquidRule::ControlledByParent) | None => LiquidRule::Off,
|
||||
Some(r) => r,
|
||||
}
|
||||
}
|
||||
|
||||
fn rule_param(p: &Value, id: &str) -> Result<LiquidRule> {
|
||||
serde_json::from_value(p.get("rule").cloned().unwrap_or(json!("off"))).map_err(|_| bad(id, "`rule`: off|scale|reCenter|guideBased|objectBased"))
|
||||
serde_json::from_value(p.get("rule").cloned().unwrap_or(json!("off")))
|
||||
.map_err(|_| bad(id, "`rule`: off|scale|reCenter|guideBased|objectBased|controlledByParent"))
|
||||
}
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
@@ -119,7 +135,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Liquid Page Rule",
|
||||
["Layout", "Liquid Layout"],
|
||||
None,
|
||||
"{rule: off|scale|reCenter|guideBased|objectBased, pages?: [1-based] (default: all)}",
|
||||
"{rule: off|scale|reCenter|guideBased|objectBased|controlledByParent (the parent page's rule), pages?: [1-based] (default: all)}",
|
||||
has_doc,
|
||||
|s, p| {
|
||||
let rule = rule_param(p, "liquid.pageRule")?;
|
||||
|
||||
@@ -15,7 +15,8 @@ mod editorial;
|
||||
mod endnotes;
|
||||
mod export;
|
||||
mod file;
|
||||
mod find;
|
||||
pub(crate) mod find;
|
||||
pub use find::same_find_domain;
|
||||
mod fonts;
|
||||
mod guides;
|
||||
mod index;
|
||||
@@ -50,6 +51,7 @@ mod strokes;
|
||||
mod style;
|
||||
pub mod table;
|
||||
pub mod text;
|
||||
mod thread;
|
||||
mod toc;
|
||||
mod transitions;
|
||||
mod variables;
|
||||
@@ -184,6 +186,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
|
||||
v.extend(package::specs());
|
||||
v.extend(print::specs());
|
||||
v.extend(text::specs());
|
||||
v.extend(thread::specs());
|
||||
v.extend(style::specs());
|
||||
v.extend(table::specs());
|
||||
v.extend(layout::specs());
|
||||
|
||||
@@ -22,7 +22,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Document Footnote Options…",
|
||||
["Type"],
|
||||
None,
|
||||
"{style?: arabic|upperRoman|lowerRoman|upperLetters|lowerLetters|symbols, startAt?, restart?: never|page|spread|section, prefix?, suffix?, affixIn?: none|reference|text|both, refPosition?: superscript|subscript|normal|otSuperscript, refCharStyle?, paraStyle?, separator?, spaceBefore?, spaceBetween?, firstBaseline?, firstBaselineMin?, spanColumns?, rule?: {on, weight, color, tint, width, offset, leftIndent}} → the options (no params: just read them)",
|
||||
"{style?: arabic|upperRoman|lowerRoman|upperLetters|lowerLetters|symbols, startAt?, restart?: never|page|spread|section, prefix?, suffix?, affixIn?: none|reference|text|both, refPosition?: superscript|subscript|normal|otSuperscript, refCharStyle?, paraStyle?, separator?, spaceBefore?, spaceBetween?, firstBaseline?: ascent|capHeight|leading|xHeight|emboxHeight|fixed, firstBaselineMin?, spanColumns?, rule?: {on, weight, color, tint, width, offset, leftIndent}} → the options (no params: just read them)",
|
||||
has_doc,
|
||||
options
|
||||
),
|
||||
|
||||
+157
-21
@@ -6,7 +6,8 @@ use std::sync::Arc;
|
||||
|
||||
use designcraft_color::BlendMode;
|
||||
use designcraft_doc::{
|
||||
Content, Document, Fill, Item, ItemId, ParaFormat, Selection, Shape, SpreadRef, Story, StoryId, Stroke, TextFrame, TextFrameOptions, TextSel,
|
||||
AssetId, Content, Document, Fill, Item, ItemId, ParaFormat, Selection, Shape, SpreadRef, Story, StoryId, Stroke, TextFrame, TextFrameOptions,
|
||||
TextSel,
|
||||
};
|
||||
use designcraft_geom::{Affine, Point, Rect, Vec2, shapes};
|
||||
use serde_json::{Value, json};
|
||||
@@ -179,12 +180,35 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
)
|
||||
}
|
||||
),
|
||||
cmd!("object.fill", "Fill", [], None, "{swatch (a swatch's name, e.g. [Paper]), tint?: 0..1, ids?}", has_selection, |s, p| {
|
||||
let sw = str_param(p, "swatch").ok_or_else(|| bad("object.fill", "missing swatch"))?.to_string();
|
||||
known_swatch(&s.doc()?.doc, &sw, "object.fill", "swatch")?;
|
||||
let tint = f64_or(p, "tint", 1.0) as f32;
|
||||
set_flag(s, p, move |i| i.fill = Fill { swatch: sw.clone(), tint, ..i.fill.clone() }, false)
|
||||
}),
|
||||
cmd!(
|
||||
"object.fill",
|
||||
"Fill",
|
||||
[],
|
||||
None,
|
||||
"{swatch? (a swatch's name, e.g. [Paper]), tint?: 0..1, ids?} — at least one; a tint alone keeps each object's own swatch (the Swatches panel's Tint field)",
|
||||
has_selection,
|
||||
|s, p| {
|
||||
let sw = str_param(p, "swatch").map(str::to_string);
|
||||
let tint = match p.get("tint") {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(v) => Some(v.as_f64().filter(|t| (0.0..=1.0).contains(t)).ok_or_else(|| bad("object.fill", "`tint` is 0..1"))? as f32),
|
||||
};
|
||||
match &sw {
|
||||
Some(sw) => known_swatch(&s.doc()?.doc, sw, "object.fill", "swatch")?,
|
||||
None if tint.is_none() => return Err(bad("object.fill", "missing swatch")),
|
||||
None => {}
|
||||
}
|
||||
set_flag(
|
||||
s,
|
||||
p,
|
||||
move |i| match &sw {
|
||||
Some(sw) => i.fill = Fill { swatch: sw.clone(), tint: tint.unwrap_or(1.0), ..i.fill.clone() },
|
||||
None => i.fill.tint = tint.unwrap_or(i.fill.tint),
|
||||
},
|
||||
false,
|
||||
)
|
||||
}
|
||||
),
|
||||
cmd!(
|
||||
"object.swapFillStroke",
|
||||
"Swap Fill and Stroke",
|
||||
@@ -217,10 +241,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
}
|
||||
}
|
||||
let p2 = p.clone();
|
||||
// A tint alone (the Swatches panel's Tint field) recolours strokes, it doesn't add one.
|
||||
let tint_only = p.as_object().is_some_and(|o| o.contains_key("tint") && o.keys().all(|k| k == "tint" || k == "ids"));
|
||||
set_flag(
|
||||
s,
|
||||
p,
|
||||
move |i| {
|
||||
if tint_only && i.stroke.is_none() {
|
||||
return;
|
||||
}
|
||||
let mut st = if i.stroke.is_none() && p2.get("swatch").is_none() { Stroke::default() } else { i.stroke.clone() };
|
||||
if let Some(v) = p2.get("swatch").and_then(Value::as_str) {
|
||||
st.swatch = v.into();
|
||||
@@ -532,7 +561,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Text Frame Options…",
|
||||
["Object"],
|
||||
Some("Cmd+B"),
|
||||
"{columns?, gutter?, inset?: number|[t,l,b,r] (null keeps that side), verticalJustification?: top|center|bottom|justify, firstBaseline?, autoSize?, ignoreWrap?, balanceColumns?, columnRule?: bool, columnRuleWeight? (pt), columnRuleColor? (swatch name), columnRuleTint? (0..1), columnRuleOffset? (pt, horizontal), columnRuleTopInset? (pt), columnRuleBottomInset? (pt), vertical?: bool (sets the story direction of the frames' stories, as Type ▸ Story Direction), ids?}",
|
||||
"{columns?, gutter?, inset?: number|[t,l,b,r] (null keeps that side), verticalJustification?: top|center|bottom|justify, firstBaseline?: ascent|capHeight|leading|xHeight|emboxHeight|fixed, autoSize?, ignoreWrap?, balanceColumns?, columnRule?: bool, columnRuleWeight? (pt), columnRuleColor? (swatch name), columnRuleTint? (0..1), columnRuleOffset? (pt, horizontal), columnRuleTopInset? (pt), columnRuleBottomInset? (pt), vertical?: bool (sets the story direction of the frames' stories, as Type ▸ Story Direction), ids?}",
|
||||
has_selection,
|
||||
text_frame_options
|
||||
),
|
||||
@@ -966,13 +995,24 @@ pub fn duplicate_from(dst: &mut Document, src: &Document, ids: &[ItemId], to: Sp
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The id to reference in `dst` for asset `id` of `src`. When `src` lacks the asset (a missing graphic), an id that `dst`
|
||||
/// already uses for a different asset is swapped for a fresh unused one so the reference stays missing instead of showing
|
||||
/// an unrelated image.
|
||||
fn adopt_or_dangle(dst: &mut Document, src: &Document, id: AssetId) -> AssetId {
|
||||
match dst.adopt_asset(src, id) {
|
||||
Some(a) => a,
|
||||
None if dst.assets.contains_key(&id) => AssetId(dst.alloc()),
|
||||
None => id,
|
||||
}
|
||||
}
|
||||
|
||||
fn renumber(dst: &mut Document, src: &Document, it: &mut Item, stories: &mut HashMap<StoryId, StoryId>) {
|
||||
it.id = ItemId(dst.alloc());
|
||||
let my_id = it.id;
|
||||
if let Some(m) = it.media.as_mut()
|
||||
&& let Some(p) = m.poster
|
||||
{
|
||||
m.poster = dst.adopt_asset(src, p).or(Some(p));
|
||||
m.poster = Some(adopt_or_dangle(dst, src, p));
|
||||
}
|
||||
match &mut it.content {
|
||||
Content::Text(tf) => {
|
||||
@@ -984,9 +1024,8 @@ fn renumber(dst: &mut Document, src: &Document, it: &mut Item, stories: &mut Has
|
||||
st.id = n;
|
||||
let mut assets = HashMap::new();
|
||||
for a in designcraft_doc::story_asset_refs(&st) {
|
||||
if let Some(na) = dst.adopt_asset(src, a)
|
||||
&& na != a
|
||||
{
|
||||
let na = adopt_or_dangle(dst, src, a);
|
||||
if na != a {
|
||||
assets.insert(a, na);
|
||||
}
|
||||
}
|
||||
@@ -1003,9 +1042,7 @@ fn renumber(dst: &mut Document, src: &Document, it: &mut Item, stories: &mut Has
|
||||
}
|
||||
}
|
||||
Content::Graphic(g) => {
|
||||
if let Some(a) = dst.adopt_asset(src, g.asset) {
|
||||
g.asset = a;
|
||||
}
|
||||
g.asset = adopt_or_dangle(dst, src, g.asset);
|
||||
}
|
||||
Content::Group { items } => {
|
||||
for c in items.iter_mut() {
|
||||
@@ -1489,6 +1526,20 @@ fn unlocked(d: &Document, it: &Item) -> bool {
|
||||
!it.locked && d.layer(it.layer).is_none_or(|l| !l.locked)
|
||||
}
|
||||
|
||||
/// Refuses a path edit on `id` when it, a group it sits in, or its layer is locked.
|
||||
pub(super) fn path_editable(d: &Document, id: ItemId, cmd: &str) -> Result<()> {
|
||||
let loc = d.find(id).ok_or(designcraft_doc::DocError::NoItem(id))?;
|
||||
let mut items = d.spread(loc.spread).map(|sp| &sp.items[..]).unwrap_or_default();
|
||||
for &i in &loc.path {
|
||||
let Some(it) = items.get(i) else { break };
|
||||
if !unlocked(d, it) {
|
||||
return Err(bad(cmd, "the path is locked"));
|
||||
}
|
||||
items = it.children();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn has_editable_selection(s: &Session) -> std::result::Result<(), String> {
|
||||
has_selection(s)?;
|
||||
let st = s.active().ok_or_else(|| super::NOTHING_SELECTED.to_string())?;
|
||||
@@ -2075,6 +2126,7 @@ fn path_append(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let a = p.get("anchor").and_then(anchor_from).ok_or_else(|| bad("path.appendAnchor", "missing anchor"))?;
|
||||
let subpath = p.get("subpath").and_then(Value::as_u64);
|
||||
s.edit(|d, _| {
|
||||
path_editable(d, id, "path.appendAnchor")?;
|
||||
let loc = d.find(id).ok_or(designcraft_doc::DocError::NoItem(id))?;
|
||||
let inv = (d.parent_xf(&loc) * d.item_at(&loc).map(|i| i.xf).unwrap_or_default()).inverse();
|
||||
let it = d.item_mut(id).ok_or(designcraft_doc::DocError::NoItem(id))?;
|
||||
@@ -2110,12 +2162,10 @@ fn path_set_anchor(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let subpath = p.get("subpath").and_then(Value::as_u64);
|
||||
let which = p.get("anchor").cloned().unwrap_or(Value::Null);
|
||||
s.edit(|d, _| {
|
||||
path_editable(d, id, ID)?;
|
||||
let loc = d.find(id).ok_or(designcraft_doc::DocError::NoItem(id))?;
|
||||
let inv = (d.parent_xf(&loc) * d.item_at(&loc).map(|i| i.xf).unwrap_or_default()).inverse();
|
||||
let it = d.item_mut(id).ok_or(designcraft_doc::DocError::NoItem(id))?;
|
||||
if it.locked {
|
||||
return Err(bad(ID, "the path is locked"));
|
||||
}
|
||||
let sp = match subpath {
|
||||
Some(i) => usize::try_from(i).ok().and_then(|i| it.path.subpaths.get_mut(i)),
|
||||
None => it.path.subpaths.last_mut(),
|
||||
@@ -2157,12 +2207,19 @@ fn path_reverse(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
{
|
||||
return Err(bad("path.reverse", "no such subpath"));
|
||||
}
|
||||
let ids = if only.is_some() { ids.into_iter().take(1).collect() } else { ids };
|
||||
let ids: Vec<ItemId> = if only.is_some() { ids.into_iter().take(1).collect() } else { ids };
|
||||
let doc = &s.doc()?.doc;
|
||||
let editable: Vec<ItemId> = ids.iter().copied().filter(|id| path_editable(doc, *id, "path.reverse").is_ok()).collect();
|
||||
if editable.is_empty()
|
||||
&& let Some(id) = ids.first()
|
||||
{
|
||||
path_editable(doc, *id, "path.reverse")?;
|
||||
}
|
||||
s.edit(|d, _| {
|
||||
let mut reversed = 0;
|
||||
for id in &ids {
|
||||
for id in &editable {
|
||||
let Some(it) = d.item_mut(*id) else { continue };
|
||||
if it.locked || it.is_group() {
|
||||
if it.is_group() {
|
||||
continue;
|
||||
}
|
||||
for (i, sp) in it.path.subpaths.iter_mut().enumerate() {
|
||||
@@ -2184,6 +2241,7 @@ fn path_close(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let id = super::id_param(p, "id").ok_or_else(|| bad("path.close", "missing id"))?;
|
||||
let only = p.get("subpath").and_then(Value::as_u64).map(|i| usize::try_from(i).unwrap_or(usize::MAX));
|
||||
s.edit(|d, _| {
|
||||
path_editable(d, id, "path.close")?;
|
||||
let it = d.item_mut(id).ok_or(designcraft_doc::DocError::NoItem(id))?;
|
||||
if only.is_some_and(|i| i >= it.path.subpaths.len()) {
|
||||
return Err(bad("path.close", "no such subpath"));
|
||||
@@ -2206,6 +2264,7 @@ fn path_move_anchors(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let d0 = Vec2::new(f64_or(p, "dx", 0.0), f64_or(p, "dy", 0.0));
|
||||
let handle = str_param(p, "handle").map(str::to_string);
|
||||
s.edit(|d, _| {
|
||||
path_editable(d, id, "path.moveAnchors")?;
|
||||
let loc = d.find(id).ok_or(designcraft_doc::DocError::NoItem(id))?;
|
||||
let m = d.parent_xf(&loc) * d.item_at(&loc).map(|i| i.xf).unwrap_or_default();
|
||||
// Spread-space delta → inner-space delta (linear part only).
|
||||
@@ -3300,6 +3359,50 @@ mod path_edit_tests {
|
||||
assert!(s.execute("path.appendAnchor", &json!({"id": id, "anchor": {"p": [0, 0]}})).is_err());
|
||||
assert!(s.execute("path.close", &json!({"id": id, "subpath": 4})).is_err());
|
||||
}
|
||||
|
||||
/// Every edit that `path_editable` guards, aimed at the path `id` of `session_with_path`.
|
||||
fn path_edits(id: u64) -> Vec<(&'static str, serde_json::Value)> {
|
||||
vec![
|
||||
("path.appendAnchor", json!({"id": id, "anchor": {"p": [400, 250]}})),
|
||||
("path.setAnchor", json!({"id": id, "anchor": 0, "p": [90, 110]})),
|
||||
("path.close", json!({"id": id})),
|
||||
("path.moveAnchors", json!({"id": id, "anchors": [[0, 0]], "dx": 10, "dy": 10})),
|
||||
("path.reverse", json!({"ids": [id]})),
|
||||
("path.addAnchor", json!({"id": id, "at": [150, 100]})),
|
||||
("path.deleteAnchor", json!({"id": id, "subpath": 0, "anchor": 0})),
|
||||
("path.convertAnchor", json!({"id": id, "subpath": 0, "anchor": 0})),
|
||||
("path.erase", json!({"id": id, "points": [[120, 100], [180, 100]]})),
|
||||
("path.smooth", json!({"id": id, "points": [[120, 100], [180, 100]]})),
|
||||
("path.split", json!({"id": id, "at": [150, 100]})),
|
||||
]
|
||||
}
|
||||
|
||||
fn assert_no_path_edit(s: &mut crate::Session, id: u64, why: &str) {
|
||||
let before = anchors(s, id);
|
||||
for (cmd, p) in path_edits(id) {
|
||||
assert!(s.execute(cmd, &p).is_err(), "{cmd} {why}");
|
||||
}
|
||||
assert_eq!(anchors(s, id), before, "{why}");
|
||||
assert!(!s.doc().unwrap().doc.item(ItemId(id)).unwrap().path.subpaths[0].closed, "{why}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn path_edits_leave_a_path_on_a_locked_layer_alone() {
|
||||
let (mut s, id) = session_with_path();
|
||||
let layer = s.doc().unwrap().doc.item(ItemId(id)).unwrap().layer;
|
||||
s.execute("layer.set", &json!({"id": layer.0, "locked": true})).unwrap();
|
||||
assert_no_path_edit(&mut s, id, "on a locked layer");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn path_edits_leave_a_path_in_a_locked_group_alone() {
|
||||
let (mut s, id) = session_with_path();
|
||||
let other = s.execute("frame.create", &json!({"rect": [400, 400, 450, 450]})).unwrap()["id"].as_u64().unwrap();
|
||||
let group = s.execute("object.group", &json!({"ids": [id, other]})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("object.lock", &json!({"ids": [group]})).unwrap();
|
||||
assert!(!s.doc().unwrap().doc.item(ItemId(id)).unwrap().locked, "only the group is locked");
|
||||
assert_no_path_edit(&mut s, id, "in a locked group");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -3327,3 +3430,36 @@ mod spread_target_tests {
|
||||
assert!(s.doc().unwrap().doc.spreads[0].items.is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod fill_tint_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_tint_alone_keeps_each_objects_own_swatch() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
let a = s.execute("frame.create", &json!({"rect": [36, 36, 100, 100]})).unwrap()["id"].as_u64().unwrap();
|
||||
let b = s.execute("frame.create", &json!({"rect": [136, 36, 200, 100]})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("object.fill", &json!({"ids": [a], "swatch": "C=100 M=0 Y=0 K=0"})).unwrap();
|
||||
s.execute("object.fill", &json!({"ids": [b], "swatch": "C=0 M=100 Y=0 K=0"})).unwrap();
|
||||
s.execute("object.fill", &json!({"ids": [a, b], "tint": 0.4})).unwrap();
|
||||
let fill_of = |s: &Session, id: u64| s.doc().unwrap().doc.item(ItemId(id)).unwrap().fill.clone();
|
||||
assert_eq!((fill_of(&s, a).swatch.as_str(), fill_of(&s, a).tint), ("C=100 M=0 Y=0 K=0", 0.4));
|
||||
assert_eq!((fill_of(&s, b).swatch.as_str(), fill_of(&s, b).tint), ("C=0 M=100 Y=0 K=0", 0.4));
|
||||
// A swatch without a tint is at 100 %, as before.
|
||||
s.execute("object.fill", &json!({"ids": [a], "swatch": "[Black]"})).unwrap();
|
||||
assert_eq!(fill_of(&s, a).tint, 1.0);
|
||||
// Neither, or a tint out of range: refused.
|
||||
assert!(s.execute("object.fill", &json!({"ids": [a]})).is_err());
|
||||
assert!(s.execute("object.fill", &json!({"ids": [a], "tint": 2})).is_err());
|
||||
assert!(s.execute("object.fill", &json!({"ids": [a], "tint": "x"})).is_err());
|
||||
// A stroke tint alone: stroked objects take it, an object without a stroke keeps none.
|
||||
s.execute("object.stroke", &json!({"ids": [a], "swatch": "C=100 M=0 Y=0 K=0", "weight": 2})).unwrap();
|
||||
s.execute("object.stroke", &json!({"ids": [b], "swatch": "[None]"})).unwrap();
|
||||
s.execute("object.stroke", &json!({"ids": [a, b], "tint": 0.5})).unwrap();
|
||||
let stroke_of = |s: &Session, id: u64| s.doc().unwrap().doc.item(ItemId(id)).unwrap().stroke.clone();
|
||||
assert_eq!((stroke_of(&s, a).swatch.as_str(), stroke_of(&s, a).tint, stroke_of(&s, a).weight), ("C=100 M=0 Y=0 K=0", 0.5, 2.0));
|
||||
assert!(stroke_of(&s, b).is_none());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -74,6 +74,8 @@ struct OutputRoot {
|
||||
|
||||
impl OutputRoot {
|
||||
fn new(path: PathBuf) -> Result<Self> {
|
||||
// Before anything is created: the folder must be inside the automation write root.
|
||||
crate::file_access::check_write(&path).map_err(EngineError::Other)?;
|
||||
ensure_real_directory(&path, false)?;
|
||||
let canonical = std::fs::canonicalize(&path).map_err(|e| path_error(&path, e))?;
|
||||
Ok(Self { path, canonical })
|
||||
@@ -292,6 +294,11 @@ fn write_links(d: &Document, root: &OutputRoot, dir: &Path, only: Option<&[Asset
|
||||
continue;
|
||||
}
|
||||
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() {
|
||||
continue;
|
||||
}
|
||||
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())?;
|
||||
@@ -472,6 +479,49 @@ mod tests {
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
/// A link whose file is gone has no bytes to copy: the package leaves it out of Links/, the
|
||||
/// report lists it as missing, and the packaged document keeps it missing (#908).
|
||||
#[test]
|
||||
fn package_leaves_missing_links_missing() {
|
||||
let nonce = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos();
|
||||
let dir = std::env::temp_dir().join(format!("dc-package-missing-{}-{nonce}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let svg = r##"<svg xmlns="http://www.w3.org/2000/svg" width="40" height="40"><rect width="40" height="40"/></svg>"##;
|
||||
let (gone, kept) = (dir.join("gone.svg"), dir.join("kept.svg"));
|
||||
std::fs::write(&gone, svg).unwrap();
|
||||
std::fs::write(&kept, svg.replace("<rect", "<circle r=\"9\"/><rect")).unwrap();
|
||||
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();
|
||||
s.execute("edit.deselectAll", &json!({})).unwrap();
|
||||
s.execute("file.place", &json!({"path": kept.to_string_lossy(), "x": 10, "y": 200})).unwrap();
|
||||
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();
|
||||
let mut s = Session::new();
|
||||
s.execute("file.openIdml", &json!({"path": idml.to_string_lossy()})).unwrap();
|
||||
let status = |s: &mut Session, name: &str| {
|
||||
let links = s.execute("links.list", &json!({})).unwrap();
|
||||
links.as_array().unwrap().iter().find(|l| l["name"] == name).map(|l| l["status"].clone())
|
||||
};
|
||||
assert_eq!(status(&mut s, "gone.svg"), Some(json!("missing")));
|
||||
|
||||
let out = dir.join("Pkg");
|
||||
let r = s.execute("file.package", &json!({"dir": out.to_string_lossy(), "idml": true})).unwrap();
|
||||
assert!(!out.join("Links").join("gone.svg").exists(), "a missing link is not copied");
|
||||
assert!(out.join("Links").join("kept.svg").exists());
|
||||
assert!(!r["files"].to_string().contains("gone.svg"), "{}", r["files"]);
|
||||
let report = r["report"].as_str().unwrap();
|
||||
assert!(report.contains("gone.svg (missing)"), "{report}");
|
||||
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();
|
||||
assert_eq!(status(&mut opened, "gone.svg"), Some(json!("missing")), "{extension}");
|
||||
assert_eq!(status(&mut opened, "kept.svg"), Some(json!("ok")), "{extension}");
|
||||
}
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn package_writes_document_links_and_report() {
|
||||
let dir = std::env::temp_dir().join(format!("dc-package-{}", std::process::id()));
|
||||
|
||||
@@ -44,7 +44,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Pathfinder",
|
||||
["Object", "Pathfinder"],
|
||||
None,
|
||||
"{op: add|subtract|intersect|exclude|minusBack, ids?} — combine the selected shapes into one (the backmost keeps its look; the frontmost for minusBack) → {id}",
|
||||
"{op: add|subtract|intersect|exclude|minusBack, ids?} — combine the selected shapes into one, which keeps the frontmost object's look and content (a placed graphic stays in it); Subtract keeps the backmost → {id}",
|
||||
has_selection,
|
||||
pathfinder
|
||||
),
|
||||
@@ -145,7 +145,9 @@ fn pathfinder(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if order.len() < 2 {
|
||||
return Err(bad("object.pathfinder", "select two or more shapes on one spread (not text frames or groups)"));
|
||||
}
|
||||
let keep = if op == Op::MinusBack { order[order.len() - 1] } else { order[0] };
|
||||
// InDesign: the result takes the frontmost object's look and content (a photo placed over
|
||||
// shapes shows through their intersection); Subtract keeps the backmost, the front cuts it.
|
||||
let keep = if op == Op::Subtract { order[0] } else { order[order.len() - 1] };
|
||||
let shapes: Vec<PathData> =
|
||||
order.iter().filter_map(|id| spread_xf(d, *id).and_then(|(_, xf)| Some(d.item(*id)?.path.transformed(xf)))).collect();
|
||||
let Some(result) = combine(op, &shapes) else { return Err(bad("object.pathfinder", "the shapes don't overlap: nothing is left")) };
|
||||
@@ -246,7 +248,7 @@ fn create_outlines(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cs = designcraft_compose::compose_story(d, tf.story, &Default::default());
|
||||
let Some(ft) = cs.frame(*id) else { continue };
|
||||
// One path per text look (fill, stroke).
|
||||
let mut runs: Vec<((String, f32, String, f32, f64), BezPath)> = Vec::new();
|
||||
let mut runs: Vec<((String, f32, String, f32, f64, bool), BezPath)> = Vec::new();
|
||||
for l in &ft.lines {
|
||||
for g in l.glyphs.iter().filter(|g| g.visible) {
|
||||
let st = &cs.styles[g.style as usize];
|
||||
@@ -256,7 +258,7 @@ fn create_outlines(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let skew = if st.skew != 0.0 { Affine::new([1.0, 0.0, -st.skew.to_radians().tan(), 1.0, 0.0, 0.0]) } else { Affine::IDENTITY };
|
||||
let a = Affine::translate((g.x, l.baseline + g.y)) * skew * Affine::scale_non_uniform(g.sx, g.sy);
|
||||
let key = (st.fill.clone(), st.fill_tint, st.stroke.clone(), st.stroke_tint, st.stroke_weight);
|
||||
let key = (st.fill.clone(), st.fill_tint, st.stroke.clone(), st.stroke_tint, st.stroke_weight, st.stroke_behind_fill);
|
||||
let k = match runs.iter().position(|r| r.0 == key) {
|
||||
Some(k) => k,
|
||||
None => {
|
||||
@@ -274,14 +276,16 @@ fn create_outlines(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (sr, _) = spread_xf(d, *id).ok_or(designcraft_doc::DocError::NoItem(*id))?;
|
||||
let at = d.spread(sr).and_then(|sp| sp.items.iter().position(|i| i.id == *id));
|
||||
let text_xf = d.text_xf(&it);
|
||||
let make = |d: &mut Document, ((fill, ft, stroke, stt, sw), bp): ((String, f32, String, f32, f64), BezPath)| {
|
||||
let make = |d: &mut Document, ((fill, ft, stroke, stt, sw, behind), bp): ((String, f32, String, f32, f64, bool), BezPath)| {
|
||||
let mut o = Item::new(ItemId(d.alloc()), it.layer, Shape::Path, PathData::from_bezpath(&bp));
|
||||
o.xf = text_xf;
|
||||
o.fill = Fill { swatch: fill, tint: ft, ..Fill::none() };
|
||||
o.stroke = if stroke == designcraft_color::swatch::NONE {
|
||||
Stroke::none()
|
||||
} else {
|
||||
Stroke { swatch: stroke, tint: stt, weight: sw, ..Stroke::default() }
|
||||
// A stroke behind the fill lies wholly outside the letters, as an outside-aligned stroke.
|
||||
let align = if behind { designcraft_doc::StrokeAlign::Outside } else { designcraft_doc::StrokeAlign::Center };
|
||||
Stroke { swatch: stroke, tint: stt, weight: sw, align, ..Stroke::default() }
|
||||
};
|
||||
o
|
||||
};
|
||||
@@ -312,6 +316,7 @@ fn split_path(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let id = super::id_param(p, "id").ok_or_else(|| bad("path.split", "missing id"))?;
|
||||
let at = point_param(p, "at").ok_or_else(|| bad("path.split", "missing at"))?;
|
||||
s.edit(|d, sel| {
|
||||
super::object::path_editable(d, id, "path.split")?;
|
||||
let (sr, xf) = spread_xf(d, id).ok_or(designcraft_doc::DocError::NoItem(id))?;
|
||||
let it = d.item(id).cloned().ok_or(designcraft_doc::DocError::NoItem(id))?;
|
||||
if !matches!(it.content, Content::Unassigned) {
|
||||
@@ -417,6 +422,55 @@ mod tests {
|
||||
assert!(s.execute("object.pathfinder", &json!({"op": "nope"})).is_err());
|
||||
}
|
||||
|
||||
/// The result keeps the frontmost object's look (Subtract: the backmost's), as InDesign's.
|
||||
#[test]
|
||||
fn pathfinder_keeps_the_frontmost_object() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
s.execute("swatch.create", &json!({"name": "Red", "color": [255, 0, 0]})).unwrap();
|
||||
for op in ["add", "intersect", "exclude", "minusBack"] {
|
||||
let a = s.execute("frame.create", &json!({"rect": [100, 100, 300, 300]})).unwrap()["id"].as_u64().unwrap();
|
||||
let b = s.execute("frame.create", &json!({"rect": [200, 100, 400, 300]})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("object.fill", &json!({"ids": [a], "swatch": "[Black]"})).unwrap();
|
||||
s.execute("object.fill", &json!({"ids": [b], "swatch": "Red"})).unwrap();
|
||||
let r = s.execute("object.pathfinder", &json!({"op": op, "ids": [a, b]})).unwrap();
|
||||
assert_eq!(r["id"], b, "{op}: the front object stays");
|
||||
let d = s.doc().unwrap().doc.clone();
|
||||
assert!(d.item(ItemId(a)).is_none(), "{op}");
|
||||
assert_eq!(d.item(ItemId(b)).unwrap().fill.swatch, "Red", "{op}");
|
||||
s.execute("edit.clear", &json!({"ids": [b]})).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
/// A photo placed over strips and intersected with them shows through the strips (it was
|
||||
/// dropped: the black strips were kept).
|
||||
#[test]
|
||||
fn pathfinder_intersect_keeps_a_placed_photo_in_front() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
let a = s.execute("frame.create", &json!({"rect": [100, 100, 300, 140]})).unwrap()["id"].as_u64().unwrap();
|
||||
let b = s.execute("frame.create", &json!({"rect": [100, 160, 300, 200]})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("object.fill", &json!({"ids": [a, b], "swatch": "[Black]"})).unwrap();
|
||||
let strips = s.execute("object.pathfinder", &json!({"op": "add", "ids": [a, b]})).unwrap()["id"].as_u64().unwrap();
|
||||
let png = designcraft_render::Rendered { width: 20, height: 20, pixels: [255u8, 255, 255, 255].repeat(400) }.to_png();
|
||||
let photo = s.execute("frame.create", &json!({"rect": [80, 80, 320, 220], "content": "graphic"})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("file.place", &json!({"base64": super::super::base64_encode(&png), "name": "white.png", "frame": photo})).unwrap();
|
||||
s.execute("object.fit", &json!({"mode": "fillProportionally", "ids": [photo]})).unwrap();
|
||||
let r = s.execute("object.pathfinder", &json!({"op": "intersect", "ids": [strips, photo]})).unwrap();
|
||||
assert_eq!(r["id"], photo);
|
||||
let d = s.doc().unwrap().doc.clone();
|
||||
assert!(d.item(ItemId(strips)).is_none());
|
||||
let it = d.item(ItemId(photo)).unwrap();
|
||||
assert!(matches!(it.content, Content::Graphic(_)), "the photo stays in the result");
|
||||
assert_eq!(it.path.subpaths.len(), 2, "cut to the two strips");
|
||||
let b = it.bounds();
|
||||
assert!((b.x0 - 100.0).abs() < 0.5 && (b.y0 - 100.0).abs() < 0.5 && (b.x1 - 300.0).abs() < 0.5 && (b.y1 - 200.0).abs() < 0.5, "{b:?}");
|
||||
let mut rr = designcraft_render::Renderer::new();
|
||||
rr.threads = 0;
|
||||
let img = rr.render_page(&d, &s.cache, 0, 1.0, false, &Default::default()).unwrap();
|
||||
assert!(img.pixel(200, 120)[0] > 230, "the photo (white) shows in a strip: {:?}", img.pixel(200, 120));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gradient_feather_fades_on_screen_and_in_pdf() {
|
||||
let mut s = Session::new();
|
||||
@@ -435,6 +489,89 @@ mod tests {
|
||||
assert!(t.contains("/SMask") || t.contains("/Luminosity"), "a soft mask");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_groups_gradient_feather_fades_it_on_screen_and_in_pdf() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
let mut ids = vec![];
|
||||
for rect in [[100, 100, 200, 200], [200, 100, 300, 200]] {
|
||||
let id = s.execute("frame.create", &json!({"rect": rect})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("object.fill", &json!({"ids": [id], "swatch": "[Black]"})).unwrap();
|
||||
ids.push(id);
|
||||
}
|
||||
let g = s.execute("object.group", &json!({"ids": ids})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("transform.move", &json!({"ids": [g], "dx": 20, "dy": 30})).unwrap();
|
||||
// The Gradient Feather tool's drag, then by angle (a group has no path of its own: the
|
||||
// gradient spans its objects). The gradient still follows the translated group even
|
||||
// though the mask geometry covers the whole output.
|
||||
for p in [json!({"ids": [g], "from": [120, 180], "to": [320, 180]}), json!({"ids": [g], "angle": 0})] {
|
||||
s.execute("object.gradientFeather", &p).unwrap();
|
||||
let d = s.doc().unwrap().doc.clone();
|
||||
let mut rr = designcraft_render::Renderer::new();
|
||||
rr.threads = 0;
|
||||
let img = rr.render_page(&d, &s.cache, 0, 1.0, false, &Default::default()).unwrap();
|
||||
let (l, m, r) = (img.pixel(125, 180)[0], img.pixel(220, 180)[0], img.pixel(315, 180)[0]);
|
||||
assert!(l < 60 && m > l + 40 && r > 220, "{p}: fades left to right on screen: {l} {m} {r}");
|
||||
let pdf = designcraft_pdf::export_pdf(&d, &s.cache, &Default::default()).unwrap();
|
||||
let pm = designcraft_render::render_pdf_page(&pdf, 0, 400).unwrap();
|
||||
// Over white paper.
|
||||
let at = |x: usize, y: usize| {
|
||||
let c = pm.data()[y * pm.width() as usize + x];
|
||||
c.r as u32 + 255 - c.a as u32
|
||||
};
|
||||
let (l, m, r) = (at(125, 180), at(220, 180), at(315, 180));
|
||||
assert!(l < 60 && m > l + 40 && r > 220, "{p}: fades left to right in PDF: {l} {m} {r}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_gradient_feather_keeps_distant_shadows_and_thick_strokes() {
|
||||
for shadow in [false, true] {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
|
||||
let mut ids = vec![];
|
||||
for rect in [[120, 120, 170, 170], [175, 120, 225, 170]] {
|
||||
let id = s.execute("frame.create", &json!({"rect": rect})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("object.fill", &json!({"ids": [id], "swatch": "[Black]"})).unwrap();
|
||||
if shadow {
|
||||
s.execute("object.dropShadow", &json!({"ids": [id], "on": true, "distance": 180, "angle": 90, "size": 0, "opacity": 1})).unwrap();
|
||||
} else {
|
||||
s.execute("object.stroke", &json!({"ids": [id], "swatch": "[Black]", "weight": 180})).unwrap();
|
||||
}
|
||||
ids.push(id);
|
||||
}
|
||||
let g = s.execute("object.group", &json!({"ids": ids})).unwrap()["id"].as_u64().unwrap();
|
||||
// Translate the group so mask geometry and gradient paint exercise distinct spaces.
|
||||
s.execute("transform.move", &json!({"ids": [g], "dx": 30, "dy": 20})).unwrap();
|
||||
let point = if shadow { (175, 345) } else { (175, 60) };
|
||||
let sample = |s: &Session| {
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let mut rr = designcraft_render::Renderer::new();
|
||||
rr.threads = 0;
|
||||
// Zoomed viewport: the mask must extend over every device pixel.
|
||||
let img = rr.render_page(d, &s.cache, 0, 2.0, false, &Default::default()).unwrap();
|
||||
let screen = img.pixel(point.0 * 2, point.1 * 2)[0];
|
||||
let pdf = designcraft_pdf::export_pdf(d, &s.cache, &Default::default()).unwrap();
|
||||
let pm = designcraft_render::render_pdf_page(&pdf, 0, 400).unwrap();
|
||||
let c = pm.data()[point.1 as usize * pm.width() as usize + point.0 as usize];
|
||||
[f32::from(screen), c.r as f32 + 255.0 - c.a as f32]
|
||||
};
|
||||
let before = sample(&s);
|
||||
// The sample lies past either end of the gradient, and outside the old fixed padding.
|
||||
s.execute("object.gradientFeather", &json!({"ids": [g], "from": [130, 120], "to": [130, 220], "start": 40, "end": 80})).unwrap();
|
||||
let after = sample(&s);
|
||||
let opacity = if shadow { 0.8 } else { 0.4 };
|
||||
for (kind, (before, after)) in ["screen", "PDF"].into_iter().zip(before.into_iter().zip(after)) {
|
||||
assert!(before < 120.0, "{kind}, shadow={shadow}: sample contains the effect before feathering: {before}");
|
||||
let expected = 255.0 - (255.0 - before) * opacity;
|
||||
assert!(
|
||||
(after - expected).abs() < 16.0,
|
||||
"{kind}, shadow={shadow}: end opacity continues past geometry: {after}, expected {expected}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn create_outlines_turns_text_into_paths() {
|
||||
let mut s = Session::new();
|
||||
|
||||
@@ -124,19 +124,25 @@ fn fit(d: &Document, sid: StoryId) -> (Option<usize>, usize, usize) {
|
||||
}
|
||||
|
||||
/// Thread new frames on new pages (margin rectangles) until the story fits. Returns pages added.
|
||||
pub(crate) fn autoflow(d: &mut Document, sid: StoryId, max_pages: usize) -> Result<usize> {
|
||||
/// A story on a parent spread doesn't autoflow: its frames thread only on that parent. Errors
|
||||
/// name `cmd`, the command that autoflows.
|
||||
pub(crate) fn autoflow(d: &mut Document, sid: StoryId, max_pages: usize, cmd: &str) -> Result<usize> {
|
||||
let last = d.story(sid).and_then(|s| s.frames.last().copied()).ok_or_else(|| bad(cmd, "the story has no frame"))?;
|
||||
if !matches!(d.find(last).map(|l| l.spread), Some(SpreadRef::Doc(_))) {
|
||||
return Err(bad(cmd, "autoflow works only from a frame on a document page"));
|
||||
}
|
||||
let mut added = 0;
|
||||
loop {
|
||||
let (overset, held, full) = fit(d, sid);
|
||||
let Some(at) = overset else { return Ok(added) };
|
||||
if added >= max_pages {
|
||||
return Err(bad("file.place", format!("autoflow stopped after {max_pages} pages")));
|
||||
return Err(bad(cmd, format!("autoflow stopped after {max_pages} pages")));
|
||||
}
|
||||
let len = d.story(sid).map_or(0, |s| s.len());
|
||||
// Frames still needed at the rate the full ones are filled (at least one); with no full
|
||||
// frame to go by yet, one more page.
|
||||
let want = held.checked_div(full).map_or(1, |per_frame| len.saturating_sub(at).div_ceil(per_frame.max(1))).clamp(1, max_pages - added);
|
||||
let last = *d.story(sid).and_then(|s| s.frames.last()).ok_or_else(|| bad("file.place", "the story has no frame"))?;
|
||||
let last = *d.story(sid).and_then(|s| s.frames.last()).ok_or_else(|| bad(cmd, "the story has no frame"))?;
|
||||
let mut page = d.page_of_item(last).unwrap_or(d.page_count().saturating_sub(1));
|
||||
let parent = d.page_loc(page).and_then(|(si, pi)| d.spreads[si].pages[pi].parent);
|
||||
d.insert_pages(Some(page), want, parent)?;
|
||||
@@ -144,7 +150,7 @@ pub(crate) fn autoflow(d: &mut Document, sid: StoryId, max_pages: usize) -> Resu
|
||||
let mut prev = last;
|
||||
for _ in 0..want {
|
||||
page += 1;
|
||||
let (si, pi) = d.page_loc(page).ok_or_else(|| bad("file.place", "page insert failed"))?;
|
||||
let (si, pi) = d.page_loc(page).ok_or_else(|| bad(cmd, "page insert failed"))?;
|
||||
let r = d.spreads[si].pages[pi].margin_rect();
|
||||
let (fid, _) = d.add_text_frame(SpreadRef::Doc(si), r, layer, "", ParaFormat::default())?;
|
||||
d.thread(prev, fid)?;
|
||||
@@ -230,7 +236,7 @@ pub(super) fn place_text(s: &mut Session, p: &Value, name: &str, bytes: &[u8]) -
|
||||
*sel = designcraft_doc::Selection::items(vec![fid]);
|
||||
sid
|
||||
};
|
||||
let pages = if autoflow_on { autoflow(d, sid, 2000)? } else { 0 };
|
||||
let pages = if autoflow_on { autoflow(d, sid, 2000, "file.place")? } else { 0 };
|
||||
let overset = fit(d, sid).0.is_some();
|
||||
Ok(json!({"story": sid.0, "pagesAdded": pages, "overset": overset, "warnings": warnings}))
|
||||
})
|
||||
|
||||
@@ -88,7 +88,7 @@ pub fn check(s: &Session, min_ppi: f64) -> Vec<Issue> {
|
||||
missing_glyphs(&cs, &story.text, 0, &mut missing);
|
||||
if cs.is_overset() {
|
||||
let last = story.frames.last().copied();
|
||||
let page = last.and_then(|f| d.find(f).zip(d.item(f))).and_then(|(loc, it)| page_of(d, loc.spread, it, Affine::IDENTITY));
|
||||
let page = last.and_then(|f| d.find(f).zip(d.item(f))).and_then(|(loc, it)| page_of(d, loc.spread, it, d.parent_xf(&loc)));
|
||||
let n = story.text[cs.overset_at.unwrap_or(0).min(story.len())..].chars().count();
|
||||
out.push(Issue { severity: "error", kind: "overset", message: format!("Overset text: {n} characters"), item: last.map(|i| i.0), page });
|
||||
}
|
||||
@@ -329,3 +329,29 @@ mod missing_glyph_tests {
|
||||
assert!(found[0].1.ends_with(" and 10 more"), "{}", found[0].1);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod overset_page_tests {
|
||||
use serde_json::json;
|
||||
|
||||
use crate::Session;
|
||||
|
||||
/// An overset frame inside a group moved onto the right-hand page was reported on the left one.
|
||||
#[test]
|
||||
fn overset_frame_in_a_moved_group_names_its_displayed_page() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"facingPages": true, "pages": 3, "width": 612, "height": 792})).unwrap();
|
||||
let frame = json!({"spread": 1, "rect": [72, 72, 140, 100], "content": "text", "text": "overflowing words ".repeat(100)});
|
||||
let a = s.execute("frame.create", &frame).unwrap()["id"].as_u64().unwrap();
|
||||
let b = s.execute("frame.create", &json!({"spread": 1, "rect": [300, 300, 350, 350]})).unwrap()["id"].as_u64().unwrap();
|
||||
let g = s.execute("object.group", &json!({"ids": [a, b]})).unwrap()["id"].as_u64().unwrap();
|
||||
let overset_page = |s: &mut Session| {
|
||||
let r = s.execute("preflight.run", &json!({})).unwrap();
|
||||
let issue = r["issues"].as_array().unwrap().iter().find(|i| i["kind"] == "overset").unwrap().clone();
|
||||
issue["page"].as_u64().unwrap()
|
||||
};
|
||||
assert_eq!(overset_page(&mut s), 1);
|
||||
s.execute("transform.move", &json!({"dx": 612, "dy": 0, "ids": [g]})).unwrap();
|
||||
assert_eq!(overset_page(&mut s), 2);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
//! Window › Utilities › Scripts: run a command script (see [`crate::script`]) as one undo step.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::{CommandSpec, always, bad, cmd, str_param};
|
||||
@@ -8,15 +10,23 @@ use crate::Result;
|
||||
fn run(s: &mut crate::Session, p: &Value) -> Result<Value> {
|
||||
let text = str_param(p, "text").ok_or_else(|| bad("script.run", "`text` required"))?;
|
||||
let steps = crate::script::parse(text).map_err(|e| bad("script.run", e))?;
|
||||
// The steps' own undo entries collapse into this command's single one.
|
||||
let uid = s.active().map(|d| d.uid);
|
||||
let before = s.active().map_or(0, |d| d.history.undo.len());
|
||||
// The steps' own undo entries collapse into this command's single one. A step that fails
|
||||
// rolls the successful prefix back (document, selection and history), so a half-run script
|
||||
// never strands edits that can't be undone (#709).
|
||||
let before = s.active().map(|d| (d.uid, d.doc.clone(), d.selection.clone(), d.history.clone()));
|
||||
let report = s.run_script(&steps);
|
||||
if let Some(st) = s.active_mut()
|
||||
&& Some(st.uid) == uid
|
||||
&& st.history.undo.len() > before
|
||||
&& let Some((uid, doc, selection, history)) = &before
|
||||
&& st.uid == *uid
|
||||
{
|
||||
st.history.undo.truncate(before);
|
||||
if report.failed.is_some() {
|
||||
st.doc = Arc::clone(doc);
|
||||
st.selection = selection.clone();
|
||||
st.history = history.clone();
|
||||
st.revision = st.revision.saturating_add(1);
|
||||
} else if st.history.undo.len() > history.undo.len() {
|
||||
st.history.undo.truncate(history.undo.len());
|
||||
}
|
||||
}
|
||||
let out = json!({"results": report.results, "steps": steps.len()});
|
||||
match report.failed {
|
||||
@@ -56,4 +66,22 @@ mod tests {
|
||||
assert_eq!(count(&s), 0, "one undo removes the whole script's work");
|
||||
assert!(s.execute("script.run", &json!({"text": "nope.command"})).is_err());
|
||||
}
|
||||
|
||||
/// A script that fails after a successful step leaves the document and its history exactly as
|
||||
/// they were: the half-run prefix is not stranded without an undo entry (#709).
|
||||
#[test]
|
||||
fn a_failed_script_rolls_the_successful_prefix_back() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
let count = |s: &Session| s.doc().unwrap().doc.spreads[0].items.len();
|
||||
let err = s.execute("script.run", &json!({"text": "frame.create {\"rect\": [72, 72, 200, 200]}\nnope.command"})).unwrap_err();
|
||||
assert!(err.to_string().contains("step 1") && err.to_string().contains("nope.command"), "{err}");
|
||||
assert_eq!(count(&s), 0, "the successful prefix is rolled back");
|
||||
assert!(s.execute("edit.undo", &json!({})).is_err(), "nothing was left to undo");
|
||||
// The session keeps working and its undo history is as it was.
|
||||
s.execute("frame.create", &json!({"rect": [72, 72, 200, 200]})).unwrap();
|
||||
assert_eq!(count(&s), 1);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(count(&s), 0);
|
||||
}
|
||||
}
|
||||
|
||||
+321
-72
@@ -135,7 +135,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"New Color Swatch…",
|
||||
[],
|
||||
None,
|
||||
"{name?, color: \"#rrggbb\"|{c,m,y,k}(0..100)|[r,g,b], spot?: bool}",
|
||||
"{name?, color: \"#rrggbb\"|{c,m,y,k}(0..100)|[r,g,b]|{model: cmyk|rgb|gray, …}(0..1), spot?: bool}",
|
||||
has_doc,
|
||||
create_swatch
|
||||
),
|
||||
@@ -144,7 +144,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Gradient",
|
||||
[],
|
||||
None,
|
||||
"{kind?: linear|radial, stops?: [{location: 0–100, color: \"#rrggbb\"|{c,m,y,k}|[r,g,b], opacity?: 0–100, midpoint?: 13–87}], reverse?: bool, angle?: degrees, from?: [x,y], to?: [x,y] (spread coords: the Gradient Swatch tool's drag), ids?} → {swatch, kind, stops} — edits the fill's gradient (an unnamed gradient unless it equals a gradient swatch)",
|
||||
"{kind?: linear|radial, stops?: [{location: 0–100, color: \"#rrggbb\"|{c,m,y,k}(0..100)|[r,g,b]|{model, …}(0..1), opacity?: 0–100, midpoint?: 13–87}], reverse?: bool, angle?: degrees, from?: [x,y], to?: [x,y] (spread coords: the Gradient Swatch tool's drag), ids?} → {swatch, kind, stops} — edits the fill's gradient (an unnamed gradient unless it equals a gradient swatch)",
|
||||
super::has_selection,
|
||||
apply_gradient
|
||||
),
|
||||
@@ -180,7 +180,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Apply Color",
|
||||
[],
|
||||
None,
|
||||
"{color: \"#rrggbb\"|{c,m,y,k}(0..100)|[r,g,b](0..255), target?: fill|stroke, text?: bool, ids?} — an unnamed colour on the selected text or objects; `text` also targets the text of selected frames",
|
||||
"{color: \"#rrggbb\"|{c,m,y,k}(0..100)|[r,g,b](0..255)|{model: cmyk|rgb|gray, …}(0..1), target?: fill|stroke, text?: bool, ids?} — an unnamed colour (not in the Swatches panel until Add to Swatches) on the selection; `text`: on the selected text, or the text of the selected frames (Formatting Affects Text)",
|
||||
has_text_or_selection,
|
||||
apply_color
|
||||
),
|
||||
@@ -438,6 +438,8 @@ fn create_para(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let base = str_param(p, "name").unwrap_or("Paragraph Style 1").to_string();
|
||||
let mut para: ParaAttrs = attrs(p.get("para"), |a: &mut ParaAttrs, k, v| a.set_json(k, v))?;
|
||||
let mut chars: CharAttrs = attrs(p.get("chars"), |a: &mut CharAttrs, k, v| a.set_json(k, v))?;
|
||||
// Validate caller-supplied fills, not selection fills retained after a swatch is deleted.
|
||||
super::text::validate_char_fill(&s.doc()?.doc, &chars, "style.paragraph.create")?;
|
||||
if p.get("fromSelection").and_then(Value::as_bool).unwrap_or(false)
|
||||
&& let Ok(cur) = s.execute("type.selectionAttrs", &json!({}))
|
||||
&& !cur.is_null()
|
||||
@@ -453,7 +455,6 @@ fn create_para(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
chars = full;
|
||||
}
|
||||
}
|
||||
super::text::validate_char_fill(&s.doc()?.doc, &chars, "style.paragraph.create")?;
|
||||
let based_on = str_param(p, "basedOn").map(str::to_string);
|
||||
let next = str_param(p, "nextStyle").map(str::to_string);
|
||||
s.edit(|d, _| {
|
||||
@@ -638,10 +639,9 @@ fn create_char(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
&& let Some(target) = super::text::format_targets_pub(s).first()
|
||||
{
|
||||
let st = s.doc()?;
|
||||
let story = st.doc.text_story(target.story, target.cell).ok_or(designcraft_doc::DocError::NoStory(target.story))?;
|
||||
// Match paragraph fromSelection's first-character/caret policy, but keep paragraph
|
||||
// attributes inherited instead of freezing the fully resolved character properties.
|
||||
let format = if target.range.is_empty() { story.char_format_at(target.range.start) } else { story.format_after(target.range.start) };
|
||||
let format = super::text::effective_char_format(s, target)?;
|
||||
let mut captured = st.doc.styles.char_style_attrs(&format.style);
|
||||
captured.merge(&format.over);
|
||||
// Replay the explicit fields so null clears a captured value rather than looking absent.
|
||||
@@ -748,18 +748,20 @@ pub fn parse_color(v: &Value) -> Option<designcraft_color::Color> {
|
||||
use designcraft_color::Color;
|
||||
match v {
|
||||
Value::String(s) => Color::from_hex(s),
|
||||
// One scale per colour, not per component: {c: 0.7, y: 12.2} is C 0.7 %, Y 12.2 %. Only a colour whose
|
||||
// One scale per colour, not per component: [1, 128, 255] is 0..255. Only an RGB array whose
|
||||
// components are all within 0..1 is read as fractions (the older form).
|
||||
Value::Array(a) if a.len() >= 3 => {
|
||||
let v = [a[0].as_f64()?, a[1].as_f64()?, a[2].as_f64()?];
|
||||
let scale = if v.iter().any(|&x| x > 1.0) { 255.0 } else { 1.0 };
|
||||
Some(Color::rgb((v[0] / scale) as f32, (v[1] / scale) as f32, (v[2] / scale) as f32))
|
||||
}
|
||||
// `{model, …}` is the colour's own form (as `color.convert` takes and returns it): fractions.
|
||||
Value::Object(o) if o.contains_key("model") => serde_json::from_value(v.clone()).ok(),
|
||||
// Bare CMYK is always 0..100, as documented: C 1 % is a real tint, so values of 1 or less can't
|
||||
// mean fractions (#910).
|
||||
Value::Object(o) => {
|
||||
let g = |k: &str| o.get(k).and_then(Value::as_f64);
|
||||
let v = [g("c")?, g("m")?, g("y")?, g("k")?];
|
||||
let scale = if v.iter().any(|&x| x > 1.0) { 100.0 } else { 1.0 };
|
||||
Some(Color::cmyk((v[0] / scale) as f32, (v[1] / scale) as f32, (v[2] / scale) as f32, (v[3] / scale) as f32))
|
||||
let g = |k: &str| o.get(k).and_then(Value::as_f64).map(|x| (x / 100.0) as f32);
|
||||
Some(Color::cmyk(g("c")?, g("m")?, g("y")?, g("k")?))
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
@@ -837,15 +839,20 @@ fn value_name(color: designcraft_color::Color) -> String {
|
||||
fn load_swatches(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let bytes = match (str_param(p, "path"), str_param(p, "base64")) {
|
||||
(_, Some(b)) => super::file::base64_decode(b),
|
||||
(Some(path), None) => std::fs::read(path).map_err(|e| bad("swatch.load", format!("{path}: {e}")))?,
|
||||
(Some(path), None) => crate::io::read_file(path).map_err(|e| bad("swatch.load", e))?,
|
||||
_ => return Err(bad("swatch.load", "give `path` or `base64`")),
|
||||
};
|
||||
let incoming = designcraft_color::ase::read(&bytes).map_err(|e| bad("swatch.load", e.to_string()))?;
|
||||
let replace = p.get("replace").and_then(Value::as_bool).unwrap_or(false);
|
||||
s.edit(|d, _| {
|
||||
// The position of the first swatch with each name, kept up to date as the file's colors are added.
|
||||
let mut at: std::collections::HashMap<String, usize> = std::collections::HashMap::new();
|
||||
for (i, x) in d.swatches.iter().enumerate() {
|
||||
at.entry(x.name.clone()).or_insert(i);
|
||||
}
|
||||
let (mut added, mut replaced) = (0, 0);
|
||||
for w in incoming {
|
||||
match d.swatches.iter_mut().find(|x| x.name == w.name) {
|
||||
match at.get(&w.name).and_then(|&i| d.swatches.get_mut(i)) {
|
||||
Some(x) if x.locked => {}
|
||||
Some(x) => {
|
||||
if replace {
|
||||
@@ -855,6 +862,7 @@ fn load_swatches(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
None => {
|
||||
at.insert(w.name.clone(), d.swatches.len());
|
||||
d.swatches.push(w);
|
||||
added += 1;
|
||||
}
|
||||
@@ -872,11 +880,7 @@ fn save_swatches(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let bytes = designcraft_color::ase::write(&chosen);
|
||||
match str_param(p, "path") {
|
||||
Some(path) => {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
let written = crate::atomic::write_atomic(std::path::Path::new(path), &bytes);
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
let written = std::fs::write(path, &bytes);
|
||||
written.map_err(|e| bad("swatch.save", format!("{path}: {e}")))?;
|
||||
crate::io::write_file(path, &bytes).map_err(|e| bad("swatch.save", e))?;
|
||||
Ok(json!({"path": path, "bytes": bytes.len()}))
|
||||
}
|
||||
None => Ok(json!({"base64": super::file::base64_encode(&bytes)})),
|
||||
@@ -986,47 +990,30 @@ fn apply_color(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let named = p.get("ids").is_some() || p.get("id").is_some();
|
||||
let text = !named
|
||||
&& (p.get("text").and_then(Value::as_bool).unwrap_or(false) || s.doc()?.selection.text.is_some() || s.doc()?.selection.cells.is_some());
|
||||
if text {
|
||||
let targets = super::text::format_targets(s);
|
||||
// A caret in existing text has no editable range. Refuse it before creating a swatch
|
||||
// or history; an empty story has a format run that the next insertion inherits.
|
||||
if !targets
|
||||
.iter()
|
||||
.any(|t| !t.range.is_empty() || s.active().is_some_and(|d| d.doc.text_story(t.story, t.cell).is_some_and(|st| st.is_empty())))
|
||||
{
|
||||
return Err(bad("object.color", "select the text to colour"));
|
||||
}
|
||||
return s.edit(|d, _| {
|
||||
let name = color_swatch(d, color);
|
||||
for t in &targets {
|
||||
let Some(story) = d.text_story_mut(t.story, t.cell) else { continue };
|
||||
let set = |f: &mut designcraft_doc::CharFormat| {
|
||||
if stroke {
|
||||
(f.over.stroke, f.over.stroke_tint) = (Some(name.clone()), Some(1.0));
|
||||
} else {
|
||||
(f.over.fill, f.over.fill_tint) = (Some(name.clone()), Some(1.0));
|
||||
}
|
||||
};
|
||||
if t.range.is_empty() {
|
||||
if story.is_empty()
|
||||
&& let Some(run) = story.chars.first_mut()
|
||||
{
|
||||
set(&mut run.format);
|
||||
story.rev = story.rev.wrapping_add(1);
|
||||
}
|
||||
} else {
|
||||
story.format_chars(t.range.clone(), set);
|
||||
}
|
||||
}
|
||||
Ok(json!({"swatch": name}))
|
||||
});
|
||||
let (ids, texts) = if text { (vec![], super::text::format_targets_pub(s)) } else { (super::targets(s, p)?, vec![]) };
|
||||
if text && texts.is_empty() {
|
||||
return Err(bad("object.color", "select the text to colour"));
|
||||
}
|
||||
let ids = super::targets(s, p)?;
|
||||
s.edit(|d, _| {
|
||||
// A caret: the colour is for the next typing (once the swatch exists).
|
||||
let caret = matches!(texts.as_slice(), [t] if t.range.is_empty());
|
||||
let r = s.edit(|d, _| {
|
||||
let name = color_swatch(d, color);
|
||||
color_items(d, &ids, &name, stroke);
|
||||
if !caret {
|
||||
let a = if stroke {
|
||||
CharAttrs { stroke: Some(name.clone()), stroke_tint: Some(1.0), ..Default::default() }
|
||||
} else {
|
||||
CharAttrs { fill: Some(name.clone()), fill_tint: Some(1.0), ..Default::default() }
|
||||
};
|
||||
super::text::apply_char_attrs(d, &texts, &a, &[]);
|
||||
}
|
||||
Ok(json!({"swatch": name}))
|
||||
})
|
||||
})?;
|
||||
if caret && let Some(name) = r.get("swatch").cloned() {
|
||||
let attrs = if stroke { json!({"stroke": name, "strokeTint": 1.0}) } else { json!({"fill": name, "fillTint": 1.0}) };
|
||||
super::text::format_chars(s, &attrs)?;
|
||||
}
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
/// A process swatch holding exactly `color`, else a new unnamed one (hidden from the Swatches
|
||||
@@ -1153,7 +1140,7 @@ fn add_to_swatches(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
};
|
||||
let rename = str_param(p, "name").map(str::to_string);
|
||||
s.edit(|d, _| {
|
||||
let result = s.edit(|d, _| {
|
||||
let w = d.swatches.iter_mut().find(|w| w.name == name).ok_or_else(|| bad("swatch.addToSwatches", format!("no swatch `{name}`")))?;
|
||||
if w.locked {
|
||||
return Err(bad("swatch.addToSwatches", "special swatches are already listed"));
|
||||
@@ -1180,8 +1167,84 @@ fn add_to_swatches(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
rename_in(std::sync::Arc::make_mut(top), &name, &new);
|
||||
}
|
||||
}
|
||||
for st in d.stories.values_mut() {
|
||||
let mut copy = (**st).clone();
|
||||
if rename_in_story(&mut copy, &name, &new, 0)? {
|
||||
*st = std::sync::Arc::new(copy);
|
||||
}
|
||||
}
|
||||
Ok(json!({"name": new}))
|
||||
})
|
||||
})?;
|
||||
if let Some(new) = result.get("name").and_then(Value::as_str) {
|
||||
super::text::rename_typing_swatch(s, &name, new);
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
/// Point text colours (character fill, stroke, underline and strikethrough; paragraph shading,
|
||||
/// border and rules; table cells, borders and alternating fills) at a renamed swatch, in a story
|
||||
/// and the texts inside it (table cells, footnotes, endnotes). Returns whether anything changed.
|
||||
fn rename_in_story(st: &mut designcraft_doc::Story, from: &str, to: &str, depth: usize) -> Result<bool> {
|
||||
// Refuse the whole edit instead of leaving deeper references pointing at a removed name.
|
||||
if depth > 32 {
|
||||
return Err(bad("swatch.addToSwatches", "story nesting exceeds 32 levels"));
|
||||
}
|
||||
fn fix(s: &mut String, from: &str, to: &str) -> bool {
|
||||
let hit = s == from;
|
||||
if hit {
|
||||
*s = to.to_string();
|
||||
}
|
||||
hit
|
||||
}
|
||||
let mut n = 0;
|
||||
let mut f = |s: &mut String| n += usize::from(fix(s, from, to));
|
||||
for r in &mut st.chars {
|
||||
let o = &mut r.format.over;
|
||||
for c in [&mut o.fill, &mut o.stroke, &mut o.underline_color, &mut o.strikethrough_color].into_iter().flatten() {
|
||||
f(c);
|
||||
}
|
||||
}
|
||||
for pf in &mut st.paras {
|
||||
let a = &mut pf.para;
|
||||
for c in [&mut a.shading_color, &mut a.border_color].into_iter().flatten() {
|
||||
f(c);
|
||||
}
|
||||
for r in [&mut a.rule_above, &mut a.rule_below].into_iter().flatten() {
|
||||
f(&mut r.color);
|
||||
}
|
||||
}
|
||||
let mut nested = false;
|
||||
for t in st.tables.values_mut() {
|
||||
let t = std::sync::Arc::make_mut(t);
|
||||
let o = &mut t.options;
|
||||
f(&mut o.border.color);
|
||||
for b in o.borders.iter_mut().flatten() {
|
||||
f(&mut b.color);
|
||||
}
|
||||
for a in [&mut o.alt_rows, &mut o.alt_cols].into_iter().flatten() {
|
||||
f(&mut a.first_color);
|
||||
f(&mut a.next_color);
|
||||
}
|
||||
for k in [&mut o.row_strokes, &mut o.column_strokes].into_iter().flatten() {
|
||||
f(&mut k.first_stroke.color);
|
||||
f(&mut k.next_stroke.color);
|
||||
}
|
||||
for c in &mut t.cells {
|
||||
f(&mut c.fill);
|
||||
for k in &mut c.strokes {
|
||||
f(&mut k.color);
|
||||
}
|
||||
nested |= rename_in_story(&mut c.text, from, to, depth + 1)?;
|
||||
}
|
||||
}
|
||||
for note in st.notes.iter_mut().chain(st.endnotes.iter_mut()) {
|
||||
nested |= rename_in_story(&mut std::sync::Arc::make_mut(note).text, from, to, depth + 1)?;
|
||||
}
|
||||
let changed = n > 0 || nested;
|
||||
if changed {
|
||||
st.rev = st.rev.wrapping_add(1);
|
||||
}
|
||||
Ok(changed)
|
||||
}
|
||||
|
||||
/// Point fills and strokes of an item (and its children) at a renamed swatch.
|
||||
@@ -1266,17 +1329,38 @@ mod color_tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn char_fill_rejects_inherited_unknown_name_when_creating_from_selection() {
|
||||
let mut session = fill_session();
|
||||
session
|
||||
.edit(|document, selection| {
|
||||
let selected = selection.text.unwrap();
|
||||
document.story_mut(selected.story).unwrap().format_chars(selected.range(), |format| format.over.fill = Some("Missing Ink".into()));
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
fn char_fill_preserves_deleted_swatch_when_creating_from_selection() {
|
||||
for params in
|
||||
[json!({"name": "Inherited", "fromSelection": true}), json!({"name": "Inherited", "fromSelection": true, "chars": {"size": 24}})]
|
||||
{
|
||||
let mut session = fill_session();
|
||||
let swatch = session.execute("swatch.create", &json!({"name": "Deleted Ink", "color": "#108080"})).unwrap();
|
||||
let fill = swatch["name"].as_str().unwrap();
|
||||
session.execute("type.char", &json!({"fill": fill})).unwrap();
|
||||
session.execute("swatch.delete", &json!({"name": fill})).unwrap();
|
||||
assert_eq!(session.execute("type.selectionAttrs", &json!({})).unwrap()["chars"]["fill"], fill);
|
||||
|
||||
assert_fill_rejected(&mut session, "style.paragraph.create", json!({"name": "Inherited", "fromSelection": true}));
|
||||
session.execute("style.paragraph.create", ¶ms).unwrap();
|
||||
|
||||
let chars = &session.doc().unwrap().doc.styles.para("Inherited").unwrap().chars;
|
||||
assert_eq!(chars.fill.as_deref(), Some(fill));
|
||||
if params.get("chars").is_some() {
|
||||
assert_eq!(chars.size, Some(24.0));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn char_fill_rejects_explicit_unknown_name_when_creating_from_selection() {
|
||||
for fill in ["Missing Ink", "#ff0000"] {
|
||||
let mut session = fill_session();
|
||||
|
||||
assert_fill_rejected(
|
||||
&mut session,
|
||||
"style.paragraph.create",
|
||||
json!({"name": "Explicit", "fromSelection": true, "chars": {"fill": fill, "size": 24}}),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1357,14 +1441,43 @@ mod color_tests {
|
||||
// {"c": 0.7, ..., "y": 12.2} is a pale cream (C 0.7 %, Y 12.2 %), not C 70 %.
|
||||
let Some(Color::Cmyk { c, m, y, k }) = parse_color(&json!({"c": 0.7, "m": 0, "y": 12.2, "k": 0})) else { panic!("not CMYK") };
|
||||
assert!((c - 0.007).abs() < 1e-6 && m == 0.0 && (y - 0.122).abs() < 1e-6 && k == 0.0, "got {c} {m} {y} {k}");
|
||||
// Fractions (every component within 0..1) keep working.
|
||||
let Some(Color::Cmyk { c, k, .. }) = parse_color(&json!({"c": 0.5, "m": 0, "y": 0, "k": 1})) else { panic!("not CMYK") };
|
||||
// Fractions take the colour's own form, with its model.
|
||||
let Some(Color::Cmyk { c, k, .. }) = parse_color(&json!({"model": "cmyk", "c": 0.5, "m": 0, "y": 0, "k": 1})) else { panic!("not CMYK") };
|
||||
assert!((c - 0.5).abs() < 1e-6 && (k - 1.0).abs() < 1e-6);
|
||||
// RGB arrays follow the same rule: [1, 128, 255] is 0..255.
|
||||
let Some(Color::Rgb { r, g, b }) = parse_color(&json!([1, 128, 255])) else { panic!("not RGB") };
|
||||
assert!((r - 1.0 / 255.0).abs() < 1e-6 && (g - 128.0 / 255.0).abs() < 1e-6 && (b - 1.0).abs() < 1e-6);
|
||||
}
|
||||
|
||||
/// #910: `{c: 1, m: 0, y: 0, k: 0}` is a 1 % cyan tint, not solid cyan, though every component is within 0..1.
|
||||
#[test]
|
||||
fn cmyk_percentages_of_one_or_less_stay_percent() {
|
||||
use designcraft_color::Color;
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
let id = s.execute("frame.create", &json!({"rect": [0, 0, 50, 50]})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("swatch.create", &json!({"name": "Tint1", "color": {"c": 1, "m": 0, "y": 0, "k": 0}})).unwrap();
|
||||
s.execute("object.fill", &json!({"ids": [id], "swatch": "Tint1"})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let Some(Color::Cmyk { c, m, y, k }) = d.resolve_color("Tint1", 1.0) else { panic!("not CMYK") };
|
||||
assert!((c - 0.01).abs() < 1e-6 && m == 0.0 && y == 0.0 && k == 0.0, "got {c} {m} {y} {k}");
|
||||
let pdf = designcraft_pdf::export_pdf(d, &s.cache, &designcraft_pdf::PdfOptions { compress: false, ..Default::default() }).unwrap();
|
||||
let text = String::from_utf8_lossy(&pdf);
|
||||
// Operands of every `k` (DeviceCMYK fill), last first: [k, y, m, c]. Inks are written in 1/255 steps (C 1 % is 3/255).
|
||||
let fills: Vec<Vec<f32>> =
|
||||
text.split(" k ").filter_map(|before| before.rsplit(' ').take(4).map(|x| x.parse().ok()).collect::<Option<Vec<f32>>>()).collect();
|
||||
let cyan = |want: f32| fills.iter().any(|f| (f[3] - want).abs() < 0.5 / 255.0 + 1e-6 && f[..3] == [0.0; 3]);
|
||||
assert!(cyan(0.01), "C 1 % in the PDF: {fills:?}");
|
||||
assert!(!cyan(1.0), "no solid cyan: {fills:?}");
|
||||
// A light tint whose components are all 1 or less, through object.color.
|
||||
s.execute("selection.set", &json!({"ids": [id]})).unwrap();
|
||||
s.execute("object.color", &json!({"color": {"c": 0.5, "m": 0.5, "y": 0, "k": 0}})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let fill = &d.item(designcraft_doc::ItemId(id)).unwrap().fill.swatch;
|
||||
let Some(Color::Cmyk { c, m, .. }) = d.resolve_color(fill, 1.0) else { panic!("not CMYK") };
|
||||
assert!((c - 0.005).abs() < 1e-6 && (m - 0.005).abs() < 1e-6, "got {c} {m}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn style_groups_rename_every_use() {
|
||||
let mut s = Session::new();
|
||||
@@ -1468,6 +1581,39 @@ mod color_tests {
|
||||
assert!(s.execute("swatch.load", &json!({"base64": "AAAA"})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn loading_swatches_matches_the_first_swatch_of_each_name() {
|
||||
use designcraft_color::{Color, ColorType};
|
||||
let ink = |k: f32| SwatchValue::Color { color: Color::cmyk(0.0, 0.0, 0.0, k), color_type: ColorType::Process };
|
||||
let sw = |name: &str, k: f32| Swatch { name: name.into(), value: ink(k), locked: false, named: true, hidden: false };
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
// Two swatches share a name, and an unnamed color is hidden.
|
||||
s.edit(|d, _| {
|
||||
d.swatches.extend([sw("Twin", 0.1), sw("Twin", 0.2), Swatch { named: false, hidden: true, ..sw("Unnamed", 0.3) }]);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let file = designcraft_color::ase::write(&[sw("New", 0.4), sw("New", 0.5), sw("Twin", 0.6), sw("Unnamed", 0.7), sw("[Black]", 0.8)]);
|
||||
let b64 = crate::cmd::base64_encode(&file);
|
||||
let named = |s: &Session, name: &str| -> Vec<(SwatchValue, bool)> {
|
||||
s.doc().unwrap().doc.swatches.iter().filter(|w| w.name == name).map(|w| (w.value.clone(), w.hidden)).collect()
|
||||
};
|
||||
// With `replace`, the file's second "New" replaces its first, only the first "Twin" changes, the hidden
|
||||
// swatch becomes visible, and the locked [Black] stays.
|
||||
let r = s.execute("swatch.load", &json!({"base64": b64, "replace": true})).unwrap();
|
||||
assert_eq!((r["added"].as_u64(), r["replaced"].as_u64()), (Some(1), Some(3)));
|
||||
assert_eq!(named(&s, "New"), [(ink(0.5), false)]);
|
||||
assert_eq!(named(&s, "Twin"), [(ink(0.6), false), (ink(0.2), false)]);
|
||||
assert_eq!(named(&s, "Unnamed"), [(ink(0.7), false)]);
|
||||
assert_eq!(named(&s, "[Black]"), [(ink(1.0), false)]);
|
||||
// Without it, every name is already there and nothing changes.
|
||||
let before = s.doc().unwrap().doc.swatches.clone();
|
||||
let r = s.execute("swatch.load", &json!({"base64": b64})).unwrap();
|
||||
assert_eq!((r["added"].as_u64(), r["replaced"].as_u64()), (Some(0), Some(0)));
|
||||
assert_eq!(s.doc().unwrap().doc.swatches, before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unnamed_colors_then_add_to_swatches() {
|
||||
let mut s = Session::new();
|
||||
@@ -1495,6 +1641,40 @@ mod color_tests {
|
||||
s.execute("object.color", &json!({"color": {"c": 10, "m": 20, "y": 30, "k": 0}})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.item(designcraft_doc::ItemId(id)).unwrap().fill.swatch, "Sand");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn add_to_swatches_renames_the_colour_in_text_cells_and_notes() {
|
||||
use std::sync::Arc;
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
let r = s.execute("frame.create", &json!({"rect": [72, 72, 400, 300], "content": "text", "text": "Hello world"})).unwrap();
|
||||
let sid = designcraft_doc::StoryId(r["story"].as_u64().unwrap());
|
||||
s.execute("text.select", &json!({"story": sid.0, "anchor": 11})).unwrap();
|
||||
s.execute("footnote.insert", &json!({"text": "note"})).unwrap();
|
||||
s.execute("text.select", &json!({"story": sid.0, "anchor": 0})).unwrap();
|
||||
s.execute("table.insert", &json!({"rows": 1, "cols": 1})).unwrap();
|
||||
s.execute("text.select", &json!({"story": sid.0, "anchor": 1, "focus": 4})).unwrap();
|
||||
let old = s.execute("object.color", &json!({"color": {"c": 10, "m": 20, "y": 30, "k": 0}})).unwrap()["swatch"].as_str().unwrap().to_string();
|
||||
// The same unnamed colour on a cell, the cell's text and the footnote's text.
|
||||
s.edit(|d, _| {
|
||||
let st = d.story_mut(sid).unwrap();
|
||||
let t = Arc::make_mut(st.tables.values_mut().next().unwrap());
|
||||
t.cells[0].fill = old.clone();
|
||||
t.cells[0].text.chars[0].format.over.fill = Some(old.clone());
|
||||
Arc::make_mut(&mut st.notes[0]).text.chars[0].format.over.stroke = Some(old.clone());
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("swatch.addToSwatches", &json!({"swatch": old, "name": "Sand"})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let st = d.story(sid).unwrap();
|
||||
assert_eq!(st.char_format_at(2).over.fill.as_deref(), Some("Sand"));
|
||||
let cell = &st.tables.values().next().unwrap().cells[0];
|
||||
assert_eq!(cell.fill, "Sand");
|
||||
assert_eq!(cell.text.chars[0].format.over.fill.as_deref(), Some("Sand"));
|
||||
assert_eq!(st.notes[0].text.chars[0].format.over.stroke.as_deref(), Some("Sand"));
|
||||
d.check().unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -1708,15 +1888,16 @@ mod sample_color_tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nothing_to_sample_or_nothing_to_colour_is_refused_without_an_edit() {
|
||||
fn nothing_to_sample_is_refused_without_an_edit() {
|
||||
let (mut s, _) = session_with_image();
|
||||
let f = s.execute("frame.create", &json!({"rect": [300, 300, 500, 360], "content": "text", "text": "Hi"})).unwrap();
|
||||
let fid = ItemId(f["id"].as_u64().unwrap());
|
||||
let story = s.doc().unwrap().doc.item(fid).unwrap().text_frame().unwrap().story;
|
||||
s.execute("text.select", &json!({"story": story.0, "anchor": 1, "focus": 1})).unwrap();
|
||||
let sampled = s.execute("color.sample", &json!({"at": [100, 100]})).unwrap();
|
||||
assert_eq!(s.execute("type.selectionAttrs", &json!({})).unwrap()["chars"]["fill"], sampled["swatch"]);
|
||||
assert_eq!(s.doc().unwrap().doc.story(story).unwrap().text, "Hi", "caret color waits for typing");
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
let caret = s.execute("color.sample", &json!({"at": [100, 100]})).unwrap_err().to_string();
|
||||
assert!(caret.contains("select the text"), "{caret}");
|
||||
s.execute("text.select", &json!({"story": story.0, "anchor": 0, "focus": 2})).unwrap();
|
||||
let none = s.execute("color.sample", &json!({"at": [600, 600]})).unwrap_err().to_string();
|
||||
assert!(none.contains("no placed image"), "{none}");
|
||||
@@ -1750,4 +1931,72 @@ mod sample_color_tests {
|
||||
assert_eq!(text.format_after(0).over.stroke.as_deref(), r["swatch"].as_str(), "selected text stroke: {command}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sampling_with_the_stroke_in_front_colours_a_lines_stroke() {
|
||||
let (mut s, _) = session_with_image();
|
||||
let line = s.execute("line.create", &json!({"a": [300, 300], "b": [500, 300]})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("selection.set", &json!({"ids": [line]})).unwrap();
|
||||
let r = s.execute("color.sample", &json!({"at": [100, 100], "target": "stroke"})).unwrap();
|
||||
let it = s.doc().unwrap().doc.item(ItemId(line)).unwrap().clone();
|
||||
assert_eq!(it.stroke.swatch, r["swatch"].as_str().unwrap(), "{r}");
|
||||
assert!(it.fill.is_none(), "the fill stays empty");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod radial_gradient_tests {
|
||||
use serde_json::json;
|
||||
|
||||
/// White at the side and the top of a 100×200 radial (black → white) rectangle at (50, 20) on
|
||||
/// a 200×240 page, rendered at 1 px/pt.
|
||||
fn sides(img: &designcraft_render::Rendered) -> (u8, u8, u8) {
|
||||
(img.pixel(100, 120)[0], img.pixel(52, 120)[0], img.pixel(100, 22)[0])
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_radial_gradient_is_the_objects_ellipse_on_screen_and_in_pdf() {
|
||||
let mut s = crate::Session::new();
|
||||
s.execute("file.new", &json!({"width": 200, "height": 240, "facingPages": false})).unwrap();
|
||||
let id = s.execute("frame.create", &json!({"rect": [50, 20, 150, 220], "content": "unassigned"})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("object.stroke", &json!({"ids": [id], "swatch": "[None]"})).unwrap();
|
||||
s.execute(
|
||||
"object.gradient",
|
||||
&json!({"ids": [id], "kind": "radial", "stops": [{"location": 0, "color": "#000000"}, {"location": 100, "color": "#ffffff"}]}),
|
||||
)
|
||||
.unwrap();
|
||||
let d = s.doc().unwrap().doc.clone();
|
||||
let mut r = designcraft_render::Renderer::new();
|
||||
let (c, side, top) = sides(&r.render_page(&d, &s.cache, 0, 1.0, false, &Default::default()).unwrap());
|
||||
assert!(c < 30 && side > 220 && top > 220, "screen: centre {c}, side {side}, top {top}");
|
||||
// The PDF, placed back and drawn: the same ellipse.
|
||||
let pdf = designcraft_pdf::export_pdf(&d, &s.cache, &Default::default()).unwrap();
|
||||
let mut p = crate::Session::new();
|
||||
p.execute("file.new", &json!({"width": 200, "height": 240, "facingPages": false})).unwrap();
|
||||
p.execute("file.place", &json!({"base64": crate::cmd::file::base64_encode(&pdf), "name": "radial.pdf", "x": 0, "y": 0, "width": 200}))
|
||||
.unwrap();
|
||||
let d = p.doc().unwrap().doc.clone();
|
||||
let (c, side, top) = sides(&r.render_page(&d, &p.cache, 0, 1.0, false, &Default::default()).unwrap());
|
||||
assert!(c < 30 && side > 220 && top > 220, "pdf: centre {c}, side {side}, top {top}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_box_with_no_height_or_width_has_a_circle_across_its_length() {
|
||||
let f = designcraft_doc::Fill::swatch("g");
|
||||
let line = designcraft_geom::Rect::new(20.0, 60.0, 180.0, 60.0);
|
||||
let (c, rx, ry) = f.radial_ellipse(line);
|
||||
assert_eq!((c.x, c.y, rx, ry), (100.0, 60.0, 80.0, 80.0));
|
||||
let (_, rx, ry) = f.radial_ellipse(designcraft_geom::Rect::new(10.0, 0.0, 10.0, 50.0));
|
||||
assert_eq!((rx, ry), (25.0, 25.0));
|
||||
// A point: a tiny circle, never a zero radius.
|
||||
let (_, rx, ry) = f.radial_ellipse(designcraft_geom::Rect::new(5.0, 5.0, 5.0, 5.0));
|
||||
assert!(rx > 0.0 && rx == ry);
|
||||
// A box keeps its ellipse.
|
||||
let (_, rx, ry) = f.radial_ellipse(designcraft_geom::Rect::new(0.0, 0.0, 100.0, 200.0));
|
||||
assert_eq!((rx, ry), (50.0, 100.0));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "text_color_tests.rs"]
|
||||
mod text_color_tests;
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
//! whole table).
|
||||
|
||||
use designcraft_compose as compose;
|
||||
use designcraft_doc::story::floor_char_boundary;
|
||||
use designcraft_doc::{
|
||||
AltFills, CellAddr, CellRange, CellStroke, Document, RowHeightMode, Selection, StoryId, StrokeType, Table, TableSel, TextSel,
|
||||
VerticalJustification,
|
||||
@@ -140,11 +141,9 @@ fn table_specs() -> Vec<CommandSpec> {
|
||||
|s, p| {
|
||||
let g = target(s, p, "table.textCell")?;
|
||||
edit_table(s, &g, "table.textCell", |t| {
|
||||
for r in g.range.r0..=g.range.r1 {
|
||||
for c in g.range.c0..=g.range.c1 {
|
||||
if let Some(cell) = t.cell_mut(r, c) {
|
||||
cell.graphic = None;
|
||||
}
|
||||
for (r, c) in t.selected_owners(g.range) {
|
||||
if let Some(cell) = t.cell_mut(r, c) {
|
||||
cell.graphic = None;
|
||||
}
|
||||
}
|
||||
ok()
|
||||
@@ -351,13 +350,17 @@ fn clamp_selection(d: &Document, sel: &mut Selection) {
|
||||
match story.and_then(|x| x.tables.get(&c.table)) {
|
||||
Some(tb) => {
|
||||
let (r, col) = tb.owner(c.row.min(tb.nrows() - 1), c.col.min(tb.ncols() - 1));
|
||||
let len = tb.cell(r, col).map_or(0, |x| x.text.len());
|
||||
sel.text =
|
||||
Some(TextSel { anchor: t.anchor.min(len), focus: t.focus.min(len), cell: Some(CellAddr { table: c.table, row: r, col }), ..t });
|
||||
let text = tb.cell(r, col).map_or("", |x| x.text.text.as_str());
|
||||
sel.text = Some(TextSel {
|
||||
anchor: floor_char_boundary(text, t.anchor),
|
||||
focus: floor_char_boundary(text, t.focus),
|
||||
cell: Some(CellAddr { table: c.table, row: r, col }),
|
||||
..t
|
||||
});
|
||||
}
|
||||
None => {
|
||||
let len = story.map_or(0, |x| x.len());
|
||||
sel.text = Some(TextSel { anchor: t.anchor.min(len), focus: t.anchor.min(len), cell: None, ..t });
|
||||
let pos = story.map_or(0, |x| floor_char_boundary(&x.text, t.anchor));
|
||||
sel.text = Some(TextSel { anchor: pos, focus: pos, cell: None, ..t });
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -648,7 +651,6 @@ fn set_cell(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let text = str_param(p, "text").map(|_| super::text_param(p, "text"));
|
||||
let stroke = p.get("stroke").cloned();
|
||||
edit_table(s, &g, "table.setCell", |t| {
|
||||
let owners = t.owners();
|
||||
let nc = t.ncols();
|
||||
let nr = t.nrows();
|
||||
let rtl = t.options.direction == designcraft_doc::TextDirection::RightToLeft;
|
||||
@@ -656,50 +658,45 @@ fn set_cell(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// Local edits outrank previously imported edges, including explicit zero/None.
|
||||
let priority = if stroke.is_some() { next_cell_stroke_priority(t) } else { 0 };
|
||||
let rg = g.range;
|
||||
for r in rg.r0..=rg.r1 {
|
||||
for c in rg.c0..=rg.c1 {
|
||||
if owners[r * nc + c] != (r, c) {
|
||||
continue;
|
||||
}
|
||||
let Some(cell) = t.cell_mut(r, c) else { continue };
|
||||
if let Some(f) = &fill {
|
||||
cell.fill = f.clone();
|
||||
}
|
||||
if let Some(ti) = tint {
|
||||
cell.fill_tint = ti;
|
||||
}
|
||||
if let Some(i) = insets {
|
||||
cell.insets = i;
|
||||
}
|
||||
if let Some(v) = vj {
|
||||
cell.vj = v;
|
||||
}
|
||||
if let Some(tx) = &text {
|
||||
let len = cell.text.len();
|
||||
cell.text.replace(0..len, tx);
|
||||
}
|
||||
if let Some(sv) = &stroke {
|
||||
let edges = str_param(sv, "edges").unwrap_or("all");
|
||||
let at_bottom = r.saturating_add(cell.row_span.max(1) as usize);
|
||||
let at_right = c.saturating_add(cell.col_span.max(1) as usize);
|
||||
let perimeter = [r == 0, if rtl { at_right == nc } else { c == 0 }, at_bottom == nr, if rtl { c == 0 } else { at_right == nc }];
|
||||
for (i, on) in [
|
||||
("top", r == rg.r0),
|
||||
("left", if rtl { at_right.saturating_sub(1) == rg.c1 } else { c == rg.c0 }),
|
||||
("bottom", at_bottom.saturating_sub(1) == rg.r1),
|
||||
("right", if rtl { c == rg.c0 } else { at_right.saturating_sub(1) == rg.c1 }),
|
||||
]
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, (name, outer))| (i, edges == "all" || edges == *name || (edges == "outer" && *outer) || (edges == "inner" && !*outer)))
|
||||
{
|
||||
if on {
|
||||
let base = if perimeter[i] && !cell.border_overrides[i] { &borders[i] } else { &cell.strokes[i] };
|
||||
cell.strokes[i] = parse_stroke(sv, base.clone());
|
||||
cell.stroke_defined[i] = true;
|
||||
cell.stroke_priorities[i] = priority;
|
||||
cell.border_overrides[i] = true;
|
||||
}
|
||||
for (r, c) in t.selected_owners(rg) {
|
||||
let Some(cell) = t.cell_mut(r, c) else { continue };
|
||||
if let Some(f) = &fill {
|
||||
cell.fill = f.clone();
|
||||
}
|
||||
if let Some(ti) = tint {
|
||||
cell.fill_tint = ti;
|
||||
}
|
||||
if let Some(i) = insets {
|
||||
cell.insets = i;
|
||||
}
|
||||
if let Some(v) = vj {
|
||||
cell.vj = v;
|
||||
}
|
||||
if let Some(tx) = &text {
|
||||
let len = cell.text.len();
|
||||
cell.text.replace(0..len, tx);
|
||||
}
|
||||
if let Some(sv) = &stroke {
|
||||
let edges = str_param(sv, "edges").unwrap_or("all");
|
||||
let at_bottom = r.saturating_add(cell.row_span.max(1) as usize);
|
||||
let at_right = c.saturating_add(cell.col_span.max(1) as usize);
|
||||
let perimeter = [r == 0, if rtl { at_right == nc } else { c == 0 }, at_bottom == nr, if rtl { c == 0 } else { at_right == nc }];
|
||||
for (i, on) in [
|
||||
("top", r == rg.r0),
|
||||
("left", if rtl { at_right.saturating_sub(1) == rg.c1 } else { c == rg.c0 }),
|
||||
("bottom", at_bottom.saturating_sub(1) == rg.r1),
|
||||
("right", if rtl { c == rg.c0 } else { at_right.saturating_sub(1) == rg.c1 }),
|
||||
]
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, (name, outer))| (i, edges == "all" || edges == *name || (edges == "outer" && *outer) || (edges == "inner" && !*outer)))
|
||||
{
|
||||
if on {
|
||||
let base = if perimeter[i] && !cell.border_overrides[i] { &borders[i] } else { &cell.strokes[i] };
|
||||
cell.strokes[i] = parse_stroke(sv, base.clone());
|
||||
cell.stroke_defined[i] = true;
|
||||
cell.stroke_priorities[i] = priority;
|
||||
cell.border_overrides[i] = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -707,6 +704,7 @@ fn set_cell(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// Keep both copies of unmerged shared boundaries consistent. Left/right name
|
||||
// physical sides, also in RTL tables.
|
||||
if let Some(sv) = &stroke {
|
||||
let owners = t.owners();
|
||||
let edges = str_param(sv, "edges").unwrap_or("all");
|
||||
let selected = |side: &str| edges == "all" || edges == "outer" || edges == side;
|
||||
if selected("top")
|
||||
@@ -931,8 +929,9 @@ fn options(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if let Some(v) = p.get("altCols") {
|
||||
o.alt_cols = parse_alt(v);
|
||||
}
|
||||
let h = p.get("headerRows").and_then(Value::as_u64).map(|v| v as usize);
|
||||
let f = p.get("footerRows").and_then(Value::as_u64).map(|v| v as usize);
|
||||
// At most 100 of each, as in `table.insert`: the rows the table lacks are added below.
|
||||
let h = p.get("headerRows").and_then(Value::as_u64).map(|v| v.min(100) as usize);
|
||||
let f = p.get("footerRows").and_then(Value::as_u64).map(|v| v.min(100) as usize);
|
||||
if h.is_some() || f.is_some() {
|
||||
let (h, f) = (h.unwrap_or(t.header_rows()), f.unwrap_or(t.footer_rows()));
|
||||
// Add rows when there aren't enough for the requested header/footer plus one body row.
|
||||
@@ -1095,7 +1094,10 @@ fn cell_style_create(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cell = d
|
||||
.story(g.story)
|
||||
.and_then(|st| st.tables.get(&g.table))
|
||||
.and_then(|t| t.cell(g.range.r0, g.range.c0))
|
||||
.and_then(|t| {
|
||||
let (r, c) = t.owner(g.range.r0, g.range.c0);
|
||||
t.cell(r, c)
|
||||
})
|
||||
.ok_or_else(|| bad("style.cell.create", "no cell"))?;
|
||||
cs.fill = Some(cell.fill.clone());
|
||||
cs.fill_tint = Some(cell.fill_tint);
|
||||
@@ -1122,17 +1124,11 @@ fn cell_style_apply(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cs = designcraft_doc::resolve_cell_style(styles, &name);
|
||||
let g = target(s, p, "style.cell.apply")?;
|
||||
edit_table(s, &g, "style.cell.apply", |t| {
|
||||
let owners = t.owners();
|
||||
let nc = t.ncols();
|
||||
let mut n = 0;
|
||||
for r in g.range.r0..=g.range.r1 {
|
||||
for c in g.range.c0..=g.range.c1 {
|
||||
if owners[r * nc + c] == (r, c)
|
||||
&& let Some(cell) = t.cell_mut(r, c)
|
||||
{
|
||||
cs.apply_to(cell);
|
||||
n += 1;
|
||||
}
|
||||
for (r, c) in t.selected_owners(g.range) {
|
||||
if let Some(cell) = t.cell_mut(r, c) {
|
||||
cs.apply_to(cell);
|
||||
n += 1;
|
||||
}
|
||||
}
|
||||
Ok(json!({"cells": n}))
|
||||
@@ -1353,7 +1349,7 @@ fn drop_cells(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
&& ts.story == sid
|
||||
&& ts.table == tid
|
||||
&& tid2 == tid
|
||||
&& ts.range.contains(fr, fc)
|
||||
&& s.doc()?.doc.story(sid).and_then(|st| st.tables.get(&tid)).is_some_and(|t| t.selected_owners(ts.range).binary_search(&(fr, fc)).is_ok())
|
||||
{
|
||||
let (nr, nc) = {
|
||||
let t = s.doc()?.doc.story(sid).and_then(|st| st.tables.get(&tid)).ok_or_else(|| bad(ID, "no table"))?;
|
||||
@@ -1680,6 +1676,19 @@ mod sort_tests {
|
||||
s.execute("table.moveColumn", &json!({"from": 1, "to": 0})).unwrap();
|
||||
assert_eq!((cell(&s, 2, 0), cell(&s, 2, 1)), ("x".to_string(), "a".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn table_options_limits_header_and_footer_rows() {
|
||||
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": 2, "cols": 2})).unwrap();
|
||||
// The limit `table.insert` has: the table used to grow by as many rows as were asked for.
|
||||
s.execute("table.options", &json!({"headerRows": 5000, "footerRows": 5000})).unwrap();
|
||||
let t = table(&s);
|
||||
assert_eq!((t.header_rows(), t.footer_rows(), t.nrows()), (100, 100, 201));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
+804
-69
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,181 @@
|
||||
//! Cross-command caret color and character-style regressions.
|
||||
use crate::Session;
|
||||
use designcraft_doc::StoryId;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
fn setup(text: &str) -> (Session, u64) {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
let f = s.execute("frame.create", &json!({"rect": [36,36,300,200], "content":"text", "text":text})).unwrap();
|
||||
let sid = f["story"].as_u64().unwrap();
|
||||
s.execute("text.select", &json!({"story":sid,"anchor":text.len()})).unwrap();
|
||||
(s, sid)
|
||||
}
|
||||
fn attrs(s: &mut Session) -> Value {
|
||||
s.execute("type.selectionAttrs", &json!({})).unwrap()["chars"].clone()
|
||||
}
|
||||
#[test]
|
||||
fn integration_color_character_style_captures_pending_and_null() {
|
||||
let (mut s, sid) = setup("hello");
|
||||
s.execute("type.char", &json!({"size":30,"tracking":40,"fill":"[Paper]"})).unwrap();
|
||||
s.execute("style.character.create", &json!({"name":"Pending","fromSelection":true,"chars":{"tracking":null}})).unwrap();
|
||||
let a = &s.doc().unwrap().doc.styles.char_style("Pending").unwrap().chars;
|
||||
assert_eq!(a.size, Some(30.0));
|
||||
assert_eq!(a.fill.as_deref(), Some("[Paper]"));
|
||||
assert_eq!(a.tracking, None);
|
||||
assert_eq!(s.doc().unwrap().doc.story(StoryId(sid)).unwrap().text, "hello");
|
||||
}
|
||||
#[test]
|
||||
fn integration_color_pending_follows_promoted_swatch() {
|
||||
for target in ["fill", "stroke"] {
|
||||
let (mut s, sid) = setup("hello");
|
||||
let old = s.execute("object.color", &json!({"color":"#123456","target":target})).unwrap()["swatch"].clone();
|
||||
s.execute("swatch.addToSwatches", &json!({"swatch":old,"name":"Brand"})).unwrap();
|
||||
assert_eq!(attrs(&mut s)[target], "Brand");
|
||||
s.execute("text.insert", &json!({"text":"X"})).unwrap();
|
||||
let st = s.doc().unwrap().doc.story(StoryId(sid)).unwrap();
|
||||
let f = &st.format_after(5).over;
|
||||
assert_eq!(if target == "fill" { f.fill.as_deref() } else { f.stroke.as_deref() }, Some("Brand"));
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn integration_color_undo_discards_missing_pending_swatch() {
|
||||
let (mut s, sid) = setup("hello");
|
||||
let old = s.execute("object.color", &json!({"color":"#123456"})).unwrap()["swatch"].as_str().unwrap().to_string();
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(s.doc().unwrap().doc.swatch(&old).is_none());
|
||||
assert_ne!(attrs(&mut s)["fill"], old);
|
||||
s.execute("text.insert", &json!({"text":"X"})).unwrap();
|
||||
assert_ne!(s.doc().unwrap().doc.story(StoryId(sid)).unwrap().format_after(5).over.fill.as_deref(), Some(old.as_str()));
|
||||
}
|
||||
#[test]
|
||||
fn integration_color_empty_story_uses_one_undo_step() {
|
||||
let (mut s, sid) = setup("");
|
||||
let before = serde_json::to_value(s.doc().unwrap().doc.as_ref()).unwrap();
|
||||
let n = s.doc().unwrap().history.undo.len();
|
||||
s.execute("object.color", &json!({"color":"#123456"})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), n + 1);
|
||||
let colored = serde_json::to_value(s.doc().unwrap().doc.as_ref()).unwrap();
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(serde_json::to_value(s.doc().unwrap().doc.as_ref()).unwrap(), before);
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
assert_eq!(serde_json::to_value(s.doc().unwrap().doc.as_ref()).unwrap(), colored);
|
||||
s.execute("text.insert", &json!({"text":"X"})).unwrap();
|
||||
assert!(s.doc().unwrap().doc.story(StoryId(sid)).unwrap().format_after(0).over.fill.is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn integration_color_swap_resolves_each_paragraph_and_keeps_unselected_text() {
|
||||
let (mut s, sid) = setup("ab\ncd");
|
||||
for (name, fill, stroke, ft, st, start, end) in
|
||||
[("First", "[Paper]", "[Black]", 0.2, 0.8, 0, 2), ("Second", "[Black]", "[Paper]", 0.4, 0.6, 3, 5)]
|
||||
{
|
||||
s.execute("style.paragraph.create", &json!({"name":name,"chars":{"fill":fill,"stroke":stroke,"fillTint":ft,"strokeTint":st}})).unwrap();
|
||||
s.execute("text.select", &json!({"story":sid,"anchor":start,"focus":end})).unwrap();
|
||||
s.execute("style.paragraph.apply", &json!({"name":name})).unwrap();
|
||||
}
|
||||
s.execute("text.select", &json!({"story":sid,"anchor":1,"focus":4})).unwrap();
|
||||
let before = serde_json::to_value(s.doc().unwrap().doc.as_ref()).unwrap();
|
||||
let n = s.doc().unwrap().history.undo.len();
|
||||
s.execute("type.swapFillStroke", &json!({})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), n + 1);
|
||||
for (pos, fill, stroke, ft, st) in [
|
||||
(0, "[Paper]", "[Black]", 0.2, 0.8),
|
||||
(1, "[Black]", "[Paper]", 0.8, 0.2),
|
||||
(2, "[Black]", "[Paper]", 0.8, 0.2),
|
||||
(3, "[Paper]", "[Black]", 0.6, 0.4),
|
||||
(4, "[Black]", "[Paper]", 0.4, 0.6),
|
||||
] {
|
||||
s.execute("text.select", &json!({"story":sid,"anchor":pos,"focus":pos+1})).unwrap();
|
||||
let a = attrs(&mut s);
|
||||
assert_eq!(a["fill"], fill);
|
||||
assert_eq!(a["stroke"], stroke);
|
||||
assert!((a["fillTint"].as_f64().unwrap() - ft).abs() < 1e-6);
|
||||
assert!((a["strokeTint"].as_f64().unwrap() - st).abs() < 1e-6);
|
||||
}
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(serde_json::to_value(s.doc().unwrap().doc.as_ref()).unwrap(), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn integration_color_swap_caret_applies_only_to_next_typing() {
|
||||
let (mut s, sid) = setup("hello");
|
||||
s.execute("type.char", &json!({"fill":"[Paper]","stroke":"[Black]","fillTint":0.2,"strokeTint":0.8})).unwrap();
|
||||
let before = serde_json::to_value(s.doc().unwrap().doc.as_ref()).unwrap();
|
||||
s.execute("type.swapFillStroke", &json!({})).unwrap();
|
||||
assert_eq!(serde_json::to_value(s.doc().unwrap().doc.as_ref()).unwrap(), before);
|
||||
let a = attrs(&mut s);
|
||||
assert_eq!(a["fill"], "[Black]");
|
||||
assert_eq!(a["stroke"], "[Paper]");
|
||||
s.execute("text.insert", &json!({"text":"X"})).unwrap();
|
||||
let st = s.doc().unwrap().doc.story(StoryId(sid)).unwrap();
|
||||
assert_eq!(st.text, "helloX");
|
||||
assert_eq!(st.format_after(0).over.fill, None);
|
||||
assert_eq!(st.format_after(5).over.stroke.as_deref(), Some("[Paper]"));
|
||||
assert_eq!(st.format_after(5).over.fill_tint, Some(0.8));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn integration_color_swap_selected_empty_cells_keeps_each_format() {
|
||||
let (mut s, sid) = setup("hello");
|
||||
let result = s.execute("table.insert", &json!({"rows":1,"cols":2})).unwrap();
|
||||
let tid = result["table"].as_u64().unwrap();
|
||||
s.edit(|d, _| {
|
||||
let table = std::sync::Arc::make_mut(d.story_mut(StoryId(sid)).unwrap().tables.get_mut(&tid).unwrap());
|
||||
for (c, fill, stroke) in [(0, "[Paper]", "[Black]"), (1, "[Black]", "[Paper]")] {
|
||||
let attrs = &mut table.cell_mut(0, c).unwrap().text.chars[0].format.over;
|
||||
attrs.fill = Some(fill.into());
|
||||
attrs.stroke = Some(stroke.into());
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("table.select", &json!({"story":sid,"table":tid,"what":"table"})).unwrap();
|
||||
let before = serde_json::to_value(s.doc().unwrap().doc.as_ref()).unwrap();
|
||||
s.execute("type.swapFillStroke", &json!({})).unwrap();
|
||||
let table = &s.doc().unwrap().doc.story(StoryId(sid)).unwrap().tables[&tid];
|
||||
assert_eq!(table.cell(0, 0).unwrap().text.chars[0].format.over.fill.as_deref(), Some("[Black]"));
|
||||
assert_eq!(table.cell(0, 1).unwrap().text.chars[0].format.over.fill.as_deref(), Some("[Paper]"));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(serde_json::to_value(s.doc().unwrap().doc.as_ref()).unwrap(), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn integration_color_failed_promotion_preserves_pending_and_history() {
|
||||
let (mut s, _) = setup("hello");
|
||||
s.execute("swatch.create", &json!({"name":"Brand","color":"#654321"})).unwrap();
|
||||
let old = s.execute("object.color", &json!({"color":"#123456"})).unwrap()["swatch"].clone();
|
||||
let before = s.doc().unwrap().clone();
|
||||
let pending = attrs(&mut s);
|
||||
assert!(s.execute("swatch.addToSwatches", &json!({"swatch":old,"name":"Brand"})).is_err());
|
||||
assert_eq!(attrs(&mut s), pending);
|
||||
assert!(std::sync::Arc::ptr_eq(&s.doc().unwrap().doc, &before.doc));
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), before.history.undo.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn integration_color_promote_undo_redo_never_reuses_a_missing_pending_name() {
|
||||
let (mut s, _) = setup("hello");
|
||||
let old = s.execute("object.color", &json!({"color":"#123456"})).unwrap()["swatch"].clone();
|
||||
s.execute("swatch.addToSwatches", &json!({"swatch":old,"name":"Brand"})).unwrap();
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
let fill = attrs(&mut s)["fill"].as_str().unwrap().to_string();
|
||||
assert!(s.doc().unwrap().doc.swatch(&fill).is_some());
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
let fill = attrs(&mut s)["fill"].as_str().unwrap().to_string();
|
||||
assert!(s.doc().unwrap().doc.swatch(&fill).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn integration_color_swap_validates_new_fill_before_any_edit() {
|
||||
let (mut s, sid) = setup("hello");
|
||||
s.execute("text.select", &json!({"story":sid,"anchor":0,"focus":5})).unwrap();
|
||||
s.execute("type.char", &json!({"fill":"[Paper]","stroke":"Missing Ink"})).unwrap();
|
||||
let before = s.doc().unwrap().clone();
|
||||
let journal = s.journal.clone();
|
||||
let error = s.execute("type.swapFillStroke", &json!({})).unwrap_err().to_string();
|
||||
assert!(error.contains("Missing Ink"), "{error}");
|
||||
assert!(std::sync::Arc::ptr_eq(&s.doc().unwrap().doc, &before.doc));
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), before.history.undo.len());
|
||||
assert_eq!(s.journal, journal);
|
||||
}
|
||||
@@ -0,0 +1,396 @@
|
||||
//! Threading text frames: thread a frame after another (their stories merge), break a thread,
|
||||
//! take a frame out of its thread. The Selection tool's loaded text cursor runs these.
|
||||
|
||||
use designcraft_doc::{Document, ItemId, ParaFormat, Selection, StoryId};
|
||||
use designcraft_geom::Rect;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::{CommandSpec, bad, bool_or, cmd, has_doc, id_param, rect_param, spread_param, str_param};
|
||||
use crate::{Result, Session};
|
||||
|
||||
/// Pages Shift-click autoflow may add before it gives up.
|
||||
const AUTOFLOW_MAX_PAGES: usize = 2000;
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!(
|
||||
"text.thread",
|
||||
"Thread Text Frames",
|
||||
[],
|
||||
None,
|
||||
"{from?, to?, rect?: [x0,y0,x1,y1] (spread coords), spread?, autoflow?: bool} — threads frame `to` right after frame `from` (between `from` and the frame that followed it, if any). `to` is an empty frame or a text frame nothing threads into yet; its text joins the end of the story. Give `rect` in place of `from` or `to` to thread a new text frame made there on `spread`: `{from, rect}` adds it after `from`, `{rect, to}` in front of `to`. autoflow: then add pages with threaded frames until the story fits. Selects the frame that joined the thread. → {story, from, to, overset, pagesAdded}",
|
||||
has_doc,
|
||||
thread
|
||||
),
|
||||
cmd!(
|
||||
"text.unthread",
|
||||
"Break Thread",
|
||||
[],
|
||||
None,
|
||||
"{frame?, side?: after|before} — breaks the thread after (or before) `frame` (default: the selected text frame). The frames from the break on stay threaded to each other but become empty; the text stays in the story, overset if the earlier frames can't hold it",
|
||||
has_doc,
|
||||
unthread
|
||||
),
|
||||
cmd!(
|
||||
"text.removeFromThread",
|
||||
"Remove Frame from Thread",
|
||||
[],
|
||||
None,
|
||||
"{frame?} — takes `frame` (default: the selected text frame) out of its thread: the frames before and after it join up and keep the text, `frame` stays empty",
|
||||
has_doc,
|
||||
remove_from_thread
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
/// `frame` param, or the first selected text frame.
|
||||
fn frame_param(s: &Session, p: &Value, cmd: &str) -> Result<ItemId> {
|
||||
let st = s.doc()?;
|
||||
let id = id_param(p, "frame")
|
||||
.or_else(|| st.selection.items.iter().copied().find(|i| st.doc.item(*i).is_some_and(|it| it.is_text_frame())))
|
||||
.ok_or_else(|| bad(cmd, "no text frame given or selected"))?;
|
||||
if !st.doc.item(id).is_some_and(|it| it.is_text_frame()) {
|
||||
return Err(bad(cmd, format!("{id} is not a text frame")));
|
||||
}
|
||||
check_editable(&st.doc, id, cmd)?;
|
||||
Ok(id)
|
||||
}
|
||||
|
||||
fn check_editable(d: &Document, id: ItemId, cmd: &str) -> Result<()> {
|
||||
let it = d.item(id).ok_or(designcraft_doc::DocError::NoItem(id))?;
|
||||
if it.locked || d.layer(it.layer).is_some_and(|l| l.locked) {
|
||||
return Err(bad(cmd, format!("{id} is locked or on a locked layer")));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A rect param made safe for a frame: finite, ordered, at least half a point each way.
|
||||
fn frame_rect(p: &Value) -> Result<Option<Rect>> {
|
||||
let Some(r) = rect_param(p, "rect") else { return Ok(None) };
|
||||
if ![r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite()) {
|
||||
return Err(bad("text.thread", "rect must be finite"));
|
||||
}
|
||||
let (x0, x1) = (r.x0.min(r.x1), r.x0.max(r.x1));
|
||||
let (y0, y1) = (r.y0.min(r.y1), r.y0.max(r.y1));
|
||||
Ok(Some(Rect::new(x0, y0, x1.max(x0 + 0.5), y1.max(y0 + 0.5))))
|
||||
}
|
||||
|
||||
fn thread(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (from, to, rect) = (id_param(p, "from"), id_param(p, "to"), frame_rect(p)?);
|
||||
let sr = spread_param(p, "spread")?;
|
||||
let autoflow = bool_or(p, "autoflow", false);
|
||||
let layer = s.doc()?.active_layer;
|
||||
s.edit(|d, sel| {
|
||||
let mut new_frame = || -> Result<ItemId> {
|
||||
let r = rect.ok_or_else(|| bad("text.thread", "give two of from, to and rect"))?;
|
||||
if d.layer(layer).is_none_or(|l| l.locked || !l.visible) {
|
||||
return Err(bad("text.thread", "the active layer is locked or hidden"));
|
||||
}
|
||||
let para = ParaFormat { style: d.styles.default_paragraph.clone(), ..Default::default() };
|
||||
Ok(d.add_text_frame(sr, r, layer, "", para)?.0)
|
||||
};
|
||||
let (from, to, joined) = match (from, to) {
|
||||
(Some(f), Some(t)) if rect.is_none() => (f, t, t),
|
||||
(Some(f), None) => {
|
||||
let t = new_frame()?;
|
||||
(f, t, t)
|
||||
}
|
||||
(None, Some(t)) => {
|
||||
let f = new_frame()?;
|
||||
(f, t, f)
|
||||
}
|
||||
_ => return Err(bad("text.thread", "give two of from, to and rect")),
|
||||
};
|
||||
d.check_thread(from, to)?;
|
||||
d.thread_keeping_story(from, to)?;
|
||||
let sid = d.item(from).and_then(|i| i.text_frame()).map(|t| t.story).ok_or_else(|| bad("text.thread", "threading lost the story"))?;
|
||||
let pages = if autoflow { super::place_text_autoflow(d, sid, AUTOFLOW_MAX_PAGES, "text.thread")? } else { 0 };
|
||||
*sel = Selection::items(vec![joined]);
|
||||
Ok(json!({"story": sid.0, "from": from.0, "to": to.0, "overset": overset(d, sid), "pagesAdded": pages}))
|
||||
})
|
||||
}
|
||||
|
||||
fn overset(d: &Document, sid: StoryId) -> bool {
|
||||
designcraft_compose::compose_story(d, sid, &Default::default()).overset_at.is_some()
|
||||
}
|
||||
|
||||
fn unthread(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const CMD: &str = "text.unthread";
|
||||
let frame = frame_param(s, p, CMD)?;
|
||||
let d0 = &s.doc()?.doc;
|
||||
let at = match str_param(p, "side").unwrap_or("after") {
|
||||
"after" => d0.next_frame(frame).map(|_| frame).ok_or_else(|| bad(CMD, format!("no frame follows {frame} in its thread")))?,
|
||||
"before" => d0.prev_frame(frame).ok_or_else(|| bad(CMD, format!("no frame comes before {frame} in its thread")))?,
|
||||
other => return Err(bad(CMD, format!("unknown side `{other}` (after, before)"))),
|
||||
};
|
||||
check_editable(d0, at, CMD)?;
|
||||
if let Some(next) = d0.next_frame(at) {
|
||||
check_editable(d0, next, CMD)?;
|
||||
}
|
||||
s.edit(|d, _| {
|
||||
d.unthread_after(at)?;
|
||||
let sid = d.item(at).and_then(|i| i.text_frame()).map(|t| t.story).ok_or_else(|| bad(CMD, "no story"))?;
|
||||
Ok(json!({"story": sid.0, "overset": overset(d, sid)}))
|
||||
})
|
||||
}
|
||||
|
||||
fn remove_from_thread(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let frame = frame_param(s, p, "text.removeFromThread")?;
|
||||
let d = &s.doc()?.doc;
|
||||
for neighbour in [d.prev_frame(frame), d.next_frame(frame)].into_iter().flatten() {
|
||||
check_editable(d, neighbour, "text.removeFromThread")?;
|
||||
}
|
||||
s.edit(|d, _| {
|
||||
d.remove_from_thread(frame)?;
|
||||
Ok(json!({}))
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use serde_json::json;
|
||||
|
||||
use crate::Session;
|
||||
|
||||
fn session() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"pages": 2})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn text_frame(s: &mut Session, rect: [f64; 4], text: &str) -> (u64, u64) {
|
||||
let r = s.execute("frame.create", &json!({"rect": rect, "content": "text", "text": text, "caret": false})).unwrap();
|
||||
(r["id"].as_u64().unwrap(), r["story"].as_u64().unwrap())
|
||||
}
|
||||
|
||||
fn story(s: &mut Session, frame: u64) -> serde_json::Value {
|
||||
s.execute("story.get", &json!({"frame": frame})).unwrap()
|
||||
}
|
||||
|
||||
fn frames(s: &mut Session, frame: u64) -> Vec<u64> {
|
||||
story(s, frame)["frames"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect()
|
||||
}
|
||||
|
||||
const LONG: &str = "Threaded text keeps flowing from one frame into the next one. ";
|
||||
|
||||
#[test]
|
||||
fn thread_into_an_empty_frame_and_undo() {
|
||||
let mut s = session();
|
||||
let (a, sid) = text_frame(&mut s, [72.0, 72.0, 200.0, 120.0], &LONG.repeat(10));
|
||||
let b = s.execute("frame.create", &json!({"rect": [72, 300, 200, 400], "content": "unassigned"})).unwrap()["id"].as_u64().unwrap();
|
||||
assert!(!story(&mut s, a)["overset"].is_null(), "the first frame is overset");
|
||||
let r = s.execute("text.thread", &json!({"from": a, "to": b})).unwrap();
|
||||
assert_eq!(r["story"].as_u64(), Some(sid));
|
||||
assert_eq!(frames(&mut s, a), [a, b]);
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert!(d.item(designcraft_doc::ItemId(b)).unwrap().is_text_frame());
|
||||
assert_eq!(s.doc().unwrap().selection.items, [designcraft_doc::ItemId(b)]);
|
||||
// The text now reaches the second frame.
|
||||
let cs = designcraft_compose::compose_story(&s.doc().unwrap().doc, designcraft_doc::StoryId(sid), &Default::default());
|
||||
assert!(cs.frames.iter().any(|f| f.frame.0 == b && !f.range.is_empty()), "text flows into the new frame");
|
||||
s.doc().unwrap().doc.check().unwrap();
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(frames(&mut s, a), [a]);
|
||||
assert!(!s.doc().unwrap().doc.item(designcraft_doc::ItemId(b)).unwrap().is_text_frame());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn thread_into_a_text_frame_merges_its_story() {
|
||||
let mut s = session();
|
||||
let (a, sa) = text_frame(&mut s, [72.0, 72.0, 200.0, 200.0], "First");
|
||||
let (b, sb) = text_frame(&mut s, [72.0, 300.0, 200.0, 400.0], "Second");
|
||||
s.execute("text.thread", &json!({"from": a, "to": b})).unwrap();
|
||||
let st = story(&mut s, b);
|
||||
assert_eq!(st["id"].as_u64(), Some(sa));
|
||||
assert_eq!(st["text"], "First\nSecond");
|
||||
assert!(s.doc().unwrap().doc.story(designcraft_doc::StoryId(sb)).is_none());
|
||||
s.doc().unwrap().doc.check().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn thread_into_the_middle_of_a_thread() {
|
||||
let mut s = session();
|
||||
let (a, _) = text_frame(&mut s, [72.0, 72.0, 200.0, 120.0], &LONG.repeat(8));
|
||||
let (c, _) = text_frame(&mut s, [72.0, 500.0, 200.0, 600.0], "");
|
||||
s.execute("text.thread", &json!({"from": a, "to": c})).unwrap();
|
||||
let (b, _) = text_frame(&mut s, [72.0, 300.0, 200.0, 400.0], "");
|
||||
s.execute("text.thread", &json!({"from": a, "to": b})).unwrap();
|
||||
assert_eq!(frames(&mut s, a), [a, b, c]);
|
||||
s.doc().unwrap().doc.check().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_threads_are_errors_and_change_nothing() {
|
||||
let mut s = session();
|
||||
let (a, _) = text_frame(&mut s, [72.0, 72.0, 200.0, 120.0], "a");
|
||||
let (b, _) = text_frame(&mut s, [72.0, 300.0, 200.0, 400.0], "b");
|
||||
let (x, _) = text_frame(&mut s, [300.0, 72.0, 400.0, 120.0], "x");
|
||||
let (y, _) = text_frame(&mut s, [300.0, 300.0, 400.0, 400.0], "y");
|
||||
let g = s.execute("line.create", &json!({"a": [300, 500], "b": [400, 600]})).unwrap()["id"].as_u64().unwrap();
|
||||
let group = {
|
||||
let p = s.execute("frame.create", &json!({"rect": [500, 500, 550, 550], "content": "unassigned"})).unwrap()["id"].clone();
|
||||
let q = s.execute("frame.create", &json!({"rect": [560, 500, 600, 550], "content": "unassigned"})).unwrap()["id"].clone();
|
||||
s.execute("selection.set", &json!({"ids": [p, q]})).unwrap();
|
||||
s.execute("object.group", &json!({})).unwrap();
|
||||
s.doc().unwrap().selection.items[0].0
|
||||
};
|
||||
s.execute("text.thread", &json!({"from": a, "to": b})).unwrap();
|
||||
s.execute("text.thread", &json!({"from": x, "to": y})).unwrap();
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
let doc = s.doc().unwrap().doc.clone();
|
||||
for p in [
|
||||
json!({"from": a, "to": a}),
|
||||
json!({"from": a, "to": g}),
|
||||
json!({"from": g, "to": a}),
|
||||
json!({"from": a, "to": group}),
|
||||
// Earlier in the same thread.
|
||||
json!({"from": b, "to": a}),
|
||||
// Text already flows into y from x.
|
||||
json!({"from": a, "to": y}),
|
||||
json!({"from": a, "to": 999_999}),
|
||||
json!({"from": a}),
|
||||
json!({"from": a, "to": b, "rect": [0, 0, 10, 10]}),
|
||||
json!({"rect": [0, 0, 10, 10]}),
|
||||
json!({"from": a, "rect": [0, 0, 10, 10], "spread": 99}),
|
||||
json!({"from": "a", "to": [1]}),
|
||||
json!([1, 2]),
|
||||
] {
|
||||
assert!(s.execute("text.thread", &p).is_err(), "{p}");
|
||||
}
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo);
|
||||
assert_eq!(*s.doc().unwrap().doc, *doc);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn locked_frames_and_layers_refuse_threads() {
|
||||
let mut s = session();
|
||||
let (a, _) = text_frame(&mut s, [72.0, 72.0, 200.0, 120.0], &LONG.repeat(8));
|
||||
let (b, _) = text_frame(&mut s, [72.0, 300.0, 200.0, 400.0], "");
|
||||
let layer = s.doc().unwrap().active_layer.0;
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
s.execute("object.lock", &json!({"ids": [b]})).unwrap();
|
||||
assert!(s.execute("text.thread", &json!({"from": a, "to": b})).is_err(), "locked frame");
|
||||
assert!(s.execute("text.thread", &json!({"from": b, "to": a})).is_err(), "locked frame");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
for (set, rect) in [(json!({"locked": true}), false), (json!({"locked": true}), true), (json!({"visible": false}), true)] {
|
||||
let mut p = json!({"id": layer});
|
||||
p.as_object_mut().unwrap().extend(set.as_object().unwrap().clone());
|
||||
s.execute("layer.set", &p).unwrap();
|
||||
let t = if rect { json!({"from": a, "rect": [300, 300, 400, 400]}) } else { json!({"from": a, "to": b}) };
|
||||
assert!(s.execute("text.thread", &t).is_err(), "{p} {t}");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
}
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo);
|
||||
assert_eq!(frames(&mut s, a), [a]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn thread_a_new_frame_after_or_in_front() {
|
||||
let mut s = session();
|
||||
let (a, sa) = text_frame(&mut s, [72.0, 72.0, 200.0, 120.0], &LONG.repeat(8));
|
||||
let r = s.execute("text.thread", &json!({"from": a, "rect": [72, 300, 200, 400]})).unwrap();
|
||||
let n = r["to"].as_u64().unwrap();
|
||||
assert_eq!(frames(&mut s, a), [a, n]);
|
||||
assert_eq!(s.doc().unwrap().selection.items, [designcraft_doc::ItemId(n)]);
|
||||
let b = s.doc().unwrap().doc.item(designcraft_doc::ItemId(n)).unwrap().bounds();
|
||||
assert_eq!(b, Rect::new(72.0, 300.0, 200.0, 400.0));
|
||||
// In front of the first frame: the story keeps its id and text.
|
||||
let r = s.execute("text.thread", &json!({"rect": [300, 72, 400, 120], "to": a})).unwrap();
|
||||
let m = r["from"].as_u64().unwrap();
|
||||
assert_eq!(r["story"].as_u64(), Some(sa));
|
||||
assert_eq!(frames(&mut s, a), [m, a, n]);
|
||||
assert_eq!(story(&mut s, a)["text"], LONG.repeat(8));
|
||||
s.doc().unwrap().doc.check().unwrap();
|
||||
// One undo step each.
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(frames(&mut s, a), [a, n]);
|
||||
}
|
||||
|
||||
use designcraft_geom::Rect;
|
||||
|
||||
#[test]
|
||||
fn thread_with_autoflow_adds_pages_until_the_text_fits() {
|
||||
let mut s = session();
|
||||
let (a, _) = text_frame(&mut s, [72.0, 72.0, 300.0, 200.0], &LONG.repeat(300));
|
||||
let r = s.execute("text.thread", &json!({"from": a, "rect": [72, 300, 300, 700], "autoflow": true})).unwrap();
|
||||
assert_eq!(r["overset"], false);
|
||||
assert!(r["pagesAdded"].as_u64().unwrap() >= 1, "{r}");
|
||||
assert!(frames(&mut s, a).len() >= 3);
|
||||
s.doc().unwrap().doc.check().unwrap();
|
||||
// One undo removes the frames and the pages.
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(frames(&mut s, a), [a]);
|
||||
assert_eq!(s.doc().unwrap().doc.page_count(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn autoflow_from_a_parent_frame_is_an_error() {
|
||||
let mut s = session();
|
||||
let parent = json!({"kind": "parent", "index": 0});
|
||||
let r = s.execute(
|
||||
"frame.create",
|
||||
&json!({"rect": [72, 72, 300, 200], "content": "text", "text": LONG.repeat(300), "caret": false, "spread": parent}),
|
||||
);
|
||||
let a = r.unwrap()["id"].as_u64().unwrap();
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
let doc = s.doc().unwrap().doc.clone();
|
||||
let e = s.execute("text.thread", &json!({"from": a, "rect": [72, 300, 300, 700], "spread": parent, "autoflow": true})).unwrap_err();
|
||||
assert!(e.to_string().contains("text.thread"), "{e}");
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo);
|
||||
assert_eq!(*s.doc().unwrap().doc, *doc);
|
||||
assert_eq!(s.doc().unwrap().doc.page_count(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unthread_after_and_before() {
|
||||
let mut s = session();
|
||||
let text = LONG.repeat(12);
|
||||
let (a, sa) = text_frame(&mut s, [72.0, 72.0, 200.0, 120.0], &text);
|
||||
let (b, _) = text_frame(&mut s, [72.0, 200.0, 200.0, 250.0], "");
|
||||
let (c, _) = text_frame(&mut s, [72.0, 300.0, 200.0, 350.0], "");
|
||||
s.execute("text.thread", &json!({"from": a, "to": b})).unwrap();
|
||||
s.execute("text.thread", &json!({"from": b, "to": c})).unwrap();
|
||||
// Break after the first frame: b and c stay threaded to each other, empty.
|
||||
let r = s.execute("text.unthread", &json!({"frame": a})).unwrap();
|
||||
assert_eq!(r["story"].as_u64(), Some(sa));
|
||||
assert_eq!(r["overset"], true);
|
||||
assert_eq!(frames(&mut s, a), [a]);
|
||||
assert_eq!(story(&mut s, a)["text"], text);
|
||||
assert_eq!(frames(&mut s, b), [b, c]);
|
||||
assert_eq!(story(&mut s, b)["text"], "");
|
||||
s.doc().unwrap().doc.check().unwrap();
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(frames(&mut s, a), [a, b, c]);
|
||||
// Break before the last frame, with the frame selected.
|
||||
s.execute("selection.set", &json!({"ids": [c]})).unwrap();
|
||||
s.execute("text.unthread", &json!({"side": "before"})).unwrap();
|
||||
assert_eq!(frames(&mut s, a), [a, b]);
|
||||
assert_eq!(frames(&mut s, c), [c]);
|
||||
// Nothing to break.
|
||||
assert!(s.execute("text.unthread", &json!({"frame": b})).is_err());
|
||||
assert!(s.execute("text.unthread", &json!({"frame": a, "side": "before"})).is_err());
|
||||
assert!(s.execute("text.unthread", &json!({"frame": a, "side": "sideways"})).is_err());
|
||||
assert!(s.execute("text.unthread", &json!({"frame": 999_999})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deleting_or_removing_a_threaded_frame_keeps_the_text_flowing() {
|
||||
let mut s = session();
|
||||
let text = LONG.repeat(12);
|
||||
let (a, _) = text_frame(&mut s, [72.0, 72.0, 200.0, 120.0], &text);
|
||||
let (b, _) = text_frame(&mut s, [72.0, 200.0, 200.0, 250.0], "");
|
||||
let (c, _) = text_frame(&mut s, [72.0, 300.0, 200.0, 350.0], "");
|
||||
s.execute("text.thread", &json!({"from": a, "to": b})).unwrap();
|
||||
s.execute("text.thread", &json!({"from": b, "to": c})).unwrap();
|
||||
s.execute("text.removeFromThread", &json!({"frame": b})).unwrap();
|
||||
assert_eq!(frames(&mut s, a), [a, c]);
|
||||
assert_eq!(story(&mut s, a)["text"], text);
|
||||
assert_eq!(story(&mut s, b)["text"], "");
|
||||
assert!(s.execute("text.removeFromThread", &json!({"frame": b})).is_err());
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.execute("edit.clear", &json!({"ids": [b]})).unwrap();
|
||||
assert_eq!(frames(&mut s, a), [a, c]);
|
||||
assert_eq!(story(&mut s, a)["text"], text);
|
||||
s.doc().unwrap().doc.check().unwrap();
|
||||
}
|
||||
}
|
||||
+199
-21
@@ -1,9 +1,9 @@
|
||||
//! Layout → Table of Contents: list the paragraphs of chosen styles with their page names, as a
|
||||
//! story with "TOC Title" / "TOC Level n" styles (right tab with dot leader). Update Table of
|
||||
//! Contents regenerates the same story after edits.
|
||||
//! story with "TOC Title" / "TOC Level n" styles (right tab with dot leader) or the entry styles
|
||||
//! chosen per style. Update Table of Contents regenerates the same story after edits.
|
||||
|
||||
use designcraft_compose::{ComposeOptions, caret, compose_story};
|
||||
use designcraft_doc::{Align, Document, ParaAttrs, ParaFormat, ParagraphStyle, SpreadRef, StoryId, TabAlign, TabStop, Toc, TocEntry};
|
||||
use designcraft_doc::{Align, Document, ParaAttrs, ParaFormat, ParagraphStyle, SpreadRef, StoryId, TabAlign, TabStop, Toc, TocEntry, TocPageNumber};
|
||||
use designcraft_geom::Rect;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
@@ -17,7 +17,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Table of Contents…",
|
||||
["Layout"],
|
||||
None,
|
||||
"{entries: [{style, level?: 1}] | styles: [names], title?: \"Contents\", pageNumbers?: true, page?: 1-based page for a new frame (its margins), rect?: [x0,y0,x1,y1] (spread coords)} → {story, entries}",
|
||||
"{entries: [{style, level?: 1 (1-9), entryStyle?: paragraph style of its entries (default \"TOC Level n\"), pageNumber?: \"after\"|\"before\"|\"none\", separator?: text between entry and number (default a tab)}] | styles: [names] (levels 1, 2, …), title?: \"Contents\", titleStyle?: paragraph style of the title (default \"TOC Title\"), pageNumbers?: true, replace?: true (regenerate the existing table of contents in place; false makes a new frame), page?: 1-based page for a new frame (its margins), rect?: [x0,y0,x1,y1] (spread coords)} → {story, entries}",
|
||||
has_doc,
|
||||
generate
|
||||
),
|
||||
@@ -44,20 +44,66 @@ fn has_toc(s: &Session) -> std::result::Result<(), String> {
|
||||
}
|
||||
}
|
||||
|
||||
const MAX_ENTRIES: usize = 64;
|
||||
const MAX_NAME: usize = 256;
|
||||
const MAX_TITLE: usize = 1024;
|
||||
const MAX_SEPARATOR: usize = 64;
|
||||
|
||||
fn entries_param(p: &Value) -> Result<Vec<TocEntry>> {
|
||||
if let Some(v) = p.get("entries") {
|
||||
return serde_json::from_value(v.clone()).map_err(|e| bad("toc.generate", e.to_string()));
|
||||
let mut entries: Vec<TocEntry> = if let Some(v) = p.get("entries") {
|
||||
if v.as_array().is_some_and(|a| a.len() > MAX_ENTRIES) {
|
||||
return Err(bad("toc.generate", format!("at most {MAX_ENTRIES} entries")));
|
||||
}
|
||||
serde_json::from_value(v.clone()).map_err(|e| bad("toc.generate", e.to_string()))?
|
||||
} else if let Some(a) = p.get("styles").and_then(Value::as_array) {
|
||||
if a.len() > MAX_ENTRIES {
|
||||
return Err(bad("toc.generate", format!("at most {MAX_ENTRIES} styles")));
|
||||
}
|
||||
a.iter().enumerate().filter_map(|(i, v)| v.as_str().map(|s| TocEntry::new(s, (i + 1).min(9) as u8))).collect()
|
||||
} else {
|
||||
return Err(bad("toc.generate", "give `entries` or `styles`"));
|
||||
};
|
||||
for e in &mut entries {
|
||||
if !(1..=9).contains(&e.level) {
|
||||
return Err(bad("toc.generate", format!("level {} of `{}` is not 1–9", e.level, e.style)));
|
||||
}
|
||||
if e.style.chars().count() > MAX_NAME || e.entry_style.as_ref().is_some_and(|n| n.chars().count() > MAX_NAME) {
|
||||
return Err(bad("toc.generate", format!("style names are at most {MAX_NAME} characters")));
|
||||
}
|
||||
if let Some(sep) = &mut e.separator {
|
||||
if sep.chars().count() > MAX_SEPARATOR {
|
||||
return Err(bad("toc.generate", format!("the separator is at most {MAX_SEPARATOR} characters")));
|
||||
}
|
||||
*sep = one_line(sep);
|
||||
}
|
||||
// The defaults are stored as `None`, so a definition reads the same however it was made.
|
||||
if e.entry_style.as_deref() == Some("") {
|
||||
e.entry_style = None;
|
||||
}
|
||||
if e.separator.as_deref() == Some("\t") {
|
||||
e.separator = None;
|
||||
}
|
||||
}
|
||||
if let Some(a) = p.get("styles").and_then(Value::as_array) {
|
||||
return Ok(a.iter().enumerate().filter_map(|(i, v)| v.as_str().map(|s| TocEntry { style: s.into(), level: (i + 1).min(9) as u8 })).collect());
|
||||
Ok(entries)
|
||||
}
|
||||
|
||||
/// Paragraph breaks in a title or separator would shift the paragraph styles after them.
|
||||
fn one_line(s: &str) -> String {
|
||||
s.chars().map(|c| if matches!(c, '\n' | '\r' | '\u{2029}') { ' ' } else { c }).collect()
|
||||
}
|
||||
|
||||
fn para_style_exists(d: &Document, name: &str) -> Result<()> {
|
||||
match d.styles.para(name) {
|
||||
Some(_) => Ok(()),
|
||||
None => Err(bad("toc.generate", format!("no paragraph style `{name}`"))),
|
||||
}
|
||||
Err(bad("toc.generate", "give `entries` or `styles`"))
|
||||
}
|
||||
|
||||
pub struct Found {
|
||||
pub level: u8,
|
||||
pub text: String,
|
||||
pub page: String,
|
||||
entry: usize,
|
||||
key: (usize, i64, i64),
|
||||
}
|
||||
|
||||
@@ -70,7 +116,7 @@ pub fn collect(d: &Document, entries: &[TocEntry], skip: Option<StoryId>) -> Vec
|
||||
}
|
||||
let cs = compose_story(d, *sid, &ComposeOptions::default());
|
||||
for (pi, r) in st.para_ranges().into_iter().enumerate() {
|
||||
let Some(e) = entries.iter().find(|e| e.style == st.paras[pi].style) else { continue };
|
||||
let Some((ei, e)) = entries.iter().enumerate().find(|(_, e)| e.style == st.paras[pi].style) else { continue };
|
||||
let text: String = st.text[r.clone()]
|
||||
.chars()
|
||||
.filter(|c| !('\u{E000}'..='\u{E1FF}').contains(c))
|
||||
@@ -95,6 +141,7 @@ pub fn collect(d: &Document, entries: &[TocEntry], skip: Option<StoryId>) -> Vec
|
||||
out.push(Found {
|
||||
level: e.level,
|
||||
text,
|
||||
entry: ei,
|
||||
page: d.page_name(abs),
|
||||
key: (abs, ((b.y0 + baseline) * 10.0) as i64, ((b.x0 + x) * 10.0) as i64),
|
||||
});
|
||||
@@ -146,22 +193,35 @@ fn fill(d: &mut Document, toc: &Toc, width: Option<f64>) -> Result<usize> {
|
||||
d.story(toc.story).and_then(|st| st.frames.first()).and_then(|f| d.item(*f)).map(|i| i.text_area().width()).unwrap_or(300.0)
|
||||
});
|
||||
ensure_styles(d, levels, width);
|
||||
for name in toc.entries.iter().filter_map(|e| e.entry_style.as_deref()).chain(toc.title_style.as_deref()) {
|
||||
para_style_exists(d, name)?;
|
||||
}
|
||||
let mut text = String::new();
|
||||
let mut styles = Vec::new();
|
||||
if !toc.title.is_empty() {
|
||||
text.push_str(&toc.title);
|
||||
styles.push("TOC Title".to_string());
|
||||
styles.push(toc.title_style.clone().unwrap_or_else(|| "TOC Title".into()));
|
||||
}
|
||||
for f in &found {
|
||||
let Some(e) = toc.entries.get(f.entry) else { continue };
|
||||
if !text.is_empty() {
|
||||
text.push('\n');
|
||||
}
|
||||
text.push_str(&f.text);
|
||||
if toc.page_numbers {
|
||||
text.push('\t');
|
||||
text.push_str(&f.page);
|
||||
let sep = e.separator.as_deref().unwrap_or("\t");
|
||||
match e.page_number {
|
||||
TocPageNumber::After if toc.page_numbers => {
|
||||
text.push_str(&f.text);
|
||||
text.push_str(sep);
|
||||
text.push_str(&f.page);
|
||||
}
|
||||
TocPageNumber::Before if toc.page_numbers => {
|
||||
text.push_str(&f.page);
|
||||
text.push_str(sep);
|
||||
text.push_str(&f.text);
|
||||
}
|
||||
_ => text.push_str(&f.text),
|
||||
}
|
||||
styles.push(format!("TOC Level {}", f.level.max(1)));
|
||||
styles.push(e.entry_style.clone().unwrap_or_else(|| format!("TOC Level {}", f.level.max(1))));
|
||||
}
|
||||
let st = d.story_mut(toc.story).ok_or(designcraft_doc::DocError::NoStory(toc.story))?;
|
||||
let len = st.len();
|
||||
@@ -179,13 +239,29 @@ fn generate(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if entries.is_empty() {
|
||||
return Err(bad("toc.generate", "no entries"));
|
||||
}
|
||||
let title = str_param(p, "title").unwrap_or("Contents").to_string();
|
||||
let title = str_param(p, "title").unwrap_or("Contents");
|
||||
if title.chars().count() > MAX_TITLE {
|
||||
return Err(bad("toc.generate", format!("the title is at most {MAX_TITLE} characters")));
|
||||
}
|
||||
let title = one_line(title);
|
||||
let title_style = str_param(p, "titleStyle").filter(|n| !n.is_empty()).map(str::to_string);
|
||||
if title_style.as_ref().is_some_and(|n| n.chars().count() > MAX_NAME) {
|
||||
return Err(bad("toc.generate", format!("style names are at most {MAX_NAME} characters")));
|
||||
}
|
||||
let page_numbers = p.get("pageNumbers").and_then(Value::as_bool).unwrap_or(true);
|
||||
let replace = p.get("replace").and_then(Value::as_bool).unwrap_or(true);
|
||||
let rect = super::rect_param(p, "rect");
|
||||
let page = p.get("page").and_then(Value::as_u64).unwrap_or(1).max(1) as usize - 1;
|
||||
if rect.is_some_and(|r| ![r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite()) || r.width() <= 0.0 || r.height() <= 0.0) {
|
||||
return Err(bad("toc.generate", "`rect` must be finite with a positive size"));
|
||||
}
|
||||
let page = p.get("page").and_then(Value::as_u64).map_or(Some(0), |n| usize::try_from(n.max(1) - 1).ok());
|
||||
let page = page.ok_or_else(|| bad("toc.generate", "no such page"))?;
|
||||
s.edit(|d, sel| {
|
||||
// Reuse the existing TOC story when there is one; otherwise make a frame.
|
||||
let existing = d.toc.as_ref().map(|t| t.story).filter(|sid| d.story(*sid).is_some());
|
||||
for e in &entries {
|
||||
para_style_exists(d, &e.style)?;
|
||||
}
|
||||
// Replace: regenerate the existing TOC story in place; otherwise make a frame.
|
||||
let existing = d.toc.as_ref().map(|t| t.story).filter(|sid| replace && d.story(*sid).is_some());
|
||||
let (story, width) = match existing {
|
||||
Some(sid) => (sid, None),
|
||||
None => {
|
||||
@@ -198,7 +274,7 @@ fn generate(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
(sid, w)
|
||||
}
|
||||
};
|
||||
let toc = Toc { story, title: title.clone(), entries: entries.clone(), page_numbers };
|
||||
let toc = Toc { story, title: title.clone(), entries: entries.clone(), page_numbers, title_style: title_style.clone() };
|
||||
let n = fill(d, &toc, width)?;
|
||||
d.toc = Some(toc);
|
||||
Ok(json!({"story": story.0, "entries": n}))
|
||||
@@ -237,4 +313,106 @@ mod tests {
|
||||
assert!(text.contains("Thoughts on the Grid"), "{text}");
|
||||
s.doc().unwrap().doc.check().unwrap();
|
||||
}
|
||||
|
||||
fn sample_with_toc_page() -> (Session, usize) {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.newSample", &json!({})).unwrap();
|
||||
let pages = s.doc().unwrap().doc.page_count();
|
||||
s.execute("layout.pages.insert", &json!({"count": 1})).unwrap();
|
||||
(s, pages + 1)
|
||||
}
|
||||
|
||||
fn toc_lines(s: &Session) -> Vec<(String, String)> {
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let st = d.story(d.toc.as_ref().unwrap().story).unwrap();
|
||||
st.para_ranges().into_iter().zip(&st.paras).map(|(r, f)| (st.text[r].trim_end_matches('\n').to_string(), f.style.clone())).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn toc_entry_style_page_number_position_and_separator_survive_update() {
|
||||
let (mut s, page) = sample_with_toc_page();
|
||||
let basic = designcraft_doc::story::BASIC_PARAGRAPH;
|
||||
s.execute(
|
||||
"toc.generate",
|
||||
&json!({"page": page, "title": "In This Issue", "titleStyle": basic, "entries": [
|
||||
{"style": "Cover Title", "level": 1, "pageNumber": "before", "separator": " — "},
|
||||
{"style": "Headline", "level": 2, "entryStyle": basic, "pageNumber": "none"},
|
||||
]}),
|
||||
)
|
||||
.unwrap();
|
||||
let check = |s: &Session, headline: &str| {
|
||||
let lines = toc_lines(s);
|
||||
assert_eq!(lines[0], ("In This Issue".to_string(), basic.to_string()));
|
||||
let cover = lines.iter().find(|(t, _)| t.contains("The Quiet")).unwrap();
|
||||
assert!(cover.0.starts_with("1 — The Quiet"), "{cover:?}");
|
||||
assert_eq!(cover.1, "TOC Level 1");
|
||||
let head = lines.iter().find(|(t, _)| t.contains("on the Grid")).unwrap();
|
||||
assert!(head.0.starts_with(headline) && !head.0.contains('\t'), "{head:?}");
|
||||
assert_eq!(head.1, basic);
|
||||
};
|
||||
check(&s, "Notes on the Grid");
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let hid = d.stories.iter().find(|(_, st)| st.text.starts_with("Notes on the Grid")).map(|(id, _)| *id).unwrap();
|
||||
s.execute("story.replaceRange", &json!({"story": hid.0, "start": 0, "end": 5, "text": "Thoughts"})).unwrap();
|
||||
s.execute("toc.update", &json!({})).unwrap();
|
||||
check(&s, "Thoughts on the Grid");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn replace_regenerates_the_toc_in_place_and_off_makes_a_new_frame() {
|
||||
let (mut s, page) = sample_with_toc_page();
|
||||
let stories = |s: &Session| s.doc().unwrap().doc.stories.len();
|
||||
let first = s.execute("toc.generate", &json!({"styles": ["Headline"], "page": page})).unwrap()["story"].clone();
|
||||
let n = stories(&s);
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
let r = s.execute("toc.generate", &json!({"styles": ["Headline"], "title": "Inside", "page": page, "replace": true})).unwrap();
|
||||
assert_eq!(r["story"], first);
|
||||
assert_eq!(stories(&s), n, "one table of contents");
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "one undo step");
|
||||
assert_eq!(toc_lines(&s)[0].0, "Inside");
|
||||
let r = s.execute("toc.generate", &json!({"styles": ["Headline"], "page": page, "replace": false})).unwrap();
|
||||
assert_ne!(r["story"], first);
|
||||
assert_eq!(stories(&s), n + 1);
|
||||
assert_eq!(s.doc().unwrap().doc.toc.as_ref().unwrap().story.0, r["story"].as_u64().unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_toc_params_are_errors_that_leave_the_document_alone() {
|
||||
let (mut s, page) = sample_with_toc_page();
|
||||
let long = "x".repeat(5000);
|
||||
let many: Vec<Value> = (0..65).map(|_| json!({"style": "Headline"})).collect();
|
||||
for p in [
|
||||
json!({"entries": [{"style": "Headline", "level": 0}]}),
|
||||
json!({"entries": [{"style": "Headline", "level": 10}]}),
|
||||
json!({"entries": [{"style": "Headline", "level": 300}]}),
|
||||
json!({"entries": [{"style": "Headline", "level": -1}]}),
|
||||
json!({"entries": [{"style": "Headline", "pageNumber": "sideways"}]}),
|
||||
json!({"entries": [{"style": "No Such Style"}]}),
|
||||
json!({"entries": [{"style": "Headline", "entryStyle": "No Such Style"}]}),
|
||||
json!({"entries": [{"style": "Headline", "separator": long}]}),
|
||||
json!({"entries": [{"style": long}]}),
|
||||
json!({"entries": many}),
|
||||
json!({"entries": "Headline"}),
|
||||
json!({"entries": []}),
|
||||
json!({"styles": ["Headline"], "titleStyle": "No Such Style"}),
|
||||
json!({"styles": ["Headline"], "title": long}),
|
||||
json!({"styles": ["Headline"], "rect": [100, 100, 50, 50]}),
|
||||
json!({"styles": ["Headline"], "page": u64::MAX}),
|
||||
json!([1, 2]),
|
||||
] {
|
||||
let rev = s.doc().unwrap().revision;
|
||||
assert!(s.execute("toc.generate", &merge(&p, page)).is_err(), "{p}");
|
||||
assert_eq!(s.doc().unwrap().revision, rev, "{p}");
|
||||
assert!(s.doc().unwrap().doc.toc.is_none());
|
||||
}
|
||||
}
|
||||
|
||||
/// `p` with the TOC page added when it is an object and has none.
|
||||
fn merge(p: &Value, page: usize) -> Value {
|
||||
let mut p = p.clone();
|
||||
if let Some(o) = p.as_object_mut() {
|
||||
o.entry("page").or_insert(json!(page));
|
||||
}
|
||||
p
|
||||
}
|
||||
}
|
||||
|
||||
@@ -153,6 +153,38 @@ mod tests {
|
||||
assert_eq!(shown(&s, 2), 3, "page 102 after renumbering");
|
||||
}
|
||||
|
||||
/// A section marker character shows the marker text of the section of the page it is composed
|
||||
/// for: on each document page a parent-page frame is shown on, and in a frame on a document
|
||||
/// page. A section without marker text shows nothing; the parent page itself shows "Section".
|
||||
#[test]
|
||||
fn section_marker_shows_the_pages_section_marker() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"pages": 4, "facingPages": false})).unwrap();
|
||||
s.execute("layout.section", &json!({"page": 3, "startNumber": 1, "marker": "Intro"})).unwrap();
|
||||
let marker = designcraft_doc::story::SECTION_MARKER.to_string();
|
||||
let r = s
|
||||
.execute("frame.create", &json!({"spread": {"kind": "parent", "index": 0}, "rect": [72, 30, 500, 60], "content": "text", "text": marker}))
|
||||
.unwrap();
|
||||
let parent = s.doc().unwrap().doc.item(designcraft_doc::ItemId(r["id"].as_u64().unwrap())).unwrap().text_frame().unwrap().story;
|
||||
let sp = s.doc().unwrap().doc.page_loc(3).unwrap().0;
|
||||
let r = s.execute("frame.create", &json!({"spread": sp, "rect": [72, 200, 400, 260], "content": "text", "text": marker})).unwrap();
|
||||
let own = s.doc().unwrap().doc.item(designcraft_doc::ItemId(r["id"].as_u64().unwrap())).unwrap().text_frame().unwrap().story;
|
||||
let shown = |s: &Session, sid, page: Option<usize>| -> usize {
|
||||
let d = s.doc().unwrap().doc.clone();
|
||||
let cs = s.cache.get(&d, sid, page);
|
||||
cs.frames.iter().flat_map(|f| f.lines.iter()).map(|l| l.glyphs.iter().filter(|g| g.visible && g.adv > 0.0).count()).sum()
|
||||
};
|
||||
assert_eq!(shown(&s, parent, Some(0)), 0, "the first section has no marker");
|
||||
assert_eq!(shown(&s, parent, Some(2)), "Intro".len());
|
||||
assert_eq!(shown(&s, parent, Some(3)), "Intro".len());
|
||||
assert_eq!(shown(&s, own, None), "Intro".len(), "a frame on a document page");
|
||||
assert_eq!(shown(&s, parent, None), "Section".len(), "the parent page itself");
|
||||
// Editing the marker recomposes.
|
||||
s.execute("layout.section", &json!({"page": 3, "marker": "Appendix"})).unwrap();
|
||||
assert_eq!(shown(&s, parent, Some(2)), "Appendix".len());
|
||||
assert_eq!(shown(&s, own, None), "Appendix".len());
|
||||
}
|
||||
|
||||
/// Two sections that both number from 1 repeat page names ("1, 2, 1, 2"). A parent-page running
|
||||
/// header is composed for the page it is shown on, not the first page with that name.
|
||||
#[test]
|
||||
|
||||
@@ -305,7 +305,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
match str_param(p, "path") {
|
||||
Some(path) => {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
crate::atomic::write_file(path, text.as_bytes())?;
|
||||
crate::io::write_file(path, text.as_bytes()).map_err(crate::EngineError::Other)?;
|
||||
Ok(json!({"path": path, "bytes": text.len()}))
|
||||
}
|
||||
None => Ok(json!({"text": text, "bytes": text.len()})),
|
||||
@@ -385,7 +385,7 @@ fn text_or_path(p: &Value, id: &str) -> Result<String> {
|
||||
(Some(t), _) => t.to_string(),
|
||||
(None, Some(path)) => {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
let t = std::fs::read_to_string(path).map_err(|e| crate::EngineError::Other(format!("{path}: {e}")))?;
|
||||
let t = crate::io::read_to_string(path).map_err(crate::EngineError::Other)?;
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
let t = {
|
||||
let _ = path;
|
||||
|
||||
@@ -214,4 +214,23 @@ mod tests {
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(s.execute("xref.list", &json!({})).unwrap()[0]["text"], "(p. 3)");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cross_reference_into_a_story_with_a_running_header_composes() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"pages": 1, "facingPages": false})).unwrap();
|
||||
let head = s.execute("frame.create", &json!({"rect": [72, 72, 400, 120], "content": "text", "text": "Chapter"})).unwrap()["story"].clone();
|
||||
let body = s.execute("frame.create", &json!({"rect": [72, 200, 400, 300], "content": "text", "text": "See"})).unwrap()["story"].clone();
|
||||
s.execute("text.select", &json!({"story": head, "anchor": 0, "focus": 0})).unwrap();
|
||||
s.execute("variables.insert", &json!({"name": "Running Header"})).unwrap();
|
||||
s.execute("text.select", &json!({"story": body, "anchor": 3, "focus": 3})).unwrap();
|
||||
s.execute("xref.insert", &json!({"story": head, "para": 0})).unwrap();
|
||||
// The cross-reference index and the running-header index used to build each other without end.
|
||||
assert_eq!(s.execute("xref.list", &json!({})).unwrap()[0]["text"], "\u{201C}Chapter\u{201D} on page 1");
|
||||
// The header shows the body's paragraph in front of its own text.
|
||||
let d = s.doc().unwrap().doc.clone();
|
||||
let cs = s.cache.get(&d, StoryId(head.as_u64().unwrap()), None);
|
||||
let glyphs: usize = cs.frames[0].lines.iter().map(|l| l.glyphs.iter().filter(|g| g.visible && g.adv > 0.0).count()).sum();
|
||||
assert_eq!(glyphs, "SeeChapter".len());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,6 +3,10 @@
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
/// How much text parameter entities may add during expansion (a pass count is not an output
|
||||
/// bound: each pass replaces whole strings, so references can inflate multiplicatively).
|
||||
const MAX_EXPANDED_BYTES: usize = 1024 * 1024;
|
||||
|
||||
/// A content particle: a name, a sequence, a choice, or one of those repeated (`?`, `*`, `+`).
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
enum Cp {
|
||||
@@ -177,10 +181,17 @@ pub fn parse(src: &str) -> Result<Dtd, String> {
|
||||
}
|
||||
}
|
||||
let mut text = src.to_string();
|
||||
// A pass count bounds the work, not the output: each pass replaces whole strings with the
|
||||
// entities' original values, so a few hundred bytes of nested parameter entities can inflate
|
||||
// to gigabytes. Expansion may not add more than this much text over the input.
|
||||
let limit = src.len().saturating_add(MAX_EXPANDED_BYTES);
|
||||
for _ in 0..8 {
|
||||
let before = text.clone();
|
||||
for (n, v) in &ents {
|
||||
text = text.replace(&format!("%{n};"), v);
|
||||
if text.len() > limit {
|
||||
return Err(format!("parameter entities expand the DTD beyond {limit} bytes"));
|
||||
}
|
||||
}
|
||||
if text == before {
|
||||
break;
|
||||
@@ -434,6 +445,23 @@ mod tests {
|
||||
assert!(parse("just text").is_err());
|
||||
}
|
||||
|
||||
/// A few hundred bytes of nested parameter entities used to inflate multiplicatively across
|
||||
/// the eight wholly-string-replacing passes (#713); expansion is capped.
|
||||
#[test]
|
||||
fn parameter_entities_cannot_expand_without_a_budget() {
|
||||
let mut src = String::from("<!ENTITY % e1 \"xx\">\n");
|
||||
for i in 2..=6 {
|
||||
src.push_str(&format!("<!ENTITY % e{i} \"{}\">\n", format!("%e{};", i - 1).repeat(16)));
|
||||
}
|
||||
src.push_str("<!ELEMENT r (%e6;)>");
|
||||
assert!(src.len() < 500, "the payload is small: {} bytes", src.len());
|
||||
let err = parse(&src).unwrap_err();
|
||||
assert!(err.contains("expand the DTD beyond"), "{err}");
|
||||
// Entities that expand a little still parse.
|
||||
let dtd = parse("<!ENTITY % inline \"#PCDATA | em\">\n<!ELEMENT r (%inline;)*>").unwrap();
|
||||
assert_eq!(dtd.element_names().collect::<Vec<_>>(), ["r"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repetition_matches_like_a_regular_expression() {
|
||||
let dtd = parse("<!ELEMENT r ((a, b?)+, c*)><!ELEMENT a EMPTY><!ELEMENT b EMPTY><!ELEMENT c EMPTY>").unwrap();
|
||||
|
||||
@@ -0,0 +1,439 @@
|
||||
//! The folders automation may read and write.
|
||||
//!
|
||||
//! `designcraft-cli mcp --automation-read-root <dir> --automation-write-root <dir>` confines the
|
||||
//! files an agent's commands reach. [`AutomationRoots`] holds the two folders. While they are in force, every path a command
|
||||
//! reads goes through [`check_read`] and every path it writes through [`check_write`]:
|
||||
//!
|
||||
//! - The path is made absolute against the working directory, as the file system reads it. Its
|
||||
//! links are followed: for a file that doesn't exist yet, the links of its nearest existing
|
||||
//! folder, the rest of the path being plain names (`..` below a missing folder is refused, and so
|
||||
//! is a link that leads nowhere).
|
||||
//! - The result must lie inside the root, compared by whole components (`/work2` isn't inside
|
||||
//! `/work`), without regard to case on Windows.
|
||||
//! - Read and write access are separate: a root given alone grants only its own kind of access.
|
||||
//!
|
||||
//! Roots are in force on a thread inside [`confine`], and in the whole process after
|
||||
//! [`confine_process`] (`designcraft-cli mcp`), except inside [`unconfined`]. Without roots
|
||||
//! nothing is checked.
|
||||
//!
|
||||
//! A path is checked, then opened: a process that can change the folders in between (swapping in
|
||||
//! a link) can still win that race. The roots keep an agent to the files it was given; they don't
|
||||
//! guard against other programs on the computer.
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::ffi::OsString;
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
use std::sync::{Arc, OnceLock};
|
||||
|
||||
/// Read access or write access.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Access {
|
||||
Read,
|
||||
Write,
|
||||
}
|
||||
|
||||
/// The folders automation may read and write; a root left out grants no access of its kind.
|
||||
#[derive(Debug)]
|
||||
pub struct AutomationRoots {
|
||||
read: Option<Root>,
|
||||
write: Option<Root>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct Root {
|
||||
/// The folder made absolute, links followed: what paths are compared with.
|
||||
resolved: PathBuf,
|
||||
/// The same without Windows' `\\?\` prefix, for people.
|
||||
shown: PathBuf,
|
||||
}
|
||||
|
||||
impl Root {
|
||||
/// The folder at `path`, which must exist.
|
||||
fn open(path: &Path, access: Access) -> Result<Self, String> {
|
||||
let kind = match access {
|
||||
Access::Read => "read",
|
||||
Access::Write => "write",
|
||||
};
|
||||
let resolved = std::fs::canonicalize(path)
|
||||
.and_then(|p| if p.is_dir() { Ok(p) } else { Err(std::io::ErrorKind::NotADirectory.into()) })
|
||||
.map_err(|e| format!("cannot open the automation {kind} root `{}`: {e}", path.display()))?;
|
||||
Ok(Self { shown: plain(resolved.clone()), resolved })
|
||||
}
|
||||
}
|
||||
|
||||
impl AutomationRoots {
|
||||
/// The roots `read` and `write`, which must be existing folders; `None` when neither is given
|
||||
/// (nothing is confined then).
|
||||
pub fn new(read: Option<&Path>, write: Option<&Path>) -> Result<Option<Arc<Self>>, String> {
|
||||
if read.is_none() && write.is_none() {
|
||||
return Ok(None);
|
||||
}
|
||||
let read = read.map(|p| Root::open(p, Access::Read)).transpose()?;
|
||||
let write = write.map(|p| Root::open(p, Access::Write)).transpose()?;
|
||||
Ok(Some(Arc::new(Self { read, write })))
|
||||
}
|
||||
|
||||
/// The read root, absolute with its links followed.
|
||||
pub fn read_root(&self) -> Option<&Path> {
|
||||
self.read.as_ref().map(|r| r.shown.as_path())
|
||||
}
|
||||
|
||||
/// The write root, absolute with its links followed.
|
||||
pub fn write_root(&self) -> Option<&Path> {
|
||||
self.write.as_ref().map(|r| r.shown.as_path())
|
||||
}
|
||||
|
||||
/// May the file or folder at `path` be read (or written)? `Err` says why not.
|
||||
pub fn check(&self, path: impl AsRef<Path>, access: Access) -> Result<(), String> {
|
||||
let path = path.as_ref();
|
||||
let root = match access {
|
||||
Access::Read => self.read.as_ref(),
|
||||
Access::Write => self.write.as_ref(),
|
||||
};
|
||||
let Some(Root { resolved: folder, shown }) = root else {
|
||||
return match access {
|
||||
Access::Read => Err(format!("automation filesystem access is not granted: read authority is absent: {}", path.display())),
|
||||
Access::Write => Err(format!("automation filesystem access is not granted: write authority is absent: {}", path.display())),
|
||||
};
|
||||
};
|
||||
if inside(&resolve(path)?, folder) {
|
||||
return Ok(());
|
||||
}
|
||||
let root = shown.display();
|
||||
match access {
|
||||
Access::Read => Err(format!("automation path rejected: outside the read root {root}: {}", path.display())),
|
||||
Access::Write => Err(format!("automation path rejected: outside the write root {root}: {}", path.display())),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Where the roots are in force on a thread ([`confine`], [`unconfined`]).
|
||||
#[derive(Clone, Debug)]
|
||||
enum Scope {
|
||||
Confined(Arc<AutomationRoots>),
|
||||
Unconfined,
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
/// This thread's scope; `None`: the process's roots ([`confine_process`]).
|
||||
static SCOPE: RefCell<Option<Scope>> = const { RefCell::new(None) };
|
||||
}
|
||||
|
||||
/// The roots in force in every thread outside [`confine`] and [`unconfined`].
|
||||
static PROCESS: OnceLock<Arc<AutomationRoots>> = OnceLock::new();
|
||||
|
||||
/// Put `roots` in force in the whole process, for good. `false` when roots were in force already
|
||||
/// (they stay as they were).
|
||||
pub fn confine_process(roots: Arc<AutomationRoots>) -> bool {
|
||||
PROCESS.set(roots).is_ok()
|
||||
}
|
||||
|
||||
/// Puts the scope it replaced back when dropped (also when `f` panics).
|
||||
struct Restore(Option<Scope>);
|
||||
|
||||
impl Drop for Restore {
|
||||
fn drop(&mut self) {
|
||||
let previous = self.0.take();
|
||||
SCOPE.with(|s| *s.borrow_mut() = previous);
|
||||
}
|
||||
}
|
||||
|
||||
fn with_scope<T>(scope: Option<Scope>, f: impl FnOnce() -> T) -> T {
|
||||
let _restore = Restore(SCOPE.with(|s| s.replace(scope)));
|
||||
f()
|
||||
}
|
||||
|
||||
/// Run `f` with `roots` in force on this thread (`None`: as things stand).
|
||||
pub fn confine<T>(roots: Option<&Arc<AutomationRoots>>, f: impl FnOnce() -> T) -> T {
|
||||
match roots {
|
||||
Some(r) => with_scope(Some(Scope::Confined(r.clone())), f),
|
||||
None => f(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Run `f` with no roots in force on this thread: what the person at the keyboard does, and the
|
||||
/// app's own folders.
|
||||
pub fn unconfined<T>(f: impl FnOnce() -> T) -> T {
|
||||
with_scope(Some(Scope::Unconfined), f)
|
||||
}
|
||||
|
||||
/// The roots in force on this thread, if any.
|
||||
pub fn current() -> Option<Arc<AutomationRoots>> {
|
||||
match SCOPE.with(|s| s.borrow().clone()) {
|
||||
Some(Scope::Confined(r)) => Some(r),
|
||||
Some(Scope::Unconfined) => None,
|
||||
None => PROCESS.get().cloned(),
|
||||
}
|
||||
}
|
||||
|
||||
/// `path` without Windows' `\\?\` prefix (which `canonicalize` adds), for people to read.
|
||||
fn plain(path: PathBuf) -> PathBuf {
|
||||
if !cfg!(windows) {
|
||||
return path;
|
||||
}
|
||||
let text = path.to_string_lossy();
|
||||
if let Some(rest) = text.strip_prefix(r"\\?\UNC\") {
|
||||
return PathBuf::from(format!(r"\\{rest}"));
|
||||
}
|
||||
match text.strip_prefix(r"\\?\") {
|
||||
Some(rest) => PathBuf::from(rest),
|
||||
None => path,
|
||||
}
|
||||
}
|
||||
|
||||
/// May `path` be read here? Always, without roots in force.
|
||||
pub fn check_read(path: impl AsRef<Path>) -> Result<(), String> {
|
||||
current().map_or(Ok(()), |r| r.check(path, Access::Read))
|
||||
}
|
||||
|
||||
/// May `path` be written here? Always, without roots in force.
|
||||
pub fn check_write(path: impl AsRef<Path>) -> Result<(), String> {
|
||||
current().map_or(Ok(()), |r| r.check(path, Access::Write))
|
||||
}
|
||||
|
||||
/// `path` made absolute with its links followed; for a path that doesn't exist (yet), its nearest
|
||||
/// existing folder's links followed and the rest appended.
|
||||
fn resolve(path: &Path) -> Result<PathBuf, String> {
|
||||
if path.as_os_str().is_empty() {
|
||||
return Err("automation path rejected: path is empty".into());
|
||||
}
|
||||
// Checked as given: making `…\NUL` absolute gives the device path `\\.\NUL` on Windows.
|
||||
if cfg!(windows) && path.components().any(|c| matches!(c, Component::Normal(n) if is_device_name(&n.to_string_lossy()))) {
|
||||
return Err(format!("automation path rejected: reserved device names are not allowed: {}", path.display()));
|
||||
}
|
||||
let absolute = std::path::absolute(path).map_err(|e| format!("automation path rejected: cannot resolve {}: {e}", path.display()))?;
|
||||
// The names below the nearest existing folder, last first.
|
||||
let mut missing: Vec<OsString> = vec![];
|
||||
let mut at = absolute.as_path();
|
||||
loop {
|
||||
match std::fs::canonicalize(at) {
|
||||
Ok(mut found) => {
|
||||
found.extend(missing.iter().rev());
|
||||
return Ok(found);
|
||||
}
|
||||
Err(e) => match std::fs::symlink_metadata(at) {
|
||||
Ok(m) if m.file_type().is_symlink() => {
|
||||
return Err(format!("automation path rejected: a link that leads nowhere: {}", path.display()));
|
||||
}
|
||||
// There, yet its real path can't be had (no permission): nothing to compare.
|
||||
Ok(_) => return Err(format!("automation path rejected: cannot resolve {}: {e}", path.display())),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
|
||||
Err(e) => return Err(format!("automation path rejected: cannot resolve {}: {e}", path.display())),
|
||||
},
|
||||
}
|
||||
let parent = at.parent();
|
||||
match (at.components().next_back(), parent) {
|
||||
(Some(Component::Normal(name)), Some(parent)) => {
|
||||
missing.push(name.to_os_string());
|
||||
at = parent;
|
||||
}
|
||||
(Some(Component::ParentDir), _) => {
|
||||
return Err(format!("automation path rejected: parent traversal below a folder that doesn't exist: {}", path.display()));
|
||||
}
|
||||
// Down to the root (or drive) and it doesn't exist either.
|
||||
_ => {
|
||||
let e = std::io::Error::from(std::io::ErrorKind::NotFound);
|
||||
return Err(format!("automation path rejected: cannot resolve {}: {e}", path.display()));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Is `path` (resolved) `root` or inside it, component by component (without regard to case on
|
||||
/// Windows, whose file systems ignore it)?
|
||||
fn inside(path: &Path, root: &Path) -> bool {
|
||||
let mut path = path.components();
|
||||
root.components().all(|r| path.next().is_some_and(|p| same_component(p, r)))
|
||||
}
|
||||
|
||||
fn same_component(a: Component, b: Component) -> bool {
|
||||
if a == b {
|
||||
return true;
|
||||
}
|
||||
if !cfg!(windows) {
|
||||
return false;
|
||||
}
|
||||
match (a.as_os_str().to_str(), b.as_os_str().to_str()) {
|
||||
(Some(a), Some(b)) => a.to_lowercase() == b.to_lowercase(),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// A Windows device name (`CON`, `NUL`, `COM1`… also with an extension), which names no file.
|
||||
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"));
|
||||
matches!(stem.as_str(), "CON" | "PRN" | "AUX" | "NUL" | "CLOCK$" | "CONIN$" | "CONOUT$") || numbered("COM") || numbered("LPT")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// A fresh folder holding `in` (read root), `out` (write root) and `outside`.
|
||||
fn folders(name: &str) -> (PathBuf, Arc<AutomationRoots>) {
|
||||
let base = std::env::temp_dir().join(format!("dc-file-access-{name}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
for d in ["in/sub", "out", "outside", "in2"] {
|
||||
std::fs::create_dir_all(base.join(d)).unwrap();
|
||||
}
|
||||
std::fs::write(base.join("in/a.designcraft"), "x").unwrap();
|
||||
std::fs::write(base.join("outside/secret.designcraft"), "x").unwrap();
|
||||
let roots = AutomationRoots::new(Some(&base.join("in")), Some(&base.join("out"))).unwrap().unwrap();
|
||||
(base, roots)
|
||||
}
|
||||
|
||||
fn s(p: PathBuf) -> String {
|
||||
p.to_string_lossy().into_owned()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paths_inside_the_roots_pass_and_others_dont() {
|
||||
let (base, roots) = folders("inside");
|
||||
assert_eq!(roots.check(s(base.join("in/a.designcraft")), Access::Read), Ok(()));
|
||||
assert_eq!(roots.check(s(base.join("in")), Access::Read), Ok(()), "the root itself");
|
||||
assert_eq!(roots.check(s(base.join("in/sub/new.designcraft")), Access::Read), Ok(()), "missing files are checked by their folder");
|
||||
assert_eq!(roots.check(s(base.join("out/new/deeper/x.png")), Access::Write), Ok(()), "and by their nearest folder");
|
||||
let e = roots.check(s(base.join("outside/secret.designcraft")), Access::Read).unwrap_err();
|
||||
assert!(e.starts_with("automation path rejected: outside the read root"), "{e}");
|
||||
// Read and write access are separate.
|
||||
let e = roots.check(s(base.join("in/a.designcraft")), Access::Write).unwrap_err();
|
||||
assert!(e.contains("outside the write root"), "{e}");
|
||||
assert!(roots.check(s(base.join("out/x.png")), Access::Read).unwrap_err().contains("outside the read root"));
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_sibling_with_the_same_prefix_is_outside() {
|
||||
let (base, roots) = folders("prefix");
|
||||
std::fs::write(base.join("in2/b.designcraft"), "x").unwrap();
|
||||
assert!(roots.check(s(base.join("in2/b.designcraft")), Access::Read).is_err(), "in2 is not inside in");
|
||||
assert!(roots.check(format!("{}2/c.designcraft", s(base.join("in"))), Access::Read).is_err());
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parent_traversal_is_resolved_or_refused() {
|
||||
let (base, roots) = folders("dotdot");
|
||||
let sep = std::path::MAIN_SEPARATOR;
|
||||
let up = format!("{}{sep}..{sep}outside{sep}secret.designcraft", s(base.join("in")));
|
||||
assert!(roots.check(&up, Access::Read).unwrap_err().contains("outside the read root"), "`..` out of the root");
|
||||
let back = format!("{}{sep}..{sep}a.designcraft", s(base.join("in/sub")));
|
||||
assert_eq!(roots.check(&back, Access::Read), Ok(()), "`..` that stays inside");
|
||||
let missing = format!("{}{sep}nope{sep}..{sep}..{sep}outside{sep}x.designcraft", s(base.join("out")));
|
||||
let e = roots.check(&missing, Access::Write).unwrap_err();
|
||||
// Windows resolves `..` by name first (so does opening the file there): then it's outside.
|
||||
assert!(e.contains("parent traversal below a folder that doesn't exist") || e.contains("outside the write root"), "{e}");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn relative_paths_resolve_against_the_working_directory() {
|
||||
let (base, roots) = folders("relative");
|
||||
// The tests' working directory is the crate's folder: not inside the roots.
|
||||
assert!(roots.check("a.designcraft", Access::Read).unwrap_err().contains("outside the read root"));
|
||||
assert!(roots.check("", Access::Read).unwrap_err().contains("path is empty"));
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_missing_root_is_an_error_and_none_is_no_confinement() {
|
||||
let (base, _) = folders("missing");
|
||||
let e = AutomationRoots::new(Some(&base.join("nope")), None).unwrap_err();
|
||||
assert!(e.starts_with("cannot open the automation read root"), "{e}");
|
||||
let e = AutomationRoots::new(None, Some(&base.join("in/a.designcraft"))).unwrap_err();
|
||||
assert!(
|
||||
e.starts_with("cannot open the automation write root")
|
||||
&& e.ends_with(&std::io::Error::from(std::io::ErrorKind::NotADirectory).to_string()),
|
||||
"{e}"
|
||||
);
|
||||
assert!(AutomationRoots::new(Some(Path::new("")), None).unwrap_err().starts_with("cannot open the automation read root ``"));
|
||||
assert!(AutomationRoots::new(None, None).unwrap().is_none());
|
||||
// One root alone grants only its own access.
|
||||
let read_only = AutomationRoots::new(Some(&base.join("in")), None).unwrap().unwrap();
|
||||
let e = read_only.check(s(base.join("in/x.designcraft")), Access::Write).unwrap_err();
|
||||
assert!(e.contains("write authority is absent"), "{e}");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn links_are_followed_before_comparing() {
|
||||
let (base, roots) = folders("links");
|
||||
#[cfg(unix)]
|
||||
let made = |target: &Path, link: &Path| std::os::unix::fs::symlink(target, link).is_ok();
|
||||
#[cfg(windows)]
|
||||
let made = |target: &Path, link: &Path| {
|
||||
let made =
|
||||
if target.is_dir() { std::os::windows::fs::symlink_dir(target, link) } else { std::os::windows::fs::symlink_file(target, link) };
|
||||
made.is_ok()
|
||||
};
|
||||
#[cfg(not(any(unix, windows)))]
|
||||
let made = |_: &Path, _: &Path| false;
|
||||
// Windows needs Developer Mode or elevation to make links: nothing to test without them.
|
||||
if !made(&base.join("outside/secret.designcraft"), &base.join("in/leak.designcraft")) {
|
||||
eprintln!("skipped: symbolic links can't be made here");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
return;
|
||||
}
|
||||
assert!(roots.check(s(base.join("in/leak.designcraft")), Access::Read).unwrap_err().contains("outside the read root"), "a file link out");
|
||||
assert!(made(&base.join("outside"), &base.join("out/away")));
|
||||
let e = roots.check(s(base.join("out/away/new.png")), Access::Write).unwrap_err();
|
||||
assert!(e.contains("outside the write root"), "a folder link out: {e}");
|
||||
assert!(made(&base.join("outside/gone.designcraft"), &base.join("out/dangling.png")));
|
||||
let e = roots.check(s(base.join("out/dangling.png")), Access::Write).unwrap_err();
|
||||
assert!(e.contains("a link that leads nowhere"), "writing would create the file outside: {e}");
|
||||
// A link to a folder inside the root stays inside.
|
||||
assert!(made(&base.join("in/sub"), &base.join("in/alias")));
|
||||
assert_eq!(roots.check(s(base.join("in/alias/x.designcraft")), Access::Read), Ok(()));
|
||||
// A root given through a link is the folder it leads to.
|
||||
assert!(made(&base.join("in"), &base.join("in-link")));
|
||||
let linked = AutomationRoots::new(Some(&base.join("in-link")), None).unwrap().unwrap();
|
||||
assert_eq!(linked.check(s(base.join("in/a.designcraft")), Access::Read), Ok(()));
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn windows_ignores_case_and_refuses_devices() {
|
||||
let (base, roots) = folders("case");
|
||||
let upper = s(base.join("IN/a.designcraft"));
|
||||
assert_eq!(roots.check(&upper, Access::Read), Ok(()), "{upper}");
|
||||
assert_eq!(roots.check(s(base.join("In/Sub/New.designcraft")), Access::Read), Ok(()));
|
||||
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());
|
||||
assert_eq!(roots.check(s(base.join("out/console.txt")), Access::Write), Ok(()));
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scopes_nest_and_stay_on_their_thread() {
|
||||
let (base, roots) = folders("scopes");
|
||||
let outside = s(base.join("outside/secret.designcraft"));
|
||||
assert_eq!(check_read(&outside), Ok(()), "nothing is confined by default");
|
||||
confine(Some(&roots), || {
|
||||
assert!(check_read(&outside).is_err());
|
||||
assert_eq!(unconfined(|| check_read(&outside)), Ok(()));
|
||||
assert!(check_read(&outside).is_err(), "restored after unconfined");
|
||||
let o = outside.clone();
|
||||
let there = std::thread::spawn(move || check_read(&o).is_ok()).join().unwrap();
|
||||
assert!(there, "another thread is not confined by this thread's scope");
|
||||
});
|
||||
assert_eq!(check_read(&outside), Ok(()), "restored after confine");
|
||||
let r = std::panic::catch_unwind(|| confine(Some(&roots), || panic!("boom")));
|
||||
assert!(r.is_err());
|
||||
assert_eq!(check_read(&outside), Ok(()), "restored after a panic");
|
||||
assert_eq!(confine(None, || check_read(&outside)), Ok(()));
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn device_names() {
|
||||
for d in ["CON", "nul", "Com1", "LPT9.txt", "aux.designcraft", "NUL "] {
|
||||
assert!(is_device_name(d), "{d}");
|
||||
}
|
||||
for f in ["console", "com10", "COM0", "lpt", "a.designcraft", "nul-x"] {
|
||||
assert!(!is_device_name(f), "{f}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -35,17 +35,23 @@ pub fn install_panic_hook() {
|
||||
impl Session {
|
||||
/// Run command `id` (`f`) inside the guard.
|
||||
pub(crate) fn guarded(&mut self, id: &str, f: impl FnOnce(&mut Session) -> Result<Value>) -> Result<Value> {
|
||||
let before = self.active().map(|d| (d.uid, d.doc.clone(), d.selection.clone(), d.revision));
|
||||
// The whole command transaction: every open document with its undo/redo history and
|
||||
// selection, which one is active, and the journal (nested commands journal too).
|
||||
let docs = self.docs.clone();
|
||||
let active = self.active;
|
||||
let revision = self.active().map_or(0, |d| d.revision);
|
||||
let journal = self.journal.len();
|
||||
match catch_unwind(AssertUnwindSafe(|| f(self))) {
|
||||
Ok(r) => r,
|
||||
Err(payload) => {
|
||||
let msg = panic_message(payload.as_ref());
|
||||
// Keep the document as it was before the command.
|
||||
if let (Some((uid, doc, selection, revision)), Some(st)) = (before, self.active_mut())
|
||||
&& st.uid == uid
|
||||
{
|
||||
st.doc = doc;
|
||||
st.selection = selection;
|
||||
// Keep the documents as they were before the command: a nested edit that
|
||||
// succeeded before the panic is rolled back with its history entry, a document
|
||||
// opened or switched by the command is gone, and redo it cleared is back.
|
||||
self.docs = docs;
|
||||
self.active = active;
|
||||
self.journal.truncate(journal);
|
||||
if let Some(st) = self.active_mut() {
|
||||
st.interaction = None;
|
||||
st.revision = revision.max(st.revision).saturating_add(1);
|
||||
}
|
||||
@@ -86,4 +92,47 @@ mod tests {
|
||||
// The session keeps working.
|
||||
s.execute("frame.create", &json!({"rect": [36, 236, 200, 400]})).unwrap();
|
||||
}
|
||||
|
||||
/// A nested edit that succeeded before the panic is rolled back with its history entry, and
|
||||
/// the redo it cleared is back (#742).
|
||||
#[test]
|
||||
fn a_panicking_command_restores_history_with_the_document() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
s.execute("frame.create", &json!({"rect": [36, 36, 200, 200]})).unwrap();
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
let (undo, redo) = {
|
||||
let h = &s.active().unwrap().history;
|
||||
(h.undo.len(), h.redo.len())
|
||||
};
|
||||
assert_eq!(redo, 1, "there is redo to lose");
|
||||
let err = s
|
||||
.guarded("test.panic", |s| {
|
||||
s.execute("frame.create", &json!({"rect": [36, 236, 200, 400]}))?;
|
||||
panic!("boom");
|
||||
})
|
||||
.unwrap_err();
|
||||
assert!(err.to_string().contains("boom"), "{err}");
|
||||
let st = s.active().unwrap();
|
||||
assert_eq!(st.history.undo.len(), undo, "the nested edit's undo entry is gone with the edit");
|
||||
assert_eq!(st.history.redo.len(), redo, "the redo the nested edit cleared is back");
|
||||
assert_eq!(st.doc.spreads[0].items.len(), 0, "the document is the one from before the command");
|
||||
}
|
||||
|
||||
/// A command that opens another document and then panics leaves none of it behind (#742).
|
||||
#[test]
|
||||
fn a_panicking_command_restores_the_document_set() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
let err = s
|
||||
.guarded("test.panic", |s| {
|
||||
s.execute("file.new", &json!({}))?;
|
||||
assert_eq!(s.docs.len(), 2);
|
||||
panic!("boom");
|
||||
})
|
||||
.unwrap_err();
|
||||
assert!(err.to_string().contains("boom"), "{err}");
|
||||
assert_eq!(s.docs.len(), 1, "the document the command opened is gone");
|
||||
assert_eq!(s.active, Some(0), "the document from before the command is active");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
//! Reading and writing the files a command names by path.
|
||||
//!
|
||||
//! Every such read and write goes through this module, so the automation roots
|
||||
//! ([`crate::file_access`]) are checked in one place. A command module that called `std::fs`
|
||||
//! itself would bypass them: a test in `file_access` keeps that from happening.
|
||||
//!
|
||||
//! A path the roots refuse reads as a file that isn't there where the caller only asks whether
|
||||
//! it is ([`is_file`], [`is_dir`], [`exists`], [`metadata`]), and as the roots' own message where
|
||||
//! it asks for the bytes.
|
||||
|
||||
use std::fs::Metadata;
|
||||
use std::path::Path;
|
||||
|
||||
/// The bytes of the file at `path`, inside the automation read root when there is one.
|
||||
pub fn read_file(path: impl AsRef<Path>) -> Result<Vec<u8>, String> {
|
||||
let path = path.as_ref();
|
||||
crate::file_access::check_read(path)?;
|
||||
std::fs::read(path).map_err(|e| format!("{}: {e}", path.display()))
|
||||
}
|
||||
|
||||
/// [`read_file`] with the file system's own error, for callers that tell "missing" from other
|
||||
/// failures. A refused path is a `PermissionDenied` error carrying the roots' message.
|
||||
pub fn read(path: impl AsRef<Path>) -> std::io::Result<Vec<u8>> {
|
||||
let path = path.as_ref();
|
||||
crate::file_access::check_read(path).map_err(|e| std::io::Error::new(std::io::ErrorKind::PermissionDenied, e))?;
|
||||
std::fs::read(path)
|
||||
}
|
||||
|
||||
/// The text of the file at `path`, inside the automation read root when there is one.
|
||||
pub fn read_to_string(path: impl AsRef<Path>) -> Result<String, String> {
|
||||
let path = path.as_ref();
|
||||
crate::file_access::check_read(path)?;
|
||||
std::fs::read_to_string(path).map_err(|e| format!("{}: {e}", path.display()))
|
||||
}
|
||||
|
||||
/// Write `bytes` to the file at `path`, inside the automation write root when there is one.
|
||||
pub fn write_file(path: impl AsRef<Path>, bytes: &[u8]) -> Result<(), String> {
|
||||
let path = path.as_ref();
|
||||
crate::file_access::check_write(path)?;
|
||||
// Replaced atomically where there is a real file system (see `atomic`).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
let written = crate::atomic::write_atomic(path, bytes);
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
let written = std::fs::write(path, bytes);
|
||||
written.map_err(|e| format!("{}: {e}", path.display()))
|
||||
}
|
||||
|
||||
/// Atomically replace the file at `path` with the contents of `staged`, a private temporary file
|
||||
/// the engine made itself (so it is not checked), inside the automation write root when there is
|
||||
/// one.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub fn replace_with(path: impl AsRef<Path>, staged: impl AsRef<Path>) -> std::io::Result<()> {
|
||||
let path = path.as_ref();
|
||||
crate::file_access::check_write(path).map_err(|e| std::io::Error::new(std::io::ErrorKind::PermissionDenied, e))?;
|
||||
let mut input = std::fs::File::open(staged)?;
|
||||
crate::atomic::write_atomic_with(path, |file| std::io::copy(&mut input, file).map(|_| ()))
|
||||
}
|
||||
|
||||
/// Could the file at `path` be opened for writing (without truncating it)? Inside the automation
|
||||
/// write root when there is one.
|
||||
pub fn writable(path: impl AsRef<Path>) -> std::io::Result<()> {
|
||||
let path = path.as_ref();
|
||||
crate::file_access::check_write(path).map_err(|e| std::io::Error::new(std::io::ErrorKind::PermissionDenied, e))?;
|
||||
std::fs::OpenOptions::new().write(true).open(path).map(drop)
|
||||
}
|
||||
|
||||
/// The canonical form of `path` (links resolved), inside the automation read root when there is
|
||||
/// one.
|
||||
pub fn canonicalize(path: impl AsRef<Path>) -> std::io::Result<std::path::PathBuf> {
|
||||
let path = path.as_ref();
|
||||
crate::file_access::check_read(path).map_err(|e| std::io::Error::new(std::io::ErrorKind::PermissionDenied, e))?;
|
||||
std::fs::canonicalize(path)
|
||||
}
|
||||
|
||||
/// What the file system says about `path` (links followed), inside the automation read root when
|
||||
/// there is one. A refused path is a `PermissionDenied` error carrying the roots' message.
|
||||
pub fn metadata(path: impl AsRef<Path>) -> std::io::Result<Metadata> {
|
||||
let path = path.as_ref();
|
||||
crate::file_access::check_read(path).map_err(|e| std::io::Error::new(std::io::ErrorKind::PermissionDenied, e))?;
|
||||
std::fs::metadata(path)
|
||||
}
|
||||
|
||||
/// Is there a file at `path` that automation may read?
|
||||
pub fn is_file(path: impl AsRef<Path>) -> bool {
|
||||
metadata(path).is_ok_and(|m| m.is_file())
|
||||
}
|
||||
|
||||
/// Is there a folder at `path` that automation may read?
|
||||
pub fn is_dir(path: impl AsRef<Path>) -> bool {
|
||||
metadata(path).is_ok_and(|m| m.is_dir())
|
||||
}
|
||||
|
||||
/// Is there anything at `path` that automation may read?
|
||||
pub fn exists(path: impl AsRef<Path>) -> bool {
|
||||
metadata(path).is_ok()
|
||||
}
|
||||
|
||||
/// The entries of the folder at `path`, inside the automation read root when there is one.
|
||||
pub fn read_dir(path: impl AsRef<Path>) -> std::io::Result<std::fs::ReadDir> {
|
||||
let path = path.as_ref();
|
||||
crate::file_access::check_read(path).map_err(|e| std::io::Error::new(std::io::ErrorKind::PermissionDenied, e))?;
|
||||
std::fs::read_dir(path)
|
||||
}
|
||||
@@ -11,7 +11,9 @@
|
||||
pub mod atomic;
|
||||
pub mod cmd;
|
||||
pub mod dtd;
|
||||
pub mod file_access;
|
||||
pub mod guard;
|
||||
pub mod io;
|
||||
pub mod links;
|
||||
pub mod math;
|
||||
pub mod recovery;
|
||||
@@ -110,6 +112,16 @@ pub struct DocState {
|
||||
#[derive(Debug)]
|
||||
pub struct FontScope(pub u32);
|
||||
|
||||
/// A graphic loaded in the place cursor (`place.load`, File › Place with no frame to fill).
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct LoadedGraphic {
|
||||
pub asset: designcraft_doc::AssetId,
|
||||
/// Natural size in points.
|
||||
pub size: (f64, f64),
|
||||
/// Image Import Options › Crop to: the box of the graphic a new frame shows (x, y, w, h).
|
||||
pub crop: Option<(f64, f64, f64, f64)>,
|
||||
}
|
||||
|
||||
impl Drop for FontScope {
|
||||
fn drop(&mut self) {
|
||||
designcraft_fonts::FontDb::global().close_scope(self.0);
|
||||
@@ -260,6 +272,7 @@ pub struct Session {
|
||||
pub cache: Arc<Cache>,
|
||||
pub(crate) tool: Box<dyn designcraft_tools::Tool>,
|
||||
pub journal: Vec<(String, Value)>,
|
||||
pub(crate) find_context: Option<cmd::find::FindContext>,
|
||||
pub clipboard: Option<Arc<Document>>,
|
||||
/// Crash-recovery folder (the app sets it; saving or closing a document removes its entry).
|
||||
pub recovery_dir: Option<std::path::PathBuf>,
|
||||
@@ -267,8 +280,8 @@ pub struct Session {
|
||||
pub text_clipboard: Option<(Arc<designcraft_doc::Story>, String)>,
|
||||
/// Requests for the UI (dialogs, view changes) produced by tools/commands.
|
||||
pub ui_requests: Vec<UiRequest>,
|
||||
/// Graphic loaded in the place cursor: (asset, natural size in points).
|
||||
pub loaded: Option<(designcraft_doc::AssetId, (f64, f64))>,
|
||||
/// Graphic loaded in the place cursor.
|
||||
pub loaded: Option<LoadedGraphic>,
|
||||
pub(crate) untitled: u32,
|
||||
/// Transforms applied to the current selection, oldest first (Transform Again / Sequence
|
||||
/// Again), with the selection they were applied to and whether the last one came from a
|
||||
@@ -276,6 +289,8 @@ pub struct Session {
|
||||
pub(crate) transforms: (Vec<(String, Value)>, Vec<designcraft_doc::ItemId>, bool),
|
||||
/// Drag and drop text editing: the press landed in the selected text.
|
||||
pub(crate) text_drag: bool,
|
||||
/// Character formatting chosen at a bare caret, for the text typed there next.
|
||||
pub(crate) typing_format: Option<cmd::text::TypingFormat>,
|
||||
/// The open Object Library (File › New / Open Library).
|
||||
pub library: Option<cmd::library::Library>,
|
||||
/// The open book (File › Open Book).
|
||||
@@ -300,6 +315,7 @@ impl Session {
|
||||
cache: Arc::new(Cache::new()),
|
||||
tool: designcraft_tools::create("selection"),
|
||||
journal: vec![],
|
||||
find_context: None,
|
||||
clipboard: None,
|
||||
recovery_dir: None,
|
||||
text_clipboard: None,
|
||||
@@ -307,6 +323,7 @@ impl Session {
|
||||
loaded: None,
|
||||
transforms: Default::default(),
|
||||
text_drag: false,
|
||||
typing_format: None,
|
||||
library: None,
|
||||
conveyor: Vec::new(),
|
||||
book: None,
|
||||
@@ -358,13 +375,26 @@ impl Session {
|
||||
pub fn doc_mut(&mut self) -> Result<&mut DocState> {
|
||||
self.active_mut().ok_or(EngineError::NoDocument)
|
||||
}
|
||||
/// Release the transient Find/Change domain when its caller starts or closes a search.
|
||||
pub fn reset_find_scope(&mut self) {
|
||||
self.find_context = None;
|
||||
}
|
||||
|
||||
fn discard_stale_find_scope(&mut self) {
|
||||
if self.find_context.as_ref().is_some_and(|c| self.active().is_none_or(|st| !c.is_current(st))) {
|
||||
self.reset_find_scope();
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_active(&mut self, i: usize) {
|
||||
if i < self.docs.len() && self.active != Some(i) {
|
||||
self.reset_find_scope();
|
||||
self.stop_data_preview();
|
||||
self.active = Some(i);
|
||||
}
|
||||
}
|
||||
pub fn add_document(&mut self, d: DocState) -> usize {
|
||||
self.reset_find_scope();
|
||||
self.stop_data_preview();
|
||||
self.docs.push(d);
|
||||
self.active = Some(self.docs.len() - 1);
|
||||
@@ -388,6 +418,7 @@ impl Session {
|
||||
recovery::discard_document(self, i, recovery_dir.as_deref());
|
||||
}
|
||||
if i < self.docs.len() {
|
||||
self.reset_find_scope();
|
||||
self.docs.remove(i);
|
||||
self.active = if self.docs.is_empty() { None } else { Some(i.min(self.docs.len() - 1)) };
|
||||
}
|
||||
@@ -418,6 +449,8 @@ impl Session {
|
||||
if id != "data.preview" && (spec.undoable || spec.journal) {
|
||||
self.stop_data_preview();
|
||||
}
|
||||
// Preview restoration can replace the document before a Find handler resolves bounds.
|
||||
self.discard_stale_find_scope();
|
||||
let before = self.active().map(|d| (d.uid, d.doc.clone()));
|
||||
let r = (spec.run)(self, params)?;
|
||||
// Undo, redo or deleting layers can take the active layer away: new objects would land on
|
||||
@@ -455,6 +488,7 @@ impl Session {
|
||||
if spec.journal {
|
||||
self.journal.push((id.to_string(), params.clone()));
|
||||
}
|
||||
self.discard_stale_find_scope();
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
@@ -475,7 +509,7 @@ impl Session {
|
||||
}
|
||||
let mut d = (*st.doc).clone();
|
||||
if overset {
|
||||
let _ = cmd::place_text_autoflow(&mut d, sid, 500);
|
||||
let _ = cmd::place_text_autoflow(&mut d, sid, 500, "Smart Text Reflow");
|
||||
} else {
|
||||
// Drop empty trailing frames on the last pages (one frame, nothing else there).
|
||||
while let Some(story) = d.story(sid) {
|
||||
@@ -542,6 +576,7 @@ impl Session {
|
||||
st.doc = Arc::new(doc);
|
||||
st.selection = sel;
|
||||
st.revision += 1;
|
||||
self.reset_find_scope();
|
||||
Ok(r)
|
||||
}
|
||||
}
|
||||
@@ -559,6 +594,10 @@ pub(crate) use push_undo as record_undo;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
#[cfg(test)]
|
||||
mod tests_file_guard;
|
||||
#[cfg(test)]
|
||||
mod tests_idml;
|
||||
#[cfg(test)]
|
||||
mod tests_roots;
|
||||
#[cfg(test)]
|
||||
mod tests_table;
|
||||
|
||||
@@ -160,9 +160,15 @@ fn big_op(name: &str) -> Option<&'static str> {
|
||||
})
|
||||
}
|
||||
|
||||
/// Deepest expression nesting parsed. Recursive descent must not overflow the stack on hostile
|
||||
/// input (`\frac\frac…`, `{{{{…`, `\left(\left(…`); past the cap groups stop descending.
|
||||
const MAX_NESTING: usize = 256;
|
||||
|
||||
struct Parser<'a> {
|
||||
s: &'a [char],
|
||||
i: usize,
|
||||
/// Enclosing group depth, at most [`MAX_NESTING`].
|
||||
depth: usize,
|
||||
}
|
||||
|
||||
impl Parser<'_> {
|
||||
@@ -220,14 +226,19 @@ impl Parser<'_> {
|
||||
out
|
||||
}
|
||||
fn arg(&mut self) -> Node {
|
||||
if self.depth >= MAX_NESTING {
|
||||
return Node::Group(Vec::new());
|
||||
}
|
||||
self.depth += 1;
|
||||
self.skip_ws();
|
||||
if self.peek() == Some('{') {
|
||||
let n = if self.peek() == Some('{') {
|
||||
self.i += 1;
|
||||
let g = self.list(Some('}'));
|
||||
Node::Group(g)
|
||||
Node::Group(self.list(Some('}')))
|
||||
} else {
|
||||
self.atom().unwrap_or(Node::Group(vec![]))
|
||||
}
|
||||
};
|
||||
self.depth -= 1;
|
||||
n
|
||||
}
|
||||
fn delimiter(&mut self) -> String {
|
||||
self.skip_ws();
|
||||
@@ -280,7 +291,7 @@ impl Parser<'_> {
|
||||
}
|
||||
s.push(c);
|
||||
}
|
||||
Box::new(parse(&s))
|
||||
Box::new(parse_at(&s, self.depth + 1))
|
||||
});
|
||||
let a = self.arg();
|
||||
Node::Sqrt(idx, Box::new(a))
|
||||
@@ -329,6 +340,10 @@ impl Parser<'_> {
|
||||
})
|
||||
}
|
||||
fn list(&mut self, end: Option<char>) -> Vec<Node> {
|
||||
if self.depth >= MAX_NESTING {
|
||||
return Vec::new();
|
||||
}
|
||||
self.depth += 1;
|
||||
let mut out: Vec<Node> = Vec::new();
|
||||
loop {
|
||||
self.skip_ws();
|
||||
@@ -362,9 +377,13 @@ impl Parser<'_> {
|
||||
}
|
||||
}
|
||||
}
|
||||
self.depth -= 1;
|
||||
out
|
||||
}
|
||||
fn list_until_right(&mut self) -> Vec<Node> {
|
||||
if self.depth >= MAX_NESTING {
|
||||
return Vec::new();
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
loop {
|
||||
self.skip_ws();
|
||||
@@ -375,7 +394,7 @@ impl Parser<'_> {
|
||||
self.i += 6;
|
||||
break;
|
||||
}
|
||||
let mut p = Parser { s: self.s, i: self.i };
|
||||
let mut p = Parser { s: self.s, i: self.i, depth: self.depth + 1 };
|
||||
let one = p.list_one();
|
||||
self.i = p.i;
|
||||
out.extend(one);
|
||||
@@ -410,8 +429,12 @@ impl Parser<'_> {
|
||||
}
|
||||
|
||||
fn parse(src: &str) -> Node {
|
||||
parse_at(src, 0)
|
||||
}
|
||||
|
||||
fn parse_at(src: &str, depth: usize) -> Node {
|
||||
let chars: Vec<char> = src.chars().collect();
|
||||
let mut p = Parser { s: &chars, i: 0 };
|
||||
let mut p = Parser { s: &chars, i: 0, depth };
|
||||
Node::Group(p.list(None))
|
||||
}
|
||||
|
||||
@@ -714,4 +737,18 @@ mod tests {
|
||||
let (svg, _) = to_svg(r"\sqrt{a^2+b^2} \ne \pi", 14.0);
|
||||
assert!(designcraft_images::svg_tree(&svg).is_some());
|
||||
}
|
||||
|
||||
/// Hostile input must not overflow the stack: nesting past the cap stops descending instead
|
||||
/// of recursing once per group (100k levels used to abort the process).
|
||||
#[test]
|
||||
fn an_over_deep_expression_is_bounded() {
|
||||
for latex in [
|
||||
format!("{}x{}", "{".repeat(100_000), "}".repeat(100_000)),
|
||||
format!("{}x", r"\frac".repeat(100_000)),
|
||||
format!("{}x", r"\left(".repeat(100_000)),
|
||||
] {
|
||||
let (svg, _) = to_svg(&latex, 12.0);
|
||||
assert!(!svg.is_empty());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+174
-40
@@ -11,6 +11,10 @@
|
||||
//! An app that starts moves into its own folder what apps that have ended left in theirs, and
|
||||
//! leaves the folder of one still running alone.
|
||||
//!
|
||||
//! A folder given to `file.recovery.save` that is not this run's own may hold other runs' entries
|
||||
//! under the same uids. This run writes there only entries it finds free, replaces and removes
|
||||
//! only those it wrote or recovered, and refuses the folder of a run whose lock is still held.
|
||||
//!
|
||||
//! Each file is replaced atomically, but the pair is not a transaction. The document is published
|
||||
//! and made durable before its metadata so a crash can leave metadata missing or stale, never a
|
||||
//! listed metadata record without a complete primary document. Listing and opening recovery data
|
||||
@@ -192,10 +196,11 @@ fn lock_marker(file: &std::fs::File) -> std::io::Result<Vec<u8>> {
|
||||
}
|
||||
|
||||
/// A run's folder that was removed while it runs is made again by the next save: so is its lock.
|
||||
/// Returns whether `dir` is this run's folder.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn relock(dir: &Path, created: bool) -> Result<()> {
|
||||
fn relock(dir: &Path, created: bool) -> Result<bool> {
|
||||
let mut runs = RUNS.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
let Some(run) = runs.iter_mut().find(|r| r.dir == dir) else { return Ok(()) };
|
||||
let Some(run) = runs.iter_mut().find(|r| r.dir == dir) else { return Ok(false) };
|
||||
validate_recovery_dir(&run.root)?;
|
||||
#[cfg(unix)]
|
||||
let directory = std::fs::symlink_metadata(dir).map_err(|e| EngineError::Other(format!("{}: {e}", dir.display())))?;
|
||||
@@ -219,7 +224,7 @@ fn relock(dir: &Path, created: bool) -> Result<()> {
|
||||
return Err(EngineError::Other(format!("{}: this run no longer owns its recovery folder", dir.display())));
|
||||
}
|
||||
match std::fs::symlink_metadata(dir.join(LOCK)) {
|
||||
Ok(_) => return validate_lock(dir, &run.lock),
|
||||
Ok(_) => return validate_lock(dir, &run.lock).map(|()| true),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
|
||||
Err(e) => return Err(EngineError::Other(format!("{}: {e}", dir.display()))),
|
||||
}
|
||||
@@ -242,7 +247,93 @@ fn relock(dir: &Path, created: bool) -> Result<()> {
|
||||
{
|
||||
run.directory = replacement_directory;
|
||||
}
|
||||
Ok(())
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// Entries this process wrote or recovered in folders that are not its run's own: (canonical
|
||||
/// folder, uid). Document uids start at 1 in every process, so a shared folder's entry under
|
||||
/// one of this run's uids may be another run's.
|
||||
static WRITTEN: std::sync::Mutex<std::collections::BTreeSet<(PathBuf, u64)>> = std::sync::Mutex::new(std::collections::BTreeSet::new());
|
||||
|
||||
/// What this run may do in a recovery folder.
|
||||
struct Access {
|
||||
/// This run's own folder (`run_dir`): every entry in it is this run's.
|
||||
own: bool,
|
||||
key: PathBuf,
|
||||
}
|
||||
|
||||
impl Access {
|
||||
fn owns(&self, uid: u64) -> bool {
|
||||
self.own || WRITTEN.lock().unwrap_or_else(std::sync::PoisonError::into_inner).contains(&(self.key.clone(), uid))
|
||||
}
|
||||
|
||||
fn record(&self, uid: u64) {
|
||||
if !self.own {
|
||||
WRITTEN.lock().unwrap_or_else(std::sync::PoisonError::into_inner).insert((self.key.clone(), uid));
|
||||
}
|
||||
}
|
||||
|
||||
fn forget(&self, uid: u64) {
|
||||
WRITTEN.lock().unwrap_or_else(std::sync::PoisonError::into_inner).remove(&(self.key.clone(), uid));
|
||||
}
|
||||
|
||||
/// Refuse an entry of another run before anything is written: this run never replaces it.
|
||||
fn check_free(&self, dir: &Path, uid: u64) -> Result<()> {
|
||||
if self.owns(uid) {
|
||||
return Ok(());
|
||||
}
|
||||
let (doc, meta) = files(dir, uid);
|
||||
for path in [doc, meta] {
|
||||
match std::fs::symlink_metadata(&path) {
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
|
||||
_ => {
|
||||
return Err(EngineError::Other(format!(
|
||||
"{}: recovery data this run did not write is there; recover it or choose another recovery folder",
|
||||
path.display()
|
||||
)));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Check what this run may do in `dir`. A folder that is not this run's own may be the folder
|
||||
/// of another running app, whose lock that app holds: this run leaves it alone.
|
||||
fn access(dir: &Path, created: bool) -> Result<Access> {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
let own = relock(dir, created)?;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if !own {
|
||||
check_unheld(dir)?;
|
||||
}
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
let own = {
|
||||
let _ = created;
|
||||
false
|
||||
};
|
||||
Ok(Access { own, key: directory_key(dir)? })
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn check_unheld(dir: &Path) -> Result<()> {
|
||||
let path = dir.join(LOCK);
|
||||
let in_use =
|
||||
|| EngineError::Other(format!("{}: another running DesignCraft keeps its recovery data here; choose another recovery folder", dir.display()));
|
||||
match std::fs::symlink_metadata(&path) {
|
||||
Ok(metadata) if is_link_like(&metadata) || !metadata.file_type().is_file() => return Err(in_use()),
|
||||
Ok(_) => {}
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()),
|
||||
Err(e) => return Err(EngineError::Other(format!("{}: {e}", path.display()))),
|
||||
}
|
||||
// Opened for writing: over NFS an exclusive lock on a file opened for reading is refused.
|
||||
let lock = std::fs::OpenOptions::new().read(true).write(true).open(&path).map_err(|e| EngineError::Other(format!("{}: {e}", path.display())))?;
|
||||
match lock.try_lock() {
|
||||
// Free: the run that held it has ended. Dropping the handle releases it again.
|
||||
Ok(()) => Ok(()),
|
||||
Err(std::fs::TryLockError::WouldBlock) => Err(in_use()),
|
||||
Err(std::fs::TryLockError::Error(e)) => Err(EngineError::Other(format!("{}: {e}", path.display()))),
|
||||
}
|
||||
}
|
||||
|
||||
/// Move into `own`, this run's folder, what is left to recover beside it: the entries of runs
|
||||
@@ -329,15 +420,21 @@ fn files(dir: &Path, uid: u64) -> (PathBuf, PathBuf) {
|
||||
(dir.join(format!("{uid}.designcraft")), dir.join(format!("{uid}.json")))
|
||||
}
|
||||
|
||||
/// Remove a document's recovery entry (it was saved or closed).
|
||||
/// Remove a document's recovery entry (it was saved or closed). In a folder that is not this
|
||||
/// run's own, only an entry this run wrote or recovered is removed.
|
||||
pub fn discard(dir: &Path, uid: u64) {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if validate_recovery_dir(dir).is_err() || relock(dir, false).is_err() {
|
||||
if validate_recovery_dir(dir).is_err() {
|
||||
return;
|
||||
}
|
||||
let Ok(access) = access(dir, false) else { return };
|
||||
if !access.owns(uid) {
|
||||
return;
|
||||
}
|
||||
let (d, m) = files(dir, uid);
|
||||
let _ = std::fs::remove_file(d);
|
||||
let _ = std::fs::remove_file(m);
|
||||
access.forget(uid);
|
||||
}
|
||||
|
||||
/// Consume this document's checkpoint provenance after Save/Close/Revert. A default-directory
|
||||
@@ -385,29 +482,29 @@ fn protect_retained_sources(s: &Session, dir: &Path) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn prepare_save(s: &Session, dir: &Path) -> Result<()> {
|
||||
fn prepare_save(s: &Session, dir: &Path) -> Result<Access> {
|
||||
// Check before any write or deletion: a failed republish can retain a source whose uid
|
||||
// coincides with an unrelated live document in a manually configured recovery directory.
|
||||
protect_retained_sources(s, dir)?;
|
||||
let created = secure_recovery_dir(dir)?;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
relock(dir, created)?;
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
let _ = created;
|
||||
Ok(())
|
||||
let access = access(dir, created)?;
|
||||
for document in s.docs.iter().filter(|d| d.is_dirty()) {
|
||||
access.check_free(dir, document.uid)?;
|
||||
}
|
||||
Ok(access)
|
||||
}
|
||||
|
||||
/// Write recovery entries for dirty documents and drop clean checkpoints. Returns how many
|
||||
/// were written. Command callers use the tracked variant without configuring automatic recovery.
|
||||
pub fn save(s: &Session, dir: &Path) -> Result<usize> {
|
||||
prepare_save(s, dir)?;
|
||||
let access = prepare_save(s, dir)?;
|
||||
let mut n = 0;
|
||||
for d in &s.docs {
|
||||
if !d.is_dirty() {
|
||||
discard(dir, d.uid);
|
||||
continue;
|
||||
}
|
||||
write_entry(dir, d)?;
|
||||
write_entry(&access, dir, d)?;
|
||||
n += 1;
|
||||
}
|
||||
Ok(n)
|
||||
@@ -424,7 +521,7 @@ pub(crate) fn save_tracked(s: &mut Session, dir: &Path) -> Result<usize> {
|
||||
));
|
||||
}
|
||||
}
|
||||
prepare_save(s, dir)?;
|
||||
let access = prepare_save(s, dir)?;
|
||||
let mut n = 0;
|
||||
for index in 0..s.docs.len() {
|
||||
if s.docs.get(index).is_some_and(|document| !document.is_dirty()) {
|
||||
@@ -435,25 +532,30 @@ pub(crate) fn save_tracked(s: &mut Session, dir: &Path) -> Result<usize> {
|
||||
let (doc, meta) = files(dir, document.uid);
|
||||
let bytes = designcraft_format::save(document.preview_stash.as_deref().unwrap_or(document.doc.as_ref()))
|
||||
.map_err(|e| EngineError::Other(e.to_string()))?;
|
||||
write_recovery_file(&doc, &bytes)?;
|
||||
// An entry this run did not write is never replaced, even one made since it checked.
|
||||
let replace = access.owns(document.uid);
|
||||
publish_recovery_file(&doc, &bytes, replace)?;
|
||||
access.record(document.uid);
|
||||
// The primary is useful even if optional metadata fails next. Track it immediately.
|
||||
if !has_checkpoint(document, dir) {
|
||||
document.recovery_entries.push((dir.to_path_buf(), document.uid));
|
||||
}
|
||||
let metadata = json!({"path": document.path, "title": document.title(), "saved": designcraft_doc::vars::now()});
|
||||
write_recovery_file(&meta, metadata.to_string().as_bytes())?;
|
||||
publish_recovery_file(&meta, metadata.to_string().as_bytes(), replace)?;
|
||||
n += 1;
|
||||
}
|
||||
Ok(n)
|
||||
}
|
||||
|
||||
/// Publish a document's recovery entry before its optional metadata.
|
||||
fn write_entry(dir: &Path, d: &DocState) -> Result<()> {
|
||||
fn write_entry(access: &Access, dir: &Path, d: &DocState) -> Result<()> {
|
||||
let (doc, meta) = files(dir, d.uid);
|
||||
let bytes = designcraft_format::save(d.preview_stash.as_deref().unwrap_or(d.doc.as_ref())).map_err(|e| EngineError::Other(e.to_string()))?;
|
||||
write_recovery_file(&doc, &bytes)?;
|
||||
let replace = access.owns(d.uid);
|
||||
publish_recovery_file(&doc, &bytes, replace)?;
|
||||
access.record(d.uid);
|
||||
let metadata = json!({"path": d.path, "title": d.title(), "saved": designcraft_doc::vars::now()});
|
||||
write_recovery_file(&meta, metadata.to_string().as_bytes())
|
||||
publish_recovery_file(&meta, metadata.to_string().as_bytes(), replace)
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
@@ -499,11 +601,6 @@ fn secure_recovery_dir(_dir: &Path) -> Result<bool> {
|
||||
Err(EngineError::Other("recovery files are unavailable on the web".into()))
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn write_recovery_file(path: &Path, bytes: &[u8]) -> Result<()> {
|
||||
publish_recovery_file(path, bytes, true)
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn publish_recovery_file(path: &Path, bytes: &[u8], replace: bool) -> Result<()> {
|
||||
let Some(dir) = path.parent() else {
|
||||
@@ -581,11 +678,6 @@ fn sync_recovery_dir(dir: &Path) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn write_recovery_file(_path: &Path, _bytes: &[u8]) -> Result<()> {
|
||||
Err(EngineError::Other("recovery files are unavailable on the web".into()))
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn publish_recovery_file(_path: &Path, _bytes: &[u8], _replace: bool) -> Result<()> {
|
||||
Err(EngineError::Other("recovery files are unavailable on the web".into()))
|
||||
@@ -661,18 +753,13 @@ pub fn open(s: &mut Session, dir: &Path) -> Result<Vec<usize>> {
|
||||
|
||||
fn open_with_publisher(s: &mut Session, dir: &Path, mut publish: impl FnMut(&Path, &[u8]) -> Result<()>) -> Result<Vec<usize>> {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
validate_recovery_dir(dir)?;
|
||||
relock(dir, false)?;
|
||||
}
|
||||
validate_recovery_dir(dir)?;
|
||||
let source = access(dir, false)?;
|
||||
let destination = s.recovery_dir.clone().unwrap_or_else(|| dir.to_path_buf());
|
||||
let created = secure_recovery_dir(&destination)?;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
relock(&destination, created)?;
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
let _ = created;
|
||||
let source_key = directory_key(dir)?;
|
||||
let destination_key = directory_key(&destination)?;
|
||||
let target = access(&destination, created)?;
|
||||
let source_key = source.key.clone();
|
||||
let destination_key = target.key.clone();
|
||||
let mut opened = Vec::new();
|
||||
// For this run's own folder, first bring in what runs that ended left in theirs.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
@@ -705,6 +792,8 @@ fn open_with_publisher(s: &mut Session, dir: &Path, mut publish: impl FnMut(&Pat
|
||||
let mut st = DocState::new(d, path);
|
||||
reserve_uid(&mut st, &mut occupied)?;
|
||||
st.recovery_entries.push((dir.to_path_buf(), uid));
|
||||
// Recovered, the entry is this run's: Save and Close of its document may remove it.
|
||||
source.record(uid);
|
||||
st.fonts = fonts;
|
||||
// Unsaved: the copy on disk (if any) is older than what was recovered.
|
||||
st.saved_doc = std::sync::Arc::new((*st.doc).clone());
|
||||
@@ -721,6 +810,7 @@ fn open_with_publisher(s: &mut Session, dir: &Path, mut publish: impl FnMut(&Pat
|
||||
.and_then(|bytes| publish(&document, &bytes));
|
||||
match published {
|
||||
Ok(()) => {
|
||||
target.record(state.uid);
|
||||
state.recovery_entries.push((destination.clone(), state.uid));
|
||||
let meta = json!({"path": state.path, "title": state.title(), "saved": designcraft_doc::vars::now()});
|
||||
match publish(&metadata, meta.to_string().as_bytes()) {
|
||||
@@ -1477,6 +1567,50 @@ mod tests {
|
||||
assert!(!left.join(LOCK).exists());
|
||||
assert_eq!(std::fs::read(left.join("1.designcraft")).unwrap(), b"left with no lock");
|
||||
}
|
||||
|
||||
/// Another run's entry under uid 7 in a chosen folder, with a document of this run numbered
|
||||
/// 7 too: document uids start at 1 in every process.
|
||||
fn chosen_folder_with_another_runs_entry() -> (tempfile::TempDir, PathBuf, PathBuf) {
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
let (doc, meta) = files(root.path(), 7);
|
||||
std::fs::write(&doc, b"another run's document").unwrap();
|
||||
std::fs::write(&meta, b"{\"title\": \"theirs\"}").unwrap();
|
||||
(root, doc, meta)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_clean_document_leaves_another_runs_entry_in_a_chosen_folder() {
|
||||
let (root, doc, meta) = chosen_folder_with_another_runs_entry();
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
s.docs[0].uid = 7;
|
||||
assert!(!s.docs[0].is_dirty());
|
||||
s.execute("file.recovery.save", &json!({"dir": root.path().to_string_lossy()})).unwrap();
|
||||
s.execute("file.close", &json!({})).unwrap();
|
||||
assert_eq!(std::fs::read(doc).unwrap(), b"another run's document");
|
||||
assert_eq!(std::fs::read(meta).unwrap(), b"{\"title\": \"theirs\"}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dirty_document_does_not_overwrite_another_runs_entry_in_a_chosen_folder() {
|
||||
let (root, doc, meta) = chosen_folder_with_another_runs_entry();
|
||||
let mut s = unsaved("this run's work");
|
||||
s.docs[0].uid = 7;
|
||||
assert!(s.execute("file.recovery.save", &json!({"dir": root.path().to_string_lossy()})).is_err());
|
||||
assert!(save(&s, root.path()).is_err());
|
||||
assert_eq!(std::fs::read(doc).unwrap(), b"another run's document");
|
||||
assert_eq!(std::fs::read(meta).unwrap(), b"{\"title\": \"theirs\"}");
|
||||
}
|
||||
|
||||
/// A chosen folder that is a running app's run folder is that app's.
|
||||
#[test]
|
||||
fn a_folder_another_running_app_holds_is_refused() {
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
let held = new_lock(root.path()).unwrap();
|
||||
held.try_lock().unwrap();
|
||||
assert!(save(&dirty_session(), root.path()).is_err());
|
||||
assert!(list(root.path()).is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
+54
-10
@@ -5,7 +5,8 @@
|
||||
//! becomes the JSON value at `path` in the result of step `N` (0-based): after
|
||||
//! `frame.create → {"id": 8, "story": 9}`, `{"story": "$0.story"}` passes `9`. Paths are dotted
|
||||
//! keys and array indices (`$2.ids.0`). Inside longer strings `${N.path}` is replaced by the
|
||||
//! value's text (`"Frame ${0.id}"`).
|
||||
//! value's text (`"Frame ${0.id}"`). Any other string starting with `$` is plain text (`"$1-$2"`,
|
||||
//! `"$5 off"`), and `$$` anywhere writes a literal `$` (`"$$1"` passes `$1`, a GREP group).
|
||||
//!
|
||||
//! **Script text** ([`parse`]): a JSON array of steps, JSON lines (`{"command": …, "params": …}`),
|
||||
//! or compact lines `command.id {json}` / `command.id={json}` / `command.id`; blank lines and
|
||||
@@ -92,27 +93,44 @@ fn short(v: &Value) -> String {
|
||||
if s.len() > 120 { format!("{}…", &s[..s.floor_char_boundary(120)]) } else { s }
|
||||
}
|
||||
|
||||
/// Whether `r` (the text after `$`) is a whole reference: digits or `last`, then zero or more
|
||||
/// `.segment` of ASCII letters, digits, `_` or `-`.
|
||||
fn is_reference(r: &str) -> bool {
|
||||
let mut parts = r.split('.');
|
||||
let head = parts.next().unwrap_or("");
|
||||
let head_ok = head == "last" || (!head.is_empty() && head.bytes().all(|b| b.is_ascii_digit()));
|
||||
head_ok && parts.all(|p| !p.is_empty() && p.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-'))
|
||||
}
|
||||
|
||||
/// Replace references in `params` with values from earlier `results`.
|
||||
pub fn resolve(params: &Value, results: &[Value]) -> Result<Value, String> {
|
||||
Ok(match params {
|
||||
Value::String(s) => {
|
||||
if let Some(r) = s.strip_prefix('$').filter(|r| !r.is_empty() && !r.contains(['{', ' '])) {
|
||||
if let Some(r) = s.strip_prefix('$').filter(|r| is_reference(r)) {
|
||||
return lookup(r, results);
|
||||
}
|
||||
if !s.contains("${") {
|
||||
if !s.contains("${") && !s.contains("$$") {
|
||||
return Ok(params.clone());
|
||||
}
|
||||
let mut out = String::new();
|
||||
let mut rest = s.as_str();
|
||||
while let Some(i) = rest.find("${") {
|
||||
while let Some(i) = rest.find('$') {
|
||||
out.push_str(&rest[..i]);
|
||||
let end = rest[i..].find('}').ok_or_else(|| format!("unclosed `${{` in {s:?}"))? + i;
|
||||
let v = lookup(&rest[i + 2..end], results)?;
|
||||
match v {
|
||||
Value::String(t) => out.push_str(&t),
|
||||
other => out.push_str(&other.to_string()),
|
||||
let after = &rest[i + 1..];
|
||||
if let Some(tail) = after.strip_prefix('$') {
|
||||
out.push('$');
|
||||
rest = tail;
|
||||
} else if let Some(inner) = after.strip_prefix('{') {
|
||||
let end = inner.find('}').ok_or_else(|| format!("unclosed `${{` in {s:?}"))?;
|
||||
match lookup(&inner[..end], results)? {
|
||||
Value::String(t) => out.push_str(&t),
|
||||
other => out.push_str(&other.to_string()),
|
||||
}
|
||||
rest = &inner[end + 1..];
|
||||
} else {
|
||||
out.push('$');
|
||||
rest = after;
|
||||
}
|
||||
rest = &rest[end + 1..];
|
||||
}
|
||||
out.push_str(rest);
|
||||
Value::String(out)
|
||||
@@ -196,6 +214,32 @@ mod tests {
|
||||
assert_eq!(r, json!({"story": 9, "id": 5, "label": "Frame 8 of A", "keep": "$", "list": ["A"]}));
|
||||
assert!(resolve(&json!({"x": "$5.id"}), &results).unwrap_err().contains("hasn't run"));
|
||||
assert!(resolve(&json!({"x": "$0.nope"}), &results).unwrap_err().contains("no `nope`"));
|
||||
assert!(resolve(&json!({"x": "Frame ${0.id"}), &results).unwrap_err().contains("unclosed"));
|
||||
}
|
||||
|
||||
/// GREP replacements start with `$` too; only a well-formed reference is looked up (#749).
|
||||
#[test]
|
||||
fn only_well_formed_references_resolve() {
|
||||
let results = vec![json!({"id": 8})];
|
||||
let p = json!({"a": "$1\u{a0}", "b": "$1-$2", "c": "$5 off", "d": "$$1", "e": "$${0.id}", "f": "$0.id", "g": "${0.id}x", "h": "$1$$", "i": "$1."});
|
||||
let r = resolve(&p, &results).unwrap();
|
||||
assert_eq!(r, json!({"a": "$1\u{a0}", "b": "$1-$2", "c": "$5 off", "d": "$1", "e": "${0.id}", "f": 8, "g": "8x", "h": "$1$", "i": "$1."}));
|
||||
}
|
||||
|
||||
/// Czech typesetting: a nonbreaking space after one-letter prepositions.
|
||||
#[test]
|
||||
fn a_script_grep_change_keeps_its_group_reference() {
|
||||
let mut s = crate::Session::new();
|
||||
let steps = vec![
|
||||
Step { command: "file.new".into(), params: json!({}) },
|
||||
Step { command: "frame.create".into(), params: json!({"rect": [36, 36, 300, 300], "content": "text", "text": "a v Praze"}) },
|
||||
Step { command: "find.change".into(), params: json!({"find": r"\b([av]) ", "change": "$1\u{a0}", "grep": true, "caseSensitive": true}) },
|
||||
Step { command: "story.get".into(), params: json!({"story": "$1.story"}) },
|
||||
];
|
||||
let r = s.run_script(&steps);
|
||||
assert!(r.failed.is_none(), "{r:?}");
|
||||
assert_eq!(r.results[2]["count"], 2);
|
||||
assert_eq!(r.results[3]["text"], "a\u{a0}v\u{a0}Praze");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -569,3 +569,366 @@ fn commands_take_non_object_params_without_panicking() {
|
||||
assert!(r.is_ok(), "{p}: {r:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn page_tool_selects_a_page_and_its_handles_preview_or_resize_it() {
|
||||
use designcraft_tools::{CanvasLayout, Mods, PointerEvent, PointerKind};
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 612, "height": 792, "facingPages": false})).unwrap();
|
||||
let id = s.execute("frame.create", &json!({"rect": [400, 100, 500, 200]})).unwrap()["id"].as_u64().unwrap();
|
||||
let frame = |s: &Session| s.doc().unwrap().doc.item(designcraft_doc::ItemId(id)).unwrap().bounds();
|
||||
let width = |s: &Session| s.doc().unwrap().doc.spreads[0].pages[0].width;
|
||||
// The page on the canvas (a single page is centred on the spine).
|
||||
let page = |s: &Session| {
|
||||
let d = &s.doc().unwrap().doc;
|
||||
CanvasLayout::new(d, false).page_rect(d, 0).unwrap()
|
||||
};
|
||||
s.set_tool("page");
|
||||
let v = ViewInfo::at_zoom(1.0);
|
||||
let ev = |kind, x: f64, y: f64, alt: bool| PointerEvent { mods: Mods { alt, ..Default::default() }, ..PointerEvent::new(kind, x, y) };
|
||||
let drag = |s: &mut Session, from: (f64, f64), by: f64, alt: bool, check: &dyn Fn(&Session)| {
|
||||
s.pointer(&ev(PointerKind::Down, from.0, from.1, alt), v).unwrap();
|
||||
s.pointer(&ev(PointerKind::Drag, from.0 + by, from.1, alt), v).unwrap();
|
||||
check(s);
|
||||
s.pointer(&ev(PointerKind::Up, from.0 + by, from.1, alt), v).unwrap();
|
||||
};
|
||||
// A click selects the page.
|
||||
let c = page(&s).center();
|
||||
s.pointer(&ev(PointerKind::Down, c.x, c.y, false), v).unwrap();
|
||||
s.pointer(&ev(PointerKind::Up, c.x, c.y, false), v).unwrap();
|
||||
assert_eq!(s.doc().unwrap().selection.page, Some(0));
|
||||
// A plain drag of the right handle previews the page's liquid rule and springs back.
|
||||
s.execute("liquid.pageRule", &json!({"rule": "scale"})).unwrap();
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
let r = page(&s);
|
||||
drag(&mut s, (r.x1, r.center().y), 612.0, false, &|s| {
|
||||
assert_eq!(width(s), 1224.0, "previewed");
|
||||
// Scale keeps proportions: only wider, so the frame is centred on the wider page.
|
||||
assert_eq!(frame(s).x0, 706.0, "the Scale rule in the preview: {:?}", frame(s));
|
||||
});
|
||||
assert_eq!((width(&s), frame(&s)), (612.0, designcraft_geom::Rect::new(400.0, 100.0, 500.0, 200.0)), "sprung back");
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo, "nothing to undo");
|
||||
// Alt-drag resizes; with the rule off the frame stays where it is.
|
||||
s.execute("liquid.pageRule", &json!({"rule": "off"})).unwrap();
|
||||
let r = page(&s);
|
||||
drag(&mut s, (r.x1, r.center().y), 100.0, true, &|_| {});
|
||||
assert_eq!(width(&s), 712.0);
|
||||
assert_eq!(frame(&s).x0, 400.0);
|
||||
// The left handle grows the page to the left: the frame keeps its place by the right edge.
|
||||
let r = page(&s);
|
||||
drag(&mut s, (r.x0, r.center().y), -100.0, true, &|_| {});
|
||||
let pg = s.doc().unwrap().doc.spreads[0].pages[0].clone();
|
||||
assert_eq!(pg.width, 812.0);
|
||||
assert_eq!(frame(&s).x0 - pg.x, 500.0, "100 pt further from the page's left edge");
|
||||
// A click on the pasteboard deselects the page.
|
||||
let r = page(&s);
|
||||
s.pointer(&ev(PointerKind::Down, r.x0 - 200.0, r.center().y, false), v).unwrap();
|
||||
assert_eq!(s.doc().unwrap().selection.page, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn page_size_keeps_objects_by_its_anchor() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 400, "facingPages": false})).unwrap();
|
||||
let id = s.execute("frame.create", &json!({"rect": [100, 100, 200, 200]})).unwrap()["id"].as_u64().unwrap();
|
||||
let frame = |s: &Session| s.doc().unwrap().doc.item(designcraft_doc::ItemId(id)).unwrap().bounds();
|
||||
// Bottom-right stays put: 100 wider and 50 taller moves the frame 100 right and 50 down.
|
||||
s.execute("layout.pageSize", &json!({"pages": [1], "width": 500, "height": 450, "anchor": 8})).unwrap();
|
||||
assert_eq!(frame(&s), designcraft_geom::Rect::new(200.0, 150.0, 300.0, 250.0));
|
||||
// The centre: half of it.
|
||||
s.execute("layout.pageSize", &json!({"pages": [1], "width": 700, "height": 450, "anchor": 4})).unwrap();
|
||||
assert_eq!(frame(&s).x0, 300.0);
|
||||
assert!(s.execute("layout.pageSize", &json!({"pages": [1], "width": 700, "anchor": 9})).is_err());
|
||||
assert!(s.execute("layout.selectPage", &json!({"page": 2})).is_err());
|
||||
assert_eq!(s.execute("layout.selectPage", &json!({"page": 1})).unwrap()["page"], 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn controlled_by_parent_takes_the_parent_pages_rule() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 400, "facingPages": false})).unwrap();
|
||||
let id = s.execute("frame.create", &json!({"rect": [100, 100, 200, 200]})).unwrap()["id"].as_u64().unwrap();
|
||||
let frame = |s: &Session| s.doc().unwrap().doc.item(designcraft_doc::ItemId(id)).unwrap().bounds();
|
||||
// The page follows its parent; the parent page re-centres.
|
||||
s.execute("liquid.pageRule", &json!({"rule": "controlledByParent", "pages": [1]})).unwrap();
|
||||
s.edit(|d, _| {
|
||||
std::sync::Arc::make_mut(&mut d.parents[0]).pages[0].liquid = designcraft_doc::LiquidRule::ReCenter;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("layout.pageSize", &json!({"pages": [1], "width": 600})).unwrap();
|
||||
assert_eq!(frame(&s).x0, 200.0, "re-centred: {:?}", frame(&s));
|
||||
// Without a parent (or a parent that's also controlled by its parent) nothing moves.
|
||||
s.execute("layout.pages.applyParent", &json!({"pages": [0], "parent": null})).unwrap();
|
||||
s.execute("layout.pageSize", &json!({"pages": [1], "width": 800})).unwrap();
|
||||
assert_eq!(frame(&s).x0, 200.0);
|
||||
// Show Parent Page Overlay is a page option.
|
||||
s.execute("layout.pageOptions", &json!({"pages": [1], "showParentOverlay": true})).unwrap();
|
||||
assert!(s.doc().unwrap().doc.spreads[0].pages[0].show_parent_overlay);
|
||||
assert!(s.execute("layout.pageOptions", &json!({"pages": [2], "showParentOverlay": true})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn page_tool_pins_and_locks_objects_on_object_based_pages() {
|
||||
use designcraft_tools::{CanvasLayout, Mods, PointerEvent, PointerKind};
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 612, "height": 792, "facingPages": false})).unwrap();
|
||||
let id = s.execute("frame.create", &json!({"rect": [256, 72, 356, 132]})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("liquid.pageRule", &json!({"rule": "objectBased"})).unwrap();
|
||||
s.execute("edit.deselectAll", &json!({})).unwrap();
|
||||
s.set_tool("page");
|
||||
let v = ViewInfo::at_zoom(1.0);
|
||||
let ev =
|
||||
|kind, p: designcraft_geom::Point, alt: bool| PointerEvent { mods: Mods { alt, ..Default::default() }, ..PointerEvent::new(kind, p.x, p.y) };
|
||||
let canvas = |s: &Session| {
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let l = CanvasLayout::new(d, false);
|
||||
(
|
||||
l.page_rect(d, 0).unwrap(),
|
||||
l.xf(designcraft_doc::SpreadRef::Doc(0)).transform_rect_bbox(d.item(designcraft_doc::ItemId(id)).unwrap().bounds()),
|
||||
)
|
||||
};
|
||||
let click = |s: &mut Session, p: designcraft_geom::Point| {
|
||||
s.pointer(&ev(PointerKind::Down, p, false), v).unwrap();
|
||||
s.pointer(&ev(PointerKind::Up, p, false), v).unwrap();
|
||||
};
|
||||
let liquid = |s: &Session| s.doc().unwrap().doc.item(designcraft_doc::ItemId(id)).unwrap().liquid;
|
||||
// A click on the object selects it with its page; its pins and locks show.
|
||||
let (_, o) = canvas(&s);
|
||||
click(&mut s, o.center());
|
||||
let sel = s.doc().unwrap().selection.clone();
|
||||
assert_eq!((sel.page, sel.items.clone()), (Some(0), vec![designcraft_doc::ItemId(id)]));
|
||||
assert!(
|
||||
s.overlays(v)
|
||||
.iter()
|
||||
.any(|o| matches!(o, designcraft_tools::Overlay::LiquidPins { pins: [false, false, false, false], resize: [true, true], .. }))
|
||||
);
|
||||
// The right pin (14 px outside the right edge) and the width lock (10 px right of the centre).
|
||||
click(&mut s, designcraft_geom::Point::new(o.x1 + 14.0, o.center().y));
|
||||
click(&mut s, designcraft_geom::Point::new(o.center().x + 10.0, o.center().y));
|
||||
let l = liquid(&s).unwrap();
|
||||
assert!(l.pin_right && !l.resize_width && l.resize_height && !l.pin_left, "{l:?}");
|
||||
// Alt-drag the page 100 pt wider: the pinned, width-locked frame keeps its size by the right edge.
|
||||
let (p, _) = canvas(&s);
|
||||
let right = designcraft_geom::Point::new(p.x1, p.center().y);
|
||||
s.pointer(&ev(PointerKind::Down, right, true), v).unwrap();
|
||||
s.pointer(&ev(PointerKind::Drag, right + designcraft_geom::Vec2::new(100.0, 0.0), true), v).unwrap();
|
||||
s.pointer(&ev(PointerKind::Up, right + designcraft_geom::Vec2::new(100.0, 0.0), true), v).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let (pg, b) = (&d.spreads[0].pages[0], d.item(designcraft_doc::ItemId(id)).unwrap().bounds());
|
||||
assert_eq!(pg.width, 712.0);
|
||||
assert!((b.width() - 100.0).abs() < 1e-6 && (pg.x + pg.width - b.x1 - 256.0).abs() < 1e-6, "{b:?}");
|
||||
// Hovering a pin shows its tooltip.
|
||||
let (_, o) = canvas(&s);
|
||||
s.pointer(&ev(PointerKind::Move, designcraft_geom::Point::new(o.x1 + 14.0, o.center().y), false), v).unwrap();
|
||||
assert!(s.overlays(v).iter().any(|o| matches!(o, designcraft_tools::Overlay::Tip { text, .. } if text.starts_with("Object is pinned"))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn duplicating_a_page_keeps_its_own_size_rule_guides_and_objects() {
|
||||
// Chris Cicchino's Page Tool video (2:06): the letterhead page is duplicated, then resized.
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 252, "height": 144, "facingPages": false})).unwrap();
|
||||
s.execute("layout.pages.insert", &json!({"count": 1})).unwrap();
|
||||
s.execute("layout.pageSize", &json!({"pages": [2], "width": 612, "height": 792})).unwrap();
|
||||
s.execute("liquid.pageRule", &json!({"rule": "scale", "pages": [2]})).unwrap();
|
||||
s.execute("guide.add", &json!({"spread": 1, "page": 0, "orientation": "vertical", "position": 300})).unwrap();
|
||||
s.execute("frame.create", &json!({"spread": 1, "rect": [100, 100, 200, 200]})).unwrap();
|
||||
let r = s.execute("layout.pages.duplicateSpread", &json!({"spread": 1})).unwrap();
|
||||
assert_eq!(r["page"], 2);
|
||||
let d = s.doc().unwrap().doc.clone();
|
||||
let (si, pi) = d.page_loc(2).unwrap();
|
||||
let pg = &d.spreads[si].pages[pi];
|
||||
assert_eq!((pg.width, pg.height, pg.liquid), (612.0, 792.0, designcraft_doc::LiquidRule::Scale));
|
||||
assert_eq!(pg.guides.len(), 1);
|
||||
assert_eq!(d.spreads[si].items.len(), 1);
|
||||
// At the end of the document (the New Page button): the business card, not the last page's size.
|
||||
let r = s.execute("layout.pages.duplicateSpread", &json!({"spread": 0, "atEnd": true})).unwrap();
|
||||
assert_eq!(r["page"], 3);
|
||||
let d = s.doc().unwrap().doc.clone();
|
||||
let (si, pi) = d.page_loc(3).unwrap();
|
||||
assert_eq!((d.spreads[si].pages[pi].width, d.spreads[si].pages[pi].height), (252.0, 144.0));
|
||||
}
|
||||
|
||||
/// Load the text from a frame's out port with the Selection tool and click on the pasteboard:
|
||||
/// a new frame is threaded there and the overset text flows into it.
|
||||
#[test]
|
||||
fn threading_with_the_loaded_text_cursor_on_the_sample() {
|
||||
use designcraft_tools::{PointerEvent, PointerKind};
|
||||
let mut s = Session::new();
|
||||
s.execute("file.newSample", &json!({})).unwrap();
|
||||
let d = s.doc().unwrap().doc.clone();
|
||||
let (sid, first) = d.stories.values().find(|st| st.frames.len() >= 2).map(|st| (st.id, st.frames[0])).expect("a threaded story");
|
||||
// Break the thread so the first frame is overset, and select it.
|
||||
s.execute("text.unthread", &json!({"frame": first.0})).unwrap();
|
||||
assert!(s.cache.get(&s.doc().unwrap().doc, sid, None).is_overset());
|
||||
s.execute("selection.set", &json!({"ids": [first.0]})).unwrap();
|
||||
s.set_tool("selection");
|
||||
let v = ViewInfo::at_zoom(1.0);
|
||||
let layout = s.layout();
|
||||
let port = designcraft_tools::thread::port_center(&s.doc().unwrap().doc, &layout, first, true, v.zoom).unwrap();
|
||||
let ev = |k, p: designcraft_geom::Point| PointerEvent::new(k, p.x, p.y);
|
||||
s.pointer(&ev(PointerKind::Down, port), v).unwrap();
|
||||
s.pointer(&ev(PointerKind::Up, port), v).unwrap();
|
||||
assert_eq!(s.cursor(port + designcraft_geom::Vec2::new(-2000.0, 0.0), Default::default(), v), designcraft_tools::Cursor::LoadedText);
|
||||
// On the pasteboard left of the first spread.
|
||||
let b = layout.slots[0].bounds;
|
||||
let at = designcraft_geom::Point::new(b.x0 - 300.0, b.y0 + 100.0);
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
s.pointer(&ev(PointerKind::Down, at), v).unwrap();
|
||||
s.pointer(&ev(PointerKind::Up, at), v).unwrap();
|
||||
let st = s.doc().unwrap();
|
||||
assert_eq!(st.history.undo.len(), undo + 1, "one undo step");
|
||||
let frames = st.doc.story(sid).unwrap().frames.clone();
|
||||
assert_eq!(frames.len(), 2);
|
||||
let new = frames[1];
|
||||
assert_eq!(st.selection.items, [new]);
|
||||
let cs = s.cache.get(&s.doc().unwrap().doc, sid, None);
|
||||
assert!(cs.frames.iter().any(|f| f.frame == new && !f.range.is_empty()), "the text flows into the new frame");
|
||||
let nb = s.doc().unwrap().doc.item(new).unwrap().bounds();
|
||||
assert!((nb.y0 - layout.to_spread(designcraft_doc::SpreadRef::Doc(0), at).y).abs() < 1e-6, "{nb:?}");
|
||||
}
|
||||
|
||||
/// Drag a selection handle of item 0 on spread 0 from the edge point `at` by `by` (canvas units).
|
||||
fn drag_handle(s: &mut Session, at: designcraft_geom::Point, by: designcraft_geom::Vec2, v: ViewInfo) {
|
||||
use designcraft_tools::{PointerEvent, PointerKind};
|
||||
let p = s.layout().to_canvas(designcraft_doc::SpreadRef::Doc(0), at);
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, p.x, p.y), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, p.x + by.x / 2.0, p.y + by.y / 2.0), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, p.x + by.x, p.y + by.y), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, p.x + by.x, p.y + by.y), v).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_frame_resize_snaps_to_the_margins() {
|
||||
use designcraft_geom::{Point, Vec2};
|
||||
for zoom in [1.0, 0.5] {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.newSample", &json!({})).unwrap();
|
||||
let margin = s.doc().unwrap().doc.spreads[0].pages[0].margin_rect();
|
||||
let (x0, y0) = (margin.x0 + 40.0, margin.y0 + 40.0);
|
||||
s.execute("frame.create", &json!({"rect": [x0, y0, x0 + 200.0, y0 + 200.0], "content": "text"})).unwrap();
|
||||
s.set_tool("selection");
|
||||
let v = ViewInfo::at_zoom(zoom);
|
||||
let b0 = s.doc().unwrap().doc.spreads[0].items.last().unwrap().bounds();
|
||||
// Right handle to 1.5 pt short of the right margin.
|
||||
drag_handle(&mut s, Point::new(b0.x1, b0.center().y), Vec2::new(margin.x1 - 1.5 - b0.x1, 0.0), v);
|
||||
let b = s.doc().unwrap().doc.spreads[0].items.last().unwrap().bounds();
|
||||
assert!((b.x1 - margin.x1).abs() < 1e-6, "zoom {zoom}: right edge {} not on the margin {}", b.x1, margin.x1);
|
||||
// Bottom handle to 1.5 pt past the bottom margin.
|
||||
drag_handle(&mut s, Point::new(b.center().x, b.y1), Vec2::new(0.0, margin.y1 + 1.5 - b.y1), v);
|
||||
let b = s.doc().unwrap().doc.spreads[0].items.last().unwrap().bounds();
|
||||
assert!((b.y1 - margin.y1).abs() < 1e-6, "zoom {zoom}: bottom edge {} not on the margin {}", b.y1, margin.y1);
|
||||
// Top-left corner handle onto the top and left margins.
|
||||
drag_handle(&mut s, Point::new(b.x0, b.y0), Vec2::new(margin.x0 + 1.0 - b.x0, margin.y0 - 1.0 - b.y0), v);
|
||||
let b = s.doc().unwrap().doc.spreads[0].items.last().unwrap().bounds();
|
||||
assert!((b.x0 - margin.x0).abs() < 1e-6 && (b.y0 - margin.y0).abs() < 1e-6, "zoom {zoom}: corner {b:?} not on the margins {margin:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn type_tool_frames_snap_to_the_margins() {
|
||||
use designcraft_geom::Point;
|
||||
use designcraft_tools::{PointerEvent, PointerKind};
|
||||
let mut s = session();
|
||||
let margin = s.doc().unwrap().doc.spreads[0].pages[0].margin_rect();
|
||||
s.set_tool("type");
|
||||
let v = ViewInfo::at_zoom(1.0);
|
||||
let c = |s: &Session, x: f64, y: f64| s.layout().to_canvas(designcraft_doc::SpreadRef::Doc(0), Point::new(x, y));
|
||||
// From 1.5 pt off the top-left margin corner to 1.5 pt off the right margin.
|
||||
let a = c(&s, margin.x0 + 1.5, margin.y0 + 1.5);
|
||||
let b = c(&s, margin.x1 - 1.5, margin.y0 + 101.5);
|
||||
let before = s.doc().unwrap().doc.spreads[0].items.len();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, a.x, a.y), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, (a.x + b.x) / 2.0, b.y), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, b.x, b.y), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, b.x, b.y), v).unwrap();
|
||||
let items = &s.doc().unwrap().doc.spreads[0].items;
|
||||
assert_eq!(items.len(), before + 1, "a frame was drawn");
|
||||
let r = items.last().unwrap().bounds();
|
||||
assert!((r.x0 - margin.x0).abs() < 1e-6 && (r.y0 - margin.y0).abs() < 1e-6, "press point {r:?} vs {margin:?}");
|
||||
assert!((r.x1 - margin.x1).abs() < 1e-6, "right edge {} vs {}", r.x1, margin.x1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn duplicating_a_page_to_an_index_is_one_undo_step() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"facingPages": false})).unwrap();
|
||||
s.execute("layout.pages.insert", &json!({"count": 2})).unwrap();
|
||||
for (page, width) in [(1, 300), (2, 400), (3, 500)] {
|
||||
s.execute("layout.pageSize", &json!({"pages": [page], "width": width, "height": 600})).unwrap();
|
||||
}
|
||||
let widths = |s: &Session| {
|
||||
let d = &s.doc().unwrap().doc;
|
||||
(0..d.page_count()).map(|i| d.page_loc(i).map(|(si, pi)| d.spreads[si].pages[pi].width)).collect::<Option<Vec<_>>>().unwrap()
|
||||
};
|
||||
// Backwards: the last page copied to the front.
|
||||
let r = s.execute("layout.pages.duplicateSpread", &json!({"spread": 2, "to": 0})).unwrap();
|
||||
assert_eq!(r["page"], 0);
|
||||
assert_eq!(widths(&s), [500.0, 300.0, 400.0, 500.0]);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(widths(&s), [300.0, 400.0, 500.0]);
|
||||
// Forwards: the first page copied to the end.
|
||||
s.execute("layout.pages.duplicateSpread", &json!({"spread": 0, "to": 3})).unwrap();
|
||||
assert_eq!(widths(&s), [300.0, 400.0, 500.0, 300.0]);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(widths(&s), [300.0, 400.0, 500.0]);
|
||||
// Past the end: refused, nothing changes.
|
||||
assert!(s.execute("layout.pages.duplicateSpread", &json!({"spread": 0, "to": 4})).is_err());
|
||||
assert_eq!(widths(&s), [300.0, 400.0, 500.0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_type_tool_draws_a_text_frame_over_a_locked_frame() {
|
||||
// Adobe's "Set up a modern magazine layout" (4:03): with the page frame locked (Cmd+L), the
|
||||
// Type tool draws text frames on top of it; the locked frame stays an empty frame.
|
||||
use designcraft_tools::{PointerEvent, PointerKind, SnapView};
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 612, "height": 792, "facingPages": false})).unwrap();
|
||||
let big = s.execute("frame.create", &json!({"rect": [36, 36, 576, 756], "content": "unassigned"})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("object.stroke", &json!({"ids": [big], "swatch": "[Black]", "weight": 6})).unwrap();
|
||||
s.execute("object.lock", &json!({"ids": [big]})).unwrap();
|
||||
s.execute("edit.deselectAll", &json!({})).unwrap();
|
||||
s.set_tool("type");
|
||||
let v = ViewInfo { snap: SnapView::OFF, ..ViewInfo::at_zoom(1.0) };
|
||||
let layout = s.layout();
|
||||
let at = |x: f64, y: f64| layout.to_canvas(designcraft_doc::SpreadRef::Doc(0), designcraft_geom::Point::new(x, y));
|
||||
let (a, b) = (at(100.0, 100.0), at(300.0, 200.0));
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, a.x, a.y), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0 + a.x - 100.0, a.y + 50.0), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, b.x, b.y), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, b.x, b.y), v).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let it = d.item(designcraft_doc::ItemId(big)).unwrap();
|
||||
assert!(matches!(it.content, designcraft_doc::Content::Unassigned), "the locked frame stays empty");
|
||||
let frames: Vec<_> = d.spreads[0].items.iter().filter(|i| i.is_text_frame()).collect();
|
||||
assert_eq!(frames.len(), 1, "a new text frame");
|
||||
let r = frames[0].bounds();
|
||||
assert!((r.x0 - 100.0).abs() < 1e-6 && (r.y1 - 200.0).abs() < 1e-6, "{r:?}");
|
||||
// The engine refuses to turn a locked empty frame into a text frame.
|
||||
assert!(s.execute("text.placeCaret", &json!({"frame": big, "point": [300, 400]})).is_err());
|
||||
// Unlocked, a press inside converts it, as before.
|
||||
s.execute("object.unlockAll", &json!({})).unwrap();
|
||||
s.execute("text.placeCaret", &json!({"frame": big, "point": [300, 400]})).unwrap();
|
||||
assert!(s.doc().unwrap().doc.item(designcraft_doc::ItemId(big)).unwrap().is_text_frame());
|
||||
}
|
||||
|
||||
/// A line is set when its baseline fits in the frame; its descenders may hang below the frame, as
|
||||
/// in InDesign. A 103 pt heading in a 78.5 pt frame (Cap Height first baseline) was overset.
|
||||
#[test]
|
||||
fn a_line_fits_when_its_baseline_does() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
let overset = |s: &mut Session, height: f64| {
|
||||
let r = s.execute("frame.create", &json!({"rect": [36, 36, 400, 36.0 + height], "content": "text", "text": "Gyp"})).unwrap();
|
||||
s.execute("object.textFrameOptions", &json!({"ids": [r["id"]], "firstBaseline": "capHeight", "inset": 0})).unwrap();
|
||||
s.execute("text.select", &json!({"story": r["story"], "anchor": 0, "focus": 3})).unwrap();
|
||||
s.execute("type.char", &json!({"attrs": {"size": 103}})).unwrap();
|
||||
let st = s.execute("story.get", &json!({"story": r["story"]})).unwrap();
|
||||
!st["overset"].is_null()
|
||||
};
|
||||
// Cap height of the default font at 103 pt is about 70 pt: the baseline fits in 78.5 pt, the
|
||||
// descent (about 25 pt more) doesn't.
|
||||
assert!(!overset(&mut s, 78.5), "the line is set; its descenders hang below the frame");
|
||||
assert!(overset(&mut s, 50.0), "a baseline below the frame still oversets the line");
|
||||
}
|
||||
|
||||
@@ -0,0 +1,250 @@
|
||||
//! The guarantee behind `--automation-read-root` and `--automation-write-root`: every file a
|
||||
//! command reads or writes by path goes through a checked reader, in every crate a command can
|
||||
//! reach, not only this one.
|
||||
//!
|
||||
//! In the engine that reader is the [`crate::io`] module. The lower crates cannot depend on the
|
||||
//! engine (`cargo xtask layers`), so they either have no file access at all or take a reader or
|
||||
//! an access check from the caller (`designcraft_idml::import_idml_with`,
|
||||
//! `designcraft_fonts::FontDb::load_document_fonts`).
|
||||
//!
|
||||
//! The scan reads the source of every crate under `crates/` and flags what touches the file
|
||||
//! system, however it is imported or spelled: `std::fs`, a bare `fs::` after `use std::fs` or
|
||||
//! `use std::{fs, ...}`, `File::open`/`File::create`, `OpenOptions`, and the `Path` probes
|
||||
//! (`.metadata(`, `.exists(`, `.canonicalize(`, `.read_dir(`...), as methods or as
|
||||
//! `Path::exists`. The host applications under `apps/` are out of scope: they run with the
|
||||
//! operator's own authority, and the roots are applied inside the process they start.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// Files that may touch the file system, with why. Paths are relative to `crates/`. A file not
|
||||
/// listed here, and not a test file or test module, must not.
|
||||
const ALLOWED: &[(&str, &str)] = &[
|
||||
("engine/src/io.rs", "the checked gateway: every read and write a command makes"),
|
||||
("engine/src/file_access.rs", "the root check itself (resolves links with the file system)"),
|
||||
("engine/src/atomic.rs", "how a write reaches the disk; commands call it only through io::write_file and io::replace_with"),
|
||||
(
|
||||
"engine/src/recovery.rs",
|
||||
"the unsaved documents live in a folder the host application chooses (a command's own `dir` is checked in cmd/file.rs before it gets here)",
|
||||
),
|
||||
(
|
||||
"engine/src/cmd/package.rs",
|
||||
"`OutputRoot` checks the folder against the write root before it creates anything and then only writes inside it. Its reads are of the font files that draw the document's text (installed fonts and the `Document Fonts` folder), never of a path a command names",
|
||||
),
|
||||
(
|
||||
"fonts/src/fontdb.rs",
|
||||
"the installed-font scan reads the platform's fixed font folders (`system_font_dirs`: no command parameter or document field names one), and `load_document_fonts` asks the caller's `allow` check about its folder and each font file before opening either",
|
||||
),
|
||||
(
|
||||
"mcp/src/tools.rs",
|
||||
"`screenshot` reads back the PNG the connected app just wrote. Connected mode cannot be combined with the roots (the CLI refuses the pair), and the app's own engine checks the path it writes",
|
||||
),
|
||||
];
|
||||
|
||||
fn rust_files(dir: &Path, files: &mut Vec<PathBuf>) {
|
||||
let Ok(entries) = std::fs::read_dir(dir) else { return };
|
||||
for entry in entries.flatten() {
|
||||
let path = entry.path();
|
||||
if path.is_dir() {
|
||||
rust_files(&path, files);
|
||||
} else if path.extension().is_some_and(|e| e == "rs") {
|
||||
files.push(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Test files (`tests.rs`, `tests_*.rs`, `*_tests.rs`, anything under a `tests/` folder) build
|
||||
/// their own fixtures on disk.
|
||||
fn is_test_file(rel: &str) -> bool {
|
||||
let name = rel.rsplit('/').next().unwrap_or(rel);
|
||||
name.starts_with("tests") || name.ends_with("_tests.rs") || name == "testing.rs" || rel.split('/').any(|part| part == "tests")
|
||||
}
|
||||
|
||||
/// The file's lines but its test modules: a module is skipped from its `#[cfg(test)]` (or
|
||||
/// `#[cfg(all(test, ...))]`) to the closing brace at the same indent. A `mod x;` declaration
|
||||
/// has no body to skip.
|
||||
fn code_outside_tests(text: &str) -> Vec<(usize, &str)> {
|
||||
let lines: Vec<&str> = text.lines().collect();
|
||||
let mut code = vec![];
|
||||
let mut i = 0;
|
||||
while i < lines.len() {
|
||||
let attr = lines[i].trim();
|
||||
let module = lines.get(i + 1).map(|l| l.trim_start().trim_start_matches("pub "));
|
||||
if attr.starts_with("#[cfg(") && attr.contains("test") && module.is_some_and(|m| m.starts_with("mod ")) {
|
||||
let header = lines[i + 1];
|
||||
i += 2;
|
||||
if header.trim_end().ends_with('{') {
|
||||
let indent = &header[..header.len() - header.trim_start().len()];
|
||||
let close = format!("{indent}}}");
|
||||
while i < lines.len() && lines[i].trim_end() != close {
|
||||
i += 1;
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
code.push((i + 1, lines[i]));
|
||||
i += 1;
|
||||
}
|
||||
code
|
||||
}
|
||||
|
||||
/// `line` without its `//` comment (a `//` inside a string or char is rare enough in this code
|
||||
/// to leave alone: it only hides the rest of that line from the scan).
|
||||
fn without_comment(line: &str) -> &str {
|
||||
line.find("//").map_or(line, |at| &line[..at])
|
||||
}
|
||||
|
||||
fn is_ident(c: char) -> bool {
|
||||
c.is_alphanumeric() || c == '_'
|
||||
}
|
||||
|
||||
/// Does `line` contain `word` not glued to a longer identifier on its left (`std::fs::` and
|
||||
/// ` fs::` match `fs::`; `ofs::` does not)?
|
||||
fn has_word(line: &str, word: &str) -> bool {
|
||||
line.match_indices(word).any(|(at, _)| !line[..at].chars().next_back().is_some_and(is_ident))
|
||||
}
|
||||
|
||||
/// What in `line` reaches the file system, or `None`.
|
||||
fn file_system_use(line: &str) -> Option<String> {
|
||||
let line = without_comment(line);
|
||||
// `std::fs::read`, `fs::read` after `use std::fs;` or `use std::{fs, io};`, `std::os::unix::fs::...`.
|
||||
for word in ["fs::", "File::open", "File::create", "File::options", "OpenOptions", "atomic::write_atomic"] {
|
||||
if has_word(line, word) {
|
||||
return Some(word.into());
|
||||
}
|
||||
}
|
||||
// The probes on a path, as `p.exists()` or `Path::exists`.
|
||||
for method in ["metadata", "symlink_metadata", "canonicalize", "read_dir", "try_exists", "exists", "is_file", "is_dir", "read_link"] {
|
||||
if line.contains(&format!(".{method}(")) || line.contains(&format!("Path::{method}")) {
|
||||
return Some(method.to_string());
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// `use` statements (which can span lines) that bring the file system module in under any name:
|
||||
/// `use std::{fs as files, io};` leaves no `fs::` to find at the call.
|
||||
fn imports_fs(text: &str) -> Vec<usize> {
|
||||
let mut hits = vec![];
|
||||
let mut statement = String::new();
|
||||
let mut start = 0;
|
||||
for (n, line) in code_outside_tests(text) {
|
||||
let line = without_comment(line);
|
||||
if statement.is_empty() {
|
||||
if !line.trim_start().starts_with("use ") && !line.trim_start().starts_with("pub use ") {
|
||||
continue;
|
||||
}
|
||||
start = n;
|
||||
}
|
||||
statement.push_str(line);
|
||||
statement.push(' ');
|
||||
if line.contains(';') {
|
||||
let words: Vec<&str> = statement.split(|c: char| !is_ident(c)).collect();
|
||||
if words.contains(&"fs") && (words.contains(&"std") || words.contains(&"tokio") || words.contains(&"async_std")) {
|
||||
hits.push(start);
|
||||
}
|
||||
statement.clear();
|
||||
}
|
||||
}
|
||||
hits
|
||||
}
|
||||
|
||||
/// Every offending line of the crate sources under `crates_dir`, minus [`ALLOWED`] and test code.
|
||||
fn offenders(crates_dir: &Path) -> (Vec<String>, usize) {
|
||||
let mut files = vec![];
|
||||
rust_files(crates_dir, &mut files);
|
||||
let mut scanned = 0;
|
||||
let mut found = vec![];
|
||||
for path in files {
|
||||
let rel = path.strip_prefix(crates_dir).unwrap_or(&path).to_string_lossy().replace('\\', "/");
|
||||
// `crates/<name>/src/...` only: build scripts, benches and `tests/` are not shipped code.
|
||||
if !rel.split('/').nth(1).is_some_and(|d| d == "src") || is_test_file(&rel) || ALLOWED.iter().any(|(allowed, _)| *allowed == rel) {
|
||||
continue;
|
||||
}
|
||||
let Ok(text) = std::fs::read_to_string(&path) else { continue };
|
||||
scanned += 1;
|
||||
for (n, line) in code_outside_tests(&text) {
|
||||
if let Some(what) = file_system_use(line) {
|
||||
found.push(format!("crates/{rel}:{n}: `{what}`: {}", line.trim()));
|
||||
}
|
||||
}
|
||||
for n in imports_fs(&text) {
|
||||
found.push(format!("crates/{rel}:{n}: imports the file system module"));
|
||||
}
|
||||
}
|
||||
(found, scanned)
|
||||
}
|
||||
|
||||
fn crates_dir() -> PathBuf {
|
||||
Path::new(env!("CARGO_MANIFEST_DIR")).join("..")
|
||||
}
|
||||
|
||||
/// Every command reads and writes files through [`crate::io`], in the engine and in every crate
|
||||
/// below it: none may reach the file system itself, so the automation roots cannot be walked
|
||||
/// around by a path that one of them opens. The exceptions are [`ALLOWED`], each with its reason.
|
||||
#[test]
|
||||
fn no_crate_touches_the_file_system_outside_the_checked_readers() {
|
||||
let (found, scanned) = offenders(&crates_dir());
|
||||
assert!(scanned > 100, "the scan found only {scanned} source files: has the layout moved?");
|
||||
assert!(
|
||||
found.is_empty(),
|
||||
"route these through crate::io (engine) or a reader the caller injects (lower crates), or add the file to ALLOWED with the reason it is safe: {found:#?}"
|
||||
);
|
||||
}
|
||||
|
||||
/// The allow list names files that exist, so a rename cannot leave a stale exception behind (or
|
||||
/// quietly exempt a new file of the same name).
|
||||
#[test]
|
||||
fn every_allowed_file_exists_and_still_needs_its_exception() {
|
||||
for (rel, reason) in ALLOWED {
|
||||
let path = crates_dir().join(rel);
|
||||
let text = std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("{rel}: {e}"));
|
||||
assert!(!reason.is_empty());
|
||||
let touches = code_outside_tests(&text).iter().any(|(_, line)| file_system_use(line).is_some()) || !imports_fs(&text).is_empty();
|
||||
assert!(touches, "{rel} no longer touches the file system: drop it from ALLOWED");
|
||||
}
|
||||
}
|
||||
|
||||
/// The scan must not be foolable by how a call is spelled.
|
||||
#[test]
|
||||
fn the_scan_sees_every_spelling() {
|
||||
let flagged = [
|
||||
"let b = std::fs::read(p)?;",
|
||||
"let b = fs::read(p)?;",
|
||||
" fs::write(p, b)",
|
||||
"let f = File::open(p)?;",
|
||||
"let f = std::fs::File::create(p)?;",
|
||||
"let f = OpenOptions::new().write(true).open(p)?;",
|
||||
"let m = path.metadata()?;",
|
||||
"let m = path.symlink_metadata()?;",
|
||||
"let c = path.canonicalize()?;",
|
||||
"for e in path.read_dir()? {}",
|
||||
"if path.try_exists()? {}",
|
||||
"if p.exists() {}",
|
||||
"if p.is_file() {}",
|
||||
"if p.is_dir() {}",
|
||||
"let l = p.read_link()?;",
|
||||
"files.retain(Path::exists);",
|
||||
"crate::atomic::write_atomic(p, b)?;",
|
||||
"(a, fs::read(x))",
|
||||
];
|
||||
for line in flagged {
|
||||
assert!(file_system_use(line).is_some(), "not flagged: {line}");
|
||||
}
|
||||
let fine = [
|
||||
"let b = crate::io::read_file(p)?;",
|
||||
"if crate::io::is_dir(p) {}",
|
||||
"let m = crate::io::metadata(p)?;",
|
||||
"// std::fs::read(p) is what io wraps",
|
||||
"let n = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);",
|
||||
"let ofs::x = 1;",
|
||||
];
|
||||
for line in fine {
|
||||
assert!(file_system_use(line).is_none(), "wrongly flagged: {line}");
|
||||
}
|
||||
for import in ["use std::fs;", "use std::{fs, io};", "use std::{\n io,\n fs as files,\n};", "use std::fs::File;"] {
|
||||
assert!(!imports_fs(import).is_empty(), "import not flagged: {import}");
|
||||
}
|
||||
assert!(imports_fs("use std::io::Read;\nuse std::path::Path;").is_empty());
|
||||
assert!(imports_fs("#[cfg(test)]\nmod tests {\n use std::fs;\n}\n").is_empty(), "test modules are skipped");
|
||||
}
|
||||
@@ -91,6 +91,92 @@ fn magazine_round_trips_through_idml() {
|
||||
assert_eq!(items(&again.spreads).len(), items(&back.spreads).len());
|
||||
}
|
||||
|
||||
/// A one-page IDML package: two threaded frames side by side, 19 lines each (10 pt on 12 pt),
|
||||
/// paragraphs of `lines` forced-break lines in style `Body`, which carries `body_attrs`.
|
||||
fn keep_lines_idml(body_attrs: &str, lines: &[usize]) -> Vec<u8> {
|
||||
use std::io::Write;
|
||||
let paras: String = lines
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(p, &n)| {
|
||||
let text = (0..n).map(|k| format!("P{p} line {k}")).collect::<Vec<_>>().join("\u{2028}");
|
||||
format!(
|
||||
r#"<ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/Body"><CharacterStyleRange AppliedCharacterStyle="CharacterStyle/$ID/[No character style]"><Content>{text}</Content>{}</CharacterStyleRange></ParagraphStyleRange>"#,
|
||||
if p + 1 < lines.len() { "<Br/>" } else { "" }
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
let frame = |me: &str, x: f64, prev: &str, next: &str| {
|
||||
// 236 pt tall: 19 lines of 12 pt leading, whether or not the last line's descent must fit.
|
||||
let pts: String = [(x, 36.0), (x, 272.0), (x + 180.0, 272.0), (x + 180.0, 36.0)]
|
||||
.iter()
|
||||
.map(|(x, y)| format!(r#"<PathPointType Anchor="{x} {y}" LeftDirection="{x} {y}" RightDirection="{x} {y}"/>"#))
|
||||
.collect();
|
||||
format!(
|
||||
r#"<TextFrame Self="{me}" ParentStory="s1" PreviousTextFrame="{prev}" NextTextFrame="{next}" ItemTransform="1 0 0 1 0 0"><Properties><PathGeometry><GeometryPathType PathOpen="false"><PathPointArray>{pts}</PathPointArray></GeometryPathType></PathGeometry></Properties></TextFrame>"#
|
||||
)
|
||||
};
|
||||
let designmap = format!(
|
||||
r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
||||
<Document xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging" DOMVersion="16.0" Self="d">
|
||||
<DocumentPreference PageWidth="450" PageHeight="312" FacingPages="false"/>
|
||||
<RootCharacterStyleGroup Self="rc"><CharacterStyle Self="CharacterStyle/$ID/[No character style]" Name="$ID/[No character style]"/></RootCharacterStyleGroup>
|
||||
<RootParagraphStyleGroup Self="rp">
|
||||
<ParagraphStyle Self="ParagraphStyle/$ID/[No paragraph style]" Name="$ID/[No paragraph style]" PointSize="12"/>
|
||||
<ParagraphStyle Self="ParagraphStyle/Body" Name="Body" PointSize="10" {body_attrs}><Properties><BasedOn type="object">ParagraphStyle/$ID/[No paragraph style]</BasedOn><Leading type="unit">12</Leading></Properties></ParagraphStyle>
|
||||
</RootParagraphStyleGroup>
|
||||
<Story Self="s1">{paras}</Story>
|
||||
<Spread Self="sp1" ItemTransform="1 0 0 1 0 0"><Page Self="p1" GeometricBounds="0 0 312 450" ItemTransform="1 0 0 1 0 0"/>{}{}</Spread>
|
||||
</Document>"#,
|
||||
frame("t1", 36.0, "n", "t2"),
|
||||
frame("t2", 234.0, "t1", "n")
|
||||
);
|
||||
let mut w = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
let stored = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored);
|
||||
w.start_file("mimetype", stored).unwrap();
|
||||
w.write_all(b"application/vnd.adobe.indesign-idml-package").unwrap();
|
||||
w.start_file("designmap.xml", zip::write::SimpleFileOptions::default()).unwrap();
|
||||
w.write_all(designmap.as_bytes()).unwrap();
|
||||
w.finish().unwrap().into_inner()
|
||||
}
|
||||
|
||||
/// Lines of paragraph `para` in each frame of the story.
|
||||
fn para_lines_per_frame(d: &Document, para: usize) -> Vec<usize> {
|
||||
let sid = *d.stories.keys().next().unwrap();
|
||||
let cs = designcraft_compose::compose_story(d, sid, &Default::default());
|
||||
cs.frames.iter().map(|f| f.lines.iter().filter(|l| l.para == para).count()).collect()
|
||||
}
|
||||
|
||||
/// Keep Lines Together without a mode in the IDML: InDesign's default, at start/end of paragraph.
|
||||
/// A 10-line paragraph starting 6 lines above the first frame's bottom splits 6/4.
|
||||
#[test]
|
||||
fn idml_keep_lines_without_mode_split_at_start_and_end() {
|
||||
let keep = r#"KeepLinesTogether="true" KeepFirstLines="2" KeepLastLines="2""#;
|
||||
let d = designcraft_idml::import_idml(&keep_lines_idml(keep, &[13, 10, 2])).unwrap();
|
||||
assert_eq!(para_lines_per_frame(&d, 0), [13, 0]);
|
||||
assert_eq!(para_lines_per_frame(&d, 1), [6, 4]);
|
||||
// All lines in paragraph, written explicitly: the paragraph moves whole.
|
||||
let d = designcraft_idml::import_idml(&keep_lines_idml(&format!(r#"{keep} KeepAllLinesTogether="true""#), &[13, 10, 2])).unwrap();
|
||||
assert_eq!(para_lines_per_frame(&d, 1), [0, 10]);
|
||||
}
|
||||
|
||||
/// A document saved in format 1 with Keep Lines Together and no mode still keeps all lines
|
||||
/// together after loading; saved now, it keeps lines at start/end of paragraph.
|
||||
#[test]
|
||||
fn format_1_keep_lines_without_mode_lays_out_all_lines() {
|
||||
use std::io::Write;
|
||||
let d = designcraft_idml::import_idml(&keep_lines_idml(r#"KeepLinesTogether="true""#, &[13, 10, 2])).unwrap();
|
||||
let mut w = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
w.start_file("meta.json", zip::write::SimpleFileOptions::default()).unwrap();
|
||||
w.write_all(br#"{"format": "designcraft", "version": 1}"#).unwrap();
|
||||
w.start_file("document.json", zip::write::SimpleFileOptions::default()).unwrap();
|
||||
w.write_all(&serde_json::to_vec(&d).unwrap()).unwrap();
|
||||
let v1 = designcraft_format::load(&w.finish().unwrap().into_inner()).unwrap();
|
||||
assert_eq!(para_lines_per_frame(&v1, 1), [0, 10]);
|
||||
let now = designcraft_format::load(&designcraft_format::save(&d).unwrap()).unwrap();
|
||||
assert_eq!(para_lines_per_frame(&now, 1), [6, 4]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn idml_commands() {
|
||||
let mut s = Session::new();
|
||||
@@ -251,3 +337,60 @@ fn named_lists_round_trip_through_idml() {
|
||||
assert_eq!(st.paras[0].para.list_name.as_deref(), Some("Steps"));
|
||||
assert_eq!(st.paras[0].para.start_at, Some(Some(5)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn type_para_sets_a_drop_cap_that_survives_idml() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
s.execute("style.character.create", &json!({"name": "Initial", "chars": {"fontStyle": "Bold"}})).unwrap();
|
||||
let text = "Once upon a time there was a paragraph long enough to run beside its drop cap for a few lines and then some more.";
|
||||
let r = s.execute("frame.create", &json!({"rect": [72, 72, 300, 400], "content": "text", "text": text})).unwrap();
|
||||
let sid = r["story"].as_u64().unwrap();
|
||||
s.execute("text.select", &json!({"story": sid, "anchor": 3, "focus": 3})).unwrap();
|
||||
s.execute("type.para", &json!({"attrs": {"dropCapLines": 3, "dropCapChars": 1, "dropCapStyle": "Initial", "dropCapAlignLeft": false}})).unwrap();
|
||||
let d = s.doc().unwrap().doc.clone();
|
||||
let cs = designcraft_compose::compose_story(&d, designcraft_doc::StoryId(sid), &Default::default());
|
||||
let lines = &cs.frames[0].lines;
|
||||
let dc = &lines[0].glyphs[0];
|
||||
assert_eq!(dc.byte, 0);
|
||||
assert!((lines[0].baseline + dc.y - lines[2].baseline).abs() < 1e-6, "on line 3's baseline");
|
||||
assert!(lines[0].drop_cap.is_some_and(|b| b.end == 1));
|
||||
let p = &d.story(designcraft_doc::StoryId(sid)).unwrap().paras[0].para;
|
||||
assert_eq!((p.drop_cap_lines, p.drop_cap_chars, p.drop_cap_style.as_deref()), (Some(3), Some(1), Some("Initial")));
|
||||
let back = designcraft_idml::import_idml(&designcraft_idml::export_idml(&d)).unwrap();
|
||||
let p = &back.stories.values().find(|st| st.text.starts_with("Once")).unwrap().paras[0].para;
|
||||
assert_eq!((p.drop_cap_lines, p.drop_cap_chars, p.drop_cap_align_left), (Some(3), Some(1), Some(false)));
|
||||
// The drop cap's character style goes through IDML as a leading Dropcap nested style.
|
||||
assert_eq!(p.drop_cap_style.as_deref(), Some("Initial"));
|
||||
assert_eq!(p.nested_styles, Some(vec![designcraft_doc::NestedStyle::drop_cap("Initial")]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn table_of_contents_definition_round_trips_through_idml_and_updates() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.newSample", &json!({})).unwrap();
|
||||
let page = s.doc().unwrap().doc.page_count() + 1;
|
||||
s.execute("layout.pages.insert", &json!({"count": 1})).unwrap();
|
||||
let basic = designcraft_doc::story::BASIC_PARAGRAPH;
|
||||
s.execute(
|
||||
"toc.generate",
|
||||
&json!({"page": page, "title": "Inside", "titleStyle": basic, "entries": [
|
||||
{"style": "Cover Title", "level": 1, "pageNumber": "before", "separator": " ^ "},
|
||||
{"style": "Headline", "level": 2, "entryStyle": basic, "pageNumber": "none"},
|
||||
]}),
|
||||
)
|
||||
.unwrap();
|
||||
let toc_text = |s: &Session| {
|
||||
let d = &s.doc().unwrap().doc;
|
||||
d.story(d.toc.as_ref().unwrap().story).unwrap().text.clone()
|
||||
};
|
||||
let before = s.doc().unwrap().doc.toc.clone().unwrap();
|
||||
let text = toc_text(&s);
|
||||
let b64 = s.execute("file.exportIdml", &json!({})).unwrap()["base64"].as_str().unwrap().to_string();
|
||||
s.execute("file.openIdml", &json!({"base64": b64, "name": "toc.idml"})).unwrap();
|
||||
let after = s.doc().unwrap().doc.toc.clone().expect("the TOC definition is imported");
|
||||
assert_eq!((&after.title, &after.title_style, &after.entries), (&before.title, &before.title_style, &before.entries));
|
||||
assert_eq!(toc_text(&s), text);
|
||||
s.execute("toc.update", &json!({})).unwrap();
|
||||
assert_eq!(toc_text(&s), text);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,233 @@
|
||||
//! The automation roots at the engine: the files a document names (links, data sources, book
|
||||
//! chapters, packaged fonts) are read and written through the same checks as the paths a command
|
||||
//! is given.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::file_access::{AutomationRoots, confine};
|
||||
use crate::{Session, cmd};
|
||||
|
||||
const PNG: &[u8] = &[
|
||||
0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01,
|
||||
0x08, 0x06, 0x00, 0x00, 0x00, 0x1f, 0x15, 0xc4, 0x89, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x44, 0x41, 0x54, 0x78, 0x9c, 0x63, 0xf8, 0xcf, 0xc0, 0xf0,
|
||||
0x1f, 0x00, 0x05, 0x00, 0x01, 0xff, 0x89, 0x99, 0x3d, 0x1d, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82,
|
||||
];
|
||||
|
||||
/// A fresh folder with `in` (the read root), `out` (the write root) and `outside`, and the roots.
|
||||
fn folders(name: &str) -> (PathBuf, Arc<AutomationRoots>) {
|
||||
let base = std::env::temp_dir().join(format!("dc-engine-roots-{name}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
for d in ["in", "out", "outside"] {
|
||||
std::fs::create_dir_all(base.join(d)).unwrap();
|
||||
}
|
||||
let roots = AutomationRoots::new(Some(&base.join("in")), Some(&base.join("out"))).unwrap().unwrap();
|
||||
(base, roots)
|
||||
}
|
||||
|
||||
fn p(path: &Path) -> String {
|
||||
path.to_string_lossy().into_owned()
|
||||
}
|
||||
|
||||
/// A document with `pic.png` placed from `dir`, so the asset is embedded and linked to the file.
|
||||
fn linked_picture(dir: &Path) -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
s.execute("file.place", &json!({"path": p(&dir.join("pic.png")), "x": 36, "y": 36, "width": 72})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn link_status(s: &mut Session) -> Value {
|
||||
s.execute("links.list", &json!({})).unwrap()[0]["status"].clone()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_link_outside_the_read_root_reads_as_missing() {
|
||||
let (base, roots) = folders("links");
|
||||
std::fs::write(base.join("outside/pic.png"), PNG).unwrap();
|
||||
std::fs::write(base.join("in/pic.png"), PNG).unwrap();
|
||||
let mut outside = linked_picture(&base.join("outside"));
|
||||
let mut inside = linked_picture(&base.join("in"));
|
||||
assert_eq!(link_status(&mut outside), "ok");
|
||||
confine(Some(&roots), || {
|
||||
assert_eq!(link_status(&mut outside), "missing", "the file is not the agent's to look at, not even to compare");
|
||||
assert_eq!(link_status(&mut inside), "ok");
|
||||
assert!(outside.execute("links.relinkFolder", &json!({"dir": p(&base.join("outside"))})).is_err());
|
||||
// A relink to a link that leads out is refused too, and the asset keeps what it had.
|
||||
let asset = outside.execute("links.list", &json!({})).unwrap()[0]["asset"].clone();
|
||||
let e = outside.execute("links.relink", &json!({"asset": asset, "path": p(&base.join("outside/pic.png"))})).unwrap_err().to_string();
|
||||
assert!(e.contains("outside the read root"), "{e}");
|
||||
});
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn idml_links_are_read_through_the_roots() {
|
||||
let (base, roots) = folders("idml");
|
||||
std::fs::write(base.join("outside/pic.png"), PNG).unwrap();
|
||||
let mut s = linked_picture(&base.join("outside"));
|
||||
// Linked, not embedded: opening the package has to read the file its link names.
|
||||
let idml = base64_idml(&mut s);
|
||||
let linked = |doc: &designcraft_doc::Document| doc.assets.values().filter(|a| !a.data.is_empty()).count();
|
||||
let unconfined = cmd::interchange::import_idml_confined(&idml).unwrap();
|
||||
assert_eq!(linked(&unconfined), 1, "without roots the link is followed");
|
||||
let confined = confine(Some(&roots), || cmd::interchange::import_idml_confined(&idml)).unwrap();
|
||||
assert_eq!(linked(&confined), 0, "with roots a link outside the read root is not read");
|
||||
// The same through the commands that open or place a package.
|
||||
let b64 = cmd::base64_encode(&idml);
|
||||
let mut t = Session::new();
|
||||
t.execute("file.new", &json!({})).unwrap();
|
||||
confine(Some(&roots), || {
|
||||
t.execute("file.openBytes", &json!({"name": "x.idml", "base64": b64})).unwrap();
|
||||
let doc = &t.doc().unwrap().doc;
|
||||
assert_eq!(linked(doc), 0);
|
||||
t.execute("file.place", &json!({"base64": b64, "name": "x.idml", "layoutPage": 1, "x": 0, "y": 0})).unwrap();
|
||||
assert_eq!(linked(&t.doc().unwrap().doc), 0);
|
||||
});
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
fn base64_idml(s: &mut Session) -> Vec<u8> {
|
||||
let r = s.execute("file.exportIdml", &json!({"embedImages": false})).unwrap();
|
||||
cmd::base64_decode(r["base64"].as_str().unwrap())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_merge_does_not_read_image_files_outside_the_read_root() {
|
||||
let (base, roots) = folders("merge");
|
||||
std::fs::write(base.join("outside/pic.png"), PNG).unwrap();
|
||||
std::fs::write(base.join("in/data.csv"), format!("@Photo\n{}\n", base.join("outside/pic.png").display())).unwrap();
|
||||
let merge = |s: &mut Session| {
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
s.execute("data.source.select", &json!({"path": p(&base.join("in/data.csv"))})).unwrap();
|
||||
let frame = s.execute("frame.create", &json!({"rect": [36.0, 36.0, 80.0, 80.0], "content": "graphic"})).unwrap();
|
||||
s.execute("data.placeholder.add", &json!({"field": "Photo", "item": frame["id"]})).unwrap();
|
||||
s.execute("data.merge", &json!({})).unwrap()["missingImages"].as_array().unwrap().len()
|
||||
};
|
||||
assert_eq!(merge(&mut Session::new()), 0, "without roots the picture is found");
|
||||
assert_eq!(confine(Some(&roots), || merge(&mut Session::new())), 1, "with roots it reads as missing");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_data_source_path_stored_in_a_document_is_read_through_the_roots() {
|
||||
let (base, roots) = folders("source");
|
||||
std::fs::write(base.join("outside/data.csv"), "name\nTOP SECRET\n").unwrap();
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
s.execute("data.source.select", &json!({"path": p(&base.join("outside/data.csv"))})).unwrap();
|
||||
confine(Some(&roots), || {
|
||||
let e = s.execute("data.source.update", &json!({})).unwrap_err().to_string();
|
||||
assert!(e.contains("outside the read root") && !e.contains("TOP SECRET"), "{e}");
|
||||
});
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_book_writes_its_chapters_only_inside_the_write_root() {
|
||||
let (base, roots) = folders("book");
|
||||
let chapter = base.join("in/a.designcraft");
|
||||
let second = base.join("in/b.designcraft");
|
||||
{
|
||||
// Made by another session: a book only rewrites chapters that are not open.
|
||||
let mut maker = Session::new();
|
||||
maker.execute("file.new", &json!({})).unwrap();
|
||||
maker.execute("file.save", &json!({"path": p(&chapter)})).unwrap();
|
||||
maker.execute("file.saveAs", &json!({"path": p(&second)})).unwrap();
|
||||
}
|
||||
let mut s = Session::new();
|
||||
let before = (std::fs::read(&chapter).unwrap(), std::fs::read(&second).unwrap());
|
||||
confine(Some(&roots), || {
|
||||
s.execute("book.new", &json!({"path": p(&base.join("out/b.dcbook"))})).unwrap();
|
||||
s.execute("book.add", &json!({"path": p(&chapter)})).unwrap();
|
||||
s.execute("book.add", &json!({"path": p(&second)})).unwrap();
|
||||
for command in ["book.paginate", "book.syncStyles", "book.exportPdf"] {
|
||||
let r = s.execute(command, &json!({"path": p(&base.join("outside/book.pdf"))}));
|
||||
let e = r.unwrap_err().to_string();
|
||||
assert!(e.contains("outside the write root"), "{command}: {e}");
|
||||
}
|
||||
let e = s.execute("book.new", &json!({"path": p(&base.join("outside/b.dcbook"))})).unwrap_err().to_string();
|
||||
assert!(e.contains("outside the write root"), "{e}");
|
||||
});
|
||||
assert_eq!((std::fs::read(&chapter).unwrap(), std::fs::read(&second).unwrap()), before, "no chapter was rewritten");
|
||||
assert!(!base.join("outside/b.dcbook").exists());
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn package_and_copy_links_create_nothing_outside_the_write_root() {
|
||||
let (base, roots) = folders("package");
|
||||
std::fs::write(base.join("in/pic.png"), PNG).unwrap();
|
||||
let mut s = linked_picture(&base.join("in"));
|
||||
confine(Some(&roots), || {
|
||||
for command in ["file.package", "links.copyTo"] {
|
||||
let e = s.execute(command, &json!({"dir": p(&base.join("outside/pkg"))})).unwrap_err().to_string();
|
||||
assert!(e.contains("outside the write root"), "{command}: {e}");
|
||||
// The read root is not writable either.
|
||||
let e = s.execute(command, &json!({"dir": p(&base.join("in/pkg"))})).unwrap_err().to_string();
|
||||
assert!(e.contains("outside the write root"), "{command}: {e}");
|
||||
}
|
||||
s.execute("file.package", &json!({"dir": p(&base.join("out/pkg"))})).unwrap();
|
||||
s.execute("links.copyTo", &json!({"dir": p(&base.join("out/copies"))})).unwrap();
|
||||
});
|
||||
assert!(!base.join("outside/pkg").exists() && !base.join("in/pkg").exists());
|
||||
assert!(base.join("out/pkg/Instructions.txt").exists() && base.join("out/copies/pic.png").exists());
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recovery_folders_named_by_a_command_are_checked() {
|
||||
let (base, roots) = folders("recovery");
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
s.execute("frame.create", &json!({"rect": [10, 10, 100, 100]})).unwrap();
|
||||
confine(Some(&roots), || {
|
||||
let out = p(&base.join("outside"));
|
||||
let inside = p(&base.join("in"));
|
||||
let to_write = p(&base.join("out"));
|
||||
let e = s.execute("file.recovery.save", &json!({"dir": out})).unwrap_err().to_string();
|
||||
assert!(e.contains("outside the write root"), "{e}");
|
||||
let e = s.execute("file.recovery.save", &json!({"dir": inside})).unwrap_err().to_string();
|
||||
assert!(e.contains("outside the write root"), "{e}");
|
||||
assert!(s.execute("file.recovery.list", &json!({"dir": out})).unwrap_err().to_string().contains("outside the read root"));
|
||||
// Reopening removes what it read, so it needs both.
|
||||
assert!(s.execute("file.recovery.open", &json!({"dir": inside})).unwrap_err().to_string().contains("outside the write root"));
|
||||
assert!(s.execute("file.recovery.open", &json!({"dir": to_write})).unwrap_err().to_string().contains("outside the read root"));
|
||||
assert_eq!(s.execute("file.recovery.save", &json!({"dir": to_write})).unwrap()["saved"], 1);
|
||||
});
|
||||
assert!(std::fs::read_dir(base.join("outside")).unwrap().next().is_none());
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fonts_beside_a_document_outside_the_read_root_are_not_loaded() {
|
||||
let (base, roots) = folders("fonts");
|
||||
std::fs::create_dir_all(base.join("outside/Document Fonts")).unwrap();
|
||||
std::fs::write(base.join("outside/Document Fonts/x.ttf"), b"not a font").unwrap();
|
||||
let mut d = designcraft_doc::Document::new(&designcraft_doc::build::NewDocument::default());
|
||||
let (_, faces, warnings) = confine(Some(&roots), || cmd::load_document_fonts(&mut d, &p(&base.join("outside/doc.designcraft"))));
|
||||
assert_eq!(faces, 0);
|
||||
assert!(warnings.iter().any(|w| w.contains("outside the read root")), "{warnings:?}");
|
||||
let (_, _, warnings) = cmd::load_document_fonts(&mut d, &p(&base.join("outside/doc.designcraft")));
|
||||
assert!(warnings.iter().any(|w| w.contains("x.ttf")), "without roots the folder is read and the bad font reported: {warnings:?}");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_font_file_that_links_out_of_the_read_root_is_skipped() {
|
||||
let (base, roots) = folders("fontlink");
|
||||
std::fs::create_dir_all(base.join("in/Document Fonts")).unwrap();
|
||||
std::fs::write(base.join("outside/secret.ttf"), b"not a font").unwrap();
|
||||
std::os::unix::fs::symlink(base.join("outside/secret.ttf"), base.join("in/Document Fonts/link.ttf")).unwrap();
|
||||
let mut d = designcraft_doc::Document::new(&designcraft_doc::build::NewDocument::default());
|
||||
let doc = p(&base.join("in/doc.designcraft"));
|
||||
let (_, _, warnings) = confine(Some(&roots), || cmd::load_document_fonts(&mut d, &doc));
|
||||
assert!(warnings.iter().any(|w| w.contains("outside the read root")), "{warnings:?}");
|
||||
assert!(!warnings.iter().any(|w| w.contains("not a font")), "the file was opened: {warnings:?}");
|
||||
let (_, _, warnings) = cmd::load_document_fonts(&mut d, &doc);
|
||||
assert!(warnings.iter().any(|w| w.contains("link.ttf")), "without roots the link is followed: {warnings:?}");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
@@ -16,6 +16,321 @@ fn check(s: &Session) {
|
||||
s.doc().unwrap().doc.check().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn table_text_replacement_floors_utf8_selection_and_allows_quote_typing() {
|
||||
for (original, (a, b), replacement, (after_a, after_b), quoted) in [
|
||||
("a", (1, 1), "é", (0, 0), Some("“é")), // Exact caret/quote baseline.
|
||||
("abc", (3, 3), "🙂", (0, 0), Some("“🙂")),
|
||||
("ab", (1, 2), "éX", (0, 2), None),
|
||||
("ab", (2, 1), "éX", (2, 0), None),
|
||||
("abcdef", (3, 5), "🙂éX", (0, 4), None),
|
||||
("abcdef", (5, 3), "🙂éX", (4, 0), None),
|
||||
("abc", (1, 2), "🙂", (0, 0), None), // Both endpoints floor to the same boundary.
|
||||
("abcdef", (2, 6), "é🙂", (2, 6), None), // Valid Unicode endpoints stay fixed.
|
||||
("abcdef", (1, 4), "ABCDEF", (1, 4), None),
|
||||
("abcdef", (4, 1), "ABCDEF", (4, 1), None),
|
||||
("abcdef", (6, 6), "é", (2, 2), None), // Shortening clamps to EOF.
|
||||
("abc", (1, 3), "", (0, 0), None),
|
||||
] {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
let frame = s.execute("frame.create", &json!({"rect": [36, 36, 300, 200], "content": "text", "text": ""})).unwrap();
|
||||
let sid = frame["story"].as_u64().unwrap();
|
||||
let fid = frame["id"].as_u64().unwrap();
|
||||
let tid = s.execute("table.insert", &json!({"rows": 1, "cols": 1})).unwrap()["table"].as_u64().unwrap();
|
||||
s.execute("text.insert", &json!({"text": original, "raw": true})).unwrap();
|
||||
// Real commands position the child selection; text.select addresses parent stories.
|
||||
for _ in a..original.len() {
|
||||
s.execute("text.move", &json!({"dir": "left"})).unwrap();
|
||||
}
|
||||
let (dir, steps) = if b >= a { ("right", b - a) } else { ("left", a - b) };
|
||||
for _ in 0..steps {
|
||||
s.execute("text.move", &json!({"dir": dir, "extend": true})).unwrap();
|
||||
}
|
||||
let mut expected = s.doc().unwrap().selection.clone();
|
||||
let selected = expected.text.as_mut().unwrap();
|
||||
assert_eq!((selected.anchor, selected.focus), (a, b));
|
||||
assert_eq!(selected.frame, Some(doc::ItemId(fid)));
|
||||
assert_eq!(selected.cell, Some(doc::CellAddr { table: tid, row: 0, col: 0 }));
|
||||
(selected.anchor, selected.focus) = (after_a, after_b);
|
||||
let parent = s.doc().unwrap().doc.story(doc::StoryId(sid)).unwrap().text.clone();
|
||||
s.execute("table.setCell", &json!({"text": replacement})).unwrap();
|
||||
assert_eq!(table_for(&s, sid, tid).cell(0, 0).unwrap().text.text, replacement);
|
||||
assert_eq!(s.doc().unwrap().selection, expected, "{original}: {a}->{b}, replacement {replacement}");
|
||||
assert!(replacement.is_char_boundary(after_a) && replacement.is_char_boundary(after_b));
|
||||
assert_eq!(s.doc().unwrap().doc.story(doc::StoryId(sid)).unwrap().text, parent);
|
||||
if let Some(quoted) = quoted {
|
||||
assert!(s.prefs.typographers_quotes);
|
||||
s.execute("text.insert", &json!({"text": "\""})).unwrap();
|
||||
assert_eq!(table_for(&s, sid, tid).cell(0, 0).unwrap().text.text, quoted);
|
||||
let selected = expected.text.as_mut().unwrap();
|
||||
(selected.anchor, selected.focus) = (3, 3); // Opening curly quote is three bytes.
|
||||
assert_eq!(s.doc().unwrap().selection, expected);
|
||||
}
|
||||
check(&s);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn table_edit_after_anchor_removal_floors_parent_caret() {
|
||||
for (original, (a, b), replacement, pos, quoted, typed_pos) in [("ab", (1, 2), "é", 0, "“é\n", 3), ("abcde", (5, 1), "é🙂", 2, "é”🙂\n", 5)]
|
||||
{
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
let other = s.execute("frame.create", &json!({"rect": [320, 36, 580, 200], "content": "text"})).unwrap();
|
||||
let other_sid = other["story"].as_u64().unwrap();
|
||||
let other_tid = s.execute("table.insert", &json!({"rows": 1, "cols": 1})).unwrap()["table"].as_u64().unwrap();
|
||||
s.execute("text.insert", &json!({"text": "keep", "raw": true})).unwrap();
|
||||
let mut expected_other = table_for(&s, other_sid, other_tid).clone();
|
||||
expected_other.cell_mut(0, 0).unwrap().insets = [7.0; 4];
|
||||
|
||||
let frame = s.execute("frame.create", &json!({"rect": [36, 36, 300, 200], "content": "text"})).unwrap();
|
||||
let sid = frame["story"].as_u64().unwrap();
|
||||
let tid = s.execute("table.insert", &json!({"rows": 1, "cols": 1})).unwrap()["table"].as_u64().unwrap();
|
||||
s.execute("text.insert", &json!({"text": original, "raw": true})).unwrap();
|
||||
for _ in a..original.len() {
|
||||
s.execute("text.move", &json!({"dir": "left"})).unwrap();
|
||||
}
|
||||
let (dir, steps) = if b >= a { ("right", b - a) } else { ("left", a - b) };
|
||||
for _ in 0..steps {
|
||||
s.execute("text.move", &json!({"dir": dir, "extend": true})).unwrap();
|
||||
}
|
||||
let mut expected = s.doc().unwrap().selection.clone();
|
||||
let selected = expected.text.unwrap();
|
||||
assert_eq!((selected.anchor, selected.focus), (a, b));
|
||||
assert_eq!(selected.frame, Some(doc::ItemId(frame["id"].as_u64().unwrap())));
|
||||
assert_eq!(selected.cell, Some(doc::CellAddr { table: tid, row: 0, col: 0 }));
|
||||
// Explicit parent replacement removes its anchor, leaving the child address stale.
|
||||
assert_eq!(
|
||||
s.execute("find.change", &json!({"story": sid, "find": doc::TABLE_ANCHOR.to_string(), "change": replacement})).unwrap()["count"],
|
||||
1
|
||||
);
|
||||
let parent = s.doc().unwrap().doc.story(doc::StoryId(sid)).unwrap();
|
||||
assert_eq!(parent.text, format!("{replacement}\n"));
|
||||
assert!(!parent.tables.contains_key(&tid));
|
||||
assert_eq!(s.doc().unwrap().selection, expected);
|
||||
assert!(!parent.text.is_char_boundary(selected.anchor));
|
||||
// An explicit edit to the surviving table reaches the disappeared-table fallback.
|
||||
s.execute("table.setCell", &json!({"story": other_sid, "table": other_tid, "insets": 7})).unwrap();
|
||||
let selected = expected.text.as_mut().unwrap();
|
||||
(selected.anchor, selected.focus, selected.cell) = (pos, pos, None); // Both floor the OLD anchor.
|
||||
assert_eq!(s.doc().unwrap().selection, expected);
|
||||
assert_eq!(s.doc().unwrap().doc.story(doc::StoryId(sid)).unwrap().text, format!("{replacement}\n"));
|
||||
assert_eq!(table_for(&s, other_sid, other_tid), &expected_other);
|
||||
s.execute("text.insert", &json!({"text": "\""})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.story(doc::StoryId(sid)).unwrap().text, quoted);
|
||||
let selected = expected.text.as_mut().unwrap();
|
||||
(selected.anchor, selected.focus) = (typed_pos, typed_pos);
|
||||
assert_eq!(s.doc().unwrap().selection, expected);
|
||||
assert_eq!(table_for(&s, other_sid, other_tid), &expected_other);
|
||||
check(&s);
|
||||
}
|
||||
}
|
||||
|
||||
fn selected_merged_table(column: bool) -> (Session, u64, u64, u64) {
|
||||
let (mut s, sid, fid) = session_with_frame();
|
||||
let tid = s.execute("table.insert", &json!({"rows": 2, "cols": 2})).unwrap()["table"].as_u64().unwrap();
|
||||
for (i, text) in ["A", "B", "C", "D"].iter().enumerate() {
|
||||
s.execute("text.insert", &json!({"text": text})).unwrap();
|
||||
if i < 3 {
|
||||
s.execute("table.nextCell", &json!({})).unwrap();
|
||||
}
|
||||
}
|
||||
let merge = if column { json!({"rows": [0, 0], "cols": [0, 1]}) } else { json!({"rows": [0, 1], "cols": [0, 0]}) };
|
||||
s.execute("table.select", &merge).unwrap();
|
||||
s.execute("table.merge", &json!({})).unwrap();
|
||||
s.execute("table.select", &json!({"rows": [1, 1], "cols": [1, 1]})).unwrap();
|
||||
s.execute(if column { "table.selectColumn" } else { "table.selectRow" }, &json!({})).unwrap();
|
||||
(s, sid, tid, fid)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selected_merged_owners_receive_text_formatting_and_character_styles() {
|
||||
for column in [true, false] {
|
||||
let (mut s, sid, tid, _) = selected_merged_table(column);
|
||||
let selected = s.doc().unwrap().selection.clone();
|
||||
assert_eq!(selected.cells.unwrap().range, if column { doc::CellRange::new(0, 1, 1, 1) } else { doc::CellRange::new(1, 0, 1, 1) });
|
||||
let before = table_for(&s, sid, tid).clone();
|
||||
let neighbor = if column { (1, 0) } else { (0, 1) };
|
||||
s.execute("type.char", &json!({"attrs": {"size": 23}})).unwrap();
|
||||
for (r, c) in [(0, 0), (1, 1)] {
|
||||
let cell = table_for(&s, sid, tid).cell(r, c).unwrap();
|
||||
assert!(cell.text.runs().all(|(_, f)| f.over.size == Some(23.0)), "all runs of owner {r},{c}");
|
||||
assert_eq!(cell.text.text, before.cell(r, c).unwrap().text.text);
|
||||
}
|
||||
assert_eq!(table_for(&s, sid, tid).cell(neighbor.0, neighbor.1), before.cell(neighbor.0, neighbor.1));
|
||||
assert_eq!(s.doc().unwrap().selection, selected);
|
||||
s.execute("style.character.create", &json!({"name": "Selected owners", "chars": {"tracking": 37}})).unwrap();
|
||||
s.execute("style.character.apply", &json!({"name": "Selected owners"})).unwrap();
|
||||
for (r, c) in [(0, 0), (1, 1)] {
|
||||
assert!(table_for(&s, sid, tid).cell(r, c).unwrap().text.runs().all(|(_, f)| f.style == "Selected owners"));
|
||||
}
|
||||
let after = table_for(&s, sid, tid);
|
||||
assert_eq!(after.cell(neighbor.0, neighbor.1), before.cell(neighbor.0, neighbor.1));
|
||||
assert_eq!(after.rows, before.rows);
|
||||
assert_eq!(after.columns, before.columns);
|
||||
assert_eq!(s.doc().unwrap().selection, selected, "formatting preserves the original grid rectangle");
|
||||
check(&s);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selected_merged_owners_receive_cell_options_and_unique_style_counts() {
|
||||
for column in [true, false] {
|
||||
let (mut s, sid, tid, _) = selected_merged_table(column);
|
||||
let range = s.doc().unwrap().selection.cells.unwrap().range;
|
||||
let before = table_for(&s, sid, tid).clone();
|
||||
let neighbor = if column { (1, 0) } else { (0, 1) };
|
||||
let covered = if column { (0, 1) } else { (1, 0) };
|
||||
s.execute("table.setCell", &json!({"fill": "[Black]", "insets": 7, "text": "REPLACED"})).unwrap();
|
||||
for (r, c) in [(0, 0), (1, 1)] {
|
||||
let cell = table_for(&s, sid, tid).cell(r, c).unwrap();
|
||||
assert_eq!(serde_json::to_value(&cell.fill).unwrap(), json!("[Black]"));
|
||||
assert_eq!(cell.insets, [7.0; 4]);
|
||||
assert_eq!(cell.text.text, "REPLACED");
|
||||
}
|
||||
s.execute("style.cell.create", &json!({"name": "Selected cell owners", "insets": 9})).unwrap();
|
||||
assert_eq!(s.execute("style.cell.apply", &json!({"name": "Selected cell owners"})).unwrap()["cells"], 2);
|
||||
let after = table_for(&s, sid, tid);
|
||||
for (r, c) in [(0, 0), (1, 1)] {
|
||||
assert_eq!(after.cell(r, c).unwrap().style, "Selected cell owners");
|
||||
assert_eq!(after.cell(r, c).unwrap().insets, [9.0; 4]);
|
||||
}
|
||||
assert_eq!(after.cell(neighbor.0, neighbor.1), before.cell(neighbor.0, neighbor.1));
|
||||
assert_eq!(after.cell(covered.0, covered.1), before.cell(covered.0, covered.1));
|
||||
assert_eq!(after.rows, before.rows);
|
||||
assert_eq!(after.columns, before.columns);
|
||||
assert_eq!(s.doc().unwrap().selection.cells.unwrap().range, range);
|
||||
let merged = if column { json!({"rows": [0, 0], "cols": [0, 1]}) } else { json!({"rows": [0, 1], "cols": [0, 0]}) };
|
||||
s.execute("table.select", &merged).unwrap();
|
||||
assert_eq!(s.execute("style.cell.apply", &json!({"name": "Selected cell owners"})).unwrap()["cells"], 1);
|
||||
check(&s);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn covered_owner_strokes_keep_literal_edge_masks_and_neighbors() {
|
||||
for rtl in [false, true] {
|
||||
for outer in [false, true] {
|
||||
let (mut s, sid, tid, _) = selected_merged_table(true);
|
||||
if rtl {
|
||||
s.execute("table.options", &json!({"direction": "rightToLeft"})).unwrap();
|
||||
}
|
||||
s.execute("table.select", &json!({"rows": [0, 0], "cols": [1, 1]})).unwrap();
|
||||
let before = table_for(&s, sid, tid).clone();
|
||||
s.execute("table.setCell", &json!({"stroke": {"weight": 3, "edges": if outer { "outer" } else { "inner" }}})).unwrap();
|
||||
let after = table_for(&s, sid, tid);
|
||||
let mask = if rtl { [true, true, true, false] } else { [true, false, true, true] };
|
||||
let expected = mask.map(|edge| if outer { edge } else { !edge });
|
||||
let owner = after.cell(0, 0).unwrap();
|
||||
assert_eq!(owner.border_overrides, expected);
|
||||
assert_eq!(owner.stroke_defined, expected);
|
||||
for (i, on) in expected.into_iter().enumerate() {
|
||||
if on {
|
||||
assert_eq!(owner.strokes[i].weight, 3.0);
|
||||
assert_eq!(owner.stroke_priorities[i], 1);
|
||||
} else {
|
||||
assert_eq!(owner.strokes[i], before.cell(0, 0).unwrap().strokes[i]);
|
||||
}
|
||||
}
|
||||
for (r, c) in [(0, 1), (1, 0), (1, 1)] {
|
||||
assert_eq!(after.cell(r, c), before.cell(r, c), "strict merged/covered mirror guard preserves {r},{c}");
|
||||
}
|
||||
assert_eq!(s.doc().unwrap().selection.cells.unwrap().range, doc::CellRange::cell(0, 1));
|
||||
check(&s);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cell_style_sampling_resolves_covered_point_but_retains_upper_left_policy() {
|
||||
let (mut s, sid, tid, _) = selected_merged_table(true);
|
||||
s.execute("table.setCell", &json!({"row": 0, "col": 0, "insets": 7})).unwrap();
|
||||
s.execute("table.select", &json!({"rows": [0, 0], "cols": [1, 1]})).unwrap();
|
||||
let selection = s.doc().unwrap().selection.clone();
|
||||
let before = table_for(&s, sid, tid).clone();
|
||||
s.execute("style.cell.create", &json!({"name": "Covered", "fromSelection": true})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.styles.cell.iter().find(|c| c.name == "Covered").unwrap().insets, Some([7.0; 4]));
|
||||
assert_eq!(table_for(&s, sid, tid), &before);
|
||||
assert_eq!(s.doc().unwrap().selection, selection);
|
||||
|
||||
let (mut s, sid, _) = session_with_frame();
|
||||
let tid = s.execute("table.insert", &json!({"rows": 2, "cols": 2})).unwrap()["table"].as_u64().unwrap();
|
||||
s.execute("table.select", &json!({"rows": [0, 1], "cols": [1, 1]})).unwrap();
|
||||
s.execute("table.merge", &json!({})).unwrap();
|
||||
for (row, col, insets, size) in [(0, 1, 7, 17), (1, 0, 11, 29)] {
|
||||
s.execute("table.setCell", &json!({"row": row, "col": col, "text": "Text", "insets": insets})).unwrap();
|
||||
s.execute("table.select", &json!({"rows": [row, row], "cols": [col, col]})).unwrap();
|
||||
s.execute("type.char", &json!({"attrs": {"size": size}})).unwrap();
|
||||
}
|
||||
s.execute("table.selectRow", &json!({})).unwrap();
|
||||
let before = table_for(&s, sid, tid).clone();
|
||||
let selection = s.doc().unwrap().selection.clone();
|
||||
// Row-major owners are [(0,1),(1,0)], while the rectangle starts at (1,0).
|
||||
assert_eq!(s.execute("type.selectionAttrs", &json!({})).unwrap()["chars"]["size"], 17.0);
|
||||
s.execute("style.cell.create", &json!({"name": "Upper left", "fromSelection": true})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.styles.cell.iter().find(|c| c.name == "Upper left").unwrap().insets, Some([11.0; 4]));
|
||||
assert_eq!(table_for(&s, sid, tid), &before);
|
||||
assert_eq!(s.doc().unwrap().selection, selection);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selected_merged_owners_convert_graphics_back_to_text() {
|
||||
let png = designcraft_render::Rendered { width: 1, height: 1, pixels: vec![255, 0, 0, 255] }.to_png();
|
||||
let image = crate::cmd::base64_encode(&png);
|
||||
for column in [true, false] {
|
||||
let (mut s, sid, tid, _) = selected_merged_table(column);
|
||||
let neighbor = if column { (1, 0) } else { (0, 1) };
|
||||
let covered = if column { (0, 1) } else { (1, 0) };
|
||||
for (r, c) in [covered, (1, 1), neighbor] {
|
||||
let placed = s.execute("table.placeGraphic", &json!({"row": r, "col": c, "base64": image, "name": "cell.png"})).unwrap();
|
||||
if (r, c) == covered {
|
||||
assert_eq!((placed["row"].as_u64(), placed["col"].as_u64()), (Some(0), Some(0)));
|
||||
}
|
||||
}
|
||||
let before = table_for(&s, sid, tid).clone();
|
||||
let selected = s.doc().unwrap().selection.cells.unwrap();
|
||||
s.execute("table.textCell", &json!({})).unwrap();
|
||||
let after = table_for(&s, sid, tid);
|
||||
for (r, c) in [(0, 0), (1, 1)] {
|
||||
assert!(before.cell(r, c).unwrap().graphic.is_some());
|
||||
assert!(after.cell(r, c).unwrap().graphic.is_none());
|
||||
assert_eq!(after.cell(r, c).unwrap().text, before.cell(r, c).unwrap().text);
|
||||
}
|
||||
assert_eq!(after.cell(neighbor.0, neighbor.1), before.cell(neighbor.0, neighbor.1));
|
||||
assert_eq!(after.cell(covered.0, covered.1), before.cell(covered.0, covered.1));
|
||||
assert_eq!(s.doc().unwrap().selection.cells, Some(selected));
|
||||
check(&s);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn covered_selected_owner_drag_keeps_merged_move_restrictions_atomic() {
|
||||
for column in [true, false] {
|
||||
let (mut s, sid, _, fid) = selected_merged_table(column);
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let selection = s.doc().unwrap().selection.clone();
|
||||
let revision = s.doc().unwrap().revision;
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
let redo = s.doc().unwrap().history.redo.len();
|
||||
let cs = s.cache.get(&before, doc::StoryId(sid), None);
|
||||
let cells = &cs.frames[0].tables[0].cells;
|
||||
let point = |row, col| {
|
||||
let cell = cells.iter().find(|c| c.row == row && c.col == col).unwrap();
|
||||
before.text_xf(before.item(doc::ItemId(fid)).unwrap()) * cell.rect.center()
|
||||
};
|
||||
let from = point(0, 0);
|
||||
let to = if column { point(1, 0) } else { point(0, 1) };
|
||||
let err = s.execute("table.dropCells", &json!({"frame": fid, "from": [from.x, from.y], "to": [to.x, to.y]})).unwrap_err();
|
||||
assert!(err.to_string().contains(if column { "unmerge cells that span columns" } else { "unmerge cells that span rows" }), "{err}");
|
||||
let st = s.doc().unwrap();
|
||||
assert_eq!(st.doc, before);
|
||||
assert_eq!(st.selection, selection);
|
||||
assert_eq!(st.revision, revision);
|
||||
assert_eq!((st.history.undo.len(), st.history.redo.len()), (undo, redo));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn insert_type_in_cells_and_tab() {
|
||||
let (mut s, sid, _) = session_with_frame();
|
||||
@@ -177,6 +492,43 @@ fn file_roundtrip_keeps_tables() {
|
||||
assert_eq!(st.tables.values().next().unwrap().cells[0].text.text, "A1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn backspace_and_paste_between_tables_keep_both_and_the_file_reopens() {
|
||||
let n = designcraft_doc::TABLE_ANCHOR.len_utf8();
|
||||
let anchor_of = |s: &Session, sid: u64, tid: u64| s.doc().unwrap().doc.story(doc::StoryId(sid)).unwrap().table_anchor(tid).unwrap();
|
||||
let reopens_with = |s: &Session, sid: u64, ids: &[u64]| {
|
||||
let back = crate::cmd::file_from(&crate::cmd::file_bytes(&s.doc().unwrap().doc)).unwrap();
|
||||
let st = back.story(doc::StoryId(sid)).unwrap();
|
||||
assert!(ids.iter().all(|id| st.table_anchor(*id).is_some()), "{:?}", st.tables.keys());
|
||||
assert_eq!(st.tables.len(), ids.len());
|
||||
};
|
||||
// Backspace at the start of the second of two consecutive tables.
|
||||
let (mut s, sid, _) = session_with_frame();
|
||||
let t1 = s.execute("table.insert", &json!({"rows": 2, "cols": 2})).unwrap()["table"].as_u64().unwrap();
|
||||
let len = s.doc().unwrap().doc.story(doc::StoryId(sid)).unwrap().len();
|
||||
s.execute("text.select", &json!({"story": sid, "anchor": len})).unwrap();
|
||||
let t2 = s.execute("table.insert", &json!({"rows": 2, "cols": 2})).unwrap()["table"].as_u64().unwrap();
|
||||
let a2 = anchor_of(&s, sid, t2);
|
||||
s.execute("text.select", &json!({"story": sid, "anchor": a2})).unwrap();
|
||||
s.execute("text.delete", &json!({})).unwrap();
|
||||
check(&s);
|
||||
reopens_with(&s, sid, &[t1, t2]);
|
||||
// Pasting a copy of a table right after its anchor.
|
||||
let (mut s, sid, _) = session_with_frame();
|
||||
let t1 = s.execute("table.insert", &json!({"rows": 2, "cols": 2})).unwrap()["table"].as_u64().unwrap();
|
||||
let a1 = anchor_of(&s, sid, t1);
|
||||
s.execute("text.select", &json!({"story": sid, "anchor": a1, "focus": a1 + n})).unwrap();
|
||||
s.execute("edit.copy", &json!({})).unwrap();
|
||||
s.execute("text.select", &json!({"story": sid, "anchor": a1 + n})).unwrap();
|
||||
let pasted = s.execute("edit.paste", &json!({})).unwrap();
|
||||
check(&s);
|
||||
assert_eq!(pasted["pos"], a1 + 2 * n + 1);
|
||||
let st = s.doc().unwrap().doc.story(doc::StoryId(sid)).unwrap().clone();
|
||||
let copy = st.tables.keys().copied().find(|id| *id != t1).unwrap();
|
||||
assert_eq!((st.table_anchor(t1), st.table_anchor(copy)), (Some(a1), Some(a1 + n + 1)));
|
||||
reopens_with(&s, sid, &[t1, copy]);
|
||||
}
|
||||
|
||||
fn table_for(s: &Session, sid: u64, tid: u64) -> &doc::Table {
|
||||
s.doc().unwrap().doc.story(doc::StoryId(sid)).unwrap().tables.get(&tid).unwrap()
|
||||
}
|
||||
|
||||
@@ -35,11 +35,13 @@ pub struct ViewInfo {
|
||||
pub zoom: f64,
|
||||
pub snap: SnapView,
|
||||
pub unit: Unit,
|
||||
/// The toolbox's Stroke box is in front (X): colour tools apply to strokes.
|
||||
pub stroke_in_front: bool,
|
||||
}
|
||||
|
||||
impl ViewInfo {
|
||||
pub const fn at_zoom(zoom: f64) -> Self {
|
||||
Self { zoom, snap: SnapView::FACTORY, unit: Unit::Points }
|
||||
Self { zoom, snap: SnapView::FACTORY, unit: Unit::Points, stroke_in_front: false }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -59,6 +61,10 @@ impl Session {
|
||||
return;
|
||||
}
|
||||
self.tool = designcraft_tools::create(id);
|
||||
// Any other tool unloads the place cursor.
|
||||
if id != "placeGun" {
|
||||
self.loaded = None;
|
||||
}
|
||||
// Leaving the Type tool keeps the text frame selected.
|
||||
if id != "type"
|
||||
&& let Some(st) = self.active_mut()
|
||||
@@ -93,6 +99,7 @@ impl Session {
|
||||
layer,
|
||||
snap: view.snap,
|
||||
unit: view.unit,
|
||||
stroke_in_front: view.stroke_in_front,
|
||||
};
|
||||
Some(f(self.tool.as_mut(), &cx))
|
||||
}
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
//! `layout.pages.insert` clamps an out-of-range `after` to the end instead of overflowing.
|
||||
use designcraft_engine::Session;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn insert_after_u64_max_appends_at_the_end() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"pages":2})).unwrap();
|
||||
let before: Vec<_> = s.doc().unwrap().doc.pages().map(|(_, _, p)| p.id).collect();
|
||||
let out = s.execute("layout.pages.insert", &json!({"after": u64::MAX, "count": 2})).unwrap();
|
||||
assert_eq!(out["total"], 4);
|
||||
let after: Vec<_> = s.doc().unwrap().doc.pages().map(|(_, _, p)| p.id).collect();
|
||||
assert_eq!(after.len(), 4);
|
||||
assert_eq!(after[..2], before[..], "the original pages must stay first; new pages go at the end");
|
||||
assert!(after[2..].iter().all(|id| !before.contains(id)));
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
//! Primary text frames retain all columns supported by the new-document command.
|
||||
use designcraft_doc::Document;
|
||||
use designcraft_engine::Session;
|
||||
use serde_json::json;
|
||||
|
||||
fn assert_primary_columns(doc: &Document, expected: u32) {
|
||||
let mut frames = 0;
|
||||
for story in doc.stories.values() {
|
||||
for spec in designcraft_compose::frame_specs(doc, story.id) {
|
||||
assert_eq!(spec.opts.columns, expected);
|
||||
let columns = spec.columns();
|
||||
assert_eq!(columns.len(), expected as usize);
|
||||
assert!(columns.iter().all(|r| r.width() > 0. && [r.x0, r.x1, r.y0, r.y1].into_iter().all(f64::is_finite)));
|
||||
frames += 1;
|
||||
}
|
||||
}
|
||||
assert!(frames > 0, "the primary text frame must exist");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn primary_columns_survive_composition_native_reopen_and_idml_round_trip() {
|
||||
for columns in [41, 216] {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"columns":columns,"gutter":0,"primaryTextFrame":true})).unwrap();
|
||||
assert_primary_columns(&s.doc().unwrap().doc, columns);
|
||||
let bytes = s.execute("file.serialize", &json!({})).unwrap();
|
||||
let mut reopened = Session::new();
|
||||
reopened.execute("file.openBytes", &json!({"name":"primary-columns.designcraft","base64":bytes["base64"]})).unwrap();
|
||||
assert_primary_columns(&reopened.doc().unwrap().doc, columns);
|
||||
let idml = designcraft_idml::export_idml(&reopened.doc().unwrap().doc);
|
||||
let imported = designcraft_idml::import_idml(&idml).unwrap();
|
||||
assert_primary_columns(&imported, columns);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,277 @@
|
||||
use designcraft_doc::{ParaFormat, Story, StoryId};
|
||||
use designcraft_engine::Session;
|
||||
use serde_json::{Value, json};
|
||||
use std::sync::Arc;
|
||||
fn setup() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
s
|
||||
}
|
||||
fn frame(s: &mut Session, text: &str) -> (u64, u64) {
|
||||
let r = s.execute("frame.create", &json!({"rect":[72,72,300,300],"content":"text","text":text,"caret":false})).unwrap();
|
||||
(r["id"].as_u64().unwrap(), r["story"].as_u64().unwrap())
|
||||
}
|
||||
fn snapshot(s: &Session) -> Value {
|
||||
let d = s.doc().unwrap();
|
||||
json!({"doc":d.doc,"selection":d.selection,"revision":d.revision,"dirty":d.is_dirty(),"undo":d.history.undo.len(),"redo":d.history.redo.len(),"journal":s.journal})
|
||||
}
|
||||
#[test]
|
||||
fn rejected_thread_is_atomic_with_new_frame_and_redo() {
|
||||
let mut s = setup();
|
||||
let (a, _) = frame(&mut s, "hello");
|
||||
frame(&mut s, "undo");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
let before = snapshot(&s);
|
||||
assert!(s.execute("text.thread", &json!({"from":999999,"rect":[0,0,100,100]})).is_err());
|
||||
assert_eq!(snapshot(&s), before);
|
||||
assert!(s.execute("text.thread", &json!({"from":a,"rect":[0,0,100,100],"spread":999})).is_err());
|
||||
assert_eq!(snapshot(&s), before);
|
||||
}
|
||||
#[test]
|
||||
fn locked_frame_cannot_be_unthreaded() {
|
||||
let mut s = setup();
|
||||
let (a, _) = frame(&mut s, "hello");
|
||||
let (b, _) = frame(&mut s, "");
|
||||
s.execute("text.thread", &json!({"from":a,"to":b})).unwrap();
|
||||
s.execute("object.lock", &json!({"ids":[a]})).unwrap();
|
||||
let before = snapshot(&s);
|
||||
let r = s.execute("text.unthread", &json!({"frame":a}));
|
||||
assert!(r.is_err(), "unthread accepted locked frame: {r:?}");
|
||||
assert_eq!(snapshot(&s), before);
|
||||
}
|
||||
#[test]
|
||||
fn locked_frame_cannot_be_removed_from_thread() {
|
||||
let mut s = setup();
|
||||
let (a, _) = frame(&mut s, "hello");
|
||||
let (b, _) = frame(&mut s, "");
|
||||
s.execute("text.thread", &json!({"from":a,"to":b})).unwrap();
|
||||
s.execute("object.lock", &json!({"ids":[a]})).unwrap();
|
||||
let before = snapshot(&s);
|
||||
let r = s.execute("text.removeFromThread", &json!({"frame":a}));
|
||||
assert!(r.is_err(), "remove accepted locked frame: {r:?}");
|
||||
assert_eq!(snapshot(&s), before);
|
||||
}
|
||||
#[test]
|
||||
fn rejected_selection_preserves_pending_typing() {
|
||||
let mut s = setup();
|
||||
let (_, sid) = frame(&mut s, "hello");
|
||||
s.execute("text.select", &json!({"story":sid,"anchor":3})).unwrap();
|
||||
s.execute("type.char", &json!({"attrs":{"size":30}})).unwrap();
|
||||
let before = s.execute("type.selectionAttrs", &json!({})).unwrap();
|
||||
assert!(s.execute("text.select", &json!({"story":999999,"anchor":0})).is_err());
|
||||
let after = s.execute("type.selectionAttrs", &json!({})).unwrap();
|
||||
assert_eq!(after, before, "rejected selection reset pending typing");
|
||||
}
|
||||
#[test]
|
||||
fn append_max_id_preserves_both_tables() {
|
||||
use designcraft_doc::table::Table;
|
||||
let mut a = Story::with_text(StoryId(1), &designcraft_doc::TABLE_ANCHOR.to_string(), ParaFormat::default());
|
||||
let mut b = Story::with_text(StoryId(2), &designcraft_doc::TABLE_ANCHOR.to_string(), ParaFormat::default());
|
||||
let mut ta = Table::new(u64::MAX, 1, 1, 0, 0, 100.);
|
||||
ta.cells[0].text = Story::with_text(StoryId(0), "ORIGINAL", ParaFormat::default());
|
||||
a.tables.insert(u64::MAX, Arc::new(ta));
|
||||
let mut tb = Table::new(1, 1, 1, 0, 0, 100.);
|
||||
tb.cells[0].text = Story::with_text(StoryId(0), "INCOMING", ParaFormat::default());
|
||||
b.tables.insert(1, Arc::new(tb));
|
||||
a.paras[0].table = Some(u64::MAX);
|
||||
b.paras[0].table = Some(1);
|
||||
a.check().unwrap();
|
||||
b.check().unwrap();
|
||||
a.append_story(b);
|
||||
let contents: Vec<_> = a.tables.values().map(|t| t.cells[0].text.text.clone()).collect();
|
||||
assert!(contents.contains(&"ORIGINAL".into()) && contents.contains(&"INCOMING".into()), "table loss: {contents:?}");
|
||||
}
|
||||
#[test]
|
||||
fn idml_dropcap_detail_preserves_inherited_other_bit() {
|
||||
use designcraft_doc::{Document, ParaAttrs, ParagraphStyle, build::NewDocument};
|
||||
let mut d = Document::new(&NewDocument::default());
|
||||
let parent = ParagraphStyle {
|
||||
name: "Parent".into(),
|
||||
based_on: None,
|
||||
next_style: None,
|
||||
para: ParaAttrs { drop_cap_align_left: Some(false), drop_cap_scale_descenders: Some(true), ..Default::default() },
|
||||
chars: Default::default(),
|
||||
shortcut: String::new(),
|
||||
};
|
||||
let child = ParagraphStyle {
|
||||
name: "Child".into(),
|
||||
based_on: Some("Parent".into()),
|
||||
next_style: None,
|
||||
para: ParaAttrs { drop_cap_scale_descenders: Some(false), ..Default::default() },
|
||||
chars: Default::default(),
|
||||
shortcut: String::new(),
|
||||
};
|
||||
d.styles_mut().paragraph.extend([parent, child]);
|
||||
let before = d.styles.resolve_para_style("Child").0;
|
||||
let bytes = designcraft_idml::export_idml(&d);
|
||||
let back = designcraft_idml::import_idml(&bytes).unwrap();
|
||||
let after = back.styles.resolve_para_style("Child").0;
|
||||
assert_eq!(
|
||||
(after.drop_cap_align_left, after.drop_cap_scale_descenders),
|
||||
(before.drop_cap_align_left, before.drop_cap_scale_descenders),
|
||||
"IDML export resets inherited align-left bit"
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
fn threading_preserves_incoming_text_hyperlink() {
|
||||
let mut s = setup();
|
||||
let (a, sa) = frame(&mut s, "First");
|
||||
let (b, sb) = frame(&mut s, "Second");
|
||||
s.execute("text.select", &json!({"story":sb,"anchor":0,"focus":6})).unwrap();
|
||||
s.execute("hyperlink.create", &json!({"url":"https://example.com"})).unwrap();
|
||||
s.execute("text.thread", &json!({"from":a,"to":b})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let back = designcraft_format::load(&designcraft_format::save(d).unwrap()).unwrap();
|
||||
match &back.hyperlinks[0].source {
|
||||
designcraft_doc::HyperlinkSource::Text { story, start, end } => {
|
||||
assert_eq!(story.0, sa, "hyperlink points to deleted incoming story");
|
||||
assert_eq!((*start, *end), (6, 12));
|
||||
}
|
||||
_ => panic!("wrong source"),
|
||||
};
|
||||
}
|
||||
#[test]
|
||||
fn thread_cannot_destroy_body_by_joining_generated_endnotes() {
|
||||
let mut s = setup();
|
||||
let (body, sid) = frame(&mut s, "KEEP THIS BODY");
|
||||
s.execute("text.select", &json!({"story":sid,"anchor":14})).unwrap();
|
||||
let e = s.execute("endnote.insert", &json!({"text":"a note"})).unwrap();
|
||||
let ef = e["frame"].as_u64().unwrap();
|
||||
let before = snapshot(&s);
|
||||
let r = s.execute("text.thread", &json!({"from":ef,"to":body}));
|
||||
assert!(
|
||||
r.is_err(),
|
||||
"thread into generated endnotes accepted: {r:?}; stories: {:?}",
|
||||
s.doc().unwrap().doc.stories.values().map(|s| &s.text).collect::<Vec<_>>()
|
||||
);
|
||||
assert_eq!(snapshot(&s), before);
|
||||
}
|
||||
#[test]
|
||||
fn generated_endnotes_accept_empty_extensions_but_reject_reverse_body_merge() {
|
||||
let mut s = setup();
|
||||
let (body, sid) = frame(&mut s, "Body");
|
||||
s.execute("text.select", &json!({"story":sid,"anchor":4})).unwrap();
|
||||
let r = s.execute("endnote.insert", &json!({"text":"note"})).unwrap();
|
||||
let ef = r["frame"].as_u64().unwrap();
|
||||
let esid = s.doc().unwrap().doc.endnote_story.unwrap();
|
||||
let before = snapshot(&s);
|
||||
assert!(s.execute("text.thread", &json!({"from":body,"to":ef})).is_err());
|
||||
assert_eq!(snapshot(&s), before);
|
||||
s.execute("text.thread", &json!({"from":ef,"rect":[72,72,300,300]})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.endnote_story, Some(esid));
|
||||
s.execute("text.thread", &json!({"to":ef,"rect":[72,72,300,300]})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.endnote_story, Some(esid));
|
||||
assert_eq!(s.doc().unwrap().doc.story(esid).unwrap().frames.len(), 3);
|
||||
assert!(s.doc().unwrap().doc.story(StoryId(sid)).unwrap().text.starts_with("Body"));
|
||||
s.doc().unwrap().doc.check().unwrap();
|
||||
}
|
||||
#[test]
|
||||
fn threading_moves_data_placeholders_and_primary_story_with_text() {
|
||||
use designcraft_doc::{Placeholder, PlaceholderAnchor, PlaceholderRole};
|
||||
let mut s = setup();
|
||||
let (a, sa) = frame(&mut s, "First");
|
||||
let (b, sb) = frame(&mut s, "<<name>>");
|
||||
s.edit(|d, _| {
|
||||
d.settings.primary_story = Some(StoryId(sb));
|
||||
d.data_merge.placeholders.push(Placeholder {
|
||||
id: 123,
|
||||
source_id: 0,
|
||||
field: "name".into(),
|
||||
role: PlaceholderRole::Text,
|
||||
anchor: PlaceholderAnchor::Text { story: StoryId(sb), start: 0, end: 8 },
|
||||
});
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
s.execute("text.thread", &json!({"from":a,"to":b})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert_eq!(d.settings.primary_story, Some(StoryId(sa)));
|
||||
assert_eq!(d.data_merge.placeholders.len(), 1);
|
||||
assert_eq!(d.data_merge.placeholders[0].anchor, PlaceholderAnchor::Text { story: StoryId(sa), start: 6, end: 14 });
|
||||
let after = d.clone();
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc, before);
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc, after);
|
||||
}
|
||||
#[test]
|
||||
fn append_max_ids_preserves_addressable_footnotes_and_endnotes() {
|
||||
let mut a = Story::with_text(StoryId(1), "A", ParaFormat::default());
|
||||
let mut b = Story::with_text(StoryId(2), "B", ParaFormat::default());
|
||||
a.insert_note(1, "original footnote", ParaFormat::default());
|
||||
b.insert_note(1, "incoming footnote", ParaFormat::default());
|
||||
Arc::make_mut(&mut a.notes[0]).id = u64::MAX;
|
||||
a.insert_endnote(1, "original endnote", ParaFormat::default());
|
||||
b.insert_endnote(1, "incoming endnote", ParaFormat::default());
|
||||
Arc::make_mut(&mut a.endnotes[0]).id = u64::MAX;
|
||||
a.check().unwrap();
|
||||
b.check().unwrap();
|
||||
a.append_story(b);
|
||||
a.check().unwrap();
|
||||
assert_ne!(a.notes[0].id, a.notes[1].id);
|
||||
assert_ne!(a.endnotes[0].id, a.endnotes[1].id);
|
||||
assert_eq!(a.notes[0].text.text, "original footnote");
|
||||
assert_eq!(a.endnotes[1].text.text, "incoming endnote");
|
||||
}
|
||||
#[test]
|
||||
fn locked_layer_and_neighbour_reject_unthread_atomically() {
|
||||
for lock_layer in [false, true] {
|
||||
let mut s = setup();
|
||||
let (a, _) = frame(&mut s, "A");
|
||||
let (b, _) = frame(&mut s, "B");
|
||||
s.execute("text.thread", &json!({"from":a,"to":b})).unwrap();
|
||||
if lock_layer {
|
||||
let lid = s.doc().unwrap().active_layer.0;
|
||||
s.execute("layer.set", &json!({"id":lid,"locked":true})).unwrap();
|
||||
} else {
|
||||
s.execute("object.lock", &json!({"ids":[b]})).unwrap();
|
||||
}
|
||||
let before = snapshot(&s);
|
||||
assert!(s.execute("text.unthread", &json!({"frame":a})).is_err());
|
||||
assert_eq!(snapshot(&s), before);
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn idml_partial_dropcap_bits_resolve_both_style_and_paragraph_inheritance() {
|
||||
use designcraft_doc::{Document, ParaAttrs, ParagraphStyle, SpreadRef, build::NewDocument};
|
||||
use designcraft_geom::Rect;
|
||||
for parent_align in [false, true] {
|
||||
for parent_scale in [false, true] {
|
||||
for local_align in [false, true] {
|
||||
let mut d = Document::new(&NewDocument::default());
|
||||
d.styles_mut().paragraph.push(ParagraphStyle {
|
||||
name: "Parent".into(),
|
||||
based_on: None,
|
||||
next_style: None,
|
||||
para: ParaAttrs { drop_cap_align_left: Some(parent_align), drop_cap_scale_descenders: Some(parent_scale), ..Default::default() },
|
||||
chars: Default::default(),
|
||||
shortcut: String::new(),
|
||||
});
|
||||
let layer = d.default_layer();
|
||||
let (_, sid) = d
|
||||
.add_text_frame(
|
||||
SpreadRef::Doc(0),
|
||||
Rect::new(10., 10., 200., 200.),
|
||||
layer,
|
||||
"Body",
|
||||
ParaFormat {
|
||||
style: "Parent".into(),
|
||||
para: ParaAttrs { drop_cap_align_left: Some(local_align), ..Default::default() },
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
let bytes = designcraft_idml::export_idml(&d);
|
||||
let back = designcraft_idml::import_idml(&bytes).unwrap();
|
||||
let st = back.stories.values().find(|s| s.text == "Body").unwrap();
|
||||
let actual = back.styles.resolve_para(&st.paras[0]).0;
|
||||
let expected = d.styles.resolve_para(&d.story(sid).unwrap().paras[0]).0;
|
||||
assert_eq!(
|
||||
(actual.drop_cap_align_left, actual.drop_cap_scale_descenders),
|
||||
(expected.drop_cap_align_left, expected.drop_cap_scale_descenders)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,223 @@
|
||||
//! Linked-story threading and text-color transaction safety.
|
||||
use designcraft_doc::{ParaFormat, Story, StoryId, table::Table};
|
||||
use designcraft_engine::Session;
|
||||
use serde_json::{Value, json};
|
||||
use std::sync::Arc;
|
||||
|
||||
fn setup() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
s
|
||||
}
|
||||
fn frame(s: &mut Session, text: &str) -> (u64, StoryId) {
|
||||
let f = s.execute("frame.create", &json!({"rect":[36,36,200,100],"content":"text","text":text,"caret":false})).unwrap();
|
||||
(f["id"].as_u64().unwrap(), StoryId(f["story"].as_u64().unwrap()))
|
||||
}
|
||||
fn child(s: &mut Session, parent: StoryId) -> (u64, StoryId) {
|
||||
let f = s.execute("story.placeAndLink", &json!({"story":parent.0,"rect":[36,150,200,100]})).unwrap();
|
||||
(f["id"].as_u64().unwrap(), StoryId(f["story"].as_u64().unwrap()))
|
||||
}
|
||||
fn state(s: &Session) -> Value {
|
||||
let d = s.doc().unwrap();
|
||||
json!({"doc":d.doc,"selection":d.selection,"revision":d.revision,"dirty":d.is_dirty(),"undo":format!("{:?}",d.history),"journal":s.journal})
|
||||
}
|
||||
fn link(s: &mut Session, sid: StoryId) -> Value {
|
||||
s.execute("story.links", &json!({})).unwrap().as_array().unwrap().iter().find(|l| l["story"] == sid.0).unwrap().clone()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn safety_linked_parent_follows_merge_and_updates_after_native_reopen() {
|
||||
let mut s = setup();
|
||||
let (first, survivor) = frame(&mut s, "PREFIX");
|
||||
let (incoming, parent) = frame(&mut s, "PARENT");
|
||||
let (_, linked) = child(&mut s, parent);
|
||||
// A coincident old parent revision must not hide the change of parent identity/content.
|
||||
let future_rev = s.doc().unwrap().doc.story(survivor).unwrap().rev + 2;
|
||||
s.edit(|d, _| {
|
||||
d.story_mut(linked).unwrap().link = Some((parent, future_rev));
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("text.thread", &json!({"from":first,"to":incoming})).unwrap();
|
||||
assert_eq!(link(&mut s, linked)["parent"], survivor.0);
|
||||
assert_eq!(link(&mut s, linked)["outOfDate"], true);
|
||||
assert_eq!(s.doc().unwrap().doc.story(linked).unwrap().text, "PARENT");
|
||||
let bytes = s.execute("file.serialize", &json!({})).unwrap();
|
||||
let mut reopened = Session::new();
|
||||
reopened.execute("file.openBytes", &json!({"name":"links.designcraft","base64":bytes["base64"]})).unwrap();
|
||||
assert_eq!(link(&mut reopened, linked)["parent"], survivor.0);
|
||||
reopened.execute("story.updateLink", &json!({"story":linked.0})).unwrap();
|
||||
assert_eq!(reopened.doc().unwrap().doc.story(linked).unwrap().text, "PREFIX\nPARENT");
|
||||
assert_eq!(link(&mut reopened, linked)["outOfDate"], false);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(link(&mut s, linked)["parent"], parent.0);
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
assert_eq!(link(&mut s, linked)["parent"], survivor.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn safety_linked_child_cannot_merge_body_text_in_either_direction() {
|
||||
for reverse in [false, true] {
|
||||
let mut s = setup();
|
||||
let (_, parent) = frame(&mut s, "SOURCE");
|
||||
let (linked, child) = child(&mut s, parent);
|
||||
let (body, _) = frame(&mut s, "BODY");
|
||||
let (from, to) = if reverse { (body, linked) } else { (linked, body) };
|
||||
let before = state(&s);
|
||||
let error = s.execute("text.thread", &json!({"from":from,"to":to})).unwrap_err();
|
||||
assert!(error.to_string().contains("linked story"));
|
||||
assert_eq!(state(&s), before);
|
||||
s.execute("story.updateLink", &json!({"story":child.0})).unwrap();
|
||||
assert!(s.doc().unwrap().doc.stories.values().any(|st| st.text == "BODY"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn safety_linked_child_allows_empty_extensions_in_both_directions() {
|
||||
for reverse in [false, true] {
|
||||
let mut s = setup();
|
||||
let (_, parent) = frame(&mut s, "SOURCE");
|
||||
let (linked, child) = child(&mut s, parent);
|
||||
let (empty, _) = frame(&mut s, "");
|
||||
let (from, to) = if reverse { (empty, linked) } else { (linked, empty) };
|
||||
s.execute("text.thread", &json!({"from":from,"to":to})).unwrap();
|
||||
assert_eq!(link(&mut s, child)["parent"], parent.0);
|
||||
s.execute("story.setText", &json!({"story":parent.0,"text":"UPDATED"})).unwrap();
|
||||
assert_eq!(link(&mut s, child)["outOfDate"], true);
|
||||
s.execute("story.updateLink", &json!({"story":child.0})).unwrap();
|
||||
let st = s.doc().unwrap().doc.story(child).unwrap();
|
||||
assert_eq!(st.text, "UPDATED");
|
||||
assert_eq!(st.frames.len(), 2);
|
||||
assert_eq!(link(&mut s, child)["outOfDate"], false);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn safety_linked_empty_parent_cannot_be_merged_into_its_child() {
|
||||
let mut s = setup();
|
||||
let (parent_frame, parent) = frame(&mut s, "");
|
||||
let (linked, _) = child(&mut s, parent);
|
||||
let before = state(&s);
|
||||
assert!(s.execute("text.thread", &json!({"from":parent_frame,"to":linked})).is_err());
|
||||
assert_eq!(state(&s), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn safety_text_color_without_target_is_atomic_and_carets_remain_valid() {
|
||||
let mut s = setup();
|
||||
let f = s.execute("frame.create", &json!({"rect":[36,36,200,100]})).unwrap();
|
||||
s.execute("selection.set", &json!({"ids":[f["id"]]})).unwrap();
|
||||
let before = state(&s);
|
||||
assert!(s.execute("object.color", &json!({"color":"#123456","text":true})).is_err());
|
||||
assert_eq!(state(&s), before);
|
||||
for text in ["", "Words"] {
|
||||
let (_, sid) = frame(&mut s, text);
|
||||
s.execute("text.select", &json!({"story":sid.0,"anchor":0})).unwrap();
|
||||
let color = s.execute("object.color", &json!({"color":"#654321","text":true})).unwrap();
|
||||
s.execute("text.insert", &json!({"text":"X"})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.story(sid).unwrap().format_after(0).over.fill.as_deref(), color["swatch"].as_str());
|
||||
}
|
||||
}
|
||||
|
||||
fn nested_story(depth: usize, name: &str) -> Story {
|
||||
let mut st = Story::with_text(StoryId(0), "leaf", ParaFormat::default());
|
||||
st.chars[0].format.over.fill = Some(name.into());
|
||||
for _ in 0..depth {
|
||||
let mut outer = Story::with_text(StoryId(0), &designcraft_doc::TABLE_ANCHOR.to_string(), ParaFormat::default());
|
||||
let mut t = Table::new(1, 1, 1, 0, 0, 100.);
|
||||
t.cells[0].text = st;
|
||||
outer.tables.insert(1, Arc::new(t));
|
||||
outer.paras[0].table = Some(1);
|
||||
st = outer;
|
||||
}
|
||||
st
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn safety_deep_swatch_rename_rejects_atomically_with_pending_color() {
|
||||
// A small boundary probe, never an attempted stack-overflow reproduction.
|
||||
for depth in [33, 34] {
|
||||
let mut s = setup();
|
||||
let (_, sid) = frame(&mut s, "root");
|
||||
s.execute("text.select", &json!({"story":sid.0,"anchor":0})).unwrap();
|
||||
let old = s.execute("object.color", &json!({"color":"#123456"})).unwrap()["swatch"].as_str().unwrap().to_string();
|
||||
s.edit(|d, _| {
|
||||
let st = d.story_mut(sid).unwrap();
|
||||
let frames = st.frames.clone();
|
||||
*st = nested_story(depth, &old);
|
||||
st.id = sid;
|
||||
st.frames = frames;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let pending = s.execute("type.selectionAttrs", &json!({})).unwrap();
|
||||
let before = state(&s);
|
||||
let doc = s.doc().unwrap().doc.clone();
|
||||
let error = s.execute("swatch.addToSwatches", &json!({"swatch":old,"name":"Brand"})).unwrap_err();
|
||||
assert!(error.to_string().contains("nesting"));
|
||||
assert!(Arc::ptr_eq(&doc, &s.doc().unwrap().doc));
|
||||
assert_eq!(state(&s), before);
|
||||
assert_eq!(s.execute("type.selectionAttrs", &json!({})).unwrap(), pending);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn safety_swatch_rename_reaches_last_supported_depth() {
|
||||
let mut s = setup();
|
||||
let (_, sid) = frame(&mut s, "root");
|
||||
s.execute("text.select", &json!({"story":sid.0,"anchor":0})).unwrap();
|
||||
let old = s.execute("object.color", &json!({"color":"#123456"})).unwrap()["swatch"].as_str().unwrap().to_string();
|
||||
s.edit(|d, _| {
|
||||
let st = d.story_mut(sid).unwrap();
|
||||
let frames = st.frames.clone();
|
||||
*st = nested_story(32, &old);
|
||||
st.id = sid;
|
||||
st.frames = frames;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("swatch.addToSwatches", &json!({"swatch":old,"name":"Brand"})).unwrap();
|
||||
let mut st = s.doc().unwrap().doc.story(sid).unwrap();
|
||||
for _ in 0..32 {
|
||||
st = &st.tables[&1].cells[0].text;
|
||||
}
|
||||
assert_eq!(st.format_after(0).over.fill.as_deref(), Some("Brand"));
|
||||
assert_eq!(s.execute("type.selectionAttrs", &json!({})).unwrap()["chars"]["fill"], "Brand");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn safety_empty_linked_parent_follows_survivor_only_on_explicit_update() {
|
||||
for incoming_empty in [false, true] {
|
||||
for alternate_layout in [false, true] {
|
||||
let mut s = setup();
|
||||
let (empty, parent) = frame(&mut s, "");
|
||||
let linked = if alternate_layout {
|
||||
s.execute("layout.createAlternate", &json!({"name":"Alternate","width":600,"height":800})).unwrap();
|
||||
let links = s.execute("story.links", &json!({})).unwrap();
|
||||
StoryId(links.as_array().unwrap().iter().find(|l| l["parent"] == parent.0).unwrap()["story"].as_u64().unwrap())
|
||||
} else {
|
||||
child(&mut s, parent).1
|
||||
};
|
||||
let (body, survivor) = frame(&mut s, "BODY");
|
||||
let (from, to) = if incoming_empty { (body, empty) } else { (empty, body) };
|
||||
s.execute("text.thread", &json!({"from":from,"to":to})).unwrap();
|
||||
assert!(s.doc().unwrap().doc.story(parent).is_none());
|
||||
assert_eq!(link(&mut s, linked)["parent"], survivor.0);
|
||||
assert_eq!(link(&mut s, linked)["outOfDate"], true);
|
||||
assert_eq!(s.doc().unwrap().doc.story(linked).unwrap().text, "");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(link(&mut s, linked)["parent"], parent.0);
|
||||
assert_eq!(s.doc().unwrap().doc.story(linked).unwrap().text, "");
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
assert_eq!(link(&mut s, linked)["parent"], survivor.0);
|
||||
let bytes = s.execute("file.serialize", &json!({})).unwrap();
|
||||
let mut reopened = Session::new();
|
||||
reopened.execute("file.openBytes", &json!({"name":"empty-parent.designcraft","base64":bytes["base64"]})).unwrap();
|
||||
assert_eq!(link(&mut reopened, linked)["outOfDate"], true);
|
||||
assert_eq!(reopened.doc().unwrap().doc.story(linked).unwrap().text, "");
|
||||
reopened.execute("story.updateLink", &json!({"story":linked.0})).unwrap();
|
||||
assert_eq!(reopened.doc().unwrap().doc.story(linked).unwrap().text, "BODY");
|
||||
assert_eq!(link(&mut reopened, linked)["outOfDate"], false);
|
||||
}
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user